AlexStocks commented on code in PR #1: URL: https://github.com/apache/dubbo-net/pull/1#discussion_r4430866939
########## DubboService/TripleDubboActuatorSuite.cs: ########## @@ -0,0 +1,504 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +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 + { + // ResponseHeadersRead ends HttpClient.Timeout at the headers. Keep a Review Comment: 🟡 **两套超时机制并存,provider 声明的 timeout 大于默认值时永远不会生效** 这里新加了 per-call 的 linked CTS,但 `CreateHttpClient` 里 `HttpClient.Timeout = Max(1, configuration.DubboRequestTimeout)` 还在(约第 401 行)。于是同一次请求有两个截止时间,来源不同: - 客户端级:`DubboRequestTimeout`,创建 HttpClient 时定死; - 单次调用级:`metadata?.Timeout ?? _requestTimeoutMilliseconds`,`metadata.Timeout` 来自 provider URL 的 `timeout` 参数(`RegisterService` 里 `Timeout = endpoint.Timeout`)。 **为什么这是 bug**:HttpClient.Timeout 至少覆盖到响应头读完为止。provider 广告 `timeout=30000`、而客户端默认 `DubboRequestTimeout=1500` 时,即使走到这里 `timeoutMilliseconds=30000`,请求仍会在 1.5s 被 HttpClient 掐掉,`tri-service-timeout` 头的语义等于失效。作者写的测试用的是 `Timeout = Timeout.InfiniteTimeSpan` 的 HttpClient,正好绕开了这条路径,所以测不出来。 **Suggestion**:既然已经有单体 deadline,把客户端级那条去掉,让这一个 CTS 成为唯一定时源;再补一个 `metadata.Timeout > DubboRequestTimeout` 的用例。 ```csharp HttpClient client = new HttpClient(handler) { BaseAddress = new Uri($"http://{address}:{port}"), Timeout = Timeout.InfiniteTimeSpan // 由每次调用的 linked CTS 负责 }; ``` 顺带说一句:注释里那句「ResponseHeadersRead ends HttpClient.Timeout at the headers」如果成立,那它更应该删掉;如果不成立,那句注释本身是错的。两种情况都指向同一个动作。 ########## Clients/DubboServiceDriver.cs: ########## @@ -0,0 +1,419 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +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<DubboEndpointKey, MethodProvider> Providers = new(); + internal double LastUsed; + internal MethodProvider For(DubboServiceEndPointInfo endpoint) => For(DubboEndpointKey.From(endpoint)); + internal MethodProvider For(DubboEndpointKey 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 Dictionary<IPEndPoint, DubboServiceEndPointInfo> HashProviders; + + internal CandidateSet(IEnumerable<DubboServiceEndPointInfo> providers) + { + Providers = providers.OrderBy(item => item.EndPoint.ToString(), StringComparer.Ordinal) + .ThenBy(item => item.Scheme, StringComparer.Ordinal) + .ThenBy(item => item.Version, StringComparer.Ordinal) + .ThenBy(item => item.Group, 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<DubboEndpointKey, DubboServiceEndPointInfo> _endpoints = new(); + private readonly Dictionary<DubboEndpointKey, DubboActuatorSuiteEndPintInfo> _shared; + private readonly Dictionary<(int Protocol, string Version, string Group), 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<DubboEndpointKey, DubboServiceEndPointInfo> InnerActuatorSuites + { get { lock (_sync) return new Dictionary<DubboEndpointKey, DubboServiceEndPointInfo>(_endpoints); } } + internal int ProviderCount { get { lock (_sync) return _endpoints.Count; } } + + public DubboServiceDriver(string serviceName, List<DubboServiceEndPointInfo> dbEpList, + Dictionary<DubboEndpointKey, 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(DubboEndpointKey.From) + .ToDictionary(group => group.Key, group => group.Last()); + // Invalidate before mutating, including when creating a new connection fails. + _candidates.Clear(); + foreach (DubboEndpointKey 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 = endpoint.EndPoint, 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; + DubboEndpointKey endpointKey = DubboEndpointKey.From(endpoint); + MethodProvider provider = method.For(endpointKey); + RequestLoadStatistics statistics = provider.Statistics; + lock (_shared) _shared[endpointKey].ReferenceCount++; + // Selection and active increment are indivisible to competing requests on this driver. + return new LoadBalancedInvocation(endpoint.InnerDubboActuatorSuite, statistics, _clock, + () => ReleaseInvocation(endpointKey, 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; + string version = string.IsNullOrWhiteSpace(invocation?.Version) ? null : invocation.Version; + string group = string.IsNullOrWhiteSpace(invocation?.Group) ? null : invocation.Group; + var key = (protocol.HasValue ? (int)protocol.Value : -1, version, group); Review Comment: 💭 **严格 version/group 匹配是行为变更,建议写进兼容性说明** 过滤逻辑本身是对的(`Version`/`Group` 为 null 时不加约束,非 null 时精确匹配 `Ordinal`),也和 Java Dubbo 的语义一致。但相比改动前「显式指定 version 也照样可能命中其它身份」的行为,这是一次静默收紧:以前能跑通的调用,现在可能返回 null(no provider 可用)。 **Suggestion**:在 README 的兼容性表里补一行,说明「显式指定 version/group 时不再回退到不匹配身份的 provider」。这类变更如果只留在代码里,升级的人会很难定位。 ########## DubboService/TripleDubboActuatorSuite.cs: ########## @@ -0,0 +1,504 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +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 + { + // ResponseHeadersRead ends HttpClient.Timeout at the headers. Keep a + // single deadline alive until the complete body has been consumed. + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(timeoutMilliseconds); + 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, + timeout.Token).ConfigureAwait(false); + string responseBody = await response.Content + .ReadAsStringAsync(timeout.Token) + .ConfigureAwait(false); + + stopwatch.Stop(); + result.RequestElapsed = (int)stopwatch.ElapsedMilliseconds; + result.Result = responseBody; + result.RawResult = ParseResponseValue(responseBody); + result.ResponseAttachments = ReadResponseHeaders(response); + + if (!response.IsSuccessStatusCode) + { + result.UpdateQueryFailed(); + result.ErrorMeaasge = BuildHttpError(response, responseBody); + } + } + catch (Exception exception) Review Comment: 🟡 **调用方取消被吞成「查询失败」,与超时无法区分** `catch (Exception)` 把 `OperationCanceledException` 一起接住了,统一变成 `result.UpdateQueryFailed()` + `ErrorMeaasge = exception.Message`。于是: - 调用方主动 `Cancel()` → 拿到一个「失败结果」而非 `OperationCanceledException`; - 超时 → 同样拿到失败结果,`ErrorMeaasge` 是 `"The operation was canceled."`,不含超时时长、不看不出是超时。 **为什么重要**:`Task.WhenAll` / 上层 `CancellationToken` 传播链里,取消语义被降级成业务失败后,上层无法中止整批请求,日志里也只剩一句通用取消消息。顺便说明:新增的 `TripleDeadlineCoversHeadersBodyCallerCancellationAndProviderTimeout` 用 `Assert.False(result.QuerySuccess)` 把这个行为固化下来了,测试是通过的,但它验证的是「取消 → 失败结果」而不是「取消 → 抛异常」。 **Suggestion**:把取消透传,超时给明确原因。 ```csharp catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; // 调用方取消,保持 .NET 惯例 } catch (Exception exception) { stopwatch.Stop(); result.RequestElapsed = (int)stopwatch.ElapsedMilliseconds; result.UpdateQueryFailed(); result.ErrorMeaasge = stopwatch.ElapsedMilliseconds >= timeoutMilliseconds ? $"Triple request timed out after {timeoutMilliseconds} ms." : exception.Message; } ``` 如果维持现状是刻意选择(RPC 客户端不抛异常),那至少让 `ErrorMeaasge` 在超时分支可读,并在 README 里写清「取消返回失败结果而不是异常」。 ########## Tests/Shared/TestEndpointOptions.cs: ########## @@ -0,0 +1,138 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System.Net; +using System.Net.Sockets; + +namespace DubboNet.Testing; + +// Shared only by the examples/tests; this is not part of the library's API. +internal sealed record TestEndpointOptions( + string RegistryAddress, + string ProviderHost, + bool PrintConfiguration, + bool ShowHelp) +{ + public const string Usage = """ + Options: + --host HOST Registry/provider host (default: localhost). + --registry ADDRESS ZooKeeper address or nacos:// address. + --provider-host HOST Override the direct provider host independently. + --nacos Use Nacos instead of ZooKeeper. + --print-config Print resolved configuration without network I/O. + --help Show this help without running requests. + The first positional argument remains a registry address or 'nacos'. + Environment: DUBBONET_TEST_HOST, DUBBONET_TEST_REGISTRY, + DUBBONET_TEST_PROVIDER_HOST. + """; + + public static TestEndpointOptions Parse( + string[] arguments, + Func<string, string?>? readEnvironment = null) + { + readEnvironment ??= Environment.GetEnvironmentVariable; + string? host = null, registry = null, provider = null; + bool nacos = false, print = false, help = false; + for (int index = 0; index < arguments.Length; index++) + { + string argument = arguments[index]; + switch (argument) + { + case "--host": host = Value(); break; + case "--registry": registry = Value(); break; + case "--provider-host": provider = Value(); break; + case "--nacos": nacos = true; break; + case "--print-config": print = true; break; + case "--help": case "-h": help = true; break; + default: + if (argument.StartsWith('-') || registry != null) + throw new ArgumentException($"Unexpected argument: {argument}"); + registry = argument; + break; + } + + string Value() + { + if (++index >= arguments.Length || string.IsNullOrWhiteSpace(arguments[index]) + || arguments[index].StartsWith("--", StringComparison.Ordinal)) + throw new ArgumentException($"{argument} requires a value."); + return arguments[index].Trim(); + } + } + + string? environmentHost = Read("DUBBONET_TEST_HOST"); + string effectiveHost = Host(host ?? environmentHost ?? "localhost"); + registry ??= host != null || nacos ? null : Read("DUBBONET_TEST_REGISTRY"); Review Comment: 💭 **`--nacos` 会静默忽略 `DUBBONET_TEST_REGISTRY`** 这一行在 `nacos==true` 或 `--host` 存在时干脆不读环境变量里的 registry。后果:CI/脚本里已经导出了 `DUBBONET_TEST_REGISTRY=nacos://prod:8848`,只因为多带了 `--nacos` 就悄悄跑到 `nacos://<host>:8848`,而 `--print-config` 之外没有任何提示。这种「参数和环境变量冲突时静默选一个」的行为最难排。 **Suggestion**:让显式 registry 优先于 `--nacos` 快捷方式;或者两者冲突时直接 `throw`(这个文件其它地方对歧义输入就是抛 `ArgumentException`,风格上也一致): ```csharp string? environmentRegistry = Read("DUBBONET_TEST_REGISTRY"); if (nacos && host == null && environmentRegistry != null) throw new ArgumentException("Use either --nacos or DUBBONET_TEST_REGISTRY, not both."); ``` 其余解析逻辑我逐条对过测试(IPv6 加括号、`localhost:0` 拒绝、多点注册中心缺端口拒绝、位置参数兼容),没发现别的问题。 ########## DubboService/Native/DubboHessian2Reader.cs: ########## @@ -0,0 +1,549 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +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 + { + // Also used when expanding references into JSON-compatible response values. + internal const int MaxNestingDepth = 64; Review Comment: 💭 **64 层是硬编码上限,且现在同时约束「引用展开后的图」** wire 上的嵌套深度和展开后的图深度是两件事。`HessianDepthLimitAcceptsBoundaryAndAlsoBoundsReferenceExpansion` 那个用例说明:一个线上只有 2 层、靠 100 个兄弟节点引用串起来的合法结构,现在也会被判定为 `InvalidDataException`。作为 DoS 防护这是合理的取舍,但有两个后果值得记一笔: - 真实业务里如果出现「深链」结构(列表里每个元素引用前一个),错误信息只会说 nesting 超限,排查的人很难想到是深度限制而不是数据损坏; - 64 这个值不可配置,将来遇到真实场景卡在 65 层就只能改代码发版。 **Suggestion**:至少把常量挂到 `DubboActuatorSuiteConf` / `DubboClient` 配置上(默认 64 不变),或者退一步——在异常信息和 README 里写清「响应嵌套(含引用展开)上限 64 层」。 ########## .github/workflows/build.yml: ########## @@ -0,0 +1,34 @@ +name: Build and test + +on: + push: + branches: [main, codex/import-dubbonet-history] Review Comment: 🟡 **个人工作分支名进了 ASF 官方工作流** `codex/import-dubbonet-history` 是这次导入用的个人分支。合并进 main 之后: - 官方仓库里每次有人(或误)推这个同名分支都会触发全量 build + docker 构建; - 这个分支名对后续维护者没有任何意义,属于残留配置。 现在它存在的唯一理由是「fork 里 push 也能跑 CI」,但 fork 要用 fork 自己的 workflow 定义就够,不需要官方仓库里留这一条。 **Suggestion**:合并前改成只有 `main`: ```yaml on: push: branches: [main] pull_request: branches: [main] workflow_dispatch: ``` `.github/workflows/license.yml:7` 同一处问题,一并改掉。 ########## Clients/DubboServiceDriver.cs: ########## @@ -0,0 +1,419 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +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<DubboEndpointKey, MethodProvider> Providers = new(); + internal double LastUsed; + internal MethodProvider For(DubboServiceEndPointInfo endpoint) => For(DubboEndpointKey.From(endpoint)); + internal MethodProvider For(DubboEndpointKey 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 Dictionary<IPEndPoint, DubboServiceEndPointInfo> HashProviders; + + internal CandidateSet(IEnumerable<DubboServiceEndPointInfo> providers) + { + Providers = providers.OrderBy(item => item.EndPoint.ToString(), StringComparer.Ordinal) + .ThenBy(item => item.Scheme, StringComparer.Ordinal) + .ThenBy(item => item.Version, StringComparer.Ordinal) + .ThenBy(item => item.Group, 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<DubboEndpointKey, DubboServiceEndPointInfo> _endpoints = new(); + private readonly Dictionary<DubboEndpointKey, DubboActuatorSuiteEndPintInfo> _shared; + private readonly Dictionary<(int Protocol, string Version, string Group), 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<DubboEndpointKey, DubboServiceEndPointInfo> InnerActuatorSuites + { get { lock (_sync) return new Dictionary<DubboEndpointKey, DubboServiceEndPointInfo>(_endpoints); } } + internal int ProviderCount { get { lock (_sync) return _endpoints.Count; } } + + public DubboServiceDriver(string serviceName, List<DubboServiceEndPointInfo> dbEpList, + Dictionary<DubboEndpointKey, 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(DubboEndpointKey.From) + .ToDictionary(group => group.Key, group => group.Last()); + // Invalidate before mutating, including when creating a new connection fails. + _candidates.Clear(); + foreach (DubboEndpointKey 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 = endpoint.EndPoint, 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; + DubboEndpointKey endpointKey = DubboEndpointKey.From(endpoint); + MethodProvider provider = method.For(endpointKey); + RequestLoadStatistics statistics = provider.Statistics; + lock (_shared) _shared[endpointKey].ReferenceCount++; + // Selection and active increment are indivisible to competing requests on this driver. + return new LoadBalancedInvocation(endpoint.InnerDubboActuatorSuite, statistics, _clock, + () => ReleaseInvocation(endpointKey, 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; + string version = string.IsNullOrWhiteSpace(invocation?.Version) ? null : invocation.Version; + string group = string.IsNullOrWhiteSpace(invocation?.Group) ? null : invocation.Group; + var key = (protocol.HasValue ? (int)protocol.Value : -1, version, group); + if (!_candidates.TryGetValue(key, out var set)) + { + set = new CandidateSet(_endpoints.Values.Where(item => item.Disabled != true && item.Weight > 0 + && (!protocol.HasValue || item.InnerDubboActuatorSuite.ProtocolType == protocol) + && (version == null || string.Equals(item.Version, version, StringComparison.Ordinal)) + && (group == null || string.Equals(item.Group, group, StringComparison.Ordinal)))); + if (_candidates.Count >= 1024) _candidates.Clear(); Review Comment: 💭 **`Clear()` 兜底缺一句注释** `if (_candidates.Count >= 1024) _candidates.Clear();` 是有意的兜底,但从代码看不出来为什么是 1024、为什么用全清而不是按 LRU 淘汰。缓存键现在含 `invocation.Version` / `invocation.Group` 两个调用方可控字符串,理论上能被撑大,所以这道闸门是有必要的——只是需要留一句「为什么」。 **Suggestion**: ```csharp // Bounded: (protocol, version, group) is partly caller-controlled. A full clear is // cheap because CandidateSet is rebuilt from _endpoints on the next miss. if (_candidates.Count >= 1024) _candidates.Clear(); ``` -- 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]
