Merge H3: OPC UA HistoryRead on projected nodes over gRPC data connections
v2-ci / unit-tests (push) Waiting to run

This commit is contained in:
Joseph Doherty
2026-11-24 07:48:11 -05:00
52 changed files with 4534 additions and 112 deletions
+24 -1
View File
@@ -253,12 +253,35 @@ continuation points up to `--max`. `--events` cannot be combined with `--modifie
| `--start` | Start time in ISO 8601 UTC format, e.g. `2026-01-15T08:00:00Z` (default: 24 hours ago) |
| `--end` | End time in ISO 8601 UTC format, e.g. `2026-01-15T09:00:00Z` (default: now) |
| `--max` | Maximum number of values (default: 1000) |
| `--aggregate` | Aggregate function: Average, Minimum, Maximum, Count, Start, End, StandardDeviation, TimeAverage, TimeAverage2, Total, Total2, Interpolative |
| `--aggregate` | Aggregate function: Average, Minimum, Maximum, Count, Start, End, StandardDeviation, TimeAverage, TimeAverage2, Total, Total2, Interpolative. Since H3 the request asks for the server's default aggregate configuration (`AggregateConfiguration.UseServerCapabilitiesDefaults = true`); it used to send the SDK's all-zero configuration, which OtOpcUa refuses (`BadAggregateConfigurationRejected`, #677) — a behaviour change against a third-party server that honoured the all-zero settings |
| `--interval` | Processing interval in milliseconds for aggregates (default: 3600000) |
| `--modified` | Read modified-value history (Part 11 `IsReadModified`) instead of raw samples |
| `--events` | Read event history (Part 11 HistoryReadEvents) from an event notifier instead of raw samples |
| `--fields` | With `--events`: comma-separated event fields to select (default `EventId,EventType,Time,SourceName,Severity,Message,ConditionName,SourceNode`) |
| `--of-type` | With `--events`: keep only events of this type or a subtype (an `OfType` where-clause), e.g. `i=2955` |
| `--at-time` | HistoryRead-AtTime at these comma-separated ISO 8601 UTC times; prints the status, the rows and each value's CLR type |
| `--page-size` | Raw only: page by hand at this `NumValuesPerNode`, printing every page as `Page k: <status> values=<n> continuation=<yes\|no>[ resumed]` (a refused page is printed, never thrown) |
| `--pause-after-page` / `--resume-when-file` / `--pause-timeout` | With `--page-size`: after page k hold the session (and its continuation point) until the file exists, then resume |
| `--held-marker-file` | With `--page-size`: create this (empty) file when the read reaches its pause, abandon or release point |
| `--fresh-after-failure` | With `--page-size`: after a refused resumed page, issue one fresh read of the same window (`Fresh: …`) |
| `--abandon-after-page` | With `--page-size`: stop after page k WITHOUT releasing its continuation point — the disconnect (session close) releases it |
| `--release-after-page` | With `--page-size`: send `releaseContinuationPoints` for page k's point and stop |
| `--hold-seconds` | With `--abandon-after-page` / `--release-after-page`: keep the session open this long before disconnecting |
The hand-paged modes exist for continuation-point lifecycle checks — most usefully on **projected** nodes of a gRPC data
connection (`DataConnections.md` §"OPC UA HistoryRead on projected nodes"), where a resumed page is bound to the origin endpoint
that issued it: pause after page 1, fail the origin over, create the resume file, and the resumed page prints
`BadContinuationPointInvalid` while `--fresh-after-failure` shows the fresh read moving to the new endpoint.
```bash
# Page 1 of a projected node, hold the session, resume once /tmp/go exists; then one fresh read if the resume is refused
otopcua-cli historyread -u opc.tcp://localhost:4841/OtOpcUa -U apikey -P "$KEY" -n "$P" \
--start 2026-11-20T10:00:00Z --end 2026-11-20T11:00:00Z --page-size 5 \
--pause-after-page 1 --resume-when-file /tmp/go --fresh-after-failure
# AtTime on an integer node
otopcua-cli historyread -u opc.tcp://localhost:4841/OtOpcUa -U apikey -P "$KEY" -n "$P" \
--at-time 2026-11-20T10:00:00Z,2026-11-20T10:00:05Z
```
### historyupdate
+67 -2
View File
@@ -192,8 +192,73 @@ local OPC UA clients keep at least one slot. At N = 1 there is no reservation: t
**Consistency.** History follows the connection's consistency. `ReadyReplica` is allowed; the newest seconds can lag on a
secondary while its continuous-historization outbox drains.
**Not supported yet.** OPC UA clients reading history on projected nodes of the consumer (H3); HistoryReadEvents and
modified-value reads (deferred); **HistoryUpdate is never forwarded**.
**Not supported yet.** HistoryReadEvents and modified-value reads (deferred); **HistoryUpdate is never forwarded**.
## OPC UA HistoryRead on projected nodes (H3)
Since H3 an OPC UA client of the CONSUMER can HistoryRead (Raw, Processed, AtTime) a projected variable in the
`https://zb.com/otopcua/mapped/raw|uns` namespaces exactly as it reads a local one; the consumer forwards the read over the
mapping's deployed connection (the runtime path above) and returns the origin's Part 11 answer verbatim — statuses, info bits,
timestamps (absent stays absent), values typed as the catalog says (a disagreeing value kind is `BadTypeMismatch`).
**What a client sees.** A projected variable is `Historizing = true` with the `HistoryRead` access-level bit **only** when the
mapping grants `HistoryRead` (masked by the export's) **and** the origin's negotiated metadata says the node is historizing for
this principal (`HistoryInfo`, bit 32). Otherwise it carries `CurrentRead` only and the SDK answers
`BadHistoryOperationUnsupported` before any remote call. The `HistoryWrite` bit is never set: HistoryUpdate is not forwarded.
**Grants** — all default off, and all required **even with `Security:Acl:Enabled=false`**, because mapped nodes always enforce the
mapping gate:
| Where | What |
|---|---|
| Consumer `DataConnection.AllowedOperations` | `HistoryRead` (32) |
| Consumer `RemoteNamespaceMapping.AllowedOperations` | `HistoryRead` (32) |
| Consumer node ACL | `NodePermissions.HistoryRead` for the client's principal on the `RemoteNamespaceMapping` scope (or a scope above it) |
| Origin `DataExport.AllowedOperations` + origin node ACL | as for the runtime path above |
Without the local grant (or without the mapping bit) the node answers `BadUserAccessDenied` — a local decision, distinct from the
origin's `BadHistoryOperationUnsupported`. An origin-side denial, an unhistorized node and an unknown node stay indistinguishable
(the origin's metadata does not mark the node historizing, so the consumer refuses it `BadHistoryOperationUnsupported`).
**Mixed batches.** One HistoryRead may mix local and projected nodes: local nodes are served by the local historian exactly as
before, projected nodes remotely, every result in its own slot. The remote half runs under the same process-wide HistoryRead batch
limiter (`ServerHistorian:MaxConcurrentHistoryReadBatches`, N) and never holds the node-manager lock; projected reads and remote peers
reading this node hold, TOGETHER (one shared semaphore), at most N − max(1, N/4) of the N slots, so a slow origin cannot starve local HistoryRead/HistoryUpdate —
past that the projected half is `BadTooManyOperations`, unsent. A fault or timeout of the remote call (including the connection's
capability probe) fails only the projected half, per node (`BadTimeout` when the deadline fired), and releases its continuation
points. Remote calls are runs of consecutive request positions that share a connection, details and (for resumes) the issuing
endpoint, read in request order and split into sub-batches at the connection's batch size; the gRPC connection splits again at the origin's advertised
`MaxBatchItems` from the capabilities each call negotiates (no extra probe) — a large batch is never refused as a whole.
**Continuation points.** A projected read's continuation point lives in the client's OPC UA session like a local one (a `Remote`
cursor; capped by `MaxHistoryContinuationPoints`, oldest evicted). It wraps the origin's token and binds the caller (principal, key,
credential version), the mapping id **and revision**, the deployed connection route, the projection generation, the origin view and
the origin serving identity; a resume resends the **original** request details (the origin binds their hash — a client that changes
details on resume gets what it first asked for, as locally). Rules:
- **A fresh read may move endpoint** within its deadline (a failed SOURCE node ⇒ the next endpoint); **a resumed read never moves**.
- A mapping revision change, a connection redeploy / lease expiry, a failover or origin restart (serving node / incarnation /
generation / role), a projection rebuild, another caller, or an origin history-epoch bump (an origin address-space removal or
rebuild) ⇒ `BadContinuationPointInvalid`; read again from the start.
- **Release:** `releaseContinuationPoints`, the session's close, an eviction and a refused save each forward one best-effort
`ReleaseHistoryAsync` per connection (releases coalesce for ~25 ms, so a session close sends one call per origin). The origin's
60 s idle expiry is the backstop.
- Uncapped Raw (`NumValuesPerNode = 0`) returns the origin's continuation point (Part 11 permits a short page + CP): the origin pages
at its `MaxHistoryValuesPerPage` ceiling.
**Limits.**
| Limit | Effect |
|---|---|
| `RemoteNamespaceMapping.MaxHistoryAssemblyBytesPerRequest` (16 MiB) | One budget per request, shared across the batch (the tightest mapping in the batch). Nodes are charged in request order (calls run in request order, and at most one node per 256 B of the remaining budget is sent); once a node does not fit, it and every later projected node with data is `BadTooManyOperations` (never a partial answer; its origin cursor is released). |
| `ServerHistorian:HistoryReadDeadline` (consumer, 60 s) | ONE deadline per request, covering the local half too: the local nodes of a mixed batch are served first, so a slow local historian leaves the projected nodes less (or no) time — they answer `BadTimeout`. Each remote call is capped by the remaining deadline and `DataConnection.HistoryTimeoutMilliseconds` ⇒ `BadTimeout`. A cancelled request is never counted as an origin fault; a cancel that is neither the caller's nor the deadline (a connection redeployed mid-read) is `BadNoCommunication` / `BadContinuationPointInvalid`. |
| Aggregates | An aggregate the consumer cannot name is `BadAggregateNotSupported` unsent; one the origin's backend refuses (unknown to it, or not valid for the node's type — #897) comes back `BadAggregateNotSupported` from the origin. The consumer's `HistoryServerCapabilities/AggregateFunctions` does not describe remote backends. |
Modified-value reads (`IsReadModified`) and HistoryReadEvents on projected nodes are refused `BadHistoryOperationUnsupported`.
**Client CLI.** Resolve projected NodeIds by browsing from the mapping anchor (never construct `p1.` ids), then
`otopcua-cli historyread -n "<printed NodeId>" …`; `--page-size`, `--pause-after-page` and `--abandon-after-page` exercise the
continuation lifecycle (`Client.CLI.md`). Live gate: `scripts/validation/grpc-data/history_gate.py` (H01–H06, README).
## Feature boundary
+181
View File
@@ -0,0 +1,181 @@
# H3 evidence — consumer OPC UA projection of remote history
Phase H3 of `docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`, 2026-11-24.
## What changed
- **Projected access level.** `ProjectedVariableDefinition.Historizing` (set by the applier and the exact-item renewal from
`ProjectedHistoryAccess.Advertises(proof)` = mapping∧export grant `HistoryRead` **and** the origin's negotiated
`HistoryInfo.Historizing`). Only then is the node `Historizing` with `CurrentRead | HistoryRead`; it follows renewals in place
(`ApplyProjectedHistorizing`, under `Lock`, a change-mask notify). `HistoryWrite` is never set.
- **`OpcUaServer/IProjectedHistoryAccess.cs`**: SDK-free contract — `ReadAsync(caller, DataHistoryDetails, nodes, deadline, ct)`,
`ProjectedHistoryNode(NodeId, AggregateId, Resume)`, `ProjectedHistoryOutcome(status, OriginHistorySample[], next)` and the
opaque `ProjectedHistoryContinuation` (idempotent `Release`, `TryClaimForResume`).
- **Override split** (`OpcUaServer/ProjectedHistoryRead.cs`, a NM partial). Raw/Processed/AtTime overrides authorize as before,
then `ServeHistoryReadSplit`: with no projected handle the H1 adapter is called exactly as before; otherwise local handles go to
the H1 port and projected handles (mapped/raw, mapped/uns namespaces) to `ProjectedHistoryAccess`, every outcome written to its
handle's own `results[i]`/`errors[i]`. The remote half runs under the same process-wide batch limiter, block-bridged once per
batch; the SDK has released `Lock` before it dispatches the overrides and nothing here takes it. Modified reads ⇒
`BadHistoryOperationUnsupported`; an aggregate the consumer cannot name ⇒ `BadAggregateNotSupported`, unsent.
- **`HistoryCursorKind.Remote`** + `HistoryContinuationState.Remote`: the cursor lives in the SDK session store, bound to the
node (realm, identifier, namespace tag) and the consumer's history epoch. A take marks the SDK point `Taken`; **any other
dispose** of the point (session close, oldest-eviction, `releaseContinuationPoints` → `ReleaseHistory`, a faulted request)
calls `Remote.Release()` (decompiled SDK 2.0.1 `SessionContinuationPoints`: `Clear`, `AddHistoryContinuationPoint` eviction,
`ReleaseHistory`, `ReleaseSavedHistory` all dispose the stored value). A cursor of another node/kind/epoch is refused
`BadContinuationPointInvalid` and released.
- **`Runtime/DataConnections/ProjectedHistoryAccess.cs`**: per node a `DataOperations.HistoryRead` demand through
`ProjectedDataAccess.TryAcquire` (allowlist extended; requires `definition.Historizing`; policy `AuthorizeMapped(HistoryRead)` ⇒
mapping bit + local `NodePermissions.HistoryRead` on the mapping scope, ACLs on or off), described by
`TryDescribeHistoryDemand` (mapping id/revision, connection, origin metadata, serving, generation). Groups =
(connection, details, resumed endpoint|fresh) so a resumed item never shares a call with items that may move. The
`RemoteCursor` binds caller key (principal, key, credential version), mapping id+revision, connection id + lease `RouteIdentity`,
projection generation, origin view, serving (node, incarnation, serving generation, role), the ORIGINAL details and aggregate;
`CursorMatches` re-checks all of it on resume, and the route identity before the call; any change ⇒ `BadContinuationPointInvalid`
and the origin token released. Per-request assembly budget = min `MaxHistoryAssemblyBytesPerRequest` of the batch's mappings,
charged in request order across groups; a node that does not fit and every later node ⇒ `BadTooManyOperations` (its origin
cursor released). Deadline = min(remaining `HistoryReadDeadline`, `HistoryTimeoutMilliseconds` — the connection applies the
latter) ⇒ `BadTimeout`; a cancel is never an origin fault. Releases coalesce per connection (25 ms) into one
`ReleaseHistoryAsync`. Values: Raw/AtTime checked against the catalog kind (`BadTypeMismatch`); Processed values keep their
aggregate's own scalar kind.
- **`DataPlaneAuthorizer`**: mapped HistoryRead opened deliberately via an explicit allowlist (Browse/Read/Write*/TransferSubscriptions/
HistoryRead); every other mapped operation stays closed. **DI/host**: `ProjectedHistoryAccess` registered beside
`ProjectedDataAccess`; `OtOpcUaServerHostedService` wires `NodeManager.ProjectedHistoryAccess`.
- **H2 pin replaced**: `HistoryRead_on_a_projected_node_stays_a_clean_refusal_until_H3` (Runtime) became
`Granted_projected_HistoryRead_is_served_verbatim…` (granted ⇒ served) and `Without_the_local_HistoryRead_grant…` (⇒
`BadUserAccessDenied`, unsent), both tagged H2 + H3.
- **Client.** `IOpcUaClientService.HistoryReadPageAsync` (one page verbatim) and CLI `historyread --page-size / --pause-after-page /
--resume-when-file / --held-marker-file / --fresh-after-failure / --abandon-after-page / --release-after-page / --hold-seconds /
--at-time`. **Defect found by the gate (H02, pre-existing):** Client.Shared processed reads sent the SDK's default
`AggregateConfiguration` (all false/0), which this server refuses `BadAggregateConfigurationRejected` (#677) — CLI/UI
`--aggregate` never worked against OtOpcUa; now `UseServerCapabilitiesDefaults = true` (OI regression test, red without).
- **Defect found by the gate (H02, H3):** projected Processed values were decoded against the node's catalog kind (a Double
Average of a UInt16 node ⇒ null + `BadTypeMismatch` per interval under a Good result). Fixed; the wire test now asserts the value.
## Tests
| Suite | What |
|---|---|
| O `ProjectedHistoryReadTests` (7) | access bit only when historizing, never HistoryWrite; allow/deny with ACLs **off and on** (no local grant, no mapping bit, no identity ⇒ `BadUserAccessDenied`, unsent); mixed local+projected batch keeps slots (one remote call); Remote cursor resumes once (same object), single use, wrong node ⇒ invalid + released, `releaseContinuationPoints` and session close (store `Clear`) release; bad remote answer keeps no cursor; consumer-unknown aggregate and modified read unsent; absent bounds |
| R `GrpcDataConfiguredDiscoveryWireTests` H3 (12) | real consumer SDK session + real projection stack + real origin (`LocalDataServices` over a real NM history port and `PeerHistoryContinuationStore`): page-through verbatim to completion (origin store 0); no local grant ⇒ `BadUserAccessDenied` unsent; session close ⇒ origin continuations 0 and exactly one release call; `releaseContinuationPoints`; resume after lease expiry (route rotated) and after an origin epoch bump ⇒ invalid, fresh read Good; uncapped Raw returns the origin CP; `BadAggregateNotSupported` both ways + a served Average's value; Historizing/AccessLevel follow the grant; assembly budget shared across the batch (25 kB ⇒ 2 of 3, 15 kB ⇒ 1, 1.2 kB ⇒ 0, refused in request order, never partial) |
| R `GrpcDataProjectedHistoryCursorTests` (12) | resume rule: mapping revision change, another mapping/connection, projection rebuild, failover (node), origin restart (incarnation), serving generation, role, origin view, another caller, rotated credential ⇒ refused; epoch-only change resumes |
| OI `GrpcDataProjectedHistoryWireTests` (6) | real consumer session → real origin NM history port: mixed batch slots + page-through (ACL off/on), single use, session close ⇒ origin cursor store 0 (one release), no grant ⇒ denied unsent (ACL off/on); Client.Shared aggregate + page API |
| CLI `HistoryReadPagedCommandTests` (6) | paging, pause/resume + fresh, abandon/release + held marker, AtTime, option validation |
## Gates
| Gate | Result |
|---|---|
| `dotnet build ZB.MOM.WW.OtOpcUa.slnx` | 0 warnings, 0 errors |
| `run-unit-phase.py H3` (new key: OpcUaServer.Tests + Runtime.Tests) | passed (at `af0618341`) |
| `run-unit-phase.py H2` | passed (at `af0618341`) |
| `run-unit-phase.py H1, X0, P01–P09` | all passed (at `07eeea2bd`; later commits touch Client/CLI/rig and one Runtime decode path covered by H3/H2 reruns) |
| Full unit suites (`Category!=E2E&Category!=LiveIntegration`) | OpcUaServer 1415 (+1 skip), Runtime 1882 (+3 skips), Host 479, Client.CLI 224, Client.Shared 361, Client.UI 131 — all green |
| OpcUaServer.IntegrationTests `Feature=GrpcData` + history classes | 87 passed, 2 skips (AVEVA live) |
| Rig harness unit tests (`scripts/validation/grpc-data/tests`) | 296 passed |
The runner accepts unit projects only, so OI is run separately (as H1 did).
## Live gate — H01–H06 on both origin backends
Standalone rig (`scripts/validation/grpc-data`, OrbStack, macOS), fresh run per backend at `af0618341`, normal build-hash checks
(no `--pinned-build`), recipe in the rig README §"H3 projected-history gate":
```bash
python3 scripts/validation/grpc-data/rig.py up --run-id h3f-<backend> --history --history-backend <sqlserver|questdb> --timeout 900
python3 scripts/validation/grpc-data/rig.py seed --run-id h3f-<backend>
sleep 75
python3 scripts/validation/grpc-data/rig.py deploy --run-id h3f-<backend> --timeout 300
python3 scripts/validation/grpc-data/history_gate.py --run-id h3f-<backend>
python3 scripts/validation/grpc-data/rig.py down --run-id h3f-<backend>
```
Every read goes through the Client CLI `historyread` on CONSUMER's OPC UA endpoint, on projected NodeIds resolved by a CLI
`browse` from the shared root (leaves under the `remote-source` anchors; the same opaque `p1.` ids come back after every
deploy — re-browsed, never constructed), and is compared with the same read on the SOURCE primary. Every scenario restored the
baseline.
| ID | SqlServer (`h3f-sqlserver`, 06:05–06:15 UTC) | QuestDB (`h3f-questdb`, 06:14–06:21 UTC) |
|---|---|---|
| H01 Raw paging, Raw + UNS | PASS (38): page size 3 ⇒ 11 pages, 31 rows per realm, last page no CP, row-for-row = origin; single read = origin | PASS (38): 10 pages, 29 rows per realm, = origin (µs timestamps) |
| H02 Processed, aggregate refused for the node type | PASS (28): Average on String `text` ⇒ `BadAggregateNotSupported` (origin answers the same); Average on `counter` 4 intervals = origin | PASS (28): same; 3 intervals = origin |
| H03 AtTime, integer node | PASS (26): 3 times, values 7/11/15 = origin, `UInt16` on both | PASS (26): 8/12/16 = origin, `UInt16` |
| H04 continuation across origin failover | PASS (38): page 1 held; `source-1` stopped ⇒ `source-2` primary; resumed page `BadContinuationPointInvalid`; fresh read Good on the new primary | PASS (38): identical |
| H05 v1 origin ⇒ unsupported (**substituted**) | PASS (46): Good ⇒ `BadHistoryOperationUnsupported` once the export drops HistoryRead; the UNS export still Good | PASS (46): identical |
| H06 denied vs unhistorized; session close; rebuild mid-page | PASS (154): unhistorized `scalar` and origin-ACL-denied `counter` ⇒ identical `HistoryRead of <node> failed: BadHistoryOperationUnsupported (0x80720000).`; no local mapping grant ⇒ `BadUserAccessDenied` (UNS mapping still Good); origin open continuations 1 while the CLI held page 1, 0 after its session closed; resume after an origin rename (epoch bump) `BadContinuationPointInvalid`, fresh Good | PASS (154): identical |
Teardown: `rig.py down` after each run; label-filtered `docker container ls -a / volume / network / image ls` ⇒ 0/0/0/0 for both
runs (the QuestDB container and volume carry the run labels). Results files: `evidence/H3-history-<backend>-results.json` in each
(removed) run folder; copies taken before `down`.
Earlier passes on `h3-sql` (pre-fix builds, same rig, `down` 0/0/0/0) found the two H02 defects above and that a deploy retires
cold projected nodes (`BadNodeIdUnknown` until re-browsed — the gate now re-browses after every deploy; a client reading a
projected node it has not browsed since a deploy sees the same; pre-existing v1 projection behaviour).
## Review (Fable, approve-with-changes) — fixes
Each fix is a new commit; red/green by reverting the fix (mutation) and re-running its test, unless noted.
| # | Finding | Resolution | Red/green |
|---|---|---|---|
| D1 | A deadline during the connection's capability probe faulted the whole HistoryRead (`RpcException(Cancelled)` escaped) | `GrpcDataConnection` turns a caller cancel during the probe into `OperationCanceledException` and caps the probe by `HistoryTimeout`; `ProjectedHistoryAccess` fails any escaping fault per node (`BadTimeout` when the deadline fired) and releases every cursor it owns; the node manager's catch is total | client probe tests; wire test (`Hang`/`Throw`): local half of a mixed batch served, projected `BadTimeout` / `BadContinuationPointInvalid`, origin store back to 0 — both red on revert |
| D2 | `Release()` after `TryClaimForResume()` was a no-op ⇒ claimed cursors leaked on post-claim exits | `ProjectedHistoryContinuation.ReleaseEvenIfClaimed()` (at most once) on every such exit: no gateway/identity, deadline spent, limiter rejection, gateway fault, count mismatch | O test over all four exits + a positive control (a normal resume does not release) — red on revert |
| D3 | Projected reads could hold every history batch slot for up to 60 s | projected sub-limit N − max(1, N/4) (`OriginHistoryPort.RemoteSlots`), `Wait(0)` ⇒ `BadTooManyOperations` for the projected half | O test: 3 held projected reads at N=4, a 4th refused at once, a local read still served — red (hangs, bounded to 5 s) on revert |
| D4 | A group larger than the lease/origin batch failed entirely | sub-batches ≤ min(lease batch, origin's advertised `MaxBatchItems`) and ≤ one item per 256 B of the remaining budget; shortfall ⇒ `BadTooManyOperations` per node | wire test: 3 nodes vs an origin batch of 2 ⇒ calls `[2, 1]`, all Good — red on revert |
| D5 | A Remote cursor presented to a local node was taken and dropped | released in the local (raw/modified) and events take paths | O test — red on revert |
| D6 | Release flush lost wake-up; `_stop` disposed under a running flush | `_flushScheduled` flag under the gate; `_stop` only cancelled | 2,000 concurrent enqueues all released — **not shown red** (the race did not reproduce with the fix reverted); kept as a regression check |
| D7 | Budget charged in group order | calls are runs of consecutive request positions read in request order, then charged in request order | wire test [A fresh, B resumed, C fresh] with room for two: C refused, not B — red on revert |
| Float32 | Double from the backend for a Float32 node | **no defect**: the origin port normalises Raw/AtTime to the node's type (Single) before the wire; Runtime test + live legs (H01/H03: Good Singles = origin) | — |
| H06(a) | Origin-ACL denial exercised only via metadata | also read through the consumer's deployed connection (node probe): denied and unhistorized both `0x80720000`, identical pages; the origin's inbound data requests 73 ⇒ 79 | live |
| Nits | page API default-throwing; probe uncapped; `int` cast; CLI doc | `HistoryReadPageAsync` abstract (fakes implement it); probe capped by `HistoryTimeout`; budgets stay `long`; `Client.CLI.md` notes `--aggregate` now sends `UseServerCapabilitiesDefaults = true` | — |
**Gates after the fixes** (HEAD `60e594ddd`): build 0/0; `run-unit-phase.py` H3, H2, H1, X0 passed; OI `Feature=GrpcData` + history
87 passed (2 AVEVA skips); OpcUaServer 1418 (+1 skip), Runtime 1890 (+3 skips), Host 479, Client.CLI 224, Client.Shared 361, Client.UI 131;
rig harness tests OK.
**Live re-run** (fresh `h3r3-sqlserver` 07:19–07:28 and `h3r3-questdb` 07:28–07:35 UTC at `60e594ddd`, normal build checks): H01–H06
**all PASS on both backends** (H06 238 assertions each); Float32 legs Good Singles equal to the origin; H06(c) origin continuations 1
while held, 0 after the session closed; `down` ⇒ 0/0/0/0 for both runs.
**Found on the re-run (pre-existing v1 projection behaviour, not an H3 defect — for a follow-up):** an idle projected node's
authority lapses with its 15 s `MetadataLeaseMilliseconds`; any read after that is `BadUserAccessDenied` — a value Read exactly as a
HistoryRead (reproduced in the Runtime harness) — and a re-browse served from the still-cached browse page does not renew it
(live: the H06 rebuild leg denied right after a re-browse). The gate now starts each held leg right after a deploy + re-browse.
## Review round 3 (approve-with-changes) — fixes
Review of `37cbeff48` + `7aaa98751`. Every finding verified before fixing; none skipped. Red/green by reverting the fix (mutation)
and re-running its test, unless noted. Commits `34e72de3d` (S4), `9c2d6273a` (S1/S2/S3/S6/a), `30d66fdc7` (S5), `f1b23abcb` (b/c/d).
| # | Finding | Resolution | Red/green |
|---|---|---|---|
| S1 | `ServeSplitAsync`: an escape (caller cancel, fault) in sub-batch k>0 stranded earlier sub-batches' answers (continuations never released, samples never disposed) | any escape disposes the collected answers and releases their new continuations on the endpoint (`Abandon`) | client test: cancel during sub-batch 2 ⇒ both sub-batch-1 page tokens released — red on revert |
| S2 | later sub-batches sent with `MaxBytes = left` could break the origin's `count <= MaxBytes/256` admission ⇒ RpcException ⇒ `RecordFailure` + `BadNoCommunication`, claimed cursors lost | each sub-batch trimmed to `left / MinimumBytesPerItem` (shared constant 256); the rest `BadTooManyOperations` with `ConsumerBudgetRefused`, unsent; an unsent resumed item's origin token released (still live there) | client test, fake origin enforcing the rule: `[2, 1]`, rest consumer-refused, next read Good (no backoff) — red on revert (`[2, 2]`, `BadNoCommunication`) |
| S3 | an assembly overflow inside a sub-batch left `used` below `MaxBytes`, so further sub-batches were still sent | any consumer budget refusal latches `spent`; the rest answered unsent | client test: calls `[2, 2]` (was `[2, 2, 1, 1]`) — red on revert |
| S4 | budget stop keyed on `Diagnostic.Contains("budget")`, which matched the ORIGIN's "remainder budget is full" and refused later nodes, incl. Good ones | internal `DataHistoryReadResult.ConsumerBudgetRefused` (never on the wire), set only by the connection's own assembly / split refusal; `ProjectedHistoryAccess` keys on it | wire test: origin refuses A ⇒ B still read (two runs sent) — red on revert |
| S5 | `RpcException(Cancelled)` without a caller cancel ⇒ `BadTimeout` even when the channel-retired / scope / shutdown token fired; the access's outer catch read any escaped OCE as a timeout | that case ⇒ `BadNoCommunication` (resumed `BadContinuationPointInvalid`), chunk tokens released, no further sub-batches; outer catch: `BadTimeout` only for the caller's cancel or the deadline, else `FailCancelled` classification | client test: scope moved mid-call ⇒ fresh `BadNoCommunication`, resumed `BadContinuationPointInvalid` — red on revert. Outer catch: no dedicated test (nothing reachable throws past `ReadGroupAsync`'s own catch) |
| S6 | a Verify failure / item mismatch on a follow-up chunk released nothing but samples; `ServeSplitAsync` swallowed later sub-batch faults silently | the assembly's catch releases finished nodes' continuations (`final[]`), held chunk tokens and the rejected response's tokens; a later sub-batch's endpoint fault is `RecordFailure`d | client test: n0 done on call 1, call 2 malformed ⇒ n0's page token and n1's chunk token released — red on revert |
| a | after a sub-batch endpoint failure further sub-batches were still sent | `ServeAsync` reports `EndpointFailed`; nothing more is sent, rest `BadNoCommunication` / resumed `BadContinuationPointInvalid` | client test: calls `[2, 2]` (was `[2, 2, 1]`) — red on revert |
| b | a Bad answer to a resumed node left the prior origin cursor open (refused unsent) | `ReleaseOrigin()` on the prior cursor for any Bad answer (and a mismatched one); idempotent | wire test: resume answered Bad unsent ⇒ origin open continuations 1 ⇒ 0 — red on revert |
| c | lease dropped an in-flight answer on a scope move without releasing its new continuations; resumed items `BadNoCommunication` | dropped answers' continuations released (best effort); resumed `BadContinuationPointInvalid` | `GrpcDataDeployedHistoryLeaseTests` — red on revert |
| d | a throw from `SaveRemoteContinuation` / `FromClr` for outcome i stranded outcomes i+1.. | the loop's catch releases outcome i's cursor unless the store owns it, and every later outcome's | `ProjectedHistoryReadTests` (unconvertible value on outcome 0 ⇒ outcome 1's cursor released once, outcome 0's left to the store) — red on revert |
**Gates after round 3** (HEAD `f1b23abcb`): build 0/0; `run-unit-phase.py` H3, H2, H1, X0 passed (H3 107 + 144); OI `Feature=GrpcData`
+ history 87 passed (2 AVEVA skips); OpcUaServer 1419 (+1 skip), Runtime 1903 (+3 skips) (`Category!=E2E&Category!=LiveIntegration`); no `GrpcDataConfiguredDiscoveryWireTests` (#920) flake this run.
**Live re-run after round 2** (`h3r5-sqlserver`, `h3r5-questdb` at `7aaa98751`) and **after round 3** (`h3r6-sqlserver`,
`h3r6-questdb` at `713cbfb21`, 2026-11-24, fresh rig per run, normal build checks): H01–H06 **all PASS on both backends, both
rounds** (H01 47, H02 34, H03 35, H04 71, H05 58, H06 238 assertions); `down` ⇒ 0 run containers left. (A first `h3r4-sqlserver`
attempt failed in `seed` after an interrupted earlier seed on the same run; torn down and replaced by `h3r5`.)
Round 3 was itself an independent (Fable) verification of the round-2 commits — approve-with-changes, every finding above fixed.
## Not verified / substitutions
- **H05**: the rig builds no pinned v1 image, so "v1 origin" is substituted by an origin that does not advertise history for the
principal (export without bit 32). The v1 wire shape itself is covered by the H2 recorded-v1-client gates; the live v1-origin
path is follow-up **#921**.
- **H01 tie clusters**: not representable live on either backend — SqlServer `hist.Sample` PK `(TagId, SourceTimeUtc)`, QuestDB
`DEDUP UPSERT KEYS(ts, tag)` keep one sample per timestamp. Tie paging is proven by the H1 port fuzz (10k seeds).
- **ReadyReplica consistency** on projected history and the Gateway backend (H4) were not run.
- **ACL-off on the live rig**: the rig runs `Security:Acl:Enabled=true`; ACL-off is covered by O and OI tests.
- Diagnostics/metrics for projected history are H4.
+26
View File
@@ -93,6 +93,32 @@ the consumer's connection and exports, and seeds a second principal `fixture-noh
the probe's `--scenario history` origin RPCs, the CLI `historyread` and the CONSUMER `history` node-probe operation, and checks
value parity. Without `--history` the rig, the seed and every D-scenario are unchanged.
## H3 projected-history gate (opt-in)
`rig.py up --run-id <id> --history [--history-backend sqlserver|questdb]` — `questdb` layers `compose.history.questdb.yml`:
SOURCE historizes into a run-owned QuestDB container (labelled, removed by `down`) instead of the run's SQL container. The H3
seed profile also: grants HistoryRead on both mappings; gives the CLI principal its CONSUMER HistoryRead **only** through
`RemoteNamespaceMapping`-scoped grants (`cli-history-map-raw|uns`; the cluster grant is `Admin` minus HistoryRead); historizes
`text` (a String node, for the per-type aggregate refusal); and accepts the mutation
`acl_permissions: {node_acl_id, permission_flags}` (one ACL row's flags; the baseline restore reverts it).
```bash
python3 scripts/validation/grpc-data/rig.py up --run-id h3-sql --history --timeout 900
python3 scripts/validation/grpc-data/rig.py seed --run-id h3-sql
sleep 75 # CONTROL's ClusterNode contact refresh before the first deploy
python3 scripts/validation/grpc-data/rig.py deploy --run-id h3-sql --timeout 300
python3 scripts/validation/grpc-data/history_gate.py --run-id h3-sql # H01..H06, or --scenario H04
python3 scripts/validation/grpc-data/rig.py down --run-id h3-sql
```
`history_gate.py` accumulates `counter` history, resolves the projected NodeIds by a CLI `browse` from the shared root
(leaves under the `remote-source` anchors; never constructed `p1.` ids), then runs each `scenarios.json` →
`history_scenarios` row through the Client CLI `historyread` on CONSUMER and compares with the same read on the SOURCE
primary. The continuation scenarios use the CLI's hand-paged mode (`--page-size`, `--pause-after-page`,
`--abandon-after-page`, `--held-marker-file`); the origin's open continuations come from the `topology` node probe
(`originAccounting.historyOpenContinuations`). Every scenario restores the baseline. Results:
`evidence/H3-history-<backend>-results.json`.
## Scenario authoring and node probes
The seeder is available through `LocalRig.seed_helper(action, *arguments)`. Its
@@ -0,0 +1,38 @@
# H3 QuestDB origin backend (opt-in: `rig.py up --history --history-backend questdb`), layered AFTER
# compose.history.yml: the SOURCE pair historizes into a run-owned QuestDB container instead of the run's SQL
# container. Same seed profile, same scenarios. The container and its volume carry the run labels, so
# `rig.py down` removes them with everything else. Image pinned as docker-dev/docker-compose.questdb.yml.
x-labels: &labels
otopcua.grpc-data.run: ${GRPC_DATA_RUN_ID:?run id required}
otopcua.grpc-data.fixture: "v1"
x-source-questdb-env: &source-questdb-env
ServerHistorian__Backend: QuestDb
ServerHistorian__QuestDb__ConnectionString: "Host=questdb;Port=8812;Username=admin;Password=quest;Database=qdb;ServerCompatibilityMode=NoTypeLoading;Maximum Pool Size=16"
ServerHistorian__QuestDb__TablePrefix: hist_
ServerHistorian__QuestDb__AutoCreateSchema: "true"
services:
questdb:
image: questdb/questdb:10.0.1
labels: *labels
networks: [rig]
volumes: [questdb-data:/var/lib/questdb]
healthcheck:
test: ["CMD-SHELL", "curl -fs http://localhost:9003/status || exit 1"]
interval: 5s
timeout: 5s
retries: 24
source-1:
environment: *source-questdb-env
depends_on:
questdb: {condition: service_healthy}
source-2:
environment: *source-questdb-env
depends_on:
questdb: {condition: service_healthy}
volumes:
questdb-data:
labels: *labels
@@ -0,0 +1,446 @@
"""H3 live gate: scenarios H01–H06 (plan §9 "Scenarios") on a `rig.py up --history [--history-backend questdb]` run.
Every scenario is driven through the production Client CLI `historyread` against CONSUMER's OPC UA endpoint, on
PROJECTED NodeIds resolved by browsing from the mapping anchor (never constructed `p1.` ids), and is compared with the
same read on the ORIGIN (SOURCE) node. Each scenario restores the baseline (transactional authoring restore + deploy)
whatever its outcome. The rows are declared in `scenarios.json` → `history_scenarios`; evidence lands in the run's
restricted `evidence/` folder (keys redacted by ScenarioRunner.save).
"""
import argparse
import json
import re
import sys
import threading
import time
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
import history_smoke
import rig
import scenarios
NODE_PERMISSIONS_ADMIN = 4095 # NodePermissions.Admin = bits 0..11 (HistoryUpdate excluded)
NODE_PERMISSIONS_HISTORY_READ = 1 << 3
NODE_PERMISSIONS_BROWSE = 1 << 0
EXPORT_WITHOUT_HISTORY = 31 # Browse | Metadata | Read | Write | Subscribe
def _iso(moment):
return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
class HistoryGate:
def __init__(self, run_id, *, pinned_build=False):
if pinned_build:
recorded = scenarios.restricted_json(rig.LocalRig(run_id).path)["source_tree_hash"]
rig.source_tree_hash = lambda: recorded
self.runner = scenarios.ScenarioRunner(run_id)
if self.runner.manifest["fixture"].get("history") is None:
raise SystemExit("run was not brought up with --history")
self.backend = self.runner.rig.environment.get("GRPC_DATA_HISTORY_BACKEND", "sqlserver")
self.catalog = json.loads((rig.HERE / "scenarios.json").read_text())["history_scenarios"]
self.window = None
self.projected = {}
# ----------------------------------------------------------------------------------------------------------- tools
def cli(self, node, extra, name, *, timeout=90):
argv = ["dotnet", str(self.runner.cli_dll), "historyread", "-u", self.runner.endpoint(node), "-U", "apikey",
"-P", self.runner.key, *extra]
return self.runner.process(argv, self.runner.active + "-" + name + "-" + uuid.uuid4().hex[:6], timeout=timeout)
def window_args(self):
return ["--start", _iso(self.window[0]), "--end", _iso(self.window[1])]
def origin_node(self, realm, name):
source = self.runner.primary("source")
alias = self.runner.manifest["resolved_nodes"][source]["aliases"][realm]
return source, alias.rsplit("/", 1)[0] + "/" + name
def accumulate(self, seconds=40):
started = datetime.now(timezone.utc)
self.runner.device("set", address=30, value=16480) # flt = 3.5f (0x40600000, big-endian words)
for second in range(seconds):
self.runner.device("advance", steps=1)
if second == seconds // 2:
self.runner.device("set", address=30, value=16616) # flt = 7.25f (0x40E80000)
time.sleep(1)
finished = datetime.now(timezone.utc)
time.sleep(4)
self.window = ((started + timedelta(seconds=5)).replace(microsecond=0), (finished - timedelta(seconds=5)).replace(microsecond=0))
def resolve_projected(self):
"""Browse CONSUMER from the shared root; keep the projected leaves under the mapping anchors (`remote-source`)."""
consumer = self.runner.primary("consumer")
uris = self.runner.manifest["resolved_nodes"][consumer]["namespace_uris"]
ns = {key: uris.index(uri) for key, uri in self.runner.manifest["fixture"]["namespace_uris"].items()}
argv = ["dotnet", str(self.runner.cli_dll), "browse", "-u", self.runner.endpoint(consumer), "-U", "apikey", "-P", self.runner.key,
"-n", f"ns={ns['raw']};s=OtOpcUa", "-r", "-d", "7"]
result = self.runner.process(argv, "H-browse-" + uuid.uuid4().hex[:6], timeout=120)
self.runner.check(result.returncode == 0, "consumer browse succeeded")
stack, found = [], {}
for line in result.stdout.splitlines():
match = re.match(r"^( *)\[(\w+)\] (.+?) \(NodeId: (.+)\)$", line)
if match is None:
continue
depth = len(match[1]) // 2
del stack[depth:]
stack.append(match[3])
node_id = match[4]
index = int(re.match(r"ns=(\d+);", node_id)[1]) if node_id.startswith("ns=") else -1
realm = "raw" if index == ns["mapped_raw"] else "uns" if index == ns["mapped_uns"] else None
if realm and "remote-source" in stack[:-1] and match[3] in {"counter", "scalar", "text", "flt"}:
self.runner.check((realm, match[3]) not in found, "one projected leaf per realm and name")
found[(realm, match[3])] = node_id
for realm in ("raw", "uns"):
for name in ("counter", "scalar", "text", "flt"):
self.runner.check((realm, name) in found, f"projected {realm}/{name} found by browse from the mapping anchor")
self.runner.check(found[(realm, name)].split(";s=", 1)[1].startswith("p1."), "projected ids are opaque p1. ids")
self.projected = found
self.runner.save("H-projected-nodes.json", {f"{k[0]}/{k[1]}": v for k, v in found.items()})
return consumer
def rebrowse(self, timeout=90):
"""A deploy retires cold projected nodes; browse from the anchor again (the SAME opaque ids come back)."""
end = time.monotonic() + timeout
while True:
try:
previous = dict(self.projected)
self.resolve_projected()
self.runner.check(not previous or previous == self.projected, "projected NodeIds are stable across a deploy")
return
except scenarios.ScenarioError:
if time.monotonic() >= end:
raise
time.sleep(3)
def change(self, **mutation):
"""A production mutation + deploy, then re-materialise the projected leaves by browse."""
self.runner.mutate(**mutation)
self.rebrowse()
def restore(self):
self.runner.baseline()
self.rebrowse()
def held(self, consumer, extra, name, during, *, marker_timeout=60):
"""Runs a hand-paged CLI read in the background; `during()` runs once the read reports its held point."""
marker = self.runner.folder / (name + "-" + uuid.uuid4().hex[:6] + ".held")
resume = self.runner.folder / (name + "-" + uuid.uuid4().hex[:6] + ".resume")
outcome = {}
def worker():
outcome["result"] = self.cli(consumer, [*extra, "--held-marker-file", str(marker), "--resume-when-file", str(resume)],
name, timeout=600)
thread = threading.Thread(target=worker, daemon=True)
thread.start()
end = time.monotonic() + marker_timeout
while not marker.exists() and thread.is_alive() and time.monotonic() < end:
time.sleep(0.1)
self.runner.check(marker.exists(), "the CLI reached its held point")
try:
during()
finally:
resume.write_text("")
thread.join(timeout=600)
self.runner.check("result" in outcome, "held CLI finished")
return outcome["result"]
@staticmethod
def status_lines(stdout):
return [line for line in stdout.splitlines() if line.startswith(("Page ", "Fresh:", "Status:", "Released", "Abandoned"))]
@staticmethod
def error_status(result):
combined = result.stdout + "\n" + result.stderr
match = re.search(r"(Bad\w+)", combined)
return match[1] if match else None
def poll_status(self, consumer, node, expected, name, *, extra=None, timeout=120):
end = time.monotonic() + timeout
attempts = []
while True:
result = self.cli(consumer, ["-n", node, *self.window_args(), "--max", "50", *(extra or [])], name)
observed = self.error_status(result) if result.returncode != 0 else "Good"
attempts.append(observed)
if observed == expected or time.monotonic() >= end:
return observed, attempts, result
time.sleep(3)
def origin_state(self):
total = 0
for node in ("source-1", "source-2"):
observed = self.runner.probe(node, "topology", timeout=30)
total += int(observed.get("originAccounting", {}).get("historyOpenContinuations") or 0)
return total
# ------------------------------------------------------------------------------------------------------- scenarios
def scenario_H01(self):
"""Raw paging across page boundaries, Raw and UNS mappings, row-for-row equal to the origin."""
report = {}
consumer = self.runner.primary("consumer")
for realm in ("raw", "uns"):
source, origin = self.origin_node(realm, "counter")
reference = self.cli(source, ["-n", origin, *self.window_args(), "--max", "1000"], f"origin-{realm}")
self.runner.check(reference.returncode == 0, f"origin {realm} read")
origin_rows = history_smoke._cli_rows(reference.stdout)
self.runner.check(len(origin_rows) >= 10, f"origin {realm} window holds history")
paged = self.cli(consumer, ["-n", self.projected[(realm, "counter")], *self.window_args(), "--page-size", "3", "--max", "1000"],
f"paged-{realm}")
pages = [line for line in paged.stdout.splitlines() if line.startswith("Page ")]
self.runner.check(paged.returncode == 0 and len(pages) >= 2, f"{realm}: several pages")
self.runner.check(all("Good" in line for line in pages), f"{realm}: every page Good")
self.runner.check(pages[-1].split("continuation=")[1].startswith("no"), f"{realm}: the last page has no continuation")
rows = history_smoke._cli_rows(paged.stdout)
self.runner.check(rows == origin_rows, f"{realm}: paged projected rows equal the origin row-for-row")
whole = self.cli(consumer, ["-n", self.projected[(realm, "counter")], *self.window_args(), "--max", "1000"], f"whole-{realm}")
self.runner.check(history_smoke._cli_rows(whole.stdout) == origin_rows, f"{realm}: single read equals the origin")
report[realm] = {"pages": len(pages), "rows": len(rows), "first": str(rows[0]), "last": str(rows[-1]), "page_lines": pages}
# H3 review: a Float32 node whose backend stores Double reads the same Good rows through the projection.
source, origin = self.origin_node("raw", "flt")
reference = self.cli(source, ["-n", origin, *self.window_args(), "--max", "1000"], "origin-flt")
floats = self.cli(consumer, ["-n", self.projected[("raw", "flt")], *self.window_args(), "--max", "1000"], "flt")
origin_rows, rows = history_smoke._cli_rows(reference.stdout), history_smoke._cli_rows(floats.stdout)
self.runner.check(reference.returncode == 0 and floats.returncode == 0 and len(rows) >= 1, "Float32 history served on both")
self.runner.check(rows == origin_rows and all(q == "Good" for _, _, q in rows), "Float32 rows Good and equal to the origin")
report["float32"] = {"rows": [str(r) for r in rows]}
report["tie_cluster"] = ("not representable on the " + self.backend + " backend: SqlServer hist.Sample PK (TagId, SourceTimeUtc), "
"QuestDB DEDUP UPSERT KEYS(ts, tag) — one stored sample per timestamp; tie paging is proven by the H1 port fuzz")
return report
def scenario_H02(self):
"""Processed: the origin refuses an aggregate for the node's type (#897); a served aggregate equals the origin."""
consumer = self.runner.primary("consumer")
refused = self.cli(consumer, ["-n", self.projected[("raw", "text")], *self.window_args(), "--aggregate", "Average", "--interval", "10000"],
"text-average")
self.runner.check(refused.returncode != 0 and self.error_status(refused) == "BadAggregateNotSupported",
"Average on a String node is BadAggregateNotSupported from the origin")
source, origin = self.origin_node("raw", "text")
origin_refused = self.cli(source, ["-n", origin, *self.window_args(), "--aggregate", "Average", "--interval", "10000"], "origin-text-average")
self.runner.check(self.error_status(origin_refused) == "BadAggregateNotSupported", "the origin answers the same refusal")
source, origin = self.origin_node("raw", "counter")
reference = self.cli(source, ["-n", origin, *self.window_args(), "--aggregate", "Average", "--interval", "10000"], "origin-average")
served = self.cli(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--aggregate", "Average", "--interval", "10000"],
"average")
self.runner.check(reference.returncode == 0 and served.returncode == 0, "Average served on both")
rows, origin_rows = history_smoke._cli_rows(served.stdout), history_smoke._cli_rows(reference.stdout)
self.runner.check(len(rows) > 0 and rows == origin_rows, "projected Average equals the origin row-for-row")
return {"refused": self.error_status(refused), "origin_refused": self.error_status(origin_refused), "average_rows": len(rows)}
def scenario_H03(self):
"""AtTime on an integer (UInt16) node: identical values, timestamps, statuses and value types."""
consumer = self.runner.primary("consumer")
start = self.window[0]
times = ",".join(_iso(start + timedelta(seconds=s)) for s in (3, 7, 11))
source, origin = self.origin_node("raw", "counter")
reference = self.cli(source, ["-n", origin, "--at-time", times], "origin-attime")
projected = self.cli(consumer, ["-n", self.projected[("raw", "counter")], "--at-time", times], "attime")
self.runner.check(reference.returncode == 0 and projected.returncode == 0, "AtTime served")
rows, origin_rows = history_smoke._cli_rows(projected.stdout), history_smoke._cli_rows(reference.stdout)
types = [line for line in projected.stdout.splitlines() if line.startswith("Type:")]
origin_types = [line for line in reference.stdout.splitlines() if line.startswith("Type:")]
self.runner.check(len(rows) == 3 and rows == origin_rows, "projected AtTime equals the origin row-for-row")
self.runner.check(types == origin_types and all(t == "Type: UInt16" for t in types), "integer values stay UInt16 end to end")
source, origin = self.origin_node("raw", "flt")
float_times = ",".join(_iso(start + timedelta(seconds=sec)) for sec in (2, 20))
reference_f = self.cli(source, ["-n", origin, "--at-time", float_times], "origin-attime-flt")
projected_f = self.cli(consumer, ["-n", self.projected[("raw", "flt")], "--at-time", float_times], "attime-flt")
rows_f, origin_rows_f = history_smoke._cli_rows(projected_f.stdout), history_smoke._cli_rows(reference_f.stdout)
types_f = [line for line in projected_f.stdout.splitlines() if line.startswith("Type:")]
origin_types_f = [line for line in reference_f.stdout.splitlines() if line.startswith("Type:")]
self.runner.check(projected_f.returncode == 0 and rows_f == origin_rows_f and all(q == "Good" for _, _, q in rows_f),
"Float32 AtTime equals the origin, Good")
self.runner.check(types_f == origin_types_f and all(t == "Type: Single" for t in types_f), "Float32 values stay Single end to end")
return {"rows": [str(r) for r in rows], "types": types, "float32": {"rows": [str(r) for r in rows_f], "types": types_f}}
def scenario_H04(self):
"""A continuation across an origin failover is BadContinuationPointInvalid; a fresh read moves and succeeds."""
consumer = self.runner.primary("consumer")
source = self.runner.primary("source")
observed = {}
def failover():
with self.runner.stopped(source):
observed["new_primary"] = self.runner.wait_primary("source", exclude=source)
self.runner.wait_connection_ready(consumer, "raw")
# Resume INSIDE the stop window: the issuing endpoint is down, the pinned resume cannot move. Re-browse first so
# the node's projection authority is current (it lapses with the 15 s metadata lease, as for a value Read).
self.rebrowse()
self.held_resume_now()
self.runner.wait_pair_topology("source")
result = self.held_with_inline_resume(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--page-size", "3",
"--pause-after-page", "1", "--fresh-after-failure"], "failover", failover)
lines = self.status_lines(result.stdout)
self.runner.check(any(l.startswith("Page 2: BadContinuationPointInvalid") for l in lines), "the resumed page is BadContinuationPointInvalid")
self.runner.check(any(l.startswith("Fresh: Good") for l in lines), "a fresh read succeeds on the new primary")
return {"old_primary": source, "new_primary": observed.get("new_primary"), "lines": lines}
def held_with_inline_resume(self, consumer, extra, name, during):
"""Like held(), but `during` decides WHEN to resume by calling self.held_resume_now()."""
marker = self.runner.folder / (name + "-" + uuid.uuid4().hex[:6] + ".held")
resume = self.runner.folder / (name + "-" + uuid.uuid4().hex[:6] + ".resume")
outcome = {}
def worker():
outcome["result"] = self.cli(consumer, [*extra, "--held-marker-file", str(marker), "--resume-when-file", str(resume)],
name, timeout=600)
thread = threading.Thread(target=worker, daemon=True)
thread.start()
end = time.monotonic() + 60
while not marker.exists() and thread.is_alive() and time.monotonic() < end:
time.sleep(0.1)
self.runner.check(marker.exists(), "the CLI reached its held point")
resumed = threading.Event()
def resume_now():
resume.write_text("")
thread.join(timeout=300)
resumed.set()
self.held_resume_now = resume_now
try:
during()
finally:
if not resumed.is_set():
resume_now()
self.runner.check("result" in outcome, "held CLI finished")
return outcome["result"]
def scenario_H05(self):
"""Substitute for "v1 origin (pinned old image)": an origin that no longer advertises history for this principal."""
consumer = self.runner.primary("consumer")
before, _, _ = self.poll_status(consumer, self.projected[("raw", "counter")], "Good", "before", timeout=30)
self.runner.check(before == "Good", "history served before the change")
self.change(export_id="export-raw", export_allowed_operations=EXPORT_WITHOUT_HISTORY)
observed, attempts, result = self.poll_status(consumer, self.projected[("raw", "counter")], "BadHistoryOperationUnsupported",
"not-advertised", timeout=180)
self.runner.check(observed == "BadHistoryOperationUnsupported", "an origin that does not advertise history ⇒ unsupported")
uns, _, _ = self.poll_status(consumer, self.projected[("uns", "counter")], "Good", "uns-still-served", timeout=30)
self.runner.check(uns == "Good", "the other export (UNS) still serves history")
return {"before": before, "after": observed, "attempts": attempts, "uns": uns,
"substitution": "no pinned v1 image is built by the rig; the export drops HistoryRead (bit 32) instead"}
def scenario_H06(self):
"""Denied vs unhistorized indistinguishable; local deny is BadUserAccessDenied; session close releases; rebuild mid-page."""
consumer = self.runner.primary("consumer")
report = {}
# (a) unhistorized vs origin-ACL-denied: the same refusal, the same text (node ids normalised).
unhistorized, _, unh = self.poll_status(consumer, self.projected[("raw", "scalar")], "BadHistoryOperationUnsupported", "unhistorized",
timeout=30)
self.runner.check(unhistorized == "BadHistoryOperationUnsupported", "unhistorized ⇒ BadHistoryOperationUnsupported")
self.change(acl_permissions={"node_acl_id": "source-peer", "permission_flags": NODE_PERMISSIONS_ADMIN & ~NODE_PERMISSIONS_HISTORY_READ})
denied, attempts, den = self.poll_status(consumer, self.projected[("raw", "counter")], "BadHistoryOperationUnsupported", "origin-denied",
timeout=180)
normalise = lambda text: re.sub(r"ns=\d+;s=\S+", "<node>", "\n".join(l for l in (text.stdout + text.stderr).splitlines() if "Bad" in l))
self.runner.check(denied == "BadHistoryOperationUnsupported", "origin ACL denial ⇒ BadHistoryOperationUnsupported")
self.runner.check(normalise(unh) == normalise(den), "denied and unhistorized are indistinguishable")
# H3 review: the per-item refusal itself, OVER THE WIRE (the consumer's deployed connection → the origin's ingress),
# not only the metadata that drops the access bit: both answers identical 0x80720000, and the origin counted the calls.
paths = self.runner.manifest["fixture"]["history"]
primary = self.runner.primary("source")
before = self.runner.probe(primary, "topology", timeout=30).get("inboundDataRequests")
wire_denied = self.runner.probe(consumer, "history", "raw", path=paths["historized"]["raw"], historyNumValues=5,
expected_state="Unsupported", timeout=60)
wire_unhistorized = self.runner.probe(consumer, "history", "raw", path=paths["unhistorized"]["raw"], historyNumValues=5,
expected_state="Unsupported", timeout=60)
after = self.runner.probe(primary, "topology", timeout=30).get("inboundDataRequests")
strip = lambda pages: [{k: v for k, v in page.items()} for page in pages]
self.runner.check(strip(wire_denied["pages"]) == strip(wire_unhistorized["pages"]),
"origin-ACL-denied and unhistorized answers are identical over the wire")
report["wire"] = {"denied": wire_denied["pages"], "unhistorized": wire_unhistorized["pages"],
"origin_inbound_requests": {"before": before, "after": after}}
report["indistinguishable"] = {"unhistorized": normalise(unh), "denied": normalise(den), "attempts": attempts}
self.restore()
# (b) the LOCAL mapping-scope grant: without it, BadUserAccessDenied (a local decision); the other mapping keeps its grant.
self.change(acl_permissions={"node_acl_id": "cli-history-map-raw", "permission_flags": NODE_PERMISSIONS_BROWSE})
local, attempts, _ = self.poll_status(consumer, self.projected[("raw", "counter")], "BadUserAccessDenied", "local-denied", timeout=90)
self.runner.check(local == "BadUserAccessDenied", "no local HistoryRead grant on the mapping scope ⇒ BadUserAccessDenied")
other, _, _ = self.poll_status(consumer, self.projected[("uns", "counter")], "Good", "local-other-mapping", timeout=30)
self.runner.check(other == "Good", "the UNS mapping's own grant still serves")
report["local_deny"] = {"raw": local, "uns": other, "attempts": attempts}
self.restore()
consumer = self.runner.primary("consumer")
# (d) origin rebuild mid-page: a resumed page after the origin's history epoch moved is BadContinuationPointInvalid.
def rebuild():
self.change(rename_tag={"tag_id": "source-array1", "name": "array1-renamed"})
rebuilt = self.held(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--page-size", "3",
"--pause-after-page", "1", "--fresh-after-failure"], "rebuild", rebuild)
lines = self.status_lines(rebuilt.stdout)
self.runner.check(any(l.startswith("Page 2: BadContinuationPointInvalid") for l in lines), "resume after the origin rebuild is invalid")
self.runner.check(any(l.startswith("Fresh: Good") for l in lines), "a fresh read after the rebuild succeeds")
report["rebuild"] = lines
# (c) a consumer session close releases the origin continuation. Each held read starts right after a deploy + re-browse:
# an idle projected node's authority lapses with its 15 s metadata lease and a re-browse served from the cached page
# does not renew it (a value Read is refused the same way — pre-existing v1 projection behaviour, reported).
self.restore()
consumer = self.runner.primary("consumer")
self.runner.check(self.origin_state() == 0, "no origin continuation open before")
counts = {}
def while_held():
counts["held"] = self.origin_state()
abandoned = self.held(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--page-size", "2",
"--abandon-after-page", "1", "--hold-seconds", "10"], "abandon", while_held)
self.runner.check(counts.get("held", 0) >= 1, "the origin holds the page cursor while the consumer session holds the point")
end = time.monotonic() + 30
after = self.origin_state()
while after != 0 and time.monotonic() < end:
time.sleep(1)
after = self.origin_state()
self.runner.check(after == 0, "the consumer session close released the origin continuation (store count back to 0)")
report["session_close"] = {"held": counts.get("held"), "after": after, "lines": self.status_lines(abandoned.stdout)}
return report
# ------------------------------------------------------------------------------------------------------------- run
def run(self, selection):
chosen = [row["id"] for row in self.catalog] if selection == "all" else [selection]
self.runner.publish()
self.runner.rig.seed_helper("snapshot")
self.runner.active, self.runner.deadline = "H00", time.monotonic() + 900
self.accumulate()
self.resolve_projected()
rows = []
for name in chosen:
spec = next(row for row in self.catalog if row["id"] == name)
self.runner.active, self.runner.count = name, 0
self.runner.deadline = time.monotonic() + spec.get("timeout_seconds", 900)
started, error, restored, detail = time.monotonic(), None, False, None
try:
detail = getattr(self, "scenario_" + name)()
except Exception as failure:
error = type(failure).__name__ + ": " + str(failure)
finally:
try:
self.runner.deadline = time.monotonic() + 600
self.restore()
restored = True
except Exception as failure:
error = (error + "; " if error else "") + "restoration " + type(failure).__name__ + ": " + str(failure)
row = {"id": name, "backend": self.backend, "passed": error is None and restored, "assertions": self.runner.count,
"restored": restored, "duration_seconds": round(time.monotonic() - started, 1), "failure": error, "detail": detail}
rows.append(row)
self.runner.save(f"H3-history-{self.backend}-results.json", {"rows": rows, "window": [_iso(w) for w in self.window]})
print(json.dumps({k: row[k] for k in ("id", "backend", "passed", "assertions", "restored", "duration_seconds", "failure")}), flush=True)
return rows
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--run-id", required=True)
parser.add_argument("--scenario", default="all")
parser.add_argument("--pinned-build", action="store_true")
arguments = parser.parse_args(argv)
gate = HistoryGate(arguments.run_id, pinned_build=arguments.pinned_build)
rows = gate.run(arguments.scenario)
return 0 if all(row["passed"] for row in rows) else 1
if __name__ == "__main__":
sys.exit(main())
@@ -66,6 +66,7 @@ public sealed partial class NodeProbeWorker(IServiceProvider services) : Backgro
acquisitionOwnerSerial = acquisition?.CurrentOwnerSerial, acquisitionControlGeneration = acquisition?.ControlGeneration,
workload = composition?.CaptureWorkloadAccounting(),
sourceIngressCounters = SourceIngressDiagnostics.Capture(),
historyOpenContinuations = composition?.Services.HistoryOpenContinuations,
definition = "actual origin hub resource charges and physical driver reservation owners; driver count is not source count"
};
}
+15 -2
View File
@@ -473,7 +473,9 @@ def require_production_prerequisites(action, available):
ROOT = Path(__file__).resolve().parents[3]
HERE = Path(__file__).resolve().parent
NODES = tuple(f"{pair}-{n}" for pair in ("control", "source", "consumer") for n in (1, 2))
SERVICES = ("sql", "migrator", "device", "seeder", *NODES)
# `questdb` exists only on a `--history-backend questdb` run (compose.history.questdb.yml); listing it is the DNS allowlist.
SERVICES = ("sql", "migrator", "device", "seeder", "questdb", *NODES)
HISTORY_BACKENDS = ("sqlserver", "questdb")
def run_command(argv, *, timeout=120, environment=None):
@@ -671,6 +673,8 @@ class LocalRig:
files = ["--file", str(HERE / "compose.yml")]
if self.environment.get("GRPC_DATA_HISTORY") == "1":
files.extend(["--file", str(HERE / "compose.history.yml")])
if self.environment.get("GRPC_DATA_HISTORY_BACKEND") == "questdb":
files.extend(["--file", str(HERE / "compose.history.questdb.yml")])
return files
def compose(self, *args, timeout=120):
@@ -841,7 +845,7 @@ class LocalRig:
self.save(manifest)
return manifest
def up(self, timeout=600, history=False):
def up(self, timeout=600, history=False, history_backend="sqlserver"):
import secrets
import credentials
if self.folder.exists():
@@ -862,7 +866,10 @@ class LocalRig:
import base64
settings["GRPC_DATA_SECRETS_KEK"] = base64.b64encode(secrets.token_bytes(32)).decode()
if history:
if history_backend not in HISTORY_BACKENDS:
raise RigError("unknown history backend")
settings["GRPC_DATA_HISTORY"] = "1"
settings["GRPC_DATA_HISTORY_BACKEND"] = history_backend
atomic_write_secret(self.folder / "environment.json", json.dumps(settings))
self.environment.update(settings)
credentials.provision_tls(self.folder / "security", NODES[2:])
@@ -1331,6 +1338,8 @@ def main(argv=None):
parser.add_argument("--run-id")
parser.add_argument("--timeout", type=float, default=None)
parser.add_argument("--history", action="store_true", help="up only: add the H2 history overlay (SOURCE historian + history seed profile)")
parser.add_argument("--history-backend", choices=HISTORY_BACKENDS, default=None,
help="up --history only: the SOURCE historian backend (sqlserver = the run's SQL container, default; questdb = a run-owned QuestDB)")
arguments = parser.parse_args(argv)
try:
if arguments.action == "preflight":
@@ -1353,6 +1362,10 @@ def main(argv=None):
if arguments.action != "up":
raise RigError("--history applies to up only; the run remembers it")
options["history"] = True
if arguments.history_backend is not None:
options["history_backend"] = arguments.history_backend
elif arguments.history_backend is not None:
raise RigError("--history-backend needs up --history")
result = action(**options)
print(json.dumps({"run_id": result["run_id"], "state": result.get("state"), "manifest": str(rig.path), "healthy": result.get("healthy")}))
return 0
@@ -1531,5 +1531,83 @@
"caller_cluster": "CONSUMER",
"target_cluster": "SOURCE"
}
],
"history_scenarios": [
{
"id": "H01",
"title": "Raw paging at page boundaries, Raw and UNS mappings",
"driver": "history_gate.py",
"restores_baseline": true,
"timeout_seconds": 600,
"coverage": [
"Client CLI --page-size on projected counter",
"pages >= 2, last page no continuation",
"rows equal the origin row-for-row",
"single read equals the origin",
"tie clusters: not storable on SqlServer (PK) or QuestDB (DEDUP UPSERT KEYS(ts, tag)); proven by the H1 fuzz"
]
},
{
"id": "H02",
"title": "Processed with an aggregate the origin backend refuses for the node type",
"driver": "history_gate.py",
"restores_baseline": true,
"timeout_seconds": 600,
"coverage": [
"Average on a String node => BadAggregateNotSupported (origin, #897)",
"the same refusal on the origin",
"Average on counter equals the origin"
]
},
{
"id": "H03",
"title": "AtTime, integer node",
"driver": "history_gate.py",
"restores_baseline": true,
"timeout_seconds": 600,
"coverage": [
"--at-time on projected counter",
"values / timestamps / statuses equal the origin",
"UInt16 value type end to end"
]
},
{
"id": "H04",
"title": "Continuation across origin failover => BadContinuationPointInvalid, fresh read succeeds",
"driver": "history_gate.py",
"restores_baseline": true,
"timeout_seconds": 900,
"coverage": [
"page 1 held in one consumer session",
"SOURCE primary stopped",
"resumed page BadContinuationPointInvalid",
"fresh read on the new primary Good"
]
},
{
"id": "H05",
"title": "Origin that does not advertise history => unsupported (substitute for a pinned v1 image)",
"driver": "history_gate.py",
"restores_baseline": true,
"timeout_seconds": 600,
"coverage": [
"export drops HistoryRead (bit 32)",
"projected node => BadHistoryOperationUnsupported",
"the other export still served"
]
},
{
"id": "H06",
"title": "Denied vs unhistorized indistinguishable; session close releases origin continuations; origin rebuild mid-page",
"driver": "history_gate.py",
"restores_baseline": true,
"timeout_seconds": 900,
"coverage": [
"unhistorized and origin-ACL-denied: identical BadHistoryOperationUnsupported",
"no local mapping-scope HistoryRead => BadUserAccessDenied (the other mapping still served)",
"origin open continuations >= 1 while held, 0 after the consumer session close",
"resume after an origin rebuild BadContinuationPointInvalid, fresh Good"
]
}
]
}
+28 -7
View File
@@ -172,7 +172,7 @@ try
var root = mutation.RootElement;
string[] allowedFields = ["connection_id", "target_mode", "target_node_id", "consistency", "consumer_node_ids", "connection_enabled", "connection_allowed_operations",
"mapping_enabled", "write_through", "allowed_operations", "export_id", "export_enabled", "export_allowed_operations", "source_redundancy_mode", "consumer_redundancy_mode",
"control_redundancy_mode", "rename_tag", "upsert_tag", "upsert_reference", "remove_tag_id", "disable_feature", "key_action", "key_expiry_seconds", "upsert_connection", "upsert_mapping", "upsert_export", "remove_mapping_id", "maintenance_mode"];
"control_redundancy_mode", "rename_tag", "upsert_tag", "upsert_reference", "remove_tag_id", "disable_feature", "key_action", "key_expiry_seconds", "upsert_connection", "upsert_mapping", "upsert_export", "remove_mapping_id", "maintenance_mode", "acl_permissions"];
if (root.ValueKind != JsonValueKind.Object || root.EnumerateObject().Any(property => !allowedFields.Contains(property.Name, StringComparer.Ordinal)))
throw new InvalidOperationException("unknown fixture mutation field");
await using var db = await factory.CreateDbContextAsync();
@@ -283,7 +283,13 @@ try
await db.UnsTagReferences.Where(x => x.TagId == removeTag.GetString()).ExecuteDeleteAsync();
await db.Tags.Where(x => x.TagId == removeTag.GetString()).ExecuteDeleteAsync();
}
if (root.TryGetProperty("disable_feature", out var disable) && disable.GetBoolean())
if (root.TryGetProperty("acl_permissions", out var aclPermissions))
{
// H3: {"node_acl_id": "...", "permission_flags": <int>} — one existing row's flags (baseline restore reverts it).
var acl = await db.NodeAcls.SingleAsync(x => x.NodeAclId == aclPermissions.GetProperty("node_acl_id").GetString());
acl.PermissionFlags = (NodePermissions)aclPermissions.GetProperty("permission_flags").GetInt32();
}
if (root.TryGetProperty("disable_feature", out var disable) && disable.GetBoolean())
{
foreach (var row in await db.DataConnections.ToListAsync()) { row.Enabled = false; row.Revision++; }
foreach (var row in await db.RemoteNamespaceMappings.ToListAsync()) { row.Enabled = false; row.Revision++; }
@@ -328,8 +334,11 @@ try
foreach (var node in nodes.Where(x => x.StartsWith(cluster.ToLowerInvariant() + "-", StringComparison.Ordinal)))
db.ClusterNodes.Add(new() { NodeId = node + ":4053", ClusterId = cluster, Host = node, OpcUaPort = 4840, DashboardPort = 9000,
GrpcPort = 4056, ApplicationUri = "urn:OtOpcUa:grpc-data:" + node, CreatedBy = "grpc-data-local-gate" });
// H3 (history profile): on CONSUMER the CLI principal's HistoryRead comes ONLY from the mapping-scoped grants below,
// so a scenario can take it away per mapping (plan §6: mapped history needs HistoryRead on the mapping scope).
db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "cli-" + cluster, ClusterId = cluster,
Principal = "fixture-cli", ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin });
Principal = "fixture-cli", ScopeKind = NodeAclScopeKind.Cluster,
PermissionFlags = history && cluster == "CONSUMER" ? NodePermissions.Admin & ~NodePermissions.HistoryRead : NodePermissions.Admin });
}
db.DriverInstances.Add(new() { DriverInstanceRowId = Guid.NewGuid(), DriverInstanceId = "source-modbus", ClusterId = "SOURCE", Name = "modbus", DriverType = "Modbus",
DriverConfig = """{"TimeoutMs":2000,"AutoReconnect":true,"Probe":{"Enabled":true,"ProbeAddress":0}}""" });
@@ -347,13 +356,21 @@ try
TagConfig = """{"region":"HoldingRegisters","address":24,"dataType":"UInt16","isArray":true,"arrayLength":3,"writable":true}""" });
db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-text", DeviceId = "source-device", Name = "text", DataType = "String",
AccessLevel = TagAccessLevel.ReadWrite, WriteIdempotent = false, PollGroupId = "source-fast",
TagConfig = """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true}""" });
TagConfig = history
? """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true,"isHistorized":true}"""
: """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true}""" });
if (history)
// H3 review: a historized Float32 (two registers 30..31, big-endian), so the gate proves a backend that stores Double
// still reads Good Singles through the projection.
db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-flt", DeviceId = "source-device", Name = "flt", DataType = "Float",
AccessLevel = TagAccessLevel.ReadWrite, WriteIdempotent = false, PollGroupId = "source-fast",
TagConfig = """{"region":"HoldingRegisters","address":30,"dataType":"Float32","writable":true,"isHistorized":true}""" });
db.UnsAreas.Add(new() { UnsAreaRowId = Guid.NewGuid(), UnsAreaId = "source-area", ClusterId = "SOURCE", Name = "area" });
db.UnsLines.Add(new() { UnsLineRowId = Guid.NewGuid(), UnsLineId = "source-line", UnsAreaId = "source-area", Name = "line" });
var uuid = Guid.NewGuid();
var equipment = DraftValidator.DeriveEquipmentId(uuid);
db.Equipment.Add(new() { EquipmentRowId = Guid.NewGuid(), EquipmentId = equipment, EquipmentUuid = uuid, UnsLineId = "source-line", Name = "plc", MachineCode = "fixture-plc" });
foreach (var name in new[] { "counter", "scalar", "array0", "array1", "array2", "vector", "text" })
foreach (var name in new[] { "counter", "scalar", "array0", "array1", "array2", "vector", "text" }.Concat(history ? ["flt"] : []))
db.UnsTagReferences.Add(new() { UnsTagReferenceRowId = Guid.NewGuid(), UnsTagReferenceId = "ref-" + name, EquipmentId = equipment, TagId = "source-" + name });
db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "source-peer", ClusterId = "SOURCE", Principal = "fixture-consumer",
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin });
@@ -376,7 +393,10 @@ try
ClusterId = "CONSUMER", DataConnectionId = "consumer-source", Enabled = true, ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"],
Realm = realm, RemoteRealm = realm, LocalParentKind = "Cluster", LocalParentId = "CONSUMER", BranchName = "remote-source",
RemoteRootEntityId = entity, RemoteNamespaceUri = realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri,
RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "modbus/plc" : equipment, AllowedOperations = operations, WriteThrough = true });
RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "modbus/plc" : equipment, AllowedOperations = grantedOperations, WriteThrough = true });
if (history)
db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "cli-history-map-" + name, ClusterId = "CONSUMER", Principal = "fixture-cli",
ScopeKind = NodeAclScopeKind.RemoteNamespaceMapping, ScopeId = "map-" + name, PermissionFlags = NodePermissions.Browse | NodePermissions.HistoryRead });
}
if (history)
// The second principal's origin ACL also lacks HistoryRead: with its export's HistoryRead off the RPC is refused
@@ -403,7 +423,8 @@ try
browse_roots = new { raw = "modbus/plc", uns = unsBrowseRoot },
browse_subjects = new { raw = "modbus/plc", uns = "area/line/plc" },
origin_paths = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar", raw_array = "modbus/plc/vector", uns_array = "area/line/plc/vector", raw_string = "modbus/plc/text", uns_string = "area/line/plc/text" }, aliases = new[] { "raw", "uns" },
history = history ? new { historized = new { raw = "modbus/plc/counter", uns = "area/line/plc/counter" }, unhistorized = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar" } } : null });
history = history ? new { historized = new { raw = "modbus/plc/counter", uns = "area/line/plc/counter" }, unhistorized = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar" },
historized_string = new { raw = "modbus/plc/text", uns = "area/line/plc/text" } } : null });
return 0;
}
catch (Exception error)
@@ -888,5 +888,36 @@
"GrpcDataEditorValidationTests"
]
}
],
"H3": [
{
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.csproj",
"filter": "(Feature=GrpcData&Phase=H3)|FullyQualifiedName~.HistoryReadPortParityTests.|FullyQualifiedName~.SessionHistoryContinuationStoreTests.|FullyQualifiedName~.NodeManagerHistoryReadTests.|FullyQualifiedName~.NodeManagerHistoryReadPagingTests.|FullyQualifiedName~.NodeManagerAclEnforcementTests.|FullyQualifiedName~.GrpcDataMappedSubjectTests.|FullyQualifiedName~.GrpcDataSdkProjectionTests.",
"new_classes": [
"ProjectedHistoryReadTests"
],
"existing_classes": [
"HistoryReadPortParityTests",
"SessionHistoryContinuationStoreTests",
"NodeManagerHistoryReadTests",
"NodeManagerHistoryReadPagingTests",
"NodeManagerAclEnforcementTests",
"GrpcDataMappedSubjectTests",
"GrpcDataSdkProjectionTests"
]
},
{
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj",
"filter": "(Feature=GrpcData&Phase=H3)|FullyQualifiedName~.GrpcDataHistoryLeaseTests.|FullyQualifiedName~.GrpcDataHistoryClientTests.|FullyQualifiedName~.GrpcDataProjectedAccessTests.",
"new_classes": [
"GrpcDataProjectedHistoryCursorTests",
"GrpcDataConfiguredDiscoveryWireTests"
],
"existing_classes": [
"GrpcDataHistoryLeaseTests",
"GrpcDataHistoryClientTests",
"GrpcDataProjectedAccessTests"
]
}
]
}
@@ -83,6 +83,159 @@ public class HistoryReadCommand : CommandBase
[CommandOption("of-type", Description = "With --events: keep only events of this type or a subtype (an OfType where-clause), e.g. i=2955 (LimitAlarmType)")]
public string? OfType { get; init; }
/// <summary>AtTime: the requested times (ISO 8601 UTC, comma-separated). One page, printed with its status.</summary>
[CommandOption("at-time", Description = "HistoryRead-AtTime at these comma-separated ISO 8601 UTC times (instead of raw/aggregate)")]
public string? AtTimes { get; init; }
/// <summary>Raw: page by hand at this NumValuesPerNode, printing each page's status, size and continuation.</summary>
[CommandOption("page-size", Description = "Raw: read page by page with this NumValuesPerNode, printing each page's status and continuation (0 = off)")]
public int PageSize { get; init; }
/// <summary>With <c>--page-size</c>: after this page, wait for <c>--resume-when-file</c> before resuming in the SAME session.</summary>
[CommandOption("pause-after-page", Description = "With --page-size: pause after this page (holding the session) until --resume-when-file exists, then resume")]
public int PauseAfterPage { get; init; }
/// <summary>The file whose appearance ends a <c>--pause-after-page</c> pause (written by the operator / a live gate).</summary>
[CommandOption("resume-when-file", Description = "With --pause-after-page: resume once this file exists (it is not read or deleted)")]
public string? ResumeWhenFile { get; init; }
/// <summary>Written (empty) once the hand-paged read reaches its pause / abandon / release point, so a driver knows the page is held.</summary>
[CommandOption("held-marker-file", Description = "With --page-size: create this file when the read reaches its pause, abandon or release point")]
public string? HeldMarkerFile { get; init; }
/// <summary>How long a pause waits for <c>--resume-when-file</c> before giving up.</summary>
[CommandOption("pause-timeout", Description = "With --pause-after-page: seconds to wait for --resume-when-file (default 300)")]
public int PauseTimeoutSeconds { get; init; } = 300;
/// <summary>With <c>--page-size</c>: when a resumed page is refused, issue one fresh read of the same window and print it.</summary>
[CommandOption("fresh-after-failure", Description = "With --page-size: after a refused resumed page, issue one fresh read of the same window")]
public bool FreshAfterFailure { get; init; }
/// <summary>With <c>--page-size</c>: stop after this page WITHOUT releasing its continuation (the session close releases it).</summary>
[CommandOption("abandon-after-page", Description = "With --page-size: stop after this page without releasing its continuation point (disconnect releases it)")]
public int AbandonAfterPage { get; init; }
/// <summary>With <c>--page-size</c>: after this page, send releaseContinuationPoints for its continuation and stop.</summary>
[CommandOption("release-after-page", Description = "With --page-size: after this page, release its continuation point (releaseContinuationPoints) and stop")]
public int ReleaseAfterPage { get; init; }
/// <summary>With <c>--abandon-after-page</c>: keep the session open this long before disconnecting.</summary>
[CommandOption("hold-seconds", Description = "With --abandon-after-page / --release-after-page: keep the session open this many seconds before disconnecting")]
public int HoldSeconds { get; init; }
private static string Format(StatusCode status)
{
var text = status.ToString();
return text.Contains("[0x", StringComparison.Ordinal) ? text : $"{text} [0x{status.Code:X8}]";
}
private static async Task WriteRowsAsync(IConsole console, IReadOnlyList<DataValue> values)
{
foreach (var dv in values)
{
var status = StatusCode.IsGood(dv.StatusCode) ? "Good" : StatusCode.IsBad(dv.StatusCode) ? "Bad" : "Uncertain";
await console.Output.WriteLineAsync(
$"{dv.SourceTimestamp.ToString("O"),-35} {ValueFormatter.Format(ValueConverter.ToClrObject(dv.WrappedValue)),-15} {status}");
}
}
/// <summary>HistoryRead-AtTime: one page, its status, then the rows (the value type is printed, so integer nodes show).</summary>
private async Task ReadAtTimeAsync(IOpcUaClientService service, IConsole console, NodeId nodeId, CancellationToken ct)
{
DateTime[] times;
try
{
times = AtTimes!.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(t => DateTime.Parse(t, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal))
.ToArray();
}
catch (FormatException ex)
{
throw new CommandException($"Invalid --at-time value: {ex.Message}");
}
if (times.Length == 0) throw new CommandException("--at-time needs at least one time.");
var details = new ReadAtTimeDetails { ReqTimes = times.Select(t => (DateTimeUtc)t).ToArray(), UseSimpleBounds = true };
var page = await service.HistoryReadPageAsync(details, nodeId, null, false, ct);
await console.Output.WriteLineAsync($"AtTime history for {NodeId} ({times.Length} times)");
await console.Output.WriteLineAsync($"Status: {Format(page.Status)}");
await console.Output.WriteLineAsync();
await console.Output.WriteLineAsync($"{"Timestamp",-35} {"Value",-15} {"Status"}");
await WriteRowsAsync(console, page.Values);
foreach (var dv in page.Values)
await console.Output.WriteLineAsync($"Type: {ValueConverter.ToClrObject(dv.WrappedValue)?.GetType().Name ?? "null"}");
await console.Output.WriteLineAsync();
await console.Output.WriteLineAsync($"{page.Values.Count} values returned.");
}
/// <summary>
/// Raw history page by page in ONE session: each page's status, size and continuation are printed, so a resume that
/// the server refuses (<c>BadContinuationPointInvalid</c>) is visible instead of an exception, and a pause holds the
/// session (and its continuation point) open while something else happens (a failover, a rebuild).
/// </summary>
private async Task ReadPagesAsync(IOpcUaClientService service, IConsole console, NodeId nodeId, DateTime start, DateTime end, CancellationToken ct)
{
var details = new ReadRawModifiedDetails
{
StartTime = start, EndTime = end, NumValuesPerNode = (uint)PageSize, IsReadModified = false, ReturnBounds = false,
};
await console.Output.WriteLineAsync($"Paged history for {NodeId} (page size {PageSize})");
byte[]? cp = null;
var total = 0;
for (var number = 1; ; number++)
{
var resumed = cp is not null;
var page = await service.HistoryReadPageAsync(details, nodeId, cp, false, ct);
await console.Output.WriteLineAsync(
$"Page {number}: {Format(page.Status)} values={page.Values.Count} continuation={(page.ContinuationPoint is null ? "no" : "yes")}{(resumed ? " resumed" : "")}");
await WriteRowsAsync(console, page.Values);
total += page.Values.Count;
if (StatusCode.IsBad(page.Status))
{
if (resumed && FreshAfterFailure)
{
var fresh = await service.HistoryReadPageAsync(details, nodeId, null, false, ct);
await console.Output.WriteLineAsync(
$"Fresh: {Format(fresh.Status)} values={fresh.Values.Count} continuation={(fresh.ContinuationPoint is null ? "no" : "yes")}");
await WriteRowsAsync(console, fresh.Values);
if (fresh.ContinuationPoint is { } freshCp) await service.HistoryReadPageAsync(details, nodeId, freshCp, true, ct);
}
break;
}
cp = page.ContinuationPoint;
if (cp is null || total >= MaxValues) break;
if (number == AbandonAfterPage)
{
await console.Output.WriteLineAsync($"Abandoned after page {number} (continuation not released; holding {HoldSeconds}s)");
if (HeldMarkerFile is not null) await File.WriteAllTextAsync(HeldMarkerFile, "", ct);
if (HoldSeconds > 0) await Task.Delay(TimeSpan.FromSeconds(HoldSeconds), ct);
return;
}
if (number == ReleaseAfterPage)
{
var released = await service.HistoryReadPageAsync(details, nodeId, cp, true, ct);
await console.Output.WriteLineAsync($"Released after page {number}: {Format(released.Status)}");
if (HeldMarkerFile is not null) await File.WriteAllTextAsync(HeldMarkerFile, "", ct);
if (HoldSeconds > 0) await Task.Delay(TimeSpan.FromSeconds(HoldSeconds), ct);
return;
}
if (number == PauseAfterPage)
{
await console.Output.WriteLineAsync($"Paused after page {number}; waiting for {ResumeWhenFile}");
if (HeldMarkerFile is not null) await File.WriteAllTextAsync(HeldMarkerFile, "", ct);
var deadline = DateTime.UtcNow.AddSeconds(PauseTimeoutSeconds);
while (!File.Exists(ResumeWhenFile))
{
if (DateTime.UtcNow >= deadline) throw new CommandException($"--resume-when-file did not appear within {PauseTimeoutSeconds}s.");
await Task.Delay(200, ct);
}
await console.Output.WriteLineAsync("Resuming");
}
}
await console.Output.WriteLineAsync();
await console.Output.WriteLineAsync($"{total} values returned.");
}
/// <summary>The event fields an event read selects when <c>--fields</c> is omitted.</summary>
internal static readonly string[] DefaultEventFields =
["EventId", "EventType", "Time", "SourceName", "Severity", "Message", "ConditionName", "SourceNode"];
@@ -101,6 +254,16 @@ public class HistoryReadCommand : CommandBase
throw new CommandException("--events cannot be combined with --modified or --aggregate.");
if (!Events && (Fields is not null || OfType is not null))
throw new CommandException("--fields and --of-type apply only to --events.");
if (PageSize < 0 || PauseAfterPage < 0 || AbandonAfterPage < 0 || ReleaseAfterPage < 0 || HoldSeconds < 0 || PauseTimeoutSeconds <= 0)
throw new CommandException("--page-size, --pause-after-page, --abandon-after-page, --release-after-page and --hold-seconds must be >= 0; --pause-timeout > 0.");
if (PageSize == 0 && (PauseAfterPage > 0 || AbandonAfterPage > 0 || ReleaseAfterPage > 0 || FreshAfterFailure))
throw new CommandException("--pause-after-page, --abandon-after-page, --release-after-page and --fresh-after-failure need --page-size.");
if (PauseAfterPage > 0 && string.IsNullOrWhiteSpace(ResumeWhenFile))
throw new CommandException("--pause-after-page needs --resume-when-file.");
if ((PageSize > 0 || AtTimes is not null) && (Events || Modified || !string.IsNullOrEmpty(Aggregate)))
throw new CommandException("--page-size and --at-time read raw / AtTime history only.");
if (PageSize > 0 && AtTimes is not null)
throw new CommandException("--page-size and --at-time cannot be combined.");
NodeId nodeId;
try
@@ -220,6 +383,18 @@ public class HistoryReadCommand : CommandBase
return;
}
if (AtTimes is not null)
{
await ReadAtTimeAsync(service, console, nodeId, ct);
return;
}
if (PageSize > 0)
{
await ReadPagesAsync(service, console, nodeId, start, end, ct);
return;
}
IReadOnlyList<DataValue> values;
if (string.IsNullOrEmpty(Aggregate))
@@ -247,6 +247,17 @@ internal sealed class DefaultSessionAdapter : ISessionAdapter
}
/// <summary>Issues one single-node HistoryRead (or a release of its continuation point).</summary>
/// <inheritdoc />
public async Task<Models.HistoryPage> HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint,
bool release, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(details);
var result = await ReadHistoryPageAsync(details, nodeId, continuationPoint, release, TimestampsToReturn.Both, ct).ConfigureAwait(false);
if (result is null) return new Models.HistoryPage(StatusCodes.BadUnexpectedError, [], null);
IReadOnlyList<DataValue> values = result.HistoryData.TryGetValue(out HistoryData? data) ? data.DataValues.ToArray() ?? [] : [];
return new Models.HistoryPage(result.StatusCode, values, result.ContinuationPoint.IsEmpty ? null : result.ContinuationPoint.ToArray());
}
private async Task<HistoryReadResult?> ReadHistoryPageAsync(
HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint, bool release,
TimestampsToReturn timestamps, CancellationToken ct)
@@ -274,7 +285,10 @@ internal sealed class DefaultSessionAdapter : ISessionAdapter
StartTime = startTime,
EndTime = endTime,
ProcessingInterval = intervalMs,
AggregateType = [aggregateId]
AggregateType = [aggregateId],
// The SDK's default AggregateConfiguration is all-false/0 — a NON-default configuration, which this server
// refuses BadAggregateConfigurationRejected (#677). Ask for the server's own defaults, as Part 13 intends.
AggregateConfiguration = new AggregateConfiguration { UseServerCapabilitiesDefaults = true },
};
ArrayOf<HistoryReadValueId> nodesToRead = [new HistoryReadValueId { NodeId = nodeId }];
@@ -162,6 +162,19 @@ internal interface ISessionAdapter : IDisposable
Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime,
NodeId aggregateId, double intervalMs, CancellationToken ct = default);
/// <summary>
/// Reads (or, with <paramref name="release"/>, releases) ONE HistoryRead page for one node, returning the server's
/// status, values and continuation point verbatim — no paging, no refusal exception.
/// </summary>
/// <param name="details">Raw, Processed or AtTime details.</param>
/// <param name="nodeId">The node.</param>
/// <param name="continuationPoint">The point to resume (or release); null = a fresh read.</param>
/// <param name="release">Send <c>releaseContinuationPoints = true</c>.</param>
/// <param name="ct">Cancellation.</param>
/// <returns>The page.</returns>
Task<Models.HistoryPage> HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint, bool release,
CancellationToken ct = default);
/// <summary>
/// Creates a subscription adapter for this session.
/// </summary>
@@ -258,6 +258,20 @@ public interface IOpcUaClientService : IDisposable
Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime,
AggregateType aggregate, double intervalMs = 3600000, CancellationToken ct = default);
/// <summary>
/// Reads (or, with <paramref name="release"/>, releases) ONE HistoryRead page for one node and returns the server's
/// status, values and continuation point verbatim — for callers that page by hand and must see each page's status
/// (a <c>BadContinuationPointInvalid</c> resume, a refusal) instead of an exception.
/// </summary>
/// <param name="details">Raw, Processed or AtTime details.</param>
/// <param name="nodeId">The node.</param>
/// <param name="continuationPoint">The point to resume (or release); null = a fresh read.</param>
/// <param name="release">Send <c>releaseContinuationPoints = true</c>.</param>
/// <param name="ct">Cancellation.</param>
/// <returns>The page.</returns>
Task<HistoryPage> HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint = null, bool release = false,
CancellationToken ct = default);
/// <summary>
/// Reads redundancy status data such as redundancy mode, service level, and partner endpoint URIs.
/// </summary>
@@ -0,0 +1,13 @@
using Opc.Ua;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
/// <summary>
/// One HistoryRead page exactly as the server answered it: the per-node status (never thrown), its values and the
/// continuation point the server returned (null when the read is complete). Used by callers that page by hand —
/// the CLI's <c>--page-size</c> / <c>--pause-after-page</c> modes and the gRPC data live gate.
/// </summary>
/// <param name="Status">The per-node operation status.</param>
/// <param name="Values">The returned values (empty on a refusal).</param>
/// <param name="ContinuationPoint">The next continuation point, or null when the read is complete.</param>
public sealed record HistoryPage(StatusCode Status, IReadOnlyList<DataValue> Values, byte[]? ContinuationPoint);
@@ -711,6 +711,15 @@ public sealed class OpcUaClientService : IOpcUaClientService
return await _session!.HistoryReadAggregateAsync(nodeId, startTime, endTime, aggregateNodeId, intervalMs, ct);
}
/// <inheritdoc />
public async Task<HistoryPage> HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint = null,
bool release = false, CancellationToken ct = default)
{
ThrowIfDisposed();
ThrowIfNotConnected();
return await _session!.HistoryReadPageAsync(details, nodeId, continuationPoint, release, ct);
}
/// <inheritdoc />
public async Task<RedundancyInfo> GetRedundancyInfoAsync(CancellationToken ct = default)
{
@@ -262,6 +262,14 @@ public sealed record DataHistoryReadResult(string CorrelationId, uint StatusCode
string? Diagnostic = null, bool ChunkContinues = false)
: IDisposable
{
/// <summary>
/// Consumer-side only, never on the wire (H3 review round 3): this <c>BadTooManyOperations</c> is the CONSUMER's own
/// assembly-budget refusal (the gRPC connection's chunk assembly or sub-batch split ran out of the request's byte
/// budget) — not an origin's refusal (e.g. its remainder budget), whose text may also mention a budget. A caller that
/// stops the request on a spent budget keys on this flag, never on <see cref="Diagnostic"/>.
/// </summary>
internal bool ConsumerBudgetRefused { get; init; }
public void Dispose()
{
foreach (var sample in Samples) sample.Dispose();
@@ -13,6 +13,7 @@
<None Include="README.md" />
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests" />
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Runtime" />
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Runtime.Tests" />
</ItemGroup>
</Project>
@@ -118,6 +118,13 @@ public static class DataConnectionRegistration
(!settings.IsWarm || state.WarmRole == WarmRole.Active), state.Generation);
}, renewalSink: sp.GetRequiredService<IProjectedNamespacePageSink>()));
services.AddSingleton<IProjectedDataAccess>(sp => sp.GetRequiredService<ProjectedDataAccess>());
// H3: OPC UA HistoryRead on projected variables, forwarded over the mapping's deployed connection.
services.AddSingleton(sp => new ProjectedHistoryAccess(sp.GetRequiredService<ProjectedDataAccess>(),
sp.GetRequiredService<IGrpcDataAdapterConnectionSource>(),
mappingId => sp.GetRequiredService<ProjectedMappingDeploymentRuntime>().TryGetHistoryAssemblyBudget(mappingId, out var bytes)
? bytes : null,
sp.GetRequiredService<TimeProvider>()));
services.AddSingleton<IProjectedHistoryAccess>(sp => sp.GetRequiredService<ProjectedHistoryAccess>());
services.AddSingleton<IConfiguredProjectionDiscovery>(sp => new ConfiguredProjectionDiscovery(
sp.GetRequiredService<ProjectedMappingDeploymentRuntime>(), sp.GetRequiredService<IFederatedProjectionCatalog>(),
sp.GetRequiredService<ProjectedNamespaceApplier>(), sp.GetRequiredService<IProjectedNodeLookup>(),
@@ -60,6 +60,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
private readonly DriverWriteBounds _writeBounds;
private readonly IProjectedBrowseAccess? _projectedBrowseAccess;
private readonly IProjectedDataAccess? _projectedDataAccess;
private readonly IProjectedHistoryAccess? _projectedHistoryAccess;
private readonly IFederatedProjectionCatalog? _projectedCatalog;
private readonly DataConnectionOptions _dataConnectionOptions;
@@ -140,6 +141,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
/// <param name="projectedBrowseAccess">Optional caller-bound mapped browse scheduler.</param>
/// <param name="projectedDataAccess">Optional bounded mapped read, write and subscription gateway.</param>
/// <param name="projectedCatalog">Optional live projection catalog used for mapped authorization.</param>
/// <param name="projectedHistoryAccess">Optional HistoryRead gateway for projected variables (H3).</param>
public OtOpcUaServerHostedService(
IOptions<OpcUaApplicationHostOptions> options,
DeferredAddressSpaceSink deferredSink,
@@ -164,8 +166,10 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
DeferredStandbyProjection? deferredStandby = null,
IProjectedBrowseAccess? projectedBrowseAccess = null,
IProjectedDataAccess? projectedDataAccess = null,
IFederatedProjectionCatalog? projectedCatalog = null)
IFederatedProjectionCatalog? projectedCatalog = null,
IProjectedHistoryAccess? projectedHistoryAccess = null)
{
_projectedHistoryAccess = projectedHistoryAccess;
_dataConnectionOptions = configuration.GetSection(DataConnectionOptions.SectionName).Get<DataConnectionOptions>() ?? new();
_projectedBrowseAccess = projectedBrowseAccess;
_projectedDataAccess = projectedDataAccess;
@@ -264,6 +268,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
_server.NodeManager.ProjectedBrowseAccess = _projectedBrowseAccess;
_server.NodeManager.ProjectedBrowseClock = _time;
_server.NodeManager.ProjectedDataAccess = _projectedDataAccess;
_server.NodeManager.ProjectedHistoryAccess = _projectedHistoryAccess;
if (_projectedCatalog is { } projectedCatalog)
_server.NodeManager.MappedSubjectResolver = (realm, identifier) =>
projectedCatalog.TryResolveProjected(realm == AddressSpaceRealm.Raw ? DataRealm.Raw : DataRealm.Uns,
@@ -87,7 +87,10 @@ internal sealed class SessionHistoryContinuationStore : IHistoryContinuationStor
// RestoreHistoryContinuationPoint REMOVES the slot (single-use) and returns null for an unknown /
// malformed (non-16-byte) point — exactly the "miss ⇒ BadContinuationPointInvalid" contract.
using var point = session.ContinuationPoints.RestoreHistory(ByteString.From(continuationPoint));
return (point as SessionHistoryPoint)?.State;
if (point is not SessionHistoryPoint taken) return null;
// A take hands the state (and an H3 remote cursor) back to the caller: disposing the slot must not release it.
taken.Taken = true;
return taken.State;
}
/// <inheritdoc />
@@ -98,8 +101,15 @@ internal sealed class SessionHistoryContinuationStore : IHistoryContinuationStor
{
public Guid Id { get; } = id;
public HistoryContinuationState State { get; } = state;
// The immutable resume state contains managed value data only. No handles or owned resources.
public void Dispose() { }
public bool Taken { get; set; }
// Local resume state is managed values only. An H3 remote cursor holds an origin continuation: the SDK disposes the
// point on session close, oldest-eviction, releaseContinuationPoints and a faulted request — each of those (never a
// take) releases it at the origin, best effort (the origin's idle expiry is the backstop).
public void Dispose()
{
if (!Taken) State.Remote?.Release();
}
}
}
@@ -132,7 +142,7 @@ internal sealed class InMemoryHistoryContinuationStore(int capacity = 100) : IHi
while (_states.Count >= _capacity && _order.Count > 0)
{
var oldest = _order.Dequeue();
_states.Remove(oldest);
if (_states.Remove(oldest, out var evicted)) evicted.Remote?.Release();
}
_states[id] = state;
@@ -160,9 +170,29 @@ internal sealed class InMemoryHistoryContinuationStore(int capacity = 100) : IHi
{
if (continuationPoint is null || continuationPoint.Length != 16) return;
var id = new Guid(continuationPoint);
HistoryContinuationState? released;
lock (_gate)
{
_states.Remove(id);
_states.Remove(id, out released);
}
released?.Remote?.Release();
}
/// <summary>Live entries (tests).</summary>
public int Count { get { lock (_gate) return _states.Count; } }
/// <summary>Drops every entry as an SDK session close does — releasing remote cursors (tests).</summary>
public void Clear()
{
HistoryContinuationState[] all;
lock (_gate)
{
all = _states.Values.ToArray();
_states.Clear();
_order.Clear();
}
foreach (var state in all) state.Remote?.Release();
}
}
@@ -98,7 +98,8 @@ internal sealed record HistoryContinuationState(
AddressSpaceRealm BoundRealm = default,
string? BoundIdentifier = null,
string? BoundTag = null,
long AddressSpaceEpoch = -1)
long AddressSpaceEpoch = -1,
ProjectedHistoryContinuation? Remote = null)
{
/// <summary>The walk-back hint this cursor carries.</summary>
public ReverseWalkHint WalkHint => new(SegmentWidthTicks, EmptyFromTicks, EmptyToTicks);
@@ -115,6 +116,12 @@ internal enum HistoryCursorKind
/// <summary>HistoryReadRaw with <c>IsReadModified = true</c> — the Part 11 modification trail.</summary>
Modified,
/// <summary>
/// H3: a projected node's remote cursor (<see cref="HistoryContinuationState.Remote"/>) — an origin token plus what the
/// projection bound it to. Disposing the stored point (session close, eviction, release) releases it at the origin.
/// </summary>
Remote,
}
/// <summary>
@@ -462,7 +462,14 @@ public sealed partial class OtOpcUaNodeManager
public byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding) =>
nm._historyContinuationStore.Save(session, state);
public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding) =>
nm._historyContinuationStore.TryTake(session, continuationPoint);
public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding)
{
var state = nm._historyContinuationStore.TryTake(session, continuationPoint);
if (state?.Remote is not { } remote) return state;
// H3 review D5: a projected node's Remote cursor presented to a LOCAL node is invalid here (the port refuses an
// unknown/mismatched cursor) — but it was taken out of the session, so release its origin continuation now.
remote.Release();
return null;
}
}
}
@@ -0,0 +1,100 @@
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>
/// H3 — the remote cursor behind a <see cref="HistoryCursorKind.Remote"/> continuation point in the consumer's SDK session
/// store (gRPC data history plan §3.2). Opaque to the node manager: the projection side (Runtime) owns what it binds —
/// the origin token, mapping id/revision, serving incarnation, projection generation, caller key and the ORIGINAL request
/// details — and re-checks all of it on resume. The node manager only binds it to the projected node it was issued for.
/// </summary>
public abstract class ProjectedHistoryContinuation
{
private int _claimed, _released;
/// <summary>Creates a cursor bound to one projected node.</summary>
/// <param name="realm">The projected node's realm.</param>
/// <param name="localIdentifier">The projected node's opaque local identifier.</param>
protected ProjectedHistoryContinuation(DataRealm realm, string localIdentifier)
{
ArgumentException.ThrowIfNullOrWhiteSpace(localIdentifier);
Realm = realm;
LocalIdentifier = localIdentifier;
}
/// <summary>The projected node's realm.</summary>
public DataRealm Realm { get; }
/// <summary>The projected node's local identifier.</summary>
public string LocalIdentifier { get; }
/// <summary>True once the cursor was released or handed back for a resume (it is single-use either way).</summary>
public bool IsSpent => Volatile.Read(ref _released) != 0 || Volatile.Read(ref _claimed) != 0;
/// <summary>
/// Best-effort, idempotent, non-blocking release of the origin continuation (<c>releaseContinuationPoints</c>, session
/// close, eviction, a store refusal). A no-op once the cursor was claimed for a resume: the resume owns it from then on
/// (and uses <see cref="ReleaseEvenIfClaimed"/> on every exit that does not send it). The origin's idle expiry is the
/// backstop.
/// </summary>
public void Release()
{
if (Volatile.Read(ref _claimed) != 0) return;
ReleaseOnce();
}
/// <summary>
/// Releases the origin continuation whether or not the cursor was claimed for a resume — for every post-claim exit that
/// never sends it (refused, limiter-rejected, timed out, faulted). Never releases twice.
/// </summary>
public void ReleaseEvenIfClaimed() => ReleaseOnce();
/// <summary>Marks the cursor as handed back for a resume: the resume read owns the origin token from here on.</summary>
/// <returns><c>false</c> when it was already released or resumed.</returns>
public bool TryClaimForResume() => Volatile.Read(ref _released) == 0 && Interlocked.Exchange(ref _claimed, 1) == 0;
private void ReleaseOnce()
{
if (Interlocked.Exchange(ref _released, 1) == 0) OnRelease();
}
/// <summary>Forwards the release to the origin (called at most once).</summary>
protected abstract void OnRelease();
}
/// <summary>One projected node of a consumer HistoryRead (H3).</summary>
/// <param name="NodeId">The projected node.</param>
/// <param name="AggregateId">Processed only: the requested aggregate's ns=0 numeric id.</param>
/// <param name="Resume">The claimed remote cursor of a resumed read; null = a fresh read.</param>
public sealed record ProjectedHistoryNode(NodeId NodeId, uint? AggregateId = null, ProjectedHistoryContinuation? Resume = null);
/// <summary>One projected node's outcome: the origin's Part 11 status verbatim, its values, and the next cursor.</summary>
/// <param name="StatusCode">The full OPC UA status.</param>
/// <param name="Samples">The values (CLR values, verbatim status and timestamps).</param>
/// <param name="Continuation">The next remote cursor; null when the read is complete.</param>
public sealed record ProjectedHistoryOutcome(uint StatusCode, IReadOnlyList<OriginHistorySample> Samples, ProjectedHistoryContinuation? Continuation = null);
/// <summary>
/// H3 — HistoryRead on projected variables (plan §2.1, §3.2): resolves each projected node to its mapping, deployed
/// connection lease and origin view, authorizes it (the mapping's HistoryRead bit and a local
/// <c>NodePermissions.HistoryRead</c> grant on the mapping scope, ACLs on or off), and forwards through
/// <see cref="IDataHistoryService"/>. A fresh read may move endpoint within its deadline; a resumed read never moves.
/// </summary>
public interface IProjectedHistoryAccess
{
/// <summary>
/// Reads one batch of projected nodes for <paramref name="caller"/>. Never called under the node-manager <c>Lock</c>.
/// Results are in <paramref name="nodes"/> order. Every <see cref="ProjectedHistoryNode.Resume"/> cursor is owned by
/// the call (resumed or released), whatever the outcome.
/// </summary>
/// <param name="caller">The session identity.</param>
/// <param name="details">The request details (fresh nodes; a resumed node resends its ORIGINAL details).</param>
/// <param name="nodes">The projected nodes.</param>
/// <param name="deadline">The consumer request's remaining <c>HistoryReadDeadline</c>; non-positive = unbounded.</param>
/// <param name="cancellationToken">The SDK request lifetime.</param>
/// <returns>One outcome per node.</returns>
Task<IReadOnlyList<ProjectedHistoryOutcome>> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details,
IReadOnlyList<ProjectedHistoryNode> nodes, TimeSpan deadline, CancellationToken cancellationToken);
}
@@ -89,23 +89,18 @@ public sealed class OriginHistoryPort(OtOpcUaNodeManager nodeManager) : IOriginH
private readonly OtOpcUaNodeManager _nm = nodeManager ?? throw new ArgumentNullException(nameof(nodeManager));
private (IHistorianDataSource Source, OriginHistoryServing? Serving)? _serving;
private SemaphoreSlim? _remoteSlots;
private readonly Lock _slotsGate = new();
/// <summary>
/// The share of the node manager's process-wide history batch limiter (N = <c>MaxConcurrentHistoryReadBatches</c>)
/// remote peers may hold: N - max(1, N/4), at least 1. The rest stays free for local OPC UA HistoryRead.
/// NON-LOCAL reads may hold: N - max(1, N/4), at least 1. The rest stays free for local OPC UA HistoryRead.
/// </summary>
public static int RemoteSlots(int batches) => Math.Max(1, batches - Math.Max(1, batches / 4));
/// <summary>Remote slots currently free (diagnostics/tests).</summary>
/// <summary>Non-local slots currently free (diagnostics/tests) — shared with the node's projected reads (H3 review round 2).</summary>
public int AvailableRemoteSlots => Slots().CurrentCount;
private SemaphoreSlim Slots()
{
if (_remoteSlots is { } slots) return slots;
lock (_slotsGate) return _remoteSlots ??= new SemaphoreSlim(RemoteSlots(Math.Max(1, _nm.MaxConcurrentHistoryReadBatches)));
}
// ONE semaphore for every non-local history read of this node manager: remote peers here AND projected reads to other
// origins. Two independent N - max(1, N/4) shares would still let both together starve local history.
private SemaphoreSlim Slots() => _nm.GetNonLocalHistoryLimiter();
/// <inheritdoc />
/// <remarks>Cached per historian source instance: the catalog asks per node, so this is a reference compare, not a rebuild.</remarks>
@@ -39,6 +39,12 @@ public sealed record ProjectedVariableDefinition(DataRealm Realm, string LocalId
{
/// <summary>Stable across same-node metadata renewal, replaced on node retirement.</summary>
public ProjectedNodeLifetime Lifetime { get; init; } = new();
/// <summary>
/// H3: the node is <c>Historizing</c> with the HistoryRead access bit — only when the mapping grants HistoryRead AND the
/// origin's negotiated metadata says the node is historizing (plan §2.1). Never the HistoryWrite bit.
/// </summary>
public bool Historizing { get; init; }
}
/// <summary>Locally authorized placement for a configured mapping anchor.</summary>
@@ -4677,6 +4683,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
!commit() || !renewed.AuthorityIsCurrent() || !old.Lifetime.IsActive) return false;
_projectedVariables[nodeId] = (existing.Parent, renewed.ProjectionGeneration, renewed.Metadata, existing.Node, renewed.AuthorityIsCurrent);
_projectedDefinitions[nodeId] = renewed;
ApplyProjectedHistorizing(existing.Node, renewed.Historizing);
_projectedNodeBytes += delta; _projectedNodeCharges[nodeId] = charge;
CommitProjectedDefinition(nodeId, renewed);
return true;
@@ -4740,6 +4747,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
_projectedVariables[renewal.Id] = (previous.Parent, renewal.Definition.ProjectionGeneration, renewal.Definition.Metadata,
previous.Node, renewal.Definition.AuthorityIsCurrent);
_projectedDefinitions[renewal.Id] = renewal.Definition;
ApplyProjectedHistorizing(previous.Node, renewal.Definition.Historizing);
_projectedNodeBytes += renewal.Charge - _projectedNodeCharges[renewal.Id];
_projectedNodeCharges[renewal.Id] = renewal.Charge;
}
@@ -4796,6 +4804,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
!installed.AuthorityIsCurrent() || !commit() || !installed.AuthorityIsCurrent()) return false;
_projectedVariables[anchorId] = (existing.Parent, existing.Generation, installed.Metadata, existingNode, installed.AuthorityIsCurrent);
_projectedDefinitions[anchorId] = installed;
ApplyProjectedHistorizing(existingNode, installed.Historizing);
_projectedNodeCharges[anchorId] = renewedCharge;
_projectedNodeBytes += delta;
CommitProjectedDefinition(anchorId, installed);
@@ -4833,6 +4842,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
var charged = false;
try
{
ApplyProjectedHistorizing(variable, installed.Historizing);
parent.RemoveChild(folder); PredefinedNodes?.Remove(anchorId);
parent.AddChild(variable); AddPredefinedNode(SystemContext, variable);
_projectedAnchors[anchorId] = (anchor.Definition, variable);
@@ -4925,6 +4935,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
AccessLevel = AccessLevels.CurrentRead, UserAccessLevel = AccessLevels.CurrentRead,
Value = Variant.Null, StatusCode = StatusCodes.BadWaitingForInitialData, Timestamp = DateTime.MinValue };
if (!definition.AuthorityIsCurrent()) return false;
ApplyProjectedHistorizing(node, definition.Historizing);
parent.AddChild(node); AddPredefinedNode(SystemContext, node);
_projectedVariables.Add(candidate, (definition.Parent, definition.ProjectionGeneration, definition.Metadata, node, definition.AuthorityIsCurrent));
_projectedDefinitions.Add(candidate, definition);
@@ -8798,7 +8809,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
}
/// <inheritdoc />
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve.</remarks>
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve (H3: projected handles go remote).</remarks>
protected override void HistoryReadRawModified(
ServerSystemContext context,
ReadRawModifiedDetails details,
@@ -8810,11 +8821,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
IDictionary<NodeId, NodeState> cache)
{
nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors);
ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors);
ServeHistoryReadSplit(context, details, nodesToRead, nodesToProcess, results, errors);
}
/// <inheritdoc />
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve.</remarks>
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve (H3: projected handles go remote).</remarks>
protected override void HistoryReadProcessed(
ServerSystemContext context,
ReadProcessedDetails details,
@@ -8826,11 +8837,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
IDictionary<NodeId, NodeState> cache)
{
nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors);
ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors);
ServeHistoryReadSplit(context, details, nodesToRead, nodesToProcess, results, errors);
}
/// <inheritdoc />
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve.</remarks>
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve (H3: projected handles go remote).</remarks>
protected override void HistoryReadAtTime(
ServerSystemContext context,
ReadAtTimeDetails details,
@@ -8842,7 +8853,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
IDictionary<NodeId, NodeState> cache)
{
nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors);
ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors);
ServeHistoryReadSplit(context, details, nodesToRead, nodesToProcess, results, errors);
}
/// <inheritdoc />
@@ -9034,6 +9045,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
// Single-use take. A miss (unknown / evicted / malformed / a RAW cursor) ⇒ BadContinuationPointInvalid
// for THIS node only.
var state = _historyContinuationStore.TryTake(session, inboundCp.ToArray());
// H3: a projected node's Remote cursor taken here is a miss — release its origin continuation.
state?.Remote?.Release();
// A point is bound to the node that issued it: another node's source name is a miss too.
var boundKey = MapKey(handle.NodeId);
if (state is null || !HistoryContinuationMatches(state, boundKey.Realm, boundKey.Id, HistoryBindingTag(handle.NodeId), historyEpoch) || state.Kind != HistoryCursorKind.Events || state.Tagname != sourceName)
@@ -9948,10 +9961,28 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (gate is not null) return gate;
lock (_historyReadBatchLimiterLock)
{
return _historyReadBatchLimiter ??= new SemaphoreSlim(Math.Max(1, MaxConcurrentHistoryReadBatches));
if (_historyReadBatchLimiter is { } created) return created;
// H3 review round 2: the NON-LOCAL share is sized from the SAME N at the same moment, so it can never exceed
// N - max(1, N/4) of the limiter that actually exists (two independent first-use sizings could disagree).
var batches = Math.Max(1, MaxConcurrentHistoryReadBatches);
_nonLocalHistoryLimiter = new SemaphoreSlim(OriginHistoryPort.RemoteSlots(batches));
return _historyReadBatchLimiter = new SemaphoreSlim(batches);
}
}
private volatile SemaphoreSlim? _nonLocalHistoryLimiter;
/// <summary>
/// The NON-LOCAL share of the history batch slots — remote peers reading this origin (<see cref="OriginHistoryPort"/>) and
/// this node's projected reads to other origins, together: <see cref="OriginHistoryPort.RemoteSlots"/> of the N the shared
/// limiter was created with (both are created together, at first use).
/// </summary>
internal SemaphoreSlim GetNonLocalHistoryLimiter()
{
GetHistoryReadBatchLimiter();
return _nonLocalHistoryLimiter!;
}
/// <summary>Link the SDK request lifetime to the application's per-batch history deadline.</summary>
/// <param name="context">The request's server context.</param>
/// <returns>The linked deadline source, or null when neither request nor application can cancel.</returns>
@@ -0,0 +1,318 @@
using System.Diagnostics;
using Opc.Ua;
using Opc.Ua.Server;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
using DataValue = Opc.Ua.DataValue;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>
/// H3 — consumer OPC UA projection of remote history (gRPC data history plan §3.2). The Raw / Processed / AtTime overrides
/// split one request's authorized handles: local handles go to the H1 port exactly as before, projected handles (the
/// mapped/raw and mapped/uns namespaces) to <see cref="ProjectedHistoryAccess"/>. Every result is written back to its own
/// handle's slot, so a mixed batch keeps request order. Nothing here runs under, or takes, <c>Lock</c>: the SDK releases it
/// before it dispatches the overrides, and the remote read is block-bridged once per batch, like the port.
/// </summary>
public sealed partial class OtOpcUaNodeManager
{
private IProjectedHistoryAccess? _projectedHistoryAccess;
/// <summary>The remote history gateway for projected variables (H3); null = projected nodes answer unsupported.</summary>
public IProjectedHistoryAccess? ProjectedHistoryAccess
{
get => Volatile.Read(ref _projectedHistoryAccess);
set => Volatile.Write(ref _projectedHistoryAccess, value);
}
/// <summary>Serves local handles through the port (unchanged) and projected handles remotely, each into its own slot.</summary>
private void ServeHistoryReadSplit(
ServerSystemContext context,
HistoryReadDetails details,
ArrayOf<HistoryReadValueId> nodesToRead,
List<NodeHandle> nodesToProcess,
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors)
{
List<NodeHandle>? projected = null;
foreach (var handle in nodesToProcess)
if (IsProjectedDescendant(handle.NodeId)) (projected ??= []).Add(handle);
if (projected is null)
{
ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors);
return;
}
var started = Stopwatch.GetTimestamp();
var local = nodesToProcess.Where(h => !IsProjectedDescendant(h.NodeId)).ToList();
if (local.Count > 0) ServeHistoryReadAdapter(context, details, nodesToRead, local, results, errors);
ServeProjectedHistory(context, details, nodesToRead, projected, results, errors, started);
}
/// <summary>The projected half of a variable-history request.</summary>
private void ServeProjectedHistory(
ServerSystemContext context,
HistoryReadDetails details,
ArrayOf<HistoryReadValueId> nodesToRead,
List<NodeHandle> handles,
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors,
long started)
{
var session = context.OperationContext?.Session;
var store = _historyContinuationStore;
var epoch = Volatile.Read(ref _historyContinuationEpoch);
var access = ProjectedHistoryAccess;
var identity = IdentityOf(context);
var remote = ToRemoteDetails(details);
var aggregates = details is ReadProcessedDetails processed ? processed.AggregateType : default;
var pending = new List<(NodeHandle Handle, ProjectedHistoryNode Node)>(handles.Count);
ProjectedHistoryContinuation? claimed = null;
try
{
foreach (var handle in handles)
{
var key = MapKey(handle.NodeId);
var tag = HistoryBindingTag(handle.NodeId);
var cp = nodesToRead[handle.Index].ContinuationPoint;
ProjectedHistoryContinuation? resume = null;
if (cp.Length > 0)
{
// Single-use: the take removes the SDK slot. A cursor of another node / kind / epoch is refused AND released.
var state = store.TryTake(session, cp.ToArray());
if (state is not { Kind: HistoryCursorKind.Remote, Remote: { } cursor }
|| !HistoryContinuationMatches(state, key.Realm, key.Id, tag, epoch)
|| !cursor.TryClaimForResume())
{
state?.Remote?.Release();
SetProjectedStatus(handle, results, errors, StatusCodes.BadContinuationPointInvalid);
continue;
}
resume = cursor;
claimed = cursor;
}
if (access is null || identity is null || remote is null)
{
// No projection gateway, no session identity, or a variant a remote read never serves (a modified read).
resume?.ReleaseEvenIfClaimed();
SetProjectedStatus(handle, results, errors, StatusCodes.BadHistoryOperationUnsupported);
continue;
}
uint? aggregateId = null;
if (remote is DataHistoryProcessedDetails && resume is null)
{
// Consumer-side unknown aggregate: refused up front, unsent (the origin refuses what IT cannot serve).
var aggregate = aggregates[handle.Index];
if (AggregateFunctionMap.Map(aggregate) is null || aggregate.NamespaceIndex != 0 || !aggregate.TryGetValue(out uint numeric))
{
SetProjectedStatus(handle, results, errors, StatusCodes.BadAggregateNotSupported);
continue;
}
aggregateId = numeric;
}
pending.Add((handle, new ProjectedHistoryNode(handle.NodeId, aggregateId, resume)));
}
}
catch
{
// H3 review round 2: whatever throws while the batch is assembled, no claimed cursor leaks its origin continuation.
claimed?.ReleaseEvenIfClaimed();
foreach (var p in pending) p.Node.Resume?.ReleaseEvenIfClaimed();
throw;
}
if (pending.Count == 0) return;
var nodes = pending.Select(p => p.Node).ToArray();
IReadOnlyList<ProjectedHistoryOutcome>? outcomes = null;
void ReleaseResumes()
{
foreach (var node in nodes) node.Resume?.ReleaseEvenIfClaimed();
}
// H3 review D3: projected reads and remote peers TOGETHER hold at most N - max(1, N/4) of the N process-wide history batch
// slots (OriginHistoryPort.RemoteSlots; one shared semaphore), so neither a slow origin nor busy peers can starve local
// HistoryRead / HistoryUpdate. Exhausted => BadTooManyOperations for the projected half, unsent; the local half is unaffected.
var projectedSlots = GetNonLocalHistoryLimiter();
if (!projectedSlots.Wait(0))
{
ReleaseResumes();
foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations);
return;
}
try
{
// The same process-wide batch limiter as local reads: a remote read also holds an SDK request thread.
WithHistoryBatchLimiter(pending, () =>
{
TimeSpan remaining;
if (HistoryReadDeadline > TimeSpan.Zero)
{
remaining = HistoryReadDeadline - Stopwatch.GetElapsedTime(started);
if (remaining <= TimeSpan.Zero)
{
outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadTimeout.Code, [])).ToArray();
ReleaseResumes();
return;
}
}
else remaining = TimeSpan.Zero;
try
{
outcomes = access!.ReadAsync(identity!, remote!, nodes, remaining,
context.OperationContext?.CancellationToken ?? CancellationToken.None).GetAwaiter().GetResult();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Whatever escaped the gateway — the SDK request ending is a timeout, never an origin fault. The gateway
// normally owns the resumes; releasing them again is idempotent, so nothing claimed can leak (H3 review D2).
var status = ex is OperationCanceledException ? StatusCodes.BadTimeout.Code : StatusCodes.BadNoCommunication.Code;
outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(status, [])).ToArray();
ReleaseResumes();
}
}, p =>
{
p.Node.Resume?.ReleaseEvenIfClaimed();
SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations);
});
}
finally
{
projectedSlots.Release();
}
if (outcomes is null) return; // the limiter rejected the batch
if (outcomes.Count != pending.Count)
{
foreach (var o in outcomes) o.Continuation?.Release();
ReleaseResumes();
foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadInternalError);
return;
}
var done = 0; // outcomes [0, done) are fully handed over (a continuation saved to the store, or released)
ProjectedHistoryContinuation? handedOver = null; // outcome `done`'s continuation once the store owns it (or released it)
try
{
for (var i = 0; i < pending.Count; i++)
{
handedOver = null;
ServeProjectedOutcome(pending[i].Handle, outcomes[i]);
done = i + 1;
}
}
catch
{
// H3 review round 3 nit (d): a throw for outcome i (FromClr on an unconvertible value, a store fault) strands no
// origin cursor: outcome i's — unless the store already owns it — and every later outcome's are released.
for (var j = done; j < outcomes.Count; j++)
if (outcomes[j].Continuation is { } c && !ReferenceEquals(c, handedOver)) c.Release();
throw;
}
void ServeProjectedOutcome(NodeHandle handle, ProjectedHistoryOutcome outcome)
{
var status = new StatusCode(outcome.StatusCode);
if (StatusCode.IsBad(status))
{
outcome.Continuation?.Release();
SetProjectedStatus(handle, results, errors, status);
return;
}
byte[]? cp = null;
if (outcome.Continuation is { } next)
{
var key = MapKey(handle.NodeId);
cp = SaveRemoteContinuation(session, store, key.Realm, key.Id, HistoryBindingTag(handle.NodeId), epoch, next);
handedOver = next; // saved (store-owned) or already released by SaveRemoteContinuation
}
var values = new List<DataValue>(outcome.Samples.Count);
foreach (var sample in outcome.Samples)
values.Add(new DataValue(SdkValueBoundary.FromClr(sample.Value), new StatusCode(sample.StatusCode),
sample.SourceTimestampUtc ?? DateTime.MinValue, sample.ServerTimestampUtc ?? DateTime.MinValue));
errors[handle.Index] = ServiceResult.Good;
results[handle.Index] = new SdkHistoryReadResult
{
StatusCode = status,
HistoryData = new ExtensionObject(new HistoryData { DataValues = values }),
ContinuationPoint = cp is null ? default : ByteString.From(cp),
};
}
}
/// <summary>
/// Stores a remote cursor in the session store, bound to its node and the current epoch. When it cannot be stored (no
/// session, the epoch moved, the session refused it) the page is returned without a continuation point — as a local
/// read degrades — and the origin cursor is released.
/// </summary>
private byte[]? SaveRemoteContinuation(ISession? session, IHistoryContinuationStore store, AddressSpaceRealm realm, string identifier,
string tag, long epoch, ProjectedHistoryContinuation cursor)
{
if (epoch != Volatile.Read(ref _historyContinuationEpoch)) { cursor.Release(); return null; }
byte[]? cp;
try
{
cp = store.Save(session, new HistoryContinuationState(string.Empty, default, default, 0, 0, HistoryCursorKind.Remote,
BoundRealm: realm, BoundIdentifier: identifier, BoundTag: tag, AddressSpaceEpoch: epoch, Remote: cursor));
}
catch (ServiceResultException) { cp = null; } // the SDK disposed (released) it
if (cp is null) cursor.Release();
return cp;
}
/// <summary>
/// H3: the projected node's history advertisement — the HistoryRead access bit (CurrentRead | HistoryRead) and
/// <c>Historizing</c> when the definition says so, plain CurrentRead otherwise. Never HistoryWrite. Under <c>Lock</c>.
/// </summary>
private void ApplyProjectedHistorizing(BaseInstanceState node, bool historizing)
{
if (node is not BaseDataVariableState variable) return;
var access = historizing ? (byte)(AccessLevels.CurrentRead | AccessLevels.HistoryRead) : AccessLevels.CurrentRead;
if (variable.AccessLevel == access && variable.UserAccessLevel == access && variable.Historizing == historizing) return;
variable.AccessLevel = access;
variable.UserAccessLevel = access;
variable.Historizing = historizing;
variable.ClearChangeMasks(SystemContext, includeChildren: false);
}
private static void SetProjectedStatus(NodeHandle handle, IList<SdkHistoryReadResult> results, IList<ServiceResult> errors, StatusCode status)
{
errors[handle.Index] = new ServiceResult(status);
results[handle.Index] = new SdkHistoryReadResult { StatusCode = status };
}
/// <summary>
/// The SDK details as the SDK-free remote shape. An unset Part 11 bound travels ABSENT, never MinValue (plan §3.3). A
/// modified read is never served remotely (null).
/// </summary>
internal static DataHistoryDetails? ToRemoteDetails(HistoryReadDetails details) => details switch
{
ReadRawModifiedDetails { IsReadModified: true } => null,
ReadRawModifiedDetails raw => new DataHistoryRawDetails(Bound(raw.StartTime), Bound(raw.EndTime), raw.NumValuesPerNode, raw.ReturnBounds),
ReadProcessedDetails processed => new DataHistoryProcessedDetails(Bound(processed.StartTime), Bound(processed.EndTime),
TimeSpan.FromMilliseconds(processed.ProcessingInterval), processed.AggregateConfiguration is { } c
? new DataAggregateConfiguration(c.UseServerCapabilitiesDefaults, c.TreatUncertainAsBad, c.PercentDataBad, c.PercentDataGood,
c.UseSlopedExtrapolation)
: null),
ReadAtTimeDetails atTime => new DataHistoryAtTimeDetails(
(atTime.ReqTimes.ToArray() ?? []).Select(t => new DateTimeOffset(DateTime.SpecifyKind(t.ToDateTime(), DateTimeKind.Utc))).ToArray(),
atTime.UseSimpleBounds),
_ => null,
};
private static DateTimeOffset? Bound(DateTimeUtc value)
{
var clr = SdkValueBoundary.ToClrTimestamp(value);
return clr == DateTime.MinValue ? null : new DateTimeOffset(DateTime.SpecifyKind(clr, DateTimeKind.Utc));
}
}
@@ -185,6 +185,12 @@ public sealed class DataPlaneAuthorizer
// lease expires, so a periodic detach is not a final-send gate. Until P08 installs a verified publish-time
// gate, do not admit mapped data or event subscriptions at all.
if (operation == OpcUaOperation.CreateMonitoredItems) { veto = DeniedResult; return true; }
// H3: HistoryRead on a mapped node is opened DELIBERATELY — it needs the mapping's own HistoryRead bit (masked by the
// export's) AND a local NodePermissions.HistoryRead grant on the mapping scope, with ACLs on or off (plan §6). Every
// other mapped operation outside this allowlist (HistoryUpdate, alarm methods…) stays closed.
if (operation is not (OpcUaOperation.Browse or OpcUaOperation.Read or OpcUaOperation.WriteOperate or OpcUaOperation.WriteTune
or OpcUaOperation.WriteConfigure or OpcUaOperation.TransferSubscriptions or OpcUaOperation.HistoryRead))
{ veto = DeniedResult; return true; }
var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId,
identity.CredentialVersion, identity.CredentialExpiresUtc);
try
@@ -511,7 +511,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
}
/// <summary>A non-owning handle with the deployed operation and resource policy.</summary>
public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IDisposable
public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IHistoryBatchLimit, IDisposable
{
/// <summary>
/// H2 remote history through the deployed connection: needs the connection row's HistoryRead bit (masked to the
@@ -541,13 +541,25 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistor
catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException or OperationCanceledException
&& !cancellationToken.IsCancellationRequested)
{
// The scope moved while the answer was in flight: the answer is dropped, so the new origin continuations it carries are
// released (best effort) rather than stranded until the origin's idle expiry (H3 review round 3 nit c).
var orphans = value.Select(x => x.Continuation).OfType<byte[]>().ToArray();
foreach (var item in value) item.Dispose();
return Unavailable(request); // the scope moved while the answer was in flight
if (orphans.Length > 0) _ = ReleaseQuietlyAsync(history, orphans);
return Unavailable(request);
}
}
private static async Task ReleaseQuietlyAsync(IDataHistoryService history, byte[][] continuations)
{
try { await history.ReleaseAsync(continuations, CancellationToken.None).ConfigureAwait(false); }
catch (Exception ex) when (ex is not OutOfMemoryException) { } // best effort; the origin's idle expiry is the backstop
}
/// <summary>A resumed item's token cannot be presented again: <c>BadContinuationPointInvalid</c>; a fresh one <c>BadNoCommunication</c>.</summary>
private static DataHistoryReadResult[] Unavailable(DataHistoryReadRequest request) => request.Items
.Select(x => new DataHistoryReadResult(x.CorrelationId, GrpcDataConnection.BadNoCommunication, [], null)).ToArray();
.Select(x => new DataHistoryReadResult(x.CorrelationId,
x.Continuation is not null ? GrpcDataConnection.BadContinuationPointInvalid : GrpcDataConnection.BadNoCommunication, [], null)).ToArray();
Task<IReadOnlyList<DataHistoryReadResult>> IDataHistoryService.ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) =>
ReadHistoryAsync(request, cancellationToken);
@@ -583,6 +595,11 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistor
internal Func<bool> RouteCurrent => _routeCurrent;
/// <summary>The configured row's operations, already masked to the understood set.</summary>
internal DataOperations AllowedOperations => _allowed;
/// <summary>The connection row's batch size: a history request with more items is refused (H3 splits below it).</summary>
internal int MaxBatchItems => _batch;
/// <inheritdoc />
int IHistoryBatchLimit.MaxHistoryBatchItems => _batch;
public IDataConnection Connection => this;
public CancellationToken CancellationToken => _scope;
public DataTarget Target => _inner.Target;
@@ -23,6 +23,8 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
internal const uint BadTooManyOperations = 0x80100000u;
internal const uint BadTimeout = 0x800A0000u;
internal const uint BadNoCommunication = 0x80310000u;
/// <summary>An origin admits at most one item per this many bytes of a request's byte budget (<c>LocalDataServices.CheckBudget</c>).</summary>
internal const long MinimumBytesPerItem = 256;
private const byte EnvelopeTag = 0xC7, EnvelopeVersion = 1;
private TimeSpan _historyTimeout = TimeSpan.FromSeconds(30);
@@ -89,7 +91,13 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
Check();
cancellationToken.ThrowIfCancellationRequested();
Selected selected;
try { selected = await SelectAsync(_endpoints[index], start, request.Budget, false, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); }
// The capability probe is capped by HistoryTimeout too (H3 review), like every history call.
try { selected = await SelectAsync(_endpoints[index], start, ProbeBudget(request.Budget), false, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); }
catch (Exception ex) when (cancellationToken.IsCancellationRequested && ex is RpcException or OperationCanceledException)
{
// A caller cancel (a deadline) during the probe is a cancel, never an escaping RpcException (H3 review D1).
throw new OperationCanceledException("History read cancelled by the caller.", ex, cancellationToken);
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested
&& ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException or ArgumentException)
{ failure = ex; RecordFailure(ex); continue; }
@@ -108,7 +116,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
continue;
}
DataHistoryReadResult[]? served;
try { served = await ServeAsync(selected, index, request, items, pending, start, cancellationToken).ConfigureAwait(false); }
try { served = await ServeSplitAsync(selected, index, request, items, pending, start, cancellationToken).ConfigureAwait(false); }
catch (Exception ex) when (!cancellationToken.IsCancellationRequested
&& ex is InvalidOperationException or ArgumentException or RpcException or HttpRequestException)
{
@@ -126,8 +134,107 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
finally { if (admitted) _unaryCapacity.Release(); ExitWork(); }
}
/// <summary>Reads on one selected endpoint and assembles its chunks; null = the endpoint failed before answering (a fresh read may move).</summary>
private async Task<DataHistoryReadResult[]?> ServeAsync(Selected selected, int endpoint, DataHistoryReadRequest request,
/// <summary>
/// Reads on one selected endpoint in sub-batches of at most the endpoint's advertised <c>MaxBatchItems</c> — taken from the
/// capabilities this call already negotiated, so no extra probe (H3 review round 2). The assembly budget is shared across
/// the sub-batches, and each sub-batch carries at most one item per <see cref="MinimumBytesPerItem"/> of what is left
/// (the origin's admission rule, round 3 S2). Once the budget is spent — exhausted, too small for one more item, or a
/// sub-batch's own assembly refused (S3) — the remaining items are <c>BadTooManyOperations</c> marked
/// <see cref="DataHistoryReadResult.ConsumerBudgetRefused"/>, unsent. Null = the endpoint failed before answering the
/// FIRST sub-batch (a fresh read may move); a later failure is recorded, nothing more is sent to that endpoint, and the
/// rest is <c>BadNoCommunication</c> (resumed items <c>BadContinuationPointInvalid</c>), never moving a half-served
/// request. A resumed item answered unsent has its origin token released (it is still live there). Anything that
/// escapes (a caller cancel, a fault) first disposes the collected answers and releases their new continuations (S1).
/// </summary>
private async Task<DataHistoryReadResult[]?> ServeSplitAsync(Selected selected, int endpoint, DataHistoryReadRequest request,
DataHistoryReadItem[] items, int[] pending, long start, CancellationToken cancellationToken)
{
var batch = Math.Max(1, selected.Capabilities.Limits.MaxBatchItems);
if (pending.Length <= batch) return (await ServeAsync(selected, endpoint, request, items, pending, start, cancellationToken).ConfigureAwait(false)).Results;
var answers = new DataHistoryReadResult?[pending.Length];
long used = 0;
bool spent = false, failed = false;
try
{
for (var offset = 0; offset < pending.Length;)
{
var left = request.Budget.MaxBytes - used;
var fitting = spent || failed ? 0 : (int)Math.Min(batch, Math.Max(0, left) / MinimumBytesPerItem);
if (fitting <= 0)
{
for (var k = offset; k < pending.Length; k++)
{
var item = request.Items[pending[k]];
var resumed = item.Continuation is not null;
if (resumed) _ = ReleaseOnEndpointAsync(selected, items[pending[k]].Continuation); // unsent: still live at the origin
answers[k] = failed
? new(item.CorrelationId, resumed ? BadContinuationPointInvalid : BadNoCommunication, [], null)
: new(item.CorrelationId, BadTooManyOperations, [], null, "History assembly budget exceeded.") { ConsumerBudgetRefused = true };
}
break;
}
var chunk = pending.Skip(offset).Take(fitting).ToArray();
DataHistoryReadResult[]? served;
try
{
var call = await ServeAsync(selected, endpoint, request with { Budget = request.Budget with { MaxBytes = left } }, items, chunk, start,
cancellationToken).ConfigureAwait(false);
served = call.Results;
failed = call.EndpointFailed; // answered, but the endpoint failed or retired mid-way: send it nothing more (nit a)
}
catch (Exception ex) when (offset > 0 && !cancellationToken.IsCancellationRequested
&& ex is InvalidOperationException or ArgumentException or RpcException or HttpRequestException)
{
// An endpoint fault after a served sub-batch: recorded like any endpoint failure (round 3 S6), and the
// request stays on this endpoint (half served) with nothing more sent to it (nit a).
RecordFailure(ex);
served = null;
}
if (served is null)
{
if (offset == 0) return null;
failed = true;
continue;
}
for (var k = 0; k < chunk.Length; k++)
{
var answer = served[k];
foreach (var sample in answer.Samples) used += sample.Value.EstimatedRetainedBytes;
if (answer.ConsumerBudgetRefused) spent = true;
answers[offset + k] = answer;
}
offset += chunk.Length;
}
return answers.Select(x => x!).ToArray();
}
catch
{
Abandon(selected, answers);
throw;
}
}
/// <summary>Disposes answers that will never be handed out and releases the new origin continuations they carry.</summary>
private void Abandon(Selected selected, IEnumerable<DataHistoryReadResult?> answers)
{
foreach (var answer in answers)
{
if (answer is null) continue;
answer.Dispose();
if (answer.Continuation is { } wrapped && TryUnwrap(wrapped, out _, out _, out var token)) _ = ReleaseOnEndpointAsync(selected, token);
}
}
/// <summary>
/// Reads on one selected endpoint and assembles its chunks. Results null = the endpoint failed before answering (a fresh
/// read may move); <c>EndpointFailed</c> = it answered (per node) but failed or retired on the way, so a caller splitting a
/// request sends it nothing more. Anything that escapes first releases every origin token this assembly holds — finished
/// nodes' continuations, chunk tokens, and the tokens of a response it rejected (H3 review round 3 S6).
/// </summary>
private async Task<(DataHistoryReadResult[]? Results, bool EndpointFailed)> ServeAsync(Selected selected, int endpoint, DataHistoryReadRequest request,
DataHistoryReadItem[] items, int[] pending, long start, CancellationToken cancellationToken)
{
var batch = pending.Select(i => items[i]).ToArray();
@@ -138,6 +245,10 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
var current = batch;
var map = Enumerable.Range(0, batch.Length).ToArray();
var first = true;
var endpointFailed = false;
var chunkTokensReleased = false;
W.HistoryReadResponse? unprocessed = null; // a received response whose tokens are not yet owned by final[] / current
IReadOnlyList<DataHistoryReadResult>? decoded = null;
try
{
while (current.Length > 0)
@@ -162,6 +273,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
{
// A caller cancel is never an outcome: surface it as cancellation, and let go of held chunk tokens.
if (!first) ReleaseChunkTokens(selected, current);
chunkTokensReleased = true;
throw new OperationCanceledException("History read cancelled by the caller.", ex, cancellationToken);
}
catch (RpcException ex) when (ex.StatusCode is StatusCode.FailedPrecondition or StatusCode.Unimplemented)
@@ -170,6 +282,16 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadHistoryOperationUnsupported, [], null);
break;
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested && Retiring(selected)
&& ex is OperationCanceledException or RpcException { StatusCode: StatusCode.Cancelled })
{
// Not the caller and not a deadline: the channel retired, the scope moved or the connection is shutting down
// (a redeploy). Not a timeout and not an endpoint fault (round 3 S5): the read cannot continue here.
if (!first) ReleaseChunkTokens(selected, current);
foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, batch[k].Continuation is not null ? BadContinuationPointInvalid : BadNoCommunication, [], null);
endpointFailed = true;
break;
}
catch (RpcException ex) when (ex.StatusCode is StatusCode.DeadlineExceeded or StatusCode.Cancelled && !cancellationToken.IsCancellationRequested)
{
// The call's own deadline, or the origin cancelling it at ITS unary timeout (the effective ceiling is
@@ -180,23 +302,22 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
}
catch (RpcException ex) when (first && ex.StatusCode is StatusCode.Unavailable or StatusCode.Unauthenticated or StatusCode.PermissionDenied
&& !cancellationToken.IsCancellationRequested)
{ RecordFailure(ex); return null; }
{ RecordFailure(ex); chunkTokensReleased = true; return (null, true); }
catch (RpcException ex)
{
RecordFailure(ex);
if (!first) ReleaseChunkTokens(selected, current); // the origin still holds their remainders
foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadNoCommunication, [], null);
endpointFailed = true;
break;
}
first = false;
unprocessed = response;
Verify(response.Serving, selected);
var decoded = DataHistoryProtoMapper.DecodeResponse(response, Limits(request.Budget, selected.Capabilities) with
decoded = DataHistoryProtoMapper.DecodeResponse(response, Limits(request.Budget, selected.Capabilities) with
{ MaxValueElements = int.MaxValue, MaxBytes = _maxMessageBytes });
if (decoded.Count != current.Length || decoded.Where((r, k) => r.CorrelationId != current[k].CorrelationId).Any())
{
foreach (var r in decoded) r.Dispose();
throw new InvalidOperationException("History response has unexpected items.");
}
var nextItems = new List<DataHistoryReadItem>();
var nextMap = new List<int>();
for (var k = 0; k < decoded.Count; k++)
@@ -210,7 +331,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
{
// The per-request assembly budget is exhausted: this and every later node is BadTooManyOperations.
_ = ReleaseOnEndpointAsync(selected, result.Continuation);
final[target] = new(result.CorrelationId, BadTooManyOperations, [], null, "History assembly budget exceeded.");
final[target] = new(result.CorrelationId, BadTooManyOperations, [], null, "History assembly budget exceeded.") { ConsumerBudgetRefused = true };
continue;
}
if (result.ChunkContinues)
@@ -225,6 +346,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
}
current = nextItems.ToArray();
map = nextMap.ToArray();
unprocessed = null; decoded = null; // every token of this response is now in final[] or current
}
var answers = new DataHistoryReadResult[batch.Length];
for (var k = 0; k < batch.Length; k++)
@@ -239,15 +361,26 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
}
answers[k] = result with { Samples = (IReadOnlyList<DataHistorySample>?)assembled[k] ?? [] };
}
return answers;
return (answers, endpointFailed);
}
catch
{
foreach (var list in assembled) foreach (var sample in list ?? []) sample.Dispose();
foreach (var r in decoded ?? []) r.Dispose();
// Nothing this assembly holds is handed out: release every origin token it owns (round 3 S6).
foreach (var r in final)
if (r?.Continuation is { } wrapped && TryUnwrap(wrapped, out _, out _, out var token)) _ = ReleaseOnEndpointAsync(selected, token);
if (!first && !chunkTokensReleased) ReleaseChunkTokens(selected, current);
foreach (var item in unprocessed?.Items ?? [])
if (item.HasContinuation) _ = ReleaseOnEndpointAsync(selected, item.Continuation.ToByteArray());
throw;
}
}
/// <summary>The call was cancelled by the connection itself: its channel retired, its scope moved, or it is shutting down.</summary>
private bool Retiring(Selected selected) =>
selected.Channel.Retired.IsCancellationRequested || _scope.CancellationToken.IsCancellationRequested || _shutdown.IsCancellationRequested;
/// <summary>Releases continuations on their issuing endpoints (<see cref="IDataHistoryService.ReleaseAsync"/>); best effort.</summary>
public async Task ReleaseHistoryAsync(IReadOnlyList<byte[]> continuations, CancellationToken cancellationToken)
{
@@ -291,6 +424,9 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
catch (Exception ex) when (ex is RpcException or OperationCanceledException or InvalidOperationException) { }
}
/// <summary>The capability probe's budget: the caller's, capped by <see cref="HistoryTimeout"/>.</summary>
private DataBudget ProbeBudget(DataBudget budget) => budget.Timeout <= HistoryTimeout ? budget : budget with { Timeout = HistoryTimeout };
private static DataHistoryReadResult[] All(DataHistoryReadRequest request, uint status) =>
request.Items.Select(x => new DataHistoryReadResult(x.CorrelationId, status, [], null)).ToArray();
@@ -43,6 +43,9 @@ public sealed partial class LocalDataServices
/// <summary>Live history sessions (diagnostics/tests).</summary>
internal int HistorySessionCount => _historySessions.Count;
/// <summary>Open origin continuations (page cursors + chunk remainders) across every session (diagnostics/tests).</summary>
public int HistoryOpenContinuations => _historySessions.OpenContinuations;
/// <summary>Remainder bytes retained for a principal across its sessions (diagnostics/tests).</summary>
internal long HistoryRetainedBytes(string principal) => _historySessions.RetainedBytes(principal);
@@ -194,6 +194,17 @@ internal sealed class OriginHistorySessions(TimeProvider clock, int maxSessions
/// <summary>Live sessions (diagnostics/tests).</summary>
public int Count { get { lock (_gate) return _sessions.Count; } }
/// <summary>Open page cursors plus chunk remainders across every session (diagnostics/tests).</summary>
public int OpenContinuations
{
get
{
OriginHistorySession[] sessions;
lock (_gate) sessions = _sessions.Values.Select(x => x.Session).ToArray();
return sessions.Sum(x => x.Cursors.Count + x.ChunkCount);
}
}
/// <summary>Remainder bytes retained for <paramref name="principal"/> across its sessions.</summary>
public long RetainedBytes(string principal) { lock (_gate) return _retained.GetValueOrDefault(principal); }
@@ -130,7 +130,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
if (metadata.ValueKind == DataValueKind.Timestamp && value is DateTime timestamp) value = new DateTimeOffset(timestamp.ToUniversalTime());
return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(metadata.ValueKind, value);
}
private static object? DecodeValue(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue value, DataMetadata metadata)
internal static object? DecodeValue(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue value, DataMetadata metadata)
{
if (value.Kind == DataValueKind.Null) return null;
if (value.Kind != metadata.ValueKind) throw new ArgumentException("Value kind does not match metadata.");
@@ -154,13 +154,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand)
{
demand = null;
if (caller is null || operation is not (DataOperations.Browse or DataOperations.Read or DataOperations.Write or DataOperations.Subscribe)) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireInvalid); return false; }
if (caller is null || operation is not (DataOperations.Browse or DataOperations.Read or DataOperations.Write or DataOperations.Subscribe or DataOperations.HistoryRead)) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireInvalid); return false; }
try
{
if (!_nodes.TryResolve(nodeId, out var definition) || definition is null || !definition.AuthorityIsCurrent() ||
!_catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var proof) || proof is null ||
proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) ||
((operation is DataOperations.Read or DataOperations.Subscribe) && proof.MaximumSampleAge <= TimeSpan.Zero) ||
// H3: history only on a node projected Historizing (mapping bit AND origin HistoryInfo), whatever the caller holds.
(operation == DataOperations.HistoryRead && (!definition.Historizing || !ProjectedHistoryAccess.Advertises(proof))) ||
proof.Metadata.View.MappingId is not { } mapping || proof.Lease.Serving.ServingGeneration <= 0 ||
_connectionForMapping(mapping) is not { Length: > 0 } connectionId) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireDefinition); return false; }
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
@@ -213,12 +215,24 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
if (lease is Demand demand) await demand.Completion.ConfigureAwait(false);
}
public bool HasLiveDemand(DataRealm realm, string localIdentifier) { lock (_sync) return _demandCounts.ContainsKey((realm, localIdentifier)); }
/// <summary>H3: what a HistoryRead demand is bound to — its mapping, revision, deployed connection and the origin's metadata.</summary>
internal bool TryDescribeHistoryDemand(IProjectedDemandLease lease, out ProjectedHistoryTarget? target)
{
target = null;
if (lease is not Demand { RequestedOperation: DataOperations.HistoryRead } demand || !demand.IsValid) return false;
var binding = demand.CurrentBinding;
if (binding.Proof.Metadata.View.MappingId is not { } mapping) return false;
target = new ProjectedHistoryTarget(mapping, binding.Proof.Metadata.View.MappingRevision, binding.ConnectionId,
binding.Proof.OriginMetadata, binding.Proof.Lease.Serving, binding.Proof.Generation);
return true;
}
private static OpcUaOperation Operation(DataOperations operation) => operation switch
{
DataOperations.Browse => OpcUaOperation.Browse,
DataOperations.Read => OpcUaOperation.Read,
DataOperations.Write => OpcUaOperation.WriteOperate,
DataOperations.Subscribe => OpcUaOperation.CreateMonitoredItems,
DataOperations.HistoryRead => OpcUaOperation.HistoryRead,
_ => throw new ArgumentOutOfRangeException(nameof(operation))
};
private sealed class Demand(ProjectedDataAccess owner, NodeId nodeId, ProjectedVariableDefinition definition,
@@ -0,0 +1,554 @@
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>A connection's own history batch size (the deployed connection row's batch); a larger request is refused.</summary>
internal interface IHistoryBatchLimit
{
int MaxHistoryBatchItems { get; }
}
/// <summary>What a projected HistoryRead demand is bound to (H3).</summary>
/// <param name="MappingId">The mapping.</param>
/// <param name="MappingRevision">The deployed mapping revision.</param>
/// <param name="ConnectionId">The deployed connection the mapping reads through.</param>
/// <param name="OriginMetadata">The origin's metadata (origin view, value kind).</param>
/// <param name="Serving">The origin serving identity the projection was built under.</param>
/// <param name="ProjectionGeneration">The projection generation.</param>
internal sealed record ProjectedHistoryTarget(string MappingId, long MappingRevision, string ConnectionId, DataMetadata OriginMetadata,
ServingIdentity Serving, long ProjectionGeneration);
/// <summary>
/// H3 — consumer OPC UA projection of remote history (gRPC data history plan §2.1, §3.2, §3.3). For each projected node:
/// resolve + authorize + pin it through <see cref="ProjectedDataAccess"/> (a <see cref="DataOperations.HistoryRead"/>
/// demand: the mapping's HistoryRead bit and a local HistoryRead grant on the mapping scope, ACLs on or off), group the
/// batch per deployed connection and per details, and forward through <see cref="IDataHistoryService"/>.
/// <list type="bullet">
/// <item>A fresh read may move endpoint within its deadline (the connection decides); a RESUMED read never moves —
/// its origin token pins the issuing endpoint and serving incarnation, and its cursor re-checks the caller, the
/// mapping revision, the projection generation, the serving identity and the connection lease (route) before any
/// call. Any mismatch ⇒ <c>BadContinuationPointInvalid</c> and the origin token is released.</item>
/// <item>A resume resends the ORIGINAL details verbatim (the origin binds their hash); local SDK resumes ignore details,
/// so the consumer does too.</item>
/// <item>The per-request assembly budget (min <c>MaxHistoryAssemblyBytesPerRequest</c> of the batch's mappings) is shared
/// across the batch; once spent, the remaining nodes are <c>BadTooManyOperations</c>.</item>
/// <item>Deadline per call = min(the consumer's remaining <c>HistoryReadDeadline</c>, the connection's
/// <c>HistoryTimeoutMilliseconds</c>) ⇒ <c>BadTimeout</c>; a cancelled read is never an origin fault.</item>
/// <item>Releases (<c>releaseContinuationPoints</c>, session close, eviction) are coalesced per connection into one
/// best-effort <c>ReleaseHistoryAsync</c>; the origin's idle expiry is the backstop.</item>
/// </list>
/// </summary>
public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposable
{
internal const uint Good = 0, BadContinuationPointInvalid = 0x804A0000u, BadTooManyOperations = 0x80100000u, BadTimeout = 0x800A0000u,
BadNoCommunication = 0x80310000u, BadTypeMismatch = 0x80740000u, BadHistoryOperationUnsupported = 0x80720000u;
internal const long DefaultAssemblyBudget = 16L * 1024 * 1024;
private readonly ProjectedDataAccess _access;
private readonly IGrpcDataAdapterConnectionSource _connections;
private readonly Func<string, long?> _assemblyBudget;
private readonly TimeProvider _clock;
private readonly object _releaseGate = new();
private readonly Dictionary<string, List<byte[]>> _pendingReleases = new(StringComparer.OrdinalIgnoreCase);
private readonly CancellationTokenSource _stop = new();
private Task _releaseFlush = Task.CompletedTask;
private bool _flushScheduled;
private int _disposed;
/// <summary>Creates the gateway.</summary>
/// <param name="access">The projected data access that resolves, authorizes and pins projected nodes.</param>
/// <param name="connections">The deployed connection registry.</param>
/// <param name="assemblyBudget">A mapping's <c>MaxHistoryAssemblyBytesPerRequest</c>; null = not deployed.</param>
/// <param name="clock">The clock.</param>
public ProjectedHistoryAccess(ProjectedDataAccess access, IGrpcDataAdapterConnectionSource connections,
Func<string, long?> assemblyBudget, TimeProvider clock)
{
_access = access ?? throw new ArgumentNullException(nameof(access));
_connections = connections ?? throw new ArgumentNullException(nameof(connections));
_assemblyBudget = assemblyBudget ?? throw new ArgumentNullException(nameof(assemblyBudget));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
}
/// <summary>How long a release waits to coalesce with others for the same connection (a session close disposes one by one).</summary>
internal TimeSpan ReleaseCoalesce { get; init; } = TimeSpan.FromMilliseconds(25);
/// <summary>Releases queued and not yet sent (tests).</summary>
internal int PendingReleasesForTests { get { lock (_releaseGate) return _pendingReleases.Values.Sum(x => x.Count); } }
/// <summary>Release calls sent (tests): one per connection per coalesced flush.</summary>
internal int ReleaseCallsForTests => Volatile.Read(ref _releaseCalls);
private int _releaseCalls;
/// <summary>Waits for the queued releases to be sent (tests).</summary>
internal async Task FlushReleasesForTestsAsync()
{
Task flush;
lock (_releaseGate) flush = _releaseFlush;
await flush.ConfigureAwait(false);
lock (_releaseGate) flush = _releaseFlush;
await flush.ConfigureAwait(false);
}
/// <summary>
/// Whether a projected node is advertised as historizing: the mapping (masked by the export) grants HistoryRead AND the
/// origin's negotiated metadata (<c>HistoryInfo</c>, bit 32) says historizing.
/// </summary>
public static bool Advertises(ProjectedNodeProof proof) =>
proof is not null && (proof.Subject.AllowedOperations & DataOperations.HistoryRead) != 0
&& (proof.OriginMetadata.AllowedOperations & DataOperations.HistoryRead) != 0
&& proof.OriginMetadata.History is { Historizing: true } && proof.OriginMetadata.NodeKind is "Variable" or "Tag";
/// <inheritdoc />
public async Task<IReadOnlyList<ProjectedHistoryOutcome>> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details,
IReadOnlyList<ProjectedHistoryNode> nodes, TimeSpan deadline, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(caller); ArgumentNullException.ThrowIfNull(details); ArgumentNullException.ThrowIfNull(nodes);
var started = _clock.GetTimestamp();
var outcomes = new ProjectedHistoryOutcome?[nodes.Count];
var demands = new IProjectedDemandLease?[nodes.Count];
var targets = new ProjectedHistoryTarget?[nodes.Count];
var assembled = new long[nodes.Count];
var assemblyRefused = new bool[nodes.Count];
var callerKey = CallerKey(caller);
long budget = DefaultAssemblyBudget, received = 0;
var budgetExhausted = false;
try
{
// 1. Resolve, authorize and pin every node; check each resumed cursor against what it was issued under.
for (var i = 0; i < nodes.Count; i++)
{
var node = nodes[i];
var cursor = node.Resume as RemoteCursor;
if (node.Resume is not null && (cursor is null || !ReferenceEquals(cursor.Owner, this)))
{
node.Resume.ReleaseEvenIfClaimed();
outcomes[i] = Fail(BadContinuationPointInvalid);
continue;
}
if (!_access.TryAcquire(node.NodeId, caller, DataOperations.HistoryRead, out var demand) || demand is null
|| !_access.TryDescribeHistoryDemand(demand, out var target) || target is null)
{
demand?.Dispose();
cursor?.ReleaseOrigin();
// The node manager already authorized the node: a projection that cannot be pinned now is not servable.
outcomes[i] = Fail(cursor is null ? BadNoCommunication : BadContinuationPointInvalid);
continue;
}
demands[i] = demand;
targets[i] = target;
if (cursor is not null && !cursor.StillMatches(callerKey, target, demand))
{
// Mapping revision change, failover, projection rebuild, another caller: the cursor never resumes.
cursor.ReleaseOrigin();
outcomes[i] = Fail(BadContinuationPointInvalid);
}
}
// 2. The per-request assembly budget, shared across the batch: the tightest mapping's.
budget = long.MaxValue;
foreach (var target in targets)
if (target is not null) budget = Math.Min(budget, _assemblyBudget(target.MappingId) is { } b and > 0 ? b : DefaultAssemblyBudget);
if (budget == long.MaxValue) budget = DefaultAssemblyBudget;
// 3. Calls per (connection, details, resumed endpoint): a resumed item pins its issuing endpoint, so cursors of
// different endpoints, and fresh items (which may move), never share a call. Calls are RUNS of consecutive
// request positions with one key, read in request order (H3 review D7), so the assembly budget is consumed in
// request order and a budget shortfall only ever refuses nodes later in the request. Each run is sub-batched.
var runs = new List<(GroupKey Key, List<int> Indices)>();
for (var i = 0; i < nodes.Count; i++)
{
if (outcomes[i] is not null) continue;
var key = new GroupKey(targets[i]!.ConnectionId, DetailsOf(nodes[i], details), ResumeKey(nodes[i]));
if (runs.Count > 0 && runs[^1].Key == key) runs[^1].Indices.Add(i);
else runs.Add((key, [i]));
}
foreach (var (key, list) in runs)
{
var indices = list.ToArray();
if (cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero) { FailAll(indices, BadTimeout); continue; }
if (received >= budget || budgetExhausted) { FailAll(indices, BadTooManyOperations); continue; }
await ReadGroupAsync(key, indices, cancellationToken).ConfigureAwait(false);
}
// 4. Charge the assembly budget in REQUEST order (H3 review D7): the first node that does not fit, and every later
// node with data, is BadTooManyOperations; its next origin cursor is released.
var left = budget;
var exhausted = false;
for (var i = 0; i < nodes.Count; i++)
{
if (assemblyRefused[i]) { exhausted = true; continue; }
if (outcomes[i] is not { } outcome || assembled[i] == 0 && !exhausted) continue;
if (exhausted || assembled[i] > left)
{
exhausted = true;
(outcome.Continuation as RemoteCursor)?.ReleaseOrigin();
outcomes[i] = Fail(BadTooManyOperations);
continue;
}
left -= assembled[i];
}
return outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Last resort (H3 review D1): whatever escaped, fail per node — a timeout only when the caller or the deadline
// cancelled; any other cancel (a retired lease) is classified as FailCancelled does (round 3 S5) — and release every
// origin cursor this request still owns. Nothing escapes to the SDK override.
var timedOut = cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero;
for (var i = 0; i < nodes.Count; i++)
{
if (outcomes[i] is not null) continue;
var resumed = nodes[i].Resume is RemoteCursor;
nodes[i].Resume?.ReleaseEvenIfClaimed();
outcomes[i] = Fail(timedOut ? BadTimeout : ex is OperationCanceledException && resumed ? BadContinuationPointInvalid : BadNoCommunication);
}
return outcomes.Select(o => o!).ToArray();
}
finally
{
foreach (var demand in demands) demand?.Dispose();
}
TimeSpan Remaining() => deadline > TimeSpan.Zero
? deadline - _clock.GetElapsedTime(started)
: TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call
async Task ReadGroupAsync(GroupKey key, int[] indices, CancellationToken ct)
{
IGrpcDataAdapterConnectionLease? lease = null;
try
{
var remaining = Remaining();
using var timeout = new CancellationTokenSource(remaining, _clock);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeout.Token);
lease = await _connections.AcquireAsync(key.ConnectionId, linked.Token).ConfigureAwait(false);
if (lease is null || lease.Connection is not IDataHistoryService history || lease.CancellationToken.IsCancellationRequested)
{
foreach (var i in indices)
{
if (nodes[i].Resume is RemoteCursor c) { c.ReleaseOrigin(); outcomes[i] = Fail(BadContinuationPointInvalid); }
else outcomes[i] = Fail(BadNoCommunication);
}
return;
}
var route = lease.RouteIdentity;
var sendable = new List<int>(indices.Length);
foreach (var i in indices)
{
// The connection lease moved (expiry, redeployment, credential change): its tokens are gone.
if (nodes[i].Resume is RemoteCursor cursor && !Equals(cursor.RouteIdentity, route))
{
cursor.ReleaseOrigin();
outcomes[i] = Fail(BadContinuationPointInvalid);
continue;
}
sendable.Add(i);
}
if (sendable.Count == 0) return;
var batch = BatchSize(lease.Connection);
for (var offset = 0; offset < sendable.Count;)
{
var now = Remaining();
if (ct.IsCancellationRequested || now <= TimeSpan.Zero) { FailAll(sendable.Skip(offset).ToArray(), BadTimeout); return; }
// A budget shortfall refuses the remaining nodes unsent — never an endpoint failure (H3 review D4). A call may
// carry at most one item per MinimumBytesPerItem of its byte budget (the origin's admission rule).
var fitting = budgetExhausted ? 0 : (int)Math.Min(int.MaxValue, (budget - received) / MinimumBytesPerItem);
if (fitting <= 0) { FailAll(sendable.Skip(offset).ToArray(), BadTooManyOperations); return; }
var from = offset;
var chunk = sendable.Skip(from).Take(Math.Min(batch, fitting)).ToArray();
offset += chunk.Length;
var items = chunk.Select((i, k) => new DataHistoryReadItem(k.ToString(System.Globalization.CultureInfo.InvariantCulture),
targets[i]!.OriginMetadata.View,
nodes[i].Resume is RemoteCursor c ? c.AggregateId : nodes[i].AggregateId,
(nodes[i].Resume as RemoteCursor)?.Token)).ToArray();
IReadOnlyList<DataHistoryReadResult> answers;
try
{
answers = await history.ReadAsync(new DataHistoryReadRequest(key.Details, items,
new DataBudget(now, items.Length, budget - received)), linked.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Our deadline or the SDK request ending: a timeout, never an origin fault (the connection records none).
// Any other cancel (the deployed lease retired by a redeploy) is not a timeout.
FailCancelled(sendable.Skip(from).ToArray());
return;
}
var assigned = new bool[answers.Count];
try
{
if (answers.Count != items.Length)
{
FailAll(chunk, BadNoCommunication);
continue;
}
for (var k = 0; k < answers.Count; k++)
{
var i = chunk[k];
var answer = answers[k];
if (answer.CorrelationId != items[k].CorrelationId)
{
(nodes[i].Resume as RemoteCursor)?.ReleaseOrigin();
outcomes[i] = Fail(BadNoCommunication);
continue; // its token (if any) is released in the finally
}
if (answer.StatusCode == BadTooManyOperations && answer.ConsumerBudgetRefused)
{
// The connection's own share of the assembly budget ran out: no further origin call in this
// request (H3 review round 2). A typed marker, never the diagnostic text — an ORIGIN's refusal
// ("remainder budget is full") is a per-node answer, not a spent request (round 3, S4).
assemblyRefused[i] = true;
budgetExhausted = true;
}
long nodeBytes = 0;
foreach (var sample in answer.Samples) nodeBytes += sample.Value.EstimatedRetainedBytes;
assembled[i] = nodeBytes;
received += nodeBytes;
var target = targets[i]!;
var samples = Convert(answer.Samples, target.OriginMetadata, key.Details is DataHistoryProcessedDetails);
var next = answer.Continuation is { } token
? new RemoteCursor(this, target.OriginMetadata.View.Realm, demands[i]!.LocalIdentifier, token, key.ConnectionId, route,
target, callerKey, key.Details, nodes[i].Resume is RemoteCursor prior ? prior.AggregateId : nodes[i].AggregateId)
: null;
outcomes[i] = new ProjectedHistoryOutcome(answer.StatusCode, samples, next);
assigned[k] = true;
// Round 3 nit (b): a Bad answer to a resume may have left the prior origin cursor unconsumed (refused
// unsent, a failed call) — release it; idempotent, and a no-op at the origin when it was consumed.
if ((answer.StatusCode & 0x80000000u) != 0 && nodes[i].Resume is RemoteCursor resumedFrom) resumedFrom.ReleaseOrigin();
}
}
finally
{
// H3 review round 2: a new origin token whose answer never became an outcome (a mismatched answer, or an
// exception mid-answer) is released, never stranded at the origin until its idle expiry.
for (var k = 0; k < answers.Count; k++)
if (!assigned[k] && answers[k].Continuation is { } orphan) EnqueueRelease(key.ConnectionId, orphan);
foreach (var answer in answers) answer.Dispose();
}
}
}
catch (OperationCanceledException)
{
FailCancelled(indices.Where(i => outcomes[i] is null).ToArray());
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// An unexpected fault (an escaping RpcException, a malformed answer): per node, never out of the batch.
var timedOut = ct.IsCancellationRequested || Remaining() <= TimeSpan.Zero;
foreach (var i in indices.Where(i => outcomes[i] is null).ToArray())
{
if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin();
outcomes[i] = Fail(timedOut ? BadTimeout : nodes[i].Resume is null ? BadNoCommunication : BadContinuationPointInvalid);
}
}
finally
{
if (lease is not null) await lease.DisposeAsync().ConfigureAwait(false);
}
}
void FailCancelled(int[] indices)
{
if (cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero) { FailAll(indices, BadTimeout); return; }
foreach (var i in indices)
{
if (nodes[i].Resume is RemoteCursor c) { c.ReleaseOrigin(); outcomes[i] = Fail(BadContinuationPointInvalid); }
else outcomes[i] = Fail(BadNoCommunication);
}
}
void FailAll(int[] indices, uint status)
{
foreach (var i in indices)
{
if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin();
outcomes[i] = Fail(status);
}
}
}
/// <summary>
/// The sub-batch size of one call (H3 review D4): the deployed connection's own batch size. No separate capability probe
/// (H3 review round 2): a probe through the connection's unary path records a cancelled probe as an endpoint failure and
/// puts the connection into discovery backoff. The ORIGIN's advertised batch is applied by the gRPC connection itself,
/// from the capabilities each history call already negotiates.
/// </summary>
private static int BatchSize(IDataConnection connection) =>
Math.Max(1, connection is IHistoryBatchLimit limit ? limit.MaxHistoryBatchItems : DefaultBatchItems);
/// <summary>The sub-batch size when the connection is not a deployment lease (tests, direct facades).</summary>
internal const int DefaultBatchItems = 100;
/// <summary>An origin admits at most one item per this many bytes of a request's byte budget.</summary>
internal const long MinimumBytesPerItem = GrpcDataConnection.MinimumBytesPerItem;
private static ProjectedHistoryOutcome Fail(uint status) => new(status, []);
private static DataHistoryDetails DetailsOf(ProjectedHistoryNode node, DataHistoryDetails request) =>
node.Resume is RemoteCursor cursor ? cursor.Details : request;
private static string ResumeKey(ProjectedHistoryNode node)
{
if (node.Resume is not RemoteCursor cursor) return "fresh";
return GrpcDataConnection.TryUnwrap(cursor.Token, out var endpoint, out var serving, out _)
? FormattableString.Invariant($"{endpoint}|{serving}") : "resume";
}
private static string CallerKey(RoleCarryingUserIdentity caller) =>
string.Join('\0', caller.Principal ?? "", caller.ApiKeyId ?? "", caller.CredentialVersion ?? "");
/// <summary>
/// Values verbatim (status, absent timestamps). Raw and AtTime values are the node's own values: a kind that disagrees
/// with the catalog is <c>BadTypeMismatch</c> (plan §3.3), never coerced. A Processed value has its AGGREGATE's type (a
/// Double Average or an Int32 Count of a UInt16 node), so only its shape is checked: any scalar kind is accepted.
/// </summary>
private static OriginHistorySample[] Convert(IReadOnlyList<DataHistorySample> samples, DataMetadata metadata, bool processed)
{
var converted = new OriginHistorySample[samples.Count];
for (var i = 0; i < samples.Count; i++)
{
var sample = samples[i];
object? value;
var status = sample.StatusCode;
try
{
var expected = processed && sample.Value.Kind is not (DataValueKind.Null or DataValueKind.Array)
? metadata with { ValueKind = sample.Value.Kind, ValueRank = -1, Dimensions = [], ArrayElementKind = null }
: metadata;
value = ProjectedDataAccess.DecodeValue(sample.Value, expected);
}
catch (Exception ex) when (ex is ArgumentException or InvalidCastException or InvalidOperationException)
{
value = null;
status = BadTypeMismatch;
}
converted[i] = new OriginHistorySample(value, status, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime);
}
return converted;
}
/// <summary>Queues a release directly (tests: the flush's wake-up under concurrent enqueues).</summary>
internal void EnqueueReleaseForTests(string connectionId, byte[] token) => EnqueueRelease(connectionId, token);
/// <summary>Queues an origin token for a coalesced best-effort release on its connection.</summary>
private void EnqueueRelease(string connectionId, byte[] token)
{
if (Volatile.Read(ref _disposed) != 0) return;
lock (_releaseGate)
{
if (!_pendingReleases.TryGetValue(connectionId, out var list)) _pendingReleases[connectionId] = list = [];
list.Add(token);
// H3 review D6: a flag under the gate, not Task.IsCompleted — a flush past its last check but not yet completed
// would otherwise swallow this token (a lost wakeup). The flush clears the flag under the same gate.
if (_flushScheduled) return;
_flushScheduled = true;
_releaseFlush = Task.Run(FlushReleasesAsync);
}
}
private async Task FlushReleasesAsync()
{
try { await Task.Delay(ReleaseCoalesce, _clock, _stop.Token).ConfigureAwait(false); }
catch (OperationCanceledException) { lock (_releaseGate) _flushScheduled = false; return; }
Dictionary<string, List<byte[]>> batch;
lock (_releaseGate)
{
batch = new(_pendingReleases, StringComparer.OrdinalIgnoreCase);
_pendingReleases.Clear();
}
foreach (var (connectionId, tokens) in batch)
{
IGrpcDataAdapterConnectionLease? lease = null;
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, _stop.Token);
lease = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false);
if (lease?.Connection is not IDataHistoryService history) continue;
Interlocked.Increment(ref _releaseCalls);
await history.ReleaseAsync(tokens, linked.Token).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException) { } // best effort; the origin's idle expiry is the backstop
finally
{
if (lease is not null) try { await lease.DisposeAsync().ConfigureAwait(false); } catch (Exception) { }
}
}
lock (_releaseGate)
{
if (_pendingReleases.Count > 0 && Volatile.Read(ref _disposed) == 0) _releaseFlush = Task.Run(FlushReleasesAsync);
else _flushScheduled = false;
}
}
/// <inheritdoc />
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
// Cancel only: a flush still running reads _stop.Token, so it is never disposed under it (H3 review D6). The source
// has no timer, so leaving it to the GC releases nothing.
_stop.Cancel();
}
/// <summary>
/// Whether a cursor issued under <paramref name="issued"/> for <paramref name="issuedCaller"/> may resume now: same caller
/// (principal, key, credential version), mapping and revision, deployed connection, projection generation, origin view
/// and serving identity (node, incarnation, serving generation, role — a failover or restart changes it).
/// </summary>
internal static bool CursorMatches(ProjectedHistoryTarget issued, string issuedCaller, ProjectedHistoryTarget now, string caller) =>
string.Equals(caller, issuedCaller, StringComparison.Ordinal)
&& string.Equals(now.MappingId, issued.MappingId, StringComparison.Ordinal) && now.MappingRevision == issued.MappingRevision
&& string.Equals(now.ConnectionId, issued.ConnectionId, StringComparison.OrdinalIgnoreCase)
&& now.ProjectionGeneration == issued.ProjectionGeneration && now.OriginMetadata.View == issued.OriginMetadata.View
&& string.Equals(now.Serving.NodeId, issued.Serving.NodeId, StringComparison.Ordinal)
&& string.Equals(now.Serving.Incarnation, issued.Serving.Incarnation, StringComparison.Ordinal)
&& now.Serving.ServingGeneration == issued.Serving.ServingGeneration
&& string.Equals(now.Serving.Role, issued.Serving.Role, StringComparison.Ordinal);
private sealed record GroupKey(string ConnectionId, DataHistoryDetails Details, string Resume);
/// <summary>The remote cursor in the consumer's SDK session store (<see cref="HistoryCursorKind"/> <c>Remote</c>).</summary>
private sealed class RemoteCursor(ProjectedHistoryAccess owner, DataRealm realm, string localIdentifier, byte[] token, string connectionId,
object? routeIdentity, ProjectedHistoryTarget target, string callerKey, DataHistoryDetails details, uint? aggregateId)
: ProjectedHistoryContinuation(realm, localIdentifier)
{
private int _originReleased;
internal ProjectedHistoryAccess Owner => owner;
internal byte[] Token => token;
internal object? RouteIdentity => routeIdentity;
internal DataHistoryDetails Details => details;
internal uint? AggregateId => aggregateId;
/// <summary>The caller, mapping revision, projection generation, serving identity and connection still match.</summary>
internal bool StillMatches(string caller, ProjectedHistoryTarget now, IProjectedDemandLease demand) =>
demand.Realm == Realm && string.Equals(demand.LocalIdentifier, LocalIdentifier, StringComparison.Ordinal)
&& CursorMatches(target, callerKey, now, caller);
/// <summary>Releases the origin token (once), whether the cursor was claimed for a resume or not.</summary>
internal void ReleaseOrigin()
{
if (Interlocked.Exchange(ref _originReleased, 1) == 0) owner.EnqueueRelease(connectionId, token);
}
protected override void OnRelease() => ReleaseOrigin();
}
}
@@ -122,6 +122,19 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable
}
}
/// <summary>H3: the mapping's per-request history assembly budget, while its activated authority is current.</summary>
public bool TryGetHistoryAssemblyBudget(string mappingId, out long bytes)
{
bytes = 0;
if (!TryGetConnectionId(mappingId, out _)) return false;
lock (_gate)
{
if (!_byMapping.TryGetValue(mappingId, out var placement)) return false;
bytes = placement.Mapping.MaxHistoryAssemblyBytesPerRequest;
return bytes > 0;
}
}
public void Stage(CatalogAttempt attempt, IReadOnlyList<RemoteNamespaceMapping> mappings, IReadOnlyList<DataConnection> connections)
{
ArgumentNullException.ThrowIfNull(attempt);
@@ -95,7 +95,8 @@ public sealed class ProjectedNamespaceApplier : IDisposable
if (!PageCurrent() || guards.Any(guard => !guard.IsCurrent()) || root is not null && !root.IsCurrent())
return ProjectionPageStatus.Unavailable;
var definitions = guards.Select(guard => new ProjectedVariableDefinition(guard.Proof.Metadata.View.Realm,
guard.Proof.LocalIdentifier, exactParent, guard.Proof.Metadata, guard.Proof.Generation, guard.IsCurrent)).ToArray();
guard.Proof.LocalIdentifier, exactParent, guard.Proof.Metadata, guard.Proof.Generation, guard.IsCurrent)
{ Historizing = ProjectedHistoryAccess.Advertises(guard.Proof) }).ToArray();
var rootLeaf = root is not null && ProjectedCatalogCache.IsValueNode(root.Proof.Metadata);
if (rootLeaf && (definitions.Length != 0 || !page.Complete)) return ProjectionPageStatus.Unavailable;
var attempted = 0;
@@ -112,7 +113,8 @@ public sealed class ProjectedNamespaceApplier : IDisposable
{
accepted = rootLeaf
? _sink.TryApplyRootLeaf(exactParent, new ProjectedVariableDefinition(root!.Proof.Metadata.View.Realm,
root.Proof.LocalIdentifier, exactParent, root.Proof.Metadata, root.Proof.Generation, root.IsCurrent), Commit)
root.Proof.LocalIdentifier, exactParent, root.Proof.Metadata, root.Proof.Generation, root.IsCurrent)
{ Historizing = ProjectedHistoryAccess.Advertises(root.Proof) }, Commit)
: _sink.TryApply(exactParent, definitions, Commit);
return accepted && committed && PageCurrent() ? ProjectionPageStatus.Ready : ProjectionPageStatus.Unavailable;
}
@@ -380,7 +380,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, OpcUaOperation.CreateMonitoredItems,
mapped.View, serving, subject, resolver, lease)) return false;
var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent,
mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime };
mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime, Historizing = ProjectedHistoryAccess.Advertises(renewed) };
return sink.TryRenewExact(nodeId, definition, newDefinition, () =>
{
var duration = Clock.GetElapsedTime(started, Clock.GetTimestamp());
@@ -108,6 +108,21 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService
/// </summary>
public Dictionary<string, IReadOnlyList<BrowseResult>> BrowseResultsByParent { get; } = new();
/// <summary>Pages HistoryReadPageAsync answers, in order (a release call consumes nothing).</summary>
public Queue<HistoryPage> HistoryPages { get; } = new();
/// <summary>Every HistoryReadPageAsync call: details, the continuation point passed, and the release flag.</summary>
public List<(HistoryReadDetails Details, byte[]? ContinuationPoint, bool Release)> HistoryPageCalls { get; } = [];
/// <inheritdoc />
public Task<HistoryPage> HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint = null,
bool release = false, CancellationToken ct = default)
{
HistoryPageCalls.Add((details, continuationPoint, release));
if (release) return Task.FromResult(new HistoryPage(StatusCodes.Good, [], null));
return Task.FromResult(HistoryPages.Count > 0 ? HistoryPages.Dequeue() : new HistoryPage(StatusCodes.GoodNoData, [], null));
}
/// <summary>Gets or sets an exception thrown by HistoryReadRawAsync (simulates a refused read).</summary>
public Exception? HistoryReadException { get; set; }
@@ -0,0 +1,129 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
using ZB.MOM.WW.OtOpcUa.Client.CLI.Tests.Fakes;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Tests;
/// <summary>
/// The hand-paged (<c>--page-size</c> + pause / abandon / release / fresh-after-failure) and AtTime (<c>--at-time</c>)
/// modes of <c>historyread</c> the gRPC data H3 live gate drives against projected nodes.
/// </summary>
public class HistoryReadPagedCommandTests
{
private static readonly DateTime T0 = new(2026, 11, 20, 10, 0, 0, DateTimeKind.Utc);
private static DataValue Value(int v, int second) => new(new Variant(v), StatusCodes.Good, T0.AddSeconds(second), T0.AddSeconds(second));
[Fact]
public async Task Pages_print_each_status_and_resume_with_the_returned_continuation_point()
{
var fake = new FakeOpcUaClientService();
fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(1, 0), Value(2, 1)], [1, 2, 3]));
fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(3, 2)], null));
using var console = TestConsoleHelper.CreateConsole();
var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(fake))
{
Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", StartTime = "2026-11-20T09:00:00Z", EndTime = "2026-11-20T11:00:00Z", PageSize = 2,
};
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Page 1: Good [0x00000000] values=2 continuation=yes");
output.ShouldContain("Page 2: Good [0x00000000] values=1 continuation=no resumed");
output.ShouldContain("3 values returned.");
fake.HistoryPageCalls.Count.ShouldBe(2);
fake.HistoryPageCalls[0].ContinuationPoint.ShouldBeNull();
fake.HistoryPageCalls[1].ContinuationPoint.ShouldBe(new byte[] { 1, 2, 3 });
((ReadRawModifiedDetails)fake.HistoryPageCalls[0].Details).NumValuesPerNode.ShouldBe(2u);
}
[Fact]
public async Task A_refused_resume_is_printed_and_followed_by_one_fresh_read()
{
var fake = new FakeOpcUaClientService();
fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(1, 0)], [9]));
fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.BadContinuationPointInvalid, [], null));
fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(1, 0)], [7]));
var marker = Path.Combine(Path.GetTempPath(), "cli-resume-" + Guid.NewGuid().ToString("N"));
File.WriteAllText(marker, "");
try
{
using var console = TestConsoleHelper.CreateConsole();
var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(fake))
{
Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", PageSize = 1, PauseAfterPage = 1, ResumeWhenFile = marker,
FreshAfterFailure = true,
};
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Paused after page 1");
output.ShouldContain("Page 2: BadContinuationPointInvalid [0x804A0000] values=0 continuation=no resumed");
output.ShouldContain("Fresh: Good [0x00000000] values=1 continuation=yes");
fake.HistoryPageCalls.Last().Release.ShouldBeTrue("the fresh read's own continuation is released");
}
finally { File.Delete(marker); }
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Abandon_leaves_the_point_to_the_session_close_and_release_sends_releaseContinuationPoints(bool release)
{
var fake = new FakeOpcUaClientService();
fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(1, 0)], [5]));
var held = Path.Combine(Path.GetTempPath(), "cli-held-" + Guid.NewGuid().ToString("N"));
using var console = TestConsoleHelper.CreateConsole();
var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(fake))
{
Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", PageSize = 1,
AbandonAfterPage = release ? 0 : 1, ReleaseAfterPage = release ? 1 : 0, HeldMarkerFile = held,
};
await command.ExecuteAsync(console);
File.Exists(held).ShouldBeTrue("the held marker is written at the abandon / release point");
File.Delete(held);
var output = TestConsoleHelper.GetOutput(console);
if (release)
{
output.ShouldContain("Released after page 1: Good");
fake.HistoryPageCalls.Count.ShouldBe(2);
fake.HistoryPageCalls[1].Release.ShouldBeTrue();
fake.HistoryPageCalls[1].ContinuationPoint.ShouldBe(new byte[] { 5 });
}
else
{
output.ShouldContain("Abandoned after page 1");
fake.HistoryPageCalls.Count.ShouldBe(1);
}
}
[Fact]
public async Task AtTime_reads_the_requested_times_and_prints_the_status_and_value_types()
{
var fake = new FakeOpcUaClientService();
fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [new DataValue(new Variant((ushort)7), StatusCodes.Good, T0, T0)], null));
using var console = TestConsoleHelper.CreateConsole();
var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(fake))
{
Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", AtTimes = "2026-11-20T10:00:00Z, 2026-11-20T10:00:01Z",
};
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Status: Good [0x00000000]");
output.ShouldContain("Type: UInt16");
var details = fake.HistoryPageCalls.Single().Details.ShouldBeOfType<ReadAtTimeDetails>();
details.ReqTimes.Count.ShouldBe(2);
}
[Fact]
public async Task Pause_without_a_resume_file_is_refused()
{
var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(new FakeOpcUaClientService()))
{
Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", PageSize = 1, PauseAfterPage = 1,
};
using var console = TestConsoleHelper.CreateConsole();
await Should.ThrowAsync<CliFx.Exceptions.CommandException>(async () => await command.ExecuteAsync(console));
}
}
@@ -188,6 +188,17 @@ internal sealed class FakeSessionAdapter : ISessionAdapter
return Task.FromResult<IReadOnlyList<DataValue>>(HistoryReadRawResponse);
}
/// <summary>Every HistoryReadPageAsync call (details, continuation point, release flag).</summary>
public List<(HistoryReadDetails Details, byte[]? ContinuationPoint, bool Release)> HistoryPageCalls { get; } = [];
/// <inheritdoc />
public Task<ZB.MOM.WW.OtOpcUa.Client.Shared.Models.HistoryPage> HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId,
byte[]? continuationPoint, bool release, CancellationToken ct = default)
{
HistoryPageCalls.Add((details, continuationPoint, release));
return Task.FromResult(new ZB.MOM.WW.OtOpcUa.Client.Shared.Models.HistoryPage(StatusCodes.GoodNoData, [], null));
}
/// <inheritdoc />
public Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(
NodeId nodeId, DateTime startTime, DateTime endTime, NodeId aggregateId, double intervalMs,
@@ -350,6 +350,11 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService
return Task.FromResult(HistoryRawResult);
}
/// <inheritdoc />
public Task<HistoryPage> HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint = null,
bool release = false, CancellationToken ct = default) =>
Task.FromResult(new HistoryPage(StatusCodes.GoodNoData, [], null));
/// <inheritdoc />
public Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime,
AggregateType aggregate, double intervalMs = 3600000, CancellationToken ct = default)
@@ -0,0 +1,272 @@
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
using SdkDataValue = Opc.Ua.DataValue;
using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.ServerEventRig;
using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.WarmRedundancyWireTests;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
/// <summary>
/// H3 end to end over the wire: a real consumer OPC UA session HistoryReads a projected variable on a real consumer SDK
/// server, whose projected half is forwarded to a real in-process ORIGIN node manager through its real history port
/// (<see cref="OriginHistoryPort"/>, <c>PeerHistoryContinuationStore</c>). Proves the Remote cursor in the real SDK
/// session store (resume, single use, session close ⇒ the origin store count returns to 0), the mapped HistoryRead gate
/// with ACLs on and off, and that a mixed local + projected batch keeps every slot.
/// </summary>
[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "H3")]
public sealed class GrpcDataProjectedHistoryWireTests
{
private static readonly DateTime T0 = new(2026, 11, 20, 10, 0, 0, DateTimeKind.Utc);
[Theory(Timeout = 90000)]
[InlineData(false)]
[InlineData(true)]
public async Task Projected_history_pages_through_the_origin_and_a_mixed_batch_keeps_its_slots(bool aclEnabled)
{
var ct = Deadline();
await using var origin = await StartModeAsync("H3Origin", "None", ct);
origin.Nm.HistorianDataSource = new Series(7, offset: 100);
origin.Nm.EnsureVariable("Plant/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed");
await using var consumer = await StartModeAsync("H3Consumer", "None", ct);
consumer.Nm.HistorianDataSource = new Series(3, offset: 0);
var mapped = Setup(consumer, aclEnabled, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
var bridge = new OriginBridge(origin.Nm, mapped.Identifier, "Plant/Speed");
consumer.Nm.ProjectedHistoryAccess = bridge;
consumer.Nm.EnsureVariable("Plant/Local", "Plant", "Local", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "local");
var local = consumer.Nm.TryGetVariable("Plant/Local", AddressSpaceRealm.Raw)!.NodeId;
using var session = await consumer.ConnectAsync(anonymous: true, ct);
var client = (SessionClient)session;
// A mixed batch [projected, local]: each slot holds its own source's answer.
var mixed = await Raw(client, [mapped.Node, local], 3, [default, default], ct);
IntValues(mixed[0]).ShouldBe([100, 101, 102]);
IntValues(mixed[1]).ShouldBe([0, 1, 2]);
mixed[0].ContinuationPoint.IsEmpty.ShouldBeFalse();
bridge.Cursors.Count.ShouldBe(1);
// Resume the projected node to completion through the real SDK session store.
var all = IntValues(mixed[0]).ToList();
var cp = mixed[0].ContinuationPoint;
while (!cp.IsEmpty)
{
var page = (await Raw(client, [mapped.Node], 3, [cp], ct))[0];
StatusCode.IsGood(page.StatusCode).ShouldBeTrue();
all.AddRange(IntValues(page));
cp = page.ContinuationPoint;
}
all.ShouldBe([100, 101, 102, 103, 104, 105, 106]);
bridge.Cursors.Count.ShouldBe(0);
// Single use: the first page's point is gone.
(await Raw(client, [mapped.Node], 3, [mixed[0].ContinuationPoint], ct))[0].StatusCode.Code
.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
}
[Fact(Timeout = 90000)]
public async Task Closing_the_consumer_session_releases_the_origin_continuations()
{
var ct = Deadline();
await using var origin = await StartModeAsync("H3OriginClose", "None", ct);
origin.Nm.HistorianDataSource = new Series(7, offset: 0);
origin.Nm.EnsureVariable("Plant/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed");
await using var consumer = await StartModeAsync("H3ConsumerClose", "None", ct);
var mapped = Setup(consumer, aclEnabled: true, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
var bridge = new OriginBridge(origin.Nm, mapped.Identifier, "Plant/Speed");
consumer.Nm.ProjectedHistoryAccess = bridge;
var session = await consumer.ConnectAsync(anonymous: true, ct);
var page = (await Raw((SessionClient)session, [mapped.Node], 2, [default], ct))[0];
page.ContinuationPoint.IsEmpty.ShouldBeFalse();
bridge.Cursors.Count.ShouldBe(1, "the origin holds the page cursor");
await session.CloseAsync(ct);
session.Dispose();
for (var i = 0; i < 200 && bridge.Cursors.Count != 0; i++) await Task.Delay(10, ct);
bridge.Cursors.Count.ShouldBe(0, "the SDK disposed the Remote point on session close and the release reached the origin");
bridge.Releases.ShouldBe(1);
}
[Theory(Timeout = 90000)]
[InlineData(false)]
[InlineData(true)]
public async Task Without_a_local_HistoryRead_grant_on_the_mapping_scope_it_is_BadUserAccessDenied_unsent(bool aclEnabled)
{
var ct = Deadline();
await using var origin = await StartModeAsync("H3OriginDeny", "None", ct);
origin.Nm.HistorianDataSource = new Series(7, offset: 0);
origin.Nm.EnsureVariable("Plant/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed");
await using var consumer = await StartModeAsync("H3ConsumerDeny", "None", ct);
var mapped = Setup(consumer, aclEnabled, NodePermissions.Browse | NodePermissions.Read);
var bridge = new OriginBridge(origin.Nm, mapped.Identifier, "Plant/Speed");
consumer.Nm.ProjectedHistoryAccess = bridge;
using var session = await consumer.ConnectAsync(anonymous: true, ct);
var result = (await Raw((SessionClient)session, [mapped.Node], 2, [default], ct))[0];
result.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
bridge.Calls.ShouldBe(0);
}
[Fact(Timeout = 90000)]
public async Task The_shared_client_aggregate_read_asks_for_server_defaults_and_is_served()
{
// Found by the H3 live gate (H02): Client.Shared sent the SDK's default AggregateConfiguration (all false / 0), a
// NON-default configuration this server refuses BadAggregateConfigurationRejected (#677) — on local and projected
// nodes alike, so the CLI's --aggregate never worked against it.
var ct = Deadline();
await using var rig = await StartModeAsync("H3ClientAggregate", "None", ct);
rig.Nm.HistorianDataSource = new Series(3, offset: 0);
rig.Nm.EnsureVariable("Plant/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed");
rig.Enforce(false, [Key()]);
using var client = new ZB.MOM.WW.OtOpcUa.Client.Shared.OpcUaClientService();
await client.ConnectAsync(new ZB.MOM.WW.OtOpcUa.Client.Shared.Models.ConnectionSettings
{
EndpointUrl = rig.EndpointUrl,
CertificateStorePath = Path.Combine(Path.GetTempPath(), $"otopcua-clientpki-{Guid.NewGuid():N}"),
}, ct);
var node = rig.Nm.TryGetVariable("Plant/Speed", AddressSpaceRealm.Raw)!.NodeId;
var values = await client.HistoryReadAggregateAsync(node, T0, T0.AddMinutes(1),
ZB.MOM.WW.OtOpcUa.Client.Shared.Models.AggregateType.Average, 60_000, ct);
values.Count.ShouldBe(1);
// The hand-paging API returns the server's page verbatim (status, values, continuation).
var page = await client.HistoryReadPageAsync(new ReadRawModifiedDetails
{
StartTime = T0.AddSeconds(-1), EndTime = T0.AddHours(1), NumValuesPerNode = 2, IsReadModified = false, ReturnBounds = false,
}, node, null, false, ct);
StatusCode.IsGood(page.Status).ShouldBeTrue();
page.Values.Count.ShouldBe(2);
page.ContinuationPoint.ShouldNotBeNull();
var released = await client.HistoryReadPageAsync(new ReadRawModifiedDetails { IsReadModified = false, ReturnBounds = false },
node, page.ContinuationPoint, true, ct);
StatusCode.IsGood(released.Status).ShouldBeTrue();
await client.DisconnectAsync(ct);
}
// ------------------------------------------------------------------------------------------------------------------
private static (NodeId Node, string Identifier) Setup(ServerEventRig consumer, bool aclEnabled, NodePermissions permissions)
{
consumer.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = consumer.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var scopePaths = new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>
{
[new(NodeAclScopeKind.RawFolder, "plant")] = [new([NodeAclRealms.Raw, "Plant"])],
};
var grant = new NodeAcl { NodeAclId = "h3", ClusterId = ServerEventRig.Cluster, Principal = OpcUaPrincipals.Anonymous,
ScopeKind = NodeAclScopeKind.RawFolder, ScopeId = "plant", PermissionFlags = permissions };
var state = consumer.Enforce(aclEnabled, [Key()], scopePaths, grant);
var origin = new DataAddress("origin", "urn:raw", "string", "Plant/Speed");
var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Speed");
var metadata = new DataMetadata(view, "Speed", "Tag", DataValueKind.Int32, -1, [], false,
DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead, 1, null, null, false, History: new DataHistoryInfo(true));
var identifier = ProjectedDataIds.Identifier("mapping", origin);
consumer.Nm.TryEnsureProjectedVariable(new ProjectedVariableDefinition(DataRealm.Raw, identifier, parent, metadata, 1, () => true)
{ Historizing = true }, out var node).ShouldBeTrue();
var lease = new Lease();
var subject = new MappedNamespaceSubject(view, new NodeScope { ClusterId = ServerEventRig.Cluster, Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Speed"] },
["plant", "mapping"], lease.Serving, DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead, WriteThrough: false);
var resolver = new MappedSubjectResolver([subject], catalogEpoch: 7, new Catalog(state));
consumer.Nm.MappedSubjectResolver = (realm, id) => realm == AddressSpaceRealm.Raw && id == identifier
? MappedNodeResolution.Mapped(view, subject, resolver, lease) : MappedNodeResolution.Local;
return (node!.Value, identifier);
}
private static async Task<Opc.Ua.HistoryReadResult[]> Raw(SessionClient client, NodeId[] nodes, uint count, ByteString[] cps, CancellationToken ct)
{
var details = new ReadRawModifiedDetails
{
StartTime = T0.AddSeconds(-1), EndTime = T0.AddHours(1), NumValuesPerNode = count, IsReadModified = false, ReturnBounds = false,
};
var response = await client.HistoryReadAsync(H(), new ExtensionObject(details), TimestampsToReturn.Both, false,
nodes.Select((n, i) => new HistoryReadValueId { NodeId = n, ContinuationPoint = cps[i] }).ToArray(), ct);
return response.Results.ToArray()!;
}
private static int[] IntValues(Opc.Ua.HistoryReadResult result) =>
(result.HistoryData.IsNull || ExtensionObject.ToEncodeable(result.HistoryData) is not HistoryData data ? [] : data.DataValues.ToArray() ?? [])
.Select(v => (int)SdkValueBoundary.ToClr(v.WrappedValue)!).ToArray();
/// <summary>
/// The consumer's projected half wired straight onto a real origin's history port: one peer cursor store, as one
/// authenticated principal on one connection; a release drops the origin token.
/// </summary>
private sealed class OriginBridge(OtOpcUaNodeManager origin, string projectedIdentifier, string originIdentifier) : IProjectedHistoryAccess
{
private readonly OriginHistoryPort _port = new(origin);
private int _calls, _releases;
public OriginHistoryCursors Cursors { get; } = new("peer", "channel-1", 16);
public int Calls => Volatile.Read(ref _calls);
public int Releases => Volatile.Read(ref _releases);
public async Task<IReadOnlyList<ProjectedHistoryOutcome>> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details,
IReadOnlyList<ProjectedHistoryNode> nodes, TimeSpan deadline, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _calls);
var items = nodes.Select(n => new OriginHistoryItem(AddressSpaceRealm.Raw, originIdentifier, "export-view", n.AggregateId,
(n.Resume as Cursor)?.Token)).ToArray();
// A resume resends the ORIGINAL details (the peer store binds their hash), as ProjectedHistoryAccess does.
var sent = nodes.Select(n => n.Resume).OfType<Cursor>().FirstOrDefault()?.Details ?? details;
var outcomes = await _port.ReadAsync(Cursors, "peer", () => "serving-1", sent, items, cancellationToken);
details = sent;
return outcomes.Select(o => new ProjectedHistoryOutcome(o.StatusCode, o.Samples,
o.Continuation is { } token ? new Cursor(this, projectedIdentifier, token, details) : null)).ToArray();
}
private sealed class Cursor(OriginBridge owner, string identifier, byte[] token, DataHistoryDetails details)
: ProjectedHistoryContinuation(DataRealm.Raw, identifier)
{
public byte[] Token => token;
public DataHistoryDetails Details => details;
protected override void OnRelease()
{
Interlocked.Increment(ref owner._releases);
owner.Cursors.Release(token);
}
}
}
private sealed class Series(int count, int offset) : IHistorianDataSource
{
private readonly DataValueSnapshot[] _series = Enumerable.Range(0, count)
.Select(i => new DataValueSnapshot(offset + i, 0, T0.AddSeconds(i), T0.AddSeconds(i))).ToArray();
public bool SupportsReverseRaw => true;
public Task<HistorianRead> ReadRawAsync(string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode, CancellationToken ct)
{
var window = _series.Where(s => s.SourceTimestampUtc >= startUtc && s.SourceTimestampUtc < endUtc);
return Task.FromResult(new HistorianRead((maxValuesPerNode == 0 ? window : window.Take((int)maxValuesPerNode)).ToList(), null));
}
public Task<HistorianRead> ReadProcessedAsync(string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
HistoryAggregateType aggregate, CancellationToken ct) =>
Task.FromResult(new HistorianRead([new DataValueSnapshot(42.0, 0, startUtc, startUtc)], null));
public Task<HistorianRead> ReadAtTimeAsync(string fullReference, IReadOnlyList<DateTime> timestampsUtc, CancellationToken ct) =>
Task.FromResult(new HistorianRead([], null));
public Task<HistoricalEventsResult> ReadEventsAsync(string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, CancellationToken ct) =>
Task.FromResult(new HistoricalEventsResult(Array.Empty<HistoricalEvent>(), null));
public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot();
public void Dispose() { }
}
private sealed class Catalog(DataPlaneAuthorityState state) : IDataMappedCatalogAuthority
{
public long CatalogEpoch => 1;
public long AuthorityEpoch => state.Current.GenerationId;
public bool IsActive => true;
}
private sealed class Lease : IDataAuthorizationLease
{
public ServingIdentity Serving { get; } = new("node-a", "incarnation-a", "Primary", 7, 1);
public bool IsValid => true;
}
}
@@ -0,0 +1,521 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Opc.Ua.Server;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
using DataValue = Opc.Ua.DataValue;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
/// <summary>
/// H3 — the SDK side of projected history: the projected access level, the mapped HistoryRead gate with ACLs on and off,
/// the local/projected split keeping per-index slots, the Remote cursor in the session store (resume, release, session
/// close, wrong node), consumer-side aggregate refusal and the never-remote modified read.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H3")]
public sealed class ProjectedHistoryReadTests : IAsyncDisposable
{
private static readonly DateTimeOffset Now = new(2026, 11, 15, 12, 0, 0, TimeSpan.Zero);
private static readonly DateTime T0 = new(2026, 11, 15, 11, 0, 0, DateTimeKind.Utc);
private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-projected-history-{Guid.NewGuid():N}");
private OpcUaApplicationHost? _host;
[Fact]
public async Task Only_a_historizing_definition_gets_the_HistoryRead_bit_and_never_HistoryWrite()
{
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
var plain = Project(nm, f, "Plain", historizing: false);
var historized = Project(nm, f, "Hist", historizing: true);
var plainNode = Variable(nm, plain);
plainNode.AccessLevel.ShouldBe(AccessLevels.CurrentRead);
plainNode.Historizing.ShouldBeFalse();
var histNode = Variable(nm, historized);
histNode.AccessLevel.ShouldBe((byte)(AccessLevels.CurrentRead | AccessLevels.HistoryRead));
histNode.UserAccessLevel.ShouldBe((byte)(AccessLevels.CurrentRead | AccessLevels.HistoryRead));
(histNode.AccessLevel & AccessLevels.HistoryWrite).ShouldBe((byte)0);
histNode.Historizing.ShouldBeTrue();
var access = new FakeAccess();
nm.ProjectedHistoryAccess = access;
var (results, errors) = Raw(nm, f.Identity, [plain, historized]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code, "no bit ⇒ the SDK refuses before any history code");
errors[1].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
access.Calls.ShouldBe(1);
access.LastNodes.Single().NodeId.ShouldBe(historized);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Mapped_HistoryRead_needs_the_local_grant_and_the_mapping_bit_with_acls_on_and_off(bool aclEnabled)
{
// Granted: served through the projection, ACLs on or off.
var (nm, f) = await BootAsync(aclEnabled, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
var node = Project(nm, f, "Speed", historizing: true);
var access = new FakeAccess();
nm.ProjectedHistoryAccess = access;
var (results, errors) = Raw(nm, f.Identity, [node]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
Values(results[0]).Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe([1.0, 2.0]);
access.Calls.ShouldBe(1);
// No local HistoryRead grant on the mapping scope ⇒ BadUserAccessDenied, never sent — even with ACLs off.
f.Grant(NodePermissions.Browse | NodePermissions.Read);
(_, errors) = Raw(nm, f.Identity, [node]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
access.Calls.ShouldBe(1);
// Local grant but the mapping (subject) lacks HistoryRead ⇒ denied too.
f.Grant(NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
f.SubjectOperations = DataOperations.Browse | DataOperations.Read;
(_, errors) = Raw(nm, f.Identity, [node]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
access.Calls.ShouldBe(1);
// No identity at all ⇒ denied.
(_, errors) = Raw(nm, null, [node]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
access.Calls.ShouldBe(1);
}
[Fact]
public async Task A_mixed_local_and_projected_batch_keeps_every_slot()
{
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
nm.EnsureVariable("Plant/LocalA", "Plant", "LocalA", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.a");
nm.EnsureVariable("Plant/LocalB", "Plant", "LocalB", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.b");
var localA = nm.TryGetVariable("Plant/LocalA", AddressSpaceRealm.Raw)!.NodeId;
var localB = nm.TryGetVariable("Plant/LocalB", AddressSpaceRealm.Raw)!.NodeId;
var p1 = Project(nm, f, "One", historizing: true);
var p2 = Project(nm, f, "Two", historizing: true);
var access = new FakeAccess { Answer = node => node.NodeId == p1 ? [10.0] : [20.0, 21.0] };
nm.ProjectedHistoryAccess = access;
var (results, errors) = Raw(nm, f.Identity, [p1, localA, p2, localB]);
Values(results[0]).Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe([10.0]);
Values(results[2]).Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe([20.0, 21.0]);
// The local slots are the H1 port's answer (no historian ⇒ GoodNoData), untouched by the projected half.
results[1].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData.Code);
results[3].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData.Code);
errors.ShouldAllBe(e => StatusCode.IsGood(e.StatusCode));
access.Calls.ShouldBe(1, "one remote call for the batch's projected half");
access.LastNodes.Select(n => n.NodeId).ShouldBe([p1, p2]);
}
[Fact]
public async Task A_remote_cursor_resumes_once_and_is_released_by_releaseContinuationPoints_and_session_close()
{
var (nm, f) = await BootAsync(aclEnabled: true, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
var store = new InMemoryHistoryContinuationStore();
nm.HistoryContinuationStore = store;
var node = Project(nm, f, "Paged", historizing: true);
var other = Project(nm, f, "Other", historizing: true);
var access = new FakeAccess { Paged = true };
nm.ProjectedHistoryAccess = access;
var (results, _) = Raw(nm, f.Identity, [node]);
var cp = results[0].ContinuationPoint;
cp.IsEmpty.ShouldBeFalse();
var first = access.Issued.Single();
store.Count.ShouldBe(1);
// Resume: the SAME cursor comes back to the projection, claimed for the resume (not released).
(results, _) = Raw(nm, f.Identity, [node], cp);
access.LastNodes.Single().Resume.ShouldBeSameAs(first);
first.Released.ShouldBe(0);
var second = access.Issued[1];
var cp2 = results[0].ContinuationPoint;
// The same point again ⇒ invalid (single-use), unsent.
var calls = access.Calls;
(results, var errors) = Raw(nm, f.Identity, [node], cp);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
access.Calls.ShouldBe(calls);
// A cursor resumed on ANOTHER node ⇒ invalid and released.
(_, errors) = Raw(nm, f.Identity, [other], cp2);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
second.Released.ShouldBe(1);
// releaseContinuationPoints forwards one release.
(results, _) = Raw(nm, f.Identity, [node]);
var third = access.Issued[2];
Release(nm, f.Identity, node, results[0].ContinuationPoint);
third.Released.ShouldBe(1);
store.Count.ShouldBe(0);
// Session close (the SDK disposes every point) releases what is still open.
Raw(nm, f.Identity, [node]);
Raw(nm, f.Identity, [other]);
store.Count.ShouldBe(2);
store.Clear();
access.Issued.Skip(3).ShouldAllBe(c => c.Released == 1);
}
[Fact]
public async Task A_bad_remote_answer_carries_no_cursor_and_unknown_aggregates_and_modified_reads_are_refused_unsent()
{
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
var node = Project(nm, f, "Speed", historizing: true);
var access = new FakeAccess { Status = StatusCodes.BadAggregateNotSupported.Code, Paged = true };
nm.ProjectedHistoryAccess = access;
// The origin refuses the aggregate: verbatim, no cursor kept (and the one it returned is released).
var processed = new ReadProcessedDetails
{
StartTime = T0, EndTime = T0.AddHours(1), ProcessingInterval = 60_000,
AggregateType = [ObjectIds.AggregateFunction_Average],
};
var (results, errors) = Read(nm, f.Identity, processed, [node]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
results[0].ContinuationPoint.IsEmpty.ShouldBeTrue();
access.Issued.ShouldAllBe(c => c.Released == 1);
access.LastNodes.Single().AggregateId.ShouldBe(Objects.AggregateFunction_Average);
// An aggregate the consumer cannot name ⇒ BadAggregateNotSupported without a call.
var calls = access.Calls;
processed.AggregateType = [new NodeId("not-an-aggregate", 2)];
(_, errors) = Read(nm, f.Identity, processed, [node]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
access.Calls.ShouldBe(calls);
// A modified read is never served remotely.
var modified = new ReadRawModifiedDetails { StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 5, IsReadModified = true };
(_, errors) = Read(nm, f.Identity, modified, [node]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
access.Calls.ShouldBe(calls);
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_throw_while_serving_one_outcome_releases_every_later_outcomes_cursor()
{
// H3 review round 3 nit (d): outcome 0's value cannot cross the SDK boundary (FromClr throws) — outcome 1's origin cursor
// must not be stranded; outcome 0's is already the session store's (saved before the throw), so it is not released twice.
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
var a = Project(nm, f, "Speed", historizing: true);
var b = Project(nm, f, "Flow", historizing: true);
var access = new FakeAccess { Paged = true, FirstValue = new object() };
nm.ProjectedHistoryAccess = access;
try { Raw(nm, f.Identity, [a, b]); }
catch (ArgumentException) { } // the fault itself is the node manager's to surface; only the cursors matter here
access.Issued.Count.ShouldBe(2);
access.Issued[1].Released.ShouldBe(1, "the later outcome's cursor is released");
access.Issued[0].Released.ShouldBe(0, "the store owns the saved cursor");
}
[Fact]
public void Unset_bounds_travel_absent_and_AtTime_carries_its_times()
{
OtOpcUaNodeManager.ToRemoteDetails(new ReadRawModifiedDetails { EndTime = T0, NumValuesPerNode = 3, ReturnBounds = true, IsReadModified = false })
.ShouldBe(new DataHistoryRawDetails(null, new DateTimeOffset(T0), 3, true));
var atTime = OtOpcUaNodeManager.ToRemoteDetails(new ReadAtTimeDetails { ReqTimes = [T0], UseSimpleBounds = true })
.ShouldBeOfType<DataHistoryAtTimeDetails>();
atTime.RequestedTimesUtc.ShouldBe([new DateTimeOffset(T0)]);
atTime.UseSimpleBounds.ShouldBeTrue();
}
[Fact]
public async Task A_claimed_cursor_is_released_on_every_exit_that_never_sends_it()
{
// H3 review D2: Release() after a claim is a no-op, so each post-claim exit must use ReleaseEvenIfClaimed — exactly once.
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
var store = new InMemoryHistoryContinuationStore();
nm.HistoryContinuationStore = store;
var node = Project(nm, f, "Leak", historizing: true);
var paging = new FakeAccess { Paged = true };
nm.ProjectedHistoryAccess = paging;
(FakeCursor Cursor, ByteString Cp) HeldPoint()
{
var (results, _) = Raw(nm, f.Identity, [node]);
results[0].ContinuationPoint.IsEmpty.ShouldBeFalse();
return (paging.Issued[^1], results[0].ContinuationPoint);
}
// (a) the gateway disappears between the issue and the resume.
var (cursor, cp) = HeldPoint();
nm.ProjectedHistoryAccess = null;
Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
cursor.Released.ShouldBe(1);
nm.ProjectedHistoryAccess = paging;
// (b) the gateway throws (anything): BadNoCommunication, the resume released, nothing escapes.
(cursor, cp) = HeldPoint();
nm.ProjectedHistoryAccess = new FakeAccess { Throw = new InvalidCastException("boom") };
Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadNoCommunication.Code);
cursor.Released.ShouldBe(1);
nm.ProjectedHistoryAccess = paging;
// (c) the request deadline was spent by the time the projected half starts.
(cursor, cp) = HeldPoint();
nm.HistoryReadDeadline = TimeSpan.FromTicks(1);
Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code);
cursor.Released.ShouldBe(1);
nm.HistoryReadDeadline = TimeSpan.FromSeconds(60);
// (d) the projected sub-limit is exhausted (limiter rejection).
(cursor, cp) = HeldPoint();
var limiter = nm.GetNonLocalHistoryLimiter();
var taken = 0;
while (limiter.Wait(0, TestContext.Current.CancellationToken)) taken++;
try
{
Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
cursor.Released.ShouldBe(1);
}
finally { limiter.Release(taken); }
// Positive control: a normal resume claims the cursor and does NOT release it (the read owns the token).
(cursor, cp) = HeldPoint();
Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
cursor.Released.ShouldBe(0);
paging.Issued.Where(c => !ReferenceEquals(c, paging.Issued[^1])).ShouldAllBe(c => c.Released <= 1, "never released twice");
}
[Fact]
public async Task Projected_reads_and_remote_peers_together_cannot_take_every_history_slot_local_history_is_still_served()
{
// H3 review D3: projected reads hold at most N - max(1, N/4) of the N shared batch slots.
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
nm.MaxConcurrentHistoryReadBatches = 4; // => 3 projected slots, 1 always left for local history
nm.EnsureVariable("Plant/LocalSlot", "Plant", "LocalSlot", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.slot");
var local = nm.TryGetVariable("Plant/LocalSlot", AddressSpaceRealm.Raw)!.NodeId;
var node = Project(nm, f, "Slow", historizing: true);
var hold = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var slow = new FakeAccess { Hold = hold };
nm.ProjectedHistoryAccess = slow;
var held = Enumerable.Range(0, 3).Select(_ => Task.Run(() => Raw(nm, f.Identity, [node]))).ToArray();
var deadline = DateTime.UtcNow.AddSeconds(10);
while (Volatile.Read(ref slow.Entries) < 3 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken);
slow.Entries.ShouldBe(3, "three projected reads hold the three projected slots");
try
{
// A fourth projected read is refused at once, unsent; local history is still served.
// (Bounded: without the sub-limit this read would take the 4th shared slot and wait on the held gateway.)
var (_, refused) = await Task.Run(() => Raw(nm, f.Identity, [node]))
.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
refused[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
slow.Entries.ShouldBe(3);
// H3 review round 2: remote peers reading THIS node share the same non-local slots — refused too, unsent — so the
// origin port and the projected path together can never take the last (local) slot.
var port = new OriginHistoryPort(nm);
port.AvailableRemoteSlots.ShouldBe(0);
var peer = await port.ReadAsync(new OriginHistoryCursors("peer", "channel", 4), "peer", () => "serving",
new DataHistoryRawDetails(new DateTimeOffset(T0), new DateTimeOffset(T0.AddHours(1)), 5, false),
[new OriginHistoryItem(AddressSpaceRealm.Raw, "Plant/LocalSlot", "tag", null, null)], TestContext.Current.CancellationToken);
peer.Single().StatusCode.ShouldBe(StatusCodes.BadTooManyOperations.Code);
var (localResults, localErrors) = Raw(nm, f.Identity, [local]);
StatusCode.IsGood(localErrors[0].StatusCode).ShouldBeTrue(localErrors[0].StatusCode.ToString());
localResults[0].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData.Code);
}
finally { hold.SetResult(); }
foreach (var (_, errors) in await Task.WhenAll(held)) StatusCode.IsGood(errors[0].StatusCode).ShouldBeTrue();
}
[Fact]
public async Task A_remote_cursor_presented_to_a_local_node_is_invalid_and_released()
{
// H3 review D5: the local take removes the SDK slot, so it must release the origin continuation.
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
var store = new InMemoryHistoryContinuationStore();
nm.HistoryContinuationStore = store;
nm.EnsureVariable("Plant/LocalCp", "Plant", "LocalCp", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.cp");
var local = nm.TryGetVariable("Plant/LocalCp", AddressSpaceRealm.Raw)!.NodeId;
var node = Project(nm, f, "Remote", historizing: true);
var access = new FakeAccess { Paged = true };
nm.ProjectedHistoryAccess = access;
var (results, _) = Raw(nm, f.Identity, [node]);
var (_, errors) = Raw(nm, f.Identity, [local], results[0].ContinuationPoint);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
access.Issued.Single().Released.ShouldBe(1);
store.Count.ShouldBe(0);
}
// ------------------------------------------------------------------------------------------------------------------
private static (List<SdkHistoryReadResult> Results, List<ServiceResult> Errors) Raw(OtOpcUaNodeManager nm, IUserIdentity? identity,
NodeId[] nodes, ByteString cp = default) =>
Read(nm, identity, new ReadRawModifiedDetails
{
StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 2, IsReadModified = false, ReturnBounds = false,
}, nodes, cp);
private static (List<SdkHistoryReadResult> Results, List<ServiceResult> Errors) Read(OtOpcUaNodeManager nm, IUserIdentity? identity,
HistoryReadDetails details, NodeId[] nodes, ByteString cp = default)
{
var context = new OperationContext(new RequestHeader(), null, RequestType.HistoryRead, RequestLifetime.None, identity);
var results = nodes.Select(_ => (SdkHistoryReadResult)null!).ToList();
var errors = nodes.Select(_ => (ServiceResult)null!).ToList();
nm.HistoryRead(context, details, TimestampsToReturn.Both, false,
nodes.Select(n => new HistoryReadValueId { NodeId = n, ContinuationPoint = cp }).ToList(), results, errors);
return (results, errors);
}
private static void Release(OtOpcUaNodeManager nm, IUserIdentity identity, NodeId node, ByteString cp)
{
var context = new OperationContext(new RequestHeader(), null, RequestType.HistoryRead, RequestLifetime.None, identity);
var results = new List<SdkHistoryReadResult> { null! };
var errors = new List<ServiceResult> { null! };
nm.HistoryRead(context, new ReadRawModifiedDetails { IsReadModified = false, ReturnBounds = false }, TimestampsToReturn.Both, true,
new List<HistoryReadValueId> { new() { NodeId = node, ContinuationPoint = cp } }, results, errors);
StatusCode.IsGood(errors[0].StatusCode).ShouldBeTrue();
}
private static IReadOnlyList<DataValue> Values(SdkHistoryReadResult result) =>
ExtensionObject.ToEncodeable(result.HistoryData) is HistoryData data ? data.DataValues.ToArray() ?? [] : [];
private static BaseDataVariableState Variable(OtOpcUaNodeManager nm, NodeId id) =>
((NodeHandle)nm.GetManagerHandle(id)!).Node.ShouldBeOfType<BaseDataVariableState>();
private static NodeId Project(OtOpcUaNodeManager nm, Fixture f, string name, bool historizing)
{
var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var origin = new DataAddress("origin", "ns", "string", "Device/" + name);
var view = new DataView(origin, DataRealm.Raw, "mapping-a", 1, "Plant/Mount/" + name);
var metadata = new DataMetadata(view, name, "Tag", DataValueKind.Double, -1, [], false,
DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead, 1, null, null, false, History: new DataHistoryInfo(historizing));
var identifier = ProjectedDataIds.Identifier("mapping-a", origin);
nm.TryEnsureProjectedVariable(new ProjectedVariableDefinition(DataRealm.Raw, identifier, parent, metadata, 1, () => true)
{ Historizing = historizing }, out var node).ShouldBeTrue();
f.Views[identifier] = view;
return node!.Value;
}
private async Task<(OtOpcUaNodeManager Nm, Fixture F)> BootAsync(bool aclEnabled, NodePermissions permissions)
{
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "ProjectedHistory", ApplicationUri = $"urn:ProjectedHistory:{Guid.NewGuid():N}",
OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki,
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
_host = started.Host;
var nm = started.Server.NodeManager!;
nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var f = new Fixture(aclEnabled, permissions);
nm.Authorizer = f.Gate;
nm.MappedSubjectResolver = (realm, id) => f.Resolve(realm, id);
return (nm, f);
}
public async ValueTask DisposeAsync()
{
if (_host is not null) await _host.DisposeAsync();
if (Directory.Exists(_pki))
try { Directory.Delete(_pki, recursive: true); } catch (IOException) { }
}
private sealed class Fixture
{
private readonly DataPlaneAuthorityState _state = new();
private readonly TestLease _lease = new();
internal readonly ApiKey Key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true,
ExpiresUtc = Now.AddHours(1).UtcDateTime };
internal readonly DataPlaneAuthorizer Gate;
internal readonly Dictionary<string, DataView> Views = new(StringComparer.Ordinal);
internal DataOperations SubjectOperations { get; set; } =
DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead;
internal Fixture(bool aclEnabled, NodePermissions permissions)
{
Grant(permissions);
var clock = new TestClock();
Gate = new DataPlaneAuthorizer(_state, new TriePermissionEvaluator(_state.Tries, clock), aclEnabled, NullLogger.Instance, clock);
}
internal void Grant(NodePermissions permissions) =>
_state.Apply("c1", "rev-" + (int)permissions, [Key],
[new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.RawFolder,
ScopeId = "folder", PermissionFlags = permissions }],
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant", "Mount"])] });
internal RoleCarryingUserIdentity Identity => new(new UserNameIdentityToken { UserName = "apikey" }, [], "reader", Key.ApiKeyId,
DataCallerIdentity.CredentialVersionFor(Key), Now.AddMinutes(2));
internal MappedNodeResolution Resolve(AddressSpaceRealm realm, string identifier)
{
if (!Views.TryGetValue(identifier, out var view)) return MappedNodeResolution.Local;
var subject = new MappedNamespaceSubject(view,
new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = view.Subject.Split('/') },
["local-parent", "mapping-a"], _lease.Serving, SubjectOperations, WriteThrough: false);
var resolver = new MappedSubjectResolver([subject], catalogEpoch: 7, new TestCatalogAuthority(_state));
return MappedNodeResolution.Mapped(view, subject, resolver, _lease);
}
}
private sealed class FakeAccess : IProjectedHistoryAccess
{
public int Calls;
public IReadOnlyList<ProjectedHistoryNode> LastNodes = [];
public readonly List<FakeCursor> Issued = [];
public bool Paged { get; init; }
public uint Status { get; init; }
public Func<ProjectedHistoryNode, double[]> Answer { get; init; } = _ => [1.0, 2.0];
/// <summary>When set, the FIRST node's first sample carries this value (e.g. one the SDK boundary cannot convert).</summary>
public object? FirstValue { get; init; }
/// <summary>When set, every call waits on it (a projected read holding its slot).</summary>
public TaskCompletionSource? Hold { get; set; }
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>When set, every call throws it (after claiming nothing — the cursors are the caller's to release).</summary>
public Exception? Throw { get; set; }
public int Entries;
public async Task<IReadOnlyList<ProjectedHistoryOutcome>> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details,
IReadOnlyList<ProjectedHistoryNode> nodes, TimeSpan deadline, CancellationToken cancellationToken)
{
Interlocked.Increment(ref Calls);
LastNodes = nodes;
if (Interlocked.Increment(ref Entries) > 0) Entered.TrySetResult();
if (Hold is { } hold) await hold.Task.ConfigureAwait(false);
if (Throw is { } error) throw error;
return (nodes.Select(node =>
{
FakeCursor? next = null;
if (Paged)
{
var key = node.NodeId.TryGetValue(out string id) ? id : "";
next = new FakeCursor(key);
Issued.Add(next);
}
var samples = Answer(node).Select((v, i) => new OriginHistorySample(v, 0, T0.AddSeconds(i), null)).ToArray();
if (FirstValue is { } poison && ReferenceEquals(node, nodes[0]) && samples.Length > 0) samples[0] = samples[0] with { Value = poison };
return new ProjectedHistoryOutcome(Status, Status == 0 ? samples : [], next);
}).ToArray());
}
}
private sealed class FakeCursor(string identifier) : ProjectedHistoryContinuation(DataRealm.Raw, identifier)
{
public int Released;
protected override void OnRelease() => Interlocked.Increment(ref Released);
}
private sealed class TestCatalogAuthority(DataPlaneAuthorityState state) : IDataMappedCatalogAuthority
{
public long CatalogEpoch => 1;
public long AuthorityEpoch => state.Current.GenerationId;
public bool IsActive => true;
}
private sealed class TestLease : IDataAuthorizationLease
{
public ServingIdentity Serving { get; } = new("node-a", "incarnation-a", "Primary", 7, 1);
public bool IsValid => true;
}
private sealed class TestClock : TimeProvider
{
public override DateTimeOffset GetUtcNow() => Now;
}
}
@@ -24,22 +24,25 @@ public sealed class OriginHistoryLimiterTests(HistoryReadPortServerFixture fx) :
var source = new BlockingSource();
try
{
fx.Nm.MaxConcurrentHistoryReadBatches = 4; // the limiter is sized at first use; this fixture is fresh
// The limiter is sized ONCE per node manager, at first use: with the shared fixture another test may have sized it
// already (H3 review round 2: the non-local share is now one node-manager semaphore), so saturate what exists.
fx.Nm.MaxConcurrentHistoryReadBatches = 4;
fx.Nm.HistorianDataSource = source;
var port = new OriginHistoryPort(fx.Nm);
OriginHistoryPort.RemoteSlots(4).ShouldBe(3);
var slots = port.AvailableRemoteSlots;
var details = new DataHistoryRawDetails(new DateTimeOffset(T0), new DateTimeOffset(T0.AddSeconds(5)), 1, false);
var item = new OriginHistoryItem(AddressSpaceRealm.Uns, "port/dbl", "peer:uns", null, null);
var remote = Enumerable.Range(0, 3).Select(i => port.ReadAsync(new OriginHistoryCursors("peer", "c" + i, 4), "peer", () => "inc",
var remote = Enumerable.Range(0, slots).Select(i => port.ReadAsync(new OriginHistoryCursors("peer", "c" + i, 4), "peer", () => "inc",
details, [item], CancellationToken.None)).ToArray();
await source.WaitForCalls(3);
await source.WaitForCalls(slots);
var refused = (await port.ReadAsync(new OriginHistoryCursors("peer", "c9", 4), "peer", () => "inc", details, [item], CancellationToken.None)).Single();
refused.StatusCode.ShouldBe(StatusCodes.BadTooManyOperations.Code, "the remote share is full");
// A local (SDK-path) read still gets the reserved slot.
var local = Task.Run(() => fx.Nm.ReadHistory(OriginHistoryPort.ToVariant(details),
[new HistoryReadPortItem(AddressSpaceRealm.Uns, "port/dbl", null, default, "urn:local")],
fx.Nm.SessionHistoryContinuationScope(null), CancellationToken.None));
await source.WaitForCalls(4);
await source.WaitForCalls(slots + 1);
source.Release.TrySetResult();
(await local).Single().Status.Code.ShouldNotBe(StatusCodes.BadTooManyOperations.Code);
foreach (var r in await Task.WhenAll(remote)) r.Single().StatusCode.ShouldNotBe(StatusCodes.BadTooManyOperations.Code);
@@ -64,7 +67,7 @@ public sealed class OriginHistoryLimiterTests(HistoryReadPortServerFixture fx) :
var port = new OriginHistoryPort(fx.Nm);
var details = new DataHistoryRawDetails(new DateTimeOffset(T0), new DateTimeOffset(T0.AddSeconds(5)), 1, false);
var item = new OriginHistoryItem(AddressSpaceRealm.Uns, "port/dbl", "peer:uns", null, null);
var slots = OriginHistoryPort.RemoteSlots(fx.Nm.MaxConcurrentHistoryReadBatches);
var slots = port.AvailableRemoteSlots; // the node manager's non-local share, sized once at first use
using var cancelled = new CancellationTokenSource();
await cancelled.CancelAsync();
for (var i = 0; i < slots + 3; i++)
@@ -362,7 +362,9 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
bool restrictToPlant = false, Action<ProjectedValueUpdate>? onPublished = null, bool mountAtRealmRoot = false,
long maxUnaryBytes = 8_000_000, bool allowWrite = false, IGrpcDataAdapterConnectionSource? connectionSource = null,
int? staleTimeoutMilliseconds = null, Func<IProjectedNamespacePageSink, IProjectedNamespacePageSink>? renewalSinkFactory = null,
Action<LocalCatalogCoordinator>? onCoordinator = null, int? localPermissions = null, bool allowHistory = false)
Action<LocalCatalogCoordinator>? onCoordinator = null, int? localPermissions = null, bool allowHistory = false,
Action<ProjectedHistoryAccess, OtOpcUaNodeManager>? onHistory = null,
Action<ZB.MOM.WW.OtOpcUa.Configuration.Entities.RemoteNamespaceMapping>? configureMapping = null)
{
var ct = TestContext.Current.CancellationToken;
var pki = Path.Combine(Path.GetTempPath(), $"composed-projection-{Guid.NewGuid():N}");
@@ -401,6 +403,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata;
if (allowWrite) { mapping.AllowedOperations |= DataOperations.Write; mapping.WriteThrough = true; }
if (allowHistory) mapping.AllowedOperations |= DataOperations.HistoryRead;
configureMapping?.Invoke(mapping);
placements.Stage(attempt, [mapping], [Connection()]);
coordinator.Complete(attempt, true).ShouldBeTrue();
var manager = started.Server.NodeManager!;
@@ -427,6 +430,12 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8);
manager.ProjectedBrowseAccess = browse;
manager.ProjectedDataAccess = access;
// H3: projected HistoryRead through the same deployed connections.
using var history = new ProjectedHistoryAccess(access, connections,
id => placements.TryGetHistoryAssemblyBudget(id, out var bytes) ? bytes : null, origin.Clock)
{ ReleaseCoalesce = TimeSpan.Zero }; // the flush delay runs on the (manual) fixture clock
manager.ProjectedHistoryAccess = history;
onHistory?.Invoke(history, manager);
var identifier = ProjectedDataIds.Identifier("map", root.Address);
((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.NamespaceUri(root.Realm), identifier, out var node).ShouldBeTrue();
var anchor = node.ShouldNotBeNull();
@@ -0,0 +1,66 @@
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;
/// <summary>
/// H3 review round 3 nit (c): the deployment lease drops a history answer when its scope moves while the answer is in flight —
/// the new origin continuations that answer carries are released (not stranded), and a resumed item is
/// <c>BadContinuationPointInvalid</c> (its token cannot be presented again), a fresh one <c>BadNoCommunication</c>.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H3")]
public sealed class GrpcDataDeployedHistoryLeaseTests
{
private static readonly DataView View = new(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x");
[Fact]
public async Task A_scope_move_during_the_answer_releases_its_new_continuations()
{
var current = true;
var inner = new Inner { OnRead = () => current = false };
var lease = new DataConnectionDeploymentLease(inner, CancellationToken.None, DataOperations.HistoryRead, TimeSpan.FromSeconds(5),
16, 16, 1 << 20, 1, 1, 1 << 20, () => current, () => { });
var request = new DataHistoryReadRequest(new DataHistoryRawDetails(null, DateTimeOffset.UnixEpoch.AddDays(1), 2, false),
[new("fresh", View), new("resumed", View, null, [1])], new DataBudget(TimeSpan.FromSeconds(5), 16, 1 << 20));
var results = await lease.ReadHistoryAsync(request, TestContext.Current.CancellationToken);
results[0].StatusCode.ShouldBe(0x80310000u);
results[1].StatusCode.ShouldBe(0x804A0000u);
var deadline = DateTime.UtcNow.AddSeconds(5);
while (inner.ReleasedCount == 0 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken);
inner.Released.ShouldBe([[8], [9]], ignoreOrder: true);
}
private sealed class Inner : IDataConnection, IDataHistoryService
{
public Action OnRead { get; init; } = () => { };
private readonly List<byte[]> _released = [];
public int ReleasedCount { get { lock (_released) return _released.Count; } }
public byte[][] Released { get { lock (_released) return _released.ToArray(); } }
public DataTarget Target => new(DataTargetMode.Cluster, "c", null);
public TimeProvider Clock => TimeProvider.System;
public Task<IReadOnlyList<DataHistoryReadResult>> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken)
{
OnRead();
byte k = 8;
return Task.FromResult<IReadOnlyList<DataHistoryReadResult>>(request.Items
.Select(i => new DataHistoryReadResult(i.CorrelationId, 0, [], [k++])).ToArray());
}
public Task ReleaseAsync(IReadOnlyList<byte[]> continuations, CancellationToken cancellationToken)
{
lock (_released) _released.AddRange(continuations);
return Task.CompletedTask;
}
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => throw new NotSupportedException();
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
@@ -193,6 +193,183 @@ public sealed class GrpcDataHistoryClientTests
await Should.ThrowAsync<OperationCanceledException>(() => connection.ReadHistoryAsync(Request(), cancel.Token));
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_caller_cancel_during_the_capability_probe_is_an_OperationCanceledException_never_an_RpcException()
{
// H3 review D1: the probe that never answers used to surface RpcException(Cancelled) and fault the consumer's HistoryRead.
var a = new Endpoint("a") { ProbeDelay = TimeSpan.FromSeconds(30) };
await using var connection = Connect([a]);
using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
var error = await Should.ThrowAsync<OperationCanceledException>(() => connection.ReadHistoryAsync(Request(), cancel.Token));
error.ShouldNotBeAssignableTo<Grpc.Core.RpcException>();
a.HistoryCalls.ShouldBe(0);
}
[Fact]
[Trait("Phase", "H3")]
public async Task The_capability_probe_is_capped_by_HistoryTimeout_too()
{
var a = new Endpoint("a");
await using var connection = Connect([a], historyTimeout: TimeSpan.FromSeconds(2));
var request = Request() with { Budget = Request().Budget with { Timeout = TimeSpan.FromMinutes(10) } };
(await connection.ReadHistoryAsync(request, TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0u);
a.LastProbeTimeout.ShouldNotBeNull();
a.LastProbeTimeout!.Value.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(2));
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_request_larger_than_the_endpoints_advertised_batch_is_split_from_the_negotiated_capabilities()
{
// H3 review round 2: the split uses the capabilities the history call itself negotiated — no extra probe.
var a = new Endpoint("a") { BatchItems = 2 };
await using var connection = Connect([a]);
var request = new DataHistoryReadRequest(Request().Details,
Enumerable.Range(0, 5).Select(i => new DataHistoryReadItem("n" + i, View)).ToArray(), Budget);
var results = await connection.ReadHistoryAsync(request, TestContext.Current.CancellationToken);
results.Select(r => r.CorrelationId).ShouldBe(["n0", "n1", "n2", "n3", "n4"]);
results.ShouldAllBe(r => r.StatusCode == 0u && r.Samples.Count == 2);
a.CallSizes.ShouldBe([2, 2, 1]);
a.Headers.Count(h => h.Path.EndsWith("/GetCapabilities", StringComparison.Ordinal)).ShouldBe(1, "one negotiation for the whole request");
foreach (var r in results) r.Dispose();
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_cancel_during_a_multi_node_read_leaves_the_connection_usable_without_backoff()
{
var a = new Endpoint("a") { ProbeDelay = TimeSpan.FromSeconds(30) };
await using var connection = Connect([a]);
var request = new DataHistoryReadRequest(Request().Details,
Enumerable.Range(0, 3).Select(i => new DataHistoryReadItem("n" + i, View)).ToArray(), Budget);
using (var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(200)))
await Should.ThrowAsync<OperationCanceledException>(() => connection.ReadHistoryAsync(request, cancel.Token));
a.ProbeDelay = null;
var again = await connection.ReadHistoryAsync(request, TestContext.Current.CancellationToken);
again.ShouldAllBe(r => r.StatusCode == 0u, "a cancel is not an endpoint failure: no discovery backoff");
foreach (var r in again) r.Dispose();
}
// ---- H3 review round 3 -------------------------------------------------------------------------------------------
private static readonly long SampleBytes = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 1.0), 0, null, null)
.Value.EstimatedRetainedBytes; // the fake answers two Double samples per item per chunk
private static DataHistoryReadRequest Many(int count, long? maxBytes = null) => new(Request().Details,
Enumerable.Range(0, count).Select(i => new DataHistoryReadItem("n" + i, View)).ToArray(), maxBytes is { } b ? Budget with { MaxBytes = b } : Budget);
private static async Task AwaitReleased(Endpoint a, Func<byte[][], bool> done)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
while (DateTime.UtcNow < deadline)
{
byte[][] released;
lock (a.Released) released = a.Released.ToArray();
if (done(released)) return;
await Task.Delay(20, TestContext.Current.CancellationToken);
}
}
private static int ReleasedCount(Endpoint a, byte[] token) { lock (a.Released) return a.Released.Count(t => t.SequenceEqual(token)); }
[Fact]
[Trait("Phase", "H3")]
public async Task A_cancel_in_a_later_sub_batch_releases_the_earlier_sub_batches_new_continuations()
{
// S1: sub-batch 1 answered (two new page continuations); the caller cancels during sub-batch 2 — nothing is stranded.
var a = new Endpoint("a") { BatchItems = 2, PageToken = [9, 9, 9], HangOnDataCall = 2 };
await using var connection = Connect([a]);
using var cancel = new CancellationTokenSource();
var read = connection.ReadHistoryAsync(Many(4), cancel.Token);
var deadline = DateTime.UtcNow.AddSeconds(10);
while (Volatile.Read(ref a.DataCalls) < 2 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken);
await cancel.CancelAsync();
await Should.ThrowAsync<OperationCanceledException>(() => read);
await AwaitReleased(a, r => r.Count(t => t.SequenceEqual(new byte[] { 9, 9, 9 })) >= 2);
ReleasedCount(a, [9, 9, 9]).ShouldBe(2, "both continuations sub-batch 1 opened are released");
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_later_sub_batch_is_trimmed_to_the_origins_byte_admission_and_the_rest_is_a_consumer_budget_refusal()
{
// S2: after sub-batch 1 only room for ONE item is left (256 B); sending two would break the origin's count <= MaxBytes/256
// rule (an RpcException ⇒ a recorded endpoint failure). Trimmed: [2, 1], the rest refused unsent, no endpoint failure.
var a = new Endpoint("a") { BatchItems = 2, EnforceAdmission = true };
await using var connection = Connect([a]);
var results = await connection.ReadHistoryAsync(Many(4, 4 * SampleBytes + 256), TestContext.Current.CancellationToken);
results.Take(2).ShouldAllBe(r => r.StatusCode == 0u && r.Samples.Count == 2);
results.Skip(2).ShouldAllBe(r => r.StatusCode == 0x80100000u && r.ConsumerBudgetRefused);
a.CallSizes.ShouldBe([2, 1]);
foreach (var r in results) r.Dispose();
var again = await connection.ReadHistoryAsync(Many(1), TestContext.Current.CancellationToken);
again.Single().StatusCode.ShouldBe(0u, "a budget refusal is not an endpoint failure");
foreach (var r in again) r.Dispose();
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_sub_batch_whose_assembly_overflows_spends_the_budget_and_nothing_more_is_sent()
{
// S3: sub-batch 2 refuses n3 inside its own assembly while what was KEPT is still below the budget — n4, n5 unsent.
var a = new Endpoint("a") { BatchItems = 2 };
await using var connection = Connect([a]);
var results = await connection.ReadHistoryAsync(Many(6, 7 * SampleBytes), TestContext.Current.CancellationToken);
results.Take(3).ShouldAllBe(r => r.StatusCode == 0u);
results.Skip(3).ShouldAllBe(r => r.StatusCode == 0x80100000u && r.ConsumerBudgetRefused);
a.CallSizes.ShouldBe([2, 2]);
foreach (var r in results) r.Dispose();
}
[Fact]
[Trait("Phase", "H3")]
public async Task After_a_sub_batch_endpoint_failure_nothing_more_is_sent_to_that_endpoint()
{
// Nit (a): sub-batch 2 fails (recorded); sub-batch 3 is answered unsent.
var a = new Endpoint("a") { BatchItems = 2, FailAfterFirst = Grpc.Core.StatusCode.Internal };
await using var connection = Connect([a]);
var results = await connection.ReadHistoryAsync(Many(5), TestContext.Current.CancellationToken);
results.Take(2).ShouldAllBe(r => r.StatusCode == 0u);
results.Skip(2).ShouldAllBe(r => r.StatusCode == 0x80310000u);
a.CallSizes.ShouldBe([2, 2]);
foreach (var r in results) r.Dispose();
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_rejected_follow_up_chunk_releases_every_token_the_assembly_holds()
{
// S6: n0 completes on call 1 (a new page continuation in final[]); n1 continues; call 2's answer is malformed.
var a = new Endpoint("a") { PageToken = [9, 9, 9], Chunks = 3, MalformedFromDataCall = 2 };
a.ChunksByItem["n0"] = 1;
await using var connection = Connect([a]);
var results = await connection.ReadHistoryAsync(Many(2), TestContext.Current.CancellationToken);
results.ShouldAllBe(r => r.StatusCode == 0x80310000u);
await AwaitReleased(a, r => r.Any(t => t.SequenceEqual(new byte[] { 9, 9, 9 })) && r.Any(t => t.SequenceEqual(new byte[] { 7, 7 })));
ReleasedCount(a, [9, 9, 9]).ShouldBe(1, "n0's finished continuation is released");
ReleasedCount(a, [7, 7]).ShouldBeGreaterThan(0, "n1's chunk tokens are released");
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_call_cancelled_by_a_scope_move_is_not_a_timeout()
{
// S5: neither the caller nor the deadline cancelled the call — the connection's scope moved (a redeploy).
DataConnectionManager? manager = null;
var a = new Endpoint("a") { HangOnDataCall = 1 };
await using var connection = Connect([a], onManager: m => manager = m);
var request = new DataHistoryReadRequest(Request().Details,
[new("fresh", View), new("resumed", View, null, GrpcDataConnection.Wrap(0, "boot-a", [1, 2]))], Budget);
var read = connection.ReadHistoryAsync(request, TestContext.Current.CancellationToken);
var deadline = DateTime.UtcNow.AddSeconds(10);
while (Volatile.Read(ref a.DataCalls) < 1 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken);
manager!.ApplyScope(new Dictionary<string, IReadOnlySet<string>>());
var results = await read;
results[0].StatusCode.ShouldBe(0x80310000u, "fresh: BadNoCommunication, not BadTimeout");
results[1].StatusCode.ShouldBe(0x804A0000u, "resumed: BadContinuationPointInvalid");
}
[Fact]
public async Task A_failure_mid_assembly_releases_the_origin_chunk_tokens_it_holds()
{
@@ -204,9 +381,10 @@ public sealed class GrpcDataHistoryClientTests
a.Released.ShouldContain(t => t.SequenceEqual(new byte[] { 7, 7 }), "the chunk token the failed follow-up carried is released");
}
private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? historyTimeout = null)
private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? historyTimeout = null, Action<DataConnectionManager>? onManager = null)
{
var manager = new DataConnectionManager("consumer", 1);
onManager?.Invoke(manager);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
var router = new Router(endpoints);
return new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), endpoints.Select(e => new Uri($"https://{e.Name}.test")),
@@ -225,9 +403,26 @@ public sealed class GrpcDataHistoryClientTests
public bool Malformed { get; set; }
/// <summary>Delay before answering a HistoryRead (honours the request's token).</summary>
public TimeSpan? Delay { get; set; }
/// <summary>Delay before answering the capability probe (honours the request's token).</summary>
public TimeSpan? ProbeDelay { get; set; }
/// <summary>The advertised MaxBatchItems (default: the shared limits').</summary>
public int? BatchItems { get; set; }
/// <summary>The item count of every HistoryRead call.</summary>
public List<int> CallSizes { get; } = [];
/// <summary>The grpc-timeout of the last capability probe.</summary>
public TimeSpan? LastProbeTimeout { get; private set; }
/// <summary>Fail every HistoryRead after the first with this status.</summary>
public Grpc.Core.StatusCode? FailAfterFirst { get; set; }
public int Chunks { get; init; } = 1;
/// <summary>Per correlation id chunk counts (overrides <see cref="Chunks"/>).</summary>
public Dictionary<string, int> ChunksByItem { get; } = new();
/// <summary>Refuse a call carrying more than one item per 256 B of its byte budget (the origin's admission rule).</summary>
public bool EnforceAdmission { get; set; }
/// <summary>The data (non-release) HistoryRead call that never answers (honours the request's token).</summary>
public int? HangOnDataCall { get; set; }
/// <summary>From this data call on, answers carry unexpected correlation ids.</summary>
public int? MalformedFromDataCall { get; set; }
public int DataCalls;
public byte[]? PageToken { get; init; }
public int HistoryCalls;
public List<(string Path, string? Features)> Headers { get; } = [];
@@ -247,10 +442,12 @@ public sealed class GrpcDataHistoryClientTests
IMessage message;
if (path.EndsWith("/GetCapabilities", StringComparison.Ordinal))
{
if (request.Headers.TryGetValues("grpc-timeout", out var probeTimeouts)) LastProbeTimeout = ParseTimeout(probeTimeouts.Single());
if (ProbeDelay is { } probeDelay) await Task.Delay(probeDelay, token);
var asked = request.Headers.Contains("x-otopcua-data-features");
var caps = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 5, Serving, Ready ? DataReadiness.Ready : DataReadiness.Unavailable,
!Ready ? DataOperations.None : DataOperationSets.V1 | (history && asked && Granted ? DataOperations.HistoryRead : DataOperations.None),
new HashSet<DataValueKind> { DataValueKind.Double }, Limits, false, 0, "c", true, true, true, true, true,
new HashSet<DataValueKind> { DataValueKind.Double }, BatchItems is { } b ? Limits with { MaxBatchItems = b } : Limits, false, 0, "c", true, true, true, true, true,
history && asked ? Caps : null));
message = caps;
}
@@ -263,6 +460,11 @@ public sealed class GrpcDataHistoryClientTests
var bytes = await request.Content!.ReadAsByteArrayAsync(token);
var wire = W.HistoryReadRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray());
LastBudgetTimeout = TimeSpan.FromTicks(wire.Budget.TimeoutTicks);
if (!wire.ReleaseContinuations) lock (CallSizes) CallSizes.Add(wire.Items.Count);
var dataCall = wire.ReleaseContinuations ? 0 : Interlocked.Increment(ref DataCalls);
if (EnforceAdmission && !wire.ReleaseContinuations && wire.Items.Count > wire.Budget.MaxBytes / 256)
return Status(Grpc.Core.StatusCode.InvalidArgument);
if (dataCall != 0 && dataCall == HangOnDataCall) await Task.Delay(Timeout.Infinite, token);
var response = new W.HistoryReadResponse { Serving = DataProtoMapper.EncodeServing(Serving) };
if (!wire.ReleaseContinuations && call > 1 && FailAfterFirst is { } later)
{
@@ -271,7 +473,7 @@ public sealed class GrpcDataHistoryClientTests
}
if (wire.ReleaseContinuations)
{
foreach (var item in wire.Items) Released.Add(item.Continuation.ToByteArray());
lock (Released) foreach (var item in wire.Items) Released.Add(item.Continuation.ToByteArray());
foreach (var item in wire.Items) response.Items.Add(new W.HistoryReadResult { CorrelationId = item.CorrelationId });
}
else
@@ -281,12 +483,13 @@ public sealed class GrpcDataHistoryClientTests
{
var key = item.CorrelationId;
int left;
lock (_chunkLeft) left = _chunkLeft[key] = item.HasContinuation && _chunkLeft.TryGetValue(key, out var l) && l > 0 ? l - 1 : Chunks - 1;
lock (_chunkLeft) left = _chunkLeft[key] = item.HasContinuation && _chunkLeft.TryGetValue(key, out var l) && l > 0 ? l - 1
: (ChunksByItem.TryGetValue(key, out var c) ? c : Chunks) - 1;
using var s1 = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 1.0), 0, DateTimeOffset.UnixEpoch, null);
using var s2 = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 2.0), 0, null, null);
var result = new DataHistoryReadResult(key, 0, [s1, s2], left > 0 ? [7, 7] : PageToken, null, left > 0);
response.Items.Add(DataHistoryProtoMapper.EncodeResult(result));
if (Malformed) response.Items[^1].CorrelationId = "not-" + key;
if (Malformed || dataCall >= MalformedFromDataCall) response.Items[^1].CorrelationId = "not-" + key;
}
}
message = response;
@@ -7,6 +7,8 @@ using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")]
@@ -131,7 +133,8 @@ internal sealed class LocalDataFixture : IDisposable
Func<DataAuthenticatedContext, DataTarget, IDataSubscriptionService>? targetSubscriptions = null,
bool advanceAuthority = false, string role = "Primary", long servingGeneration = 0, bool nestedCatalog = false, bool nestedUnsCatalog = false,
Func<DataAuthenticatedContext, IDataWriteService>? writes = null, bool denyReadExport = false,
ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1")
ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1",
IOriginHistoryPort? history = null, DataValueKind rawValueKind = DataValueKind.Int32, int maxBatchItems = 100)
{
if (clock is not null) Clock = clock;
Serving = Serving with { NodeId = servingNode, Incarnation = servingIncarnation, Role = role, ServingGeneration = servingGeneration };
@@ -158,8 +161,9 @@ internal sealed class LocalDataFixture : IDisposable
Context = new("peer", key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key), Clock.GetUtcNow().AddMinutes(10), Authority.Current.GenerationId);
var operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe;
if (denyReadExport) operations &= ~DataOperations.Read;
if (history is not null) operations |= DataOperations.HistoryRead;
var rootMetadata = new DataMetadata(Root, "Plant", "Folder", DataValueKind.Null, -1, [], false, operations, 1, null, null, false);
var rawMetadata = new DataMetadata(Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true, operations, 1, Ticket.Key.StableSourceId, "rpm", false);
var rawMetadata = new DataMetadata(Raw, "Speed", "Variable", rawValueKind, -1, [], true, operations, 1, Ticket.Key.StableSourceId, "rpm", false);
var unsMetadata = rawMetadata with { View = Uns };
var folder = Root with { Address = Root.Address with { Identifier = "Plant/Driver" }, Subject = "Plant/Driver" };
var unsRoot = Uns with { Address = Uns.Address with { Identifier = "Area" }, Subject = "Area" };
@@ -188,11 +192,11 @@ internal sealed class LocalDataFixture : IDisposable
Catalog = new LocalExportCatalog("cluster", Serving, Activation.CaptureAuthority(), nodes,
[new() { DataExportId = "raw-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "RawFolder", RootEntityId = "folder", PrincipalId = "peer", AllowedOperations = operations },
new() { DataExportId = "uns-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = nestedUnsCatalog ? "UnsArea" : "UnsTagReference", RootEntityId = nestedUnsCatalog ? "area" : "reference", PrincipalId = "peer", AllowedOperations = operations }]);
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
var limits = new DataLimits(100, maxBatchItems, 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, writes: writes, subscriptions: subscriptions,
targetSubscriptions: targetSubscriptions);
targetSubscriptions: targetSubscriptions, history: history);
}
internal IDataConnection Connection() => Services.Create(Context, new(DataTargetMode.Node, "cluster", Serving.NodeId));
@@ -0,0 +1,54 @@
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;
/// <summary>
/// H3 — the resume rule of a consumer Remote cursor: it resumes only under the caller, mapping revision, deployed
/// connection, projection generation, origin view and serving identity it was issued under. A mapping revision change,
/// a failover / origin restart (serving node, incarnation, generation or role), a projection rebuild or another caller
/// ⇒ the cursor never resumes (<c>BadContinuationPointInvalid</c>, origin token released).
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H3")]
public sealed class GrpcDataProjectedHistoryCursorTests
{
private static readonly DataView View = new(new DataAddress("origin", "urn:raw", "string", "Plant/Speed"), DataRealm.Raw, null, 0, "Plant/Speed");
private static readonly DataMetadata Metadata = new(View, "Speed", "Tag", DataValueKind.Int32, -1, [], false,
DataOperations.Read | DataOperations.HistoryRead, 1, null, null, false, History: new DataHistoryInfo(true));
private static readonly ProjectedHistoryTarget Issued = new("map", 3, "link", Metadata, new ServingIdentity("node-a", "boot-1", "Primary", 5, 6, 2), 7);
private const string Caller = "peer\0key\0v1";
private static readonly Dictionary<string, (ProjectedHistoryTarget Now, string Caller)> ChangeMap = new()
{
["mapping revision change"] = (Issued with { MappingRevision = 4 }, Caller),
["another mapping"] = (Issued with { MappingId = "other" }, Caller),
["another connection"] = (Issued with { ConnectionId = "link-2" }, Caller),
["projection rebuild"] = (Issued with { ProjectionGeneration = 8 }, Caller),
["failover to the pair member"] = (Issued with { Serving = Issued.Serving with { NodeId = "node-b" } }, Caller),
["origin restart"] = (Issued with { Serving = Issued.Serving with { Incarnation = "boot-2" } }, Caller),
["serving generation bump"] = (Issued with { Serving = Issued.Serving with { ServingGeneration = 3 } }, Caller),
["role change"] = (Issued with { Serving = Issued.Serving with { Role = "Secondary" } }, Caller),
["another origin view"] = (Issued with { OriginMetadata = Metadata with { View = View with { Subject = "Plant/Other" } } }, Caller),
["another caller"] = (Issued, "intruder\0key\0v1"),
["a rotated credential"] = (Issued, "peer\0key\0v2"),
};
[Fact]
public void The_same_binding_resumes_even_when_only_the_catalog_or_authority_epoch_moved()
{
ProjectedHistoryAccess.CursorMatches(Issued, Caller, Issued, Caller).ShouldBeTrue();
// A metadata renewal or ACL redeploy at the origin moves epochs, not the serving identity the token is bound to
// (the origin itself still refuses a token its own history epoch no longer matches).
ProjectedHistoryAccess.CursorMatches(Issued, Caller,
Issued with { Serving = Issued.Serving with { CatalogEpoch = 9, AuthorityEpoch = 9 } }, Caller).ShouldBeTrue();
}
public static TheoryData<string> Changes => new(ChangeMap.Keys);
[Theory]
[MemberData(nameof(Changes))]
public void Any_binding_change_refuses_the_resume(string change) =>
ProjectedHistoryAccess.CursorMatches(Issued, Caller, ChangeMap[change].Now, ChangeMap[change].Caller).ShouldBeFalse(change);
}
@@ -1,39 +0,0 @@
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
/// <summary>
/// H2 review 7: <c>DataOperationPolicy</c> now maps OPC UA HistoryRead to the mapping's HistoryRead bit, so a mapped
/// HistoryRead is AUTHORISABLE before H3 projects history. Pin that a projected node with the mapping bit AND a local
/// HistoryRead grant still answers a clean refusal — never data, never a fault — until H3.
/// </summary>
[Fact(Timeout = 90000)]
[Trait("Phase", "H2")]
public async Task HistoryRead_on_a_projected_node_stays_a_clean_refusal_until_H3()
{
using var origin = new LocalDataFixture(servingGeneration: 1);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var details = new ReadRawModifiedDetails
{
StartTime = DateTime.UtcNow.AddHours(-1), EndTime = DateTime.UtcNow, NumValuesPerNode = 10,
IsReadModified = false, ReturnBounds = false,
};
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = anchor }], TestContext.Current.CancellationToken);
var result = response.Results.ToArray()!.Single();
// Pinned: the projected variable carries no HistoryRead access-level bit, so the SDK refuses before any history code.
result.StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
(result.HistoryData.IsNull || ExtensionObject.ToEncodeable(result.HistoryData) is not HistoryData { DataValues.Count: > 0 })
.ShouldBeTrue("no data is served from a projected node before H3");
result.ContinuationPoint.IsEmpty.ShouldBeTrue();
}, localPermissions: 15, allowHistory: true);
}
}
@@ -0,0 +1,743 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
using SdkDataValue = Opc.Ua.DataValue;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// H3 — a real consumer OPC UA session HistoryReads a projected node through the real projection stack
/// (<see cref="ProjectedDataAccess"/> + <see cref="ProjectedHistoryAccess"/>) and a real in-process origin
/// (<see cref="LocalDataServices"/> over a real <see cref="OtOpcUaNodeManager"/> history port and its
/// <c>PeerHistoryContinuationStore</c>). Replaces the H2 pin that a projected node refused HistoryRead "until H3".
/// </summary>
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
private static readonly DateTime HistoryT0 = new(2026, 11, 20, 10, 0, 0, DateTimeKind.Utc);
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
[Trait("Phase", "H2")] // replaces the H2 pin "a projected node refuses HistoryRead until H3"
public async Task Granted_projected_HistoryRead_is_served_verbatim_and_pages_to_completion_through_the_origin()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new PersistentConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var values = new List<SdkDataValue>();
var cp = default(ByteString);
var pages = 0;
do
{
var result = await RawHistory(client, anchor, 3, cp);
StatusCode.IsGood(result.StatusCode).ShouldBeTrue(result.StatusCode.ToString());
values.AddRange(Values(result));
cp = result.ContinuationPoint;
pages++;
} while (!cp.IsEmpty && pages < 10);
values.Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe(Enumerable.Range(0, 7).Cast<object?>());
values.Select(v => v.SourceTimestamp.ToDateTime()).ShouldBe(Enumerable.Range(0, 7).Select(i => HistoryT0.AddSeconds(i)));
pages.ShouldBe(3);
origin.Services.HistoryOpenContinuations.ShouldBe(0, "a page-through to completion leaves nothing open at the origin");
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
[Trait("Phase", "H2")] // replaces the H2 pin "a projected node refuses HistoryRead until H3"
public async Task Without_the_local_HistoryRead_grant_on_the_mapping_scope_it_is_BadUserAccessDenied_and_unsent()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var result = await RawHistory(client, anchor, 3, default);
result.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
result.ContinuationPoint.IsEmpty.ShouldBeTrue();
originServer.Source.Calls.ShouldBe(0);
}, localPermissions: 7, allowHistory: true, connectionSource: new PersistentConnections(origin));
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task Consumer_session_close_releases_the_origin_continuations()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
ProjectedHistoryAccess? history = null;
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var page = await RawHistory(client, anchor, 2, default);
page.ContinuationPoint.IsEmpty.ShouldBeFalse();
origin.Services.HistoryOpenContinuations.ShouldBe(1);
await session.CloseAsync(TestContext.Current.CancellationToken);
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
origin.Services.HistoryOpenContinuations.ShouldBe(0, "the SDK disposed the Remote point and the release reached the origin");
history!.ReleaseCallsForTests.ShouldBe(1);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin),
onHistory: (h, _) => history = h);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task ReleaseContinuationPoints_forwards_one_release_and_the_point_is_then_invalid()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
ProjectedHistoryAccess? history = null;
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var page = await RawHistory(client, anchor, 2, default);
origin.Services.HistoryOpenContinuations.ShouldBe(1);
var released = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(2)), TimestampsToReturn.Both, true,
[new HistoryReadValueId { NodeId = anchor, ContinuationPoint = page.ContinuationPoint }], TestContext.Current.CancellationToken);
StatusCode.IsGood(released.Results[0].StatusCode).ShouldBeTrue();
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
origin.Services.HistoryOpenContinuations.ShouldBe(0);
var resumed = await RawHistory(client, anchor, 2, page.ContinuationPoint);
resumed.StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), onHistory: (h, _) => history = h);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task A_resume_after_lease_expiry_or_an_origin_rebuild_epoch_bump_is_invalid_and_a_fresh_read_succeeds()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new PersistentConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
// Lease expiry / redeployment: the deployed connection (route) is replaced — its tokens never resume.
var page = await RawHistory(client, anchor, 2, default);
connections.Rotate();
(await RawHistory(client, anchor, 2, page.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
var fresh = await RawHistory(client, anchor, 2, default);
StatusCode.IsGood(fresh.StatusCode).ShouldBeTrue();
// Origin rebuild: its history epoch moves (a removal), so the origin itself refuses the resumed token.
originServer.BumpEpoch();
(await RawHistory(client, anchor, 2, fresh.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
StatusCode.IsGood((await RawHistory(client, anchor, 2, default)).StatusCode).ShouldBeTrue();
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task Uncapped_raw_returns_the_origin_continuation_and_aggregates_are_refused_both_ways()
{
await using var originServer = await HistoryOrigin.StartAsync(25, maxRawPerRead: 10);
originServer.Source.Aggregates = new HashSet<HistoryAggregateType> { HistoryAggregateType.Average };
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
// NumValuesPerNode = 0: the origin pages at its ceiling and the consumer hands back its continuation (Part 11).
var uncapped = await RawHistory(client, anchor, 0, default);
StatusCode.IsGood(uncapped.StatusCode).ShouldBeTrue();
uncapped.ContinuationPoint.IsEmpty.ShouldBeFalse();
Values(uncapped).Count.ShouldBeLessThan(25);
// The origin refuses an aggregate its backend does not serve.
var refused = await ProcessedHistory(client, anchor, ObjectIds.AggregateFunction_Count);
refused.StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
// The consumer refuses an aggregate it cannot name, unsent.
var calls = originServer.Source.Calls;
var unknown = await ProcessedHistory(client, anchor, new NodeId("no-such-aggregate", 1));
unknown.StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
originServer.Source.Calls.ShouldBe(calls);
// A served aggregate passes through.
var average = await ProcessedHistory(client, anchor, ObjectIds.AggregateFunction_Average);
StatusCode.IsGood(average.StatusCode).ShouldBeTrue(average.StatusCode.ToString());
// Found by the H3 live gate (H02): an aggregate's value has ITS OWN type (a Double Average of an Int32 node),
// never the node's — it must not be refused BadTypeMismatch against the catalog's value kind.
var interval = Values(average).ShouldHaveSingleItem();
StatusCode.IsGood(interval.StatusCode).ShouldBeTrue(interval.StatusCode.ToString());
SdkValueBoundary.ToClr(interval.WrappedValue).ShouldBeOfType<double>().ShouldBe(3.0);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin));
}
[Theory(Timeout = 90000)]
[Trait("Phase", "H3")]
[InlineData(1_000_000, 3)]
[InlineData(25_000, 2)] // ≈ 288 B a value × 40 per node: two nodes fit, the third is refused
[InlineData(15_000, 1)]
[InlineData(1_200, 0)]
public async Task The_per_request_assembly_budget_is_shared_across_the_batch(int budget, int expectedGood)
{
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2);
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var children = (await BrowseAll(client, anchor, 10))
.Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
children.Length.ShouldBe(3);
var details = new ReadAtTimeDetails { ReqTimes = Enumerable.Range(0, 40).Select(i => (DateTimeUtc)HistoryT0.AddSeconds(i)).ToArray() };
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false,
children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken);
var results = response.Results.ToArray()!;
var statuses = results.Select(r => r.StatusCode.Code).ToArray();
statuses.Count(s => StatusCode.IsGood(s)).ShouldBe(expectedGood, string.Join(",", statuses.Select(x => x.ToString("X8"))));
foreach (var r in results.Where(r => !StatusCode.IsGood(r.StatusCode)))
{
r.StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
Values(r).ShouldBeEmpty("never a partial answer under an error status");
}
foreach (var r in results.Where(r => StatusCode.IsGood(r.StatusCode))) Values(r).Count.ShouldBe(40);
// The budget is consumed in request order: once a node does not fit, every later node is refused too.
statuses.TakeWhile(x => StatusCode.IsGood(x)).Count().ShouldBe(expectedGood);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin),
configureMapping: m => m.MaxHistoryAssemblyBytesPerRequest = budget);
}
[Theory(Timeout = 90000)]
[Trait("Phase", "H3")]
[InlineData(false)]
[InlineData(true)]
public async Task Historizing_and_the_HistoryRead_bit_follow_the_mapping_grant_and_never_HistoryWrite(bool granted)
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither,
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.Historizing },
new ReadValueId { NodeId = anchor, AttributeId = Attributes.AccessLevel }], TestContext.Current.CancellationToken);
read.Results[0].WrappedValue.TryGetValue(out bool historizing).ShouldBeTrue();
historizing.ShouldBe(granted);
read.Results[1].WrappedValue.TryGetValue(out byte level).ShouldBeTrue();
((level & AccessLevels.HistoryRead) != 0).ShouldBe(granted);
(level & AccessLevels.HistoryWrite).ShouldBe((byte)0);
if (granted) return;
var result = await RawHistory(client, anchor, 3, default);
result.StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
originServer.Source.Calls.ShouldBe(0);
}, localPermissions: 15, allowHistory: granted, connectionSource: new PersistentConnections(origin));
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task A_Float32_node_whose_backend_returns_Double_reads_Good_through_the_projection_as_it_does_locally()
{
// H3 review: SQL backends store every float as a Double. The origin port normalises Raw / AtTime to the node's type
// (Single) before the wire, so the projected rows are Good Singles — never a BadTypeMismatch per row while local works.
await using var originServer = await HistoryOrigin.StartAsync(5, dataType: "Float", value: i => i + 0.5);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port, rawValueKind: DataValueKind.Float);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var raw = await RawHistory(client, anchor, 0, default);
StatusCode.IsGood(raw.StatusCode).ShouldBeTrue(raw.StatusCode.ToString());
var values = Values(raw);
values.Count.ShouldBe(5);
values.ShouldAllBe(v => StatusCode.IsGood(v.StatusCode));
values.Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe(Enumerable.Range(0, 5).Select(i => (object?)(float)(i + 0.5)));
var details = new ReadAtTimeDetails { ReqTimes = [(DateTimeUtc)HistoryT0.AddSeconds(2)] };
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = anchor }], TestContext.Current.CancellationToken);
var atTime = Values(response.Results.ToArray()!.Single()).ShouldHaveSingleItem();
StatusCode.IsGood(atTime.StatusCode).ShouldBeTrue(atTime.StatusCode.ToString());
SdkValueBoundary.ToClr(atTime.WrappedValue).ShouldBeOfType<float>().ShouldBe(2.5f);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin));
}
[Theory(Timeout = 90000)]
[Trait("Phase", "H3")]
[InlineData(HistoryMode.Hang)]
[InlineData(HistoryMode.Throw)]
public async Task A_history_call_that_never_answers_or_faults_fails_only_the_projected_half_and_releases_its_cursor(HistoryMode mode)
{
// H3 review D1: a deadline during the connection's capability probe used to escape as an RpcException and fault the
// whole HistoryRead. Now the projected half fails per node (BadTimeout when the deadline fired), the local half of the
// same batch is served, and the claimed origin cursor is released (positive control: the origin store returns to 0).
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new HistorySwitchConnections(origin);
ProjectedHistoryAccess? history = null;
OtOpcUaNodeManager? manager = null;
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
manager!.HistorianDataSource = new SeriesSource(Enumerable.Range(0, 3)
.Select(i => new DataValueSnapshot(i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray());
manager.EnsureVariable("Plant/LocalH", "Plant", "LocalH", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "local");
var local = manager.TryGetVariable("Plant/LocalH", AddressSpaceRealm.Raw)!.NodeId;
var page = await RawHistory(client, anchor, 2, default);
page.ContinuationPoint.IsEmpty.ShouldBeFalse();
origin.Services.HistoryOpenContinuations.ShouldBe(1);
connections.Mode = mode;
manager.HistoryReadDeadline = TimeSpan.FromSeconds(1);
var response = await client.HistoryReadAsync(new RequestHeader { TimeoutHint = 20_000 }, new ExtensionObject(RawDetails(2)),
TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = local }, new HistoryReadValueId { NodeId = anchor, ContinuationPoint = page.ContinuationPoint }],
TestContext.Current.CancellationToken);
var results = response.Results.ToArray()!;
StatusCode.IsGood(results[0].StatusCode).ShouldBeTrue("the local half of the batch is still served");
Values(results[0]).Count.ShouldBe(2);
results[1].StatusCode.Code.ShouldBe(mode == HistoryMode.Hang ? StatusCodes.BadTimeout.Code : StatusCodes.BadContinuationPointInvalid.Code);
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
origin.Services.HistoryOpenContinuations.ShouldBe(0, "the claimed cursor's origin continuation was released");
}, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, m) => { history = h; manager = m; });
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task A_group_larger_than_the_origin_batch_is_split_into_sub_batches()
{
// H3 review D4: three projected nodes against an origin that admits two items per request.
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2);
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port, maxBatchItems: 2);
var connections = new HistorySwitchConnections(origin) { BatchItems = 2 };
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
children.Length.ShouldBe(3);
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false,
children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken);
var results = response.Results.ToArray()!;
results.ShouldAllBe(r => StatusCode.IsGood(r.StatusCode));
results.ShouldAllBe(r => Values(r).Count == 3);
connections.HistoryCallSizes.ShouldBe([2, 1]);
foreach (var r in results) await RawHistory(client, children[Array.IndexOf(results, r)], 3, r.ContinuationPoint);
// H3 review round 2: the batch size is the deployed connection's own — no separate capability probe (a cancelled
// probe put the gRPC connection into discovery backoff).
var before = Volatile.Read(ref connections.CapabilityCalls);
await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false,
children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken);
Volatile.Read(ref connections.CapabilityCalls).ShouldBe(before, "a projected history read sends no capability probe");
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task The_assembly_budget_is_charged_in_request_order_across_groups()
{
// H3 review D7: request [A fresh, B resumed, C fresh] runs as two groups ({A, C} then {B}); with room for two nodes the
// refused one must be C — the last in REQUEST order — not B.
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2);
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
children.Length.ShouldBe(3);
var first = await RawHistory(client, children[1], 3, default);
first.ContinuationPoint.IsEmpty.ShouldBeFalse();
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = children[0] }, new HistoryReadValueId { NodeId = children[1], ContinuationPoint = first.ContinuationPoint },
new HistoryReadValueId { NodeId = children[2] }], TestContext.Current.CancellationToken);
var results = response.Results.ToArray()!;
StatusCode.IsGood(results[0].StatusCode).ShouldBeTrue(results[0].StatusCode.ToString());
StatusCode.IsGood(results[1].StatusCode).ShouldBeTrue("the resumed node is second in request order: it fits");
results[2].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
Values(results[2]).ShouldBeEmpty();
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin),
configureMapping: m => m.MaxHistoryAssemblyBytesPerRequest = 2 * 3 * 288 + 100); // ≈ 288 B a value: two 3-value nodes fit
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task Releases_queued_while_a_flush_is_finishing_are_never_lost()
{
// H3 review D6: the flush used to be re-armed from Task.IsCompleted, so a token queued after its last check but before it
// completed waited for the NEXT release — or forever. Many concurrent enqueues must all reach the connection.
await using var originServer = await HistoryOrigin.StartAsync(1);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new HistorySwitchConnections(origin);
ProjectedHistoryAccess? history = null;
await WithComposedServer(origin, origin.Raw, async (_, _, _, _, _, _, _) =>
{
const int count = 2000;
await Task.WhenAll(Enumerable.Range(0, 8).Select(t => Task.Run(() =>
{
for (var i = t; i < count; i += 8) history!.EnqueueReleaseForTests("link", BitConverter.GetBytes(i));
})));
var deadline = DateTime.UtcNow.AddSeconds(20);
while (connections.ReleasedTokens < count && DateTime.UtcNow < deadline)
{
await history!.FlushReleasesForTestsAsync();
await Task.Delay(10, TestContext.Current.CancellationToken);
}
connections.ReleasedTokens.ShouldBe(count);
}, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, _) => history = h);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task A_retired_lease_is_not_a_timeout_and_a_fault_mid_answer_releases_the_new_origin_token()
{
// H3 review round 2 (5): a cancel that is neither the caller's nor the deadline (a lease retired by a redeploy) is
// BadContinuationPointInvalid for a resume / BadNoCommunication for a fresh node — never BadTimeout.
// (4): an exception mid-answer leaves no new origin token behind (positive control: the origin store returns to 0).
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new HistorySwitchConnections(origin);
ProjectedHistoryAccess? history = null;
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var page = await RawHistory(client, anchor, 2, default);
connections.Mode = HistoryMode.Retired;
(await RawHistory(client, anchor, 2, page.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
(await RawHistory(client, anchor, 2, default)).StatusCode.Code.ShouldBe(StatusCodes.BadNoCommunication.Code);
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
origin.Services.HistoryOpenContinuations.ShouldBe(0);
connections.Mode = HistoryMode.Poison;
(await RawHistory(client, anchor, 2, default)).StatusCode.Code.ShouldBe(StatusCodes.BadNoCommunication.Code);
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
origin.Services.HistoryOpenContinuations.ShouldBe(0, "the new origin token of the faulted answer was released");
}, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, _) => history = h);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task Once_the_connection_reports_the_assembly_budget_spent_no_further_origin_call_is_made()
{
// H3 review round 2 (3): [A fresh, B resumed] is two calls; when the first comes back budget-refused, B is refused unsent.
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 1);
using var origin = new LocalDataFixture(additionalRawNodes: 1, servingGeneration: 1, history: originServer.Port);
var connections = new HistorySwitchConnections(origin);
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
var first = await RawHistory(client, children[1], 3, default);
connections.Mode = HistoryMode.BudgetRefused;
var calls = connections.HistoryCallSizes.Count;
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = children[0] }, new HistoryReadValueId { NodeId = children[1], ContinuationPoint = first.ContinuationPoint }],
TestContext.Current.CancellationToken);
response.Results.ToArray()!.ShouldAllBe(r => r.StatusCode.Code == StatusCodes.BadTooManyOperations.Code);
(connections.HistoryCallSizes.Count - calls).ShouldBe(1, "the second run is refused unsent");
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task A_bad_answer_to_a_resume_releases_the_prior_origin_cursor()
{
// H3 review round 3 nit (b): the connection answered the resume Bad without sending it — the origin still holds page 1's
// cursor; the consumer releases it (positive control: the store returns to 0).
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new HistorySwitchConnections(origin);
ProjectedHistoryAccess? history = null;
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var page = await RawHistory(client, anchor, 2, default);
origin.Services.HistoryOpenContinuations.ShouldBe(1);
connections.Mode = HistoryMode.RefuseResumedUnsent;
(await RawHistory(client, anchor, 2, page.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadNoCommunication.Code);
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
origin.Services.HistoryOpenContinuations.ShouldBe(0, "the unconsumed prior cursor was released");
connections.Mode = HistoryMode.Pass;
}, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, _) => history = h);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task An_origins_budget_refusal_is_a_per_node_answer_and_never_stops_the_request()
{
// H3 review round 3 (S4): the stop keys on the consumer's typed marker, not on "budget" in the diagnostic — the origin's
// "remainder budget is full" refusal of A must not refuse B (sent in the next run) nor a Good answer after it.
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 1);
using var origin = new LocalDataFixture(additionalRawNodes: 1, servingGeneration: 1, history: originServer.Port);
var connections = new HistorySwitchConnections(origin);
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
var first = await RawHistory(client, children[1], 3, default);
connections.Mode = HistoryMode.OriginRefusedFresh;
var calls = connections.HistoryCallSizes.Count;
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = children[0] }, new HistoryReadValueId { NodeId = children[1], ContinuationPoint = first.ContinuationPoint }],
TestContext.Current.CancellationToken);
var results = response.Results.ToArray()!;
results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code, "the origin refused A");
StatusCode.IsGood(results[1].StatusCode).ShouldBeTrue("B is still read: an origin refusal is not a spent consumer budget");
Values(results[1]).Count.ShouldBeGreaterThan(0);
(connections.HistoryCallSizes.Count - calls).ShouldBe(2, "both runs are sent");
connections.Mode = HistoryMode.Pass;
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
}
// ------------------------------------------------------------------------------------------------------------------
private static ReadRawModifiedDetails RawDetails(uint count) => new()
{
StartTime = HistoryT0.AddSeconds(-1), EndTime = HistoryT0.AddHours(1), NumValuesPerNode = count, IsReadModified = false, ReturnBounds = false,
};
private static async Task<Opc.Ua.HistoryReadResult> RawHistory(SessionClient client, NodeId node, uint count, ByteString cp)
{
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(count)), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = node, ContinuationPoint = cp }], TestContext.Current.CancellationToken);
return response.Results.ToArray()!.Single();
}
private static async Task<Opc.Ua.HistoryReadResult> ProcessedHistory(SessionClient client, NodeId node, NodeId aggregate)
{
var details = new ReadProcessedDetails
{
StartTime = HistoryT0, EndTime = HistoryT0.AddMinutes(1), ProcessingInterval = 10_000, AggregateType = [aggregate],
AggregateConfiguration = new AggregateConfiguration { UseServerCapabilitiesDefaults = true },
};
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = node }], TestContext.Current.CancellationToken);
return response.Results.ToArray()!.Single();
}
private static IReadOnlyList<SdkDataValue> Values(Opc.Ua.HistoryReadResult result) =>
result.HistoryData.IsNull || ExtensionObject.ToEncodeable(result.HistoryData) is not HistoryData data ? [] : data.DataValues.ToArray() ?? [];
private static async Task AwaitReleases(ProjectedHistoryAccess history, Func<bool> done)
{
for (var i = 0; i < 200 && !done(); i++)
{
await history.FlushReleasesForTestsAsync();
if (!done()) await Task.Delay(10, TestContext.Current.CancellationToken);
}
}
public enum HistoryMode { Pass, Hang, Throw, Retired, Poison, BudgetRefused, OriginRefusedFresh, RefuseResumedUnsent }
/// <summary>
/// One long-lived origin connection whose HISTORY path can be switched to never answer (then fault as a cancelled gRPC call,
/// as a probe cancelled by its deadline did) or to fault at once; releases always pass through and are counted.
/// </summary>
private sealed class HistorySwitchConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
{
private IDataConnection? _inner;
private readonly object _gate = new();
private int _released;
private readonly List<int> _sizes = [];
public HistoryMode Mode { get; set; }
/// <summary>The deployed connection's own batch size the lease reports.</summary>
public int? BatchItems { get; set; }
public int CapabilityCalls;
public int ReleasedTokens => Volatile.Read(ref _released);
public IReadOnlyList<int> HistoryCallSizes { get { lock (_sizes) return _sizes.ToArray(); } }
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken)
{
if (connectionId != "link") return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null);
lock (_gate) _inner ??= peer.Connection();
return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Borrowed(new Switch(_inner, this), _gate));
}
private sealed class Borrowed(IDataConnection connection, object route) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public object? RouteIdentity => route;
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
private sealed class Switch(IDataConnection inner, HistorySwitchConnections owner) : IDataConnection, IDataHistoryService, IHistoryBatchLimit
{
public int MaxHistoryBatchItems => owner.BatchItems ?? ProjectedHistoryAccess.DefaultBatchItems;
public DataTarget Target => inner.Target;
public TimeProvider Clock => inner.Clock;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken)
{
Interlocked.Increment(ref owner.CapabilityCalls);
return inner.GetCapabilitiesAsync(budget, cancellationToken);
}
public Task<DataBrowseBranch> BrowseAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken cancellationToken) => inner.BrowseAsync(request, cancellationToken);
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => inner.GetMetadataAsync(request, cancellationToken);
public Task<IReadOnlyList<ReadResult>> ReadAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest request, CancellationToken cancellationToken) => inner.ReadAsync(request, cancellationToken);
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken);
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
public async Task<IReadOnlyList<DataHistoryReadResult>> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken)
{
lock (owner._sizes) owner._sizes.Add(request.Items.Count);
switch (owner.Mode)
{
case HistoryMode.Hang:
try { await Task.Delay(Timeout.Infinite, cancellationToken); }
catch (OperationCanceledException ex)
{ throw new Grpc.Core.RpcException(new Grpc.Core.Status(Grpc.Core.StatusCode.Cancelled, "probe cancelled", ex)); }
break;
case HistoryMode.Throw:
throw new Grpc.Core.RpcException(new Grpc.Core.Status(Grpc.Core.StatusCode.Internal, "boom"));
case HistoryMode.Retired:
// A deployment lease retired by a redeploy: its scope token cancels, not the caller's.
throw new OperationCanceledException("lease retired");
case HistoryMode.BudgetRefused:
return request.Items.Select(i => new DataHistoryReadResult(i.CorrelationId, 0x80100000u, [], null,
"History assembly budget exceeded.") { ConsumerBudgetRefused = true }).ToArray();
case HistoryMode.RefuseResumedUnsent when request.Items.Any(i => i.Continuation is not null):
// Answered Bad without the origin ever seeing the resume: its cursor is still open there.
return request.Items.Select(i => new DataHistoryReadResult(i.CorrelationId, 0x80310000u, [], null)).ToArray();
case HistoryMode.OriginRefusedFresh when request.Items.All(i => i.Continuation is null):
// The ORIGIN's own refusal, whose text also mentions a budget (LocalDataServices.History).
return request.Items.Select(i => new DataHistoryReadResult(i.CorrelationId, 0x80100000u, [], null,
"Origin history remainder budget is full; retry with a lower NumValuesPerNode.")).ToArray();
}
var answers = await ((IDataHistoryService)inner).ReadAsync(request, cancellationToken);
if (owner.Mode == HistoryMode.Poison)
foreach (var answer in answers) if (answer.Samples.Count > 0) answer.Samples[^1].Dispose(); // faults the reader mid-answer
return answers;
}
public async Task ReleaseAsync(IReadOnlyList<byte[]> continuations, CancellationToken cancellationToken)
{
Interlocked.Add(ref owner._released, continuations.Count);
await ((IDataHistoryService)inner).ReleaseAsync(continuations, cancellationToken);
}
}
}
/// <summary>One long-lived origin connection, as a deployed gRPC connection is; <see cref="Rotate"/> replaces it (a redeploy).</summary>
private sealed class PersistentConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
{
private (IDataConnection Connection, object Route)? _current;
private readonly object _gate = new();
public void Rotate()
{
lock (_gate)
{
if (_current is { } old) _ = old.Connection.DisposeAsync();
_current = null;
}
}
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken)
{
if (connectionId != "link") return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null);
lock (_gate)
{
_current ??= (peer.Connection(), new object());
return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Borrowed(_current.Value.Connection, _current.Value.Route));
}
}
private sealed class Borrowed(IDataConnection connection, object route) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public object? RouteIdentity => route;
public ValueTask DisposeAsync() => ValueTask.CompletedTask; // non-owning, like a deployment lease
}
}
/// <summary>A real origin node manager with a historized raw <c>Plant/Driver/Device/Speed</c> behind a real history port.</summary>
private sealed class HistoryOrigin : IAsyncDisposable
{
private readonly OpcUaApplicationHost _host;
private readonly string _pki;
private readonly OtOpcUaNodeManager _nm;
public SeriesSource Source { get; }
public OriginHistoryPort Port { get; }
private HistoryOrigin(OpcUaApplicationHost host, string pki, OtOpcUaNodeManager nm, SeriesSource source)
{ _host = host; _pki = pki; _nm = nm; Source = source; Port = new OriginHistoryPort(nm); }
public static async Task<HistoryOrigin> StartAsync(int samples, int maxRawPerRead = 0, int extra = 0, string dataType = "Int32",
Func<int, object>? value = null)
{
var pki = Path.Combine(Path.GetTempPath(), $"h3-origin-{Guid.NewGuid():N}");
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "H3Origin", ApplicationUri = $"urn:h3-origin:{Guid.NewGuid():N}", OpcUaPort = port,
PublicHostname = "127.0.0.1", PkiStoreRoot = pki, EnabledSecurityProfiles = [OpcUaSecurityProfile.None],
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
var nm = started.Server.NodeManager!;
var source = new SeriesSource(Enumerable.Range(0, samples)
.Select(i => new DataValueSnapshot(value?.Invoke(i) ?? i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray()) { MaxRawValuesPerRead = maxRawPerRead };
nm.HistorianDataSource = source;
nm.EnsureVariable("Plant/Driver/Device/Speed", null, "Speed", dataType, false, AddressSpaceRealm.Raw, historianTagname: "speed");
nm.EnsureVariable("Plant/Driver/Device/Other", null, "Other", "Int32", false, AddressSpaceRealm.Raw);
for (var i = 0; i < extra; i++)
nm.EnsureVariable("Plant/Driver/Device/Speed" + i, null, "Speed" + i, "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed" + i);
return new HistoryOrigin(started.Host, pki, nm, source);
}
public void BumpEpoch() => _nm.RemoveVariableNode("Plant/Driver/Device/Other", AddressSpaceRealm.Raw).ShouldBeTrue();
public async ValueTask DisposeAsync()
{
await _host.DisposeAsync();
if (Directory.Exists(_pki)) try { Directory.Delete(_pki, recursive: true); } catch (IOException) { }
}
}
private sealed class SeriesSource(IReadOnlyList<DataValueSnapshot> series) : IHistorianDataSource
{
private int _calls;
public int Calls => Volatile.Read(ref _calls);
public int MaxRawValuesPerRead { get; init; }
public IReadOnlySet<HistoryAggregateType> Aggregates { get; set; } = HistoryAggregateTypes.All;
public IReadOnlySet<HistoryAggregateType> SupportedAggregates => Aggregates;
public bool SupportsReverseRaw => true;
public Task<HistorianRead> ReadRawAsync(string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode,
CancellationToken cancellationToken)
{
Interlocked.Increment(ref _calls);
IEnumerable<DataValueSnapshot> window = startUtc <= endUtc
? series.Where(s => s.SourceTimestampUtc >= startUtc && s.SourceTimestampUtc < endUtc)
: series.Where(s => s.SourceTimestampUtc <= startUtc && s.SourceTimestampUtc > endUtc).Reverse();
return Task.FromResult(new HistorianRead((maxValuesPerNode == 0 ? window : window.Take((int)maxValuesPerNode)).ToList(), null));
}
public Task<HistorianRead> ReadProcessedAsync(string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
HistoryAggregateType aggregate, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _calls);
return Task.FromResult(new HistorianRead([new DataValueSnapshot(3.0, 0, startUtc, startUtc)], null));
}
public Task<HistorianRead> ReadAtTimeAsync(string fullReference, IReadOnlyList<DateTime> timestampsUtc, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _calls);
return Task.FromResult(new HistorianRead(timestampsUtc.Select(t => series.LastOrDefault(s => s.SourceTimestampUtc <= t)
?? new DataValueSnapshot(null, 0x809B0000u, t, t)).Select(s => s with { SourceTimestampUtc = s.SourceTimestampUtc }).ToList(), null));
}
public Task<HistoricalEventsResult> ReadEventsAsync(
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, CancellationToken cancellationToken) =>
Task.FromResult(new HistoricalEventsResult(Array.Empty<HistoricalEvent>(), null));
public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot();
public void Dispose() { }
}
}