From eb29360d47ab9bf23fdcab348709250a50f626db Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Mon, 23 Nov 2026 23:13:31 -0500 Subject: [PATCH] test(grpc-data): opt-in H2 history profile for the standalone rig (SqlServer historian overlay, history seed grants, probe HistoryRead, smoke runner) --- .../validation/grpc-data/compose.history.yml | 21 ++++ scripts/validation/grpc-data/history_smoke.py | 110 +++++++++++++++++ .../validation/grpc-data/probe/ProbeEngine.cs | 60 ++++++++- scripts/validation/grpc-data/probe/Program.cs | 116 +++++++++++++++++- scripts/validation/grpc-data/rig.py | 25 +++- scripts/validation/grpc-data/seed/Program.cs | 23 +++- 6 files changed, 344 insertions(+), 11 deletions(-) create mode 100644 scripts/validation/grpc-data/compose.history.yml create mode 100644 scripts/validation/grpc-data/history_smoke.py diff --git a/scripts/validation/grpc-data/compose.history.yml b/scripts/validation/grpc-data/compose.history.yml new file mode 100644 index 000000000..f5a025c39 --- /dev/null +++ b/scripts/validation/grpc-data/compose.history.yml @@ -0,0 +1,21 @@ +# H2 remote-history smoke overlay (opt-in: `rig.py up --history`). Adds a SqlServer historian backend +# and continuous historization to the SOURCE pair, and selects the seeder's history profile. The +# historian schema (`hist`, auto-created) lives in the run's own SQL container, beside the config DB. +# Without this file the rig is the unchanged v1 fixture. + +x-source-history-env: &source-history-env + ServerHistorian__Enabled: "true" + ServerHistorian__Backend: SqlServer + ServerHistorian__SqlServer__ConnectionString: "Server=sql,1433;Database=OtOpcUa;User Id=sa;Password=${GRPC_DATA_SQL_PASSWORD:?generated SQL password required};TrustServerCertificate=True;Encrypt=False" + ContinuousHistorization__Enabled: "true" + ContinuousHistorization__OutboxPath: /app/data/historization-outbox + ContinuousHistorization__DrainIntervalSeconds: "1" + +services: + seeder: + environment: + GRPC_DATA_HISTORY: "1" + source-1: + environment: *source-history-env + source-2: + environment: *source-history-env diff --git a/scripts/validation/grpc-data/history_smoke.py b/scripts/validation/grpc-data/history_smoke.py new file mode 100644 index 000000000..33a42e0a6 --- /dev/null +++ b/scripts/validation/grpc-data/history_smoke.py @@ -0,0 +1,110 @@ +"""H2 remote-history live smoke on a `rig.py up --history` run (plan ยง9 H2 exit gate). + +Drives the deployed rig only through its owned surfaces: the device control API (advances the +historized `counter`), the probe's raw origin RPCs (`--scenario history`), the CONSUMER node probe's +deployed-connection lease (`history` operation = a runtime consumer's IDataHistoryService read) and the +Client CLI's OPC UA `historyread` on the SOURCE node. Evidence lands in the run's restricted +`evidence/` folder; keys are redacted by ScenarioRunner.save. +""" +import argparse +import json +import re +import sys +import time +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import scenarios +import rig + + +def _iso(moment): + return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _cli_rows(stdout): + """`historyread` rows โ†’ [(source time ISO, value text, status text)].""" + rows = [] + for line in stdout.splitlines(): + match = re.match(r"^\s*(\d{4}-\d{2}-\d{2}[T ][0-9:.]+Z?)\s*\|?\s*(.*)$", line) + if match: + rows.append((match[1], match[2].strip())) + return rows + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-id", required=True) + parser.add_argument("--accumulate-seconds", type=int, default=40) + arguments = parser.parse_args(argv) + runner = scenarios.ScenarioRunner(arguments.run_id) + if runner.manifest["fixture"].get("history") is None: + raise SystemExit("run was not brought up with --history") + runner.active, runner.deadline = "H2", time.monotonic() + 900 + runner.publish() + report = {"run_id": arguments.run_id, "source_revision": runner.manifest.get("source_revision"), + "source_tree_hash": runner.manifest.get("source_tree_hash"), "items": {}} + + # 1. Accumulate history: one counter step per second. + started = datetime.now(timezone.utc) + for _ in range(arguments.accumulate_seconds): + runner.device("advance", steps=1) + time.sleep(1) + finished = datetime.now(timezone.utc) + time.sleep(4) # let the outbox drain (DrainIntervalSeconds=1) + window_start = (started + timedelta(seconds=5)).replace(microsecond=0) + window_end = (finished - timedelta(seconds=5)).replace(microsecond=0) + report["accumulation"] = {"started": started.isoformat(), "finished": finished.isoformat(), + "window": [_iso(window_start), _iso(window_end)], "device": runner.device()} + + # 2. Origin RPCs on both SOURCE data listeners. + output = runner.folder / "H2-history-wire.json" + result = runner.process(["dotnet", str(runner.probe_dll), "--manifest", str(runner.manifest_path), "--scenario", "history", + "--history-start", _iso(window_start), "--history-end", _iso(window_end), "--output", str(output)], + "H2-history-wire", timeout=120) + wire = scenarios.restricted_json(output) if output.exists() else {"passed": False, "stderr": result.stderr[-4000:]} + report["items"]["wire"] = wire + + # 3. OPC UA historyread on each SOURCE node for the same window. + cli = {} + for node in ("source-1", "source-2"): + resolved = runner.manifest["resolved_nodes"][node]["aliases"]["raw"] + node_id = resolved.rsplit("/", 1)[0] + "/counter" + argv = ["dotnet", str(runner.cli_dll), "historyread", "-u", runner.endpoint(node), "-U", "apikey", "-P", runner.key, + "-n", node_id, "--start", _iso(window_start), "--end", _iso(window_end), "--max", "1000"] + run = runner.process(argv, "H2-cli-historyread-" + node, timeout=60) + cli[node] = {"node_id": node_id, "returncode": run.returncode, "stdout": run.stdout[-8000:], "stderr": run.stderr[-2000:]} + # The non-historized tag over OPC UA, for contrast with the remote refusal. + argv[argv.index("-n") + 1] = resolved + run = runner.process(argv, "H2-cli-historyread-unhistorized-" + node, timeout=60) + cli[node]["unhistorized"] = {"node_id": resolved, "returncode": run.returncode, "stdout": run.stdout[-2000:], "stderr": run.stderr[-2000:]} + report["items"]["cli"] = cli + + # 4. Runtime consumer: the deployed connection lease on each CONSUMER node. + consumer = {} + paths = runner.manifest["fixture"]["history"] + for node in ("consumer-1", "consumer-2"): + observed = {} + for name, fields in ( + ("newest5", {"path": paths["historized"]["raw"], "historyNumValues": 5}), + ("window", {"path": paths["historized"]["raw"], "historyNumValues": 0, + "historyStartUtc": window_start.isoformat(), "historyEndUtc": window_end.isoformat()}), + ("unhistorized", {"path": paths["unhistorized"]["raw"], "historyNumValues": 5, "expected_state": "Unsupported"}), + ("uns-newest5", {"realm": "uns", "path": paths["historized"]["uns"], "historyNumValues": 5})): + realm = fields.pop("realm", "raw") + expected = fields.pop("expected_state", None) + try: + observed[name] = {"passed": True, "observations": runner.probe(node, "history", realm, expected_state=expected, timeout=60, **fields)} + except Exception as error: # record and continue: the smoke reports per item + observed[name] = {"passed": False, "error": type(error).__name__ + ": " + str(error)} + consumer[node] = observed + report["items"]["consumer"] = consumer + runner.save("H2-history-smoke.json", report) + print(json.dumps({"saved": str(runner.folder / "H2-history-smoke.json"), "wire_passed": wire.get("passed"), + "consumer": {node: {k: v["passed"] for k, v in rows.items()} for node, rows in consumer.items()}, + "cli": {node: row["returncode"] for node, row in cli.items()}}, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/validation/grpc-data/probe/ProbeEngine.cs b/scripts/validation/grpc-data/probe/ProbeEngine.cs index a2a1e34a8..f3cbfaf32 100644 --- a/scripts/validation/grpc-data/probe/ProbeEngine.cs +++ b/scripts/validation/grpc-data/probe/ProbeEngine.cs @@ -10,7 +10,8 @@ public sealed record ProbeCommand(string Id, string ConnectionId, string Operati string? ExpectedRole = null, string? ExpectedState = null, string? Continuation = null, long? ExpectedCatalogRevision = null, string? ExpectedIncarnation = null, long? ExpectedGeneration = null, WorkloadOptions? Workload = null, string? WorkloadUnsNamespaceUri = null, - IReadOnlyDictionary? WorkloadBrowseRoots = null, int? MaximumAgeMilliseconds = 5000); + IReadOnlyDictionary? WorkloadBrowseRoots = null, int? MaximumAgeMilliseconds = 5000, + DateTimeOffset? HistoryStartUtc = null, DateTimeOffset? HistoryEndUtc = null, uint HistoryNumValues = 5); public sealed record ProbeResult(string Id, string Operation, bool Passed, int Assertions, Dictionary Observations, string? Failure = null); @@ -234,6 +235,63 @@ public static class ProbeEngine observations["distinctValues"] = values.Count; observations["lastSequence"] = lastSequence; } + else if (command.Operation == "history") + { + // H2 smoke: a Raw HistoryRead through whatever IDataConnection the caller holds (the deployed lease on a + // consumer node, or a probe-built GrpcDataConnection). ExpectedState: Good (default) | Unsupported. + phase = ProbeFailurePhase.Read; + Check(connection is IDataHistoryService, "connection serves history"); + var history = (IDataHistoryService)connection; + observations["historyCapabilities"] = caps.History; + observations["historyReadAdvertised"] = caps.Operations.HasFlag(DataOperations.HistoryRead); + var details = new DataHistoryRawDetails(command.HistoryStartUtc, command.HistoryEndUtc ?? DateTimeOffset.UtcNow, + command.HistoryNumValues, false); + var historyBudget = budget with { MaxBytes = 4 * 1024 * 1024 }; + static object Page(DataHistoryReadResult result) => new + { + statusCode = "0x" + result.StatusCode.ToString("X8"), result.Diagnostic, hasContinuation = result.Continuation is not null, + samples = result.Samples.Select(sample => new + { + value = ZB.MOM.WW.OtOpcUa.Commons.DataConnections.TypedValueCodec.Encode(sample.Value).ToString(), + statusCode = "0x" + sample.StatusCode.ToString("X8"), sourceTimestampUtc = sample.SourceTimestampUtc?.ToString("O"), + serverTimestampUtc = sample.ServerTimestampUtc?.ToString("O"), + }).ToArray(), + }; + var pages = new List(); + observations["pages"] = pages; + var first = await history.ReadAsync(new(details, [new("one", view)], historyBudget), ct); + try + { + Check(first.Count == 1 && first[0].CorrelationId == "one", "history cardinality"); + pages.Add(Page(first[0])); + if (command.ExpectedState == "Unsupported") + { + Check(first[0].StatusCode == 0x80720000u && first[0].Samples.Count == 0 && first[0].Continuation is null, "history unsupported"); + } + else + { + Check(first[0].StatusCode >> 30 == 0, "history status Good"); + Check(first[0].Samples.Count > 0 && (command.HistoryNumValues == 0 || first[0].Samples.Count <= command.HistoryNumValues), "history page bound"); + if (command.HistoryStartUtc is null) + Check(first[0].Samples.Zip(first[0].Samples.Skip(1)).All(pair => pair.First.SourceTimestampUtc > pair.Second.SourceTimestampUtc), "end-only read newest first"); + if (first[0].Continuation is { } token) + { + var second = await history.ReadAsync(new(details, [new("one", view, null, token)], historyBudget), ct); + try + { + Check(second.Count == 1, "resumed cardinality"); + pages.Add(Page(second[0])); + Check(second[0].StatusCode >> 30 == 0 && second[0].Samples.Count > 0, "resumed page Good"); + if (command.HistoryStartUtc is null) + Check(second[0].Samples[0].SourceTimestampUtc < first[0].Samples[^1].SourceTimestampUtc, "resumed page continues older"); + if (second[0].Continuation is { } rest) await history.ReleaseAsync([rest], ct); + } + finally { foreach (var item in second) item.Dispose(); } + } + } + } + finally { foreach (var item in first) item.Dispose(); } + } else throw new InvalidOperationException("unsupported operation"); return new(command.Id, command.Operation, true, assertions, observations); } diff --git a/scripts/validation/grpc-data/probe/Program.cs b/scripts/validation/grpc-data/probe/Program.cs index 31399efeb..7b11a2428 100644 --- a/scripts/validation/grpc-data/probe/Program.cs +++ b/scripts/validation/grpc-data/probe/Program.cs @@ -5,6 +5,7 @@ using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text.Json; +using Google.Protobuf; using Grpc.Core; using Grpc.Net.Client; using GrpcDataProbe; @@ -25,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")) throw new ArgumentException("Unsupported wire scenario."); + if (scenario is not ("all" or "D13" or "wire" or "history")) 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()!; @@ -122,7 +123,118 @@ try } } } - if (scenario != "D13") + if (scenario == "history") + { + // H2 smoke (opt-in history fixture): raw origin RPCs on each SOURCE data listener. + failurePhase = ProbeFailurePhase.WireOperation; + var fixture = root.GetProperty("fixture"); + var rawUri = fixture.GetProperty("namespace_uris").GetProperty("raw").GetString()!; + var paths = fixture.GetProperty("history"); + var historized = paths.GetProperty("historized").GetProperty("raw").GetString()!; + var unhistorized = paths.GetProperty("unhistorized").GetProperty("raw").GetString()!; + var otherKeyPath = root.GetProperty("credentials").GetProperty("data_key_files").GetProperty("source_nohistory").GetString()!; + Restricted(otherKeyPath); + var otherKey = (await File.ReadAllTextAsync(otherKeyPath)).Trim(); + W.View View(string path) => new() { Address = new() { OriginClusterId = "SOURCE", NamespaceUri = rawUri, IdentifierKind = "string", Identifier = path }, + Realm = (int)DataRealm.Raw, Subject = path }; + W.Budget HistoryBudget() => new() { TimeoutTicks = TimeSpan.FromSeconds(20).Ticks, MaxItems = 8, MaxBytes = 4 * 1024 * 1024 }; + static string Hex(uint status) => "0x" + status.ToString("X8"); + static object Samples(W.HistoryReadResult item) => item.Samples.Select(sample => new + { + value = sample.Value?.ToString(), statusCode = Hex(sample.StatusCode), + sourceTimestampUtc = sample.SourceTimestamp?.Value?.ToDateTimeOffset().ToString("O"), + serverTimestampUtc = sample.ServerTimestamp?.Value?.ToDateTimeOffset().ToString("O"), + }).ToArray(); + static byte[] Shape(W.HistoryReadResult item) { var copy = item.Clone(); copy.CorrelationId = ""; return copy.ToByteArray(); } + var windowStart = arguments.TryGetValue("--history-start", out var startText) ? DateTimeOffset.Parse(startText, System.Globalization.CultureInfo.InvariantCulture) : (DateTimeOffset?)null; + var windowEnd = arguments.TryGetValue("--history-end", out var endText) ? DateTimeOffset.Parse(endText, System.Globalization.CultureInfo.InvariantCulture) : (DateTimeOffset?)null; + foreach (var node in sourceNodes) + { + var name = node.Name; + failureTarget = name; + var nodeId = node.Value.GetProperty("node_id").GetString()!; + Metadata With(string credential, bool feature) + { + var headers = Headers(credential, "Node", nodeId); + if (feature) headers.Add("x-otopcua-data-features", "history"); + 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 deadline = () => DateTime.UtcNow.AddSeconds(20); + // 1. Capabilities with and without the feature header. + var plain = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(key, false), deadline()); + var featured = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(key, true), deadline()); + var plainV1Shape = plain.History is null && (plain.Operations & 32) == 0; + var featuredShape = featured.History is not null && (featured.Operations & 32) == 32; + var sameOtherwise = plain.Operations == (featured.Operations & ~32u) && plain.ClusterId == featured.ClusterId; + results.Add(new("history-capabilities-" + name, "history-capabilities", plainV1Shape && featuredShape && sameOtherwise, 3, new() + { + ["withoutHeader"] = new { operations = plain.Operations, historyPresent = plain.History is not null, bytes = plain.CalculateSize() }, + ["withHeader"] = new { operations = featured.Operations, history = featured.History?.ToString(), bytes = featured.CalculateSize() }, + ["serving"] = featured.Serving.ToString(), + })); + // 2. Raw end=now, 5 values, newest first + continuation; resume once; resume the same token again. + var now = DateTimeOffset.UtcNow; + W.HistoryReadRequest Raw(W.View view, ByteString? continuation, DateTimeOffset? start = null, DateTimeOffset? end = null, uint count = 5) + { + var request = new W.HistoryReadRequest { Budget = HistoryBudget(), Raw = new() { NumValuesPerNode = count, ReturnBounds = false } }; + if (start is { } s) request.Raw.Start = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTimeOffset(s); + request.Raw.End = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTimeOffset(end ?? now); + var item = new W.HistoryReadItem { CorrelationId = "one", View = view }; + if (continuation is not null) item.Continuation = continuation; + request.Items.Add(item); + return request; + } + var page1 = (await client.HistoryReadAsync(Raw(View(historized), null), With(key, true), deadline())).Items.Single(); + var times1 = page1.Samples.Select(x => x.SourceTimestamp.Value.ToDateTimeOffset()).ToArray(); + var page1Ok = page1.StatusCode >> 30 == 0 && page1.Samples.Count is > 0 and <= 5 && page1.HasContinuation + && times1.Zip(times1.Skip(1)).All(pair => pair.First > pair.Second); + var page2 = page1.HasContinuation ? (await client.HistoryReadAsync(Raw(View(historized), page1.Continuation), With(key, true), deadline())).Items.Single() : null; + var times2 = page2?.Samples.Select(x => x.SourceTimestamp.Value.ToDateTimeOffset()).ToArray() ?? []; + var page2Ok = page2 is not null && page2.StatusCode >> 30 == 0 && page2.Samples.Count is > 0 and <= 5 + && times2.Zip(times2.Skip(1)).All(pair => pair.First > pair.Second) && times2[0] < times1[^1]; + var replay = page1.HasContinuation ? (await client.HistoryReadAsync(Raw(View(historized), page1.Continuation), With(key, true), deadline())).Items.Single() : null; + var replayOk = replay is not null && replay.StatusCode == 0x804A0000u && replay.Samples.Count == 0; + if (page2 is not null && page2.HasContinuation) + await client.HistoryReadAsync(new W.HistoryReadRequest { Budget = HistoryBudget(), Raw = new() { NumValuesPerNode = 5 }, ReleaseContinuations = true, + Items = { new W.HistoryReadItem { CorrelationId = "one", View = View(historized), Continuation = page2.Continuation } } }, With(key, true), deadline()); + results.Add(new("history-raw-paging-" + name, "history-raw", page1Ok && page2Ok && replayOk, 3, new() + { + ["end"] = now.ToString("O"), + ["page1"] = new { statusCode = Hex(page1.StatusCode), hasContinuation = page1.HasContinuation, samples = Samples(page1) }, + ["page2"] = page2 is null ? null : new { statusCode = Hex(page2.StatusCode), hasContinuation = page2.HasContinuation, samples = Samples(page2) }, + ["replaySameToken"] = replay is null ? null : new { statusCode = Hex(replay.StatusCode), samples = replay.Samples.Count, hasContinuation = replay.HasContinuation }, + ["serving"] = featured.Serving.ToString(), + })); + // 3. Unhistorized tag and the no-HistoryRead principal answer the same bytes; no header โ‡’ FAILED_PRECONDITION. + var unhist = (await client.HistoryReadAsync(Raw(View(unhistorized), null), With(key, true), deadline())).Items.Single(); + var denied = (await client.HistoryReadAsync(Raw(View(historized), null), With(otherKey, true), deadline())).Items.Single(); + var identical = Shape(unhist).AsSpan().SequenceEqual(Shape(denied)); + string? precondition = null; + try { await client.HistoryReadAsync(Raw(View(historized), null), With(key, false), deadline()); precondition = "OK"; } + catch (RpcException error) { precondition = error.StatusCode.ToString(); } + results.Add(new("history-refusals-" + name, "history-refusals", + unhist.StatusCode == 0x80720000u && denied.StatusCode == 0x80720000u && identical && precondition == "FailedPrecondition", 4, new() + { + ["unhistorized"] = new { statusCode = Hex(unhist.StatusCode), unhist.Samples.Count, unhist.HasContinuation, unhist.HasDiagnostic, bytes = Convert.ToHexString(Shape(unhist)) }, + ["deniedPrincipal"] = new { statusCode = Hex(denied.StatusCode), denied.Samples.Count, denied.HasContinuation, denied.HasDiagnostic, bytes = Convert.ToHexString(Shape(denied)) }, + ["byteIdentical"] = identical, + ["withoutFeatureHeader"] = precondition, + })); + // 4. Optional fixed window (forward, all values) for comparison with an OPC UA historyread. + if (windowStart is { } ws && windowEnd is { } we) + { + var window = (await client.HistoryReadAsync(Raw(View(historized), null, ws, we, 0), With(key, true), deadline())).Items.Single(); + results.Add(new("history-window-" + name, "history-window", window.StatusCode >> 30 == 0 && window.Samples.Count > 0 && !window.HasContinuation, 1, new() + { + ["start"] = ws.ToString("O"), ["end"] = we.ToString("O"), ["statusCode"] = Hex(window.StatusCode), ["samples"] = Samples(window), + })); + } + } + } + if (scenario is not ("D13" or "history")) { 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 cd025e8f9..2b32e484c 100644 --- a/scripts/validation/grpc-data/rig.py +++ b/scripts/validation/grpc-data/rig.py @@ -666,8 +666,15 @@ class LocalRig: if env_path.exists(): self.environment.update(json.loads(env_path.read_text())) + def compose_files(self): + """The run's Compose files: the v1 fixture, plus the H2 history overlay when the run opted in.""" + files = ["--file", str(HERE / "compose.yml")] + if self.environment.get("GRPC_DATA_HISTORY") == "1": + files.extend(["--file", str(HERE / "compose.history.yml")]) + return files + def compose(self, *args, timeout=120): - return run_command([*self.docker, "compose", "--project-name", self.project, "--file", str(HERE / "compose.yml"), *args], timeout=timeout, environment=self.environment) + return run_command([*self.docker, "compose", "--project-name", self.project, *self.compose_files(), *args], timeout=timeout, environment=self.environment) @contextmanager def hub_partitions(self, count): @@ -700,7 +707,7 @@ class LocalRig: # Inspect exact project resources before changing its owned services. self.inspect_resources() run_command([*self.docker, "compose", "--project-name", self.project, - "--file", str(HERE / "compose.yml"), *extra, "up", "--detach", "--no-deps", *nodes], + *self.compose_files(), *extra, "up", "--detach", "--no-deps", *nodes], timeout=300, environment=self.environment) manifest = self.refresh_endpoints(nodes) self.capture(manifest) @@ -834,7 +841,7 @@ class LocalRig: self.save(manifest) return manifest - def up(self, timeout=600): + def up(self, timeout=600, history=False): import secrets import credentials if self.folder.exists(): @@ -854,6 +861,8 @@ class LocalRig: settings["GRPC_DATA_SQL_PASSWORD"] = "Gd!" + secrets.token_hex(24) import base64 settings["GRPC_DATA_SECRETS_KEK"] = base64.b64encode(secrets.token_bytes(32)).decode() + if history: + settings["GRPC_DATA_HISTORY"] = "1" atomic_write_secret(self.folder / "environment.json", json.dumps(settings)) self.environment.update(settings) credentials.provision_tls(self.folder / "security", NODES[2:]) @@ -926,6 +935,8 @@ class LocalRig: manifest["node_probe_dirs"] = {node: str(self.folder / "probe" / node) for node in NODES} manifest["credentials"] = {"cli_key_file": str(self.folder / "seed" / "cli.key"), "data_key_files": {"source": str(self.folder / "seed" / "source.key")}} + if self.environment.get("GRPC_DATA_HISTORY") == "1": + manifest["credentials"]["data_key_files"]["source_nohistory"] = str(self.folder / "seed" / "source-nohistory.key") manifest["state"] = "seeded" self.capture(manifest) return manifest @@ -1319,6 +1330,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("--history", action="store_true", help="up only: add the H2 history overlay (SOURCE historian + history seed profile)") arguments = parser.parse_args(argv) try: if arguments.action == "preflight": @@ -1336,7 +1348,12 @@ def main(argv=None): return 0 rig = LocalRig(arguments.run_id) action = getattr(rig, arguments.action) - result = action(**({"timeout": arguments.timeout} if arguments.timeout is not None and arguments.action in {"up", "deploy"} else {})) + options = {"timeout": arguments.timeout} if arguments.timeout is not None and arguments.action in {"up", "deploy"} else {} + if arguments.history: + if arguments.action != "up": + raise RigError("--history applies to up only; the run remembers it") + options["history"] = 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 except (RigError, ValueError, OSError, KeyError) as error: diff --git a/scripts/validation/grpc-data/seed/Program.cs b/scripts/validation/grpc-data/seed/Program.cs index fdc5fdeb6..912b7ecd1 100644 --- a/scripts/validation/grpc-data/seed/Program.cs +++ b/scripts/validation/grpc-data/seed/Program.cs @@ -25,6 +25,10 @@ var options = new DbContextOptionsBuilder().UseSqlServer IDbContextFactory factory = new PooledDbContextFactory(options); string[] nodes = ["control-1", "control-2", "source-1", "source-2", "consumer-1", "consumer-2"]; const DataOperations operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe; +// H2 smoke profile (opt-in, `rig.py up --history`): SOURCE historizes `counter`, the consumer's connection and +// 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; try { if (args.Length == 0) return 2; @@ -335,7 +339,9 @@ try foreach (var (name, address, writable) in new[] { ("counter", 0, false), ("scalar", 20, true), ("array0", 10, false), ("array1", 11, false), ("array2", 12, false) }) db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-" + name, DeviceId = "source-device", Name = name, DataType = "UInt16", AccessLevel = writable ? TagAccessLevel.ReadWrite : TagAccessLevel.Read, WriteIdempotent = false, PollGroupId = "source-fast", - TagConfig = JsonSerializer.Serialize(new { region = "HoldingRegisters", address, dataType = "UInt16", writable }) }); + TagConfig = history && name == "counter" + ? JsonSerializer.Serialize(new { region = "HoldingRegisters", address, dataType = "UInt16", writable, isHistorized = true }) + : JsonSerializer.Serialize(new { region = "HoldingRegisters", address, dataType = "UInt16", writable }) }); db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-vector", DeviceId = "source-device", Name = "vector", DataType = "UInt16", AccessLevel = TagAccessLevel.ReadWrite, WriteIdempotent = false, PollGroupId = "source-fast", TagConfig = """{"region":"HoldingRegisters","address":24,"dataType":"UInt16","isArray":true,"arrayLength":3,"writable":true}""" }); @@ -354,7 +360,7 @@ try db.DataConnections.Add(new() { DataConnectionRowId = Guid.NewGuid(), DataConnectionId = "consumer-source", ClusterId = "CONSUMER", Enabled = true, ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"], TargetMode = DataTargetMode.Cluster, ExpectedClusterId = "SOURCE", EligibleTargetNodeIds = ["source-1:4053", "source-2:4053"], Endpoints = ["https://source-1:4057", "https://source-2:4057"], - SecretReference = "secret:data/source", SecretScopeClusterId = "CONSUMER", AllowedOperations = operations, + SecretReference = "secret:data/source", SecretScopeClusterId = "CONSUMER", AllowedOperations = grantedOperations, TimeoutMilliseconds = 30000 }); foreach (var realm in new[] { DataRealm.Raw, DataRealm.Uns }) { @@ -362,18 +368,26 @@ 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 = operations }); + Realm = realm, RootKind = rootKind, RootEntityId = entity, PrincipalId = "fixture-consumer", AllowedOperations = grantedOperations }); + 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 }); db.RemoteNamespaceMappings.Add(new() { RemoteNamespaceMappingRowId = Guid.NewGuid(), RemoteNamespaceMappingId = "map-" + name, ClusterId = "CONSUMER", DataConnectionId = "consumer-source", Enabled = true, ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"], Realm = realm, RemoteRealm = realm, LocalParentKind = "Cluster", LocalParentId = "CONSUMER", BranchName = "remote-source", RemoteRootEntityId = entity, RemoteNamespaceUri = realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri, RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "modbus/plc" : equipment, AllowedOperations = operations, WriteThrough = true }); } + if (history) + db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "source-peer-nohistory", ClusterId = "SOURCE", Principal = "fixture-nohistory", + ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin }); await db.SaveChangesAsync(); } var seedAdmin = new ApiKeyAdminService(factory, pepper); await SaveText("cli.key", await seedAdmin.CreateAsync("fixture-cli", "fixture-cli", null, "owned local fixture", default)); await SaveText("source.key", await seedAdmin.CreateAsync("source-issued-consumer", "fixture-consumer", null, "SOURCE grants for CONSUMER", default)); + if (history) + await SaveText("source-nohistory.key", await seedAdmin.CreateAsync("source-issued-nohistory", "fixture-nohistory", null, "SOURCE export without HistoryRead", default)); string unsBrowseRoot; await using (var db = await factory.CreateDbContextAsync()) { @@ -386,7 +400,8 @@ try namespace_uris = new { raw = V3NodeIds.RawNamespaceUri, uns = V3NodeIds.UnsNamespaceUri, mapped_raw = ProjectedDataIds.RawNamespaceUri, mapped_uns = ProjectedDataIds.UnsNamespaceUri }, browse_roots = new { raw = "modbus/plc", uns = unsBrowseRoot }, browse_subjects = new { raw = "modbus/plc", uns = "area/line/plc" }, - origin_paths = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar", raw_array = "modbus/plc/vector", uns_array = "area/line/plc/vector", raw_string = "modbus/plc/text", uns_string = "area/line/plc/text" }, aliases = new[] { "raw", "uns" } }); + origin_paths = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar", raw_array = "modbus/plc/vector", uns_array = "area/line/plc/vector", raw_string = "modbus/plc/text", uns_string = "area/line/plc/text" }, aliases = new[] { "raw", "uns" }, + history = history ? new { historized = new { raw = "modbus/plc/counter", uns = "area/line/plc/counter" }, unhistorized = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar" } } : null }); return 0; } catch (Exception error)