diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 769c98549..aa10711cb 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -123,6 +123,26 @@ retained bytes, metadata and call lifetimes. Tune them together for measured wor defaults are admission bounds, not a throughput or capacity guarantee. Overload can reject work or reset a stream, requiring a fresh snapshot. Do not interpret that recovery as lossless replay. +### Mixed versions (X0 rollout) + +The remote history and alarm work (`docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`) +adds new operation bits (`HistoryRead` 32, `AlarmSubscribe` 64, `AlarmAcknowledge` 128, +`AlarmConfirm` 256, `AlarmShelve` 512). A node older than X0 rejects the whole data-connection +snapshot when a row carries a bit it does not know, taking down every connection on that node. + +- **Run X0 on every node of both clusters before any of these bits is authored.** Nothing checks + this: ConfigDb records no node build, so it is a deploy-checklist step. +- An X0 node drops any operation bit it does not implement from that row only, fail closed (an + unknown grant is no grant). This applies to connections, exports and mappings alike. +- Each drop is logged as a warning naming the row and counted on + `otopcua.dataconnection.unknown_operations_dropped` (tag `kind` = connection, export or mapping). + - A drop is counted once per row per accepted artifact change. A → B → A counts again, and a + restart resets the count. + - The dropped bits also show in the node's fleet diagnostics. +- Authoring still rejects the bits until the release that implements them. +- The optional per-call header `x-otopcua-data-features` is reserved. X0 parses it but supports no + feature, and an X0 consumer never sends it, so the wire behaviour is unchanged v1. + ## Feature boundary Remote history, alarm/event forwarding and relay operations are future work. Authorized imported diff --git a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md index 53db90580..bdedc010d 100644 --- a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md +++ b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md @@ -352,6 +352,12 @@ X0 changes: grant) and counted in diagnostics. They no longer throw for the whole snapshot. - `DataContracts.cs:271-276`: `DataCapabilities.Validate` masks to the known set instead of throwing. - `DataProtoMapper.cs:284`: `Metadata.allowed_operations` masked on decode. `:1054-1062` is already masking (kept). +- **Two more node-side sites, found in X0:** artifact data-row parsing (`DeploymentArtifact.DataConnections.cs`) and origin + catalog compile (`LocalExportCatalog.Compilation.cs`) re-ran the authoring validator. + - Both now call `DataConnectionValidator.ValidateDeployed`. It ignores any bit outside `Understood` and still validates + the understood subset. + - Export rules and staged mapping copies are masked too. + - Drops are logged, counted (tag `kind`) and shown in node diagnostics (`docs/plans/evidence/grpc-data-ext/X0.md`). - `DataConnectionValidator.cs:12`: still rejects unknown bits. The known set grows only in the phase that adds the feature (H2, A2), so authoring cannot get ahead of the code. - `ProjectedDataAccess.cs:157`: extended in the phase that acquires with a new operation (H3, A3). @@ -362,6 +368,12 @@ X0 changes: behaviour, no new shapes without the header) is an exit gate of X0, **H2, A2 and A3** — the phases that touch v1 hot paths — so a v1 regression is attributable without a soak baseline. +**Gate extension rule (X0):** the gate drives the real `DataConnectionGrpcService` from the golden request bytes, backed by a +fake origin. +1. Each of H2/A2/A3 first extends that fake origin (and the real-origin variant, a follow-up) to emit its new-shape data. +2. Without the header, the gate must still see the same golden bytes. +3. The goldens are never re-recorded. + **The "every node is on X0" check is procedural (settled).** ConfigDb records no node build or feature level: `ClusterNode` has only identity, ports, flags and `LastSeenAt`. The validator therefore cannot enforce it. diff --git a/docs/plans/evidence/grpc-data-ext/X0.md b/docs/plans/evidence/grpc-data-ext/X0.md new file mode 100644 index 000000000..8a5a99c5f --- /dev/null +++ b/docs/plans/evidence/grpc-data-ext/X0.md @@ -0,0 +1,190 @@ +# X0 evidence: tolerant readers and contract reservation + +Phase X0 of `docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`. It has two parts: + +1. the provenance of revision 4's settled offline investigations (plan §5.1, §5.5, §5.6, §9.3); +2. what X0 changed, and the gate runs. + +## 1. Revision 4 investigations (provenance) + +All three investigations were offline, against the pinned `OPCFoundation.NetStandard.Opc.Ua.Server` 2.0.1 +(`Directory.Packages.props`). The second Fable pass reviewed them in +`docs/plans/2026-11-23-grpc-data-connections-history-alarms-relay-plan-review.md` (§"B5 — `ICallAsyncNodeManager.CallAsync`: +confirmed", N5, m-T7). That pass could not re-run the harness, because the harness was not yet in the repo. It is committed +here. + +### (a) SDK Call dispatch trace (B5, plan §5.6 step 1) + +The trace was decompiled with `ilspycmd` from +`~/.nuget/packages/opcfoundation.netstandard.opc.ua.server/2.0.1/lib/net10.0/Opc.Ua.Server.dll`. The excerpts were kept in +the session scratchpad and are not committed (SDK source). Files and members used: + +| Step | Decompiled file | Member | +|---|---|---| +| Service entry, async end to end | `StandardServer.cs` | `StandardServer.CallAsync` awaits `ServerInternal.NodeManager.CallAsync` | +| Master hand-off | `Opc.Ua.Server.MasterNodeManager.cs` | `MasterNodeManager.CallAsync` → `NodeManagerServiceDispatcher.CallAsync`; managers wrapped by `ToAsyncNodeManager()` | +| Validation, then per-manager await | `Opc.Ua.Server.NodeManagerServiceDispatcher.cs` | `CallAsync` runs `ValidateCallRequestItemAsync` (`GetManagerHandleAsync`, `FindMethodStateAsync`, `ValidatePermissionsAsync`). It marks bad items `Processed`, then awaits `IAsyncNodeManager.CallAsync` on each registered manager **sequentially**, with `ConfigureAwait(false)` | +| Adapter decision | `Opc.Ua.Server.AsyncNodeManagerAdapter.cs` | `CallAsync`: `if (SyncNodeManager is ICallAsyncNodeManager m) return m.CallAsync(...)`, else the synchronous `Call` (checked at call time, ≈ line 269) | +| Lock scope during validation | `Opc.Ua.Server.CustomNodeManager2.cs` | `FindMethodState` holds `lock (Lock)` only around `ValidateNode` + `FindMethod` | +| Where the lock is taken today | `Opc.Ua.Server.CustomNodeManager2.cs` | `Call` → `CallSynchronousBatch` → `GetMethodCalls`, which skips `Processed` items and locks per owned item. NM adds its own `lock (Lock)` in `ReportAfterMethod` | +| Interface | `Opc.Ua.Server.ICallAsyncNodeManager.cs` | `ValueTask CallAsync(OperationContext, ArrayOf, IList, IList, CancellationToken)` | + +Conclusion: `OtOpcUaNodeManager` can implement `ICallAsyncNodeManager`. It claims imported-condition calls (sets `Processed`), +runs `base.Call` for the rest, and then awaits the claimed calls with no NM `Lock` held. Lock-freedom stays a hard A3 gate (L3). + +The review added two non-blocking notes, both now in §5.6: + +- `base.Call` runs under `BeginNodeManagerOperation()`. Finish it before awaiting. +- Managers are awaited sequentially. A mixed batch delays later-registered managers. + +### (b) Condition node and byte count (N5, plan §5.5) + +The harness is `harness/Program.cs` and `harness/count.csproj`, copied verbatim. It builds each condition type with the +optional children NM adds before `Create()`: `ConfirmedState`, `Confirm`, `ShelvingState` and `MaxTimeShelved` +(`NM:2461-2475`). It then counts the tree through `GetChildren`. + +| Type | Nodes | Objects / variables / methods | +|---|---|---| +| `AlarmConditionType` | 48 | 2 / 38 / 8 | +| `OffNormalAlarmType` | 49 | 2 / 39 / 8 | +| `DiscreteAlarmType` | 48 | 2 / 38 / 8 | + +`Quality`, `BranchId` and `Comment` are present. + +Retained size is ≈ 157 KiB per condition (160,997 B). It was measured on 2,000 `OffNormal` instances as a +`GC.GetTotalMemory(true)` delta. + +- It excludes NM's indexes, the `c1.` identifier strings, the EventId registry and placement sets (m-T7). +- L2 (A3 exit) is the authority for `MaxImportedConditionBytes`. + +### (c) Snapshot-copy timing (plan §5.1) + +The same harness copies the snapshot fields of each of the 2,000 `OffNormalAlarmState` instances into a record. It takes +3.3–5.8 ms per 2,000 over three warm runs, which is ≈ 1.7–2.9 µs per condition. + +- At `MaxConditions` 1,000, one `Lock` hold is ≈ 2–3 ms. +- This was measured outside the server. L1 (A1) measures the real hold under load. + +To re-run: `dotnet run -c Release --project docs/plans/evidence/grpc-data-ext/harness/count.csproj`. It is not part of the +solution. + +## 2. What X0 changed + +- **Operation bits.** `DataOperations` reserves `HistoryRead`, `AlarmSubscribe`, `AlarmAcknowledge`, `AlarmConfirm` and + `AlarmShelve` (32 to 512). `DataOperationSets` is the one authority: `V1`, `Understood` (= `V1` in X0) and `Reserved`. +- **Tolerant readers.** Any bit outside `Understood` is dropped, fail closed (an unknown grant is no grant), at every + node-side reader: + - `DataConnectionValidator.ValidateDeployed` re-validates a deployed artifact. It is called by `DeploymentArtifact` + data-row parsing and `LocalExportCatalog.Compile`. + - It ignores every bit outside `Understood`, not only the reservation. A newer central may define bits this build has + never heard of. + - It still validates the understood subset: a row must be non-empty, and a mapping may not grant an understood + operation its connection lacks. + - These two sites were missed by the plan. Before X0 they rejected the whole snapshot (consumer side) or the whole + origin catalog (origin side). + - `DataConnectionDeploymentRuntime.Apply` drops the bits per connection row. + - `LocalExportCatalog` masks export rules. + - `ProjectedMappingDeploymentRuntime.Stage` masks its frozen mapping copies. + - `DataCapabilities.Operations` masks in its accessor, both at construction and on `with`. + - `DataProtoMapper` masks metadata and capabilities on decode. +- **Dropped-bit diagnostics.** + - Every drop is logged as a Warning naming the row id and the bits. + - It is counted on `otopcua.dataconnection.unknown_operations_dropped`, tagged `kind` = connection | export | mapping. + The helper is `UnknownOperationDrops`. + - A drop is counted once per row per accepted artifact change. Re-applying the same revision does not recount, A → B → A + does, and a restart resets. + - Drops are collected under each component's lock and logged after the lock is released. + - Production reader: `NodeDiagnosticsSnapshot` (AdminUI fleet diagnostics). + - Each `DataConnectionDiagnosticsSnapshot` carries `DroppedUnknownOperations` and `MappingsWithDroppedOperations`. + - The node carries `DroppedExportOperations`. +- **Grow sites unchanged.** Authoring `Validate` still rejects everything outside `V1`. `ProjectedDataAccess` and + `LocalDataServices.Implemented` are unchanged. +- **Feature header.** `x-otopcua-data-features` is parsed on every RPC after authentication. + - The server records requested and effective features. Effective = requested ∩ `SupportedFeatures` = none in X0. + - A binary value, or a value longer than 256 characters in total, gets `InvalidArgument`. + - The consumer derives the header per selected endpoint. It is always empty in X0, so it is never sent. +- **Proto reservations.** These are comments plus `DataConnectionProtoContract` constants: + - Capabilities 16 `HistoryCapabilities history` and 17 `ConditionCapabilities conditions`; + - Metadata 14 `HistoryInfo history`; + - SubscriptionItem 4 `ConditionScope condition_scope`; + - SubscriptionFrame oneof `frame` arm 9 `ConditionStates condition_states`. + + The descriptor tests pin name, singular message type and oneof, so `string history = 16` fails. + `DataConnectionProtoContract.Validate()` (frozen numbers plus reservations) now runs at host start in + `AddOtOpcUaDataConnections`, when data connections are enabled. No field was added, so the server advertises nothing new. + +### Recorded-v1-client gate: what is real and what is faked + +`GrpcDataV1CompatibilityTests` (Host.Tests) works as follows. + +- **Inputs.** It parses each recorded v1 request from `GrpcDataV1Goldens.Requests`, the golden hex itself (not + re-encoded), and calls the six RPCs in-process. +- **Real.** + - `DataConnectionGrpcService`: header parsing, authentication seam, readiness and permission gates, budget clamping, + response serving stamp, size checks and the subscription delivery sink; + - `DataProtoMapper` (all encoders and decoders); + - `DataConnectionAuthenticator` with a real API key. +- **Faked.** + - The origin facade behind `IDataConnectionFactory`: a deterministic fake `Origin`, not `LocalDataServices`, + `LocalExportCatalog` or `DataCapabilitiesProvider`; + - the gRPC/HTTP2 transport: a hand-built `ServerCallContext`. Response marshalling is the generated `ToByteArray()`. +- **Assertions.** + - Response bytes equal goldens captured on pre-X0 master `2e4e4063` (commit `3279a7f9d`, before any X0 change). Nothing + varies, so nothing is normalised. + - This holds with no header, and with `history,conditions` (the server supports nothing yet). + - The v1 rejection statuses keep their code, detail and empty trailers, with and without the header: Unimplemented + major, PermissionDenied for each missing grant. + - A binary or oversized header gets `InvalidArgument` with the family's existing detail and no trailers. +- **Not covered: a real-origin variant** (`LocalDataServices` + `LocalExportCatalog` + `DataCapabilitiesProvider`). It needs + the Runtime.Tests origin fixture rebuilt in Host.Tests through public APIs, plus its own golden set captured against + pre-X0 code. That was judged too heavy for X0 and is left as a follow-up. +- **Rule for H2, A2 and A3.** + 1. First extend the fake `Origin` (and the real-origin variant, once it exists) so it emits that phase's new-shape data: + history info, conditions, and the new operation bits in metadata and capabilities. + 2. Then, **without the header**, the test must still see the same golden bytes. + 3. **Never re-record the goldens**. A difference is a v1 wire regression. + +## 3. Gate runs + +Run on macOS, 2026-11-23, on HEAD `981c60784`: every code and test change, after the review fixes. The only later commit +is this results table. + +| Gate | Result | +|---|---| +| `dotnet build ZB.MOM.WW.OtOpcUa.slnx` | succeeded, 0 warnings, 0 errors | +| `run-unit-phase.py X0` | passed, 95 tests | +| P01 / P02 / P03 / P04 / P05 | passed: 53 / 213 / 239 / 542 / 939 | +| P06 / P07 / P08 / P09 | passed: 353 / 455 / 619 / 248 | +| `pytest test_unit_phase_runner.py` | 30 passed | + +The full unit suites of the touched projects, filtered `Category!=E2E&Category!=LiveIntegration`, all passed: + +| Project | Passed | +|---|---| +| Core.Abstractions | 849 | +| Commons | 485 | +| Configuration | 314 | +| Runtime | 1,835 (3 pre-existing skips) | +| Host | 424 | +| ControlPlane | 476 | +| AdminUI | 2,689 | + +Final round (second Fable pass, approve; three small fixes `9b29a5f65`, `5453c20d9`, `87c9f9c0b`), re-run on HEAD +`87c9f9c0b`: X0 passed 99 tests; P02 213, P07 456, P08 620 passed; Runtime 1,837 (3 pre-existing skips) and +Configuration 314 passed. Follow-ups: #918 (real-origin variant of the v1 gate, required before the H2 exit), #919 +(render the dropped-operation diagnostics in AdminUI). + +History of failed runs: + +- The first P02/P07 run (before `75cf5eb8f`) failed. + - P02 pinned `1 << 30` as malformed. The review later reversed that; it is now tolerated. + - P07 reflects over the runtime constructor. + +Commands: + +```bash +dotnet build ZB.MOM.WW.OtOpcUa.slnx +python3 scripts/validation/grpc-data/run-unit-phase.py X0 # and P01 … P09 +python3 -m pytest scripts/validation/grpc-data/test_unit_phase_runner.py +dotnet test --filter "Category!=E2E&Category!=LiveIntegration" +``` diff --git a/docs/plans/evidence/grpc-data-ext/harness/Program.cs b/docs/plans/evidence/grpc-data-ext/harness/Program.cs new file mode 100644 index 000000000..28605d4b2 --- /dev/null +++ b/docs/plans/evidence/grpc-data-ext/harness/Program.cs @@ -0,0 +1,40 @@ +using Opc.Ua; +sealed class Ids : INodeIdFactory { int n; public NodeId New(ISystemContext c, NodeState node) => new NodeId("n" + (++n), 2); } +static class P { + static int Count(ISystemContext ctx, NodeState n, Dictionary kinds) { + kinds[n.NodeClass.ToString()] = kinds.GetValueOrDefault(n.NodeClass.ToString()) + 1; + var children = new List(); n.GetChildren(ctx, children); + int c = 1; foreach (var ch in children) c += Count(ctx, ch, kinds); return c; + } + static void Run(string name, Func make, ISystemContext ctx) { + var parent = new FolderState(null); + var alarm = make(parent); + alarm.ConfirmedState = new TwoStateVariableState(alarm); + alarm.Confirm = new AddCommentMethodState(alarm); + alarm.ShelvingState = new ShelvedStateMachineState(alarm); + alarm.MaxTimeShelved = new PropertyState.Implementation(alarm); + alarm.Create(ctx, new NodeId("cond", 2), new QualifiedName("cond", 2), new LocalizedText("cond"), true); + var kinds = new Dictionary(); + int total = Count(ctx, alarm, kinds); + Console.WriteLine($"{name}: total={total} ({string.Join(", ", kinds.Select(k => k.Key + "=" + k.Value))}); Quality={(alarm.Quality!=null)} BranchId={(alarm.BranchId!=null)} Comment={(alarm.Comment!=null)}"); + } + static void Main() { + var ctx = new SystemContext((ITelemetryContext)null) { NodeIdFactory = new Ids(), NamespaceUris = new NamespaceTable() }; + ctx.NamespaceUris.Append("urn:a"); ctx.NamespaceUris.Append("urn:b"); + Run("AlarmConditionState", p => new AlarmConditionState(p), ctx); + Run("OffNormalAlarmState", p => new OffNormalAlarmState(p), ctx); + Run("DiscreteAlarmState", p => new DiscreteAlarmState(p), ctx); + var keep = new List(); long before = GC.GetTotalMemory(true); + for (int i = 0; i < 2000; i++) { var parent = new FolderState(null); var a = new OffNormalAlarmState(parent); + a.ConfirmedState = new TwoStateVariableState(a); a.Confirm = new AddCommentMethodState(a); a.ShelvingState = new ShelvedStateMachineState(a); + a.MaxTimeShelved = new PropertyState.Implementation(a); + a.Create(ctx, new NodeId("c"+i, 2), new QualifiedName("c"+i, 2), new LocalizedText("c"+i), true); keep.Add(a); } + long after = GC.GetTotalMemory(true); Console.WriteLine($"retained bytes/condition (2000, OffNormal, no address-space indexes): {(after-before)/2000}"); GC.KeepAlive(keep); + var conds = keep.Cast().ToArray(); var recs = new object[conds.Length]; + for (int w = 0; w < 3; w++) { var sw = System.Diagnostics.Stopwatch.StartNew(); + for (int i = 0; i < conds.Length; i++) { var c = conds[i]; recs[i] = (c.NodeId, c.ActiveState?.Id?.Value, c.AckedState?.Id?.Value, c.ConfirmedState?.Id?.Value, + c.EnabledState?.Id?.Value, c.ShelvingState?.CurrentState?.Value, c.Severity?.Value, c.Message?.Value, c.Quality?.Value, c.Retain?.Value, + c.Time?.Value, c.Comment?.Value, c.ClientUserId?.Value, c.ConditionClassId?.Value, c.ActiveState?.TransitionTime?.Value); } + sw.Stop(); Console.WriteLine($"snapshot copy of {conds.Length} conditions: {sw.Elapsed.TotalMilliseconds:F2} ms"); } + } +} diff --git a/docs/plans/evidence/grpc-data-ext/harness/count.csproj b/docs/plans/evidence/grpc-data-ext/harness/count.csproj new file mode 100644 index 000000000..7aac843d9 --- /dev/null +++ b/docs/plans/evidence/grpc-data-ext/harness/count.csproj @@ -0,0 +1,4 @@ + + Exenet10.0disablefalseenable + + diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index 8724deaa7..b92871cfc 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -721,5 +721,53 @@ "existing_classes": [], "integration_unit_guards": true } + ], + "X0": [ + { + "project": "tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=X0)", + "new_classes": [ + "GrpcDataOperationToleranceTests" + ], + "existing_classes": [] + }, + { + "project": "tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/ZB.MOM.WW.OtOpcUa.Commons.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=X0)", + "new_classes": [ + "GrpcDataProtoReservationTests", + "GrpcDataFeatureHeaderTests", + "GrpcDataTolerantDecodeTests" + ], + "existing_classes": [] + }, + { + "project": "tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/ZB.MOM.WW.OtOpcUa.Configuration.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=X0)", + "new_classes": [ + "GrpcDataReservedOperationAuthoringTests" + ], + "existing_classes": [] + }, + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=X0)", + "new_classes": [ + "GrpcDataUnknownOperationToleranceTests", + "GrpcDataFeatureHeaderClientTests" + ], + "existing_classes": [ + "GrpcDataArtifactReadTests", + "GrpcDataCatalogStagingTests" + ] + }, + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/ZB.MOM.WW.OtOpcUa.Host.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=X0)", + "new_classes": [ + "GrpcDataV1CompatibilityTests" + ], + "existing_classes": [] + } ] } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataFeatureHeader.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataFeatureHeader.cs new file mode 100644 index 000000000..007cefd81 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataFeatureHeader.cs @@ -0,0 +1,70 @@ +using Grpc.Core; +using ZB.MOM.WW.OtOpcUa.Commons.Protos; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Commons.DataConnections; + +/// +/// The per-call feature set the server derived for one RPC: what the caller asked for, and what this server +/// will actually honour (requested ∩ supported). A handler serves a feature only when it is in +/// ; an empty effective set means exactly the v1 behaviour. +/// +public sealed record DataCallFeatures(DataFeatures Requested, DataFeatures Effective) +{ + public static readonly DataCallFeatures None = new(DataFeatures.None, DataFeatures.None); +} + +/// Formats and parses . +public static class DataFeatureHeader +{ + public const string HistoryToken = "history"; + public const string ConditionsToken = "conditions"; + + /// The header value for , or null when nothing is requested (no header is sent). + public static string? Format(DataFeatures features) + { + var tokens = new List(2); + if ((features & DataFeatures.History) != 0) tokens.Add(HistoryToken); + if ((features & DataFeatures.Conditions) != 0) tokens.Add(ConditionsToken); + return tokens.Count == 0 ? null : string.Join(',', tokens); + } + + /// Adds the header only for a non-empty feature set, so a v1-equivalent call stays byte-identical. + public static void Apply(Metadata headers, DataFeatures features) + { + ArgumentNullException.ThrowIfNull(headers); + if (Format(features) is { } value) headers.Add(DataConnectionProtoContract.FeaturesHeader, value); + } + + /// + /// The union of every entry. Unknown, empty and + /// whitespace tokens are ignored (forward compatibility). A binary (-bin) entry or a summed length over + /// throws , + /// which the server maps to InvalidArgument. + /// + public static DataFeatures Parse(Metadata? headers) + { + if (headers is null) return DataFeatures.None; + var features = DataFeatures.None; + var length = 0; + foreach (var entry in headers) + { + if (!IsFeaturesKey(entry.Key)) continue; + if (entry.IsBinary) throw new ArgumentException("Invalid data feature negotiation."); + var value = entry.Value ?? string.Empty; + length += value.Length; + if (length > DataConnectionProtoContract.MaxFeaturesHeaderLength) throw new ArgumentException("Invalid data feature negotiation."); + foreach (var token in value.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) + { + if (string.Equals(token, HistoryToken, StringComparison.OrdinalIgnoreCase)) features |= DataFeatures.History; + else if (string.Equals(token, ConditionsToken, StringComparison.OrdinalIgnoreCase)) features |= DataFeatures.Conditions; + } + } + return features; + } + + // gRPC lower-cases keys; "-bin" is the binary form of the same logical header. + private static bool IsFeaturesKey(string key) => + string.Equals(key, DataConnectionProtoContract.FeaturesHeader, StringComparison.OrdinalIgnoreCase) + || string.Equals(key, DataConnectionProtoContract.FeaturesHeader + "-bin", StringComparison.OrdinalIgnoreCase); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs index 766ded7dd..b75f0d9c7 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs @@ -281,7 +281,8 @@ public static class DataProtoMapper x.ValueRank, x.Dimensions.ToArray(), x.Writable, - (DataOperations)x.AllowedOperations, + // X0 tolerant reader: an operation bit this build does not understand is no grant. + (DataOperations)(x.AllowedOperations & (uint)DataOperationSets.Understood), x.CatalogRevision, x.HasStableSourceId ? x.StableSourceId : null, x.HasEngineeringUnits ? x.EngineeringUnits : null, @@ -1051,16 +1052,7 @@ public static class DataProtoMapper x.ProtocolMinor, DecodeServing(x.Serving), r, - (DataOperations)( - x.Operations - & (uint)( - DataOperations.Browse - | DataOperations.Metadata - | DataOperations.Read - | DataOperations.Write - | DataOperations.Subscribe - ) - ), + (DataOperations)(x.Operations & (uint)DataOperationSets.Understood), kinds, new DataLimits( l.MaxPageItems, diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs index eab2c01a8..819a0d770 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs @@ -34,4 +34,8 @@ public sealed record DataConnectionDiagnosticsSnapshot( long? CompactFrameCount = null, long? FallbackFrameCount = null, long? SerializedValueFrameBytes = null, - string? AccountingInstanceId = null); + string? AccountingInstanceId = null, + // X0 tolerant reader: operation bits this connection row was authored with that this node does not implement and + // dropped (None = nothing dropped; null = from an older sender), and how many of its mappings had bits dropped. + DataOperations? DroppedUnknownOperations = null, + int? MappingsWithDroppedOperations = null); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs index f8686d205..019d3404f 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs @@ -43,10 +43,15 @@ public sealed record DriverInstanceDiagnostics( /// needs to be explicitly visible rather than inferred. Defaults to false, which is also what /// every node that booted normally reports. /// +/// +/// X0 tolerant reader: origin exports on this node whose operation bits this build does not implement, with the +/// bits dropped (no grant). Empty when none; null from a sender built before X0 or when no catalog is staged. +/// public sealed record NodeDiagnosticsSnapshot( NodeId NodeId, RevisionHash? CurrentRevision, IReadOnlyList Drivers, DateTime AsOfUtc, bool RunningFromCache = false, - IReadOnlyList? DataConnections = null); + IReadOnlyList? DataConnections = null, + IReadOnlyDictionary? DroppedExportOperations = null); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs index aebbfb775..644d5eba8 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs @@ -10,6 +10,26 @@ public static class DataConnectionProtoContract public const int CompactCodecVersion = 1; /// Optional, per-subscription client opt-in to a supported compact codec. public const string CompactCodecHeader = "x-data-compact-codec"; + /// + /// Per-RPC feature request (comma list of history, conditions), sent by a consumer only for features + /// the selected endpoint advertised. Absent ⇒ v1 behaviour on every RPC. See . + /// + public const string FeaturesHeader = "x-otopcua-data-features"; + /// Cap on the summed length of every entry of one call. + public const int MaxFeaturesHeaderLength = 256; + + // X0 field reservations (history + alarm plan §4.2). Not protobuf `reserved`: each number is held for the + // named field of a later phase. GrpcDataProtoReservationTests pins each as unused-or-that-field. + /// CapabilitiesResponse.history (H2). + public const int CapabilitiesHistoryField = 16; + /// CapabilitiesResponse.conditions (A2). + public const int CapabilitiesConditionsField = 17; + /// Metadata.history (H2). + public const int MetadataHistoryField = 14; + /// SubscriptionItem.condition_scope (A2). + public const int SubscriptionItemConditionScopeField = 4; + /// SubscriptionFrame.condition_states oneof arm (A2). + public const int SubscriptionFrameConditionStatesArm = 9; public static void Validate() { @@ -18,7 +38,24 @@ public static class DataConnectionProtoContract || Sample.StatusCodeFieldNumber != 2 || SubscriptionFrame.CompactValuesFieldNumber != 7 || (int)ValueKind.Unspecified != 0 + || !Reserved(CapabilitiesResponse.Descriptor, CapabilitiesHistoryField, "history", "HistoryCapabilities") + || !Reserved(CapabilitiesResponse.Descriptor, CapabilitiesConditionsField, "conditions", "ConditionCapabilities") + || !Reserved(Metadata.Descriptor, MetadataHistoryField, "history", "HistoryInfo") + || !Reserved(SubscriptionItem.Descriptor, SubscriptionItemConditionScopeField, "condition_scope", "ConditionScope") + || !Reserved(SubscriptionFrame.Descriptor, SubscriptionFrameConditionStatesArm, "condition_states", "ConditionStates", "frame") ) throw new InvalidOperationException("Data connection wire contract changed."); } + + /// + /// A reserved number is either still unused, or carries exactly the planned field: that name, a singular field of + /// message type , inside when one is given + /// (and outside any real oneof otherwise). string history = 16 fails. + /// + public static bool Reserved(Google.Protobuf.Reflection.MessageDescriptor message, int number, string expectedName, + string expectedMessageType, string? expectedOneof = null) => + message.FindFieldByNumber(number) is not { } field || + (field.Name == expectedName && !field.IsRepeated && !field.IsMap && + field.FieldType == Google.Protobuf.Reflection.FieldType.Message && field.MessageType.Name == expectedMessageType && + field.RealContainingOneof?.Name == expectedOneof); } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto index ec061e12a..d048729e8 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto @@ -119,6 +119,8 @@ message CapabilitiesResponse { bool subscription_freshness_challenges = 14; // Good GetMetadata results may include an exact-item authority lease. bool metadata_item_leases = 15; + // X0 RESERVATION (not protobuf `reserved`: the numbers WILL be used): 16 = HistoryCapabilities history (H2), + // 17 = ConditionCapabilities conditions (A2). Pinned by DataConnectionProtoContract + GrpcDataProtoReservationTests. } message Metadata { View view = 1; @@ -134,6 +136,7 @@ message Metadata { optional string engineering_units = 11; bool is_stale = 12; optional ValueKind array_element_kind = 13; + // X0 RESERVATION: 14 = HistoryInfo history (H2). Pinned by GrpcDataProtoReservationTests. } message Lease { int64 catalog_epoch = 1; @@ -223,6 +226,7 @@ message SubscriptionItem { string client_item_id = 1; View view = 2; Settings settings = 3; + // X0 RESERVATION: 4 = ConditionScope condition_scope (A2, header-gated). Pinned by GrpcDataProtoReservationTests. } message SubscriptionCommand { string subscription_id = 1; @@ -317,5 +321,7 @@ message SubscriptionFrame { Control control = 5; Values values = 6; CompactValues compact_values = 7; + // X0 RESERVATION: oneof arm 9 = ConditionStates condition_states (A2). Only ever sent on a call that + // negotiated `conditions` through x-otopcua-data-features: v1 clients fault on an unknown frame arm. } } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs index 8d19117d9..dd0f6da64 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs @@ -9,17 +9,36 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation; /// Validates deployed data-service configuration without resolving consumer-side secrets. public static class DataConnectionValidator { - private const DataOperations KnownOperations = DataOperations.Browse | DataOperations.Metadata | - DataOperations.Read | DataOperations.Write | DataOperations.Subscribe; + /// + /// The operations AUTHORING may grant. Deliberately the v1 set: it grows only in the phase that implements a bit + /// (H2, A2), so authoring cannot get ahead of the code (plan section 4.3, "grow site"). + /// + private const DataOperations KnownOperations = DataOperationSets.V1; private static readonly StringComparer Ids = StringComparer.OrdinalIgnoreCase; - public static IReadOnlyList Validate(DraftSnapshot draft) + /// Authoring/deploy-gate validation: an operation bit outside the known set is an error. + public static IReadOnlyList Validate(DraftSnapshot draft) => Validate(draft, deployed: false); + + /// + /// Node-side re-validation of an already-deployed artifact (artifact parse, origin catalog compile). Identical to + /// except that operation bits outside + /// are IGNORED rather than rejected (X0 tolerant reader): a newer central may author them, and rejecting would take + /// down every data connection/export on the node. The understood subset is still validated (a mapping may not grant + /// an understood operation its connection lacks), and every consumer of the rows masks the rest away, so an unknown bit + /// grants nothing (fail closed). A row must carry SOME bit (zero is still invalid), but it may carry only unknown + /// bits: such a row is kept and grants nothing. + /// + public static IReadOnlyList ValidateDeployed(DraftSnapshot draft) => Validate(draft, deployed: true); + + private static IReadOnlyList Validate(DraftSnapshot draft, bool deployed) { ArgumentNullException.ThrowIfNull(draft); var errors = new List(); void Add(string code, string id, string message) => errors.Add(new(code, message, id)); bool Same(string? a, string? b) => Ids.Equals(a, b); - bool ValidOps(DataOperations operations) => operations != DataOperations.None && (operations & ~KnownOperations) == 0; + bool ValidOps(DataOperations operations) => operations != DataOperations.None && + (deployed || (operations & ~KnownOperations) == 0); + DataOperations Understood(DataOperations operations) => deployed ? operations & DataOperationSets.Understood : operations; bool NodesValid(IEnumerable ids, string owner) { var list = ids.ToList(); @@ -251,7 +270,7 @@ public static class DataConnectionValidator Same(other.ClusterId, mapping.ClusterId) && other.Realm == mapping.Realm && Same(other.LocalParentKind, mapping.LocalParentKind) && Same(other.LocalParentId, mapping.LocalParentId) && string.Equals(other.BranchName, mapping.BranchName, StringComparison.Ordinal))) Add("DataMappingNameCollision", id, "A mapping branch collides with an existing sibling."); - if (!ValidOps(mapping.AllowedOperations) || connection is null || (mapping.AllowedOperations & ~connection.AllowedOperations) != 0 || + if (!ValidOps(mapping.AllowedOperations) || connection is null || (Understood(mapping.AllowedOperations) & ~connection.AllowedOperations) != 0 || (mapping.AllowedOperations.HasFlag(DataOperations.Write) && !mapping.WriteThrough)) Add("DataMappingOperationsInvalid", id, "Mapping operations must be permitted by the connection and write-through policy."); if (mapping.MaxProjectionNodes <= 0 || mapping.MaxProjectionDepth <= 0 || mapping.MetadataLeaseMilliseconds <= 0 || diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs index e166e0551..7a6ef751c 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs @@ -226,7 +226,46 @@ 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 } +/// +/// Data operation grants. The values are persisted (ConfigDb int) and carried on the wire (uint); never renumber. +/// Bits 32..512 are RESERVED by phase X0 of the history/alarm plan: no node implements them yet, so every reader +/// masks them to (an unknown grant is no grant) and the authoring +/// validator keeps rejecting them until the phase that implements each one (H2, A2). +/// +[Flags] public enum DataOperations +{ + None = 0, Browse = 1, Metadata = 2, Read = 4, Write = 8, Subscribe = 16, + /// Reserved (H2): Raw/Processed/AtTime history reads. + HistoryRead = 32, + /// Reserved (A2): root-scoped condition items (origin-side grant). + AlarmSubscribe = 64, + /// Reserved (A2): Acknowledge and AddComment. + AlarmAcknowledge = 128, + /// Reserved (A2): Confirm. + AlarmConfirm = 256, + /// Reserved for the deferred shelve methods. + AlarmShelve = 512, +} +/// The one authority for which bits this build understands. +public static class DataOperationSets +{ + /// The v1 operation set. + public const DataOperations V1 = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | + DataOperations.Write | DataOperations.Subscribe; + /// + /// What tolerant readers keep; every other bit is dropped fail-closed. Grows only in the phase that implements + /// a bit (H2 adds ; A2 the alarm bits). + /// + public const DataOperations Understood = V1; + /// Bits reserved by X0 for later phases. + public const DataOperations Reserved = DataOperations.HistoryRead | DataOperations.AlarmSubscribe | + DataOperations.AlarmAcknowledge | DataOperations.AlarmConfirm | DataOperations.AlarmShelve; +} +/// +/// Optional per-call protocol features negotiated through the x-otopcua-data-features request header. +/// A call without the header (or with an empty effective set) gets exactly the v1 behaviour. +/// +[Flags] public enum DataFeatures { None = 0, History = 1, Conditions = 2 } /// /// Negotiated limits. When a peer omits the per-value element limit, the protocol default is 100,000. /// @@ -250,6 +289,10 @@ public sealed record DataCapabilities(int ProtocolMajor, int ProtocolMinor, Serv bool WriteServingGenerationEnforced = false, bool SubscriptionFreshnessChallenges = false, bool MetadataItemLeases = false) { + private readonly DataOperations _operations = Operations & DataOperationSets.Understood; + /// Masked to on construction and on every with. + public DataOperations Operations { get => _operations; init => _operations = value & DataOperationSets.Understood; } + public void Validate() { ArgumentException.ThrowIfNullOrWhiteSpace(ClusterId); @@ -268,12 +311,7 @@ public sealed record DataCapabilities(int ProtocolMajor, int ProtocolMinor, Serv { 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)); - } + // Operations is masked by its accessor, so unknown bits from a newer peer never reach here (X0). } } public sealed record DataMetadata(DataView View, string BrowseName, string NodeKind, DataValueKind ValueKind, int ValueRank, diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs index 9f58fccd8..a99b7f078 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs @@ -33,6 +33,8 @@ public static class DataConnectionRegistration services.AddSingleton>(new DataConnectionOptionsValidator(environment)); if (!options.Enabled) return options; if (!hasDriver) throw new InvalidOperationException("DataConnections requires this node's driver role."); + // Fail host start on a wire-contract drift (frozen field numbers and the X0 reservations); a descriptor walk, cheap. + ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnectionProtoContract.Validate(); services.TryAddSingleton(TimeProvider.System); services.TryAddSingleton(); @@ -56,7 +58,7 @@ public static class DataConnectionRegistration var state = CaptureReadRole(role, warm); var servingRole = settings.IsWarm && state.WarmRole != WarmRole.Active ? "Standby" : state.Role; return new(identity.NodeId, identity.Incarnation, servingRole, 0, 0, state.Generation); - }); + }) { Logger = LoggerFor(sp) }; }); services.AddSingleton(sp => new PartitionedSampleHub(options.Hub, sp.GetRequiredService())); services.AddSingleton(sp => new SourceSamplePublisher(sp.GetRequiredService(), @@ -72,7 +74,8 @@ public static class DataConnectionRegistration sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), 256, options.MaxConcurrentCalls)); services.AddSingleton(sp => sp.GetRequiredService()); - services.AddSingleton(); + services.AddSingleton(sp => new ProjectedMappingDeploymentRuntime(sp.GetRequiredService(), + sp.GetRequiredService()) { Logger = LoggerFor(sp) }); services.TryAddSingleton(); services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); @@ -212,7 +215,10 @@ public static class DataConnectionRegistration var eligible = state.Generation > 0 && Enum.TryParse(state.Role, out var actual) && DataConnectionRoleAdapter.MayAcquire(mode, state.WarmRole, actual); return new DataConnectionConsumerRoleSnapshot(mode, eligible, state.Generation); - }); + }) + { + Logger = LoggerFor(sp), + }; return runtime; }); services.AddSingleton(sp => @@ -233,6 +239,9 @@ public static class DataConnectionRegistration return options; } + private static Microsoft.Extensions.Logging.ILogger LoggerFor(IServiceProvider sp) => + (Microsoft.Extensions.Logging.ILogger?)sp.GetService()?.CreateLogger() + ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance; private static (string Role, long Generation, WarmRole? WarmRole, long ReadEpoch) CaptureReadRole( RedundancyRoleView role, DataConnectionWarmRoleView warm) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs index aac25b963..442748f08 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs @@ -16,6 +16,29 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO { private readonly DataConnectionOptions _options = options.Value; + /// + /// The optional features this server honours on a call that requests them. X0 reserves the negotiation and + /// supports nothing, so every call's effective set is empty and every RPC keeps its v1 behaviour. + /// + internal static DataFeatures SupportedFeatures => DataFeatures.None; + + /// The feature set recorded for this call by (v1 when absent). + internal static DataCallFeatures CallFeatures(ServerCallContext context) => + context.UserState.TryGetValue(typeof(DataCallFeatures), out var value) && value is DataCallFeatures features + ? features : DataCallFeatures.None; + + /// + /// Parses on every RPC (after authentication) and records + /// requested ∩ supported. A binary or oversized value is an ⇒ InvalidArgument. + /// + private static DataCallFeatures NegotiateFeatures(ServerCallContext context) + { + var requested = DataFeatureHeader.Parse(context.RequestHeaders); + var features = requested == DataFeatures.None ? DataCallFeatures.None : new DataCallFeatures(requested, requested & SupportedFeatures); + context.UserState[typeof(DataCallFeatures)] = features; + return features; + } + public override Task GetCapabilities(W.CapabilitiesRequest request, ServerCallContext context) => Execute(context, async (connection, caller, token) => { @@ -133,6 +156,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO context.WriteOptions = new(WriteFlags.NoCompress); responses.WriteOptions = new(WriteFlags.NoCompress); var (caller, target) = AuthenticateCall(context); + NegotiateFeatures(context); await using var connection = factory.Create(caller, target); DataCapabilities caps; IDataSubscription subscription; @@ -254,6 +278,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO context.WriteOptions = new(WriteFlags.NoCompress); var http = context.GetHttpContext(); var (caller, target) = AuthenticateCall(context); + NegotiateFeatures(context); if (!http.Items.ContainsKey(typeof(DataConnectionUnaryLifetime))) http.Items[typeof(DataConnectionUnaryLifetime)] = new DataConnectionUnaryLifetime(TimeProvider.System, _options.UnaryTimeout); var timeout = new CancellationTokenSource(_options.UnaryTimeout); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs index 786232a8e..7f712b127 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -1,3 +1,5 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Configuration.Enums; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; @@ -39,7 +41,13 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable internal bool Ready; internal int Leases; } + /// Counter of rows whose unknown operation bits were dropped (X0 tolerant reader); see . + public const string UnknownOperationsCounterName = UnknownOperationDrops.CounterName; private readonly object _sync = new(); + /// Diagnostics sink for the X0 dropped-operation warning; optional (an init property keeps the constructor shape). + public ILogger Logger { private get; init; } = NullLogger.Instance; + private IReadOnlyDictionary _droppedOperations = new Dictionary(); + private long _unknownOperationRows; private readonly string _node, _owner; private readonly IDataConnectionSecurityProvider _security; private readonly IDataConnectionScopeActivator _activator; @@ -81,23 +89,45 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable /// True only after the current scope version and allowlist are durably accepted. public bool CurrentScopeReady { get { lock (_sync) return !_disposed && _scopeReady; } } + /// + /// X0 diagnostics: per enabled connection of the current artifact, the operation bits it was authored with that + /// this node does not understand and therefore dropped (an unknown grant is no grant). Empty when none. + /// + public IReadOnlyDictionary DroppedUnknownOperations { get { lock (_sync) return _droppedOperations; } } + /// + /// Cumulative count of connection rows that had unknown bits dropped: once per row per accepted artifact change + /// (same revision re-applied does not recount; A → B → A does; a restart resets). + /// + public long UnknownOperationRowsDropped => Interlocked.Read(ref _unknownOperationRows); /// Configured redundancy mode from the current validated artifact. public RedundancyMode CurrentConsumerMode { get { lock (_sync) return _desired?.ConsumerMode ?? RedundancyMode.None; } } /// Captures only this node's applied scope and current transport evidence. - public IReadOnlyList CaptureDiagnostics(IReadOnlyDictionary? retainedSourceCounts = null) + /// Per connection id, the projected sources retained (host-supplied). + /// + /// Per connection id, how many of its mappings had unknown operation bits dropped (from + /// ); null = not available. + /// + public IReadOnlyList CaptureDiagnostics(IReadOnlyDictionary? retainedSourceCounts = null, + IReadOnlyDictionary? mappingsWithDroppedOperations = null) { lock (_sync) { if (_disposed || _desired is not { } desired) return []; + var dropped = _droppedOperations; + DataOperations? Dropped(string id) => dropped.TryGetValue(id, out var bits) ? bits : DataOperations.None; + int? MappingDrops(string id) => mappingsWithDroppedOperations is null ? null + : mappingsWithDroppedOperations.TryGetValue(id, out var count) ? count : 0; return desired.Specs.Values.Select(spec => { if (!_attemptPending && _scopeReady && _entries.TryGetValue(spec.Id, out var entry) && entry.Ready) return entry.Connection.CaptureDiagnostics(spec.Revision, desired.ScopeVersion, desired.ArtifactRevision) with - { SourceCount = retainedSourceCounts is null ? null : retainedSourceCounts.TryGetValue(spec.Id, out var count) ? count : 0 }; + { SourceCount = retainedSourceCounts is null ? null : retainedSourceCounts.TryGetValue(spec.Id, out var count) ? count : 0, + DroppedUnknownOperations = Dropped(spec.Id), MappingsWithDroppedOperations = MappingDrops(spec.Id) }; return new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot(spec.Id, spec.Revision, _attemptPending ? "connecting" : _retryNotBefore > _clock.GetTimestamp() ? "backoff" : "connecting", - null, null, 0, 0, desired.ScopeVersion, desired.ArtifactRevision, _clock.GetUtcNow().UtcDateTime); + null, null, 0, 0, desired.ScopeVersion, desired.ArtifactRevision, _clock.GetUtcNow().UtcDateTime) + { DroppedUnknownOperations = Dropped(spec.Id), MappingsWithDroppedOperations = MappingDrops(spec.Id) }; }).ToArray(); } } @@ -133,6 +163,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable if (snapshot.Connections.Count > _maximum) throw new ArgumentException("Connection capacity exceeded.", nameof(snapshot)); var specs = new Dictionary(StringComparer.OrdinalIgnoreCase); var allow = new Dictionary(StringComparer.OrdinalIgnoreCase); + var dropped = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var item in snapshot.Connections) { ArgumentNullException.ThrowIfNull(item); @@ -148,20 +179,25 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable item.MaxMessageBytes <= 0 || item.MaxStreams <= 0 || item.MaxMonitoredItems <= 0 || item.MaxPendingBytes <= 0 || item.Endpoints is null || item.Endpoints.Count == 0 || item.Endpoints.Count > 32 || item.EligibleTargetNodeIds is null) throw new ArgumentException("Connection limits or endpoints are invalid.", nameof(snapshot)); - const DataOperations known = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe; - if ((item.AllowedOperations & ~known) != 0) throw new ArgumentException("Unknown operation.", nameof(snapshot)); + // X0 tolerant reader (plan §4.3): a bit a newer central authored that this build does not implement is + // dropped from THIS row only, fail closed, and counted. It used to reject the whole snapshot. A row left + // with no understood operation stays configured and grants nothing. + var operations = item.AllowedOperations & DataOperationSets.Understood; + if (UnknownOperationDrops.Unknown(item.AllowedOperations) is var unknown && unknown != DataOperations.None) + dropped[item.DataConnectionId] = unknown; var endpoints = item.Endpoints.Select(value => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps ? uri : throw new ArgumentException("Only HTTPS endpoints are accepted.", nameof(snapshot))).Distinct().ToArray(); var eligible = new HashSet(item.EligibleTargetNodeIds, StringComparer.OrdinalIgnoreCase); if (target.Mode == DataTargetMode.Cluster && (eligible.Count == 0 || eligible.Any(string.IsNullOrWhiteSpace))) throw new ArgumentException("Cluster target has no eligible nodes.", nameof(snapshot)); var spec = new Spec(item.DataConnectionId, item.Revision, target, endpoints, eligible, item.SecretReference, - item.AllowedOperations, TimeSpan.FromMilliseconds(item.TimeoutMilliseconds), item.MaxBatchItems, + operations, TimeSpan.FromMilliseconds(item.TimeoutMilliseconds), item.MaxBatchItems, item.MaxPageItems, item.MaxMessageBytes, item.MaxStreams, item.MaxMonitoredItems, item.MaxPendingBytes); if (!specs.TryAdd(spec.Id, spec) || !allow.TryAdd(spec.Id, spec.Secret)) throw new ArgumentException("Duplicate connection identity.", nameof(snapshot)); } Entry[] old; + var report = false; lock (_sync) { ObjectDisposedException.ThrowIf(_disposed, this); @@ -176,6 +212,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable { if (snapshot.ScopeVersion != previous.ScopeVersion || snapshot.ConsumerMode != previous.ConsumerMode || !SameSpecs(previous.Specs, specs)) throw new InvalidOperationException("An artifact revision cannot identify different definitions."); + // Same revision re-applied: identical rows, so the dropped set is unchanged and is not recounted. if (!_attemptPending) { if (!_scopeReady) DisarmRetryLocked(); WakeLocked(); return; } } } @@ -183,13 +220,19 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable var generation = checked(++_generation); _routeRevisions.Clear(); foreach (var id in specs.Keys) _routeRevisions.Add(id, generation); + var priorRevision = _desired?.ArtifactRevision; _desired = new(snapshot.ScopeVersion, snapshot.ArtifactRevision, generation, snapshot.ConsumerMode, specs, allow); + _droppedOperations = dropped; + report = dropped.Count != 0 && !string.Equals(snapshot.ArtifactRevision, priorRevision, StringComparison.Ordinal); + if (report) Interlocked.Add(ref _unknownOperationRows, dropped.Count); _scopeReady = false; old = _entries.Values.ToArray(); _entries.Clear(); ApplyManagerScopeLocked(_desired); foreach (var entry in old) Retire(entry); WakeLocked(); } + // Collected under _sync, reported after release (logging may block). + if (report) UnknownOperationDrops.Report(Logger, UnknownOperationDrops.ConnectionKind, snapshot.ArtifactRevision, dropped); } private static bool SameAllowlist(IReadOnlyDictionary left, IReadOnlyDictionary right) => left.Count == right.Count && left.All(x => right.TryGetValue(x.Key, out var value) && string.Equals(value, x.Value, StringComparison.Ordinal)); @@ -488,6 +531,8 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDisposable RouteIdentity = routeIdentity; } internal Func RouteCurrent => _routeCurrent; + /// The configured row's operations, already masked to the understood set. + internal DataOperations AllowedOperations => _allowed; public IDataConnection Connection => this; public CancellationToken CancellationToken => _scope; public DataTarget Target => _inner.Target; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs index 2ffb7044f..17d669bc2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs @@ -211,12 +211,23 @@ public sealed partial class GrpcDataConnection : IDataConnection catch { handler.Dispose(); throw; } } } - private Metadata Headers(ChannelEntry channel) + /// + /// The optional features to request from the SELECTED endpoint: only what that endpoint advertised, re-derived on + /// every selection so a failover follows the new endpoint. X0 reserves the negotiation; no capability field + /// advertises a feature yet, so this is always empty and the header is never sent. + /// + internal static DataFeatures RequestedFeatures(DataCapabilities capabilities) + { + ArgumentNullException.ThrowIfNull(capabilities); + return DataFeatures.None; + } + private Metadata Headers(ChannelEntry channel, DataFeatures features = DataFeatures.None) { var headers = new Metadata { { "authorization", "Bearer " + channel.Bearer }, { "x-data-target-mode", Target.Mode.ToString() }, { "x-data-consistency", Target.Consistency.ToString() }, { "x-data-cluster-id", Target.ExpectedClusterId } }; if (Target.Mode == DataTargetMode.Node) headers.Add("x-data-node-id", Target.ExpectedNodeId!); + DataFeatureHeader.Apply(headers, features); return headers; } private TimeSpan Remaining(long start, DataBudget budget) @@ -227,6 +238,8 @@ public sealed partial class GrpcDataConnection : IDataConnection } private CallOptions Options(ChannelEntry channel, long start, DataBudget budget, CancellationToken ct) => new(Headers(channel), DateTime.UtcNow + Remaining(start, budget), ct); + private CallOptions Options(Selected selected, long start, DataBudget budget, CancellationToken ct) => + new(Headers(selected.Channel, RequestedFeatures(selected.Capabilities)), DateTime.UtcNow + Remaining(start, budget), ct); private DataDecodeLimits Limits(DataBudget budget, DataCapabilities caps) => new(Math.Min(budget.MaxItems, caps.Limits.MaxBatchItems), (int)Math.Min(Math.Min(budget.MaxBytes, _maxMessageBytes), caps.Limits.MaxMessageBytes), caps.Limits.MaxValueElements); private async Task SelectAsync(Uri endpoint, long start, DataBudget budget, bool write, CancellationToken ct) @@ -271,7 +284,7 @@ public sealed partial class GrpcDataConnection : IDataConnection ProbeSucceeded(); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token); var remaining = budget with { Timeout = Remaining(start, budget) }; - var result = await call(selected, remaining, Options(selected.Channel, start, budget, linked.Token)).ConfigureAwait(false); + var result = await call(selected, remaining, Options(selected, start, budget, linked.Token)).ConfigureAwait(false); try { linked.Token.ThrowIfCancellationRequested(); return result; } catch { if (result is IEnumerable reads) foreach (var item in reads) item.Dispose(); throw; } } @@ -432,7 +445,7 @@ public sealed partial class GrpcDataConnection : IDataConnection var budget = request.Budget with { Timeout = remaining }; var metadataRequest = new MetadataRequest(legacy.Select(i => items[i].View).ToArray(), budget); var wireMetadata = await selected.Channel.Client.GetMetadataAsync(DataProtoMapper.EncodeMetadataRequest(metadataRequest), - Options(selected.Channel, start, request.Budget, linked.Token)).ResponseAsync.ConfigureAwait(false); + Options(selected, start, request.Budget, linked.Token)).ResponseAsync.ConfigureAwait(false); Verify(wireMetadata.Serving, selected); var metadata = DataProtoMapper.DecodeMetadataResponse(wireMetadata, Limits(budget, selected.Capabilities)); metadataValid = metadata.Count == legacy.Length && !metadata.Where((x, i) => @@ -475,7 +488,7 @@ public sealed partial class GrpcDataConnection : IDataConnection var remaining = Remaining(start, request.Budget); var batch = new WriteBatch(items.Select(x => x with { RemainingBudget = x.RemainingBudget < remaining ? x.RemainingBudget : remaining }).ToArray(), request.Budget with { Timeout = remaining }); - var options = Options(selected.Channel, start, request.Budget, linked.Token); + var options = Options(selected, start, request.Budget, linked.Token); var encoded = DataProtoMapper.EncodeWriteRequest(batch); linked.Token.ThrowIfCancellationRequested(); dispatchStarted = true; @@ -544,7 +557,7 @@ public sealed partial class GrpcDataConnection : IDataConnection try { var compact = _enableCompactBatches && DataProtoMapper.NegotiateCompact(selected.Capabilities); - var headers = Headers(selected.Channel); + var headers = Headers(selected.Channel, RequestedFeatures(selected.Capabilities)); if (compact) headers.Add(DataConnectionProtoContract.CompactCodecHeader, DataConnectionProtoContract.CompactCodecVersion.ToString(System.Globalization.CultureInfo.InvariantCulture)); var call = selected.Channel.Client.Subscribe(headers, cancellationToken: lifetime.Token); subscription = new RemoteSubscription(this, call, selected, lifetime, compact, _maxMessageBytes, diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs index 33e61d771..388416776 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs @@ -46,6 +46,10 @@ public sealed class LocalCatalogCoordinator // A test can hold the host's existing subscription boundary to observe ordering. internal Action? BeforeSubscriptionApplyForTests { get; set; } + private string? _droppedExportRevision; + /// Diagnostics sink for the X0 dropped export-operation warning. + public Microsoft.Extensions.Logging.ILogger Logger { private get; init; } = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance; + public LocalCatalogCoordinator(CatalogActivation activation, DataPlaneAuthorityState authority, Func serving) { _activation = activation ?? throw new ArgumentNullException(nameof(activation)); @@ -132,6 +136,7 @@ public sealed class LocalCatalogCoordinator { ArgumentNullException.ThrowIfNull(attempt); ArgumentNullException.ThrowIfNull(snapshot); + IReadOnlyDictionary? dropped = null; lock (_gate) { var state = _activation.Current; @@ -145,8 +150,13 @@ public sealed class LocalCatalogCoordinator && node.Enabled && !node.MaintenanceMode)) return false; var token = _activation.CaptureStagedAuthority(attempt.Epoch, state.AuthorityEpoch); _staged = LocalExportCatalog.Compile(snapshot, serving, token); - return true; + if (_staged.DroppedUnknownOperations.Count != 0 && !string.Equals(_droppedExportRevision, attempt.Revision, StringComparison.Ordinal)) + dropped = _staged.DroppedUnknownOperations; + _droppedExportRevision = attempt.Revision; } + // Collected under _gate, reported after release. + if (dropped is not null) UnknownOperationDrops.Report(Logger, UnknownOperationDrops.ExportKind, attempt.Revision, dropped); + return true; } public bool Complete(CatalogAttempt attempt, bool topologySucceeded) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs index 1a6681113..63a50792e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs @@ -25,7 +25,7 @@ public sealed partial class LocalExportCatalog { ArgumentNullException.ThrowIfNull(snapshot); serving.Validate(requireEpochs: true); - if (DataConnectionValidator.Validate(snapshot).Count != 0) + if (DataConnectionValidator.ValidateDeployed(snapshot).Count != 0) throw new InvalidDataException("Origin catalog configuration is invalid."); var cluster = snapshot.ClusterId; var ids = StringComparer.OrdinalIgnoreCase; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs index 6de13fcc1..f54e00b1f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs @@ -78,6 +78,7 @@ public sealed partial class LocalExportCatalog .ToDictionary(x => x.Key, x => x.OrderBy(n => n.Metadata.BrowseName, StringComparer.Ordinal) .ThenBy(n => n.Metadata.View.Address.Identifier, StringComparer.Ordinal).ToArray()); var rules = new List(); + var dropped = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var export in exports.Where(x => x.Enabled && string.Equals(x.ClusterId, clusterId, StringComparison.OrdinalIgnoreCase))) { var wholeRealm = export.RootKind == "Cluster" && string.Equals(export.RootEntityId, clusterId, StringComparison.OrdinalIgnoreCase); @@ -89,13 +90,19 @@ public sealed partial class LocalExportCatalog || export.MaxMonitoredItems <= 0 || export.MaxStreams <= 0) throw new ArgumentException("Export has no valid origin root or policy.", nameof(exports)); rules.Add(new(export.DataExportId, export.PrincipalId, export.Realm, wholeRealm ? null : roots[0].Metadata.View, wholeRealm, - export.AllowedOperations, export.MaxBatchItems, export.MaxPageItems, export.MaxMonitoredItems, export.MaxStreams)); + // X0: an export bit this build does not implement grants nothing (a None-after-mask rule is kept and inert). + export.AllowedOperations & DataOperationSets.Understood, export.MaxBatchItems, export.MaxPageItems, export.MaxMonitoredItems, export.MaxStreams)); + if (UnknownOperationDrops.Unknown(export.AllowedOperations) is var unknown && unknown != DataOperations.None) + dropped[export.DataExportId] = unknown; } _exports = rules.ToArray(); + DroppedUnknownOperations = dropped; Nodes = new ReadOnlyCollection(_nodes.Values.ToArray()); } public string ClusterId { get; } + /// X0 diagnostics: exports whose operation bits this build does not implement were dropped, by export id. + public IReadOnlyDictionary DroppedUnknownOperations { get; } public ServingIdentity Serving { get; } internal IDataMappedCatalogAuthority MappingAuthority => _activation; public long AuthorityEpoch => _activation.AuthorityEpoch; @@ -111,6 +118,7 @@ public sealed partial class LocalExportCatalog throw new ArgumentException("A new process or catalog generation requires a newly compiled catalog.", nameof(serving)); ClusterId = current.ClusterId; Serving = serving; _activation = current._activation; _nodes = current._nodes; _children = current._children; _exports = current._exports; Nodes = current.Nodes; + DroppedUnknownOperations = current.DroppedUnknownOperations; } /// A role-only transition changes serving provenance without freshening source acquisitions. @@ -174,7 +182,10 @@ public sealed partial class LocalExportCatalog internal DataLimits LimitsFor(string principal, DataLimits limits) { - var rules = _exports.Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase)).ToArray(); + // An inert rule (X0: only operation bits this build does not implement) grants nothing, so it cannot lower the + // principal's limits on its other exports either. + var rules = _exports.Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase) + && x.Operations != DataOperations.None).ToArray(); return rules.Length == 0 ? limits : limits with { MaxBatchItems = Math.Min(limits.MaxBatchItems, rules.Min(x => x.Batch)), diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs index 57867d25c..7dcf4a669 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs @@ -29,6 +29,12 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable private object _configuredStamp = new(); private bool _disposed; + private IReadOnlyDictionary _droppedOperations = + new Dictionary(); + private string? _droppedRevision; + /// Diagnostics sink for the X0 dropped-operation warning (init so the DI constructor shape is unchanged). + public Microsoft.Extensions.Logging.ILogger Logger { private get; init; } = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance; + public ProjectedMappingDeploymentRuntime(LocalCatalogCoordinator coordinator, RemoteNamespaceResolver resolver) { _coordinator = coordinator ?? throw new ArgumentNullException(nameof(coordinator)); @@ -123,13 +129,46 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable ArgumentNullException.ThrowIfNull(connections); var frozenMappings = mappings.Select(Copy).ToArray(); var frozenConnections = connections.Select(Copy).ToArray(); + // X0 tolerant reader: a mapping bit this build does not implement grants nothing. Mask the frozen copies (the + // caller's rows are untouched) so every downstream check sees only understood operations. + var dropped = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var mapping in frozenMappings) + { + var unknown = UnknownOperationDrops.Unknown(mapping.AllowedOperations); + if (unknown == DataOperations.None) continue; + mapping.AllowedOperations &= DataOperationSets.Understood; + // Every mapping is masked; only an enabled one is a live grant worth reporting (as for connections/exports). + if (mapping.Enabled) dropped[mapping.RemoteNamespaceMappingId] = (mapping.DataConnectionId, unknown); + } + var report = false; lock (_gate) { ObjectDisposedException.ThrowIf(_disposed, this); if (!ReferenceEquals(attempt, _attempt)) return; _staged = frozenMappings; _connections = frozenConnections; + _droppedOperations = dropped; + report = dropped.Count != 0 && !string.Equals(_droppedRevision, attempt.Revision, StringComparison.Ordinal); + _droppedRevision = attempt.Revision; } + // Collected under _gate, reported after release. + if (report) + UnknownOperationDrops.Report(Logger, UnknownOperationDrops.MappingKind, attempt.Revision, + dropped.ToDictionary(x => x.Key, x => x.Value.Bits, StringComparer.OrdinalIgnoreCase)); + } + + /// X0 diagnostics: the staged mappings whose unknown operation bits were dropped, by mapping id. + public IReadOnlyDictionary DroppedUnknownOperations + { + get { lock (_gate) return _droppedOperations.ToDictionary(x => x.Key, x => x.Value.Bits, StringComparer.OrdinalIgnoreCase); } + } + + /// Per data connection id, how many of the staged mappings had unknown operation bits dropped. + public IReadOnlyDictionary CaptureDroppedByConnection() + { + lock (_gate) + return _droppedOperations.Values.GroupBy(x => x.ConnectionId, StringComparer.OrdinalIgnoreCase) + .ToDictionary(x => x.Key, x => x.Count(), StringComparer.OrdinalIgnoreCase); } internal void AttemptBegan(CatalogAttempt attempt) @@ -144,6 +183,7 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable Volatile.Write(ref _configuredStamp, new object()); _configuredCapabilities.Clear(); _staged = []; _connections = []; + _droppedOperations = new Dictionary(); changed = _active.Count != 0; Volatile.Write(ref _active, Array.Empty()); _byMapping.Clear(); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/UnknownOperationDrops.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/UnknownOperationDrops.cs new file mode 100644 index 000000000..f702397af --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/UnknownOperationDrops.cs @@ -0,0 +1,51 @@ +using System.Diagnostics.Metrics; +using Microsoft.Extensions.Logging; +using ZB.MOM.WW.OtOpcUa.Commons.Observability; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// +/// X0 tolerant-reader diagnostics. A deployed row (connection, export or mapping) may carry operation bits a newer +/// central authored and this build does not implement. They are dropped (no grant). Each drop is logged and counted. +/// +/// +/// +/// Semantics: counted once per row per ACCEPTED ARTIFACT CHANGE for that kind. Re-applying the same revision does not +/// recount, but A → B → A does (each is a change), and a process restart resets the per-kind memory. +/// +/// +/// The counter is , tagged kind = connection | export | mapping. +/// +/// +/// Callers collect under their own lock and call after releasing it. +/// +/// +public static class UnknownOperationDrops +{ + public const string CounterName = "otopcua.dataconnection.unknown_operations_dropped"; + public const string ConnectionKind = "connection"; + public const string ExportKind = "export"; + public const string MappingKind = "mapping"; + + private static readonly Counter Counter = OtOpcUaTelemetry.Meter.CreateCounter(CounterName, unit: "{row}", + description: "Deployed data-connection, export or mapping rows carrying operation bits this node does not implement; " + + "the bits were dropped (no grant). Counted once per row per accepted artifact change."); + + /// The bits of this build drops (zero when it understands all of them). + public static DataOperations Unknown(DataOperations authored) => authored & ~DataOperationSets.Understood; + + /// Logs a Warning and counts one per row. Never call while holding a component lock. + public static void Report(ILogger logger, string kind, string revision, IReadOnlyDictionary dropped) + { + ArgumentNullException.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(dropped); + foreach (var (id, bits) in dropped) + { + Counter.Add(1, new KeyValuePair("kind", kind)); + logger.LogWarning("Data {Kind} {Id} in artifact {ArtifactRevision} grants operation bits 0x{UnknownOperations:X} this node " + + "does not implement; they were dropped (no grant). Upgrade this node before relying on them.", + kind, id, revision, (int)bits); + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs index c96e7c45f..0ae0ce274 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs @@ -332,7 +332,7 @@ internal sealed partial class ParsedDeploymentArtifact { var requested = ids.ToHashSet(DataIds); var error = DataConnectionValidator - .Validate(snapshot) + .ValidateDeployed(snapshot) .FirstOrDefault(x => x.Context is not null && requested.Contains(x.Context)); if (error is not null) throw InvalidRow(error.Context); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index d60a19b5f..eeef8df2b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -2981,7 +2981,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS Drivers: drivers, AsOfUtc: DateTime.UtcNow, RunningFromCache: _isRunningFromCache, - DataConnections: _dataConnections?.CaptureDiagnostics(_projectedPublisher?.CaptureSourceCounts())); + DataConnections: _dataConnections?.CaptureDiagnostics(_projectedPublisher?.CaptureSourceCounts(), + _catalogCoordinator?.ProjectedMappings?.CaptureDroppedByConnection()), + DroppedExportOperations: _catalogCoordinator?.Current?.DroppedUnknownOperations); Sender.Tell(snapshot); } diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataFeatureHeaderTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataFeatureHeaderTests.cs new file mode 100644 index 000000000..f854f542b --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataFeatureHeaderTests.cs @@ -0,0 +1,103 @@ +using Grpc.Core; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.DataConnections; + +/// X0: the feature header round-trips and is tolerant of what a newer peer may send. +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")] +public sealed class GrpcDataFeatureHeaderTests +{ + [Theory] + [InlineData(DataFeatures.None, null)] + [InlineData(DataFeatures.History, "history")] + [InlineData(DataFeatures.Conditions, "conditions")] + [InlineData(DataFeatures.History | DataFeatures.Conditions, "history,conditions")] + public void Format_emits_a_header_only_for_a_nonempty_set(DataFeatures features, string? expected) + { + DataFeatureHeader.Format(features).ShouldBe(expected); + var headers = new Metadata(); + DataFeatureHeader.Apply(headers, features); + if (expected is null) headers.ShouldBeEmpty(); + else + { + var entry = headers.ShouldHaveSingleItem(); + entry.Key.ShouldBe("x-otopcua-data-features"); + entry.Value.ShouldBe(expected); + DataFeatureHeader.Parse(headers).ShouldBe(features); + } + } + + [Theory] + [InlineData("history", DataFeatures.History)] + [InlineData(" history , conditions ", DataFeatures.History | DataFeatures.Conditions)] + [InlineData("HISTORY", DataFeatures.History)] + [InlineData("", DataFeatures.None)] + [InlineData(",, ,", DataFeatures.None)] + [InlineData("events,history,quantum", DataFeatures.History)] + [InlineData("unknown", DataFeatures.None)] + public void Unknown_empty_and_whitespace_tokens_are_ignored(string value, DataFeatures expected) => + DataFeatureHeader.Parse(new Metadata { { "x-otopcua-data-features", value } }).ShouldBe(expected); + + [Fact] + public void Absent_header_is_none_and_multiple_entries_are_unioned() + { + DataFeatureHeader.Parse(null).ShouldBe(DataFeatures.None); + DataFeatureHeader.Parse(new Metadata { { "authorization", "Bearer x" } }).ShouldBe(DataFeatures.None); + DataFeatureHeader.Parse(new Metadata { { "x-otopcua-data-features", "history" }, { "x-otopcua-data-features", "conditions" } }) + .ShouldBe(DataFeatures.History | DataFeatures.Conditions); + } + + [Fact] + public void Binary_or_oversized_values_are_rejected() + { + Should.Throw(() => DataFeatureHeader.Parse(new Metadata { { "x-otopcua-data-features-bin", new byte[] { 1 } } })); + Should.Throw(() => DataFeatureHeader.Parse(new Metadata { { "x-otopcua-data-features", new string('h', 257) } })); + // The cap is on the summed length, so splitting a long value across entries does not evade it. + Should.Throw(() => DataFeatureHeader.Parse(new Metadata + { { "x-otopcua-data-features", new string(',', 200) }, { "x-otopcua-data-features", new string(',', 57) } })); + Should.NotThrow(() => DataFeatureHeader.Parse(new Metadata { { "x-otopcua-data-features", new string(',', 256) } })); + } +} + +/// X0 tolerant decode: an operation bit this build does not understand is dropped, never thrown on. +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")] +public sealed class GrpcDataTolerantDecodeTests +{ + private static readonly DataView View = new(new DataAddress("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "subject"); + + [Fact] + public void Metadata_decode_masks_unknown_allowed_operations() + { + var wire = DataProtoMapper.EncodeMetadata(new DataMetadata(View, "x", "Variable", DataValueKind.Int32, -1, [], true, + DataOperations.Read | DataOperations.Subscribe, 1, null, null, false)); + wire.AllowedOperations |= 32u | 64u | 128u | 256u | 512u | (1u << 20) | 0x8000_0000u; + var decoded = DataProtoMapper.DecodeMetadata(wire); + decoded.AllowedOperations.ShouldBe(DataOperations.Read | DataOperations.Subscribe); + } + + [Fact] + public void Capabilities_decode_masks_with_the_shared_understood_set() + { + var caps = new DataCapabilities(1, 3, new ServingIdentity("n", "i", "Primary", 1, 1, 1), DataReadiness.Ready, + DataOperations.Browse | DataOperations.Write, new HashSet { DataValueKind.Int32 }, + new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)), false, 0, "c"); + var wire = DataProtoMapper.EncodeCapabilities(caps); + wire.Operations |= 32u | 512u | 0x8000_0000u; + DataProtoMapper.DecodeCapabilities(wire).Operations.ShouldBe(DataOperations.Browse | DataOperations.Write); + } + + [Fact] + public void Metadata_response_with_unknown_bits_decodes_whole() + { + var response = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, new DataMetadata(View, "x", "Variable", + DataValueKind.Int32, -1, [], false, DataOperations.Read, 1, null, null, false), null)]); + response.Items[0].Value.AllowedOperations |= 32u; + var decoded = DataProtoMapper.DecodeMetadataResponse(response, new(16, 65536, 1000)); + decoded.ShouldHaveSingleItem().Value!.AllowedOperations.ShouldBe(DataOperations.Read); + W.Metadata.Descriptor.FindFieldByName("allowed_operations").FieldNumber.ShouldBe(8); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataProtoReservationTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataProtoReservationTests.cs new file mode 100644 index 000000000..4f785b026 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataProtoReservationTests.cs @@ -0,0 +1,107 @@ +using Google.Protobuf; +using Google.Protobuf.Reflection; +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; + +/// +/// X0 contract reservation. Each reserved number must stay unused until its phase adds it, and then carry exactly +/// the planned field. These run against the generated descriptors, so a proto edit that takes a number for +/// something else fails here. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")] +public sealed class GrpcDataProtoReservationTests +{ + public static TheoryData Reservations => new() + { + { nameof(CapabilitiesResponse), DataConnectionProtoContract.CapabilitiesHistoryField, "history", "HistoryCapabilities", "" }, + { nameof(CapabilitiesResponse), DataConnectionProtoContract.CapabilitiesConditionsField, "conditions", "ConditionCapabilities", "" }, + { nameof(Metadata), DataConnectionProtoContract.MetadataHistoryField, "history", "HistoryInfo", "" }, + { nameof(SubscriptionItem), DataConnectionProtoContract.SubscriptionItemConditionScopeField, "condition_scope", "ConditionScope", "" }, + { nameof(SubscriptionFrame), DataConnectionProtoContract.SubscriptionFrameConditionStatesArm, "condition_states", "ConditionStates", "frame" }, + }; + + [Theory] + [MemberData(nameof(Reservations))] + public void Reserved_number_is_unused_or_carries_its_planned_field(string message, int number, string expected, string type, string oneof) + { + var descriptor = DataConnectionReflection.Descriptor.MessageTypes.Single(m => m.Name == message); + var field = descriptor.FindFieldByNumber(number); + if (field is not null) + { + field.Name.ShouldBe(expected, $"{message} field {number} is reserved for '{expected}'"); + field.FieldType.ShouldBe(FieldType.Message); + field.IsRepeated.ShouldBeFalse(); + field.MessageType.Name.ShouldBe(type); + if (oneof.Length == 0) field.RealContainingOneof.ShouldBeNull(); + else field.RealContainingOneof.ShouldNotBeNull().Name.ShouldBe(oneof); + } + // The planned name is not squatted on another number either. + var named = descriptor.FindFieldByName(expected); + if (named is not null) named.FieldNumber.ShouldBe(number, $"{message}.{expected} must use its reserved number"); + DataConnectionProtoContract.Reserved(descriptor, number, expected, type, oneof.Length == 0 ? null : oneof).ShouldBeTrue(); + DataConnectionProtoContract.Reserved(descriptor, number, expected + "_other", type, oneof.Length == 0 ? null : oneof).ShouldBe(field is null); + } + + [Fact] + public void A_reserved_number_taken_with_the_wrong_type_or_shape_fails_the_check() + { + // Synthetic descriptors: the same name on the reserved number but the wrong type must not pass. + var file = new FileDescriptorProto { Name = "x0_reservation_probe.proto", Package = "probe", Syntax = "proto3" }; + file.MessageType.Add(new DescriptorProto { Name = "HistoryCapabilities" }); + var wrongType = new DescriptorProto { Name = "WrongType" }; + wrongType.Field.Add(new FieldDescriptorProto { Name = "history", Number = 16, Type = FieldDescriptorProto.Types.Type.String, + Label = FieldDescriptorProto.Types.Label.Optional, JsonName = "history" }); + var repeated = new DescriptorProto { Name = "Repeated" }; + repeated.Field.Add(new FieldDescriptorProto { Name = "history", Number = 16, Type = FieldDescriptorProto.Types.Type.Message, + TypeName = ".probe.HistoryCapabilities", Label = FieldDescriptorProto.Types.Label.Repeated, JsonName = "history" }); + var right = new DescriptorProto { Name = "Right" }; + right.Field.Add(new FieldDescriptorProto { Name = "history", Number = 16, Type = FieldDescriptorProto.Types.Type.Message, + TypeName = ".probe.HistoryCapabilities", Label = FieldDescriptorProto.Types.Label.Optional, JsonName = "history" }); + file.MessageType.Add(wrongType); file.MessageType.Add(repeated); file.MessageType.Add(right); + var built = FileDescriptor.BuildFromByteStrings([file.ToByteString()]).Single(); + DataConnectionProtoContract.Reserved(built.FindTypeByName("WrongType"), 16, "history", "HistoryCapabilities").ShouldBeFalse(); + DataConnectionProtoContract.Reserved(built.FindTypeByName("Repeated"), 16, "history", "HistoryCapabilities").ShouldBeFalse(); + DataConnectionProtoContract.Reserved(built.FindTypeByName("Right"), 16, "history", "HistoryCapabilities").ShouldBeTrue(); + DataConnectionProtoContract.Reserved(built.FindTypeByName("Right"), 16, "history", "HistoryCapabilities", "frame").ShouldBeFalse(); + } + + [Fact] + public void Reserved_numbers_are_pinned() + { + DataConnectionProtoContract.CapabilitiesHistoryField.ShouldBe(16); + DataConnectionProtoContract.CapabilitiesConditionsField.ShouldBe(17); + DataConnectionProtoContract.MetadataHistoryField.ShouldBe(14); + DataConnectionProtoContract.SubscriptionItemConditionScopeField.ShouldBe(4); + DataConnectionProtoContract.SubscriptionFrameConditionStatesArm.ShouldBe(9); + // The arm is a member of the frame oneof once it exists (a null oneof fails). + var arm = SubscriptionFrame.Descriptor.FindFieldByNumber(DataConnectionProtoContract.SubscriptionFrameConditionStatesArm); + if (arm is not null) arm.RealContainingOneof.ShouldNotBeNull().Name.ShouldBe("frame"); + } + + // X0-ONLY: the phase that adds one of these fields (H2: 16 and 14; A2: 17, 4 and 9) REPLACES this test with + // its own "advertised only when negotiated/provisioned" assertion. The reservation theory above stays. + [Fact] + public void X0_adds_no_field_yet_so_the_server_advertises_nothing_new() + { + foreach (var (descriptor, number) in new (MessageDescriptor, int)[] + { + (CapabilitiesResponse.Descriptor, 16), (CapabilitiesResponse.Descriptor, 17), (Metadata.Descriptor, 14), + (SubscriptionItem.Descriptor, 4), (SubscriptionFrame.Descriptor, 9), + }) + descriptor.FindFieldByNumber(number).ShouldBeNull($"{descriptor.Name} field {number} must not exist before its phase"); + DataConnectionReflection.Descriptor.Services.Single().Methods.Count.ShouldBe(6); + } + + [Fact] + public void Header_names_are_pinned_and_contract_validation_includes_the_reservations() + { + DataConnectionProtoContract.FeaturesHeader.ShouldBe("x-otopcua-data-features"); + DataConnectionProtoContract.CompactCodecHeader.ShouldBe("x-data-compact-codec"); + DataConnectionProtoContract.MaxFeaturesHeaderLength.ShouldBe(256); + Should.NotThrow(DataConnectionProtoContract.Validate); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataReservedOperationAuthoringTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataReservedOperationAuthoringTests.cs new file mode 100644 index 000000000..ebb94867d --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataReservedOperationAuthoringTests.cs @@ -0,0 +1,84 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests.DataConnections; + +/// +/// X0 grow site: authoring keeps rejecting the reserved bits until the phase that implements each one, so central +/// cannot hand a node a grant it does not implement. Only the node-side re-validation of a deployed artifact tolerates them. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")] +public sealed class GrpcDataReservedOperationAuthoringTests +{ + public static TheoryData ReservedBits => new(32, 64, 128, 256, 512); + + [Theory] + [MemberData(nameof(ReservedBits))] + public void Authoring_rejects_a_reserved_bit_on_connections_exports_and_mappings(int bit) + { + var errors = DataConnectionValidator.Validate(Snapshot(DataOperations.Read | (DataOperations)bit)); + errors.ShouldContain(x => x.Code == "DataConnectionOperationsInvalid" && x.Context == "connection"); + errors.ShouldContain(x => x.Code == "DataExportOperationsInvalid" && x.Context == "export"); + errors.ShouldContain(x => x.Code == "DataMappingOperationsInvalid" && x.Context == "mapping"); + } + + [Fact] + public void Authoring_accepts_the_v1_set_unchanged() + { + var errors = DataConnectionValidator.Validate(Snapshot(DataOperations.Read)); + errors.ShouldNotContain(x => x.Code.EndsWith("OperationsInvalid", StringComparison.Ordinal)); + DataOperationSets.V1.ShouldBe(DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe); + } + + [Theory] + [MemberData(nameof(ReservedBits))] + public void Deployed_revalidation_ignores_reserved_bits_but_keeps_every_other_operation_rule(int bit) + { + DataConnectionValidator.ValidateDeployed(Snapshot(DataOperations.Read | (DataOperations)bit)) + .ShouldNotContain(x => x.Code.EndsWith("OperationsInvalid", StringComparison.Ordinal)); + // Still rejected node-side: an empty grant, and a mapping wider than its connection in UNDERSTOOD bits. + DataConnectionValidator.ValidateDeployed(Snapshot(DataOperations.None)) + .ShouldContain(x => x.Code == "DataConnectionOperationsInvalid"); + var wider = Snapshot(DataOperations.Read | (DataOperations)bit); + wider.RemoteNamespaceMappings[0].AllowedOperations = DataOperations.Read | DataOperations.Subscribe; + DataConnectionValidator.ValidateDeployed(wider).ShouldContain(x => x.Code == "DataMappingOperationsInvalid"); + } + + [Theory] + [InlineData(1 << 10)] + [InlineData(1 << 30)] + public void Any_bit_outside_v1_is_rejected_at_authoring_and_tolerated_on_a_deployed_artifact(int bit) + { + // Authoring rejects anything outside V1. A deployed artifact may come from a newer central that defines bits this + // build has never heard of (not only the X0 reservation), so node-side re-validation ignores them; consumers mask + // them away (GrpcDataArtifactReadTests / GrpcDataUnknownOperationToleranceTests pin "parses, grants nothing"). + var authored = DataConnectionValidator.Validate(Snapshot(DataOperations.Read | (DataOperations)bit)); + authored.ShouldContain(x => x.Code == "DataConnectionOperationsInvalid"); + authored.ShouldContain(x => x.Code == "DataExportOperationsInvalid"); + DataConnectionValidator.ValidateDeployed(Snapshot(DataOperations.Read | (DataOperations)bit)) + .ShouldNotContain(x => x.Code.EndsWith("OperationsInvalid", StringComparison.Ordinal)); + // An all-unknown row is non-empty, so it is not an error; it simply grants nothing downstream. + DataConnectionValidator.ValidateDeployed(Snapshot((DataOperations)bit)) + .ShouldNotContain(x => x.Code == "DataConnectionOperationsInvalid" || x.Code == "DataExportOperationsInvalid"); + } + + private static DraftSnapshot Snapshot(DataOperations operations) => new() + { + GenerationId = 1, ClusterId = "local", + DataConnections = [new DataConnection + { + DataConnectionId = "connection", ClusterId = "local", Revision = 1, Enabled = true, AllowedOperations = operations, + ConsumerNodeIds = [], EligibleTargetNodeIds = [], Endpoints = ["https://origin.example:7443"], + MaxMessageBytes = 1, MaxBatchItems = 1, MaxPageItems = 1, MaxStreams = 1, MaxMonitoredItems = 1, MaxPendingBytes = 1, TimeoutMilliseconds = 1, + }], + DataExports = [new DataExport { DataExportId = "export", ClusterId = "local", Enabled = true, AllowedOperations = operations, PrincipalId = "p", Revision = 1 }], + RemoteNamespaceMappings = [new RemoteNamespaceMapping + { + RemoteNamespaceMappingId = "mapping", ClusterId = "local", DataConnectionId = "connection", Enabled = true, + AllowedOperations = operations, ConsumerNodeIds = [], Revision = 1, + }], + }; +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataOperationToleranceTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataOperationToleranceTests.cs new file mode 100644 index 000000000..7cbdeffe0 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataOperationToleranceTests.cs @@ -0,0 +1,73 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.DataConnections; + +/// X0: reserved operation bits and feature flags are pinned; unknown bits are tolerated fail-closed. +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")] +public sealed class GrpcDataOperationToleranceTests +{ + private static readonly DataLimits Limits = new(10, 10, 1024, 10, 1, 1024, + TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); + private static readonly HashSet Kinds = [DataValueKind.Int32]; + + [Fact] + public void Every_operation_bit_keeps_its_wire_value() + { + // Persisted as int in ConfigDb and carried as uint on the wire: never renumber. + var expected = new Dictionary + { + ["None"] = 0, ["Browse"] = 1, ["Metadata"] = 2, ["Read"] = 4, ["Write"] = 8, ["Subscribe"] = 16, + ["HistoryRead"] = 32, ["AlarmSubscribe"] = 64, ["AlarmAcknowledge"] = 128, ["AlarmConfirm"] = 256, ["AlarmShelve"] = 512, + }; + Enum.GetNames().Order().ShouldBe(expected.Keys.Order()); + foreach (var (name, value) in expected) ((int)Enum.Parse(name)).ShouldBe(value, name); + } + + [Fact] + public void Feature_flags_keep_their_values() + { + Enum.GetNames().ShouldBe(["None", "History", "Conditions"]); + ((int)DataFeatures.None).ShouldBe(0); + ((int)DataFeatures.History).ShouldBe(1); + ((int)DataFeatures.Conditions).ShouldBe(2); + } + + [Fact] + public void X0_understands_only_v1_and_reserves_the_five_new_bits() + { + DataOperationSets.V1.ShouldBe(DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe); + DataOperationSets.Understood.ShouldBe(DataOperationSets.V1); + DataOperationSets.Reserved.ShouldBe(DataOperations.HistoryRead | DataOperations.AlarmSubscribe | DataOperations.AlarmAcknowledge + | DataOperations.AlarmConfirm | DataOperations.AlarmShelve); + (DataOperationSets.Reserved & DataOperationSets.Understood).ShouldBe(DataOperations.None); + ((int)DataOperationSets.Reserved).ShouldBe(0x3E0); + } + + [Fact] + public void Capabilities_mask_unknown_bits_on_construction_instead_of_throwing() + { + var unknown = DataOperations.Read | DataOperations.HistoryRead | DataOperations.AlarmSubscribe | (DataOperations)(1 << 20); + var capabilities = Create(unknown); + capabilities.Operations.ShouldBe(DataOperations.Read); + Should.NotThrow(capabilities.Validate); + capabilities.ShouldBe(Create(DataOperations.Read)); + capabilities.GetHashCode().ShouldBe(Create(DataOperations.Read).GetHashCode()); + } + + [Fact] + public void Capabilities_mask_unknown_bits_through_with_expressions() + { + var capabilities = Create(DataOperations.Browse) with { Operations = DataOperations.Write | DataOperations.AlarmConfirm }; + capabilities.Operations.ShouldBe(DataOperations.Write); + Should.NotThrow(capabilities.Validate); + (capabilities with { Operations = DataOperations.AlarmShelve }).Operations.ShouldBe(DataOperations.None); + // Other members are untouched by the masking accessor. + (capabilities with { ClusterId = "other" }).Operations.ShouldBe(DataOperations.Write); + } + + private static DataCapabilities Create(DataOperations operations) => new(1, 0, + new ServingIdentity("node", "incarnation", "primary", 1, 1), DataReadiness.Ready, operations, + Kinds, Limits, false, 0, "cluster-a"); +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs new file mode 100644 index 000000000..ae4e40bc7 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs @@ -0,0 +1,376 @@ +using Google.Protobuf; +using Grpc.Core; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using ZB.MOM.WW.OtOpcUa.Host.Grpc; +using ZB.MOM.WW.OtOpcUa.Host.OpcUa; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +/// +/// Recorded-v1-client compatibility gate (plan test "C/H", exit gate of X0, H2, A2 and A3). +/// The recorded v1 client requests (, parsed from the golden hex, never +/// re-encoded) are replayed against the REAL (header parsing, authentication +/// seam, readiness/permission gates, DataProtoMapper encoders, size checks, subscription sink). Only the origin +/// facade behind is a deterministic FAKE. Every response must serialize to the +/// golden bytes captured from the pre-X0 server (master 2e4e4063); no field is time-varying, so nothing is +/// normalised ( is the one place a later phase may list a genuinely varying field). +/// RULE for H2/A2/A3: first extend the fake origin to emit that phase's new-shape data, then this test must still see +/// the same golden bytes without the header. Never re-record the goldens. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")] +public sealed class GrpcDataV1CompatibilityTests +{ + /// Every RPC of the v1 service, in the order records them. + internal static readonly string[] RpcNames = ["GetCapabilities", "Browse", "GetMetadata", "Read", "Write", "Subscribe"]; + public static TheoryData Rpcs => new(RpcNames); + + [Fact] + public void Recorded_v1_requests_still_encode_identically() + { + // The service is driven from the golden hex itself; this only checks the request encoders did not drift. + foreach (var rpc in RpcNames) + Hex(V1Requests.Bytes(rpc)).ShouldBe(GrpcDataV1Goldens.Requests[rpc], $"recorded {rpc} request"); + } + + [Theory] + [MemberData(nameof(Rpcs))] + public async Task V1_client_without_feature_header_gets_the_recorded_v1_response_bytes(string rpc) + { + var actual = await V1CompatibilityHarness.DriveAsync(rpc, new Metadata()); + actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response diverged from the recorded v1 bytes"); + } + + [Theory] + [MemberData(nameof(Rpcs))] + public async Task Feature_header_changes_nothing_while_the_server_supports_no_feature(string rpc) + { + var headers = new Metadata { { "x-otopcua-data-features", "history,conditions" } }; + var actual = await V1CompatibilityHarness.DriveAsync(rpc, headers); + actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response must not change in X0 when features are requested"); + } + + [Theory] + [MemberData(nameof(Rpcs))] + public async Task Every_rpc_records_the_requested_and_effective_feature_set(string rpc) + { + var (_, absent) = await V1CompatibilityHarness.DriveWithContextAsync(rpc, new Metadata()); + DataConnectionGrpcService.CallFeatures(absent).ShouldBe(DataCallFeatures.None); + absent.UserState.ContainsKey(typeof(DataCallFeatures)).ShouldBeTrue(); + + var (_, requested) = await V1CompatibilityHarness.DriveWithContextAsync(rpc, + new Metadata { { "x-otopcua-data-features", "history" }, { "x-otopcua-data-features", " conditions, future" } }); + // X0: the server supports no feature, so whatever is asked for, nothing is effective. + DataConnectionGrpcService.CallFeatures(requested).ShouldBe(new DataCallFeatures(DataFeatures.History | DataFeatures.Conditions, DataFeatures.None)); + DataConnectionGrpcService.SupportedFeatures.ShouldBe(DataFeatures.None); + } + + public static TheoryData MalformedHeaders() + { + var data = new TheoryData(); + foreach (var rpc in RpcNames) { data.Add(rpc, "binary"); data.Add(rpc, "oversized"); } + return data; + } + + [Theory] + [MemberData(nameof(MalformedHeaders))] + public async Task Binary_or_oversized_feature_header_is_rejected_invalid_argument(string rpc, string shape) + { + var headers = shape == "binary" + ? new Metadata { { "x-otopcua-data-features-bin", new byte[] { 0x68 } } } + : new Metadata { { "x-otopcua-data-features", "history," + new string(' ', 256) } }; + var failure = await Should.ThrowAsync(() => V1CompatibilityHarness.DriveAsync(rpc, headers)); + failure.StatusCode.ShouldBe(StatusCode.InvalidArgument); + // The same detail each RPC family already uses for any other invalid argument; no trailers. + failure.Status.Detail.ShouldBe(rpc == "Subscribe" ? "Invalid stream command." : "Invalid data request."); + failure.Trailers.ShouldBeEmpty(); + } + + public static TheoryData V1Statuses() + { + var data = new TheoryData(); + foreach (var header in new[] { "", "history,conditions" }) + { + data.Add("GetCapabilities/major-2", header); + data.Add("Browse/no-browse-grant", header); + data.Add("GetMetadata/no-metadata-grant", header); + data.Add("Read/no-read-grant", header); + data.Add("Subscribe/no-subscribe-grant", header); + } + return data; + } + + /// The v1 rejection statuses (code, detail and trailers) do not change with or without the header. + [Theory] + [MemberData(nameof(V1Statuses))] + public async Task V1_rejections_keep_their_status_detail_and_trailers(string scenario, string header) + { + var headers = header.Length == 0 ? new Metadata() : new Metadata { { "x-otopcua-data-features", header } }; + var (rpc, shape) = (scenario.Split('/')[0], scenario.Split('/')[1]); + var operations = shape switch + { + "no-browse-grant" => DataOperationSets.V1 & ~DataOperations.Browse, + "no-metadata-grant" => DataOperationSets.V1 & ~DataOperations.Metadata, + "no-read-grant" => DataOperationSets.V1 & ~DataOperations.Read, + "no-subscribe-grant" => DataOperationSets.V1 & ~DataOperations.Subscribe, + _ => DataOperationSets.V1, + }; + var request = shape == "major-2" ? new W.CapabilitiesRequest { ProtocolMajor = 2, ProtocolMinor = 5 }.ToByteArray() : null; + var failure = await Should.ThrowAsync(() => V1CompatibilityHarness.DriveAsync(rpc, headers, operations, request)); + var (code, detail) = shape == "major-2" + ? (StatusCode.Unimplemented, "Incompatible protocol major.") + : (StatusCode.PermissionDenied, "Data operation denied."); + failure.StatusCode.ShouldBe(code); + failure.Status.Detail.ShouldBe(detail); + failure.Trailers.ShouldBeEmpty(); + } + + /// + /// v1 Write without a write grant is not an RpcException: each item is answered RejectedBeforeDispatch in the body + /// (after a serving re-check). Those bytes are pinned like the other goldens, with and without the header. + /// + [Theory] + [InlineData("")] + [InlineData("history,conditions")] + public async Task Write_without_a_write_grant_rejects_each_item_before_dispatch_with_the_v1_bytes(string header) + { + var headers = header.Length == 0 ? new Metadata() : new Metadata { { "x-otopcua-data-features", header } }; + var actual = await V1CompatibilityHarness.DriveAsync("Write", headers, DataOperationSets.V1 & ~DataOperations.Write); + actual.ShouldBe(GrpcDataV1Goldens.Responses["Write/no-write-grant"]); + } + + internal static string Hex(byte[] bytes) => Convert.ToHexString(bytes); + + /// X0: no field varies. Add explicit, listed normalisations here only if a later phase needs one. + internal static IMessage Normalise(IMessage message) => message; +} + +/// The recorded v1 client requests. Changing any value here invalidates the goldens. +internal static class V1Requests +{ + internal static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 16, 65_536); + internal static readonly DataView Raw = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant/Speed"), + DataRealm.Raw, null, 0, "Plant/Speed"); + internal static readonly DataView Folder = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant"), + DataRealm.Raw, null, 0, "Plant"); + internal static readonly DataView Array = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant/Array"), + DataRealm.Raw, null, 0, "Plant/Array"); + internal static readonly DataView Missing = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant/Missing"), + DataRealm.Raw, null, 0, "Plant/Missing"); + + internal static IMessage Message(string rpc) => rpc switch + { + "GetCapabilities" => new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 5 }, + "Browse" => DataProtoMapper.EncodeBrowseRequest(new BrowseRequest(Folder, null, null, Budget)), + "GetMetadata" => DataProtoMapper.EncodeMetadataRequest(new MetadataRequest([Raw, Missing], Budget)), + "Read" => DataProtoMapper.EncodeReadRequest(new ReadRequest([new("r1", Raw, TimeSpan.FromSeconds(2)), new("r2", Missing, null)], Budget)), + "Write" => WriteRequest(), + "Subscribe" => DataProtoMapper.EncodeCommand(new OpenSubscription("sub-1", 1, "open-1", TimeSpan.FromSeconds(5), + [new("item-1", Raw, new(TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null))], + false, TimeSpan.FromMinutes(5), Budget)), + _ => throw new ArgumentOutOfRangeException(nameof(rpc)), + }; + + private static W.WriteRequest WriteRequest() + { + using var first = DataValue.FromScalar(DataValueKind.Int32, 17); + using var second = DataValue.FromScalar(DataValueKind.String, "abc"); + return DataProtoMapper.EncodeWriteRequest(new WriteBatch( + [ + new("w1", "op-1", Raw, first, 1, "boot", TimeSpan.FromSeconds(4), 1), + new("w2", "op-2", Missing, second, 1, "boot", TimeSpan.FromSeconds(4), 1), + ], Budget)); + } + + internal static byte[] Bytes(string rpc) => Message(rpc).ToByteArray(); +} + +/// +/// Drives the real in-process with a recorded request and a +/// deterministic origin facade. Reusable by H2/A2/A3: pass the headers a client of that phase sends. +/// +internal static class V1CompatibilityHarness +{ + /// The fake origin's granted operations (default: the full v1 set). + /// Request bytes; default is the recorded golden request for . + internal static async Task DriveAsync(string rpc, Metadata headers, DataOperations operations = DataOperationSets.V1, + byte[]? request = null) => (await DriveWithContextAsync(rpc, headers, operations, request)).Bytes; + + internal static async Task<(string Bytes, ServerCallContext Context)> DriveWithContextAsync(string rpc, Metadata headers, + DataOperations operations = DataOperationSets.V1, byte[]? request = null) + { + var (service, context) = Create(rpc, headers, operations); + return (await DriveAsync(service, context, rpc, request ?? Convert.FromHexString(GrpcDataV1Goldens.Requests[rpc])), context); + } + + private static async Task DriveAsync(DataConnectionGrpcService service, ServerCallContext context, string rpc, byte[] bytes) + { + IMessage response = rpc switch + { + "GetCapabilities" => await service.GetCapabilities(W.CapabilitiesRequest.Parser.ParseFrom(bytes), context), + "Browse" => await service.Browse(W.BrowseRequest.Parser.ParseFrom(bytes), context), + "GetMetadata" => await service.GetMetadata(W.MetadataRequest.Parser.ParseFrom(bytes), context), + "Read" => await service.Read(W.ReadRequest.Parser.ParseFrom(bytes), context), + "Write" => await service.Write(W.WriteRequest.Parser.ParseFrom(bytes), context), + "Subscribe" => null!, + _ => throw new ArgumentOutOfRangeException(nameof(rpc)), + }; + if (rpc != "Subscribe") + return GrpcDataV1CompatibilityTests.Hex(GrpcDataV1CompatibilityTests.Normalise(response).ToByteArray()); + var writer = new Writer(); + await service.Subscribe(new Reader(W.SubscriptionCommand.Parser.ParseFrom(bytes)), writer, context); + return string.Join("|", writer.Frames.Select(f => GrpcDataV1CompatibilityTests.Hex(GrpcDataV1CompatibilityTests.Normalise(f).ToByteArray()))); + } + + internal static (DataConnectionGrpcService Service, CallContext Context) Create(string rpc, Metadata headers, + DataOperations operations = DataOperationSets.V1) + { + var (bearer, id, hash) = ApiKeySecret.Generate("pepper"); + var authority = new DataPlaneAuthorityState(); + authority.Apply("cluster", "v1", [new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash, Enabled = true }], + [], new Dictionary>()); + var authenticator = new DataConnectionAuthenticator(authority, Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System); + var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, AllowedHosts = ["source.local"], CertificatePath = "server.pem" }; + var context = new CallContext(rpc, headers); + var http = new DefaultHttpContext(); + http.Connection.LocalPort = 9443; http.Request.Protocol = "HTTP/2"; http.Request.Scheme = "https"; http.Request.Method = "POST"; + http.Request.Host = new HostString("source.local", 9443); http.Request.Path = context.Method; + http.Items[typeof(DataAuthenticatedContext)] = authenticator.Authenticate(bearer); + http.Items[typeof(DataTarget)] = new DataTarget(DataTargetMode.Node, "cluster", "node"); + context.UserState["__HttpContext"] = http; + return (new DataConnectionGrpcService(new Factory(operations), Options.Create(options), authenticator), context); + } + + internal static HttpContext Http(ServerCallContext context) => (HttpContext)context.UserState["__HttpContext"]; + + private sealed class Factory(DataOperations operations) : IDataConnectionFactory + { + public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) => new Origin(target, operations); + } + + /// A deterministic v1 origin exercising every optional v1 field the encoders emit. + private sealed class Origin(DataTarget target, DataOperations operations) : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate + { + internal static readonly ServingIdentity Serving = new("node", "boot", "Primary", 1, 1, 1); + private static readonly DateTimeOffset Source = new(2026, 11, 23, 12, 0, 0, TimeSpan.Zero); + private static readonly DateTimeOffset Server = Source.AddMilliseconds(250); + public DataTarget Target => target; + public TimeProvider Clock => TimeProvider.System; + public bool CanPublish(ServingIdentity expectedServing) => expectedServing == Serving; + public bool CanPublishCapabilities(DataCapabilities expected) => true; + + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken token) => Task.FromResult(new DataCapabilities( + 1, 3, Serving, DataReadiness.Ready, operations, + new HashSet { DataValueKind.Int32, DataValueKind.String, DataValueKind.Array }, + new(16, 16, 65_536, 16, 4, 65_536, TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(10), TimeSpan.FromSeconds(5), 1000), + false, 0, "cluster", true, true, true, true, true)); + + private static DataMetadata Scalar => new(V1Requests.Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true, + DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe, + 1, "src-1", "rpm", false); + private static DataMetadata ArrayItem => new(V1Requests.Array, "Array", "Variable", DataValueKind.Array, 1, [3], false, + DataOperations.Browse | DataOperations.Metadata | DataOperations.Read, 1, null, null, true, DataValueKind.UInt8); + + public Task BrowseAsync(BrowseRequest request, CancellationToken token) => Task.FromResult(new DataBrowseBranch( + request.Parent, DataItemStatus.Good, [Scalar, ArrayItem], false, "next-page", new MetadataLease(1, 1, TimeSpan.FromSeconds(30)))); + + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken token) => + Task.FromResult>>( + [ + new("0", DataItemStatus.Good, Scalar, null, new MetadataLease(1, 1, TimeSpan.FromSeconds(30))), + new("1", DataItemStatus.NotFound, null, "No such node."), + ]); + + public Task> ReadAsync(ReadRequest request, CancellationToken token) => + Task.FromResult>( + [ + new("r1", DataItemStatus.Good, DataReadiness.Ready, TimeSpan.FromMilliseconds(120), + new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 0, Source, Server, Serving, 7), null, new Lease()), + new("r2", DataItemStatus.Denied, DataReadiness.Unavailable, null, null, "Denied."), + ]); + + public Task> WriteAsync(WriteBatch request, CancellationToken token) => + Task.FromResult>( + [ + new("w1", new(DataWriteState.DriverConfirmedSuccess, 0, null)), + new("w2", new(DataWriteState.RejectedBeforeDispatch, 0x80340000u, "Unknown node.")), + ]); + + public Task SubscribeAsync(CancellationToken token) => Task.FromResult(new Subscription()); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + + private sealed class Lease : IDataPublicationLease { public bool IsValid => true; public void Dispose() { } } + + private sealed class Subscription : IDataSubscriptionTransport + { + private readonly TaskCompletionSource _opened = new(TaskCreationOptions.RunContinuationsAsynchronously); + public Task SendAsync(DataSubscriptionCommand command, CancellationToken token) { _opened.TrySetResult(command); return Task.CompletedTask; } + public IAsyncEnumerable ReadAllAsync(CancellationToken token) => throw new NotSupportedException(); + public async Task RunDeliveryAsync(IDataSubscriptionDeliverySink sink, CancellationToken token) + { + var open = (OpenSubscription)await _opened.Task.WaitAsync(token); + var handle = new DataItemHandle(open.SubscriptionId, open.StreamEpoch, 1, 1); + await Emit(sink, new DataSubscriptionAck(open.SubscriptionId, open.StreamEpoch, 1, open.CommandId, + [new("item-1", DataItemStatus.Good, handle, open.Items[0].Settings, null)]), token); + await Emit(sink, new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 2, DataStreamControlKind.SnapshotBegin, + [new(0, 3)], 1, 1, null), token); + using (var values = new DataSubscriptionValues(open.SubscriptionId, open.StreamEpoch, 3, true, + [new(handle, new(DataValue.FromScalar(DataValueKind.Int32, 42), 0, Source, Server, Serving, 7), + new(TimeSpan.Zero, TimeSpan.FromMilliseconds(120)), DataReadiness.Ready)])) + await Emit(sink, values, token); + await Emit(sink, new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 4, DataStreamControlKind.SnapshotEnd, + [new(0, 3)], 1, 1, "done"), token); + } + private static async Task Emit(IDataSubscriptionDeliverySink sink, DataSubscriptionFrame frame, CancellationToken token) + { + using var prepared = await sink.PrepareAsync(frame, 65_536, token); + ((IDataPreparedSubscriptionPublication)prepared).SetPublicationGuard(() => true); + await sink.WriteAsync(prepared, token); + } + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + } + + internal sealed class Reader(W.SubscriptionCommand open) : IAsyncStreamReader + { + private int _read; + public W.SubscriptionCommand Current { get; private set; } = null!; + public async Task MoveNext(CancellationToken token) + { + if (Interlocked.Exchange(ref _read, 1) == 0) { Current = open; return true; } + await Task.Delay(Timeout.Infinite, token); return false; + } + } + + internal sealed class Writer : IServerStreamWriter + { + public List Frames { get; } = []; + public WriteOptions? WriteOptions { get; set; } + public Task WriteAsync(W.SubscriptionFrame frame) { Frames.Add(frame); return Task.CompletedTask; } + public Task WriteAsync(W.SubscriptionFrame frame, CancellationToken cancellationToken) => WriteAsync(frame); + } + + internal sealed class CallContext(string rpc, Metadata headers) : ServerCallContext + { + protected override string MethodCore => DataConnectionEndpoints.ServicePrefix + rpc; + protected override string HostCore => "source.local"; + protected override string PeerCore => "ipv4:127.0.0.1:0"; + protected override DateTime DeadlineCore => DateTime.MaxValue; + protected override Metadata RequestHeadersCore => headers; + protected override CancellationToken CancellationTokenCore => TestContext.Current.CancellationToken; + protected override Metadata ResponseTrailersCore { get; } = []; + protected override Status StatusCore { get; set; } + protected override WriteOptions? WriteOptionsCore { get; set; } + protected override AuthContext AuthContextCore => new(null, new Dictionary>()); + protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) => throw new NotSupportedException(); + protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) => Task.CompletedTask; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1Goldens.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1Goldens.cs new file mode 100644 index 000000000..baf73dc20 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1Goldens.cs @@ -0,0 +1,31 @@ +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +/// +/// Golden bytes recorded from the pre-X0 server (master 2e4e4063) by . +/// Uppercase hex of ToByteArray(); Subscribe frames are joined with '|'. Never re-record these to make a +/// later phase pass: a difference is a v1 wire regression. +/// +internal static class GrpcDataV1Goldens +{ + internal static readonly IReadOnlyDictionary Requests = new Dictionary + { + ["GetCapabilities"] = "08011005", + ["Browse"] = "0A3A0A2F0A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A01732205506C616E7410012A05506C616E74220B0880E1EB17101018808004", + ["GetMetadata"] = "0A460A350A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220B506C616E742F537065656410012A0B506C616E742F53706565640A4A0A370A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220D506C616E742F4D697373696E6710012A0D506C616E742F4D697373696E67120B0880E1EB17101018808004", + ["Read"] = "0A510A02723112460A350A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220B506C616E742F537065656410012A0B506C616E742F53706565641880DAC4090A500A027232124A0A370A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220D506C616E742F4D697373696E6710012A0D506C616E742F4D697373696E67120B0880E1EB17101018808004", + ["Write"] = "0A670A02773112046F702D311A460A350A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220B506C616E742F537065656410012A0B506C616E742F537065656422040805182228013204626F6F743880B4891340010A6E0A02773212046F702D321A4A0A370A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220D506C616E742F4D697373696E6710012A0D506C616E742F4D697373696E672207080D3A0361626328013204626F6F743880B489134001120B0880E1EB17101018808004", + ["Subscribe"] = "0A057375622D3110011A066F70656E2D312080E1EB172A730A5E0A066974656D2D3112460A350A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220B506C616E742F537065656410012A0B506C616E742F53706565641A0C08C096B1021080ADE20418021880BCC1960B220B0880E1EB17101018808004", + }; + + internal static readonly IReadOnlyDictionary Responses = new Dictionary + { + ["GetCapabilities"] = "080110031A1B0A046E6F64651204626F6F741A075072696D6172792001280130012001281F3203050D113A24081010101880800420102804308080043880C6868F014080F882AD164880E1EB1750E8075207636C757374657258016001680170017801", + ["Browse"] = "0A3A0A2F0A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A01732205506C616E7410012A05506C616E7410011A780A460A350A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220B506C616E742F537065656410012A0B506C616E742F5370656564120553706565641A085661726961626C65200528FFFFFFFFFFFFFFFFFF013801401F480152057372632D315A0372706D1A680A460A350A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220B506C616E742F417272617910012A0B506C616E742F4172726179120541727261791A085661726961626C652011280132010340074801600168072A096E6578742D70616765320A080110011880C6868F013A1B0A046E6F64651204626F6F741A075072696D617279200128013001", + ["GetMetadata"] = "0A8B010A013010011A780A460A350A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220B506C616E742F537065656410012A0B506C616E742F5370656564120553706565641A085661726961626C65200528FFFFFFFFFFFFFFFFFF013801401F480152057372632D315A0372706D2A0A080110011880C6868F010A140A01311003220D4E6F2073756368206E6F64652E121B0A046E6F64651204626F6F741A075072696D617279200128013001", + ["Read"] = "0A480A0272311001180120809F492A3A0A04080518541A0608C0D590D806220B08C0D590D8061080E59A772A1B0A046E6F64651204626F6F741A075072696D61727920012801300130070A110A02723210021803320744656E6965642E121B0A046E6F64651204626F6F741A075072696D617279200128013001", + ["Write"] = "0A060A02773110020A1B0A0277321001188080D08108220D556E6B6E6F776E206E6F64652E121B0A046E6F64651204626F6F741A075072696D617279200128013001", + ["Subscribe"] = "0A057375622D311001180122310A066F70656E2D3112270A066974656D2D3110011A0D0A057375622D31100118012001220C08C096B1021080ADE2041802421B0A046E6F64651204626F6F741A075072696D617279200128013001|0A057375622D31100118022A0A08011202100318012001421B0A046E6F64651204626F6F741A075072696D617279200128013001|0A057375622D311001180332530801124F0A0D0A057375622D31100118012001123A0A04080518541A0608C0D590D806220B08C0D590D8061080E59A772A1B0A046E6F64651204626F6F741A075072696D617279200128013001300718002001421B0A046E6F64651204626F6F741A075072696D617279200128013001|0A057375622D31100118042A10080212021003180120012A04646F6E65421B0A046E6F64651204626F6F741A075072696D617279200128013001", + // Write with the origin lacking the Write grant (recorded on pre-X0 DataConnectionGrpcService). + ["Write/no-write-grant"] = "0A300A0277311001188080C481082222577269746520756E617661696C61626C65206265666F72652064697370617463682E0A300A0277321001188080C481082222577269746520756E617661696C61626C65206265666F72652064697370617463682E121B0A046E6F64651204626F6F741A075072696D617279200128013001", + }; +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs index eb7837c7e..f73118526 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs @@ -188,7 +188,6 @@ public sealed class GrpcDataArtifactReadTests [InlineData("Endpoints", "null")] [InlineData("Endpoints", "[\"http://node-b:7443\"]")] [InlineData("AllowedOperations", "0")] - [InlineData("AllowedOperations", "1073741824")] [InlineData("MaxBatchItems", "0")] [InlineData("Revision", "0")] public void Malformed_enabled_connection_fails_closed_with_row_diagnostics( @@ -235,7 +234,6 @@ public sealed class GrpcDataArtifactReadTests [InlineData("Realm", "0")] [InlineData("RootEntityId", "\"missing-origin\"")] [InlineData("RootKind", "\"RemoteNamespaceMapping\"")] - [InlineData("AllowedOperations", "1073741824")] [InlineData("Revision", "0")] public void Malformed_enabled_export_cannot_become_a_broad_or_reexport_grant( string field, @@ -251,6 +249,29 @@ public sealed class GrpcDataArtifactReadTests error.Message.ShouldContain("export-a"); } + [Trait("Phase", "X0")] + // X0 (plan section 4.3): an operation bit this build does not understand, e.g. one a newer central authored, is + // TOLERATED at the parse seam and grants nothing downstream. Before X0 it failed the whole row closed (and with it + // the snapshot). Only the understood subset is validated; an all-unknown row parses and is inert. + [Theory] + [InlineData(1073741824, 0)] + [InlineData(5 | 1073741824, 5)] + [InlineData(5 | 32, 5)] + public void Unknown_operation_bit_on_a_connection_or_export_parses_and_grants_nothing(int authored, int understood) + { + var root = Fixture(); + root["DataConnections"]![0]!["AllowedOperations"] = authored; + root["DataExports"]![0]!["AllowedOperations"] = authored; + using var parsed = DeploymentArtifact.Open(Blob(root)); + + var connection = parsed.ParseDataConnections(NodeA).ShouldHaveSingleItem(); + var export = parsed.ParseDataExports(NodeA).ShouldHaveSingleItem(); + connection.AllowedOperations.ShouldBe((DataOperations)authored, "rows are returned as authored"); + (connection.AllowedOperations & DataOperationSets.Understood).ShouldBe((DataOperations)understood); + (export.AllowedOperations & DataOperationSets.Understood).ShouldBe((DataOperations)understood); + (DataOperationSets.Understood & (DataOperations)1073741824).ShouldBe(DataOperations.None, "the bit is never granted"); + } + [Fact] public void Missing_connection_array_does_not_leave_an_enabled_orphan_mount() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs index 344942182..26f6ed984 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs @@ -152,6 +152,112 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase runtime.Active.ShouldBeEmpty(); } + /// + /// X0 end to end (plan §4.3): an operation bit no build defines (1 << 30) on one connection, one export and one mapping + /// flows through the REAL artifact parse, origin catalog compile, mapping stage and consumer runtime. Every other + /// connection/export stays up, the bit is never granted anywhere, and each drop is visible in diagnostics. + /// + [Fact(Timeout = 30000), Trait("Phase", "X0")] + public async Task X0_unknown_operation_bit_flows_through_parse_catalog_mapping_and_runtime_and_is_never_granted() + { + const DataOperations Unknown = (DataOperations)(1 << 30); + const DataOperations Bmr = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read; + var root = JsonNode.Parse(Artifact())!.AsObject(); + root["DataConnectionScopeVersion"] = 1; + DataConnection Connection(string id, DataOperations operations) => new() + { + DataConnectionId = id, ClusterId = "cluster", Revision = 1, Enabled = true, ConsumerNodeIds = ["node-a"], + TargetMode = DataTargetMode.Node, Consistency = DataConsistency.Primary, ExpectedClusterId = "remote-cluster", + ExpectedNodeId = "remote", Endpoints = ["https://remote.example:8443"], SecretReference = "secret:data/" + id, + SecretScopeClusterId = "cluster", AllowedOperations = operations, MaxMessageBytes = 65536, MaxBatchItems = 16, + MaxPageItems = 16, MaxStreams = 2, MaxMonitoredItems = 16, MaxPendingBytes = 65536, TimeoutMilliseconds = 5000, + }; + root["DataConnections"] = JsonSerializer.SerializeToNode(new[] { Connection("link", Bmr | Unknown), Connection("plain", Bmr) }); + root["DataExports"]![0]!["AllowedOperations"] = (int)(Bmr | Unknown); + root["DataExports"]!.AsArray().Add(JsonNode.Parse(""" + {"DataExportId":"uns","ClusterId":"cluster","Enabled":true,"Realm":2,"RootKind":"Cluster","RootEntityId":"cluster","PrincipalId":"other","AllowedOperations":7} + """)); + var mapping = TestMapping(); mapping.ConsumerNodeIds = ["node-a"]; mapping.RemoteNamespaceUri = V3NodeIds.RawNamespaceUri; + mapping.AllowedOperations = DataOperations.Browse | Unknown; + root["RemoteNamespaceMappings"] = JsonSerializer.SerializeToNode(new[] { mapping }); + var bytes = Encoding.UTF8.GetBytes(root.ToJsonString()); + + // Origin side: the catalog compiles (pre-X0 it threw "Origin catalog configuration is invalid"). + var authority = new DataPlaneAuthorityState(); + var coordinator = NewCoordinator(authority, new CatalogActivation()); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy), + new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); + using var mappings = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var attempt = Prepare(coordinator, bytes); + using var parsed = DeploymentArtifact.Open(bytes); + var connections = parsed.ParseDataConnections(Node.Value); + mappings.Stage(attempt, parsed.ParseRemoteNamespaceMappings(Node.Value), connections); + coordinator.Complete(attempt, true).ShouldBeTrue(); + var catalog = coordinator.Current.ShouldNotBeNull(); + catalog.ExportOperations("peer").ShouldBe(Bmr, "the unknown export bit is never granted"); + catalog.ExportOperations("other").ShouldBe(Bmr, "the unaffected export is up"); + catalog.DroppedUnknownOperations.ShouldBe(new Dictionary { ["raw"] = Unknown }); + + // Mapping stage: masked, placed, counted per connection. + mappings.Active.ShouldHaveSingleItem().Mapping.AllowedOperations.ShouldBe(DataOperations.Browse); + mappings.DroppedUnknownOperations.ShouldBe(new Dictionary { ["map"] = Unknown }); + var mappingDrops = mappings.CaptureDroppedByConnection(); + mappingDrops.ShouldBe(new Dictionary { ["link"] = 1 }); + + // Consumer runtime: both connections are up; the bit is never granted; diagnostics carry the drops. + await using var runtime = new DataConnectionDeploymentRuntime(Node.Value, "cluster", new X0Security(), new X0Activator(), 4); + runtime.Apply(new(1, attempt.Revision, connections)); + foreach (var id in new[] { "link", "plain" }) + { + DataConnectionDeploymentLease? lease = null; + for (var i = 0; i < 250 && !runtime.TryAcquire(id, out lease); i++) await Task.Delay(20, TestContext.Current.CancellationToken); + lease.ShouldNotBeNull(id); + using (lease) lease.AllowedOperations.ShouldBe(Bmr, id); + } + var diagnostics = runtime.CaptureDiagnostics(null, mappingDrops).ToDictionary(x => x.ConnectionId); + diagnostics["link"].DroppedUnknownOperations.ShouldBe(Unknown); + diagnostics["link"].MappingsWithDroppedOperations.ShouldBe(1); + diagnostics["plain"].DroppedUnknownOperations.ShouldBe(DataOperations.None); + diagnostics["plain"].MappingsWithDroppedOperations.ShouldBe(0); + } + + [Fact, Trait("Phase", "X0")] + public void X0_a_disabled_mapping_is_masked_but_its_dropped_bits_are_not_reported() + { + var authority = new DataPlaneAuthorityState(); + var coordinator = NewCoordinator(authority, new CatalogActivation()); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy), + new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); + using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var attempt = Prepare(coordinator, Artifact()); + var enabled = TestMapping(); enabled.AllowedOperations = DataOperations.Browse | DataOperations.HistoryRead; + var disabled = TestMapping(); disabled.RemoteNamespaceMappingId = "off"; disabled.BranchName = "Off"; disabled.Enabled = false; + disabled.AllowedOperations = DataOperations.Browse | DataOperations.AlarmSubscribe; + runtime.Stage(attempt, [enabled, disabled], [TestConnection()]); + runtime.DroppedUnknownOperations.ShouldBe(new Dictionary { ["map"] = DataOperations.HistoryRead }); + runtime.CaptureDroppedByConnection().ShouldBe(new Dictionary { ["link"] = 1 }); + coordinator.Complete(attempt, true).ShouldBeTrue(); + runtime.Active.ShouldHaveSingleItem().Mapping.AllowedOperations.ShouldBe(DataOperations.Browse); + } + + private sealed class X0Security : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new("1", "trust", "key", () => new X0NoNetwork())); + } + private sealed class X0NoNetwork : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + throw new InvalidOperationException("This test must not use the network."); + } + private sealed class X0Activator : IDataConnectionScopeActivator + { + public Task SetScopeAsync(long version, IReadOnlyDictionary allowlist, CancellationToken cancellationToken) => Task.CompletedTask; + } + private static RemoteNamespaceMapping TestMapping() => new() { RemoteNamespaceMappingId = "map", ClusterId = "cluster", DataConnectionId = "link", Revision = 1, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, LocalParentKind = "RawFolder", LocalParentId = "folder", BranchName = "Remote", RemoteRootEntityId = "remote-root", diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFeatureHeaderClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFeatureHeaderClientTests.cs new file mode 100644 index 000000000..65d1e8c37 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFeatureHeaderClientTests.cs @@ -0,0 +1,113 @@ +using System.Buffers.Binary; +using System.Net; +using Google.Protobuf; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// X0 consumer side of the feature negotiation: the header is derived from the SELECTED endpoint's capabilities +/// and sent only when non-empty. No capability advertises a feature yet, so an X0 consumer never sends it, even +/// to an origin that advertises every v1 flag and unknown operation bits. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")] +public sealed class GrpcDataFeatureHeaderClientTests +{ + private static readonly DataLimits Limits = new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)); + private static readonly ServingIdentity Serving = new("a", "boot", "Primary", 1, 1, 1); + private static readonly DataView View = new(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x"); + private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 16, 65536); + + [Fact] + public void Requested_features_follow_the_selected_endpoint_and_are_empty_in_X0() + { + var everything = new DataCapabilities(1, 5, Serving, DataReadiness.Ready, DataOperationSets.V1 | DataOperationSets.Reserved, + new HashSet { DataValueKind.Int32 }, Limits, true, 1, "c", true, true, true, true, true); + GrpcDataConnection.RequestedFeatures(everything).ShouldBe(DataFeatures.None); + } + + [Fact] + public async Task No_rpc_carries_the_feature_header_in_X0() + { + var handler = new RecordingHandler(); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); + var ct = TestContext.Current.CancellationToken; + + (await connection.GetCapabilitiesAsync(Budget, ct)).Operations.ShouldBe(DataOperationSets.V1); + (await connection.GetMetadataAsync(new MetadataRequest([View], Budget), ct)).ShouldHaveSingleItem().Value!.AllowedOperations + .ShouldBe(DataOperations.Read | DataOperations.Write); + foreach (var result in await connection.ReadAsync(new ReadRequest([new("r", View, null)], Budget), ct)) result.Dispose(); + using (var value = DataValue.FromScalar(DataValueKind.Int32, 1)) + (await connection.WriteAsync(new WriteBatch([new("w", "op", View, value, 1, "boot", TimeSpan.FromSeconds(4), 1)], Budget), ct)) + .ShouldHaveSingleItem(); + + handler.Paths.ShouldContain(p => p.EndsWith("/GetMetadata", StringComparison.Ordinal)); + handler.Paths.ShouldContain(p => p.EndsWith("/Read", StringComparison.Ordinal)); + handler.Paths.ShouldContain(p => p.EndsWith("/Write", StringComparison.Ordinal)); + handler.FeatureHeaders.ShouldBeEmpty(); + } + + private sealed class RecordingHandler : HttpMessageHandler + { + public List Paths { get; } = []; + public List FeatureHeaders { get; } = []; + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var path = request.RequestUri!.AbsolutePath; + lock (Paths) + { + Paths.Add(path); + if (request.Headers.TryGetValues("x-otopcua-data-features", out var values)) FeatureHeaders.AddRange(values); + } + IMessage message; + if (path.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + { + var caps = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 3, Serving, DataReadiness.Ready, DataOperationSets.V1, + new HashSet { DataValueKind.Int32 }, Limits, false, 0, "c", true, true, true, true, true)); + caps.Operations |= 32u | 64u | 128u | 256u | 512u; // a newer origin advertising reserved bits + message = caps; + } + else if (path.EndsWith("/GetMetadata", StringComparison.Ordinal)) + { + var wire = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, + new DataMetadata(View, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Read | DataOperations.Write, 1, null, null, false), null)]); + wire.Items[0].Value.AllowedOperations |= 32u; + wire.Serving = DataProtoMapper.EncodeServing(Serving); message = wire; + } + else if (path.EndsWith("/Read", StringComparison.Ordinal)) + { + var wire = DataProtoMapper.EncodeReadResponse([new ReadResult("r", DataItemStatus.Denied, DataReadiness.Unavailable, null, null, "no")]); + wire.Serving = DataProtoMapper.EncodeServing(Serving); message = wire; + } + else + { + var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken); + var write = W.WriteRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray()); + var result = new W.WriteResponse { Serving = DataProtoMapper.EncodeServing(Serving) }; + foreach (var item in write.Items) + result.Items.Add(DataProtoMapper.EncodeWriteResult(new(item.CorrelationId, new(DataWriteState.DriverConfirmedSuccess, 0, null)))); + message = result; + } + var payload = message.ToByteArray(); var framed = new byte[payload.Length + 5]; + BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); payload.CopyTo(framed, 5); + var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) }; + response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0"); + return response; + } + } + + private sealed class Security(HttpMessageHandler handler) : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new("v1", "ca1", "key", () => handler)); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataUnknownOperationToleranceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataUnknownOperationToleranceTests.cs new file mode 100644 index 000000000..9e8991078 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataUnknownOperationToleranceTests.cs @@ -0,0 +1,242 @@ +using System.Text; +using System.Text.Json.Nodes; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// X0 mixed-version tolerance (plan §4.3, test "R"). A newer central may author an operation bit this node does +/// not implement. Before X0 that rejected the WHOLE data-connection snapshot (every connection on the node went +/// down); after X0 the unknown bit is dropped from that row only (an unknown grant is no grant) and counted. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")] +public sealed class GrpcDataUnknownOperationToleranceTests +{ + private static DataConnection Definition(string id, DataOperations operations) => new() + { + DataConnectionId = id, ClusterId = "owner", Revision = 1, Enabled = true, + ConsumerNodeIds = ["node-a"], TargetMode = DataTargetMode.Node, + ExpectedClusterId = "target", ExpectedNodeId = "remote", Endpoints = ["https://remote.example:8443"], + SecretReference = "secret:data/" + id, SecretScopeClusterId = "owner", AllowedOperations = operations, + MaxMessageBytes = 65536, MaxBatchItems = 16, MaxPageItems = 16, MaxStreams = 2, + MaxMonitoredItems = 16, MaxPendingBytes = 65536, TimeoutMilliseconds = 5000 + }; + + [Fact] + public async Task Unknown_bit_on_one_row_is_dropped_from_that_row_only_and_counted() + { + var activator = new Activator(); + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); + var history = Definition("history", DataOperations.Read | DataOperations.Browse | DataOperations.HistoryRead | DataOperations.AlarmShelve); + var plain = Definition("plain", DataOperations.Read | DataOperations.Subscribe); + var future = Definition("future", (DataOperations)(1 << 30) | DataOperations.AlarmSubscribe); + + // The pre-X0 runtime threw ArgumentException("Unknown operation.") here for the whole snapshot. + Should.NotThrow(() => runtime.Apply(new(1, "artifact-1", [history, plain, future]))); + + await EventuallyAsync(() => runtime.CurrentScopeReady); + (await Lease(runtime, "history")).ShouldBe(DataOperations.Read | DataOperations.Browse); + (await Lease(runtime, "plain")).ShouldBe(DataOperations.Read | DataOperations.Subscribe); + // A row left with no understood operation stays configured and grants nothing (fail closed). + (await Lease(runtime, "future")).ShouldBe(DataOperations.None); + + runtime.DroppedUnknownOperations.ShouldBe(new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["history"] = DataOperations.HistoryRead | DataOperations.AlarmShelve, + ["future"] = (DataOperations)(1 << 30) | DataOperations.AlarmSubscribe, + }); + runtime.UnknownOperationRowsDropped.ShouldBe(2); + // The production reader: the node diagnostics snapshot carries each row's dropped bits. + var diagnostics = runtime.CaptureDiagnostics().ToDictionary(x => x.ConnectionId); + diagnostics["history"].DroppedUnknownOperations.ShouldBe(DataOperations.HistoryRead | DataOperations.AlarmShelve); + diagnostics["plain"].DroppedUnknownOperations.ShouldBe(DataOperations.None); + diagnostics["future"].DroppedUnknownOperations.ShouldBe((DataOperations)(1 << 30) | DataOperations.AlarmSubscribe); + diagnostics["plain"].MappingsWithDroppedOperations.ShouldBeNull("no mapping evidence was supplied"); + // The input rows are not mutated: the drop is the node's reading, not a rewrite of the artifact. + history.AllowedOperations.ShouldBe(DataOperations.Read | DataOperations.Browse | DataOperations.HistoryRead | DataOperations.AlarmShelve); + activator.Allowlists.Last().Keys.Order(StringComparer.OrdinalIgnoreCase).ShouldBe(["future", "history", "plain"]); + } + + [Fact] + public async Task Reapplying_the_same_revision_does_not_recount_and_a_clean_artifact_clears_the_diagnostic() + { + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), new Activator(), 4); + var snapshot = new DataConnectionDeploymentSnapshot(1, "artifact-1", [Definition("history", DataOperations.Read | DataOperations.HistoryRead)]); + runtime.Apply(snapshot); + runtime.Apply(snapshot); + runtime.UnknownOperationRowsDropped.ShouldBe(1); + runtime.DroppedUnknownOperations.ShouldContainKey("history"); + + runtime.Apply(new(2, "artifact-2", [Definition("history", DataOperations.Read)])); + runtime.DroppedUnknownOperations.ShouldBeEmpty(); + runtime.UnknownOperationRowsDropped.ShouldBe(1); + + // A -> B -> A is an accepted artifact CHANGE each time, so it recounts (documented semantics). + runtime.Apply(new(3, "artifact-1", [Definition("history", DataOperations.Read | DataOperations.HistoryRead)])); + runtime.UnknownOperationRowsDropped.ShouldBe(2); + } + + [Fact] + public void Node_side_artifact_parse_accepts_rows_carrying_bits_a_newer_central_authored() + { + var root = Fixture(); + root["DataConnections"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead); + root["DataExports"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead | DataOperations.AlarmSubscribe); + root["RemoteNamespaceMappings"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.HistoryRead); + using var parsed = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(root.ToJsonString())); + + // Pre-X0 each of these threw InvalidDataException through the node-side DataConnectionValidator pass. + // Rows come back as authored; each consumer keeps only the bits it understands. + parsed.ParseDataConnections("node-a").ShouldHaveSingleItem().AllowedOperations.ShouldBe( + DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead); + parsed.ParseDataExports("node-b").ShouldHaveSingleItem().DataExportId.ShouldBe("export-a"); + parsed.ParseRemoteNamespaceMappings("node-a").ShouldHaveSingleItem().RemoteNamespaceMappingId.ShouldBe("mapping-a"); + } + + [Fact] + public void Node_side_artifact_parse_still_rejects_what_it_rejected_before() + { + // Tolerance is only for unknown bits: a row with no operations at all, or a mapping granting an understood + // operation its connection lacks, is still invalid. + var none = Fixture(); + none["DataConnections"]![0]!["AllowedOperations"] = 0; + using (var parsed = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(none.ToJsonString()))) + Should.Throw(() => parsed.ParseDataConnections("node-a")); + var wider = Fixture(); + wider["RemoteNamespaceMappings"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Subscribe); + using (var parsed = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(wider.ToJsonString()))) + Should.Throw(() => parsed.ParseRemoteNamespaceMappings("node-a")); + } + + [Fact] + public void Origin_catalog_compiles_an_export_with_unknown_bits_and_grants_only_what_it_understands() + { + using var fixture = new LocalDataFixture(); + var snapshot = new DraftSnapshot + { + GenerationId = 1, ClusterId = "cluster", + ServerClusters = [new() { ClusterId = "cluster", Name = "Cluster", Enterprise = "Enterprise", Site = "Site", CreatedBy = "test", RedundancyMode = RedundancyMode.None }], + RawFolders = [new() { RawFolderId = "folder", ClusterId = "cluster", Name = "Plant" }], + DataExports = + [ + new() { DataExportId = "history", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "Cluster", + RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead }, + new() { DataExportId = "alarms-only", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = "Cluster", + RootEntityId = "cluster", PrincipalId = "other", AllowedOperations = DataOperations.AlarmSubscribe | DataOperations.AlarmAcknowledge }, + ], + }; + DataConnectionValidator.Validate(snapshot).ShouldContain(x => x.Code == "DataExportOperationsInvalid", "authoring still rejects reserved bits"); + + // Pre-X0 Compile threw InvalidDataException("Origin catalog configuration is invalid."): the whole origin went dark. + var catalog = LocalExportCatalog.Compile(snapshot, fixture.Serving, fixture.Activation.CaptureAuthority()); + catalog.ExportOperations("peer").ShouldBe(DataOperations.Browse | DataOperations.Read); + catalog.ExportOperations("other").ShouldBe(DataOperations.None); + } + + [Fact] + public void An_inert_all_unknown_export_does_not_lower_the_principals_limits_on_its_other_exports() + { + using var fixture = new LocalDataFixture(); + var snapshot = new DraftSnapshot + { + GenerationId = 1, ClusterId = "cluster", + ServerClusters = [new() { ClusterId = "cluster", Name = "Cluster", Enterprise = "Enterprise", Site = "Site", CreatedBy = "test", RedundancyMode = RedundancyMode.None }], + RawFolders = [new() { RawFolderId = "folder", ClusterId = "cluster", Name = "Plant" }], + DataExports = + [ + new() { DataExportId = "live", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "Cluster", + RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Read, + MaxBatchItems = 100, MaxPageItems = 100, MaxMonitoredItems = 100, MaxStreams = 10 }, + new() { DataExportId = "future-only", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = "Cluster", + RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.HistoryRead | (DataOperations)(1 << 30), + MaxBatchItems = 1, MaxPageItems = 1, MaxMonitoredItems = 1, MaxStreams = 1 }, + ], + }; + var catalog = LocalExportCatalog.Compile(snapshot, fixture.Serving, fixture.Activation.CaptureAuthority()); + var limits = new DataLimits(1000, 1000, 1_000_000, 1000, 100, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1)); + var effective = catalog.LimitsFor("peer", limits); + effective.MaxBatchItems.ShouldBe(100); + effective.MaxPageItems.ShouldBe(100); + effective.MaxMonitoredItems.ShouldBe(100); + effective.MaxStreams.ShouldBe(10); + catalog.ExportOperations("peer").ShouldBe(DataOperations.Browse | DataOperations.Read); + } + + private static async Task Lease(DataConnectionDeploymentRuntime runtime, string id) + { + DataConnectionDeploymentLease? lease = null; + await EventuallyAsync(() => runtime.TryAcquire(id, out lease)); + using (lease) return lease!.AllowedOperations; + } + + private static async Task EventuallyAsync(Func condition) + { + for (var i = 0; i < 250; i++) + { + if (condition()) return; + await Task.Delay(20, TestContext.Current.CancellationToken); + } + throw new TimeoutException("Expected deployment state did not arrive."); + } + + private sealed class Activator : IDataConnectionScopeActivator + { + public List> Allowlists { get; } = []; + public Task SetScopeAsync(long version, IReadOnlyDictionary allowlist, CancellationToken cancellationToken) + { + lock (Allowlists) Allowlists.Add(new Dictionary(allowlist, StringComparer.OrdinalIgnoreCase)); + return Task.CompletedTask; + } + } + + private sealed class Security : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new("1", "trust", "key", () => new NoNetwork())); + } + + private sealed class NoNetwork : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + throw new InvalidOperationException("This tolerance test must not use the network."); + } + + private static JsonObject Fixture() => JsonNode.Parse( + """ + { + "Clusters": [{"ClusterId":"local","Name":"Local","Enterprise":"ent","Site":"site","RedundancyMode":0,"CreatedBy":"test","Enabled":true}], + "Nodes": [ + {"NodeId":"node-a","ClusterId":"local","Host":"node-a","ApplicationUri":"urn:node-a","CreatedBy":"test","Enabled":true,"MaintenanceMode":false}, + {"NodeId":"node-b","ClusterId":"local","Host":"node-b","ApplicationUri":"urn:node-b","CreatedBy":"test","Enabled":true,"MaintenanceMode":false} + ], + "RawFolders": [{"RawFolderId":"local-root","ClusterId":"local","Name":"Local"}], + "DataConnections": [{ + "DataConnectionId":"connection-a","ClusterId":"local","Revision":3,"Enabled":true, + "ConsumerNodeIds":["node-a"],"TargetMode":1,"Consistency":1, + "ExpectedClusterId":"local","ExpectedNodeId":"node-b","EligibleTargetNodeIds":[], + "Endpoints":["https://node-b:7443"],"SecretReference":"secret:data/upstream", + "SecretScopeClusterId":"local","AllowedOperations":5 + }], + "DataExports": [{ + "DataExportId":"export-a","ClusterId":"local","Revision":4,"Enabled":true, + "Realm":1,"RootKind":"RawFolder","RootEntityId":"local-root", + "PrincipalId":"peer","AllowedOperations":5 + }], + "RemoteNamespaceMappings": [{ + "RemoteNamespaceMappingId":"mapping-a","ClusterId":"local","DataConnectionId":"connection-a", + "Revision":5,"Enabled":true,"ConsumerNodeIds":["node-a"],"Realm":1,"RemoteRealm":1, + "LocalParentKind":"RawFolder","LocalParentId":"local-root","BranchName":"Remote", + "RemoteRootEntityId":"origin-root","RemoteNamespaceUri":"https://zb.com/otopcua/raw","RemoteIdentifierKind":"string", + "RemoteIdentifier":"origin-root","AllowedOperations":1,"WriteThrough":false + }] + } + """)!.AsObject(); +}