Repository navigation
Conversation
审查结论(源码级)以 base 关键链路已核对:watch 重新武装( [P2] 服务节点整体消失时会清空端点,行为变更需确认是否有意
( 状态当前 未覆盖范围本机无 dotnet SDK,未编译、未运行测试,全部结论来自源码推导。 |
|
@NeverENG plz fix the file confiction. |
5ce65db to
91036c1
Compare
|
@AlexStocks 两件事都处理了。 1. 冲突:分支已 rebase 到
2. [P2] 服务节点整体消失时会清空端点:确认是刻意语义,已写进 PR 描述
理由:能确认节点真实不存在时,继续保留旧端点只会把请求继续打到已下线实例;而瞬时故障仍然走 另外 #47 与 |
8e92921 to
91036c1
Compare
|
@NeverENG there are some github ci failures. plz fix them. |
Order completed discovery snapshots independently of backend revisions so delayed callers cannot replace newer providers. Release the atomic recovery guard after refresh failures. Cover provider retention, empty snapshots, recreation, overlapping notifications, delayed callers and retryable recovery through real HTTP/2 calls. Add a real ZooKeeper watch lifecycle test with isolated publisher and consumer sessions. Part of apache#42 Signed-off-by: bang <3656828039@qq.com>
|
@AlexStocks,冲突和相关问题已修复,补充了恢复及并发场景测试,本地两组单元测试各 838 项通过,真实 ZooKeeper 生命周期测试也已通过。最新 CI 正在等待维护者批准,麻烦帮忙放行,我们再根据结果跟进。 |
Reject empty metadata discovery before Telnet probing and version checks. Track snapshot watermarks only while discovery/application operations overlap, with cleanup on completion, failure, cancellation and disposal. Replace recursive routing recovery with a three-attempt discovery budget. Add ten regression cases for metadata recovery, dynamic missing services, state cleanup and repeated stale snapshots. Keep deterministic coverage for delayed snapshots preserving newer providers. Part of apache#42 Signed-off-by: bang <3656828039@qq.com>
NeverENG
left a comment
There was a problem hiding this comment.
审查结论:建议合并(LGTM with comments)
方向正确:把「读到哪里算哪里」的 ZK/Nacos 分支替换为后端无关的 snapshot 契约(5 种状态)+ 序号 watermark + 有界重试,并把 watch 生命周期收拢到一个 adapter 里。噪声最大的两处旧逻辑(IsNoProviderError 字符串匹配、路径反解析服务名)都被消掉了。
本地验证(head 5488612):
dotnet build DubboNet.csproj(net8.0 / net10.0 / netstandard2.0):0 error。dotnet test Tests/UnitTestForDubboNet -f net10.0:848 passed, 0 failed。
写得好的地方:
ProviderRegistrySnapshotState让「确认没有 provider」与「后端暂时不可用」彻底分开,只有Empty才清空 driver 候选。- watch 注册的丢事件窗口被显式关掉:无 watch 探测 →
RegisterWatch→ 再带 watcher 读一次;providers节点不存在时退化为监听服务目录;children == null时二次Exists区分「节点被删」与「后端抖动」。 - 序号 + 引用计数(
LatestSequence/Readers)在取消、异常、Dispose 路径都由finally释放,且用RemoveExact(KeyValuePair)而不是TryRemove(key),避免误删并发新建的 lookup。 - 通知与 in-flight 查询的竞态用
DispatchAfterLookupAsync(先等查询完成、精确摘除、再派发刷新)处理,不会被合并吞掉。 ReLoadDubboDriverCollection用Interlocked.CompareExchange+finally取代volatile bool,修掉了异常路径永久卡死的可能。
下面 7 条行内评论是具体建议,都不阻塞合并;另外几条只能写在正文里:
Registry/ProviderRegistryAdapter.cs的ProviderRegistrySnapshot.Revision目前所有 adapter 都传null,只出现在一行诊断日志中:要么从 ZKStat/ Nacos 版本真正填上,要么删掉,避免读者以为存在 revision 语义。Clients/DubboClient.cs:957在Empty状态下仍返回"[SendRequestAsync] GetSeviceProviderEndPoints fail ..."。语义上 discovery 已成功、只是没有 provider,保留旧文案对兼容性友好,建议在 PR 描述里点明这是有意为之(有调用方可能按该子串匹配)。Registry/ProviderRegistryAdapter.cs:151process(WatchedEvent @event)没有 null 防护(MyWatcher有),@event.getState()会 NRE;ZKNetEx 正常不会传 null,属 nit。_watchers只在Dispose里Clear(),服务名集合无限增长的场景下会有微小内存增长,可忽略。- 文档(
Docs/en|zh/architecture/registry.md)里「Empty provider directories are watched too; if the directory does not exist, the service directory is watched」容易被读成「任何时候都有 watch」,与「刷新失败后 watch 不重挂」的实际行为有出入,建议随行内评论一并校准。
建议补充的测试:
DiscoverAndApplyProvidersAsync与Dispose()竞争:水印表被清空后finally里--Readers的路径。- 连续通知风暴下
QueryInternalAsync的 3 次预算不会被Applied == false → continue饿死。 - 刷新失败后 watch 的重挂(若采纳对应建议)。
Serialize snapshot application per service without holding the global state map through driver updates. Repair consumed ZooKeeper watches after unavailable reads and recover pending subscriptions from default session events, with listener cleanup on disposal. Expose retry budgets, backoff delays and jitter through client configuration. Skip metadata refreshes for unchanged provider configuration, continue recovery after per-service failures, and document retry costs, optional backend revisions and Empty error compatibility. Add 21 regression cases covering lock contention, watch repair and default connection notifications, configurable retries, and metadata refresh behavior. Preserve deterministic stale-snapshot coverage without synchronization-context capture. Part of apache#42 Signed-off-by: bang <3656828039@qq.com>
Refresh notifications while the first snapshot application is still active, even before the service driver exists. This advances the shared sequence watermark so delayed initial snapshots cannot install superseded endpoints. Queue notification dispatch outside the Lazy lookup factory and retain invalidations when the overlapping read faults. Ignore ZooKeeper provider URLs with missing or zero ports without discarding valid siblings. Add eight regression cases for first-driver ordering, synchronous subscription callbacks, failed lookup handoff, and malformed provider ports. Update both registry architecture documents. Part of apache#42 Signed-off-by: bang <3656828039@qq.com>
| // Retain routing even if the very first network read fails. | ||
| string servicePath = $"{_rootPath}{serviceName}"; | ||
| string providerPath = servicePath + ZooKeeperRegistryPaths.ProvidersSuffix; | ||
| RegisterWatch(servicePath, serviceName, onChanged); |
There was a problem hiding this comment.
[P2] 释放已无消费者的服务 watch 路由,避免长期累积
这里为每个查询过的服务无条件写入 service/provider 两条 _watchers 记录,但 RegisterWatch 只有覆盖写入,唯一清理路径是 adapter 的 Dispose()。查询返回 Empty/失败、调用取消或服务驱动被 MaintainServiceNum 淘汰后,都不会移除对应记录。尤其是查询不存在的接口:调用完成后既无 driver、待完成的快照应用,也无缓存元数据,后续通知会被 HandleProviderRegistryChangedAsync 跳过,但映射仍然保留。
按当前源码,一个长期存活的客户端查询 N 个不同的不存在接口,就会保留约 2N 条路径记录;例如 10,000 个接口对应 20,000 条记录,与默认只缓存 20 个 driver 的上限无关。该新增持久状态在客户端销毁前无法回收。此处是源码级判断,本轮未执行运行时复现。
建议根据待完成查询、driver 和元数据缓存的实际使用状态,对 adapter 的路由及 _pendingWatchRecovery 做生命周期清理或有界淘汰,同时保留首次发现与通知交错时的保护;补充大量不存在服务查询及 driver 淘汰后的回归测试。
NeverENG
left a comment
There was a problem hiding this comment.
Review summary
Thanks — the direction is right. Splitting "how to read a registry" from "what a snapshot means" (ProviderRegistrySnapshotState with Available / Empty / Unavailable / InvalidRequest / PermissionDenied) and deleting the string matching (IsNoProviderError and friends) is the most valuable part of this PR: "no providers" stops being indistinguishable from "the registry is down".
Verified on b9dce71 in a clean worktree (the pr-48-conflicts worktree is read-only for builds):
dotnet build Tests/UnitTestForDubboNet/UnitTestForDubboNet.csproj -c Release→ 0 errors (14 pre-existing warnings).dotnet test -f net10.0→ 877 passed, 0 failed, matching the PR description.
What I really liked: typed snapshots instead of error strings; an injectable, validated retry policy (ArgumentOutOfRangeException on nonpositive attempts / negative delays / non-finite or out-of-range jitter) with retryTime: 0 at the ZooKeeper layer so the two retry layers do not multiply; watch registration before the first read; the snapshot sequence watermark, including the "initial read completed but the driver is not created yet" window handled through metadata refresh; HasSameProviderConfiguration to stop metadata reload storms; Nacos subscription ownership moved into the adapter with correct disposal ordering.
Points raised inline, roughly by severity:
ZooKeeperProviderRegistryonly repairs watches onSyncConnected, so session expiry leaves most services unwatched whileDocs/en/architecture/registry.md:26says otherwise; the existingDubboClientZookeeperWatcherexpiry path is not reachable in the current wiring._onRegistryRecovered()still runs synchronously inside theLazyfactory, so the recovery callback can re-enter the in-flight lookup (repro included) — the same bug class this PR fixed for change notifications.- The three-attempt discovery budget is also spent on
NoActuatorInService(group/version/method mismatch), where a reread can never help, and then reports "discovery did not stabilize". NoNodenow maps toEmptyand clears the driver, while the old code deliberately preserved the last endpoints. Please confirm that is intended and pin it with a test.- Nits: one redundant
ExistsAsyncin the empty-service path, adapter exceptions bypassing the retry budget, and the PR description could call out the removedinternalmembers.
None of this questions the architecture — 1-4 all look like small, local fixes. Happy to re-review once they land.
| await RecoverPendingWatchesAsync().ConfigureAwait(false); | ||
| } | ||
|
|
||
| private void OnDefaultConnectionEvent(WatchedEvent @event) |
There was a problem hiding this comment.
Session expiry does not rebuild most watches.
_pendingWatchRecovery only receives services whose last snapshot was Unavailable (line 269), and this handler only reacts to SyncConnected. After KeeperState.Expired every node watch from the old session is gone, so:
- a service that is currently
Availablekeeps no watch until its next read, and - a service that is legitimately
Emptywith no driver is never re-read at all:HandleProviderRegistryChangedAsync(Clients/DubboClient.cs:1316) has nothing to do without a driver or cached metadata, so the pending entry stays forever without a watch being installed.
The existing safety net in Clients/DubboClientZookeeperWatcher.cs (Disconnected/Expired → StartConnecTaskAsync → ReLoadDubboDriverCollection) does not close this gap: MyZookeeper offers no way to plug in a connection watcher (Registry/MyZookeeper.cs:200 routes session events only to DefaultWatch), and _dubboClientZookeeperWatcher is invoked only from ForwardConnectionEventAsync, which needs a node watcher to receive a non-node event.
Suggestion: on Expired / AuthFailed, mark every service in _watchers as pending (or invoke all callbacks) so reconnection performs a real reload; alternatively wire ConnectionStateChanged into the existing connection watcher and let its reload path run. Until then Docs/en/architecture/registry.md:26 ("connection loss and session expiration ... after recovery, services are reread and watches reinstalled") promises more than the code does.
| } | ||
|
|
||
| if (stat.getNumChildren() > 0) | ||
| _onRegistryRecovered(); |
There was a problem hiding this comment.
_onRegistryRecovered() still runs synchronously inside the Lazy<Task<ProviderRegistrySnapshot>> factory.
DubboClient's callback (Clients/DubboClient.cs:461-466) synchronously starts ReLoadDubboDriverCollection(), which reaches GetProviderEndPointsAsync for the same service and therefore hits the Lazy that is currently executing. Minimal repro with a fake IProviderZooKeeper and ForZooKeeper(..., onRegistryRecovered: () => _ = discovery.GetProviderEndPointsAsync(Service)):
InvalidOperationException: ValueFactory attempted to access the Value property of this instance.
inFlightContainsService=False // checked from inside the callback, while the outer read is still running
Two consequences: the nested call always faults (swallowed by the per-driver catch in ReLoadDubboDriverCollection, so it only shows up as a misleading error log), and its finally executes _inFlight.RemoveExact(...) while the factory is still running. That breaks the one-read-per-service invariant: a concurrent notification or business call can GetOrAdd a second Lazy and run two overlapping reads, and since DiscoverySequence is assigned on completion (Registry/ProviderDiscovery.cs:225 and below), an older snapshot can be applied last — exactly the ordering the sequence watermark is there to prevent.
The change-notification path already solves this properly with the queued Task.Run in OnRegistryChangedAsync; please apply the same deferral here (or fire the callback after the Lazy completes). Same pattern exists in b4b4500, so this is not a regression — but it is the same bug class, and there is currently no test for the recovery callback (the analogous SynchronousNotificationDuringSubscriptionRefreshesAfterInitialRead exists for notifications).
| // can proceed through its children, while a missing service | ||
| // retains a NodeCreated watch for a later refresh. | ||
| await _zookeeper | ||
| .ExistsAsync(servicePathForLookup, retryTime: 0).ConfigureAwait(false); |
There was a problem hiding this comment.
Nit: this ExistsAsync is a wasted round trip — the result is discarded and the very next call performs the same read with the watcher installed.
The race rationale in the comment does not hold either: exists(path, watcher) installs the watch atomically with the read, so there is no window between "check" and "install" to close. Dropping lines 336-337 and keeping RegisterWatch(...) + the watched ExistsAsync gives the same guarantees with one request fewer on every empty-service lookup.
| string tempErrorMes = $"[SendRequestAsync] GetSeviceProviderEndPoints fail {nowServiceName} -> {serviceEndPointsInfo.ErrorInfo}"; | ||
| MyLogger.LogWarning(tempErrorMes); | ||
| return new DubboRequestResult() | ||
| if (discoveryAttempts++ >= MaxDiscoveryAttempts) |
There was a problem hiding this comment.
This budget is also spent where rereading cannot help.
NoActuatorInService covers group/version/method mismatches: the snapshot is already Available, the endpoints are fine, and no number of refreshes will produce a matching actuator. Each such call then pays up to 3 complete discoveries × ProviderDiscoveryMaxAttempts (9 ZooKeeper reads plus backoff sleeps with defaults) and finally reports "Provider discovery did not stabilize", which points at the wrong cause.
Two related nits: MaxDiscoveryAttempts (Clients/DubboClient.cs:251) is a hardcoded const that is easy to confuse with the configurable ProviderDiscoveryMaxAttempts, and Docs/en/architecture/registry.md:47 only documents the "newer snapshot keeps winning the race" trigger, not this one.
Suggestion: when the snapshot is Available and only NoActuatorInService remains, skip the refresh and return a deterministic configuration error (e.g. "endpoints exist but no actuator matches group/version/method"); otherwise rename the const to MaxDiscoveryRefreshes or reuse the configured budget, and document the product of the two limits.
| if (snapshot.State == ProviderRegistrySnapshotState.Available) | ||
| changed = _dubboDriverCollection.AddDubboServiceDriver( | ||
| serviceName, new List<DubboServiceEndPointInfo>(snapshot.EndPoints)); | ||
| else if (snapshot.State == ProviderRegistrySnapshotState.Empty |
There was a problem hiding this comment.
Behaviour change worth confirming: a missing service node now clears routing state.
NoNode maps to Empty (Registry/ProviderRegistryAdapter.cs:346 and :361), and Empty clears the driver here. In b4b4500 the equivalent decision came from IsNoProviderError, which matched only no provider / no healthy provider, so serviceName [x] is error preserved the last known endpoints.
Consequences now: a mistyped DubboRootPath, a mistyped interface name, or the service node being briefly absent during re-registration tears down a driver that was working. If Empty is meant to mean "the providers path exists and is confirmed empty", then NoNode is arguably a different state (configuration/InvalidRequest), or should keep the previous snapshot.
Whichever semantics you pick, please pin it with a test — right now neither the old nor the new behaviour is locked, and this is the kind of change that shows up as a production incident when a root path is wrong.
| /// <returns></returns> | ||
| /// <exception cref="ArgumentNullException"></exception> | ||
| private async Task<DubboServiceEndPointInfos> DiscoverAsync(string serviceName ,bool isFullPath = false) | ||
| private async Task<ProviderRegistrySnapshot> DiscoverAsync(string serviceName) |
There was a problem hiding this comment.
DiscoverAsync does not guard against an adapter that throws, so an exception bypasses the retry policy and escapes into the business call path: DiscoverAndApplyProvidersAsync (Clients/DubboClient.cs:1230) has no catch, so QueryInternalAsync throws instead of returning DubboRequestResult { QuerySuccess = false }.
The built-in adapters catch broadly today, but GetSnapshotAsync still throws ObjectDisposedException on a disposal race (Registry/ProviderRegistryAdapter.cs:269), and PR B's etcd adapter will add surface here. Suggest converting anything except ObjectDisposedException into an Unavailable snapshot around the adapter call, so the configured budget applies and callers keep getting a result object rather than an exception.
|
@NeverENG Review of b9dce71 P1 — before merge R02 · Don't require listing the interface node to clear missing providers (ProviderRegistryAdapter.cs:351). A client may be allowed to read /providers but not list the interface node's children. When /providers disappeared in the ACL simulation, the parent lookup produced NoAuth. The PR returned PermissionDenied and kept one stale candidate, while the baseline cleared it. Could we watch for creation on /providers itself, without requiring the parent listing? R03 · Refresh metadata even when the new driver is already in place (DubboClient.cs:1224). A metadata-only lookup cached application A's signature. A business call installed B's driver before the registry notification; when the callback re-read B, Changed == false skipped metadata refresh. A subsequent lookup still returned A's java.lang.String signature instead of B's java.lang.Long. Could metadata invalidation track the provider identity used to load it rather than whether this refresh changed the driver? R05 · Avoid rooting unused clients through the shared connection event (ProviderRegistryAdapter.cs:158). The shared connection now retains the adapter, whose watcher retains the client. A weak-reference test collected a never-queried client on the baseline but not on the PR. Without explicit Dispose, the existing finalizer can't run while the subscription keeps the client reachable. Could the connection observer avoid strongly holding the client while still unregistering on disposal? R06 · Clean up local watch routes when service interest ends (ProviderRegistryAdapter.cs:260). With MaintainServiceNum = 1, the first driver was evicted but its provider path remained in _watchers. The driver cap therefore doesn't bound watch-route records for previously queried services. Could we clear records that no longer have a driver, cached metadata, or an in-flight consumer, or otherwise bound their lifetime? Questions to resolve R09 · Should an unsuccessful refresh supersede a success that hasn't been applied yet? (DubboClient.cs:1285). A gated test let a newer Unavailable advance the sequence before the initial Available was applied. The success was rejected and no driver was installed. Is that intentional, or should only Available and Empty advance the sequence used to apply routes? A test for the intended contract would help. P2 — non-blocking behavior issues R10 · Cancel retry backoff on discovery disposal (ProviderDiscovery.cs:249). In the gated test, the waiter remained pending after Dispose until the delay gate was released. Could the delay observe a discovery-lifetime token without letting an individual caller cancel the shared lookup? P3 — configuration edge case and test coverage R13 · Match the empty snapshot to the directory-deletion step (ZooKeeperProviderDiscoveryEndToEndTests.cs:114). With an extra Empty queued from the preceding step, the helper returned that snapshot instead of the one for the deletion under test. This is an in-memory check of the helper, not real-session evidence. Can the assertion wait for the deletion's corresponding notification or refresh rather than matching on state alone? |
|
@CarolDestiny Thanks for the detailed repro scenarios. I checked the relevant paths at
The current Head should not be treated as merge-ready based on the existing passing tests. R06's local fix covers one of these findings; it does not resolve the other scenarios above. |
Recheck protocol restrictions after discovery, remove the parent ACL requirement for missing providers, and refresh cached metadata independently of driver changes. Apply successful watch repair reads and prevent failed snapshots from superseding usable results. Use a weak shared connection observer, release unused local watch routes, validate paths and retry delays, and cancel backoff on discovery disposal. Add regression coverage and make the ZooKeeper deletion assertion reject snapshots from earlier phases. Validation: 899 tests passed each on .NET 10, .NET 8, and the netstandard2.0 asset under .NET 8. The E2E helper regression passed; real ZooKeeper sessions were not rerun because the Docker daemon was unavailable. Part of apache#42 Signed-off-by: bang <3656828039@qq.com>
|
@NeverENG review of P1 — Recheck the overload restriction when a newer refresh wins (
|
Recheck protocol restrictions when a newer discovery supersedes a business lookup, and refresh metadata even when a notification loses snapshot application. Serialize metadata lookup startup with unused-subscription cleanup so a stale interest check cannot delete a newly acquired subscription. Keep watch recovery pending after unusable reads, including permission failures on the initial refresh or its repair, without retrying them immediately. Add five regression cases and align the English and Chinese registry architecture docs. Validation: 904 tests passed each on .NET 10, .NET 8, and the netstandard2.0 asset under .NET 8. The original four cases failed before the fixes; a fifth case exposed direct NoAuth recovery. Real ZooKeeper E2E remains unrun because the Docker daemon socket is unavailable. Part of apache#42 Signed-off-by: bang <3656828039@qq.com>
Summary
PR A for #42 establishes a backend-neutral provider discovery contract and migrates ZooKeeper/Nacos discovery behind it. Typed snapshots distinguish available providers, confirmed empty results, transient failures, invalid requests, and permission errors. The public invocation API remains compatible.
The current implementation also protects endpoint freshness during overlapping calls and notifications, restores watches after transient reads fail, and bounds recovery work. PR B will add etcd v3 interface-level discovery on this contract. This PR does not include an etcd SDK, metadata publication, application-level discovery, or .NET Provider export.
Snapshot application and recovery
finally. One service refresh throwing is logged without preventing the remaining services from refreshing.ZooKeeper watches and Empty semantics
/dubbo/<service>with the default root) is intentionallyEmpty, as is a providers node with zero usable children. Existing driver endpoints are cleared; existence/children watches detect recreation.Empty.Unavailableand permanent failures retain existing endpoints. Transient discovery failures retry; permanent failures andEmptydo not.SyncConnectedeven when no node watch remains. Adapter disposal removes only its own connection listener. An unreachable ZooKeeper cannot accept a watch; repair also runs on subsequent discovery.Availableresult. TemporaryEmptyresults do not poison the permanent Telnet negative cache or incorrectly report that all Provider releases are too old.Emptyretain the existingGetSeviceProviderEndPoints fail/no providererror wording, although discovery itself succeeded with no providers.Retry configuration and cost
DubboClientConfnow exposes:ProviderDiscoveryMaxAttemptsProviderDiscoveryBaseDelayProviderDiscoveryMaxDelayProviderDiscoveryJitterRatioOnly
Unavailablesnapshots retry. Default waits are 80–120 ms and 160–240 ms. ZooKeeper adapter reads passretryTime: 0to avoid stackingMyZookeeperretries. Watch repair adds a separate best-effort subscription sequence per unavailable lookup; it is not another snapshot attempt.Each of the query's three discoveries has the configured snapshot budget: repeated superseding notifications can therefore lead to at most nine snapshot attempts by default. One snapshot can contain several SDK reads, whose timeouts still apply. Binary Triple retains its whole-call deadline including discovery. These retries do not replay business requests. Details are in the English/Chinese registry architecture docs.
ProviderRegistrySnapshot.Revisionremains optional for backends with a reliable revision. Current adapters leave it unset: the narrow ZooKeeper reader does not return an atomic children-list revision, and this Naming path provides no equivalent version. Local application ordering never depends on that field.Verification
On the current implementation:
e38c0bbcover per-service locking, default session listener lifetime, failed watch repair and recovery, configurable retry parameters and validation, unchanged-provider metadata behavior, and continuation after a service refresh throws.b9dce71cover notifications before first-driver creation (replacement/Empty), synchronous subscription callbacks, failed lookup notification handoff, and missing/zero provider ports (with/without healthy siblings). All eight fail before the corresponding fixes and pass afterward.c636d08CI runs passed build/test, license checks, and the full registry/provider matrix; those results do not validate later commits.main@b4b4500(#47) was merged in2dd4007. Recovery fixes are inc636d08; the first three review fixes are in5488612; watch/locking/configuration hardening is ine38c0bb; first-discovery notification and malformed-port fixes are inb9dce71.Related
Part of #42
Related to #36