Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch to System.Text.Json #158

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Consul.Test/ACLTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public class ACLTest : BaseFixture
async Task SkipIfAclNotSupportedAsync()
{
var info = await _client.Agent.Self();
var version = new Version(info.Response["Config"]["Version"]);
var version = new Version(info.Response["Config"]["Version"].GetString());
Skip.If(version >= new Version("1.11.0"), "Legacy ACL system was removed in Consul 1.11.");
}

Expand Down
8 changes: 4 additions & 4 deletions Consul.Test/AgentTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ public async Task Agent_GetSelf()
var info = await _client.Agent.Self();

Assert.NotNull(info);
Assert.False(string.IsNullOrEmpty(info.Response["Config"]["NodeName"]));
Assert.False(string.IsNullOrEmpty(info.Response["Member"]["Tags"]["bootstrap"].ToString()));
Assert.False(string.IsNullOrEmpty(info.Response["Config"]["NodeName"].GetString()));
Assert.False(string.IsNullOrEmpty(info.Response["Member"]["Tags"].GetProperty("bootstrap").GetString()));
}

[Fact]
Expand Down Expand Up @@ -411,15 +411,15 @@ public async Task Agent_Checks_ServiceBound()
public async Task Agent_Join()
{
var info = await _client.Agent.Self();
await _client.Agent.Join(info.Response["DebugConfig"]["AdvertiseAddrLAN"], false);
await _client.Agent.Join(info.Response["DebugConfig"]["AdvertiseAddrLAN"].GetString(), false);
// Success is not throwing an exception
}

[Fact]
public async Task Agent_ForceLeave()
{
var info = await _client.Agent.Self();
await _client.Agent.ForceLeave(info.Response["Config"]["NodeName"]);
await _client.Agent.ForceLeave(info.Response["Config"]["NodeName"].GetString());
// Success is not throwing an exception
}

Expand Down
1 change: 0 additions & 1 deletion Consul.Test/Consul.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
<ItemGroup Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' ">
<Reference Include="System.Net.Http" />
<Reference Include="System.Net.Http.WebRequest" />
<Reference Include="Microsoft.CSharp" />
</ItemGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion Consul.Test/HealthTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class HealthTest : BaseFixture
public async Task Health_GetLocalNode()
{
var info = await _client.Agent.Self();
var checks = await _client.Health.Node((string)info.Response["Config"]["NodeName"]);
var checks = await _client.Health.Node(info.Response["Config"]["NodeName"].GetString());

Assert.NotEqual((ulong)0, checks.LastIndex);
Assert.NotEmpty(checks.Response);
Expand Down
52 changes: 17 additions & 35 deletions Consul/ACL.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@
// -----------------------------------------------------------------------

using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Consul
{
Expand Down Expand Up @@ -80,45 +81,32 @@ public override int GetHashCode()
}

[Obsolete("The Legacy ACL system has been deprecated, please use Token, Role and Policy instead.")]
public class ACLTypeConverter : JsonConverter
public class ACLTypeConverter : JsonConverter<ACLType>
{
#pragma warning disable CS0809 // Obsolete member 'ACLType.Equals(object)' overrides non-obsolete member
[Obsolete("The Legacy ACL system has been deprecated, please use Token, Role and Policy instead.")]
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
#pragma warning restore CS0809 // Obsolete member 'ACLType.Equals(object)' overrides non-obsolete member
{
serializer.Serialize(writer, ((ACLType)value).Type);
}

#pragma warning disable CS0809 // Obsolete member 'ACLType.Equals(object)' overrides non-obsolete member
#pragma warning disable CS0809
[Obsolete("The Legacy ACL system has been deprecated, please use Token, Role and Policy instead.")]
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
#pragma warning restore CS0809 // Obsolete member 'ACLType.Equals(object)' overrides non-obsolete member
public override ACLType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
#pragma warning restore CS0809
{
var type = (string)serializer.Deserialize(reader, typeof(string));
var type = reader.GetString();
switch (type)
{
case "client":
return ACLType.Client;
case "management":
return ACLType.Management;
default:
throw new ArgumentOutOfRangeException("serializer", type,
throw new ArgumentOutOfRangeException(nameof(type), type,
"Unknown ACL token type value found during deserialization");
}
}

#pragma warning disable CS0809 // Obsolete member 'ACLType.Equals(object)' overrides non-obsolete member
#pragma warning disable CS0809
[Obsolete("The Legacy ACL system has been deprecated, please use Token, Role and Policy instead.")]
public override bool CanConvert(Type objectType)
#pragma warning restore CS0809 // Obsolete member 'ACLType.Equals(object)' overrides non-obsolete member
public override void Write(Utf8JsonWriter writer, ACLType value, JsonSerializerOptions options)
#pragma warning restore CS0809
{
if (objectType == typeof(ACLType))
{
return true;
}
return false;
writer.WriteStringValue(value.Type);
}
}

Expand All @@ -139,7 +127,7 @@ public class ACLEntry

[Obsolete("The Legacy ACL system has been deprecated, please use Token, Role and Policy instead.")]
[JsonConverter(typeof(ACLTypeConverter))]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public ACLType Type { get; set; }

[Obsolete("The Legacy ACL system has been deprecated, please use Token, Role and Policy instead.")]
Expand Down Expand Up @@ -192,12 +180,6 @@ internal ACL(ConsulClient c)
_client = c;
}

private class ACLCreationResult
{
[JsonProperty]
internal string ID { get; set; }
}

/// <summary>
/// [Deprecated] Create is used to generate a new token with the given parameters
/// </summary>
Expand All @@ -218,8 +200,8 @@ private class ACLCreationResult
[Obsolete("The Legacy ACL system has been deprecated, please use Token, Role and Policy instead.")]
public async Task<WriteResult<string>> Create(ACLEntry acl, WriteOptions q, CancellationToken ct = default(CancellationToken))
{
var res = await _client.Put<ACLEntry, ACLCreationResult>("/v1/acl/create", acl, q).Execute(ct).ConfigureAwait(false);
return new WriteResult<string>(res, res.Response.ID);
var res = await _client.Put<ACLEntry, JsonElement>("/v1/acl/create", acl, q).Execute(ct).ConfigureAwait(false);
return new WriteResult<string>(res, res.Response.GetProperty("ID").GetString());
}

/// <summary>
Expand Down Expand Up @@ -288,8 +270,8 @@ private class ACLCreationResult
[Obsolete("The Legacy ACL system has been deprecated, please use Token, Role and Policy instead.")]
public async Task<WriteResult<string>> Clone(string id, WriteOptions q, CancellationToken ct = default(CancellationToken))
{
var res = await _client.PutReturning<ACLCreationResult>(string.Format("/v1/acl/clone/{0}", id), q).Execute(ct).ConfigureAwait(false);
return new WriteResult<string>(res, res.Response.ID);
var res = await _client.PutReturning<JsonElement>(string.Format("/v1/acl/clone/{0}", id), q).Execute(ct).ConfigureAwait(false);
return new WriteResult<string>(res, res.Response.GetProperty("ID").GetString());
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion Consul/ACLReplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
// -----------------------------------------------------------------------

using System;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Consul
{
Expand Down
89 changes: 41 additions & 48 deletions Consul/Agent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Consul.Filtering;
using Newtonsoft.Json;

namespace Consul
{
Expand Down Expand Up @@ -70,18 +71,11 @@ public override int GetHashCode()
/// <summary>
/// TLS Status Convertor (to and from JSON)
/// </summary>
public class TTLStatusConverter : JsonConverter
public class TTLStatusConverter : JsonConverter<TTLStatus>
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override TTLStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
serializer.Serialize(writer, ((TTLStatus)value).Status);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var status = (string)serializer.Deserialize(reader, typeof(string));
switch (status)
switch (reader.GetString())
{
case "pass":
return TTLStatus.Pass;
Expand All @@ -100,9 +94,9 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
}
}

public override bool CanConvert(Type objectType)
public override void Write(Utf8JsonWriter writer, TTLStatus value, JsonSerializerOptions options)
{
return objectType == typeof(TTLStatus);
writer.WriteStringValue(value.Status);
}
}

Expand Down Expand Up @@ -169,34 +163,34 @@ public AgentMember()
/// </summary>
public class AgentServiceRegistration
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string ID { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string Name { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string[] Tags { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public int Port { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string Address { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public bool EnableTagOverride { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public AgentServiceCheck Check { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public AgentServiceCheck[] Checks { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public IDictionary<string, string> Meta { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public IDictionary<string, ServiceTaggedAddress> TaggedAddresses { get; set; }
}

Expand All @@ -205,7 +199,7 @@ public class AgentServiceRegistration
/// </summary>
public class AgentCheckRegistration : AgentServiceCheck
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string ServiceID { get; set; }
}

Expand All @@ -214,66 +208,65 @@ public class AgentCheckRegistration : AgentServiceCheck
/// </summary>
public class AgentServiceCheck
{

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string ID { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string Name { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string Notes { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string Script { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string[] Args { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string DockerContainerID { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string Shell { get; set; } // Only supported for Docker.

[JsonConverter(typeof(DurationTimespanConverter))]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public TimeSpan? Interval { get; set; }

[JsonConverter(typeof(DurationTimespanConverter))]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public TimeSpan? Timeout { get; set; }

[JsonConverter(typeof(DurationTimespanConverter))]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public TimeSpan? TTL { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string HTTP { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public Dictionary<string, List<string>> Header { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string Method { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string Body { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string TCP { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
[JsonConverter(typeof(HealthStatusConverter))]
public HealthStatus Status { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public bool TLSSkipVerify { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string GRPC { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public bool GRPCUseTLS { get; set; }

/// <summary>
Expand All @@ -285,7 +278,7 @@ public class AgentServiceCheck
/// automatically be deregistered.
/// </summary>
[JsonConverter(typeof(DurationTimespanConverter))]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public TimeSpan? DeregisterCriticalServiceAfter { get; set; }
}

Expand Down Expand Up @@ -325,9 +318,9 @@ internal Agent(ConsulClient c)
/// Self is used to query the agent we are speaking to for information about itself
/// </summary>
/// <returns>A somewhat dynamic object representing the various data elements in Self</returns>
public Task<QueryResult<Dictionary<string, Dictionary<string, dynamic>>>> Self(CancellationToken ct = default(CancellationToken))
public Task<QueryResult<Dictionary<string, Dictionary<string, JsonElement>>>> Self(CancellationToken ct = default(CancellationToken))
{
return _client.Get<Dictionary<string, Dictionary<string, dynamic>>>("/v1/agent/self").Execute(ct);
return _client.Get<Dictionary<string, Dictionary<string, JsonElement>>>("/v1/agent/self").Execute(ct);
}

/// <summary>
Expand All @@ -353,7 +346,7 @@ public string NodeName
{
if (_nodeName == null)
{
_nodeName = (await Self(ct).ConfigureAwait(false)).Response["Config"]["NodeName"];
_nodeName = (await Self(ct).ConfigureAwait(false)).Response["Config"]["NodeName"].GetString();
}
}
}
Expand Down
Loading