lulianqi commented on code in PR #1:
URL: https://github.com/apache/dubbo-net/pull/1#discussion_r4421620676
##########
.gitattributes:
##########
@@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
Review Comment:
已核对 git ls-files --eol:当前 Git 中所有带换行的 C# blob 已是 i/lf。新增 *.cs text eol=lf
固定跨平台 checkout,并实际运行 git add --renormalize .,没有产生任何 staged
diff,因此未创建无内容的规范化提交,也没有去掉原有 BOM。
##########
Clients/DubboServiceDriver.cs:
##########
@@ -0,0 +1,389 @@
+using DubboNet.Clients.DataModle;
+using DubboNet.Clients.Helper;
+using DubboNet.Clients.LoadBalancing;
+using DubboNet.DubboService;
+using DubboNet.DubboService.DataModle;
+using MyCommonHelper;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Text;
+using static DubboNet.Clients.DubboClient;
+
+namespace DubboNet.Clients
+{
+ /// <summary>管理单个服务的 Provider、共享连接及负载状态。EN: Manages providers, shared
connections and load state for one service.</summary>
+ internal class DubboServiceDriver : IDisposable
+ {
+ internal class DubboServiceDriverConf
+ {
+ public int DubboActuatorSuiteMaxConnections { get; set; } = 20;
+ public int DubboActuatorSuiteAssistConnectionAliveTime { get; set;
} = 60 * 5;
+ public int DubboActuatorSuiteMasterConnectionAliveTime { get; set;
} = 60 * 20;
+ public int DubboRequestTimeout { get; set; } = 60 * 1000;
+ }
+
+ private sealed class MethodProvider
+ {
+ internal readonly RequestLoadStatistics Statistics = new();
+ internal long CurrentWeight;
+ internal volatile bool Retired;
+ }
+
+ private sealed class MethodState
+ {
+ internal readonly Dictionary<IPEndPoint, MethodProvider> Providers
= new();
+ internal double LastUsed;
+ internal MethodProvider For(IPEndPoint endpoint)
+ {
+ if (!Providers.TryGetValue(endpoint, out var provider))
Providers.Add(endpoint, provider = new MethodProvider());
+ return provider;
+ }
+ }
+
+ private sealed class CandidateSet
+ {
+ internal readonly DubboServiceEndPointInfo[] Providers;
+ internal readonly long[] PrefixWeights;
+ internal readonly long TotalWeight;
+ internal DubboSuiteConsistentHash Hash;
+
+ internal CandidateSet(IEnumerable<DubboServiceEndPointInfo>
providers)
+ {
+ Providers = providers.OrderBy(item =>
item.EndPoint.ToString(), StringComparer.Ordinal).ToArray();
+ PrefixWeights = new long[Providers.Length];
+ for (int i = 0; i < Providers.Length; i++) PrefixWeights[i] =
TotalWeight += Providers[i].Weight;
+ }
+ }
+
+ private readonly object _sync = new();
+ private readonly Dictionary<IPEndPoint, DubboServiceEndPointInfo>
_endpoints = new();
+ private readonly Dictionary<IPEndPoint, DubboActuatorSuiteEndPintInfo>
_shared;
+ private readonly Dictionary<int, CandidateSet> _candidates = new();
+ private readonly Dictionary<string, MethodState> _methods =
new(StringComparer.Ordinal);
+ private readonly DubboServiceDriverConf _configuration;
+ private readonly Func<double> _clock;
+ private readonly Func<long, long> _random;
+ private readonly Func<DubboServiceEndPointInfo, IDubboActuatorSuite>
_factory;
+ private bool _disposed;
+ private long _lastActivateTicks;
+
+ public string ServiceName { get; }
+ public DateTime LastActivateTime => new
DateTime(System.Threading.Interlocked.Read(ref _lastActivateTicks));
+ // Callers cannot enumerate a dictionary while a registry watcher
mutates it.
+ public Dictionary<IPEndPoint, DubboServiceEndPointInfo>
InnerActuatorSuites
+ { get { lock (_sync) return new Dictionary<IPEndPoint,
DubboServiceEndPointInfo>(_endpoints); } }
+ internal int ProviderCount { get { lock (_sync) return
_endpoints.Count; } }
+
+ public DubboServiceDriver(string serviceName,
List<DubboServiceEndPointInfo> dbEpList,
+ Dictionary<IPEndPoint, DubboActuatorSuiteEndPintInfo>
dubboActuatorSuiteCollection,
+ DubboServiceDriverConf dubboServiceDriverConf = null, Func<double>
clock = null,
+ Func<long, long> random = null, Func<DubboServiceEndPointInfo,
IDubboActuatorSuite> factory = null)
+ {
+ ArgumentNullException.ThrowIfNull(dbEpList);
+ ArgumentNullException.ThrowIfNull(dubboActuatorSuiteCollection);
+ ServiceName = serviceName;
+ _shared = dubboActuatorSuiteCollection;
+ _configuration = dubboServiceDriverConf ?? new
DubboServiceDriverConf();
+ _clock = clock ?? RequestLoadStatistics.MonotonicMilliseconds;
+ _random = random ?? Random.Shared.NextInt64;
+ _factory = factory ?? CreateSuite;
+ _lastActivateTicks = DateTime.Now.Ticks;
+ try { UpdateActuatorSuiteEndPoints(dbEpList); }
+ catch { Dispose(); throw; }
+ }
+
+ private IDubboActuatorSuite CreateSuite(DubboServiceEndPointInfo
endpoint)
+ {
+ var options = new DubboActuatorSuiteConf
+ {
+ AssistConnectionAliveTime =
_configuration.DubboActuatorSuiteAssistConnectionAliveTime,
+ MasterConnectionAliveTime =
_configuration.DubboActuatorSuiteMasterConnectionAliveTime,
+ DubboRequestTimeout = _configuration.DubboRequestTimeout,
+ MaxConnections =
_configuration.DubboActuatorSuiteMaxConnections
+ };
+ if (string.Equals(endpoint.Scheme, "dubbo",
StringComparison.OrdinalIgnoreCase))
+ return new NativeDubboActuatorSuite(endpoint.EndPoint,
options);
+ if (string.Equals(endpoint.Scheme, "tri",
StringComparison.OrdinalIgnoreCase))
+ return new TripleDubboActuatorSuite(endpoint.EndPoint,
options);
+ return new TelnetDubboActuatorSuite(endpoint.EndPoint, options);
+ }
+
+ private void RegisterMetadata(DubboServiceEndPointInfo endpoint)
+ {
+ if (string.IsNullOrWhiteSpace(endpoint.Interface))
endpoint.Interface = ServiceName;
+ if (endpoint.InnerDubboActuatorSuite is NativeDubboActuatorSuite
native) native.RegisterService(endpoint);
+ else if (endpoint.InnerDubboActuatorSuite is
TripleDubboActuatorSuite triple) triple.RegisterService(endpoint);
+ }
+
+ public int UpdateActuatorSuiteEndPoints(List<DubboServiceEndPointInfo>
dbEpList)
+ {
+ ArgumentNullException.ThrowIfNull(dbEpList);
+ if (dbEpList.Any(item => item?.EndPoint == null))
+ throw new ArgumentException("Provider snapshots must contain
non-null endpoints.", nameof(dbEpList));
+ var retired = new List<IDubboActuatorSuite>();
+ int changes = 0;
+ try
+ {
+ lock (_sync)
+ {
+ if (_disposed) return 0;
+ var latest = dbEpList.Where(item => item.Disabled !=
true).Select(item => item.RoutingSnapshot()).GroupBy(item => item.EndPoint)
+ .ToDictionary(group => group.Key, group =>
group.Last());
+ // Invalidate before mutating, including when creating a
new connection fails.
+ _candidates.Clear();
+ foreach (IPEndPoint endpoint in _endpoints.Keys.Where(key
=> !latest.ContainsKey(key)).ToArray())
+ {
+ _endpoints.Remove(endpoint);
+ foreach (MethodState method in _methods.Values)
+ if (method.Providers.TryGetValue(endpoint, out var
state))
+ {
+ state.Retired = true;
+ if (state.Statistics.Active == 0)
method.Providers.Remove(endpoint);
+ }
+ IDubboActuatorSuite unused =
ReleaseReference(endpoint);
+ if (unused != null) retired.Add(unused);
+ changes++;
+ }
+ foreach (var pair in latest)
+ {
+ DubboServiceEndPointInfo endpoint = pair.Value;
+ if (_endpoints.TryGetValue(pair.Key, out var previous))
+ {
+ endpoint.InnerDubboActuatorSuite =
previous.InnerDubboActuatorSuite;
+ if (previous.Weight != endpoint.Weight)
+ foreach (MethodState method in _methods.Values)
+ if (method.Providers.TryGetValue(pair.Key,
out var state)) state.CurrentWeight = 0;
+ }
+ else
+ {
+ lock (_shared)
+ {
+ if (!_shared.TryGetValue(pair.Key, out var
shared))
Review Comment:
已在 a62f339 修复:端点去重、共享执行器、方法统计和在途引用数统一使用 endpoint + scheme + version + group
的内部身份,避免同端口不同协议及默认服务元数据互相覆盖。匹配身份的跨服务连接仍复用;注册快照协议变化时旧连接只保留到在途调用完成。覆盖相反加载顺序、同
socket 多协议/多身份、协议变化及引用释放,261 项全量测试通过。
##########
Clients/DubboServiceDriver.cs:
##########
@@ -0,0 +1,389 @@
+using DubboNet.Clients.DataModle;
+using DubboNet.Clients.Helper;
+using DubboNet.Clients.LoadBalancing;
+using DubboNet.DubboService;
+using DubboNet.DubboService.DataModle;
+using MyCommonHelper;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Text;
+using static DubboNet.Clients.DubboClient;
+
+namespace DubboNet.Clients
+{
+ /// <summary>管理单个服务的 Provider、共享连接及负载状态。EN: Manages providers, shared
connections and load state for one service.</summary>
+ internal class DubboServiceDriver : IDisposable
+ {
+ internal class DubboServiceDriverConf
+ {
+ public int DubboActuatorSuiteMaxConnections { get; set; } = 20;
+ public int DubboActuatorSuiteAssistConnectionAliveTime { get; set;
} = 60 * 5;
+ public int DubboActuatorSuiteMasterConnectionAliveTime { get; set;
} = 60 * 20;
+ public int DubboRequestTimeout { get; set; } = 60 * 1000;
+ }
+
+ private sealed class MethodProvider
+ {
+ internal readonly RequestLoadStatistics Statistics = new();
+ internal long CurrentWeight;
+ internal volatile bool Retired;
+ }
+
+ private sealed class MethodState
+ {
+ internal readonly Dictionary<IPEndPoint, MethodProvider> Providers
= new();
+ internal double LastUsed;
+ internal MethodProvider For(IPEndPoint endpoint)
+ {
+ if (!Providers.TryGetValue(endpoint, out var provider))
Providers.Add(endpoint, provider = new MethodProvider());
+ return provider;
+ }
+ }
+
+ private sealed class CandidateSet
+ {
+ internal readonly DubboServiceEndPointInfo[] Providers;
+ internal readonly long[] PrefixWeights;
+ internal readonly long TotalWeight;
+ internal DubboSuiteConsistentHash Hash;
+
+ internal CandidateSet(IEnumerable<DubboServiceEndPointInfo>
providers)
+ {
+ Providers = providers.OrderBy(item =>
item.EndPoint.ToString(), StringComparer.Ordinal).ToArray();
+ PrefixWeights = new long[Providers.Length];
+ for (int i = 0; i < Providers.Length; i++) PrefixWeights[i] =
TotalWeight += Providers[i].Weight;
+ }
+ }
+
+ private readonly object _sync = new();
+ private readonly Dictionary<IPEndPoint, DubboServiceEndPointInfo>
_endpoints = new();
+ private readonly Dictionary<IPEndPoint, DubboActuatorSuiteEndPintInfo>
_shared;
+ private readonly Dictionary<int, CandidateSet> _candidates = new();
+ private readonly Dictionary<string, MethodState> _methods =
new(StringComparer.Ordinal);
+ private readonly DubboServiceDriverConf _configuration;
+ private readonly Func<double> _clock;
+ private readonly Func<long, long> _random;
+ private readonly Func<DubboServiceEndPointInfo, IDubboActuatorSuite>
_factory;
+ private bool _disposed;
+ private long _lastActivateTicks;
+
+ public string ServiceName { get; }
+ public DateTime LastActivateTime => new
DateTime(System.Threading.Interlocked.Read(ref _lastActivateTicks));
+ // Callers cannot enumerate a dictionary while a registry watcher
mutates it.
+ public Dictionary<IPEndPoint, DubboServiceEndPointInfo>
InnerActuatorSuites
+ { get { lock (_sync) return new Dictionary<IPEndPoint,
DubboServiceEndPointInfo>(_endpoints); } }
+ internal int ProviderCount { get { lock (_sync) return
_endpoints.Count; } }
+
+ public DubboServiceDriver(string serviceName,
List<DubboServiceEndPointInfo> dbEpList,
+ Dictionary<IPEndPoint, DubboActuatorSuiteEndPintInfo>
dubboActuatorSuiteCollection,
+ DubboServiceDriverConf dubboServiceDriverConf = null, Func<double>
clock = null,
+ Func<long, long> random = null, Func<DubboServiceEndPointInfo,
IDubboActuatorSuite> factory = null)
+ {
+ ArgumentNullException.ThrowIfNull(dbEpList);
+ ArgumentNullException.ThrowIfNull(dubboActuatorSuiteCollection);
+ ServiceName = serviceName;
+ _shared = dubboActuatorSuiteCollection;
+ _configuration = dubboServiceDriverConf ?? new
DubboServiceDriverConf();
+ _clock = clock ?? RequestLoadStatistics.MonotonicMilliseconds;
+ _random = random ?? Random.Shared.NextInt64;
+ _factory = factory ?? CreateSuite;
+ _lastActivateTicks = DateTime.Now.Ticks;
+ try { UpdateActuatorSuiteEndPoints(dbEpList); }
+ catch { Dispose(); throw; }
+ }
+
+ private IDubboActuatorSuite CreateSuite(DubboServiceEndPointInfo
endpoint)
+ {
+ var options = new DubboActuatorSuiteConf
+ {
+ AssistConnectionAliveTime =
_configuration.DubboActuatorSuiteAssistConnectionAliveTime,
+ MasterConnectionAliveTime =
_configuration.DubboActuatorSuiteMasterConnectionAliveTime,
+ DubboRequestTimeout = _configuration.DubboRequestTimeout,
+ MaxConnections =
_configuration.DubboActuatorSuiteMaxConnections
+ };
+ if (string.Equals(endpoint.Scheme, "dubbo",
StringComparison.OrdinalIgnoreCase))
+ return new NativeDubboActuatorSuite(endpoint.EndPoint,
options);
+ if (string.Equals(endpoint.Scheme, "tri",
StringComparison.OrdinalIgnoreCase))
+ return new TripleDubboActuatorSuite(endpoint.EndPoint,
options);
+ return new TelnetDubboActuatorSuite(endpoint.EndPoint, options);
+ }
+
+ private void RegisterMetadata(DubboServiceEndPointInfo endpoint)
+ {
+ if (string.IsNullOrWhiteSpace(endpoint.Interface))
endpoint.Interface = ServiceName;
+ if (endpoint.InnerDubboActuatorSuite is NativeDubboActuatorSuite
native) native.RegisterService(endpoint);
+ else if (endpoint.InnerDubboActuatorSuite is
TripleDubboActuatorSuite triple) triple.RegisterService(endpoint);
+ }
+
+ public int UpdateActuatorSuiteEndPoints(List<DubboServiceEndPointInfo>
dbEpList)
+ {
+ ArgumentNullException.ThrowIfNull(dbEpList);
+ if (dbEpList.Any(item => item?.EndPoint == null))
+ throw new ArgumentException("Provider snapshots must contain
non-null endpoints.", nameof(dbEpList));
+ var retired = new List<IDubboActuatorSuite>();
+ int changes = 0;
+ try
+ {
+ lock (_sync)
+ {
+ if (_disposed) return 0;
+ var latest = dbEpList.Where(item => item.Disabled !=
true).Select(item => item.RoutingSnapshot()).GroupBy(item => item.EndPoint)
+ .ToDictionary(group => group.Key, group =>
group.Last());
+ // Invalidate before mutating, including when creating a
new connection fails.
+ _candidates.Clear();
+ foreach (IPEndPoint endpoint in _endpoints.Keys.Where(key
=> !latest.ContainsKey(key)).ToArray())
+ {
+ _endpoints.Remove(endpoint);
+ foreach (MethodState method in _methods.Values)
+ if (method.Providers.TryGetValue(endpoint, out var
state))
+ {
+ state.Retired = true;
+ if (state.Statistics.Active == 0)
method.Providers.Remove(endpoint);
+ }
+ IDubboActuatorSuite unused =
ReleaseReference(endpoint);
+ if (unused != null) retired.Add(unused);
+ changes++;
+ }
+ foreach (var pair in latest)
+ {
+ DubboServiceEndPointInfo endpoint = pair.Value;
+ if (_endpoints.TryGetValue(pair.Key, out var previous))
+ {
+ endpoint.InnerDubboActuatorSuite =
previous.InnerDubboActuatorSuite;
+ if (previous.Weight != endpoint.Weight)
+ foreach (MethodState method in _methods.Values)
+ if (method.Providers.TryGetValue(pair.Key,
out var state)) state.CurrentWeight = 0;
+ }
+ else
+ {
+ lock (_shared)
+ {
+ if (!_shared.TryGetValue(pair.Key, out var
shared))
+ {
+ var suite = _factory(endpoint) ?? throw
new InvalidOperationException("The provider factory returned no actuator
suite.");
+ shared = new DubboActuatorSuiteEndPintInfo
{ EndPoint = pair.Key, ActuatorSuite = suite };
+ _shared.Add(pair.Key, shared);
+ }
+ shared.ReferenceCount++;
+ endpoint.InnerDubboActuatorSuite =
shared.ActuatorSuite;
+ }
+ }
+ RegisterMetadata(endpoint);
+ foreach (MethodState method in _methods.Values)
+ if (method.Providers.TryGetValue(pair.Key, out var
state)) state.Retired = false;
+ _endpoints[pair.Key] = endpoint;
+ changes++;
+ }
+ }
+ }
+ finally { DisposeRetired(retired); }
+ return changes;
+ }
+
+ public IDubboActuatorSuite GetDubboActuatorSuite(LoadBalanceMode
loadBalanceMode, string qurey = null,
+ DubboActuatorProtocolType? requiredProtocol = null)
+ {
+ lock (_sync) return Select(loadBalanceMode, qurey,
requiredProtocol, null)?.InnerDubboActuatorSuite;
+ }
+
+ internal LoadBalancedInvocation SelectAndReserve(LoadBalanceMode mode,
string query,
+ DubboActuatorProtocolType? protocol, DubboInvocation invocation)
+ {
+ lock (_sync)
+ {
+ if (_disposed) return null;
+ MethodState method = Method(invocation);
+ DubboServiceEndPointInfo endpoint = Select(mode, query,
protocol, invocation, method);
+ if (endpoint == null) return null;
+ MethodProvider provider = method.For(endpoint.EndPoint);
+ RequestLoadStatistics statistics = provider.Statistics;
+ lock (_shared) _shared[endpoint.EndPoint].ReferenceCount++;
+ // Selection and active increment are indivisible to competing
requests on this driver.
+ return new
LoadBalancedInvocation(endpoint.InnerDubboActuatorSuite, statistics, _clock,
+ () => ReleaseInvocation(endpoint.EndPoint, method,
provider));
+ }
+ }
+
+ private DubboServiceEndPointInfo Select(LoadBalanceMode mode, string
query,
+ DubboActuatorProtocolType? protocol, DubboInvocation invocation,
MethodState method = null)
+ {
+ if ((uint)mode > (uint)LoadBalanceMode.P2CLoadBalance) throw new
ArgumentOutOfRangeException(nameof(mode));
+ System.Threading.Interlocked.Exchange(ref _lastActivateTicks,
DateTime.Now.Ticks);
+ if (_disposed) return null;
+ int key = protocol.HasValue ? (int)protocol.Value : -1;
+ if (!_candidates.TryGetValue(key, out var set))
+ {
+ set = new CandidateSet(_endpoints.Values.Where(item =>
item.Disabled != true && item.Weight > 0
Review Comment:
已在 a62f339 修复:候选集缓存键包含 protocol/version/group,仅对显式 version/group
作精确筛选,无匹配返回不可用。一致性 Hash 也仅从筛选后的候选集取节点。还修复了 Nacos
两个发现路径按地址过早去重的同类问题。新增六种负载模式、只指定 version/只指定 group、无匹配以及同 socket 多身份的回归测试;全量 261
项通过。
##########
.vscode/tasks.json:
##########
@@ -0,0 +1,81 @@
+{
Review Comment:
本轮保留可选开发脚手架,未顺带删除功能。检查当前 tasks.json 使用的是 ${workspaceFolder}
相对路径,而不是某台机器的绝对路径;是否统一迁到 .devcontainer/ 可以另行整理,不作为本轮已解决事项。
##########
DubboService/Native/DubboHessian2Reader.cs:
##########
@@ -0,0 +1,520 @@
+using System;
+using System.Buffers.Binary;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+
+namespace DubboNet.DubboService.Native
+{
+ /// <summary>
+ /// 将 Hessian2 值读取为动态 .NET 列表和字典,用于 CLR 返回类型未知的 Dubbo 泛化响应。
+ /// <para>EN: Reads Hessian2 values into dynamic .NET lists and
dictionaries for generic Dubbo responses whose CLR result type is
unknown.</para>
+ /// </summary>
+ internal sealed class DubboHessian2Reader
+ {
+ private sealed class ClassDefinition
+ {
+ public string TypeName { get; set; }
+ public string[] Fields { get; set; }
+ }
+
+ private readonly byte[] _buffer;
+ private readonly List<object> _references = new List<object>();
+ private readonly List<string> _typeReferences = new List<string>();
+ private readonly List<ClassDefinition> _classDefinitions = new
List<ClassDefinition>();
+ private int _position;
+
+ /// <summary>
+ /// 创建读取指定 Hessian2 数据的解析器。
+ /// <para>EN: Creates a reader for the supplied Hessian2
payload.</para>
+ /// </summary>
+ public DubboHessian2Reader(byte[] buffer)
+ {
+ _buffer = buffer ?? throw new
ArgumentNullException(nameof(buffer));
+ }
+
+ /// <summary>
+ /// 读取一个 Hessian2 整数。
+ /// <para>EN: Reads one Hessian2 integer.</para>
+ /// </summary>
+ public int ReadInt()
+ {
+ return ReadInt(ReadByte());
+ }
+
+ /// <summary>
+ /// 读取一个 Hessian2 字符串。
+ /// <para>EN: Reads one Hessian2 string.</para>
+ /// </summary>
+ public string ReadString()
+ {
+ return ReadString(ReadByte());
+ }
+
+ /// <summary>
+ /// 读取下一个动态 Hessian2 值。
+ /// <para>EN: Reads the next dynamic Hessian2 value.</para>
+ /// </summary>
+ public object ReadValue()
+ {
+ byte tag = ReadByte();
+ if (tag == (byte)'N') return null;
+ if (tag == (byte)'T') return true;
+ if (tag == (byte)'F') return false;
+
+ if (IsIntTag(tag)) return ReadInt(tag);
+ if (IsLongTag(tag)) return ReadLong(tag);
+ if (IsDoubleTag(tag)) return ReadDouble(tag);
+
+ if (tag == 0x4a)
+ {
+ return
DateTimeOffset.FromUnixTimeMilliseconds(ReadInt64()).UtcDateTime;
+ }
+ if (tag == 0x4b)
+ {
+ return DateTimeOffset.FromUnixTimeSeconds((long)ReadInt32() *
60).UtcDateTime;
+ }
+
+ if (IsStringTag(tag)) return ReadString(tag);
+ if (IsBinaryTag(tag)) return ReadBinary(tag);
+
+ if (IsListTag(tag)) return ReadList(tag);
+ if (tag == (byte)'C') return ReadClassDefinitionAndValue();
+ if (IsMapOrObjectTag(tag)) return ReadMapOrObject(tag);
+
+ if (tag == 0x51)
+ {
+ int reference = ReadInt();
+ if (reference < 0 || reference >= _references.Count)
+ {
+ throw new InvalidDataException($"Invalid Hessian2
reference index {reference}.");
+ }
+ return _references[reference];
+ }
+
+ throw new InvalidDataException($"Unsupported Hessian2 tag
0x{tag:x2}.");
+ }
+
+ private object ReadClassDefinitionAndValue()
+ {
+ string typeName = ReadString();
+ int fieldCount = ReadInt();
+ if (fieldCount < 0)
+ {
+ throw new InvalidDataException($"Invalid Hessian2 class field
count {fieldCount}.");
+ }
+
+ string[] fields = new string[fieldCount];
+ for (int i = 0; i < fields.Length; i++)
+ {
+ fields[i] = ReadString();
+ }
+ _classDefinitions.Add(new ClassDefinition
+ {
+ TypeName = typeName,
+ Fields = fields
+ });
+ return ReadValue();
+ }
+
+ private object ReadMapOrObject(byte tag)
+ {
+ if (tag == (byte)'H' || tag == (byte)'M')
+ {
+ string typeName = tag == (byte)'M' ? ReadType() : null;
+ Dictionary<object, object> map = NewMap(typeName);
+ _references.Add(map);
+ while (PeekByte() != (byte)'Z')
+ {
+ object key = ReadValue();
+ object value = ReadValue();
+ map[key ?? "null"] = value;
+ }
+ _position++;
+ return map;
+ }
+
+ int definitionIndex = tag == (byte)'O' ? ReadInt() : tag - 0x60;
+ if (definitionIndex < 0 || definitionIndex >=
_classDefinitions.Count)
+ {
+ throw new InvalidDataException(
+ $"Invalid Hessian2 class definition index
{definitionIndex}.");
+ }
+
+ ClassDefinition definition = _classDefinitions[definitionIndex];
+ Dictionary<object, object> instance = NewMap(definition.TypeName);
+ _references.Add(instance);
+ foreach (string field in definition.Fields)
+ {
+ instance[field] = ReadValue();
+ }
+ return instance;
+ }
+
+ private static Dictionary<object, object> NewMap(string typeName)
+ {
+ Dictionary<object, object> result = new Dictionary<object,
object>();
+ if (!string.IsNullOrWhiteSpace(typeName))
+ {
+ result["class"] = typeName;
+ }
+ return result;
+ }
+
+ private object ReadList(byte tag)
+ {
+ bool hasEnd;
+ int length;
+
+ switch (tag)
+ {
+ case 0x55:
+ _ = ReadType();
+ hasEnd = true;
+ length = -1;
+ break;
+ case 0x56:
+ _ = ReadType();
+ hasEnd = false;
+ length = ReadInt();
+ break;
+ case 0x57:
+ hasEnd = true;
+ length = -1;
+ break;
+ case 0x58:
+ hasEnd = false;
+ length = ReadInt();
+ break;
+ default:
+ hasEnd = false;
+ if (tag >= 0x70 && tag <= 0x77)
+ {
+ length = tag - 0x70;
+ _ = ReadType();
+ }
+ else
+ {
+ length = tag - 0x78;
+ }
+ break;
+ }
+
+ if (length < -1)
+ {
+ throw new InvalidDataException($"Invalid Hessian2 list length
{length}.");
+ }
+
+ List<object> list = length > 0 ? new List<object>(length) : new
List<object>();
+ _references.Add(list);
+ if (hasEnd)
+ {
+ while (PeekByte() != (byte)'Z')
+ {
+ list.Add(ReadValue());
+ }
+ _position++;
+ }
+ else
+ {
+ for (int i = 0; i < length; i++)
+ {
+ list.Add(ReadValue());
Review Comment:
已在 a62f339 修复:ReadValue 的所有递归入口统一限制为 64 层,finally 回收深度计数;ToJsonCompatible
使用同一深度上限,防止浅 wire graph 通过引用展开成过深结构。超限抛 InvalidDataException。新增
list/map/object/连续 class definition 的 20,000 层响应、允许/拒绝边界以及引用链展开回归测试,全量 261 项通过。
##########
DubboService/TripleDubboActuatorSuite.cs:
##########
@@ -0,0 +1,483 @@
+using DubboNet.Clients.DataModle;
+using DubboNet.DubboService.DataModle;
+using DubboNet.DubboService.Native;
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Text;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace DubboNet.DubboService
+{
+ /// <summary>
+ /// 通过 Dubbo 3.3 引入的 HTTP/JSON 兼容端点调用 Dubbo Triple Java 接口一元方法。
+ /// EN: Invokes Dubbo Triple Java-interface unary methods through the
HTTP/JSON
+ /// compatibility endpoint introduced by Dubbo 3.3.
+ /// </summary>
+ /// <remarks>
+ /// 第一期实现仅面向使用 <c>application/json</c> 的 Java 接口一元调用,不包含
+ /// Protobuf IDL、流式调用和带帧的 gRPC 线协议。
+ /// EN: This first implementation intentionally targets unary
Java-interface calls
+ /// with <c>application/json</c>. Protobuf IDL, streaming and the framed
gRPC
+ /// wire format are outside its scope.
+ /// </remarks>
+ public sealed class TripleDubboActuatorSuite :
+ IDubboActuatorSuite,
+ IDubboGenericInvocationActuator
+ {
+ private const string ServiceVersionHeader = "tri-service-version";
+ private const string ServiceGroupHeader = "tri-service-group";
+ private const string ServiceTimeoutHeader = "tri-service-timeout";
+
+ private static readonly HashSet<string> ReservedRequestHeaders =
+ new HashSet<string>(StringComparer.OrdinalIgnoreCase)
+ {
+ "host",
+ "content-length",
+ "content-type",
+ "grpc-timeout",
+ ServiceVersionHeader,
+ ServiceGroupHeader,
+ ServiceTimeoutHeader
+ };
+
+ private sealed class ServiceMetadata
+ {
+ public string Version { get; set; }
+ public string Group { get; set; }
+ public int? Timeout { get; set; }
+ }
+
+ private readonly HttpClient _httpClient;
+ private readonly bool _ownsHttpClient;
+ private readonly int _requestTimeoutMilliseconds;
+ private readonly ConcurrentDictionary<string, ServiceMetadata>
_services =
+ new ConcurrentDictionary<string,
ServiceMetadata>(StringComparer.Ordinal);
+ private bool _disposed;
+
+ /// <inheritdoc/>
+ public DubboActuatorProtocolType ProtocolType =>
DubboActuatorProtocolType.Triple;
+
+ /// <inheritdoc/>
+ public string ServiceFuncSpit => "/";
+
+ /// <inheritdoc/>
+ public DubboActuatorSuiteStatus ActuatorSuiteStatusInfo { get; private
set; } =
+ new DubboActuatorSuiteStatus();
+
+ /// <inheritdoc/>
+ public DateTime LastActivateTime { get; private set; } = DateTime.Now;
+
+ /// <summary>
+ /// 获取默认的 Java 服务接口名。
+ /// EN: Gets the default Java service interface name.
+ /// </summary>
+ public string DefaultServiceName { get; private set; }
+
+ /// <summary>
+ /// 使用指定地址和端口创建 Triple HTTP/JSON 执行器。
+ /// EN: Creates a Triple HTTP/JSON actuator from an address and port.
+ /// </summary>
+ /// <param name="address">Provider 地址。EN: Provider address.</param>
+ /// <param name="port">Provider 端口。EN: Provider port.</param>
+ /// <param name="dubboActuatorSuiteConf">执行器配置。EN: Actuator
configuration.</param>
+ public TripleDubboActuatorSuite(
+ string address,
+ int port,
+ DubboActuatorSuiteConf dubboActuatorSuiteConf = null)
+ : this(
+ CreateHttpClient(address, port, dubboActuatorSuiteConf),
+ dubboActuatorSuiteConf,
+ true)
+ {
+ }
+
+ /// <summary>
+ /// 使用网络端点创建 Triple HTTP/JSON 执行器。
+ /// EN: Creates a Triple HTTP/JSON actuator from a network endpoint.
+ /// </summary>
+ /// <param name="endPoint">Provider 网络端点。EN: Provider network
endpoint.</param>
+ /// <param name="dubboActuatorSuiteConf">执行器配置。EN: Actuator
configuration.</param>
+ public TripleDubboActuatorSuite(
+ IPEndPoint endPoint,
+ DubboActuatorSuiteConf dubboActuatorSuiteConf = null)
+ : this(
+ endPoint?.Address.ToString()
+ ?? throw new ArgumentNullException(nameof(endPoint)),
+ endPoint.Port,
+ dubboActuatorSuiteConf)
+ {
+ }
+
+ internal TripleDubboActuatorSuite(
+ HttpClient httpClient,
+ DubboActuatorSuiteConf dubboActuatorSuiteConf = null)
+ : this(httpClient, dubboActuatorSuiteConf, false)
+ {
+ }
+
+ private TripleDubboActuatorSuite(
+ HttpClient httpClient,
+ DubboActuatorSuiteConf dubboActuatorSuiteConf,
+ bool ownsHttpClient)
+ {
+ _httpClient = httpClient ?? throw new
ArgumentNullException(nameof(httpClient));
+ if (_httpClient.BaseAddress == null)
+ {
+ throw new ArgumentException(
+ "Triple HttpClient must define BaseAddress.",
+ nameof(httpClient));
+ }
+
+ DubboActuatorSuiteConf configuration =
+ dubboActuatorSuiteConf ?? new DubboActuatorSuiteConf();
+ DefaultServiceName = configuration.DefaultServiceName;
+ _requestTimeoutMilliseconds = Math.Max(1,
configuration.DubboRequestTimeout);
+ _ownsHttpClient = ownsHttpClient;
+ }
+
+ internal void RegisterService(DubboServiceEndPointInfo endpoint)
+ {
+ if (endpoint == null)
+ {
+ throw new ArgumentNullException(nameof(endpoint));
+ }
+ if (string.IsNullOrWhiteSpace(endpoint.Interface))
+ {
+ return;
+ }
+
+ _services[endpoint.Interface] = new ServiceMetadata
+ {
+ Version = endpoint.Version,
+ Group = endpoint.Group,
+ Timeout = endpoint.Timeout
+ };
+ }
+
+ /// <inheritdoc/>
+ public Task<DubboRequestResult> SendQuery(string endPoint)
+ {
+ return SendQuery(endPoint, string.Empty);
+ }
+
+ /// <inheritdoc/>
+ public Task<DubboRequestResult> SendQuery(string endPoint, string req)
+ {
+ if (!string.IsNullOrWhiteSpace(DefaultServiceName)
+ && !string.IsNullOrWhiteSpace(endPoint)
+ && !endPoint.Contains("#")
+ && !endPoint.Contains("/")
+ && !endPoint.Contains("."))
+ {
+ endPoint = $"{DefaultServiceName}.{endPoint}";
+ }
+
+ DubboInvocation invocation =
NativeDubboCodec.ParseInvocation(endPoint, req);
+ return SendQuery(invocation);
+ }
+
+ /// <inheritdoc/>
+ public Task<DubboRequestResult> SendQuery(DubboInvocation invocation)
+ {
+ return SendQuery(invocation, CancellationToken.None);
+ }
+
+ /// <inheritdoc/>
+ public async Task<DubboRequestResult> SendQuery(
+ DubboInvocation invocation,
+ CancellationToken cancellationToken)
+ {
+ if (_disposed)
+ {
+ throw new
ObjectDisposedException(nameof(TripleDubboActuatorSuite));
+ }
+
+ invocation.Validate();
+ LastActivateTime = DateTime.Now;
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ DubboRequestResult result = new DubboRequestResult
+ {
+ ServiceElapsed = 0,
+ ServiceElapsedAvailable = false
+ };
+
+ _services.TryGetValue(invocation.Service, out ServiceMetadata
metadata);
+ string version = FirstNonBlank(invocation.Version,
metadata?.Version);
+ string group = FirstNonBlank(invocation.Group, metadata?.Group);
+ int timeoutMilliseconds = Math.Max(
+ 1,
+ metadata?.Timeout ?? _requestTimeoutMilliseconds);
+
+ string requestPath =
$"/{Uri.EscapeDataString(invocation.Service)}" +
+ $"/{Uri.EscapeDataString(invocation.Method)}";
+ string requestBody =
JsonSerializer.Serialize(invocation.Arguments);
+
+ try
+ {
+ using HttpRequestMessage request = new
HttpRequestMessage(HttpMethod.Post, requestPath)
+ {
+ Version = HttpVersion.Version11,
+ VersionPolicy = HttpVersionPolicy.RequestVersionExact,
+ Content = new StringContent(requestBody, Encoding.UTF8,
"application/json")
+ };
+
+ AddHeader(request, ServiceVersionHeader, version);
+ AddHeader(request, ServiceGroupHeader, group);
+ AddHeader(request, ServiceTimeoutHeader,
timeoutMilliseconds.ToString());
+ AddAttachments(request, invocation.Attachments);
+
+ using HttpResponseMessage response = await
_httpClient.SendAsync(
+ request,
+ HttpCompletionOption.ResponseHeadersRead,
+ cancellationToken).ConfigureAwait(false);
+ string responseBody = await response.Content
+ .ReadAsStringAsync(cancellationToken)
Review Comment:
已在 a62f339 修复:每次调用创建 linked CTS,按实际 timeout 设置 CancelAfter,同一个 token 同时传入
SendAsync 和 ReadAsStringAsync,并在完成后释放 CTS/response。新增延迟响应头、正文永久停滞、调用方提前取消和
Provider timeout 元数据测试,均在本地截止时间内结束。
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]