feat: define validated grpc data contracts and codecs
This commit is contained in:
@@ -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).
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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;
|
||||
|
||||
/// <summary>Explicit typed values only; limits are checked before constructing domain arrays.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Commons.Protos;
|
||||
|
||||
/// <summary>Frozen wire contract identifiers; removed field numbers must remain reserved.</summary>
|
||||
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.");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@
|
||||
<Protobuf Include="Protos\deployment_artifact.proto" GrpcServices="Both"/>
|
||||
<Protobuf Include="Protos\telemetry.proto" GrpcServices="Both"/>
|
||||
<Protobuf Include="Protos\mesh_transport.proto" GrpcServices="Both"/>
|
||||
<Protobuf Include="Protos\data_connection.proto" GrpcServices="Both"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
/// <summary>Origin-qualified public identity; namespace indexes are never portable identities.</summary>
|
||||
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 }
|
||||
|
||||
/// <summary>A request is bound to a cluster and, for node mode, an expected node.</summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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.");
|
||||
}
|
||||
}
|
||||
/// <summary>Actual serving replica provenance, distinct from origin ownership.</summary>
|
||||
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
|
||||
{
|
||||
/// <summary>Reject zero and unrecognized values for a required enum decision.</summary>
|
||||
public static void Required<T>(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.");
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
|
||||
/// <summary>
|
||||
/// Owned immutable value. Factory methods copy mutable inputs; Retain creates an independently
|
||||
/// disposable lease. Consumers must dispose every lease after asynchronous use completes.
|
||||
/// </summary>
|
||||
public sealed class DataValue : IDisposable
|
||||
{
|
||||
private readonly object? _payload;
|
||||
private bool _disposed;
|
||||
private DataValue(DataValueKind kind, object? payload, IReadOnlyList<int>? dimensions = null)
|
||||
{ Kind = kind; _payload = payload; Dimensions = dimensions; }
|
||||
public DataValueKind Kind { get; }
|
||||
public IReadOnlyList<int>? 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);
|
||||
}
|
||||
/// <summary>Copies elements and shape; arrays contain one declared scalar kind, including empty arrays.</summary>
|
||||
public static DataValue FromArray(DataValueKind elementKind, IReadOnlyList<object> elements, IReadOnlyList<int> dimensions)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(elements); ArgumentNullException.ThrowIfNull(dimensions);
|
||||
if (!IsSupportedArrayElementKind(elementKind))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(elementKind));
|
||||
}
|
||||
if (dimensions.Count == 0 || dimensions.Any(d => d < 0)) throw new ArgumentException("Invalid dimensions.", nameof(dimensions));
|
||||
long count = 1;
|
||||
foreach (var dimension in dimensions) count = checked(count * dimension);
|
||||
if (count != elements.Count) throw new ArgumentException("Dimensions do not match element count.", nameof(dimensions));
|
||||
var copy = new object[elements.Count];
|
||||
for (var i = 0; i < copy.Length; i++) { using var scalar = FromScalar(elementKind, elements[i]); copy[i] = scalar._payload!; }
|
||||
return new(DataValueKind.Array, new ArrayPayload(elementKind, copy), Array.AsReadOnly(dimensions.ToArray()));
|
||||
}
|
||||
/// <summary>Whether the value kind is supported as an element of a typed array.</summary>
|
||||
public static bool IsSupportedArrayElementKind(DataValueKind kind) => kind is
|
||||
DataValueKind.Boolean or DataValueKind.Int8 or DataValueKind.Int16 or DataValueKind.Int32 or
|
||||
DataValueKind.Int64 or DataValueKind.UInt8 or DataValueKind.UInt16 or DataValueKind.UInt32 or
|
||||
DataValueKind.UInt64 or DataValueKind.Float or DataValueKind.Double or DataValueKind.String or
|
||||
DataValueKind.Timestamp or DataValueKind.Guid;
|
||||
|
||||
public object GetScalar() { ThrowIfDisposed(); return Kind is DataValueKind.Null or DataValueKind.Bytes or DataValueKind.Array ? throw new InvalidOperationException() : _payload!; }
|
||||
public ReadOnlyMemory<byte> GetBytes() { ThrowIfDisposed(); return Kind == DataValueKind.Bytes ? ((byte[])_payload!).ToArray() : throw new InvalidOperationException(); }
|
||||
public DataValueKind ArrayElementKind { get { ThrowIfDisposed(); return (_payload as ArrayPayload)?.Kind ?? throw new InvalidOperationException(); } }
|
||||
public IReadOnlyList<object> GetArray() { ThrowIfDisposed(); return _payload is ArrayPayload a ? Array.AsReadOnly((object[])a.Elements.Clone()) : throw new InvalidOperationException(); }
|
||||
public DataValue Retain() { ThrowIfDisposed(); return new(Kind, _payload, Dimensions); }
|
||||
public void Dispose() => _disposed = true;
|
||||
private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
private sealed record ArrayPayload(DataValueKind Kind, object[] Elements);
|
||||
}
|
||||
|
||||
/// <summary>Owns its value lease; timestamps are independent original timestamps, never synthesized.</summary>
|
||||
public sealed record DataSample(DataValue Value, uint StatusCode, DateTimeOffset? SourceTimestampUtc,
|
||||
DateTimeOffset? ServerTimestampUtc, ServingIdentity Serving, long Version) : IDisposable
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(Value);
|
||||
ArgumentNullException.ThrowIfNull(Serving);
|
||||
Serving.Validate(requireEpochs: true);
|
||||
if (Version <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(Version));
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => Value.Dispose();
|
||||
}
|
||||
public sealed record DataWriteOutcome(DataWriteState State, uint StatusCode, string? Diagnostic)
|
||||
{
|
||||
public bool IsConfirmedSuccess => State == DataWriteState.DriverConfirmedSuccess;
|
||||
public void Validate() => DataContractValidation.Required(State);
|
||||
}
|
||||
public sealed record DataItemHandle(string SubscriptionId, long StreamEpoch, ulong Handle, long ItemRevision)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(SubscriptionId);
|
||||
if (StreamEpoch <= 0 || Handle == 0 || ItemRevision <= 0) throw new ArgumentOutOfRangeException(nameof(Handle));
|
||||
}
|
||||
}
|
||||
/// <summary>Renewal is anchored at monotonic request start, not response receipt.</summary>
|
||||
public sealed record MetadataLease(long CatalogEpoch, long AuthorityEpoch, TimeSpan Duration)
|
||||
{
|
||||
public void Validate() { if (Duration <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(Duration)); }
|
||||
public long Deadline(long requestStartTimestamp, TimeSpan transportMargin, TimeProvider clock)
|
||||
{
|
||||
Validate(); ArgumentNullException.ThrowIfNull(clock);
|
||||
if (transportMargin < TimeSpan.Zero || transportMargin >= Duration) throw new ArgumentOutOfRangeException(nameof(transportMargin));
|
||||
return checked(requestStartTimestamp + (long)((Duration - transportMargin).TotalSeconds * clock.TimestampFrequency));
|
||||
}
|
||||
}
|
||||
public sealed record DataBudget(TimeSpan Timeout, int MaxItems, long MaxBytes)
|
||||
{
|
||||
public void Validate() { if (Timeout <= TimeSpan.Zero || MaxItems <= 0 || MaxBytes <= 0) throw new ArgumentOutOfRangeException(nameof(Timeout)); }
|
||||
}
|
||||
[Flags] public enum DataOperations { None = 0, Browse = 1, Metadata = 2, Read = 4, Write = 8, Subscribe = 16 }
|
||||
/// <summary>
|
||||
/// Negotiated limits. When a peer omits the per-value element limit, the protocol default is 100,000.
|
||||
/// </summary>
|
||||
public sealed record DataLimits(int MaxPageItems, int MaxBatchItems, int MaxMessageBytes, int MaxMonitoredItems,
|
||||
int MaxStreams, long MaxPendingBytes, TimeSpan MaxMetadataLease, TimeSpan MaxSessionLifetime,
|
||||
TimeSpan WriteRetryWindow, int MaxValueElements = 100_000)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
if (MaxPageItems <= 0 || MaxBatchItems <= 0 || MaxMessageBytes <= 0 || MaxMonitoredItems <= 0 ||
|
||||
MaxStreams <= 0 || MaxPendingBytes <= 0 || MaxMetadataLease <= TimeSpan.Zero ||
|
||||
MaxSessionLifetime <= TimeSpan.Zero || WriteRetryWindow <= TimeSpan.Zero || MaxValueElements <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(DataLimits), "Limits must be positive.");
|
||||
}
|
||||
}
|
||||
}
|
||||
public sealed record DataCapabilities(int ProtocolMajor, int ProtocolMinor, ServingIdentity Serving, DataReadiness Readiness,
|
||||
DataOperations Operations, IReadOnlySet<DataValueKind> ValueKinds, DataLimits Limits, bool CompactBatches,
|
||||
int CompactCodecVersion, string ClusterId)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(ClusterId);
|
||||
ArgumentNullException.ThrowIfNull(Serving);
|
||||
DataContractValidation.Required(Readiness);
|
||||
Serving.Validate(requireEpochs: Readiness == DataReadiness.Ready);
|
||||
if (ProtocolMajor <= 0 || ProtocolMinor < 0 || CompactCodecVersion < 0 ||
|
||||
(CompactBatches && CompactCodecVersion == 0))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(ProtocolMajor));
|
||||
}
|
||||
ArgumentNullException.ThrowIfNull(Limits);
|
||||
Limits.Validate();
|
||||
ArgumentNullException.ThrowIfNull(ValueKinds);
|
||||
foreach (var kind in ValueKinds)
|
||||
{
|
||||
DataContractValidation.Required(kind);
|
||||
}
|
||||
const DataOperations known = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read |
|
||||
DataOperations.Write | DataOperations.Subscribe;
|
||||
if ((Operations & ~known) != 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(Operations));
|
||||
}
|
||||
}
|
||||
}
|
||||
public sealed record DataMetadata(DataView View, string BrowseName, string NodeKind, DataValueKind ValueKind, int ValueRank,
|
||||
IReadOnlyList<int> Dimensions, bool Writable, DataOperations AllowedOperations, long CatalogRevision,
|
||||
string? StableSourceId, string? EngineeringUnits, bool IsStale, DataValueKind? ArrayElementKind = null)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(View);
|
||||
View.Validate();
|
||||
DataContractValidation.Required(ValueKind);
|
||||
ArgumentNullException.ThrowIfNull(Dimensions);
|
||||
if (CatalogRevision <= 0 || Dimensions.Any(d => d < 0))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(CatalogRevision));
|
||||
}
|
||||
if (ValueKind == DataValueKind.Array && (ValueRank <= 0 || Dimensions.Count != ValueRank))
|
||||
{
|
||||
throw new ArgumentException("Array rank and dimensions must agree.", nameof(ValueRank));
|
||||
}
|
||||
if (ValueKind != DataValueKind.Array && (ValueRank != -1 || Dimensions.Count != 0))
|
||||
{
|
||||
throw new ArgumentException("A scalar requires rank -1 and no dimensions.", nameof(ValueRank));
|
||||
}
|
||||
if (ValueKind == DataValueKind.Array)
|
||||
{
|
||||
if (ArrayElementKind is not { } kind || !DataValue.IsSupportedArrayElementKind(kind))
|
||||
{
|
||||
throw new ArgumentException("Arrays require a supported element kind.", nameof(ArrayElementKind));
|
||||
}
|
||||
}
|
||||
else if (ArrayElementKind is not null)
|
||||
{
|
||||
throw new ArgumentException("Only arrays may specify an element kind.", nameof(ArrayElementKind));
|
||||
}
|
||||
}
|
||||
}
|
||||
public sealed record DataItemResult<T>(string CorrelationId, DataItemStatus Status, T? Value, string? Diagnostic);
|
||||
public sealed record DataBrowseBranch(DataView Parent, DataItemStatus Status, IReadOnlyList<DataMetadata> Items,
|
||||
bool Complete, string? Continuation, MetadataLease? Lease);
|
||||
@@ -0,0 +1,45 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// A caller-bound facade. Direct access needs no namespace mount; every operation applies the
|
||||
/// bound caller's authority and retains the same policy and outcomes.
|
||||
/// </summary>
|
||||
public interface IDataConnection : IDataCatalogService, IDataReadService, IDataWriteService, IDataSubscriptionService, IAsyncDisposable
|
||||
{
|
||||
DataTarget Target { get; }
|
||||
TimeProvider Clock { get; }
|
||||
Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Authenticated authority established by the host, never supplied by an operation payload.
|
||||
/// CredentialVersion is a non-secret authority fingerprint, not a bearer credential. The original
|
||||
/// expiry is retained so renewal or replacement cannot extend an already admitted operation.
|
||||
/// </summary>
|
||||
public sealed record DataAuthenticatedContext(string PrincipalId, string ApiKeyId, string CredentialVersion,
|
||||
DateTimeOffset? CredentialExpiresUtc, long AuthorityEpoch)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(PrincipalId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(ApiKeyId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(CredentialVersion);
|
||||
if (CredentialExpiresUtc is { Offset: var offset } && offset != TimeSpan.Zero)
|
||||
{
|
||||
throw new ArgumentException("Credential expiry must be UTC.", nameof(CredentialExpiresUtc));
|
||||
}
|
||||
if (AuthorityEpoch <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(AuthorityEpoch));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates strictly caller-bound local facades. Hosts construct context from authenticated
|
||||
/// authority, never from caller-supplied request fields, and must validate it before creation.
|
||||
/// </summary>
|
||||
public interface IDataConnectionFactory
|
||||
{
|
||||
IDataConnection Create(DataAuthenticatedContext context, DataTarget target);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
public sealed record BrowseRequest(DataView Parent, string? Filter, string? Continuation, DataBudget Budget);
|
||||
public sealed record MetadataRequest(IReadOnlyList<DataView> Views, DataBudget Budget);
|
||||
public sealed record ReadItem(string CorrelationId, DataView View, TimeSpan? MaximumAge);
|
||||
public sealed record ReadRequest(IReadOnlyList<ReadItem> Items, DataBudget Budget);
|
||||
/// <summary>Sample is owned by the recipient. Status/age/readiness are distinct from original sample quality.</summary>
|
||||
public sealed record ReadResult(string CorrelationId, DataItemStatus Status, DataReadiness Readiness,
|
||||
TimeSpan? Age, DataSample? Sample, string? Diagnostic) : IDisposable
|
||||
{
|
||||
public void Dispose() => Sample?.Dispose();
|
||||
}
|
||||
public sealed record WriteItem(string CorrelationId, string OperationId, DataView View, DataValue Value,
|
||||
long ExpectedCatalogRevision, string ExpectedServingIncarnation, TimeSpan RemainingBudget);
|
||||
/// <summary>
|
||||
/// Admission binds the stable principal and original credential separately. Before dispatch,
|
||||
/// recheck the original key's current principal and credential version against authority and its
|
||||
/// original expiry even when the epoch is unchanged. ApiKeyId and CredentialVersion are non-secret
|
||||
/// identifiers, never the bearer credential.
|
||||
/// </summary>
|
||||
public sealed record DataWriteAdmission(string PrincipalId, DataView View, long AuthorityEpoch, long CatalogRevision,
|
||||
string ServingIncarnation, string DriverIncarnation, string OperationId, long MonotonicExpiry,
|
||||
string ApiKeyId, DateTimeOffset? CredentialExpiresUtc, string CredentialVersion)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(PrincipalId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(ApiKeyId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(CredentialVersion);
|
||||
ArgumentNullException.ThrowIfNull(View);
|
||||
View.Validate();
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(ServingIncarnation);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(DriverIncarnation);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(OperationId);
|
||||
if (CredentialExpiresUtc is { Offset: var offset } && offset != TimeSpan.Zero)
|
||||
{
|
||||
throw new ArgumentException("Credential expiry must be UTC.", nameof(CredentialExpiresUtc));
|
||||
}
|
||||
}
|
||||
}
|
||||
public sealed record WriteBatch(IReadOnlyList<WriteItem> Items, DataBudget Budget);
|
||||
public sealed record WriteItemResult(string CorrelationId, DataWriteOutcome Outcome);
|
||||
|
||||
/// <summary>Operations use the authenticated caller bound to the containing connection facade.</summary>
|
||||
public interface IDataCatalogService
|
||||
{
|
||||
Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken);
|
||||
Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken);
|
||||
}
|
||||
/// <summary>Operations use the authenticated caller bound to the containing connection facade.</summary>
|
||||
public interface IDataReadService
|
||||
{
|
||||
/// <summary>Reads cached values only, in request order; never initiates a device read.</summary>
|
||||
Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken);
|
||||
}
|
||||
/// <summary>Operations use the authenticated caller bound to the containing connection facade.</summary>
|
||||
public interface IDataWriteService
|
||||
{
|
||||
/// <summary>Returns ordered item outcomes; cancellation after dispatch cannot undo a write.</summary>
|
||||
Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed record DataSubscriptionSettings(TimeSpan SamplingInterval, TimeSpan PublishingInterval,
|
||||
DataChangeTrigger Trigger, double? Deadband)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
DataContractValidation.Required(Trigger);
|
||||
if (SamplingInterval < TimeSpan.Zero || PublishingInterval < TimeSpan.Zero ||
|
||||
(Deadband is { } deadband && (!double.IsFinite(deadband) || deadband < 0)))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(Deadband));
|
||||
}
|
||||
}
|
||||
}
|
||||
public sealed record DataSubscriptionItem(string ClientItemId, DataView View, DataSubscriptionSettings Settings);
|
||||
public abstract record DataSubscriptionCommand(string SubscriptionId, long StreamEpoch, string CommandId, TimeSpan AcknowledgementTimeout);
|
||||
public sealed record OpenSubscription(string SubscriptionId, long StreamEpoch, string CommandId, TimeSpan AcknowledgementTimeout,
|
||||
IReadOnlyList<DataSubscriptionItem> Items, bool WatchCatalogOnly, TimeSpan SessionLifetime, DataBudget SnapshotBudget)
|
||||
: DataSubscriptionCommand(SubscriptionId, StreamEpoch, CommandId, AcknowledgementTimeout);
|
||||
public sealed record AddSubscriptionItems(string SubscriptionId, long StreamEpoch, string CommandId, TimeSpan AcknowledgementTimeout,
|
||||
IReadOnlyList<DataSubscriptionItem> Items) : DataSubscriptionCommand(SubscriptionId, StreamEpoch, CommandId, AcknowledgementTimeout);
|
||||
public sealed record ModifySubscriptionItems(string SubscriptionId, long StreamEpoch, string CommandId, TimeSpan AcknowledgementTimeout,
|
||||
IReadOnlyList<DataSubscriptionItem> Items) : DataSubscriptionCommand(SubscriptionId, StreamEpoch, CommandId, AcknowledgementTimeout);
|
||||
public sealed record RemoveSubscriptionItems(string SubscriptionId, long StreamEpoch, string CommandId, TimeSpan AcknowledgementTimeout,
|
||||
IReadOnlyList<DataItemHandle> Items) : DataSubscriptionCommand(SubscriptionId, StreamEpoch, CommandId, AcknowledgementTimeout);
|
||||
public sealed record DataSubscriptionItemAck(string ClientItemId, DataItemStatus Status, DataItemHandle? Handle,
|
||||
DataSubscriptionSettings? RevisedSettings, string? Diagnostic);
|
||||
public abstract record DataSubscriptionFrame(string SubscriptionId, long StreamEpoch, long Sequence);
|
||||
public sealed record DataSubscriptionAck(string SubscriptionId, long StreamEpoch, long Sequence, string CommandId,
|
||||
IReadOnlyList<DataSubscriptionItemAck> Items) : DataSubscriptionFrame(SubscriptionId, StreamEpoch, Sequence);
|
||||
public sealed record PartitionWatermark(int PartitionId, long Version);
|
||||
public sealed record DataSubscriptionControl(string SubscriptionId, long StreamEpoch, long Sequence, DataStreamControlKind Kind,
|
||||
IReadOnlyList<PartitionWatermark> Watermarks, long CatalogEpoch, long AuthorityEpoch, string? Diagnostic)
|
||||
: DataSubscriptionFrame(SubscriptionId, StreamEpoch, Sequence);
|
||||
/// <summary>Each frame owns its samples until disposed, including during asynchronous encoding.</summary>
|
||||
public sealed record DataSubscriptionValues(string SubscriptionId, long StreamEpoch, long Sequence, bool IsSnapshot,
|
||||
IReadOnlyList<DataSubscriptionValue> Items) : DataSubscriptionFrame(SubscriptionId, StreamEpoch, Sequence), IDisposable
|
||||
{
|
||||
public void Dispose() { foreach (var item in Items) item.Sample.Dispose(); }
|
||||
}
|
||||
public sealed record DataSubscriptionValue(DataItemHandle Handle, DataSample Sample);
|
||||
|
||||
/// <summary>Commands and frames are ordered per stream. Dispose cancels the stream and releases demand.</summary>
|
||||
public interface IDataSubscription : IAsyncDisposable
|
||||
{
|
||||
Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken);
|
||||
IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
/// <summary>Operations use the authenticated caller bound to the containing connection facade.</summary>
|
||||
public interface IDataSubscriptionService
|
||||
{
|
||||
/// <summary>Stream lifetime is independent of unary deadlines; cancellation ends the stream.</summary>
|
||||
Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
/// <summary>Additive driver capability for explicit dispatch and completion outcomes; IWritable remains supported.</summary>
|
||||
public interface IWriteOutcomeCapability
|
||||
{
|
||||
Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(
|
||||
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
using Google.Protobuf;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData"), Trait("Phase", "P01"), Trait("Category", "Unit")]
|
||||
public sealed class GrpcDataCodecTests
|
||||
{
|
||||
[Fact]
|
||||
public void UInt64_and_empty_arrays_round_trip()
|
||||
{
|
||||
using var original = DataValue.FromArray(
|
||||
DataValueKind.UInt64,
|
||||
new object[] { ulong.MaxValue, 0UL },
|
||||
new[] { 2 }
|
||||
);
|
||||
using var decoded = TypedValueCodec.Decode(TypedValueCodec.Encode(original));
|
||||
decoded.ArrayElementKind.ShouldBe(DataValueKind.UInt64);
|
||||
decoded.GetArray().ShouldBe(new object[] { ulong.MaxValue, 0UL });
|
||||
using var empty = DataValue.FromArray(
|
||||
DataValueKind.Int32,
|
||||
Array.Empty<object>(),
|
||||
new[] { 0, 2 }
|
||||
);
|
||||
using var roundTrip = TypedValueCodec.Decode(TypedValueCodec.Encode(empty));
|
||||
roundTrip.Dimensions.ShouldBe(new[] { 0, 2 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Null_and_empty_bytes_are_distinct()
|
||||
{
|
||||
using var value = DataValue.FromBytes(Array.Empty<byte>());
|
||||
using var decoded = TypedValueCodec.Decode(TypedValueCodec.Encode(value));
|
||||
decoded.Kind.ShouldBe(DataValueKind.Bytes);
|
||||
decoded.GetBytes().Length.ShouldBe(0);
|
||||
using var nullValue = TypedValueCodec.Decode(TypedValueCodec.Encode(DataValue.Null()));
|
||||
nullValue.Kind.ShouldBe(DataValueKind.Null);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Malformed_shape_and_oversized_payload_are_rejected()
|
||||
{
|
||||
var wire = new ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.TypedValue
|
||||
{
|
||||
Kind = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.ValueKind.Array,
|
||||
Array = new()
|
||||
{
|
||||
ElementKind = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.ValueKind.Int32,
|
||||
},
|
||||
};
|
||||
wire.Array.Dimensions.Add(1000000);
|
||||
Should.Throw<ArgumentException>(() => TypedValueCodec.Decode(wire, 10, 1000));
|
||||
using var large = DataValue.FromBytes(new byte[100]);
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
TypedValueCodec.Decode(TypedValueCodec.Encode(large), 10, 10)
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Encoding_does_not_take_ownership_of_the_sample()
|
||||
{
|
||||
using var original = DataValue.FromBytes(new byte[] { 1, 2 });
|
||||
var wire = TypedValueCodec.Encode(original);
|
||||
original.Dispose();
|
||||
using var decoded = TypedValueCodec.Decode(wire);
|
||||
decoded.GetBytes().ToArray().ShouldBe(new byte[] { 1, 2 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Numeric_boundaries_and_special_floats_round_trip()
|
||||
{
|
||||
foreach (
|
||||
var pair in new (DataValueKind Kind, object Value)[]
|
||||
{
|
||||
(DataValueKind.Int8, sbyte.MinValue),
|
||||
(DataValueKind.Int16, short.MaxValue),
|
||||
(DataValueKind.Int32, int.MinValue),
|
||||
(DataValueKind.Int64, long.MaxValue),
|
||||
(DataValueKind.UInt8, byte.MaxValue),
|
||||
(DataValueKind.UInt16, ushort.MaxValue),
|
||||
(DataValueKind.UInt32, uint.MaxValue),
|
||||
(DataValueKind.UInt64, ulong.MaxValue),
|
||||
(DataValueKind.Float, float.NaN),
|
||||
(DataValueKind.Double, double.PositiveInfinity),
|
||||
}
|
||||
)
|
||||
{
|
||||
using var value = DataValue.FromScalar(pair.Kind, pair.Value);
|
||||
using var decoded = TypedValueCodec.Decode(TypedValueCodec.Encode(value));
|
||||
decoded.GetScalar().ShouldBe(pair.Value);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wrong_payload_and_array_element_type_are_rejected()
|
||||
{
|
||||
var wrong = new ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.TypedValue
|
||||
{
|
||||
Kind = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.ValueKind.Int8,
|
||||
Unsigned = 1,
|
||||
};
|
||||
Should.Throw<ArgumentException>(() => TypedValueCodec.Decode(wrong));
|
||||
var array = new ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.TypedValue
|
||||
{
|
||||
Kind = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.ValueKind.Array,
|
||||
Array = new()
|
||||
{
|
||||
ElementKind = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.ValueKind.Int32,
|
||||
},
|
||||
};
|
||||
array.Array.Dimensions.Add(1);
|
||||
array.Array.Elements.Add(wrong);
|
||||
Should.Throw<ArgumentException>(() => TypedValueCodec.Decode(array));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Array_metadata_preserves_element_kind_even_for_empty_arrays()
|
||||
{
|
||||
var view = new DataView(
|
||||
new DataAddress("c", "urn:test", "string", "x"),
|
||||
DataRealm.Raw,
|
||||
null,
|
||||
0,
|
||||
"subject"
|
||||
);
|
||||
foreach (var elementKind in new[] { DataValueKind.Int32, DataValueKind.String })
|
||||
{
|
||||
var metadata = new DataMetadata(
|
||||
view,
|
||||
"x",
|
||||
"Variable",
|
||||
DataValueKind.Array,
|
||||
1,
|
||||
new[] { 0 },
|
||||
false,
|
||||
DataOperations.Read,
|
||||
1,
|
||||
null,
|
||||
null,
|
||||
false,
|
||||
elementKind
|
||||
);
|
||||
var decoded = DataProtoMapper.DecodeMetadata(DataProtoMapper.EncodeMetadata(metadata));
|
||||
decoded.ArrayElementKind.ShouldBe(elementKind);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Array_metadata_rejects_missing_and_invalid_element_kind()
|
||||
{
|
||||
var view = new DataView(
|
||||
new DataAddress("c", "urn:test", "string", "x"),
|
||||
DataRealm.Raw,
|
||||
null,
|
||||
0,
|
||||
"subject"
|
||||
);
|
||||
var metadata = new DataMetadata(
|
||||
view,
|
||||
"x",
|
||||
"Variable",
|
||||
DataValueKind.Array,
|
||||
1,
|
||||
new[] { 0 },
|
||||
false,
|
||||
DataOperations.Read,
|
||||
1,
|
||||
null,
|
||||
null,
|
||||
false,
|
||||
DataValueKind.Int32
|
||||
);
|
||||
var wire = DataProtoMapper.EncodeMetadata(metadata);
|
||||
wire.ClearArrayElementKind();
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeMetadata(wire));
|
||||
wire.ArrayElementKind = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.ValueKind.Array;
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeMetadata(wire));
|
||||
var scalar = metadata with { ValueKind = DataValueKind.Int32 };
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.EncodeMetadata(scalar));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Write_batch_uses_independent_item_and_array_limits()
|
||||
{
|
||||
var view = new DataView(
|
||||
new DataAddress("c", "urn:test", "string", "x"),
|
||||
DataRealm.Raw,
|
||||
null,
|
||||
0,
|
||||
"subject"
|
||||
);
|
||||
using var value = DataValue.FromArray(
|
||||
DataValueKind.Int32,
|
||||
Enumerable.Range(0, 100).Cast<object>().ToArray(),
|
||||
new[] { 100 }
|
||||
);
|
||||
var item = new WriteItem(
|
||||
"correlation",
|
||||
"operation",
|
||||
view,
|
||||
value,
|
||||
1,
|
||||
"incarnation",
|
||||
TimeSpan.FromSeconds(1)
|
||||
);
|
||||
var wire = DataProtoMapper.EncodeWriteRequest(
|
||||
new WriteBatch(new[] { item }, new DataBudget(TimeSpan.FromSeconds(1), 1, 100000))
|
||||
);
|
||||
var decoded = DataProtoMapper.DecodeWriteRequest(wire, 1, 100000, 1000);
|
||||
try
|
||||
{
|
||||
decoded.Items.Single().Value.GetArray().Count.ShouldBe(100);
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var entry in decoded.Items)
|
||||
entry.Value.Dispose();
|
||||
}
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeWriteRequest(wire, 1, 100, 1000)
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Write_hash_ignores_retry_fields_but_binds_semantic_preconditions()
|
||||
{
|
||||
var view = new DataView(
|
||||
new DataAddress("c", "urn:test", "string", "x"),
|
||||
DataRealm.Raw,
|
||||
null,
|
||||
0,
|
||||
"subject"
|
||||
);
|
||||
using var value = DataValue.FromScalar(DataValueKind.Int32, 5);
|
||||
using var other = DataValue.FromScalar(DataValueKind.Int32, 6);
|
||||
var item = new WriteItem("one", "op", view, value, 1, "inc", TimeSpan.FromSeconds(1));
|
||||
var hash = DataProtoMapper.WritePayloadHash(item);
|
||||
DataProtoMapper
|
||||
.WritePayloadHash(
|
||||
item with
|
||||
{
|
||||
CorrelationId = "two",
|
||||
RemainingBudget = TimeSpan.FromMilliseconds(5),
|
||||
}
|
||||
)
|
||||
.ShouldBe(hash);
|
||||
DataProtoMapper.WritePayloadHash(item with { Value = other }).ShouldNotBe(hash);
|
||||
DataProtoMapper
|
||||
.WritePayloadHash(item with { ExpectedCatalogRevision = 2 })
|
||||
.ShouldNotBe(hash);
|
||||
DataProtoMapper
|
||||
.WritePayloadHash(
|
||||
item with
|
||||
{
|
||||
View = view with { Address = view.Address with { Identifier = "y" } },
|
||||
}
|
||||
)
|
||||
.ShouldNotBe(hash);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Timestamp_ticks_round_trip_and_subtick_precision_is_rejected()
|
||||
{
|
||||
var instant = DateTimeOffset.UnixEpoch.AddTicks(1234567);
|
||||
using var value = DataValue.FromScalar(DataValueKind.Timestamp, instant);
|
||||
var wire = TypedValueCodec.Encode(value);
|
||||
using var decoded = TypedValueCodec.Decode(wire);
|
||||
decoded.GetScalar().ShouldBe(instant);
|
||||
wire.Timestamp.Nanos += 1;
|
||||
Should.Throw<ArgumentException>(() => TypedValueCodec.Decode(wire));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Compatible_capabilities_ignore_unknown_kinds_and_fallback_compact_version()
|
||||
{
|
||||
var limits = new DataLimits(
|
||||
10,
|
||||
10,
|
||||
10000,
|
||||
10,
|
||||
2,
|
||||
10000,
|
||||
TimeSpan.FromSeconds(1),
|
||||
TimeSpan.FromSeconds(1),
|
||||
TimeSpan.FromSeconds(1)
|
||||
);
|
||||
var capabilities = new DataCapabilities(
|
||||
1,
|
||||
0,
|
||||
new ServingIdentity("node", "inc", "primary", 1, 2),
|
||||
DataReadiness.Ready,
|
||||
DataOperations.Read,
|
||||
new HashSet<DataValueKind> { DataValueKind.Int32 },
|
||||
limits,
|
||||
true,
|
||||
1,
|
||||
"cluster"
|
||||
);
|
||||
var wire = DataProtoMapper.EncodeCapabilities(capabilities);
|
||||
wire.ValueKinds.Add((ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.ValueKind)999);
|
||||
wire.Operations |= 0x80000000;
|
||||
wire.CompactCodecVersion = 99;
|
||||
var decoded = DataProtoMapper.DecodeCapabilities(wire);
|
||||
decoded.ClusterId.ShouldBe("cluster");
|
||||
decoded.ValueKinds.ShouldContain(DataValueKind.Int32);
|
||||
decoded.ValueKinds.Count.ShouldBe(1);
|
||||
decoded.Operations.ShouldBe(DataOperations.Read);
|
||||
DataProtoMapper.NegotiateCompact(decoded).ShouldBeFalse();
|
||||
wire.ProtocolMajor = 2;
|
||||
Should.Throw<NotSupportedException>(() => DataProtoMapper.DecodeCapabilities(wire));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Receiver_limits_reject_collection_counts_and_aggregate_write_expansion()
|
||||
{
|
||||
var view = new DataView(
|
||||
new DataAddress("c", "urn:test", "string", "x"),
|
||||
DataRealm.Raw,
|
||||
null,
|
||||
0,
|
||||
"subject"
|
||||
);
|
||||
var budget = new DataBudget(TimeSpan.FromSeconds(1), 100, 100000);
|
||||
var read = DataProtoMapper.EncodeReadRequest(
|
||||
new ReadRequest(
|
||||
new[] { new ReadItem("1", view, null), new ReadItem("2", view, null) },
|
||||
budget
|
||||
)
|
||||
);
|
||||
var metadata = DataProtoMapper.EncodeMetadataRequest(
|
||||
new MetadataRequest(new[] { view, view }, budget)
|
||||
);
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeReadRequest(read, new DataDecodeLimits(1, 100000, 100))
|
||||
);
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeMetadataRequest(metadata, new DataDecodeLimits(1, 100000, 100))
|
||||
);
|
||||
using var first = DataValue.FromBytes(new byte[400]);
|
||||
using var second = DataValue.FromBytes(new byte[400]);
|
||||
var write = DataProtoMapper.EncodeWriteRequest(
|
||||
new WriteBatch(
|
||||
new[]
|
||||
{
|
||||
new WriteItem("1", "o1", view, first, 1, "inc", TimeSpan.FromSeconds(1)),
|
||||
new WriteItem("2", "o2", view, second, 1, "inc", TimeSpan.FromSeconds(1)),
|
||||
},
|
||||
budget
|
||||
)
|
||||
);
|
||||
write.CalculateSize().ShouldBeLessThan(2000);
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeWriteRequest(write, 2, 2000, 100)
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Malformed_settings_identity_and_versions_are_rejected()
|
||||
{
|
||||
var settings = new ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.Settings
|
||||
{
|
||||
SamplingTicks = 1,
|
||||
PublishingTicks = 1,
|
||||
Trigger = (int)DataChangeTrigger.StatusValue,
|
||||
Deadband = double.NaN,
|
||||
};
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeSettings(settings));
|
||||
var serving = new ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.Serving
|
||||
{
|
||||
NodeId = "",
|
||||
Incarnation = "i",
|
||||
Role = "primary",
|
||||
CatalogEpoch = 1,
|
||||
AuthorityEpoch = 1,
|
||||
};
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeServing(serving));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Write_requires_operation_identity_incarnation_and_positive_preconditions()
|
||||
{
|
||||
var view = new DataView(
|
||||
new DataAddress("c", "urn:test", "string", "x"),
|
||||
DataRealm.Raw,
|
||||
null,
|
||||
0,
|
||||
"subject"
|
||||
);
|
||||
using var value = DataValue.Null();
|
||||
var item = new WriteItem("c", "operation", view, value, 1, "inc", TimeSpan.FromSeconds(1));
|
||||
var request = DataProtoMapper.EncodeWriteRequest(
|
||||
new WriteBatch(new[] { item }, new DataBudget(TimeSpan.FromSeconds(1), 1, 10000))
|
||||
);
|
||||
var wire = request.Items[0];
|
||||
wire.OperationId = "";
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeWriteRequest(request, 1, 10000)
|
||||
);
|
||||
wire.OperationId = "operation";
|
||||
wire.ExpectedServingIncarnation = "";
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeWriteRequest(request, 1, 10000)
|
||||
);
|
||||
wire.ExpectedServingIncarnation = "inc";
|
||||
wire.ExpectedCatalogRevision = 0;
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeWriteRequest(request, 1, 10000)
|
||||
);
|
||||
wire.ExpectedCatalogRevision = 1;
|
||||
wire.RemainingBudgetTicks = 0;
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeWriteRequest(request, 1, 10000)
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Browse_and_nested_metadata_obey_receiver_limits()
|
||||
{
|
||||
var view = new DataView(
|
||||
new DataAddress("c", "urn:test", "string", "x"),
|
||||
DataRealm.Raw,
|
||||
null,
|
||||
0,
|
||||
"subject"
|
||||
);
|
||||
var budget = new DataBudget(TimeSpan.FromSeconds(1), 10, 100000);
|
||||
var request = DataProtoMapper.EncodeBrowseRequest(
|
||||
new BrowseRequest(view, new string('a', 200), null, budget)
|
||||
);
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeBrowseRequest(request, new DataDecodeLimits(1, 100, 100))
|
||||
);
|
||||
var metadata = new DataMetadata(
|
||||
view,
|
||||
"x",
|
||||
"Variable",
|
||||
DataValueKind.Array,
|
||||
16,
|
||||
Enumerable.Repeat(0, 16).ToArray(),
|
||||
false,
|
||||
DataOperations.Read,
|
||||
1,
|
||||
null,
|
||||
null,
|
||||
false,
|
||||
DataValueKind.Int32
|
||||
);
|
||||
var branch = new DataBrowseBranch(
|
||||
view,
|
||||
DataItemStatus.Good,
|
||||
new[] { metadata },
|
||||
true,
|
||||
null,
|
||||
null
|
||||
);
|
||||
var response = DataProtoMapper.EncodeBrowseResponse(branch);
|
||||
DataProtoMapper
|
||||
.DecodeBrowseResponse(response, new DataDecodeLimits(1, 10000, 100))
|
||||
.Items.Count.ShouldBe(1);
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeBrowseResponse(response, new DataDecodeLimits(1, 100, 100))
|
||||
);
|
||||
response.Items[0].Dimensions.Add(0);
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeBrowseResponse(response, new DataDecodeLimits(1, 10000, 100))
|
||||
);
|
||||
}
|
||||
}
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData"), Trait("Phase", "P01"), Trait("Category", "Unit")]
|
||||
public sealed class GrpcDataCompactCodecTests
|
||||
{
|
||||
[Fact]
|
||||
public void Sample_preserves_status_timestamps_and_provenance()
|
||||
{
|
||||
using var sample = new DataSample(
|
||||
DataValue.FromScalar(DataValueKind.UInt64, ulong.MaxValue),
|
||||
0x81234567,
|
||||
null,
|
||||
DateTimeOffset.UnixEpoch,
|
||||
new ServingIdentity("n", "i", "primary", 4, 5),
|
||||
8
|
||||
);
|
||||
using var decoded = DataProtoMapper.DecodeSample(DataProtoMapper.EncodeSample(sample));
|
||||
decoded.StatusCode.ShouldBe(sample.StatusCode);
|
||||
decoded.SourceTimestampUtc.ShouldBeNull();
|
||||
decoded.ServerTimestampUtc.ShouldBe(sample.ServerTimestampUtc);
|
||||
decoded.Serving.ShouldBe(sample.Serving);
|
||||
decoded.Version.ShouldBe(8);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Compact_and_fallback_preserve_explicit_absence_and_reject_stale_handles()
|
||||
{
|
||||
var serving = new ServingIdentity("n", "i", "primary", 1, 2);
|
||||
var h1 = new DataItemHandle("s", 1, 1, 1);
|
||||
var h2 = new DataItemHandle("s", 1, 2, 1);
|
||||
using var frame = new DataSubscriptionValues(
|
||||
"s",
|
||||
1,
|
||||
1,
|
||||
false,
|
||||
new[]
|
||||
{
|
||||
new DataSubscriptionValue(
|
||||
h1,
|
||||
new DataSample(DataValue.Null(), 12, DateTimeOffset.UnixEpoch, null, serving, 2)
|
||||
),
|
||||
new DataSubscriptionValue(
|
||||
h2,
|
||||
new DataSample(
|
||||
DataValue.FromBytes(Array.Empty<byte>()),
|
||||
13,
|
||||
null,
|
||||
null,
|
||||
serving,
|
||||
3
|
||||
)
|
||||
),
|
||||
}
|
||||
);
|
||||
var handles = new Dictionary<ulong, DataItemHandle> { [1] = h1, [2] = h2 };
|
||||
using var compact = DataProtoMapper.DecodeValues(
|
||||
DataProtoMapper.EncodeValues(frame, true),
|
||||
handles,
|
||||
10,
|
||||
10000,
|
||||
serving
|
||||
);
|
||||
using var fallback = DataProtoMapper.DecodeValues(
|
||||
DataProtoMapper.EncodeValues(frame, false),
|
||||
handles,
|
||||
10,
|
||||
10000,
|
||||
serving
|
||||
);
|
||||
compact.Items[1].Sample.SourceTimestampUtc.ShouldBeNull();
|
||||
compact.Items[1].Sample.StatusCode.ShouldBe(fallback.Items[1].Sample.StatusCode);
|
||||
compact.Items[1].Sample.Value.Kind.ShouldBe(fallback.Items[1].Sample.Value.Kind);
|
||||
handles[2] = h2 with { ItemRevision = 2 };
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeValues(
|
||||
DataProtoMapper.EncodeValues(frame, true),
|
||||
handles,
|
||||
10,
|
||||
10000,
|
||||
serving
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Compact_batch_rejects_mixed_provenance()
|
||||
{
|
||||
var first = new ServingIdentity("a", "i", "primary", 1, 2);
|
||||
var second = first with { NodeId = "b" };
|
||||
using var frame = new DataSubscriptionValues(
|
||||
"s",
|
||||
1,
|
||||
1,
|
||||
false,
|
||||
new[]
|
||||
{
|
||||
new DataSubscriptionValue(
|
||||
new DataItemHandle("s", 1, 1, 1),
|
||||
new DataSample(DataValue.Null(), 0, null, null, first, 1)
|
||||
),
|
||||
new DataSubscriptionValue(
|
||||
new DataItemHandle("s", 1, 2, 1),
|
||||
new DataSample(DataValue.Null(), 0, null, null, second, 1)
|
||||
),
|
||||
}
|
||||
);
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.EncodeValues(frame, true));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Control_and_ack_preserve_ordering_epochs_and_revisions()
|
||||
{
|
||||
var control = new DataSubscriptionControl(
|
||||
"s",
|
||||
3,
|
||||
9,
|
||||
DataStreamControlKind.CatalogInvalidated,
|
||||
new[] { new PartitionWatermark(2, 7) },
|
||||
4,
|
||||
5,
|
||||
null
|
||||
);
|
||||
var decoded = (DataSubscriptionControl)
|
||||
DataProtoMapper.DecodeControlOrAck(DataProtoMapper.EncodeControlOrAck(control));
|
||||
decoded.Kind.ShouldBe(control.Kind);
|
||||
decoded.Watermarks.Single().ShouldBe(control.Watermarks.Single());
|
||||
var ack = new DataSubscriptionAck(
|
||||
"s",
|
||||
3,
|
||||
10,
|
||||
"cmd",
|
||||
new[]
|
||||
{
|
||||
new DataSubscriptionItemAck(
|
||||
"item",
|
||||
DataItemStatus.Good,
|
||||
new DataItemHandle("s", 3, 7, 2),
|
||||
null,
|
||||
null
|
||||
),
|
||||
}
|
||||
);
|
||||
var decodedAck = (DataSubscriptionAck)
|
||||
DataProtoMapper.DecodeControlOrAck(DataProtoMapper.EncodeControlOrAck(ack));
|
||||
decodedAck.Items.Single().Handle.ShouldBe(ack.Items.Single().Handle);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void One_item_can_contain_many_array_elements_and_serving_is_authenticated()
|
||||
{
|
||||
var serving = new ServingIdentity("n", "i", "primary", 1, 2);
|
||||
var handle = new DataItemHandle("s", 1, 1, 1);
|
||||
using var frame = new DataSubscriptionValues(
|
||||
"s",
|
||||
1,
|
||||
1,
|
||||
false,
|
||||
new[]
|
||||
{
|
||||
new DataSubscriptionValue(
|
||||
handle,
|
||||
new DataSample(
|
||||
DataValue.FromArray(
|
||||
DataValueKind.Int32,
|
||||
Enumerable.Range(0, 100).Cast<object>().ToArray(),
|
||||
new[] { 100 }
|
||||
),
|
||||
0,
|
||||
null,
|
||||
null,
|
||||
serving,
|
||||
1
|
||||
)
|
||||
),
|
||||
}
|
||||
);
|
||||
var handles = new Dictionary<ulong, DataItemHandle> { [1] = handle };
|
||||
foreach (var compact in new[] { false, true })
|
||||
{
|
||||
var wire = DataProtoMapper.EncodeValues(frame, compact);
|
||||
using var decoded = DataProtoMapper.DecodeValues(
|
||||
wire,
|
||||
handles,
|
||||
1,
|
||||
100000,
|
||||
serving,
|
||||
1000
|
||||
);
|
||||
decoded.Items.Single().Sample.Value.GetArray().Count.ShouldBe(100);
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeValues(
|
||||
wire,
|
||||
handles,
|
||||
1,
|
||||
100000,
|
||||
serving with
|
||||
{
|
||||
Incarnation = "other",
|
||||
},
|
||||
1000
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fallback_mixed_provenance_and_ack_other_epoch_are_rejected()
|
||||
{
|
||||
var serving = new ServingIdentity("n", "i", "primary", 1, 2);
|
||||
var handle = new DataItemHandle("s", 1, 1, 1);
|
||||
using var frame = new DataSubscriptionValues(
|
||||
"s",
|
||||
1,
|
||||
1,
|
||||
false,
|
||||
new[]
|
||||
{
|
||||
new DataSubscriptionValue(
|
||||
handle,
|
||||
new DataSample(DataValue.Null(), 0, null, null, serving, 1)
|
||||
),
|
||||
}
|
||||
);
|
||||
var wire = DataProtoMapper.EncodeValues(frame, false);
|
||||
wire.Values.Items[0].Sample.Serving.NodeId = "other";
|
||||
var handles = new Dictionary<ulong, DataItemHandle> { [1] = handle };
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeValues(wire, handles, 1, 10000, serving)
|
||||
);
|
||||
var ack = new DataSubscriptionAck(
|
||||
"s",
|
||||
1,
|
||||
2,
|
||||
"command",
|
||||
new[] { new DataSubscriptionItemAck("x", DataItemStatus.Good, handle, null, null) }
|
||||
);
|
||||
var ackWire = DataProtoMapper.EncodeControlOrAck(ack);
|
||||
ackWire.Ack.Items[0].Handle.StreamEpoch = 2;
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeControlOrAck(ackWire));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Control_and_ack_obey_receiver_item_limits()
|
||||
{
|
||||
var control = new DataSubscriptionControl(
|
||||
"s",
|
||||
1,
|
||||
1,
|
||||
DataStreamControlKind.SnapshotEnd,
|
||||
new[] { new PartitionWatermark(1, 1), new PartitionWatermark(2, 1) },
|
||||
1,
|
||||
1,
|
||||
null
|
||||
);
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeControlOrAck(
|
||||
DataProtoMapper.EncodeControlOrAck(control),
|
||||
new DataDecodeLimits(1, 10000, 100)
|
||||
)
|
||||
);
|
||||
var ack = new DataSubscriptionAck(
|
||||
"s",
|
||||
1,
|
||||
2,
|
||||
"command",
|
||||
new[]
|
||||
{
|
||||
new DataSubscriptionItemAck("x", DataItemStatus.Good, null, null, null),
|
||||
new DataSubscriptionItemAck("y", DataItemStatus.Good, null, null, null),
|
||||
}
|
||||
);
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
DataProtoMapper.DecodeControlOrAck(
|
||||
DataProtoMapper.EncodeControlOrAck(ack),
|
||||
new DataDecodeLimits(1, 10000, 100)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Invalid_control_generations_and_cross_stream_removals_are_rejected()
|
||||
{
|
||||
var control = new DataSubscriptionControl(
|
||||
"s",
|
||||
1,
|
||||
1,
|
||||
DataStreamControlKind.SnapshotEnd,
|
||||
new[] { new PartitionWatermark(1, 1) },
|
||||
1,
|
||||
1,
|
||||
null
|
||||
);
|
||||
var wire = DataProtoMapper.EncodeControlOrAck(control);
|
||||
wire.Control.CatalogEpoch = -1;
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeControlOrAck(wire));
|
||||
wire.Control.CatalogEpoch = 1;
|
||||
wire.Control.Watermarks[0].PartitionId = -1;
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeControlOrAck(wire));
|
||||
wire.Control.Watermarks[0].PartitionId = 1;
|
||||
wire.Control.Watermarks[0].Version = -1;
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeControlOrAck(wire));
|
||||
var command = new RemoveSubscriptionItems(
|
||||
"s",
|
||||
1,
|
||||
"command",
|
||||
TimeSpan.FromSeconds(1),
|
||||
new[] { new DataItemHandle("s", 1, 1, 1) }
|
||||
);
|
||||
var removal = DataProtoMapper.EncodeCommand(command);
|
||||
removal.Remove.Items[0].StreamEpoch = 2;
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeCommand(removal));
|
||||
}
|
||||
}
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
using Google.Protobuf;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Protos;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData"), Trait("Phase", "P01"), Trait("Category", "Unit")]
|
||||
public sealed class GrpcDataProtoContractTests
|
||||
{
|
||||
[Fact]
|
||||
public void Contract_has_stable_service_field_numbers_and_streaming()
|
||||
{
|
||||
DataConnectionProtoContract.Validate();
|
||||
var methods = DataConnectionReflection.Descriptor.Services.Single().Methods;
|
||||
methods
|
||||
.Select(m => m.Name)
|
||||
.ShouldBe(
|
||||
new[] { "GetCapabilities", "Browse", "GetMetadata", "Read", "Write", "Subscribe" }
|
||||
);
|
||||
methods.Take(5).All(m => !m.IsClientStreaming && !m.IsServerStreaming).ShouldBeTrue();
|
||||
var signatures = new[]
|
||||
{
|
||||
("CapabilitiesRequest", "CapabilitiesResponse"),
|
||||
("BrowseRequest", "BrowseResponse"),
|
||||
("MetadataRequest", "MetadataResponse"),
|
||||
("ReadRequest", "ReadResponse"),
|
||||
("WriteRequest", "WriteResponse"),
|
||||
("SubscriptionCommand", "SubscriptionFrame"),
|
||||
};
|
||||
for (var i = 0; i < signatures.Length; i++)
|
||||
{
|
||||
methods[i].InputType.Name.ShouldBe(signatures[i].Item1);
|
||||
methods[i].OutputType.Name.ShouldBe(signatures[i].Item2);
|
||||
}
|
||||
methods[5].IsClientStreaming.ShouldBeTrue();
|
||||
methods[5].IsServerStreaming.ShouldBeTrue();
|
||||
Sample.Descriptor.FindFieldByName("status_code").FieldNumber.ShouldBe(2);
|
||||
CompactUpdate.Descriptor.FindFieldByName("source_timestamp").FieldNumber.ShouldBe(6);
|
||||
((int)ValueKind.Unspecified).ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Golden_payload_and_unknown_additive_field_round_trip()
|
||||
{
|
||||
var sample = new Sample { StatusCode = 1, Version = 2 };
|
||||
sample.ToByteArray().ShouldBe(new byte[] { 0x10, 1, 0x30, 2 });
|
||||
var extended = new byte[] { 0x10, 1, 0x30, 2, 0x98, 0x06, 7 };
|
||||
Sample.Parser.ParseFrom(extended).ToByteArray().ShouldBe(extended);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Every_existing_field_keeps_its_tag_type_cardinality_and_oneof()
|
||||
{
|
||||
const string expected = """
|
||||
TypedValue|kind|1|14|1|.data_connection.v1.ValueKind|-1
|
||||
TypedValue|boolean|2|8|1||0
|
||||
TypedValue|signed|3|18|1||0
|
||||
TypedValue|unsigned|4|4|1||0
|
||||
TypedValue|float_value|5|2|1||0
|
||||
TypedValue|double_value|6|1|1||0
|
||||
TypedValue|string_value|7|9|1||0
|
||||
TypedValue|bytes_value|8|12|1||0
|
||||
TypedValue|timestamp|9|11|1|.google.protobuf.Timestamp|0
|
||||
TypedValue|guid|10|9|1||0
|
||||
TypedValue|array|11|11|1|.data_connection.v1.TypedArray|0
|
||||
TypedArray|element_kind|1|14|1|.data_connection.v1.ValueKind|-1
|
||||
TypedArray|dimensions|2|13|3||-1
|
||||
TypedArray|elements|3|11|3|.data_connection.v1.TypedValue|-1
|
||||
Address|origin_cluster_id|1|9|1||-1
|
||||
Address|namespace_uri|2|9|1||-1
|
||||
Address|identifier_kind|3|9|1||-1
|
||||
Address|identifier|4|9|1||-1
|
||||
View|address|1|11|1|.data_connection.v1.Address|-1
|
||||
View|realm|2|5|1||-1
|
||||
View|mapping_id|3|9|1||0
|
||||
View|mapping_revision|4|3|1||-1
|
||||
View|subject|5|9|1||-1
|
||||
Serving|node_id|1|9|1||-1
|
||||
Serving|incarnation|2|9|1||-1
|
||||
Serving|role|3|9|1||-1
|
||||
Serving|catalog_epoch|4|3|1||-1
|
||||
Serving|authority_epoch|5|3|1||-1
|
||||
Sample|value|1|11|1|.data_connection.v1.TypedValue|-1
|
||||
Sample|status_code|2|13|1||-1
|
||||
Sample|source_timestamp|3|11|1|.google.protobuf.Timestamp|-1
|
||||
Sample|server_timestamp|4|11|1|.google.protobuf.Timestamp|-1
|
||||
Sample|serving|5|11|1|.data_connection.v1.Serving|-1
|
||||
Sample|version|6|3|1||-1
|
||||
Budget|timeout_ticks|1|3|1||-1
|
||||
Budget|max_items|2|5|1||-1
|
||||
Budget|max_bytes|3|3|1||-1
|
||||
Limits|max_page_items|1|5|1||-1
|
||||
Limits|max_batch_items|2|5|1||-1
|
||||
Limits|max_message_bytes|3|5|1||-1
|
||||
Limits|max_monitored_items|4|5|1||-1
|
||||
Limits|max_streams|5|5|1||-1
|
||||
Limits|max_pending_bytes|6|3|1||-1
|
||||
Limits|max_metadata_lease_ticks|7|3|1||-1
|
||||
Limits|max_session_lifetime_ticks|8|3|1||-1
|
||||
Limits|write_retry_window_ticks|9|3|1||-1
|
||||
Limits|max_value_elements|10|5|1||0
|
||||
CapabilitiesRequest|protocol_major|1|5|1||-1
|
||||
CapabilitiesRequest|protocol_minor|2|5|1||-1
|
||||
CapabilitiesResponse|protocol_major|1|5|1||-1
|
||||
CapabilitiesResponse|protocol_minor|2|5|1||-1
|
||||
CapabilitiesResponse|serving|3|11|1|.data_connection.v1.Serving|-1
|
||||
CapabilitiesResponse|readiness|4|5|1||-1
|
||||
CapabilitiesResponse|operations|5|13|1||-1
|
||||
CapabilitiesResponse|value_kinds|6|14|3|.data_connection.v1.ValueKind|-1
|
||||
CapabilitiesResponse|limits|7|11|1|.data_connection.v1.Limits|-1
|
||||
CapabilitiesResponse|compact_batches|8|8|1||-1
|
||||
CapabilitiesResponse|compact_codec_version|9|5|1||-1
|
||||
CapabilitiesResponse|cluster_id|10|9|1||-1
|
||||
Metadata|view|1|11|1|.data_connection.v1.View|-1
|
||||
Metadata|browse_name|2|9|1||-1
|
||||
Metadata|node_kind|3|9|1||-1
|
||||
Metadata|value_kind|4|14|1|.data_connection.v1.ValueKind|-1
|
||||
Metadata|value_rank|5|5|1||-1
|
||||
Metadata|dimensions|6|5|3||-1
|
||||
Metadata|writable|7|8|1||-1
|
||||
Metadata|allowed_operations|8|13|1||-1
|
||||
Metadata|catalog_revision|9|3|1||-1
|
||||
Metadata|stable_source_id|10|9|1||0
|
||||
Metadata|engineering_units|11|9|1||1
|
||||
Metadata|is_stale|12|8|1||-1
|
||||
Metadata|array_element_kind|13|14|1|.data_connection.v1.ValueKind|2
|
||||
Lease|catalog_epoch|1|3|1||-1
|
||||
Lease|authority_epoch|2|3|1||-1
|
||||
Lease|duration_ticks|3|3|1||-1
|
||||
BrowseRequest|parent|1|11|1|.data_connection.v1.View|-1
|
||||
BrowseRequest|filter|2|9|1||0
|
||||
BrowseRequest|continuation|3|9|1||1
|
||||
BrowseRequest|budget|4|11|1|.data_connection.v1.Budget|-1
|
||||
BrowseResponse|parent|1|11|1|.data_connection.v1.View|-1
|
||||
BrowseResponse|status|2|5|1||-1
|
||||
BrowseResponse|items|3|11|3|.data_connection.v1.Metadata|-1
|
||||
BrowseResponse|complete|4|8|1||-1
|
||||
BrowseResponse|continuation|5|9|1||0
|
||||
BrowseResponse|lease|6|11|1|.data_connection.v1.Lease|-1
|
||||
MetadataRequest|views|1|11|3|.data_connection.v1.View|-1
|
||||
MetadataRequest|budget|2|11|1|.data_connection.v1.Budget|-1
|
||||
MetadataResult|correlation_id|1|9|1||-1
|
||||
MetadataResult|status|2|5|1||-1
|
||||
MetadataResult|value|3|11|1|.data_connection.v1.Metadata|-1
|
||||
MetadataResult|diagnostic|4|9|1||0
|
||||
MetadataResponse|items|1|11|3|.data_connection.v1.MetadataResult|-1
|
||||
ReadItem|correlation_id|1|9|1||-1
|
||||
ReadItem|view|2|11|1|.data_connection.v1.View|-1
|
||||
ReadItem|maximum_age_ticks|3|3|1||0
|
||||
ReadRequest|items|1|11|3|.data_connection.v1.ReadItem|-1
|
||||
ReadRequest|budget|2|11|1|.data_connection.v1.Budget|-1
|
||||
ReadResult|correlation_id|1|9|1||-1
|
||||
ReadResult|status|2|5|1||-1
|
||||
ReadResult|readiness|3|5|1||-1
|
||||
ReadResult|age_ticks|4|3|1||0
|
||||
ReadResult|sample|5|11|1|.data_connection.v1.Sample|-1
|
||||
ReadResult|diagnostic|6|9|1||1
|
||||
ReadResponse|items|1|11|3|.data_connection.v1.ReadResult|-1
|
||||
WriteItem|correlation_id|1|9|1||-1
|
||||
WriteItem|operation_id|2|9|1||-1
|
||||
WriteItem|view|3|11|1|.data_connection.v1.View|-1
|
||||
WriteItem|value|4|11|1|.data_connection.v1.TypedValue|-1
|
||||
WriteItem|expected_catalog_revision|5|3|1||-1
|
||||
WriteItem|expected_serving_incarnation|6|9|1||-1
|
||||
WriteItem|remaining_budget_ticks|7|3|1||-1
|
||||
WriteRequest|items|1|11|3|.data_connection.v1.WriteItem|-1
|
||||
WriteRequest|budget|2|11|1|.data_connection.v1.Budget|-1
|
||||
WriteResult|correlation_id|1|9|1||-1
|
||||
WriteResult|state|2|5|1||-1
|
||||
WriteResult|status_code|3|13|1||-1
|
||||
WriteResult|diagnostic|4|9|1||0
|
||||
WriteResponse|items|1|11|3|.data_connection.v1.WriteResult|-1
|
||||
Handle|subscription_id|1|9|1||-1
|
||||
Handle|stream_epoch|2|3|1||-1
|
||||
Handle|handle|3|4|1||-1
|
||||
Handle|item_revision|4|3|1||-1
|
||||
Settings|sampling_ticks|1|3|1||-1
|
||||
Settings|publishing_ticks|2|3|1||-1
|
||||
Settings|trigger|3|5|1||-1
|
||||
Settings|deadband|4|1|1||0
|
||||
SubscriptionItem|client_item_id|1|9|1||-1
|
||||
SubscriptionItem|view|2|11|1|.data_connection.v1.View|-1
|
||||
SubscriptionItem|settings|3|11|1|.data_connection.v1.Settings|-1
|
||||
SubscriptionCommand|subscription_id|1|9|1||-1
|
||||
SubscriptionCommand|stream_epoch|2|3|1||-1
|
||||
SubscriptionCommand|command_id|3|9|1||-1
|
||||
SubscriptionCommand|acknowledgement_timeout_ticks|4|3|1||-1
|
||||
SubscriptionCommand|open|5|11|1|.data_connection.v1.Open|0
|
||||
SubscriptionCommand|add|6|11|1|.data_connection.v1.ItemChanges|0
|
||||
SubscriptionCommand|modify|7|11|1|.data_connection.v1.ItemChanges|0
|
||||
SubscriptionCommand|remove|8|11|1|.data_connection.v1.HandleChanges|0
|
||||
Open|items|1|11|3|.data_connection.v1.SubscriptionItem|-1
|
||||
Open|watch_catalog_only|2|8|1||-1
|
||||
Open|session_lifetime_ticks|3|3|1||-1
|
||||
Open|snapshot_budget|4|11|1|.data_connection.v1.Budget|-1
|
||||
ItemChanges|items|1|11|3|.data_connection.v1.SubscriptionItem|-1
|
||||
HandleChanges|items|1|11|3|.data_connection.v1.Handle|-1
|
||||
ItemAck|client_item_id|1|9|1||-1
|
||||
ItemAck|status|2|5|1||-1
|
||||
ItemAck|handle|3|11|1|.data_connection.v1.Handle|-1
|
||||
ItemAck|revised_settings|4|11|1|.data_connection.v1.Settings|-1
|
||||
ItemAck|diagnostic|5|9|1||0
|
||||
Ack|command_id|1|9|1||-1
|
||||
Ack|items|2|11|3|.data_connection.v1.ItemAck|-1
|
||||
Watermark|partition_id|1|5|1||-1
|
||||
Watermark|version|2|3|1||-1
|
||||
Control|kind|1|5|1||-1
|
||||
Control|watermarks|2|11|3|.data_connection.v1.Watermark|-1
|
||||
Control|catalog_epoch|3|3|1||-1
|
||||
Control|authority_epoch|4|3|1||-1
|
||||
Control|diagnostic|5|9|1||0
|
||||
ValueUpdate|handle|1|11|1|.data_connection.v1.Handle|-1
|
||||
ValueUpdate|sample|2|11|1|.data_connection.v1.Sample|-1
|
||||
Values|is_snapshot|1|8|1||-1
|
||||
Values|items|2|11|3|.data_connection.v1.ValueUpdate|-1
|
||||
TimestampOverride|value|1|11|1|.google.protobuf.Timestamp|-1
|
||||
CompactUpdate|handle|1|4|1||-1
|
||||
CompactUpdate|item_revision|2|3|1||-1
|
||||
CompactUpdate|version|3|3|1||-1
|
||||
CompactUpdate|value|4|11|1|.data_connection.v1.TypedValue|-1
|
||||
CompactUpdate|status_code|5|13|1||0
|
||||
CompactUpdate|source_timestamp|6|11|1|.data_connection.v1.TimestampOverride|-1
|
||||
CompactUpdate|server_timestamp|7|11|1|.data_connection.v1.TimestampOverride|-1
|
||||
CompactValues|is_snapshot|1|8|1||-1
|
||||
CompactValues|serving|2|11|1|.data_connection.v1.Serving|-1
|
||||
CompactValues|default_status_code|3|13|1||-1
|
||||
CompactValues|default_source_timestamp|4|11|1|.google.protobuf.Timestamp|-1
|
||||
CompactValues|default_server_timestamp|5|11|1|.google.protobuf.Timestamp|-1
|
||||
CompactValues|items|6|11|3|.data_connection.v1.CompactUpdate|-1
|
||||
SubscriptionFrame|subscription_id|1|9|1||-1
|
||||
SubscriptionFrame|stream_epoch|2|3|1||-1
|
||||
SubscriptionFrame|sequence|3|3|1||-1
|
||||
SubscriptionFrame|ack|4|11|1|.data_connection.v1.Ack|0
|
||||
SubscriptionFrame|control|5|11|1|.data_connection.v1.Control|0
|
||||
SubscriptionFrame|values|6|11|1|.data_connection.v1.Values|0
|
||||
SubscriptionFrame|compact_values|7|11|1|.data_connection.v1.CompactValues|0
|
||||
""";
|
||||
foreach (
|
||||
var row in expected.Split(
|
||||
'\n',
|
||||
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries
|
||||
)
|
||||
)
|
||||
{
|
||||
var parts = row.Split('|');
|
||||
var message = DataConnectionReflection.Descriptor.MessageTypes.Single(m =>
|
||||
m.Name == parts[0]
|
||||
);
|
||||
var field = message.FindFieldByName(parts[1]);
|
||||
field.ShouldNotBeNull();
|
||||
field.FieldNumber.ShouldBe(int.Parse(parts[2]));
|
||||
var proto = field.ToProto();
|
||||
((int)proto.Type).ShouldBe(int.Parse(parts[3]));
|
||||
((int)proto.Label).ShouldBe(int.Parse(parts[4]));
|
||||
proto.TypeName.ShouldBe(parts[5]);
|
||||
(proto.HasOneofIndex ? proto.OneofIndex : -1).ShouldBe(int.Parse(parts[6]));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Value_kind_numbers_are_locked_against_domain_decisions()
|
||||
{
|
||||
var kinds = new[]
|
||||
{
|
||||
"Unspecified",
|
||||
"Null",
|
||||
"Boolean",
|
||||
"Int8",
|
||||
"Int16",
|
||||
"Int32",
|
||||
"Int64",
|
||||
"UInt8",
|
||||
"UInt16",
|
||||
"UInt32",
|
||||
"UInt64",
|
||||
"Float",
|
||||
"Double",
|
||||
"String",
|
||||
"Bytes",
|
||||
"Timestamp",
|
||||
"Guid",
|
||||
"Array",
|
||||
};
|
||||
for (var i = 0; i < kinds.Length; i++)
|
||||
{
|
||||
((int)Enum.Parse<ValueKind>(kinds[i], ignoreCase: true)).ShouldBe(i);
|
||||
(
|
||||
(int)
|
||||
Enum.Parse<ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValueKind>(
|
||||
kinds[i]
|
||||
)
|
||||
).ShouldBe(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit")]
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Phase", "P01")]
|
||||
public sealed class GrpcDataContractsTests
|
||||
{
|
||||
[Fact]
|
||||
public void Realm_and_serving_provenance_are_part_of_view_identity()
|
||||
{
|
||||
var address = new DataAddress("cluster", "urn:test", "string", "same/path");
|
||||
var raw = new DataView(address, DataRealm.Raw, "mapping", 1, "subject");
|
||||
var uns = raw with { Realm = DataRealm.Uns };
|
||||
raw.ShouldNotBe(uns);
|
||||
var first = new ServingIdentity("node-a", "incarnation", "primary", 1, 2);
|
||||
var second = first with { NodeId = "node-b" };
|
||||
first.ShouldNotBe(second);
|
||||
new DataTarget(DataTargetMode.Node, "cluster", "node-a").Validate();
|
||||
Should.Throw<ArgumentException>(() => new DataTarget(DataTargetMode.Node, "cluster", null).Validate());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Required_enums_reject_unspecified_and_unknown_values()
|
||||
{
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => DataContractValidation.Required(DataRealm.Unspecified));
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => DataContractValidation.Required((DataTargetMode)99));
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => new DataWriteOutcome(DataWriteState.Unspecified, 0, null).Validate());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Only_driver_confirmed_success_is_success()
|
||||
{
|
||||
new DataWriteOutcome(DataWriteState.DriverConfirmedSuccess, 0, null).IsConfirmedSuccess.ShouldBeTrue();
|
||||
new DataWriteOutcome(DataWriteState.AcceptedUnconfirmed, 0, null).IsConfirmedSuccess.ShouldBeFalse();
|
||||
new DataWriteOutcome(DataWriteState.OutcomeUnknown, 0, null).IsConfirmedSuccess.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sample_preserves_optional_timestamps_and_owned_bytes()
|
||||
{
|
||||
var bytes = new byte[] { 1, 2 };
|
||||
using var value = DataValue.FromBytes(bytes);
|
||||
bytes[0] = 9;
|
||||
value.GetBytes().ToArray().ShouldBe(new byte[] { 1, 2 });
|
||||
using var sample = new DataSample(value.Retain(), 0x80000001, null, null,
|
||||
new ServingIdentity("node", "incarnation", "primary", 1, 2), 3);
|
||||
sample.SourceTimestampUtc.ShouldBeNull();
|
||||
sample.ServerTimestampUtc.ShouldBeNull();
|
||||
sample.StatusCode.ShouldBe(0x80000001u);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lease_deadline_is_anchored_to_request_start_and_bounded()
|
||||
{
|
||||
var lease = new MetadataLease(2, 3, TimeSpan.FromSeconds(15));
|
||||
lease.Deadline(100, TimeSpan.FromSeconds(1), TimeProvider.System).ShouldBeLessThan(
|
||||
100 + (long)(15 * TimeProvider.System.TimestampFrequency));
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => new MetadataLease(2, 3, TimeSpan.Zero).Validate());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Compact_handle_is_scoped_to_stream_and_item_revision()
|
||||
{
|
||||
var first = new DataItemHandle("stream", 1, 10, 1);
|
||||
first.ShouldNotBe(first with { StreamEpoch = 2 });
|
||||
first.ShouldNotBe(first with { ItemRevision = 2 });
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => (first with { Handle = 0 }).Validate());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Write_admission_keeps_original_credential_separate_from_principal()
|
||||
{
|
||||
var view = new DataView(new DataAddress("cluster", "urn:test", "string", "tag"),
|
||||
DataRealm.Raw, null, 0, "subject");
|
||||
var expiry = DateTimeOffset.UtcNow.AddMinutes(1);
|
||||
var ticket = new DataWriteAdmission("principal", view, 1, 2, "node-incarnation",
|
||||
"driver-incarnation", "operation", 100, "key-a", expiry, "fingerprint");
|
||||
|
||||
ticket.Validate();
|
||||
ticket.PrincipalId.ShouldBe("principal");
|
||||
ticket.ApiKeyId.ShouldBe("key-a");
|
||||
ticket.CredentialVersion.ShouldBe("fingerprint");
|
||||
ticket.CredentialExpiresUtc.ShouldBe(expiry);
|
||||
Should.Throw<ArgumentException>(() => (ticket with { ApiKeyId = "" }).Validate());
|
||||
Should.Throw<ArgumentException>(() => (ticket with { CredentialVersion = "" }).Validate());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Empty_array_metadata_retains_its_element_type()
|
||||
{
|
||||
var view = new DataView(new DataAddress("cluster", "urn:test", "string", "tag"),
|
||||
DataRealm.Raw, null, 0, "subject");
|
||||
var integerArray = new DataMetadata(view, "tag", "variable", DataValueKind.Array, 1,
|
||||
new[] { 0 }, false, DataOperations.Read, 1, null, null, false, DataValueKind.Int32);
|
||||
var stringArray = integerArray with { ArrayElementKind = DataValueKind.String };
|
||||
|
||||
integerArray.Validate();
|
||||
stringArray.Validate();
|
||||
integerArray.ShouldNotBe(stringArray);
|
||||
Should.Throw<ArgumentException>(() => (integerArray with { ArrayElementKind = null }).Validate());
|
||||
Should.Throw<ArgumentException>(() => (integerArray with { ArrayElementKind = DataValueKind.Array }).Validate());
|
||||
Should.Throw<ArgumentException>(() => (integerArray with { ValueKind = DataValueKind.Int32 }).Validate());
|
||||
}
|
||||
|
||||
|
||||
[Fact]
|
||||
public void Capabilities_bind_expected_cluster_and_validate_required_discovery_fields()
|
||||
{
|
||||
var limits = new DataLimits(10, 10, 1024, 10, 1, 1024,
|
||||
TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
|
||||
var capabilities = new DataCapabilities(1, 0,
|
||||
new ServingIdentity("node", "incarnation", "primary", 1, 1), DataReadiness.Ready,
|
||||
DataOperations.Read, new HashSet<DataValueKind> { DataValueKind.Int32 }, limits, false, 0, "cluster-a");
|
||||
|
||||
capabilities.Validate();
|
||||
capabilities.ClusterId.ShouldBe("cluster-a");
|
||||
Should.Throw<ArgumentException>(() => (capabilities with { ClusterId = "" }).Validate());
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => (capabilities with { Readiness = DataReadiness.Unspecified }).Validate());
|
||||
Should.Throw<ArgumentException>(() => (capabilities with { Serving = capabilities.Serving with { NodeId = "" } }).Validate());
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => (capabilities with { ProtocolMajor = 0 }).Validate());
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => (capabilities with { Limits = limits with { MaxBatchItems = 0 } }).Validate());
|
||||
}
|
||||
|
||||
|
||||
[Fact]
|
||||
public void Wire_enum_numbers_are_stable()
|
||||
{
|
||||
Enum.GetNames<DataValueKind>().ShouldBe(new[] { "Unspecified", "Null", "Boolean", "Int8", "Int16", "Int32", "Int64", "UInt8", "UInt16", "UInt32", "UInt64", "Float", "Double", "String", "Bytes", "Timestamp", "Guid", "Array" });
|
||||
Enum.GetValues<DataValueKind>().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 18));
|
||||
Enum.GetNames<DataItemStatus>().ShouldBe(new[] { "Unspecified", "Good", "Denied", "NotFound", "Unsupported", "InvalidArgument", "Unavailable", "WaitingForInitialData", "Stale", "LimitExceeded", "InvalidContinuation", "TypeMismatch", "ResourceExhausted" });
|
||||
Enum.GetValues<DataItemStatus>().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 13));
|
||||
Enum.GetNames<DataReadiness>().ShouldBe(new[] { "Unspecified", "Ready", "WaitingForInitialData", "Unavailable", "Invalidated" });
|
||||
Enum.GetValues<DataReadiness>().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 5));
|
||||
Enum.GetNames<DataWriteState>().ShouldBe(new[] { "Unspecified", "RejectedBeforeDispatch", "DriverConfirmedSuccess", "DriverConfirmedFailure", "AcceptedUnconfirmed", "OutcomeUnknown" });
|
||||
Enum.GetValues<DataWriteState>().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 6));
|
||||
Enum.GetNames<DataChangeTrigger>().ShouldBe(new[] { "Unspecified", "Status", "StatusValue", "StatusValueTimestamp" });
|
||||
Enum.GetValues<DataChangeTrigger>().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 4));
|
||||
Enum.GetNames<DataStreamControlKind>().ShouldBe(new[] { "Unspecified", "SnapshotBegin", "SnapshotEnd", "CatalogInvalidated", "AuthorityInvalidated", "Heartbeat", "Reset", "Coalesced" });
|
||||
Enum.GetValues<DataStreamControlKind>().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 8));
|
||||
((int)DataRealm.Raw).ShouldBe(1);
|
||||
((int)DataRealm.Uns).ShouldBe(2);
|
||||
((int)DataTargetMode.Node).ShouldBe(1);
|
||||
((int)DataTargetMode.Cluster).ShouldBe(2);
|
||||
((int)DataConsistency.Primary).ShouldBe(1);
|
||||
((int)DataConsistency.ReadyReplica).ShouldBe(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Settings_and_versioned_samples_reject_malformed_values()
|
||||
{
|
||||
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1),
|
||||
DataChangeTrigger.StatusValue, 1);
|
||||
settings.Validate();
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => (settings with { Deadband = double.NaN }).Validate());
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => (settings with { SamplingInterval = TimeSpan.FromSeconds(-1) }).Validate());
|
||||
using var sample = new DataSample(DataValue.Null(), 0, null, null,
|
||||
new ServingIdentity("node", "incarnation", "primary", 1, 1), 1);
|
||||
sample.Validate();
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => (sample with { Version = 0 }).Validate());
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => (sample with { Serving = sample.Serving with { CatalogEpoch = 0 } }).Validate());
|
||||
}
|
||||
|
||||
|
||||
[Fact]
|
||||
public void Limits_advertise_a_positive_per_value_element_budget()
|
||||
{
|
||||
var limits = new DataLimits(10, 10, 1024, 10, 1, 1024,
|
||||
TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
|
||||
limits.MaxValueElements.ShouldBe(100_000);
|
||||
limits.Validate();
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => (limits with { MaxValueElements = 0 }).Validate());
|
||||
}
|
||||
|
||||
|
||||
[Fact]
|
||||
public void Authenticated_context_binds_the_original_credential_and_authority()
|
||||
{
|
||||
var expiry = DateTimeOffset.UtcNow.AddMinutes(1);
|
||||
var context = new DataAuthenticatedContext("principal", "key", "fingerprint", expiry, 7);
|
||||
context.Validate();
|
||||
context.CredentialVersion.ShouldBe("fingerprint");
|
||||
Should.Throw<ArgumentException>(() => (context with { CredentialVersion = "" }).Validate());
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => (context with { AuthorityEpoch = 0 }).Validate());
|
||||
typeof(IDataConnectionFactory).GetMethod(nameof(IDataConnectionFactory.Create))!.ReturnType.ShouldBe(typeof(IDataConnection));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Unmapped_view_rejects_a_mapping_revision()
|
||||
{
|
||||
var view = new DataView(new DataAddress("cluster", "urn:test", "string", "tag"),
|
||||
DataRealm.Raw, null, 1, "untrusted-subject");
|
||||
Should.Throw<ArgumentException>(() => view.Validate());
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user