diff --git a/docs/plans/2026-11-15-grpc-data-connections-implementation-plan.md b/docs/plans/2026-11-15-grpc-data-connections-implementation-plan.md
index 5d96bdc4e..3e17d8778 100644
--- a/docs/plans/2026-11-15-grpc-data-connections-implementation-plan.md
+++ b/docs/plans/2026-11-15-grpc-data-connections-implementation-plan.md
@@ -10,7 +10,7 @@
---
-Status: Astra reviewed; approved for user implementation-plan review after revision. Awaiting user review. This task prepares a plan only; it does not authorize implementation, builds, running fixtures or deployment.
+Status: Astra-reviewed plan; user has authorized implementation with the specified subagents and gates. Execution is in progress on `codex/grpc-data-connections`; see [execution ledger](evidence/grpc-data/README.md). Remote deployment/push/merge remains outside this implementation request.
Design: [reviewed design](2026-11-15-grpc-data-connections-design.md). Design review: [Astra design findings](2026-11-15-grpc-data-connections-astra-review.md). Plan review: [Astra implementation-plan review](2026-11-15-grpc-data-connections-plan-astra-review.md).
diff --git a/docs/plans/evidence/grpc-data/README.md b/docs/plans/evidence/grpc-data/README.md
index cf9bd0abc..989edf70e 100644
--- a/docs/plans/evidence/grpc-data/README.md
+++ b/docs/plans/evidence/grpc-data/README.md
@@ -16,8 +16,8 @@ The [implementation plan](../../2026-11-15-grpc-data-connections-implementation-
| Phase | Scope | Status | Evidence |
|---|---|---|---|
| P00 | Unit discovery isolation and execution controls | Passed | 22 Python runner units after Astra correction; 2 C# guard units, zero failures/skips; clean phase run `20261116T020813.843515Z-2ebe0fbcb7d2` |
-| P01 | Domain/protobuf contracts | In progress | Domain-contract worker next; codec follows frozen types |
-| P02 | Schema/artifact/consumer projection | Pending | |
+| P01 | Domain/protobuf contracts | Passed; Astra freeze approved | 15 domain + 36 wire tests, zero failures/skips; run `20261116T024814.318745Z-3a06bbb5af5e` |
+| P02 | Schema/artifact/consumer projection | In progress | Schema/validator worker next; artifact projection follows entity freeze |
| P03 | Shared authorization and leases | Pending | |
| P04 | Immutable publication, hub and local ports | Pending | |
| P05 | Mutation tickets/outcomes | Pending | |
@@ -58,3 +58,13 @@ Runtime artifacts belong under ignored `artifacts/grpc-data/`; this tracked ledg
## P00 verification
The runner tests first failed as expected while `run-unit-phase.py` was absent. After initial implementation, 18 fake-subprocess Python units passed. Astra found required existing regression classes were not enforced as strictly as new classes; four added regression tests failed before the correction. The final 22 Python tests passed, with red/green logs in `artifacts/grpc-data/p00-runner-regressions/`. The real P00 discovery/execution runner passed both counting-probe/reaper C# tests with no skips; the starting production graph compiled successfully. No solution test run or Docker mutation occurred. Raw TRX/commands/discovery identities remain in ignored artifacts. The runner validates discovery AND executed results for every required new class, retains parameterized class filters, and sanitizes both child environments. Astra approved P00 after the required-existing-class correction; see [checkpoint review](p00-astra-review.md).
+
+## P03 preparation obligations
+
+Read-only security preparation confirmed that caller-supplied `DataView.Subject` is a claim, never an ACL authority. P03 resolves subject/provenance against the active deployed catalog before either Raw/UNS fallback or cache lookup, and strictly caller-bound facades carry authenticated principal/key/version/original expiry. Revalidate the current key principal and credential version as well as expiry even without an authority-generation change. Deep-copy mutable authority inputs before publishing security snapshots. Failed desired-authority staging must close new mapped/data access rather than retain stale permissions. These obligations supplement the planned spoofed-subject, queued expiry, same-ID credential replacement, deep-copy mutation, and failed/empty apply tests; they are not yet implemented.
+
+## P01 verification and frozen contracts
+
+Test-first domain/protocol changes and targeted review regressions produced recorded failures before correction. Final P01 run `20261116T024814.318745Z-3a06bbb5af5e` passed 15 Core.Abstractions and 36 Commons tests, including named existing protocol regressions, with no failures or skips. No broad unit or integration suite was run. [Astra checkpoint](p01-astra-review.md) approves P01 freeze only after cluster identity, original credential identity, array metadata, receiver-owned aggregate decoding, per-value element limits, pinned stream provenance, additive negotiation and structural/descriptor corrections.
+
+The frozen facade is caller-bound through `IDataConnectionFactory` and `DataAuthenticatedContext`; no authenticated identity comes from protobuf claims. `DataWriteAdmission` retains original key/version/expiry. Capabilities carry cluster identity and independently advertised array-element limits. Compact and fallback stream decoding require expected serving identity. Array/byte storage uses defensive managed copies and separate disposable leases; pooling is deferred. Post-parse budget checks do not substitute for the P07 transport parse/decompression or P11 measured-memory gates.
diff --git a/docs/plans/evidence/grpc-data/p01-astra-review.md b/docs/plans/evidence/grpc-data/p01-astra-review.md
new file mode 100644
index 000000000..e40eb05a6
--- /dev/null
+++ b/docs/plans/evidence/grpc-data/p01-astra-review.md
@@ -0,0 +1,108 @@
+# P01 Astra contract-freeze review
+
+Date: 2026-11-15 (America/Indiana/Indianapolis)
+Scope: initial and corrected frozen P01 Task 2/3 working candidates based on `c3abd468211bf1c8202708447e84df9a2d90bd3f`; the five Core.Abstractions data-connection files, the new protobuf/service registration, mapper and value codec, and the four new test classes. Candidate file digests are recorded in phase runs `20261116T022304.446452Z-4dfc62e5c9c2` and `20261116T023911.320464Z-fa7c2928e3f6`.
+
+**Disposition after follow-up: revisions required; H2 and M5 remain open, and final green evidence is pending.** H1, H3, M1, M2, and M3 are resolved in the corrected candidate. M4's source correction is sound, with its test-name casing fix awaiting passing evidence. This review does not approve later phases or the completed feature. The reviewer inspected source and existing run evidence only; no build or test was executed, and only this review document was edited.
+
+The review uses the [implementation plan](../../2026-11-15-grpc-data-connections-implementation-plan.md), [design](../../2026-11-15-grpc-data-connections-design.md), and preceding design/plan findings. Source line numbers below refer to the reviewed candidate, before corrective edits.
+
+## Follow-up assessment
+
+The complete corrected source and tests were reread. The following table supersedes the original finding statuses where stated; original explanations remain below for traceability.
+
+| Finding | Follow-up assessment |
+|---|---|
+| H1 | Resolved: required `DataCapabilities.ClusterId` is encoded/decoded and validated; capability round-trip and empty cluster identity tests cover it. Configured expected-cluster comparison remains a P07 selector obligation. |
+| H2 | Partially resolved: receiver-owned `DataDecodeLimits`, aggregate typed-value accounting, collection-count checks, and read/write/metadata response helpers are present. `DecodeMetadata` checks the fixed 16-dimension ceiling before `ToArray`. Remaining gaps and evidence requests are below. |
+| H3 | Resolved: both compact/fallback value decoders require validated `expectedServing`, compare every sample/batch against it, and check ack-handle stream/epoch consistency. Regression cases cover changed incarnation, fallback node mismatch, and another ack epoch. Runtime control/reset transitions must supply the correctly updated context; they are not implicitly accepted by the codec. |
+| M1 | Resolved: array element kind is preserved and validated in both directions; positive and malformed array metadata tests passed in the follow-up run. |
+| M2 | Resolved: framing/write item counts and value-element counts are separate parameters. A positive `MaxValueElements` is advertised with an explicit backward default. One-item/100-element write and compact/fallback cases passed. |
+| M3 | Resolved: known value kinds/operation bits are intersected, unknown compact version falls back, and major mismatch still rejects. The corresponding capability test passed. |
+| M4 | Source correction complete: stable explicit domain values, full existing-field descriptor assertions, service signatures, and hash invariance/change tests are present. The second run failed only because the generated wire enum uses `Uint8` while the test parsed `UInt8` case-sensitively. The reviewed `ignoreCase: true` correction needs successful execution before closing this evidence item. |
+| M5 | Partially resolved: identities, ready epochs, samples, settings, negotiated limits, top-level command/frame generations, and lease duration are checked; sub-tick timestamp precision is rejected explicitly. The residual cases below still pass through the decode boundary. |
+
+### H2 residual work
+
+`DataProtoMapper.DecodeBrowseRequest` still has no receiver limits or preflight, unlike the other operation envelopes (corrected source lines 743–749). An arbitrarily large filter/continuation/view within the transport's separate ceiling can therefore bypass a stricter receiver decode budget. Add the same receiver-owned boundary to this entry point.
+
+The generic preflight now estimates decoded cost as `encoded * 2 + count * 256 + 128` plus typed-value cost (lines 25–47). This is meaningfully stronger than the initial code, but its constants and the assumption that nested object graphs fit inside the per-item allowance are not documented or pinned by boundary tests. Do not treat it as a measured heap bound. The fixed dimension check prevents unbounded metadata-dimension copies, but the suite still needs valid maximal-rank metadata nested in browse/metadata-result envelopes, strict-budget/over-count response cases, and an oversized browse request. Establish and document the accounting invariant for nested view/address/metadata/ID/list overhead and test both sides of its rejection threshold. Transport parsing/decompression remains explicitly outside this post-parse accounting.
+
+### M5 residual work
+
+- `DataView.Validate` still permits `MappingId = null` with a positive `MappingRevision`.
+- `DecodeWriteRequest` still admits empty operation ID/expected serving incarnation and nonpositive catalog revision/remaining budget without structural validation. Validate these before allocating/returning owned values.
+- `DecodeControlOrAck` still copies negative control catalog/authority epochs, negative partition IDs, and negative watermark versions into domain controls. Define permitted zero values explicitly, then reject negative/illegal values.
+- Remove-command handles are individually validated but are not checked against their enclosing command's subscription ID and stream epoch. Apply the same cross-envelope consistency already added for acknowledgments.
+
+These are transport/domain structure checks. They do not replace P03 authorization or P05 live role/catalog/deadline revalidation. Likewise, `DataView.Subject` remains a caller-supplied claim copied by the mapper. P03 must resolve the authoritative subject from the active catalog and authenticated principal/key, and reject a spoofed claim; no P01 type or codec makes that string authoritative. Carry this explicit negative test into P03.
+
+## H1 — Preserve the expected cluster identity through capabilities
+
+**Severity: High. Status: resolved in follow-up.** Originally, `CapabilitiesResponse.cluster_id` existed at wire field 10, but `DataCapabilities` had no cluster identity (`DataContracts.cs:113–114`). `DataProtoMapper.EncodeCapabilities` never wrote that field and `DecodeCapabilities` discarded it (`DataProtoMapper.cs:743–803`). `ServingIdentity` supplies node/incarnation, not cluster. Thus the normal domain-to-wire-to-domain capabilities path could not supply the information required to verify `DataTarget.ExpectedClusterId` before node/cluster selection. An identity check added only to raw gRPC messages would also leave the transport-neutral path inconsistent.
+
+**Correction:** Add required serving-cluster identity to the domain capabilities contract, preserve and structurally validate it in both directions, and require the later connection selector to compare it with the configured target. Add round-trip, empty-identity, and wrong-target identity tests at the responsible boundary. Keep origin ownership and serving-node/incarnation distinct.
+
+## H2 — Enforce receiver-owned aggregate decode budgets before collection allocation
+
+**Severity: High. Status: open.** `DecodeWriteRequest` checks aggregate encoded size, then independently decodes every value with the entire `maxBytes` allowance (`DataProtoMapper.cs:559–585`). It never sums decoded storage, so several individually small values can collectively exceed the batch's decoded budget. For example, two byte values each accepted by the per-value decoded limit can fit the encoded envelope while their combined copies exceed that limit.
+
+Other exposed collection decoders have no receiver-owned count/byte parameters and allocate with `ToArray`/`List` directly: read requests (529–538), metadata requests (617–618), subscription commands (270–308), browse responses (642–659), and control/ack frames (858–901). Payload-supplied `Budget` is validated only for positivity and is not an independent receiver limit. Compact/fallback value-frame accounting covers typed values but does not account for their per-item domain samples/list entries or other decoded frame state. A wire-byte ceiling alone does not establish the decoded resource bound required by P01 and the design.
+
+**Correction:** Define a receiver-supplied decode-limit context and preflight each collection/envelope against its item, dimension/element, encoded-byte, and aggregate decoded-byte limits before constructing domain collections or owned values. Include surrounding per-item/envelope storage in the accounting. Apply it consistently to request, response, command, ack/control, and both value encodings; handle partial decode cleanup consistently. Transport parsing/decompression ceilings remain separate P07 ingress obligations and must not be claimed as covered by these post-parse helpers.
+
+**Regression evidence required:** A multi-value write whose encoded envelope fits but aggregate decoded storage does not; over-count read/metadata/add/control/ack envelopes; compact and fallback envelopes that exceed decoded storage while fitting wire bytes; and boundary-sized valid messages. Tests should demonstrate rejection at preflight, not after creating every domain item.
+
+## H3 — Bind decoded stream handles to the serving incarnation
+
+**Severity: High. Status: resolved in follow-up.** Originally, compact decoding verified the handle's stream ID, epoch, and item revision but accepted whatever `Serving` the incoming batch claimed (`DataProtoMapper.cs:336–364`). The handle context had no expected serving node/incarnation. Fallback decoding likewise accepted each sample's independent serving identity, including a frame mixing different nodes (`454–509`). The encoder's compact-only mixed-provenance check did not protect a consumer from an invalid peer frame. Consequently, the same valid handle/epoch could accept samples from another node or restarted incarnation, contrary to design §6's pinned stream and fresh-epoch requirement.
+
+**Correction:** Carry expected serving-node/incarnation identity in the stream decode context or handle bindings and enforce it in compact and fallback paths. Check handle/frame epoch consistency for acknowledgments as well. Permit catalog/authority transitions only through the specified control/reset behavior; do not equate arbitrary epoch changes with a new serving incarnation. Add tests for a different node, a changed incarnation, mixed fallback provenance, and mismatched ack handles, alongside valid compact/fallback equivalence.
+
+## M1 — Complete the array metadata mapper correction
+
+**Severity: Medium. Status: resolved in follow-up; initially reproduced by the phase gate.** The earlier Task 2 finding added `DataMetadata.ArrayElementKind` and protobuf field 13, but `EncodeMetadata` did not assign it and `DecodeMetadata` did not read it or call `DataMetadata.Validate` (`DataProtoMapper.cs:178–218`). Empty integer and string arrays therefore lost their distinct type metadata. The new `Array_metadata_preserves_element_kind_even_for_empty_arrays` test failed at its element-kind assertion.
+
+**Correction:** Preserve field presence and element kind in both directions and validate the completed metadata. Retain the existing positive regression and add missing/unknown element kind, nested/unsupported element kind, and scalar-with-array-kind rejection cases. Validate rank/dimension structure together with the type information rather than allowing contradictory metadata into the projection layer.
+
+## M2 — Separate frame item limits from typed-array element limits
+
+**Severity: Medium. Status: resolved in follow-up.** Originally, `DecodeCompact` passed frame `maxItems` into `TypedValueCodec.Decode` as `maxElements` (line 357); fallback did the same through `DecodeSample` (line 494), and writes repeated it at line 572. These are distinct quantities. A permitted one-item batch carrying a 100-element array failed with `maxItems = 1`, even when the array was supported and fit its element/byte limits. The original standalone array codec test did not exercise the framing paths.
+
+**Correction:** Give value array elements their own receiver limit and pass it independently from the count of read/write/stream items. Advertise the limit where peers need it for admission. Add successful one-item/multi-element round trips for writes, compact, and fallback, plus independent rejection at each limit.
+
+## M3 — Negotiate additive capabilities without rejecting a compatible peer
+
+**Severity: Medium. Status: resolved in follow-up.** Originally, `DecodeCapabilities` called `DataContractValidation.Required` on every advertised value kind (`DataProtoMapper.cs:780–782`). A newer peer on the same protocol major advertising an additional unknown kind alongside supported kinds therefore failed the entire handshake. The design requires unsupported capabilities to become unavailable individually while supported operations remain usable. Unknown values in an actual typed payload should still reject; capability advertisement is a different boundary.
+
+**Correction:** Define explicit same-major intersection/fallback behavior for unknown advertised value kinds, operation bits, and compact versions. Preserve major-version rejection and do not silently accept an unknown actual payload. Add old/new peer capability tests with both known and unknown kinds, an unsupported compact version falling back, and a major mismatch. The current unknown-protobuf-field preservation test does not cover this negotiation behavior.
+
+## M4 — Freeze all wire decisions and compatibility-sensitive descriptors
+
+**Severity: Medium. Status: source corrected; final passing evidence pending.** Originally, most wire decisions were bare `int32` fields populated by casts from implicitly numbered C# enums (`DataContracts.cs:3–8`). Inserting a status/write/control enum member could silently renumber deployed meanings. `DataConnectionProtoContract.Validate` pinned only three field numbers and the zero `ValueKind`; the test added one compact timestamp field. Most field numbers, wire types, oneofs, enum values, operation bits, and service request/response signatures were consequently outside the promised contract lock.
+
+**Correction:** Assign explicit stable values to every wire-visible decision and pin the complete message/service/enum contract with a descriptor snapshot or equivalent comprehensive assertions. Protobuf enums are preferable for self-describing decisions; explicit domain-number assertions are required if `int32` remains deliberate. Reserve removed numbers/names. Keep evolution tests additive: adding fields/capabilities must not authorize renumbering existing ones. Add write-payload-hash tests proving correlation/remaining-budget independence and changes for value/address/semantic preconditions; those critical hash invariants currently have no test despite `WritePayloadHash` being implemented.
+
+## M5 — Define and enforce malformed envelope invariants at decode boundaries
+
+**Severity: Medium. Status: open.** Required enum validation is present in several paths, but the domain constructors/decoders otherwise accept structurally invalid state. Examples include empty node/incarnation and arbitrary epochs from `DecodeServing` (70–74), negative negotiated capacity values from `DecodeCapabilities` (790–800), and command/frame IDs, epochs, timeouts, and sequence values copied without validation. `DecodeSettings` accepts nonfinite deadband values without defining their meaning; `DecodeBrowseResponse` constructs a nonpositive lease without validating it. `DataView.Validate` also permits a positive mapping revision with no mapping ID. These values should not become apparently valid domain envelopes on which later admission and ordering code depends.
+
+**Correction:** Define shared structural validation for identities, generations, settings, limits, leases, and required command/frame fields, then invoke it consistently on both mapping paths. Document any deliberately allowed sentinel values such as zero sampling before enforcing them; distinguish such protocol semantics from unsupported policy requests. Reject malformed known decisions and illegal combinations before later services consume them. Add focused negative cases for the examples above and full request/response/command round trips for all six services. Timestamp tests should cover nonzero subsecond precision and establish the policy for protobuf precision finer than the domain's ticks.
+
+## Evidence and coverage limits
+
+The completed phase run `20261116T022304.446452Z-4dfc62e5c9c2` records the candidate SHA, tracked diff hash, and per-untracked-file hashes. Core.Abstractions executed 9 tests, all passed, with zero skips; its expected new and existing classes were verified. Commons executed 21 tests: 20 passed, 1 failed, zero skipped. The failure is the array metadata regression above; `run.json` correctly reports the phase as failed. No whole-solution or integration result is inferred.
+
+The follow-up phase run `20261116T023911.320464Z-fa7c2928e3f6` also records the candidate digests and correctly reports failure. Core.Abstractions executed 13 tests, all passed, zero skipped. Commons executed 33 tests: 32 passed, one failed, zero skipped. The only failure was the generated `UInt8`/`Uint8` enum-name casing in the new contract-number test; the new metadata, aggregate-write/count, serving-context, independent-array-limit, capability, timestamp, and hash cases passed. The reviewer inspected `run.json` and the failure log directly. The casing correction was read in source but has no passing result in this review's evidence yet.
+
+The initial candidate's new tests cover enum validation examples, explicit write-outcome classification, optional timestamps, copied input bytes, request-start lease timing, handle revisions, scalar/array codec examples, one compact absence override, one stale handle, one mixed compact encoding case, control/ack round trips, and a small golden/unknown-field payload. They do not yet establish the aggregate budgets, complete service envelope mappings, expected serving provenance, operation hash, or additive negotiation required by this checkpoint.
+
+## Reviewed strengths and earlier findings
+
+- The direct API composes browse/metadata/read/write/subscription without actor, OPC UA SDK, generated gRPC, or channel types. The service descriptor defines the six planned methods, with bidirectional subscription streaming. Existing mesh/telemetry proto registrations are unchanged.
+- The Task 2 admission correction now separates stable principal from authenticated `ApiKeyId` and optional credential expiry. The contract explicitly requires checking the original credential at dispatch even when the authority epoch is unchanged. Actual P03/P05 revalidation and expiry behavior remain later gates.
+- `DataValue` copies input bytes, array elements, and dimensions; supported scalar elements are immutable. `Retain` creates a separate disposal state, and getters do not expose the private mutable byte/array storage. This is a managed-copy implementation, not evidence of pooled payload release or bounded retained memory under hub/stream load. Add independent-lease disposal tests as ownership behavior develops.
+- Full unsigned status codes, UInt64 values, null versus empty byte/array values, original optional timestamps, and explicit uncertain/unconfirmed write outcomes are represented. Compact timestamp override messages can express inherited, explicitly absent, and explicitly present values. The compact encoder refuses mixed provenance within a batch, and both decoders reject unknown/removed handle revisions.
+- The hash implementation omits transport correlation and remaining budget and includes the value/view and incarnation/catalog preconditions. Its missing regression coverage is called out in M4. No automatic retry or transport behavior is introduced by these contract files.
+
+The residual H2/M5 work and final focused green evidence are required before the P01 freeze is approved. Later runtime policy, queue ordering, revocation, ingress authentication, Docker, scaling, and final-suite gates remain outstanding.
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs
new file mode 100644
index 000000000..491d0e028
--- /dev/null
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs
@@ -0,0 +1,1225 @@
+using Google.Protobuf;
+using Google.Protobuf.WellKnownTypes;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
+using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
+
+namespace ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
+
+/// Receiver-owned post-parse limits; transport must separately bound decompression and parsing.
+public sealed record DataDecodeLimits(
+ int MaxItems = 1000,
+ int MaxBytes = 4 * 1024 * 1024,
+ int MaxValueElements = 100000
+)
+{
+ public void Validate()
+ {
+ if (MaxItems <= 0 || MaxBytes <= 0 || MaxValueElements <= 0)
+ throw new ArgumentOutOfRangeException(nameof(MaxItems));
+ }
+}
+
+/// Maps the explicit transport envelope to owned domain values.
+public static class DataProtoMapper
+{
+ private static void Preflight(
+ IMessage message,
+ int count,
+ DataDecodeLimits? limits,
+ IEnumerable? values = null
+ )
+ {
+ limits ??= new DataDecodeLimits();
+ limits.Validate();
+ int encoded = message.CalculateSize();
+ if (count < 0 || count > limits.MaxItems || encoded > limits.MaxBytes)
+ throw new ArgumentException("Envelope exceeds receiver limits.");
+ long decoded = (long)encoded * 2 + (long)count * 256 + 128;
+ if (values is not null)
+ foreach (var value in values)
+ {
+ decoded += TypedValueCodec.DecodedBytes(value, limits.MaxBytes - decoded);
+ if (decoded > limits.MaxBytes)
+ throw new ArgumentException("Decoded envelope exceeds receiver limits.");
+ }
+ if (decoded > limits.MaxBytes)
+ throw new ArgumentException("Decoded envelope exceeds receiver limits.");
+ }
+
+ private static void ValidateFrame(string id, long epoch, long sequence)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(id);
+ if (epoch <= 0 || sequence <= 0)
+ throw new ArgumentOutOfRangeException(nameof(epoch));
+ }
+
+ public static W.Address EncodeAddress(DataAddress x)
+ {
+ x.Validate();
+ return new()
+ {
+ OriginClusterId = x.OriginClusterId,
+ NamespaceUri = x.NamespaceUri,
+ IdentifierKind = x.IdentifierKind,
+ Identifier = x.Identifier,
+ };
+ }
+
+ public static DataAddress DecodeAddress(W.Address x)
+ {
+ ArgumentNullException.ThrowIfNull(x);
+ var v = new DataAddress(x.OriginClusterId, x.NamespaceUri, x.IdentifierKind, x.Identifier);
+ v.Validate();
+ return v;
+ }
+
+ public static W.View EncodeView(DataView x)
+ {
+ x.Validate();
+ var v = new W.View
+ {
+ Address = EncodeAddress(x.Address),
+ Realm = (int)x.Realm,
+ MappingRevision = x.MappingRevision,
+ Subject = x.Subject,
+ };
+ if (x.MappingId is not null)
+ v.MappingId = x.MappingId;
+ return v;
+ }
+
+ public static DataView DecodeView(W.View x)
+ {
+ ArgumentNullException.ThrowIfNull(x);
+ var v = new DataView(
+ DecodeAddress(x.Address),
+ (DataRealm)x.Realm,
+ x.HasMappingId ? x.MappingId : null,
+ x.MappingRevision,
+ x.Subject
+ );
+ v.Validate();
+ return v;
+ }
+
+ public static W.Serving EncodeServing(ServingIdentity x) =>
+ new()
+ {
+ NodeId = x.NodeId,
+ Incarnation = x.Incarnation,
+ Role = x.Role,
+ CatalogEpoch = x.CatalogEpoch,
+ AuthorityEpoch = x.AuthorityEpoch,
+ };
+
+ public static ServingIdentity DecodeServing(W.Serving x)
+ {
+ ArgumentNullException.ThrowIfNull(x);
+ var identity = new ServingIdentity(
+ x.NodeId,
+ x.Incarnation,
+ x.Role,
+ x.CatalogEpoch,
+ x.AuthorityEpoch
+ );
+ identity.Validate();
+ return identity;
+ }
+
+ public static W.Sample EncodeSample(DataSample x)
+ {
+ x.Validate();
+ var v = new W.Sample
+ {
+ Value = TypedValueCodec.Encode(x.Value),
+ StatusCode = x.StatusCode,
+ Serving = EncodeServing(x.Serving),
+ Version = x.Version,
+ };
+ if (x.SourceTimestampUtc is { } source)
+ v.SourceTimestamp = Timestamp.FromDateTimeOffset(source);
+ if (x.ServerTimestampUtc is { } server)
+ v.ServerTimestamp = Timestamp.FromDateTimeOffset(server);
+ return v;
+ }
+
+ public static DataSample DecodeSample(
+ W.Sample x,
+ int maxElements = TypedValueCodec.DefaultMaxElements,
+ int maxBytes = TypedValueCodec.DefaultMaxBytes
+ )
+ {
+ ArgumentNullException.ThrowIfNull(x);
+ var serving = DecodeServing(x.Serving);
+ var source = x.SourceTimestamp is null
+ ? (DateTimeOffset?)null
+ : TypedValueCodec.DecodeTimestamp(x.SourceTimestamp);
+ var server = x.ServerTimestamp is null
+ ? (DateTimeOffset?)null
+ : TypedValueCodec.DecodeTimestamp(x.ServerTimestamp);
+ if (x.Version <= 0)
+ throw new ArgumentException("Invalid sample version.");
+ serving.Validate(requireEpochs: true);
+ return new(
+ TypedValueCodec.Decode(x.Value, maxElements, maxBytes),
+ x.StatusCode,
+ source,
+ server,
+ serving,
+ x.Version
+ );
+ }
+
+ public static W.Budget EncodeBudget(DataBudget x)
+ {
+ x.Validate();
+ return new()
+ {
+ TimeoutTicks = x.Timeout.Ticks,
+ MaxItems = x.MaxItems,
+ MaxBytes = x.MaxBytes,
+ };
+ }
+
+ public static DataBudget DecodeBudget(W.Budget x)
+ {
+ ArgumentNullException.ThrowIfNull(x);
+ var v = new DataBudget(TimeSpan.FromTicks(x.TimeoutTicks), x.MaxItems, x.MaxBytes);
+ v.Validate();
+ return v;
+ }
+
+ public static W.Handle EncodeHandle(DataItemHandle x)
+ {
+ x.Validate();
+ return new()
+ {
+ SubscriptionId = x.SubscriptionId,
+ StreamEpoch = x.StreamEpoch,
+ Handle_ = x.Handle,
+ ItemRevision = x.ItemRevision,
+ };
+ }
+
+ public static DataItemHandle DecodeHandle(W.Handle x)
+ {
+ ArgumentNullException.ThrowIfNull(x);
+ var v = new DataItemHandle(x.SubscriptionId, x.StreamEpoch, x.Handle_, x.ItemRevision);
+ v.Validate();
+ return v;
+ }
+
+ public static W.Settings EncodeSettings(DataSubscriptionSettings x)
+ {
+ x.Validate();
+ var v = new W.Settings
+ {
+ SamplingTicks = x.SamplingInterval.Ticks,
+ PublishingTicks = x.PublishingInterval.Ticks,
+ Trigger = (int)x.Trigger,
+ };
+ if (x.Deadband is { } d)
+ v.Deadband = d;
+ return v;
+ }
+
+ public static DataSubscriptionSettings DecodeSettings(W.Settings x)
+ {
+ ArgumentNullException.ThrowIfNull(x);
+ var trigger = (DataChangeTrigger)x.Trigger;
+ DataContractValidation.Required(trigger);
+ var settings = new DataSubscriptionSettings(
+ TimeSpan.FromTicks(x.SamplingTicks),
+ TimeSpan.FromTicks(x.PublishingTicks),
+ trigger,
+ x.HasDeadband ? x.Deadband : null
+ );
+ settings.Validate();
+ return settings;
+ }
+
+ public static W.Metadata EncodeMetadata(DataMetadata x)
+ {
+ x.Validate();
+ var v = new W.Metadata
+ {
+ View = EncodeView(x.View),
+ BrowseName = x.BrowseName,
+ NodeKind = x.NodeKind,
+ ValueKind = (W.ValueKind)x.ValueKind,
+ ValueRank = x.ValueRank,
+ Writable = x.Writable,
+ AllowedOperations = (uint)x.AllowedOperations,
+ CatalogRevision = x.CatalogRevision,
+ IsStale = x.IsStale,
+ };
+ v.Dimensions.AddRange(x.Dimensions);
+ if (x.ArrayElementKind is { } elementKind)
+ v.ArrayElementKind = (W.ValueKind)elementKind;
+ if (x.StableSourceId is not null)
+ v.StableSourceId = x.StableSourceId;
+ if (x.EngineeringUnits is not null)
+ v.EngineeringUnits = x.EngineeringUnits;
+ return v;
+ }
+
+ public static DataMetadata DecodeMetadata(W.Metadata x)
+ {
+ ArgumentNullException.ThrowIfNull(x);
+ if (x.Dimensions.Count > TypedValueCodec.MaxDimensions)
+ throw new ArgumentException("Too many dimensions.");
+ Preflight(x, 1, null);
+ var kind = (DataValueKind)x.ValueKind;
+ DataContractValidation.Required(kind);
+ var metadata = new DataMetadata(
+ DecodeView(x.View),
+ x.BrowseName,
+ x.NodeKind,
+ kind,
+ x.ValueRank,
+ x.Dimensions.ToArray(),
+ x.Writable,
+ (DataOperations)x.AllowedOperations,
+ x.CatalogRevision,
+ x.HasStableSourceId ? x.StableSourceId : null,
+ x.HasEngineeringUnits ? x.EngineeringUnits : null,
+ x.IsStale,
+ x.HasArrayElementKind ? (DataValueKind)x.ArrayElementKind : null
+ );
+ metadata.Validate();
+ return metadata;
+ }
+
+ public static W.SubscriptionItem EncodeSubscriptionItem(DataSubscriptionItem x) =>
+ new()
+ {
+ ClientItemId = x.ClientItemId,
+ View = EncodeView(x.View),
+ Settings = EncodeSettings(x.Settings),
+ };
+
+ public static DataSubscriptionItem DecodeSubscriptionItem(W.SubscriptionItem x) =>
+ new(x.ClientItemId, DecodeView(x.View), DecodeSettings(x.Settings));
+
+ public static W.SubscriptionCommand EncodeCommand(DataSubscriptionCommand x)
+ {
+ var v = new W.SubscriptionCommand
+ {
+ SubscriptionId = x.SubscriptionId,
+ StreamEpoch = x.StreamEpoch,
+ CommandId = x.CommandId,
+ AcknowledgementTimeoutTicks = x.AcknowledgementTimeout.Ticks,
+ };
+ switch (x)
+ {
+ case OpenSubscription o:
+ v.Open = new W.Open
+ {
+ WatchCatalogOnly = o.WatchCatalogOnly,
+ SessionLifetimeTicks = o.SessionLifetime.Ticks,
+ SnapshotBudget = EncodeBudget(o.SnapshotBudget),
+ };
+ v.Open.Items.AddRange(o.Items.Select(EncodeSubscriptionItem));
+ break;
+ case AddSubscriptionItems a:
+ v.Add = new W.ItemChanges();
+ v.Add.Items.AddRange(a.Items.Select(EncodeSubscriptionItem));
+ break;
+ case ModifySubscriptionItems m:
+ v.Modify = new W.ItemChanges();
+ v.Modify.Items.AddRange(m.Items.Select(EncodeSubscriptionItem));
+ break;
+ case RemoveSubscriptionItems r:
+ v.Remove = new W.HandleChanges();
+ v.Remove.Items.AddRange(r.Items.Select(EncodeHandle));
+ break;
+ default:
+ throw new ArgumentException("Unsupported command.");
+ }
+ return v;
+ }
+
+ public static DataSubscriptionCommand DecodeCommand(
+ W.SubscriptionCommand x,
+ DataDecodeLimits? limits = null
+ )
+ {
+ ArgumentNullException.ThrowIfNull(x);
+ var count = x.CommandCase switch
+ {
+ W.SubscriptionCommand.CommandOneofCase.Open => x.Open.Items.Count,
+ W.SubscriptionCommand.CommandOneofCase.Add => x.Add.Items.Count,
+ W.SubscriptionCommand.CommandOneofCase.Modify => x.Modify.Items.Count,
+ W.SubscriptionCommand.CommandOneofCase.Remove => x.Remove.Items.Count,
+ _ => 0,
+ };
+ Preflight(x, count, limits);
+ ArgumentException.ThrowIfNullOrWhiteSpace(x.SubscriptionId);
+ ArgumentException.ThrowIfNullOrWhiteSpace(x.CommandId);
+ if (x.StreamEpoch <= 0 || x.AcknowledgementTimeoutTicks <= 0)
+ throw new ArgumentException("Invalid command generation or timeout.");
+ if (
+ x.Open is { } open
+ && (open.SessionLifetimeTicks <= 0 || (open.WatchCatalogOnly && open.Items.Count != 0))
+ )
+ throw new ArgumentException("Invalid open subscription.");
+ if (x.Remove is { } remove)
+ foreach (var handle in remove.Items)
+ if (
+ handle.SubscriptionId != x.SubscriptionId
+ || handle.StreamEpoch != x.StreamEpoch
+ )
+ throw new ArgumentException("Removal handle belongs to another stream.");
+ var t = TimeSpan.FromTicks(x.AcknowledgementTimeoutTicks);
+ return x.CommandCase switch
+ {
+ W.SubscriptionCommand.CommandOneofCase.Open => new OpenSubscription(
+ x.SubscriptionId,
+ x.StreamEpoch,
+ x.CommandId,
+ t,
+ x.Open.Items.Select(DecodeSubscriptionItem).ToArray(),
+ x.Open.WatchCatalogOnly,
+ TimeSpan.FromTicks(x.Open.SessionLifetimeTicks),
+ DecodeBudget(x.Open.SnapshotBudget)
+ ),
+ W.SubscriptionCommand.CommandOneofCase.Add => new AddSubscriptionItems(
+ x.SubscriptionId,
+ x.StreamEpoch,
+ x.CommandId,
+ t,
+ x.Add.Items.Select(DecodeSubscriptionItem).ToArray()
+ ),
+ W.SubscriptionCommand.CommandOneofCase.Modify => new ModifySubscriptionItems(
+ x.SubscriptionId,
+ x.StreamEpoch,
+ x.CommandId,
+ t,
+ x.Modify.Items.Select(DecodeSubscriptionItem).ToArray()
+ ),
+ W.SubscriptionCommand.CommandOneofCase.Remove => new RemoveSubscriptionItems(
+ x.SubscriptionId,
+ x.StreamEpoch,
+ x.CommandId,
+ t,
+ x.Remove.Items.Select(DecodeHandle).ToArray()
+ ),
+ _ => throw new ArgumentException("Missing command."),
+ };
+ }
+
+ /// Decodes compact updates only for handles currently bound to this stream and revision.
+ public static DataSubscriptionValues DecodeCompact(
+ W.SubscriptionFrame frame,
+ IReadOnlyDictionary handles,
+ int maxItems,
+ int maxBytes,
+ ServingIdentity expectedServing,
+ int maxElements = TypedValueCodec.DefaultMaxElements
+ )
+ {
+ ArgumentNullException.ThrowIfNull(frame);
+ ArgumentNullException.ThrowIfNull(handles);
+ ArgumentNullException.ThrowIfNull(expectedServing);
+ expectedServing.Validate(requireEpochs: true);
+ var batch = frame.CompactValues ?? throw new ArgumentException("Compact batch required.");
+ ValidateFrame(frame.SubscriptionId, frame.StreamEpoch, frame.Sequence);
+ Preflight(
+ frame,
+ batch.Items.Count,
+ new DataDecodeLimits(maxItems, maxBytes, maxElements),
+ batch.Items.Select(i => i.Value)
+ );
+ if (
+ maxItems <= 0
+ || maxBytes <= 0
+ || batch.Items.Count > maxItems
+ || frame.CalculateSize() > maxBytes
+ )
+ throw new ArgumentException("Frame exceeds budget.");
+ long decodedBytes = 0;
+ foreach (var update in batch.Items)
+ {
+ decodedBytes += TypedValueCodec.DecodedBytes(update.Value, maxBytes - decodedBytes);
+ if (decodedBytes > maxBytes)
+ throw new ArgumentException("Decoded frame exceeds budget.");
+ }
+ var serving = DecodeServing(batch.Serving);
+ serving.Validate(requireEpochs: true);
+ if (serving != expectedServing)
+ throw new ArgumentException("Unexpected serving identity.");
+ var items = new List(batch.Items.Count);
+ try
+ {
+ foreach (var update in batch.Items)
+ {
+ if (
+ !handles.TryGetValue(update.Handle, out var handle)
+ || handle.SubscriptionId != frame.SubscriptionId
+ || handle.StreamEpoch != frame.StreamEpoch
+ || handle.ItemRevision != update.ItemRevision
+ )
+ throw new ArgumentException("Unknown or stale handle.");
+ handle.Validate();
+ if (update.Version <= 0)
+ throw new ArgumentException("Invalid sample version.");
+ var source = update.SourceTimestamp is null
+ ? batch.DefaultSourceTimestamp
+ : update.SourceTimestamp.Value;
+ var server = update.ServerTimestamp is null
+ ? batch.DefaultServerTimestamp
+ : update.ServerTimestamp.Value;
+ var sourceTime = source is null
+ ? (DateTimeOffset?)null
+ : TypedValueCodec.DecodeTimestamp(source);
+ var serverTime = server is null
+ ? (DateTimeOffset?)null
+ : TypedValueCodec.DecodeTimestamp(server);
+ var sample = new DataSample(
+ TypedValueCodec.Decode(update.Value, maxElements, maxBytes),
+ update.HasStatusCode ? update.StatusCode : batch.DefaultStatusCode,
+ sourceTime,
+ serverTime,
+ serving,
+ update.Version
+ );
+ items.Add(new DataSubscriptionValue(handle, sample));
+ }
+ return new DataSubscriptionValues(
+ frame.SubscriptionId,
+ frame.StreamEpoch,
+ frame.Sequence,
+ batch.IsSnapshot,
+ items
+ );
+ }
+ catch
+ {
+ foreach (var item in items)
+ item.Sample.Dispose();
+ throw;
+ }
+ }
+
+ public static W.SubscriptionFrame EncodeValues(
+ DataSubscriptionValues frame,
+ bool compactNegotiated
+ )
+ {
+ var result = new W.SubscriptionFrame
+ {
+ SubscriptionId = frame.SubscriptionId,
+ StreamEpoch = frame.StreamEpoch,
+ Sequence = frame.Sequence,
+ };
+ if (!compactNegotiated)
+ {
+ result.Values = new W.Values { IsSnapshot = frame.IsSnapshot };
+ foreach (var item in frame.Items)
+ result.Values.Items.Add(
+ new W.ValueUpdate
+ {
+ Handle = EncodeHandle(item.Handle),
+ Sample = EncodeSample(item.Sample),
+ }
+ );
+ return result;
+ }
+ if (frame.Items.Count == 0)
+ throw new ArgumentException("A compact batch requires provenance.");
+ var first = frame.Items[0].Sample;
+ result.CompactValues = new W.CompactValues
+ {
+ IsSnapshot = frame.IsSnapshot,
+ Serving = EncodeServing(first.Serving),
+ DefaultStatusCode = first.StatusCode,
+ };
+ if (first.SourceTimestampUtc is { } source)
+ result.CompactValues.DefaultSourceTimestamp = Timestamp.FromDateTimeOffset(source);
+ if (first.ServerTimestampUtc is { } server)
+ result.CompactValues.DefaultServerTimestamp = Timestamp.FromDateTimeOffset(server);
+ foreach (var item in frame.Items)
+ {
+ item.Handle.Validate();
+ item.Sample.Validate();
+ if (
+ item.Handle.SubscriptionId != frame.SubscriptionId
+ || item.Handle.StreamEpoch != frame.StreamEpoch
+ || item.Sample.Serving != first.Serving
+ )
+ throw new ArgumentException("Mixed stream or provenance in compact batch.");
+ var update = new W.CompactUpdate
+ {
+ Handle = item.Handle.Handle,
+ ItemRevision = item.Handle.ItemRevision,
+ Version = item.Sample.Version,
+ Value = TypedValueCodec.Encode(item.Sample.Value),
+ };
+ if (item.Sample.StatusCode != first.StatusCode)
+ update.StatusCode = item.Sample.StatusCode;
+ if (item.Sample.SourceTimestampUtc != first.SourceTimestampUtc)
+ {
+ update.SourceTimestamp = new W.TimestampOverride();
+ if (item.Sample.SourceTimestampUtc is { } s)
+ update.SourceTimestamp.Value = Timestamp.FromDateTimeOffset(s);
+ }
+ if (item.Sample.ServerTimestampUtc != first.ServerTimestampUtc)
+ {
+ update.ServerTimestamp = new W.TimestampOverride();
+ if (item.Sample.ServerTimestampUtc is { } s)
+ update.ServerTimestamp.Value = Timestamp.FromDateTimeOffset(s);
+ }
+ result.CompactValues.Items.Add(update);
+ }
+ return result;
+ }
+
+ public static DataSubscriptionValues DecodeValues(
+ W.SubscriptionFrame frame,
+ IReadOnlyDictionary handles,
+ int maxItems,
+ int maxBytes,
+ ServingIdentity expectedServing,
+ int maxElements = TypedValueCodec.DefaultMaxElements
+ )
+ {
+ ArgumentNullException.ThrowIfNull(expectedServing);
+ expectedServing.Validate(requireEpochs: true);
+ ValidateFrame(frame.SubscriptionId, frame.StreamEpoch, frame.Sequence);
+ if (frame.CompactValues is not null)
+ return DecodeCompact(frame, handles, maxItems, maxBytes, expectedServing, maxElements);
+ if (
+ frame.Values is null
+ || maxItems <= 0
+ || maxBytes <= 0
+ || frame.Values.Items.Count > maxItems
+ || frame.CalculateSize() > maxBytes
+ )
+ throw new ArgumentException("Invalid or oversized values frame.");
+ Preflight(
+ frame,
+ frame.Values.Items.Count,
+ new DataDecodeLimits(maxItems, maxBytes, maxElements),
+ frame.Values.Items.Select(i => i.Sample.Value)
+ );
+ long decodedBytes = 0;
+ foreach (var update in frame.Values.Items)
+ {
+ decodedBytes += TypedValueCodec.DecodedBytes(
+ update.Sample.Value,
+ maxBytes - decodedBytes
+ );
+ if (decodedBytes > maxBytes)
+ throw new ArgumentException("Decoded frame exceeds budget.");
+ }
+ var items = new List(frame.Values.Items.Count);
+ try
+ {
+ foreach (var item in frame.Values.Items)
+ {
+ var handle = DecodeHandle(item.Handle);
+ if (
+ handle.SubscriptionId != frame.SubscriptionId
+ || handle.StreamEpoch != frame.StreamEpoch
+ || !handles.TryGetValue(handle.Handle, out var expected)
+ || expected != handle
+ )
+ throw new ArgumentException("Unknown or stale handle.");
+ if (DecodeServing(item.Sample.Serving) != expectedServing)
+ throw new ArgumentException("Unexpected serving identity.");
+ items.Add(new(handle, DecodeSample(item.Sample, maxElements, maxBytes)));
+ }
+ return new(
+ frame.SubscriptionId,
+ frame.StreamEpoch,
+ frame.Sequence,
+ frame.Values.IsSnapshot,
+ items
+ );
+ }
+ catch
+ {
+ foreach (var item in items)
+ item.Sample.Dispose();
+ throw;
+ }
+ }
+
+ public static W.ReadRequest EncodeReadRequest(ReadRequest x)
+ {
+ var v = new W.ReadRequest { Budget = EncodeBudget(x.Budget) };
+ foreach (var item in x.Items)
+ {
+ var w = new W.ReadItem
+ {
+ CorrelationId = item.CorrelationId,
+ View = EncodeView(item.View),
+ };
+ if (item.MaximumAge is { } age)
+ w.MaximumAgeTicks = age.Ticks;
+ v.Items.Add(w);
+ }
+ return v;
+ }
+
+ public static ReadRequest DecodeReadRequest(W.ReadRequest x, DataDecodeLimits? limits = null)
+ {
+ Preflight(x, x.Items.Count, limits);
+ return new(
+ x.Items.Select(i => new ReadItem(
+ i.CorrelationId,
+ DecodeView(i.View),
+ i.HasMaximumAgeTicks ? TimeSpan.FromTicks(i.MaximumAgeTicks) : null
+ ))
+ .ToArray(),
+ DecodeBudget(x.Budget)
+ );
+ }
+
+ public static W.WriteRequest EncodeWriteRequest(WriteBatch x)
+ {
+ var v = new W.WriteRequest { Budget = EncodeBudget(x.Budget) };
+ foreach (var i in x.Items)
+ v.Items.Add(
+ new W.WriteItem
+ {
+ CorrelationId = i.CorrelationId,
+ OperationId = i.OperationId,
+ View = EncodeView(i.View),
+ Value = TypedValueCodec.Encode(i.Value),
+ ExpectedCatalogRevision = i.ExpectedCatalogRevision,
+ ExpectedServingIncarnation = i.ExpectedServingIncarnation,
+ RemainingBudgetTicks = i.RemainingBudget.Ticks,
+ }
+ );
+ return v;
+ }
+
+ public static WriteBatch DecodeWriteRequest(
+ W.WriteRequest x,
+ int maxItems,
+ int maxBytes,
+ int maxElements = TypedValueCodec.DefaultMaxElements
+ )
+ {
+ Preflight(
+ x,
+ x.Items.Count,
+ new DataDecodeLimits(maxItems, maxBytes, maxElements),
+ x.Items.Select(i => i.Value)
+ );
+ foreach (var item in x.Items)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(item.OperationId);
+ ArgumentException.ThrowIfNullOrWhiteSpace(item.ExpectedServingIncarnation);
+ if (item.ExpectedCatalogRevision <= 0 || item.RemainingBudgetTicks <= 0)
+ throw new ArgumentException("Invalid write preconditions.");
+ }
+ var items = new List();
+ try
+ {
+ foreach (var i in x.Items)
+ items.Add(
+ new(
+ i.CorrelationId,
+ i.OperationId,
+ DecodeView(i.View),
+ TypedValueCodec.Decode(i.Value, maxElements, maxBytes),
+ i.ExpectedCatalogRevision,
+ i.ExpectedServingIncarnation,
+ TimeSpan.FromTicks(i.RemainingBudgetTicks)
+ )
+ );
+ return new(items, DecodeBudget(x.Budget));
+ }
+ catch
+ {
+ foreach (var i in items)
+ i.Value.Dispose();
+ throw;
+ }
+ }
+
+ public static W.BrowseRequest EncodeBrowseRequest(BrowseRequest x)
+ {
+ var v = new W.BrowseRequest
+ {
+ Parent = EncodeView(x.Parent),
+ Budget = EncodeBudget(x.Budget),
+ };
+ if (x.Filter is not null)
+ v.Filter = x.Filter;
+ if (x.Continuation is not null)
+ v.Continuation = x.Continuation;
+ return v;
+ }
+
+ public static BrowseRequest DecodeBrowseRequest(
+ W.BrowseRequest x,
+ DataDecodeLimits? limits = null
+ )
+ {
+ Preflight(x, 1, limits);
+ return new(
+ DecodeView(x.Parent),
+ x.HasFilter ? x.Filter : null,
+ x.HasContinuation ? x.Continuation : null,
+ DecodeBudget(x.Budget)
+ );
+ }
+
+ public static W.MetadataRequest EncodeMetadataRequest(MetadataRequest x)
+ {
+ var v = new W.MetadataRequest { Budget = EncodeBudget(x.Budget) };
+ v.Views.AddRange(x.Views.Select(EncodeView));
+ return v;
+ }
+
+ public static MetadataRequest DecodeMetadataRequest(
+ W.MetadataRequest x,
+ DataDecodeLimits? limits = null
+ )
+ {
+ Preflight(x, x.Views.Count, limits);
+ return new(x.Views.Select(DecodeView).ToArray(), DecodeBudget(x.Budget));
+ }
+
+ public static W.BrowseResponse EncodeBrowseResponse(DataBrowseBranch x)
+ {
+ DataContractValidation.Required(x.Status);
+ var v = new W.BrowseResponse
+ {
+ Parent = EncodeView(x.Parent),
+ Status = (int)x.Status,
+ Complete = x.Complete,
+ };
+ v.Items.AddRange(x.Items.Select(EncodeMetadata));
+ if (x.Continuation is not null)
+ v.Continuation = x.Continuation;
+ if (x.Lease is { } l)
+ v.Lease = new W.Lease
+ {
+ CatalogEpoch = l.CatalogEpoch,
+ AuthorityEpoch = l.AuthorityEpoch,
+ DurationTicks = l.Duration.Ticks,
+ };
+ return v;
+ }
+
+ public static DataBrowseBranch DecodeBrowseResponse(
+ W.BrowseResponse x,
+ DataDecodeLimits? limits = null
+ )
+ {
+ Preflight(x, x.Items.Count, limits);
+ if (x.Lease is not null)
+ new MetadataLease(
+ x.Lease.CatalogEpoch,
+ x.Lease.AuthorityEpoch,
+ TimeSpan.FromTicks(x.Lease.DurationTicks)
+ ).Validate();
+ var status = (DataItemStatus)x.Status;
+ DataContractValidation.Required(status);
+ return new(
+ DecodeView(x.Parent),
+ status,
+ x.Items.Select(DecodeMetadata).ToArray(),
+ x.Complete,
+ x.HasContinuation ? x.Continuation : null,
+ x.Lease is null
+ ? null
+ : new MetadataLease(
+ x.Lease.CatalogEpoch,
+ x.Lease.AuthorityEpoch,
+ TimeSpan.FromTicks(x.Lease.DurationTicks)
+ )
+ );
+ }
+
+ public static W.ReadResult EncodeReadResult(ReadResult x)
+ {
+ DataContractValidation.Required(x.Status);
+ DataContractValidation.Required(x.Readiness);
+ var v = new W.ReadResult
+ {
+ CorrelationId = x.CorrelationId,
+ Status = (int)x.Status,
+ Readiness = (int)x.Readiness,
+ };
+ if (x.Age is { } age)
+ v.AgeTicks = age.Ticks;
+ if (x.Sample is not null)
+ v.Sample = EncodeSample(x.Sample);
+ if (x.Diagnostic is not null)
+ v.Diagnostic = x.Diagnostic;
+ return v;
+ }
+
+ public static ReadResult DecodeReadResult(W.ReadResult x, DataDecodeLimits? limits = null)
+ {
+ limits ??= new DataDecodeLimits();
+ Preflight(x, 1, limits, x.Sample is null ? null : new[] { x.Sample.Value });
+ var status = (DataItemStatus)x.Status;
+ var readiness = (DataReadiness)x.Readiness;
+ DataContractValidation.Required(status);
+ DataContractValidation.Required(readiness);
+ return new(
+ x.CorrelationId,
+ status,
+ readiness,
+ x.HasAgeTicks ? TimeSpan.FromTicks(x.AgeTicks) : null,
+ x.Sample is null
+ ? null
+ : DecodeSample(x.Sample, limits.MaxValueElements, limits.MaxBytes),
+ x.HasDiagnostic ? x.Diagnostic : null
+ );
+ }
+
+ public static W.WriteResult EncodeWriteResult(WriteItemResult x)
+ {
+ x.Outcome.Validate();
+ var v = new W.WriteResult
+ {
+ CorrelationId = x.CorrelationId,
+ State = (int)x.Outcome.State,
+ StatusCode = x.Outcome.StatusCode,
+ };
+ if (x.Outcome.Diagnostic is not null)
+ v.Diagnostic = x.Outcome.Diagnostic;
+ return v;
+ }
+
+ public static WriteItemResult DecodeWriteResult(W.WriteResult x)
+ {
+ var outcome = new DataWriteOutcome(
+ (DataWriteState)x.State,
+ x.StatusCode,
+ x.HasDiagnostic ? x.Diagnostic : null
+ );
+ outcome.Validate();
+ return new(x.CorrelationId, outcome);
+ }
+
+ /// Hash immutable operation semantics, excluding correlation and retry-varying budgets.
+ public static byte[] WritePayloadHash(WriteItem item)
+ {
+ var wire = new W.WriteItem
+ {
+ OperationId = item.OperationId,
+ View = EncodeView(item.View),
+ Value = TypedValueCodec.Encode(item.Value),
+ ExpectedCatalogRevision = item.ExpectedCatalogRevision,
+ ExpectedServingIncarnation = item.ExpectedServingIncarnation,
+ };
+ return System.Security.Cryptography.SHA256.HashData(wire.ToByteArray());
+ }
+
+ public static bool NegotiateCompact(DataCapabilities peer)
+ {
+ if (peer.ProtocolMajor != 1)
+ throw new NotSupportedException("Incompatible protocol major.");
+ return peer.CompactBatches && peer.CompactCodecVersion == 1;
+ }
+
+ public static W.CapabilitiesResponse EncodeCapabilities(DataCapabilities x)
+ {
+ x.Validate();
+ var l = x.Limits;
+ var v = new W.CapabilitiesResponse
+ {
+ ProtocolMajor = x.ProtocolMajor,
+ ProtocolMinor = x.ProtocolMinor,
+ ClusterId = x.ClusterId,
+ Serving = EncodeServing(x.Serving),
+ Readiness = (int)x.Readiness,
+ Operations = (uint)x.Operations,
+ CompactBatches = x.CompactBatches,
+ CompactCodecVersion = x.CompactCodecVersion,
+ Limits = new W.Limits
+ {
+ MaxPageItems = l.MaxPageItems,
+ MaxBatchItems = l.MaxBatchItems,
+ MaxMessageBytes = l.MaxMessageBytes,
+ MaxMonitoredItems = l.MaxMonitoredItems,
+ MaxStreams = l.MaxStreams,
+ MaxPendingBytes = l.MaxPendingBytes,
+ MaxMetadataLeaseTicks = l.MaxMetadataLease.Ticks,
+ MaxSessionLifetimeTicks = l.MaxSessionLifetime.Ticks,
+ WriteRetryWindowTicks = l.WriteRetryWindow.Ticks,
+ MaxValueElements = l.MaxValueElements,
+ },
+ };
+ v.ValueKinds.AddRange(x.ValueKinds.Select(k => (W.ValueKind)k));
+ return v;
+ }
+
+ public static DataCapabilities DecodeCapabilities(
+ W.CapabilitiesResponse x,
+ DataDecodeLimits? limits = null
+ )
+ {
+ Preflight(x, x.ValueKinds.Count, limits);
+ if (x.ProtocolMajor != 1)
+ throw new NotSupportedException("Incompatible protocol major.");
+ var r = (DataReadiness)x.Readiness;
+ DataContractValidation.Required(r);
+ var l = x.Limits ?? throw new ArgumentException("Missing limits.");
+ var kinds = x
+ .ValueKinds.Select(k => (DataValueKind)k)
+ .Where(k => k != DataValueKind.Unspecified && System.Enum.IsDefined(k))
+ .ToHashSet();
+ var result = new DataCapabilities(
+ x.ProtocolMajor,
+ x.ProtocolMinor,
+ DecodeServing(x.Serving),
+ r,
+ (DataOperations)(
+ x.Operations
+ & (uint)(
+ DataOperations.Browse
+ | DataOperations.Metadata
+ | DataOperations.Read
+ | DataOperations.Write
+ | DataOperations.Subscribe
+ )
+ ),
+ kinds,
+ new DataLimits(
+ l.MaxPageItems,
+ l.MaxBatchItems,
+ l.MaxMessageBytes,
+ l.MaxMonitoredItems,
+ l.MaxStreams,
+ l.MaxPendingBytes,
+ TimeSpan.FromTicks(l.MaxMetadataLeaseTicks),
+ TimeSpan.FromTicks(l.MaxSessionLifetimeTicks),
+ TimeSpan.FromTicks(l.WriteRetryWindowTicks),
+ l.HasMaxValueElements ? l.MaxValueElements : TypedValueCodec.DefaultMaxElements
+ ),
+ x.CompactBatches,
+ x.CompactCodecVersion,
+ x.ClusterId
+ );
+ result.Validate();
+ return result;
+ }
+
+ public static W.SubscriptionFrame EncodeControlOrAck(DataSubscriptionFrame frame)
+ {
+ var v = new W.SubscriptionFrame
+ {
+ SubscriptionId = frame.SubscriptionId,
+ StreamEpoch = frame.StreamEpoch,
+ Sequence = frame.Sequence,
+ };
+ if (frame is DataSubscriptionControl c)
+ {
+ DataContractValidation.Required(c.Kind);
+ v.Control = new W.Control
+ {
+ Kind = (int)c.Kind,
+ CatalogEpoch = c.CatalogEpoch,
+ AuthorityEpoch = c.AuthorityEpoch,
+ };
+ v.Control.Watermarks.AddRange(
+ c.Watermarks.Select(w => new W.Watermark
+ {
+ PartitionId = w.PartitionId,
+ Version = w.Version,
+ })
+ );
+ if (c.Diagnostic is not null)
+ v.Control.Diagnostic = c.Diagnostic;
+ }
+ else if (frame is DataSubscriptionAck a)
+ {
+ v.Ack = new W.Ack { CommandId = a.CommandId };
+ foreach (var item in a.Items)
+ {
+ DataContractValidation.Required(item.Status);
+ var w = new W.ItemAck
+ {
+ ClientItemId = item.ClientItemId,
+ Status = (int)item.Status,
+ };
+ if (item.Handle is not null)
+ w.Handle = EncodeHandle(item.Handle);
+ if (item.RevisedSettings is not null)
+ w.RevisedSettings = EncodeSettings(item.RevisedSettings);
+ if (item.Diagnostic is not null)
+ w.Diagnostic = item.Diagnostic;
+ v.Ack.Items.Add(w);
+ }
+ }
+ else
+ throw new ArgumentException("Expected control or acknowledgement.");
+ return v;
+ }
+
+ public static DataSubscriptionFrame DecodeControlOrAck(
+ W.SubscriptionFrame frame,
+ DataDecodeLimits? limits = null
+ )
+ {
+ ValidateFrame(frame.SubscriptionId, frame.StreamEpoch, frame.Sequence);
+ Preflight(frame, frame.Control?.Watermarks.Count ?? frame.Ack?.Items.Count ?? 0, limits);
+ if (frame.Control is { } c)
+ {
+ var kind = (DataStreamControlKind)c.Kind;
+ DataContractValidation.Required(kind);
+ if (
+ c.CatalogEpoch < 0
+ || c.AuthorityEpoch < 0
+ || c.Watermarks.Any(w => w.PartitionId < 0 || w.Version < 0)
+ )
+ throw new ArgumentException("Invalid control epochs or watermarks.");
+ return new DataSubscriptionControl(
+ frame.SubscriptionId,
+ frame.StreamEpoch,
+ frame.Sequence,
+ kind,
+ c.Watermarks.Select(w => new PartitionWatermark(w.PartitionId, w.Version))
+ .ToArray(),
+ c.CatalogEpoch,
+ c.AuthorityEpoch,
+ c.HasDiagnostic ? c.Diagnostic : null
+ );
+ }
+ if (frame.Ack is { } a)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(a.CommandId);
+ var items = new List();
+ foreach (var item in a.Items)
+ {
+ if (
+ item.Handle is not null
+ && (
+ item.Handle.SubscriptionId != frame.SubscriptionId
+ || item.Handle.StreamEpoch != frame.StreamEpoch
+ )
+ )
+ throw new ArgumentException(
+ "Acknowledgement handle belongs to another stream."
+ );
+ var status = (DataItemStatus)item.Status;
+ DataContractValidation.Required(status);
+ items.Add(
+ new(
+ item.ClientItemId,
+ status,
+ item.Handle is null ? null : DecodeHandle(item.Handle),
+ item.RevisedSettings is null ? null : DecodeSettings(item.RevisedSettings),
+ item.HasDiagnostic ? item.Diagnostic : null
+ )
+ );
+ }
+ return new DataSubscriptionAck(
+ frame.SubscriptionId,
+ frame.StreamEpoch,
+ frame.Sequence,
+ a.CommandId,
+ items
+ );
+ }
+ throw new ArgumentException("Expected control or acknowledgement.");
+ }
+
+ public static W.MetadataResult EncodeMetadataResult(DataItemResult item)
+ {
+ DataContractValidation.Required(item.Status);
+ var result = new W.MetadataResult
+ {
+ CorrelationId = item.CorrelationId,
+ Status = (int)item.Status,
+ };
+ if (item.Value is not null)
+ result.Value = EncodeMetadata(item.Value);
+ if (item.Diagnostic is not null)
+ result.Diagnostic = item.Diagnostic;
+ return result;
+ }
+
+ public static DataItemResult DecodeMetadataResult(
+ W.MetadataResult item,
+ DataDecodeLimits? limits = null
+ )
+ {
+ Preflight(item, 1, limits);
+ var status = (DataItemStatus)item.Status;
+ DataContractValidation.Required(status);
+ return new(
+ item.CorrelationId,
+ status,
+ item.Value is null ? null : DecodeMetadata(item.Value),
+ item.HasDiagnostic ? item.Diagnostic : null
+ );
+ }
+
+ public static W.ReadResponse EncodeReadResponse(IReadOnlyList items)
+ {
+ var response = new W.ReadResponse();
+ response.Items.AddRange(items.Select(EncodeReadResult));
+ return response;
+ }
+
+ public static IReadOnlyList DecodeReadResponse(
+ W.ReadResponse response,
+ DataDecodeLimits? limits = null
+ )
+ {
+ limits ??= new DataDecodeLimits();
+ Preflight(
+ response,
+ response.Items.Count,
+ limits,
+ response.Items.Where(i => i.Sample is not null).Select(i => i.Sample.Value)
+ );
+ var result = new List(response.Items.Count);
+ try
+ {
+ foreach (var item in response.Items)
+ result.Add(DecodeReadResult(item, limits));
+ return result;
+ }
+ catch
+ {
+ foreach (var item in result)
+ item.Dispose();
+ throw;
+ }
+ }
+
+ public static W.WriteResponse EncodeWriteResponse(IReadOnlyList items)
+ {
+ var response = new W.WriteResponse();
+ response.Items.AddRange(items.Select(EncodeWriteResult));
+ return response;
+ }
+
+ public static IReadOnlyList DecodeWriteResponse(
+ W.WriteResponse response,
+ DataDecodeLimits? limits = null
+ )
+ {
+ Preflight(response, response.Items.Count, limits);
+ return response.Items.Select(DecodeWriteResult).ToArray();
+ }
+
+ public static W.MetadataResponse EncodeMetadataResponse(
+ IReadOnlyList> items
+ )
+ {
+ var response = new W.MetadataResponse();
+ response.Items.AddRange(items.Select(EncodeMetadataResult));
+ return response;
+ }
+
+ public static IReadOnlyList> DecodeMetadataResponse(
+ W.MetadataResponse response,
+ DataDecodeLimits? limits = null
+ )
+ {
+ Preflight(response, response.Items.Count, limits);
+ return response.Items.Select(i => DecodeMetadataResult(i, limits)).ToArray();
+ }
+}
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/TypedValueCodec.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/TypedValueCodec.cs
new file mode 100644
index 000000000..348864839
--- /dev/null
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/TypedValueCodec.cs
@@ -0,0 +1,246 @@
+using Google.Protobuf;
+using Google.Protobuf.WellKnownTypes;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
+using Wire = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
+
+namespace ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
+
+/// Explicit typed values only; limits are checked before constructing domain arrays.
+public static class TypedValueCodec
+{
+ public const int DefaultMaxElements = 100_000;
+ public const int DefaultMaxBytes = 4 * 1024 * 1024;
+ public const int MaxDimensions = 16;
+
+ public static Wire.TypedValue Encode(DataValue value)
+ {
+ ArgumentNullException.ThrowIfNull(value);
+ var result = new Wire.TypedValue { Kind = (Wire.ValueKind)value.Kind };
+ if (value.Kind == DataValueKind.Null)
+ return result;
+ if (value.Kind == DataValueKind.Bytes)
+ {
+ result.BytesValue = ByteString.CopyFrom(value.GetBytes().Span);
+ return result;
+ }
+ if (value.Kind == DataValueKind.Array)
+ {
+ var array = new Wire.TypedArray
+ {
+ ElementKind = (Wire.ValueKind)value.ArrayElementKind,
+ };
+ array.Dimensions.AddRange(value.Dimensions!.Select(x => checked((uint)x)));
+ foreach (var element in value.GetArray())
+ {
+ using var scalar = DataValue.FromScalar(value.ArrayElementKind, element);
+ array.Elements.Add(Encode(scalar));
+ }
+ result.Array = array;
+ return result;
+ }
+ var scalarValue = value.GetScalar();
+ switch (value.Kind)
+ {
+ case DataValueKind.Boolean:
+ result.Boolean = (bool)scalarValue;
+ break;
+ case DataValueKind.Int8:
+ result.Signed = (sbyte)scalarValue;
+ break;
+ case DataValueKind.Int16:
+ result.Signed = (short)scalarValue;
+ break;
+ case DataValueKind.Int32:
+ result.Signed = (int)scalarValue;
+ break;
+ case DataValueKind.Int64:
+ result.Signed = (long)scalarValue;
+ break;
+ case DataValueKind.UInt8:
+ result.Unsigned = (byte)scalarValue;
+ break;
+ case DataValueKind.UInt16:
+ result.Unsigned = (ushort)scalarValue;
+ break;
+ case DataValueKind.UInt32:
+ result.Unsigned = (uint)scalarValue;
+ break;
+ case DataValueKind.UInt64:
+ result.Unsigned = (ulong)scalarValue;
+ break;
+ case DataValueKind.Float:
+ result.FloatValue = (float)scalarValue;
+ break;
+ case DataValueKind.Double:
+ result.DoubleValue = (double)scalarValue;
+ break;
+ case DataValueKind.String:
+ result.StringValue = (string)scalarValue;
+ break;
+ case DataValueKind.Timestamp:
+ result.Timestamp = Timestamp.FromDateTimeOffset((DateTimeOffset)scalarValue);
+ break;
+ case DataValueKind.Guid:
+ result.Guid = ((Guid)scalarValue).ToString("D");
+ break;
+ default:
+ throw new ArgumentException("Unsupported value kind.", nameof(value));
+ }
+ return result;
+ }
+
+ public static DataValue Decode(
+ Wire.TypedValue value,
+ int maxElements = DefaultMaxElements,
+ int maxBytes = DefaultMaxBytes
+ )
+ {
+ ArgumentNullException.ThrowIfNull(value);
+ if (maxElements <= 0 || maxBytes <= 0)
+ throw new ArgumentOutOfRangeException(nameof(maxElements));
+ if (value.CalculateSize() > maxBytes || DecodedBytes(value, maxBytes) > maxBytes)
+ throw new ArgumentException("Decoded value exceeds budget.");
+ return DecodeCore(value, maxElements, maxBytes);
+ }
+
+ internal static long DecodedBytes(Wire.TypedValue value, long limit)
+ {
+ long size = 32;
+ if (value.PayloadCase == Wire.TypedValue.PayloadOneofCase.StringValue)
+ size += (long)value.StringValue.Length * sizeof(char);
+ else if (value.PayloadCase == Wire.TypedValue.PayloadOneofCase.BytesValue)
+ size += (long)value.BytesValue.Length * 2;
+ else if (value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Guid)
+ size += (long)value.Guid.Length * sizeof(char);
+ else if (value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Array)
+ {
+ var array = value.Array;
+ size +=
+ (long)array.Dimensions.Count * sizeof(int) * 2
+ + (long)array.Elements.Count * (IntPtr.Size * 2 + 32);
+ if (size > limit)
+ return size;
+ foreach (var item in array.Elements)
+ {
+ if ((DataValueKind)item.Kind == DataValueKind.Array)
+ throw new ArgumentException("Nested arrays are unsupported.");
+ size += DecodedBytes(item, limit - size);
+ if (size > limit)
+ return size;
+ }
+ }
+ return size;
+ }
+
+ internal static DateTimeOffset DecodeTimestamp(Timestamp value)
+ {
+ if (value.Nanos % 100 != 0)
+ throw new ArgumentException("Timestamp is finer than domain tick precision.");
+ return value.ToDateTimeOffset();
+ }
+
+ private static DataValue DecodeCore(Wire.TypedValue value, int maxElements, int maxBytes)
+ {
+ var kind = (DataValueKind)value.Kind;
+ if (
+ kind == DataValueKind.Null
+ && value.PayloadCase == Wire.TypedValue.PayloadOneofCase.None
+ )
+ return DataValue.Null();
+ if (
+ kind == DataValueKind.Array
+ && value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Array
+ )
+ {
+ var a = value.Array;
+ if (
+ a.Dimensions.Count == 0
+ || a.Dimensions.Count > MaxDimensions
+ || a.Elements.Count > maxElements
+ || (long)a.Elements.Count * IntPtr.Size > maxBytes
+ )
+ throw new ArgumentException("Array exceeds budget.");
+ long count = 1;
+ foreach (var d in a.Dimensions)
+ {
+ if (d > int.MaxValue || (d != 0 && count > maxElements / (long)d))
+ throw new ArgumentException("Invalid array dimensions.");
+ count *= d;
+ }
+ if (count != a.Elements.Count)
+ throw new ArgumentException("Array shape mismatch.");
+ var elementKind = (DataValueKind)a.ElementKind;
+ if (
+ elementKind
+ is DataValueKind.Unspecified
+ or DataValueKind.Null
+ or DataValueKind.Array
+ or DataValueKind.Bytes
+ || !System.Enum.IsDefined(elementKind)
+ )
+ throw new ArgumentException("Unsupported array kind.");
+ var elements = new object[a.Elements.Count];
+ for (int i = 0; i < elements.Length; i++)
+ {
+ if ((DataValueKind)a.Elements[i].Kind != elementKind)
+ throw new ArgumentException("Array element kind mismatch.");
+ using var item = DecodeCore(a.Elements[i], maxElements, maxBytes);
+ elements[i] = item.GetScalar();
+ }
+ return DataValue.FromArray(
+ elementKind,
+ elements,
+ a.Dimensions.Select(x => checked((int)x)).ToArray()
+ );
+ }
+ object scalar = kind switch
+ {
+ DataValueKind.Boolean
+ when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Boolean => value.Boolean,
+ DataValueKind.Int8 when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Signed =>
+ checked((sbyte)value.Signed),
+ DataValueKind.Int16 when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Signed =>
+ checked((short)value.Signed),
+ DataValueKind.Int32 when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Signed =>
+ checked((int)value.Signed),
+ DataValueKind.Int64 when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Signed =>
+ value.Signed,
+ DataValueKind.UInt8
+ when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Unsigned => checked(
+ (byte)value.Unsigned
+ ),
+ DataValueKind.UInt16
+ when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Unsigned => checked(
+ (ushort)value.Unsigned
+ ),
+ DataValueKind.UInt32
+ when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Unsigned => checked(
+ (uint)value.Unsigned
+ ),
+ DataValueKind.UInt64
+ when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Unsigned =>
+ value.Unsigned,
+ DataValueKind.Float
+ when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.FloatValue =>
+ value.FloatValue,
+ DataValueKind.Double
+ when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.DoubleValue =>
+ value.DoubleValue,
+ DataValueKind.String
+ when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.StringValue =>
+ value.StringValue,
+ DataValueKind.Timestamp
+ when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Timestamp =>
+ DecodeTimestamp(value.Timestamp),
+ DataValueKind.Guid when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Guid =>
+ Guid.ParseExact(value.Guid, "D"),
+ DataValueKind.Bytes
+ when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.BytesValue =>
+ value.BytesValue.ToByteArray(),
+ _ => throw new ArgumentException("Invalid or unsupported typed value."),
+ };
+ return kind == DataValueKind.Bytes
+ ? DataValue.FromBytes((byte[])scalar)
+ : DataValue.FromScalar(kind, scalar);
+ }
+}
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs
new file mode 100644
index 000000000..a0da45d0e
--- /dev/null
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs
@@ -0,0 +1,22 @@
+using ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
+
+namespace ZB.MOM.WW.OtOpcUa.Commons.Protos;
+
+/// Frozen wire contract identifiers; removed field numbers must remain reserved.
+public static class DataConnectionProtoContract
+{
+ public const int ProtocolMajor = 1;
+ public const int ProtocolMinor = 0;
+ public const int CompactCodecVersion = 1;
+
+ public static void Validate()
+ {
+ if (
+ TypedValue.KindFieldNumber != 1
+ || Sample.StatusCodeFieldNumber != 2
+ || SubscriptionFrame.CompactValuesFieldNumber != 7
+ || (int)ValueKind.Unspecified != 0
+ )
+ throw new InvalidOperationException("Data connection wire contract changed.");
+ }
+}
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto
new file mode 100644
index 000000000..5446f9fca
--- /dev/null
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto
@@ -0,0 +1,293 @@
+syntax = "proto3";
+package data_connection.v1;
+option csharp_namespace = "ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1";
+import "google/protobuf/timestamp.proto";
+service DataConnectionService {
+ rpc GetCapabilities(CapabilitiesRequest) returns (CapabilitiesResponse);
+ rpc Browse(BrowseRequest) returns (BrowseResponse);
+ rpc GetMetadata(MetadataRequest) returns (MetadataResponse);
+ rpc Read(ReadRequest) returns (ReadResponse);
+ rpc Write(WriteRequest) returns (WriteResponse);
+ rpc Subscribe(stream SubscriptionCommand) returns (stream SubscriptionFrame);
+}
+enum ValueKind {
+ VALUE_KIND_UNSPECIFIED = 0;
+ VALUE_KIND_NULL = 1;
+ VALUE_KIND_BOOLEAN = 2;
+ VALUE_KIND_INT8 = 3;
+ VALUE_KIND_INT16 = 4;
+ VALUE_KIND_INT32 = 5;
+ VALUE_KIND_INT64 = 6;
+ VALUE_KIND_UINT8 = 7;
+ VALUE_KIND_UINT16 = 8;
+ VALUE_KIND_UINT32 = 9;
+ VALUE_KIND_UINT64 = 10;
+ VALUE_KIND_FLOAT = 11;
+ VALUE_KIND_DOUBLE = 12;
+ VALUE_KIND_STRING = 13;
+ VALUE_KIND_BYTES = 14;
+ VALUE_KIND_TIMESTAMP = 15;
+ VALUE_KIND_GUID = 16;
+ VALUE_KIND_ARRAY = 17;
+}
+message TypedValue {
+ ValueKind kind = 1;
+ oneof payload {
+ bool boolean = 2;
+ sint64 signed = 3;
+ uint64 unsigned = 4;
+ float float_value = 5;
+ double double_value = 6;
+ string string_value = 7;
+ bytes bytes_value = 8;
+ google.protobuf.Timestamp timestamp = 9;
+ string guid = 10;
+ TypedArray array = 11;
+ }
+}
+message TypedArray {
+ ValueKind element_kind = 1;
+ repeated uint32 dimensions = 2;
+ repeated TypedValue elements = 3;
+}
+message Address {
+ string origin_cluster_id = 1;
+ string namespace_uri = 2;
+ string identifier_kind = 3;
+ string identifier = 4;
+}
+message View {
+ Address address = 1;
+ int32 realm = 2;
+ optional string mapping_id = 3;
+ int64 mapping_revision = 4;
+ string subject = 5;
+}
+message Serving {
+ string node_id = 1;
+ string incarnation = 2;
+ string role = 3;
+ int64 catalog_epoch = 4;
+ int64 authority_epoch = 5;
+}
+message Sample {
+ TypedValue value = 1;
+ uint32 status_code = 2;
+ google.protobuf.Timestamp source_timestamp = 3;
+ google.protobuf.Timestamp server_timestamp = 4;
+ Serving serving = 5;
+ int64 version = 6;
+}
+message Budget {
+ int64 timeout_ticks = 1;
+ int32 max_items = 2;
+ int64 max_bytes = 3;
+}
+message Limits {
+ int32 max_page_items = 1;
+ int32 max_batch_items = 2;
+ int32 max_message_bytes = 3;
+ int32 max_monitored_items = 4;
+ int32 max_streams = 5;
+ int64 max_pending_bytes = 6;
+ int64 max_metadata_lease_ticks = 7;
+ int64 max_session_lifetime_ticks = 8;
+ int64 write_retry_window_ticks = 9;
+ optional int32 max_value_elements = 10;
+}
+message CapabilitiesRequest {
+ int32 protocol_major = 1;
+ int32 protocol_minor = 2;
+}
+message CapabilitiesResponse {
+ int32 protocol_major = 1;
+ int32 protocol_minor = 2;
+ Serving serving = 3;
+ int32 readiness = 4;
+ uint32 operations = 5;
+ repeated ValueKind value_kinds = 6;
+ Limits limits = 7;
+ bool compact_batches = 8;
+ int32 compact_codec_version = 9;
+ string cluster_id = 10;
+}
+message Metadata {
+ View view = 1;
+ string browse_name = 2;
+ string node_kind = 3;
+ ValueKind value_kind = 4;
+ int32 value_rank = 5;
+ repeated int32 dimensions = 6;
+ bool writable = 7;
+ uint32 allowed_operations = 8;
+ int64 catalog_revision = 9;
+ optional string stable_source_id = 10;
+ optional string engineering_units = 11;
+ bool is_stale = 12;
+ optional ValueKind array_element_kind = 13;
+}
+message Lease {
+ int64 catalog_epoch = 1;
+ int64 authority_epoch = 2;
+ int64 duration_ticks = 3;
+}
+message BrowseRequest {
+ View parent = 1;
+ optional string filter = 2;
+ optional string continuation = 3;
+ Budget budget = 4;
+}
+message BrowseResponse {
+ View parent = 1;
+ int32 status = 2;
+ repeated Metadata items = 3;
+ bool complete = 4;
+ optional string continuation = 5;
+ Lease lease = 6;
+}
+message MetadataRequest {
+ repeated View views = 1;
+ Budget budget = 2;
+}
+message MetadataResult {
+ string correlation_id = 1;
+ int32 status = 2;
+ Metadata value = 3;
+ optional string diagnostic = 4;
+}
+message MetadataResponse { repeated MetadataResult items = 1; }
+message ReadItem {
+ string correlation_id = 1;
+ View view = 2;
+ optional int64 maximum_age_ticks = 3;
+}
+message ReadRequest {
+ repeated ReadItem items = 1;
+ Budget budget = 2;
+}
+message ReadResult {
+ string correlation_id = 1;
+ int32 status = 2;
+ int32 readiness = 3;
+ optional int64 age_ticks = 4;
+ Sample sample = 5;
+ optional string diagnostic = 6;
+}
+message ReadResponse { repeated ReadResult items = 1; }
+message WriteItem {
+ string correlation_id = 1;
+ string operation_id = 2;
+ View view = 3;
+ TypedValue value = 4;
+ int64 expected_catalog_revision = 5;
+ string expected_serving_incarnation = 6;
+ int64 remaining_budget_ticks = 7;
+}
+message WriteRequest {
+ repeated WriteItem items = 1;
+ Budget budget = 2;
+}
+message WriteResult {
+ string correlation_id = 1;
+ int32 state = 2;
+ uint32 status_code = 3;
+ optional string diagnostic = 4;
+}
+message WriteResponse { repeated WriteResult items = 1; }
+message Handle {
+ string subscription_id = 1;
+ int64 stream_epoch = 2;
+ uint64 handle = 3;
+ int64 item_revision = 4;
+}
+message Settings {
+ int64 sampling_ticks = 1;
+ int64 publishing_ticks = 2;
+ int32 trigger = 3;
+ optional double deadband = 4;
+}
+message SubscriptionItem {
+ string client_item_id = 1;
+ View view = 2;
+ Settings settings = 3;
+}
+message SubscriptionCommand {
+ string subscription_id = 1;
+ int64 stream_epoch = 2;
+ string command_id = 3;
+ int64 acknowledgement_timeout_ticks = 4;
+ oneof command {
+ Open open = 5;
+ ItemChanges add = 6;
+ ItemChanges modify = 7;
+ HandleChanges remove = 8;
+ }
+}
+message Open {
+ repeated SubscriptionItem items = 1;
+ bool watch_catalog_only = 2;
+ int64 session_lifetime_ticks = 3;
+ Budget snapshot_budget = 4;
+}
+message ItemChanges { repeated SubscriptionItem items = 1; }
+message HandleChanges { repeated Handle items = 1; }
+message ItemAck {
+ string client_item_id = 1;
+ int32 status = 2;
+ Handle handle = 3;
+ Settings revised_settings = 4;
+ optional string diagnostic = 5;
+}
+message Ack {
+ string command_id = 1;
+ repeated ItemAck items = 2;
+}
+message Watermark {
+ int32 partition_id = 1;
+ int64 version = 2;
+}
+message Control {
+ int32 kind = 1;
+ repeated Watermark watermarks = 2;
+ int64 catalog_epoch = 3;
+ int64 authority_epoch = 4;
+ optional string diagnostic = 5;
+}
+message ValueUpdate {
+ Handle handle = 1;
+ Sample sample = 2;
+}
+message Values {
+ bool is_snapshot = 1;
+ repeated ValueUpdate items = 2;
+}
+// Override messages distinguish absent timestamp from an inherited default.
+message TimestampOverride { google.protobuf.Timestamp value = 1; }
+message CompactUpdate {
+ uint64 handle = 1;
+ int64 item_revision = 2;
+ int64 version = 3;
+ TypedValue value = 4;
+ optional uint32 status_code = 5;
+ TimestampOverride source_timestamp = 6;
+ TimestampOverride server_timestamp = 7;
+}
+message CompactValues {
+ bool is_snapshot = 1;
+ Serving serving = 2;
+ uint32 default_status_code = 3;
+ google.protobuf.Timestamp default_source_timestamp = 4;
+ google.protobuf.Timestamp default_server_timestamp = 5;
+ repeated CompactUpdate items = 6;
+}
+message SubscriptionFrame {
+ string subscription_id = 1;
+ int64 stream_epoch = 2;
+ int64 sequence = 3;
+ oneof frame {
+ Ack ack = 4;
+ Control control = 5;
+ Values values = 6;
+ CompactValues compact_values = 7;
+ }
+}
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/ZB.MOM.WW.OtOpcUa.Commons.csproj b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/ZB.MOM.WW.OtOpcUa.Commons.csproj
index eb0929108..16c27ef35 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/ZB.MOM.WW.OtOpcUa.Commons.csproj
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/ZB.MOM.WW.OtOpcUa.Commons.csproj
@@ -28,6 +28,7 @@
+
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataAddress.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataAddress.cs
new file mode 100644
index 000000000..24ce1e2d4
--- /dev/null
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataAddress.cs
@@ -0,0 +1,72 @@
+namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
+
+/// Origin-qualified public identity; namespace indexes are never portable identities.
+public sealed record DataAddress(string OriginClusterId, string NamespaceUri, string IdentifierKind, string Identifier)
+{
+ public void Validate()
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(OriginClusterId);
+ ArgumentException.ThrowIfNullOrWhiteSpace(NamespaceUri);
+ ArgumentException.ThrowIfNullOrWhiteSpace(IdentifierKind);
+ ArgumentException.ThrowIfNullOrWhiteSpace(Identifier);
+ }
+}
+public enum DataRealm { Unspecified = 0, Raw = 1, Uns = 2 }
+public enum DataTargetMode { Unspecified = 0, Node = 1, Cluster = 2 }
+public enum DataConsistency { Unspecified = 0, Primary = 1, ReadyReplica = 2 }
+
+/// A request is bound to a cluster and, for node mode, an expected node.
+public sealed record DataTarget(DataTargetMode Mode, string ExpectedClusterId, string? ExpectedNodeId)
+{
+ public void Validate()
+ {
+ DataContractValidation.Required(Mode);
+ ArgumentException.ThrowIfNullOrWhiteSpace(ExpectedClusterId);
+ if (Mode == DataTargetMode.Node) ArgumentException.ThrowIfNullOrWhiteSpace(ExpectedNodeId);
+ if (Mode == DataTargetMode.Cluster && ExpectedNodeId is not null)
+ throw new ArgumentException("Cluster targets cannot pin a node.", nameof(ExpectedNodeId));
+ }
+}
+
+///
+/// The requested view, independent of backing-source identity. Subject is an untrusted claim until
+/// resolved against the authoritative catalog; it must not independently grant access.
+///
+public sealed record DataView(DataAddress Address, DataRealm Realm, string? MappingId, long MappingRevision, string Subject)
+{
+ public void Validate()
+ {
+ ArgumentNullException.ThrowIfNull(Address); Address.Validate();
+ DataContractValidation.Required(Realm);
+ ArgumentException.ThrowIfNullOrWhiteSpace(Subject);
+ if (MappingRevision < 0 || (MappingId is null && MappingRevision != 0) ||
+ (MappingId is not null && (string.IsNullOrWhiteSpace(MappingId) || MappingRevision == 0)))
+ throw new ArgumentException("Mapped views require an ID and positive revision.");
+ }
+}
+/// Actual serving replica provenance, distinct from origin ownership.
+public sealed record ServingIdentity(string NodeId, string Incarnation, string Role, long CatalogEpoch, long AuthorityEpoch)
+{
+ public void Validate(bool requireEpochs = false)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(NodeId);
+ ArgumentException.ThrowIfNullOrWhiteSpace(Incarnation);
+ ArgumentException.ThrowIfNullOrWhiteSpace(Role);
+ if (CatalogEpoch < 0 || AuthorityEpoch < 0 || (requireEpochs && (CatalogEpoch == 0 || AuthorityEpoch == 0)))
+ {
+ throw new ArgumentOutOfRangeException(nameof(CatalogEpoch));
+ }
+ }
+}
+public sealed record DataSourceIdentity(DataAddress Address, string StableSourceId, ServingIdentity Serving, DataTargetMode TargetMode,
+ DataConsistency Consistency, string PrincipalId, string ExportScope);
+
+public static class DataContractValidation
+{
+ /// Reject zero and unrecognized values for a required enum decision.
+ public static void Required(T value) where T : struct, Enum
+ {
+ if (Convert.ToInt64(value) == 0 || !Enum.IsDefined(value))
+ throw new ArgumentOutOfRangeException(nameof(value), value, "A defined nonzero value is required.");
+ }
+}
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs
new file mode 100644
index 000000000..9af7f87d1
--- /dev/null
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs
@@ -0,0 +1,206 @@
+namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
+
+public enum DataValueKind { Unspecified = 0, Null = 1, Boolean = 2, Int8 = 3, Int16 = 4, Int32 = 5, Int64 = 6, UInt8 = 7, UInt16 = 8, UInt32 = 9, UInt64 = 10, Float = 11, Double = 12, String = 13, Bytes = 14, Timestamp = 15, Guid = 16, Array = 17 }
+public enum DataItemStatus { Unspecified = 0, Good = 1, Denied = 2, NotFound = 3, Unsupported = 4, InvalidArgument = 5, Unavailable = 6, WaitingForInitialData = 7, Stale = 8, LimitExceeded = 9, InvalidContinuation = 10, TypeMismatch = 11, ResourceExhausted = 12 }
+public enum DataReadiness { Unspecified = 0, Ready = 1, WaitingForInitialData = 2, Unavailable = 3, Invalidated = 4 }
+public enum DataWriteState { Unspecified = 0, RejectedBeforeDispatch = 1, DriverConfirmedSuccess = 2, DriverConfirmedFailure = 3, AcceptedUnconfirmed = 4, OutcomeUnknown = 5 }
+public enum DataChangeTrigger { Unspecified = 0, Status = 1, StatusValue = 2, StatusValueTimestamp = 3 }
+public enum DataStreamControlKind { Unspecified = 0, SnapshotBegin = 1, SnapshotEnd = 2, CatalogInvalidated = 3, AuthorityInvalidated = 4, Heartbeat = 5, Reset = 6, Coalesced = 7 }
+
+///
+/// Owned immutable value. Factory methods copy mutable inputs; Retain creates an independently
+/// disposable lease. Consumers must dispose every lease after asynchronous use completes.
+///
+public sealed class DataValue : IDisposable
+{
+ private readonly object? _payload;
+ private bool _disposed;
+ private DataValue(DataValueKind kind, object? payload, IReadOnlyList? dimensions = null)
+ { Kind = kind; _payload = payload; Dimensions = dimensions; }
+ public DataValueKind Kind { get; }
+ public IReadOnlyList? Dimensions { get; }
+ public static DataValue Null() => new(DataValueKind.Null, null);
+ public static DataValue FromBytes(byte[] bytes) => new(DataValueKind.Bytes, (byte[])bytes.Clone());
+ public static DataValue FromScalar(DataValueKind kind, object value)
+ {
+ ArgumentNullException.ThrowIfNull(value);
+ var valid = kind switch
+ {
+ DataValueKind.Boolean => value is bool, DataValueKind.Int8 => value is sbyte,
+ DataValueKind.Int16 => value is short, DataValueKind.Int32 => value is int,
+ DataValueKind.Int64 => value is long, DataValueKind.UInt8 => value is byte,
+ DataValueKind.UInt16 => value is ushort, DataValueKind.UInt32 => value is uint,
+ DataValueKind.UInt64 => value is ulong, DataValueKind.Float => value is float,
+ DataValueKind.Double => value is double, DataValueKind.String => value is string,
+ DataValueKind.Timestamp => value is DateTimeOffset, DataValueKind.Guid => value is Guid,
+ _ => false
+ };
+ if (!valid) throw new ArgumentException("Unsupported value or kind mismatch.", nameof(value));
+ if (value is DateTimeOffset timestamp && timestamp.Offset != TimeSpan.Zero)
+ throw new ArgumentException("Timestamp must be UTC.", nameof(value));
+ return new(kind, value);
+ }
+ /// Copies elements and shape; arrays contain one declared scalar kind, including empty arrays.
+ public static DataValue FromArray(DataValueKind elementKind, IReadOnlyList