NeverENG commented on code in PR #36:
URL: https://github.com/apache/dubbo-net/pull/36#discussion_r4510755709


##########
Registry/ProviderDiscovery.cs:
##########
@@ -0,0 +1,236 @@
+/*
+ * 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.RegistryClient;
+using MyCommonHelper;
+using org.apache.zookeeper;
+using org.apache.zookeeper.data;
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Net;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace DubboNet.Registry
+{
+    // Owns this client's Nacos provider subscriptions and in-flight discovery.
+    // The client owns registry leases and its ZooKeeper watcher; the service 
driver
+    // alone owns callable endpoint state. Metadata has a separate subscriber.
+    internal sealed class ProviderDiscovery : IDisposable
+    {
+        private readonly MyZookeeper _zookeeper;
+        private readonly MyNacos _nacos;
+        private readonly string _rootPath;
+        private readonly Watcher _watcher;
+        private readonly Func<string, Task> _onNacosChanged;
+        private readonly Action _onRegistryRecovered;
+        private readonly ConcurrentDictionary<(string Service, bool FullPath), 
Lazy<Task<DubboServiceEndPointInfos>>> _inFlight = new();
+        private int _disposed;
+
+        internal ProviderDiscovery(MyZookeeper zookeeper, MyNacos nacos, 
string rootPath,
+            Watcher watcher, Func<string, Task> onNacosChanged, Action 
onRegistryRecovered)
+        {
+            if ((zookeeper is null) == (nacos is null))
+                throw new ArgumentException("Exactly one Provider registry is 
required.");
+            if (string.IsNullOrWhiteSpace(rootPath))
+                throw new ArgumentException("Provider registry root cannot be 
empty.", nameof(rootPath));
+            if (zookeeper != null && watcher is null)
+                throw new ArgumentNullException(nameof(watcher));
+            _zookeeper = zookeeper;
+            _nacos = nacos;
+            _rootPath = rootPath;
+            _watcher = watcher;
+            _onNacosChanged = onNacosChanged ?? throw new 
ArgumentNullException(nameof(onNacosChanged));
+            _onRegistryRecovered = onRegistryRecovered ?? throw new 
ArgumentNullException(nameof(onRegistryRecovered));
+        }
+
+        internal bool IsDisposed => Volatile.Read(ref _disposed) != 0;
+
+        public void Dispose()
+        {
+            if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
+            // Remove only our Nacos Naming subscriptions. Metadata and other
+            // clients have distinct subscriber identities on the shared 
connection.
+            _nacos?.RemoveSubscriber(this);
+            // ZooKeeper watches are one-shot and have no per-watcher 
unsubscribe API;
+            // the owning client watcher checks IsDisposed before handling 
callbacks.
+        }
+
+        private Task OnNacosChangedAsync(string serviceName) =>
+            IsDisposed ? Task.CompletedTask : _onNacosChanged(serviceName);
+
+        internal bool TryGetServiceNameFromProviderPath(
+            string providerPath,
+            out string serviceName)
+        {
+            serviceName = null;
+            if (string.IsNullOrEmpty(providerPath)
+                || !providerPath.StartsWith(_rootPath, 
StringComparison.Ordinal)
+                || 
!providerPath.EndsWith(ZooKeeperRegistryPaths.ProvidersSuffix, 
StringComparison.Ordinal))
+            {
+                return false;
+            }
+
+            serviceName = providerPath.Substring(
+                _rootPath.Length,
+                providerPath.Length - _rootPath.Length - 
ZooKeeperRegistryPaths.ProvidersSuffix.Length);
+            return !string.IsNullOrWhiteSpace(serviceName);
+        }
+
+        internal async Task<DubboServiceEndPointInfos> 
GetProviderEndPointsAsync(string serviceName, bool isFullPath = false)

Review Comment:
   #34 已在 e2de98f 承接全部双语源码链接、方法名与状态归属同步;两份 PR 描述均明确先合并 #36、再合并 #34,并须在 #34 
合并前重新校验实际源码。



##########
Registry/ProviderDiscovery.cs:
##########
@@ -0,0 +1,236 @@
+/*
+ * 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.RegistryClient;
+using MyCommonHelper;
+using org.apache.zookeeper;
+using org.apache.zookeeper.data;
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Net;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace DubboNet.Registry
+{
+    // Owns this client's Nacos provider subscriptions and in-flight discovery.
+    // The client owns registry leases and its ZooKeeper watcher; the service 
driver
+    // alone owns callable endpoint state. Metadata has a separate subscriber.
+    internal sealed class ProviderDiscovery : IDisposable
+    {
+        private readonly MyZookeeper _zookeeper;
+        private readonly MyNacos _nacos;
+        private readonly string _rootPath;
+        private readonly Watcher _watcher;
+        private readonly Func<string, Task> _onNacosChanged;
+        private readonly Action _onRegistryRecovered;
+        private readonly ConcurrentDictionary<(string Service, bool FullPath), 
Lazy<Task<DubboServiceEndPointInfos>>> _inFlight = new();
+        private int _disposed;
+
+        internal ProviderDiscovery(MyZookeeper zookeeper, MyNacos nacos, 
string rootPath,
+            Watcher watcher, Func<string, Task> onNacosChanged, Action 
onRegistryRecovered)
+        {
+            if ((zookeeper is null) == (nacos is null))
+                throw new ArgumentException("Exactly one Provider registry is 
required.");
+            if (string.IsNullOrWhiteSpace(rootPath))
+                throw new ArgumentException("Provider registry root cannot be 
empty.", nameof(rootPath));
+            if (zookeeper != null && watcher is null)
+                throw new ArgumentNullException(nameof(watcher));
+            _zookeeper = zookeeper;
+            _nacos = nacos;
+            _rootPath = rootPath;
+            _watcher = watcher;
+            _onNacosChanged = onNacosChanged ?? throw new 
ArgumentNullException(nameof(onNacosChanged));
+            _onRegistryRecovered = onRegistryRecovered ?? throw new 
ArgumentNullException(nameof(onRegistryRecovered));
+        }
+
+        internal bool IsDisposed => Volatile.Read(ref _disposed) != 0;
+
+        public void Dispose()
+        {
+            if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
+            // Remove only our Nacos Naming subscriptions. Metadata and other
+            // clients have distinct subscriber identities on the shared 
connection.
+            _nacos?.RemoveSubscriber(this);

Review Comment:
   已在 9809cea 更新 `MyNacos.RemoveSubscriber` 的 XML 注释,明确订阅者现在是 ProviderDiscovery。



##########
Clients/DubboClient.cs:
##########
@@ -1218,55 +1120,17 @@ private static bool IsNoProviderError(string errorInfo) 
=>
             && (errorInfo.Contains("no provider", 
StringComparison.OrdinalIgnoreCase)
                 || errorInfo.Contains("no healthy provider", 
StringComparison.OrdinalIgnoreCase));
 
-        internal bool TryGetServiceNameFromProviderPath(
-            string providerPath,
-            out string serviceName)
-        {
-            serviceName = null;
-            if (string.IsNullOrEmpty(providerPath)
-                || !providerPath.StartsWith(DubboRootPath, 
StringComparison.Ordinal)
-                || 
!providerPath.EndsWith(ZooKeeperRegistryPaths.ProvidersSuffix, 
StringComparison.Ordinal))
-            {
-                return false;
-            }
-
-            serviceName = providerPath.Substring(
-                DubboRootPath.Length,
-                providerPath.Length - DubboRootPath.Length - 
ZooKeeperRegistryPaths.ProvidersSuffix.Length);
-            return !string.IsNullOrWhiteSpace(serviceName);
-        }
+        internal bool TryGetServiceNameFromProviderPath(string providerPath, 
out string serviceName) =>
+            _providerDiscovery.TryGetServiceNameFromProviderPath(providerPath, 
out serviceName);
 
-        /// <summary>
-        /// 
对GetSeviceProviderEndPointsAsync重复并发的封装(用于应对短时间并行同时对同一个serviceName节点信息进行获取,同时重复获会耗费不必要的性能,这里会复用可复用的Task完成获取任务)
-        /// EN: Coalesces concurrent provider-discovery calls for the same 
service into one reusable task.
-        /// </summary>
-        /// <param name="serviceName"></param>
-        /// <param name="isFullPath"></param>
-        /// <returns></returns>
-        private async Task<DubboServiceEndPointInfos> 
ConcurrentGetProviderEndPoints(string serviceName, bool isFullPath = false)
-        {
-            Task<DubboServiceEndPointInfos> getProviderEndPointsTask =
-                _concurrentGetProviderEndPointsTasks.GetOrAdd(
-                    serviceName,
-                    _ => GetSeviceProviderEndPointsAsync(serviceName, 
isFullPath));
-            try
-            {
-                return await getProviderEndPointsTask.ConfigureAwait(false);
-            }
-            finally
-            {
-                _concurrentGetProviderEndPointsTasks.TryRemove(
-                    new KeyValuePair<string, Task<DubboServiceEndPointInfos>>(
-                        serviceName,
-                        getProviderEndPointsTask));
-            }
-        }
+        private Task<DubboServiceEndPointInfos> DiscoverProvidersAsync(string 
serviceName, bool isFullPath = false) =>

Review Comment:
   已在 9809cea 将 `_providerDiscovery` 改为 readonly,并在转发发现和路径解析前检查 Dispose;不再通过置 
null 引入 NRE 竞态。



##########
Tests/UnitTestForDubboNet/MyNacosTest.cs:
##########
@@ -104,6 +106,94 @@ await nacos.GetProvidersAsync(Service, Group),
         }
     }
 
+    [Fact]
+    public async Task 
ProviderDiscovery_DisposeRemovesOnlyItsOwnNamingSubscription()
+    {
+        var server = new FakeNacos();
+        server.Add("1", 20880);
+        using MyNacos nacos = server.CreateClient();
+        int callsA = 0, callsB = 0;
+        using var first = new ProviderDiscovery(null!, nacos, Group, null!,
+            _ => { callsA++; return Task.CompletedTask; }, () => { });
+        using var second = new ProviderDiscovery(null!, nacos, Group, null!,
+            _ => { callsB++; return Task.CompletedTask; }, () => { });
+
+        Assert.Single((await 
first.GetProviderEndPointsAsync(Service)).EndPoints);
+        Assert.Single((await 
second.GetProviderEndPointsAsync(Service)).EndPoints);
+        Assert.Equal(1, server.NamingSubscribes);
+        await server.PushNaming();
+        Assert.Equal((1, 1), (callsA, callsB));
+
+        first.Dispose();
+        Assert.Single(server.NamingListeners);
+        await server.PushNaming();
+        Assert.Equal((1, 2), (callsA, callsB));
+        second.Dispose();
+        Assert.Empty(server.NamingListeners);
+    }
+
+    [Fact]
+    public async Task 
ProviderDiscovery_CoalescesConcurrentLookupsAndDoesNotCacheTheResult()
+    {
+        var server = new FakeNacos();
+        server.Add("1", 20880);
+        server.InstanceGate = new TaskCompletionSource<List<Instance>>(
+            TaskCreationOptions.RunContinuationsAsynchronously);
+        using MyNacos nacos = server.CreateClient();
+        using var discovery = new ProviderDiscovery(null!, nacos, Group, null!,
+            _ => Task.CompletedTask, () => { });
+
+        Task<DubboServiceEndPointInfos>[] callers = Enumerable.Range(0, 32)
+            .Select(_ => 
discovery.GetProviderEndPointsAsync(Service)).ToArray();
+        await 
server.InstanceReadStarted.Task.WaitAsync(TimeSpan.FromSeconds(5));
+        Assert.Equal(1, server.InstanceReads);
+        
server.InstanceGate.SetResult(server.Instances[Assert.Single(server.Services)]);
+        Assert.All(await Task.WhenAll(callers), result => 
Assert.Single(result.EndPoints));
+        Assert.Equal(1, server.InstanceReads);
+
+        Assert.Single((await 
discovery.GetProviderEndPointsAsync(Service)).EndPoints);
+        Assert.Equal(2, server.InstanceReads);
+    }
+
+    [Fact]
+    public async Task ProviderDiscovery_DisposeDoesNotCancelAnInFlightLookup()
+    {
+        var server = new FakeNacos();
+        server.Add("1", 20880);
+        server.InstanceGate = new TaskCompletionSource<List<Instance>>(
+            TaskCreationOptions.RunContinuationsAsynchronously);
+        using MyNacos nacos = server.CreateClient();
+        using var discovery = new ProviderDiscovery(null!, nacos, Group, null!,
+            _ => Task.CompletedTask, () => { });
+
+        Task<DubboServiceEndPointInfos> pending = 
discovery.GetProviderEndPointsAsync(Service);
+        await 
server.InstanceReadStarted.Task.WaitAsync(TimeSpan.FromSeconds(5));
+        discovery.Dispose();
+        await Assert.ThrowsAsync<ObjectDisposedException>(() => 
discovery.GetProviderEndPointsAsync(Service));
+        
server.InstanceGate.SetResult(server.Instances[Assert.Single(server.Services)]);
+        Assert.Single((await pending).EndPoints);

Review Comment:
   已在 9809cea 补充 Dispose 后在途 Nacos 查询的拒绝测试;SDK 查询可完成,但发现结果会被 
`ObjectDisposedException` 拒绝,不发布僵尸端点。



-- 
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]

Reply via email to