diff --git a/docs/plans/evidence/grpc-data/README.md b/docs/plans/evidence/grpc-data/README.md index 8dbdb18af..280a6116a 100644 --- a/docs/plans/evidence/grpc-data/README.md +++ b/docs/plans/evidence/grpc-data/README.md @@ -21,7 +21,7 @@ The [implementation plan](../../2026-11-15-grpc-data-connections-implementation- | P03 | Shared authorization and leases | Passed; Astra approved | 77 K + 89 O + 53 R + 19 H, no failures/skips; final run `20261116T034150.797719Z-8f107e03d8d5` | | P04 | Immutable publication, hub and local ports | Passed; Astra approved | 185 R + 16 A + 16 C + 77 O + 74 ScriptWorker + 88 MTConnect + 40 OpcUaClient = 496, no failures/skips; final run `20261116T060538.590404Z-b8ef1894731e` | | P05 | Mutation tickets/outcomes | Passed; Astra approved | Complete gate 910/910 passed `20261116T084759.594405Z-42a294fc7f4f` after three Astra regression corrections; source and candidate reconciliation approved | -| P06 | Streams/sharing/fair delivery | Pending | | +| P06 | Streams/sharing/fair delivery | Passed | 347/347 applicable tests; Astra approved frozen source and evidence | | P07 | TLS/provisioning/node+cluster clients | Pending | | | P08 | Raw/UNS projection and adapter | Pending | | | P09 | Authoring/diagnostics/docs | Pending | | @@ -67,6 +67,8 @@ Final [Astra P02/P03 review](p02-p03-astra-review.md) closes all five findings a Independent Python helpers for local-context validation, fixture endpoint/manifest isolation, ownership-only cleanup, atomic secret files, bounded/redacted processes, deployment outcome polling and CLI result validation have test-first preparation evidence: initial discovery failed on missing modules; the focused combined run subsequently passed 44 tests. This is not the P10 gate. Concrete Compose, SQL/device/seeder, TLS/provisioning, runtime observation, CLI/probe scenarios and actual Docker integration remain pending. No containers or databases have been modified. +Further independent preparation adds a standalone six-process Compose scaffold and standard-library Modbus fixture with controlled values, bounded request/effect ledgers and response loss after a committed write. The device import and missing Compose file first failed the focused tests. Device tests subsequently passed 6/6; Compose checks initially passed 3/4 because the static test did not resolve shared environment anchors, then passed 4/4 after anchor-aware validation. These ten pure tests do not start sockets, images, SQL or clusters. The scaffold still needs actual P07 option/provisioning integration, production seeding, rig bring-up, probes and the complete scenario matrix. Its README explicitly marks it unready for integration execution. + ## P05 execution notes Runtime and SDK missing-API RED evidence is `20261116T062437.578601Z-6e2b4f1b2274` and `20261116T062507.986231Z-c09214fa8087`. The real DI composition test failed on the missing shared fence in `20261116T064939.908320Z-4dd869b001d4`; runtime registration now supplies one singleton without replacing an explicit registration. Rich actor creation initially failed all 19 startup checks because Akka constructor-based Props could not use the private rich constructor. An explicit indirect producer fixed creation, verified by one narrowly filtered positive test in `20261116T071454.486118Z-e187323e8fe5`; this was a diagnostic selection through the same discovery/TRX/source-identity guards, not a complete phase gate. @@ -99,6 +101,48 @@ The second complete P04 attempt (`20261116T051418.493232Z-1a9b4de9e45b`) passed The P04 selector manifest adds only affected virtual/restart, timestamp/worker/history, domain-value and wire-read regression classes. Runtime desired-catalog staging now closes before physical driver replacement, shares an exact attempt with the SDK publisher, and also supports headless application/cache/restore. Source/hub and staging review findings have been corrected; see the final checkpoint disposition. P08 must consume independent original timestamps at the mapped SDK sink; carrying them in the compatible legacy envelope does not prove the SDK import boundary already preserves them. +## P06 execution notes + +Contract/snapshot/scheduler missing-API RED runs are `20261116T090555.887076Z-88a1a655c97a` (domain), `20261116T090622.646503Z-69431655f988` (codec), and `20261116T090949.154052Z-f390d639aa3b` (Runtime). The initial implemented checkpoints passed three age-bound cases in `20261116T091759.726527Z-47842bcc7d04` and 17 Runtime snapshot/demand/filter/scheduler cases in `20261116T091915.704872Z-979135d67097`. These are partial checkpoints, not the completed P06 phase. + +The first new-codec gate passed nine cases and failed two large-payload positive assertions in `20261116T091836.781413Z-d8ddfcedba28`: the test budget covered the wire frame but not conservative decoded ownership. Tests now explicitly distinguish wire size from retained-memory admission; production limits were preserved. The complete selected Commons contract/codec regression packet passed in `20261116T092030.559269Z-346643852cdf`. + +Age means residence since normalized ingress into the origin cache, independently of optional source/server wall-clock timestamps; it is not a claim about physical sensor measurement age. Remote age has explicit unknown bounds. The additive readiness/age capability stays unadvertised until the actual subscription pipeline is wired. The physical acquisition capability and actual Modbus adapter must report every genuine read before legacy change/deadband filtering, acknowledge the applied nominal cadence/revision, and avoid replaying cached values as new acquisitions. Session/driver integration and Astra implementation approval remain pending. + +Physical acquisition RED is `20261116T092213.780186Z-6e75dfd1fc3b` (missing polling overload; also corrected test cancellation analyzer calls) and `20261116T092313.306040Z-370aa67ce4d6` (all three Modbus capability assertions failed). The initial Modbus discovery attempt `20261116T092232.356497Z-194e5da4a6f3` was blocked by test cancellation analyzers, so it is not behavioral evidence. A subsequent shared-graph build exposed an internal capability self-call analyzer error; cancellation cleanup now uses a private shared teardown helper. The selected Core packet passed 46/46 in `20261116T092653.614865Z-b9ed343a2334`; the accompanying Modbus packet passed 22 and failed the added zero-revision rejection. Positive revision/incarnation validation corrected that case, and all 23 selected Modbus tests passed in `20261116T092821.814454Z-4024463d7fca`. Existing teardown has a bounded drain; late callbacks still require Runtime producer/revision fences. + +The next Runtime integration packet produced expected missing session/demand API RED in `20261116T092616.984947Z-66d46b727bc0`. Actual stream delivery, atomic snapshot interests, process/principal retained-work accounting, final authorization, actor demand integration and allocation-bounded filters remain in progress. Root review additionally identified case-variant principal quota bypass and defensive payload copies during comparisons; their regression tests are included in that packet. No complete P06 gate or implementation approval is claimed yet. + +[Astra's partial implementation review](p06-implementation-astra-review.md) identified quadratic aggregate churn and acceptance of timer-unsupported acquisition intervals. The timer boundary regression failed in `20261116T093305.697958Z-fa3bd0327df6` (three passed/one failed); acquisition-only duration admission then passed all four new Modbus cases in `20261116T093519.443159Z-996d88ad1e71`. The legacy subscription API remains unchanged. Incremental shared-demand aggregation and its allocation/work regression remain pending. + +Directly delivered value frames need resource ownership that survives session disposal. The first ownership checkpoint `20261116T093216.693352Z-2db0e105997b` was blocked by incomplete Runtime production types: Abstractions.Tests transitively builds Runtime through Historian.Gateway. After a coordinated source freeze, the expected missing ResourceLease API RED was recorded in `20261116T093431.313767Z-ef4fa54f980a`. The additive frame lease, idempotent disposal and rejection of both leased and unleased record copies passed all four cases in `20261116T093704.423755Z-5feafefc60ff`. Actor desired/ack API RED is `20261116T093549.082848Z-403e19b7ba34`; unrelated sink/test-call typos were also corrected after that run. Actor/session integration is not yet verified. The phase selector now includes affected hub ownership/history, local catalog/read and actor subscription/lifetime regressions because those production paths change in P06; no full solution test is run here. + +The three child actor cases passed in `20261116T094432.038923Z-6d193b687a72`: acknowledgment waits for the actual driver operation, and failed or unsupported acquisition replacements preserve a live legacy subscription. Earlier actor-checkpoint builds `20261116T094215.457791Z-72f90b742d04` and `20261116T094312.925616Z-6154cc7d41c9` were blocked by an unused partial-session field and test cancellation analyzer errors; they are not behavioral evidence. A focused 20-case Runtime packet then passed 19 and failed the aggregate-churn allocation regression in `20261116T094545.247524Z-87d37de0efa1`, confirming Astra's finding without a throughput/timing threshold. Counted extrema now replace full-interest rescans, but its green gate is pending the complete assembly's next compile checkpoint. + +The next test-first packet covers physical establishment capacity across stopped/replaced actors, bounded late handle cleanup, actual Host merged demand and the shared bridge. Expected missing capacity/bridge/Host API RED is `20261116T094938.676145Z-40dbd55d4320`; an unrelated missing test namespace also needs correction. The capacity owner must be explicitly shared for the process, survive actor lifetimes, and retain its permit through the actual operation and cleanup even when cancellation is ignored. A demand acknowledgment boundary is an applied desired-revision fence, not a sample version or freshness claim; the session separately captures real origin partition watermarks and original ingress age after that acknowledgment. Idle/control-only sessions also require process/principal admission before allocating their queues and workers. All these integrations remain unapproved until their complete gate. + +The combined checkpoint `20261116T100206.021944Z-b25026632dfd` executed 31 tests: **29 passed/two failed**. All six demand-sharing cases (including allocation churn and counted extrema), five filter cases, nine snapshot cases, three existing new actor cases, two bridge cases, and one actual Host demand merge case passed. Acquisition capacity had one pass and one deathwatch-harness failure caused by a legitimate disconnect notification preceding termination. Recovery admission had two passes and the expected failure at the still-unavailable subscription service. Neither this packet nor its compiler-blocked predecessor `20261116T095912.915565Z-a34b86c483b0` is a complete P06 gate. The predecessor identified cleanup-invoker analyzer typing, subsequently corrected while preserving no-retry actual-task observation. Actor reservations now cover active handles plus pending establishment/cleanup; final lifetime and post-stop tests remain required. + +The next RED packet `20261116T100629.814124Z-bbbd8baf04d4` confirms missing snapshot principal-byte/rate/lifetime APIs and typed proven-undispatched Busy acknowledgments. Busy cleanup recovery must coalesce latest demand without blocking other drivers or retrying uncertain establishment. Raw callbacks must reject references outside the acknowledged desired set. Main session work also needs a resumable snapshot job, original-age preservation during concurrent ordinary updates, escaped-frame accounting, final authorization/sequence gates, idle admission, process fairness and target-aware local composition before enabling its port. + +Fixture preparation commit `136c8a38e` used the older Sol model in error; that assignment was stopped and the user was informed. An independent review using the required `gpt-6.1-sol`/high model is recorded in the [draft fixture inventory](fixture-inventory-preparation.md). It identifies a required Modbus exception-response fix, limited fixture request-ledger evidence, and P12 local-endpoint/container-ownership seams that must be fixed before the full run. Its 64-project inventory is source inspection only and must be refreshed against final discovery/TRX. No Docker, SQL or full-suite execution is implied. + +Expanded status, fake-clock timeout, bridge-work/fairness and Host lifecycle regressions first reached missing-API RED in `20261116T102033.317886Z-fe030bebd5db`. After the coherent overhaul, all **22** selected actor/acquisition cases passed in `20261116T103207.142491Z-f2c7a4f94f17` (six bridge, four child actor, three capacity, five status and four Host). The preceding attempt `20261116T102936.004453Z-8b5110c07719` was blocked by an unused field in the unfinished session engine. This 22-case result is a component checkpoint, not P06 approval. Astra's independent rereview verified those fixes but identified additional owner/tombstone lifetime, alarm-only merge, canceled-demand rollback and retired-handle legacy-event gaps. Their next test-first packet produced missing owner/key registration and Host-turn seam API RED in `20261116T104024.331048Z-91174ab24adc`; implementation/rereview remain pending. + +The main session port is now constructible only through an explicitly injected local factory after stream admission; Host/network registration and default capability exposure remain absent. Resumable snapshots, modified-item writer barriers, principal fairness, command ownership/rates and physical quota lifetimes are still draft code. A stale-authentication-epoch subscription regression was authored before its guard, but no separate pre-fix behavioral RED was observed for that small correction; the positive-control/new-epoch and stale-epoch outcomes must pass the actual engine gate. Initial acquisition failure remains WaitingForInitialData without a sample; it does not invent Good/null values or claim the original Bad quality was transmitted before a real sample exists. Pre-ack callback dropping is an approved latency tradeoff only with honest Waiting and a subsequent genuine acquisition, not replayed freshness. + +Delayed reservation commit produced actual timestamp RED in `20261116T104832.453678Z-1758fc97601e` (nine passed/one failed). Admission now captures the origin monotonic timestamp in the owned ingress reservation rather than refreshing it at commit. The first real engine packet passed 35/36 in `20261116T105127.719002Z-6c64769eb114`; its multi-alias snapshot test exposed an actual post-SnapshotEnd overflow because dirty traversal advanced more interests than free value slots. Capacity-limited resumable traversal and a stronger all-five-handles/explicit-heartbeat regression passed 36/36 in `20261116T105445.951505Z-23dc2a9591ff`. The selected independent Commons/Modbus packet passed 39 + 24 = 63 tests in `20261116T105648.129219Z-c0505982db88`. + +Astra's next eight engine findings received diagnostic-only hooks and an actual pre-fix behavioral run. `20261116T111337.858796Z-822cd358d71d` executed 87 tests (69 passed/18 failed): ten engine failures reproduced the eight findings, including both post-Prepare stale-authority emissions, queued cadence, direct age bounds, invisible coalescing, spare-slot fairness, repeated snapshot-validation allocation, timer bookkeeping, and unopened cancellation/expiry. The other eight failures shared an unrelated Host startup problem: Receive handlers had been registered from PreStart instead of actor construction/Become. One narrowly selected Host case passed after that correction in `20261116T112616.645708Z-382c46b4cf80`, followed by all eight Host cases in `20261116T112828.508164Z-bfeaacf1ab99`. The earlier run's remaining physical classes passed seven bridge, seven actor, three capacity and five status cases; these component results do not substitute for a final combined gate. + +Session corrections and the first aggregate-fence implementation passed all 54 focused cases in `20261116T114015.329991Z-4a96ebf2233e` (19 ordering, 19 snapshot, ten recovery, six fairness). A preceding discovery attempt `20261116T113546.146967Z-314d908e7dae` was blocked by test cancellation analyzers. Main code is frozen for independent rereview; aggregate counter/partition-boundary follow-ups and three further bridge lifecycle findings remain open. The latter cover owner refresh after Host restart with no live keys, admission ownership after a canceled Open reply, and already-captured retired callbacks during handler detachment. No P06 completion or final approval is claimed. + +Independent P10 fixture protocol preparation now uses the specified Sol model and is committed as `92e6430e0`. Fourteen pure function/fake-stream tests first failed on refusal replies and missing total-request accounting, then passed after proper exception responses, bounded structural ledgers and preserved deliberate close-after-commit behavior. This exercises the actual handler with memory-only sockets; it is not a real network, Docker, SQL or CLI scenario gate. Those remain pending. + +The aggregate hub correction was delegated to a separate Terra/xhigh owner while the actor owner held a read-only role. Immutable current-route attachment vectors, one-hub ownership, control in-progress markers, retirement helping, finite partition bounds, advancing cached history minima and per-item handoff checks now replace full-source validation scans. The focused aggregate follow-up passed all 22 snapshot tests in `20261116T115224.552541Z-89d4622a55af`; its independent review is pending. Ordinary sample changes preserve frozen snapshots. Control and routing exhaustion fail closed; the pre-existing ordinary watermark/ordinal overflow paths were not expanded in this change. + +That same combined run executed 61 cases: 56 passed and five failed exactly in newly added reviewer regressions. Two Main failures reproduce a quiet return-to-baseline suppressing the Coalesced notice and a direct Modify acknowledgment escaping after revocation during commit cleanup. Three actor/bridge failures reproduce cached owner proof after an idle Host restart, uncertain Open reply admission leakage, and an already-captured old callback during handler detachment. The respective owners are fixing these after the observed behavioral RED; no final component or P06 approval is inferred. Earlier review suspicions of a direct *value* blocking-lock authorization gap were withdrawn after source inspection and are not represented as confirmed findings. + ## Later-phase integration obligations P05 read-only preparation located the actual device invocation inside the resilience delegate, after actor dispatch and `Task.Yield`; final ticket validation must occur there. Capture the actual driver task for bounded late observation, because the resilience wrapper can time out first. Legacy Good acknowledgments without established device-application guarantees remain unconfirmed. The agreed rich path shares a short dispatch/publication fence across actual authority, catalog, primary-verdict, route and driver-lifetime pointer changes; permission evaluation, callbacks and arbitrary driver code remain outside it. The dispatch mark is the documented linearization point immediately before the driver call on the same delegate path. Dispatched Unknown claims and physical-call/payload permits remain pinned until the actual task ends, even after observer retention expires. Real per-item endpoint switching belongs to the P07 connection-client gate, with mapped integration in P08; P05 must prove ordered partial executor outcomes without a fabricated failover client. @@ -118,3 +162,7 @@ Read-only security preparation confirmed that caller-supplied `DataView.Subject` Test-first domain/protocol changes and targeted review regressions produced recorded failures before correction. Final P01 run `20261116T024814.318745Z-3a06bbb5af5e` passed 15 Core.Abstractions and 36 Commons tests, including named existing protocol regressions, with no failures or skips. No broad unit or integration suite was run. [Astra checkpoint](p01-astra-review.md) approves P01 freeze only after cluster identity, original credential identity, array metadata, receiver-owned aggregate decoding, per-value element limits, pinned stream provenance, additive negotiation and structural/descriptor corrections. The frozen facade is caller-bound through `IDataConnectionFactory` and `DataAuthenticatedContext`; no authenticated identity comes from protobuf claims. `DataWriteAdmission` retains original key/version/expiry. Capabilities carry cluster identity and independently advertised array-element limits. Compact and fallback stream decoding require expected serving identity. Array/byte storage uses defensive managed copies and separate disposable leases; pooling is deferred. Post-parse budget checks do not substitute for the P07 transport parse/decompression or P11 measured-memory gates. + +### P06 final gate and approval + +The frozen full P06 gate `20261116T121919.790393Z-0175b7fac86f` passed **347/347**, with zero failures or skips: Runtime 234, Abstractions 50, Commons 39, Modbus 24. Astra independently reconciled all four TRX files, HEAD, tracked diff and all 28 untracked production/test file hashes. [Final P06 review](p06-implementation-astra-review.md) approves the phase with no remaining actionable findings. This supersedes the earlier in-progress checkpoint notes; production network composition, Docker validation, benchmarks and final integrated review remain P07/P10/P11/P12 work. diff --git a/docs/plans/evidence/grpc-data/p06-implementation-astra-review.md b/docs/plans/evidence/grpc-data/p06-implementation-astra-review.md new file mode 100644 index 000000000..42e3a0f95 --- /dev/null +++ b/docs/plans/evidence/grpc-data/p06-implementation-astra-review.md @@ -0,0 +1,388 @@ +# P06 Astra implementation review — approved + +**Final disposition: P06 approved.** All actionable findings in this review are closed by frozen-source rereview and the complete applicable P06 gate: **347 passed, zero failed, zero skipped** in `20261116T121919.790393Z-0175b7fac86f`. The final source/evidence reconciliation and scope limits are recorded at the end of this note. This approves Tasks 13/14 and the P06 implementation scope; it does not approve the later network integration or the completed overall feature. + +The review began with dirty P06 work over baseline `65871d079` on `codex/grpc-data-connections`, against Tasks 13/14 and `p06-contract-astra-review.md`, and continued through the final frozen implementation at HEAD `92e6430e062cfde1a97d7142d46581f05c893091`. The final reviewed scope includes domain age/value and delivery ownership contracts, physical acquisition and Modbus/PollGroupEngine, protobuf/mapper extensions, demand/filter/scheduler/admission primitives, the session and target-aware local service, transport capacity, atomic snapshot/steady-interest capture, hub control fences/history, and the actual driver actor/Host bridge. + +The sections below preserve the chronological checkpoints, original findings, and repair evidence. Their historical pending/open dispositions are superseded by the final disposition above and the final reconciliation below. The initial checkpoint deliberately excluded then-active session, actor, capture, and snapshot work; those components were subsequently frozen and independently reviewed. No tests, builds, Docker commands, or commits were run by this reviewer; source inspection and independent reading of coordinator-produced artifacts establish the review evidence. + +## Finding dispositions + +### P2 — Shared-interest churn performs quadratic work under the registry-wide lock + +The original `UpstreamDemandRegistry.TryAdd` and `Remove` called `Update` while holding `_gate`. `Update` copied all settings with `e.Interests.Values.ToArray()` on every mutation (original `UpstreamDemandRegistry.cs:87-90`); `SubscriptionSettingsAggregator.Aggregate` validated and scanned the collection for both minima and the maximum trigger (`SubscriptionSettingsAggregator.cs:12-14`). Adding and then releasing N views of one shared source therefore performed Θ(N²) traversal/allocation, including when every view asked for identical settings. Because the lock belongs to the entire registry, this also delayed unrelated source/principal demand operations. + +**Focused rereview: closed for the registry primitive.** The current entry maintains counted sampling/publishing intervals and triggers (`UpstreamDemandRegistry.cs:20-62`), updates them on add/removal, and derives desired settings from the extrema (`:126-129`). Multiplicity keeps an extreme present until its last holder leaves. There is no whole-interest traversal or copy in the mutation path; work is bounded by logarithmic access to distinct settings rather than total shared-view fan-out. The added tests cover add/remove allocation, duplicate extrema with unchanged revision, and trigger downgrade. The coordinator supplied an actual behavioral red run, `20261116T094545.247524Z-87d37de0efa1` (19 passed, 1 failed), with approximately 3.8 MB allocated by the original implementation for 64 additions, followed by 6/6 registry tests passing in `20261116T100956.692745Z-3b3534c093bc`. The bridge's separate aggregation finding below remains open. + +### P2 — Acknowledged Modbus cadence can exceed the polling timer's supported range + +The original `ModbusDriver.SubscribeAcquisitionAsync` rejected negative intervals but accepted every positive `TimeSpan` and reported the requested value as the supported nominal cadence (original `ModbusDriver.cs:2030-2046`). `PollGroupEngine` later passes the remaining interval directly to `Task.Delay` (`PollGroupEngine.cs:313-324`). A request such as `TimeSpan.MaxValue` returned an apparently valid acquisition acknowledgment, then the poll loop faulted after its initial read because the timer could not accept that duration. That exception is not caught by the delay branch. + +**Focused rereview: closed for the new acquisition capability.** `MaxAcquisitionInterval` is the supported timer ceiling, `uint.MaxValue - 1` milliseconds (`ModbusDriver.cs:235-237`), and the new capability rejects larger durations before `_poll.Subscribe` (`:2035-2042`). The boundary test rejects one millisecond above the ceiling and `TimeSpan.MaxValue` before any physical read, then admits the exact ceiling. The coordinator reports 4/4 passing in `20261116T093519.443159Z-996d88ad1e71`. The legacy subscription API is unchanged; this closure covers the P06 acknowledgment path reviewed here. + +## Reviewed behavior that is consistent with the contract direction + +- `DataAgeBounds` validates nonnegative and ordered bounds, preserves unknown endpoints, uses checked elapsed-time addition, and requires a finite known upper bound to certify freshness. These are bounds on normalized origin-cache ingress age, not sensor measurement age. +- Fallback and compact protobuf forms use additive optional age/readiness fields. The capability bit is explicit. Negotiated missing/invalid readiness and negative age reject; unnegotiated readiness remains unspecified. Stream decoding creates a lower bound without a finite upper bound. Unary decoding clears the former exact-looking `Age` and only derives an upper bound when a causal request elapsed duration is supplied. +- `DataValue.ContentEquals` compares private immutable byte/array storage directly and checks array kind and dimensions. The source inspection found no payload copy on that comparison path. The newly added Runtime allocation regressions still require a green coordinator-owned run. +- The acquisition callback is installed before the poll task starts, receives every completed reader result before legacy change/deadband filtering, and carries the supplied desired revision/producer incarnation. The documented trusted callback must synchronously copy borrowed mutable values and must not mutate producer storage. Callback completion can precede establishment acknowledgment. Bounded teardown does not eliminate late callbacks; the Runtime generation fence remains essential. +- `ClientFilterState.ShouldDeliver` does not commit considered candidates. `Commit` retains a distinct value lease and disposes the previous baseline. Status/serving changes bypass a value deadband, and the large-integer path conservatively avoids double-conversion suppression. +- The scheduler deduplicates dirty source entries and resumes round-robin interest slices instead of restarting a hot source on every change. Snapshot and transport reservation leases release once, and capacity is checked before the primitive grants a reservation. + +## Ownership direction reviewed during this checkpoint + +The coordinator identified that a direct `DataSubscriptionValues` frame can outlive its session. The domain implementation now accepts an optional `ResourceLease`, disposes samples once, and releases the lease in `finally` (`IDataServices.cs:107-122`). A custom copy constructor rejects all record copies, including frames without a resource lease, so `with` cannot silently alias independently disposable sample ownership. The focused tests cover repeat disposal, existing constructor use, and rejection of leased/unleased copies without harming the original. The coordinator reports 4/4 passing in `20261116T093704.423755Z-5feafefc60ff`. This domain fix is accepted. + +The Runtime ownership integration remains pending: reserve before retaining payloads; transfer the lease with an escaped direct frame; keep transport-owned frame/prepared bytes and reservations until the actual prepare/write operation completes, including ignored cancellation. Regressions must still demonstrate a frame retained beyond session disposal and prepare/write tasks that ignore cancellation. Domain disposal tests alone do not establish those session-level lifetimes. + +## Required final P06 obligations + +The primitive tests and this partial inspection do not demonstrate the following integrated requirements. The final review must inspect the frozen implementation and its actual gate evidence: + +- Actual driver subscription acknowledgment with desired revision and producer incarnation; legacy/alarm plus gRPC union; unsupported/faster demand failure and revised settings; callback-before-ack and superseded/late callbacks; final-interest removal without deleting legacy interest. +- Atomic steady-interest registration and snapshot/version capture; ownership independent of finite snapshot payload leases; updates during the acknowledgment/capture gap represented by snapshot or catch-up; bounded reset when catch-up cannot be maintained. +- One stream consumer and serialized writer; exclusive direct versus transport delivery mode; actual adapter acceptance as the commit boundary; final authority/lease/item revision checks; successful-delivery baseline independent of considered/pending work; late receipts unable to commit into a replacement epoch. +- Removal acknowledgment after prior in-flight delivery settles and queued old revisions are canceled/rejected; modify/re-add revision behavior; failed/ambiguous writer invalidating the epoch; old prepared candidates re-evaluated against the committed baseline. +- Quiet-stream credential/authority/session expiry from monotonic deadlines, including control-only watches; admission of a disclosed positive capped lifetime; command acknowledgment timeout reported as uncertain where appropriate. +- Bounded command and pending-value ownership, due-interest rescheduling, control/data fairness under a hot source and abusive command stream, no actor/partition/authority lock held through a stalled writer, and bounded outstanding operations when cancellation is ignored. +- Global and per-principal recovery concurrency/bytes, snapshot lifetime and bandwidth admission, plus jittered retry guidance. The current `SnapshotAdmissionScheduler` primitive only establishes global byte and global/per-principal slot limits; other required limits must be demonstrated by its integration or additional primitives. +- Late age sampling from the retained ingress timestamp, receiver-local elapsed age advancement, and status/readiness transitions that cannot reset origin age or be concealed by value filtering. P07's unary caller must supply elapsed time from the causal request start; the mapper cannot prove that causality itself. +- A final P06 manifest gate covering the new classes and affected contracts on the reviewed candidate, followed by Astra review of the complete session/actor/resource paths. No OPC UA, Host ingress, or Docker integration claim follows from this checkpoint. + +## Coordinator-supplied evidence available at review start + +The coordinator reported the following existing runs; this reviewer did not rerun them: + +| Scope | Result | Run ID | +| --- | --- | --- | +| Domain age/contracts | 3/3 | `20261116T091759.726527Z-47842bcc7d04` | +| Commons selected classes | 39/39 | `20261116T092030.559269Z-346643852cdf` | +| Early Runtime primitives | 17/17 | `20261116T091915.704872Z-979135d67097` | +| Core age/contracts and existing/new PollGroupEngine | 46/46 | `20261116T092653.614865Z-b9ed343a2334` | +| Final Modbus packet | 23/23 | `20261116T092821.814454Z-4024463d7fca` | + +The earlier Modbus packet in the Core-associated run had 22 passing tests and one positive-fence red test; the later 23/23 packet supersedes that focused failure. The later `ContentEquals`/Runtime allocation additions and the still-active session integration are not covered by the early Runtime result. Follow-up coordinator-supplied evidence is recorded with each finding and in the actor checkpoint below. Final source freeze/phase gate remain pending; no final P06 approval is implied. + +## Subsequent frozen actor/bridge checkpoint + +This focused checkpoint reviewed `DriverInstanceActor.cs`, `DriverHostActor.cs`, `DriverHostSubscriptionDemandSource.cs`, the acquisition capacity implementation, and the four new actor/bridge test classes over HEAD `136c8a38e` plus dirty P06 work. The session engine, local subscription service implementation, rate admission, and changing atomic-capture/history paths remain excluded from final approval. The known failed-read status/age issue was already assigned for test-first repair and is recorded below without duplicating that investigation. No reviewer tests, builds, Docker commands, or commits were run. + +### P1 — An abandoned replacement can multiply outstanding operations behind one driver reservation + +**Closed in the subsequent frozen rereview below; original finding follows.** When an acquisition is already active, a replacement retains `_activeCapacity` (`DriverInstanceActor.cs:2046-2055`). If establishment times out, the catch abandons the operation and the finally block clears `_pendingAcquisition` (`:2124-2131`), but no unresolved-operation/cleanup task is installed in the guard consulted by the next request. The old active reference keeps the shared driver reservation alive, so another replacement can retain it and start. Repeated replacements against a driver ignoring cancellation can therefore accumulate unbounded pending establishments and late cleanup operations behind a single charged driver key. + +Keep every unresolved replacement charged against an explicit per-key operation limit until its backend and any returned handle cleanup actually settle. A later request rejected before dispatch can return typed Busy with that real completion boundary. The required regression starts with an active subscription, times out a blocked replacement, then tries multiple further replacements and proves that the physical operation count and retained references remain bounded. The existing abandoned-initial-establishment test covers a different path where the absence of `_activeCapacity` correctly makes the global driver-key reservation reject another establishment. + +### P1 — Bridge cache reuse can acknowledge a retired producer + +**Closed in the subsequent frozen rereview below; original finding follows.** `DriverHostSubscriptionDemandSource.ApplyAsync` returns cached `Applied` when reference names and requested interval match (`DriverHostSubscriptionDemandSource.cs:88-93`). Although `Applied` stores `Producer`, the shortcut never checks it against the current child/producer, and the bridge has no retirement/invalidation input. After a driver restart or reconnect, a same-settings acquisition can return Good and the old boundary even while the new child has failed or is still blocked from establishing by old cleanup capacity. + +Validate the actual current producer and applied revision before reusing an acknowledgment, or invalidate the bridge cache on the relevant route/incarnation change. Add a regression with an acknowledged initial demand, a replacement child whose establishment cannot finish, and a same-settings Acquire that must not succeed from the retired producer's cache. + +### P1 — Deployment can overwrite a newly acknowledged gRPC demand with an older complete set + +**Closed for value-reference/producer changes in the subsequent frozen rereview; the newly discovered alarm-only case remains open below. Original finding follows.** While `HandleAcquisitionDemand` waits for the child's physical operation, `_acquisitionDemands` still contains the previously acknowledged set or no gRPC demand. A concurrent deployment's bulk `SendDesiredSubscriptions` uses that old state (`DriverHostActor.cs:4014-4017`, `:4073-4089`) and queues it to the child. When establishment succeeds, `OnAcquisitionApplyCompleted` stores the new demand but does not resend the merge against the latest legacy set (`:4126-4136`). The queued legacy-only/older message can then clear `_desiredAcquisition` and replace the physical subscription after the caller received Good. + +Serialize or revision-fence the complete desired state across both deployment and gRPC changes, and ensure successful acknowledgment corresponds to the final current merged state. Add a real-Host regression that gates gRPC establishment, applies a changed legacy set while it is pending, releases establishment, and verifies the final physical references/cadence contain the latest legacy plus admitted gRPC demand. + +### P1 — A final removal after the driver disappears can leave demand that resurrects later + +**Closed in the subsequent frozen rereview below; original finding follows.** `StopChild` removes the child but does not clear `_acquisitionDemands` (`DriverHostActor.cs:4292-4301`). `HandleAcquisitionDemand` rejects an empty update before removing stored demand if there is no live eligible child (`:4094-4106`). If the final lease is released after the driver leaves the plan, the bridge forgets its local demand but the Host retains it. Re-adding the same driver ID later merges and installs that stale gRPC interest despite having no consumer. + +Process logical demand removal independently of whether a child is currently alive, and clear definitively retired driver demand as appropriate. Preserve revision fencing so a stale removal cannot erase a newer demand. Add a remove-driver, release-final-lease, re-add-driver regression that proves the old gRPC references do not return. + +### P2 — Bridge aggregation repeats whole-interest churn and blocks unrelated driver establishment + +**Closed in the subsequent frozen rereview below; original finding follows.** The bridge scans every interest, copies the selected driver's entries, computes distinct sorted references, and finds the minimum interval before testing its unchanged-demand shortcut (`DriverHostSubscriptionDemandSource.cs:88-93`). Adding N identical shared views again performs quadratic traversal/allocation, including scanning unrelated drivers, despite the registry's counted-extrema fix. In addition, the bridge-wide `_serial` is held across the actual Host Ask (`:59-76`, `:105-106`), so one stalled first establishment delays every other driver until timeout. The current fairness test only covers waiting after a typed Busy result has already returned. + +Use bounded per-driver counted reference/settings state and per-driver serialization or an equivalent fair bounded dispatcher. Verify identical-view allocation/work scaling and driver B's progress while driver A's first establishment acknowledgment remains gated. + +### Additional callback and status obligations + +- **Callback-before-ack dropping is an approved latency tradeoff; the subsequent frozen rereview verifies the new ordering regression below.** The raw callback accepts only the new active fence, while that fence is installed after the backend Subscribe task completes, so initial callbacks before return are discarded. The coordinator clarified that the opted-in Modbus path may deliberately wait for the next genuine acquisition because it reports unchanged values every poll. This is not a correctness finding or a requirement to buffer tentative samples. A bounded owned pending-sample optimization preserving original ingress time is optional later latency work, not a P06 approval condition. +- **The failed-read age gap is closed in the subsequent frozen rereview below.** The previous raw path sent bad/null acquisition results through normal `TryPublish`, which could replace the cached value and refresh `Received`. A status-only transition must preserve the retained last value, original timestamps, and normalized ingress age. Before any initial value exists, WaitingForInitialData with no sample remains the approved behavior; this checkpoint does not request a new domain/protobuf status payload. +- **Legacy restoration versus blocked retirement still needs explicit evidence.** The final gRPC removal can route through `HandleSubscribeAsync`; `UnsubscribeAsync` retires an acquisition handle asynchronously and returns before its cleanup finishes (`DriverInstanceActor.cs:2185-2190`), after which legacy Subscribe continues. The final review should demonstrate the intended bound on overlapping physical polls and behavior when that retirement ignores cancellation, including subsequent legacy changes. The existing Host restoration test uses immediate unsubscribe completion. + +### Actor evidence and limits + +The coordinator reports run `20261116T100956.692745Z-3b3534c093bc`: 21 executed, 20 passed, one expected unfinished-Main-service Unavailable failure. Within this checkpoint's scope, actor 4/4, acquisition capacity 2/2, bridge 4/4, Host 1/1, and registry 6/6 passed; recovery had 3 passing and the Main Unavailable failure. This supplies green evidence for the counted-extrema registry fix described earlier, closing that original finding in its own class. It does not address the bridge's separate aggregation finding above. + +The passing tests demonstrate actual driver completion before acknowledgment, failed/unsupported establishment preserving legacy acquisition, raw-reference scope rejection, capacity retained across an abandoned initial establishment and old-handle cleanup, typed-undispatched Busy reconciliation, another driver progressing during an already-reported Busy wait, and a simple real-Host legacy/gRPC union with final restoration. Source inspection also confirms a local actor-ref restriction, producer/desired-revision checks on returned acknowledgments, source publication before actor mailbox forwarding, and late abandoned-handle cleanup owned independently of actor lifetime. These claims do not cover the additional interleavings identified above. All new findings require focused regressions and rereview before final P06 disposition. + +## Frozen actor/bridge/status overhaul rereview + +**Disposition: the prior fixes below are verified in source and supported by the coordinator's focused 22/22 run, but four newly identified findings remain open. This is not actor checkpoint completion or final P06 approval.** The session engine, local service, hub/atomic-capture integration, and transport capacity remain active and unverified outside this scope. + +The coordinator reports `20261116T103207.142491Z-f2c7a4f94f17`: bridge 6/6, actor 4/4, acquisition capacity 3/3, status 5/5, Host 4/4; zero required skips. The preceding `20261116T102936.004...` attempt was blocked by an unused field in the active Main implementation and supplied no behavioral gate result. No test commands were run by this reviewer. + +### Verified fixes + +- **Abandoned replacement bound:** `PendingAcquisition.Finished` covers backend completion plus cleanup. `_abandonedAcquisition` survives the mailbox-level timeout, and the next request returns Busy with that task before retaining capacity or starting a backend operation (`DriverInstanceActor.cs:1974-2057`, `:2064-2076`, `:2191`). The fake-clock regression establishes an active handle, times out its replacement, proves another request does not increment physical calls, then proves Busy remains pending until late-handle unsubscribe finishes. +- **Current producer acknowledgment:** every bridge Acquire now asks the local Host, including unchanged desired settings (`DriverHostSubscriptionDemandSource.cs:136-160`). Host sends through the current child and checks pending-child identity. The real restart regression does not permit Good while the replacement has not acknowledged. +- **Value-reference deployment merge:** Host records the desired gRPC state before dispatch, suppresses obsolete complete-set pushes while pending, and compares the completed operation with current value references, cadence, and producer before releasing acknowledgment (`DriverHostActor.cs:4079-4085`, `:4132-4140`, `:4201-4207`). The real deployment regression covers replacement with the new legacy value set plus gRPC demand. The alarm-only omission is a separate open finding below. +- **Removal while absent:** empty logical demand clears Host state before requiring a current child (`DriverHostActor.cs:4123-4130`). The removal/re-add regression proves no gRPC acquisition is recreated after final interest release while the driver is absent. Revision tombstone reclamation remains unresolved below. +- **Bridge churn/fairness:** per-driver counted references and interval counts replace global-interest scans. A reference snapshot is materialized only when unique reference membership changes, and serialization belongs to each driver (`DriverHostSubscriptionDemandSource.cs:14-25`, `:105-134`). Deterministic `ReferenceVisitCount` coverage checks identical-view churn, and a gated first acknowledgment on A no longer prevents B from completing. +- **Failed-read status and age:** bad/null raw acquisitions use `TryPublishAcquisitionStatus` (`DriverInstanceActor.cs:2150-2152`). That method avoids the publisher-wide gate, tries the source-slot gate without waiting, preserves the cached value/timestamps/ingress age through status-only publication, and invalidates on contention/admission failure (`SourceSamplePublisher.cs:368-397`). The regression retains value 42 and both original timestamps after fake time advances three minutes, changes quality/version, and preserves `ReceivedTimestamp`. Initial status without a value remains WaitingForInitialData/no sample; global-gate and slot-gate contention tests establish nonblocking behavior at those boundaries. +- **Approved pre-ack ordering:** `Pre_ack_callback_is_dropped_and_waiting_ends_only_after_a_later_real_read` confirms Waiting/no sample before and after acknowledgment, then Ready only after a new explicit physical callback. This verifies the approved latency tradeoff; no buffered initial sample or fabricated freshness is claimed. + +### P2 — Settled revision tombstones permanently consume concurrent-driver admission + +**Original settled-history leak repaired in the later owner/key checkpoint below; uncertain-open admission remains a separate finding.** `_acquisitionRevisions` retains every driver ID ever touched, including settled empty demands, and `HandleAcquisitionDemand` uses its count against `MaxReservations` (`DriverHostActor.cs:4103-4123`). For a configured capacity of eight, eight sequential fully cleaned-up distinct driver IDs permanently deny a ninth even when no physical reservations or interests remain. This is bounded retained memory but unbounded loss of future availability over process lifetime. The revision namespace also lacks a demand-owner incarnation: a recreated bridge restarts its local counter below retained Host revisions. + +Use a Host/bridge owner or catalog-generation barrier that fences stale messages while permitting safe reclamation of retired per-driver tombstones. Do not simply delete tombstones and accept stale queued updates, or redefine a concurrency limit as a hidden process-lifetime distinct-ID quota. Regress sequential distinct IDs beyond concurrent capacity, owner replacement, and delayed old-owner requests. + +### P1 — Alarm-only deployment changes are lost while acquisition is pending + +**Closed in the later owner/key checkpoint below; original finding follows.** `SendDesiredSubscriptions` suppresses child updates while acquisition is pending, but the completion comparison checks only value references, cadence, and producer (`DriverHostActor.cs:4201-4207`), omitting `AlarmReferences`. If a deployment changes only the legacy alarm set while physical establishment is gated, completion can return success with the old alarms and never send the new set. Compare the alarm portion of the complete desired state as well. Add a real-Host alarm-only deployment during pending acquisition and verify the actual alarm subscription receives the latest references. + +### P1 — Canceled stronger demand can prevent rollback by reusing an old applied revision + +**Closed in the later owner/key checkpoint below; original finding follows.** Bridge `ApplyAsync` reuses `existing.Revision` whenever the requested references and interval match its last successful `Applied` (`DriverHostSubscriptionDemandSource.cs:136-140`). Consider A applied at revision 1; adding B sends revision 2, then B's waiter cancels before the response. `state.Applied` remains revision 1. Reconciliation removes B, sees the old A-only desired set, and resends revision 1. The Host has already recorded revision 2 and rejects the rollback as stale (`DriverHostActor.cs:4105`). Reconciliation treats the ordinary failure as settled, so a late successful revision-2 establishment can leave canceled B polling indefinitely. + +Track last-issued desired state separately from last successful application. Reuse a cached proof revision only when no newer desired revision was sent; rollback after an uncertain newer request needs a fresh revision. Regress active A, gated add B, cancel B, then late acknowledgment, and assert that final actual demand returns to A alone. + +### P1 — Late old-handle legacy events bypass the acquisition fence after restoration + +**Partially repaired: restored-handle staging is verified below, but the retirement/detachment transition remains open.** Final gRPC removal can retire the raw handle asynchronously and immediately establish the legacy subscription. Retirement clears `_activeAcquisition` and `_subscriptionHandle`; the newly attached legacy handler's `AcceptLegacyHandle` accepts every handle when no acquisition is active/pending (`DriverInstanceActor.cs:1944-1946`, `:2253-2256`, `:2297-2310`). If old-handle unsubscribe is still blocked, that old acquisition can emit its legacy `OnDataChange`/batch event into the new handler. The event is accepted, published into the source cache, and forwarded as current producer data even though the raw callback correctly rejects the old acquisition fence. + +Keep obsolete handles fenced across the return to legacy operation, or wait for physical retirement before permitting the new publication path. Regress blocked old-handle cleanup, a late legacy event from that handle, and a genuine event from the restored legacy handle; only the current operation may update the cache and mailbox publication. This is the concrete correctness consequence of the earlier blocked-retirement coverage obligation. + +## Frozen Main engine and snapshot checkpoint + +**Disposition: partial review; changes required below. The 36/36 focused engine result does not establish final engine or P06 approval.** This checkpoint inspected the frozen `DataSubscriptionSession`, local subscription facade/factory changes, transport and snapshot admission, steady source interests, snapshot capture/history, and the previously reviewed domain ownership/age contracts. The actor/Host/bridge/status files are being repaired separately and were not re-approved here. Production Host DI, HTTP/2 adapters, and network ingress remain P07 work; default feature advertisement remains disabled without an explicit subscription factory. + +The coordinator reports engine run `20261116T105445.951505Z-23dc2a9591ff`: snapshot 10/10, recovery 7/7, stream ordering 14/14, fairness 5/5, zero skips. The preceding `20261116T105127.719...` run had 35 passed and one genuine post-SnapshotEnd dirty-cursor overflow failure; the corrected resumable cursor uses available value capacity, and the test now requires deltas for all five views plus only the explicitly expected heartbeat. Domain stale-authority coverage was authored before implementation but had no observed prefix red run; no such red evidence is claimed. The reviewer ran no tests, builds, Docker commands, or commits. + +### Main behavior verified in source + +- Transport mode and direct enumeration are exclusive for a session. Network delivery awaits `PrepareAsync`, performs validation, awaits actual `WriteAsync`, and commits a value baseline only after successful completion. Abandoning the caller's wait does not dispose the underlying frame/prepared operation early: the physical task retains frame, transport reservation, and a session hold until it finishes. The final-check ordering finding below narrows what can currently be claimed about authorization at handoff. +- Direct value frames transfer a resource lease to the recipient and keep that charge after session disposal. Item and session resource holds are explicit; record copying remains rejected. Considered versions and delivered filter baselines are distinct, and an obsolete handle's queued values are rejected before a remove acknowledgment is emitted by the serialized writer. +- Modify stages tentative demand and snapshot state, commits replacements only at acknowledgment acceptance, and defers later commands across that barrier. Changed filters obtain a new item revision/handle boundary and an ordered replacement snapshot. Interval-only changes preserve the item baseline and recalculate its due time; queued candidates still need the cadence fix below. +- Authorization resolves the local authoritative view, source, target, export scope, exact context authority epoch, and original caller key. Node and Cluster targets reach the target-aware subscription factory. Value publication reuses the independently authorized view gate; original key expiry is capped into a monotonic session timer. Explicitly opened quiet control-only sessions expire without renewal. +- Partition capture registers steady metadata interest and captures immutable state/watermark under the same partition lock. Snapshot payload lifetime is independent of steady-interest lifetime. Indexed bounded change history supports resumable per-partition catch-up; a gap or epoch mismatch resets the stream. Snapshot data uses the retained ingress timestamp, and ingress timestamp capture occurs before delayed normalization/commit rather than at later cache draining. +- Snapshot permits account for global/per-principal slots and bytes, retain ownership through escaped/in-flight values, expire monotonically, and charge actual snapshot send bytes against per-second windows. Rejection supplies deterministic principal jitter. Command input collections are copied under a reserved budget and command rate is shared by case-insensitive principal. + +### P1 — Final authority validation precedes later potentially blocking work + +**Transport repair verified in the later Main rereview below; a direct control-commit handoff finding remains separately open.** `DeliverAsync` validates `pending.Gate()` after Prepare, then executes eligibility and snapshot-rate admission before `WriteAsync` (`DataSubscriptionSession.cs:1111-1117`). Eligibility can read the hub under a partition lock. In addition, the value gate itself evaluates `item.View.CanPublish()` before `snapshotLease.IsReset` (`:933-935`), whose validation acquires partition locks. Authority or credential expiry while those subsequent operations are blocked can leave a stale successful authorization decision and still hand previously unsent bytes to the transport. + +Perform potentially blocking snapshot/eligibility/rate work before the final authority/lease/revision validation, then place that last validation immediately before the actual write handoff without holding owner locks through the write. Add a deterministic regression that blocks post-Prepare validation, revokes authority, and proves `WriteAsync` is never entered. This concerns a substantial controllable validation gap, not bytes already handed to the transport. + +### P2 — An eligible principal can be stranded behind a quota-blocked waiter + +**Closed in the later Main rereview below; also originally identified by the coordinator's self-audit.** `SubscriptionTransportCapacity.ReserveAsync` registers/enqueues a waiter but does not call `GrantWaiters` (`SubscriptionTransportCapacity.cs:139-150`). With global capacity two and per-principal capacity one, A can hold one operation and queue another. B then queues because `_waiting != 0`, even though the other global slot is free, and cannot advance until some unrelated release/cancellation occurs. The current release-order fairness tests do not cover an idle eligible slot at enqueue time. + +Run the grant logic after safe waiter registration/enqueue, preserving synchronous cancellation handling. Regress B receiving its reservation while A's active operation and quota-blocked waiter remain unresolved. + +### P2 — Queued live candidates can violate the newly committed publishing deadline + +**Closed in the later Main rereview below; original finding follows.** `MakeValue.Eligible` reevaluates current sample version and filter baseline but does not check the item's latest `NextDue` (`DataSubscriptionSession.cs:950-957`). While a live WriteAsync is blocked, another candidate may be prepared using the old due time. The first write's eventual commit moves `NextDue` from actual delivery time (`:943-946`), yet the queued candidate can be sent immediately afterward. This violates the admitted sampling/publishing cadence even though the value filter is reevaluated. + +Recheck due eligibility at delivery and reschedule the latest candidate without losing its dirty/considered boundary. Use fake time and a blocked first live write to prove the next live write waits until the recomputed deadline. + +### P2 — Per-frame snapshot validation rescans the entire snapshot + +**Closed in the later frozen aggregate-hub checkpoint below; original finding follows.** `SnapshotLease.IsReset` repeatedly groups all captured items, computes partition minima, and validates every ticket under partition locks (`SnapshotLease.cs:43-53`). `PumpSnapshotsAsync` invokes it per item, and each value gate invokes it again (`DataSubscriptionSession.cs:852`, `:933-935`). A snapshot containing N distinct captured sources consequently performs Θ(N²) validation work with repeated grouping allocations while emitting N frames. + +Cache immutable partition grouping/boundaries and use bounded incremental validation or per-item validation combined with partition epoch/history fences. Add deterministic work/allocation coverage for a large snapshot; the five-view correctness case does not establish scalable validation. + +### P2 — Unsupported acknowledgment timer durations leave unqueued pending state + +**Closed in the later Main rereview below; original finding follows.** `SendAsync` accepts any positive acknowledgment timeout, inserts `_ackByCommand` and `_ackDeadlines`, then calls `ArmAckTimer` (`DataSubscriptionSession.cs:201`, `:217-222`). `ITimer.Change` cannot schedule every positive TimeSpan; an input such as `TimeSpan.MaxValue` can throw at `:285`. The catch releases only the command byte charge, leaving the acknowledgment ID/deadline installed even though no Work was queued. Repeating this can exhaust command admission, including before Open has installed session expiry. + +Validate, cap, or segment supported timer durations before mutating admission state, and roll back acknowledgment bookkeeping if timer setup fails. Regress unsupported upper-bound input followed by a valid command to demonstrate no retained pending entry or capacity loss. + +### P2 — Unopened streams ignore lifetime cancellation and have no timeout + +**Closed in the later Main rereview below; original finding follows.** `LocalSubscriptionService.SubscribeAsync` checks the supplied token once but does not pass or link it to the new session (`LocalSubscriptionService.cs:46-57`). `DataSubscriptionSession` allocates a worker and stream reservation immediately, while its expiry/tick timers are not created until Open (`DataSubscriptionSession.cs:182-195`, `:374-396`). A caller can allocate a stream, never send Open, and cancel the documented stream-lifetime token without releasing any of those resources until explicit disposal. + +Link subscription lifetime cancellation to Stop and enforce a bounded unopened/handshake lifetime. Regress cancellation of an unopened stream releasing its principal/global reservation without requiring an additional Dispose call. + +### P2 — Pressure coalescing is invisible on the stream + +**Partially repaired in the later Main rereview below; suppressed replacement values still leave the notification pending indefinitely.** The writer drops an already queued candidate when a newer hub version exists (`DataSubscriptionSession.cs:950-957`) and schedules the source again, but the engine never emits `DataStreamControlKind.Coalesced`. Sequence numbers advance only for accepted deliveries, so the receiver has no explicit indication of this replacement. Task 14 requires coalescing/reset visibility; pressure reset is implemented, but this coalescing path is not visible. + +Emit a bounded coalescing notification for replacing an already queued value, distinct from normal interval/deadband suppression. Verify its ordering and ability to use the reserved control capacity without generating an unbounded control stream. + +### P2 — Direct handoff can expose an age upper bound sampled too early + +**Closed in the later Main rereview below; original finding follows.** `MakeValue` creates `DataAgeBounds(age, age)` when a pending frame is taken (`DataSubscriptionSession.cs:959-964`). Direct enumeration subsequently runs the gate and commit before returning MoveNext (`:1060-1063`), potentially waiting on session/snapshot/partition locks. If time advances during that delay, the finite Upper is below the actual age at receipt and `IsFresh(maximum)` can incorrectly certify freshness. The wire mapper avoids this by sending only a lower bound; direct consumers receive the finite bound unchanged. + +Carry a usable local monotonic age anchor for direct consumers, or do not claim a finite upper bound from the pre-handoff age sample. Add a gated direct handoff with fake-time advancement and verify that freshness cannot be certified from an outdated upper bound. + +### Snapshot validation repair direction — design review only + +**The quadratic-validation finding remains open.** The coordinator reports that the eight-finding regression packet first reached a missing-diagnostic-API red result (`20261116T110903.018133...`); this is not behavioral red evidence. Only diagnostic seams are authorized before the next behavioral run. The following is a proposed control/lifetime design, not a verified implementation or phase approval. + +Cache the snapshot's immutable partition groups and history minima once. Validate the individual ticket/read fence at a value handoff, and validate cached partition control stamps, epochs, history boundaries, routing, and lifetime in O(partitions) for aggregate reset/End checks. Ordinary sample publication must not change the control stamp. Preserve `TryReadDelta`'s advancing history positions with an incremental minimum if that API continues advancing them; permanently retaining the initial minimum would introduce false overflow resets after all items have advanced. + +A plain `IsRetired = true; increment partition stamp` is insufficient: preemption between those operations lets End accept an unchanged stamp after retirement is visible. Use an explicit in-progress control phase. A producer's immutable attachment state moves Active → Sealing → Retired. Sealing freezes the unique partition-signal set and rejects new attachments, but existing reads see retirement only after every frozen signal has entered its control phase. Publish Retired, then complete each signal. This requires no partition lock, callback wait, or source scan. A concurrent Retire caller observing Sealing must not return with retirement incomplete; it can independently bracket the same frozen vector and publish Retired, with harmless duplicate invalidations, rather than waiting for the first caller. + +Attach each signal before publishing its source binding, using CAS against Active. An attachment that wins before Sealing is included in retirement; an attachment that loses must fail binding publication. SourceBindingFence needs the same attach-before-visibility rule for its single partition. Keep the producer vector scoped to one explicitly enforced hub owner and its latest routing epoch; reject stale epoch attachments and replace the vector on a newer epoch, because old snapshots already fail routing validation. Never append historical partition objects. A monotonic unique-partition set within one epoch is bounded by that epoch's partition count, with a conservative reset of previously touched partitions as the availability tradeoff. Cross-hub reuse cannot silently overwrite another hub's signals. + +For a strictly bounded retirement path, an equivalent representation uses a separate atomic Sealing flag and an immutable attachment vector. Attachment checks Active, CAS-publishes its vector, then checks Active again before binding publication. Retirement sets Sealing first and reads the vector once; all attachments permitted to publish a binding are then represented, while a late speculative vector update must fail its second Active check. Attachment can use bounded retries and fail closed under contention. This avoids a retirement CAS loop competing indefinitely with attachment churn while preserving the logically frozen set of published bindings. + +Each partition signal needs a generation plus an active-control count, either atomically represented together or updated with the necessary ordering: Begin marks active before changing generation; End changes generation before clearing active. Capture/validation requires an unchanged generation and no active control on both sides of the relevant observation. Control operations must be nonthrowing, and counter overflow must fail closed rather than allow an ABA match. Bracket every source-invalidating mutation, including the lock-free `Signal` path, status barriers, generation replacement, and binding/producer retirement; covering retirement alone leaves other invalidations invisible. + +Required repair evidence includes attach versus Sealing, retirement paused before all partition signals are marked, capture/End overlapping a control phase, concurrent Retire callers, retirement during repartition, stale-epoch attachment rejection, repeated repartition with bounded retained signal references, and unchanged sample updates leaving snapshots valid. Large-snapshot work/allocation coverage remains required in addition to these correctness interleavings. No implementation tests were run by this reviewer. + +## Frozen actor owner/key and legacy-restoration checkpoint + +**Disposition: partial checkpoint; three findings below require changes. No actor completion or final P06 approval is given.** This rereview inspected the frozen Host, instance actor, demand bridge, acquisition capacity, staged source publication, and focused regressions at coordinator-reported HEAD `92e6430e0` plus P06 working changes. Session fixes and aggregate hub fencing remain active and outside this checkpoint. + +The coordinator reports physical non-Host run `20261116T111337.858796...`: bridge 7/7, actor 7/7, capacity 3/3, status 5/5. Host cases initially failed at common startup because Receive handlers were registered from PreStart. After removing those invalid registrations, the real-Host merge case passed in `20261116T112616.645708...`, then all Host 8/8 passed in `20261116T112828.508164Z-bfeaacf1ab99`. These component runs cover 30 cases, with full-phase reconciliation still pending. The reviewer ran no tests or builds. + +### Prior fix dispositions + +- **Settled historical tombstones:** explicit owner and per-key generations now fence old commands while successful empty demand removes revision/key entries (`DriverHostActor.cs:4123-4168`, `:4220-4227`). Shared process-lifetime counters survive Host actor recreation. The capacity-two test opens/closes ten distinct keys, rejects an old key after reuse, rejects delayed old-owner registration/commands, and accepts a recreated owner. This repairs the original settled-history lifetime quota. The uncertain Open handshake below exposes a separate unreclaimed admission path. +- **Alarm-only pending changes:** completion now compares AlarmReferences as part of the full desired state (`DriverHostActor.cs:4308-4313`). Both a same-child alarm-only change during pending establishment and a real deployment changing alarms through replacement are covered. The instance actor's unchanged-physical-demand shortcut still stores the new desired state and reconciles alarms. The original alarm-only finding is closed. +- **Canceled expansion rollback:** the bridge records `LastIssuedRevision`, references, and interval before dispatch, independent of successful application (`DriverHostSubscriptionDemandSource.cs:161-174`). The gated cancellation regression observes a rollback revision greater than the hidden late expansion. The original revision-reuse finding is closed. +- **Restored legacy callback ownership:** after an acquisition has been installed, legacy restoration stages pre-return callbacks with bounded owned SDK copies and independent optional hub reservations. Finish accepts only the returned handle; rejected staged samples are disposed. The retained ingress reservation preserves original callback receipt time (`DriverInstanceActor.cs:1983-2090`; `SourceSamplePublisher.cs:369-460`). Tests cover a blocked old cleanup with a late old event after restoration, all 130 quiet initial SDK values despite hub pressure/missing shapes, and a three-minute delayed acknowledgment preserving original hub age. This repairs the steady restored-handle case, but not the transition window below. + +### P1 — An idle bridge cannot refresh its owner proof after Host restart + +**Closed in the later five-fix checkpoint below; original finding follows.** A surviving bridge caches a successful `_ownerRegistration`. After all keys are released and the Host restarts, a new driver state has `KeyGeneration == 0`, so its first operation is Open using the old owner proof. Host rejects it, but `AcquisitionDemandOpened` carries no typed owner-invalid result and `ApplyAsync` returns immediately (`DriverHostSubscriptionDemandSource.cs:144-158`; `DriverHostActor.cs:4151-4157`). Only the later Apply response refreshes an invalid owner; this path never reaches Apply. Subsequent new-key acquires keep reusing the same stale cached proof and fail indefinitely. + +Return an explicit invalid-owner outcome from Open and refresh the owner proof safely, or provide an equivalent bounded recovery protocol. Regress the actual bridge acquiring and releasing all interests, restarting its real Host, then successfully acquiring a new key. The existing Host restart test manually re-registers an owner and therefore does not establish bridge recovery. + +### P2 — A canceled or timed-out Open can leak Host key admission + +**Original hidden-Open cleanup path repaired in the later checkpoint below; lost Abort acknowledgment recovery remains separately open.** Host allocates `_acquisitionKeyGenerations[id]` before replying (`DriverHostActor.cs:4159-4168`), but the bridge awaits Open with the caller token and records the returned key only after receiving the acknowledgment (`DriverHostSubscriptionDemandSource.cs:153-158`). If cancellation or timeout hides that acknowledgment, Reject removes the interest. Cleanup sees empty references and `KeyGeneration == 0`, returns without closing the Host key (`:147-149`), then removes its DriverState. Repeating distinct abandoned opens fills the concurrent Host key quota permanently. + +Keep ownership of an issued Open and its uncertain completion until its key is safely closed or definitively fenced; caller cancellation must not discard that cleanup obligation. Add a regression that gates the Open response after Host allocation, cancels the acquire, then proves distinct-key churn beyond concurrent capacity still succeeds. Preserve key-generation fencing when recovering an uncertain open. + +### P1 — Retirement still briefly admits every legacy event handle + +**Closed in the later five-fix checkpoint below; original finding follows.** `AcceptLegacyHandle` retains the broad fallback accepting any handle when no acquisition is pending/active (`DriverInstanceActor.cs:1976-1978`). `RetireAcquisitionHandle` clears the active fence and installed handle before removing the event handler (`:2450-2463`), and detachment clears LegacyAdmission before unsubscribing the delegate (`:2476-2490`). A callback during that boundary, including a delegate already captured before removal, sees no staging admission and no active acquisition, passes the fallback, and can publish the retired handle into the hub and mailbox. The passing regression fires its old event after replacement admission is already installed. + +Once handle fencing has been enabled, fail closed in the fallback unless the callback matches a current installed handle. Initial callbacks should enter only through the explicit bounded staging gate. Regress an old callback during retirement/detachment as well as one invoked through a delegate captured before event removal; neither may publish. Preserve the existing restored initial-value and age regressions. + +The bridge constructor in the reviewed source requires an explicit ownership allocator. P07 composition must supply the same process-lifetime allocator to Host and bridge, with one intended owner relationship; this checkpoint does not establish production DI or network exposure. + +## Frozen Main repair rereview + +**Disposition: partial checkpoint, with two concrete follow-ups below. Aggregate hub fencing and the latest actor repairs remain outside this source freeze; no final P06 approval is given.** The coordinator reports `20261116T114015.329991Z-4a96ebf2233e`, all 54 selected cases green: stream ordering 19, snapshot 19, recovery 10, fairness 6. The earlier `20261116T111337.858796...` run established behavioral red for all ten Main regressions, including the two forbidden transport writes, stale direct freshness, cadence, coalescing, and quota progress. Its overall 69 passed/18 failed included eight unrelated Host startup failures subsequently corrected and tested separately. The reviewer ran no commands to build or test. + +### Verified Main repairs + +- **Final transport authority:** delivery now orders Prepare, eligibility, snapshot rate admission, then Gate immediately before Write (`DataSubscriptionSession.cs:1161-1169`). The value gate evaluates snapshot/item state before its final view authority check (`:944-947`). Both regressions revoke authority while post-Prepare snapshot validation or live eligibility is blocked and require zero value writes. This closes the original network handoff finding. A separate direct control commit gap is documented below. +- **Fair waiter progress:** ReserveAsync calls GrantWaiters after registration/enqueue, preserving the existing synchronous cancellation handling (`SubscriptionTransportCapacity.cs:139-152`). The capacity-two/per-principal-one regression proves B progresses while A remains active and A's second waiter stays blocked. Original finding closed. +- **Queued cadence:** live eligibility checks current NextDue and schedules deferred reconsideration, restoring the considered boundary when necessary (`DataSubscriptionSession.cs:973-981`). The blocked-write regression observes a later candidate, commits the first write, proves the candidate has not sent, then advances fake time to its recomputed deadline. Original finding closed. +- **Acknowledgment timer admission:** unsupported positive durations are rejected before command rate/memory/ID admission; timer setup failure removes the newly inserted ID and deadline (`DataSubscriptionSession.cs:207-229`). The oversized-timeout regression subsequently succeeds with the same command ID. Original finding closed. +- **Unopened lifetime:** the subscription token reaches the worker's lifetime registration; a configurable, validated pre-Open timer defaults to ten seconds and is disposed at accepted Open or Stop (`LocalSubscriptionService.cs:48-57`; `DataSubscriptionSession.cs:187-200`, `:305-307`, `:396`, `:1180-1183`). Separate regressions release the sole stream slot after token cancellation and after a three-second unopened deadline, without relying on explicit disposal. Original finding closed. +- **Direct age:** frames carry `DataAgeBounds(age, null)` (`DataSubscriptionSession.cs:985-989`), so time spent before direct handoff cannot produce a falsely finite upper bound. The gated fake-time regression cannot certify one-second freshness after a two-second delay. Original finding closed. +- **Coalescing:** a one-bit marker generates one bounded control before a subsequent dequeued value, and the replacement-value regression proves its order and absence of the superseded version. This repairs the ordinary replacement path but leaves the quiet/suppressed-replacement case below open. +- **Snapshot scaling:** session value gates now request per-item snapshot validation. Pump/Begin/End still rely on aggregate snapshot validity. The independently changing hub implementation and its lifecycle/counter proof require their own frozen rereview; the original quadratic-validation finding is not closed by this Main checkpoint alone. + +### P2 — Coalescing remains invisible when the replacement is filtered out + +**Closed in the later five-fix checkpoint below; original finding follows.** Eligibility sets `_coalesced` when it drops an already queued older value, but writers consume that marker only when dequeuing another IsValue frame (`DataSubscriptionSession.cs:967-970`, `:1093-1095`, `:1136-1138`). If delivered baseline is 1, queued 2 is superseded by a return to 1, the queued 2 is dropped and the newest 1 is correctly suppressed by the filter. No subsequent value exists to flush the pending notification, so a quiet stream or later heartbeats can leave this coalescing invisible indefinitely. + +Flush the bounded notification independently of a future deliverable value while preserving stream order and reserved control capacity. Add a return-to-baseline, deadband, or status-only replacement case followed by quiet/control activity; the existing version-4 regression always supplies a later deliverable value. + +### P2 — Direct Modify acknowledgment can cross a blocking commit after its final authority check + +**Closed in the later five-fix checkpoint below; original finding follows.** DirectReader runs the pending gate, then Commit, then exposes Current/returns (`DataSubscriptionSession.cs:1103-1105`). For a Modify acknowledgment, CommitStaged checks view authority before snapshot validation and subsequently releases old demand/snapshot/interest ownership (`:647-664`). Those operations can acquire locks. Revocation during that commit validation or cleanup can therefore leave an unsent direct Good acknowledgment returned after authority is lost. The network path has already handed its acknowledgment to Write before commit, so this is specifically a direct handoff boundary. + +Add a separate publication-authority check after direct commit work and immediately before handoff, with a deterministic direct Modify acknowledgment regression that revokes while commit validation/cleanup is gated. Do not simply rerun the entire pre-commit Gate: successful commits change staged state and dispose snapshots, making that precondition intentionally false afterward. An initial suspicion about a blocking budget lock in direct value Commit was withdrawn after source inspection: DataResourceBudget uses atomics and DataValue ownership does not run arbitrary cleanup. No direct-value P1 is claimed here. + +## Frozen aggregate-hub checkpoint + +**Disposition: the original quadratic snapshot-validation finding is closed in source and focused evidence; two additional hub findings below remain open. This is not full hub or P06 approval.** Reviewed frozen scope: ProducerFence, SourceBindingFence, PartitionControlSignal, partition capture/control/history, SnapshotLease, steady SourceInterestLease, the finite partition-count bound, and snapshot regressions. Current actor and session repair work was not re-approved here. + +The coordinator reports snapshot 22/22 green in `20261116T115224.552541Z-89d4622a55af`. The complete selected packet had 61 executed, 56 passed, and five expected new actor/session regression failures; none was a snapshot failure. The larger existing P04 hub/bounds selection in the P06 manifest and the final phase gate remain pending. No tests, builds, Docker commands, or commits were run by this reviewer. + +### Aggregate fence and scaling behavior verified + +- SnapshotLease caches source-to-partition ownership and one cursor per participating partition. IsReset checks those cached cursors, with no source grouping or all-ticket validation on each call. IsItemCurrent adds the selected source's fence check; its aggregate prerequisite is bounded by the configured maximum of 256 partitions. The work/allocation regression performs 128 validations over 256 sources and bounds both allocations and partition visits. The original Θ(N²) finding is closed. +- Each partition cursor maintains counted positions and a cached minimum; TryReadDelta advances the relevant count/minimum rather than rescanning all source positions. The advancing-history regression verifies repeated deltas remain valid as retained history progresses. +- PartitionControlSignal increments its active count before its generation on Begin, and increments generation before decrementing active on End. Validation rejects active controls, negative generations, or permanent poison. Source invalidation, status admission, partition invalidation, and removal bracket their mutations. Generation replacement retires the old binding before replacing state. Ordinary value publication leaves the control stamp unchanged. +- Producer retirement seals attachment before publishing retirement. Attach checks Active before and after CAS publication; Retire brackets every observed partition signal before making IsRetired true. A concurrent Retire caller can complete the same logical fence without waiting for a paused caller. Tests cover a two-partition partial Begin, concurrent helping, and retirement while a partition lock is held. +- Attachments enforce one hub owner, reject older attachment epochs, replace rather than append old routing vectors, and use bounded retries. The finite partition bound limits a production vector's fan-out; repeated repartition coverage checks retained signal counts. Source bindings attach their one signal before source visibility. These paths take no partition lock during fence retirement. +- Capture checks routing against the selected partition array, validates control stamps around capture, and rejects a missing ticket. Repartition rejects routing-epoch exhaustion before mutation. Counter-overflow tests establish permanent rejection after overflow; rejection in the interval before `_poisoned` publication follows from the negative-generation/active-count source ordering, not a separately gated test. + +The existing unchecked sample watermark/ordinal exhaustion behavior was not expanded in this repair and remains future hardening rather than a new finding in this checkpoint. + +### P2 — Nonblocking ticket proof accepts the old partition during a routing change + +**Closed in the later frozen two-fix hub checkpoint below; original finding follows.** Repartition advances the hub routing epoch before disposing the old partitions and publishing the new array (`PartitionedSampleHub.cs:330-343`). `SamplePartition.IsTicketCurrentNonBlocking` checks the source/binding/producer fields but omits its captured `_routingEpoch` and disposed state (`SamplePartition.cs:106-112`). Hold an old partition lock and start repartition: the global epoch advances, disposal waits for that lock, and the nonblocking proof still returns true for an old ticket through the old array. + +Snapshot capture now explicitly rejects this gap, but live session publication uses this nonblocking ticket proof. Add current routing/disposal validation to that proof and regress the lock-held gap deterministically. The check must remain nonblocking; waiting for partition disposal would defeat its purpose. + +### P2 — Quiet source invalidation is invisible to steady interests after SnapshotEnd + +**Closed in the later frozen two-fix hub checkpoint below; original finding follows.** After the finite SnapshotLease is released, `Invalidate(ticket, ...)` changes the source invalidation/control state without appending a history entry or changing the partition epoch (`SamplePartition.cs:132-149`, `:214`). ProducerFence.Retire similarly changes only the producer/control fences. A steady interest at the current watermark then takes `ReadInterestChanges`' early successful empty return (`:473-480`), while SourceInterestLease.IsReset checks only release, hub disposal, and routing. Without a later sample or generation bind, the session can continue heartbeats without reporting the invalidation or retirement. + +Make steady interests observe a bounded control event or reset independently of future value traffic. Regress capture plus steady registration, dispose only the finite snapshot, then invalidate the source or retire its producer without publishing another sample; the interest/session must observe the control boundary. This does not require ordinary sample updates to invalidate frozen snapshots, nor an unbounded producer listener list. The new aggregate snapshot stamps alone do not repair this steady-state notification path. + +## Frozen five-fix session/actor checkpoint + +**Disposition: the five targeted repairs are verified below, with one new logical-abort recovery finding. The two hub findings remain pending and no overall P06 approval is given.** This rereview covered only the frozen session coalescing/direct-ack repair and actor owner/open/callback repair. The coordinator reports all applicable selected P06 runtime cases green, 228/228 in `20261116T115709.770041Z-202bd2543520`, including affected legacy regressions. The five targeted regressions had actual behavioral red evidence in `20261116T115224.552541Z-89d4622a55af`. Build and final-phase work remain coordinator-owned; the reviewer ran no tests, builds, Docker commands, or commits. + +### Targeted repair dispositions + +- **Quiet coalescing visibility closed:** both delivery loops check the single coalesced marker before waiting for or dequeuing the next outbound frame (`DataSubscriptionSession.cs:1089-1099`, `:1133-1142`). Thus a dropped candidate can produce its bounded control even when the newest sample is filtered out and no later value is queued. The return-to-baseline regression observes the notice, no superseded value, and no redundant baseline value; subsequent probe acknowledgment and heartbeat still progress. +- **Direct Modify acknowledgment boundary closed:** direct acknowledgment handoff performs a post-commit session-authority check plus a separate per-change view-authority callback (`DataSubscriptionSession.cs:1106-1111`, `:637-643`). This callback does not rerun disposed snapshot or staged-state preconditions. The actual blocking old-demand lease regression revokes authority during commit cleanup and observes no returned acknowledgment. The earlier direct-value P1 suspicion remains withdrawn and is not actionable. +- **Idle bridge Host restart closed:** Open now returns typed OwnerInvalid; the bridge invalidates its cached owner registration and obtains a new proof before retrying (`DriverHostSubscriptionDemandSource.cs:184-188`; `DriverHostActor.cs:4168-4173`). The regression uses the same surviving bridge after releasing its last key and restarting the real Host, waits for the replacement physical acknowledgment, then obtains Good. +- **Hidden Open cleanup repaired:** the bridge preallocates a key from the shared process allocator, carries it in Open, and sends a matching Abort independently of caller cancellation when Open completion becomes uncertain (`DriverHostSubscriptionDemandSource.cs:164-181`, `:258-267`). Host abort uses owner/key matching and a scalar retired-key floor to reject late reopening without retaining historical key entries (`DriverHostActor.cs:4168-4238`). The capacity-two regression cancels six distinct opens after Host allocation while their replies are gated, then verifies zero retained Host keys after each cleanup. Recovery from a lost Abort acknowledgment is separately open below. +- **Retire/detach callback window closed:** once handle fencing is enabled, the fallback requires a non-null current installed handle with reference identity equality (`DriverInstanceActor.cs:1976-1983`). A captured old delegate invoked synchronously during old-handle unsubscribe is rejected before the replacement staging gate exists; the genuine legacy initial value still reaches the mailbox and is the first hub version. Existing bounded 130-initial and original-age staging regressions remain in the passing selection. + +### P2 — A lost logical Abort acknowledgment permanently poisons the bridge driver slot + +**Closed by the final logical-abort source checkpoint and the complete 347/347 gate below; original finding follows.** `AbortOpenAsync` converts any Ask failure/timeout into false (`DriverHostSubscriptionDemandSource.cs:258-267`). That completed-false task remains in `DriverState.PendingOpenCleanup`: every subsequent ApplyAsync returns immediately at `:139-142`, and reconciliation cannot reclaim the driver because removal requires a null pending cleanup (`:343-350`). A transiently delayed or lost Abort acknowledgment therefore permanently disables the driver and consumes one bridge driver slot, even when Host processed the abort and later recovers. + +This is a logical Open/Abort handshake before any acquisition dispatch, not an uncertain physical unsubscribe whose effects cannot safely be replayed. Abort already carries an idempotent, fenced owner/key identity. Retain bounded ownership while allowing safe logical-abort reconciliation or an owner-generation recovery barrier; do not discard the cleanup obligation or retain a completed-false sentinel forever. Regress an Abort response delayed beyond its timeout, then a responsive Host and fresh acquire, and require eventual cleanup/progress without recreating the bridge. + +## Frozen two-fix hub checkpoint + +**Disposition: both hub findings above are closed in source and focused evidence. No new concrete hub finding was identified in this pass. Final P06 approval remains pending the active bridge repair, its independent rereview, and the complete phase gate.** The coordinator reports snapshot 26/26 green in `20261116T121623.900158Z-93a293f4c25c`, following actual red cases in `20261116T121124.117185...` for the routing-gap proof and both quiet-control paths. The reviewer ran no tests, builds, Docker commands, or commits. + +- **Routing gap closed:** IsTicketCurrentNonBlocking now checks hub disposal, partition disposal, and its captured routing epoch before observing source state, then rechecks them after the binding/producer proof (`SamplePartition.cs:106-115`). The regression holds the old partition lock, advances routing through concurrent repartition, and obtains false from the nonblocking ticket check before allowing disposal to finish. +- **Quiet control propagation closed:** each partition control signal owns a separate leaf lifecycle counter. BeginQuiet enters both counters before source mutation or retirement publication, and EndQuiet completes them afterward. Source invalidation, removal, partition invalidation, producer retirement, and binding retirement use this path (`PartitionControlSignal.cs:10-18`; `SamplePartition.cs:134-151`, `:217-221`, `:250-257`, `:329-333`; `PartitionedSampleHub.cs:21-27`, `:69-76`). The existing sealing/helping protocol therefore covers steady interests as well as finite snapshots without waiting for partition locks. +- **Atomic steady registration preserved:** capture takes both stamps around the existing partition-locked snapshot/interest registration and retains the lifecycle stamp in each interest cursor (`PartitionedSampleHub.cs:288-313`). SourceInterestLease.IsReset validates the bounded partition vector independently of change-history length, and TryReadChanges checks it before and after scanning (`SourceInterestLease.cs:53-87`). Both explicit invalidation and producer retirement are detected after disposing only the finite snapshot, with no later value required. +- **Status/history behavior preserved:** normal admitted status barriers increment only the snapshot control signal (`SamplePartition.cs:226-238`). Their drained history entry remains observable to the steady interest. The new positive status-history regression requires the interest to remain valid and return the changed ticket; existing ordinary-value snapshot and lifetime/counter regressions remain in the 26/26 selection. + +The lifecycle signal is intentionally partition-wide: a quiet invalidation can conservatively reset other steady interests sharing that partition. The vector remains bounded by the configured partition limit and introduces no per-source listener list or historical routing-vector accumulation. This checkpoint does not claim narrower invalidation isolation. + +## Final logical-abort recovery source checkpoint + +**Disposition: source review found no further actionable findings in this frozen repair. Final gate evidence remains pending, so this is not yet final P06 approval.** The coordinator reports actual same-driver lost-Abort-ack red evidence in `20261116T121124.117185...`, followed by the positive same-driver Host result in the subsequent 11-case Host selection. A separate cross-driver capacity-pressure regression then supplied the sole failure in a 38-case packet (37 passed, including all 26 snapshot cases). Its production repair was released only after that red result. The full manifest gate is running; no unobserved green result is claimed here. + +The bridge now retains the uncertain owner/key and DriverState through failed logical cleanup. A fresh acquisition for that driver may retry the idempotent Abort after the bounded configured delay; capacity pressure from a different new driver schedules eligible inactive cleanup states using the existing per-driver coalescer (`DriverHostSubscriptionDemandSource.cs:91-100`, `:162-177`, `:368-407`). The new driver initially receives ResourceExhausted while the old ownership is retained. Successful cleanup reclaims the old slot, allowing a later admission attempt without reacquiring the old driver. + +Each driver has one scheduled reconciliation and one serialized logical-abort attempt. A retry-request bit preserves pressure arriving while that work is already running. Without new demand or pressure, a failed result does not start an autonomous retry loop. The global bridge lock is not held across Host Ask, and physical Subscribe/Unsubscribe retry behavior is unchanged. Cleanup clears only after successful Abort or typed OwnerInvalid; cancellation of a new wait does not cancel the owned cleanup task. Host owner/key matching and the retired-key floor continue fencing delayed Open/Abort messages against replacement keys. + +The same-driver regression loses the Abort response after Host has processed cleanup, waits for the observed timeout, then requires a fresh physical operation and its actual acknowledgment. The cross-driver regression fills the sole bridge slot with A's uncertain cleanup, requests B, permits the disclosed initial ResourceExhausted result, waits for A's reclamation, and then requires B's physical acknowledgment. Final green evidence for the complete frozen implementation is still required. The reviewer ran no tests, builds, Docker commands, or commits. + +## Final P06 source and evidence reconciliation + +**P06 approved, with no remaining actionable findings in the reviewed scope.** This final disposition supersedes every historical pending/open status above. The withdrawn direct-value P1 suspicion remains withdrawn; it is not an unresolved finding. The final logical-abort P2 is closed, including recovery prompted by capacity pressure from a different driver. Prior session, actor, domain/primitive, and hub repairs remain source-verified and are covered together by the final applicable selection. + +The reviewer independently read [the complete P06 run record](../../../../artifacts/grpc-data/20261116T121919.790393Z-0175b7fac86f/unit/P06/run.json) and all four referenced TRX files. Each recorded result is Passed; there are no skipped/not-executed cases or platform exclusions in this run. + +| Selected project | Executed | Passed | Failed | Skipped | +| --- | ---: | ---: | ---: | ---: | +| Runtime, including new P06 cases and affected legacy regressions | 234 | 234 | 0 | 0 | +| Core.Abstractions, including contracts and PollGroupEngine | 50 | 50 | 0 | 0 | +| Commons, including fallback/compact codecs and protobuf contracts | 39 | 39 | 0 | 0 | +| Driver.Modbus, including affected legacy subscription behavior | 24 | 24 | 0 | 0 | +| **Total** | **347** | **347** | **0** | **0** | + +The frozen checkout was reconciled directly against the run identity: + +- HEAD exactly matches `92e6430e062cfde1a97d7142d46581f05c893091`. +- The complete tracked diff SHA-256 exactly matches `f81d6ce3c5a656d8867d6b278137e32135e8c69e13b202d7005e185ecbe88292`. +- All 28 recorded untracked production/test files match their individual SHA-256 values, with no additional unrecorded files under `src/` or `tests/`. The fixture preparation note also matches. This review note changed after the run as authorized; its differing Markdown hash is not a source/test difference. The later P07 preparation note is likewise documentation-only. + +The final TRX explicitly includes passing `Lost_abort_ack_is_reconciled_before_a_fresh_acquisition_uses_the_key` and `Capacity_pressure_reconciles_lost_abort_ack_for_an_inactive_different_driver`, as well as the quiet lifecycle, direct Modify authority, and return-to-baseline coalescing regressions. These close the remaining focused-evidence gaps; the passing gate is the final combined selection, not a sum of earlier partial runs. + +Final source inspection confirms that a lost logical Abort response keeps the owner/key and driver slot charged until a successful fenced Abort or typed OwnerInvalid proves cleanup. Caller cancellation does not cancel that owned cleanup. New demand or capacity pressure requests one coalesced retry per driver; pressure arriving during cleanup is retained by a flag. There is no global Host Ask lock, per-update task accumulation, autonomous idle retry loop, or retry of uncertain physical Subscribe/Unsubscribe. Reclamation permits a subsequent different-driver admission without reacquiring the old driver. + +### Approval boundary and remaining phases + +- **P07 remains:** production Host DI must inject the same process-shared acquisition capacity/owner allocator into Host and bridge; concrete server/client transport, TLS/HTTP2 wiring, and network adapter acceptance semantics require their own implementation and evidence. P06's explicit local factory and fake delivery-sink tests do not constitute a deployed gRPC service. The default feature remains unadvertised without the explicit composition. +- **P10 remains:** real Docker/system validation and the required multi-node, restart, cancellation, and transport conditions. This review makes no Docker or OPC UA integration claim. +- **P11 remains:** measured throughput, latency, memory, and scaling evidence at the planned sizes. Allocation/work regressions establish the specific repaired bounds; they do not establish production benchmark targets. The approved callback-before-ack drop can wait for the next genuine acquisition and is a documented latency tradeoff. Quiet lifecycle resets are conservatively partition-wide. +- **P12 remains:** final integrated Astra review of the completed implementation and its complete evidence. This P06 approval is a phase checkpoint, not that final feature approval. + +The approved age contract continues to describe normalized origin-cache ingress age, not physical measurement age. Unknown stream upper bounds, honest WaitingForInitialData before a genuine usable acquisition, and successful-delivery-only baseline commitment remain part of the approved behavior. diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index 6b1c9205e..916176f90 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -296,15 +296,77 @@ "P06": [ { "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj", - "filter": "(Feature=GrpcData&Phase=P06)", + "filter": "(Feature=GrpcData&Phase=P06)|FullyQualifiedName~.GrpcDataSnapshotTests.|FullyQualifiedName~.GrpcDataLocalConnectionTests.|FullyQualifiedName~.GrpcDataSampleOwnershipTests.|FullyQualifiedName~.GrpcDataSourceFeedParityTests.|FullyQualifiedName~.GrpcDataPartitionTests.|FullyQualifiedName~.GrpcDataIngressOverflowTests.|FullyQualifiedName~.GrpcDataCachedReadTests.|FullyQualifiedName~.GrpcDataLocalExportCatalogTests.|FullyQualifiedName~.DriverInstanceActorSubscriptionReconcileTests.|FullyQualifiedName~.DriverInstanceActorWriteAndSubscribeTests.|FullyQualifiedName~.DriverInstanceActorBatchForwardTests.|FullyQualifiedName~.DriverInstanceActorDisposeTests.|FullyQualifiedName~.DriverHostActorBatchFanOutTests.|FullyQualifiedName~.DriverHostActorSourceRemovedTests.|FullyQualifiedName~.DriverHostActorCommsLossTests.|FullyQualifiedName~.DriverHostActorRestartTests.|FullyQualifiedName~.DriverHostActorReprovisionStampTests.", "new_classes": [ "GrpcDataDemandSharingTests", "GrpcDataFilterAggregationTests", "GrpcDataStreamOrderingTests", "GrpcDataDeliveryFairnessTests", - "GrpcDataRecoveryAdmissionTests" + "GrpcDataRecoveryAdmissionTests", + "GrpcDataDriverDemandActorTests", + "GrpcDataAcquisitionCapacityTests", + "GrpcDataDriverDemandBridgeTests", + "GrpcDataDriverHostDemandTests", + "GrpcDataAcquisitionStatusTests" ], - "existing_classes": [] + "existing_classes": [ + "GrpcDataSnapshotTests", + "GrpcDataLocalConnectionTests", + "GrpcDataSampleOwnershipTests", + "GrpcDataSourceFeedParityTests", + "GrpcDataPartitionTests", + "GrpcDataIngressOverflowTests", + "GrpcDataCachedReadTests", + "GrpcDataLocalExportCatalogTests", + "DriverInstanceActorSubscriptionReconcileTests", + "DriverInstanceActorWriteAndSubscribeTests", + "DriverInstanceActorBatchForwardTests", + "DriverInstanceActorDisposeTests", + "DriverHostActorBatchFanOutTests", + "DriverHostActorSourceRemovedTests", + "DriverHostActorCommsLossTests", + "DriverHostActorRestartTests", + "DriverHostActorReprovisionStampTests" + ] + }, + { + "project": "tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=P06)|FullyQualifiedName~.GrpcDataContractsTests.|FullyQualifiedName~.PollGroupEngineTests.", + "new_classes": [ + "GrpcDataAgeBoundsTests", + "PollGroupEngineAcquisitionTests", + "GrpcDataSubscriptionFrameOwnershipTests" + ], + "existing_classes": [ + "GrpcDataContractsTests", + "PollGroupEngineTests" + ] + }, + { + "project": "tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/ZB.MOM.WW.OtOpcUa.Commons.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=P06)|FullyQualifiedName~.GrpcDataProtoContractTests.|FullyQualifiedName~.GrpcDataCodecTests.|FullyQualifiedName~.GrpcDataCompactCodecTests.", + "new_classes": [ + "GrpcDataAgeReadinessCodecTests" + ], + "existing_classes": [ + "GrpcDataProtoContractTests", + "GrpcDataCodecTests", + "GrpcDataCompactCodecTests" + ] + }, + { + "project": "tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=P06)|FullyQualifiedName~.ModbusSubscribeOptionsTests.|FullyQualifiedName~.ModbusDeadbandRecoveryTests.|FullyQualifiedName~.ModbusPollErrorHealthTests.|FullyQualifiedName~.ModbusBatchSubscriptionTests.|FullyQualifiedName~.ModbusSubscriptionTests.", + "new_classes": [ + "GrpcDataModbusAcquisitionTests" + ], + "existing_classes": [ + "ModbusSubscribeOptionsTests", + "ModbusDeadbandRecoveryTests", + "ModbusPollErrorHealthTests", + "ModbusBatchSubscriptionTests", + "ModbusSubscriptionTests" + ] } ], "P07": [ diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs index 491d0e028..fea2ab05d 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs @@ -415,7 +415,8 @@ public static class DataProtoMapper int maxItems, int maxBytes, ServingIdentity expectedServing, - int maxElements = TypedValueCodec.DefaultMaxElements + int maxElements = TypedValueCodec.DefaultMaxElements, + bool subscriptionAgeReadiness = false ) { ArgumentNullException.ThrowIfNull(frame); @@ -475,6 +476,8 @@ public static class DataProtoMapper var serverTime = server is null ? (DateTimeOffset?)null : TypedValueCodec.DecodeTimestamp(server); + var (ageBounds, readiness) = DecodeSubscriptionAgeReadiness(subscriptionAgeReadiness, + update.HasOriginAgeTicks, update.OriginAgeTicks, update.HasReadiness, update.Readiness); var sample = new DataSample( TypedValueCodec.Decode(update.Value, maxElements, maxBytes), update.HasStatusCode ? update.StatusCode : batch.DefaultStatusCode, @@ -483,7 +486,7 @@ public static class DataProtoMapper serving, update.Version ); - items.Add(new DataSubscriptionValue(handle, sample)); + items.Add(new DataSubscriptionValue(handle, sample, ageBounds, readiness)); } return new DataSubscriptionValues( frame.SubscriptionId, @@ -503,7 +506,8 @@ public static class DataProtoMapper public static W.SubscriptionFrame EncodeValues( DataSubscriptionValues frame, - bool compactNegotiated + bool compactNegotiated, + bool subscriptionAgeReadiness = false ) { var result = new W.SubscriptionFrame @@ -516,13 +520,20 @@ public static class DataProtoMapper { result.Values = new W.Values { IsSnapshot = frame.IsSnapshot }; foreach (var item in frame.Items) - result.Values.Items.Add( - new W.ValueUpdate - { - Handle = EncodeHandle(item.Handle), - Sample = EncodeSample(item.Sample), - } - ); + { + var update = new W.ValueUpdate + { + Handle = EncodeHandle(item.Handle), + Sample = EncodeSample(item.Sample), + }; + if (subscriptionAgeReadiness) + { + ValidateSubscriptionAgeReadiness(item); + if (item.AgeBounds.Lower is { } lower) update.OriginAgeTicks = lower.Ticks; + update.Readiness = (int)item.Readiness; + } + result.Values.Items.Add(update); + } return result; } if (frame.Items.Count == 0) @@ -555,6 +566,12 @@ public static class DataProtoMapper Version = item.Sample.Version, Value = TypedValueCodec.Encode(item.Sample.Value), }; + if (subscriptionAgeReadiness) + { + ValidateSubscriptionAgeReadiness(item); + if (item.AgeBounds.Lower is { } lower) update.OriginAgeTicks = lower.Ticks; + update.Readiness = (int)item.Readiness; + } if (item.Sample.StatusCode != first.StatusCode) update.StatusCode = item.Sample.StatusCode; if (item.Sample.SourceTimestampUtc != first.SourceTimestampUtc) @@ -580,14 +597,15 @@ public static class DataProtoMapper int maxItems, int maxBytes, ServingIdentity expectedServing, - int maxElements = TypedValueCodec.DefaultMaxElements + int maxElements = TypedValueCodec.DefaultMaxElements, + bool subscriptionAgeReadiness = false ) { ArgumentNullException.ThrowIfNull(expectedServing); expectedServing.Validate(requireEpochs: true); ValidateFrame(frame.SubscriptionId, frame.StreamEpoch, frame.Sequence); if (frame.CompactValues is not null) - return DecodeCompact(frame, handles, maxItems, maxBytes, expectedServing, maxElements); + return DecodeCompact(frame, handles, maxItems, maxBytes, expectedServing, maxElements, subscriptionAgeReadiness); if ( frame.Values is null || maxItems <= 0 @@ -627,7 +645,9 @@ public static class DataProtoMapper throw new ArgumentException("Unknown or stale handle."); if (DecodeServing(item.Sample.Serving) != expectedServing) throw new ArgumentException("Unexpected serving identity."); - items.Add(new(handle, DecodeSample(item.Sample, maxElements, maxBytes))); + var (ageBounds, readiness) = DecodeSubscriptionAgeReadiness(subscriptionAgeReadiness, + item.HasOriginAgeTicks, item.OriginAgeTicks, item.HasReadiness, item.Readiness); + items.Add(new(handle, DecodeSample(item.Sample, maxElements, maxBytes), ageBounds, readiness)); } return new( frame.SubscriptionId, @@ -645,6 +665,23 @@ public static class DataProtoMapper } } + private static void ValidateSubscriptionAgeReadiness(DataSubscriptionValue item) + { + item.AgeBounds.Validate(); + DataContractValidation.Required(item.Readiness); + } + + private static (DataAgeBounds AgeBounds, DataReadiness Readiness) DecodeSubscriptionAgeReadiness( + bool enabled, bool hasAge, long ageTicks, bool hasReadiness, int readinessValue) + { + if (!enabled) return (default, DataReadiness.Unspecified); + if (!hasReadiness) throw new ArgumentException("Missing negotiated readiness."); + var readiness = (DataReadiness)readinessValue; + DataContractValidation.Required(readiness); + if (hasAge && ageTicks < 0) throw new ArgumentException("Invalid origin-cache age."); + return (new DataAgeBounds(hasAge ? TimeSpan.FromTicks(ageTicks) : null, null), readiness); + } + public static W.ReadRequest EncodeReadRequest(ReadRequest x) { var v = new W.ReadRequest { Budget = EncodeBudget(x.Budget) }; @@ -846,8 +883,12 @@ public static class DataProtoMapper Status = (int)x.Status, Readiness = (int)x.Readiness, }; + x.AgeBounds.Validate(); if (x.Age is { } age) + { + if (age < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(x)); v.AgeTicks = age.Ticks; + } if (x.Sample is not null) v.Sample = EncodeSample(x.Sample); if (x.Diagnostic is not null) @@ -855,23 +896,31 @@ public static class DataProtoMapper return v; } - public static ReadResult DecodeReadResult(W.ReadResult x, DataDecodeLimits? limits = null) + public static ReadResult DecodeReadResult(W.ReadResult x, DataDecodeLimits? limits = null, + TimeSpan? causalRequestElapsed = null) { + if (causalRequestElapsed < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(causalRequestElapsed)); limits ??= new DataDecodeLimits(); Preflight(x, 1, limits, x.Sample is null ? null : new[] { x.Sample.Value }); var status = (DataItemStatus)x.Status; var readiness = (DataReadiness)x.Readiness; DataContractValidation.Required(status); DataContractValidation.Required(readiness); + if (x.HasAgeTicks && x.AgeTicks < 0) throw new ArgumentException("Invalid origin-cache age."); + var bounds = x.HasAgeTicks + ? new DataAgeBounds(TimeSpan.FromTicks(x.AgeTicks), causalRequestElapsed is { } elapsed + ? TimeSpan.FromTicks(checked(x.AgeTicks + elapsed.Ticks)) : null) + : default; return new( x.CorrelationId, status, readiness, - x.HasAgeTicks ? TimeSpan.FromTicks(x.AgeTicks) : null, + null, x.Sample is null ? null : DecodeSample(x.Sample, limits.MaxValueElements, limits.MaxBytes), - x.HasDiagnostic ? x.Diagnostic : null + x.HasDiagnostic ? x.Diagnostic : null, + AgeBounds: bounds ); } @@ -935,6 +984,7 @@ public static class DataProtoMapper Operations = (uint)x.Operations, CompactBatches = x.CompactBatches, CompactCodecVersion = x.CompactCodecVersion, + SubscriptionAgeReadiness = x.SubscriptionAgeReadiness, Limits = new W.Limits { MaxPageItems = l.MaxPageItems, @@ -998,7 +1048,8 @@ public static class DataProtoMapper ), x.CompactBatches, x.CompactCodecVersion, - x.ClusterId + x.ClusterId, + x.SubscriptionAgeReadiness ); result.Validate(); return result; @@ -1164,7 +1215,8 @@ public static class DataProtoMapper public static IReadOnlyList DecodeReadResponse( W.ReadResponse response, - DataDecodeLimits? limits = null + DataDecodeLimits? limits = null, + TimeSpan? causalRequestElapsed = null ) { limits ??= new DataDecodeLimits(); @@ -1178,7 +1230,7 @@ public static class DataProtoMapper try { foreach (var item in response.Items) - result.Add(DecodeReadResult(item, limits)); + result.Add(DecodeReadResult(item, limits, causalRequestElapsed)); return result; } catch diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs index a0da45d0e..29bc1c877 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs @@ -6,7 +6,7 @@ namespace ZB.MOM.WW.OtOpcUa.Commons.Protos; public static class DataConnectionProtoContract { public const int ProtocolMajor = 1; - public const int ProtocolMinor = 0; + public const int ProtocolMinor = 1; public const int CompactCodecVersion = 1; public static void Validate() diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto index 5446f9fca..22aa9a9f8 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto @@ -110,6 +110,7 @@ message CapabilitiesResponse { bool compact_batches = 8; int32 compact_codec_version = 9; string cluster_id = 10; + bool subscription_age_readiness = 11; } message Metadata { View view = 1; @@ -256,6 +257,9 @@ message Control { message ValueUpdate { Handle handle = 1; Sample sample = 2; + // Age since normalized origin-cache ingress, not sensor measurement age. + optional int64 origin_age_ticks = 3; + optional int32 readiness = 4; } message Values { bool is_snapshot = 1; @@ -271,6 +275,9 @@ message CompactUpdate { optional uint32 status_code = 5; TimestampOverride source_timestamp = 6; TimestampOverride server_timestamp = 7; + // Age since normalized origin-cache ingress, not sensor measurement age. + optional int64 origin_age_ticks = 8; + optional int32 readiness = 9; } message CompactValues { bool is_snapshot = 1; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs index cada8ac66..97423b294 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs @@ -2,6 +2,44 @@ using System.Security.Cryptography; namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +/// +/// Bounds on age since normalized ingress into the origin cache, not sensor measurement age. +/// A null endpoint is unknown. An upper bound alone certifies freshness; a lower bound alone +/// can prove staleness. Original wall-clock timestamps are independent of these bounds. +/// +public readonly record struct DataAgeBounds(TimeSpan? Lower, TimeSpan? Upper) +{ + public void Validate() + { + if (Lower < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(Lower)); + if (Upper < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(Upper)); + if (Lower is { } lower && Upper is { } upper && upper < lower) + throw new ArgumentException("Upper age bound must not precede lower bound."); + } + + public DataAgeBounds Advance(TimeSpan elapsed) + { + Validate(); + if (elapsed < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(elapsed)); + return new(Lower is { } lower ? TimeSpan.FromTicks(checked(lower.Ticks + elapsed.Ticks)) : null, + Upper is { } upper ? TimeSpan.FromTicks(checked(upper.Ticks + elapsed.Ticks)) : null); + } + + public bool IsFresh(TimeSpan maximumAge) + { + Validate(); + if (maximumAge < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(maximumAge)); + return Upper is { } upper && upper <= maximumAge; + } + + public bool IsStale(TimeSpan maximumAge) + { + Validate(); + if (maximumAge < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(maximumAge)); + return Lower is { } lower && lower > maximumAge; + } +} + public enum DataValueKind { Unspecified = 0, Null = 1, Boolean = 2, Int8 = 3, Int16 = 4, Int32 = 5, Int64 = 6, UInt8 = 7, UInt16 = 8, UInt32 = 9, UInt64 = 10, Float = 11, Double = 12, String = 13, Bytes = 14, Timestamp = 15, Guid = 16, Array = 17 } public enum DataItemStatus { Unspecified = 0, Good = 1, Denied = 2, NotFound = 3, Unsupported = 4, InvalidArgument = 5, Unavailable = 6, WaitingForInitialData = 7, Stale = 8, LimitExceeded = 9, InvalidContinuation = 10, TypeMismatch = 11, ResourceExhausted = 12 } public enum DataReadiness { Unspecified = 0, Ready = 1, WaitingForInitialData = 2, Unavailable = 3, Invalidated = 4 } @@ -92,6 +130,26 @@ public sealed class DataValue : IDisposable public DataValueKind ArrayElementKind { get { ThrowIfDisposed(); return (_payload as ArrayPayload)?.Kind ?? throw new InvalidOperationException(); } } public IReadOnlyList GetArray() { ThrowIfDisposed(); return _payload is ArrayPayload a ? Array.AsReadOnly((object[])a.Elements.Clone()) : throw new InvalidOperationException(); } public DataValue Retain() { ThrowIfDisposed(); return new(Kind, _payload, Dimensions); } + /// Compares immutable owned values without exposing or duplicating their storage. + internal bool ContentEquals(DataValue other) + { + ArgumentNullException.ThrowIfNull(other); + ThrowIfDisposed(); other.ThrowIfDisposed(); + if (Kind != other.Kind) return false; + if (ReferenceEquals(_payload, other._payload)) return true; + if (Kind == DataValueKind.Null) return true; + if (_payload is byte[] bytes && other._payload is byte[] otherBytes) + return bytes.AsSpan().SequenceEqual(otherBytes); + if (_payload is ArrayPayload array && other._payload is ArrayPayload otherArray) + { + if (array.Kind != otherArray.Kind || Dimensions is null || other.Dimensions is null || + Dimensions.Count != other.Dimensions.Count || array.Elements.Length != otherArray.Elements.Length) return false; + for (var i = 0; i < Dimensions.Count; i++) if (Dimensions[i] != other.Dimensions[i]) return false; + for (var i = 0; i < array.Elements.Length; i++) if (!Equals(array.Elements[i], otherArray.Elements[i])) return false; + return true; + } + return Equals(_payload, other._payload); + } /// Appends a private canonical value encoding without exposing or copying owned payload storage. internal void AppendSemanticFingerprint(IncrementalHash hash) { @@ -188,7 +246,7 @@ public sealed record DataLimits(int MaxPageItems, int MaxBatchItems, int MaxMess } public sealed record DataCapabilities(int ProtocolMajor, int ProtocolMinor, ServingIdentity Serving, DataReadiness Readiness, DataOperations Operations, IReadOnlySet ValueKinds, DataLimits Limits, bool CompactBatches, - int CompactCodecVersion, string ClusterId) + int CompactCodecVersion, string ClusterId, bool SubscriptionAgeReadiness = false) { public void Validate() { diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs index 99406cfd0..5c1d55faf 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs @@ -12,7 +12,8 @@ public sealed record ReadItem(string CorrelationId, DataView View, TimeSpan? Max public sealed record ReadRequest(IReadOnlyList Items, DataBudget Budget); /// Sample is owned by the recipient. Status/age/readiness are distinct from original sample quality. public sealed record ReadResult(string CorrelationId, DataItemStatus Status, DataReadiness Readiness, - TimeSpan? Age, DataSample? Sample, string? Diagnostic, IDisposable? ResourceLease = null) : IDisposable + TimeSpan? Age, DataSample? Sample, string? Diagnostic, IDisposable? ResourceLease = null, + DataAgeBounds AgeBounds = default) : IDisposable { public void Dispose() { @@ -105,11 +106,24 @@ public sealed record DataSubscriptionControl(string SubscriptionId, long StreamE : DataSubscriptionFrame(SubscriptionId, StreamEpoch, Sequence); /// Each frame owns its samples until disposed, including during asynchronous encoding. public sealed record DataSubscriptionValues(string SubscriptionId, long StreamEpoch, long Sequence, bool IsSnapshot, - IReadOnlyList Items) : DataSubscriptionFrame(SubscriptionId, StreamEpoch, Sequence), IDisposable + IReadOnlyList Items, IDisposable? ResourceLease = null) + : DataSubscriptionFrame(SubscriptionId, StreamEpoch, Sequence), IDisposable { - public void Dispose() { foreach (var item in Items) item.Sample.Dispose(); } + private int _disposed; + // A record clone would alias independently disposable samples and resource ownership. + private DataSubscriptionValues(DataSubscriptionValues original) : base(original) => + throw new InvalidOperationException("Owned subscription frames cannot be copied."); + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + try { foreach (var item in Items) item.Sample.Dispose(); } + finally { ResourceLease?.Dispose(); } + } } -public sealed record DataSubscriptionValue(DataItemHandle Handle, DataSample Sample); +/// Age bounds describe normalized origin-cache ingress age, independent of wall timestamps. +public sealed record DataSubscriptionValue(DataItemHandle Handle, DataSample Sample, + DataAgeBounds AgeBounds = default, DataReadiness Readiness = DataReadiness.Unspecified); /// Commands and frames are ordered per stream. Dispose cancels the stream and releases demand. public interface IDataSubscription : IAsyncDisposable @@ -117,6 +131,27 @@ public interface IDataSubscription : IAsyncDisposable Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken); IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken); } +/// One lifetime-scoped delivery mode, separate from direct enumeration. +public interface IDataSubscriptionTransport : IDataSubscription +{ + Task RunDeliveryAsync(IDataSubscriptionDeliverySink sink, CancellationToken cancellationToken); +} + +/// Transport-owned preparation and actual acceptance boundary for a serialized stream. +public interface IDataSubscriptionDeliverySink +{ + /// Prepare without emitting. Allocations must stay within the already reserved byte budget. + ValueTask PrepareAsync(DataSubscriptionFrame frame, long reservedBytes, CancellationToken cancellationToken); + /// Complete only when the transport accepts the prepared delivery. + ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken); +} + +/// Prepared transport-owned bytes retained through completion of the underlying operation. +public interface IDataPreparedSubscriptionDelivery : IDisposable +{ + long RetainedBytes { get; } +} + /// Operations use the authenticated caller bound to the containing connection facade. public interface IDataSubscriptionService { diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAcknowledgedAcquisitionSource.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAcknowledgedAcquisitionSource.cs new file mode 100644 index 000000000..61c508c79 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAcknowledgedAcquisitionSource.cs @@ -0,0 +1,30 @@ +namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +/// +/// Optional physical acquisition capability. Successful establishment acknowledges the current +/// revision and supported nominal cadence; it does not guarantee actual device timing. +/// Unsupported drivers must not claim this capability. +/// +public interface IAcknowledgedAcquisitionSource +{ + /// + /// Installs the complete reference set and callback. The callback may run before this task + /// completes. It delivers fresh acquisition results, not replayed cache values. The caller + /// must fence revisions and synchronously copy mutable values into bounded owned storage + /// before returning; the producer retains ownership until then. Failed or superseded + /// establishment must release any returned physical subscription handle. + /// + Task SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, + Action onAcquired, CancellationToken cancellationToken); +} + +/// Complete physical interest and revision fence for one producer incarnation. +public sealed record AcquisitionSubscriptionRequest(IReadOnlyList FullReferences, + TimeSpan RequestedSamplingInterval, long DesiredRevision, long ProducerIncarnation); + +/// The installed physical handle, supported nominal cadence, and acknowledged fence. +public sealed record AcquisitionSubscriptionResult(ISubscriptionHandle Handle, TimeSpan NominalSamplingInterval, + long DesiredRevision, long ProducerIncarnation); + +/// Fresh device acquisition results under a specific desired revision and producer incarnation. +public sealed record AcquisitionBatch(long DesiredRevision, long ProducerIncarnation, IReadOnlyList Items); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/PollGroupEngine.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/PollGroupEngine.cs index 81621c144..704b8eadd 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/PollGroupEngine.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/PollGroupEngine.cs @@ -105,7 +105,7 @@ public sealed class PollGroupEngine : IAsyncDisposable /// own elapsed time is NOT subtracted, so the failure branch is a fixed DELAY (cycle = /// poll + backoff), deliberately unlike the fixed-rate success branch. /// The interval feeding that schedule is the per-subscription interval - /// already clamped to in , so + /// already clamped to in , so /// the first failure's wait equals the clamped interval (shift 0 → 1×) and the floor is /// honoured for free. One asymmetry worth knowing: ComputeDelay saturates at the cap /// unconditionally, so a set SMALLER than the clamped @@ -154,20 +154,39 @@ public sealed class PollGroupEngine : IAsyncDisposable /// The desired polling interval; will be clamped to the configured minimum. /// A handle identifying the new subscription, for later use with . public ISubscriptionHandle Subscribe(IReadOnlyList fullReferences, TimeSpan publishingInterval) + => SubscribeCore(fullReferences, publishingInterval, null); + + /// Starts a subscription with a synchronous callback for each completed physical read. + /// The callback must copy mutable data before returning and must not mutate producer-owned + /// data. Teardown uses the engine's bounded drain; consumers must fence late callbacks when a + /// reader ignores cancellation or a callback blocks beyond that bound. + /// The list of tag references to poll. + /// The desired polling interval, clamped to the configured minimum. + /// Receives every result in reader order before change filtering. Values are borrowed until the callback returns. + /// A handle identifying the subscription. + public ISubscriptionHandle Subscribe(IReadOnlyList fullReferences, TimeSpan publishingInterval, + Action> onAcquired) + { + ArgumentNullException.ThrowIfNull(onAcquired); + return SubscribeCore(fullReferences, publishingInterval, onAcquired); + } + + private ISubscriptionHandle SubscribeCore(IReadOnlyList fullReferences, TimeSpan publishingInterval, + Action>? onAcquired) { ArgumentNullException.ThrowIfNull(fullReferences); var id = Interlocked.Increment(ref _nextId); var cts = new CancellationTokenSource(); var interval = publishingInterval < _minInterval ? _minInterval : publishingInterval; var handle = new PollSubscriptionHandle(id); - var state = new SubscriptionState(handle, [.. fullReferences], interval, cts); + var state = new SubscriptionState(handle, [.. fullReferences], interval, cts, onAcquired); _subscriptions[id] = state; state.LoopTask = Task.Run(() => PollLoopAsync(state, cts.Token)); return handle; } /// - /// Cancel the background loop for a handle returned by , BLOCKING the + /// Cancel the background loop for a handle returned by , BLOCKING the /// calling thread until the in-flight poll drains. Retained for compatibility; prefer /// on any path that runs inside an actor mailbox turn or a /// request pipeline, where blocking a thread for up to 5 s is never acceptable. @@ -183,8 +202,9 @@ public sealed class PollGroupEngine : IAsyncDisposable /// /// Non-blocking counterpart of : identical teardown semantics (the - /// loop is cancelled and awaited before the CTS is disposed, so no callback can fire after - /// this completes) but it awaits the loop task instead of blocking a thread on it. + /// loop is cancelled and awaited up to the drain timeout before the CTS is disposed) but it + /// awaits the loop task instead of blocking a thread on it. A reader or callback that does + /// not finish within that bound can outlive this call, so consumers must fence late callbacks. /// /// The subscription handle to cancel. /// true when the handle was known to the engine and has been torn down. @@ -391,6 +411,19 @@ public sealed class PollGroupEngine : IAsyncDisposable $"Reader contract violation: expected {state.TagReferences.Count} snapshots but received {snapshots.Count}. " + "The reader delegate must return one snapshot per input reference in input order."); + // Do not publish a read that completed after teardown was requested. The callback is + // installed in the state before the loop starts and runs inline, while reader values are + // still owned by the producer. A broken consumer must not suppress legacy changes. + ct.ThrowIfCancellationRequested(); + if (state.OnAcquired is not null) + { + var acquired = new DataChangeItem[state.TagReferences.Count]; + for (var i = 0; i < acquired.Length; i++) + acquired[i] = new DataChangeItem(state.TagReferences[i], snapshots[i]); + try { state.OnAcquired(acquired); } + catch (Exception ex) when (!IsFatal(ex)) { ReportError(ex); } + } + // Collected lazily: nothing is allocated for a cycle with no changes, and nothing at all // when no batch callback is wired. List? changed = null; @@ -461,7 +494,8 @@ public sealed class PollGroupEngine : IAsyncDisposable PollSubscriptionHandle Handle, IReadOnlyList TagReferences, TimeSpan Interval, - CancellationTokenSource Cts) + CancellationTokenSource Cts, + Action>? OnAcquired) { /// Gets the cache of last-seen values per tag reference. public ConcurrentDictionary LastValues { get; } @@ -469,7 +503,7 @@ public sealed class PollGroupEngine : IAsyncDisposable /// /// The background poll-loop task. Assigned immediately after creation in - /// ; awaited during / + /// ; awaited during / /// so disposal is deterministic and no /// _onChange callback can fire after the caller tears down the subscription. /// diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs index 65ac4d0ed..1c6d4d868 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs @@ -21,7 +21,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus; /// since Modbus has no native push model. /// public sealed class ModbusDriver - : IDriver, ITagDiscovery, IReadable, IWritable, IWriteOutcomeCapability, IBatchSubscribable, IHostConnectivityProbe, IPerCallHostResolver, ISkippedTagReporter, IDisposable, IAsyncDisposable + : IDriver, ITagDiscovery, IReadable, IWritable, IWriteOutcomeCapability, IBatchSubscribable, IAcknowledgedAcquisitionSource, IHostConnectivityProbe, IPerCallHostResolver, ISkippedTagReporter, IDisposable, IAsyncDisposable { /// Authored tags this driver could not build into its poll table. private readonly SkippedTagLedger _skippedTags = new(); @@ -232,6 +232,10 @@ public sealed class ModbusDriver /// Upper bound on the poll-loop failure backoff — adopts the S7-proven 30 s cap fleet-wide. private static readonly TimeSpan PollBackoffCap = TimeSpan.FromSeconds(30); + // Task.Delay's largest supported timer duration. Acquisition acknowledgments must never + // promise a cadence the polling loop cannot schedule. + private static readonly TimeSpan MaxAcquisitionInterval = TimeSpan.FromMilliseconds(uint.MaxValue - 1d); + /// /// Routes a poll-loop reader failure to the driver health surface: logs it and /// degrades to preserving LastSuccessfulRead. @@ -2017,13 +2021,47 @@ public sealed class ModbusDriver Task.FromResult(_poll.Subscribe(fullReferences, publishingInterval)); /// - public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) + /// The polling engine uses a bounded drain during teardown. Consumers must fence late + /// callbacks if a reader ignores cancellation or a callback blocks beyond that bound. Intervals + /// above the polling timer's maximum supported duration are rejected. + public async Task SubscribeAcquisitionAsync( + AcquisitionSubscriptionRequest request, Action onAcquired, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(onAcquired); + ArgumentNullException.ThrowIfNull(request.FullReferences); + if (request.FullReferences.Count == 0 || request.FullReferences.Any(string.IsNullOrWhiteSpace)) + throw new ArgumentException("At least one nonempty reference is required.", nameof(request)); + if (request.RequestedSamplingInterval < TimeSpan.Zero || request.RequestedSamplingInterval > MaxAcquisitionInterval) + throw new ArgumentOutOfRangeException(nameof(request), "Sampling interval is outside the supported timer range."); + if (request.DesiredRevision <= 0 || request.ProducerIncarnation <= 0) + throw new ArgumentOutOfRangeException(nameof(request), "Revision and producer incarnation must be positive."); + cancellationToken.ThrowIfCancellationRequested(); + + var handle = _poll.Subscribe(request.FullReferences, request.RequestedSamplingInterval, + items => onAcquired(new AcquisitionBatch(request.DesiredRevision, request.ProducerIncarnation, items))); + if (cancellationToken.IsCancellationRequested) + { + await UnsubscribeCoreAsync(handle).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + } + + var nominal = request.RequestedSamplingInterval < PollGroupEngine.DefaultMinInterval + ? PollGroupEngine.DefaultMinInterval : request.RequestedSamplingInterval; + return new AcquisitionSubscriptionResult(handle, nominal, request.DesiredRevision, request.ProducerIncarnation); + } + + /// + public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) => + UnsubscribeCoreAsync(handle); + + private async Task UnsubscribeCoreAsync(ISubscriptionHandle handle) { // Async teardown: the engine drains the in-flight poll without blocking the caller's // thread — this runs inside a DriverInstanceActor mailbox turn. await _poll.UnsubscribeAsync(handle).ConfigureAwait(false); - // Drop any partially-collected cycle buffer so a torn-down subscription leaks nothing. - // The teardown above awaits the loop task, so no onChange can re-add after this point. + // Drop any partially-collected cycle buffer. The bounded drain normally finishes the loop; + // a callback blocked beyond its timeout may still finish late and must be fenced by consumers. _cycleBatchItems.TryRemove(handle, out _); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ClientFilterState.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ClientFilterState.cs new file mode 100644 index 000000000..f93f8a0ef --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ClientFilterState.cs @@ -0,0 +1,56 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Per-registration baseline. Only a successful delivery may call Commit. +internal sealed class ClientFilterState : IDisposable +{ + private DataSample? _baseline; + + internal bool ShouldDeliver(DataSample sample, DataSubscriptionSettings settings) + { + ArgumentNullException.ThrowIfNull(sample); + ArgumentNullException.ThrowIfNull(settings); + settings.Validate(); + var baseline = _baseline; + if (baseline is null || sample.StatusCode != baseline.StatusCode || sample.Serving != baseline.Serving) + return true; + if (settings.Trigger == DataChangeTrigger.Status) return false; + if (settings.Trigger == DataChangeTrigger.StatusValueTimestamp && + (sample.SourceTimestampUtc != baseline.SourceTimestampUtc || sample.ServerTimestampUtc != baseline.ServerTimestampUtc)) + return true; + if (sample.Value.Kind != baseline.Value.Kind) return true; + if (settings.Deadband is { } deadband) + { + if (!Numeric(sample.Value, out var current) || !Numeric(baseline.Value, out var previous)) + throw new ArgumentException("A numeric deadband requires numeric scalar values.", nameof(settings)); + // Integer conversion to double can collapse distinct values above 2^53. Deliver + // conservatively rather than suppressing a real change in that range. + if (sample.Value.Kind is DataValueKind.Int64 or DataValueKind.UInt64 && + (Math.Abs(current) > 9_007_199_254_740_992d || Math.Abs(previous) > 9_007_199_254_740_992d) && + !Equals(sample.Value.GetScalar(), baseline.Value.GetScalar())) return true; + return !double.IsFinite(current) || !double.IsFinite(previous) || Math.Abs(current - previous) > deadband; + } + return !sample.Value.ContentEquals(baseline.Value); + } + + internal void Commit(DataSample sample) + { + ArgumentNullException.ThrowIfNull(sample); + var retained = sample with { Value = sample.Value.Retain() }; + var previous = _baseline; + _baseline = retained; + previous?.Dispose(); + } + + private static bool Numeric(DataValue value, out double number) + { + if (value.Kind is DataValueKind.Int8 or DataValueKind.Int16 or DataValueKind.Int32 or DataValueKind.Int64 or + DataValueKind.UInt8 or DataValueKind.UInt16 or DataValueKind.UInt32 or DataValueKind.UInt64 or + DataValueKind.Float or DataValueKind.Double) + { number = Convert.ToDouble(value.GetScalar(), System.Globalization.CultureInfo.InvariantCulture); return true; } + number = 0; return false; + } + + public void Dispose() { _baseline?.Dispose(); _baseline = null; } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataCapabilitiesProvider.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataCapabilitiesProvider.cs index d0234be58..a1fa67ea2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataCapabilitiesProvider.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataCapabilitiesProvider.cs @@ -26,7 +26,7 @@ public sealed class DataCapabilitiesProvider var ready = IsReady; serving.Validate(requireEpochs: ready); if (!string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) operations &= ~DataOperations.Write; - return new(1, 0, serving, ready ? DataReadiness.Ready : DataReadiness.Unavailable, + return new(1, 1, serving, ready ? DataReadiness.Ready : DataReadiness.Unavailable, ready ? operations : DataOperations.None, Enum.GetValues().Where(x => x != DataValueKind.Unspecified).ToHashSet(), limits, true, 1, ClusterId); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataResourceBudget.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataResourceBudget.cs index 910860269..22923c259 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataResourceBudget.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataResourceBudget.cs @@ -3,6 +3,8 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// Node-wide admission limits for the source cache and retained work. public sealed class DataResourceLimits { + /// Maximum bounded partition fan-out for a hub and its producer fences. + public const int MaxPartitionCount = 256; public int PartitionCount { get; init; } = 4; public long MaxRetainedBytes { get; init; } = 64 * 1024 * 1024; public int MaxTrackedSources { get; init; } = 100_000; @@ -16,7 +18,7 @@ public sealed class DataResourceLimits internal void Validate() { - if (PartitionCount <= 0 || MaxRetainedBytes <= 0 || MaxTrackedSources <= 0 || + if (PartitionCount <= 0 || PartitionCount > MaxPartitionCount || MaxRetainedBytes <= 0 || MaxTrackedSources <= 0 || MaxIngressItemsPerPartition <= 0 || MaxDirtySourcesPerPartition <= 0 || MaxControlItemsPerPartition <= 0 || MaxSnapshotItems <= 0 || MaxSnapshotBytes <= 0 || MaxSnapshotCatchUpItems <= 0 || MaxSnapshotLifetime <= TimeSpan.Zero) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs new file mode 100644 index 000000000..28aaa4556 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs @@ -0,0 +1,1187 @@ +using System.Threading.Channels; +using System.Collections.Concurrent; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// One caller-bound subscription with bounded commands and one ordered delivery mode. +internal sealed class DataSubscriptionSession : IDataSubscriptionTransport +{ + private readonly LocalDataServices _services; + private readonly DataAuthenticatedContext _context; + private readonly DataTarget _target; + private readonly ISubscriptionDemandSource _demand; + private readonly SubscriptionSessionLimits _limits; + private readonly SubscriptionTransportCapacity _capacity; + private readonly SharedSessionLease _sessionLease; + private readonly Channel _commands; + private readonly Queue _deferred = new(); + private readonly Channel _outbound; + private readonly CancellationTokenSource _stop = new(); + private readonly object _gate = new(); + private readonly Dictionary _items = new(); + private readonly Dictionary _itemsByClient = new(StringComparer.Ordinal); + private readonly LinkedList _interests = new(); + private LinkedListNode? _interestCursor; + private readonly List _snapshots = []; + private readonly List _snapshotAdmissions = []; + private readonly DeliveryScheduler _scheduler; + private readonly SortedSet<(long Due, ulong Handle)> _due = new(); + private readonly LinkedList _waiting = new(); + private readonly LinkedList _snapshotJobs = new(); + private readonly ConcurrentQueue _committedSnapshots = new(); + private readonly HashSet _pendingChanges = new(); + private readonly SortedSet<(long Deadline, long Id)> _ackDeadlines = new(); + private readonly Dictionary _ackByCommand = new(StringComparer.Ordinal); + private SubscriptionItemHandleTable? _handles; + private ITimer? _expiry, _tick, _ackTimer, _preOpen; + private string? _subscriptionId; + private ServingIdentity? _serving; + private long _epoch, _sequence, _dirtySequence, _ackId, _lastHeartbeat; + private int _mode, _closed, _closing, _tickQueued, _queuedValues, _barrier, _admissionCursor, _coalesced; + private readonly Task _worker; + internal Task Completion => _worker; + internal Action? BeforeDirectCommitForTests { get; set; } + internal Action? OnCandidateQueuedForTests { get; set; } + + private sealed class SharedSessionLease(IDisposable lease) : IDisposable + { + private IDisposable? _lease = lease; + private int _references = 1; + private sealed class Hold(SharedSessionLease owner) : IDisposable + { + private SharedSessionLease? _owner = owner; + public void Dispose() => Interlocked.Exchange(ref _owner, null)?.Dispose(); + } + internal IDisposable Retain() + { + while (true) + { + var current = Volatile.Read(ref _references); + if (current <= 0) throw new ObjectDisposedException(nameof(SharedSessionLease)); + if (Interlocked.CompareExchange(ref _references, checked(current + 1), current) == current) return new Hold(this); + } + } + public void Dispose() + { + if (Interlocked.Decrement(ref _references) == 0) Interlocked.Exchange(ref _lease, null)?.Dispose(); + } + } + + private sealed record Work(DataSubscriptionCommand? Command, long Started, IDisposable? Charge = null); + private sealed class Item(string clientItemId, DataItemHandle handle, SubscriptionAuthorizedView view, + DataSubscriptionSettings settings, IDisposable demandLease, IDisposable itemReservation) : IDisposable + { + internal readonly string ClientItemId = clientItemId; + internal readonly DataItemHandle Handle = handle; + internal readonly SubscriptionAuthorizedView View = view; + internal DataSubscriptionSettings Settings = settings; + internal IDisposable DemandLease = demandLease; + internal readonly SharedSessionLease Resources = new(itemReservation); + internal readonly ClientFilterState Filter = new(); + internal IDisposable? BaselineCharge; + internal SourceTicket? Ticket; + internal long LastConsidered, LastPublished, NextDue = 0; + internal long? LastDeliveryTimestamp; + internal long? QueuedDue; + internal LinkedListNode? WaitingNode; + internal InterestGroup? Interest; + public void Dispose() { Filter.Dispose(); BaselineCharge?.Dispose(); DemandLease.Dispose(); Resources.Dispose(); } + } + private sealed class InterestGroup(SourceInterestLease lease) + { + internal readonly SourceInterestLease Lease = lease; + internal int Count; + internal readonly Dictionary Sources = new(); + internal LinkedListNode? Node; + internal bool SnapshotComplete; + } + private sealed class SnapshotJob(SnapshotLease snapshot, IDisposable admission, InterestGroup group, + IReadOnlyList items, IReadOnlyList watermarks) + { + internal readonly SnapshotLease Snapshot = snapshot; + internal readonly IDisposable Admission = admission; + internal readonly InterestGroup Group = group; + internal readonly IReadOnlyList Items = items; + internal readonly IReadOnlyList Watermarks = watermarks; + internal int Index; + } + private sealed class StagedChange(Item previous, SubscriptionAuthorizedView view, DataSubscriptionSettings settings, + IDisposable demand, SnapshotLease snapshot, SourceInterestLease interest, IDisposable admission, + Item? replacement) + { + internal readonly Item Previous = previous; + internal readonly SubscriptionAuthorizedView View = view; + internal readonly DataSubscriptionSettings Settings = settings; + internal readonly IDisposable Demand = demand; + internal readonly SnapshotLease Snapshot = snapshot; + internal readonly SourceInterestLease Interest = interest; + internal readonly IDisposable Admission = admission; + internal readonly Item? Replacement = replacement; + internal int State = 0; + } + private sealed class BudgetLease(DataResourceBudget budget, long charge) : IDisposable + { + private DataResourceBudget? _budget = budget; + public void Dispose() => Interlocked.Exchange(ref _budget, null)?.Release(charge); + } + private sealed class CompositeLease(IDisposable first, IDisposable second) : IDisposable + { + private IDisposable? _first = first, _second = second; + public void Dispose() + { + try { Interlocked.Exchange(ref _first, null)?.Dispose(); } + finally { Interlocked.Exchange(ref _second, null)?.Dispose(); } + } + } + private sealed class SnapshotOwnership(SnapshotAdmissionScheduler.Permit permit, IDisposable hold) : IDisposable + { + internal readonly SnapshotAdmissionScheduler.Permit Permit = permit; + private IDisposable? _hold = hold; + public void Dispose() + { + Permit.Dispose(); + Interlocked.Exchange(ref _hold, null)?.Dispose(); + } + } + private sealed class PendingDelivery(Func create, Func gate, + Func? commit = null, Action? drop = null, bool isValue = false, Func? obsolete = null, + Func? eligible = null, Func? consumeSnapshot = null, + long directSnapshotBytes = 0, Action? settle = null, Action? failed = null, + Func? finalAuthority = null) : IDisposable + { + private int _transferred, _settled; + internal bool IsValue { get; } = isValue; + internal bool IsObsolete() => obsolete?.Invoke() == true; + internal bool IsEligible() => eligible?.Invoke() ?? true; + internal (bool Accepted, TimeSpan Retry) ConsumeSnapshot(long? bytes = null) => + consumeSnapshot?.Invoke(bytes ?? directSnapshotBytes) ?? (true, TimeSpan.Zero); + internal bool Gate() => gate(); + internal bool FinalAuthority() => finalAuthority?.Invoke() ?? true; + internal bool Commit() + { + var success = false; + try { success = commit?.Invoke() ?? true; return success; } + finally { Settle(success); } + } + internal void Fail() => Settle(false); + private void Settle(bool success) + { + if (Interlocked.Exchange(ref _settled, 1) != 0) return; + try { if (!success) failed?.Invoke(); } + finally { settle?.Invoke(); } + } + internal DataSubscriptionFrame Take(long sequence) + { + if (Interlocked.Exchange(ref _transferred, 1) != 0) throw new InvalidOperationException(); + try { return create(sequence); } + catch { drop?.Invoke(); Settle(false); throw; } + } + public void Dispose() + { + try { if (Interlocked.Exchange(ref _transferred, 1) == 0) drop?.Invoke(); } + finally { Settle(false); } + } + } + + internal DataSubscriptionSession(LocalDataServices services, DataAuthenticatedContext context, DataTarget target, + ISubscriptionDemandSource demand, SubscriptionSessionLimits limits, SubscriptionTransportCapacity capacity, + IDisposable sessionReservation, CancellationToken lifetimeToken = default) + { + _services = services; _context = context; _target = target; _demand = demand; _limits = limits; _capacity = capacity; + _sessionLease = new(sessionReservation); + limits.Validate(); + _commands = Channel.CreateBounded(new BoundedChannelOptions(limits.MaxCommands) + { SingleReader = true, FullMode = BoundedChannelFullMode.Wait }); + _outbound = Channel.CreateBounded(new BoundedChannelOptions(limits.MaxPendingFrames) + { SingleReader = true, SingleWriter = true, FullMode = BoundedChannelFullMode.Wait }); + _scheduler = new DeliveryScheduler(limits.MaxPendingFrames * 16, limits.MaxPendingFrames * 16); + var preOpen = limits.PreOpenTimeout ?? TimeSpan.FromSeconds(10); + _preOpen = services.Clock.CreateTimer(static state => ((DataSubscriptionSession)state!).Stop(), this, + preOpen, Timeout.InfiniteTimeSpan); + _worker = Task.Run(() => ProcessCommandsAsync(lifetimeToken)); + } + + public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(command); cancellationToken.ThrowIfCancellationRequested(); + if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _closing) != 0) throw new InvalidOperationException("Subscription is closed."); + if (command.AcknowledgementTimeout <= TimeSpan.Zero || command.AcknowledgementTimeout > TimeSpan.FromMilliseconds(uint.MaxValue - 1)) + throw new ArgumentOutOfRangeException(nameof(command)); + ArgumentException.ThrowIfNullOrWhiteSpace(command.CommandId); + ArgumentException.ThrowIfNullOrWhiteSpace(command.SubscriptionId); + if (!_capacity.TryAdmitCommand(_context.PrincipalId)) { Stop(); throw new InvalidOperationException("Principal command rate exceeded."); } + var reservedBytes = _limits.MaxPendingBytes; + if (!_services.SubscriptionHub.Resources.TryReserve(reservedBytes)) throw new InvalidOperationException("Command memory capacity exhausted."); + var commandCharge = new BudgetLease(_services.SubscriptionHub.Resources, reservedBytes); + try { command = CopyCommand(command); } + catch { commandCharge.Dispose(); throw; } + var started = _services.Clock.GetTimestamp(); + try + { + lock (_gate) + { + if (_ackByCommand.ContainsKey(command.CommandId) || _ackByCommand.Count >= _limits.MaxCommands) + throw new InvalidOperationException("Command ID is pending or command capacity is exhausted."); + var delta = (decimal)command.AcknowledgementTimeout.Ticks * _services.Clock.TimestampFrequency / TimeSpan.TicksPerSecond; + var deadline = delta >= (decimal)long.MaxValue - started ? long.MaxValue : started + (long)decimal.Ceiling(delta); + var entry = (deadline, checked(++_ackId)); + _ackByCommand.Add(command.CommandId, entry); _ackDeadlines.Add(entry); + try { ArmAckTimer(); } + catch { _ackByCommand.Remove(command.CommandId); _ackDeadlines.Remove(entry); throw; } + } + if (!_commands.Writer.TryWrite(new(command, started, commandCharge))) + { Stop(); throw new InvalidOperationException("Subscription command capacity exhausted."); } + } + catch { commandCharge.Dispose(); throw; } + return Task.CompletedTask; + } + + private DataSubscriptionCommand CopyCommand(DataSubscriptionCommand command) + { + long bytes = checked(256L + 2L * (command.SubscriptionId.Length + command.CommandId.Length)); + DataSubscriptionItem[] CopyItems(IReadOnlyList source) + { + ArgumentNullException.ThrowIfNull(source); + if (source.Count > _services.SubscriptionLimits.MaxBatchItems) throw new ArgumentOutOfRangeException(nameof(source)); + var copy = new DataSubscriptionItem[source.Count]; + for (var i = 0; i < copy.Length; i++) + { + var item = source[i] ?? throw new ArgumentException("Null subscription item."); + var view = item.View ?? throw new ArgumentException("Missing subscription view."); + var address = view.Address ?? throw new ArgumentException("Missing subscription address."); + bytes = checked(bytes + 512L + 2L * ((long)(item.ClientItemId?.Length ?? 0) + (view.Subject?.Length ?? 0) + + (view.MappingId?.Length ?? 0) + (address.OriginClusterId?.Length ?? 0) + (address.NamespaceUri?.Length ?? 0) + + (address.IdentifierKind?.Length ?? 0) + (address.Identifier?.Length ?? 0))); + if (bytes > _limits.MaxPendingBytes) throw new ArgumentOutOfRangeException(nameof(source)); + copy[i] = item; + } + return copy; + } + DataItemHandle[] CopyHandles(IReadOnlyList source) + { + ArgumentNullException.ThrowIfNull(source); + if (source.Count > _services.SubscriptionLimits.MaxBatchItems) throw new ArgumentOutOfRangeException(nameof(source)); + var copy = new DataItemHandle[source.Count]; + for (var i = 0; i < copy.Length; i++) + { + var item = source[i] ?? throw new ArgumentException("Null item handle."); + bytes = checked(bytes + 128L + 2L * (item.SubscriptionId?.Length ?? 0)); + if (bytes > _limits.MaxPendingBytes) throw new ArgumentOutOfRangeException(nameof(source)); + copy[i] = item; + } + return copy; + } + DataSubscriptionCommand result = command switch + { + OpenSubscription open => open with { Items = CopyItems(open.Items) }, + AddSubscriptionItems add => add with { Items = CopyItems(add.Items) }, + ModifySubscriptionItems modify => modify with { Items = CopyItems(modify.Items) }, + RemoveSubscriptionItems remove => remove with { Items = CopyHandles(remove.Items) }, + _ => throw new ArgumentException("Unknown subscription command.", nameof(command)) + }; + if (bytes > _limits.MaxPendingBytes) throw new ArgumentOutOfRangeException(nameof(command)); + return result; + } + + private void ArmAckTimer() + { + if (_ackDeadlines.Count == 0) { _ackTimer?.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); return; } + var now = _services.Clock.GetTimestamp(); + var deadline = _ackDeadlines.Min.Deadline; + var due = deadline <= now ? TimeSpan.Zero : _services.Clock.GetElapsedTime(now, deadline); + _ackTimer ??= _services.Clock.CreateTimer(static state => ((DataSubscriptionSession)state!).Stop(), this, + Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); + _ackTimer.Change(due, Timeout.InfiniteTimeSpan); + } + + private bool CompleteAck(string command) + { + lock (_gate) + { + if (!_ackByCommand.Remove(command, out var entry) || _services.Clock.GetTimestamp() >= entry.Deadline) return false; + _ackDeadlines.Remove(entry); ArmAckTimer(); return true; + } + } + + private async Task ProcessCommandsAsync(CancellationToken lifetimeToken) + { + using var lifetime = lifetimeToken.Register(static state => ((DataSubscriptionSession)state!).Stop(), this); + try + { + while (!_stop.IsCancellationRequested) + { + Work work; + if (Volatile.Read(ref _barrier) == 0 && _deferred.TryDequeue(out var deferred)) work = deferred; + else work = await _commands.Reader.ReadAsync(_stop.Token).ConfigureAwait(false); + var retained = false; + try + { + if (work.Command is null) { Interlocked.Exchange(ref _tickQueued, 0); await TickAsync().ConfigureAwait(false); continue; } + if (Volatile.Read(ref _barrier) != 0) + { + if (_deferred.Count >= _limits.MaxCommands) { Stop(); break; } + _deferred.Enqueue(work); retained = true; continue; + } + var command = work.Command; + if (_services.Clock.GetElapsedTime(work.Started) >= command.AcknowledgementTimeout) { Stop(); break; } + if (command is OpenSubscription open) await OpenAsync(open, work.Started).ConfigureAwait(false); + else + { + if (_handles is null || command.SubscriptionId != _subscriptionId || command.StreamEpoch != _epoch) { Stop(); break; } + if (command is ModifySubscriptionItems && HasIncompleteSnapshot()) + { _deferred.Enqueue(work); retained = true; Interlocked.CompareExchange(ref _barrier, 1, 0); continue; } + switch (command) + { + case AddSubscriptionItems add: await AddAsync(add.Items, add.CommandId, work.Started, add.AcknowledgementTimeout).ConfigureAwait(false); break; + case ModifySubscriptionItems modify: await ModifyAsync(modify, work.Started).ConfigureAwait(false); break; + case RemoveSubscriptionItems remove: await RemoveAsync(remove).ConfigureAwait(false); break; + default: Stop(); break; + } + } + } + finally { if (!retained) work.Charge?.Dispose(); } + } + } + catch (OperationCanceledException) when (_stop.IsCancellationRequested) { } + catch { Stop(); } + finally + { + _outbound.Writer.TryComplete(); + while (_commands.Reader.TryRead(out var abandoned)) abandoned.Charge?.Dispose(); + while (_deferred.TryDequeue(out var deferredWork)) deferredWork.Charge?.Dispose(); + while (_outbound.Reader.TryRead(out var pending)) { Dequeued(pending); pending.Dispose(); } + lock (_gate) + { + foreach (var item in _items.Values) item.Dispose(); + _items.Clear(); + _itemsByClient.Clear(); + foreach (var interest in _interests) interest.Lease.Dispose(); + _interests.Clear(); + foreach (var snapshot in _snapshots) snapshot.Dispose(); + _snapshots.Clear(); + foreach (var admission in _snapshotAdmissions) admission.Dispose(); + _snapshotAdmissions.Clear(); + _snapshotJobs.Clear(); + foreach (var change in _pendingChanges.ToArray()) CleanupStaged(change); + _pendingChanges.Clear(); + } + _sessionLease.Dispose(); + } + } + + private bool HasIncompleteSnapshot() + { + lock (_gate) return _interests.Any(group => !group.SnapshotComplete); + } + + private void ReleaseBarrier(int expected) + { + if (Interlocked.CompareExchange(ref _barrier, 0, expected) != expected) return; + // A full command queue already wakes the worker; otherwise this bounded signal does. + _commands.Writer.TryWrite(new(null, 0)); + } + + private async Task OpenAsync(OpenSubscription open, long started) + { + if (_handles is not null || string.IsNullOrWhiteSpace(open.SubscriptionId) || open.StreamEpoch <= 0 || + open.SessionLifetime <= TimeSpan.Zero || open.SessionLifetime > _limits.MaxSessionLifetime || + open.SessionLifetime > _services.SubscriptionLimits.MaxSessionLifetime) + { Stop(); return; } + open.SnapshotBudget.Validate(); + _serving = _services.SubscriptionServing(_context, _target); + if (_serving is null) { Stop(); return; } + _subscriptionId = open.SubscriptionId; _epoch = open.StreamEpoch; + _lastHeartbeat = _services.Clock.GetTimestamp(); + _handles = new SubscriptionItemHandleTable(open.SubscriptionId, open.StreamEpoch, + Math.Min(open.SnapshotBudget.MaxItems, _services.SubscriptionItemLimit(_context))); + Interlocked.Exchange(ref _preOpen, null)?.Dispose(); + var duration = open.SessionLifetime; + if (_context.CredentialExpiresUtc is { } expires) + { + var untilExpiry = expires - _services.Clock.GetUtcNow(); + if (untilExpiry <= TimeSpan.Zero) { Stop(); return; } + if (untilExpiry < duration) duration = untilExpiry; + } + _expiry = _services.Clock.CreateTimer(static s => ((DataSubscriptionSession)s!).Stop(), this, duration, Timeout.InfiniteTimeSpan); + _tick = _services.Clock.CreateTimer(static s => ((DataSubscriptionSession)s!).QueueTick(), this, + TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100)); + await AddAsync(open.Items, open.CommandId, started, open.AcknowledgementTimeout, open.SnapshotBudget).ConfigureAwait(false); + } + + private async Task AddAsync(IReadOnlyList requested, string commandId, long started, + TimeSpan timeout, DataBudget? snapshotBudget = null) + { + var acks = new List(requested.Count); + var admitted = new List(); + foreach (var request in requested) + { + _stop.Token.ThrowIfCancellationRequested(); + if (request is null || string.IsNullOrWhiteSpace(request.ClientItemId) || request.View is null || request.Settings is null) + { acks.Add(new(request?.ClientItemId ?? "", DataItemStatus.InvalidArgument, null, null, null)); continue; } + DataItemStatus status; + SubscriptionAuthorizedView? view; + try { request.Settings.Validate(); status = _services.AuthorizeSubscription(_context, _target, request.View, out view); } + catch (ArgumentException) { acks.Add(new(request.ClientItemId, DataItemStatus.InvalidArgument, null, null, null)); continue; } + if (status != DataItemStatus.Good || view is null) + { acks.Add(new(request.ClientItemId, status, null, null, null)); continue; } + if (view.Serving != _serving) + { acks.Add(new(request.ClientItemId, DataItemStatus.Unavailable, null, null, null)); continue; } + if (request.Settings.Deadband is not null && view.Metadata.ValueKind is not (DataValueKind.Int8 or DataValueKind.Int16 or + DataValueKind.Int32 or DataValueKind.Int64 or DataValueKind.UInt8 or DataValueKind.UInt16 or DataValueKind.UInt32 or + DataValueKind.UInt64 or DataValueKind.Float or DataValueKind.Double)) + { acks.Add(new(request.ClientItemId, DataItemStatus.Unsupported, null, null, "Deadband requires a numeric scalar.")); continue; } + var fixedBytes = checked(1024L + 2L * (request.ClientItemId.Length + view.View.Subject.Length + + view.View.Address.Identifier.Length + view.View.Address.NamespaceUri.Length + view.Source.StableSourceId.Length)); + var itemLimit = _services.SubscriptionItemLimit(_context); + if (itemLimit <= 0 || !_capacity.TryReserveInterest(_context.PrincipalId, itemLimit, fixedBytes, out var itemReservation)) + { acks.Add(new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null)); continue; } + var remaining = timeout - _services.Clock.GetElapsedTime(started); + if (remaining <= TimeSpan.Zero) { itemReservation!.Dispose(); Stop(); return; } + Task pending; + try { pending = _demand.AcquireAsync(view, request.Settings, _stop.Token).AsTask(); } + catch (Exception ex) when (ex is not OutOfMemoryException) + { itemReservation!.Dispose(); acks.Add(new(request.ClientItemId, DataItemStatus.Unavailable, null, null, null)); continue; } + SubscriptionDemandResult result; + try { result = await pending.WaitAsync(remaining, _services.Clock, _stop.Token).ConfigureAwait(false); } + catch (Exception ex) when (ex is TimeoutException or OperationCanceledException) + { + itemReservation!.Dispose(); + _ = pending.ContinueWith(static task => { if (task.Status == TaskStatus.RanToCompletion) task.Result.Lease?.Dispose(); }, + CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + Stop(); return; + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { itemReservation!.Dispose(); acks.Add(new(request.ClientItemId, DataItemStatus.Unavailable, null, null, null)); continue; } + if (result.Status != DataItemStatus.Good || result.Lease is null || result.RevisedSettings is null || result.Boundary <= 0 || !view.CanPublish()) + { + itemReservation!.Dispose(); result.Lease?.Dispose(); acks.Add(new(request.ClientItemId, + result.Status == DataItemStatus.Good ? DataItemStatus.Unavailable : result.Status, null, null, null)); continue; + } + DataItemHandle handle; + try { handle = _handles!.Add(request.ClientItemId); } + catch (Exception ex) when (ex is InvalidOperationException or OverflowException) + { itemReservation!.Dispose(); result.Lease.Dispose(); acks.Add(new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null)); continue; } + var item = new Item(request.ClientItemId, handle, view, result.RevisedSettings, result.Lease, itemReservation!); + if (_services.SubscriptionHub.TryGetCurrentTicket(view.Source, out var ticket)) item.Ticket = ticket; + lock (_gate) { _items.Add(handle.Handle, item); _itemsByClient.Add(item.ClientItemId, item); } + if (item.Ticket is null) lock (_gate) item.WaitingNode = _waiting.AddLast(handle.Handle); + admitted.Add(item); + acks.Add(new(request.ClientItemId, item.Ticket is null ? DataItemStatus.WaitingForInitialData : DataItemStatus.Good, + handle, result.RevisedSettings, null)); + } + if (_services.Clock.GetElapsedTime(started) >= timeout) { Stop(); return; } + if (admitted.Count == 0) { await EnqueueAsync(ControlAck(commandId, acks)).ConfigureAwait(false); return; } + var tickets = admitted.Where(x => x.Ticket is not null).Select(x => x.Ticket!.Value).Distinct().ToArray(); + if (tickets.Length == 0) + { await EnqueueAsync(ControlAck(commandId, acks, () => admitted.All(item => item.View.CanPublish()))).ConfigureAwait(false); return; } + var budget = snapshotBudget ?? new DataBudget(timeout, Math.Max(tickets.Length, 1), _limits.MaxPendingBytes); + if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, 1, out var rawAdmission)) { CloseWithReset("Snapshot admission exhausted; retry later."); return; } + var permit = (SnapshotAdmissionScheduler.Permit)rawAdmission!; + if (!permit.TryRetain(out var snapshotHold)) { permit.Dispose(); CloseWithReset("Snapshot admission expired."); return; } + var admission = new SnapshotOwnership(permit, snapshotHold!); + if (!_services.SubscriptionHub.TryCaptureInterestSnapshot(tickets, budget, _stop.Token, out var snapshot, out var interest, + permit)) + { admission.Dispose(); Stop(); return; } + InterestGroup group; + lock (_gate) + { + _snapshots.Add(snapshot!); _snapshotAdmissions.Add(admission!); + group = new InterestGroup(interest!); + foreach (var item in admitted.Where(x => x.Ticket is not null)) + { + item.Interest = group; group.Count++; + group.Sources.TryGetValue(item.View.Source, out var count); + group.Sources[item.View.Source] = count + 1; + } + group.Node = _interests.AddLast(group); + } + var byHandle = admitted.ToDictionary(x => x.Handle.Handle); + for (var i = 0; i < acks.Count; i++) + { + if (acks[i].Handle is not { } handle) continue; + var item = byHandle[handle.Handle]; + if (item.Ticket is not { } ticket || !snapshot!.Items.TryGetValue(ticket, out var captured) || + captured.Readiness != DataReadiness.Ready || captured.Sample is null) + acks[i] = acks[i] with { Status = DataItemStatus.WaitingForInitialData }; + } + await EnqueueAsync(ControlAck(commandId, acks, + () => !snapshot!.IsReset && admission.Permit.IsValid && admitted.All(item => item.View.CanPublish()))).ConfigureAwait(false); + var marks = snapshot!.Watermarks.Select(x => new PartitionWatermark(x.Key, x.Value)).ToArray(); + await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, marks, snapshot, admission.Permit)).ConfigureAwait(false); + foreach (var item in admitted) + { + if (item.Ticket is not { } ticket || !snapshot.Items.TryGetValue(ticket, out var captured)) continue; + if (!_scheduler.TryRegister(item.View.Source, checked((long)item.Handle.Handle))) { Stop(); return; } + if (captured.Sample is not null) item.LastConsidered = captured.Sample.Version; + } + _snapshotJobs.AddLast(new SnapshotJob(snapshot, admission, group, admitted, marks)); + await PumpSnapshotsAsync().ConfigureAwait(false); + } + + private async Task RemoveAsync(RemoveSubscriptionItems remove) + { + var acks = new List(); + foreach (var handle in remove.Items) + { + Item? item; + lock (_gate) + { + if (!_handles!.IsCurrent(handle) || !_items.Remove(handle.Handle, out item)) item = null; + else { _handles.Remove(handle); _itemsByClient.Remove(item.ClientItemId); } + } + if (item is null) { acks.Add(new("", DataItemStatus.NotFound, null, null, null)); continue; } + ReleaseItem(item); + acks.Add(new(item.ClientItemId, DataItemStatus.Good, handle, null, null)); + } + await EnqueueAsync(ControlAck(remove.CommandId, acks)).ConfigureAwait(false); + } + + private async Task ModifyAsync(ModifySubscriptionItems modify, long started) + { + var acks = new List(modify.Items.Count); + var changes = new List(); + var seen = new HashSet(StringComparer.Ordinal); + foreach (var request in modify.Items) + { + if (request is null || string.IsNullOrWhiteSpace(request.ClientItemId) || request.View is null || request.Settings is null || !seen.Add(request.ClientItemId)) + { acks.Add(new(request?.ClientItemId ?? "", DataItemStatus.InvalidArgument, null, null, null)); continue; } + Item? previous; + lock (_gate) _itemsByClient.TryGetValue(request.ClientItemId, out previous); + if (previous is null) { acks.Add(new(request.ClientItemId, DataItemStatus.NotFound, null, null, null)); continue; } + DataItemStatus status; + SubscriptionAuthorizedView? view; + try { request.Settings.Validate(); status = _services.AuthorizeSubscription(_context, _target, request.View, out view); } + catch (ArgumentException) { acks.Add(new(request.ClientItemId, DataItemStatus.InvalidArgument, null, null, null)); continue; } + if (status != DataItemStatus.Good || view is null || view.Serving != _serving) + { acks.Add(new(request.ClientItemId, status == DataItemStatus.Good ? DataItemStatus.Unavailable : status, null, null, null)); continue; } + if (request.Settings.Deadband is not null && view.Metadata.ValueKind is not (DataValueKind.Int8 or DataValueKind.Int16 or + DataValueKind.Int32 or DataValueKind.Int64 or DataValueKind.UInt8 or DataValueKind.UInt16 or DataValueKind.UInt32 or + DataValueKind.UInt64 or DataValueKind.Float or DataValueKind.Double)) + { acks.Add(new(request.ClientItemId, DataItemStatus.Unsupported, null, null, null)); continue; } + var remaining = modify.AcknowledgementTimeout - _services.Clock.GetElapsedTime(started); + if (remaining <= TimeSpan.Zero) { foreach (var c in changes) CleanupStaged(c); Stop(); return; } + Task pending; + try { pending = _demand.AcquireAsync(view, request.Settings, _stop.Token).AsTask(); } + catch (Exception ex) when (ex is not OutOfMemoryException) + { acks.Add(new(request.ClientItemId, DataItemStatus.Unavailable, null, null, null)); continue; } + SubscriptionDemandResult result; + try { result = await pending.WaitAsync(remaining, _services.Clock, _stop.Token).ConfigureAwait(false); } + catch (Exception ex) when (ex is TimeoutException or OperationCanceledException) + { + _ = pending.ContinueWith(static task => { if (task.Status == TaskStatus.RanToCompletion) task.Result.Lease?.Dispose(); }, + CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + foreach (var c in changes) CleanupStaged(c); Stop(); return; + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { acks.Add(new(request.ClientItemId, DataItemStatus.Unavailable, null, null, null)); continue; } + if (result.Status != DataItemStatus.Good || result.Lease is null || result.RevisedSettings is null || result.Boundary <= 0 || + !view.CanPublish() || !_services.SubscriptionHub.TryGetCurrentTicket(view.Source, out var ticket)) + { + result.Lease?.Dispose(); acks.Add(new(request.ClientItemId, + result.Status == DataItemStatus.Good ? DataItemStatus.WaitingForInitialData : result.Status, null, null, null)); continue; + } + var budget = new DataBudget(remaining, 1, _limits.MaxPendingBytes); + if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, 1, out var rawAdmission)) + { + result.Lease.Dispose(); + acks.Add(new(request.ClientItemId, DataItemStatus.ResourceExhausted, null, null, null)); continue; + } + var permit = (SnapshotAdmissionScheduler.Permit)rawAdmission!; + if (!permit.TryRetain(out var snapshotHold)) + { permit.Dispose(); result.Lease.Dispose(); acks.Add(new(request.ClientItemId, DataItemStatus.ResourceExhausted, null, null, null)); continue; } + var admission = new SnapshotOwnership(permit, snapshotHold!); + if (!_services.SubscriptionHub.TryCaptureInterestSnapshot([ticket], budget, _stop.Token, out var snapshot, out var interest, permit)) + { admission.Dispose(); result.Lease.Dispose(); acks.Add(new(request.ClientItemId, DataItemStatus.ResourceExhausted, null, null, null)); continue; } + var captured = snapshot!.Items[ticket]; + if (captured.Readiness != DataReadiness.Ready || captured.Sample is null) + { + snapshot.Dispose(); interest!.Dispose(); admission!.Dispose(); result.Lease.Dispose(); + acks.Add(new(request.ClientItemId, DataItemStatus.WaitingForInitialData, null, null, null)); continue; + } + var intervalOnly = previous.View.View == view.View && previous.Settings.Trigger == result.RevisedSettings.Trigger && + previous.Settings.Deadband == result.RevisedSettings.Deadband; + Item? replacement = null; + if (!intervalOnly) + { + var fixedBytes = checked(1024L + 2L * (request.ClientItemId.Length + view.View.Subject.Length + + view.View.Address.Identifier.Length + view.View.Address.NamespaceUri.Length + view.Source.StableSourceId.Length)); + if (!_capacity.TryReserveInterest(_context.PrincipalId, _services.SubscriptionItemLimit(_context), fixedBytes, out var itemReservation)) + { + snapshot.Dispose(); interest!.Dispose(); admission!.Dispose(); result.Lease.Dispose(); + acks.Add(new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null)); continue; + } + DataItemHandle handle; + try { handle = _handles!.ReserveReplacement(previous.Handle); } + catch (Exception ex) when (ex is InvalidOperationException or OverflowException) + { + itemReservation!.Dispose(); snapshot.Dispose(); interest!.Dispose(); admission!.Dispose(); result.Lease.Dispose(); + acks.Add(new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null)); continue; + } + replacement = new Item(request.ClientItemId, handle, view, result.RevisedSettings, result.Lease, itemReservation!) + { Ticket = ticket, LastConsidered = captured.Sample.Version }; + if (!_scheduler.TryRegister(view.Source, checked((long)handle.Handle))) + { + _handles.CancelReplacement(handle); replacement.Dispose(); snapshot.Dispose(); interest!.Dispose(); admission!.Dispose(); + acks.Add(new(request.ClientItemId, DataItemStatus.ResourceExhausted, null, null, null)); continue; + } + } + var change = new StagedChange(previous, view, result.RevisedSettings, result.Lease, snapshot, interest!, admission!, replacement); + lock (_gate) _pendingChanges.Add(change); + changes.Add(change); + acks.Add(new(request.ClientItemId, DataItemStatus.Good, replacement?.Handle ?? previous.Handle, result.RevisedSettings, null)); + } + if (_services.Clock.GetElapsedTime(started) >= modify.AcknowledgementTimeout) + { foreach (var change in changes) CleanupStaged(change); Stop(); return; } + if (changes.Count == 0) { await EnqueueAsync(ControlAck(modify.CommandId, acks)).ConfigureAwait(false); return; } + Interlocked.Exchange(ref _barrier, 2); + await EnqueueAsync(ControlAck(modify.CommandId, acks, + () => changes.All(change => change.State == 0 && !change.Snapshot.IsReset && + ((SnapshotOwnership)change.Admission).Permit.IsValid) && changes.All(change => change.View.CanPublish()), + () => CommitStaged(changes), + () => { foreach (var change in changes) CleanupStaged(change); }, + () => changes.All(change => change.View.CanPublish()))).ConfigureAwait(false); + } + + private bool CommitStaged(IReadOnlyList changes) + { + lock (_gate) + { + if (Volatile.Read(ref _closed) != 0 || changes.Any(change => change.State != 0 || !change.View.CanPublish() || + change.Snapshot.IsReset || !((SnapshotOwnership)change.Admission).Permit.IsValid || + !_handles!.IsCurrent(change.Previous.Handle))) return false; + foreach (var change in changes) + { + if (change.Replacement is null) + { + var oldDemand = change.Previous.DemandLease; + change.Previous.Settings = change.Settings; change.Previous.DemandLease = change.Demand; + change.Previous.NextDue = DueFor(change.Previous.LastDeliveryTimestamp, change.Settings); + if (change.Previous.QueuedDue is { } previousDue) + { + _due.Remove((previousDue, change.Previous.Handle.Handle)); + change.Previous.QueuedDue = change.Previous.NextDue; + _due.Add((change.Previous.NextDue, change.Previous.Handle.Handle)); + } + MarkDirty(change.Previous.View.Source); + oldDemand.Dispose(); change.Snapshot.Dispose(); change.Interest.Dispose(); change.Admission.Dispose(); + } + else + { + var item = change.Replacement; + if (!_handles!.CommitReplacement(change.Previous.Handle, item.Handle)) return false; + _items.Remove(change.Previous.Handle.Handle); _itemsByClient.Remove(change.Previous.ClientItemId); + ReleaseItem(change.Previous); + _items.Add(item.Handle.Handle, item); _itemsByClient.Add(item.ClientItemId, item); + var group = new InterestGroup(change.Interest) { Count = 1 }; + group.Sources.Add(item.View.Source, 1); group.Node = _interests.AddLast(group); item.Interest = group; + _snapshots.Add(change.Snapshot); _snapshotAdmissions.Add(change.Admission); + var marks = change.Snapshot.Watermarks.Select(x => new PartitionWatermark(x.Key, x.Value)).ToArray(); + _committedSnapshots.Enqueue(new SnapshotJob(change.Snapshot, change.Admission, group, [item], marks)); + } + change.State = 1; _pendingChanges.Remove(change); + } + } + ReleaseBarrier(2); return true; + } + + private void CleanupStaged(StagedChange change) + { + lock (_gate) + { + if (change.State != 0) return; + change.State = 2; _pendingChanges.Remove(change); + if (change.Replacement is { } replacement) + { + _handles?.CancelReplacement(replacement.Handle); + _scheduler.Unregister(replacement.View.Source, checked((long)replacement.Handle.Handle)); + replacement.Dispose(); + } + else change.Demand.Dispose(); + change.Snapshot.Dispose(); change.Interest.Dispose(); change.Admission.Dispose(); + } + } + + private void ReleaseItem(Item item) + { + lock (_gate) + { + _scheduler.Unregister(item.View.Source, checked((long)item.Handle.Handle)); + if (item.QueuedDue is { } due) _due.Remove((due, item.Handle.Handle)); + if (item.WaitingNode is not null) { _waiting.Remove(item.WaitingNode); item.WaitingNode = null; } + if (item.Interest is { } group) + { + var sourceCount = group.Sources[item.View.Source] - 1; + if (sourceCount == 0) + { + group.Sources.Remove(item.View.Source); + if (item.Ticket is { } ticket) group.Lease.ReleaseTicket(ticket); + } + else group.Sources[item.View.Source] = sourceCount; + if (--group.Count == 0) + { + if (_interestCursor == group.Node) _interestCursor = group.Node!.Next ?? _interests.First; + _interests.Remove(group.Node!); + if (_interestCursor == group.Node) _interestCursor = _interests.First; + group.Lease.Dispose(); + } + } + } + item.Dispose(); + } + + private void QueueTick() + { + if (Interlocked.Exchange(ref _tickQueued, 1) != 0 || Volatile.Read(ref _closed) != 0) return; + if (!_commands.Writer.TryWrite(new(null, 0))) { Interlocked.Exchange(ref _tickQueued, 0); Stop(); } + } + + private async Task TickAsync() + { + lock (_gate) + { + for (var count = 0; count < Math.Min(32, _snapshotAdmissions.Count); count++) + { + if (_admissionCursor >= _snapshotAdmissions.Count) _admissionCursor = 0; + if (_snapshotAdmissions[_admissionCursor++] is SnapshotOwnership ownership && !ownership.Permit.IsValid) + { CloseWithReset("Snapshot lifetime expired; retry later."); return; } + } + } + for (var count = 0; count < 32 && _committedSnapshots.TryDequeue(out var committed); count++) + { + await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, committed.Watermarks, committed.Snapshot, + ((SnapshotOwnership)committed.Admission).Permit)).ConfigureAwait(false); + _snapshotJobs.AddLast(committed); + } + if (_services.Clock.GetElapsedTime(_lastHeartbeat) >= TimeSpan.FromSeconds(5)) + { + _lastHeartbeat = _services.Clock.GetTimestamp(); + var serving = _serving!; + await EnqueueAsync(new PendingDelivery(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, + sequence, DataStreamControlKind.Heartbeat, [], serving.CatalogEpoch, serving.AuthorityEpoch, null), + () => Volatile.Read(ref _closed) == 0 && _services.CanUseSubscription(_context, _target, _serving))).ConfigureAwait(false); + } + int retryCount; + lock (_gate) retryCount = Math.Min(32, _waiting.Count); + for (var count = 0; count < retryCount; count++) + { + Item? waiting; + lock (_gate) + { + if (_waiting.First is not { } node) break; + _waiting.RemoveFirst(); _items.TryGetValue(node.Value, out waiting); + if (waiting is not null) waiting.WaitingNode = null; + } + if (waiting is null) continue; + if (!_services.SubscriptionHub.TryGetCurrentTicket(waiting.View.Source, out var ticket)) + { + lock (_gate) if (_items.ContainsKey(waiting.Handle.Handle)) waiting.WaitingNode = _waiting.AddLast(waiting.Handle.Handle); + continue; + } + waiting.Ticket = ticket; + if (!await RecoverWaitingAsync(waiting, ticket).ConfigureAwait(false)) + { + lock (_gate) if (_items.ContainsKey(waiting.Handle.Handle)) + { waiting.Ticket = null; waiting.WaitingNode = _waiting.AddLast(waiting.Handle.Handle); } + } + } + List interests = []; + lock (_gate) + { + _interestCursor ??= _interests.First; + for (var count = 0; count < Math.Min(32, _interests.Count); count++) + { + var current = _interestCursor!; + if (current.Value.SnapshotComplete) interests.Add(current.Value.Lease); + _interestCursor = current.Next ?? _interests.First; + } + } + await PumpSnapshotsAsync().ConfigureAwait(false); + foreach (var interest in interests) + { + if (!interest.TryReadChanges(32, out var changes)) { CloseWithReset("Source change history expired."); return; } + foreach (var change in changes) MarkDirty(change.Ticket.Key); + } + var availableValues = Math.Max(0, Math.Max(1, _limits.MaxPendingFrames - 2) - Volatile.Read(ref _queuedValues)); + if (availableValues > 0) + foreach (var scheduled in _scheduler.TakeSlice(Math.Min(32, availableValues))) + { + Item? item; + lock (_gate) _items.TryGetValue((ulong)scheduled.InterestId, out item); + if (item is not null) await ConsiderAsync(item).ConfigureAwait(false); + } + var now = _services.Clock.GetTimestamp(); + var dueItems = new List(); + lock (_gate) + { + availableValues = Math.Max(0, Math.Max(1, _limits.MaxPendingFrames - 2) - Volatile.Read(ref _queuedValues)); + for (var count = 0; count < Math.Min(32, availableValues) && _due.Count > 0 && _due.Min.Due <= now; count++) + { + var entry = _due.Min; _due.Remove(entry); + if (!_items.TryGetValue(entry.Handle, out var item)) continue; + item.QueuedDue = null; dueItems.Add(item); + } + } + foreach (var item in dueItems) await ConsiderAsync(item).ConfigureAwait(false); + } + + private async Task RecoverWaitingAsync(Item item, SourceTicket ticket) + { + var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, _limits.MaxPendingBytes); + if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, 1, out var rawAdmission)) return false; + var permit = (SnapshotAdmissionScheduler.Permit)rawAdmission!; + if (!permit.TryRetain(out var snapshotHold)) { permit.Dispose(); return false; } + var admission = new SnapshotOwnership(permit, snapshotHold!); + if (!_services.SubscriptionHub.TryCaptureInterestSnapshot([ticket], budget, _stop.Token, out var snapshot, out var interest, + permit)) + { admission.Dispose(); return false; } + InterestGroup group; + lock (_gate) + { + if (!_items.TryGetValue(item.Handle.Handle, out var current) || !ReferenceEquals(current, item)) + { snapshot!.Dispose(); interest!.Dispose(); admission!.Dispose(); return true; } + if (!_scheduler.TryRegister(item.View.Source, checked((long)item.Handle.Handle))) + { snapshot!.Dispose(); interest!.Dispose(); admission!.Dispose(); CloseWithReset("Interest capacity exhausted."); return true; } + _snapshots.Add(snapshot!); _snapshotAdmissions.Add(admission!); + group = new InterestGroup(interest!) { Count = 1 }; + group.Sources.Add(item.View.Source, 1); + group.Node = _interests.AddLast(group); item.Interest = group; + } + var marks = snapshot!.Watermarks.Select(x => new PartitionWatermark(x.Key, x.Value)).ToArray(); + await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, marks, snapshot, admission.Permit)).ConfigureAwait(false); + var captured = snapshot.Items[ticket]; + if (captured.Sample is not null) item.LastConsidered = captured.Sample.Version; + _snapshotJobs.AddLast(new SnapshotJob(snapshot, admission!, group, [item], marks)); + await PumpSnapshotsAsync().ConfigureAwait(false); + return true; + } + + private async Task PumpSnapshotsAsync() + { + var budget = Math.Min(32, _snapshotJobs.Count * 2); + while (budget-- > 0 && _snapshotJobs.First is { } node && Volatile.Read(ref _closing) == 0) + { + var job = node.Value; _snapshotJobs.RemoveFirst(); + if (job.Snapshot.IsReset || !((SnapshotOwnership)job.Admission).Permit.IsValid) + { CloseWithReset("Snapshot catch-up expired; retry later."); return; } + if (job.Index < job.Items.Count) + { + if (Volatile.Read(ref _queuedValues) >= Math.Max(1, _limits.MaxPendingFrames - 2)) + { _snapshotJobs.AddFirst(job); return; } + var item = job.Items[job.Index++]; + if (_handles!.IsCurrent(item.Handle) && item.Ticket is { } ticket && + job.Snapshot.Items.TryGetValue(ticket, out var captured) && captured.Sample is not null && + captured.ReceivedTimestamp is { } received) + { + var delivery = MakeValue(item, captured.Sample, received, true, job.Snapshot, + ((SnapshotOwnership)job.Admission).Permit); + if (delivery is null) + { + if (!_handles.IsCurrent(item.Handle)) { _snapshotJobs.AddLast(job); continue; } + CloseWithReset("Pending snapshot memory exhausted."); return; + } + await EnqueueAsync(delivery).ConfigureAwait(false); + } + _snapshotJobs.AddLast(job); + continue; + } + await EnqueueAsync(Control(DataStreamControlKind.SnapshotEnd, job.Watermarks, job.Snapshot, + ((SnapshotOwnership)job.Admission).Permit, () => + { + var allComplete = false; + lock (_gate) + { + job.Group.SnapshotComplete = true; + _snapshots.Remove(job.Snapshot); _snapshotAdmissions.Remove(job.Admission); + allComplete = _interests.All(group => group.SnapshotComplete); + } + job.Snapshot.Dispose(); job.Admission.Dispose(); QueueTick(); + if (allComplete) ReleaseBarrier(1); + }, () => { job.Snapshot.Dispose(); job.Admission.Dispose(); })).ConfigureAwait(false); + } + } + + private void MarkDirty(BackingSourceKey source) => _scheduler.TryMarkDirty(source, Interlocked.Increment(ref _dirtySequence)); + + private async Task ConsiderAsync(Item item) + { + if (item.Ticket is not { } ticket) return; + using var read = _services.SubscriptionHub.Read(ticket); + if (read.Readiness != DataReadiness.Ready || read.Sample is null) { CloseWithReset("Source became unavailable."); return; } + if (read.Sample.Version <= item.LastConsidered) return; + var now = _services.Clock.GetTimestamp(); + lock (_gate) + { + if (!_items.TryGetValue(item.Handle.Handle, out var current) || !ReferenceEquals(current, item)) return; + if (now < item.NextDue) + { + if (item.QueuedDue is null) { item.QueuedDue = item.NextDue; _due.Add((item.NextDue, item.Handle.Handle)); } + return; + } + item.LastConsidered = read.Sample.Version; + if (!item.Filter.ShouldDeliver(read.Sample, item.Settings)) return; + } + var delivery = MakeValue(item, read.Sample, read.ReceivedTimestamp, false, null); + if (delivery is null) { if (!_handles!.IsCurrent(item.Handle)) return; CloseWithReset("Pending value memory exhausted."); return; } + await EnqueueAsync(delivery).ConfigureAwait(false); + OnCandidateQueuedForTests?.Invoke(item.Handle, read.Sample.Version); + } + + private PendingDelivery? MakeValue(Item item, DataSample sample, long received, bool snapshot, SnapshotLease? snapshotLease, + SnapshotAdmissionScheduler.Permit? snapshotPermit = null) + { + var charge = checked(sample.Value.EstimatedRetainedBytes + PartitionedSampleHub.ReferenceOverhead); + IDisposable? snapshotHold = null; + if (snapshotPermit is not null && !snapshotPermit.TryRetain(out snapshotHold)) return null; + if (!_services.SubscriptionHub.Resources.TryReserve(charge)) { snapshotHold?.Dispose(); return null; } + DataSample owned; + try { owned = sample with { Value = sample.Value.Retain(), Serving = item.View.Serving }; } + catch { snapshotHold?.Dispose(); _services.SubscriptionHub.Resources.Release(charge); throw; } + IDisposable lease; + try + { + lease = new CompositeLease(new BudgetLease(_services.SubscriptionHub.Resources, charge), item.Resources.Retain()); + if (snapshotHold is not null) lease = new CompositeLease(lease, snapshotHold); + } + catch { owned.Dispose(); snapshotHold?.Dispose(); _services.SubscriptionHub.Resources.Release(charge); return null; } + bool Gate() => item.Ticket is { } ticket && + (snapshotLease is null || snapshotLease.IsItemCurrent(ticket) && snapshotPermit?.IsValid == true) && + Volatile.Read(ref _closed) == 0 && Volatile.Read(ref _closing) == 0 && _handles!.IsCurrent(item.Handle) && + _services.SubscriptionHub.IsTicketCurrentNonBlocking(ticket) && item.View.CanPublish(); + bool Commit() + { + lock (_gate) + { + if (!Gate() || !_items.TryGetValue(item.Handle.Handle, out var current) || !ReferenceEquals(current, item)) return false; + if (!_services.SubscriptionHub.Resources.TryReserve(charge)) return false; + var next = new BudgetLease(_services.SubscriptionHub.Resources, charge); + item.Filter.Commit(owned); item.BaselineCharge?.Dispose(); item.BaselineCharge = next; + item.LastPublished = owned.Version; + var now = _services.Clock.GetTimestamp(); + item.LastDeliveryTimestamp = now; item.NextDue = DueFor(now, item.Settings); + return true; + } + } + bool Eligible() + { + if (snapshot) return true; + if (item.Ticket is not { } ticket) return false; + using var latest = _services.SubscriptionHub.Read(ticket); + if (latest.Readiness != DataReadiness.Ready || latest.Sample is null) { CloseWithReset("Source became unavailable."); return false; } + if (latest.Sample.Version > owned.Version) + { + Interlocked.Exchange(ref _coalesced, 1); + MarkDirty(item.View.Source); QueueTick(); return false; + } + lock (_gate) + { + if (_services.Clock.GetTimestamp() < item.NextDue) + { + if (item.LastConsidered == owned.Version) item.LastConsidered = item.LastPublished; + if (item.QueuedDue is null) { item.QueuedDue = item.NextDue; _due.Add((item.NextDue, item.Handle.Handle)); } + return false; + } + return item.Filter.ShouldDeliver(owned, item.Settings); + } + } + return new PendingDelivery(sequence => + { + var age = _services.Clock.GetElapsedTime(received); + if (age < TimeSpan.Zero) throw new InvalidOperationException("Invalid monotonic age."); + return new DataSubscriptionValues(_subscriptionId!, _epoch, sequence, snapshot, + [new(item.Handle, owned, new DataAgeBounds(age, null), DataReadiness.Ready)], lease); + }, Gate, Commit, () => { owned.Dispose(); lease.Dispose(); }, true, + () => Volatile.Read(ref _closing) != 0 || !_handles!.IsCurrent(item.Handle), Eligible, + snapshot ? bytes => + { + if (snapshotPermit?.IsValid != true) return (false, TimeSpan.FromSeconds(1)); + var accepted = _capacity.Snapshots.TryConsume(_context.PrincipalId, bytes, out var retry); + return (accepted, retry); + } : null, charge); + } + + private long DueFor(long? observedStart, DataSubscriptionSettings settings) + { + if (observedStart is not { } start) return 0; + var interval = settings.SamplingInterval > settings.PublishingInterval ? settings.SamplingInterval : settings.PublishingInterval; + var delta = (decimal)interval.Ticks * _services.Clock.TimestampFrequency / TimeSpan.TicksPerSecond; + return delta >= (decimal)long.MaxValue - start ? long.MaxValue : start + (long)decimal.Ceiling(delta); + } + + private PendingDelivery ControlAck(string command, IReadOnlyList acks, + Func? additionalGate = null, Func? onDelivered = null, Action? onFailed = null, + Func? finalAuthority = null) + { + long bytes = checked(256L + 2L * command.Length); + foreach (var ack in acks) + bytes = checked(bytes + 256L + 2L * ((ack.ClientItemId?.Length ?? 0) + (ack.Diagnostic?.Length ?? 0))); + if (bytes > _limits.MaxPendingBytes || !_services.SubscriptionHub.Resources.TryReserve(bytes)) + throw new InvalidOperationException("Acknowledgement memory capacity exhausted."); + var charge = new BudgetLease(_services.SubscriptionHub.Resources, bytes); + return new PendingDelivery(sequence => new DataSubscriptionAck(_subscriptionId!, _epoch, sequence, command, acks), + () => (additionalGate?.Invoke() ?? true) && Volatile.Read(ref _closed) == 0 && + _services.CanUseSubscription(_context, _target, _serving), + () => CompleteAck(command) && (onDelivered?.Invoke() ?? true), settle: charge.Dispose, failed: onFailed, + finalAuthority: finalAuthority); + } + private PendingDelivery Control(DataStreamControlKind kind, IReadOnlyList marks, SnapshotLease snapshot, + SnapshotAdmissionScheduler.Permit permit, Action? delivered = null, Action? dropped = null) + { + var serving = _serving ?? throw new InvalidOperationException("Stream serving identity is unavailable."); + return new(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence, kind, marks, + serving.CatalogEpoch, serving.AuthorityEpoch, null), + () => !snapshot.IsReset && permit.IsValid && Volatile.Read(ref _closed) == 0 && Volatile.Read(ref _closing) == 0 && + _services.CanUseSubscription(_context, _target, _serving), + () => { delivered?.Invoke(); return true; }, dropped, obsolete: () => Volatile.Read(ref _closing) != 0); + } + private Task EnqueueAsync(PendingDelivery delivery) + { + if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _closing) != 0) { delivery.Dispose(); return Task.CompletedTask; } + if (delivery.IsValue && Interlocked.Increment(ref _queuedValues) > Math.Max(1, _limits.MaxPendingFrames - 2)) + { + Interlocked.Decrement(ref _queuedValues); delivery.Dispose(); CloseWithReset("Pending value capacity exhausted."); return Task.CompletedTask; + } + if (!_outbound.Writer.TryWrite(delivery)) + { + Dequeued(delivery); delivery.Dispose(); CloseWithReset("Pending control capacity exhausted."); + } + return Task.CompletedTask; + } + private void Dequeued(PendingDelivery delivery) + { + if (delivery.IsValue) Interlocked.Decrement(ref _queuedValues); + QueueTick(); + } + private PendingDelivery CoalescedControl() + { + var serving = _serving ?? throw new InvalidOperationException("Stream serving identity is unavailable."); + return new PendingDelivery(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence, + DataStreamControlKind.Coalesced, [], serving.CatalogEpoch, serving.AuthorityEpoch, null), + () => Volatile.Read(ref _closed) == 0 && Volatile.Read(ref _closing) == 0 && + _services.CanUseSubscription(_context, _target, serving)); + } + private void CloseWithReset(string diagnostic) + { + if (Interlocked.Exchange(ref _closing, 1) != 0) return; + _tick?.Dispose(); + var serving = _serving; + if (serving is null || !_outbound.Writer.TryWrite(new PendingDelivery(sequence => + new DataSubscriptionControl(_subscriptionId!, _epoch, sequence, DataStreamControlKind.Reset, [], + serving.CatalogEpoch, serving.AuthorityEpoch, diagnostic), () => Volatile.Read(ref _closed) == 0 && + _services.CanUseSubscription(_context, _target, serving), + () => { Stop(); return true; }))) Stop(); + } + + public IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken) => new DirectReader(this, cancellationToken); + private sealed class DirectReader(DataSubscriptionSession owner, CancellationToken token) : IAsyncEnumerable, IAsyncEnumerator + { + private CancellationTokenSource? _linked; + private int _disposed; + public DataSubscriptionFrame Current { get; private set; } = null!; + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + if (Interlocked.CompareExchange(ref owner._mode, 1, 0) != 0) throw new InvalidOperationException("Delivery mode already selected."); + _linked = CancellationTokenSource.CreateLinkedTokenSource(token, cancellationToken, owner._stop.Token); return this; + } + public async ValueTask MoveNextAsync() + { + try + { + while (true) + { + PendingDelivery pending; + if (Interlocked.Exchange(ref owner._coalesced, 0) != 0) pending = owner.CoalescedControl(); + else + { + if (!await owner._outbound.Reader.WaitToReadAsync(_linked!.Token).ConfigureAwait(false)) break; + if (!owner._outbound.Reader.TryRead(out pending!)) continue; + owner.Dequeued(pending); + } + if (!pending.Gate()) { pending.Dispose(); if (pending.IsObsolete()) continue; owner.Stop(); return false; } + if (!pending.IsEligible()) { pending.Dispose(); continue; } + var rate = pending.ConsumeSnapshot(); + if (!rate.Accepted) { pending.Dispose(); owner.CloseWithReset($"Snapshot pacing; retry after {rate.Retry.TotalMilliseconds:F0} ms."); continue; } + var frame = pending.Take(checked(Interlocked.Read(ref owner._sequence) + 1)); + if (frame is DataSubscriptionValues) owner.BeforeDirectCommitForTests?.Invoke(); + if (!pending.Gate() || !pending.Commit()) + { pending.Fail(); (frame as IDisposable)?.Dispose(); if (pending.IsObsolete()) continue; owner.Stop(); return false; } + if (frame is DataSubscriptionAck && + (!owner._services.CanUseSubscription(owner._context, owner._target, owner._serving) || !pending.FinalAuthority())) + { (frame as IDisposable)?.Dispose(); owner.Stop(); return false; } + Interlocked.Increment(ref owner._sequence); Current = frame; return true; + } + } + catch (OperationCanceledException) when (_linked!.IsCancellationRequested) { } + catch { owner.Stop(); throw; } + return false; + } + public ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) == 0) + { owner.Stop(); _linked?.Cancel(); _linked?.Dispose(); } + return ValueTask.CompletedTask; + } + } + + public async Task RunDeliveryAsync(IDataSubscriptionDeliverySink sink, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(sink); + if (Interlocked.CompareExchange(ref _mode, 2, 0) != 0) throw new InvalidOperationException("Delivery mode already selected."); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _stop.Token); + try + { + while (true) + { + PendingDelivery pending; + if (Interlocked.Exchange(ref _coalesced, 0) != 0) pending = CoalescedControl(); + else + { + if (!await _outbound.Reader.WaitToReadAsync(linked.Token).ConfigureAwait(false)) break; + if (!_outbound.Reader.TryRead(out pending!)) continue; + Dequeued(pending); + } + if (!pending.Gate()) { pending.Dispose(); if (pending.IsObsolete()) continue; Stop(); return; } + IDisposable? reservation; + try { reservation = await _capacity.ReserveAsync(_context.PrincipalId, _limits.MaxPendingBytes, linked.Token).ConfigureAwait(false); } + catch { pending.Dispose(); throw; } + if (reservation is null) { pending.Dispose(); CloseWithReset("Transport capacity exhausted."); continue; } + var frame = pending.Take(checked(Interlocked.Read(ref _sequence) + 1)); + IDisposable sessionHold; + try { sessionHold = _sessionLease.Retain(); } + catch { pending.Fail(); (frame as IDisposable)?.Dispose(); reservation!.Dispose(); Stop(); throw; } + var physical = DeliverAsync(sink, frame, pending, reservation!, sessionHold, linked.Token); + await physical.WaitAsync(linked.Token).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (linked.IsCancellationRequested) { } + finally { Stop(); } + } + private async Task DeliverAsync(IDataSubscriptionDeliverySink sink, DataSubscriptionFrame frame, + PendingDelivery pending, IDisposable reservation, IDisposable sessionHold, CancellationToken cancellationToken) + { + IDataPreparedSubscriptionDelivery? prepared = null; + try + { + prepared = await sink.PrepareAsync(frame, _limits.MaxPendingBytes, cancellationToken).ConfigureAwait(false); + if (prepared is null || prepared.RetainedBytes < 0 || prepared.RetainedBytes > _limits.MaxPendingBytes) + { if (!pending.IsObsolete()) Stop(); return; } + if (!pending.IsEligible()) return; + var rate = pending.ConsumeSnapshot(prepared.RetainedBytes); + if (!rate.Accepted) { CloseWithReset($"Snapshot pacing; retry after {rate.Retry.TotalMilliseconds:F0} ms."); return; } + if (!pending.Gate()) { if (!pending.IsObsolete()) Stop(); return; } + await sink.WriteAsync(prepared, cancellationToken).ConfigureAwait(false); + if (!pending.Commit()) Stop(); else Interlocked.Increment(ref _sequence); + } + catch { Stop(); } + finally + { + pending.Fail(); (frame as IDisposable)?.Dispose(); reservation.Dispose(); sessionHold.Dispose(); prepared?.Dispose(); + } + } + private void Stop() + { + if (Interlocked.Exchange(ref _closed, 1) != 0) return; + _preOpen?.Dispose(); _expiry?.Dispose(); _tick?.Dispose(); _ackTimer?.Dispose(); _commands.Writer.TryComplete(); _stop.Cancel(); + } + public async ValueTask DisposeAsync() { Stop(); await _worker.ConfigureAwait(false); } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DeliveryScheduler.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DeliveryScheduler.cs new file mode 100644 index 000000000..2358bec03 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DeliveryScheduler.cs @@ -0,0 +1,105 @@ +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +internal readonly record struct ScheduledInterest(BackingSourceKey Source, long InterestId, long Generation); + +/// Bounded source-dirty index with resumable round-robin interest slices. +internal sealed class DeliveryScheduler +{ + private readonly object _gate = new(); + private readonly int _maxSources, _maxInterests; + private readonly Dictionary _buckets = new(); + private readonly LinkedList _ready = new(); + private int _interests; + private sealed class Bucket + { + internal readonly LinkedList Interests = new(); + internal readonly Dictionary> Index = new(); + internal LinkedListNode? Cursor; + internal LinkedListNode? ReadyNode; + internal long ActiveGeneration, PendingGeneration; + internal int Remaining; + } + private sealed class Interest(long id, long lastVisited) { internal long Id = id, LastVisited = lastVisited; } + internal DeliveryScheduler(int maxSources, int maxInterests) + { + if (maxSources <= 0 || maxInterests <= 0) throw new ArgumentOutOfRangeException(nameof(maxSources)); + _maxSources = maxSources; _maxInterests = maxInterests; + } + internal bool TryRegister(BackingSourceKey source, long interestId) + { + ArgumentNullException.ThrowIfNull(source); + if (interestId <= 0) throw new ArgumentOutOfRangeException(nameof(interestId)); + lock (_gate) + { + if (_interests >= _maxInterests) return false; + if (!_buckets.TryGetValue(source, out var b)) + { + if (_buckets.Count >= _maxSources) return false; + _buckets.Add(source, b = new Bucket()); + } + if (b.Index.ContainsKey(interestId)) return false; + b.Index.Add(interestId, b.Interests.AddLast(new Interest(interestId, b.ActiveGeneration))); + _interests++; return true; + } + } + internal bool Unregister(BackingSourceKey source, long interestId) + { + lock (_gate) + { + if (!_buckets.TryGetValue(source, out var b) || !b.Index.Remove(interestId, out var node)) return false; + if (b.Cursor == node) b.Cursor = node.Next ?? b.Interests.First; + if (b.Remaining > 0 && node.Value.LastVisited != b.ActiveGeneration) b.Remaining--; + b.Interests.Remove(node); _interests--; + if (b.Interests.Count == 0) + { + if (b.ReadyNode is not null) _ready.Remove(b.ReadyNode); + _buckets.Remove(source); + } + else if (b.Cursor == node) b.Cursor = b.Interests.First; + return true; + } + } + internal bool TryMarkDirty(BackingSourceKey source, long generation) + { + ArgumentNullException.ThrowIfNull(source); + if (generation <= 0) throw new ArgumentOutOfRangeException(nameof(generation)); + lock (_gate) + { + if (!_buckets.TryGetValue(source, out var b)) return false; + if (generation > b.ActiveGeneration) b.PendingGeneration = Math.Max(generation, b.PendingGeneration); + Queue(source, b); return true; + } + } + internal IReadOnlyList TakeSlice(int maximum) + { + if (maximum <= 0) throw new ArgumentOutOfRangeException(nameof(maximum)); + lock (_gate) + { + var result = new List(Math.Min(maximum, _interests)); + while (result.Count < maximum && _ready.First is { } ready) + { + var source = ready.Value; _ready.RemoveFirst(); + if (!_buckets.TryGetValue(source, out var b)) continue; + b.ReadyNode = null; + if (b.Remaining == 0 && b.PendingGeneration > b.ActiveGeneration) + { + b.ActiveGeneration = b.PendingGeneration; b.PendingGeneration = 0; + b.Cursor = b.Interests.First; b.Remaining = b.Interests.Count; + } + if (b.Remaining > 0 && b.Cursor is { } node) + { + node.Value.LastVisited = b.ActiveGeneration; + result.Add(new(source, node.Value.Id, b.ActiveGeneration)); + b.Cursor = node.Next ?? b.Interests.First; b.Remaining--; + } + if (b.Remaining > 0 || b.PendingGeneration > b.ActiveGeneration) Queue(source, b); + } + return result; + } + } + private void Queue(BackingSourceKey source, Bucket bucket) + { + if (bucket.ReadyNode is null && (bucket.Remaining > 0 || bucket.PendingGeneration > bucket.ActiveGeneration)) + bucket.ReadyNode = _ready.AddLast(source); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DriverHostSubscriptionDemandSource.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DriverHostSubscriptionDemandSource.cs new file mode 100644 index 000000000..e0698032a --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DriverHostSubscriptionDemandSource.cs @@ -0,0 +1,430 @@ +using Akka.Actor; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Bridges independently authorized views to bounded per-driver physical demand. +internal sealed class DriverHostSubscriptionDemandSource : ISubscriptionDemandSource, IDisposable +{ + private sealed record Interest(long Id, DemandSharingKey Key, string Reference, DataSubscriptionSettings Settings, + IDisposable RegistryLease, Func CanPublish, DriverState Driver); + private sealed record Applied(string[] References, TimeSpan Interval, long Revision, long Producer, TimeSpan Nominal); + private sealed record ApplyOutcome(Applied? Applied, Task? Busy); + private sealed class DriverState(string id) + { + internal readonly string Id = id; + internal readonly SemaphoreSlim Serial = new(1, 1); + internal readonly Dictionary References = new(StringComparer.Ordinal); + internal readonly SortedDictionary Intervals = new(); + internal string[]? Snapshot; + internal int Interests; + internal long Change; + internal Applied? Applied; + internal long OwnerGeneration, KeyGeneration, LastIssuedRevision; + internal string[]? LastIssuedReferences; + internal TimeSpan LastIssuedInterval; + internal bool Scheduled; + internal bool RetryCleanupRequested; + internal Task? BusySource, BusyAdmissionWait; + internal Task? PendingOpenCleanup; + internal long PendingOpenOwner, PendingOpenKey; + internal readonly TaskCompletionSource IdleForTest = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource OpenAbortFailedForTest = new(TaskCreationOptions.RunContinuationsAsynchronously); + } + private readonly object _gate = new(); + private readonly IActorRef _host; + private readonly UpstreamDemandRegistry _registry; + private readonly int _maxDrivers, _maxInterests; + private readonly TimeSpan _timeout; + private readonly TimeSpan _abortRetryDelay; + private readonly Guid _ownerId = Guid.NewGuid(); + private readonly long _ownerSerial; + private readonly SubscriptionAcquisitionCapacity _ownership; + private Task? _ownerRegistration; + private readonly Dictionary _interests = new(); + private readonly Dictionary _drivers = new(StringComparer.Ordinal); + private long _nextId, _nextRevision, _referenceVisits; + private bool _disposed; + + internal DriverHostSubscriptionDemandSource(IActorRef host, UpstreamDemandRegistry registry, + int maxDrivers, int maxInterests, TimeSpan timeout, SubscriptionAcquisitionCapacity ownership, + TimeSpan? abortRetryDelay = null) + { + ArgumentNullException.ThrowIfNull(host); ArgumentNullException.ThrowIfNull(registry); ArgumentNullException.ThrowIfNull(ownership); + if (host is not IActorRefScope { IsLocal: true }) + throw new ArgumentException("Physical subscription demand requires a local driver host.", nameof(host)); + if (maxDrivers <= 0 || maxInterests <= 0 || timeout <= TimeSpan.Zero || abortRetryDelay < TimeSpan.Zero) + throw new ArgumentOutOfRangeException(nameof(maxDrivers)); + _host = host; _registry = registry; _maxDrivers = maxDrivers; _maxInterests = maxInterests; _timeout = timeout; + _abortRetryDelay = abortRetryDelay ?? TimeSpan.FromMilliseconds(100); + _ownership = ownership; + _ownerSerial = ownership.NextOwnerSerial(); + } + + // Counts actual reference keys visited to materialize physical desired sets. + internal long ReferenceVisitCount => Interlocked.Read(ref _referenceVisits); + internal Task WaitForDriverIdleForTest(string driver) + { + lock (_gate) return _drivers.TryGetValue(driver, out var state) ? state.IdleForTest.Task : Task.CompletedTask; + } + internal Task WaitForOpenAbortFailureForTest(string driver) + { + lock (_gate) + return _drivers.TryGetValue(driver, out var state) + ? state.OpenAbortFailedForTest.Task + : Task.FromException(new InvalidOperationException("The driver has no active Open cleanup.")); + } + + public async ValueTask AcquireAsync(SubscriptionAuthorizedView view, + DataSubscriptionSettings settings, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(view); ArgumentNullException.ThrowIfNull(settings); + cancellationToken.ThrowIfCancellationRequested(); settings.Validate(); + if (!view.CanPublish() || !SourceKey.TryDriver(view.Source, out var driver, out var reference) || + string.IsNullOrWhiteSpace(driver) || string.IsNullOrWhiteSpace(reference)) return Failed(DataItemStatus.Unavailable); + var key = new DemandSharingKey(view.Source, view.Target, view.Consistency, view.PrincipalId, view.ExportScope, + view.Serving.CatalogEpoch, view.Serving.AuthorityEpoch); + Interest interest; + lock (_gate) + { + if (_disposed || _interests.Count >= _maxInterests) + return Failed(DataItemStatus.ResourceExhausted); + if (!_drivers.ContainsKey(driver) && _drivers.Count >= _maxDrivers) + { + // Reclaim inactive logical Open aborts under pressure. Each driver has one + // coalescing worker, so one unavailable host or key does not serialize others. + foreach (var candidate in _drivers.Values) + if (candidate.Interests == 0 && candidate.PendingOpenCleanup is not null) + Schedule(candidate, retryOpenCleanup: true); + return Failed(DataItemStatus.ResourceExhausted); + } + if (!_registry.TryAdd(key, settings, out var registryLease) || registryLease is null) return Failed(DataItemStatus.ResourceExhausted); + if (!_drivers.TryGetValue(driver, out var state)) _drivers.Add(driver, state = new DriverState(driver)); + interest = new Interest(checked(++_nextId), key, reference, settings, registryLease, view.CanPublish, state); + _interests.Add(interest.Id, interest); + Add(state, interest); + } + try + { + while (true) + { + await interest.Driver.Serial.WaitAsync(cancellationToken).ConfigureAwait(false); + ApplyOutcome outcome; + try + { + lock (_gate) + if (_disposed || !_interests.ContainsKey(interest.Id) || !interest.CanPublish()) + return Reject(interest, DataItemStatus.Unavailable); + outcome = await ApplyAsync(interest.Driver, cancellationToken, retryOpenCleanup: true).ConfigureAwait(false); + } + finally { interest.Driver.Serial.Release(); } + if (outcome.Busy is { } ready) + { + if (!await SharedBusyWait(interest.Driver, ready).WaitAsync(cancellationToken).ConfigureAwait(false)) + return Reject(interest, DataItemStatus.Unavailable); + continue; + } + var applied = outcome.Applied; + if (applied is null || applied.Nominal > settings.SamplingInterval || !interest.CanPublish()) + return Reject(interest, DataItemStatus.Unavailable); + var state = _registry.GetState(key); + if (state is null || !_registry.TryAcknowledge(key, state.DesiredRevision, + state.Desired with { SamplingInterval = applied.Nominal, Deadband = null }, applied.Revision)) + return Reject(interest, DataItemStatus.Unavailable); + // Boundary is a physical demand generation, not a sample version or freshness claim. + return new(DataItemStatus.Good, settings, applied.Revision, new InterestLease(this, interest.Id)); + } + } + catch (OperationCanceledException) { Reject(interest, DataItemStatus.Unavailable); throw; } + catch (Exception) { return Reject(interest, DataItemStatus.Unavailable); } + } + + private void Add(DriverState state, Interest interest) + { + if (!state.References.TryGetValue(interest.Reference, out var refs)) { state.Snapshot = null; refs = 0; } + state.References[interest.Reference] = refs + 1; + state.Intervals[interest.Settings.SamplingInterval] = state.Intervals.GetValueOrDefault(interest.Settings.SamplingInterval) + 1; + state.Interests++; state.Change++; + } + private void Subtract(DriverState state, Interest interest) + { + var refs = state.References[interest.Reference]; + if (refs == 1) { state.References.Remove(interest.Reference); state.Snapshot = null; } + else state.References[interest.Reference] = refs - 1; + var interval = interest.Settings.SamplingInterval; + if (state.Intervals[interval] == 1) state.Intervals.Remove(interval); else state.Intervals[interval]--; + state.Interests--; state.Change++; + } + + private async Task ApplyAsync(DriverState state, CancellationToken cancellationToken, + bool retryOpenCleanup = false) + { + if (state.PendingOpenCleanup is { } cleanup) + { + if (!await cleanup.WaitAsync(cancellationToken).ConfigureAwait(false)) + { + // Abort is an idempotent owner/key-fenced control operation. Retry only when a + // new acquisition requests this driver; the driver slot remains held throughout. + if (!retryOpenCleanup) return new(null, null); + cleanup = ObserveOpenAbortForTest(RetryOpenAbortAsync(state.Id, state.PendingOpenOwner, state.PendingOpenKey), state); + state.PendingOpenCleanup = cleanup; + if (!await cleanup.WaitAsync(cancellationToken).ConfigureAwait(false)) return new(null, null); + } + state.PendingOpenCleanup = null; + state.PendingOpenOwner = 0; state.PendingOpenKey = 0; + } + string[] refs; TimeSpan interval; + lock (_gate) + { + if (state.Snapshot is null) + { + Interlocked.Add(ref _referenceVisits, state.References.Count); + state.Snapshot = state.References.Keys.Order(StringComparer.Ordinal).ToArray(); + } + refs = state.Snapshot; + interval = state.Intervals.Count == 0 ? TimeSpan.Zero : state.Intervals.First().Key; + } + if (refs.Length == 0 && state.KeyGeneration == 0) return new(null, null); + for (var attempt = 0; attempt < 2; attempt++) + { + var owner = await GetOwnerAsync(cancellationToken).ConfigureAwait(false); + if (owner <= 0) return new(null, null); + if (state.OwnerGeneration != owner) { state.OwnerGeneration = owner; state.KeyGeneration = 0; state.Applied = null; } + if (state.KeyGeneration == 0) + { + if (refs.Length == 0) return new(null, null); + var proposedKey = _ownership.NextControlGeneration(); + var opening = _host.Ask( + new DriverHostActor.OpenAcquisitionDemand(state.Id, owner, proposedKey), _timeout); + DriverHostActor.AcquisitionDemandOpened opened; + try + { + opened = await opening.WaitAsync(cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + ObserveAbandonedOpen(opening); + state.PendingOpenOwner = owner; state.PendingOpenKey = proposedKey; + state.PendingOpenCleanup = ObserveOpenAbortForTest(AbortOpenAsync(state.Id, owner, proposedKey), state); + throw; + } + catch (Exception) + { + ObserveAbandonedOpen(opening); + state.PendingOpenOwner = owner; state.PendingOpenKey = proposedKey; + state.PendingOpenCleanup = ObserveOpenAbortForTest(AbortOpenAsync(state.Id, owner, proposedKey), state); + return new(null, null); + } + if (opened.OwnerInvalid) + { + InvalidateOwner(owner); + state.OwnerGeneration = 0; state.KeyGeneration = 0; state.Applied = null; + continue; + } + if (opened.StaleGeneration) continue; + if (!opened.Succeeded || opened.KeyGeneration != proposedKey) return new(null, null); + state.KeyGeneration = opened.KeyGeneration; + state.LastIssuedRevision = 0; state.LastIssuedReferences = null; + } + long revision; + lock (_gate) + { + revision = state.LastIssuedRevision != 0 && ReferenceEquals(state.LastIssuedReferences, refs) && state.LastIssuedInterval == interval + ? state.LastIssuedRevision : checked(++_nextRevision); + // Record issued state before dispatch, even when cancellation hides its eventual ACK. + state.LastIssuedRevision = revision; state.LastIssuedReferences = refs; state.LastIssuedInterval = interval; + } + DriverInstanceActor.AcquisitionDemandApplied result; + try + { + result = await _host.Ask( + new DriverHostActor.ApplyAcquisitionDemand(state.Id, refs, interval, revision, owner, state.KeyGeneration), + _timeout, cancellationToken).ConfigureAwait(false); + } + catch (Exception) when (!cancellationToken.IsCancellationRequested) { return new(null, null); } + if (result.OwnerInvalid) + { + InvalidateOwner(owner); + state.OwnerGeneration = 0; state.KeyGeneration = 0; state.Applied = null; + continue; + } + if (result.KeyInvalid) + { + state.KeyGeneration = 0; state.Applied = null; + continue; + } + if (refs.Length == 0) + { + if (!result.Succeeded || result.DesiredRevision != revision) return new(null, null); + state.KeyGeneration = 0; state.Applied = null; state.LastIssuedRevision = 0; state.LastIssuedReferences = null; + return new(null, null); + } + if (result.Busy && !result.Succeeded && result.DesiredRevision == revision && + result.ProducerIncarnation > 0 && result.RetryWhenReady is not null) + return new(null, result.RetryWhenReady); + if (!result.Succeeded || result.DesiredRevision != revision || result.ProducerIncarnation <= 0 || result.NominalSamplingInterval <= TimeSpan.Zero) + return new(null, null); + var applied = new Applied(refs, interval, revision, result.ProducerIncarnation, result.NominalSamplingInterval); + lock (_gate) state.Applied = applied; + return new(applied, null); + } + return new(null, null); + } + + private Task GetOwnerAsync(CancellationToken cancellationToken) + { + Task registration; + lock (_gate) + { + if (_ownerRegistration is { IsCompletedSuccessfully: true } previous && previous.Result == 0) + _ownerRegistration = null; + registration = _ownerRegistration ??= RegisterOwnerAsync(); + } + return registration.WaitAsync(cancellationToken); + } + + private static void ObserveAbandonedOpen(Task opening) + { + _ = opening.ContinueWith(static task => { _ = task.Exception; }, CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + + private static async Task ObserveOpenAbortForTest(Task attempt, DriverState state) + { + var completed = await attempt.ConfigureAwait(false); + if (!completed) state.OpenAbortFailedForTest.TrySetResult(); + return completed; + } + + private async Task AbortOpenAsync(string driver, long owner, long key) + { + try + { + var result = await _host.Ask( + new DriverHostActor.AbortOpenAcquisitionDemand(driver, owner, key), _timeout).ConfigureAwait(false); + if (result.OwnerInvalid) { InvalidateOwner(owner); return true; } + return result.Succeeded; + } + catch (Exception) { return false; } + } + + private async Task RetryOpenAbortAsync(string driver, long owner, long key) + { + if (_abortRetryDelay > TimeSpan.Zero) await Task.Delay(_abortRetryDelay).ConfigureAwait(false); + return await AbortOpenAsync(driver, owner, key).ConfigureAwait(false); + } + private async Task RegisterOwnerAsync() + { + try + { + var result = await _host.Ask( + new DriverHostActor.RegisterAcquisitionOwner(_ownerId, _ownerSerial), _timeout).ConfigureAwait(false); + return result.Succeeded && result.Generation > 0 ? result.Generation : 0; + } + catch (Exception) { return 0; } + } + private void InvalidateOwner(long generation) + { + lock (_gate) + if (_ownerRegistration is { IsCompletedSuccessfully: true } task && task.Result == generation) + _ownerRegistration = null; + } + + private static SubscriptionDemandResult Failed(DataItemStatus status) => new(status, null, 0, null); + private Task SharedBusyWait(DriverState state, Task ready) + { + lock (_gate) + { + if (!ReferenceEquals(state.BusySource, ready)) + { + state.BusySource = ready; + state.BusyAdmissionWait = AwaitBusyAsync(ready); + } + return state.BusyAdmissionWait!; + } + } + private async Task AwaitBusyAsync(Task ready) + { + try { return await ready.WaitAsync(_timeout).ConfigureAwait(false); } + catch (Exception) { return false; } + } + private SubscriptionDemandResult Reject(Interest interest, DataItemStatus status) { Remove(interest.Id); return Failed(status); } + private sealed class InterestLease(DriverHostSubscriptionDemandSource owner, long id) : IDisposable + { + private DriverHostSubscriptionDemandSource? _owner = owner; + public void Dispose() => Interlocked.Exchange(ref _owner, null)?.Remove(id); + } + private void Remove(long id) + { + lock (_gate) + { + if (!_interests.Remove(id, out var interest)) return; + interest.RegistryLease.Dispose(); Subtract(interest.Driver, interest); + Schedule(interest.Driver); + } + } + // One coalescing reconciliation or cleanup waiter per charged driver; no per-update task. + private void Schedule(DriverState state, bool retryOpenCleanup = false) + { + if (retryOpenCleanup) state.RetryCleanupRequested = true; + if (state.Scheduled) return; + state.Scheduled = true; + _ = Task.Run(() => ReconcileAsync(state)); + } + private async Task ReconcileAsync(DriverState state) + { + while (true) + { + long version; + bool retryOpenCleanup; + lock (_gate) + { + version = state.Change; + retryOpenCleanup = state.RetryCleanupRequested; + state.RetryCleanupRequested = false; + } + ApplyOutcome? outcome = null; + await state.Serial.WaitAsync().ConfigureAwait(false); + try { outcome = await ApplyAsync(state, CancellationToken.None, retryOpenCleanup).ConfigureAwait(false); } + catch (Exception) { } + finally { state.Serial.Release(); } + if (outcome?.Busy is { } ready) + { + _ = WaitForReadyAsync(state, ready); + return; + } + lock (_gate) + { + if (state.Change != version || state.RetryCleanupRequested) continue; + state.Scheduled = false; + if (state.Interests == 0 && state.Applied is null && state.KeyGeneration == 0 && state.PendingOpenCleanup is null) + { + _drivers.Remove(state.Id); + state.IdleForTest.TrySetResult(); + } + return; + } + } + } + private async Task WaitForReadyAsync(DriverState state, Task ready) + { + try + { + if (await ready.ConfigureAwait(false)) await ReconcileAsync(state).ConfigureAwait(false); + // A failed/uncertain cleanup leaves the key charged and is never replayed. + } + catch (Exception) { } + } + public void Dispose() + { + lock (_gate) + { + if (_disposed) return; + _disposed = true; + foreach (var interest in _interests.Values) { interest.RegistryLease.Dispose(); Subtract(interest.Driver, interest); } + _interests.Clear(); + foreach (var state in _drivers.Values) Schedule(state); + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs index 4c98bcd52..fc8599010 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs @@ -15,16 +15,16 @@ public sealed class LocalDataConnection : IDataConnection, IDataConnectionPublic public bool CanPublish(ServingIdentity expectedServing) => Volatile.Read(ref _disposed) == 0 && _services.CanPublish(_context, expectedServing); private void Check() => ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) - { Check(); return _services.GetCapabilitiesAsync(_context, budget, cancellationToken); } + { Check(); return _services.GetCapabilitiesAsync(_context, Target, budget, cancellationToken); } public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) - { Check(); return _services.BrowseAsync(_context, request, cancellationToken); } + { Check(); return _services.BrowseAsync(_context, Target, request, cancellationToken); } public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) - { Check(); return _services.GetMetadataAsync(_context, request, cancellationToken); } + { Check(); return _services.GetMetadataAsync(_context, Target, request, cancellationToken); } public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) { Check(); return _services.ReadAsync(_context, request, cancellationToken); } public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) { Check(); return _services.WriteAsync(_context, request, cancellationToken); } public Task SubscribeAsync(CancellationToken cancellationToken) - { Check(); return _services.SubscribeAsync(_context, cancellationToken); } + { Check(); return _services.SubscribeAsync(_context, Target, cancellationToken); } public ValueTask DisposeAsync() { Interlocked.Exchange(ref _disposed, 1); return ValueTask.CompletedTask; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs index 5af31e9a9..4033df2e0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs @@ -17,6 +17,7 @@ public sealed class LocalDataServices : IDataConnectionFactory private readonly DataCapabilitiesProvider _capabilities; private readonly Func? _writes; private readonly Func? _subscriptions; + private readonly Func? _targetSubscriptions; private readonly byte[] _continuationKey = RandomNumberGenerator.GetBytes(32); private readonly ConditionalWeakTable _callers = new(); private sealed record Continuation(DataView Parent, string? Filter, int Offset, string Principal, @@ -25,7 +26,8 @@ public sealed class LocalDataServices : IDataConnectionFactory public LocalDataServices(Func catalog, PartitionedSampleHub hub, DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock, Func? writes = null, - Func? subscriptions = null) + Func? subscriptions = null, + Func? targetSubscriptions = null) { _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); _hub = hub ?? throw new ArgumentNullException(nameof(hub)); @@ -35,12 +37,14 @@ public sealed class LocalDataServices : IDataConnectionFactory if (!ReferenceEquals(hub.Clock, clock)) throw new ArgumentException("Hub and facade must use one clock.", nameof(clock)); _writes = writes; _subscriptions = subscriptions; + _targetSubscriptions = targetSubscriptions; } public TimeProvider Clock { get; } - private DataOperations Implemented => DataOperations.Browse | DataOperations.Metadata | DataOperations.Read + private DataOperations Implemented(DataTarget target) => DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | (_writes is null ? DataOperations.None : DataOperations.Write) - | (_subscriptions is null ? DataOperations.None : DataOperations.Subscribe); + | (_targetSubscriptions is not null || _subscriptions is not null && target.Mode == DataTargetMode.Node + ? DataOperations.Subscribe : DataOperations.None); private DataCallerIdentity Caller(DataAuthenticatedContext context) => _callers.GetValue(context, static value => new(value.PrincipalId, value.ApiKeyId, value.CredentialVersion, value.CredentialExpiresUtc)); @@ -93,6 +97,62 @@ public sealed class LocalDataServices : IDataConnectionFactory return allowed && Ready(catalog); } + internal DataItemStatus AuthorizeSubscription(DataAuthenticatedContext context, DataTarget target, DataView view, + out SubscriptionAuthorizedView? authorized) + { + authorized = null; + view.Validate(); target.Validate(); + var catalog = _catalog(); + if (catalog is null || !Ready(catalog)) return DataItemStatus.Unavailable; + if (context.AuthorityEpoch != catalog.AuthorityEpoch) return DataItemStatus.Denied; + if (!string.Equals(target.ExpectedClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase) || + target.Mode == DataTargetMode.Node && !string.Equals(target.ExpectedNodeId, catalog.Serving.NodeId, StringComparison.OrdinalIgnoreCase)) + return DataItemStatus.Unavailable; + if (!_policy.IsCallerUsable(Caller(context))) return DataItemStatus.Denied; + if (!catalog.TryResolve(view, out var node)) return catalog.ContainsAddress(view) ? DataItemStatus.Denied : DataItemStatus.NotFound; + if (!Allowed(catalog, context, node, DataOperations.Subscribe)) return DataItemStatus.Denied; + var source = node.Source; + if (!node.Supported || source is null) return DataItemStatus.Unsupported; + if (!node.SourceEnabled) return DataItemStatus.Unavailable; + var serving = catalog.Serving; + var consistency = string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) + ? DataConsistency.Primary : DataConsistency.ReadyReplica; + authorized = new(node.Metadata.View, source, serving, node.Metadata, context.PrincipalId, + catalog.SubscriptionExportScope(context.PrincipalId, node), target, consistency, () => + { + var current = _catalog(); + return current is not null && current.Serving == serving && current.TryResolve(view, out var now) && + now.Source == source && Allowed(current, context, now, DataOperations.Subscribe); + }); + return DataItemStatus.Good; + } + + internal PartitionedSampleHub SubscriptionHub => _hub; + internal DataLimits SubscriptionLimits => _capabilities.Limits; + internal int SubscriptionItemLimit(DataAuthenticatedContext context) + { + var catalog = _catalog(); + return catalog is null ? 0 : Limits(catalog, context).MaxMonitoredItems; + } + internal int SubscriptionStreamLimit(DataAuthenticatedContext context) + { + var catalog = _catalog(); + return catalog is null ? 0 : Limits(catalog, context).MaxStreams; + } + internal bool CanUseSubscription(DataAuthenticatedContext context, DataTarget target, ServingIdentity? expected = null) + { + var catalog = _catalog(); + return catalog is not null && Ready(catalog) && context.AuthorityEpoch == catalog.AuthorityEpoch && + (expected is null || catalog.Serving == expected) && _policy.IsCallerUsable(Caller(context)) && + string.Equals(target.ExpectedClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase) && + (target.Mode != DataTargetMode.Node || string.Equals(target.ExpectedNodeId, catalog.Serving.NodeId, StringComparison.OrdinalIgnoreCase)); + } + internal ServingIdentity? SubscriptionServing(DataAuthenticatedContext context, DataTarget target) + { + var catalog = _catalog(); + return catalog is not null && CanUseSubscription(context, target, catalog.Serving) ? catalog.Serving : null; + } + private DataLimits Limits(LocalExportCatalog catalog, DataAuthenticatedContext context) => catalog.LimitsFor(context.PrincipalId, _capabilities.Limits); private void CheckBudget(DataBudget budget, int count, int limit, CancellationToken cancellationToken) @@ -103,31 +163,31 @@ public sealed class LocalDataServices : IDataConnectionFactory throw new ArgumentOutOfRangeException(nameof(count), "Request exceeds the admitted item/byte budget."); } private bool Expired(long start, DataBudget budget) => Clock.GetElapsedTime(start) >= budget.Timeout; - private DataMetadata Metadata(LocalExportCatalog catalog, DataAuthenticatedContext context, LocalDataNode node) + private DataMetadata Metadata(LocalExportCatalog catalog, DataAuthenticatedContext context, DataTarget target, LocalDataNode node) { var operations = DataOperations.None; foreach (var operation in new[] { DataOperations.Browse, DataOperations.Metadata, DataOperations.Read, DataOperations.Write, DataOperations.Subscribe }) if ((node.Supported || operation == DataOperations.Browse) && (node.SourceEnabled || operation is DataOperations.Browse or DataOperations.Metadata) - && (Implemented & operation) != 0 && (node.Metadata.AllowedOperations & operation) != 0 + && (Implemented(target) & operation) != 0 && (node.Metadata.AllowedOperations & operation) != 0 && (operation != DataOperations.Write || node.Metadata.Writable && string.Equals(_capabilities.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) && Allowed(catalog, context, node, operation)) operations |= operation; return node.Metadata with { AllowedOperations = operations, Writable = node.Metadata.Writable && operations.HasFlag(DataOperations.Write) }; } - internal Task GetCapabilitiesAsync(DataAuthenticatedContext context, DataBudget budget, CancellationToken cancellationToken) + internal Task GetCapabilitiesAsync(DataAuthenticatedContext context, DataTarget target, DataBudget budget, CancellationToken cancellationToken) { CheckBudget(budget, 0, 0, cancellationToken); var catalog = _catalog(); if (!_policy.IsCallerUsable(Caller(context))) throw new UnauthorizedAccessException(); - var capabilities = _capabilities.Get(catalog is null ? DataOperations.None : catalog.ExportOperations(context.PrincipalId) & Implemented, + var capabilities = _capabilities.Get(catalog is null ? DataOperations.None : catalog.ExportOperations(context.PrincipalId) & Implemented(target), catalog is null ? _capabilities.Limits : Limits(catalog, context)); if (catalog is null || !Ready(catalog)) capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None }; return Task.FromResult(capabilities); } - internal Task>> GetMetadataAsync(DataAuthenticatedContext context, MetadataRequest request, CancellationToken cancellationToken) + internal Task>> GetMetadataAsync(DataAuthenticatedContext context, DataTarget target, MetadataRequest request, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Views); var catalog = _catalog(); @@ -152,7 +212,7 @@ public sealed class LocalDataServices : IDataConnectionFactory else if (!node.Supported) status = DataItemStatus.Unsupported; else { - metadata = Metadata(catalog, context, node); + metadata = Metadata(catalog, context, target, node); bytes = checked(bytes + MetadataBytes(metadata)); if (bytes > Math.Min(request.Budget.MaxBytes, _capabilities.Limits.MaxMessageBytes)) { status = DataItemStatus.LimitExceeded; metadata = null; } @@ -207,7 +267,7 @@ public sealed class LocalDataServices : IDataConnectionFactory { read.Dispose(); results.Add(Empty(DataItemStatus.LimitExceeded)); continue; } var age = Clock.GetElapsedTime(read.ReceivedTimestamp); if (age < TimeSpan.Zero) { read.Dispose(); results.Add(Empty(DataItemStatus.Unavailable)); continue; } - // Catalog/authority headers describe current serving. Acquisition age, value version + // Catalog/authority headers describe current serving. Cache ingress age, value version // and original timestamps remain unchanged, including provisional boot acquisitions. var exposed = sample with { Value = sample.Value.Retain(), Serving = catalog.Serving }; exposed.Validate(); @@ -217,7 +277,7 @@ public sealed class LocalDataServices : IDataConnectionFactory var publication = new PublicationReadLease(read, () => CanPublish(context, exposed.Serving) && !Expired(start, request.Budget)); results.Add(new(item.CorrelationId, item.MaximumAge is { } max && age > max ? DataItemStatus.Stale : DataItemStatus.Good, - DataReadiness.Ready, age, exposed, null, publication)); + DataReadiness.Ready, age, exposed, null, publication, new DataAgeBounds(age, age))); } if (!Ready(catalog) || !_policy.IsCallerUsable(Caller(context))) for (var i = 0; i < results.Count; i++) @@ -228,7 +288,7 @@ public sealed class LocalDataServices : IDataConnectionFactory catch { foreach (var result in results) result.Dispose(); throw; } } - internal Task BrowseAsync(DataAuthenticatedContext context, BrowseRequest request, CancellationToken cancellationToken) + internal Task BrowseAsync(DataAuthenticatedContext context, DataTarget target, BrowseRequest request, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); request.Parent.Validate(); var catalog = _catalog(); @@ -263,7 +323,7 @@ public sealed class LocalDataServices : IDataConnectionFactory var child = children[offset++]; if ((request.Filter is { Length: > 0 } filter && !child.Metadata.BrowseName.Contains(filter, StringComparison.Ordinal)) || !Allowed(catalog, context, child, DataOperations.Browse)) continue; - var metadata = Metadata(catalog, context, child); + var metadata = Metadata(catalog, context, target, child); var size = MetadataBytes(metadata); if (bytes + size > Math.Min(request.Budget.MaxBytes, limits.MaxMessageBytes)) { @@ -307,13 +367,14 @@ public sealed class LocalDataServices : IDataConnectionFactory return results; } - internal Task SubscribeAsync(DataAuthenticatedContext context, CancellationToken cancellationToken) + internal Task SubscribeAsync(DataAuthenticatedContext context, DataTarget target, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var catalog = _catalog(); - if (_subscriptions is null || catalog is null || !Ready(catalog) || !_policy.IsCallerUsable(Caller(context))) + if ((_targetSubscriptions is null && (_subscriptions is null || target.Mode != DataTargetMode.Node)) || + catalog is null || !Ready(catalog) || !_policy.IsCallerUsable(Caller(context))) throw new InvalidOperationException("Subscriptions are unavailable."); - return _subscriptions(context).SubscribeAsync(cancellationToken); + return (_targetSubscriptions?.Invoke(context, target) ?? _subscriptions!(context)).SubscribeAsync(cancellationToken); } private static bool ValueMatches(DataMetadata metadata, DataValue value) => value.Kind == DataValueKind.Null || metadata.ValueKind == value.Kind diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs index 62de6615b..e0eab3592 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs @@ -17,7 +17,7 @@ public sealed partial class LocalExportCatalog private readonly Dictionary _children; private readonly ExportRule[] _exports; private readonly IDataMappedCatalogAuthority _activation; - private sealed record ExportRule(string Principal, DataRealm Realm, DataView? Root, bool WholeRealm, + private sealed record ExportRule(string Identity, string Principal, DataRealm Realm, DataView? Root, bool WholeRealm, DataOperations Operations, int Batch, int Page, int Items, int Streams); public LocalExportCatalog(string clusterId, ServingIdentity serving, IDataMappedCatalogAuthority activation, @@ -88,7 +88,7 @@ public sealed partial class LocalExportCatalog || export.AllowedOperations == DataOperations.None || export.MaxBatchItems <= 0 || export.MaxPageItems <= 0 || export.MaxMonitoredItems <= 0 || export.MaxStreams <= 0) throw new ArgumentException("Export has no valid origin root or policy.", nameof(exports)); - rules.Add(new(export.PrincipalId, export.Realm, wholeRealm ? null : roots[0].Metadata.View, wholeRealm, + rules.Add(new(export.DataExportId, export.PrincipalId, export.Realm, wholeRealm ? null : roots[0].Metadata.View, wholeRealm, export.AllowedOperations, export.MaxBatchItems, export.MaxPageItems, export.MaxMonitoredItems, export.MaxStreams)); } _exports = rules.ToArray(); @@ -147,6 +147,18 @@ public sealed partial class LocalExportCatalog return false; } + internal string SubscriptionExportScope(string principal, LocalDataNode node) + { + var ids = _exports.Where(rule => string.Equals(principal, rule.Principal, StringComparison.OrdinalIgnoreCase) && + rule.Realm == node.Metadata.View.Realm && (rule.Operations & DataOperations.Subscribe) != 0 && + (rule.WholeRealm || IsAncestor(rule.Root!, node.Metadata.View))) + .Select(rule => rule.Identity).Order(StringComparer.Ordinal).ToArray(); + // Invalid/missing export identities must not accidentally share across views. + if (ids.Length == 0 || ids.Any(string.IsNullOrWhiteSpace)) + return $"view:{node.Metadata.View.Realm}:{node.Metadata.View.Address.NamespaceUri.Length}:{node.Metadata.View.Address.NamespaceUri}:{node.Metadata.View.Address.IdentifierKind.Length}:{node.Metadata.View.Address.IdentifierKind}:{node.Metadata.View.Address.Identifier.Length}:{node.Metadata.View.Address.Identifier}"; + return string.Concat(ids.Select(id => $"{id.Length}:{id}")); + } + private bool IsAncestor(DataView ancestor, DataView candidate) { var current = candidate; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalSubscriptionService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalSubscriptionService.cs new file mode 100644 index 000000000..35913c6ef --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalSubscriptionService.cs @@ -0,0 +1,62 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// An independently authorized view and its current publication fence. +internal sealed record SubscriptionAuthorizedView(DataView View, BackingSourceKey Source, ServingIdentity Serving, + DataMetadata Metadata, string PrincipalId, string ExportScope, DataTarget Target, DataConsistency Consistency, + Func CanPublish); + +/// Physical upstream establishment, independently of the downstream stream. +internal interface ISubscriptionDemandSource +{ + ValueTask AcquireAsync(SubscriptionAuthorizedView view, + DataSubscriptionSettings settings, CancellationToken cancellationToken); +} +internal sealed record SubscriptionDemandResult(DataItemStatus Status, DataSubscriptionSettings? RevisedSettings, + long Boundary, IDisposable? Lease); + +internal sealed record SubscriptionSessionLimits(int MaxCommands, int MaxPendingFrames, long MaxPendingBytes, + TimeSpan MaxSessionLifetime, TimeSpan? PreOpenTimeout = null) +{ + internal void Validate() + { + if (MaxCommands <= 0 || MaxPendingFrames <= 0 || MaxPendingBytes <= 0 || MaxSessionLifetime <= TimeSpan.Zero || + PreOpenTimeout is { } timeout && (timeout <= TimeSpan.Zero || timeout > TimeSpan.FromMilliseconds(uint.MaxValue - 1))) + throw new ArgumentOutOfRangeException(nameof(MaxCommands)); + } +} + +/// Caller-bound subscription service; authorization is resolved through the same local facade. +internal sealed class LocalSubscriptionService : IDataSubscriptionService +{ + private readonly LocalDataServices _services; + private readonly DataAuthenticatedContext _context; + private readonly DataTarget _target; + private readonly ISubscriptionDemandSource _demand; + private readonly SubscriptionSessionLimits _limits; + private readonly SubscriptionTransportCapacity _capacity; + internal LocalSubscriptionService(LocalDataServices services, DataAuthenticatedContext context, DataTarget target, + ISubscriptionDemandSource demand, SubscriptionSessionLimits limits, SubscriptionTransportCapacity capacity) + { + _services = services; _context = context; _target = target; _demand = demand; _limits = limits; _capacity = capacity; + ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(demand); ArgumentNullException.ThrowIfNull(limits); ArgumentNullException.ThrowIfNull(capacity); + context.Validate(); target.Validate(); limits.Validate(); + } + public Task SubscribeAsync(CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!_services.CanUseSubscription(_context, _target)) throw new InvalidOperationException("Subscription authority is unavailable."); + var fixedBytes = checked(4096L + 128L * _limits.MaxCommands + 256L * _limits.MaxPendingFrames); + var streamLimit = _services.SubscriptionStreamLimit(_context); + if (streamLimit <= 0 || !_capacity.TryOpenSession(_context.PrincipalId, fixedBytes, streamLimit, out var reservation)) + throw new InvalidOperationException("Subscription stream capacity exhausted."); + try + { + return Task.FromResult(new DataSubscriptionSession(_services, _context, _target, + _demand, _limits, _capacity, reservation!, cancellationToken)); + } + catch { reservation!.Dispose(); throw; } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionControlSignal.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionControlSignal.cs new file mode 100644 index 000000000..cb6885efb --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionControlSignal.cs @@ -0,0 +1,45 @@ +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +// Active controls bracket each generation change. Overflow poisons the signal +// permanently, rather than allowing a wrapped generation to match a snapshot. +internal sealed class PartitionControlSignal +{ + private long _generation; + private long _active; + private int _poisoned; + // Only the outer signal owns this additional lifecycle counter; its child is a leaf. + internal PartitionControlSignal Quiet { get; } = null!; + internal PartitionControlSignal() : this(true) { } + private PartitionControlSignal(bool includeQuiet) + { + if (includeQuiet) Quiet = new PartitionControlSignal(false); + } + + internal void BeginQuiet() { Begin(); Quiet.Begin(); } + internal void EndQuiet() { Quiet.End(); End(); } + + internal void Begin() + { + if (Volatile.Read(ref _poisoned) != 0) return; + if (Interlocked.Increment(ref _active) <= 0) { Interlocked.Exchange(ref _poisoned, 1); return; } + if (Interlocked.Increment(ref _generation) < 0) Interlocked.Exchange(ref _poisoned, 1); + } + internal void End() + { + if (Volatile.Read(ref _poisoned) != 0) return; + if (Interlocked.Increment(ref _generation) < 0) { Interlocked.Exchange(ref _poisoned, 1); return; } + if (Interlocked.Decrement(ref _active) < 0) Interlocked.Exchange(ref _poisoned, 1); + } + internal bool TryCapture(out long stamp) + { + stamp = -1; + if (Volatile.Read(ref _poisoned) != 0 || Volatile.Read(ref _active) != 0) return false; + var generation = Volatile.Read(ref _generation); + if (generation < 0 || Volatile.Read(ref _active) != 0 || Volatile.Read(ref _poisoned) != 0) return false; + stamp = generation; + return true; + } + internal bool Matches(long stamp) => stamp >= 0 && Volatile.Read(ref _poisoned) == 0 && + Volatile.Read(ref _active) == 0 && Volatile.Read(ref _generation) == stamp && + Volatile.Read(ref _active) == 0 && Volatile.Read(ref _poisoned) == 0; +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs index ae4806dca..c0e80d4d3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs @@ -9,9 +9,23 @@ public sealed record BackingSourceKey(string OriginClusterId, string SourceKind, public readonly record struct SourceGeneration(long Incarnation, long Lifecycle); internal sealed class SourceBindingFence { - private int _retired; - internal bool IsRetired => Volatile.Read(ref _retired) != 0; - internal void Retire() => Interlocked.Exchange(ref _retired, 1); + private int _state; + private PartitionControlSignal? _signal; + internal bool IsRetired => Volatile.Read(ref _state) == 2; + internal bool TryAttach(PartitionControlSignal signal) + { + if (Volatile.Read(ref _state) != 0) return false; + var old = Interlocked.CompareExchange(ref _signal, signal, null); + return (old is null || ReferenceEquals(old, signal)) && Volatile.Read(ref _state) == 0; + } + internal void Retire() + { + if (Interlocked.CompareExchange(ref _state, 1, 0) == 2 || Volatile.Read(ref _state) == 2) return; + var signal = Volatile.Read(ref _signal); + signal?.BeginQuiet(); + Interlocked.Exchange(ref _state, 2); + signal?.EndQuiet(); + } } /// An individual binding; two bindings of the same key and generation remain distinct. public readonly record struct SourceTicket(BackingSourceKey Key, SourceGeneration Generation) @@ -22,15 +36,45 @@ public readonly record struct SourceTicket(BackingSourceKey Key, SourceGeneratio /// Shared producer lifetime; retirement immediately fences every source bound to this token. public sealed class ProducerFence { - private int _retired; + private sealed record Attachments(PartitionedSampleHub Owner, long Epoch, PartitionControlSignal[] Signals); + private int _state; + private Attachments? _attachments; public ProducerFence(long incarnation) { if (incarnation <= 0) throw new ArgumentOutOfRangeException(nameof(incarnation)); Incarnation = incarnation; } public long Incarnation { get; } - public bool IsRetired => Volatile.Read(ref _retired) != 0; - public void Retire() => Interlocked.Exchange(ref _retired, 1); + public bool IsRetired => Volatile.Read(ref _state) == 2; + internal Action? BeforeRetirementPublicationForTests { get; set; } + internal Action? AfterSignalBegunForTests { get; set; } + internal int AttachedSignalCountForTests => Volatile.Read(ref _attachments)?.Signals.Length ?? 0; + internal bool TryAttach(PartitionedSampleHub owner, long epoch, PartitionControlSignal signal) + { + // Bounded retries keep producer admission from spinning indefinitely under churn. + for (var attempt = 0; attempt < 32; attempt++) + { + if (Volatile.Read(ref _state) != 0) return false; + var old = Volatile.Read(ref _attachments); + if (old is not null && (!ReferenceEquals(old.Owner, owner) || epoch < old.Epoch)) return false; + if (old is not null && old.Epoch == epoch && Array.IndexOf(old.Signals, signal) >= 0) + return Volatile.Read(ref _state) == 0; + PartitionControlSignal[] signals = old is null || old.Epoch != epoch ? [signal] : old.Signals.Append(signal).ToArray(); + var next = new Attachments(owner, epoch, signals); + if (Interlocked.CompareExchange(ref _attachments, next, old) == old) + return Volatile.Read(ref _state) == 0; + } + return false; + } + public void Retire() + { + if (Interlocked.CompareExchange(ref _state, 1, 0) == 2 || Volatile.Read(ref _state) == 2) return; + var signals = Volatile.Read(ref _attachments)?.Signals; + if (signals is not null) foreach (var signal in signals) { signal.BeginQuiet(); AfterSignalBegunForTests?.Invoke(); } + BeforeRetirementPublicationForTests?.Invoke(); + Interlocked.Exchange(ref _state, 2); + if (signals is not null) foreach (var signal in signals) signal.EndQuiet(); + } } public interface IIngressReservation : IDisposable @@ -102,9 +146,16 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable private readonly bool _autoDrain; private readonly object _routingLock = new(); private readonly ConcurrentDictionary _snapshots = new(); + private readonly ConcurrentDictionary _interests = new(); private SamplePartition[] _partitions; private int _trackedSources; private int _snapshotItems; + private int _interestItems; + private long _snapshotValidationWork; + internal Action? BeforeReadForTests { get; set; } + internal Action? BeforeSnapshotValidationForTests { get; set; } + internal long SnapshotValidationWorkForTests => Interlocked.Read(ref _snapshotValidationWork); + internal void CountSnapshotValidationForTests() => Interlocked.Increment(ref _snapshotValidationWork); private long _routingEpoch = 1; private int _disposed; @@ -135,6 +186,17 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable internal bool TryTrackSnapshotItems(int count) { while (true) { var current = Volatile.Read(ref _snapshotItems); if (count > _limits.MaxSnapshotItems - current) return false; if (Interlocked.CompareExchange(ref _snapshotItems, current + count, current) == current) return true; } } internal void UntrackSnapshotItems(int count) => Interlocked.Add(ref _snapshotItems, -count); internal void ForgetSnapshot(SnapshotLease snapshot) => _snapshots.TryRemove(snapshot, out _); + internal void ForgetInterest(SourceInterestLease interest) => _interests.TryRemove(interest, out _); + internal void UntrackInterestItems(int count) => Interlocked.Add(ref _interestItems, -count); + private bool TryTrackInterestItems(int count) + { + while (true) + { + var current = Volatile.Read(ref _interestItems); + if (count > _limits.MaxSnapshotItems - current) return false; + if (Interlocked.CompareExchange(ref _interestItems, current + count, current) == current) return true; + } + } internal void Schedule(SamplePartition partition) { if (_autoDrain) partition.Schedule(); } private static bool ValidKey(BackingSourceKey? key) => key is not null && @@ -155,30 +217,37 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable public bool TryPublishStatus(SourceTicket ticket, long sequence, uint statusCode, DateTimeOffset? sourceTimestampUtc, DateTimeOffset? serverTimestampUtc) => !IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).TryStatus(ticket, sequence, statusCode, sourceTimestampUtc, serverTimestampUtc); public bool TryRemove(SourceTicket ticket, long sequence) => !IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).TryRemove(ticket, sequence); - public CachedSourceRead Read(SourceTicket ticket) => IsDisposed || !ValidKey(ticket.Key) ? EmptyRead(DataItemStatus.Unavailable, DataReadiness.Unavailable, 0) : Partition(ticket.Key).Read(ticket); + public CachedSourceRead Read(SourceTicket ticket) + { + BeforeReadForTests?.Invoke(ticket); + return IsDisposed || !ValidKey(ticket.Key) ? EmptyRead(DataItemStatus.Unavailable, DataReadiness.Unavailable, 0) : Partition(ticket.Key).Read(ticket); + } internal CachedSourceRead EmptyRead(DataItemStatus status, DataReadiness readiness, long epoch) => new(Resources, status, readiness, null, 0, epoch, 0, 0); internal void ProcessPending() { foreach (var partition in Volatile.Read(ref _partitions)) partition.Drain(); } internal void WithPartitionLockForTest(BackingSourceKey key, Action action) => Partition(key).WithLockForTest(action); + internal PartitionControlSignal ControlSignalForTests(BackingSourceKey key) => Partition(key).Control; public bool TryCaptureSnapshot(IReadOnlyList tickets, DataBudget budget, CancellationToken cancellationToken, out SnapshotLease? snapshot) { snapshot = null; ArgumentNullException.ThrowIfNull(tickets); ArgumentNullException.ThrowIfNull(budget); budget.Validate(); if (IsDisposed || cancellationToken.IsCancellationRequested || tickets.Count == 0 || tickets.Count > budget.MaxItems || tickets.Count > _limits.MaxSnapshotItems || tickets.Any(t => !ValidKey(t.Key)) || tickets.Distinct().Count() != tickets.Count || !TryTrackSnapshotItems(tickets.Count)) return false; - var routing = RoutingEpoch; var items = new Dictionary(); var watermarks = new Dictionary(); var epochs = new Dictionary(); + var routing = RoutingEpoch; var items = new Dictionary(); var watermarks = new Dictionary(); var epochs = new Dictionary(); var controls = new Dictionary(); long charge = 0; try { var partitions = Volatile.Read(ref _partitions); foreach (var group in tickets.GroupBy(t => GetPartitionFor(t.Key, partitions.Length))) { - if (cancellationToken.IsCancellationRequested || routing != RoutingEpoch || + if (cancellationToken.IsCancellationRequested || routing != RoutingEpoch || partitions[group.Key].RoutingEpoch != routing || !partitions[group.Key].Control.TryCapture(out var control) || !partitions[group.Key].Capture(group, items, out var watermark, out var epoch, ref charge, Math.Min(budget.MaxBytes, _limits.MaxSnapshotBytes))) return false; + if (!partitions[group.Key].Control.Matches(control)) return false; watermarks.Add(group.Key, watermark); epochs.Add(group.Key, epoch); + controls.Add(group.Key, control); } if (cancellationToken.IsCancellationRequested || routing != RoutingEpoch) return false; - snapshot = new SnapshotLease(this, items, watermarks, epochs, partitions, routing, charge, tickets.Count, + snapshot = new SnapshotLease(this, items, watermarks, epochs, controls, partitions, routing, charge, tickets.Count, budget.Timeout < _limits.MaxSnapshotLifetime ? budget.Timeout : _limits.MaxSnapshotLifetime, cancellationToken); charge = 0; items = null!; _snapshots.TryAdd(snapshot, 0); @@ -191,14 +260,79 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable } } + /// Atomically retains interests and captures a watermark within each source partition. + public bool TryCaptureInterestSnapshot(IReadOnlyList tickets, DataBudget budget, + CancellationToken cancellationToken, out SnapshotLease? snapshot, out SourceInterestLease? interest) + => TryCaptureInterestSnapshotCore(tickets, budget, cancellationToken, out snapshot, out interest, null); + + internal bool TryCaptureInterestSnapshot(IReadOnlyList tickets, DataBudget budget, + CancellationToken cancellationToken, out SnapshotLease? snapshot, out SourceInterestLease? interest, + SnapshotAdmissionScheduler.Permit admission) + => TryCaptureInterestSnapshotCore(tickets, budget, cancellationToken, out snapshot, out interest, admission); + + private bool TryCaptureInterestSnapshotCore(IReadOnlyList tickets, DataBudget budget, + CancellationToken cancellationToken, out SnapshotLease? snapshot, out SourceInterestLease? interest, + SnapshotAdmissionScheduler.Permit? admission) + { + snapshot = null; interest = null; + ArgumentNullException.ThrowIfNull(tickets); ArgumentNullException.ThrowIfNull(budget); budget.Validate(); + if (IsDisposed || cancellationToken.IsCancellationRequested || tickets.Count == 0 || tickets.Count > budget.MaxItems || + tickets.Count > _limits.MaxSnapshotItems || tickets.Any(t => !ValidKey(t.Key)) || + tickets.Select(t => t.Key).Distinct().Count() != tickets.Count || !TryTrackSnapshotItems(tickets.Count)) return false; + if (!TryTrackInterestItems(tickets.Count)) { UntrackSnapshotItems(tickets.Count); return false; } + var routing = RoutingEpoch; + var items = new Dictionary(); + var watermarks = new Dictionary(); + var epochs = new Dictionary(); + var controls = new Dictionary(); + var quietControls = new Dictionary(); + var owners = new Dictionary(); + long snapshotCharge = 0, interestCharge = 0; + try + { + var partitions = Volatile.Read(ref _partitions); + foreach (var group in tickets.GroupBy(t => GetPartitionFor(t.Key, partitions.Length))) + { + var captured = new Dictionary(); + long watermark = 0, epoch = 0, control = 0, quietControl = 0; + var ok = !cancellationToken.IsCancellationRequested && routing == RoutingEpoch && partitions[group.Key].RoutingEpoch == routing && partitions[group.Key].Control.TryCapture(out control) && + partitions[group.Key].Control.Quiet.TryCapture(out quietControl) && + partitions[group.Key].CaptureAndRegister(group.ToArray(), items, captured, out watermark, + out epoch, ref snapshotCharge, ref interestCharge, Math.Min(budget.MaxBytes, _limits.MaxSnapshotBytes), admission); + foreach (var pair in captured) owners.Add(pair.Key, (partitions[group.Key], pair.Value)); + if (!ok || !partitions[group.Key].Control.Matches(control) || !partitions[group.Key].Control.Quiet.Matches(quietControl)) return false; + watermarks.Add(group.Key, watermark); epochs.Add(group.Key, epoch); + controls.Add(group.Key, control); + quietControls.Add(group.Key, quietControl); + } + if (cancellationToken.IsCancellationRequested || routing != RoutingEpoch) return false; + snapshot = new SnapshotLease(this, items, watermarks, epochs, controls, partitions, routing, snapshotCharge, tickets.Count, + budget.Timeout < _limits.MaxSnapshotLifetime ? budget.Timeout : _limits.MaxSnapshotLifetime, cancellationToken); + snapshotCharge = 0; items = null!; _snapshots.TryAdd(snapshot, 0); + interest = new SourceInterestLease(this, owners, watermarks, epochs, quietControls, routing, interestCharge, cancellationToken); + interestCharge = 0; owners = null!; _interests.TryAdd(interest, 0); + if (!snapshot.IsReset && !interest.IsReset) return true; + snapshot.Dispose(); ForgetSnapshot(snapshot); interest.Dispose(); snapshot = null; interest = null; return false; + } + finally + { + if (items is not null) + { foreach (var item in items.Values) { item.Sample?.Dispose(); item.ReleaseSource(); } Resources.Release(snapshotCharge); UntrackSnapshotItems(tickets.Count); } + if (owners is not null) + { foreach (var owner in owners.Values) owner.Partition.ReleaseInterest(owner.Source); Resources.Release(interestCharge); UntrackInterestItems(tickets.Count); } + } + } + public void Repartition(int count) { - if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count)); + if (count <= 0 || count > DataResourceLimits.MaxPartitionCount) throw new ArgumentOutOfRangeException(nameof(count)); lock (_routingLock) { if (IsDisposed) throw new ObjectDisposedException(nameof(PartitionedSampleHub)); + if (RoutingEpoch == long.MaxValue) throw new InvalidOperationException("The routing epoch is exhausted."); Interlocked.Increment(ref _routingEpoch); var old = Volatile.Read(ref _partitions); + foreach (var interest in _interests.Keys) interest.Dispose(); foreach (var snapshot in _snapshots.Keys) snapshot.Dispose(); foreach (var partition in old) partition.Dispose(); // Retire all old binding tokens before exposing new owners; otherwise an old @@ -211,7 +345,8 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable lock (_routingLock) { if (Interlocked.Exchange(ref _disposed, 1) != 0) return; - Interlocked.Increment(ref _routingEpoch); + if (RoutingEpoch != long.MaxValue) Interlocked.Increment(ref _routingEpoch); + foreach (var interest in _interests.Keys) interest.Dispose(); foreach (var snapshot in _snapshots.Keys) snapshot.Dispose(); foreach (var partition in _partitions) partition.Dispose(); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs index 61e1420db..d86545d48 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs @@ -8,13 +8,14 @@ internal sealed class SamplePartition : IDisposable { private const long SourceOverhead = 768; private const long ControlOverhead = 256; - private const long ChangeOverhead = 192; + private const long ChangeOverhead = 256; private readonly PartitionedSampleHub _hub; private readonly object _gate = new(); private readonly ConcurrentDictionary _sources = new(); private readonly Queue _queue = new(); private readonly Dictionary _dirty = new(); - private readonly Queue<(long Version, BackingSourceKey Key)> _changes = new(); + private readonly LinkedList<(long Version, BackingSourceKey Key)> _changes = new(); + private readonly Dictionary> _changeIndex = new(); private long _epoch = 1; private long _cleanedEpoch = 1; private long _watermark; @@ -28,8 +29,10 @@ internal sealed class SamplePartition : IDisposable private bool _disposed; private readonly long _routingEpoch; + internal readonly PartitionControlSignal Control = new(); internal SamplePartition(PartitionedSampleHub hub, int id) { _hub = hub; Id = id; _routingEpoch = hub.RoutingEpoch; } internal int Id { get; } + internal long RoutingEpoch => _routingEpoch; internal long Epoch { get { lock (_gate) return _epoch; } } private static bool Valid(SourceTicket ticket) @@ -57,7 +60,8 @@ internal sealed class SamplePartition : IDisposable } try { - if (_disposed || ticket.Binding.IsRetired) return false; + if (_disposed || _hub.RoutingEpoch != _routingEpoch || ticket.Binding.IsRetired || + !ticket.Binding.TryAttach(Control) || (fence is not null && !fence.TryAttach(_hub, _routingEpoch, Control))) return false; if (_sources.TryGetValue(ticket.Key, out var state)) { var order = Compare(ticket.Generation, state.Generation); @@ -101,11 +105,13 @@ internal sealed class SamplePartition : IDisposable } internal bool IsTicketCurrentNonBlocking(SourceTicket ticket) { + if (_hub.IsDisposed || Volatile.Read(ref _disposed) || _hub.RoutingEpoch != _routingEpoch) return false; if (!_sources.TryGetValue(ticket.Key, out var state)) return false; var gate = Volatile.Read(ref state.Gate); var fence = Volatile.Read(ref state.Fence); return gate.Generation == ticket.Generation && ReferenceEquals(gate.Binding, ticket.Binding) && !gate.Binding.IsRetired && Volatile.Read(ref gate.Retired) == 0 && - fence?.IsRetired != true && ReferenceEquals(gate, Volatile.Read(ref state.Gate)); + fence?.IsRetired != true && ReferenceEquals(gate, Volatile.Read(ref state.Gate)) && + !Volatile.Read(ref _disposed) && !_hub.IsDisposed && _hub.RoutingEpoch == _routingEpoch; } internal void WithLockForTest(Action action) { lock (_gate) action(); } private bool Current(SourceTicket ticket, out SourceState state) @@ -130,14 +136,19 @@ internal sealed class SamplePartition : IDisposable if (!_sources.TryGetValue(ticket.Key, out var state)) return; var gate = Volatile.Read(ref state.Gate); if (gate.Generation != ticket.Generation || !ReferenceEquals(gate.Binding, ticket.Binding)) return; - if (retired) + Control.BeginQuiet(); + try { - gate.Binding.Retire(); - Interlocked.Exchange(ref gate.Retired, 1); - Interlocked.Exchange(ref _retiredSweepRequested, 1); - _hub.Schedule(this); + if (retired) + { + gate.Binding.Retire(); + Interlocked.Exchange(ref gate.Retired, 1); + Interlocked.Exchange(ref _retiredSweepRequested, 1); + _hub.Schedule(this); + } + Interlocked.Increment(ref gate.Invalidated); } - Interlocked.Increment(ref gate.Invalidated); + finally { Control.EndQuiet(); } } internal bool TryReserve(SourceTicket ticket, long estimated, out IIngressReservation? reservation) @@ -155,12 +166,13 @@ internal sealed class SamplePartition : IDisposable Interlocked.Increment(ref state.Reservations); Interlocked.Increment(ref state.MetadataOwners); reservation = new Reservation(this, state, ticket, estimated, estimated + PartitionedSampleHub.SampleOverhead, - state.InvalidationVersion, _epoch); + state.InvalidationVersion, _epoch, _hub.Clock.GetTimestamp()); return true; } finally { Monitor.Exit(_gate); } } - private bool Commit(SourceState reservedState, SourceTicket ticket, long estimate, long charge, long invalidationVersion, long partitionEpoch, DataSample sample, long sequence) + private bool Commit(SourceState reservedState, SourceTicket ticket, long estimate, long charge, long invalidationVersion, + long partitionEpoch, long receivedTimestamp, DataSample sample, long sequence) { if (!Monitor.TryEnter(_gate)) { ReleaseReservation(reservedState); _hub.Resources.Release(charge); Signal(ticket); return false; } @@ -180,7 +192,7 @@ internal sealed class SamplePartition : IDisposable } catch (Exception e) when (e is ArgumentException or ObjectDisposedException or OverflowException) { _hub.Resources.Release(charge); InvalidateSource(state); return false; } - var pending = new Pending(ticket, sequence, ++_ordinal, sample, charge, _hub.Clock.GetTimestamp()) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch }; + var pending = new Pending(ticket, sequence, ++_ordinal, sample, charge, receivedTimestamp) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch }; if (_queuedValues < _hub.Limits.MaxIngressItemsPerPartition) { _queue.Enqueue(pending); _queuedValues++; } else if (_dirty.TryGetValue(ticket.Key, out var previous)) @@ -202,7 +214,12 @@ internal sealed class SamplePartition : IDisposable } private void Abandon(SourceState state, long charge) { ReleaseReservation(state); _hub.Resources.Release(charge); } internal void Invalidate(SourceTicket ticket) => Signal(ticket); - private void InvalidateSource(SourceState state) { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); ReleaseCache(state); } + private void InvalidateSource(SourceState state) + { + Control.BeginQuiet(); + try { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); ReleaseCache(state); } + finally { Control.EndQuiet(); } + } internal bool TryStatus(SourceTicket ticket, long sequence, uint status, DateTimeOffset? source, DateTimeOffset? server) { @@ -213,7 +230,9 @@ internal sealed class SamplePartition : IDisposable if (_disposed || !Current(ticket, out var state) || sequence <= state.LastSubmitted) return false; if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead)) { InvalidatePartition(); return false; } var wasReady = state.Readiness == DataReadiness.Ready; - state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); state.Barrier = sequence; state.LastSubmitted = sequence; + Control.Begin(); + try { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); state.Barrier = sequence; state.LastSubmitted = sequence; } + finally { Control.End(); } _queue.Enqueue(new Pending(ticket, sequence, ++_ordinal, status, source, server, wasReady, ControlOverhead) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch }); _queuedControls++; _hub.Schedule(this); return true; } @@ -228,9 +247,14 @@ internal sealed class SamplePartition : IDisposable if (_disposed || !_sources.TryGetValue(ticket.Key, out var state)) return false; ApplyGate(state); ApplyPartitionEpoch(state); if (state.Removed || state.Ticket != ticket || Volatile.Read(ref state.Gate.Retired) != 0 || sequence <= state.LastSubmitted) return false; - if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead)) - { state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); RequestReclaim(); InvalidatePartition(); return false; } - state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); state.LastSubmitted = sequence; ReleaseCache(state); + Control.BeginQuiet(); + try + { + if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead)) + { state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); RequestReclaim(); InvalidatePartition(); return false; } + state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); state.LastSubmitted = sequence; ReleaseCache(state); + } + finally { Control.EndQuiet(); } RequestReclaim(); _queue.Enqueue(new Pending(ticket, sequence, ++_ordinal, ControlOverhead) { PartitionEpoch = _epoch }); _queuedControls++; _hub.Schedule(this); return true; @@ -298,13 +322,15 @@ internal sealed class SamplePartition : IDisposable { _watermark++; if (_changes.Count == _hub.Limits.MaxSnapshotCatchUpItems) - { _changes.Dequeue(); _hub.Resources.Release(ChangeOverhead); } + { _changeIndex.Remove(_changes.First!.Value.Version); _changes.RemoveFirst(); _hub.Resources.Release(ChangeOverhead); } if (!_hub.Resources.TryReserve(ChangeOverhead)) { InvalidatePartition(); return; } - _changes.Enqueue((_watermark, key)); + _changeIndex.Add(_watermark, _changes.AddLast((_watermark, key))); } internal void InvalidatePartition() { - Interlocked.Increment(ref _epoch); + Control.BeginQuiet(); + try { Interlocked.Increment(ref _epoch); } + finally { Control.EndQuiet(); } _hub.Schedule(this); } private void ApplyPartitionEpoch(SourceState state) @@ -318,7 +344,8 @@ internal sealed class SamplePartition : IDisposable var epoch = Interlocked.Read(ref _epoch); if (_cleanedEpoch == epoch) return; foreach (var pair in _sources) ApplyPartitionEpoch(pair.Value); - while (_changes.TryDequeue(out _)) _hub.Resources.Release(ChangeOverhead); + while (_changes.First is not null) { _changes.RemoveFirst(); _hub.Resources.Release(ChangeOverhead); } + _changeIndex.Clear(); _cleanedEpoch = epoch; } private void CleanupRetiredSources() @@ -398,7 +425,8 @@ internal sealed class SamplePartition : IDisposable Volatile.Read(ref gate.Invalidated) == sourceSignal && Volatile.Read(ref state.InvalidationVersion) == sourceVersion && Volatile.Read(ref state.Fence)?.IsRetired != true; } - internal bool Capture(IEnumerable tickets, Dictionary items, out long watermark, out long epoch, ref long charge, long limit) + internal bool Capture(IEnumerable tickets, Dictionary items, out long watermark, out long epoch, + ref long charge, long limit, SnapshotAdmissionScheduler.Permit? admission = null) { lock (_gate) { @@ -407,15 +435,60 @@ internal sealed class SamplePartition : IDisposable foreach (var ticket in tickets) { var exists = Current(ticket, out var state); + if (!exists) return false; var ready = exists && state.Readiness == DataReadiness.Ready && state.Sample is not null; var bytes = PartitionedSampleHub.ReferenceOverhead + (ready ? state.Sample!.Value.EstimatedRetainedBytes : 0); - if (bytes > limit - charge || !_hub.Resources.TryReserve(bytes)) return false; + if (bytes > limit - charge || admission is not null && !admission.TryGrow(bytes) || !_hub.Resources.TryReserve(bytes)) return false; charge += bytes; var sample = ready ? state.Sample! with { Value = state.Sample.Value.Retain() } : null; if (exists) { Interlocked.Increment(ref state.Snapshots); Interlocked.Increment(ref state.MetadataOwners); } items.Add(ticket, new SnapshotItem(exists ? state.Readiness : DataReadiness.Unavailable, exists ? (ready ? DataItemStatus.Good : DataItemStatus.Unavailable) : DataItemStatus.NotFound, sample, - exists ? state.InvalidationVersion : -1) { Owner = exists ? this : null, Source = exists ? state : null }); + exists ? state.InvalidationVersion : -1, ready ? state.Received : null) + { Owner = exists ? this : null, Source = exists ? state : null }); + } + return true; + } + } + internal bool CaptureAndRegister(IReadOnlyList tickets, Dictionary items, + Dictionary interests, out long watermark, out long epoch, + ref long snapshotCharge, ref long interestCharge, long limit, SnapshotAdmissionScheduler.Permit? admission) + { + lock (_gate) + { + if (!Capture(tickets, items, out watermark, out epoch, ref snapshotCharge, limit, admission)) return false; + foreach (var ticket in tickets) + { + if (!Current(ticket, out var state) || interestCharge > limit - snapshotCharge - PartitionedSampleHub.ReferenceOverhead || + admission is not null && !admission.TryGrow(PartitionedSampleHub.ReferenceOverhead) || + !_hub.Resources.TryReserve(PartitionedSampleHub.ReferenceOverhead)) return false; + interestCharge += PartitionedSampleHub.ReferenceOverhead; + Interlocked.Increment(ref state.MetadataOwners); + interests.Add(ticket, state); + } + return true; + } + } + internal void ReleaseInterest(object source) => ReleaseMetadataOwner((SourceState)source); + + internal bool ReadInterestChanges(long epoch, ref long position, IReadOnlyDictionary tickets, + int maximum, List changes, out int scanned) + { + scanned = 0; + lock (_gate) + { + if (_disposed || epoch != _epoch) return false; + if (position == _watermark) return true; + if (!_changeIndex.TryGetValue(position + 1, out var node)) return false; + while (node is not null && scanned < maximum) + { + var change = node.Value; position = change.Version; scanned++; + if (tickets.TryGetValue(change.Key, out var ticket)) + { + if (!Current(ticket, out _)) return false; + changes.Add(new(ticket, change.Version)); + } + node = node.Next; } return true; } @@ -427,14 +500,21 @@ internal sealed class SamplePartition : IDisposable ReleaseMetadataOwner(state); if (lastSnapshot && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim(); } - internal bool IsSnapshotCurrent(long epoch, long watermark, IEnumerable> tickets) + internal bool IsSnapshotCurrent(long epoch, long watermark, long control) { + if (!Control.Matches(control)) return false; lock (_gate) { - if (_disposed || epoch != _epoch || (_changes.Count > 0 && watermark < _changes.Peek().Version - 1)) return false; - return tickets.All(t => Current(t.Key, out var state) && state.InvalidationVersion == t.Value.InvalidationVersion); + if (_disposed || epoch != _epoch || (_changes.Count > 0 && watermark < _changes.First!.Value.Version - 1)) return false; + return Control.Matches(control); } } + internal bool IsSnapshotItemCurrent(SourceTicket ticket, SnapshotItem item, long control) + { + if (!Control.Matches(control)) return false; + lock (_gate) + return !_disposed && Current(ticket, out var state) && state.InvalidationVersion == item.InvalidationVersion && Control.Matches(control); + } internal long CurrentWatermark { get { lock (_gate) return _watermark; } } public void Dispose() @@ -476,11 +556,11 @@ internal sealed class SamplePartition : IDisposable public bool IsControl; public bool IsStatus; public uint Status; public DateTimeOffset? SourceTimestamp; public DateTimeOffset? ServerTimestamp; public bool WasReady; } private sealed class Reservation(SamplePartition partition, SourceState state, SourceTicket ticket, long estimate, long charge, - long invalidationVersion, long partitionEpoch) : IIngressReservation + long invalidationVersion, long partitionEpoch, long receivedTimestamp) : IIngressReservation { private int _completed; public bool TryCommit(DataSample owned, long sequence) - { ArgumentNullException.ThrowIfNull(owned); return Interlocked.Exchange(ref _completed, 1) == 0 && partition.Commit(state, ticket, estimate, charge, invalidationVersion, partitionEpoch, owned, sequence); } + { ArgumentNullException.ThrowIfNull(owned); return Interlocked.Exchange(ref _completed, 1) == 0 && partition.Commit(state, ticket, estimate, charge, invalidationVersion, partitionEpoch, receivedTimestamp, owned, sequence); } public void Dispose() { if (Interlocked.Exchange(ref _completed, 1) == 0) partition.Abandon(state, charge); } } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SnapshotAdmissionScheduler.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SnapshotAdmissionScheduler.cs new file mode 100644 index 000000000..52a5319c7 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SnapshotAdmissionScheduler.cs @@ -0,0 +1,162 @@ +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Node-wide and per-principal snapshot slots, bytes, lifetime and send-rate limits. +internal sealed class SnapshotAdmissionScheduler +{ + private readonly object _gate = new(); + private readonly int _maxConcurrent, _maxPerPrincipal, _maxPrincipals; + private readonly long _maxBytes, _maxPrincipalBytes, _globalRate, _principalRate; + private readonly TimeSpan _lifetime; + private readonly TimeProvider _clock; + private readonly Dictionary _principals = new(StringComparer.OrdinalIgnoreCase); + private int _count; + private long _bytes, _windowStart, _windowBytes; + private sealed class Principal(long now) + { + internal int Count; + internal long Bytes, WindowStart = now, WindowBytes; + } + internal sealed class Permit : IDisposable + { + private readonly SnapshotAdmissionScheduler _owner; + private readonly object _state = new(); + internal readonly string Principal; + internal long Bytes; + private ITimer? _timer; + private int _references = 1, _expired; + private sealed class Hold(Permit permit) : IDisposable + { + private Permit? _permit = permit; + public void Dispose() => Interlocked.Exchange(ref _permit, null)?.ReleaseHold(); + } + internal Permit(SnapshotAdmissionScheduler owner, string principal, long bytes, TimeSpan lifetime) + { + _owner = owner; Principal = principal; Bytes = bytes; + _timer = owner._clock.CreateTimer(static state => ((Permit)state!).Dispose(), this, lifetime, Timeout.InfiniteTimeSpan); + } + internal bool IsValid => Volatile.Read(ref _expired) == 0; + internal bool TryRetain(out IDisposable? hold) + { + hold = null; + lock (_state) + { + if (_expired != 0) return false; + _references = checked(_references + 1); hold = new Hold(this); return true; + } + } + internal bool TryGrow(long bytes) + { + if (bytes <= 0) throw new ArgumentOutOfRangeException(nameof(bytes)); + return IsValid && _owner.Grow(this, bytes); + } + internal bool OwnedBy(SnapshotAdmissionScheduler owner) => ReferenceEquals(_owner, owner) && IsValid; + public void Dispose() + { + var release = false; + lock (_state) + { + if (_expired != 0) return; + Volatile.Write(ref _expired, 1); + release = --_references == 0; + } + _timer?.Dispose(); + if (release) _owner.Release(this); + } + private void ReleaseHold() + { + var release = false; + lock (_state) release = --_references == 0; + if (release) _owner.Release(this); + } + } + internal SnapshotAdmissionScheduler(int maxConcurrent, int maxPerPrincipal, long maxBytes, + long? maxPrincipalBytes = null, long globalBytesPerSecond = long.MaxValue, + long principalBytesPerSecond = long.MaxValue, TimeSpan? maxLifetime = null, TimeProvider? clock = null) + { + if (maxConcurrent <= 0 || maxPerPrincipal <= 0 || maxBytes <= 0 || maxPrincipalBytes is <= 0 || + globalBytesPerSecond <= 0 || principalBytesPerSecond <= 0 || maxLifetime is { } lifetime && lifetime <= TimeSpan.Zero) + throw new ArgumentOutOfRangeException(nameof(maxConcurrent)); + _maxConcurrent = maxConcurrent; _maxPerPrincipal = maxPerPrincipal; _maxBytes = maxBytes; + _maxPrincipalBytes = maxPrincipalBytes ?? maxBytes; + _globalRate = globalBytesPerSecond; _principalRate = principalBytesPerSecond; + _lifetime = maxLifetime ?? TimeSpan.FromSeconds(30); _clock = clock ?? TimeProvider.System; + _maxPrincipals = checked(maxConcurrent * 16); _windowStart = _clock.GetTimestamp(); + } + internal bool TryAcquire(string principal, long bytes, out IDisposable? lease) => TryAcquire(principal, bytes, out lease, out _); + internal bool TryAcquire(string principal, long bytes, out IDisposable? lease, out TimeSpan retryAfter) + { + ArgumentException.ThrowIfNullOrWhiteSpace(principal); + if (bytes <= 0) throw new ArgumentOutOfRangeException(nameof(bytes)); + lease = null; retryAfter = Jitter(principal); + lock (_gate) + { + var now = _clock.GetTimestamp(); + if (!TryPrincipal(principal, now, out var state)) return false; + if (_count >= _maxConcurrent || state.Count >= _maxPerPrincipal || bytes > _maxBytes - _bytes || + bytes > _maxPrincipalBytes - state.Bytes) + { + if (state.Count == 0 && state.WindowBytes == 0) _principals.Remove(principal); + return false; + } + state.Count++; state.Bytes += bytes; _count++; _bytes += bytes; + try { lease = new Permit(this, principal, bytes, _lifetime); return true; } + catch { state.Count--; state.Bytes -= bytes; _count--; _bytes -= bytes; throw; } + } + } + /// Charges actual snapshot bytes immediately before the delivery handoff; no waiting queue. + internal bool TryConsume(string principal, long bytes, out TimeSpan retryAfter) + { + ArgumentException.ThrowIfNullOrWhiteSpace(principal); + if (bytes < 0) throw new ArgumentOutOfRangeException(nameof(bytes)); + retryAfter = Jitter(principal); + lock (_gate) + { + var now = _clock.GetTimestamp(); + if (!TryPrincipal(principal, now, out var state)) return false; + if (_clock.GetElapsedTime(_windowStart, now) >= TimeSpan.FromSeconds(1)) { _windowStart = now; _windowBytes = 0; } + if (_clock.GetElapsedTime(state.WindowStart, now) >= TimeSpan.FromSeconds(1)) { state.WindowStart = now; state.WindowBytes = 0; } + var globalExceeded = bytes > _globalRate - _windowBytes; + var principalExceeded = bytes > _principalRate - state.WindowBytes; + if (globalExceeded || principalExceeded) + { + var globalRemaining = globalExceeded ? TimeSpan.FromSeconds(1) - _clock.GetElapsedTime(_windowStart, now) : TimeSpan.Zero; + var principalRemaining = principalExceeded ? TimeSpan.FromSeconds(1) - _clock.GetElapsedTime(state.WindowStart, now) : TimeSpan.Zero; + var remaining = globalRemaining > principalRemaining ? globalRemaining : principalRemaining; + if (remaining > TimeSpan.Zero) retryAfter += remaining; + return false; + } + _windowBytes += bytes; state.WindowBytes += bytes; return true; + } + } + private bool TryPrincipal(string principal, long now, out Principal state) + { + if (_principals.TryGetValue(principal, out state!)) return true; + if (_principals.Count >= _maxPrincipals) + { + var expired = _principals.FirstOrDefault(pair => pair.Value.Count == 0 && + _clock.GetElapsedTime(pair.Value.WindowStart, now) >= TimeSpan.FromSeconds(1)); + if (expired.Key is null) return false; + _principals.Remove(expired.Key); + } + state = new Principal(now); _principals.Add(principal, state); return true; + } + private static TimeSpan Jitter(string principal) => TimeSpan.FromMilliseconds(50 + + (unchecked((uint)StringComparer.OrdinalIgnoreCase.GetHashCode(principal)) % 101)); + private bool Grow(Permit permit, long bytes) + { + lock (_gate) + { + if (!permit.OwnedBy(this) || !_principals.TryGetValue(permit.Principal, out var state) || + bytes > _maxBytes - _bytes || bytes > _maxPrincipalBytes - state.Bytes) return false; + state.Bytes += bytes; _bytes += bytes; permit.Bytes += bytes; return true; + } + } + private void Release(Permit permit) + { + lock (_gate) + { + var state = _principals[permit.Principal]; state.Count--; state.Bytes -= permit.Bytes; _count--; _bytes -= permit.Bytes; + if (state.Count == 0 && (_principalRate == long.MaxValue || state.WindowBytes == 0)) _principals.Remove(permit.Principal); + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SnapshotLease.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SnapshotLease.cs index e24d8d2ab..4837c52cd 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SnapshotLease.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SnapshotLease.cs @@ -4,7 +4,8 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// Frozen item state. Its sample belongs to the containing snapshot. -public sealed record SnapshotItem(DataReadiness Readiness, DataItemStatus Status, DataSample? Sample, long InvalidationVersion) +public sealed record SnapshotItem(DataReadiness Readiness, DataItemStatus Status, DataSample? Sample, long InvalidationVersion, + long? ReceivedTimestamp = null) { internal SamplePartition? Owner { get; init; } internal object? Source { get; init; } @@ -14,12 +15,29 @@ public sealed record SnapshotItem(DataReadiness Readiness, DataItemStatus Status /// Retained immutable snapshots and per-partition catch-up watermarks. public sealed class SnapshotLease : IDisposable { + private sealed class PartitionCursor(SamplePartition partition, long epoch, long control, long watermark, int count) + { + internal readonly SamplePartition Partition = partition; + internal readonly long Epoch = epoch, Control = control; + private readonly SortedDictionary _positions = new() { [watermark] = count }; + private long _minimum = watermark; + internal long Minimum => _minimum; + internal void Advance(long oldPosition, long newPosition) + { + if (oldPosition == newPosition) return; + var removed = --_positions[oldPosition] == 0; + if (removed) _positions.Remove(oldPosition); + _positions.TryGetValue(newPosition, out var count); + _positions[newPosition] = count + 1; + if (removed && oldPosition == _minimum) _minimum = _positions.First().Key; + } + } private readonly PartitionedSampleHub _hub; private readonly SamplePartition[] _partitions; private readonly long _routingEpoch; private readonly long _charge; private readonly int _itemCount; - private readonly Dictionary _epochs; + private readonly Dictionary _cursors; private readonly Dictionary _owners; private readonly Dictionary _positions; private readonly Dictionary _versions; @@ -29,14 +47,15 @@ public sealed class SnapshotLease : IDisposable private int _released; internal SnapshotLease(PartitionedSampleHub hub, Dictionary items, - Dictionary watermarks, Dictionary epochs, SamplePartition[] partitions, + Dictionary watermarks, Dictionary epochs, Dictionary controls, SamplePartition[] partitions, long routingEpoch, long charge, int itemCount, TimeSpan lifetime, CancellationToken cancellationToken) { _hub = hub; _partitions = partitions; _routingEpoch = routingEpoch; _charge = charge; _itemCount = itemCount; - _epochs = epochs; Items = new ReadOnlyDictionary(items); Watermarks = new ReadOnlyDictionary(watermarks); _owners = items.Keys.ToDictionary(t => t, t => PartitionedSampleHub.GetPartitionFor(t.Key, partitions.Length)); + _cursors = _owners.Values.GroupBy(i => i).ToDictionary(g => g.Key, + g => new PartitionCursor(partitions[g.Key], epochs[g.Key], controls[g.Key], watermarks[g.Key], g.Count())); _positions = items.Keys.ToDictionary(t => t, t => watermarks[_owners[t]]); _versions = items.ToDictionary(p => p.Key, p => p.Value.Sample?.Version ?? 0); _timer = hub.Clock.CreateTimer(static o => ((SnapshotLease)o!).Dispose(), this, lifetime, Timeout.InfiniteTimeSpan); @@ -52,15 +71,29 @@ public sealed class SnapshotLease : IDisposable { if (_released != 0) return true; if (_hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) { Release(); return true; } - foreach (var group in Items.GroupBy(p => _owners[p.Key])) + foreach (var cursor in _cursors.Values) { - var watermark = group.Min(p => _positions[p.Key]); - if (!_partitions[group.Key].IsSnapshotCurrent(_epochs[group.Key], watermark, group)) { Release(); return true; } + _hub.BeforeSnapshotValidationForTests?.Invoke(); + _hub.CountSnapshotValidationForTests(); + if (!cursor.Partition.IsSnapshotCurrent(cursor.Epoch, cursor.Minimum, cursor.Control)) { Release(); return true; } } + if (_hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) { Release(); return true; } return false; } } } + /// Validates the captured source and read fence immediately before its value is handed off. + internal bool IsItemCurrent(SourceTicket ticket) + { + lock (_gate) + { + if (IsReset || !_owners.TryGetValue(ticket, out var owner) || !Items.TryGetValue(ticket, out var item)) return false; + var cursor = _cursors[owner]; + if (!cursor.Partition.IsSnapshotItemCurrent(ticket, item, cursor.Control) || + _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) { Release(); return false; } + return true; + } + } /// Returns the latest newer sample as an independently disposable, globally charged read. public bool TryReadDelta(SourceTicket ticket, out CachedSourceRead? delta) { @@ -75,6 +108,7 @@ public sealed class SnapshotLease : IDisposable var version = read.Sample.Version; if (version <= _versions[ticket]) { read.Dispose(); return false; } _versions[ticket] = version; + _cursors[owner].Advance(_positions[ticket], readWatermark); _positions[ticket] = readWatermark; delta = read; return true; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceInterestLease.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceInterestLease.cs new file mode 100644 index 000000000..ce1e46caf --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceInterestLease.cs @@ -0,0 +1,98 @@ +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// A dirty source generation, distinct from an individual delivered sample version. +public readonly record struct SourceInterestChange(SourceTicket Ticket, long Generation); + +/// Retains source metadata after the finite snapshot payload has been released. +public sealed class SourceInterestLease : IDisposable +{ + private sealed class Cursor(SamplePartition partition, long position, long epoch, long quietControl, + Dictionary tickets) + { + internal readonly SamplePartition Partition = partition; + internal long Position = position; + internal readonly long Epoch = epoch; + internal readonly long QuietControl = quietControl; + internal readonly Dictionary Tickets = tickets; + } + private readonly object _gate = new(); + private readonly PartitionedSampleHub _hub; + private readonly Dictionary _owners; + private Cursor[] _cursors; + private readonly long _routingEpoch; + private long _charge; + private CancellationTokenRegistration _cancellation; + private int _released, _next; + + internal SourceInterestLease(PartitionedSampleHub hub, + Dictionary owners, + IReadOnlyDictionary watermarks, IReadOnlyDictionary epochs, IReadOnlyDictionary quietControls, + long routingEpoch, long charge, CancellationToken cancellationToken) + { + _hub = hub; _owners = owners; _routingEpoch = routingEpoch; _charge = charge; + _cursors = owners.GroupBy(x => x.Value.Partition.Id).Select(group => new Cursor(group.First().Value.Partition, + watermarks[group.Key], epochs[group.Key], quietControls[group.Key], group.ToDictionary(x => x.Key.Key, x => x.Key))).ToArray(); + _cancellation = cancellationToken.Register(static state => ((SourceInterestLease)state!).Dispose(), this); + } + internal bool ReleaseTicket(SourceTicket ticket) + { + lock (_gate) + { + if (_released != 0 || !_owners.Remove(ticket, out var owner)) return false; + foreach (var cursor in _cursors) cursor.Tickets.Remove(ticket.Key); + _cursors = _cursors.Where(cursor => cursor.Tickets.Count != 0).ToArray(); + if (_next >= _cursors.Length) _next = 0; + owner.Partition.ReleaseInterest(owner.Source); + _hub.Resources.Release(PartitionedSampleHub.ReferenceOverhead); + _hub.UntrackInterestItems(1); + _charge -= PartitionedSampleHub.ReferenceOverhead; + if (_owners.Count == 0) Release(); + return true; + } + } + public bool IsReset + { + get + { + if (Volatile.Read(ref _released) != 0 || _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) return true; + foreach (var cursor in Volatile.Read(ref _cursors)) + if (!cursor.Partition.Control.Quiet.Matches(cursor.QuietControl)) return true; + return Volatile.Read(ref _released) != 0 || _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch; + } + } + + /// Scans at most maximum retained partition changes, returning false on a gap or epoch reset. + public bool TryReadChanges(int maximum, out IReadOnlyList changes) + { + if (maximum <= 0) throw new ArgumentOutOfRangeException(nameof(maximum)); + lock (_gate) + { + var result = new List(); + changes = result; + if (IsReset) { Release(); return false; } + var scanned = 0; + for (var visited = 0; visited < _cursors.Length && scanned < maximum; visited++) + { + var cursor = _cursors[_next]; _next = (_next + 1) % _cursors.Length; + if (!cursor.Partition.ReadInterestChanges(cursor.Epoch, ref cursor.Position, cursor.Tickets, + maximum - scanned, result, out var used)) { Release(); result.Clear(); return false; } + scanned += used; + } + if (IsReset) { Release(); result.Clear(); return false; } + return true; + } + } + private void Release() + { + if (Interlocked.Exchange(ref _released, 1) == 0) + { + _cancellation.Unregister(); + var count = _owners.Count; + foreach (var owner in _owners.Values) owner.Partition.ReleaseInterest(owner.Source); + _owners.Clear(); _cursors = []; + _hub.Resources.Release(_charge); _hub.UntrackInterestItems(count); + } + _hub.ForgetInterest(this); + } + public void Dispose() { lock (_gate) Release(); } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs index ba45ea526..8fdd332fd 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs @@ -57,7 +57,7 @@ public sealed class SourceSamplePublisher private readonly Dictionary _tickets = new(); private readonly Dictionary<(string Driver, string Reference), BackingSourceKey> _drivers = new(); private readonly Dictionary _virtuals = new(StringComparer.Ordinal); - private sealed class SourceSlot + internal sealed class SourceSlot { public readonly object Gate = new(); public SourceBinding? Current; @@ -65,7 +65,7 @@ public sealed class SourceSamplePublisher public int RepairQueued; public int RepairAttempts; } - private sealed class SourceBinding(SourceTicket ticket, SourceSlot slot, ProducerFence? producer, SourceValueShape? shape) + internal sealed class SourceBinding(SourceTicket ticket, SourceSlot slot, ProducerFence? producer, SourceValueShape? shape) { public SourceTicket Ticket { get; } = ticket; public SourceSlot Slot { get; } = slot; @@ -365,6 +365,138 @@ public sealed class SourceSamplePublisher } } + /// An owned, budgeted callback sample whose handle has not yet been acknowledged. + internal sealed class StagedSourceSample : IDisposable + { + private readonly SourceSamplePublisher _owner; + private readonly SourceBinding _binding; + private readonly SourceTicket _ticket; + private readonly uint _status; + private readonly DateTimeOffset? _source, _server; + private IIngressReservation? _reservation; + private DataValue? _value; + private int _finished; + + internal StagedSourceSample(SourceSamplePublisher owner, SourceBinding binding, SourceTicket ticket, + DataValueSnapshot snapshot, IIngressReservation reservation, DataValue value) + { + _owner = owner; _binding = binding; _ticket = ticket; _status = snapshot.StatusCode; + _source = OwnedDataSample.Timestamp(snapshot.SourceTimestampUtc); + _server = OwnedDataSample.Timestamp(snapshot.ServerTimestampUtc); + _reservation = reservation; _value = value; + } + + internal bool Commit() + { + if (Interlocked.Exchange(ref _finished, 1) != 0) return false; + var reservation = _reservation!; _reservation = null; + var value = _value!; _value = null; + DataSample? sample = null; + try + { + var slot = _binding.Slot; + if (!Monitor.TryEnter(slot.Gate)) { _owner._hub.Invalidate(_ticket, "staged source contention"); return false; } + try + { + if (!_binding.Active || !ReferenceEquals(Volatile.Read(ref slot.Current), _binding)) return false; + var serving = _owner._serving(); + if (serving is null || serving.NodeId != _ticket.Key.ServingNodeId || + serving.Incarnation != _ticket.Key.ServingIncarnation || string.IsNullOrWhiteSpace(serving.Role)) + { _owner._hub.Invalidate(_ticket, "staged source identity unavailable"); return false; } + var sequence = checked(++slot.Sequence); + sample = new DataSample(value, _status, _source, _server, serving, sequence); + value = null!; + if (!reservation.TryCommit(sample, sequence)) + { _owner._hub.Invalidate(_ticket, "staged source admission rejected"); return false; } + sample = null; + return true; + } + finally { Monitor.Exit(slot.Gate); } + } + catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException) + { _owner._hub.Invalidate(_ticket, "staged source commit failed"); return false; } + finally + { + value?.Dispose(); sample?.Dispose(); reservation.Dispose(); + Interlocked.Decrement(ref _binding.InFlight); + } + } + + public void Dispose() + { + if (Interlocked.Exchange(ref _finished, 1) != 0) return; + _value?.Dispose(); _value = null; + _reservation?.Dispose(); _reservation = null; + Interlocked.Decrement(ref _binding.InFlight); + } + } + + /// Reserves and owns a borrowed callback value synchronously, before handle validation. + internal bool TryStage(SourceTicket ticket, DataValueSnapshot snapshot, out StagedSourceSample? staged) + { + staged = null; + if (!_slots.TryGetValue(ticket.Key, out var slot)) return false; + var binding = Volatile.Read(ref slot.Current); + if (binding is null || binding.Ticket != ticket || !binding.Active) return false; + Interlocked.Increment(ref binding.InFlight); + IIngressReservation? reservation = null; + DataValue? value = null; + try + { + if (!binding.Active || !ReferenceEquals(Volatile.Read(ref slot.Current), binding)) return false; + var size = OwnedDataSample.Estimate(snapshot.Value, binding.Shape); + if (!_hub.TryReserveIngress(ticket, size, out reservation) || reservation is null) + { _hub.Invalidate(ticket, "staged source ingress capacity"); return false; } + value = OwnedDataSample.Copy(snapshot.Value, binding.Shape); + staged = new StagedSourceSample(this, binding, ticket, snapshot, reservation, value); + reservation = null; value = null; + return true; + } + catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException) + { _hub.Invalidate(ticket, "staged source value invalid"); return false; } + finally + { + if (staged is null) { value?.Dispose(); reservation?.Dispose(); Interlocked.Decrement(ref binding.InFlight); } + } + } + + /// Attempts status-only acquisition ingress without waiting or refreshing value age. + public bool TryPublishAcquisitionStatus(SourceTicket ticket, uint status) + { + if (!_slots.TryGetValue(ticket.Key, out var slot)) return false; + if (!Monitor.TryEnter(slot.Gate)) + { + _hub.Invalidate(ticket, "source status contention"); + return false; + } + try + { + var binding = Volatile.Read(ref slot.Current); + if (binding is null || binding.Ticket != ticket || !binding.Active) return false; + if (Volatile.Read(ref binding.InFlight) != 0) + { + _hub.Invalidate(ticket, "source status overtook in-flight sample"); + return false; + } + if (_hub.TryPublishStatus(ticket, checked(++slot.Sequence), status, null, null)) return true; + _hub.Invalidate(ticket, "source status admission failed"); + return false; + } + catch (OverflowException) + { + _hub.Invalidate(ticket, "source status sequence exhausted"); + return false; + } + finally { Monitor.Exit(slot.Gate); } + } + + internal void WithAcquisitionStatusLockForTest(SourceTicket ticket, bool publisherGate, Action action) + { + if (publisherGate) { lock (_gate) action(); return; } + if (!_slots.TryGetValue(ticket.Key, out var slot)) throw new InvalidOperationException("Source slot is unavailable."); + lock (slot.Gate) action(); + } + /// Synchronously invalidates a malformed callback's captured source generation. public void Invalidate(SourceTicket ticket, string reason) => _hub.Invalidate(ticket, reason); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionItemHandleTable.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionItemHandleTable.cs new file mode 100644 index 000000000..6cd393a80 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionItemHandleTable.cs @@ -0,0 +1,76 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Epoch-local non-reusable item identifiers and revision fences. +internal sealed class SubscriptionItemHandleTable +{ + private readonly object _gate = new(); + private readonly string _subscription; + private readonly long _epoch; + private readonly int _capacity; + private readonly Dictionary _items = new(); + private readonly HashSet _clientIds = new(StringComparer.Ordinal); + private readonly Dictionary _reserved = new(); + private readonly Dictionary _replacementByOld = new(); + private ulong _next; + internal SubscriptionItemHandleTable(string subscriptionId, long epoch, int capacity) + { + ArgumentException.ThrowIfNullOrWhiteSpace(subscriptionId); + if (epoch <= 0 || capacity <= 0) throw new ArgumentOutOfRangeException(nameof(epoch)); + _subscription = subscriptionId; _epoch = epoch; _capacity = capacity; + } + internal DataItemHandle Add(string clientItemId) + { + ArgumentException.ThrowIfNullOrWhiteSpace(clientItemId); + lock (_gate) + { + if (_items.Count >= _capacity || _clientIds.Contains(clientItemId)) throw new InvalidOperationException("Item capacity or ID conflict."); + var id = checked(++_next); + _clientIds.Add(clientItemId); _items.Add(id, (clientItemId, 1)); + return new(_subscription, _epoch, id, 1); + } + } + internal bool Remove(DataItemHandle handle) + { + lock (_gate) + { + if (!Current(handle) || !_items.Remove(handle.Handle, out var item)) return false; + if (_replacementByOld.Remove(handle.Handle, out var reserved)) _reserved.Remove(reserved); + _clientIds.Remove(item.ClientId); return true; + } + } + internal bool IsCurrent(DataItemHandle handle) { lock (_gate) return Current(handle); } + internal DataItemHandle ReserveReplacement(DataItemHandle previous) + { + lock (_gate) + { + if (!Current(previous) || _replacementByOld.ContainsKey(previous.Handle) || _reserved.Count >= _capacity) + throw new InvalidOperationException("Item cannot be revised."); + var id = checked(++_next); + var item = _items[previous.Handle]; + var revision = checked(item.Revision + 1); + _reserved.Add(id, (previous, item.ClientId, revision)); _replacementByOld.Add(previous.Handle, id); + return new(_subscription, _epoch, id, revision); + } + } + internal bool CommitReplacement(DataItemHandle previous, DataItemHandle replacement) + { + lock (_gate) + { + if (!Current(previous) || replacement.SubscriptionId != _subscription || replacement.StreamEpoch != _epoch || + !_reserved.TryGetValue(replacement.Handle, out var reserved) || reserved.Previous != previous || reserved.Revision != replacement.ItemRevision) + return false; + _reserved.Remove(replacement.Handle); _replacementByOld.Remove(previous.Handle); + _items.Remove(previous.Handle); _items.Add(replacement.Handle, (reserved.ClientId, reserved.Revision)); + return true; + } + } + internal void CancelReplacement(DataItemHandle replacement) + { + lock (_gate) + if (_reserved.Remove(replacement.Handle, out var reserved)) _replacementByOld.Remove(reserved.Previous.Handle); + } + private bool Current(DataItemHandle handle) => handle is not null && handle.SubscriptionId == _subscription && + handle.StreamEpoch == _epoch && _items.TryGetValue(handle.Handle, out var item) && item.Revision == handle.ItemRevision; +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionSettingsAggregator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionSettingsAggregator.cs new file mode 100644 index 000000000..44d244bf3 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionSettingsAggregator.cs @@ -0,0 +1,16 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Computes a shared demand that cannot suppress any admitted consumer's changes. +internal static class SubscriptionSettingsAggregator +{ + internal static DataSubscriptionSettings Aggregate(IReadOnlyCollection settings) + { + ArgumentNullException.ThrowIfNull(settings); + if (settings.Count == 0) throw new ArgumentException("At least one interest is required.", nameof(settings)); + foreach (var item in settings) item.Validate(); + return new(settings.Min(x => x.SamplingInterval), settings.Min(x => x.PublishingInterval), + settings.Max(x => x.Trigger), null); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionTransportCapacity.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionTransportCapacity.cs new file mode 100644 index 000000000..46a1015fc --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionTransportCapacity.cs @@ -0,0 +1,231 @@ +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Shared physical prepare/write slots and byte reservations across all sessions. +internal sealed class SubscriptionTransportCapacity +{ + private readonly object _gate = new(); + private readonly int _maximum, _perPrincipal; + private readonly long _maximumBytes; + private readonly TimeProvider _clock; + private readonly int _maxCommandsPerSecond, _maxRatePrincipals; + private readonly Dictionary _commandRates = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _principals = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _sessionsByPrincipal = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _interestsByPrincipal = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _waiters = new(StringComparer.OrdinalIgnoreCase); + private readonly LinkedList _roundRobin = new(); + private int _waiting; + private int _active; + private int _sessions; + private int _interests; + private const int MaxGlobalInterests = 100_000; + private sealed class PrincipalWaiters(string principal) + { + internal readonly string Principal = principal; + internal readonly LinkedList Queue = new(); + internal LinkedListNode? Node; + } + private sealed class Waiter(SubscriptionTransportCapacity owner, PrincipalWaiters group, long bytes, CancellationToken token) + { + internal readonly SubscriptionTransportCapacity Owner = owner; + internal readonly PrincipalWaiters Group = group; + internal readonly long Bytes = bytes; + internal readonly CancellationToken Token = token; + internal readonly TaskCompletionSource Completion = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal LinkedListNode? Node; + internal CancellationTokenRegistration Registration; + internal bool Pending = true; + } + private long _bytes; + internal SnapshotAdmissionScheduler Snapshots { get; } + private sealed class Lease(SubscriptionTransportCapacity owner, string principal, long bytes) : IDisposable + { + private SubscriptionTransportCapacity? _owner = owner; + public void Dispose() => Interlocked.Exchange(ref _owner, null)?.Release(principal, bytes); + } + private sealed class SessionLease(SubscriptionTransportCapacity owner, string principal, long bytes) : IDisposable + { + private SubscriptionTransportCapacity? _owner = owner; + public void Dispose() => Interlocked.Exchange(ref _owner, null)?.ReleaseSession(principal, bytes); + } + private sealed class InterestLease(SubscriptionTransportCapacity owner, string principal, long bytes) : IDisposable + { + private SubscriptionTransportCapacity? _owner = owner; + public void Dispose() => Interlocked.Exchange(ref _owner, null)?.ReleaseInterest(principal, bytes); + } + internal SubscriptionTransportCapacity(int maximum, int perPrincipal, long maximumBytes, TimeProvider? clock = null, + int? maxSnapshots = null, int? maxSnapshotsPerPrincipal = null, long? maxSnapshotBytes = null, + long? maxPrincipalSnapshotBytes = null, long? globalSnapshotBytesPerSecond = null, + long? principalSnapshotBytesPerSecond = null, TimeSpan? maxSnapshotLifetime = null, int maxCommandsPerSecond = 128) + { + if (maximum <= 0 || perPrincipal <= 0 || maximumBytes <= 0 || maxCommandsPerSecond <= 0) throw new ArgumentOutOfRangeException(nameof(maximum)); + _maximum = maximum; _perPrincipal = perPrincipal; _maximumBytes = maximumBytes; + _clock = clock ?? TimeProvider.System; _maxCommandsPerSecond = maxCommandsPerSecond; _maxRatePrincipals = checked(maximum * 16); + Snapshots = new(maxSnapshots ?? maximum, maxSnapshotsPerPrincipal ?? perPrincipal, maxSnapshotBytes ?? maximumBytes, + maxPrincipalBytes: maxPrincipalSnapshotBytes, globalBytesPerSecond: globalSnapshotBytesPerSecond ?? maximumBytes, + principalBytesPerSecond: principalSnapshotBytesPerSecond ?? maximumBytes, maxLifetime: maxSnapshotLifetime, clock: clock); + } + internal int ActiveOperations { get { lock (_gate) return _active; } } + internal bool TryAdmitCommand(string principal) + { + ArgumentException.ThrowIfNullOrWhiteSpace(principal); + lock (_gate) + { + var now = _clock.GetTimestamp(); + if (!_commandRates.TryGetValue(principal, out var rate)) + { + if (_commandRates.Count >= _maxRatePrincipals) + { + var expired = _commandRates.FirstOrDefault(pair => _clock.GetElapsedTime(pair.Value.Started, now) >= TimeSpan.FromSeconds(1)); + if (expired.Key is null) return false; + _commandRates.Remove(expired.Key); + } + _commandRates.Add(principal, (now, 1)); return true; + } + if (_clock.GetElapsedTime(rate.Started, now) >= TimeSpan.FromSeconds(1)) rate = (now, 0); + if (rate.Count >= _maxCommandsPerSecond) return false; + _commandRates[principal] = (rate.Started, rate.Count + 1); return true; + } + } + internal bool TryOpenSession(string principal, long fixedBytes, int admittedLimit, out IDisposable? lease) + { + ArgumentException.ThrowIfNullOrWhiteSpace(principal); + if (fixedBytes <= 0 || admittedLimit <= 0) throw new ArgumentOutOfRangeException(nameof(fixedBytes)); + lease = null; + lock (_gate) + { + _sessionsByPrincipal.TryGetValue(principal, out var count); + if (_waiting != 0 || _sessions >= _maximum || count >= Math.Min(_perPrincipal, admittedLimit) || + fixedBytes > _maximumBytes - _bytes) return false; + _sessionsByPrincipal[principal] = count + 1; _sessions++; _bytes += fixedBytes; + lease = new SessionLease(this, principal, fixedBytes); return true; + } + } + internal bool TryReserveInterest(string principal, int principalLimit, long fixedBytes, out IDisposable? lease) + { + ArgumentException.ThrowIfNullOrWhiteSpace(principal); + if (principalLimit <= 0 || fixedBytes <= 0) throw new ArgumentOutOfRangeException(nameof(principalLimit)); + lease = null; + lock (_gate) + { + _interestsByPrincipal.TryGetValue(principal, out var count); + if (_waiting != 0 || _interests >= MaxGlobalInterests || count >= principalLimit || fixedBytes > _maximumBytes - _bytes) return false; + _interestsByPrincipal[principal] = count + 1; _interests++; _bytes += fixedBytes; + lease = new InterestLease(this, principal, fixedBytes); return true; + } + } + internal bool TryReserve(string principal, long bytes, out IDisposable? lease) + { + ArgumentException.ThrowIfNullOrWhiteSpace(principal); + if (bytes <= 0) throw new ArgumentOutOfRangeException(nameof(bytes)); + lease = null; + lock (_gate) + { + if (_waiting != 0) return false; + return TryReserveCore(principal, bytes, out lease); + } + } + /// Waits in a bounded principal-round-robin queue without blocking producers or actors. + internal ValueTask ReserveAsync(string principal, long bytes, CancellationToken cancellationToken) + { + ArgumentException.ThrowIfNullOrWhiteSpace(principal); + if (bytes <= 0) throw new ArgumentOutOfRangeException(nameof(bytes)); + cancellationToken.ThrowIfCancellationRequested(); + lock (_gate) + { + if (bytes > _maximumBytes) return ValueTask.FromResult(null); + if (_waiting == 0 && TryReserveCore(principal, bytes, out var lease)) return ValueTask.FromResult(lease); + if (_waiting >= _maximum) return ValueTask.FromResult(null); + if (!_waiters.TryGetValue(principal, out var group)) + { + group = new PrincipalWaiters(principal); group.Node = _roundRobin.AddLast(group); _waiters.Add(principal, group); + } + var waiter = new Waiter(this, group, bytes, cancellationToken); + waiter.Node = group.Queue.AddLast(waiter); _waiting++; + waiter.Registration = cancellationToken.Register(static state => + { + var pending = (Waiter)state!; pending.Owner.CancelWaiter(pending); + }, waiter); + if (!waiter.Pending) waiter.Registration.Unregister(); + GrantWaiters(); + return new ValueTask(waiter.Completion.Task); + } + } + private bool TryReserveCore(string principal, long bytes, out IDisposable? lease) + { + lease = null; + _principals.TryGetValue(principal, out var current); + if (_active >= _maximum || current >= _perPrincipal || bytes > _maximumBytes - _bytes) return false; + _principals[principal] = current + 1; _active++; _bytes += bytes; + lease = new Lease(this, principal, bytes); return true; + } + private void CancelWaiter(Waiter waiter) + { + lock (_gate) + { + if (!waiter.Pending) return; + RemoveWaiter(waiter); + waiter.Completion.TrySetCanceled(waiter.Token); + GrantWaiters(); + } + } + private void RemoveWaiter(Waiter waiter) + { + waiter.Pending = false; waiter.Group.Queue.Remove(waiter.Node!); _waiting--; + if (waiter.Group.Queue.Count == 0) + { _roundRobin.Remove(waiter.Group.Node!); _waiters.Remove(waiter.Group.Principal); waiter.Group.Node = null; } + waiter.Registration.Unregister(); + } + private void GrantWaiters() + { + var visited = _roundRobin.Count; + while (_active < _maximum && visited-- > 0 && _roundRobin.First is { } node) + { + var group = node.Value; + _roundRobin.RemoveFirst(); group.Node = _roundRobin.AddLast(group); + var waiter = group.Queue.First!.Value; + _principals.TryGetValue(group.Principal, out var activeForPrincipal); + if (activeForPrincipal >= _perPrincipal) continue; + // Preserve the oldest principal's turn rather than starving a large reservation + // behind an unlimited stream of smaller ones. + if (waiter.Bytes > _maximumBytes - _bytes) + { + _roundRobin.Remove(group.Node!); group.Node = _roundRobin.AddFirst(group); break; + } + RemoveWaiter(waiter); + if (!TryReserveCore(group.Principal, waiter.Bytes, out var lease)) throw new InvalidOperationException("Invalid transport reservation state."); + waiter.Completion.TrySetResult(lease); + visited = _roundRobin.Count; + } + } + private void Release(string principal, long bytes) + { + lock (_gate) + { + var count = _principals[principal] - 1; + if (count == 0) _principals.Remove(principal); else _principals[principal] = count; + _active--; _bytes -= bytes; + GrantWaiters(); + } + } + private void ReleaseSession(string principal, long bytes) + { + lock (_gate) + { + var count = _sessionsByPrincipal[principal] - 1; + if (count == 0) _sessionsByPrincipal.Remove(principal); else _sessionsByPrincipal[principal] = count; + _sessions--; _bytes -= bytes; + GrantWaiters(); + } + } + private void ReleaseInterest(string principal, long bytes) + { + lock (_gate) + { + var count = _interestsByPrincipal[principal] - 1; + if (count == 0) _interestsByPrincipal.Remove(principal); else _interestsByPrincipal[principal] = count; + _interests--; _bytes -= bytes; + GrantWaiters(); + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/UpstreamDemandRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/UpstreamDemandRegistry.cs new file mode 100644 index 000000000..92ce6a4fb --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/UpstreamDemandRegistry.cs @@ -0,0 +1,131 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// A sharing boundary, established only after independently authorizing the view. +internal sealed record DemandSharingKey(BackingSourceKey Source, DataTarget Target, DataConsistency Consistency, + string PrincipalId, string ExportScope, long CatalogEpoch, long AuthorityEpoch); + +internal sealed record UpstreamDemandState(int InterestCount, DataSubscriptionSettings Desired, + long DesiredRevision, long AppliedRevision, long AppliedBoundary); + +/// Bounded demand accounting. It does not itself establish a physical driver subscription. +internal sealed class UpstreamDemandRegistry +{ + private readonly object _gate = new(); + private readonly int _maxKeys, _maxInterests; + private readonly Dictionary _entries = new(new KeyComparer()); + private long _nextInterest, _nextRevision; + private int _interestCount; + private sealed class Entry + { + internal readonly Dictionary Interests = new(); + internal readonly CountedValues SamplingIntervals = new(); + internal readonly CountedValues PublishingIntervals = new(); + internal readonly CountedValues Triggers = new(); + internal DataSubscriptionSettings Desired = null!; + internal long Revision, Applied, Boundary; + + internal void Add(DataSubscriptionSettings settings) + { + SamplingIntervals.Add(settings.SamplingInterval); + PublishingIntervals.Add(settings.PublishingInterval); + Triggers.Add(settings.Trigger); + } + + internal void Remove(DataSubscriptionSettings settings) + { + SamplingIntervals.Remove(settings.SamplingInterval); + PublishingIntervals.Remove(settings.PublishingInterval); + Triggers.Remove(settings.Trigger); + } + } + // Track multiplicity separately so duplicate extrema survive until their last interest leaves. + private sealed class CountedValues where T : notnull + { + private readonly Dictionary _counts = new(); + private readonly SortedSet _values = new(); + internal T Min => _values.Min!; + internal T Max => _values.Max!; + + internal void Add(T value) + { + if (_counts.TryGetValue(value, out var count)) _counts[value] = count + 1; + else { _counts.Add(value, 1); _values.Add(value); } + } + + internal void Remove(T value) + { + var count = _counts[value]; + if (count > 1) _counts[value] = count - 1; + else { _counts.Remove(value); _values.Remove(value); } + } + } + private sealed class KeyComparer : IEqualityComparer + { + public bool Equals(DemandSharingKey? a, DemandSharingKey? b) => ReferenceEquals(a, b) || a is not null && b is not null && + a.Source == b.Source && a.Target == b.Target && a.Consistency == b.Consistency && + StringComparer.OrdinalIgnoreCase.Equals(a.PrincipalId, b.PrincipalId) && a.ExportScope == b.ExportScope && + a.CatalogEpoch == b.CatalogEpoch && a.AuthorityEpoch == b.AuthorityEpoch; + public int GetHashCode(DemandSharingKey key) => HashCode.Combine(key.Source, key.Target, key.Consistency, + StringComparer.OrdinalIgnoreCase.GetHashCode(key.PrincipalId), key.ExportScope, key.CatalogEpoch, key.AuthorityEpoch); + } + private sealed class Lease(UpstreamDemandRegistry owner, DemandSharingKey key, long id) : IDisposable + { + private UpstreamDemandRegistry? _owner = owner; + public void Dispose() => Interlocked.Exchange(ref _owner, null)?.Remove(key, id); + } + internal UpstreamDemandRegistry(int maxKeys, int maxInterests) + { + if (maxKeys <= 0 || maxInterests <= 0) throw new ArgumentOutOfRangeException(nameof(maxKeys)); + _maxKeys = maxKeys; _maxInterests = maxInterests; + } + internal bool TryAdd(DemandSharingKey key, DataSubscriptionSettings settings, out IDisposable? lease) + { + ArgumentNullException.ThrowIfNull(key); ArgumentNullException.ThrowIfNull(settings); + key.Target.Validate(); DataContractValidation.Required(key.Consistency); settings.Validate(); + ArgumentException.ThrowIfNullOrWhiteSpace(key.PrincipalId); ArgumentException.ThrowIfNullOrWhiteSpace(key.ExportScope); + if (key.CatalogEpoch <= 0 || key.AuthorityEpoch <= 0) throw new ArgumentOutOfRangeException(nameof(key)); + lease = null; + lock (_gate) + { + if (_interestCount >= _maxInterests || (!_entries.ContainsKey(key) && _entries.Count >= _maxKeys)) return false; + if (!_entries.TryGetValue(key, out var entry)) _entries.Add(key, entry = new Entry()); + var id = checked(++_nextInterest); + entry.Interests.Add(id, settings); entry.Add(settings); _interestCount++; + Update(entry); + lease = new Lease(this, key, id); return true; + } + } + internal UpstreamDemandState? GetState(DemandSharingKey key) + { + lock (_gate) return _entries.TryGetValue(key, out var e) + ? new(e.Interests.Count, e.Desired, e.Revision, e.Applied, e.Boundary) : null; + } + internal bool TryAcknowledge(DemandSharingKey key, long revision, DataSubscriptionSettings effective, long boundary) + { + ArgumentNullException.ThrowIfNull(effective); effective.Validate(); + lock (_gate) + { + if (!_entries.TryGetValue(key, out var e) || revision != e.Revision || boundary <= 0 || + effective.SamplingInterval > e.Desired.SamplingInterval || effective.PublishingInterval > e.Desired.PublishingInterval || + (int)effective.Trigger < (int)e.Desired.Trigger || effective.Deadband is not null) return false; + e.Applied = revision; e.Boundary = boundary; return true; + } + } + private void Remove(DemandSharingKey key, long id) + { + lock (_gate) + { + if (!_entries.TryGetValue(key, out var e) || !e.Interests.Remove(id, out var settings)) return; + e.Remove(settings); + _interestCount--; + if (e.Interests.Count == 0) _entries.Remove(key); else Update(e); + } + } + private void Update(Entry e) + { + var desired = new DataSubscriptionSettings(e.SamplingIntervals.Min, e.PublishingIntervals.Min, e.Triggers.Max, null); + if (e.Revision == 0 || e.Desired != desired) { e.Desired = desired; e.Revision = checked(++_nextRevision); } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index 34fca0ef7..d4b631a36 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -60,6 +60,43 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers; /// public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedStash { + /// Replace the bounded physical gRPC interest for one driver; empty removes it. + public sealed record ApplyAcquisitionDemand(string DriverInstanceId, IReadOnlyList FullReferences, + TimeSpan SamplingInterval, long DesiredRevision, long OwnerGeneration = 0, long KeyGeneration = 0); + internal sealed record RegisterAcquisitionOwner(Guid OwnerId, long OwnerSerial); + internal sealed record AcquisitionOwnerRegistered(bool Succeeded, long Generation); + internal sealed record OpenAcquisitionDemand(string DriverInstanceId, long OwnerGeneration, long RequestedKeyGeneration = 0); + internal sealed record AcquisitionDemandOpened(bool Succeeded, long KeyGeneration, + bool OwnerInvalid = false, bool StaleGeneration = false); + internal sealed record AbortOpenAcquisitionDemand(string DriverInstanceId, long OwnerGeneration, long KeyGeneration); + internal sealed record AcquisitionOpenAborted(bool Succeeded, bool OwnerInvalid = false); + internal sealed record GateOpenReplyForTest(string DriverInstanceId, TaskCompletionSource Allocated, Task Release); + internal sealed record OpenReplyGateInstalledForTest; + internal sealed record GateAbortReplyForTest(string DriverInstanceId, TaskCompletionSource Processed, Task Release); + internal sealed record AbortReplyGateInstalledForTest; + internal sealed record GetOpenAcquisitionCountForTest; + internal sealed record OpenAcquisitionCountForTest(int Count); + internal sealed record CrashForTest; + internal sealed record SetLegacySubscriptionsForTest(string DriverInstanceId, IReadOnlyList ValueReferences, + IReadOnlyList AlarmReferences); + internal sealed record LegacySubscriptionsTestApplied; + private sealed record AcquisitionApplyCompleted(HostDemandPending Pending, DriverInstanceActor.AcquisitionDemandApplied Result); + private sealed record AcquisitionRetryReady(string DriverInstanceId, long Revision, long OwnerGeneration, long KeyGeneration, bool Succeeded); + private sealed record ActiveAcquisitionDemand(IReadOnlyList References, TimeSpan Interval, long Revision); + private sealed record HostDemandPending(ApplyAcquisitionDemand Request, IActorRef Child, IActorRef ReplyTo, + DriverInstanceActor.SetDesiredSubscriptions Sent, CancellationTokenSource Stop, TaskCompletionSource Idle); + private readonly Dictionary _acquisitionDemands = new(StringComparer.Ordinal); + private readonly Dictionary _acquisitionPending = new(StringComparer.Ordinal); + private readonly Dictionary _acquisitionRevisions = new(StringComparer.Ordinal); + private readonly Dictionary _acquisitionKeyGenerations = new(StringComparer.Ordinal); + private Guid _acquisitionOwnerId; + private long _acquisitionOwnerSerial, _acquisitionOwnerGeneration; + private long _retiredAcquisitionKeyFloor; + private readonly long _acquisitionHostGeneration; + private GateOpenReplyForTest? _openReplyGateForTest; + private GateAbortReplyForTest? _abortReplyGateForTest; + private readonly HashSet _acquisitionRetryWaiting = new(StringComparer.Ordinal); + private readonly SubscriptionAcquisitionCapacity? _acquisitionCapacity; public const string DeploymentsTopic = "deployments"; public const string DeploymentAcksTopic = "deployment-acks"; public const string DriverControlTopic = ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin.DriverControlTopic.Name; @@ -801,7 +838,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS bool enforceSnapshotOrdering = false, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null, - DataWriteRuntime? dataWriteRuntime = null) => + DataWriteRuntime? dataWriteRuntime = null, + SubscriptionAcquisitionCapacity? acquisitionCapacity = null) => // WARNING: this forwarding list is POSITIONAL, and Props.Create compiles it into an // expression tree. Six IActorRef? parameters and several interface-typed ones mean a // mis-ordered argument is usually type-compatible and therefore compiles clean, then binds @@ -816,7 +854,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS sharesHistorizationScopeWithLocal, applyWedgeTimeout, reprovisionBackoff, commsRecoveryAuditDelay, sharesAlarmQueueWithLocal, applyOutcomeTimeout, captureWhilePrimaryUnreachable, historyUpdateRoleView, scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout, - enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime)); + enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime, acquisitionCapacity)); /// Initializes a new DriverHostActor with the specified dependencies. /// Database context factory for configuration database access. @@ -955,9 +993,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS bool enforceSnapshotOrdering = false, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null, - DataWriteRuntime? dataWriteRuntime = null) + DataWriteRuntime? dataWriteRuntime = null, + SubscriptionAcquisitionCapacity? acquisitionCapacity = null) { _dataWriteRuntime = dataWriteRuntime; + _acquisitionCapacity = acquisitionCapacity; + _acquisitionHostGeneration = acquisitionCapacity?.NextControlGeneration() ?? 0; _sourcePublisher = sourcePublisher; _catalogCoordinator = catalogCoordinator; _snapshotOrdering = enforceSnapshotOrdering ? new SnapshotRevisionGate() : null; @@ -1641,6 +1682,18 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS private void Steady() { + Receive(OnRegisterAcquisitionOwner); + Receive(OnOpenAcquisitionDemand); + Receive(OnAbortOpenAcquisitionDemand); + Receive(OnGateOpenReplyForTest); + Receive(OnGateAbortReplyForTest); + Receive(_ => Sender.Tell(new OpenAcquisitionCountForTest(_acquisitionKeyGenerations.Count))); + Receive(_ => throw new InvalidOperationException("test host restart")); + Receive(HandleAcquisitionDemand); + Receive(OnAcquisitionApplyCompleted); + Receive(OnAcquisitionRetryReady); + Receive(OnSetLegacySubscriptionsForTest); + Receive(_ => { }); Receive(HandleDispatchFromSteady); // The held Applied ack is released by the address-space outcome (or its timeout); both can // land in any behaviour, so all three register them. @@ -1678,6 +1731,18 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS private void Applying() { + Receive(OnRegisterAcquisitionOwner); + Receive(OnOpenAcquisitionDemand); + Receive(OnAbortOpenAcquisitionDemand); + Receive(OnGateOpenReplyForTest); + Receive(OnGateAbortReplyForTest); + Receive(_ => Sender.Tell(new OpenAcquisitionCountForTest(_acquisitionKeyGenerations.Count))); + Receive(_ => throw new InvalidOperationException("test host restart")); + Receive(HandleAcquisitionDemand); + Receive(OnAcquisitionApplyCompleted); + Receive(OnAcquisitionRetryReady); + Receive(OnSetLegacySubscriptionsForTest); + Receive(_ => { }); Receive(msg => { if (_applyingDeploymentId is not null && msg.DeploymentId == _applyingDeploymentId.Value) @@ -1878,6 +1943,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS /// private void OnDriverConnectivityChanged(DriverInstanceActor.ConnectivityChanged msg) { + if (msg.Connected && _acquisitionDemands.ContainsKey(msg.DriverInstanceId) && + _children.TryGetValue(msg.DriverInstanceId, out var activeChild) && Equals(activeChild.Actor, Sender)) + SendDesiredSubscriptions(activeChild.Actor, msg.DriverInstanceId); // The mux fan-out is independent of the OPC UA sink — a node with scripted alarms but no // publish actor (the mux-only test/dev path) must still see comms loss. Done before the early // return for exactly that reason. @@ -2748,6 +2816,13 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS private void Stale() { + Receive(HandleAcquisitionDemand); + Receive(OnAcquisitionApplyCompleted); + Receive(OnAcquisitionRetryReady); + Receive(OnRegisterAcquisitionOwner); + Receive(OnOpenAcquisitionDemand); + Receive(OnAbortOpenAcquisitionDemand); + Receive(_ => throw new InvalidOperationException("test host restart")); // lmxopcua#765: a native ack routed here while Stale is dropped before the projector records it, so it // could not be reverted and the node would show Acknowledged for an ack no driver saw. Refuse it // synchronously at the node manager instead (cleared by BecomeSteady, the only way out of Stale). @@ -4050,13 +4125,306 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS /// The driver instance whose set to send. /// The value-ref count, for the bulk loop's log total. private int SendDesiredSubscriptions(IActorRef actor, string driverId) + { + var demand = _acquisitionDemands.GetValueOrDefault(driverId); + var message = BuildDesiredSubscriptions(driverId, demand); + if (demand is null) actor.Tell(message); + else if (!_acquisitionPending.ContainsKey(driverId)) StartAcquisitionDemand(driverId, demand, ActorRefs.Nobody); + return message.FullReferences.Count; + } + + private void OnSetLegacySubscriptionsForTest(SetLegacySubscriptionsForTest message) + { + _desiredByDriver[message.DriverInstanceId] = new DesiredSubscriptionSet(message.ValueReferences, message.AlarmReferences); + if (_children.TryGetValue(message.DriverInstanceId, out var child)) + SendDesiredSubscriptions(child.Actor, message.DriverInstanceId); + Sender.Tell(new LegacySubscriptionsTestApplied()); + } + + private void OnRegisterAcquisitionOwner(RegisterAcquisitionOwner message) + { + if (_acquisitionCapacity is null || message.OwnerId == Guid.Empty || message.OwnerSerial <= 0 || + message.OwnerSerial != _acquisitionCapacity.CurrentOwnerSerial || message.OwnerSerial < _acquisitionOwnerSerial || + (message.OwnerSerial == _acquisitionOwnerSerial && message.OwnerId != _acquisitionOwnerId)) + { + Sender.Tell(new AcquisitionOwnerRegistered(false, 0)); + return; + } + if (message.OwnerSerial == _acquisitionOwnerSerial && _acquisitionOwnerGeneration > 0) + { + Sender.Tell(new AcquisitionOwnerRegistered(true, _acquisitionOwnerGeneration)); + return; + } + var previous = _acquisitionDemands.Keys.ToArray(); + _acquisitionDemands.Clear(); + _acquisitionRevisions.Clear(); + _acquisitionKeyGenerations.Clear(); + _retiredAcquisitionKeyFloor = 0; + foreach (var pending in _acquisitionPending.Values) pending.Stop.Cancel(); + _acquisitionOwnerId = message.OwnerId; + _acquisitionOwnerSerial = message.OwnerSerial; + _acquisitionOwnerGeneration = _acquisitionCapacity.NextControlGeneration(); + if (_acquisitionOwnerGeneration <= _acquisitionHostGeneration) throw new InvalidOperationException("Invalid host generation."); + foreach (var id in previous) + if (_children.TryGetValue(id, out var child)) SendDesiredSubscriptions(child.Actor, id); + Sender.Tell(new AcquisitionOwnerRegistered(true, _acquisitionOwnerGeneration)); + } + + private void OnOpenAcquisitionDemand(OpenAcquisitionDemand message) + { + if (_acquisitionCapacity is null || message.OwnerGeneration <= 0 || message.OwnerGeneration != _acquisitionOwnerGeneration) + { + Sender.Tell(new AcquisitionDemandOpened(false, 0, OwnerInvalid: true)); + return; + } + if (string.IsNullOrWhiteSpace(message.DriverInstanceId) || message.RequestedKeyGeneration < 0 || + message.RequestedKeyGeneration > _acquisitionCapacity.ControlGeneration) + { + Sender.Tell(new AcquisitionDemandOpened(false, 0)); + return; + } + if (_acquisitionKeyGenerations.TryGetValue(message.DriverInstanceId, out var key)) + { + if (message.RequestedKeyGeneration != 0 && message.RequestedKeyGeneration != key) + { + Sender.Tell(new AcquisitionDemandOpened(false, 0)); + return; + } + } + else + { + if (_acquisitionKeyGenerations.Count >= _acquisitionCapacity.MaxReservations) + { + Sender.Tell(new AcquisitionDemandOpened(false, 0)); + return; + } + key = message.RequestedKeyGeneration == 0 ? _acquisitionCapacity.NextControlGeneration() : message.RequestedKeyGeneration; + if (key <= _retiredAcquisitionKeyFloor) + { + Sender.Tell(new AcquisitionDemandOpened(false, 0, StaleGeneration: true)); + return; + } + _acquisitionKeyGenerations.Add(message.DriverInstanceId, key); + } + var reply = new AcquisitionDemandOpened(true, key); + if (_openReplyGateForTest is { } gate && gate.DriverInstanceId == message.DriverInstanceId) + { + _openReplyGateForTest = null; + var recipient = Sender; + gate.Allocated.TrySetResult(); + _ = gate.Release.ContinueWith(_ => recipient.Tell(reply), CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + else Sender.Tell(reply); + } + + private void OnAbortOpenAcquisitionDemand(AbortOpenAcquisitionDemand message) + { + if (_acquisitionCapacity is null || message.OwnerGeneration <= 0 || message.OwnerGeneration != _acquisitionOwnerGeneration) + { + Sender.Tell(new AcquisitionOpenAborted(false, OwnerInvalid: true)); + return; + } + if (string.IsNullOrWhiteSpace(message.DriverInstanceId) || message.KeyGeneration <= 0 || + message.KeyGeneration > _acquisitionCapacity.ControlGeneration) + { + Sender.Tell(new AcquisitionOpenAborted(false)); + return; + } + _retiredAcquisitionKeyFloor = Math.Max(_retiredAcquisitionKeyFloor, message.KeyGeneration); + if (_acquisitionKeyGenerations.TryGetValue(message.DriverInstanceId, out var key) && key == message.KeyGeneration) + { + _acquisitionKeyGenerations.Remove(message.DriverInstanceId); + var hadDemand = _acquisitionDemands.Remove(message.DriverInstanceId); + _acquisitionRevisions.Remove(message.DriverInstanceId); + if (hadDemand && _children.TryGetValue(message.DriverInstanceId, out var child)) + SendDesiredSubscriptions(child.Actor, message.DriverInstanceId); + } + var reply = new AcquisitionOpenAborted(true); + if (_abortReplyGateForTest is { } gate && gate.DriverInstanceId == message.DriverInstanceId) + { + _abortReplyGateForTest = null; + var recipient = Sender; + gate.Processed.TrySetResult(); + _ = gate.Release.ContinueWith(_ => recipient.Tell(reply), CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + else Sender.Tell(reply); + } + + private void OnGateAbortReplyForTest(GateAbortReplyForTest message) + { + if (_abortReplyGateForTest is not null) throw new InvalidOperationException("An Abort test gate is already installed."); + _abortReplyGateForTest = message; + Sender.Tell(new AbortReplyGateInstalledForTest()); + } + + private void OnGateOpenReplyForTest(GateOpenReplyForTest message) + { + if (_openReplyGateForTest is not null) throw new InvalidOperationException("An Open test gate is already installed."); + _openReplyGateForTest = message; + Sender.Tell(new OpenReplyGateInstalledForTest()); + } + + private DriverInstanceActor.SetDesiredSubscriptions BuildDesiredSubscriptions(string driverId, ActiveAcquisitionDemand? demand) { var set = _desiredByDriver.TryGetValue(driverId, out var s) - ? s - : new DesiredSubscriptionSet(Array.Empty(), Array.Empty()); - actor.Tell(new DriverInstanceActor.SetDesiredSubscriptions( - set.ValueRefs, SubscriptionPublishingInterval, set.AlarmRefs)); - return set.ValueRefs.Count; + ? s : new DesiredSubscriptionSet(Array.Empty(), Array.Empty()); + if (demand is null) return new(set.ValueRefs, SubscriptionPublishingInterval, set.AlarmRefs); + var refs = set.ValueRefs.Concat(demand.References).Distinct(StringComparer.Ordinal).ToArray(); + var interval = demand.Interval < SubscriptionPublishingInterval ? demand.Interval : SubscriptionPublishingInterval; + var incarnation = _children.TryGetValue(driverId, out var entry) ? entry.SourceIncarnation ?? 0 : 0; + return new(refs, interval, set.AlarmRefs, demand.Revision, incarnation, true); + } + + private void HandleAcquisitionDemand(ApplyAcquisitionDemand request) + { + var id = request.DriverInstanceId; + var replyTo = Sender; + if (request.OwnerGeneration != _acquisitionOwnerGeneration || + (request.OwnerGeneration == 0 && request.KeyGeneration != 0)) + { + replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(request.DesiredRevision, 0, TimeSpan.Zero, false, OwnerInvalid: true)); + return; + } + if (request.OwnerGeneration != 0 && + (!_acquisitionKeyGenerations.TryGetValue(id, out var key) || request.KeyGeneration != key)) + { + replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(request.DesiredRevision, 0, TimeSpan.Zero, false, KeyInvalid: true)); + return; + } + if (request.DesiredRevision <= 0 || _acquisitionCapacity is null || + (!_acquisitionRevisions.ContainsKey(id) && _acquisitionRevisions.Count >= _acquisitionCapacity.MaxReservations) || + (_acquisitionRevisions.TryGetValue(id, out var last) && request.DesiredRevision < last)) + { + replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(request.DesiredRevision, 0, TimeSpan.Zero, false)); + return; + } + if (_acquisitionRevisions.TryGetValue(id, out last) && request.DesiredRevision == last && request.FullReferences.Count > 0 && + (!_acquisitionDemands.TryGetValue(id, out var prior) || + !prior.References.SequenceEqual(request.FullReferences, StringComparer.Ordinal) || prior.Interval != request.SamplingInterval)) + { + replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(request.DesiredRevision, 0, TimeSpan.Zero, false)); + return; + } + if (_acquisitionRevisions.TryGetValue(id, out last) && request.DesiredRevision == last && + request.FullReferences.Count == 0 && _acquisitionDemands.ContainsKey(id)) + { + replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(request.DesiredRevision, 0, TimeSpan.Zero, false)); + return; + } + _acquisitionRevisions[id] = request.DesiredRevision; + if (request.FullReferences.Count == 0) + { + _acquisitionDemands.Remove(id); + _acquisitionRevisions.Remove(id); + if (request.OwnerGeneration != 0) + { + _acquisitionKeyGenerations.Remove(id); + _retiredAcquisitionKeyFloor = Math.Max(_retiredAcquisitionKeyFloor, request.KeyGeneration); + } + if (_children.TryGetValue(id, out var existing)) SendDesiredSubscriptions(existing.Actor, id); + replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(request.DesiredRevision, + _children.GetValueOrDefault(id)?.SourceIncarnation ?? 0, TimeSpan.Zero, true)); + return; + } + var demand = new ActiveAcquisitionDemand(request.FullReferences.ToArray(), request.SamplingInterval, request.DesiredRevision); + _acquisitionDemands[id] = demand; + if (_acquisitionPending.TryGetValue(id, out var pending)) + { + replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(request.DesiredRevision, + _children.GetValueOrDefault(id)?.SourceIncarnation ?? 0, TimeSpan.Zero, false, true, pending.Idle.Task)); + return; + } + StartAcquisitionDemand(id, demand, replyTo); + } + + private void StartAcquisitionDemand(string id, ActiveAcquisitionDemand demand, IActorRef replyTo) + { + if (_acquisitionPending.ContainsKey(id)) return; + if (!_children.TryGetValue(id, out var child) || child.Stubbed || child.SourceIncarnation is not { } incarnation) + { + replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(demand.Revision, 0, TimeSpan.Zero, false)); + return; + } + var message = BuildDesiredSubscriptions(id, demand); + var request = new ApplyAcquisitionDemand(id, demand.References, demand.Interval, demand.Revision, + _acquisitionOwnerGeneration, _acquisitionKeyGenerations.GetValueOrDefault(id)); + var stop = new CancellationTokenSource(); + var pending = new HostDemandPending(request, child.Actor, replyTo, message, stop, + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)); + _acquisitionPending.Add(id, pending); + var self = Self; + _ = child.Actor.Ask(message, TimeSpan.FromSeconds(15), stop.Token) + .ContinueWith(t => self.Tell(new AcquisitionApplyCompleted(pending, + t.Status == TaskStatus.RanToCompletion ? t.Result : + new DriverInstanceActor.AcquisitionDemandApplied(demand.Revision, incarnation, TimeSpan.Zero, false))), + CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + + private void OnAcquisitionApplyCompleted(AcquisitionApplyCompleted completed) + { + var pending = completed.Pending; + var id = pending.Request.DriverInstanceId; + if (!_acquisitionPending.TryGetValue(id, out var current) || !ReferenceEquals(current, pending)) return; + _acquisitionPending.Remove(id); + pending.Stop.Dispose(); + pending.Idle.TrySetResult(true); + if (pending.Request.OwnerGeneration != _acquisitionOwnerGeneration || + (pending.Request.OwnerGeneration != 0 && + (!_acquisitionKeyGenerations.TryGetValue(id, out var activeKey) || activeKey != pending.Request.KeyGeneration))) + { + pending.ReplyTo.Tell(completed.Result with { Succeeded = false }); + if (_acquisitionDemands.TryGetValue(id, out var newer)) StartAcquisitionDemand(id, newer, ActorRefs.Nobody); + return; + } + if (!_acquisitionDemands.TryGetValue(id, out var desired)) + { + pending.ReplyTo.Tell(completed.Result with { Succeeded = false, Busy = false, RetryWhenReady = null }); + return; + } + if (desired.Revision != pending.Request.DesiredRevision) + { + pending.ReplyTo.Tell(completed.Result with { Succeeded = false, Busy = false, RetryWhenReady = null }); + StartAcquisitionDemand(id, desired, ActorRefs.Nobody); + return; + } + if (!_children.TryGetValue(id, out var child) || !Equals(child.Actor, pending.Child)) + { + StartAcquisitionDemand(id, desired, pending.ReplyTo); + return; + } + if (completed.Result.Busy && completed.Result.RetryWhenReady is { } ready) + { + pending.ReplyTo.Tell(completed.Result); + if (_acquisitionRetryWaiting.Add(id)) + { + var self = Self; + _ = ready.ContinueWith(t => self.Tell(new AcquisitionRetryReady(id, desired.Revision, + pending.Request.OwnerGeneration, pending.Request.KeyGeneration, + t.Status == TaskStatus.RanToCompletion && t.Result)), CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + return; + } + var latest = BuildDesiredSubscriptions(id, desired); + if (completed.Result.Succeeded && + (!latest.FullReferences.SequenceEqual(pending.Sent.FullReferences, StringComparer.Ordinal) || + !(latest.AlarmReferences ?? Array.Empty()).SequenceEqual(pending.Sent.AlarmReferences ?? Array.Empty(), StringComparer.Ordinal) || + latest.PublishingInterval != pending.Sent.PublishingInterval || latest.ProducerIncarnation != pending.Sent.ProducerIncarnation)) + { + StartAcquisitionDemand(id, desired, pending.ReplyTo); + return; + } + pending.ReplyTo.Tell(completed.Result); + } + + private void OnAcquisitionRetryReady(AcquisitionRetryReady ready) + { + _acquisitionRetryWaiting.Remove(ready.DriverInstanceId); + if (ready.Succeeded && _acquisitionDemands.TryGetValue(ready.DriverInstanceId, out var desired) && + !_acquisitionPending.ContainsKey(ready.DriverInstanceId)) + StartAcquisitionDemand(ready.DriverInstanceId, desired, ActorRefs.Nobody); } private void SpawnChild(DriverInstanceSpec spec, bool deferSubscriptions = false) @@ -4113,12 +4481,13 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS reconnectInterval: null, startStubbed: true, healthPublisher: _healthPublisher, - clusterId: clusterId, sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation) + clusterId: clusterId, sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation, + acquisitionCapacity: _acquisitionCapacity) : DriverInstanceActor.PropsForRichWrites(new StubbedDriver(spec.DriverInstanceId, spec.DriverType), startStubbed: true, healthPublisher: _healthPublisher, clusterId: clusterId, sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation, writeDispatchGate: _dataWriteRuntime.Gate, lateWriteObserver: _dataWriteRuntime.Observer, - writeRouteState: _dataWriteRuntime.Routes), + writeRouteState: _dataWriteRuntime.Routes, acquisitionCapacity: _acquisitionCapacity), actorName); } else @@ -4137,12 +4506,13 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS writeTimeout: _writeBounds.Timeout, writeClock: _writeClock, shutdownTimeout: _childShutdownTimeout, - sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation) + sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation, acquisitionCapacity: _acquisitionCapacity) : DriverInstanceActor.PropsForRichWrites(driver!, healthPublisher: _healthPublisher, clusterId: clusterId, invoker: invoker, writeTimeout: _writeBounds.Timeout, writeClock: _writeClock, shutdownTimeout: _childShutdownTimeout, sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation, writeDispatchGate: _dataWriteRuntime.Gate, - lateWriteObserver: _dataWriteRuntime.Observer, writeRouteState: _dataWriteRuntime.Routes), + lateWriteObserver: _dataWriteRuntime.Observer, writeRouteState: _dataWriteRuntime.Routes, + acquisitionCapacity: _acquisitionCapacity), actorName); child.Tell(new DriverInstanceActor.InitializeRequested(spec.DriverConfig)); } @@ -4264,6 +4634,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS /// The child being stopped. private void RetireChild(IActorRef child) { + foreach (var pending in _acquisitionPending.Values) + if (Equals(pending.Child, child)) pending.Stop.Cancel(); _retiredChildren.Add(child); Context.Watch(child); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs index 24f7d73dd..f7d10f4b0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs @@ -18,6 +18,70 @@ file sealed class HealthPollTick private HealthPollTick() { } } +/// Process-lifetime bound for physical subscription establishments and late cleanup. +public sealed class SubscriptionAcquisitionCapacity +{ + private readonly object _gate = new(); + private readonly Dictionary<(string Cluster, string Driver), TaskCompletionSource> _inFlight = new(); + private readonly int _limit; + private long _ownerSerial; + private long _controlGeneration; + + /// Creates a shared capacity with a fixed maximum number of in-flight drivers. + public SubscriptionAcquisitionCapacity(int limit) + { + if (limit <= 0) throw new ArgumentOutOfRangeException(nameof(limit)); + _limit = limit; + } + + /// Number of driver keys held by active subscriptions, establishments, or cleanup. + public int ReservedDriverCount { get { lock (_gate) return _inFlight.Count; } } + /// Configured maximum concurrent driver reservations. + public int MaxReservations => _limit; + /// Issues a process-lifetime serial for a new bridge owner. + public long NextOwnerSerial() + { + var serial = Interlocked.Increment(ref _ownerSerial); + return serial > 0 ? serial : throw new InvalidOperationException("Acquisition owner serial exhausted."); + } + /// Latest issued bridge owner serial. + public long CurrentOwnerSerial => Interlocked.Read(ref _ownerSerial); + /// Latest process-lifetime control generation. + public long ControlGeneration => Interlocked.Read(ref _controlGeneration); + internal long NextControlGeneration() + { + var generation = Interlocked.Increment(ref _controlGeneration); + return generation > 0 ? generation : throw new InvalidOperationException("Acquisition generation exhausted."); + } + + internal IDisposable? TryAcquire(string cluster, string driver, out Task? ready) + { + var key = (cluster.ToUpperInvariant(), driver); + lock (_gate) + { + if (_inFlight.TryGetValue(key, out var existing)) { ready = existing.Task; return null; } + ready = null; + if (_inFlight.Count >= _limit) return null; + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _inFlight.Add(key, completion); + return new Reservation(this, key, completion); + } + } + + private sealed class Reservation(SubscriptionAcquisitionCapacity owner, (string Cluster, string Driver) key, + TaskCompletionSource completion) : IDisposable + { + private SubscriptionAcquisitionCapacity? _owner = owner; + public void Dispose() + { + var current = Interlocked.Exchange(ref _owner, null); + if (current is null) return; + lock (current._gate) current._inFlight.Remove(key); + completion.TrySetResult(true); + } + } +} + /// /// Akka wrapper for a single instance. States: /// @@ -127,7 +191,12 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers public sealed record SetDesiredSubscriptions( IReadOnlyList FullReferences, TimeSpan PublishingInterval, - IReadOnlyList? AlarmReferences = null); + IReadOnlyList? AlarmReferences = null, + long DesiredRevision = 0, long ProducerIncarnation = 0, bool RequireAcquisition = false); + /// Physical demand installation result, including the driver-acknowledged fence. + public sealed record AcquisitionDemandApplied(long DesiredRevision, long ProducerIncarnation, + TimeSpan NominalSamplingInterval, bool Succeeded, bool Busy = false, Task? RetryWhenReady = null, + bool OwnerInvalid = false, bool KeyInvalid = false); public sealed record SubscriptionEstablished(string DiagnosticId, int ReferenceCount); public sealed record SubscriptionFailed(string Reason); public sealed record Unsubscribe; @@ -404,6 +473,27 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher; private long? _sourceIncarnation; private long _sourceBindingVersion; + private sealed class AcquisitionFence(long revision, long producer) + { + internal readonly long Revision = revision; + internal readonly long Producer = producer; + } + private AcquisitionFence? _activeAcquisition; + private int _acquisitionPending; + private readonly SubscriptionAcquisitionCapacity? _acquisitionCapacity; + private PendingAcquisition? _pendingAcquisition; + private PendingAcquisition? _abandonedAcquisition; + private readonly TimeSpan _acquisitionTimeout; + private readonly TimeProvider _acquisitionClock; + private SharedAcquisitionReservation? _activeCapacity; + private IDisposable? _activeCapacityReference; + private Task? _previousAcquisitionCleanup; + private bool _fenceLegacyHandles; + private LegacyAdmission? _legacyAdmission; + private SetDesiredSubscriptions? _desiredAcquisition; + private TimeSpan _acquisitionNominal; + private SetDesiredSubscriptions? _deferredLegacyDemand; + private sealed record ResumeDeferredLegacy; private const int SourceBindingBatchSize = 128; private EventHandler? _alarmEventHandler; private EventHandler? _rediscoveryHandler; @@ -509,7 +599,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers TimeSpan? writeTimeout = null, TimeProvider? writeClock = null, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null, - long? sourceIncarnation = null) => + long? sourceIncarnation = null, + SubscriptionAcquisitionCapacity? acquisitionCapacity = null, + TimeSpan? acquisitionTimeout = null, TimeProvider? acquisitionClock = null) => Akka.Actor.Props.Create(() => new DriverInstanceActor( driver, reconnectInterval ?? DefaultReconnectInterval, @@ -524,17 +616,20 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers queuedWriteBudget, initializeTimeout, writeTimeout, - writeClock, sourcePublisher, sourceIncarnation)); + writeClock, sourcePublisher, sourceIncarnation, acquisitionCapacity, acquisitionTimeout, acquisitionClock)); internal static Props PropsForRichWrites(IDriver driver, IDriverCapabilityInvoker? invoker = null, TimeSpan? commsLossTimeout = null, int? maxWritesInFlight = null, TimeSpan? writeTimeout = null, IWriteDispatchGate? writeDispatchGate = null, LateWriteObserver? lateWriteObserver = null, WriteRouteState? writeRouteState = null, TimeProvider? writeClock = null, IDriverHealthPublisher? healthPublisher = null, string? clusterId = null, TimeSpan? shutdownTimeout = null, - SourceSamplePublisher? sourcePublisher = null, long? sourceIncarnation = null, bool startStubbed = false) => + SourceSamplePublisher? sourcePublisher = null, long? sourceIncarnation = null, bool startStubbed = false, + SubscriptionAcquisitionCapacity? acquisitionCapacity = null, + TimeSpan? acquisitionTimeout = null, TimeProvider? acquisitionClock = null) => Akka.Actor.Props.CreateBy(new RichWriteActorProducer(() => new DriverInstanceActor(driver, DefaultReconnectInterval, startStubbed, healthPublisher, clusterId, invoker, null, commsLossTimeout, shutdownTimeout, maxWritesInFlight, null, null, writeTimeout, writeClock, - sourcePublisher, sourceIncarnation, writeDispatchGate, lateWriteObserver, writeRouteState))); + sourcePublisher, sourceIncarnation, writeDispatchGate, lateWriteObserver, writeRouteState, acquisitionCapacity, + acquisitionTimeout, acquisitionClock))); private sealed class RichWriteActorProducer(Func create) : IIndirectActorProducer { @@ -605,10 +700,13 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers TimeSpan? writeTimeout = null, TimeProvider? writeClock = null, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null, - long? sourceIncarnation = null) + long? sourceIncarnation = null, + SubscriptionAcquisitionCapacity? acquisitionCapacity = null, + TimeSpan? acquisitionTimeout = null, TimeProvider? acquisitionClock = null) : this(driver, reconnectInterval, startStubbed, healthPublisher, clusterId, invoker, healthPollInterval, commsLossTimeout, shutdownTimeout, maxWritesInFlight, queuedWriteBudget, initializeTimeout, - writeTimeout, writeClock, sourcePublisher, sourceIncarnation, null, null, null) { } + writeTimeout, writeClock, sourcePublisher, sourceIncarnation, null, null, null, acquisitionCapacity, + acquisitionTimeout, acquisitionClock) { } private DriverInstanceActor(IDriver driver, TimeSpan reconnectInterval, bool startStubbed, IDriverHealthPublisher? healthPublisher, string? clusterId, IDriverCapabilityInvoker? invoker, @@ -616,12 +714,16 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers int? maxWritesInFlight, TimeSpan? queuedWriteBudget, TimeSpan? initializeTimeout, TimeSpan? writeTimeout, TimeProvider? writeClock, SourceSamplePublisher? sourcePublisher, long? sourceIncarnation, IWriteDispatchGate? writeDispatchGate, LateWriteObserver? lateWriteObserver, - WriteRouteState? writeRouteState) + WriteRouteState? writeRouteState, SubscriptionAcquisitionCapacity? acquisitionCapacity, + TimeSpan? acquisitionTimeout, TimeProvider? acquisitionClock) { _writeDispatchGate = writeDispatchGate; _lateWriteObserver = lateWriteObserver; _writeRouteState = writeRouteState; _sourcePublisher = sourcePublisher; + _acquisitionCapacity = acquisitionCapacity; + _acquisitionTimeout = acquisitionTimeout is { } timeout && timeout > TimeSpan.Zero ? timeout : TimeSpan.FromSeconds(10); + _acquisitionClock = acquisitionClock ?? TimeProvider.System; _sourceIncarnation = sourceIncarnation; _writeTimeout = writeTimeout is { } wt && wt > TimeSpan.Zero ? wt : DefaultWriteTimeout; _writeClock = writeClock ?? TimeProvider.System; @@ -709,7 +811,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers Receive(_ => { /* stubbed drivers don't disconnect */ }); Receive(IgnoreConnectionLoss); Receive(_ => { /* stubbed drivers don't reconnect */ }); - Receive(StoreDesiredSubscriptions); + Receive(StoreDisconnectedDesiredSubscriptions); // Stubbed drivers never enter Connected, so they never kick discovery; swallow defensively in case a // re-discovery self-tick is ever routed here so it doesn't surface as an Akka Unhandled message. Receive(HandleRediscoveryRaised); @@ -755,7 +857,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers Become(Reconnecting); PublishHealthSnapshot(); }); - Receive(StoreDesiredSubscriptions); + Receive(StoreDisconnectedDesiredSubscriptions); Receive(_ => { /* already connecting — no-op */ }); Receive(IgnoreConnectionLoss); // ResubscribeDesired self-Tells Subscribe; HandleSubscribeAsync replies SubscriptionEstablished to the @@ -812,8 +914,45 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers ReceiveAsync(HandleSubscribeAsync); ReceiveAsync(_ => { CancelSourceBindingRetry(); return UnsubscribeAsync(); }); Receive(RetrySourceBindingBatch); - Receive(msg => + ReceiveAsync(async msg => { + if (msg.RequireAcquisition) { await ApplyAcquisitionDemandAsync(msg, Sender); return; } + if (_abandonedAcquisition is { } abandoned && !abandoned.Finished.IsCompleted) + { + var schedule = _deferredLegacyDemand is null; + _deferredLegacyDemand = msg; + if (schedule) + { + var self = Self; + _ = abandoned.Finished.ContinueWith(t => { if (t.Status == TaskStatus.RanToCompletion && t.Result) self.Tell(new ResumeDeferredLegacy()); }, + CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + return; + } + if (_abandonedAcquisition is { Finished: { IsCompletedSuccessfully: true, Result: false } }) + { + _deferredLegacyDemand = msg; + return; + } + if (_previousAcquisitionCleanup is { IsCompletedSuccessfully: true, Result: false } && _activeCapacityReference is not null) + { + _deferredLegacyDemand = msg; + return; + } + if (_previousAcquisitionCleanup is { IsCompleted: false } cleanup && _activeCapacityReference is not null) + { + var schedule = _deferredLegacyDemand is null; + _deferredLegacyDemand = msg; + if (schedule) + { + var self = Self; + _ = cleanup.ContinueWith(t => { if (t.Status == TaskStatus.RanToCompletion && t.Result) self.Tell(new ResumeDeferredLegacy()); }, + CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + return; + } + _deferredLegacyDemand = null; + _desiredAcquisition = null; CancelSourceBindingRetry(); StoreDesiredSubscriptions(msg); if (_desiredRefs.Count > 0) Self.Tell(new Subscribe(_desiredRefs, _desiredInterval)); @@ -831,6 +970,12 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers // removed alarm. SubscribeDesiredAlarms(); }); + Receive(_ => + { + if (_deferredLegacyDemand is not { } desired) return; + _deferredLegacyDemand = null; + Self.Tell(desired); + }); ReceiveAsync(HandleSubscribeAlarmsAsync); Receive(OnDataChangeForward); Receive(OnDataChangeBatchForward); @@ -985,7 +1130,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers _log.Info( "DriverInstance {Id}: connected with {Count} desired subscription ref(s) but no live subscription handle — re-subscribing (periodic reconcile)", _driverInstanceId, _desiredRefs.Count); - Self.Tell(new Subscribe(_desiredRefs, _desiredInterval)); + if (_desiredAcquisition is { } acquisition) Self.Tell(acquisition); + else Self.Tell(new Subscribe(_desiredRefs, _desiredInterval)); } /// @@ -1065,7 +1211,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers { if (msg.Generation == _initGeneration) CompleteInitAttempt(); }); - Receive(StoreDesiredSubscriptions); + Receive(StoreDisconnectedDesiredSubscriptions); Receive(_ => { /* already reconnecting — no-op */ }); Receive(IgnoreConnectionLoss); // A watchdog DisconnectObserved self-sent on the Connected tick can still be queued when a ConnectionLossRaised @@ -1742,44 +1888,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers sourceBindingNeedsRetry |= !TryEnsureSourceBinding(msg.FullReferences[i], incarnation); sourceBindingNeedsRetry |= count < msg.FullReferences.Count; } - // EXACTLY ONE of the two data-change events is subscribed. An IBatchSubscribable driver raises - // OnDataChangeBatch once per production burst AND the per-tag OnDataChange for every item in - // that same burst (the per-tag event is kept for legacy consumers — Galaxy cold reads, driver - // CLIs). Attaching both here would forward every value twice. The batch event is preferred: one - // Tell, one parent hop, one mux pass per burst instead of per tag. - if (subscribable is IBatchSubscribable batchable) - { - _batchChangeHandler = (_, args) => - { - // A null/empty raise from a buggy driver must never enter the mailbox: an unguarded null - // would throw in the handler, restart the actor, and tear down the driver transport. - if (args?.Items is not { Count: > 0 }) return; - var owned = new DataChangeItem[args.Items.Count]; - for (var i = 0; i < owned.Length; i++) - { - var item = args.Items[i]; - if (item is null) { owned[i] = null!; continue; } - PublishSource(item.FullReference, item.Snapshot); - owned[i] = new DataChangeItem(item.FullReference, CopyLegacySnapshot(item.Snapshot)); - } - self.Tell(new DataChangeBatchForward(owned, _sourceIncarnation)); - }; - batchable.OnDataChangeBatch += _batchChangeHandler; - } - else - { - _dataChangeHandler = (_, args) => - { - if (args is null) - { - self.Tell(new DataChangeForward(string.Empty, null!, _sourceIncarnation)); - return; - } - PublishSource(args.FullReference, args.Snapshot); - self.Tell(new DataChangeForward(args.FullReference, CopyLegacySnapshot(args.Snapshot), _sourceIncarnation)); - }; - subscribable.OnDataChange += _dataChangeHandler; - } + var legacyAdmission = _fenceLegacyHandles ? new LegacyAdmission(this, self) : null; + Volatile.Write(ref _legacyAdmission, legacyAdmission); + AttachDataChangeHandler(subscribable, self); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); // A bulk subscribe spans potentially many hosts, so key the pipeline on the driver @@ -1790,6 +1901,13 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers async ct => await subscribable.SubscribeAsync(msg.FullReferences, msg.PublishingInterval, ct), cts.Token); + if (legacyAdmission is not null && !legacyAdmission.Finish(_subscriptionHandle)) + { + await UnsubscribeAsync(); + replyTo.Tell(new SubscriptionFailed("Legacy initial callback staging capacity exceeded.")); + return; + } + if (sourceBindingNeedsRetry && _sourceIncarnation is { } retryIncarnation) Timers.StartSingleTimer("source-binding-retry", new RetrySourceBindings(msg.FullReferences, 0, false, 0, sourceBindingVersion, retryIncarnation), TimeSpan.FromMilliseconds(250)); @@ -1806,6 +1924,449 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers } } + private void AttachDataChangeHandler(ISubscribable subscribable, IActorRef self) + { + if (_dataChangeHandler is not null || _batchChangeHandler is not null) return; + // EXACTLY ONE of the two data-change events is subscribed. An IBatchSubscribable driver raises + // OnDataChangeBatch once per production burst AND the per-tag OnDataChange for every item in + // that same burst (the per-tag event is kept for legacy consumers — Galaxy cold reads, driver + // CLIs). Attaching both here would forward every value twice. The batch event is preferred: one + // Tell, one parent hop, one mux pass per burst instead of per tag. + if (subscribable is IBatchSubscribable batchable) + { + _batchChangeHandler = (_, args) => + { + // A null/empty raise from a buggy driver must never enter the mailbox: an unguarded null + // would throw in the handler, restart the actor, and tear down the driver transport. + if (args?.Items is not { Count: > 0 }) return; + var admission = Volatile.Read(ref _legacyAdmission); + if (admission is not null ? !admission.Admit(args.SubscriptionHandle, args.Items) : !AcceptLegacyHandle(args.SubscriptionHandle)) return; + var owned = new DataChangeItem[args.Items.Count]; + for (var i = 0; i < owned.Length; i++) + { + var item = args.Items[i]; + if (item is null) { owned[i] = null!; continue; } + if (Volatile.Read(ref _activeAcquisition) is null) PublishSource(item.FullReference, item.Snapshot); + owned[i] = new DataChangeItem(item.FullReference, CopyLegacySnapshot(item.Snapshot)); + } + self.Tell(new DataChangeBatchForward(owned, _sourceIncarnation)); + }; + batchable.OnDataChangeBatch += _batchChangeHandler; + } + else + { + _dataChangeHandler = (_, args) => + { + if (args is null) + { + self.Tell(new DataChangeForward(string.Empty, null!, _sourceIncarnation)); + return; + } + var admission = Volatile.Read(ref _legacyAdmission); + if (admission is not null ? !admission.Admit(args.SubscriptionHandle, + [new DataChangeItem(args.FullReference, args.Snapshot)]) : !AcceptLegacyHandle(args.SubscriptionHandle)) return; + if (Volatile.Read(ref _activeAcquisition) is null) PublishSource(args.FullReference, args.Snapshot); + self.Tell(new DataChangeForward(args.FullReference, CopyLegacySnapshot(args.Snapshot), _sourceIncarnation)); + }; + subscribable.OnDataChange += _dataChangeHandler; + } + + } + + private bool AcceptLegacyHandle(ISubscriptionHandle handle) + { + var current = Volatile.Read(ref _subscriptionHandle); + if (Volatile.Read(ref _fenceLegacyHandles)) return current is not null && ReferenceEquals(current, handle); + return Volatile.Read(ref _acquisitionPending) == 0 && Volatile.Read(ref _activeAcquisition) is null || + current is not null && ReferenceEquals(current, handle); + } + + // The legacy API permits callbacks before SubscribeAsync returns its handle. Stage those + // callbacks under a bounded generation gate, then accept only the returned handle. Source + // reservations capture their own monotonic ingress time at callback time; SDK delivery does + // not depend on source-hub admission. + private sealed class LegacyAdmission(DriverInstanceActor owner, IActorRef self) : IDisposable + { + private const int MaxItems = 4096; + private const long MaxBytes = 16 * 1024 * 1024; + private readonly object _gate = new(); + private readonly List _events = new(); + private ISubscriptionHandle? _handle; + private long _bytes; + private int _items, _failed; + private int _closed; + private sealed record StagedEvent(ISubscriptionHandle Handle, DataChangeItem[] Items, StagedSource?[] Sources); + internal sealed record StagedSource(SourceSamplePublisher.StagedSourceSample? Sample, SourceTicket Ticket, uint? Status); + + // True means the caller may deliver directly; false means staged or rejected. + internal bool Admit(ISubscriptionHandle handle, IReadOnlyList items) + { + var installed = Volatile.Read(ref _handle); + if (installed is not null) return Volatile.Read(ref _closed) == 0 && ReferenceEquals(handle, installed); + if (!Monitor.TryEnter(_gate)) + { + Interlocked.Exchange(ref _failed, 1); + owner.InvalidateLegacySources(items); + return false; + } + try + { + if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _failed) != 0) return false; + if (_handle is not null) return ReferenceEquals(handle, _handle); + if (items.Count == 0 || items.Count > MaxItems - _items) + { Interlocked.Exchange(ref _failed, 1); owner.InvalidateLegacySources(items); return false; } + var copied = new DataChangeItem[items.Count]; + var sources = new StagedSource?[items.Count]; + long bytes = 0; + try + { + for (var i = 0; i < items.Count; i++) + { + var item = items[i]; + if (item?.Snapshot is null) throw new ArgumentException("Malformed legacy callback."); + bytes = checked(bytes + OwnedDataSample.Estimate(item.Snapshot.Value) + 2L * item.FullReference.Length); + if (bytes > MaxBytes - _bytes) throw new ArgumentException("Legacy initial callback budget exceeded."); + copied[i] = new DataChangeItem(item.FullReference, CopyLegacySnapshot(item.Snapshot)); + sources[i] = owner.StageLegacySource(item); + } + _items += items.Count; _bytes += bytes; + _events.Add(new StagedEvent(handle, copied, sources)); + } + catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException) + { + foreach (var source in sources) source?.Sample?.Dispose(); + Interlocked.Exchange(ref _failed, 1); + owner.InvalidateLegacySources(items); + } + return false; + } + finally { Monitor.Exit(_gate); } + } + + internal bool Finish(ISubscriptionHandle handle) + { + lock (_gate) + { + if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _failed) != 0) + { DisposeEvents(); Volatile.Write(ref _closed, 1); return false; } + foreach (var staged in _events) + { + if (ReferenceEquals(staged.Handle, handle)) + { + foreach (var source in staged.Sources) + { + if (source?.Sample is { } sample) sample.Commit(); + else if (source?.Status is { } status) owner._sourcePublisher?.TryPublishAcquisitionStatus(source.Ticket, status); + } + self.Tell(new DataChangeBatchForward(staged.Items, owner._sourceIncarnation)); + } + else foreach (var source in staged.Sources) source?.Sample?.Dispose(); + } + _events.Clear(); _items = 0; _bytes = 0; + if (Volatile.Read(ref _failed) == 0) { Volatile.Write(ref _handle, handle); return true; } + Volatile.Write(ref _closed, 1); + return false; + } + } + + private void DisposeEvents() + { + foreach (var entry in _events) foreach (var source in entry.Sources) source?.Sample?.Dispose(); + _events.Clear(); + } + public void Dispose() { lock (_gate) { Volatile.Write(ref _closed, 1); DisposeEvents(); } } + + internal static StagedSource? Stage(SourceSamplePublisher publisher, SourceTicket ticket, DataValueSnapshot snapshot) + { + if (snapshot.Value is null && !OpcUaStatus.IsGood(snapshot.StatusCode)) return new(null, ticket, snapshot.StatusCode); + return publisher.TryStage(ticket, snapshot, out var sample) ? new(sample, ticket, null) : null; + } + } + + private LegacyAdmission.StagedSource? StageLegacySource(DataChangeItem item) + { + if (_sourcePublisher is null || _sourceIncarnation is not { } incarnation) return null; + if (!_sourcePublisher.TryCaptureDriver(_driverInstanceId, item.FullReference, incarnation, out var ticket) && + (!TryEnsureSourceBinding(item.FullReference, incarnation) || + !_sourcePublisher.TryCaptureDriver(_driverInstanceId, item.FullReference, incarnation, out ticket))) return null; + return LegacyAdmission.Stage(_sourcePublisher, ticket, item.Snapshot); + } + + private void InvalidateLegacySources(IReadOnlyList items) + { + if (_sourcePublisher is null || _sourceIncarnation is not { } incarnation) return; + foreach (var item in items) + if (item is not null && _sourcePublisher.TryCaptureDriver(_driverInstanceId, item.FullReference, incarnation, out var ticket)) + _sourcePublisher.Invalidate(ticket, "legacy callback staging overflow"); + } + + private sealed class SharedAcquisitionReservation(IDisposable reservation) + { + private readonly IDisposable _reservation = reservation; + private int _references = 1; + private int _uncertain; + internal bool IsUncertain => Volatile.Read(ref _uncertain) != 0; + internal void MarkUncertain() => Interlocked.Exchange(ref _uncertain, 1); + internal IDisposable Retain() + { + if (Interlocked.Increment(ref _references) <= 1) throw new InvalidOperationException("Reservation already released."); + return new Reference(this); + } + internal IDisposable InitialReference() => new Reference(this); + private sealed class Reference(SharedAcquisitionReservation owner) : IDisposable + { + private SharedAcquisitionReservation? _owner = owner; + public void Dispose() + { + var current = Interlocked.Exchange(ref _owner, null); + if (current is not null && Interlocked.Decrement(ref current._references) == 0) current._reservation.Dispose(); + } + } + } + + // Owns the backend task independently of the actor. Admission remains pinned across actor + // death and until an abandoned operation's eventual handle has actually been released. + private sealed class PendingAcquisition(IDisposable reservation, ISubscribable subscribable, SharedAcquisitionReservation shared) + { + private readonly object _gate = new(); + private readonly CancellationTokenSource _stop = new(); + private readonly TaskCompletionSource _completion = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _finished = new(TaskCreationOptions.RunContinuationsAsynchronously); + private AcquisitionSubscriptionResult? _result; + private bool _abandoned, _settled; + internal Task Completion => _completion.Task; + internal Task Finished => _finished.Task; + + internal void CancelBeforeStart() + { + lock (_gate) _settled = true; + reservation.Dispose(); + _stop.Dispose(); + _finished.TrySetResult(true); + } + + internal void Start(IAcknowledgedAcquisitionSource source, AcquisitionSubscriptionRequest request, + Action callback) => _ = ObserveAsync(Task.Run(() => + source.SubscribeAcquisitionAsync(request, callback, _stop.Token))); + + private async Task ObserveAsync(Task operation) + { + try + { + var result = await operation.ConfigureAwait(false) ?? throw new InvalidOperationException("Acquisition returned no acknowledgment."); + var clean = false; + lock (_gate) + { + if (_abandoned) { _settled = true; clean = true; } + else { _result = result; _completion.TrySetResult(result); } + } + if (clean) await CleanupAsync(result).ConfigureAwait(false); + } + catch (Exception ex) + { + lock (_gate) { _settled = true; _completion.TrySetException(ex); } + reservation.Dispose(); + _stop.Dispose(); + _finished.TrySetResult(true); + } + } + + internal bool TryAdopt(AcquisitionSubscriptionResult result) + { + lock (_gate) + { + if (_abandoned || _settled || !ReferenceEquals(_result, result)) return false; + _settled = true; + } + reservation.Dispose(); + _stop.Dispose(); + _finished.TrySetResult(true); + return true; + } + + internal void Abandon() + { + AcquisitionSubscriptionResult? clean = null; + lock (_gate) + { + if (_settled || _abandoned) return; + _abandoned = true; + if (_result is not null) { _settled = true; clean = _result; } + } + try { _stop.Cancel(); } catch (Exception) { } + if (clean is not null) _ = CleanupAsync(clean); + } + + private async Task CleanupAsync(AcquisitionSubscriptionResult result) + { + try + { + if (result.Handle is not null) + await ((IDriverCapabilityInvoker)NullDriverCapabilityInvoker.Instance).ExecuteAsync(DriverCapability.Subscribe, "acquisition-cleanup", + async ct => await subscribable.UnsubscribeAsync(result.Handle, ct), CancellationToken.None).ConfigureAwait(false); + reservation.Dispose(); + _finished.TrySetResult(true); + } + catch (Exception) { shared.MarkUncertain(); _finished.TrySetResult(false); /* retain reservation */ } + finally { _stop.Dispose(); } + } + } + + private async Task ApplyAcquisitionDemandAsync(SetDesiredSubscriptions desired, IActorRef replyTo) + { + var failed = new AcquisitionDemandApplied(desired.DesiredRevision, desired.ProducerIncarnation, TimeSpan.Zero, false); + if (_abandonedAcquisition is { } abandoned) + { + if (!abandoned.Finished.IsCompleted) + { + replyTo.Tell(failed with { Busy = true, RetryWhenReady = abandoned.Finished }); + return; + } + if (!abandoned.Finished.IsCompletedSuccessfully || !abandoned.Finished.Result) + { + replyTo.Tell(failed); + return; + } + _abandonedAcquisition = null; + } + if (_desiredAcquisition is { } current && _subscriptionHandle is not null && + Volatile.Read(ref _activeAcquisition) is not null && current.DesiredRevision == desired.DesiredRevision && + current.ProducerIncarnation == desired.ProducerIncarnation && current.PublishingInterval == desired.PublishingInterval && + current.FullReferences.SequenceEqual(desired.FullReferences, StringComparer.Ordinal)) + { + StoreDesiredSubscriptions(desired); + SubscribeDesiredAlarms(); + replyTo.Tell(new AcquisitionDemandApplied(desired.DesiredRevision, desired.ProducerIncarnation, _acquisitionNominal, true)); + return; + } + if (_previousAcquisitionCleanup is { IsCompleted: false } cleanup) + { + replyTo.Tell(failed with { Busy = true, RetryWhenReady = cleanup }); + return; + } + if (_driver is not IAcknowledgedAcquisitionSource source || _driver is not ISubscribable subscribable || + desired.DesiredRevision <= 0 || desired.ProducerIncarnation <= 0 || + _sourceIncarnation != desired.ProducerIncarnation || desired.FullReferences.Count == 0 || + _acquisitionCapacity is null || _activeCapacity?.IsUncertain == true || _previousAcquisitionCleanup is { IsCompleted: false } || + _previousAcquisitionCleanup is { IsCompletedSuccessfully: true, Result: false }) + { + replyTo.Tell(failed); + return; + } + var shared = _activeCapacity; + IDisposable operationReference; + if (shared is null) + { + var reservation = _acquisitionCapacity.TryAcquire(_clusterId, _driverInstanceId, out var ready); + if (reservation is null) + { + replyTo.Tell(ready is null ? failed : failed with { Busy = true, RetryWhenReady = ready }); + return; + } + shared = new SharedAcquisitionReservation(reservation); + operationReference = shared.InitialReference(); + } + else operationReference = shared.Retain(); + + var hadHandler = _dataChangeHandler is not null || _batchChangeHandler is not null; + var previousHandle = _subscriptionHandle; + var fence = new AcquisitionFence(desired.DesiredRevision, desired.ProducerIncarnation); + var permittedReferences = new HashSet(desired.FullReferences, StringComparer.Ordinal); + using var cts = new CancellationTokenSource(_acquisitionTimeout, _acquisitionClock); + var operation = new PendingAcquisition(operationReference, subscribable, shared); + _pendingAcquisition = operation; + Volatile.Write(ref _acquisitionPending, 1); + var started = false; + try + { + AttachDataChangeHandler(subscribable, Self); + CancelSourceBindingRetry(); + var sourceBindingVersion = _sourceBindingVersion; + var sourceBindingNeedsRetry = false; + if (_sourcePublisher is not null) + { + var count = Math.Min(desired.FullReferences.Count, SourceBindingBatchSize); + for (var i = 0; i < count; i++) + sourceBindingNeedsRetry |= !TryEnsureSourceBinding(desired.FullReferences[i], fence.Producer); + sourceBindingNeedsRetry |= count < desired.FullReferences.Count; + } + operation.Start(source, new AcquisitionSubscriptionRequest(desired.FullReferences, + desired.PublishingInterval, fence.Revision, fence.Producer), batch => + { + if (!ReferenceEquals(Volatile.Read(ref _activeAcquisition), fence) || batch is null || + batch.DesiredRevision != fence.Revision || batch.ProducerIncarnation != fence.Producer) return; + foreach (var item in batch.Items) + { + if (!ReferenceEquals(Volatile.Read(ref _activeAcquisition), fence)) return; + if (item is not null && permittedReferences.Contains(item.FullReference) && _sourcePublisher is not null && + _sourcePublisher.TryCaptureDriver(_driverInstanceId, item.FullReference, fence.Producer, out var ticket)) + { + if (item.Snapshot.Value is null && !OpcUaStatus.IsGood(item.Snapshot.StatusCode)) + _sourcePublisher.TryPublishAcquisitionStatus(ticket, item.Snapshot.StatusCode); + else _sourcePublisher.TryPublish(ticket, item.Snapshot); + } + } + }); + started = true; + var installed = await operation.Completion.WaitAsync(cts.Token); + if (installed.Handle is null || installed.DesiredRevision != fence.Revision || + installed.ProducerIncarnation != fence.Producer || installed.NominalSamplingInterval <= TimeSpan.Zero) + { + operation.Abandon(); + _abandonedAcquisition = operation; + if (!hadHandler) DetachDataSubscription(); + replyTo.Tell(failed); + return; + } + var activeReference = _activeCapacityReference is null ? shared.Retain() : null; + if (!operation.TryAdopt(installed)) + { + activeReference?.Dispose(); + replyTo.Tell(failed); + return; + } + if (activeReference is not null) { _activeCapacity = shared; _activeCapacityReference = activeReference; } + _subscriptionHandle = installed.Handle; + Volatile.Write(ref _fenceLegacyHandles, true); + Interlocked.Exchange(ref _legacyAdmission, null)?.Dispose(); + Volatile.Write(ref _activeAcquisition, fence); + Volatile.Write(ref _acquisitionPending, 0); + StoreDesiredSubscriptions(desired); + _desiredAcquisition = desired; + _acquisitionNominal = installed.NominalSamplingInterval; + if (sourceBindingNeedsRetry) + Timers.StartSingleTimer("source-binding-retry", new RetrySourceBindings(desired.FullReferences, + 0, false, 0, sourceBindingVersion, fence.Producer), TimeSpan.FromMilliseconds(250)); + SubscribeDesiredAlarms(); + if (previousHandle is not null && !ReferenceEquals(previousHandle, installed.Handle)) + _previousAcquisitionCleanup = CleanupAcquiredHandleAsync(subscribable, previousHandle, shared.Retain(), shared); + replyTo.Tell(new AcquisitionDemandApplied(fence.Revision, fence.Producer, installed.NominalSamplingInterval, true)); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + if (started) { operation.Abandon(); _abandonedAcquisition = operation; } + else operation.CancelBeforeStart(); + if (!hadHandler) DetachDataSubscription(); + _log.Warning(ex, "DriverInstance {Id}: acquisition demand failed", _driverInstanceId); + replyTo.Tell(failed); + } + finally { _pendingAcquisition = null; Volatile.Write(ref _acquisitionPending, 0); } + } + + private static async Task CleanupAcquiredHandleAsync(ISubscribable subscribable, ISubscriptionHandle handle, + IDisposable reservation, SharedAcquisitionReservation shared) + { + try + { + await ((IDriverCapabilityInvoker)NullDriverCapabilityInvoker.Instance).ExecuteAsync(DriverCapability.Subscribe, "acquisition-cleanup", + async ct => await subscribable.UnsubscribeAsync(handle, ct), CancellationToken.None).ConfigureAwait(false); + reservation.Dispose(); + return true; + } + catch (Exception) { shared.MarkUncertain(); return false; } // retain capacity after an uncertain release + } + private void CancelSourceBindingRetry() { Timers.Cancel("source-binding-retry"); @@ -1846,6 +2407,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers private async Task UnsubscribeAsync() { + if (RetireAcquisitionHandle()) + { + DetachDataSubscription(); + return; + } if (_driver is not ISubscribable subscribable || _subscriptionHandle is null) { DetachDataSubscription(); @@ -1879,10 +2445,28 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers private void DetachSubscription() { CancelSourceBindingRetry(); + RetireAcquisitionHandle(); + Volatile.Write(ref _activeAcquisition, null); DetachDataSubscription(); DetachAlarmSource(); } + private bool RetireAcquisitionHandle() + { + var capacityReference = _activeCapacityReference; + var shared = _activeCapacity; + if (capacityReference is null || shared is null) return false; + _activeCapacityReference = null; + _activeCapacity = null; + var handle = _subscriptionHandle; + _subscriptionHandle = null; + Volatile.Write(ref _activeAcquisition, null); + if (handle is not null && _driver is ISubscribable subscribable) + _previousAcquisitionCleanup = CleanupAcquiredHandleAsync(subscribable, handle, capacityReference, shared); + else capacityReference.Dispose(); + return true; + } + /// Tear down the data-change (per-tag AND batch) handlers + null the data handle, leaving the /// native-alarm handler and handle alone. /// The data Unsubscribe / re-subscribe path used to run the full , @@ -1895,6 +2479,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers /// driver's event would keep Telling a dead actor. private void DetachDataSubscription() { + Volatile.Write(ref _activeAcquisition, null); + Interlocked.Exchange(ref _legacyAdmission, null)?.Dispose(); if (_driver is ISubscribable subscribable && _dataChangeHandler is not null) { subscribable.OnDataChange -= _dataChangeHandler; @@ -2200,15 +2786,20 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers _desiredAlarmRefs = msg.AlarmReferences ?? Array.Empty(); } + private void StoreDisconnectedDesiredSubscriptions(SetDesiredSubscriptions msg) + { + if (msg.RequireAcquisition) + Sender.Tell(new AcquisitionDemandApplied(msg.DesiredRevision, msg.ProducerIncarnation, TimeSpan.Zero, false)); + else StoreDesiredSubscriptions(msg); + } + /// Re-establish the desired subscription after (re)connecting. Self-sends the one-shot /// the Connected behaviour already handles (which drops any prior handle /// first), so values resume streaming after a reconnect or redeploy without host involvement. private void ResubscribeDesired() { - if (_desiredRefs.Count > 0) - { - Self.Tell(new Subscribe(_desiredRefs, _desiredInterval)); - } + if (_desiredAcquisition is { } acquisition) Self.Tell(acquisition); + else if (_desiredRefs.Count > 0) Self.Tell(new Subscribe(_desiredRefs, _desiredInterval)); } /// Forward a per-tag-only driver's data change to the parent for OPC UA publication, as a @@ -2396,6 +2987,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers /// protected override void PostStop() { + _pendingAcquisition?.Abandon(); if (_writeIncarnation is { } writeIncarnation) _writeRouteState?.RetireDriver(_driverInstanceId, writeIncarnation); if (_sourceIncarnation is { } incarnation) _sourcePublisher?.RetireDriver(_driverInstanceId, incarnation); // Archreview 03/S15 — announce comms loss on the way out. Every OTHER route into Reconnecting diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataAgeReadinessCodecTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataAgeReadinessCodecTests.cs new file mode 100644 index 000000000..71ef46b74 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataAgeReadinessCodecTests.cs @@ -0,0 +1,149 @@ +using Google.Protobuf; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using WireReadResult = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.ReadResult; + +namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Phase", "P06"), Trait("Category", "Unit")] +public sealed class GrpcDataAgeReadinessCodecTests +{ + private static readonly ServingIdentity Serving = new("n", "i", "primary", 1, 2); + private static readonly DataItemHandle Handle = new("s", 1, 1, 1); + private static readonly IReadOnlyDictionary Handles = new Dictionary { [1] = Handle }; + + private static DataSubscriptionValues Frame(DataAgeBounds age, DataReadiness readiness) => new("s", 1, 1, false, + new[] { new DataSubscriptionValue(Handle, new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 123, null, null, Serving, 9), age, readiness) }); + + [Fact] + public void Additive_descriptor_fields_lock_numbers_types_and_presence() + { + Check(CapabilitiesResponse.Descriptor.FindFieldByName("subscription_age_readiness"), 11, 8, false); + Check(ValueUpdate.Descriptor.FindFieldByName("origin_age_ticks"), 3, 3, true); + Check(ValueUpdate.Descriptor.FindFieldByName("readiness"), 4, 5, true); + Check(CompactUpdate.Descriptor.FindFieldByName("origin_age_ticks"), 8, 3, true); + Check(CompactUpdate.Descriptor.FindFieldByName("readiness"), 9, 5, true); + for (var i = 1; i <= 7; i++) CompactUpdate.Descriptor.FindFieldByNumber(i).ShouldNotBeNull(); + static void Check(Google.Protobuf.Reflection.FieldDescriptor field, int number, int type, bool optional) + { + field.ShouldNotBeNull(); + field.FieldNumber.ShouldBe(number); + ((int)field.ToProto().Type).ShouldBe(type); + field.ToProto().Proto3Optional.ShouldBe(optional); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Negotiated_frames_preserve_zero_nonzero_unknown_and_original_sample(bool compact) + { + foreach (var ticks in new long?[] { null, 0, 123 }) + { + using var frame = Frame(new DataAgeBounds(ticks is null ? null : TimeSpan.FromTicks(ticks.Value), null), DataReadiness.Ready); + var wire = DataProtoMapper.EncodeValues(frame, compact, subscriptionAgeReadiness: true); + using var decoded = DataProtoMapper.DecodeValues(wire, Handles, 10, 10000, Serving, subscriptionAgeReadiness: true); + var item = decoded.Items.Single(); + item.AgeBounds.Lower.ShouldBe(ticks is null ? null : TimeSpan.FromTicks(ticks.Value)); + item.AgeBounds.Upper.ShouldBeNull(); + item.Readiness.ShouldBe(DataReadiness.Ready); + item.Sample.StatusCode.ShouldBe(123u); + item.Sample.Value.Kind.ShouldBe(DataValueKind.Int32); + item.Sample.Value.GetScalar().ShouldBe(42); + item.Sample.SourceTimestampUtc.ShouldBeNull(); + item.Sample.ServerTimestampUtc.ShouldBeNull(); + item.Sample.Serving.ShouldBe(Serving); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Old_peer_fallback_ignores_extension_and_does_not_infer_readiness(bool compact) + { + using var frame = Frame(new DataAgeBounds(TimeSpan.Zero, null), DataReadiness.Ready); + var wire = DataProtoMapper.EncodeValues(frame, compact, subscriptionAgeReadiness: true); + using var oldPeer = DataProtoMapper.DecodeValues(wire, Handles, 10, 10000, Serving, subscriptionAgeReadiness: false); + oldPeer.Items.Single().AgeBounds.ShouldBe(default(DataAgeBounds)); + oldPeer.Items.Single().Readiness.ShouldBe(DataReadiness.Unspecified); + var legacyWire = DataProtoMapper.EncodeValues(frame, compact, subscriptionAgeReadiness: false); + Should.Throw(() => DataProtoMapper.DecodeValues(legacyWire, Handles, 10, 10000, Serving, subscriptionAgeReadiness: true)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Negative_age_missing_or_invalid_readiness_and_limits_are_rejected(bool compact) + { + using var frame = Frame(new DataAgeBounds(TimeSpan.Zero, null), DataReadiness.Ready); + var wire = DataProtoMapper.EncodeValues(frame, compact, subscriptionAgeReadiness: true); + void Set(long age, int readiness) + { + if (compact) { wire.CompactValues.Items[0].OriginAgeTicks = age; wire.CompactValues.Items[0].Readiness = readiness; } + else { wire.Values.Items[0].OriginAgeTicks = age; wire.Values.Items[0].Readiness = readiness; } + } + Set(-1, (int)DataReadiness.Ready); + Should.Throw(() => DataProtoMapper.DecodeValues(wire, Handles, 10, 10000, Serving, subscriptionAgeReadiness: true)); + foreach (var readiness in new[] { 0, -1, 99 }) + { + Set(0, readiness); + Should.Throw(() => DataProtoMapper.DecodeValues(wire, Handles, 10, 10000, Serving, subscriptionAgeReadiness: true)); + } + Set(0, (int)DataReadiness.Ready); + Should.Throw(() => DataProtoMapper.DecodeValues(wire, Handles, 10, 1, Serving, subscriptionAgeReadiness: true)); + Should.Throw(() => DataProtoMapper.DecodeValues(wire, Handles, 10, 10000, Serving with { Incarnation = "other" }, subscriptionAgeReadiness: true)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Large_payload_still_obeys_owned_decode_budgets(bool compact) + { + using var frame = new DataSubscriptionValues("s", 1, 1, false, new[] { + new DataSubscriptionValue(Handle, new DataSample(DataValue.FromBytes(new byte[32_000]), 0, null, null, Serving, 1), + new DataAgeBounds(TimeSpan.Zero, null), DataReadiness.Ready) }); + var wire = DataProtoMapper.EncodeValues(frame, compact, subscriptionAgeReadiness: true); + wire.CalculateSize().ShouldBeLessThan(100_000); + // Encoded bytes fit, but the conservative decoded ownership estimate does not. + Should.Throw(() => DataProtoMapper.DecodeValues(wire, Handles, 1, 100_000, Serving, subscriptionAgeReadiness: true)); + using var decoded = DataProtoMapper.DecodeValues(wire, Handles, 1, 160_000, Serving, subscriptionAgeReadiness: true); + decoded.Items.Single().Sample.Value.GetBytes().Length.ShouldBe(32_000); + Should.Throw(() => DataProtoMapper.DecodeValues(wire, Handles, 1, 1_000, Serving, subscriptionAgeReadiness: true)); + } + + [Fact] + public void Capability_bit_is_explicit_not_inferred_from_minor_version() + { + var limits = new DataLimits(10, 10, 10000, 10, 1, 10000, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); + var capabilities = new DataCapabilities(1, 1, Serving, DataReadiness.Ready, DataOperations.Subscribe, + new HashSet { DataValueKind.Int32 }, limits, true, 1, "cluster"); + var wire = DataProtoMapper.EncodeCapabilities(capabilities); + DataProtoMapper.DecodeCapabilities(wire).SubscriptionAgeReadiness.ShouldBeFalse(); + wire.SubscriptionAgeReadiness = true; + DataProtoMapper.DecodeCapabilities(wire).SubscriptionAgeReadiness.ShouldBeTrue(); + DataProtoMapper.EncodeCapabilities(capabilities with { SubscriptionAgeReadiness = true }).SubscriptionAgeReadiness.ShouldBeTrue(); + } + + [Fact] + public void Unary_wire_age_is_not_presented_as_exact_receiver_age() + { + var wire = new WireReadResult { CorrelationId = "x", Status = (int)DataItemStatus.Good, Readiness = (int)DataReadiness.Ready, AgeTicks = 5 }; + using var bounded = DataProtoMapper.DecodeReadResult(wire, causalRequestElapsed: TimeSpan.FromTicks(3)); + bounded.Age.ShouldBeNull(); + bounded.AgeBounds.ShouldBe(new DataAgeBounds(TimeSpan.FromTicks(5), TimeSpan.FromTicks(8))); + using var unknownUpper = DataProtoMapper.DecodeReadResult(wire); + unknownUpper.AgeBounds.ShouldBe(new DataAgeBounds(TimeSpan.FromTicks(5), null)); + wire.ClearAgeTicks(); + using var absent = DataProtoMapper.DecodeReadResult(wire, causalRequestElapsed: TimeSpan.Zero); + absent.AgeBounds.ShouldBe(default(DataAgeBounds)); + wire.AgeTicks = -1; + Should.Throw(() => DataProtoMapper.DecodeReadResult(wire)); + wire.AgeTicks = long.MaxValue; + Should.Throw(() => DataProtoMapper.DecodeReadResult(wire, causalRequestElapsed: TimeSpan.FromTicks(1))); + wire.AgeTicks = 0; + Should.Throw(() => DataProtoMapper.DecodeReadResult(wire, causalRequestElapsed: TimeSpan.FromTicks(-1))); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataAgeBoundsTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataAgeBoundsTests.cs new file mode 100644 index 000000000..5a96bdba1 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataAgeBoundsTests.cs @@ -0,0 +1,56 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Phase", "P06"), Trait("Category", "Unit")] +public sealed class GrpcDataAgeBoundsTests +{ + [Fact] + public void Unknown_and_lower_only_ages_never_prove_freshness() + { + var maximum = TimeSpan.FromSeconds(5); + var unknown = default(DataAgeBounds); + unknown.Validate(); + unknown.Lower.ShouldBeNull(); + unknown.Upper.ShouldBeNull(); + unknown.IsFresh(maximum).ShouldBeFalse(); + unknown.IsStale(maximum).ShouldBeFalse(); + var lowerOnly = new DataAgeBounds(TimeSpan.FromSeconds(3), null); + lowerOnly.IsFresh(maximum).ShouldBeFalse(); + lowerOnly.IsStale(maximum).ShouldBeFalse(); + lowerOnly.Advance(TimeSpan.FromSeconds(3)).IsStale(maximum).ShouldBeTrue(); + new DataAgeBounds(null, maximum).IsFresh(maximum).ShouldBeTrue(); + new DataAgeBounds(maximum, null).IsStale(maximum).ShouldBeFalse(); + } + + [Fact] + public void Bounds_validate_and_advance_with_checked_arithmetic() + { + var bounds = new DataAgeBounds(TimeSpan.Zero, TimeSpan.FromTicks(4)); + bounds.Validate(); + bounds.Advance(TimeSpan.FromTicks(2)).ShouldBe(new DataAgeBounds(TimeSpan.FromTicks(2), TimeSpan.FromTicks(6))); + default(DataAgeBounds).Advance(TimeSpan.FromSeconds(1)).ShouldBe(default(DataAgeBounds)); + Should.Throw(() => new DataAgeBounds(TimeSpan.FromTicks(-1), null).Validate()); + Should.Throw(() => new DataAgeBounds(null, TimeSpan.FromTicks(-1)).Validate()); + Should.Throw(() => new DataAgeBounds(TimeSpan.FromTicks(2), TimeSpan.FromTicks(1)).Validate()); + Should.Throw(() => bounds.Advance(TimeSpan.FromTicks(-1))); + Should.Throw(() => new DataAgeBounds(TimeSpan.MaxValue, null).Advance(TimeSpan.FromTicks(1))); + Should.Throw(() => bounds.IsFresh(TimeSpan.FromTicks(-1))); + Should.Throw(() => bounds.IsStale(TimeSpan.FromTicks(-1))); + } + + [Fact] + public void Added_contract_fields_have_compatible_unknown_defaults() + { + using var value = new DataSubscriptionValues("s", 1, 1, true, new[] { + new DataSubscriptionValue(new DataItemHandle("s", 1, 1, 1), + new DataSample(DataValue.Null(), 0, null, null, new ServingIdentity("n", "i", "primary", 1, 1), 1)) }); + value.Items[0].AgeBounds.ShouldBe(default(DataAgeBounds)); + value.Items[0].Readiness.ShouldBe(DataReadiness.Unspecified); + using var read = new ReadResult("id", DataItemStatus.Good, DataReadiness.Ready, null, null, null); + read.AgeBounds.ShouldBe(default(DataAgeBounds)); + typeof(IDataSubscription).IsAssignableFrom(typeof(IDataSubscriptionTransport)).ShouldBeTrue(); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataSubscriptionFrameOwnershipTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataSubscriptionFrameOwnershipTests.cs new file mode 100644 index 000000000..ebcdd5256 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataSubscriptionFrameOwnershipTests.cs @@ -0,0 +1,53 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")] +public sealed class GrpcDataSubscriptionFrameOwnershipTests +{ + [Fact] + public void Frame_owns_its_resource_lease_until_disposed_and_releases_it_once() + { + var lease = new CountingLease(); + var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 1), 0, null, null, + new ServingIdentity("node", "incarnation", "Primary", 1, 1), 1); + var frame = new DataSubscriptionValues("stream", 1, 1, true, + [new(new DataItemHandle("stream", 1, 1, 1), sample)], ResourceLease: lease); + lease.Disposals.ShouldBe(0); + sample.Value.GetScalar().ShouldBe(1); + frame.Dispose(); + frame.Dispose(); + lease.Disposals.ShouldBe(1); + Should.Throw(() => sample.Value.GetScalar()); + } + + [Fact] + public void Existing_constructor_remains_usable_without_a_resource_lease() + { + using var frame = new DataSubscriptionValues("stream", 1, 1, false, []); + frame.ResourceLease.ShouldBeNull(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Record_copy_is_rejected_without_disposing_or_aliasing_the_original(bool leased) + { + var lease = new CountingLease(); + var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 5), 0, null, null, + new ServingIdentity("node", "incarnation", "Primary", 1, 1), 1); + using var original = new DataSubscriptionValues("stream", 1, 1, false, + [new(new DataItemHandle("stream", 1, 1, 1), sample)], ResourceLease: leased ? lease : null); + Should.Throw(() => original with { Sequence = 2 }); + lease.Disposals.ShouldBe(0); + sample.Value.GetScalar().ShouldBe(5); + } + + private sealed class CountingLease : IDisposable + { + internal int Disposals; + public void Dispose() => Interlocked.Increment(ref Disposals); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/PollGroupEngineAcquisitionTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/PollGroupEngineAcquisitionTests.cs new file mode 100644 index 000000000..76d2e5684 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/PollGroupEngineAcquisitionTests.cs @@ -0,0 +1,104 @@ +using System.Collections.Concurrent; +using System.Threading.Channels; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests; + +[Trait("Feature", "GrpcData")] +[Trait("Phase", "P06")] +[Trait("Category", "Unit")] +public sealed class PollGroupEngineAcquisitionTests +{ + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(5); + private static DataValueSnapshot Snapshot(int value) => new(value, 0, DateTime.UtcNow, DateTime.UtcNow); + + [Fact] + public async Task Every_completed_read_is_reported_before_legacy_changes_even_when_values_are_unchanged() + { + var releases = Channel.CreateUnbounded(); + var entered = Channel.CreateUnbounded(); + var raw = Channel.CreateUnbounded(); + var legacy = new ConcurrentQueue(); + var order = new ConcurrentQueue(); + await using var engine = new PollGroupEngine(async (_, ct) => + { + entered.Writer.TryWrite(true); + return [Snapshot(await releases.Reader.ReadAsync(ct))]; + }, (_, _, s) => { legacy.Enqueue((int)s.Value!); order.Enqueue("legacy"); }, minInterval: TimeSpan.Zero); + + var handle = engine.Subscribe(["tag"], TimeSpan.Zero, items => + { + order.Enqueue("raw"); + raw.Writer.TryWrite((int)items.Single().Snapshot.Value!); + }); + for (var i = 0; i < 3; i++) + { + await entered.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(Timeout, TestContext.Current.CancellationToken); + releases.Writer.TryWrite(100); + (await raw.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(Timeout, TestContext.Current.CancellationToken)).ShouldBe(100); + } + await entered.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(Timeout, TestContext.Current.CancellationToken); + (await engine.UnsubscribeAsync(handle)).ShouldBeTrue(); + legacy.ToArray().ShouldBe([100]); + order.ToArray().ShouldBe(["raw", "legacy", "raw", "raw"]); + } + + [Fact] + public async Task Synchronously_completed_first_read_has_callback_installed_before_loop_launch() + { + var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await using var engine = new PollGroupEngine( + (_, _) => Task.FromResult>([Snapshot(17)]), + (_, _, _) => { }, minInterval: TimeSpan.FromHours(1)); + var handle = engine.Subscribe(["tag"], TimeSpan.FromHours(1), items => received.TrySetResult((int)items.Single().Snapshot.Value!)); + (await received.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken)).ShouldBe(17); + await engine.UnsubscribeAsync(handle); + } + + [Fact] + public async Task Failed_and_canceled_reads_do_not_fabricate_batches_and_unsubscribe_drains() + { + var entered = Channel.CreateUnbounded(); + var raw = new ConcurrentQueue>(); + var errors = Channel.CreateUnbounded(); + var calls = 0; + await using var engine = new PollGroupEngine(async (_, ct) => + { + var call = Interlocked.Increment(ref calls); + entered.Writer.TryWrite(call); + if (call == 1) throw new InvalidOperationException("read failed"); + await Task.Delay(System.Threading.Timeout.InfiniteTimeSpan, ct); + return [Snapshot(1)]; + }, (_, _, _) => { }, minInterval: TimeSpan.Zero, onError: ex => errors.Writer.TryWrite(ex)); + var handle = engine.Subscribe(["tag"], TimeSpan.Zero, items => raw.Enqueue(items)); + (await errors.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(Timeout, TestContext.Current.CancellationToken)).ShouldBeOfType(); + (await entered.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(Timeout, TestContext.Current.CancellationToken)).ShouldBe(1); + (await entered.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(Timeout, TestContext.Current.CancellationToken)).ShouldBe(2); + (await engine.UnsubscribeAsync(handle)).ShouldBeTrue(); + raw.ShouldBeEmpty(); + engine.ActiveSubscriptionCount.ShouldBe(0); + } + + [Fact] + public async Task Throwing_acquisition_callback_does_not_suppress_legacy_or_stop_later_reads() + { + var raw = Channel.CreateUnbounded(); + var legacy = Channel.CreateUnbounded(); + var count = 0; + await using var engine = new PollGroupEngine( + (_, _) => Task.FromResult>([Snapshot(Interlocked.Increment(ref count))]), + (_, _, s) => legacy.Writer.TryWrite((int)s.Value!), minInterval: TimeSpan.Zero); + var handle = engine.Subscribe(["tag"], TimeSpan.Zero, items => + { + raw.Writer.TryWrite((int)items.Single().Snapshot.Value!); + throw new InvalidOperationException("bad consumer"); + }); + (await raw.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(Timeout, TestContext.Current.CancellationToken)).ShouldBe(1); + (await legacy.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(Timeout, TestContext.Current.CancellationToken)).ShouldBe(1); + (await raw.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(Timeout, TestContext.Current.CancellationToken)).ShouldBe(2); + (await legacy.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(Timeout, TestContext.Current.CancellationToken)).ShouldBe(2); + await engine.UnsubscribeAsync(handle); + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/GrpcDataModbusAcquisitionTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/GrpcDataModbusAcquisitionTests.cs new file mode 100644 index 000000000..ab00e26b8 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/GrpcDataModbusAcquisitionTests.cs @@ -0,0 +1,140 @@ +using System.Collections.Concurrent; +using System.Threading.Channels; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests; + +[Trait("Feature", "GrpcData")] +[Trait("Phase", "P06")] +[Trait("Category", "Unit")] +public sealed class GrpcDataModbusAcquisitionTests +{ + private static readonly TimeSpan Wait = TimeSpan.FromSeconds(5); + + private sealed class GatedTransport : IModbusTransport + { + public readonly Channel> Reads = Channel.CreateUnbounded>(); + public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask; + public async Task SendAsync(byte unitId, byte[] pdu, CancellationToken ct) + { + pdu[0].ShouldBe((byte)3); + var response = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Reads.Writer.TryWrite(response); + var value = await response.Task.WaitAsync(ct); + return [3, 2, (byte)(value >> 8), (byte)value]; + } + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + + private static async Task CreateAsync(GatedTransport transport) + { + var driver = new ModbusDriver(new ModbusDriverOptions + { + Host = "fake", Probe = new ModbusProbeOptions { Enabled = false }, + RawTags = ModbusRawTags.Entries([new ModbusTagDefinition("Temp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, Deadband: 5)]), + }, "acquisition", _ => transport); + await driver.InitializeAsync("{}", TestContext.Current.CancellationToken); + return driver; + } + + private static Task> NextRead(GatedTransport transport) => transport.Reads.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(Wait, TestContext.Current.CancellationToken); + + [Fact] + public async Task Raw_reads_include_unchanged_and_deadband_suppressed_values_with_exact_acknowledged_fence() + { + var transport = new GatedTransport(); + await using var driver = await CreateAsync(transport); + var source = ((object)driver).ShouldBeAssignableTo(); + var raw = Channel.CreateUnbounded(); + var legacy = new ConcurrentQueue(); + var legacyBatches = new ConcurrentQueue(); + driver.OnDataChange += (_, e) => legacy.Enqueue(e); + ((IBatchSubscribable)driver).OnDataChangeBatch += (_, e) => legacyBatches.Enqueue(e); + + var ack = await source.SubscribeAcquisitionAsync(new(["Temp"], TimeSpan.FromMilliseconds(1), 42, 73), + batch => raw.Writer.TryWrite(batch), TestContext.Current.CancellationToken); + ack.NominalSamplingInterval.ShouldBe(TimeSpan.FromMilliseconds(100)); + ack.DesiredRevision.ShouldBe(42); + ack.ProducerIncarnation.ShouldBe(73); + foreach (var value in new ushort[] { 100, 102, 102 }) + { + (await NextRead(transport)).SetResult(value); + var batch = await raw.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(Wait, TestContext.Current.CancellationToken); + batch.DesiredRevision.ShouldBe(42); + batch.ProducerIncarnation.ShouldBe(73); + batch.Items.Single().FullReference.ShouldBe("Temp"); + batch.Items.Single().Snapshot.Value.ShouldBe((short)value); + batch.Items.Single().Snapshot.StatusCode.ShouldBe(0u); + } + // Entering the next transport call proves the previous cycle's legacy callbacks have finished. + await NextRead(transport); + await driver.UnsubscribeAsync(ack.Handle, CancellationToken.None); + legacy.Count.ShouldBe(1); + legacyBatches.Count.ShouldBe(1); + legacy.Single().Snapshot.Value.ShouldBe((short)100); + raw.Reader.TryRead(out _).ShouldBeFalse(); + } + + [Fact] + public async Task Transport_failure_produces_bad_status_without_a_fresh_source_timestamp() + { + var transport = new GatedTransport(); + await using var driver = await CreateAsync(transport); + var source = ((object)driver).ShouldBeAssignableTo(); + var raw = Channel.CreateUnbounded(); + var ack = await source.SubscribeAcquisitionAsync(new(["Temp"], TimeSpan.FromMilliseconds(250), 1, 2), + batch => raw.Writer.TryWrite(batch), TestContext.Current.CancellationToken); + ack.NominalSamplingInterval.ShouldBe(TimeSpan.FromMilliseconds(250)); + (await NextRead(transport)).SetException(new IOException("transport failed")); + var snapshot = (await raw.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(Wait, TestContext.Current.CancellationToken)).Items.Single().Snapshot; + snapshot.StatusCode.ShouldNotBe(0u); + snapshot.Value.ShouldBeNull(); + snapshot.SourceTimestampUtc.ShouldBeNull(); + await NextRead(transport); + await driver.UnsubscribeAsync(ack.Handle, CancellationToken.None); + raw.Reader.TryRead(out _).ShouldBeFalse(); + } + + [Fact] + public async Task Pre_canceled_and_invalid_requests_never_start_a_physical_read() + { + var transport = new GatedTransport(); + await using var driver = await CreateAsync(transport); + var source = ((object)driver).ShouldBeAssignableTo(); + using var canceled = new CancellationTokenSource(); + canceled.Cancel(); + await Should.ThrowAsync(() => source.SubscribeAcquisitionAsync( + new(["Temp"], TimeSpan.FromMilliseconds(100), 1, 1), _ => { }, canceled.Token)); + await Should.ThrowAsync(() => source.SubscribeAcquisitionAsync( + new([], TimeSpan.FromMilliseconds(100), 1, 1), _ => { }, CancellationToken.None)); + await Should.ThrowAsync(() => source.SubscribeAcquisitionAsync( + new(["Temp"], TimeSpan.FromMilliseconds(-1), 1, 1), _ => { }, CancellationToken.None)); + await Should.ThrowAsync(() => source.SubscribeAcquisitionAsync( + new(["Temp"], TimeSpan.FromMilliseconds(100), 0, 1), _ => { }, CancellationToken.None)); + await Should.ThrowAsync(() => source.SubscribeAcquisitionAsync( + new(["Temp"], TimeSpan.FromMilliseconds(100), 1, 0), _ => { }, CancellationToken.None)); + transport.Reads.Reader.TryRead(out _).ShouldBeFalse(); + } + + [Fact] + public async Task Unsupported_timer_interval_is_rejected_before_read_and_supported_boundary_is_acknowledged() + { + var transport = new GatedTransport(); + await using var driver = await CreateAsync(transport); + var source = ((object)driver).ShouldBeAssignableTo(); + var maximum = TimeSpan.FromMilliseconds(uint.MaxValue - 1d); + + await Should.ThrowAsync(() => source.SubscribeAcquisitionAsync( + new(["Temp"], maximum + TimeSpan.FromMilliseconds(1), 1, 1), _ => { }, TestContext.Current.CancellationToken)); + await Should.ThrowAsync(() => source.SubscribeAcquisitionAsync( + new(["Temp"], TimeSpan.MaxValue, 1, 1), _ => { }, TestContext.Current.CancellationToken)); + transport.Reads.Reader.TryRead(out _).ShouldBeFalse(); + + var ack = await source.SubscribeAcquisitionAsync(new(["Temp"], maximum, 1, 1), _ => { }, TestContext.Current.CancellationToken); + ack.NominalSamplingInterval.ShouldBe(maximum); + await NextRead(transport); + await driver.UnsubscribeAsync(ack.Handle, CancellationToken.None); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeliveryFairnessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeliveryFairnessTests.cs new file mode 100644 index 000000000..73f984897 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeliveryFairnessTests.cs @@ -0,0 +1,115 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")] +public sealed class GrpcDataDeliveryFairnessTests +{ + [Fact(Timeout = 30000)] + public async Task A_quota_blocked_waiter_does_not_strand_another_principal_with_a_free_global_slot() + { + var capacity = new SubscriptionTransportCapacity(2, 1, 1_000); + capacity.TryReserve("a", 100, out var active).ShouldBeTrue(); + using var cancellation = new CancellationTokenSource(); + var blockedA = capacity.ReserveAsync("a", 100, cancellation.Token).AsTask(); + blockedA.IsCompleted.ShouldBeFalse(); + var waitingB = capacity.ReserveAsync("b", 100, TestContext.Current.CancellationToken).AsTask(); + try + { + var grantedB = await waitingB.WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken); + grantedB.ShouldNotBeNull(); + blockedA.IsCompleted.ShouldBeFalse(); + grantedB.Dispose(); + } + finally + { + cancellation.Cancel(); active!.Dispose(); + try { await blockedA; } catch (OperationCanceledException) { } + } + } + + [Fact] + public void Command_rate_limit_is_shared_by_case_insensitive_principal_and_uses_monotonic_time() + { + var clock = new ManualTimeProvider(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000, clock: clock, maxCommandsPerSecond: 2); + capacity.TryAdmitCommand("peer").ShouldBeTrue(); + capacity.TryAdmitCommand("PEER").ShouldBeTrue(); + capacity.TryAdmitCommand("peer").ShouldBeFalse(); + capacity.TryAdmitCommand("other").ShouldBeTrue(); + clock.Advance(TimeSpan.FromSeconds(1)); + capacity.TryAdmitCommand("peer").ShouldBeTrue(); + } + + [Fact] + public async Task A_waiting_principal_gets_the_next_physical_writer_slot_before_a_hot_stream_reacquires_it() + { + var capacity = new SubscriptionTransportCapacity(1, 1, 1_000); + capacity.TryReserve("busy", 500, out var busy).ShouldBeTrue(); + var quiet = capacity.ReserveAsync("quiet", 500, TestContext.Current.CancellationToken).AsTask(); + quiet.IsCompleted.ShouldBeFalse(); + busy!.Dispose(); + capacity.TryReserve("busy", 500, out _).ShouldBeFalse(); + var granted = await quiet.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + granted.ShouldNotBeNull(); + granted.Dispose(); + capacity.ActiveOperations.ShouldBe(0); + } + + [Fact] + public async Task Canceling_a_waiter_removes_it_without_consuming_a_future_slot() + { + var capacity = new SubscriptionTransportCapacity(1, 1, 1_000); + capacity.TryReserve("busy", 500, out var busy).ShouldBeTrue(); + using var cancellation = new CancellationTokenSource(); + var waiting = capacity.ReserveAsync("quiet", 500, cancellation.Token).AsTask(); + cancellation.Cancel(); + await Should.ThrowAsync(async () => await waiting); + busy!.Dispose(); + capacity.TryReserve("next", 500, out var next).ShouldBeTrue(); + next!.Dispose(); + } + + [Fact] + public void Changing_hot_source_during_traversal_does_not_restart_or_starve_other_work() + { + var scheduler = new DeliveryScheduler(maxSources: 4, maxInterests: 16); + var hot = HubTest.Ticket("driver", "hot").Key; + var quiet = HubTest.Ticket("driver", "quiet").Key; + for (var i = 0; i < 8; i++) scheduler.TryRegister(hot, i + 1).ShouldBeTrue(); + scheduler.TryRegister(quiet, 100).ShouldBeTrue(); + scheduler.TryMarkDirty(hot, 1).ShouldBeTrue(); + scheduler.TryMarkDirty(quiet, 1).ShouldBeTrue(); + var first = scheduler.TakeSlice(2); + first.Count.ShouldBeLessThanOrEqualTo(2); + scheduler.TryMarkDirty(hot, 2).ShouldBeTrue(); + var seen = first.ToList(); + for (var i = 0; i < 16; i++) + { + var slice = scheduler.TakeSlice(2); + slice.Count.ShouldBeLessThanOrEqualTo(2); + seen.AddRange(slice); + } + seen.ShouldContain(x => x.Source == quiet && x.InterestId == 100); + foreach (var interest in Enumerable.Range(1, 8)) + seen.ShouldContain(x => x.Source == hot && x.InterestId == interest); + seen.ShouldContain(x => x.Source == hot && x.Generation == 2); + } + + [Fact] + public void Interest_and_dirty_capacity_are_enforced_before_allocating_more_work() + { + var scheduler = new DeliveryScheduler(maxSources: 1, maxInterests: 1); + var first = HubTest.Ticket("driver", "first").Key; + var second = HubTest.Ticket("driver", "second").Key; + scheduler.TryRegister(first, 1).ShouldBeTrue(); + scheduler.TryRegister(first, 2).ShouldBeFalse(); + scheduler.TryRegister(second, 3).ShouldBeFalse(); + scheduler.TryMarkDirty(first, 1).ShouldBeTrue(); + scheduler.TryMarkDirty(first, 2).ShouldBeTrue(); + scheduler.TryMarkDirty(second, 1).ShouldBeFalse(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDemandSharingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDemandSharingTests.cs new file mode 100644 index 000000000..71fbbd569 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDemandSharingTests.cs @@ -0,0 +1,146 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")] +public sealed class GrpcDataDemandSharingTests +{ + private static readonly DataSubscriptionSettings Slow = new(TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2), + DataChangeTrigger.StatusValue, null); + private static readonly DataSubscriptionSettings Fast = Slow with { SamplingInterval = TimeSpan.FromMilliseconds(100) }; + + [Fact] + public void Ref_counts_are_shared_only_within_the_full_upstream_authority_key() + { + var registry = new UpstreamDemandRegistry(maxKeys: 8, maxInterests: 8); + var key = Key(); + registry.TryAdd(key, Slow, out var first).ShouldBeTrue(); + registry.TryAdd(key, Fast, out var second).ShouldBeTrue(); + var otherPrincipal = key with { PrincipalId = "other" }; + registry.TryAdd(otherPrincipal, Slow, out var isolated).ShouldBeTrue(); + registry.GetState(key)!.InterestCount.ShouldBe(2); + registry.GetState(otherPrincipal)!.InterestCount.ShouldBe(1); + registry.GetState(key)!.Desired.SamplingInterval.ShouldBe(Fast.SamplingInterval); + second!.Dispose(); + registry.GetState(key)!.InterestCount.ShouldBe(1); + first!.Dispose(); + registry.GetState(key).ShouldBeNull(); + registry.GetState(otherPrincipal)!.InterestCount.ShouldBe(1); + isolated!.Dispose(); + registry.GetState(otherPrincipal).ShouldBeNull(); + } + + [Fact] + public void Principal_case_variants_share_the_same_demand_and_limits() + { + var registry = new UpstreamDemandRegistry(maxKeys: 1, maxInterests: 2); + var key = Key(); + registry.TryAdd(key, Slow, out var first).ShouldBeTrue(); + registry.TryAdd(key with { PrincipalId = "PRINCIPAL" }, Fast, out var second).ShouldBeTrue(); + registry.GetState(key)!.InterestCount.ShouldBe(2); + registry.GetState(key with { PrincipalId = "PRINCIPAL" })!.Desired.SamplingInterval.ShouldBe(Fast.SamplingInterval); + first!.Dispose(); second!.Dispose(); + } + + [Fact] + public void Adding_and_removing_interests_does_not_copy_the_whole_existing_registration_set() + { + var registry = new UpstreamDemandRegistry(maxKeys: 1, maxInterests: 2048); + var key = Key(); + var leases = new List(1100); + for (var i = 0; i < 1024; i++) + { + registry.TryAdd(key, Slow, out var lease).ShouldBeTrue(); + leases.Add(lease!); + } + var beforeAdd = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < 64; i++) + { + if (!registry.TryAdd(key, Slow, out var lease)) throw new InvalidOperationException(); + leases.Add(lease!); + } + var addBytes = GC.GetAllocatedBytesForCurrentThread() - beforeAdd; + var beforeRemove = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 1024; i < 1088; i++) leases[i].Dispose(); + var removeBytes = GC.GetAllocatedBytesForCurrentThread() - beforeRemove; + addBytes.ShouldBeLessThan(128 * 1024, "an add must not copy all 1,000 existing interests"); + removeBytes.ShouldBeLessThan(128 * 1024, "a remove must not copy all 1,000 existing interests"); + foreach (var lease in leases) lease.Dispose(); + } + + [Fact] + public void Removing_interests_recomputes_each_extreme_only_after_its_last_holder_leaves() + { + var registry = new UpstreamDemandRegistry(maxKeys: 1, maxInterests: 4); + var key = Key(); + var first = new DataSubscriptionSettings(TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(100), + DataChangeTrigger.Status, 5); + var second = new DataSubscriptionSettings(TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(200), + DataChangeTrigger.StatusValueTimestamp, 10); + var third = new DataSubscriptionSettings(TimeSpan.FromMilliseconds(30), TimeSpan.FromMilliseconds(100), + DataChangeTrigger.StatusValueTimestamp, null); + registry.TryAdd(key, first, out var firstLease).ShouldBeTrue(); + registry.TryAdd(key, second, out var secondLease).ShouldBeTrue(); + registry.TryAdd(key, third, out var thirdLease).ShouldBeTrue(); + var combined = registry.GetState(key)!; + combined.Desired.ShouldBe(new DataSubscriptionSettings(TimeSpan.FromMilliseconds(10), + TimeSpan.FromMilliseconds(100), DataChangeTrigger.StatusValueTimestamp, null)); + + secondLease!.Dispose(); + var afterSecond = registry.GetState(key)!; + afterSecond.Desired.ShouldBe(combined.Desired); + afterSecond.DesiredRevision.ShouldBe(combined.DesiredRevision); + + firstLease!.Dispose(); + var afterFirst = registry.GetState(key)!; + afterFirst.Desired.ShouldBe(third with { Deadband = null }); + afterFirst.DesiredRevision.ShouldBeGreaterThan(afterSecond.DesiredRevision); + thirdLease!.Dispose(); + registry.GetState(key).ShouldBeNull(); + } + + [Fact] + public void Removing_the_last_strong_trigger_reduces_the_shared_trigger() + { + var registry = new UpstreamDemandRegistry(maxKeys: 1, maxInterests: 3); + var key = Key(); + var low = Slow with { Trigger = DataChangeTrigger.Status }; + var high = Slow with { Trigger = DataChangeTrigger.StatusValueTimestamp }; + registry.TryAdd(key, low, out var lowLease).ShouldBeTrue(); + registry.TryAdd(key, Slow, out var middleLease).ShouldBeTrue(); + registry.TryAdd(key, high, out var highLease).ShouldBeTrue(); + var strongRevision = registry.GetState(key)!.DesiredRevision; + + highLease!.Dispose(); + registry.GetState(key)!.Desired.Trigger.ShouldBe(DataChangeTrigger.StatusValue); + registry.GetState(key)!.DesiredRevision.ShouldBeGreaterThan(strongRevision); + middleLease!.Dispose(); + registry.GetState(key)!.Desired.Trigger.ShouldBe(DataChangeTrigger.Status); + lowLease!.Dispose(); + } + + [Fact] + public void A_late_physical_ack_cannot_claim_a_newer_stronger_demand_is_applied() + { + var registry = new UpstreamDemandRegistry(maxKeys: 4, maxInterests: 4); + var key = Key(); + registry.TryAdd(key, Slow, out var slow).ShouldBeTrue(); + var oldRevision = registry.GetState(key)!.DesiredRevision; + registry.TryAdd(key, Fast, out var fast).ShouldBeTrue(); + var current = registry.GetState(key)!; + current.DesiredRevision.ShouldBeGreaterThan(oldRevision); + registry.TryAcknowledge(key, oldRevision, Slow, 1).ShouldBeFalse(); + registry.GetState(key)!.AppliedRevision.ShouldNotBe(current.DesiredRevision); + registry.TryAcknowledge(key, current.DesiredRevision, Fast, 2).ShouldBeTrue(); + registry.GetState(key)!.AppliedRevision.ShouldBe(current.DesiredRevision); + fast!.Dispose(); + slow!.Dispose(); + } + + private static DemandSharingKey Key() => new(HubTest.Ticket("driver", "tag").Key, + new DataTarget(DataTargetMode.Node, "cluster", "node-a"), DataConsistency.Primary, + "principal", "export", 1, 1); +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFilterAggregationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFilterAggregationTests.cs new file mode 100644 index 000000000..3f7240916 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFilterAggregationTests.cs @@ -0,0 +1,99 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")] +public sealed class GrpcDataFilterAggregationTests +{ + [Fact] + public void Shared_upstream_is_a_superset_of_fast_filtered_and_slow_unfiltered_consumers() + { + var fast = new DataSubscriptionSettings(TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(200), + DataChangeTrigger.StatusValueTimestamp, 10); + var slow = new DataSubscriptionSettings(TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3), + DataChangeTrigger.StatusValue, null); + var aggregate = SubscriptionSettingsAggregator.Aggregate([fast, slow]); + aggregate.SamplingInterval.ShouldBe(fast.SamplingInterval); + aggregate.PublishingInterval.ShouldBe(fast.PublishingInterval); + aggregate.Trigger.ShouldBe(DataChangeTrigger.StatusValueTimestamp); + aggregate.Deadband.ShouldBeNull(); + } + + [Fact] + public void Committed_baselines_are_independent_and_quality_changes_bypass_deadband() + { + var filtered = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, 10); + var unfiltered = filtered with { Deadband = null }; + using var narrow = new ClientFilterState(); + using var broad = new ClientFilterState(); + using var initial = Sample(1, 100, 0); + using var small = Sample(2, 105, 0); + using var bad = Sample(3, 105, 0x80000000u); + narrow.ShouldDeliver(initial, filtered).ShouldBeTrue(); + broad.ShouldDeliver(initial, unfiltered).ShouldBeTrue(); + narrow.Commit(initial); + broad.Commit(initial); + narrow.ShouldDeliver(small, filtered).ShouldBeFalse(); + broad.ShouldDeliver(small, unfiltered).ShouldBeTrue(); + broad.Commit(small); + narrow.ShouldDeliver(bad, filtered).ShouldBeTrue(); + broad.ShouldDeliver(bad, unfiltered).ShouldBeTrue(); + } + + [Fact] + public void Considering_a_candidate_does_not_advance_the_committed_baseline() + { + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, 10); + using var state = new ClientFilterState(); + using var initial = Sample(1, 100, 0); + using var candidate = Sample(2, 111, 0); + using var later = Sample(3, 95, 0); + state.Commit(initial); + state.ShouldDeliver(candidate, settings).ShouldBeTrue(); + state.ShouldDeliver(later, settings).ShouldBeFalse("the unsent candidate is not a delivered baseline"); + state.Commit(candidate); + state.ShouldDeliver(later, settings).ShouldBeTrue(); + using var farther = Sample(4, 99, 0); + state.ShouldDeliver(farther, settings).ShouldBeTrue(); + } + + [Fact] + public void Comparing_large_equal_byte_values_does_not_copy_payloads_per_delivery() + { + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + var bytes = Enumerable.Range(0, 1024 * 1024).Select(i => (byte)i).ToArray(); + using var first = new DataSample(DataValue.FromBytes(bytes), 0, null, null, HubTest.Serving, 1); + using var second = new DataSample(DataValue.FromBytes(bytes), 0, null, null, HubTest.Serving, 2); + using var state = new ClientFilterState(); + state.Commit(first); + state.ShouldDeliver(second, settings).ShouldBeFalse(); // warm JIT before measuring + var before = GC.GetAllocatedBytesForCurrentThread(); + var deliver = state.ShouldDeliver(second, settings); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + deliver.ShouldBeFalse(); + allocated.ShouldBeLessThan(64 * 1024, "comparing a 1 MiB value should not copy either payload"); + } + + [Fact] + public void Comparing_large_equal_arrays_does_not_copy_elements_per_delivery() + { + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + var elements = Enumerable.Range(0, 100_000).Select(i => (object)i).ToArray(); + using var first = new DataSample(DataValue.FromArray(DataValueKind.Int32, elements, [elements.Length]), 0, null, null, HubTest.Serving, 1); + using var second = new DataSample(DataValue.FromArray(DataValueKind.Int32, elements, [elements.Length]), 0, null, null, HubTest.Serving, 2); + using var state = new ClientFilterState(); + state.Commit(first); + state.ShouldDeliver(second, settings).ShouldBeFalse(); + var before = GC.GetAllocatedBytesForCurrentThread(); + var deliver = state.ShouldDeliver(second, settings); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + deliver.ShouldBeFalse(); + allocated.ShouldBeLessThan(64 * 1024, "comparing an array should not allocate a copy of its elements"); + } + + private static DataSample Sample(long version, int value, uint status) => + new(DataValue.FromScalar(DataValueKind.Int32, value), status, null, null, HubTest.Serving, version); +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs index 3f35c3e37..9d7244876 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs @@ -107,7 +107,10 @@ internal sealed class LocalDataFixture : IDisposable internal readonly LocalExportCatalog Catalog; internal readonly DataAuthenticatedContext Context; - internal LocalDataFixture(int additionalRawNodes = 0) + internal LocalDataFixture(int additionalRawNodes = 0, + Func? subscriptions = null, + Func? targetSubscriptions = null, + bool advanceAuthority = false) { Hub = HubTest.Create(clock: Clock, bytes: 1_000_000); Hub.TryBind(Ticket).ShouldBeTrue(); @@ -116,6 +119,14 @@ internal sealed class LocalDataFixture : IDisposable [new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.RawFolder, ScopeId = "folder", PermissionFlags = NodePermissions.ReadOnly }], new Dictionary> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] }); + if (advanceAuthority) + { + Authority.Apply("cluster", "second", [key], + [new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.RawFolder, + ScopeId = "folder", PermissionFlags = NodePermissions.ReadOnly }], + new Dictionary> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] }); + Serving = Serving with { AuthorityEpoch = Authority.Current.GenerationId }; + } var epoch = Activation.Begin("first"); Activation.AuthorityInstalled(epoch, Authority.Current.GenerationId); Activation.Complete(epoch, true); @@ -140,7 +151,8 @@ internal sealed class LocalDataFixture : IDisposable var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1)); var capabilities = new DataCapabilitiesProvider("cluster", () => Serving, () => Catalog.IsActive, limits); Services = new LocalDataServices(() => Catalog, Hub, new DataOperationPolicy(Authority, - new TriePermissionEvaluator(Authority.Tries, Clock), Clock), capabilities, Clock); + new TriePermissionEvaluator(Authority.Tries, Clock), Clock), capabilities, Clock, subscriptions: subscriptions, + targetSubscriptions: targetSubscriptions); } internal IDataConnection Connection() => Services.Create(Context, new(DataTargetMode.Node, "cluster", "node-a")); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataRecoveryAdmissionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataRecoveryAdmissionTests.cs new file mode 100644 index 000000000..c39ab11f0 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataRecoveryAdmissionTests.cs @@ -0,0 +1,218 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")] +public sealed class GrpcDataRecoveryAdmissionTests +{ + [Fact(Timeout = 30000)] + public async Task Canceling_unopened_stream_releases_its_slot_without_explicit_disposal() + { + var demand = new DeferredSubscriptionDemand(); + var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + using (var cancellation = new CancellationTokenSource()) + { + await using var firstConnection = fixture.Connection(); + await using var secondConnection = fixture.Connection(); + var first = await firstConnection.SubscribeAsync(cancellation.Token); + try + { + var session = first.ShouldBeOfType(); + cancellation.Cancel(); + await session.Completion.WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken); + await using var replacement = await secondConnection.SubscribeAsync(TestContext.Current.CancellationToken); + } + finally { await first.DisposeAsync(); } + } + } + + [Fact(Timeout = 30000)] + public async Task Unopened_stream_expires_on_a_bounded_handshake_deadline() + { + var demand = new DeferredSubscriptionDemand(); + var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1), + PreOpenTimeout: TimeSpan.FromSeconds(3)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + { + await using var firstConnection = fixture.Connection(); + await using var secondConnection = fixture.Connection(); + var first = await firstConnection.SubscribeAsync(TestContext.Current.CancellationToken); + try + { + var session = first.ShouldBeOfType(); + fixture.Clock.Advance(TimeSpan.FromSeconds(3)); + await session.Completion.WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken); + await using var replacement = await secondConnection.SubscribeAsync(TestContext.Current.CancellationToken); + } + finally { await first.DisposeAsync(); } + } + } + + [Fact(Timeout = 30000)] + public async Task Oversized_ack_timeout_is_rejected_without_poisoning_the_command_id() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + { + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var invalid = new OpenSubscription("s", 1, "same-command", TimeSpan.MaxValue, [], true, + TimeSpan.FromSeconds(30), LocalDataFixture.Budget); + await Should.ThrowAsync(() => subscription.SendAsync(invalid, TestContext.Current.CancellationToken)); + await subscription.SendAsync(invalid with { AcknowledgementTimeout = TimeSpan.FromSeconds(5) }, TestContext.Current.CancellationToken); + await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken) + .GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue(); + reader.Current.ShouldBeOfType().CommandId.ShouldBe("same-command"); + } + } + + [Fact] + public void Expired_snapshot_permit_retains_its_quota_while_a_physical_owner_is_alive() + { + var clock = new ManualTimeProvider(); + var scheduler = new SnapshotAdmissionScheduler(1, 1, 1_000, maxLifetime: TimeSpan.FromSeconds(2), clock: clock); + scheduler.TryAcquire("peer", 1, out var lease, out _).ShouldBeTrue(); + var permit = lease.ShouldBeOfType(); + permit.TryGrow(500).ShouldBeTrue(); + permit.TryRetain(out var physicalOwner).ShouldBeTrue(); + clock.Advance(TimeSpan.FromSeconds(2)); + permit.IsValid.ShouldBeFalse(); + scheduler.TryAcquire("peer", 1, out _, out _).ShouldBeFalse("expired physical ownership remains charged"); + physicalOwner!.Dispose(); + scheduler.TryAcquire("peer", 1, out var next, out _).ShouldBeTrue(); + next!.Dispose(); permit.Dispose(); + } + + [Fact] + public void Snapshot_permits_grow_before_retention_and_respect_global_and_principal_bytes() + { + var scheduler = new SnapshotAdmissionScheduler(4, 2, 1_000, maxPrincipalBytes: 700); + scheduler.TryAcquire("a", 1, out var first, out _).ShouldBeTrue(); + scheduler.TryAcquire("b", 1, out var second, out _).ShouldBeTrue(); + var firstPermit = first.ShouldBeOfType(); + var secondPermit = second.ShouldBeOfType(); + firstPermit.TryGrow(600).ShouldBeTrue(); + firstPermit.TryGrow(100).ShouldBeFalse(); + secondPermit.TryGrow(400).ShouldBeFalse(); + secondPermit.TryGrow(398).ShouldBeTrue(); + firstPermit.Dispose(); secondPermit.Dispose(); + scheduler.TryAcquire("a", 700, out var replacement, out _).ShouldBeTrue(); + replacement!.Dispose(); + } + + [Fact(Timeout = 30000)] + public async Task Stream_open_rejects_old_authority_epoch_while_current_epoch_and_same_key_succeed() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(advanceAuthority: true, targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + { + fixture.Context.AuthorityEpoch.ShouldBe(2); + var target = new DataTarget(DataTargetMode.Node, "cluster", "node-a"); + await using var fresh = fixture.Services.Create(fixture.Context, target); + await using var accepted = await fresh.SubscribeAsync(TestContext.Current.CancellationToken); + var staleContext = fixture.Context with { AuthorityEpoch = 1 }; + await using var stale = fixture.Services.Create(staleContext, target); + await Should.ThrowAsync(() => stale.SubscribeAsync(TestContext.Current.CancellationToken)); + } + } + + [Fact] + public void Snapshot_admission_bounds_principal_bytes_send_rate_lifetime_and_retry_guidance() + { + var clock = new ManualTimeProvider(); + var scheduler = new SnapshotAdmissionScheduler(4, 2, 1_000, maxPrincipalBytes: 700, + globalBytesPerSecond: 100, principalBytesPerSecond: 60, + maxLifetime: TimeSpan.FromSeconds(2), clock: clock); + scheduler.TryAcquire("peer", 600, out var first, out _).ShouldBeTrue(); + scheduler.TryAcquire("PEER", 101, out _, out var quotaRetry).ShouldBeFalse(); + quotaRetry.ShouldBeGreaterThan(TimeSpan.Zero); + scheduler.TryConsume("peer", 60, out _).ShouldBeTrue(); + scheduler.TryConsume("PEER", 1, out var retry).ShouldBeFalse(); + retry.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(1)); + retry.ShouldBeLessThan(TimeSpan.FromSeconds(2)); + scheduler.TryConsume("other", 41, out _).ShouldBeFalse(); + clock.Advance(TimeSpan.FromSeconds(1)); + scheduler.TryConsume("other", 41, out _).ShouldBeTrue(); + clock.Advance(TimeSpan.FromSeconds(1)); + first.ShouldBeOfType().IsValid.ShouldBeFalse(); + scheduler.TryAcquire("PEER", 700, out var afterExpiry, out _).ShouldBeTrue(); + first!.Dispose(); afterExpiry!.Dispose(); + } + + [Fact(Timeout = 30000)] + public async Task Idle_streams_obey_shared_principal_admission_and_disposal_releases_the_slot() + { + var demand = new DeferredSubscriptionDemand(); + var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(subscriptions: context => + new LocalSubscriptionService(fixture!.Services, context, + new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity))) + { + await using var firstConnection = fixture.Connection(); + await using var secondConnection = fixture.Connection(); + var first = await firstConnection.SubscribeAsync(TestContext.Current.CancellationToken); + await Should.ThrowAsync(() => secondConnection.SubscribeAsync(TestContext.Current.CancellationToken)); + await first.DisposeAsync(); + await using var replacement = await secondConnection.SubscribeAsync(TestContext.Current.CancellationToken); + } + } + + [Fact] + public void Transport_capacity_is_shared_across_sessions_and_principals() + { + var capacity = new SubscriptionTransportCapacity(2, 1, 1_000); + capacity.TryReserve("a", 400, out var first).ShouldBeTrue(); + capacity.TryReserve("A", 100, out _).ShouldBeFalse("principal quota is case-insensitive"); + capacity.TryReserve("a", 100, out _).ShouldBeFalse(); + capacity.TryReserve("b", 700, out _).ShouldBeFalse(); + capacity.TryReserve("b", 600, out var second).ShouldBeTrue(); + capacity.TryReserve("c", 1, out _).ShouldBeFalse(); + first!.Dispose(); + first.Dispose(); + capacity.TryReserve("c", 400, out var third).ShouldBeTrue(); + third!.Dispose(); + second!.Dispose(); + capacity.ActiveOperations.ShouldBe(0); + } + + [Fact] + public void Snapshot_capacity_is_global_and_per_principal_and_disposal_releases_it_once() + { + var scheduler = new SnapshotAdmissionScheduler(maxConcurrent: 2, maxPerPrincipal: 1, maxBytes: 1000); + scheduler.TryAcquire("a", 400, out var first).ShouldBeTrue(); + scheduler.TryAcquire("A", 100, out _).ShouldBeFalse("principal quota is case-insensitive"); + scheduler.TryAcquire("a", 100, out _).ShouldBeFalse(); + scheduler.TryAcquire("b", 700, out _).ShouldBeFalse(); + scheduler.TryAcquire("b", 600, out var second).ShouldBeTrue(); + scheduler.TryAcquire("c", 1, out _).ShouldBeFalse(); + first!.Dispose(); + first.Dispose(); + scheduler.TryAcquire("c", 400, out var replacement).ShouldBeTrue(); + replacement!.Dispose(); + second!.Dispose(); + scheduler.TryAcquire("a", 1000, out var last).ShouldBeTrue(); + last!.Dispose(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSnapshotTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSnapshotTests.cs index 4190363b6..c29b39a89 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSnapshotTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSnapshotTests.cs @@ -11,6 +11,446 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; [Trait("Phase", "P04")] public sealed class GrpcDataSnapshotTests { + [Fact] + public async Task Nonblocking_ticket_validation_rejects_old_partition_during_repartition() + { + using var hub = HubTest.Create(partitions: 1); + var ticket = HubTest.Ticket("driver", "routing-gap"); + hub.TryBind(ticket).ShouldBeTrue(); + var epoch = hub.RoutingEpoch; + var cancellationToken = TestContext.Current.CancellationToken; + using var entered = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var holder = Task.Run(() => hub.WithPartitionLockForTest(ticket.Key, () => + { + entered.Set(); + release.Wait(cancellationToken); + }), cancellationToken); + Task? repartition = null; + try + { + entered.Wait(TimeSpan.FromSeconds(5), cancellationToken).ShouldBeTrue(); + repartition = Task.Run(() => hub.Repartition(2), cancellationToken); + SpinWait.SpinUntil(() => + { + cancellationToken.ThrowIfCancellationRequested(); + return hub.RoutingEpoch != epoch; + }, TimeSpan.FromSeconds(5)).ShouldBeTrue(); + var isCurrent = await Task.Run(() => hub.IsTicketCurrentNonBlocking(ticket), cancellationToken) + .WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); + isCurrent.ShouldBeFalse(); + } + finally + { + release.Set(); + await holder.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); + if (repartition is not null) await repartition.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Steady_interest_detects_quiet_source_invalidation_after_snapshot_disposal(bool retireProducer) + { + using var hub = HubTest.Create(partitions: 1); + var ticket = HubTest.Ticket("driver", "quiet-control"); + var producer = new ProducerFence(1); + hub.TryBind(ticket, producer).ShouldBeTrue(); + HubTest.Publish(hub, ticket, 1, 1); + hub.ProcessPending(); + hub.TryCaptureInterestSnapshot([ticket], HubTest.Budget, CancellationToken.None, + out var snapshot, out var interest).ShouldBeTrue(); + using (interest!) + { + snapshot!.Dispose(); + if (retireProducer) producer.Retire(); + else hub.Invalidate(ticket, "source invalidated"); + (interest!.IsReset || !interest.TryReadChanges(1, out _)).ShouldBeTrue(); + } + } + + [Fact] + public void Status_changes_remain_observable_through_steady_interest_history() + { + using var hub = HubTest.Create(partitions: 1); + var ticket = HubTest.Ticket("driver", "status-history"); + HubTest.BindAndPublish(hub, ticket, 1, 1); + hub.ProcessPending(); + hub.TryCaptureInterestSnapshot([ticket], HubTest.Budget, CancellationToken.None, + out var snapshot, out var interest).ShouldBeTrue(); + using (interest!) + { + snapshot!.Dispose(); + hub.TryPublishStatus(ticket, 2, 0x80000000, null, null).ShouldBeTrue(); + hub.ProcessPending(); + interest!.IsReset.ShouldBeFalse(); + interest.TryReadChanges(1, out var changes).ShouldBeTrue(); + changes.ShouldHaveSingleItem().Ticket.ShouldBe(ticket); + } + } + + [Fact] + public void Source_control_and_status_reset_the_snapshot_but_ordinary_values_do_not() + { + using var hub = HubTest.Create(partitions: 1); + var source = HubTest.Ticket("driver", "control"); + HubTest.BindAndPublish(hub, source, 1, 1); + hub.ProcessPending(); + hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var frozen).ShouldBeTrue(); + using (frozen!) + { + HubTest.Publish(hub, source, 2, 2); + hub.ProcessPending(); + frozen!.IsReset.ShouldBeFalse(); + frozen.IsItemCurrent(source).ShouldBeTrue(); + frozen.Items[source].Sample!.Value.GetScalar().ShouldBe(1); + hub.TryPublishStatus(source, 3, 0x80000000, null, null).ShouldBeTrue(); + frozen.IsReset.ShouldBeTrue(); + } + } + + [Fact] + public void Active_partition_control_cannot_be_accepted_by_snapshot_validation() + { + using var hub = HubTest.Create(partitions: 1); + var source = HubTest.Ticket("driver", "active-control"); + HubTest.BindAndPublish(hub, source, 1, 1); + hub.ProcessPending(); + hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue(); + using (snapshot!) + { + var signal = hub.ControlSignalForTests(source.Key); + signal.Begin(); + try { snapshot!.IsReset.ShouldBeTrue(); } + finally { signal.End(); } + } + } + + [Fact] + public void Control_counter_overflow_permanently_rejects_snapshots() + { + var signal = new PartitionControlSignal(); + typeof(PartitionControlSignal).GetField("_generation", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)! + .SetValue(signal, long.MaxValue); + signal.Begin(); + signal.TryCapture(out _).ShouldBeFalse(); + signal.End(); + signal.TryCapture(out _).ShouldBeFalse(); + } + + [Fact] + public void Routing_epoch_exhaustion_rejects_repartition_before_mutation() + { + using var hub = HubTest.Create(partitions: 1); + typeof(PartitionedSampleHub).GetField("_routingEpoch", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)! + .SetValue(hub, long.MaxValue); + Should.Throw(() => hub.Repartition(2)); + hub.RoutingEpoch.ShouldBe(long.MaxValue); + hub.GetPartition(HubTest.Ticket("driver", "epoch-limit").Key).ShouldBe(0); + } + + [Fact] + public async Task Retirement_help_covers_all_partitions_when_first_caller_pauses_mid_vector() + { + using var hub = HubTest.Create(partitions: 2); + var firstSource = HubTest.Ticket("driver", "first-signal"); + var secondSource = Enumerable.Range(0, 1000).Select(i => HubTest.Ticket("driver", "second-signal-" + i)) + .First(t => hub.GetPartition(t.Key) != hub.GetPartition(firstSource.Key)); + var producer = new ProducerFence(1); + foreach (var source in new[] { firstSource, secondSource }) + { + hub.TryBind(source, producer).ShouldBeTrue(); + HubTest.Publish(hub, source, 1, 1); + } + hub.ProcessPending(); + hub.TryCaptureSnapshot([firstSource, secondSource], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue(); + using (snapshot!) + using (var entered = new ManualResetEventSlim()) + using (var release = new ManualResetEventSlim()) + { + var cancellationToken = TestContext.Current.CancellationToken; + var calls = 0; + producer.AfterSignalBegunForTests = () => + { + if (Interlocked.Increment(ref calls) == 1) { entered.Set(); release.Wait(); } + }; + var first = Task.Run(producer.Retire, cancellationToken); + try + { + entered.Wait(TimeSpan.FromSeconds(5), cancellationToken).ShouldBeTrue(); + snapshot!.IsReset.ShouldBeTrue(); + await Task.Run(producer.Retire, cancellationToken).WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); + producer.IsRetired.ShouldBeTrue(); + } + finally { release.Set(); await first.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); } + } + } + + [Fact] + public async Task Concurrent_retire_helps_complete_while_first_caller_is_paused() + { + using var hub = HubTest.Create(partitions: 1); + var source = HubTest.Ticket("driver", "retire-help"); + var producer = new ProducerFence(1); + hub.TryBind(source, producer).ShouldBeTrue(); + HubTest.Publish(hub, source, 1, 1); + hub.ProcessPending(); + hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue(); + using (snapshot!) + using (var entered = new ManualResetEventSlim()) + using (var release = new ManualResetEventSlim()) + { + var cancellationToken = TestContext.Current.CancellationToken; + var calls = 0; + producer.BeforeRetirementPublicationForTests = () => + { + if (Interlocked.Increment(ref calls) == 1) { entered.Set(); release.Wait(); } + }; + var first = Task.Run(producer.Retire, cancellationToken); + try + { + entered.Wait(TimeSpan.FromSeconds(5), cancellationToken).ShouldBeTrue(); + await Task.Run(producer.Retire, cancellationToken).WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); + producer.IsRetired.ShouldBeTrue(); + snapshot!.IsReset.ShouldBeTrue(); + hub.TryBind(HubTest.Ticket("driver", "late"), producer).ShouldBeFalse(); + } + finally { release.Set(); await first.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); } + } + } + + [Fact] + public void Producer_is_owned_by_one_hub_and_routing_replaces_old_signal_vectors() + { + using var first = HubTest.Create(partitions: 2); + using var second = HubTest.Create(partitions: 2); + var producer = new ProducerFence(1); + first.TryBind(HubTest.Ticket("driver", "first"), producer).ShouldBeTrue(); + second.TryBind(HubTest.Ticket("driver", "second"), producer).ShouldBeFalse(); + for (var i = 0; i < 10; i++) + { + first.Repartition(2); + first.TryBind(HubTest.Ticket("driver", "epoch-" + i), producer).ShouldBeTrue(); + producer.AttachedSignalCountForTests.ShouldBeLessThanOrEqualTo(2); + } + } + + [Fact] + public async Task Producer_retirement_never_waits_for_a_partition_lock() + { + using var hub = HubTest.Create(partitions: 1); + var source = HubTest.Ticket("driver", "locked-partition"); + var producer = new ProducerFence(1); + hub.TryBind(source, producer).ShouldBeTrue(); + using var entered = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var cancellationToken = TestContext.Current.CancellationToken; + var holder = Task.Run(() => hub.WithPartitionLockForTest(source.Key, () => { entered.Set(); release.Wait(); }), cancellationToken); + try + { + entered.Wait(TimeSpan.FromSeconds(5), cancellationToken).ShouldBeTrue(); + await Task.Run(producer.Retire, cancellationToken).WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); + producer.IsRetired.ShouldBeTrue(); + } + finally { release.Set(); await holder.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); } + } + + [Fact] + public void Producer_rejects_stale_epoch_attachment_after_repartition() + { + using var hub = HubTest.Create(partitions: 1); + var producer = new ProducerFence(1); + hub.TryBind(HubTest.Ticket("driver", "before"), producer).ShouldBeTrue(); + var oldEpoch = hub.RoutingEpoch; + hub.Repartition(1); + hub.TryBind(HubTest.Ticket("driver", "after"), producer).ShouldBeTrue(); + producer.TryAttach(hub, oldEpoch, new PartitionControlSignal()).ShouldBeFalse(); + } + + [Fact] + public void Missing_ticket_cannot_be_accepted_as_a_captured_source() + { + using var hub = HubTest.Create(partitions: 1); + var missing = HubTest.Ticket("driver", "missing"); + hub.TryCaptureSnapshot([missing], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeFalse(); + snapshot.ShouldBeNull(); + } + + [Fact] + public void Delta_positions_advance_the_partition_history_minimum() + { + using var hub = HubTest.Create(partitions: 1); + var source = HubTest.Ticket("driver", "cursor"); + HubTest.BindAndPublish(hub, source, 1, 1); + hub.ProcessPending(); + hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue(); + using (snapshot!) + for (var version = 2; version <= 5; version++) + { + HubTest.Publish(hub, source, version, version); + hub.ProcessPending(); + snapshot!.TryReadDelta(source, out var delta).ShouldBeTrue(); + delta!.Dispose(); + snapshot.IsReset.ShouldBeFalse(); + } + } + + [Fact] + public void Repeated_snapshot_validity_checks_do_not_rebuild_groups_for_every_captured_item() + { + var limits = new DataResourceLimits + { + PartitionCount = 4, MaxRetainedBytes = 16_000_000, MaxTrackedSources = 512, + MaxIngressItemsPerPartition = 512, MaxDirtySourcesPerPartition = 512, + MaxControlItemsPerPartition = 32, MaxSnapshotItems = 512, MaxSnapshotBytes = 8_000_000, + MaxSnapshotCatchUpItems = 512, MaxSnapshotLifetime = TimeSpan.FromMinutes(1) + }; + using var hub = new PartitionedSampleHub(limits, new ManualTimeProvider(), autoDrain: false); + var tickets = Enumerable.Range(0, 256).Select(i => HubTest.Ticket("driver", "snapshot-" + i)).ToArray(); + foreach (var ticket in tickets) HubTest.BindAndPublish(hub, ticket, 1, 1); + hub.ProcessPending(); + hub.TryCaptureSnapshot(tickets, new DataBudget(TimeSpan.FromSeconds(30), 512, 8_000_000), + CancellationToken.None, out var snapshot).ShouldBeTrue(); + using (snapshot!) + { + snapshot!.IsReset.ShouldBeFalse(); // warm JIT outside measured work + var before = GC.GetAllocatedBytesForCurrentThread(); + var workBefore = hub.SnapshotValidationWorkForTests; + for (var i = 0; i < 128; i++) if (snapshot.IsReset) throw new InvalidOperationException(); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + allocated.ShouldBeLessThan(64 * 1024, "each check must not regroup all 256 source entries"); + (hub.SnapshotValidationWorkForTests - workBefore).ShouldBeLessThan(128 * 16, + "a validity check must not walk every source in the snapshot"); + } + } + + [Fact] + public void Delayed_reserved_ingress_commit_keeps_original_normalized_receipt_time() + { + var clock = new ManualTimeProvider(); + using var hub = HubTest.Create(clock: clock); + var source = HubTest.Ticket("driver", "staged"); + hub.TryBind(source).ShouldBeTrue(); + var received = clock.GetTimestamp(); + hub.TryReserveIngress(source, 288, out var reservation).ShouldBeTrue(); + using (reservation!) + { + clock.Advance(TimeSpan.FromSeconds(5)); + var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 8), 0, null, null, HubTest.Serving, 1); + if (!reservation!.TryCommit(sample, 1)) { sample.Dispose(); throw new InvalidOperationException(); } + } + hub.ProcessPending(); + using var read = hub.Read(source); + read.ReceivedTimestamp.ShouldBe(received); + clock.GetElapsedTime(read.ReceivedTimestamp).ShouldBe(TimeSpan.FromSeconds(5)); + } + + [Fact] + public void Steady_interest_survives_snapshot_disposal_and_observes_later_dirty_generation() + { + using var hub = HubTest.Create(); + var source = HubTest.Ticket("driver", "interest"); + HubTest.BindAndPublish(hub, source, 1, 10); + hub.ProcessPending(); + hub.TryCaptureInterestSnapshot([source], HubTest.Budget, CancellationToken.None, + out var snapshot, out var interest).ShouldBeTrue(); + using (interest!) + { + snapshot!.Items[source].Sample!.Value.GetScalar().ShouldBe(10); + snapshot.Dispose(); + HubTest.Publish(hub, source, 2, 20); + hub.ProcessPending(); + interest!.TryReadChanges(1, out var changes).ShouldBeTrue(); + changes.ShouldHaveSingleItem().Ticket.ShouldBe(source); + using var latest = hub.Read(source); + latest.Sample!.Value.GetScalar().ShouldBe(20); + } + } + + [Fact] + public void Atomic_interest_registration_cannot_lose_a_racing_source_update() + { + using var hub = HubTest.Create(); + var source = HubTest.Ticket("driver", "interest-race"); + HubTest.BindAndPublish(hub, source, 1, 10); + hub.ProcessPending(); + SnapshotLease? snapshot = null; + SourceInterestLease? interest = null; + var accepted = false; + var captured = false; + Parallel.Invoke( + () => captured = hub.TryCaptureInterestSnapshot([source], HubTest.Budget, CancellationToken.None, + out snapshot, out interest), + () => + { + if (!hub.TryReserveIngress(source, 288, out var reservation)) return; + using (reservation!) + { + var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 20), 0, null, null, HubTest.Serving, 2); + accepted = reservation!.TryCommit(sample, 2); + if (!accepted) sample.Dispose(); + } + hub.ProcessPending(); + }); + if (!captured) return; // bounded contention is an explicit retry boundary + using (snapshot!) + using (interest!) + { + if (!accepted) { snapshot!.IsReset.ShouldBeTrue(); return; } + var value = (int)snapshot!.Items[source].Sample!.Value.GetScalar(); + if (value == 10) + { + interest!.TryReadChanges(1, out var changes).ShouldBeTrue(); + changes.ShouldContain(x => x.Ticket == source); + } + else value.ShouldBe(20); + } + } + + [Fact] + public void Snapshot_retains_original_monotonic_acquisition_time_after_status_and_reconnect() + { + var clock = new ManualTimeProvider(); + using var hub = HubTest.Create(clock: clock); + var source = HubTest.Ticket("driver", "age"); + var acquired = clock.GetTimestamp(); + HubTest.BindAndPublish(hub, source, 1, 42); + hub.ProcessPending(); + clock.Advance(TimeSpan.FromSeconds(3)); + hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var first).ShouldBeTrue(); + using (first!) + { + first!.Items[source].ReceivedTimestamp.ShouldBe(acquired); + first.Items[source].Sample!.SourceTimestampUtc.ShouldBeNull(); + first.Items[source].Sample!.ServerTimestampUtc.ShouldBeNull(); + } + hub.TryPublishStatus(source, 2, 0x80000000, null, null).ShouldBeTrue(); + hub.ProcessPending(); + clock.Advance(TimeSpan.FromSeconds(4)); + hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var reconnected).ShouldBeTrue(); + using (reconnected!) + { + reconnected!.Items[source].ReceivedTimestamp.ShouldBe(acquired); + clock.GetElapsedTime(reconnected.Items[source].ReceivedTimestamp!.Value).ShouldBe(TimeSpan.FromSeconds(7)); + reconnected.Items[source].Sample!.StatusCode.ShouldBe(0x80000000u); + } + } + + [Fact] + public void Snapshot_with_no_sample_has_no_acquisition_timestamp() + { + using var hub = HubTest.Create(); + var source = HubTest.Ticket("driver", "waiting"); + hub.TryBind(source).ShouldBeTrue(); + hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue(); + using (snapshot!) + { + snapshot!.Items[source].Sample.ShouldBeNull(); + snapshot.Items[source].ReceivedTimestamp.ShouldBeNull(); + } + } + [Fact] public void Snapshot_freezes_samples_and_its_watermarks_cover_every_participating_partition() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs new file mode 100644 index 000000000..caa60b108 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs @@ -0,0 +1,995 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")] +public sealed class GrpcDataStreamOrderingTests +{ + [Fact(Timeout = 30000)] + public async Task Coalescing_notice_is_delivered_when_the_latest_value_returns_to_the_baseline() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + { + fixture.Publish(1); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var session = subscription.ShouldBeOfType(); + var queued = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + session.OnCandidateQueuedForTests = (_, version) => { if (version == 3) queued.TrySetResult(true); }; + var sink = new SequencedLiveSink(); + var writer = subscription.ShouldBeAssignableTo() + .RunDeliveryAsync(sink, TestContext.Current.CancellationToken); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken); + await sink.SnapshotEnd.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending(); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(200)); + await sink.FirstLiveEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + HubTest.Publish(fixture.Hub, fixture.Ticket, 3, 3); fixture.Hub.ProcessPending(); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(200)); + await queued.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + HubTest.Publish(fixture.Hub, fixture.Ticket, 4, 2); fixture.Hub.ProcessPending(); + await subscription.SendAsync(new AddSubscriptionItems("s", 1, "probe", TimeSpan.FromSeconds(10), []), + TestContext.Current.CancellationToken); + sink.ReleaseFirst(); + await sink.ProbeAck.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.Clock.Advance(TimeSpan.FromSeconds(5)); + await sink.Heartbeat.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var events = sink.Events.ToArray(); + events.ShouldContain("coalesced", "a suppressed replacement must not hide the loss indication"); + events.ShouldNotContain("value-3"); + events.ShouldNotContain("value-4"); + await subscription.DisposeAsync(); + await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + } + } + + [Fact(Timeout = 30000)] + public async Task Direct_modify_ack_is_not_published_when_authority_is_revoked_during_commit_cleanup() + { + using var demand = new BlockingFirstLeaseDemand(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + { + fixture.Publish(10); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken); + await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken) + .GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue(); + reader.Current.ShouldBeOfType(); + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin); + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Dispose(); + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd); + await subscription.SendAsync(new ModifySubscriptionItems("s", 1, "modify", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings with { SamplingInterval = TimeSpan.FromMilliseconds(100) })]), TestContext.Current.CancellationToken); + var next = Task.Run(async () => await reader.MoveNextAsync(), TestContext.Current.CancellationToken); + try + { + await demand.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.Activation.Begin("revoke-during-modify-cleanup"); + } + finally { demand.Release(); } + (await next.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeFalse(); + } + } + + [Fact(Timeout = 30000)] + public async Task A_queued_candidate_rechecks_due_time_after_the_previous_blocked_write_commits() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + { + fixture.Publish(1); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var session = subscription.ShouldBeOfType(); + var queued = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + session.OnCandidateQueuedForTests = (_, version) => { if (version == 3) queued.TrySetResult(true); }; + var sink = new SequencedLiveSink(); + var writer = subscription.ShouldBeAssignableTo().RunDeliveryAsync(sink, TestContext.Current.CancellationToken); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken); + await sink.SnapshotEnd.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.Clock.Advance(TimeSpan.FromSeconds(1)); + HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending(); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(200)); + await sink.FirstLiveEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + HubTest.Publish(fixture.Hub, fixture.Ticket, 3, 3); fixture.Hub.ProcessPending(); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(200)); + await queued.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + await subscription.SendAsync(new AddSubscriptionItems("s", 1, "probe", TimeSpan.FromSeconds(5), + [new("probe", fixture.Raw, settings)]), TestContext.Current.CancellationToken); + sink.ReleaseFirst(); + await sink.ProbeAck.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + sink.Version3Written.Task.IsCompleted.ShouldBeFalse("the preceding write advanced the next due time"); + fixture.Clock.Advance(TimeSpan.FromSeconds(1)); + await sink.Version3Written.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + await subscription.DisposeAsync(); + await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + } + } + + [Fact(Timeout = 30000)] + public async Task Superseded_queued_value_emits_coalescing_control_before_the_newest_delta() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 4, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + { + fixture.Publish(1); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var session = subscription.ShouldBeOfType(); + var queued = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + session.OnCandidateQueuedForTests = (_, version) => { if (version == 3) queued.TrySetResult(true); }; + var sink = new SequencedLiveSink(); + var writer = subscription.ShouldBeAssignableTo().RunDeliveryAsync(sink, TestContext.Current.CancellationToken); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken); + await sink.SnapshotEnd.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending(); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(200)); + await sink.FirstLiveEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + HubTest.Publish(fixture.Hub, fixture.Ticket, 3, 3); fixture.Hub.ProcessPending(); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(200)); + await queued.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + HubTest.Publish(fixture.Hub, fixture.Ticket, 4, 4); fixture.Hub.ProcessPending(); + sink.ReleaseFirst(); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(200)); + await sink.Version4Written.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var events = sink.Events.ToArray(); + Array.IndexOf(events, "coalesced").ShouldBeGreaterThanOrEqualTo(0); + Array.IndexOf(events, "coalesced").ShouldBeLessThan(Array.IndexOf(events, "value-4")); + events.ShouldNotContain("value-3"); + await subscription.DisposeAsync(); + await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + } + } + + [Fact(Timeout = 30000)] + public async Task Revocation_during_post_prepare_snapshot_validation_prevents_transport_handoff() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + { + fixture.Publish(1); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var sink = new PostPrepareGateSink(fixture.Hub, blockSnapshot: true); + var writer = subscription.ShouldBeAssignableTo() + .RunDeliveryAsync(sink, TestContext.Current.CancellationToken); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), + TestContext.Current.CancellationToken); + try + { + await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.Activation.Begin("revoke-after-check"); + } + finally { sink.Release(); } + await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + sink.BlockedValueWrites.ShouldBe(0); + } + } + + [Fact(Timeout = 30000)] + public async Task Revocation_during_post_prepare_live_eligibility_prevents_transport_handoff() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + { + fixture.Publish(1); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var sink = new PostPrepareGateSink(fixture.Hub, blockSnapshot: false); + var writer = subscription.ShouldBeAssignableTo() + .RunDeliveryAsync(sink, TestContext.Current.CancellationToken); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), + TestContext.Current.CancellationToken); + await sink.SnapshotEnd.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending(); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(200)); + try + { + await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.Activation.Begin("revoke-after-eligibility-start"); + } + finally { sink.Release(); } + await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + sink.BlockedValueWrites.ShouldBe(0); + } + } + + [Fact(Timeout = 30000)] + public async Task Direct_handoff_does_not_certify_stale_age_after_a_blocking_final_check() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + using (var release = new ManualResetEventSlim()) + { + fixture.Publish(1); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var session = subscription.ShouldBeOfType(); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), + TestContext.Current.CancellationToken); + await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken) + .GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await reader.MoveNextAsync()).ShouldBeTrue(); // ack + (await reader.MoveNextAsync()).ShouldBeTrue(); // begin + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + session.BeforeDirectCommitForTests = () => + { + session.BeforeDirectCommitForTests = null; entered.TrySetResult(true); + if (!release.Wait(TimeSpan.FromSeconds(5))) throw new TimeoutException(); + }; + var move = Task.Run(async () => await reader.MoveNextAsync(), TestContext.Current.CancellationToken); + try + { + await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.Clock.Advance(TimeSpan.FromSeconds(2)); + } + finally { release.Set(); } + (await move.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue(); + using var values = reader.Current.ShouldBeOfType(); + var bounds = values.Items.ShouldHaveSingleItem().AgeBounds; + bounds.IsFresh(TimeSpan.FromSeconds(1)).ShouldBeFalse(); + if (bounds.Upper is { } upper) upper.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(2)); + } + } + + [Fact(Timeout = 30000)] + public async Task Local_facades_preserve_node_and_cluster_target_identity_in_demand_admission() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + { + fixture.Publish(3); + var nodeTarget = new DataTarget(DataTargetMode.Node, "cluster", "node-a"); + var clusterTarget = new DataTarget(DataTargetMode.Cluster, "cluster", null); + await using var node = fixture.Services.Create(fixture.Context, nodeTarget); + await using var cluster = fixture.Services.Create(fixture.Context, clusterTarget); + await using var nodeSubscription = await node.SubscribeAsync(TestContext.Current.CancellationToken); + await using var clusterSubscription = await cluster.SubscribeAsync(TestContext.Current.CancellationToken); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + await nodeSubscription.SendAsync(new OpenSubscription("node", 1, "open-node", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken); + await clusterSubscription.SendAsync(new OpenSubscription("cluster", 1, "open-cluster", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken); + await using var nodeReader = nodeSubscription.ReadAllAsync(TestContext.Current.CancellationToken) + .GetAsyncEnumerator(TestContext.Current.CancellationToken); + await using var clusterReader = clusterSubscription.ReadAllAsync(TestContext.Current.CancellationToken) + .GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await nodeReader.MoveNextAsync()).ShouldBeTrue(); + (await clusterReader.MoveNextAsync()).ShouldBeTrue(); + demand.AuthorizedViews.Select(x => x.Target).ShouldContain(nodeTarget); + demand.AuthorizedViews.Select(x => x.Target).ShouldContain(clusterTarget); + demand.AuthorizedViews.Select(x => x.Target.Mode).Distinct().Count().ShouldBe(2); + var views = demand.AuthorizedViews.ToArray(); + views[0].Source.ShouldBe(views[1].Source); + var registry = new UpstreamDemandRegistry(2, 2); + var firstKey = new DemandSharingKey(views[0].Source, views[0].Target, views[0].Consistency, + views[0].PrincipalId, views[0].ExportScope, views[0].Serving.CatalogEpoch, views[0].Serving.AuthorityEpoch); + var secondKey = firstKey with { Target = views[1].Target }; + registry.TryAdd(firstKey, settings, out var firstLease).ShouldBeTrue(); + registry.TryAdd(secondKey, settings, out var secondLease).ShouldBeTrue(); + registry.GetState(firstKey)!.InterestCount.ShouldBe(1); + registry.GetState(secondKey)!.InterestCount.ShouldBe(1); + firstLease!.Dispose(); secondLease!.Dispose(); + } + } + + [Fact(Timeout = 30000)] + public async Task Local_connection_waits_for_physical_ack_before_acknowledging_and_sending_snapshot() + { + var demand = new DeferredSubscriptionDemand(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(subscriptions: context => + new LocalSubscriptionService(fixture!.Services, context, + new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity))) + { + fixture.Publish(42); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var item = new DataSubscriptionItem("one", fixture.Raw, + new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null)); + var open = new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [item], false, + TimeSpan.FromSeconds(30), LocalDataFixture.Budget); + var send = subscription.SendAsync(open, TestContext.Current.CancellationToken); + await demand.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); + var first = reader.MoveNextAsync().AsTask(); + first.IsCompleted.ShouldBeFalse("an unacknowledged physical subscription is not ready"); + demand.Accept(); + await send; + (await first.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue(); + var ack = reader.Current.ShouldBeOfType(); + ack.Items.ShouldHaveSingleItem().Status.ShouldBe(DataItemStatus.Good); + ack.Items[0].Handle.ShouldNotBeNull(); + (await reader.MoveNextAsync()).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin); + (await reader.MoveNextAsync()).ShouldBeTrue(); + using (var values = reader.Current.ShouldBeOfType()) + { + values.IsSnapshot.ShouldBeTrue(); + values.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(42); + values.Items[0].Readiness.ShouldBe(DataReadiness.Ready); + } + (await reader.MoveNextAsync()).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd); + } + } + + [Fact(Timeout = 30000)] + public async Task Accepted_command_owns_its_item_list_before_the_caller_can_mutate_it() + { + var demand = new DeferredSubscriptionDemand(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(subscriptions: context => + new LocalSubscriptionService(fixture!.Services, context, + new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity))) + { + fixture.Publish(1); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("first", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), + TestContext.Current.CancellationToken); + await demand.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var mutable = new List { new("second", fixture.Raw, settings) }; + await subscription.SendAsync(new AddSubscriptionItems("s", 1, "add", TimeSpan.FromSeconds(5), mutable), + TestContext.Current.CancellationToken); + mutable.Clear(); + demand.Accept(); + await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken) + .GetAsyncEnumerator(TestContext.Current.CancellationToken); + while (true) + { + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue(); + if (reader.Current is DataSubscriptionValues values) values.Dispose(); + if (reader.Current is DataSubscriptionAck { CommandId: "add" } ack) + { + ack.Items.ShouldHaveSingleItem().ClientItemId.ShouldBe("second"); + ack.Items[0].Status.ShouldBe(DataItemStatus.Good); + break; + } + } + } + } + + [Fact(Timeout = 30000)] + public async Task A_denied_alias_cannot_inherit_authority_from_a_shared_backing_source() + { + var demand = new DeferredSubscriptionDemand(); + demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(subscriptions: context => + new LocalSubscriptionService(fixture!.Services, context, + new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity))) + { + fixture.Publish(42); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), + DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("allowed", fixture.Raw, settings), new("denied", fixture.Uns, settings)], false, + TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken); + await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await reader.MoveNextAsync()).ShouldBeTrue(); + var ack = reader.Current.ShouldBeOfType(); + ack.Items[0].Status.ShouldBe(DataItemStatus.Good); + ack.Items[1].Status.ShouldBe(DataItemStatus.Denied); + ack.Items[1].Handle.ShouldBeNull(); + demand.AuthorizedViews.ShouldHaveSingleItem().View.ShouldBe(fixture.Raw); + } + } + + [Fact(Timeout = 30000)] + public async Task A_bound_source_without_a_sample_is_waiting_until_a_real_acquisition_arrives() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(subscriptions: context => + new LocalSubscriptionService(fixture!.Services, context, + new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity))) + { + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), + TestContext.Current.CancellationToken); + await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken) + .GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await reader.MoveNextAsync()).ShouldBeTrue(); + var ack = reader.Current.ShouldBeOfType(); + ack.Items[0].Status.ShouldBe(DataItemStatus.WaitingForInitialData); + ack.Items[0].Handle.ShouldNotBeNull(); + (await reader.MoveNextAsync()).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin); + (await reader.MoveNextAsync()).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd); + fixture.Publish(9); + fixture.Clock.Advance(TimeSpan.FromSeconds(1)); + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue(); + using var values = reader.Current.ShouldBeOfType(); + values.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(9); + values.Items[0].Readiness.ShouldBe(DataReadiness.Ready); + } + } + + [Fact(Timeout = 30000)] + public async Task Snapshot_larger_than_queue_finishes_frozen_values_before_a_racing_delta() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 4, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(additionalRawNodes: 4, subscriptions: context => + new LocalSubscriptionService(fixture!.Services, context, + new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity))) + { + fixture.Publish(1); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + var items = Enumerable.Range(0, 5).Select(i => + { + var view = i == 0 ? fixture.Raw : fixture.Raw with + { + Address = fixture.Raw.Address with { Identifier = fixture.Raw.Address.Identifier + (i - 1) }, + Subject = fixture.Raw.Subject + (i - 1) + }; + return new DataSubscriptionItem("item-" + i, view, settings); + }).ToArray(); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10), items, + false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken); + await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken) + .GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await reader.MoveNextAsync()).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Items.Count.ShouldBe(5); + (await reader.MoveNextAsync()).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin); + (await reader.MoveNextAsync()).ShouldBeTrue(); + using (var first = reader.Current.ShouldBeOfType()) + first.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(1); + fixture.Clock.Advance(TimeSpan.FromSeconds(2)); + HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); + fixture.Hub.ProcessPending(); + var frozen = 1; + while (true) + { + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue(); + if (reader.Current is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) break; + using var values = reader.Current.ShouldBeOfType(); + values.IsSnapshot.ShouldBeTrue(); + values.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(1); + values.Items[0].AgeBounds.Lower.ShouldNotBeNull(); + values.Items[0].AgeBounds.Lower!.Value.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(2)); + frozen++; + } + frozen.ShouldBe(5); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(200)); + var delivered = new HashSet(); + while (delivered.Count < 5) + { + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue(); + if (reader.Current is DataSubscriptionControl control) + { + control.Kind.ShouldBe(DataStreamControlKind.Heartbeat, $"Unexpected {control.Kind}: {control.Diagnostic}"); + continue; + } + using var delta = reader.Current.ShouldBeOfType(); + delta.IsSnapshot.ShouldBeFalse(); + delta.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(2); + delivered.Add(delta.Items[0].Handle.Handle); + } + } + } + + [Fact(Timeout = 30000)] + public async Task Direct_frame_retains_its_resource_charge_after_session_disposal() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(subscriptions: context => + new LocalSubscriptionService(fixture!.Services, context, + new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity))) + { + fixture.Publish(7); + var baseline = fixture.Hub.Resources.RetainedBytes; + await using var connection = fixture.Connection(); + var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), + TestContext.Current.CancellationToken); + await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken) + .GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await reader.MoveNextAsync()).ShouldBeTrue(); // ack + (await reader.MoveNextAsync()).ShouldBeTrue(); // begin + (await reader.MoveNextAsync()).ShouldBeTrue(); + var frame = reader.Current.ShouldBeOfType(); + await subscription.DisposeAsync(); + fixture.Hub.Resources.RetainedBytes.ShouldBeGreaterThan(baseline); + capacity.Snapshots.TryAcquire("peer", 1, out _).ShouldBeFalse("escaped snapshot frame still owns its snapshot permit"); + frame.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(7); + frame.Dispose(); + fixture.Hub.Resources.RetainedBytes.ShouldBe(baseline); + capacity.Snapshots.TryAcquire("peer", 1, out var next).ShouldBeTrue(); + next!.Dispose(); + } + } + + [Fact(Timeout = 30000)] + public async Task Expired_original_key_fences_a_value_blocked_in_transport_preparation() + { + var demand = new DeferredSubscriptionDemand(); + demand.Accept(); + var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(subscriptions: context => + new LocalSubscriptionService(fixture!.Services, context, + new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity))) + { + fixture.Publish(42); + var baselineBytes = fixture.Hub.Resources.RetainedBytes; + var shortKey = fixture.Context with { CredentialExpiresUtc = fixture.Clock.GetUtcNow().AddSeconds(2) }; + await using var connection = fixture.Services.Create(shortKey, new(DataTargetMode.Node, "cluster", "node-a")); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var transport = subscription.ShouldBeAssignableTo(); + var sink = new BlockingValuePreparationSink(); + var writer = transport.RunDeliveryAsync(sink, TestContext.Current.CancellationToken); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), + DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), + TestContext.Current.CancellationToken); + await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.Clock.Advance(TimeSpan.FromSeconds(3)); + await subscription.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + capacity.ActiveOperations.ShouldBe(1, "a sink ignoring cancellation still owns its physical slot"); + fixture.Hub.Resources.RetainedBytes.ShouldBeGreaterThan(baselineBytes); + capacity.Snapshots.TryAcquire("peer", 1, out _).ShouldBeFalse(); + sink.Release(); + await sink.ValueDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + try { await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); } + catch (OperationCanceledException) { } + sink.ValueWrites.ShouldBe(0, "the final key/authority gate follows preparation"); + capacity.ActiveOperations.ShouldBe(0); + fixture.Hub.Resources.RetainedBytes.ShouldBe(baselineBytes); + capacity.Snapshots.TryAcquire("peer", 1, out var next).ShouldBeTrue(); + next!.Dispose(); + } + } + + [Fact(Timeout = 30000)] + public async Task A_write_ignoring_cancellation_retains_frame_and_capacity_until_its_actual_completion() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(subscriptions: context => + new LocalSubscriptionService(fixture!.Services, context, + new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity))) + { + fixture.Publish(42); + var baseline = fixture.Hub.Resources.RetainedBytes; + await using var connection = fixture.Connection(); + var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var transport = subscription.ShouldBeAssignableTo(); + var sink = new BlockingValueWriteSink(); + var writer = transport.RunDeliveryAsync(sink, TestContext.Current.CancellationToken); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(2), LocalDataFixture.Budget), + TestContext.Current.CancellationToken); + await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.Clock.Advance(TimeSpan.FromSeconds(3)); + await subscription.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + capacity.ActiveOperations.ShouldBe(1); + fixture.Hub.Resources.RetainedBytes.ShouldBeGreaterThan(baseline); + sink.Value!.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(42); + sink.Release(); + await sink.ValueDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + try { await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); } + catch (OperationCanceledException) { } + capacity.ActiveOperations.ShouldBe(0); + fixture.Hub.Resources.RetainedBytes.ShouldBe(baseline); + } + } + + [Fact(Timeout = 30000)] + public async Task Remove_ack_is_a_barrier_before_readding_the_same_client_item() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(subscriptions: context => + new LocalSubscriptionService(fixture!.Services, context, + new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity))) + { + fixture.Publish(1); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), + DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), + TestContext.Current.CancellationToken); + await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await reader.MoveNextAsync()).ShouldBeTrue(); + var old = reader.Current.ShouldBeOfType().Items[0].Handle!; + (await reader.MoveNextAsync()).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin); + (await reader.MoveNextAsync()).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Dispose(); + (await reader.MoveNextAsync()).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd); + HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); + fixture.Hub.ProcessPending(); + fixture.Clock.Advance(TimeSpan.FromSeconds(1)); + var remove = subscription.SendAsync(new RemoveSubscriptionItems("s", 1, "remove", TimeSpan.FromSeconds(5), [old]), + TestContext.Current.CancellationToken); + while (true) + { + (await reader.MoveNextAsync()).ShouldBeTrue(); + if (reader.Current is DataSubscriptionValues earlier) earlier.Dispose(); + if (reader.Current is DataSubscriptionAck { CommandId: "remove" }) break; + } + await remove; + var add = subscription.SendAsync(new AddSubscriptionItems("s", 1, "add", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings)]), TestContext.Current.CancellationToken); + DataItemHandle? replacement = null; + while (replacement is null) + { + (await reader.MoveNextAsync()).ShouldBeTrue(); + if (reader.Current is DataSubscriptionValues values) + { + values.Items.ShouldNotContain(x => x.Handle == old); + values.Dispose(); + } + if (reader.Current is DataSubscriptionAck { CommandId: "add" } ack) + { + ack.Items[0].Status.ShouldBe(DataItemStatus.Good); + ack.Items[0].Handle.ShouldNotBeNull(); + replacement = ack.Items[0].Handle; + } + } + await add; + replacement.Handle.ShouldNotBe(old.Handle); + } + } + + [Fact(Timeout = 30000)] + public async Task Changing_the_filter_acknowledges_a_new_revision_before_its_snapshot() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(subscriptions: context => + new LocalSubscriptionService(fixture!.Services, context, + new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity))) + { + fixture.Publish(10); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), + TestContext.Current.CancellationToken); + await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken) + .GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await reader.MoveNextAsync()).ShouldBeTrue(); + var original = reader.Current.ShouldBeOfType().Items[0].Handle!; + (await reader.MoveNextAsync()).ShouldBeTrue(); // begin + (await reader.MoveNextAsync()).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Dispose(); + (await reader.MoveNextAsync()).ShouldBeTrue(); // end + var modified = settings with { Deadband = 5 }; + await subscription.SendAsync(new ModifySubscriptionItems("s", 1, "modify", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, modified)]), TestContext.Current.CancellationToken); + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue(); + var ack = reader.Current.ShouldBeOfType(); + ack.CommandId.ShouldBe("modify"); + var replacement = ack.Items.ShouldHaveSingleItem().Handle; + replacement.ShouldNotBeNull(); + replacement.ShouldNotBe(original); + (await reader.MoveNextAsync()).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin); + (await reader.MoveNextAsync()).ShouldBeTrue(); + using var snapshot = reader.Current.ShouldBeOfType(); + snapshot.Items.ShouldHaveSingleItem().Handle.ShouldBe(replacement); + snapshot.Items[0].Sample.Value.GetScalar().ShouldBe(10); + } + } + + [Fact(Timeout = 30000)] + public async Task Quiet_control_only_session_expires_without_renewal_or_further_commands() + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + { + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + await subscription.SendAsync(new OpenSubscription("watch", 1, "open", TimeSpan.FromSeconds(5), [], true, + TimeSpan.FromSeconds(2), LocalDataFixture.Budget), TestContext.Current.CancellationToken); + await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken) + .GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await reader.MoveNextAsync()).ShouldBeTrue(); + reader.Current.ShouldBeOfType().CommandId.ShouldBe("open"); + fixture.Clock.Advance(TimeSpan.FromSeconds(2)); + await Should.ThrowAsync(() => subscription.SendAsync( + new AddSubscriptionItems("watch", 1, "late", TimeSpan.FromSeconds(1), []), TestContext.Current.CancellationToken)); + (await reader.MoveNextAsync()).ShouldBeFalse(); + } + } + + [Fact] + public void Removed_handle_never_becomes_current_after_readd() + { + var handles = new SubscriptionItemHandleTable("stream", 1, 4); + var first = handles.Add("item"); + handles.IsCurrent(first).ShouldBeTrue(); + handles.Remove(first).ShouldBeTrue(); + var second = handles.Add("item"); + second.Handle.ShouldNotBe(first.Handle); + handles.IsCurrent(first).ShouldBeFalse(); + handles.IsCurrent(second).ShouldBeTrue(); + } + + [Fact] + public void Revision_and_epoch_are_checked_even_if_the_numeric_handle_matches() + { + var handles = new SubscriptionItemHandleTable("stream", 7, 4); + var current = handles.Add("item"); + handles.IsCurrent(current with { ItemRevision = current.ItemRevision + 1 }).ShouldBeFalse(); + handles.IsCurrent(current with { StreamEpoch = current.StreamEpoch + 1 }).ShouldBeFalse(); + handles.IsCurrent(current with { SubscriptionId = "other" }).ShouldBeFalse(); + handles.IsCurrent(current).ShouldBeTrue(); + } +} + +internal sealed class DeferredSubscriptionDemand : ISubscriptionDemandSource +{ + private readonly TaskCompletionSource _accepted = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly List AuthorizedViews = []; + public async ValueTask AcquireAsync(SubscriptionAuthorizedView view, + DataSubscriptionSettings settings, CancellationToken cancellationToken) + { + lock (AuthorizedViews) AuthorizedViews.Add(view); + Entered.TrySetResult(true); + await _accepted.Task.WaitAsync(cancellationToken); + return new(DataItemStatus.Good, settings, 1, new NoopLease()); + } + internal void Accept() => _accepted.TrySetResult(true); + private sealed class NoopLease : IDisposable { public void Dispose() { } } +} + +internal sealed class BlockingFirstLeaseDemand : ISubscriptionDemandSource, IDisposable +{ + private readonly ManualResetEventSlim _release = new(); + private int _calls; + internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ValueTask AcquireAsync(SubscriptionAuthorizedView view, + DataSubscriptionSettings settings, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromResult(new SubscriptionDemandResult(DataItemStatus.Good, settings, 1, + new Lease(this, Interlocked.Increment(ref _calls) == 1))); + } + internal void Release() => _release.Set(); + public void Dispose() { _release.Set(); _release.Dispose(); } + private sealed class Lease(BlockingFirstLeaseDemand owner, bool blocks) : IDisposable + { + public void Dispose() + { + if (!blocks) return; + owner.Entered.TrySetResult(true); + if (!owner._release.Wait(TimeSpan.FromSeconds(5))) throw new TimeoutException(); + } + } +} + +internal sealed class BlockingValuePreparationSink : IDataSubscriptionDeliverySink +{ + internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource ValueDisposed = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal int ValueWrites; + public async ValueTask PrepareAsync(DataSubscriptionFrame frame, + long reservedBytes, CancellationToken cancellationToken) + { + if (frame is DataSubscriptionValues) + { + Entered.TrySetResult(true); + await _release.Task; // intentionally ignores cancellation + } + return new Prepared(frame is DataSubscriptionValues, ValueDisposed); + } + public ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken) + { + if (((Prepared)prepared).Value) Interlocked.Increment(ref ValueWrites); + return ValueTask.CompletedTask; + } + internal void Release() => _release.TrySetResult(true); + private sealed class Prepared(bool value, TaskCompletionSource disposed) : IDataPreparedSubscriptionDelivery + { + internal bool Value { get; } = value; + public long RetainedBytes => 1; + public void Dispose() { if (Value) disposed.TrySetResult(true); } + } +} + +internal sealed class PostPrepareGateSink(PartitionedSampleHub hub, bool blockSnapshot) : IDataSubscriptionDeliverySink +{ + private readonly ManualResetEventSlim _release = new(); + internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource SnapshotEnd = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal int BlockedValueWrites; + public ValueTask PrepareAsync(DataSubscriptionFrame frame, long reservedBytes, + CancellationToken cancellationToken) + { + if (frame is DataSubscriptionValues values && values.IsSnapshot == blockSnapshot) + { + if (blockSnapshot) hub.BeforeSnapshotValidationForTests = Block; + else hub.BeforeReadForTests = _ => Block(); + } + return ValueTask.FromResult(new Prepared(frame)); + } + private void Block() + { + hub.BeforeSnapshotValidationForTests = null; hub.BeforeReadForTests = null; + Entered.TrySetResult(true); + if (!_release.Wait(TimeSpan.FromSeconds(5))) throw new TimeoutException(); + } + public ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken) + { + var frame = ((Prepared)prepared).Frame; + if (frame is DataSubscriptionValues values && values.IsSnapshot == blockSnapshot) + Interlocked.Increment(ref BlockedValueWrites); + if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) SnapshotEnd.TrySetResult(true); + return ValueTask.CompletedTask; + } + internal void Release() => _release.Set(); + private sealed class Prepared(DataSubscriptionFrame frame) : IDataPreparedSubscriptionDelivery + { + internal DataSubscriptionFrame Frame { get; } = frame; + public long RetainedBytes => 1; + public void Dispose() { } + } +} + +internal sealed class SequencedLiveSink : IDataSubscriptionDeliverySink +{ + internal readonly TaskCompletionSource SnapshotEnd = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource FirstLiveEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource ProbeAck = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource Version3Written = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource Version4Written = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource Heartbeat = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly System.Collections.Concurrent.ConcurrentQueue Events = new(); + private readonly TaskCompletionSource _releaseFirst = new(TaskCreationOptions.RunContinuationsAsynchronously); + private ulong _firstHandle; + public ValueTask PrepareAsync(DataSubscriptionFrame frame, long reservedBytes, + CancellationToken cancellationToken) => ValueTask.FromResult(new Prepared(frame)); + public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken) + { + var frame = ((Prepared)prepared).Frame; + if (frame is DataSubscriptionAck { CommandId: "open" } open) _firstHandle = open.Items[0].Handle!.Handle; + if (frame is DataSubscriptionAck { CommandId: "probe" }) ProbeAck.TrySetResult(true); + if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) SnapshotEnd.TrySetResult(true); + if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Heartbeat }) Heartbeat.TrySetResult(true); + if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Coalesced }) Events.Enqueue("coalesced"); + if (frame is not DataSubscriptionValues { IsSnapshot: false } values || values.Items[0].Handle.Handle != _firstHandle) return; + var version = values.Items[0].Sample.Version; + if (version == 2) + { + FirstLiveEntered.TrySetResult(true); + await _releaseFirst.Task; // intentionally gated transport write + } + Events.Enqueue("value-" + version); + if (version == 3) Version3Written.TrySetResult(true); + if (version == 4) Version4Written.TrySetResult(true); + } + internal void ReleaseFirst() => _releaseFirst.TrySetResult(true); + private sealed class Prepared(DataSubscriptionFrame frame) : IDataPreparedSubscriptionDelivery + { + internal DataSubscriptionFrame Frame { get; } = frame; + public long RetainedBytes => 1; + public void Dispose() { } + } +} + +internal sealed class BlockingValueWriteSink : IDataSubscriptionDeliverySink +{ + internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource ValueDisposed = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal DataSubscriptionValues? Value; + public ValueTask PrepareAsync(DataSubscriptionFrame frame, long reservedBytes, + CancellationToken cancellationToken) => ValueTask.FromResult(new Prepared(frame, ValueDisposed)); + public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken) + { + if (((Prepared)prepared).Frame is not DataSubscriptionValues value) return; + Value = value; Entered.TrySetResult(true); + await _release.Task; // intentionally ignores cancellation after transport handoff + } + internal void Release() => _release.TrySetResult(true); + private sealed class Prepared(DataSubscriptionFrame frame, TaskCompletionSource disposed) : IDataPreparedSubscriptionDelivery + { + internal DataSubscriptionFrame Frame { get; } = frame; + public long RetainedBytes => 1; + public void Dispose() { if (Frame is DataSubscriptionValues) disposed.TrySetResult(true); } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataAcquisitionCapacityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataAcquisitionCapacityTests.cs new file mode 100644 index 000000000..8ae2684af --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataAcquisitionCapacityTests.cs @@ -0,0 +1,202 @@ +using Akka.Actor; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")] +public sealed class GrpcDataAcquisitionCapacityTests : RuntimeActorTestBase +{ + [Fact] + public async Task Abandoned_establishment_pins_shared_driver_capacity_until_the_late_handle_is_released() + { + var capacity = new SubscriptionAcquisitionCapacity(2); + var parent = CreateTestProbe(); + var firstDriver = new GateDriver("same", blocked: true, blockCleanup: true); + var first = parent.ChildActorOf(DriverInstanceActor.Props(firstDriver, commsLossTimeout: TimeSpan.Zero, + clusterId: "cluster", sourceIncarnation: 7, acquisitionCapacity: capacity), TestContext.Current.CancellationToken); + first.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + first.Tell(new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, 7, true)); + await firstDriver.Entered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + var watcher = CreateTestProbe(); + watcher.Watch(first); + Sys.Stop(first); + watcher.ExpectTerminated(first, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + parent.ExpectMsg(m => !m.Connected && m.ProducerIncarnation == 7, + PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + + var replacementDriver = new GateDriver("same", blocked: false, blockCleanup: false); + var replacement = parent.ChildActorOf(DriverInstanceActor.Props(replacementDriver, commsLossTimeout: TimeSpan.Zero, + clusterId: "cluster", sourceIncarnation: 8, acquisitionCapacity: capacity), TestContext.Current.CancellationToken); + replacement.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + var denied = await replacement.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 2, 8, true), PresenceBudget, + TestContext.Current.CancellationToken); + denied.Succeeded.ShouldBeFalse(); + replacementDriver.Entered.Task.IsCompleted.ShouldBeFalse(); + + var otherDriver = new GateDriver("other", blocked: false, blockCleanup: false); + var other = parent.ChildActorOf(DriverInstanceActor.Props(otherDriver, commsLossTimeout: TimeSpan.Zero, + clusterId: "cluster", sourceIncarnation: 9, acquisitionCapacity: capacity), TestContext.Current.CancellationToken); + other.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + var otherAck = await other.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 3, 9, true), PresenceBudget, + TestContext.Current.CancellationToken); + otherAck.Succeeded.ShouldBeTrue(); + + firstDriver.Complete(); + await firstDriver.CleanupEntered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + denied = await replacement.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 4, 8, true), PresenceBudget, + TestContext.Current.CancellationToken); + denied.Succeeded.ShouldBeFalse("a late handle's unsubscribe is still in flight"); + firstDriver.CompleteCleanup(); + AwaitAssert(() => capacity.ReservedDriverCount.ShouldBe(1), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + var accepted = await replacement.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 5, 8, true), PresenceBudget, + TestContext.Current.CancellationToken); + accepted.Succeeded.ShouldBeTrue(); + firstDriver.CleanupCount.ShouldBe(1); + } + + [Fact] + public async Task Replacement_keeps_capacity_until_previous_handle_actually_finishes_cleanup() + { + var capacity = new SubscriptionAcquisitionCapacity(2); + var parent = CreateTestProbe(); + var driver = new GateDriver("same", blocked: false, blockCleanup: true); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, commsLossTimeout: TimeSpan.Zero, + clusterId: "cluster", sourceIncarnation: 7, acquisitionCapacity: capacity), TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + var first = await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, 7, true), PresenceBudget, + TestContext.Current.CancellationToken); + first.Succeeded.ShouldBeTrue(); + var replacement = actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag", "next"], TimeSpan.FromSeconds(1), [], 2, 7, true), PresenceBudget, + TestContext.Current.CancellationToken); + await driver.CleanupEntered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + (await replacement.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue(); + var third = await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag", "third"], TimeSpan.FromSeconds(1), [], 3, 7, true), PresenceBudget, + TestContext.Current.CancellationToken); + third.Succeeded.ShouldBeFalse(); + capacity.ReservedDriverCount.ShouldBe(1); + driver.CompleteCleanup(); + } + + [Fact] + public async Task Timed_out_replacement_blocks_further_dispatch_until_late_handle_cleanup_finishes() + { + var clock = new ManualTimeProvider(); + var capacity = new SubscriptionAcquisitionCapacity(2); + var parent = CreateTestProbe(); + var driver = new SlowReplacementDriver(); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, commsLossTimeout: TimeSpan.Zero, + clusterId: "cluster", sourceIncarnation: 7, acquisitionCapacity: capacity, + acquisitionTimeout: TimeSpan.FromSeconds(5), acquisitionClock: clock), TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + var first = await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, 7, true), PresenceBudget, + TestContext.Current.CancellationToken); + first.Succeeded.ShouldBeTrue(); + var deadline = clock.GetUtcNow().AddSeconds(5); + var second = actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag", "b"], TimeSpan.FromSeconds(1), [], 2, 7, true), PresenceBudget, + TestContext.Current.CancellationToken); + await driver.Entered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + await clock.WaitForTimerDueAtAsync(deadline, PresenceBudget); + clock.Advance(TimeSpan.FromSeconds(5)); + (await second.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeFalse(); + var denied = await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag", "c"], TimeSpan.FromSeconds(1), [], 3, 7, true), PresenceBudget, + TestContext.Current.CancellationToken); + denied.Succeeded.ShouldBeFalse(); + denied.Busy.ShouldBeTrue(); + var ready = denied.RetryWhenReady.ShouldNotBeNull(); + driver.CallCount.ShouldBe(2); + driver.CompleteLate(); + await driver.CleanupEntered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + ready.IsCompleted.ShouldBeFalse(); + driver.CompleteCleanup(); + (await ready.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).ShouldBeTrue(); + var fourth = await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag", "d"], TimeSpan.FromSeconds(1), [], 4, 7, true), PresenceBudget, + TestContext.Current.CancellationToken); + fourth.Succeeded.ShouldBeTrue(); + driver.CallCount.ShouldBe(3); + } + + private sealed class SlowReplacementDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource + { + private readonly TaskCompletionSource _late = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _cleanup = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource CleanupEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal int CallCount; + public event EventHandler? OnDataChange { add { } remove { } } + public Task SubscribeAsync(IReadOnlyList refs, TimeSpan interval, CancellationToken ct) => + Task.FromResult(new Handle()); + public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) + { + CleanupEntered.TrySetResult(); + await _cleanup.Task; + } + public async Task SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, + Action callback, CancellationToken ct) + { + if (Interlocked.Increment(ref CallCount) == 2) + { + Entered.TrySetResult(); + await _late.Task; // deliberate cancellation-ignoring late operation + } + return new(new Handle(), request.RequestedSamplingInterval, request.DesiredRevision, request.ProducerIncarnation); + } + internal void CompleteLate() => _late.TrySetResult(); + internal void CompleteCleanup() => _cleanup.TrySetResult(); + private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "late-replacement"; } + } + + private sealed class GateDriver(string id, bool blocked, bool blockCleanup) : StubDriver, IDriver, ISubscribable, IAcknowledgedAcquisitionSource + { + string IDriver.DriverInstanceId => id; + private readonly TaskCompletionSource _result = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _cleanup = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource CleanupEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal int CleanupCount; + public event EventHandler? OnDataChange { add { } remove { } } + public Task SubscribeAsync(IReadOnlyList refs, TimeSpan interval, CancellationToken ct) => + Task.FromResult(new Handle()); + public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) + { + Interlocked.Increment(ref CleanupCount); + CleanupEntered.TrySetResult(); + if (blockCleanup) await _cleanup.Task; + } + public async Task SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, + Action callback, CancellationToken ct) + { + Entered.TrySetResult(); + if (blocked) await _result.Task; // deliberately ignores actor cancellation + return new(new Handle(), request.RequestedSamplingInterval, request.DesiredRevision, request.ProducerIncarnation); + } + internal void Complete() => _result.TrySetResult(); + internal void CompleteCleanup() => _cleanup.TrySetResult(); + private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "capacity"; } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataAcquisitionStatusTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataAcquisitionStatusTests.cs new file mode 100644 index 000000000..999bd7560 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataAcquisitionStatusTests.cs @@ -0,0 +1,202 @@ +using Akka.Actor; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")] +public sealed class GrpcDataAcquisitionStatusTests : RuntimeActorTestBase +{ + private const uint Bad = 0x80050000u; + private static readonly DateTime SourceTime = new(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc); + private static readonly DateTime ServerTime = SourceTime.AddSeconds(1); + + private static (PartitionedSampleHub Hub, SourceSamplePublisher Publisher, SourceTicket Ticket, long Incarnation, ManualTimeProvider Clock) Setup() + { + var clock = new ManualTimeProvider(); + var hub = HubTest.Create(clock: clock); + var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1)); + var incarnation = publisher.RegisterDriverIncarnation("stub-driver-1"); + publisher.RegisterDriverShape("stub-driver-1", "tag", new(DataValueKind.Int32, null, -1)).ShouldBeTrue(); + publisher.EnsureDriverBinding("cluster", "stub-driver-1", "tag", incarnation).ShouldBeTrue(); + publisher.TryCaptureDriver("stub-driver-1", "tag", incarnation, out var ticket).ShouldBeTrue(); + return (hub, publisher, ticket, incarnation, clock); + } + + [Fact] + public async Task Bad_null_acquisition_updates_status_without_refreshing_a_previous_value() + { + var (hub, publisher, ticket, incarnation, clock) = Setup(); + using (hub) + { + publisher.TryPublish(ticket, new(42, 0, SourceTime, ServerTime)).ShouldBeTrue(); + hub.ProcessPending(); + using var before = hub.Read(ticket); + var received = before.ReceivedTimestamp; + var version = before.Sample.ShouldNotBeNull().Version; + clock.Advance(TimeSpan.FromMinutes(3)); + var driver = new StatusDriver(); + var parent = CreateTestProbe(); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero, + sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(4)), + TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + var ack = await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true), + PresenceBudget, TestContext.Current.CancellationToken); + ack.Succeeded.ShouldBeTrue(); + driver.Emit(null, Bad); + hub.ProcessPending(); + using var after = hub.Read(ticket); + after.Readiness.ShouldBe(DataReadiness.Ready); + var sample = after.Sample.ShouldNotBeNull(); + sample.Value.GetScalar().ShouldBe(42); + sample.StatusCode.ShouldBe(Bad); + sample.SourceTimestampUtc.ShouldBe(new DateTimeOffset(SourceTime)); + sample.ServerTimestampUtc.ShouldBe(new DateTimeOffset(ServerTime)); + sample.Version.ShouldBeGreaterThan(version); + after.ReceivedTimestamp.ShouldBe(received); + } + } + + [Fact] + public void First_status_only_result_remains_waiting_without_a_fabricated_sample() + { + var (hub, publisher, ticket, _, _) = Setup(); + using (hub) + { + publisher.TryPublishAcquisitionStatus(ticket, Bad).ShouldBeTrue(); + hub.ProcessPending(); + using var read = hub.Read(ticket); + read.Readiness.ShouldBe(DataReadiness.WaitingForInitialData); + read.Sample.ShouldBeNull(); + } + } + + [Fact] + public async Task Pre_ack_callback_is_dropped_and_waiting_ends_only_after_a_later_real_read() + { + var (hub, publisher, ticket, incarnation, _) = Setup(); + using (hub) + { + var driver = new EarlyDriver(); + var parent = CreateTestProbe(); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero, + sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(4)), + TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + var pending = actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true), + PresenceBudget, TestContext.Current.CancellationToken); + await driver.Entered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + hub.ProcessPending(); + using (var early = hub.Read(ticket)) + { + early.Readiness.ShouldBe(DataReadiness.WaitingForInitialData); + early.Sample.ShouldBeNull(); + } + driver.Acknowledge(); + (await pending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue(); + hub.ProcessPending(); + using (var afterAck = hub.Read(ticket)) + { + afterAck.Readiness.ShouldBe(DataReadiness.WaitingForInitialData); + afterAck.Sample.ShouldBeNull(); + } + driver.Emit(42); + hub.ProcessPending(); + using var observed = hub.Read(ticket); + observed.Readiness.ShouldBe(DataReadiness.Ready); + observed.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(42); + } + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Status_ingress_never_waits_for_publisher_or_slot_contention_and_invalidates_old_good(bool publisherGate) + { + var (hub, publisher, ticket, _, _) = Setup(); + using (hub) + using (var entered = new ManualResetEventSlim()) + using (var release = new ManualResetEventSlim()) + { + publisher.TryPublish(ticket, new(42, 0, SourceTime, ServerTime)).ShouldBeTrue(); + hub.ProcessPending(); + var holder = Task.Run(() => publisher.WithAcquisitionStatusLockForTest(ticket, publisherGate, () => + { + entered.Set(); release.Wait(TestContext.Current.CancellationToken); + }), TestContext.Current.CancellationToken); + try + { + entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue(); + var result = Task.Run(() => publisher.TryPublishAcquisitionStatus(ticket, Bad), TestContext.Current.CancellationToken); + (await result.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).ShouldBe(publisherGate); + } + finally { release.Set(); await holder.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); } + hub.ProcessPending(); + using var read = hub.Read(ticket); + if (publisherGate) + { + read.Readiness.ShouldBe(DataReadiness.Ready); + read.Sample.ShouldNotBeNull().StatusCode.ShouldBe(Bad); + } + else read.Readiness.ShouldNotBe(DataReadiness.Ready); + } + } + + private sealed class StatusDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource + { + private AcquisitionSubscriptionRequest? _request; + private Action? _callback; + public event EventHandler? OnDataChange { add { } remove { } } + public Task SubscribeAsync(IReadOnlyList refs, TimeSpan interval, CancellationToken ct) => + Task.FromResult(new Handle()); + public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask; + public Task SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, + Action callback, CancellationToken ct) + { + _request = request; _callback = callback; + return Task.FromResult(new AcquisitionSubscriptionResult(new Handle(), request.RequestedSamplingInterval, + request.DesiredRevision, request.ProducerIncarnation)); + } + internal void Emit(object? value, uint status) => _callback!(new(_request!.DesiredRevision, _request.ProducerIncarnation, + [new("tag", new DataValueSnapshot(value, status, null, DateTime.UtcNow))])); + private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "status"; } + } + + private sealed class EarlyDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource + { + private readonly TaskCompletionSource _ack = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + private AcquisitionSubscriptionRequest? _request; + private Action? _callback; + public event EventHandler? OnDataChange { add { } remove { } } + public Task SubscribeAsync(IReadOnlyList refs, TimeSpan interval, CancellationToken ct) => + Task.FromResult(new Handle()); + public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask; + public async Task SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, + Action callback, CancellationToken ct) + { + _request = request; _callback = callback; + Emit(41); + Entered.TrySetResult(); + await _ack.Task.WaitAsync(ct); + return new(new Handle(), request.RequestedSamplingInterval, request.DesiredRevision, request.ProducerIncarnation); + } + internal void Acknowledge() => _ack.TrySetResult(); + internal void Emit(int value) => _callback!(new(_request!.DesiredRevision, _request.ProducerIncarnation, + [new("tag", new DataValueSnapshot(value, 0, DateTime.UtcNow, DateTime.UtcNow))])); + private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "early"; } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataDriverDemandActorTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataDriverDemandActorTests.cs new file mode 100644 index 000000000..1406950ce --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataDriverDemandActorTests.cs @@ -0,0 +1,415 @@ +using Akka.Actor; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")] +public sealed class GrpcDataDriverDemandActorTests : RuntimeActorTestBase +{ + [Fact] + public async Task Desired_revision_is_acknowledged_only_after_the_actual_driver_operation() + { + var driver = new ControlledAcquisitionDriver(); + var parent = CreateTestProbe(); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, commsLossTimeout: TimeSpan.Zero, + sourceIncarnation: 7, acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)), TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var requested = new DriverInstanceActor.SetDesiredSubscriptions(["legacy", "grpc"], + TimeSpan.FromMilliseconds(200), ["alarm"], DesiredRevision: 17, ProducerIncarnation: 7, + RequireAcquisition: true); + var response = actor.Ask(requested, + PresenceBudget, TestContext.Current.CancellationToken); + var request = await driver.Entered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + request.FullReferences.ShouldBe(["legacy", "grpc"]); + request.DesiredRevision.ShouldBe(17); + request.ProducerIncarnation.ShouldBe(7); + response.IsCompleted.ShouldBeFalse("the real SubscribeAcquisitionAsync has not completed"); + driver.Complete(); + var ack = await response; + ack.DesiredRevision.ShouldBe(17); + ack.ProducerIncarnation.ShouldBe(7); + ack.NominalSamplingInterval.ShouldBe(TimeSpan.FromMilliseconds(200)); + ack.Succeeded.ShouldBeTrue(); + } + + [Fact] + public async Task Failed_replacement_preserves_the_existing_legacy_subscription() + { + var driver = new ControlledAcquisitionDriver(); + var parent = CreateTestProbe(); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, commsLossTimeout: TimeSpan.Zero, + sourceIncarnation: 7, acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)), TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + await actor.Ask( + new DriverInstanceActor.Subscribe(["legacy"], TimeSpan.FromSeconds(1)), PresenceBudget, TestContext.Current.CancellationToken); + var response = actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["legacy", "grpc"], TimeSpan.FromMilliseconds(200), [], + DesiredRevision: 18, ProducerIncarnation: 7, RequireAcquisition: true), PresenceBudget, TestContext.Current.CancellationToken); + await driver.Entered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + driver.Fail(); + (await response).Succeeded.ShouldBeFalse(); + driver.FireLegacy(11); + var published = parent.ExpectMsg(PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + published.Items.ShouldHaveSingleItem().Value.ShouldBe(11); + driver.UnsubscribeCount.ShouldBe(0, "the failed stronger demand must not tear down independent legacy acquisition"); + } + + [Fact] + public async Task Unsupported_acquisition_is_rejected_before_touching_the_legacy_handle() + { + var driver = new SubscribableStubDriver(); + var parent = CreateTestProbe(); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, commsLossTimeout: TimeSpan.Zero, + sourceIncarnation: 7, acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)), TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + await actor.Ask( + new DriverInstanceActor.Subscribe(["legacy"], TimeSpan.FromSeconds(1)), PresenceBudget, TestContext.Current.CancellationToken); + var ack = await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["legacy", "grpc"], TimeSpan.FromMilliseconds(200), [], + DesiredRevision: 19, ProducerIncarnation: 7, RequireAcquisition: true), PresenceBudget, TestContext.Current.CancellationToken); + ack.Succeeded.ShouldBeFalse(); + driver.UnsubscribeCount.ShouldBe(0); + driver.FireDataChange("legacy", 12, 0); + parent.ExpectMsg(PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken).Items.ShouldHaveSingleItem().Value.ShouldBe(12); + } + + [Fact] + public async Task Raw_callback_cannot_publish_a_reference_outside_its_acknowledged_set() + { + using var hub = HubTest.Create(); + var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1)); + const string driverId = "stub-driver-1"; + var incarnation = publisher.RegisterDriverIncarnation(driverId); + var shape = new SourceValueShape(DataValueKind.Int32, null, -1); + publisher.RegisterDriverShape(driverId, "tag", shape).ShouldBeTrue(); + publisher.RegisterDriverShape(driverId, "other", shape).ShouldBeTrue(); + publisher.EnsureDriverBinding("cluster", driverId, "tag", incarnation).ShouldBeTrue(); + publisher.EnsureDriverBinding("cluster", driverId, "other", incarnation).ShouldBeTrue(); + publisher.TryCaptureDriver(driverId, "tag", incarnation, out var tag).ShouldBeTrue(); + publisher.TryCaptureDriver(driverId, "other", incarnation, out var other).ShouldBeTrue(); + var driver = new ControlledAcquisitionDriver(); + var parent = CreateTestProbe(); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero, + sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)), + TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + var pending = actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true), + PresenceBudget, TestContext.Current.CancellationToken); + await driver.Entered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + driver.Complete(); + (await pending).Succeeded.ShouldBeTrue(); + driver.FireAcquired("other", 40); + driver.FireAcquired("tag", 41); + hub.ProcessPending(); + using var valid = hub.Read(tag); + using var outside = hub.Read(other); + valid.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(41); + outside.Sample.ShouldBeNull(); + } + + [Fact] + public async Task Retiring_acquisition_handle_cannot_publish_through_the_replacement_legacy_handler() + { + using var hub = HubTest.Create(); + var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1)); + const string driverId = "stub-driver-1"; + var incarnation = publisher.RegisterDriverIncarnation(driverId); + publisher.RegisterDriverShape(driverId, "tag", new(DataValueKind.Int32, null, -1)).ShouldBeTrue(); + publisher.EnsureDriverBinding("cluster", driverId, "tag", incarnation).ShouldBeTrue(); + publisher.TryCaptureDriver(driverId, "tag", incarnation, out var ticket).ShouldBeTrue(); + var driver = new RetiringDriver(); + var parent = CreateTestProbe(); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero, + sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(4)), + TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + (await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true), + PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue(); + try + { + actor.Tell(new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [])); + await driver.CleanupEntered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + await driver.LegacyEntered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + var initial = parent.ExpectMsg(PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + initial.Items.ShouldHaveSingleItem().Value.ShouldBe(123, "the initial legacy callback can precede its subscribe return"); + hub.ProcessPending(); + using (var first = hub.Read(ticket)) first.Sample.ShouldNotBeNull().Version.ShouldBe(1); + driver.FireOld(999); + driver.FireCurrent(124); + var current = parent.ExpectMsg(PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + current.Items.ShouldHaveSingleItem().Value.ShouldBe(124); + hub.ProcessPending(); + using var read = hub.Read(ticket); + read.Sample.ShouldNotBeNull().Version.ShouldBe(2, "a late old-handle event cannot reach the source hub"); + read.Sample.Value.GetScalar().ShouldBe(124); + } + finally { driver.ReleaseCleanup(); } + } + + [Fact] + public async Task Captured_old_delegate_during_retire_cannot_publish_before_new_legacy_gate_exists() + { + using var hub = HubTest.Create(); + var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1)); + const string driverId = "stub-driver-1"; + var incarnation = publisher.RegisterDriverIncarnation(driverId); + publisher.RegisterDriverShape(driverId, "tag", new(DataValueKind.Int32, null, -1)).ShouldBeTrue(); + publisher.EnsureDriverBinding("cluster", driverId, "tag", incarnation).ShouldBeTrue(); + publisher.TryCaptureDriver(driverId, "tag", incarnation, out var ticket).ShouldBeTrue(); + var driver = new RetireWindowDriver(); + var parent = CreateTestProbe(); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero, + sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(4)), + TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + (await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true), + PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue(); + try + { + actor.Tell(new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [])); + await driver.RetireCallbackFired.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + await driver.LegacyCallbackFired.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + var initial = parent.ExpectMsg(PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + initial.Items.ShouldHaveSingleItem().Value.ShouldBe(123, "the captured old event must not cross the retire/detach gap"); + hub.ProcessPending(); + using var read = hub.Read(ticket); + read.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(123); + read.Sample.Version.ShouldBe(1, "the stale event must not reach the source hub"); + } + finally { driver.ReleaseCleanup(); } + } + + private sealed class RetireWindowDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource + { + private readonly Handle _old = new("old"), _legacy = new("legacy"); + private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + private EventHandler? _events, _captured; + internal readonly TaskCompletionSource RetireCallbackFired = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource LegacyCallbackFired = new(TaskCreationOptions.RunContinuationsAsynchronously); + public event EventHandler? OnDataChange { add { _events += value; } remove { _events -= value; } } + public Task SubscribeAsync(IReadOnlyList refs, TimeSpan interval, CancellationToken ct) + { + _events?.Invoke(this, Event(_legacy, 123)); + LegacyCallbackFired.TrySetResult(); + return Task.FromResult(_legacy); + } + public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) + { + if (!ReferenceEquals(handle, _old)) return; + _captured?.Invoke(this, Event(_old, 999)); + RetireCallbackFired.TrySetResult(); + await _release.Task; + } + public Task SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, + Action callback, CancellationToken ct) + { + _captured = _events; + return Task.FromResult(new AcquisitionSubscriptionResult(_old, request.RequestedSamplingInterval, + request.DesiredRevision, request.ProducerIncarnation)); + } + internal void ReleaseCleanup() => _release.TrySetResult(); + private static DataChangeEventArgs Event(ISubscriptionHandle handle, int value) => + new(handle, "tag", new DataValueSnapshot(value, 0, DateTime.UtcNow, DateTime.UtcNow)); + private sealed record Handle(string DiagnosticId) : ISubscriptionHandle; + } + + [Fact] + public async Task Restoration_preserves_all_130_synchronous_legacy_initials_despite_hub_pressure_and_missing_shapes() + { + using var hub = HubTest.Create(bytes: 10_000, ingress: 1, dirty: 1, maxSources: 1); + var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1)); + const string driverId = "stub-driver-1"; + var incarnation = publisher.RegisterDriverIncarnation(driverId); + publisher.RegisterDriverShape(driverId, "tag-0", new(DataValueKind.Int32, null, -1)).ShouldBeTrue(); + publisher.EnsureDriverBinding("cluster", driverId, "tag-0", incarnation).ShouldBeTrue(); + var driver = new ManyInitialDriver(); + var parent = CreateTestProbe(); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero, + sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(4)), + TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + (await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag-0"], TimeSpan.FromSeconds(1), [], 1, incarnation, true), + PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue(); + var refs = Enumerable.Range(0, 130).Select(i => $"tag-{i}").ToArray(); + actor.Tell(new DriverInstanceActor.SetDesiredSubscriptions(refs, TimeSpan.FromSeconds(1), [])); + for (var i = 0; i < refs.Length; i++) + { + var batch = parent.ExpectMsg(PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + batch.Items.ShouldHaveSingleItem().FullReference.ShouldBe(refs[i]); + batch.Items[0].Value.ShouldBe(i); + } + } + + [Fact] + public async Task Staged_legacy_initial_keeps_its_original_ingress_age_while_subscribe_ack_is_delayed() + { + var clock = new ManualTimeProvider(); + using var hub = HubTest.Create(clock: clock); + var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1)); + const string driverId = "stub-driver-1"; + var incarnation = publisher.RegisterDriverIncarnation(driverId); + publisher.RegisterDriverShape(driverId, "tag", new(DataValueKind.Int32, null, -1)).ShouldBeTrue(); + publisher.EnsureDriverBinding("cluster", driverId, "tag", incarnation).ShouldBeTrue(); + publisher.TryCaptureDriver(driverId, "tag", incarnation, out var ticket).ShouldBeTrue(); + var driver = new DelayedLegacyDriver(); + var parent = CreateTestProbe(); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero, + sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(4)), + TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + (await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true), + PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue(); + var originalReceipt = clock.GetTimestamp(); + try + { + actor.Tell(new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [])); + await driver.Entered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + clock.Advance(TimeSpan.FromMinutes(3)); + driver.Complete(); + var initial = parent.ExpectMsg(PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + initial.Items.ShouldHaveSingleItem().Value.ShouldBe(42); + hub.ProcessPending(); + using var read = hub.Read(ticket); + read.ReceivedTimestamp.ShouldBe(originalReceipt); + read.Sample.ShouldNotBeNull().SourceTimestampUtc.ShouldBe(new DateTimeOffset(DelayedLegacyDriver.SourceTime)); + } + finally { driver.Complete(); } + } + + private sealed class DelayedLegacyDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource + { + internal static readonly DateTime SourceTime = new(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc); + private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + public event EventHandler? OnDataChange; + public async Task SubscribeAsync(IReadOnlyList refs, TimeSpan interval, CancellationToken ct) + { + var handle = new Handle("legacy"); + OnDataChange?.Invoke(this, new DataChangeEventArgs(handle, "tag", new DataValueSnapshot(42, 0, SourceTime, SourceTime))); + Entered.TrySetResult(); + await _release.Task.WaitAsync(ct); + return handle; + } + public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask; + public Task SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, + Action callback, CancellationToken ct) => Task.FromResult( + new AcquisitionSubscriptionResult(new Handle("acquisition"), request.RequestedSamplingInterval, + request.DesiredRevision, request.ProducerIncarnation)); + internal void Complete() => _release.TrySetResult(); + private sealed record Handle(string DiagnosticId) : ISubscriptionHandle; + } + + private sealed class ManyInitialDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource + { + public event EventHandler? OnDataChange; + public Task SubscribeAsync(IReadOnlyList refs, TimeSpan interval, CancellationToken ct) + { + var handle = new Handle("legacy"); + for (var i = 0; i < refs.Count; i++) + OnDataChange?.Invoke(this, new DataChangeEventArgs(handle, refs[i], + new DataValueSnapshot(i, 0, DateTime.UtcNow, DateTime.UtcNow))); + return Task.FromResult(handle); + } + public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask; + public Task SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, + Action callback, CancellationToken ct) => Task.FromResult( + new AcquisitionSubscriptionResult(new Handle("acquisition"), request.RequestedSamplingInterval, + request.DesiredRevision, request.ProducerIncarnation)); + private sealed record Handle(string DiagnosticId) : ISubscriptionHandle; + } + + private sealed class RetiringDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource + { + private readonly Handle _old = new("old"), _current = new("current"); + private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource CleanupEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource LegacyEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + public event EventHandler? OnDataChange; + public Task SubscribeAsync(IReadOnlyList refs, TimeSpan interval, CancellationToken ct) + { + Fire(_current, 123); + LegacyEntered.TrySetResult(); + return Task.FromResult(_current); + } + public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) + { + if (!ReferenceEquals(handle, _old)) return; + CleanupEntered.TrySetResult(); + await _release.Task; + } + public Task SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, + Action callback, CancellationToken ct) => Task.FromResult( + new AcquisitionSubscriptionResult(_old, request.RequestedSamplingInterval, request.DesiredRevision, request.ProducerIncarnation)); + internal void FireOld(int value) => Fire(_old, value); + internal void FireCurrent(int value) => Fire(_current, value); + internal void ReleaseCleanup() => _release.TrySetResult(); + private void Fire(ISubscriptionHandle handle, int value) => OnDataChange?.Invoke(this, + new DataChangeEventArgs(handle, "tag", new DataValueSnapshot(value, 0, DateTime.UtcNow, DateTime.UtcNow))); + private sealed record Handle(string DiagnosticId) : ISubscriptionHandle; + } + + private sealed class ControlledAcquisitionDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource + { + internal readonly TaskCompletionSource Entered = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _complete = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly Handle _legacy = new(); + private Action? _callback; + private AcquisitionSubscriptionRequest? _request; + internal int UnsubscribeCount; + public event EventHandler? OnDataChange; + public Task SubscribeAsync(IReadOnlyList fullReferences, + TimeSpan publishingInterval, CancellationToken cancellationToken) => + Task.FromResult(_legacy); + public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) + { Interlocked.Increment(ref UnsubscribeCount); return Task.CompletedTask; } + public async Task SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, + Action onAcquired, CancellationToken cancellationToken) + { + _callback = onAcquired; + _request = request; + Entered.TrySetResult(request); + await _complete.Task.WaitAsync(cancellationToken); + return new(new Handle(), request.RequestedSamplingInterval, request.DesiredRevision, request.ProducerIncarnation); + } + internal void Complete() => _complete.TrySetResult(true); + internal void Fail() => _complete.TrySetException(new InvalidOperationException("device rejected replacement")); + internal void FireLegacy(int value) => OnDataChange?.Invoke(this, + new DataChangeEventArgs(_legacy, "legacy", new DataValueSnapshot(value, 0, null, null))); + internal void FireAcquired(string reference, int value) => _callback!(new(_request!.DesiredRevision, + _request.ProducerIncarnation, [new(reference, new DataValueSnapshot(value, 0, DateTime.UtcNow, DateTime.UtcNow))])); + private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "controlled"; } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataDriverDemandBridgeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataDriverDemandBridgeTests.cs new file mode 100644 index 000000000..4f5991abf --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataDriverDemandBridgeTests.cs @@ -0,0 +1,225 @@ +using Akka.Actor; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")] +public sealed class GrpcDataDriverDemandBridgeTests : RuntimeActorTestBase +{ + private static readonly DataSubscriptionSettings Settings = new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + private static SubscriptionAuthorizedView View() + { + var view = new DataView(new("cluster", "urn:raw", "string", "tag"), DataRealm.Raw, null, 0, "subject"); + var source = SourceKey.ForDriver("cluster", "driver", "tag", "node", "inc"); + return new SubscriptionAuthorizedView(view, source, new("node", "inc", "Primary", 1, 1), + new(view, "tag", "Variable", DataValueKind.Int32, -1, [], false, DataOperations.Subscribe, 1, "tag", null, false), + "principal", "export", new(DataTargetMode.Node, "cluster", "node"), DataConsistency.Primary, () => true); + } + + [Fact] + public async Task Shared_interests_wait_for_driver_ack_and_last_release_removes_physical_demand() + { + var host = CreateTestProbe(); + var registry = new UpstreamDemandRegistry(8, 16); + using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), registry, maxDrivers: 8, maxInterests: 16, timeout: PresenceBudget, ownership: new SubscriptionAcquisitionCapacity(8)); + var firstTask = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask(); + var demand = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + demand.DriverInstanceId.ShouldBe("driver"); + demand.FullReferences.ShouldBe(["tag"]); + firstTask.IsCompleted.ShouldBeFalse(); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(demand.DesiredRevision, 7, Settings.SamplingInterval, true)); + var first = await firstTask.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + first.Status.ShouldBe(DataItemStatus.Good); + first.Boundary.ShouldBe(demand.DesiredRevision); + var secondPending = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask(); + var verified = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + verified.DesiredRevision.ShouldBe(demand.DesiredRevision); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(verified.DesiredRevision, 7, Settings.SamplingInterval, true)); + var second = await secondPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + second.Status.ShouldBe(DataItemStatus.Good); + first.Lease.ShouldNotBeNull().Dispose(); + second.Lease.ShouldNotBeNull().Dispose(); + var removed = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + removed.FullReferences.ShouldBeEmpty(); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(removed.DesiredRevision, 7, TimeSpan.Zero, true)); + } + + [Fact] + public async Task Slower_physical_floor_rejects_interest_and_restores_previous_demand() + { + var host = CreateTestProbe(); + var registry = new UpstreamDemandRegistry(8, 16); + using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), registry, maxDrivers: 8, maxInterests: 16, timeout: PresenceBudget, ownership: new SubscriptionAcquisitionCapacity(8)); + var request = Settings with { SamplingInterval = TimeSpan.FromMilliseconds(1) }; + var pending = source.AcquireAsync(View(), request, TestContext.Current.CancellationToken).AsTask(); + var demand = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(demand.DesiredRevision, 7, TimeSpan.FromMilliseconds(100), true)); + var result = await pending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + result.Status.ShouldNotBe(DataItemStatus.Good); + result.Lease.ShouldBeNull(); + var removed = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + removed.FullReferences.ShouldBeEmpty(); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(removed.DesiredRevision, 7, TimeSpan.Zero, true)); + } + + [Fact] + public async Task Relaxation_waits_for_proven_busy_cleanup_then_applies_latest_refs() + { + var host = CreateTestProbe(); + var registry = new UpstreamDemandRegistry(8, 16); + using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), registry, 8, 16, PresenceBudget, new SubscriptionAcquisitionCapacity(8)); + var firstPending = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask(); + var firstApply = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(firstApply.DesiredRevision, 7, Settings.SamplingInterval, true)); + var first = await firstPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + var secondView = View() with { Source = SourceKey.ForDriver("cluster", "driver", "next", "node", "inc") }; + var secondPending = source.AcquireAsync(secondView, Settings, TestContext.Current.CancellationToken).AsTask(); + var expanded = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + expanded.FullReferences.ShouldBe(["next", "tag"]); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(expanded.DesiredRevision, 7, Settings.SamplingInterval, true)); + var second = await secondPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + second.Lease.ShouldNotBeNull().Dispose(); + var relaxation = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + relaxation.FullReferences.ShouldBe(["tag"]); + var cleanup = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(relaxation.DesiredRevision, 7, TimeSpan.Zero, false, + Busy: true, RetryWhenReady: cleanup.Task)); + cleanup.SetResult(true); + var retried = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + retried.FullReferences.ShouldBe(["tag"]); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(retried.DesiredRevision, 7, Settings.SamplingInterval, true)); + first.Lease.ShouldNotBeNull().Dispose(); + var removed = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + removed.FullReferences.ShouldBeEmpty(); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(removed.DesiredRevision, 7, TimeSpan.Zero, true)); + } + + [Fact] + public async Task A_busy_driver_does_not_block_a_different_driver() + { + var host = CreateTestProbe(); + var registry = new UpstreamDemandRegistry(8, 16); + using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), registry, 8, 16, PresenceBudget, new SubscriptionAcquisitionCapacity(8)); + var firstPending = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask(); + var initial = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(initial.DesiredRevision, 7, Settings.SamplingInterval, true)); + var first = await firstPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + var nextView = View() with { Source = SourceKey.ForDriver("cluster", "driver", "next", "node", "inc") }; + var secondPending = source.AcquireAsync(nextView, Settings, TestContext.Current.CancellationToken).AsTask(); + var expanded = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(expanded.DesiredRevision, 7, Settings.SamplingInterval, true)); + var second = await secondPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + second.Lease.ShouldNotBeNull().Dispose(); + var relax = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var blocked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(relax.DesiredRevision, 7, TimeSpan.Zero, false, + Busy: true, RetryWhenReady: blocked.Task)); + + var otherView = View() with { Source = SourceKey.ForDriver("cluster", "driver2", "tag", "node", "inc") }; + var otherPending = source.AcquireAsync(otherView, Settings, TestContext.Current.CancellationToken).AsTask(); + var otherApply = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + otherApply.DriverInstanceId.ShouldBe("driver2"); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(otherApply.DesiredRevision, 8, Settings.SamplingInterval, true)); + var other = await otherPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + other.Status.ShouldBe(DataItemStatus.Good); + blocked.TrySetResult(false); + first.Lease.ShouldNotBeNull().Dispose(); + other.Lease.ShouldNotBeNull().Dispose(); + } + + [Fact] + public async Task A_driver_with_an_unanswered_first_ack_does_not_block_another_driver() + { + var host = CreateTestProbe(); + using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), new UpstreamDemandRegistry(8, 16), 8, 16, PresenceBudget, new SubscriptionAcquisitionCapacity(8)); + var pendingA = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask(); + var requestA = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var replyA = host.LastSender; + var otherView = View() with { Source = SourceKey.ForDriver("cluster", "driver2", "tag", "node", "inc") }; + var pendingB = source.AcquireAsync(otherView, Settings, TestContext.Current.CancellationToken).AsTask(); + var requestB = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + requestB.DriverInstanceId.ShouldBe("driver2"); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(requestB.DesiredRevision, 8, Settings.SamplingInterval, true)); + var second = await pendingB.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + second.Status.ShouldBe(DataItemStatus.Good); + pendingA.IsCompleted.ShouldBeFalse(); + replyA.Tell(new DriverInstanceActor.AcquisitionDemandApplied(requestA.DesiredRevision, 7, Settings.SamplingInterval, true)); + var first = await pendingA.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + first.Status.ShouldBe(DataItemStatus.Good); + first.Lease?.Dispose(); second.Lease?.Dispose(); + } + + [Fact] + public async Task Identical_interest_churn_does_not_rescan_all_existing_interests() + { + var host = Sys.ActorOf(Props.Create(() => new AutomaticAckHost())); + using var source = new DriverHostSubscriptionDemandSource(host, new UpstreamDemandRegistry(4, 2048), 4, 2048, PresenceBudget, new SubscriptionAcquisitionCapacity(4)); + var leases = new List(); + for (var i = 0; i < 1024; i++) + { + var result = await source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken); + leases.Add(result.Lease.ShouldNotBeNull()); + } + var before = source.ReferenceVisitCount; + for (var i = 0; i < 64; i++) + { + var result = await source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken); + leases.Add(result.Lease.ShouldNotBeNull()); + } + (source.ReferenceVisitCount - before).ShouldBeLessThan(1024L, "each add must not scan the existing 1,000 interests"); + foreach (var lease in leases) lease.Dispose(); + } + + [Fact] + public async Task Canceled_expansion_rolls_back_with_a_revision_newer_than_the_late_expansion() + { + var host = CreateTestProbe(); + using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), new UpstreamDemandRegistry(8, 16), 8, 16, PresenceBudget, new SubscriptionAcquisitionCapacity(8)); + var aPending = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask(); + var a = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(a.DesiredRevision, 7, Settings.SamplingInterval, true)); + var first = await aPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + using var cancel = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + var bView = View() with { Source = SourceKey.ForDriver("cluster", "driver", "next", "node", "inc") }; + var bPending = source.AcquireAsync(bView, Settings, cancel.Token).AsTask(); + var b = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + b.DesiredRevision.ShouldBeGreaterThan(a.DesiredRevision); + var lateReply = host.LastSender; + cancel.Cancel(); + await Should.ThrowAsync(() => bPending); + var rollback = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + rollback.FullReferences.ShouldBe(["tag"]); + rollback.DesiredRevision.ShouldBeGreaterThan(b.DesiredRevision); + lateReply.Tell(new DriverInstanceActor.AcquisitionDemandApplied(b.DesiredRevision, 7, Settings.SamplingInterval, true)); + host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(rollback.DesiredRevision, 7, Settings.SamplingInterval, true)); + first.Lease.ShouldNotBeNull().Dispose(); + } + + private IActorRef Wrap(IActorRef target) => Sys.ActorOf(Props.Create(() => new OwnerProxy(target))); + private sealed class OwnerProxy : ReceiveActor + { + public OwnerProxy(IActorRef target) + { + Receive(_ => Sender.Tell(new DriverHostActor.AcquisitionOwnerRegistered(true, 1))); + Receive(message => Sender.Tell(new DriverHostActor.AcquisitionDemandOpened(true, message.RequestedKeyGeneration))); + Receive(_ => Sender.Tell(new DriverHostActor.AcquisitionOpenAborted(true))); + Receive(message => target.Forward(message)); + } + } + private sealed class AutomaticAckHost : ReceiveActor + { + public AutomaticAckHost() + { + Receive(_ => Sender.Tell(new DriverHostActor.AcquisitionOwnerRegistered(true, 1))); + Receive(message => Sender.Tell(new DriverHostActor.AcquisitionDemandOpened(true, message.RequestedKeyGeneration))); + Receive(_ => Sender.Tell(new DriverHostActor.AcquisitionOpenAborted(true))); + Receive(message => Sender.Tell(new DriverInstanceActor.AcquisitionDemandApplied( + message.DesiredRevision, 7, message.SamplingInterval == TimeSpan.Zero ? TimeSpan.FromMilliseconds(100) : message.SamplingInterval, true))); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataDriverHostDemandTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataDriverHostDemandTests.cs new file mode 100644 index 000000000..e20afade8 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataDriverHostDemandTests.cs @@ -0,0 +1,656 @@ +using System.Collections.Concurrent; +using System.Threading.Channels; +using Akka.Actor; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Engines; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")] +public sealed class GrpcDataDriverHostDemandTests : RuntimeActorTestBase +{ + [Fact] + public async Task Real_host_merges_legacy_refs_then_restores_them_after_last_grpc_interest() + { + var db = NewInMemoryDbFactory(); + var revision = RevisionHash.Parse(new string('a', 64)); + var deploy = V3ArtifactSeeder.SeedV3Deployment(db, revision, + [("DI-1", "Modbus", "dev1", "speed", "Double", false)], [], enabled: true); + var factory = new Factory(); + using var hub = HubTest.Create(); + var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1)); + var coordinator = CreateTestProbe(); + var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref, + driverFactory: factory, localRoles: new HashSet { "driver" }, + dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance, + virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher, + acquisitionCapacity: new SubscriptionAcquisitionCapacity(8))); + V3ArtifactSeeder.Dispatch(host, coordinator, deploy, revision); + AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var driver = factory.Driver!; + const string legacy = "Plant/Modbus/dev1/speed"; + AwaitAssert(() => driver.LegacyRefs.ShouldContain(legacy), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + + var pending = host.Ask( + new DriverHostActor.ApplyAcquisitionDemand("DI-1", ["grpc"], TimeSpan.FromMilliseconds(200), 17), + PresenceBudget, TestContext.Current.CancellationToken); + var request = await driver.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask() + .WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + request.FullReferences.ShouldContain(legacy); + request.FullReferences.ShouldContain("grpc"); + request.RequestedSamplingInterval.ShouldBe(TimeSpan.FromMilliseconds(200)); + pending.IsCompleted.ShouldBeFalse(); + driver.Complete(); + (await pending).Succeeded.ShouldBeTrue(); + + host.Tell(new DriverHostActor.ApplyAcquisitionDemand("DI-1", [], TimeSpan.Zero, 18)); + AwaitAssert(() => driver.LegacyRefs.ShouldBe([legacy]), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + AwaitAssert(() => driver.LegacySubscribeCount.ShouldBeGreaterThanOrEqualTo(2), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + } + + [Fact] + public async Task Same_interest_after_real_driver_restart_never_reuses_an_old_producer_ack() + { + var db = NewInMemoryDbFactory(); + var revision = RevisionHash.Parse(new string('b', 64)); + var deploy = V3ArtifactSeeder.SeedV3Deployment(db, revision, + [("DI-1", "Modbus", "dev1", "speed", "Double", false)], [], enabled: true); + var factory = new Factory(); + using var hub = HubTest.Create(); + var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1)); + var coordinator = CreateTestProbe(); + var capacity = new SubscriptionAcquisitionCapacity(8); + var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref, + driverFactory: factory, localRoles: new HashSet { "driver" }, + dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance, + virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher, + acquisitionCapacity: capacity)); + V3ArtifactSeeder.Dispatch(host, coordinator, deploy, revision); + AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var original = factory.Driver!; + AwaitAssert(() => original.LegacyRefs.ShouldContain("Plant/Modbus/dev1/speed"), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + var view = new DataView(new("cluster", "urn:raw", "string", "speed"), DataRealm.Raw, null, 0, "subject"); + var auth = new SubscriptionAuthorizedView(view, SourceKey.ForDriver("cluster", "DI-1", "Plant/Modbus/dev1/speed", "node-a", "inc"), + new("node-a", "inc", "Primary", 1, 1), + new(view, "speed", "Variable", DataValueKind.Double, -1, [], false, DataOperations.Subscribe, 1, "speed", null, false), + "principal", "export", new(DataTargetMode.Node, "cluster", "node-a"), DataConsistency.Primary, () => true); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + using var source = new DriverHostSubscriptionDemandSource(host, new UpstreamDemandRegistry(8, 16), 8, 16, PresenceBudget, capacity); + var firstPending = source.AcquireAsync(auth, settings, TestContext.Current.CancellationToken).AsTask(); + await original.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + original.Complete(); + var first = await firstPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + first.Status.ShouldBe(DataItemStatus.Good); + + host.Tell(new RestartDriver("cluster", "DI-1", "test", Guid.NewGuid())); + AwaitAssert(() => factory.Driver.ShouldNotBeSameAs(original), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var replacement = factory.Driver!; + var secondPending = source.AcquireAsync(auth, settings, TestContext.Current.CancellationToken).AsTask(); + var entered = replacement.Requests.Reader.WaitToReadAsync(TestContext.Current.CancellationToken).AsTask(); + var winner = await Task.WhenAny(secondPending, entered).WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + if (ReferenceEquals(winner, secondPending)) + (await secondPending).Status.ShouldNotBe(DataItemStatus.Good, "the new producer has not acknowledged a subscription"); + else + { + (await entered).ShouldBeTrue(); + secondPending.IsCompleted.ShouldBeFalse("a request to the replacement is still awaiting its acknowledgment"); + replacement.Complete(); + var second = await secondPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + second.Lease?.Dispose(); + } + first.Lease?.Dispose(); + } + + [Fact] + public async Task Deployment_while_first_demand_is_pending_reconciles_latest_legacy_and_grpc_refs() + { + var db = NewInMemoryDbFactory(); + var revA = RevisionHash.Parse(new string('c', 64)); + var revB = RevisionHash.Parse(new string('d', 64)); + var deployA = V3ArtifactSeeder.SeedV3Deployment(db, revA, + [("DI-1", "Modbus", "dev1", "speed", "Double", false)], [], enabled: true); + var factory = new Factory(); + using var hub = HubTest.Create(); + var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1)); + var coordinator = CreateTestProbe(); + var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref, + driverFactory: factory, localRoles: new HashSet { "driver" }, + dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance, + virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher, + acquisitionCapacity: new SubscriptionAcquisitionCapacity(8))); + V3ArtifactSeeder.Dispatch(host, coordinator, deployA, revA); + AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var original = factory.Driver!; + AwaitAssert(() => original.LegacyRefs.ShouldContain("Plant/Modbus/dev1/speed"), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + var pending = host.Ask( + new DriverHostActor.ApplyAcquisitionDemand("DI-1", ["grpc"], TimeSpan.FromMilliseconds(200), 17), + PresenceBudget, TestContext.Current.CancellationToken); + await original.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask() + .WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + pending.IsCompleted.ShouldBeFalse(); + + var deployB = V3ArtifactSeeder.SeedV3Deployment(db, revB, + [("DI-1", "Modbus", "dev1", "speed", "Double", false), + ("DI-1", "Modbus", "dev1", "flow", "Double", false)], [], enabled: true); + V3ArtifactSeeder.Dispatch(host, coordinator, deployB, revB); + AwaitAssert(() => factory.Driver.ShouldNotBeSameAs(original), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var replacement = factory.Driver!; + original.Complete(); + var reconciled = await replacement.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask() + .WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + reconciled.FullReferences.ShouldContain("Plant/Modbus/dev1/speed"); + reconciled.FullReferences.ShouldContain("Plant/Modbus/dev1/flow"); + reconciled.FullReferences.ShouldContain("grpc"); + reconciled.RequestedSamplingInterval.ShouldBe(TimeSpan.FromMilliseconds(200)); + replacement.Complete(); + } + + [Fact] + public async Task Removing_last_demand_while_driver_is_absent_prevents_ghost_polling_after_readd() + { + var db = NewInMemoryDbFactory(); + var revA = RevisionHash.Parse(new string('e', 64)); + var revB = RevisionHash.Parse(new string('f', 64)); + var revC = RevisionHash.Parse(new string('1', 64)); + var tags = new[] { ("DI-1", "Modbus", "dev1", "speed", "Double", false) }; + var deployA = V3ArtifactSeeder.SeedV3Deployment(db, revA, tags, [], enabled: true); + var factory = new Factory(); + using var hub = HubTest.Create(); + var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1)); + var coordinator = CreateTestProbe(); + var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref, + driverFactory: factory, localRoles: new HashSet { "driver" }, + dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance, + virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher, + acquisitionCapacity: new SubscriptionAcquisitionCapacity(8))); + V3ArtifactSeeder.Dispatch(host, coordinator, deployA, revA); + AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var original = factory.Driver!; + AwaitAssert(() => original.LegacyRefs.ShouldContain("Plant/Modbus/dev1/speed"), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + var demand = host.Ask( + new DriverHostActor.ApplyAcquisitionDemand("DI-1", ["grpc"], TimeSpan.FromMilliseconds(200), 17), + PresenceBudget, TestContext.Current.CancellationToken); + await original.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask() + .WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + original.Complete(); + (await demand).Succeeded.ShouldBeTrue(); + + var remove = V3ArtifactSeeder.SeedV3Deployment(db, revB, [], [], enabled: true); + V3ArtifactSeeder.Dispatch(host, coordinator, remove, revB); + var cleared = await host.Ask( + new DriverHostActor.ApplyAcquisitionDemand("DI-1", [], TimeSpan.Zero, 18), PresenceBudget, + TestContext.Current.CancellationToken); + cleared.Succeeded.ShouldBeTrue(); + var readd = V3ArtifactSeeder.SeedV3Deployment(db, revC, tags, [], enabled: true); + V3ArtifactSeeder.Dispatch(host, coordinator, readd, revC); + AwaitAssert(() => factory.Driver.ShouldNotBeSameAs(original), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var replacement = factory.Driver!; + AwaitAssert(() => replacement.LegacyRefs.ShouldContain("Plant/Modbus/dev1/speed"), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + replacement.Requests.Reader.TryRead(out _).ShouldBeFalse(); + } + + [Fact] + public async Task Reclaimed_driver_histories_do_not_exhaust_capacity_and_old_owner_or_key_commands_are_fenced() + { + var db = NewInMemoryDbFactory(); + var revision = RevisionHash.Parse(new string('2', 64)); + var deployment = V3ArtifactSeeder.SeedV3Deployment(db, revision, [], [], enabled: true); + var coordinator = CreateTestProbe(); + var capacity = new SubscriptionAcquisitionCapacity(2); + var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref, + localRoles: new HashSet { "driver" }, dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), + virtualTagEvaluator: NullVirtualTagEvaluator.Instance, virtualTagHostOverride: CreateTestProbe().Ref, + acquisitionCapacity: capacity)); + V3ArtifactSeeder.Dispatch(host, coordinator, deployment, revision); + var oldOwnerId = Guid.NewGuid(); + var oldSerial = capacity.NextOwnerSerial(); + var owner = await host.Ask( + new DriverHostActor.RegisterAcquisitionOwner(oldOwnerId, oldSerial), PresenceBudget, TestContext.Current.CancellationToken); + owner.Generation.ShouldBeGreaterThan(0); + for (var i = 0; i < 10; i++) + { + var id = $"retired-{i}"; + var opened = await host.Ask( + new DriverHostActor.OpenAcquisitionDemand(id, owner.Generation), PresenceBudget, TestContext.Current.CancellationToken); + opened.Succeeded.ShouldBeTrue(); + var closed = await host.Ask( + new DriverHostActor.ApplyAcquisitionDemand(id, [], TimeSpan.Zero, 1, + OwnerGeneration: owner.Generation, KeyGeneration: opened.KeyGeneration), PresenceBudget, + TestContext.Current.CancellationToken); + closed.Succeeded.ShouldBeTrue(); + } + var old = await host.Ask( + new DriverHostActor.OpenAcquisitionDemand("same", owner.Generation), PresenceBudget, TestContext.Current.CancellationToken); + (await host.Ask(new DriverHostActor.ApplyAcquisitionDemand( + "same", [], TimeSpan.Zero, 1, OwnerGeneration: owner.Generation, KeyGeneration: old.KeyGeneration), PresenceBudget, + TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue(); + var current = await host.Ask( + new DriverHostActor.OpenAcquisitionDemand("same", owner.Generation), PresenceBudget, TestContext.Current.CancellationToken); + current.KeyGeneration.ShouldBeGreaterThan(old.KeyGeneration); + var stale = await host.Ask(new DriverHostActor.ApplyAcquisitionDemand( + "same", [], TimeSpan.Zero, 2, OwnerGeneration: owner.Generation, KeyGeneration: old.KeyGeneration), PresenceBudget, + TestContext.Current.CancellationToken); + stale.Succeeded.ShouldBeFalse("a late clear from a retired key must not close its replacement"); + var newSerial = capacity.NextOwnerSerial(); + var newOwner = await host.Ask( + new DriverHostActor.RegisterAcquisitionOwner(Guid.NewGuid(), newSerial), PresenceBudget, TestContext.Current.CancellationToken); + newOwner.Generation.ShouldBeGreaterThan(owner.Generation); + var delayedRegistration = await host.Ask( + new DriverHostActor.RegisterAcquisitionOwner(oldOwnerId, oldSerial), PresenceBudget, TestContext.Current.CancellationToken); + delayedRegistration.Succeeded.ShouldBeFalse(); + var oldOwnerCommand = await host.Ask(new DriverHostActor.ApplyAcquisitionDemand( + "same", [], TimeSpan.Zero, 3, OwnerGeneration: owner.Generation, KeyGeneration: current.KeyGeneration), PresenceBudget, + TestContext.Current.CancellationToken); + oldOwnerCommand.Succeeded.ShouldBeFalse(); + var newOwnerKey = await host.Ask( + new DriverHostActor.OpenAcquisitionDemand("same", newOwner.Generation), PresenceBudget, TestContext.Current.CancellationToken); + newOwnerKey.Succeeded.ShouldBeTrue(); + (await host.Ask(new DriverHostActor.ApplyAcquisitionDemand( + "same", [], TimeSpan.Zero, 1, OwnerGeneration: newOwner.Generation, KeyGeneration: newOwnerKey.KeyGeneration), PresenceBudget, + TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue("a recreated bridge can restart its per-key revision sequence"); + } + + [Fact] + public async Task Alarm_only_desired_change_while_acquisition_is_pending_reaches_the_same_driver() + { + var db = NewInMemoryDbFactory(); + var revision = RevisionHash.Parse(new string('3', 64)); + var deployment = V3ArtifactSeeder.SeedV3Deployment(db, revision, + [("DI-1", "Modbus", "dev1", "speed", "Double", false)], [], enabled: true); + var factory = new Factory(); + using var hub = HubTest.Create(); + var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1)); + var coordinator = CreateTestProbe(); + var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref, + driverFactory: factory, localRoles: new HashSet { "driver" }, + dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance, + virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher, + acquisitionCapacity: new SubscriptionAcquisitionCapacity(8))); + V3ArtifactSeeder.Dispatch(host, coordinator, deployment, revision); + AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var driver = factory.Driver!; + const string speed = "Plant/Modbus/dev1/speed"; + AwaitAssert(() => driver.LegacyRefs.ShouldContain(speed), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var pending = host.Ask( + new DriverHostActor.ApplyAcquisitionDemand("DI-1", ["grpc"], TimeSpan.FromMilliseconds(200), 17), + PresenceBudget, TestContext.Current.CancellationToken); + await driver.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask() + .WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + await host.Ask( + new DriverHostActor.SetLegacySubscriptionsForTest("DI-1", [speed], ["alarm-X"]), PresenceBudget, + TestContext.Current.CancellationToken); + driver.Complete(); + (await pending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue(); + var alarms = await driver.AlarmRequests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask() + .WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + alarms.ShouldBe(["alarm-X"]); + factory.Driver.ShouldBeSameAs(driver); + } + + [Fact] + public async Task Supervised_host_restart_gives_same_bridge_a_new_proof_and_fences_old_commands() + { + var db = NewInMemoryDbFactory(); + var revision = RevisionHash.Parse(new string('6', 64)); + var deployment = V3ArtifactSeeder.SeedV3Deployment(db, revision, [], [], enabled: true); + var coordinator = CreateTestProbe(); + var capacity = new SubscriptionAcquisitionCapacity(2); + var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref, + localRoles: new HashSet { "driver" }, dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), + virtualTagEvaluator: NullVirtualTagEvaluator.Instance, virtualTagHostOverride: CreateTestProbe().Ref, + acquisitionCapacity: capacity)); + V3ArtifactSeeder.Dispatch(host, coordinator, deployment, revision); + var ownerId = Guid.NewGuid(); + var serial = capacity.NextOwnerSerial(); + var first = await host.Ask( + new DriverHostActor.RegisterAcquisitionOwner(ownerId, serial), PresenceBudget, TestContext.Current.CancellationToken); + var oldKey = await host.Ask( + new DriverHostActor.OpenAcquisitionDemand("driver", first.Generation), PresenceBudget, TestContext.Current.CancellationToken); + var priorControl = capacity.ControlGeneration; + host.Tell(new DriverHostActor.CrashForTest()); + AwaitAssert(() => capacity.ControlGeneration.ShouldBeGreaterThan(priorControl), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + var restarted = await host.Ask( + new DriverHostActor.RegisterAcquisitionOwner(ownerId, serial), PresenceBudget, TestContext.Current.CancellationToken); + restarted.Succeeded.ShouldBeTrue(); + restarted.Generation.ShouldBeGreaterThan(first.Generation); + var newKey = await host.Ask( + new DriverHostActor.OpenAcquisitionDemand("driver", restarted.Generation), PresenceBudget, TestContext.Current.CancellationToken); + newKey.Succeeded.ShouldBeTrue(); + var stale = await host.Ask(new DriverHostActor.ApplyAcquisitionDemand( + "driver", [], TimeSpan.Zero, 1, OwnerGeneration: first.Generation, KeyGeneration: oldKey.KeyGeneration), PresenceBudget, + TestContext.Current.CancellationToken); + stale.Succeeded.ShouldBeFalse(); + (await host.Ask(new DriverHostActor.ApplyAcquisitionDemand( + "driver", [], TimeSpan.Zero, 1, OwnerGeneration: restarted.Generation, KeyGeneration: newKey.KeyGeneration), PresenceBudget, + TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue(); + } + + [Fact] + public async Task Idle_bridge_re_registers_after_real_host_restart_before_opening_a_new_key() + { + var db = NewInMemoryDbFactory(); + var revision = RevisionHash.Parse(new string('7', 64)); + var deployment = V3ArtifactSeeder.SeedV3Deployment(db, revision, + [("DI-1", "Modbus", "dev1", "speed", "Double", false)], [], enabled: true); + var factory = new Factory(); + using var hub = HubTest.Create(); + var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1)); + var coordinator = CreateTestProbe(); + var capacity = new SubscriptionAcquisitionCapacity(4); + var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref, + driverFactory: factory, localRoles: new HashSet { "driver" }, + dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance, + virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher, acquisitionCapacity: capacity)); + V3ArtifactSeeder.Dispatch(host, coordinator, deployment, revision); + AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var original = factory.Driver!; + const string reference = "Plant/Modbus/dev1/speed"; + AwaitAssert(() => original.LegacyRefs.ShouldContain(reference), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + using var source = new DriverHostSubscriptionDemandSource(host, new UpstreamDemandRegistry(4, 8), 4, 8, PresenceBudget, capacity); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + var firstTask = source.AcquireAsync(Authorized("DI-1", reference), settings, TestContext.Current.CancellationToken).AsTask(); + await original.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + original.Complete(); + var first = await firstTask.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + first.Status.ShouldBe(DataItemStatus.Good); + first.Lease.ShouldNotBeNull().Dispose(); + await source.WaitForDriverIdleForTest("DI-1").WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + + var priorControl = capacity.ControlGeneration; + host.Tell(new DriverHostActor.CrashForTest()); + AwaitAssert(() => capacity.ControlGeneration.ShouldBeGreaterThan(priorControl), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + AwaitAssert(() => factory.Driver.ShouldNotBeSameAs(original), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var replacement = factory.Driver!; + AwaitAssert(() => replacement.LegacyRefs.ShouldContain(reference), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var secondTask = source.AcquireAsync(Authorized("DI-1", reference), settings, TestContext.Current.CancellationToken).AsTask(); + await replacement.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + secondTask.IsCompleted.ShouldBeFalse(); + replacement.Complete(); + var second = await secondTask.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + second.Status.ShouldBe(DataItemStatus.Good); + second.Lease.ShouldNotBeNull().Dispose(); + } + + [Fact] + public async Task Canceled_opens_release_host_keys_even_if_their_allocated_replies_arrive_late() + { + var db = NewInMemoryDbFactory(); + var revision = RevisionHash.Parse(new string('8', 64)); + var deployment = V3ArtifactSeeder.SeedV3Deployment(db, revision, [], [], enabled: true); + var coordinator = CreateTestProbe(); + var capacity = new SubscriptionAcquisitionCapacity(2); + var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref, + localRoles: new HashSet { "driver" }, dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), + virtualTagEvaluator: NullVirtualTagEvaluator.Instance, virtualTagHostOverride: CreateTestProbe().Ref, + acquisitionCapacity: capacity)); + V3ArtifactSeeder.Dispatch(host, coordinator, deployment, revision); + using var source = new DriverHostSubscriptionDemandSource(host, new UpstreamDemandRegistry(2, 4), 2, 4, PresenceBudget, capacity); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + for (var i = 0; i < 6; i++) + { + var driver = $"canceled-{i}"; + var allocated = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await host.Ask( + new DriverHostActor.GateOpenReplyForTest(driver, allocated, release.Task), PresenceBudget, + TestContext.Current.CancellationToken); + using var canceled = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + var pending = source.AcquireAsync(Authorized(driver, "tag"), settings, canceled.Token).AsTask(); + try + { + await allocated.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + canceled.Cancel(); + await Should.ThrowAsync(() => pending); + } + finally { release.TrySetResult(); } + await source.WaitForDriverIdleForTest(driver).WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + var count = await host.Ask( + new DriverHostActor.GetOpenAcquisitionCountForTest(), PresenceBudget, TestContext.Current.CancellationToken); + count.Count.ShouldBe(0, "cancellation must reclaim the key even when the Open reply was lost"); + } + } + + [Fact] + public async Task Lost_abort_ack_is_reconciled_before_a_fresh_acquisition_uses_the_key() + { + var db = NewInMemoryDbFactory(); + var revision = RevisionHash.Parse(new string('9', 64)); + var deployment = V3ArtifactSeeder.SeedV3Deployment(db, revision, + [("DI-1", "Modbus", "dev1", "speed", "Double", false)], [], enabled: true); + var factory = new Factory(); + using var hub = HubTest.Create(); + var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1)); + var coordinator = CreateTestProbe(); + var capacity = new SubscriptionAcquisitionCapacity(2); + var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref, + driverFactory: factory, localRoles: new HashSet { "driver" }, + dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance, + virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher, acquisitionCapacity: capacity)); + V3ArtifactSeeder.Dispatch(host, coordinator, deployment, revision); + AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var driver = factory.Driver!; + const string reference = "Plant/Modbus/dev1/speed"; + AwaitAssert(() => driver.LegacyRefs.ShouldContain(reference), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + using var source = new DriverHostSubscriptionDemandSource(host, new UpstreamDemandRegistry(2, 4), 2, 4, + TimeSpan.FromSeconds(2), capacity, abortRetryDelay: TimeSpan.Zero); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + var allocated = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseOpen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var aborted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseAbort = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await host.Ask( + new DriverHostActor.GateOpenReplyForTest("DI-1", allocated, releaseOpen.Task), PresenceBudget, + TestContext.Current.CancellationToken); + await host.Ask( + new DriverHostActor.GateAbortReplyForTest("DI-1", aborted, releaseAbort.Task), PresenceBudget, + TestContext.Current.CancellationToken); + using var canceled = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + var canceledOpen = source.AcquireAsync(Authorized("DI-1", reference), settings, canceled.Token).AsTask(); + try + { + await allocated.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + canceled.Cancel(); + await Should.ThrowAsync(() => canceledOpen); + releaseOpen.TrySetResult(); + await aborted.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + await source.WaitForOpenAbortFailureForTest("DI-1").WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + var count = await host.Ask( + new DriverHostActor.GetOpenAcquisitionCountForTest(), PresenceBudget, TestContext.Current.CancellationToken); + count.Count.ShouldBe(0, "the host processed the abort even though its acknowledgement was lost"); + releaseAbort.TrySetResult(); + + var retry = source.AcquireAsync(Authorized("DI-1", reference), settings, TestContext.Current.CancellationToken).AsTask(); + await driver.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask() + .WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + retry.IsCompleted.ShouldBeFalse("the fresh driver operation still needs its own acknowledgement"); + driver.Complete(); + var accepted = await retry.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + accepted.Status.ShouldBe(DataItemStatus.Good); + accepted.Lease.ShouldNotBeNull().Dispose(); + } + finally { releaseOpen.TrySetResult(); releaseAbort.TrySetResult(); } + } + + [Fact] + public async Task Capacity_pressure_reconciles_lost_abort_ack_for_an_inactive_different_driver() + { + var db = NewInMemoryDbFactory(); + var revision = RevisionHash.Parse(new string('a', 64)); + var deployment = V3ArtifactSeeder.SeedV3Deployment(db, revision, + [("DI-A", "Modbus", "devA", "speedA", "Double", false), + ("DI-B", "ModbusB", "devB", "speedB", "Double", false)], [], enabled: true); + var factory = new Factory(); + using var hub = HubTest.Create(); + var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1)); + var coordinator = CreateTestProbe(); + var capacity = new SubscriptionAcquisitionCapacity(1); + var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref, + driverFactory: factory, localRoles: new HashSet { "driver" }, + dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance, + virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher, acquisitionCapacity: capacity)); + V3ArtifactSeeder.Dispatch(host, coordinator, deployment, revision); + AwaitAssert(() => factory.Drivers.Count.ShouldBe(2), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var driverB = factory.Drivers["DI-B"]; + const string referenceB = "Plant/ModbusB/devB/speedB"; + AwaitAssert(() => driverB.LegacyRefs.ShouldContain(referenceB), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + using var source = new DriverHostSubscriptionDemandSource(host, new UpstreamDemandRegistry(2, 4), 1, 4, + TimeSpan.FromSeconds(2), capacity, abortRetryDelay: TimeSpan.Zero); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + var allocated = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseOpen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var aborted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseAbort = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await host.Ask( + new DriverHostActor.GateOpenReplyForTest("DI-A", allocated, releaseOpen.Task), PresenceBudget, TestContext.Current.CancellationToken); + await host.Ask( + new DriverHostActor.GateAbortReplyForTest("DI-A", aborted, releaseAbort.Task), PresenceBudget, TestContext.Current.CancellationToken); + using var canceled = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + var old = source.AcquireAsync(Authorized("DI-A", "Plant/Modbus/devA/speedA"), settings, canceled.Token).AsTask(); + try + { + await allocated.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + canceled.Cancel(); + await Should.ThrowAsync(() => old); + releaseOpen.TrySetResult(); + await aborted.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + await source.WaitForOpenAbortFailureForTest("DI-A").WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + releaseAbort.TrySetResult(); + + var current = source.AcquireAsync(Authorized("DI-B", referenceB), settings, TestContext.Current.CancellationToken).AsTask(); + var entered = driverB.Requests.Reader.WaitToReadAsync(TestContext.Current.CancellationToken).AsTask(); + var winner = await Task.WhenAny(current, entered).WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + if (ReferenceEquals(winner, current)) + { + (await current).Status.ShouldBe(DataItemStatus.ResourceExhausted); + await source.WaitForDriverIdleForTest("DI-A").WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + current = source.AcquireAsync(Authorized("DI-B", referenceB), settings, TestContext.Current.CancellationToken).AsTask(); + } + (await entered.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).ShouldBeTrue(); + driverB.Complete(); + var accepted = await current.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + accepted.Status.ShouldBe(DataItemStatus.Good); + accepted.Lease.ShouldNotBeNull().Dispose(); + } + finally { releaseOpen.TrySetResult(); releaseAbort.TrySetResult(); } + } + + private static SubscriptionAuthorizedView Authorized(string driver, string reference) + { + var view = new DataView(new("cluster", "urn:raw", "string", reference), DataRealm.Raw, null, 0, "subject"); + return new(view, SourceKey.ForDriver("cluster", driver, reference, "node-a", "inc"), + new("node-a", "inc", "Primary", 1, 1), + new(view, reference, "Variable", DataValueKind.Double, -1, [], false, DataOperations.Subscribe, 1, reference, null, false), + "principal", "export", new(DataTargetMode.Node, "cluster", "node-a"), DataConsistency.Primary, () => true); + } + + [Fact] + public async Task Alarm_deployment_during_pending_acquisition_reaches_the_replacement_driver() + { + var db = NewInMemoryDbFactory(); + var revA = RevisionHash.Parse(new string('4', 64)); + var revB = RevisionHash.Parse(new string('5', 64)); + var firstDeploy = V3ArtifactSeeder.SeedV3Deployment(db, revA, + [("DI-1", "Modbus", "dev1", "speed", "Double", false)], [], enabled: true); + var factory = new Factory(); + using var hub = HubTest.Create(); + var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1)); + var coordinator = CreateTestProbe(); + var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref, + driverFactory: factory, localRoles: new HashSet { "driver" }, + dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance, + virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher, + acquisitionCapacity: new SubscriptionAcquisitionCapacity(8))); + V3ArtifactSeeder.Dispatch(host, coordinator, firstDeploy, revA); + AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var old = factory.Driver!; + AwaitAssert(() => old.LegacyRefs.ShouldContain("Plant/Modbus/dev1/speed"), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + var pending = host.Ask( + new DriverHostActor.ApplyAcquisitionDemand("DI-1", ["grpc"], TimeSpan.FromMilliseconds(200), 17), + PresenceBudget, TestContext.Current.CancellationToken); + await old.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask() + .WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + var secondDeploy = V3ArtifactSeeder.SeedV3Deployment(db, revB, + [("DI-1", "Modbus", "dev1", "speed", "Double", false), + ("DI-1", "Modbus", "dev1", "alarmX", "Double", false)], [], enabled: true, + tagConfigByTag: new Dictionary { ["alarmX"] = """{"alarm":{"alarmType":"AlarmCondition","severity":500}}""" }); + V3ArtifactSeeder.Dispatch(host, coordinator, secondDeploy, revB); + AwaitAssert(() => factory.Driver.ShouldNotBeSameAs(old), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var replacement = factory.Driver!; + old.Complete(); + var acquisition = await replacement.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask() + .WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + acquisition.FullReferences.ShouldContain("grpc"); + replacement.Complete(); + var alarms = await replacement.AlarmRequests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask() + .WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); + alarms.ShouldContain("Plant/Modbus/dev1/alarmX"); + _ = pending; + } + + private sealed class Factory : IDriverFactory + { + internal TestDriver? Driver; + internal readonly ConcurrentDictionary Drivers = new(StringComparer.Ordinal); + public IReadOnlyCollection SupportedTypes => ["Modbus"]; + public IDriver? TryCreate(string type, string id, string config) + { + var driver = new TestDriver(id); + Drivers[id] = driver; + return Driver = driver; + } + } + private sealed class TestDriver(string id) : StubDriver, IDriver, ISubscribable, IAcknowledgedAcquisitionSource, IAlarmSource + { + string IDriver.DriverInstanceId => id; + private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly Channel Requests = Channel.CreateUnbounded(); + internal readonly Channel> AlarmRequests = Channel.CreateUnbounded>(); + internal IReadOnlyList LegacyRefs = []; + internal int LegacySubscribeCount; + public event EventHandler? OnDataChange { add { } remove { } } + public event EventHandler? OnAlarmEvent { add { } remove { } } + public Task SubscribeAsync(IReadOnlyList refs, TimeSpan interval, CancellationToken ct) + { + LegacyRefs = refs.ToArray(); + Interlocked.Increment(ref LegacySubscribeCount); + return Task.FromResult(new Handle()); + } + public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask; + public async Task SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, + Action callback, CancellationToken ct) + { + Requests.Writer.TryWrite(request); + await _completion.Task.WaitAsync(ct); + return new(new Handle(), request.RequestedSamplingInterval, request.DesiredRevision, request.ProducerIncarnation); + } + internal void Complete() => _completion.TrySetResult(); + public Task SubscribeAlarmsAsync(IReadOnlyList refs, CancellationToken ct) + { + AlarmRequests.Writer.TryWrite(refs.ToArray()); + return Task.FromResult(new AlarmHandle()); + } + public Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask; + public Task AcknowledgeAsync(IReadOnlyList acknowledgements, CancellationToken ct) => Task.CompletedTask; + private sealed class AlarmHandle : IAlarmSubscriptionHandle { public string DiagnosticId => "alarm"; } + private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "host-test"; } + } +}