diff --git a/scripts/validation/grpc-data/compose.conditions.yml b/scripts/validation/grpc-data/compose.conditions.yml new file mode 100644 index 000000000..842c432ac --- /dev/null +++ b/scripts/validation/grpc-data/compose.conditions.yml @@ -0,0 +1,9 @@ +# A2a condition-streaming smoke overlay (opt-in: `rig.py up --conditions`). Selects the seeder's conditions profile: +# SOURCE exports gain AlarmSubscribe and the SOURCE equipment gets one scripted alarm (`ScalarHigh`, scalar > 100). +# The dev DataConnections__ConditionKeySecret is already set on both source services in compose.yml. +# Without this file the rig is the unchanged v1 fixture. + +services: + seeder: + environment: + GRPC_DATA_CONDITIONS: "1" diff --git a/scripts/validation/grpc-data/conditions_smoke.py b/scripts/validation/grpc-data/conditions_smoke.py new file mode 100644 index 000000000..f04143826 --- /dev/null +++ b/scripts/validation/grpc-data/conditions_smoke.py @@ -0,0 +1,34 @@ +"""A2a condition-streaming live smoke on a `rig.py up --conditions` run (plan §9 A2; the full gate is A4). + +Raises the SOURCE scripted alarm `ScalarHigh` (scalar register 20 := 150) through the device control API, then runs the +probe's `--scenario conditions` on both SOURCE data listeners: the Primary must stream a snapshot (total, records with +the active alarm, snapshot_complete) and, after the probe clears the alarm (scalar := 0), a delta record; the Secondary +must refuse the condition item (Primary-only). Evidence lands in the run's restricted `evidence/` folder. +""" +import argparse +import json +import sys +import time + +import scenarios + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-id", required=True) + parser.add_argument("--settle-seconds", type=int, default=8) + arguments = parser.parse_args(argv) + runner = scenarios.ScenarioRunner(arguments.run_id) + runner.device("set", address=20, value=150) + time.sleep(arguments.settle_seconds) + output = runner.folder / "A2a-conditions-wire.json" + result = runner.process(["dotnet", str(runner.probe_dll), "--manifest", str(runner.manifest_path), "--scenario", "conditions", + "--output", str(output)], "A2a-conditions-wire", timeout=240) + wire = scenarios.restricted_json(output) if output.exists() else {"passed": False, "stderr": result.stderr[-4000:]} + runner.device("set", address=20, value=0) + print(json.dumps(wire, indent=2)[:20000]) + return 0 if wire.get("passed") else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/validation/grpc-data/probe/Program.cs b/scripts/validation/grpc-data/probe/Program.cs index 70d3cfec4..1907e7083 100644 --- a/scripts/validation/grpc-data/probe/Program.cs +++ b/scripts/validation/grpc-data/probe/Program.cs @@ -26,7 +26,7 @@ try using var manifest = JsonDocument.Parse(await File.ReadAllTextAsync(manifestPath)); var root = manifest.RootElement; var scenario = arguments.GetValueOrDefault("--scenario", "all"); - if (scenario is not ("all" or "D13" or "wire" or "history")) throw new ArgumentException("Unsupported wire scenario."); + if (scenario is not ("all" or "D13" or "wire" or "history" or "conditions")) throw new ArgumentException("Unsupported wire scenario."); var nodes = root.GetProperty("nodes"); var endpoints = root.GetProperty("endpoints"); var keyPath = root.GetProperty("credentials").GetProperty("data_key_files").GetProperty("source").GetString()!; @@ -251,7 +251,101 @@ try } } } - if (scenario is not ("D13" or "history")) + if (scenario == "conditions") + { + // A2a smoke (opt-in conditions fixture): a root-scoped condition item on each SOURCE listener's UNS equipment root. + failurePhase = ProbeFailurePhase.WireOperation; + var unsUri = root.GetProperty("fixture").GetProperty("namespace_uris").GetProperty("uns").GetString()!; + var equipmentPath = arguments.GetValueOrDefault("--equipment", "area/line/plc"); + var deviceUrl = endpoints.GetProperty("device.control").GetProperty("url").GetString()!; + using var http = new HttpClient(); + async Task SetScalar(int value) + { + using var response = await http.PostAsync(deviceUrl + "/control", new StringContent( + JsonSerializer.Serialize(new { action = "set", address = 20, value }), System.Text.Encoding.UTF8, "application/json")); + response.EnsureSuccessStatusCode(); + } + var equipmentView = new W.View { Address = new() { OriginClusterId = "SOURCE", NamespaceUri = unsUri, IdentifierKind = "string", + Identifier = equipmentPath }, Realm = (int)DataRealm.Uns, Subject = equipmentPath }; + static object Record(W.ConditionState r) => new + { + key = r.ConditionKey, r.Version, r.Removed, r.StateKnown, r.Active, r.Acknowledged, r.Severity, r.Message, + info = r.Info is null ? null : new { r.Info.ConditionType, r.Info.ConditionName, r.Info.SourceKind, + placements = r.Info.Placements.Select(p => p.Address.NamespaceUri + "|" + p.Address.Identifier).ToArray() }, + }; + foreach (var node in sourceNodes) + { + var name = node.Name; + failureTarget = name; + var nodeId = node.Value.GetProperty("node_id").GetString()!; + Metadata With(bool feature) + { + var headers = Headers(key, "Node", nodeId); + if (feature) headers.Add("x-otopcua-data-features", "conditions"); + return headers; + } + using var handler = security.Handler(name); + using var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler }); + var client = new W.DataConnectionService.DataConnectionServiceClient(channel); + var plain = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(false), DateTime.UtcNow.AddSeconds(20)); + var featured = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(true), DateTime.UtcNow.AddSeconds(20)); + var capsOk = plain.Conditions is null && (plain.Operations & 64) == 0 && featured.Conditions is not null && (featured.Operations & 64) == 64; + var primary = featured.Serving.Role == "Primary"; + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(90)); + using var call = client.Subscribe(With(true), cancellationToken: cts.Token); + var open = new W.SubscriptionCommand { SubscriptionId = "conditions-" + name, StreamEpoch = 1, CommandId = "open-1", + AcknowledgementTimeoutTicks = TimeSpan.FromSeconds(10).Ticks, Open = new() { SessionLifetimeTicks = TimeSpan.FromMinutes(5).Ticks, + SnapshotBudget = new() { TimeoutTicks = TimeSpan.FromSeconds(20).Ticks, MaxItems = 8, MaxBytes = 4 * 1024 * 1024 } } }; + open.Open.Items.Add(new W.SubscriptionItem { ClientItemId = "conditions", View = equipmentView, + Settings = new() { Trigger = 2 }, ConditionScope = new() { IncludeInfo = true } }); + await call.RequestStream.WriteAsync(open); + int? ackStatus = null, total = null; + var snapshot = new List(); + var deltas = new List(); + var complete = false; + var frames = new List(); + var flipped = false; + while (await call.ResponseStream.MoveNext(cts.Token)) + { + var frame = call.ResponseStream.Current; + frames.Add(frame.FrameCase.ToString()); + if (frame.Ack is { } ack) { ackStatus = ack.Items.Single().Status; if (ackStatus != 1) break; continue; } + if (frame.ConditionStates is not { } states) continue; + if (states.IsSnapshot) + { + if (states.HasTotal) { total = states.Total; snapshot.Clear(); } + snapshot.AddRange(states.Items); + complete = states.SnapshotComplete; + if (complete && !flipped) + { + // The alarm was raised (scalar 150) before the stream opened; clear it now and wait for the delta. + flipped = true; + await SetScalar(0); + } + continue; + } + deltas.AddRange(states.Items); + if (deltas.Any(r => !r.Active && r.StateKnown)) break; + } + await cts.CancelAsync(); + var leaked = snapshot.Concat(deltas).Any(r => Record(r).ToString()!.Contains("modbus/plc", StringComparison.Ordinal)); + var passed = capsOk && (primary + ? ackStatus == 1 && total >= 1 && complete && snapshot.Count == total && snapshot.Any(r => r.Active && r.StateKnown) + && deltas.Any(r => !r.Active && r.StateKnown) && !leaked + : ackStatus == 6); + results.Add(new("conditions-" + name, "conditions", passed, primary ? 7 : 2, new() + { + ["role"] = featured.Serving.Role, + ["capabilities"] = new { withoutHeader = new { operations = plain.Operations, conditions = plain.Conditions?.ToString() }, + withHeader = new { operations = featured.Operations, conditions = featured.Conditions?.ToString() } }, + ["ackStatus"] = ackStatus, ["total"] = total, ["snapshotComplete"] = complete, + ["snapshot"] = snapshot.Select(Record).ToArray(), ["deltas"] = deltas.Select(Record).ToArray(), + ["frames"] = frames, ["rawPathLeaked"] = leaked, + })); + if (primary && flipped) await SetScalar(150); // restore for the other node + } + } + if (scenario is not ("D13" or "history" or "conditions")) { var fixture = root.GetProperty("fixture"); var rawUri = fixture.GetProperty("namespace_uris").GetProperty("raw").GetString()!; diff --git a/scripts/validation/grpc-data/rig.py b/scripts/validation/grpc-data/rig.py index 5b75330ea..ffbbdd02f 100644 --- a/scripts/validation/grpc-data/rig.py +++ b/scripts/validation/grpc-data/rig.py @@ -675,6 +675,8 @@ class LocalRig: files.extend(["--file", str(HERE / "compose.history.yml")]) if self.environment.get("GRPC_DATA_HISTORY_BACKEND") == "questdb": files.extend(["--file", str(HERE / "compose.history.questdb.yml")]) + if self.environment.get("GRPC_DATA_CONDITIONS") == "1": + files.extend(["--file", str(HERE / "compose.conditions.yml")]) return files def compose(self, *args, timeout=120): @@ -845,7 +847,7 @@ class LocalRig: self.save(manifest) return manifest - def up(self, timeout=600, history=False, history_backend="sqlserver"): + def up(self, timeout=600, history=False, history_backend="sqlserver", conditions=False): import secrets import credentials if self.folder.exists(): @@ -870,6 +872,8 @@ class LocalRig: raise RigError("unknown history backend") settings["GRPC_DATA_HISTORY"] = "1" settings["GRPC_DATA_HISTORY_BACKEND"] = history_backend + if conditions: + settings["GRPC_DATA_CONDITIONS"] = "1" atomic_write_secret(self.folder / "environment.json", json.dumps(settings)) self.environment.update(settings) credentials.provision_tls(self.folder / "security", NODES[2:]) @@ -1337,6 +1341,7 @@ def main(argv=None): parser.add_argument("action", choices=("preflight", "up", "seed", "deploy", "status", "down")) parser.add_argument("--run-id") parser.add_argument("--timeout", type=float, default=None) + parser.add_argument("--conditions", action="store_true", help="up only: add the A2a conditions overlay (AlarmSubscribe exports + one scripted alarm)") parser.add_argument("--history", action="store_true", help="up only: add the H2 history overlay (SOURCE historian + history seed profile)") parser.add_argument("--history-backend", choices=HISTORY_BACKENDS, default=None, help="up --history only: the SOURCE historian backend (sqlserver = the run's SQL container, default; questdb = a run-owned QuestDB)") @@ -1366,6 +1371,10 @@ def main(argv=None): options["history_backend"] = arguments.history_backend elif arguments.history_backend is not None: raise RigError("--history-backend needs up --history") + if arguments.conditions: + if arguments.action != "up": + raise RigError("--conditions applies to up only; the run remembers it") + options["conditions"] = True result = action(**options) print(json.dumps({"run_id": result["run_id"], "state": result.get("state"), "manifest": str(rig.path), "healthy": result.get("healthy")})) return 0 diff --git a/scripts/validation/grpc-data/seed/Program.cs b/scripts/validation/grpc-data/seed/Program.cs index e72964e7d..dd39093d1 100644 --- a/scripts/validation/grpc-data/seed/Program.cs +++ b/scripts/validation/grpc-data/seed/Program.cs @@ -29,6 +29,9 @@ const DataOperations operations = DataOperations.Browse | DataOperations.Metadat // exports gain HistoryRead, and a second principal's export lacks it. Unset ⇒ the v1 fixture, unchanged. var history = Environment.GetEnvironmentVariable("GRPC_DATA_HISTORY") == "1"; var grantedOperations = history ? operations | DataOperations.HistoryRead : operations; +// A2a smoke profile (opt-in, `rig.py up --conditions`): SOURCE exports gain AlarmSubscribe and the SOURCE equipment gets +// one scripted alarm, ScalarHigh (scalar > 100), so a condition stream sees a snapshot and a delta. Unset ⇒ v1 fixture. +var conditions = Environment.GetEnvironmentVariable("GRPC_DATA_CONDITIONS") == "1"; try { if (args.Length == 0) return 2; @@ -372,6 +375,14 @@ try db.Equipment.Add(new() { EquipmentRowId = Guid.NewGuid(), EquipmentId = equipment, EquipmentUuid = uuid, UnsLineId = "source-line", Name = "plc", MachineCode = "fixture-plc" }); foreach (var name in new[] { "counter", "scalar", "array0", "array1", "array2", "vector", "text" }.Concat(history ? ["flt"] : [])) db.UnsTagReferences.Add(new() { UnsTagReferenceRowId = Guid.NewGuid(), UnsTagReferenceId = "ref-" + name, EquipmentId = equipment, TagId = "source-" + name }); + if (conditions) + { + const string predicate = "return Convert.ToInt32(ctx.GetTag(\"modbus/plc/scalar\").Value) > 100;"; + db.Scripts.Add(new() { ScriptRowId = Guid.NewGuid(), ScriptId = "source-scalar-high", Name = "scalar-high", SourceCode = predicate, + SourceHash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(predicate))) }); + db.ScriptedAlarms.Add(new() { ScriptedAlarmRowId = Guid.NewGuid(), ScriptedAlarmId = "source-scalar-high", EquipmentId = equipment, + Name = "ScalarHigh", AlarmType = "AlarmCondition", MessageTemplate = "scalar high", PredicateScriptId = "source-scalar-high" }); + } db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "source-peer", ClusterId = "SOURCE", Principal = "fixture-consumer", ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin }); db.DataConnections.Add(new() { DataConnectionRowId = Guid.NewGuid(), DataConnectionId = "consumer-source", ClusterId = "CONSUMER", Enabled = true, @@ -385,7 +396,8 @@ try var rootKind = realm == DataRealm.Raw ? "RawDevice" : "Equipment"; var entity = realm == DataRealm.Raw ? "source-device" : equipment; db.DataExports.Add(new() { DataExportRowId = Guid.NewGuid(), DataExportId = "export-" + name, ClusterId = "SOURCE", Enabled = true, - Realm = realm, RootKind = rootKind, RootEntityId = entity, PrincipalId = "fixture-consumer", AllowedOperations = grantedOperations }); + Realm = realm, RootKind = rootKind, RootEntityId = entity, PrincipalId = "fixture-consumer", + AllowedOperations = grantedOperations | (conditions ? DataOperations.AlarmSubscribe : DataOperations.None) }); if (history) db.DataExports.Add(new() { DataExportRowId = Guid.NewGuid(), DataExportId = "export-" + name + "-nohistory", ClusterId = "SOURCE", Enabled = true, Realm = realm, RootKind = rootKind, RootEntityId = entity, PrincipalId = "fixture-nohistory", AllowedOperations = operations }); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs index 95be22d99..611cf33fd 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs @@ -34,7 +34,8 @@ public sealed class GrpcDataHistoryClientTests var results = await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken); results.Single().StatusCode.ShouldBe(0x80720000u); a.HistoryCalls.ShouldBe(0); - a.Headers.ShouldAllBe(x => x.Path.EndsWith("/GetCapabilities", StringComparison.Ordinal) && x.Features == "history"); + // A2a: the probe asks for every feature this consumer understands (history, conditions). + a.Headers.ShouldAllBe(x => x.Path.EndsWith("/GetCapabilities", StringComparison.Ordinal) && x.Features == "history,conditions"); } [Fact] 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 index 7a90c8646..9514a45af 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataUnknownOperationToleranceTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataUnknownOperationToleranceTests.cs @@ -36,7 +36,7 @@ public sealed class GrpcDataUnknownOperationToleranceTests await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); var history = Definition("history", DataOperations.Read | DataOperations.Browse | DataOperations.AlarmConfirm | DataOperations.AlarmShelve); var plain = Definition("plain", DataOperations.Read | DataOperations.Subscribe); - var future = Definition("future", (DataOperations)(1 << 30) | DataOperations.AlarmSubscribe); + var future = Definition("future", (DataOperations)(1 << 30) | DataOperations.AlarmAcknowledge); // A2a: 64 is understood // The pre-X0 runtime threw ArgumentException("Unknown operation.") here for the whole snapshot. Should.NotThrow(() => runtime.Apply(new(1, "artifact-1", [history, plain, future]))); @@ -50,14 +50,14 @@ public sealed class GrpcDataUnknownOperationToleranceTests runtime.DroppedUnknownOperations.ShouldBe(new Dictionary(StringComparer.OrdinalIgnoreCase) { ["history"] = DataOperations.AlarmConfirm | DataOperations.AlarmShelve, - ["future"] = (DataOperations)(1 << 30) | DataOperations.AlarmSubscribe, + ["future"] = (DataOperations)(1 << 30) | DataOperations.AlarmAcknowledge, }); 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.AlarmConfirm | DataOperations.AlarmShelve); diagnostics["plain"].DroppedUnknownOperations.ShouldBe(DataOperations.None); - diagnostics["future"].DroppedUnknownOperations.ShouldBe((DataOperations)(1 << 30) | DataOperations.AlarmSubscribe); + diagnostics["future"].DroppedUnknownOperations.ShouldBe((DataOperations)(1 << 30) | DataOperations.AlarmAcknowledge); 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.AlarmConfirm | DataOperations.AlarmShelve); @@ -129,7 +129,7 @@ public sealed class GrpcDataUnknownOperationToleranceTests new() { DataExportId = "history", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "Cluster", RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Read | DataOperations.AlarmConfirm }, new() { DataExportId = "alarms-only", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = "Cluster", - RootEntityId = "cluster", PrincipalId = "other", AllowedOperations = DataOperations.AlarmSubscribe | DataOperations.AlarmAcknowledge }, + RootEntityId = "cluster", PrincipalId = "other", AllowedOperations = DataOperations.AlarmConfirm | DataOperations.AlarmAcknowledge }, // A2a: 64 is understood ], }; DataConnectionValidator.Validate(snapshot).ShouldContain(x => x.Code == "DataExportOperationsInvalid", "authoring still rejects reserved bits");