From a6ae08146d82aa76bed12ffd079c9c7103e11f32 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 28 Nov 2026 09:23:45 -0500 Subject: [PATCH] =?UTF-8?q?test(grpc-data):=20Gateway=20origin=20backend?= =?UTF-8?q?=20for=20the=20history=20rig=20=E2=80=94=20read-only=20AVEVA=20?= =?UTF-8?q?bindings,=20reverse/end-only=20H07,=20strict-ceiling=20H08=20(#?= =?UTF-8?q?923)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../grpc-data/compose.history.gateway.yml | 27 +++ scripts/validation/grpc-data/history_gate.py | 167 +++++++++++++++++- scripts/validation/grpc-data/rig.py | 57 +++++- scripts/validation/grpc-data/scenarios.json | 28 +++ scripts/validation/grpc-data/seed/Program.cs | 23 ++- .../validation/grpc-data/tests/test_rig.py | 29 +++ 6 files changed, 316 insertions(+), 15 deletions(-) create mode 100644 scripts/validation/grpc-data/compose.history.gateway.yml diff --git a/scripts/validation/grpc-data/compose.history.gateway.yml b/scripts/validation/grpc-data/compose.history.gateway.yml new file mode 100644 index 000000000..6c4345742 --- /dev/null +++ b/scripts/validation/grpc-data/compose.history.gateway.yml @@ -0,0 +1,27 @@ +# #923 Gateway origin backend (opt-in: `rig.py up --history --history-backend gateway`), layered AFTER compose.history.yml: +# the SOURCE pair reads history from a HOST-RUN, READ-ONLY HistorianGateway (`ServerHistorian:Backend=Gateway`) that reads +# the real AVEVA Historian. The gateway is NOT run-owned: start it yourself before `up` (README §"Gateway origin backend") +# with `ApiKeys:Mode=Disabled` and `Historian:LiveWritesEnabled=false`, its ports bound to the host loopback. +# +# Read-only on this side too: the historized fixture tags are bound `historianReadOnly` to existing historian tags +# (GRPC_DATA_HISTORY_GATEWAY_TAGS, applied by the seeder), provisioning is Off and continuous historization is off, so +# nothing here asks the gateway to create a tag or write a value. No API key is configured (the gateway ignores keys in +# Disabled mode); never put a real key in this file. + +x-source-gateway-env: &source-gateway-env + ServerHistorian__Backend: Gateway + ServerHistorian__Endpoint: ${GRPC_DATA_HISTORY_GATEWAY_ENDPOINT:?gateway endpoint required} + ServerHistorian__UseTls: "false" + ServerHistorian__AllowUntrustedServerCertificate: "true" + ServerHistorian__ProvisionTags: "Off" + ServerHistorian__SqlServer__ConnectionString: "" + ContinuousHistorization__Enabled: "false" + +services: + seeder: + environment: + GRPC_DATA_HISTORY_GATEWAY_TAGS: ${GRPC_DATA_HISTORY_GATEWAY_TAGS:?gateway tag bindings required} + source-1: + environment: *source-gateway-env + source-2: + environment: *source-gateway-env diff --git a/scripts/validation/grpc-data/history_gate.py b/scripts/validation/grpc-data/history_gate.py index 5a5dc2587..550b7f4e3 100644 --- a/scripts/validation/grpc-data/history_gate.py +++ b/scripts/validation/grpc-data/history_gate.py @@ -1,4 +1,9 @@ -"""H3 live gate: scenarios H01–H06 (plan §9 "Scenarios") on a `rig.py up --history [--history-backend questdb]` run. +"""H3 live gate: scenarios H01–H06 (plan §9 "Scenarios") on a `rig.py up --history [--history-backend questdb|gateway]` run. + +On the gateway backend (#923) the origin reads the REAL AVEVA Historian through a host-run read-only HistorianGateway, so the +window is a fixed stretch of the recent past of the bound historian tags (nothing is accumulated), H07 adds the reverse and +end-only raw reads, and H08 (run on its own, after restarting the gateway with a strict row ceiling) re-reads the H01/H03/H07 +baseline through ceiling-bounded pages. Every scenario is driven through the production Client CLI `historyread` against CONSUMER's OPC UA endpoint, on PROJECTED NodeIds resolved by browsing from the mapping anchor (never constructed `p1.` ids), and is compared with the @@ -24,6 +29,10 @@ NODE_PERMISSIONS_ADMIN = 4095 # NodePermissions.Admin = bits 0..11 (HistoryUpda NODE_PERMISSIONS_HISTORY_READ = 1 << 3 NODE_PERMISSIONS_BROWSE = 1 << 0 EXPORT_WITHOUT_HISTORY = 31 # Browse | Metadata | Read | Write | Subscribe +GATEWAY_WINDOW_SECONDS = 120 # SysTimeSec stores one value per second ⇒ ~120 counter rows, ~12 flt rows (10 s) +GATEWAY_WINDOW_LAG_SECONDS = 15 # stay clear of the historian's real-time storage lag +GATEWAY_BASELINE = "H-gateway-baseline.json" +MIN_TIME = "0001-01-01T00:00:00Z" # DateTime.MinValue ⇒ an unspecified StartTime on the wire (an end-only read) def _iso(moment): @@ -31,7 +40,7 @@ def _iso(moment): class HistoryGate: - def __init__(self, run_id, *, pinned_build=False): + def __init__(self, run_id, *, pinned_build=False, gateway_ceiling=None): if pinned_build: recorded = scenarios.restricted_json(rig.LocalRig(run_id).path)["source_tree_hash"] rig.source_tree_hash = lambda: recorded @@ -42,6 +51,8 @@ class HistoryGate: self.catalog = json.loads((rig.HERE / "scenarios.json").read_text())["history_scenarios"] self.window = None self.projected = {} + self.gateway_ceiling = gateway_ceiling + self.baseline = {} # ----------------------------------------------------------------------------------------------------------- tools @@ -70,6 +81,30 @@ class HistoryGate: time.sleep(4) self.window = ((started + timedelta(seconds=5)).replace(microsecond=0), (finished - timedelta(seconds=5)).replace(microsecond=0)) + def gateway_window(self): + """Gateway backend: a fixed stretch of the recent past — the historian already holds it, nothing is written.""" + now = datetime.now(timezone.utc).replace(microsecond=0) + end = now - timedelta(seconds=GATEWAY_WINDOW_LAG_SECONDS) + self.window = (end - timedelta(seconds=GATEWAY_WINDOW_SECONDS), end) + + def keep(self, name, value): + """Gateway backend: remember an answer of the unconstrained leg, for H08's ceiling-bounded re-read.""" + if self.backend == "gateway": + self.baseline[name] = value + self.runner.save(GATEWAY_BASELINE, {"window": [_iso(w) for w in self.window], **self.baseline}) + + @staticmethod + def rows_text(rows): + return [[r[0].isoformat(), r[1], r[2]] for r in rows] + + @staticmethod + def page_lines(stdout): + return [line for line in stdout.splitlines() if line.startswith("Page ")] + + @staticmethod + def page_sizes(lines): + return [int(re.search(r" values=(\d+) ", line)[1]) for line in lines] + def resolve_projected(self): """Browse CONSUMER from the shared root; keep the projected leaves under the mapping anchors (`remote-source`).""" consumer = self.runner.primary("consumer") @@ -199,6 +234,7 @@ class HistoryGate: whole = self.cli(consumer, ["-n", self.projected[(realm, "counter")], *self.window_args(), "--max", "1000"], f"whole-{realm}") self.runner.check(history_smoke._cli_rows(whole.stdout) == origin_rows, f"{realm}: single read equals the origin") report[realm] = {"pages": len(pages), "rows": len(rows), "first": str(rows[0]), "last": str(rows[-1]), "page_lines": pages} + self.keep(f"forward_{realm}", self.rows_text(origin_rows)) # H3 review: a Float32 node whose backend stores Double reads the same Good rows through the projection. source, origin = self.origin_node("raw", "flt") reference = self.cli(source, ["-n", origin, *self.window_args(), "--max", "1000"], "origin-flt") @@ -207,8 +243,12 @@ class HistoryGate: self.runner.check(reference.returncode == 0 and floats.returncode == 0 and len(rows) >= 1, "Float32 history served on both") self.runner.check(rows == origin_rows and all(q == "Good" for _, _, q in rows), "Float32 rows Good and equal to the origin") report["float32"] = {"rows": [str(r) for r in rows]} - report["tie_cluster"] = ("not representable on the " + self.backend + " backend: SqlServer hist.Sample PK (TagId, SourceTimeUtc), " - "QuestDB DEDUP UPSERT KEYS(ts, tag) — one stored sample per timestamp; tie paging is proven by the H1 port fuzz") + self.keep("forward_flt", self.rows_text(origin_rows)) + report["tie_cluster"] = ("not representable on the " + self.backend + " backend: " + ( + "the bound AVEVA system tags store one value per timestamp and the leg is read-only (no tie can be written)" + if self.backend == "gateway" else + "SqlServer hist.Sample PK (TagId, SourceTimeUtc), QuestDB DEDUP UPSERT KEYS(ts, tag) — one stored sample per timestamp") + + "; tie paging is proven by the H1 port fuzz") return report def scenario_H02(self): @@ -228,6 +268,7 @@ class HistoryGate: self.runner.check(reference.returncode == 0 and served.returncode == 0, "Average served on both") rows, origin_rows = history_smoke._cli_rows(served.stdout), history_smoke._cli_rows(reference.stdout) self.runner.check(len(rows) > 0 and rows == origin_rows, "projected Average equals the origin row-for-row") + self.keep("average", self.rows_text(rows)) return {"refused": self.error_status(refused), "origin_refused": self.error_status(origin_refused), "average_rows": len(rows)} def scenario_H03(self): @@ -254,6 +295,7 @@ class HistoryGate: self.runner.check(projected_f.returncode == 0 and rows_f == origin_rows_f and all(q == "Good" for _, _, q in rows_f), "Float32 AtTime equals the origin, Good") self.runner.check(types_f == origin_types_f and all(t == "Type: Single" for t in types_f), "Float32 values stay Single end to end") + self.keep("attime", {"times": times, "rows": self.rows_text(rows), "types": types}) return {"rows": [str(r) for r in rows], "types": types, "float32": {"rows": [str(r) for r in rows_f], "types": types_f}} def scenario_H04(self): @@ -397,14 +439,121 @@ class HistoryGate: report["session_close"] = {"held": counts.get("held"), "after": after, "lines": self.status_lines(abandoned.stdout)} return report + def end_only_reference(self, source, origin, count): + """The latest `count` stored rows at or before the window end, newest first, from a FORWARD origin read.""" + end = self.window[1] + reference = self.cli(source, ["-n", origin, "--start", _iso(end - timedelta(seconds=count * 4)), "--end", + _iso(end + timedelta(seconds=1)), "--max", "1000"], "origin-end-only-reference") + self.runner.check(reference.returncode == 0, "origin forward reference read for the end-only case") + rows = [r for r in history_smoke._cli_rows(reference.stdout) if r[0] <= end] + return list(reversed(rows))[:count] + + def scenario_H07(self): + """Gateway backend: reverse (start > end) and end-only raw reads through the projection — the server walks them back from + forward gateway reads (#686) — equal to the origin and to the forward rows reversed.""" + consumer = self.runner.primary("consumer") + report = {} + source, origin = self.origin_node("raw", "counter") + forward = self.cli(source, ["-n", origin, *self.window_args(), "--max", "1000"], "origin-forward") + forward_rows = history_smoke._cli_rows(forward.stdout) + self.runner.check(forward.returncode == 0 and len(forward_rows) >= 20, "origin forward window holds history") + reverse = ["--start", _iso(self.window[1]), "--end", _iso(self.window[0])] + for label, extra in (("paged", ["--page-size", "7"]), ("whole", [])): + origin_rev = self.cli(source, ["-n", origin, *reverse, *extra, "--max", "1000"], f"origin-reverse-{label}") + projected_rev = self.cli(consumer, ["-n", self.projected[("raw", "counter")], *reverse, *extra, "--max", "1000"], + f"reverse-{label}") + rows, origin_rows = history_smoke._cli_rows(projected_rev.stdout), history_smoke._cli_rows(origin_rev.stdout) + self.runner.check(origin_rev.returncode == 0 and projected_rev.returncode == 0, f"reverse {label} read served on both") + self.runner.check(rows == origin_rows, f"reverse {label}: projected rows equal the origin row-for-row") + self.runner.check(rows == list(reversed(forward_rows)), f"reverse {label}: the forward rows, newest first") + entry = {"rows": len(rows), "first": str(rows[0]) if rows else None, "last": str(rows[-1]) if rows else None} + if extra: + pages = self.page_lines(projected_rev.stdout) + self.runner.check(len(pages) >= 2 and all("Good" in line for line in pages), "reverse paged: several Good pages") + self.runner.check(pages[-1].split("continuation=")[1].startswith("no"), "reverse paged: the last page has no continuation") + entry["page_lines"] = pages + self.keep("reverse", self.rows_text(rows)) + report["reverse_" + label] = entry + end_only = ["--start", MIN_TIME, "--end", _iso(self.window[1]), "--page-size", "5", "--max", "20"] + origin_eo = self.cli(source, ["-n", origin, *end_only], "origin-end-only") + projected_eo = self.cli(consumer, ["-n", self.projected[("raw", "counter")], *end_only], "end-only") + rows, origin_rows = history_smoke._cli_rows(projected_eo.stdout), history_smoke._cli_rows(origin_eo.stdout) + expected = self.end_only_reference(source, origin, 20) + pages = self.page_lines(projected_eo.stdout) + self.runner.check(origin_eo.returncode == 0 and projected_eo.returncode == 0, "end-only read served on both") + self.runner.check(len(pages) == 4 and all("Good" in line for line in pages), "end-only: four Good pages of five") + self.runner.check(rows == origin_rows, "end-only: projected rows equal the origin row-for-row") + self.runner.check(len(rows) == 20 and rows == expected, "end-only: the latest 20 rows at or before EndTime, newest first") + self.keep("end_only", self.rows_text(rows)) + report["end_only"] = {"rows": len(rows), "first": str(rows[0]) if rows else None, "last": str(rows[-1]) if rows else None, + "page_lines": pages} + return report + + def scenario_H08(self): + """Gateway backend, strict ceiling (run alone, after restarting the gateway with `MaxValuesCeiling = C` and + `AllowStreamingBeyondCeiling = false`): the H01/H03/H07 answers re-read through ceiling-bounded pages (#694).""" + self.runner.check(self.backend == "gateway" and self.gateway_ceiling is not None, "H08 needs the gateway backend and --gateway-ceiling") + consumer = self.runner.primary("consumer") + limit = self.gateway_ceiling - 16 # RawPageLimit: L = learned ceiling − 16 + report = {"ceiling": self.gateway_ceiling, "page_limit": limit} + rows_of = lambda result: self.rows_text(history_smoke._cli_rows(result.stdout)) + source, origin = self.origin_node("raw", "counter") + forward = self.baseline["forward_raw"] + self.runner.check(len(forward) > self.gateway_ceiling, "the baseline window holds more rows than the ceiling") + # (a) one read capped above the ceiling, on the origin and through the projection: every row, in order. + for label, node, host in (("origin", origin, source), ("projected", self.projected[("raw", "counter")], consumer)): + whole = self.cli(host, ["-n", node, *self.window_args(), "--max", "1000"], f"ceiling-whole-{label}") + self.runner.check(whole.returncode == 0 and rows_of(whole) == forward, f"{label}: a read above the ceiling returns the baseline rows") + # (b) pages asked for 100 rows come back ceiling-sized (<= L - 1) with continuations, and still equal the baseline. + paged = self.cli(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--page-size", "100", "--max", "1000"], + "ceiling-paged") + pages = self.page_lines(paged.stdout) + sizes = self.page_sizes(pages) + self.runner.check(paged.returncode == 0 and all("Good" in line for line in pages), "ceiling paged: every page Good") + self.runner.check(len(pages) >= 2 and max(sizes) <= limit - 1, "ceiling paged: pages are ceiling-sized, not 100") + self.runner.check(rows_of(paged) == forward, "ceiling paged: rows equal the unconstrained baseline") + report["paged"] = pages + # (c) reverse and end-only, walked back under the ceiling. + reverse = self.cli(consumer, ["-n", self.projected[("raw", "counter")], "--start", _iso(self.window[1]), "--end", _iso(self.window[0]), + "--page-size", "100", "--max", "1000"], "ceiling-reverse") + reverse_pages = self.page_lines(reverse.stdout) + self.runner.check(reverse.returncode == 0 and rows_of(reverse) == self.baseline["reverse"], "ceiling reverse equals the baseline") + self.runner.check(max(self.page_sizes(reverse_pages)) <= limit - 1, "ceiling reverse: pages are ceiling-sized") + end_only = self.cli(consumer, ["-n", self.projected[("raw", "counter")], "--start", MIN_TIME, "--end", _iso(self.window[1]), + "--page-size", "5", "--max", "20"], "ceiling-end-only") + self.runner.check(end_only.returncode == 0 and rows_of(end_only) == self.baseline["end_only"], "ceiling end-only equals the baseline") + report["reverse"] = reverse_pages + # (d) AtTime under the ceiling: the baseline values. + attime = self.baseline["attime"] + at = self.cli(consumer, ["-n", self.projected[("raw", "counter")], "--at-time", attime["times"]], "ceiling-attime") + self.runner.check(at.returncode == 0 and rows_of(at) == attime["rows"], "ceiling AtTime equals the baseline") + # (e) a raw-evaluated aggregate whose window exceeds the ceiling: the projection answers exactly what the origin answers. + aggregate = [*self.window_args(), "--aggregate", "Average", "--interval", "10000"] + origin_avg = self.cli(source, ["-n", origin, *aggregate], "ceiling-origin-average") + projected_avg = self.cli(consumer, ["-n", self.projected[("raw", "counter")], *aggregate], "ceiling-average") + observed = lambda result: ("Good", rows_of(result)) if result.returncode == 0 else (self.error_status(result), None) + self.runner.check(observed(origin_avg) == observed(projected_avg), "ceiling Average: the projection answers what the origin answers") + report["average"] = {"origin": observed(origin_avg)[0], "projected": observed(projected_avg)[0], + "equals_baseline": observed(projected_avg)[1] == self.baseline.get("average")} + return report + # ------------------------------------------------------------------------------------------------------------- run def run(self, selection): - chosen = [row["id"] for row in self.catalog] if selection == "all" else [selection] + applies = lambda row: self.backend in row.get("backends", [self.backend]) + chosen = ([row["id"] for row in self.catalog if applies(row) and not row.get("run_alone")] if selection == "all" else [selection]) self.runner.publish() self.runner.rig.seed_helper("snapshot") self.runner.active, self.runner.deadline = "H00", time.monotonic() + 900 - self.accumulate() + if self.backend != "gateway": + self.accumulate() + elif chosen == ["H08"]: + # The ceiling leg re-reads the unconstrained leg's window and compares with its answers. + recorded = json.loads((self.runner.folder / GATEWAY_BASELINE).read_text()) + self.window = tuple(datetime.fromisoformat(w.replace("Z", "+00:00")) for w in recorded.pop("window")) + self.baseline = recorded + else: + self.gateway_window() self.resolve_projected() rows = [] for name in chosen: @@ -436,8 +585,12 @@ def main(argv=None): parser.add_argument("--run-id", required=True) parser.add_argument("--scenario", default="all") parser.add_argument("--pinned-build", action="store_true") + parser.add_argument("--gateway-ceiling", type=int, default=None, + help="H08 only: the strict MaxValuesCeiling the host-run gateway was restarted with (> 16)") arguments = parser.parse_args(argv) - gate = HistoryGate(arguments.run_id, pinned_build=arguments.pinned_build) + if arguments.gateway_ceiling is not None and arguments.gateway_ceiling <= 16: + parser.error("--gateway-ceiling must exceed the 16-row allowance") + gate = HistoryGate(arguments.run_id, pinned_build=arguments.pinned_build, gateway_ceiling=arguments.gateway_ceiling) rows = gate.run(arguments.scenario) return 0 if all(row["passed"] for row in rows) else 1 diff --git a/scripts/validation/grpc-data/rig.py b/scripts/validation/grpc-data/rig.py index 7d28ac4b2..1b976d0ab 100644 --- a/scripts/validation/grpc-data/rig.py +++ b/scripts/validation/grpc-data/rig.py @@ -8,6 +8,7 @@ import math import os from pathlib import Path import re +import socket import tempfile import time from urllib.parse import urljoin, urlsplit @@ -147,17 +148,40 @@ def _plain_host(value): return re.split(r"[,:/\\]", value, maxsplit=1)[0] -def validate_fixture_endpoints(document, *, local_services): +# #923: the one non-run-owned endpoint a `--history-backend gateway` run may name — the HOST-run read-only HistorianGateway, +# reached from the containers through the Docker host alias, and only under this exact key. +HOST_GATEWAY_ALIAS = "host.docker.internal" +GATEWAY_ENDPOINT_KEY = "ServerHistorian__Endpoint" + + +def validate_host_gateway_endpoint(value): + """A plaintext h2c URL `http://host.docker.internal:` — no credentials, path, query or fragment.""" + try: + parsed = urlsplit(value) if isinstance(value, str) else None + port = parsed.port if parsed is not None else None + except ValueError: + parsed, port = None, None + if (parsed is None or parsed.scheme != "http" or parsed.hostname != HOST_GATEWAY_ALIAS or port is None + or parsed.username is not None or parsed.password is not None or parsed.path not in ("", "/") + or parsed.query or parsed.fragment): + raise RigError("the gateway endpoint must be http://host.docker.internal:") + return value + + +def validate_fixture_endpoints(document, *, local_services, host_gateway_keys=()): """Reject endpoint escape in resolved Compose/config/seed data, without DNS. Pass resolved data, never a YAML file with uninterpreted environment expansion. Image registries are build inputs; endpoint URLs, SQL connection hosts, and host/server/address configuration values must name an explicit local service - or loopback. No arbitrary private subnet is treated as local. + or loopback. No arbitrary private subnet is treated as local. The only exception + is `host_gateway_keys` (a gateway-backend run passes `ServerHistorian__Endpoint`): + a value under exactly such a key must be the host-run gateway URL and nothing else. """ services = set(local_services) if not services or any(not isinstance(name, str) or not _SERVICE_PATTERN.fullmatch(name) for name in services): raise RigError("an explicit local service allowlist is required") + host_gateway_keys = frozenset(host_gateway_keys) def check_host(host): if not _host_allowed(host, services): @@ -174,6 +198,9 @@ def validate_fixture_endpoints(document, *, local_services): elif isinstance(value, str): if "${" in value: raise RigError("fixture configuration must be fully resolved") + if key in host_gateway_keys: + validate_host_gateway_endpoint(value) + return urls = _URL_PATTERN.findall(value) for url in urls: try: @@ -476,7 +503,11 @@ NODES = tuple(f"{pair}-{n}" for pair in ("control", "source", "consumer") for n # `questdb` exists only on a `--history-backend questdb` run (compose.history.questdb.yml), `opcplc` only on a `--conditions` # run (compose.conditions.yml); listing them is the DNS allowlist. SERVICES = ("sql", "migrator", "device", "seeder", "questdb", "opcplc", *NODES) -HISTORY_BACKENDS = ("sqlserver", "questdb") +HISTORY_BACKENDS = ("sqlserver", "questdb", "gateway") +# #923 gateway backend defaults: the host-run read-only gateway's loopback gRPC port, and the fixture tags bound read-only to +# real historian system tags (1 Hz UInt2 seconds counter, a 10 s Float, a string). Overridable through the same env names. +GATEWAY_DEFAULT_ENDPOINT = "http://host.docker.internal:5231" +GATEWAY_DEFAULT_TAGS = "counter=SysTimeSec,flt=SysDataAcqOverallItemsPerSec,text=SysString" def run_command(argv, *, timeout=120, environment=None): @@ -676,6 +707,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_HISTORY_BACKEND") == "gateway": + files.extend(["--file", str(HERE / "compose.history.gateway.yml")]) if self.environment.get("GRPC_DATA_CONDITIONS") == "1": files.extend(["--file", str(HERE / "compose.conditions.yml")]) return files @@ -873,6 +906,18 @@ class LocalRig: raise RigError("unknown history backend") settings["GRPC_DATA_HISTORY"] = "1" settings["GRPC_DATA_HISTORY_BACKEND"] = history_backend + if history_backend == "gateway": + endpoint = validate_host_gateway_endpoint(os.environ.get("GRPC_DATA_HISTORY_GATEWAY_ENDPOINT") or GATEWAY_DEFAULT_ENDPOINT) + tags = os.environ.get("GRPC_DATA_HISTORY_GATEWAY_TAGS") or GATEWAY_DEFAULT_TAGS + if not re.fullmatch(r"[a-z]+=[A-Za-z0-9_.]+(?:,[a-z]+=[A-Za-z0-9_.]+)*", tags): + raise RigError("gateway tag bindings must be name=historianTag[,...]") + # Fail before any build: the gateway is not run-owned, so `up` cannot start it. + try: + socket.create_connection(("127.0.0.1", urlsplit(endpoint).port), timeout=5).close() + except OSError: + raise RigError("the host-run HistorianGateway is not listening on the host loopback") from None + settings["GRPC_DATA_HISTORY_GATEWAY_ENDPOINT"] = endpoint + settings["GRPC_DATA_HISTORY_GATEWAY_TAGS"] = tags if conditions: settings["GRPC_DATA_CONDITIONS"] = "1" atomic_write_secret(self.folder / "environment.json", json.dumps(settings)) @@ -889,7 +934,8 @@ class LocalRig: # builds can still be collected by exact observed object IDs on `down`. atomic_write_secret(self.folder / "setup.json", json.dumps({"run_id": self.run_id, "docker_context": self.context["Name"], "project": self.project})) resolved = json.loads(self.compose("config", "--format", "json")) - validate_fixture_endpoints(resolved, local_services=SERVICES) + validate_fixture_endpoints(resolved, local_services=SERVICES, + host_gateway_keys={GATEWAY_ENDPOINT_KEY} if settings.get("GRPC_DATA_HISTORY_BACKEND") == "gateway" else ()) try: self.compose("build", "--pull", "migrator", "device", "control-1", "seeder", timeout=1800) self.compose("up", "--detach", "sql", "device", "migrator", *NODES, timeout=timeout) @@ -1350,7 +1396,8 @@ def main(argv=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)") + help="up --history only: the SOURCE historian backend (sqlserver = the run's SQL container, default; questdb = a run-owned QuestDB; " + "gateway = a host-run read-only HistorianGateway, README)") arguments = parser.parse_args(argv) try: if arguments.action == "preflight": diff --git a/scripts/validation/grpc-data/scenarios.json b/scripts/validation/grpc-data/scenarios.json index 108a5b6a3..a73b94213 100644 --- a/scripts/validation/grpc-data/scenarios.json +++ b/scripts/validation/grpc-data/scenarios.json @@ -1608,6 +1608,34 @@ "origin open continuations >= 1 while held, 0 after the consumer session close", "resume after an origin rebuild BadContinuationPointInvalid, fresh Good" ] + }, + { + "id": "H07", + "title": "Gateway origin: reverse and end-only raw reads through the projection (#923)", + "driver": "history_gate.py", + "backends": ["gateway"], + "restores_baseline": true, + "timeout_seconds": 600, + "coverage": [ + "reverse (start > end) paged and whole: projected = origin = forward rows newest first", + "end-only (unspecified StartTime) paged: the latest 20 rows at or before EndTime, newest first, = origin" + ] + }, + { + "id": "H08", + "title": "Gateway origin behind a strict row ceiling: ceiling-bounded pages equal the unconstrained baseline (#923)", + "driver": "history_gate.py", + "backends": ["gateway"], + "run_alone": true, + "restores_baseline": true, + "timeout_seconds": 900, + "coverage": [ + "run alone with --gateway-ceiling C after restarting the gateway (MaxValuesCeiling=C, AllowStreamingBeyondCeiling=false)", + "a read capped above the ceiling returns every baseline row (origin and projected)", + "100-row pages come back ceiling-sized (<= C - 17) with continuations, rows = baseline", + "reverse and end-only under the ceiling = baseline; AtTime = baseline", + "raw-evaluated Average over more rows than the ceiling: projected answer = origin answer" + ] } ] } diff --git a/scripts/validation/grpc-data/seed/Program.cs b/scripts/validation/grpc-data/seed/Program.cs index b6b00300c..255304968 100644 --- a/scripts/validation/grpc-data/seed/Program.cs +++ b/scripts/validation/grpc-data/seed/Program.cs @@ -29,6 +29,23 @@ 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; +// #923 Gateway origin backend (`rig.py up --history --history-backend gateway`): `name=historianTag,...` binds the historized +// fixture tags READ-ONLY (lmxopcua#899 `historianReadOnly`) to existing tags of the real historian behind a read-only +// HistorianGateway, so OtOpcUa never provisions or records into them. Unset ⇒ the tags own their history, as before. +var gatewayTags = (Environment.GetEnvironmentVariable("GRPC_DATA_HISTORY_GATEWAY_TAGS") ?? "") + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(pair => pair.Split('=', 2, StringSplitOptions.TrimEntries)) + .ToDictionary(pair => pair.Length == 2 && pair[0].Length > 0 && pair[1].Length > 0 ? pair[0] : throw new InvalidOperationException("GRPC_DATA_HISTORY_GATEWAY_TAGS entries are name=historianTag"), + pair => pair[1], StringComparer.Ordinal); +if (gatewayTags.Count > 0 && !history) throw new InvalidOperationException("GRPC_DATA_HISTORY_GATEWAY_TAGS needs the history profile"); +string HistoryConfig(string name, string tagConfig) +{ + if (!gatewayTags.TryGetValue(name, out var historianTag)) return tagConfig; + var node = System.Text.Json.Nodes.JsonNode.Parse(tagConfig)!.AsObject(); + node["historianTagname"] = historianTag; + node["historianReadOnly"] = true; + return node.ToJsonString(); +} // 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"; @@ -360,7 +377,7 @@ try 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 = history && name == "counter" - ? JsonSerializer.Serialize(new { region = "HoldingRegisters", address, dataType = "UInt16", writable, isHistorized = true }) + ? HistoryConfig(name, 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", @@ -368,14 +385,14 @@ try db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-text", DeviceId = "source-device", Name = "text", DataType = "String", AccessLevel = TagAccessLevel.ReadWrite, WriteIdempotent = false, PollGroupId = "source-fast", TagConfig = history - ? """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true,"isHistorized":true}""" + ? HistoryConfig("text", """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true,"isHistorized":true}""") : """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true}""" }); if (history) // H3 review: a historized Float32 (two registers 30..31, big-endian), so the gate proves a backend that stores Double // still reads Good Singles through the projection. db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-flt", DeviceId = "source-device", Name = "flt", DataType = "Float", AccessLevel = TagAccessLevel.ReadWrite, WriteIdempotent = false, PollGroupId = "source-fast", - TagConfig = """{"region":"HoldingRegisters","address":30,"dataType":"Float32","writable":true,"isHistorized":true}""" }); + TagConfig = HistoryConfig("flt", """{"region":"HoldingRegisters","address":30,"dataType":"Float32","writable":true,"isHistorized":true}""") }); db.UnsAreas.Add(new() { UnsAreaRowId = Guid.NewGuid(), UnsAreaId = "source-area", ClusterId = "SOURCE", Name = "area" }); db.UnsLines.Add(new() { UnsLineRowId = Guid.NewGuid(), UnsLineId = "source-line", UnsAreaId = "source-area", Name = "line" }); var uuid = Guid.NewGuid(); diff --git a/scripts/validation/grpc-data/tests/test_rig.py b/scripts/validation/grpc-data/tests/test_rig.py index fe00cf21a..ae899142a 100644 --- a/scripts/validation/grpc-data/tests/test_rig.py +++ b/scripts/validation/grpc-data/tests/test_rig.py @@ -551,6 +551,35 @@ class RuntimeCompositionTests(unittest.TestCase): self.assertFalse(instance.health(row)) +class HostGatewayEndpointTests(unittest.TestCase): + """#923: a gateway-backend run may name the host-run HistorianGateway, under ServerHistorian__Endpoint only.""" + + def test_host_gateway_url_allowed_only_under_the_named_key(self): + row = {"ServerHistorian__Endpoint": "http://host.docker.internal:5231"} + rig.validate_fixture_endpoints(row, local_services={"source-1"}, host_gateway_keys={rig.GATEWAY_ENDPOINT_KEY}) + # Positive control for the exception: without the key opt-in the same row is outside the allowlist. + with self.assertRaises(rig.RigError): + rig.validate_fixture_endpoints(row, local_services={"source-1"}) + with self.assertRaises(rig.RigError): + rig.validate_fixture_endpoints({"Mesh__Endpoint": "http://host.docker.internal:5231"}, local_services={"source-1"}, + host_gateway_keys={rig.GATEWAY_ENDPOINT_KEY}) + + def test_the_gateway_key_accepts_nothing_but_the_plain_host_alias_url(self): + for value in ["https://host.docker.internal:5231", "http://host.docker.internal", "http://10.100.0.48:5221", + "http://wonder-sql-vd03.zmr.zimmer.com:5221", "http://user:key@host.docker.internal:5231", + "http://host.docker.internal:5231/escape", "http://host.docker.internal:5231?k=v", "http://source-1:5231", ""]: + with self.subTest(value=value), self.assertRaises(rig.RigError): + rig.validate_fixture_endpoints({"ServerHistorian__Endpoint": value}, local_services={"source-1"}, + host_gateway_keys={rig.GATEWAY_ENDPOINT_KEY}) + + def test_gateway_backend_overlay_layers_after_the_history_overlay(self): + instance = rig.LocalRig.__new__(rig.LocalRig) + instance.environment = {"GRPC_DATA_HISTORY": "1", "GRPC_DATA_HISTORY_BACKEND": "gateway"} + files = [f for f in instance.compose_files() if f != "--file"] + self.assertEqual([Path(f).name for f in files], ["compose.yml", "compose.history.yml", "compose.history.gateway.yml"]) + self.assertIn("gateway", rig.HISTORY_BACKENDS) + + class AkkaSeedEndpointTests(unittest.TestCase): def test_named_akka_system_in_owned_seed_context_is_not_a_password(self): rig.validate_fixture_endpoints({"Cluster__SeedNodes__0": "akka.tcp://otopcua@source-1:4053"}, local_services={"source-1"})