@yarkivaev/scada 2.22.0 → 2.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/charts/scada-workloads/Chart.yaml +5 -0
  2. package/charts/scada-workloads/README.md +45 -0
  3. package/charts/scada-workloads/templates/_collector.tpl +103 -0
  4. package/charts/scada-workloads/templates/_control-agent.tpl +80 -0
  5. package/charts/scada-workloads/templates/_controller.tpl +69 -0
  6. package/charts/scada-workloads/templates/_etcd-member.tpl +92 -0
  7. package/charts/scada-workloads/templates/_history-maintenance.tpl +44 -0
  8. package/charts/scada-workloads/templates/_history-receiver.tpl +88 -0
  9. package/charts/scada-workloads/templates/_journal-supervisor.tpl +82 -0
  10. package/charts/scada-workloads/templates/_postgres-role.tpl +43 -0
  11. package/charts/scada-workloads/templates/_reserve-supervisor.tpl +65 -0
  12. package/charts/scada-workloads/templates/_site-server.tpl +74 -0
  13. package/charts/scada-workloads/templates/_supervisor-history.tpl +12 -0
  14. package/charts/scada-workloads/templates/_supervisor.tpl +87 -0
  15. package/charts/scada-workloads/templates/_telemetry.tpl +181 -0
  16. package/db/migrations/E0027__metric_claim_trigger.sql +33 -0
  17. package/package.json +4 -1
  18. package/src/application/runtime/applicationRuntime.js +5 -2
  19. package/src/application/runtime/index.js +3 -0
  20. package/src/application/runtime/opcuaTask.js +63 -0
  21. package/src/application/runtime/runCommand.js +10 -0
  22. package/src/application/runtime/runService.js +14 -0
  23. package/src/application/siteRuntime/backfillOperationPayloads.js +41 -0
  24. package/src/application/siteRuntime/centralConnections.js +13 -0
  25. package/src/application/siteRuntime/edgeIngress.js +25 -0
  26. package/src/application/siteRuntime/index.js +5 -0
  27. package/src/application/siteRuntime/startAnalyticsRuntime.js +33 -0
  28. package/src/infrastructure/deploy/ci/applicationBundleLock.js +51 -0
  29. package/src/infrastructure/deploy/ci/archiveApplication.py +30 -0
  30. package/src/infrastructure/deploy/ci/packageApplication.js +63 -0
  31. package/src/infrastructure/deploy/ci/releaseArtifacts.js +55 -0
  32. package/src/infrastructure/deploy/ci/scada_gitlab.py +75 -0
  33. package/src/infrastructure/deploy/ci/scada_registry.py +91 -0
  34. package/src/infrastructure/deploy/configuredSiteAssets.js +8 -2
  35. package/src/infrastructure/deploy/executeStages.js +8 -1
  36. package/src/infrastructure/deploy/index.js +3 -1
  37. package/src/infrastructure/deploy/installVerifiedTools.js +44 -0
  38. package/src/infrastructure/deploy/stagedSitePlan.js +3 -1
  39. package/src/infrastructure/deploy/useApplicationBundle.sh +22 -0
  40. package/src/infrastructure/opcua/index.js +2 -0
  41. package/src/infrastructure/opcua/opcuaRecord.js +44 -0
  42. package/src/infrastructure/opcua/publishOpcuaRecord.js +23 -0
  43. package/src/infrastructure/persistence/pg/orderedRows.js +31 -0
  44. package/src/testing/boundedQueue.js +50 -0
  45. package/stream-processing/project/plugins.sbt +2 -0
  46. package/stream-processing/src/main/resources/logback.xml +16 -0
  47. package/stream-processing/src/main/scala/scada/processing/runtime/DurableMachineInput.scala +6 -0
  48. package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +31 -2
@@ -2,6 +2,8 @@ import { createClient } from '@clickhouse/client';
2
2
  import operationSyncIngest from '../../infrastructure/sync/operationSyncIngest.js';
3
3
  import clickhouseMetricsState from '../../infrastructure/persistence/clickhouse/metricsState.js';
4
4
  import { withTelemetryState } from '../../infrastructure/persistence/stateDataFromPool.js';
5
+ import embeddedCollectors from '../runtime/embeddedCollectors.js';
6
+ import { historySettings } from './history.js';
5
7
  import { orderedMetricsIngest } from './telemetry.js';
6
8
 
7
9
  async function start(writer) {
@@ -33,3 +35,26 @@ export function edgeTelemetryReaders(env, { readingsTable, createHistory, histor
33
35
  stateData(data, pool) { return withTelemetryState(data, metrics, createHistory ? createHistory(client, pool) : data.history); }
34
36
  };
35
37
  }
38
+
39
+ /** Start the core receivers before installation-owned embedded input adapters. */
40
+ export function startEdgeReceivers(env, { operations, metrics }, starters = [], {
41
+ inbound = startInboundOperations, edgeMetrics = startEdgeMetrics
42
+ } = {}) {
43
+ return embeddedCollectors(env.COLLECTOR_MODE || undefined, [
44
+ () => { return inbound(env, operations); },
45
+ () => { return edgeMetrics(env, metrics); },
46
+ ...starters
47
+ ]);
48
+ }
49
+
50
+ /** Read the history policy and compose the receiver environment before opening storage. */
51
+ export function edgeHistoryEnvironment(env, protocol) {
52
+ const settings = historySettings(env, protocol);
53
+ if (!settings) { return { settings }; }
54
+ if (env.TELEMETRY_BACKEND !== 'clickhouse' || !env.STATE_HTTP_TOKEN) {
55
+ throw new Error('ClickHouse history requires telemetry backend and STATE_HTTP_TOKEN');
56
+ }
57
+ return { settings, env: { ...env,
58
+ HISTORY_REPLICA_AMQP_URL: env.HISTORY_REPLICA_AMQP_URL || env.HISTORY_AMQP_URL || env.AMQP_URL || undefined
59
+ } };
60
+ }
@@ -15,3 +15,8 @@ export { default as reconcileOperationSnapshot } from './operationSnapshot.js';
15
15
  export { default as operatorFieldStore, verifyPostgresRelation } from '../../infrastructure/persistence/pg/operatorFieldStore.js';
16
16
  export { operatorFieldRoute } from '../../infrastructure/http/plant/routes/operatorRoute.js';
17
17
  export { edgeTelemetryReaders, startEdgeMetrics, startInboundOperations } from './edgeIngress.js';
18
+ export { default as centralConnections } from './centralConnections.js';
19
+ export { default as startAnalyticsRuntime } from './startAnalyticsRuntime.js';
20
+ export { startEdgeReceivers, edgeHistoryEnvironment } from './edgeIngress.js';
21
+ export { default as backfillOperationPayloads } from './backfillOperationPayloads.js';
22
+ export { default as orderedRows } from '../../infrastructure/persistence/pg/orderedRows.js';
@@ -0,0 +1,33 @@
1
+ import clickhouseConnection from '../../infrastructure/persistence/clickhouse/connection.js';
2
+ import pgOperations from '../../infrastructure/persistence/pg/operations.js';
3
+ import { openPostgresPool } from '../../infrastructure/persistence/postgresPool.js';
4
+ import analyticsMcpPort from '../mcp/analyticsMcpPort.js';
5
+ import { clickhousePort, cursorPort, postgresPort } from '../mcp/metricQueryPorts.js';
6
+ import parseBearerTokens from '../mcp/parseBearerTokens.js';
7
+ import plantReadPorts from '../mcp/plantReadPorts.js';
8
+
9
+ function analyticsPorts(plant, connection, pool, standby) {
10
+ return plantReadPorts(plant, {
11
+ cursor: cursorPort(pool, plant), queryClickhouse: clickhousePort(connection),
12
+ ...(standby && { queryPostgres: postgresPort(standby) })
13
+ });
14
+ }
15
+
16
+ /** Start the common analytics transport with an application-owned catalog and user-facing tools. */
17
+ export default async function startAnalyticsRuntime(env, { createPlant, createApp,
18
+ openPostgres = openPostgresPool, openClickHouse = clickhouseConnection,
19
+ journal = (line) => { process.stdout.write(line); }
20
+ }) {
21
+ const host = env.CLICKHOUSE_HOST || 'localhost';
22
+ const clickhouse = { password: env.CLICKHOUSE_PASSWORD, username: env.CLICKHOUSE_USER };
23
+ const standbyUrl = env.POSTGRES_STANDBY_URL;
24
+ const plantUrl = env.POSTGRES_URL || standbyUrl;
25
+ const pool = plantUrl ? openPostgres(plantUrl) : undefined;
26
+ const standby = standbyUrl ? openPostgres(standbyUrl) : undefined;
27
+ const connection = await openClickHouse(host, clickhouse);
28
+ const plant = await createPlant(host, { ...clickhouse, connectionString: plantUrl,
29
+ operations: pool ? pgOperations(pool) : undefined });
30
+ const app = createApp({ journal, plant, ports: analyticsPorts(plant, connection, pool, standby),
31
+ tokens: parseBearerTokens(env.ANALYTICS_MCP_TOKEN) });
32
+ return app.listen(analyticsMcpPort(env), '0.0.0.0');
33
+ }
@@ -0,0 +1,51 @@
1
+ import { readFileSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ function readJson(directory, file) {
5
+ return JSON.parse(readFileSync(path.join(directory, file), 'utf8'));
6
+ }
7
+
8
+ function writeJson(directory, file, value) {
9
+ writeFileSync(path.join(directory, file), JSON.stringify(value));
10
+ }
11
+
12
+ function selectDependencies(dependencies, policy) {
13
+ const { privateDependencies, providedDependencies } = policy;
14
+ Object.keys(dependencies).forEach((name) => {
15
+ if (!privateDependencies.includes(name) && !providedDependencies.includes(name)) {
16
+ throw new Error(`Classify added runtime dependency for application bundle: ${name}`);
17
+ }
18
+ });
19
+ return Object.fromEntries(privateDependencies.map((name) => {
20
+ if (!dependencies[name] || providedDependencies.includes(name)) {
21
+ throw new Error(`Invalid private application dependency: ${name}`);
22
+ }
23
+ return [name, dependencies[name]];
24
+ }));
25
+ }
26
+
27
+ export function stageApplicationLock(source, destination, policy) {
28
+ const manifest = readJson(source, 'package.json');
29
+ const lock = readJson(source, 'package-lock.json');
30
+ const { name, version, type } = manifest;
31
+ const dependencies = selectDependencies(manifest.dependencies || {}, policy);
32
+ lock.packages[''] = { name, version, dependencies };
33
+ writeJson(destination, 'package.json', { name, version, type, dependencies });
34
+ writeJson(destination, 'package-lock.json', lock);
35
+ }
36
+
37
+ export function verifyApplicationLock(source, destination, excludedDependencies) {
38
+ const original = readJson(source, 'package-lock.json').packages;
39
+ const projected = readJson(destination, 'package-lock.json').packages;
40
+ Object.entries(projected).filter(([entryPath]) => { return entryPath; }).forEach(([entryPath, entry]) => {
41
+ const packageName = entryPath.split('node_modules/').at(-1);
42
+ if (excludedDependencies.includes(packageName)) {
43
+ throw new Error(`Application bundle must resolve ${packageName} from the runtime`);
44
+ }
45
+ const pinned = original[entryPath];
46
+ if (!entry.integrity || entry.integrity !== pinned?.integrity ||
47
+ entry.version !== pinned.version || entry.resolved !== pinned.resolved) {
48
+ throw new Error(`Application dependency must match the source lock: ${entryPath}`);
49
+ }
50
+ });
51
+ }
@@ -0,0 +1,30 @@
1
+ """Write a sorted tar.gz with normalized permissions, ownership and time."""
2
+
3
+ import gzip
4
+ from pathlib import Path
5
+ import sys
6
+ import tarfile
7
+
8
+
9
+ def normalized(entry):
10
+ if not (entry.isfile() or entry.isdir()):
11
+ raise ValueError(f"Application archive only accepts regular files and directories: {entry.name}")
12
+ entry.uid = entry.gid = entry.mtime = 0
13
+ entry.uname = entry.gname = ""
14
+ entry.mode = 0o755 if entry.isdir() or entry.mode & 0o111 else 0o644
15
+ return entry
16
+
17
+
18
+ def archive(source, destination):
19
+ # Check every entry first, including types tarfile may silently ignore.
20
+ for path in Path(source).rglob("*"):
21
+ if path.is_symlink() or not (path.is_file() or path.is_dir()):
22
+ raise ValueError(f"Application archive only accepts regular files and directories: {path}")
23
+ with open(destination, "wb") as output:
24
+ with gzip.GzipFile(fileobj=output, filename="", mode="wb", mtime=0) as compressed:
25
+ with tarfile.open(fileobj=compressed, mode="w", dereference=True) as bundle:
26
+ bundle.add(source, arcname=".", filter=normalized)
27
+
28
+
29
+ if __name__ == "__main__":
30
+ archive(*sys.argv[1:])
@@ -0,0 +1,63 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { stageApplicationLock, verifyApplicationLock } from './applicationBundleLock.js';
8
+
9
+ const NPM_SAFETY_FLAGS = ['--omit=dev', '--ignore-scripts', '--no-audit', '--no-fund'];
10
+
11
+ function stageSources(source, destination, stage, policy) {
12
+ policy.requiredPaths.forEach((entry) => {
13
+ if (!existsSync(path.join(source, entry))) {
14
+ throw new Error(`Application bundle requires ${entry}`);
15
+ }
16
+ });
17
+ const sourceArchive = path.join(stage, 'sources.tar');
18
+ const excludes = policy.excludePatterns.map((pattern) => { return `--exclude=${pattern}`; });
19
+ const env = { ...process.env, COPYFILE_DISABLE: '1' };
20
+ execFileSync('tar', ['-C', source, ...excludes, '-cf', sourceArchive, ...policy.sourcePaths], { env, stdio: 'inherit' });
21
+ execFileSync('tar', ['-C', destination, '-xf', sourceArchive], { env, stdio: 'inherit' });
22
+ }
23
+
24
+ function installDependencies(source, destination, policy) {
25
+ stageApplicationLock(source, destination, policy);
26
+ const options = { cwd: destination, stdio: 'inherit' };
27
+ execFileSync('npm', ['install', '--package-lock-only', '--offline', ...NPM_SAFETY_FLAGS], options);
28
+ verifyApplicationLock(source, destination, policy.excludedDependencies);
29
+ execFileSync('npm', ['ci', '--no-bin-links', ...NPM_SAFETY_FLAGS], options);
30
+ rmSync(path.join(destination, 'package-lock.json'));
31
+ rmSync(path.join(destination, 'node_modules', '.package-lock.json'), { force: true });
32
+ }
33
+
34
+ function createArchive(destination, stage, output) {
35
+ const archive = path.join(stage, 'application.tar.gz');
36
+ const archiveTool = fileURLToPath(new URL('./archiveApplication.py', import.meta.url));
37
+ execFileSync('python3', [archiveTool, destination, archive], { stdio: 'inherit' });
38
+ const digest = createHash('sha256').update(readFileSync(archive)).digest('hex');
39
+ mkdirSync(path.dirname(output), { recursive: true });
40
+ copyFileSync(archive, output);
41
+ writeFileSync(`${output}.sha256`, `${digest}\n`);
42
+ }
43
+
44
+ function packageApplication(source, output, policy, extraSource) {
45
+ const stage = mkdtempSync(path.join(tmpdir(), 'scada-application-'));
46
+ const destination = path.join(stage, 'app');
47
+ try {
48
+ mkdirSync(destination);
49
+ stageSources(source, destination, stage, policy);
50
+ installDependencies(source, destination, policy);
51
+ if (extraSource) { copyFileSync(extraSource, path.join(destination, policy.extraFile)); }
52
+ createArchive(destination, stage, output);
53
+ } finally {
54
+ rmSync(stage, { recursive: true, force: true });
55
+ }
56
+ }
57
+
58
+ const [source, output, policyFile, extraSource] = process.argv.slice(2);
59
+ if (!source || !output || !policyFile) {
60
+ throw new Error('Usage: packageApplication.js SOURCE OUTPUT_TAR_GZ POLICY_JSON [EXTRA_FILE]');
61
+ }
62
+ const policy = JSON.parse(readFileSync(policyFile, 'utf8'));
63
+ packageApplication(source, output, policy, extraSource);
@@ -0,0 +1,55 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { mkdirSync, writeFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ function gitOutput(args, cwd) {
6
+ return execFileSync('git', args, { cwd, encoding: 'utf8' }).trim();
7
+ }
8
+
9
+ function fetchRevision(remote, ref, cwd) {
10
+ execFileSync('git', ['fetch', '--quiet', '--', remote, ref], { cwd, stdio: 'inherit' });
11
+ return gitOutput(['rev-parse', '--verify', 'FETCH_HEAD^{commit}'], cwd);
12
+ }
13
+
14
+ export function checkoutRevision(cwd) {
15
+ return gitOutput(['rev-parse', '--verify', 'HEAD^{commit}'], cwd);
16
+ }
17
+
18
+ export function branchRevision(remote, branch, cwd) {
19
+ return fetchRevision(remote, `refs/heads/${branch}`, cwd);
20
+ }
21
+
22
+ export function tagRevision(remote, tag, cwd) {
23
+ const ref = `refs/tags/${tag}`;
24
+ execFileSync('git', ['fetch', '--quiet', '--', remote, `${ref}:${ref}`], { cwd, stdio: 'inherit' });
25
+ return gitOutput(['rev-parse', '--verify', `${ref}^{commit}`], cwd);
26
+ }
27
+
28
+ export function requireCurrentReleaseRevision(expected, checkout, current) {
29
+ if (checkout !== expected) { throw new Error('Release checkout differs from the tested CI revision'); }
30
+ if (current !== checkout) { throw new Error('Release is superseded by a newer branch revision'); }
31
+ return checkout;
32
+ }
33
+
34
+ export function stableImageTag(image, repository, tagPrefix = '') {
35
+ const prefix = `${repository}:`;
36
+ const version = image.slice(prefix.length);
37
+ if (!image.startsWith(prefix) || !/^\d+\.\d+\.\d+$/u.test(version)) {
38
+ throw new Error('Expected a stable image from the configured registry repository');
39
+ }
40
+ return `${tagPrefix}${version}`;
41
+ }
42
+
43
+ export function verifyReleaseArtifact({ remote, tag, checkout, image, verifyRevision, waitForImage }) {
44
+ const revision = tagRevision(remote, tag);
45
+ if (revision !== checkout) { verifyRevision(revision); }
46
+ waitForImage(image);
47
+ }
48
+
49
+ export async function downloadReleaseArtifact(url, destination, { headers, timeout = 60000 } = {}) {
50
+ const response = await fetch(url, { headers, redirect: 'error', signal: AbortSignal.timeout(timeout) });
51
+ if (!response.ok) { throw new Error(`Release artifact returned HTTP ${response.status}`); }
52
+ const bytes = Buffer.from(await response.arrayBuffer());
53
+ mkdirSync(path.dirname(destination), { recursive: true });
54
+ writeFileSync(destination, bytes);
55
+ }
@@ -0,0 +1,75 @@
1
+ """GitLab pipeline operations for release jobs running on Python alone."""
2
+
3
+ import json
4
+ import time
5
+ import urllib.error
6
+ import urllib.parse
7
+ import urllib.request
8
+
9
+
10
+ def verified(pipeline, jobs, ref, sha, required):
11
+ statuses = {job["name"]: job["status"] for job in jobs}
12
+ return (pipeline.get("ref") == ref and pipeline.get("sha") == sha
13
+ and pipeline.get("status") == "success"
14
+ and all(statuses.get(name) == "success" for name in required))
15
+
16
+
17
+ class GitLab:
18
+ def __init__(self, api_url, project, headers=None):
19
+ self.base = api_url.rstrip("/") + "/projects/" + urllib.parse.quote(project, safe="")
20
+ self.headers = dict(headers or {})
21
+
22
+ def get(self, path):
23
+ request = urllib.request.Request(self.base + path, headers=self.headers)
24
+ with urllib.request.urlopen(request, timeout=30) as response:
25
+ return json.load(response)
26
+
27
+ def jobs(self, pipeline_id):
28
+ page = 1
29
+ result = []
30
+ while True:
31
+ batch = self.get(f"/pipelines/{pipeline_id}/jobs?per_page=100&page={page}")
32
+ result.extend(batch)
33
+ if len(batch) < 100:
34
+ return result
35
+ page += 1
36
+
37
+ def wait_for_verified_pipeline(self, ref, sha, required, *, timeout=480, interval=10, waiting=None):
38
+ deadline = time.monotonic() + timeout
39
+ query = urllib.parse.urlencode({
40
+ "ref": ref, "sha": sha, "per_page": 100, "order_by": "id", "sort": "desc",
41
+ })
42
+ while True:
43
+ pipelines = self.get("/pipelines?" + query)
44
+ # A previous green pipeline must never hide a newer failure.
45
+ candidates = [p for p in pipelines if p.get("ref") == ref and p.get("sha") == sha]
46
+ latest = max(candidates, key=lambda p: p["id"], default=None)
47
+ if latest and verified(latest, self.jobs(latest["id"]), ref, sha, required):
48
+ return latest["id"]
49
+ if latest and latest["status"] in ("failed", "canceled", "skipped", "success"):
50
+ raise RuntimeError(f"Latest {ref} pipeline failed or lacks successful mandatory suites")
51
+ if time.monotonic() >= deadline:
52
+ raise RuntimeError(f"No fully tested successful {ref} pipeline for release SHA")
53
+ if waiting:
54
+ waiting()
55
+ time.sleep(interval)
56
+
57
+ def trigger(self, ref, token, variables):
58
+ form = {"token": token, "ref": ref}
59
+ form.update({f"variables[{key}]": value for key, value in variables.items()})
60
+ data = urllib.parse.urlencode(form).encode("utf-8")
61
+ path = "/trigger/pipeline"
62
+ request = urllib.request.Request(
63
+ self.base + path, data=data, method="POST",
64
+ headers={**self.headers, "Content-Type": "application/x-www-form-urlencoded"},
65
+ )
66
+ try:
67
+ with urllib.request.urlopen(request, timeout=60) as response:
68
+ body = response.read()
69
+ return json.loads(body) if body else {}
70
+ except urllib.error.HTTPError as error:
71
+ with error:
72
+ detail = error.read().decode("utf-8", errors="replace")
73
+ raise RuntimeError(
74
+ f"GitLab API POST {request.selector} failed status={error.code} body={detail}"
75
+ ) from error
@@ -0,0 +1,91 @@
1
+ """OCI manifest inspection and polling with caller-supplied registry access."""
2
+
3
+ import base64
4
+ import json
5
+ import ssl
6
+ import time
7
+ import urllib.error
8
+ import urllib.parse
9
+ import urllib.request
10
+
11
+
12
+ MANIFEST_ACCEPT = (
13
+ "application/vnd.docker.distribution.manifest.v2+json, "
14
+ "application/vnd.docker.distribution.manifest.list.v2+json, "
15
+ "application/vnd.oci.image.manifest.v1+json, "
16
+ "application/vnd.oci.image.index.v1+json"
17
+ )
18
+
19
+
20
+ class Registry:
21
+ def __init__(self, *, scheme="https", jwt_url=None, jwt_service=None, user="",
22
+ password="", tls_verify=True, emit=print):
23
+ self.scheme = scheme
24
+ self.jwt_url = jwt_url
25
+ self.jwt_service = jwt_service
26
+ self.user = user
27
+ self.password = password
28
+ self.context = ssl.create_default_context() if tls_verify else ssl._create_unverified_context()
29
+ self.emit = emit
30
+
31
+ def open(self, request):
32
+ return urllib.request.urlopen(request, timeout=30, context=self.context)
33
+
34
+ def bearer_token(self, name):
35
+ if not self.jwt_url or not self.jwt_service:
36
+ raise ValueError("Registry JWT URL and service are required with credentials")
37
+ auth = base64.b64encode(f"{self.user}:{self.password}".encode()).decode("ascii")
38
+ query = urllib.parse.urlencode(
39
+ {"service": self.jwt_service, "scope": f"repository:{name}:pull"}
40
+ )
41
+ url = urllib.parse.urlsplit(self.jwt_url)
42
+ url = url._replace(query="&".join(filter(None, (url.query, query)))).geturl()
43
+ request = urllib.request.Request(url, headers={"Authorization": f"Basic {auth}"})
44
+ with self.open(request) as response:
45
+ payload = json.load(response)
46
+ token = payload.get("token") or payload.get("access_token")
47
+ if not token:
48
+ raise RuntimeError("registry jwt response missing token")
49
+ return token
50
+
51
+ def inspect(self, image_ref):
52
+ if "/" not in image_ref or ":" not in image_ref.rsplit("/", 1)[-1]:
53
+ raise RuntimeError(f"unexpected image ref {image_ref}")
54
+ host, remainder = image_ref.split("/", 1)
55
+ name, tag = remainder.rsplit(":", 1)
56
+ url = f"{self.scheme}://{host}/v2/{name}/manifests/{tag}"
57
+ headers = {"Accept": MANIFEST_ACCEPT}
58
+ if self.user and self.password:
59
+ try:
60
+ headers["Authorization"] = f"Bearer {self.bearer_token(name)}"
61
+ except Exception as error:
62
+ raise RuntimeError(f"registry jwt failed for {image_ref}: {error}") from error
63
+ request = urllib.request.Request(url, headers=headers, method="GET")
64
+ try:
65
+ with self.open(request) as response:
66
+ return 200 <= response.status < 300
67
+ except urllib.error.HTTPError as error:
68
+ with error:
69
+ if error.code == 404:
70
+ return False
71
+ raise RuntimeError(
72
+ f"registry inspect failed for {image_ref} status={error.code}"
73
+ ) from error
74
+ except urllib.error.URLError as error:
75
+ self.emit(f"registry inspect unreachable for {image_ref}: {error}")
76
+ return False
77
+
78
+ def wait(self, image_ref, *, timeout=2700, interval=15):
79
+ if interval <= 0 or timeout < 0:
80
+ raise ValueError("Registry interval must be positive and timeout cannot be negative")
81
+ self.emit(f"waiting for image {image_ref} timeout={timeout}s")
82
+ start = time.monotonic()
83
+ while True:
84
+ if self.inspect(image_ref):
85
+ self.emit(f"image ready {image_ref} after {int(time.monotonic() - start)}s")
86
+ return True
87
+ elapsed = time.monotonic() - start
88
+ self.emit(f"image not ready {image_ref} elapsed={int(elapsed)}s")
89
+ if elapsed >= timeout:
90
+ return False
91
+ time.sleep(min(interval, timeout - elapsed))
@@ -41,15 +41,21 @@ export function secretEnvironment(name, keys) {
41
41
  }));
42
42
  }
43
43
 
44
+ /** Require a concrete startup history repair decision from deployment policy. */
45
+ export function startupHistoryPolicy(value) {
46
+ if (typeof value !== 'boolean') { throw new TypeError('repairHistoryOnStart must be boolean'); }
47
+ return value;
48
+ }
49
+
44
50
  /** Render concrete site environment, Kubernetes objects and supervisor file assets. */
45
- export function configuredSiteAssets(settings, base, startupHistoryPolicy) {
51
+ export function configuredSiteAssets(settings, base, repairPolicy = startupHistoryPolicy) {
46
52
  function text(file) { return readFileSync(new URL(file, base), 'utf8'); }
47
53
  const observationUrl = configuredObservationUrl(settings.observation);
48
54
  return {
49
55
  observationUrl,
50
56
  supervisorConfig: supervisorConfig(settings.supervisor, text, observationUrl),
51
57
  siteEnvironment(cluster, app, security) {
52
- const repairHistoryOnStart = startupHistoryPolicy(app.ingest.stomp.repairHistoryOnStart);
58
+ const repairHistoryOnStart = repairPolicy(app.ingest.stomp.repairHistoryOnStart);
53
59
  const bindings = { app, number: cluster.at(-1), repairHistoryOnStart };
54
60
  const environment = deploymentTemplate(settings.apiEnvironment, bindings);
55
61
  return databaseEnvironment({ ...environment,
@@ -1,12 +1,19 @@
1
1
  import { execFileSync } from 'node:child_process';
2
- import executeRelease from './executeRelease.js';
2
+ import executeRelease, { requireReleaseAction } from './executeRelease.js';
3
3
 
4
4
  /** Execute ordered full release plans, preflighting every stage before mutations.
5
5
  * Stage rollout/afterReady and beforeApply gates must succeed before continuing.
6
6
  * Read-only actions execute each stage without invoking mutation gates.
7
+ * Stages with buildDependencies enabled build their chart from its Helm lock.
7
8
  */
8
9
  export default function executeStages(stages, action = 'render', execute = execFileSync) {
9
10
  if (!Array.isArray(stages) || !stages.length) { throw new Error('stages must be a nonempty array'); }
11
+ requireReleaseAction(action);
12
+ const charts = new Set(stages.filter(({ buildDependencies }) => { return buildDependencies === true; })
13
+ .map(({ chart }) => { return chart; }));
14
+ for (const chart of charts) {
15
+ execute('helm', ['dependency', 'build', '--skip-refresh', chart], { stdio: 'pipe' });
16
+ }
10
17
  if (['apply', 'adopt'].includes(action)) {
11
18
  for (const stage of stages) {
12
19
  // SSA can claim legacy fields only after the stage's CSA handoff.
@@ -77,10 +77,12 @@ export { default as configuredRuntimeCapabilities } from './configuredRuntimeCap
77
77
  export { classificationEnvironment, configuredClassification, configuredSupervisor } from './configuredClassification.js';
78
78
  export { default as configuredArchivePlan } from './configuredArchivePlan.js';
79
79
  export { default as configuredEtcdInventory } from './configuredEtcdInventory.js';
80
- export { configuredSiteAssets } from './configuredSiteAssets.js';
80
+ export { configuredSiteAssets, startupHistoryPolicy } from './configuredSiteAssets.js';
81
81
  export { default as configuredBrokerRoutes } from './configuredBrokerRoutes.js';
82
82
  export { default as controlPlaneCli } from './controlPlaneCli.js';
83
83
  export { default as configuredCollectorChartDeployment } from './configuredCollectorChartDeployment.js';
84
84
  export { default as configuredRuntimeArtifacts } from './configuredRuntimeArtifacts.js';
85
85
  export { secretEnvironment } from './configuredSiteAssets.js';
86
86
  export { default as configuredBundleCapabilities } from './configuredBundleCapabilities.js';
87
+ export { default as installVerifiedTools } from './installVerifiedTools.js';
88
+ export { branchRevision, checkoutRevision, downloadReleaseArtifact, requireCurrentReleaseRevision, stableImageTag, verifyReleaseArtifact } from './ci/releaseArtifacts.js';
@@ -0,0 +1,44 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { basename, join } from 'node:path';
6
+
7
+ async function fetchTool(name, spec, request, fetch) {
8
+ const { url, headers } = request(name, spec);
9
+ const response = await fetch(url, { headers, signal: AbortSignal.timeout(60000) });
10
+ if (!response.ok) { throw new Error(`${name} mirror returned HTTP ${response.status}`); }
11
+ const bytes = Buffer.from(await response.arrayBuffer());
12
+ if (createHash('sha256').update(bytes).digest('hex') !== spec.sha256) {
13
+ throw new Error(`${name} mirror checksum mismatch`);
14
+ }
15
+ return bytes;
16
+ }
17
+
18
+ function install(name, spec, bytes, { directory, scratch, execute }) {
19
+ const destination = join(directory, basename(name));
20
+ if (spec.archiveEntry) {
21
+ const archive = join(scratch, 'tool.tar.gz');
22
+ writeFileSync(archive, bytes);
23
+ execute('tar', ['-xzf', archive, '-C', scratch, '--', spec.archiveEntry]);
24
+ copyFileSync(join(scratch, spec.archiveEntry), destination);
25
+ } else {
26
+ writeFileSync(destination, bytes);
27
+ }
28
+ chmodSync(destination, 0o755);
29
+ }
30
+
31
+ /** Install checksum-pinned CI binaries, accepting release pins and mirror credentials from the application. */
32
+ export default async function installVerifiedTools(tools, { directory, request, fetch = globalThis.fetch, execute = execFileSync }) {
33
+ const scratch = mkdtempSync(join(tmpdir(), 'scada-deploy-tools-'));
34
+ try {
35
+ mkdirSync(directory, { recursive: true });
36
+ for (const [name, spec] of Object.entries(tools)) {
37
+ // eslint-disable-next-line no-await-in-loop -- the tools use one temporary extraction directory
38
+ const bytes = await fetchTool(name, spec, request, fetch);
39
+ install(name, spec, bytes, { directory, scratch, execute });
40
+ }
41
+ } finally {
42
+ rmSync(scratch, { recursive: true, force: true });
43
+ }
44
+ }
@@ -3,6 +3,7 @@ import { brokerClientEnvironment } from './brokerSecurity.js';
3
3
  import buildDeploymentStages from './buildDeploymentStages.js';
4
4
  import { databaseSecurity } from './databaseSecurity.js';
5
5
  import deploymentTemplate from './deploymentTemplate.js';
6
+ import { secretEnvironment as environmentFromSecret } from './configuredSiteAssets.js';
6
7
  import { brokerPolicy } from './securityPolicy.js';
7
8
 
8
9
  function nodeAddress(server, service) {
@@ -84,7 +85,8 @@ function supervisor(state, policy, ports) {
84
85
  const machine = deploymentTemplate(policy.supervisor.machineId, { number: cluster.at(-1) });
85
86
  const config = ports.supervisorConfig(cluster, Boolean(brokerEnvironment), [machine], policy.supervisor.checkpointUrl);
86
87
  const environment = { ...(document.edgeControlPlane && { [policy.supervisor.groupVariable]: machine }),
87
- ...deploymentTemplate(policy.supervisorEnvironment, { app }), ...brokerEnvironment };
88
+ ...deploymentTemplate(policy.supervisorEnvironment ?? {}, { app }),
89
+ ...environmentFromSecret(app.api.secret, policy.supervisorSecretKeys ?? {}), ...brokerEnvironment };
88
90
  return { values: { ...profile.apps.supervisor, ...deploymentTemplate(policy.supervisorValues, { app, image, config, environment }) } };
89
91
  }
90
92
 
@@ -0,0 +1,22 @@
1
+ # Source from a protected release job to read its same-pipeline artifact.
2
+ scada_bundle_error() {
3
+ printf 'SCADA application bundle unavailable: %s\n' "$1" >&2
4
+ exit 1
5
+ }
6
+
7
+ if [ -n "${SCADA_APP_BUNDLE_TARGET:-}" ]; then
8
+ test "$CI_COMMIT_REF_PROTECTED" = true || scada_bundle_error "expected a protected release tag"
9
+ test -s scada-app.env || scada_bundle_error "missing release record"
10
+ release=$(sed -n 's/^SCADA_APP_BUNDLE_RELEASE_SHA=//p' scada-app.env)
11
+ digest=$(sed -n 's/^SCADA_APP_BUNDLE_SHA256=//p' scada-app.env)
12
+ url=$(sed -n 's/^SCADA_APP_BUNDLE_URL=//p' scada-app.env)
13
+ test "$release" = "$CI_COMMIT_SHA" || scada_bundle_error "release record does not match this commit"
14
+ case "$digest" in
15
+ *[!a-f0-9]*) scada_bundle_error "invalid digest" ;;
16
+ esac
17
+ test "${#digest}" -eq 64 || scada_bundle_error "invalid digest length"
18
+ origin="${SCADA_APP_BUNDLE_PACKAGE_ORIGIN:-https://${CI_GIT_HOST:-$CI_SERVER_HOST}}"
19
+ expected="${origin%/}/api/v4/projects/$CI_PROJECT_ID/packages/generic/scada-app/$release-$digest/scada-app.tar.gz"
20
+ test "$url" = "$expected" || scada_bundle_error "release URL does not match this project, commit and digest"
21
+ export SCADA_APP_BUNDLE_URL="$url" SCADA_APP_BUNDLE_SHA256="$digest"
22
+ fi
@@ -9,3 +9,5 @@ export default function opcuaConnections(connections, publish, options = {}) {
9
9
 
10
10
  export { default as opcuaSource } from './source.js';
11
11
  export { default as opcuaHealth } from './health.js';
12
+ export { default as opcuaRecord, opcuaNumber, opcuaRoutingKey } from './opcuaRecord.js';
13
+ export { default as publishOpcuaRecord, TELEMETRY } from './publishOpcuaRecord.js';
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Coerces OPC UA bool/number to a metrics numeric value.
3
+ *
4
+ * @param {*} value - raw node value
5
+ * @returns {number} 0, 1, or the original number
6
+ */
7
+ export function opcuaNumber(value) {
8
+ if (value === true) {
9
+ return 1;
10
+ }
11
+ if (value === false) {
12
+ return 0;
13
+ }
14
+ if (typeof value === 'number' && Number.isFinite(value)) {
15
+ return value;
16
+ }
17
+ throw new Error(`opcua value is not numeric: ${String(value)}`);
18
+ }
19
+
20
+ /** Wire key emitted for a pinned OPC UA channel on the telemetry exchange. */
21
+ export function opcuaRoutingKey(device, key) {
22
+ return `OPCUA.${device}.GET.${key}.VALUE`;
23
+ }
24
+
25
+ /**
26
+ * Maps an OPC UA sample to an AMQP telemetry record.
27
+ *
28
+ * @example
29
+ * const row = opcuaRecord('cell-demo', 'sensor_ready', true);
30
+ * row.routingKey === 'OPCUA.cell-demo.GET.sensor_ready.VALUE';
31
+ *
32
+ * @param {string} device - MQTT/AMQP device id
33
+ * @param {string} key - sensor key
34
+ * @param {*} value - OPC UA value
35
+ * @param {number} [ts] - epoch millis
36
+ * @param {string} [route] - document path, when the chart names one
37
+ * @returns {{ routingKey: string, body: string }}
38
+ */
39
+ export default function opcuaRecord(device, key, value, ts = Date.now(), route = '') {
40
+ return {
41
+ routingKey: route.length > 0 ? route : opcuaRoutingKey(device, key),
42
+ body: JSON.stringify({ ts, value: opcuaNumber(value) })
43
+ };
44
+ }