@yarkivaev/scada 2.14.0 → 2.16.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 (66) hide show
  1. package/charts/scada/templates/processes.yaml +6 -1
  2. package/charts/scada/values.schema.json +1 -0
  3. package/db/bootstrap/apply-hba.sh +11 -0
  4. package/db/bootstrap/entrypoint.sh +6 -0
  5. package/db/bootstrap/ownership.sql +18 -0
  6. package/db/bootstrap/zz-auth.sh +3 -0
  7. package/index.js +1 -0
  8. package/package.json +3 -2
  9. package/src/application/control/agent.js +8 -14
  10. package/src/application/control/controller.js +2 -9
  11. package/src/application/control/executionSnapshot.js +4 -5
  12. package/src/application/control/periodicReconciliation.js +19 -0
  13. package/src/application/control/publishControlCatalog.js +25 -0
  14. package/src/application/control/reconcileStoredChoice.js +10 -0
  15. package/src/application/deploy/controlPlan.js +93 -0
  16. package/src/application/deploy/deploymentCommands.js +29 -0
  17. package/src/application/deploy/deploymentPlan.js +84 -0
  18. package/src/application/deploy/readDocumentFile.js +28 -0
  19. package/src/application/deploy/releases.js +14 -10
  20. package/src/application/runtime/deliveryOperations.js +6 -3
  21. package/src/application/runtime/deliveryPublications.js +13 -11
  22. package/src/application/runtime/deliveryQueue.js +5 -4
  23. package/src/application/runtime/index.js +0 -1
  24. package/src/application/runtime/queuedDelivery.js +6 -5
  25. package/src/application/runtime/runCollector.js +8 -6
  26. package/src/application/runtime/runtime.js +1 -0
  27. package/src/application/runtime/runtimeServices.js +6 -26
  28. package/src/infrastructure/deploy/applyHelmResources.js +17 -0
  29. package/src/infrastructure/deploy/bootstrapKubeStorage.js +28 -0
  30. package/src/infrastructure/deploy/deploymentChecks.js +68 -0
  31. package/src/infrastructure/deploy/deploymentPatch.js +36 -0
  32. package/src/infrastructure/deploy/executeChartDeployment.js +19 -0
  33. package/src/infrastructure/deploy/executeRelease.js +6 -2
  34. package/src/infrastructure/deploy/executeStagedDeployment.js +31 -0
  35. package/src/infrastructure/deploy/index.js +29 -0
  36. package/src/infrastructure/deploy/postgresBootstrap.js +79 -0
  37. package/src/infrastructure/deploy/reconcileDeployments.js +47 -0
  38. package/src/infrastructure/deploy/requestFromWorkload.js +30 -0
  39. package/src/infrastructure/deploy/verifyRuntimeCapabilities.js +34 -0
  40. package/src/infrastructure/management/kiosk/kiosk-browser.py +91 -0
  41. package/src/infrastructure/management/kiosk/kiosk-volume.sh +105 -0
  42. package/src/infrastructure/management/kiosk/listen.mjs.txt +14 -0
  43. package/src/infrastructure/management/kiosk/operateKiosk.js +74 -0
  44. package/src/infrastructure/management/kiosk/renderKioskResources.js +41 -0
  45. package/src/infrastructure/management/kiosk/shellArgument.js +4 -0
  46. package/src/infrastructure/management/kiosk/wait-x11.sh +1 -0
  47. package/src/infrastructure/management/kiosk/watchdog-liveness.sh +1 -0
  48. package/src/infrastructure/management/kiosk/watchdog-readiness.sh +1 -0
  49. package/src/infrastructure/management/kiosk/watchdog.sh +137 -0
  50. package/src/infrastructure/management/serveReconciliation.js +17 -0
  51. package/src/infrastructure/persistence/runtime/memoryDeliveryStore.js +186 -0
  52. package/src/infrastructure/persistence/runtime/spoolCodec.js +0 -27
  53. package/src/infrastructure/persistence/runtime/taskStateMemory.js +40 -0
  54. package/src/application/control/snapshotFile.js +0 -24
  55. package/src/infrastructure/persistence/runtime/deliverySpool.js +0 -86
  56. package/src/infrastructure/persistence/runtime/spoolCheckpoints.js +0 -65
  57. package/src/infrastructure/persistence/runtime/spoolDatabase.js +0 -69
  58. package/src/infrastructure/persistence/runtime/spoolFormat.js +0 -63
  59. package/src/infrastructure/persistence/runtime/spoolLimits.js +0 -8
  60. package/src/infrastructure/persistence/runtime/spoolMigration.js +0 -66
  61. package/src/infrastructure/persistence/runtime/spoolMutations.js +0 -19
  62. package/src/infrastructure/persistence/runtime/spoolProcess.js +0 -89
  63. package/src/infrastructure/persistence/runtime/spoolProcessChild.js +0 -32
  64. package/src/infrastructure/persistence/runtime/spoolRecords.js +0 -56
  65. package/src/infrastructure/persistence/runtime/spoolReplay.js +0 -55
  66. package/src/infrastructure/persistence/runtime/taskStateSqlite.js +0 -37
@@ -101,9 +101,14 @@ spec:
101
101
  {{- toYaml . | nindent 12 }}
102
102
  {{- end }}
103
103
  {{- end }}
104
- {{- if .hostDevices }}
104
+ {{- if or .hostDevices .readOnlyRootFilesystem }}
105
105
  securityContext:
106
+ {{- if .hostDevices }}
106
107
  privileged: true
108
+ {{- end }}
109
+ {{- if .readOnlyRootFilesystem }}
110
+ readOnlyRootFilesystem: true
111
+ {{- end }}
107
112
  {{- end }}
108
113
  {{- if or .hostDevices .volumeMounts }}
109
114
  volumeMounts:
@@ -87,6 +87,7 @@
87
87
  }
88
88
  }
89
89
  },
90
+ "readOnlyRootFilesystem": { "type": "boolean" },
90
91
  "hostDevices": {
91
92
  "type": "array",
92
93
  "uniqueItems": true,
@@ -0,0 +1,11 @@
1
+ #!/bin/sh
2
+ set -eu
3
+ hba="$PGDATA/pg_hba.conf"
4
+ awk '
5
+ /^# DSL target pod CIDRs/ { next }
6
+ $1 == "host" && $2 == "all" && $3 == "all" { next }
7
+ { print }
8
+ ' "$hba" > "$hba.dsl"
9
+ cat /pg-auth/pg_hba.conf.fragment >> "$hba.dsl"
10
+ cat "$hba.dsl" > "$hba"
11
+ rm -f "$hba.dsl"
@@ -0,0 +1,6 @@
1
+ #!/bin/sh
2
+ set -eu
3
+ if [ -f "$PGDATA/PG_VERSION" ]; then
4
+ /pg-auth/apply-hba.sh
5
+ fi
6
+ exec /usr/local/bin/docker-entrypoint.sh postgres
@@ -0,0 +1,18 @@
1
+ CREATE TABLE IF NOT EXISTS schema_migrations (
2
+ version TEXT PRIMARY KEY,
3
+ applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
4
+ );
5
+
6
+ DO $$
7
+ BEGIN
8
+ IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '@RUNTIME_ROLE@') THEN
9
+ CREATE ROLE @RUNTIME_ROLE@ NOLOGIN;
10
+ END IF;
11
+ END
12
+ $$;
13
+
14
+ ALTER TABLE IF EXISTS public.segments OWNER TO @RUNTIME_ROLE@;
15
+ ALTER TABLE IF EXISTS public.alerts OWNER TO @RUNTIME_ROLE@;
16
+ ALTER SEQUENCE IF EXISTS public.alerts_id_seq OWNER TO @RUNTIME_ROLE@;
17
+ ALTER TABLE IF EXISTS public.user_decisions OWNER TO @OWNER_ROLE@;
18
+ ALTER TABLE IF EXISTS public.schema_migrations OWNER TO @RUNTIME_ROLE@;
@@ -0,0 +1,3 @@
1
+ #!/bin/sh
2
+ set -eu
3
+ /pg-auth/apply-hba.sh
package/index.js CHANGED
@@ -158,3 +158,4 @@ export { default as prepareKubePrerequisites } from './src/infrastructure/deploy
158
158
  export { default as executeKubeSeed } from './src/infrastructure/deploy/executeKubeSeed.js';
159
159
  export { default as edgeTelemetryRuntime } from './src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js';
160
160
  export { default as kubeServiceAccount } from './src/infrastructure/management/kubeServiceAccount.js';
161
+ export * from './src/infrastructure/deploy/index.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.14.0",
3
+ "version": "2.16.0",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,7 +21,8 @@
21
21
  "./runtime": "./src/application/runtime/index.js",
22
22
  "./streams": "./src/infrastructure/streams/index.js",
23
23
  "./control": "./src/application/control/index.js",
24
- "./mdmesh": "./src/infrastructure/mdmesh/index.js"
24
+ "./mdmesh": "./src/infrastructure/mdmesh/index.js",
25
+ "./deployment": "./src/infrastructure/deploy/index.js"
25
26
  },
26
27
  "bin": {
27
28
  "modbus-to-mqtt": "./src/bin/modbus-to-mqtt.js",
@@ -1,7 +1,6 @@
1
1
  import executionSnapshot, { remoteSnapshot, remoteStatus } from './executionSnapshot.js';
2
2
  import localAssignment from './localAssignment.js';
3
3
  import { randomUUID } from 'node:crypto';
4
- import { checkSnapshot, loadSnapshot, saveSnapshot } from './snapshotFile.js';
5
4
  async function applyTasks(runtime,snapshot,nodeId,onError) {
6
5
  const ids=new Set(snapshot.assignments.map((row)=>{return row.taskId;}));
7
6
  const removals=runtime.status().tasks.filter((row)=>{return !ids.has(row.taskId);});
@@ -15,22 +14,19 @@ async function applyTasks(runtime,snapshot,nodeId,onError) {
15
14
  }
16
15
  return applied;
17
16
  }
18
- /** Control connectivity never determines whether the saved assignment may execute. */
19
- export default function assignmentAgent({ nodeId, file, store, runtime, validate, intervalMs = 5000, onError = () => {
17
+ /** Keep reconciling the current assignment when the controller is unavailable. */
18
+ export default function assignmentAgent({ nodeId, store, runtime, validate, intervalMs = 5000, onError = () => {
20
19
  // Optional diagnostic sink.
21
20
  } }) {
22
- if (!nodeId || !file) { throw new TypeError('Control node id and assignment file required'); }
21
+ if (!nodeId) { throw new TypeError('Control node id required'); }
23
22
  const state = { desired: null, appliedGeneration: null, stopped: false, timer: null, pending: null, sequence: 0, bootId: randomUUID() };
24
23
  // Serialized by tick and startup; mutations cannot overlap.
25
24
  /* eslint-disable require-atomic-updates */
26
- async function reconcile(input, restored = false) {
27
- checkSnapshot(input);
28
- await validate(remoteSnapshot(input));
29
- const snapshot = executionSnapshot(input, state.desired, runtime.status().tasks, restored);
30
- if (snapshot !== state.desired) {
31
- await saveSnapshot(file, snapshot);
32
- state.desired = snapshot;
33
- }
25
+ async function reconcile(input) {
26
+ const remote = remoteSnapshot(input);
27
+ await validate(remote);
28
+ const snapshot = executionSnapshot(remote, state.desired, runtime.status().tasks);
29
+ state.desired = snapshot;
34
30
  const applied=await applyTasks(runtime,snapshot,nodeId,onError);
35
31
  state.appliedGeneration=applied?snapshot.generation:null;
36
32
  }
@@ -51,8 +47,6 @@ export default function assignmentAgent({ nodeId, file, store, runtime, validate
51
47
  tick,
52
48
  status() { return { hasAssignment: Boolean(state.desired), appliedGeneration: state.appliedGeneration }; },
53
49
  async start({ waitForInitialTick = true } = {}) {
54
- const saved = await loadSnapshot(file);
55
- if (saved) { await reconcile(saved, true); }
56
50
  if (waitForInitialTick) { await tick(); } else { void tick().catch(onError); }
57
51
  state.timer = setInterval(() => { void tick(); }, intervalMs);
58
52
  },
@@ -1,4 +1,5 @@
1
1
  import schedule from './schedule.js';
2
+ import periodicReconciliation from './periodicReconciliation.js';
2
3
  export async function reconcile(store, nodeId, options = {}) {
3
4
  const token = await store.acquire(nodeId);
4
5
  if (!token) { return false; }
@@ -10,13 +11,5 @@ export async function reconcile(store, nodeId, options = {}) {
10
11
  export default function controlLoop(store, nodeId, { intervalMs = 5000, onError = () => {
11
12
  // Optional diagnostic sink.
12
13
  }, ...options } = {}) {
13
- let stopped = false;
14
- let pending = null;
15
- function tick() {
16
- pending ??= reconcile(store, nodeId, options).catch(onError).finally(() => { pending = null; });
17
- return pending;
18
- }
19
- const timer = setInterval(() => { if (!stopped) { void tick(); } }, intervalMs);
20
- void tick();
21
- return { tick, async stop() { stopped = true; clearInterval(timer); await pending; } };
14
+ return periodicReconciliation(() => { return reconcile(store, nodeId, options); }, { intervalMs, onError });
22
15
  }
@@ -1,5 +1,7 @@
1
- import { checkSnapshot } from './snapshotFile.js';
2
1
  export function remoteSnapshot(snapshot) {
2
+ if (!snapshot || !Number.isSafeInteger(snapshot.generation) || snapshot.generation < 0 || !Array.isArray(snapshot.assignments)) {
3
+ throw new TypeError('Invalid assignment snapshot');
4
+ }
3
5
  const remote = { ...snapshot };
4
6
  delete remote.localGeneration;
5
7
  delete remote.executionGenerations;
@@ -7,15 +9,12 @@ export function remoteSnapshot(snapshot) {
7
9
  }
8
10
  function epoch(snapshot) { return snapshot?.controlEpoch ?? 'initial'; }
9
11
  /** Local runtime generations remain monotonic even when an operator restores etcd. */
10
- export default function executionSnapshot(snapshot, previous, tasks, restored = false) {
11
- checkSnapshot(snapshot);
12
- const remote = remoteSnapshot(snapshot);
12
+ export default function executionSnapshot(remote, previous, tasks) {
13
13
  if (previous && epoch(previous) === epoch(remote)) {
14
14
  if (remote.generation < previous.generation) { throw new Error('Stale assignment snapshot'); }
15
15
  if (remote.generation === previous.generation && JSON.stringify(remote) !== JSON.stringify(remoteSnapshot(previous))) { throw new Error('Conflicting assignment snapshot'); }
16
16
  if (remote.generation === previous.generation) { return previous; }
17
17
  }
18
- if (restored && Number.isSafeInteger(snapshot.localGeneration) && snapshot.executionGenerations) { return snapshot; }
19
18
  const localGeneration = Math.max(previous?.localGeneration ?? 0, remote.generation, ...tasks.map((row) => { return row.generation ?? 0; })) + 1;
20
19
  const executionGenerations = Object.fromEntries(remote.assignments.map((row) => {
21
20
  const prior = previous?.assignments.find((item) => { return item.taskId === row.taskId; });
@@ -0,0 +1,19 @@
1
+ /** Run one reconciliation at a time, starting immediately. */
2
+ export default function periodicReconciliation(run, { intervalMs, onError }) {
3
+ const state = { stopped: false, pending: null };
4
+ function tick() {
5
+ if (state.stopped) { return state.pending; }
6
+ state.pending ??= Promise.resolve().then(run).catch(onError).finally(() => { state.pending = null; });
7
+ return state.pending;
8
+ }
9
+ const timer = setInterval(() => { void tick(); }, intervalMs);
10
+ void tick();
11
+ return {
12
+ tick,
13
+ async stop() {
14
+ state.stopped = true;
15
+ clearInterval(timer);
16
+ await state.pending;
17
+ }
18
+ };
19
+ }
@@ -0,0 +1,25 @@
1
+ /** Publish desired catalog independently of bootstrap; disconnected agents remain explicitly pending. */
2
+ export default async function publishControlCatalog(plan, store, publish, { now = Date.now, freshnessMs = 15000, clockSkewMs = 5000 } = {}) {
3
+ const result = await publish(store, plan.catalog);
4
+ const view = await store.read();
5
+ const nodes = plan.catalog.nodes.map(({ id }) => {
6
+ const assignment = view.assignments[id];
7
+ const report = view.reports.find((item) => { return item.nodeId === id; });
8
+ const epoch = plan.catalog.controlEpoch ?? 'initial';
9
+ const matching = assignment?.catalogVersion === plan.catalog.version
10
+ && (assignment?.controlEpoch ?? 'initial') === epoch
11
+ && (report?.controlEpoch ?? 'initial') === epoch;
12
+ const received = matching && (report?.receivedGeneration ?? report?.appliedGeneration) === assignment.generation;
13
+ const applied = received && report?.appliedGeneration === assignment.generation;
14
+ const errors = received ? (report.tasks ?? []).filter((task) => { return task.state === 'failed'; })
15
+ .map(({ taskId, state }) => { return { taskId, state }; }) : [];
16
+ let status = applied ? 'applied' : 'pending';
17
+ if (errors.length) { status = 'error'; }
18
+ const at = now();
19
+ const fresh = Number.isFinite(report?.receivedAt) && report.receivedAt <= at + clockSkewMs && at - report.receivedAt <= freshnessMs;
20
+ if (received && !fresh) { status = 'stale'; }
21
+ return { nodeId: id, status, errors,
22
+ desiredGeneration: assignment?.generation ?? null, appliedGeneration: report?.appliedGeneration ?? null };
23
+ });
24
+ return { ...result, nodes };
25
+ }
@@ -0,0 +1,10 @@
1
+ /** Publish a choice only if its observed revision still matches, then use the stored value. */
2
+ export default async function reconcileStoredChoice({ key, read, choose, compareAndSet }) {
3
+ const view = await read();
4
+ const previous = view.assignments[key] ?? {};
5
+ const next = choose(previous, view);
6
+ if (JSON.stringify(next) === JSON.stringify(previous)) { return { record: previous, view }; }
7
+ const committed = await compareAndSet(view.revisions[`assignments/${key}`], next);
8
+ if (!committed) { return { record: previous, view }; }
9
+ return { record: (await read()).assignments[key] ?? next, view };
10
+ }
@@ -0,0 +1,93 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ function endpoint(address, port) {
4
+ const host = address.includes(':') && !address.startsWith('[') ? `[${address}]` : address;
5
+ return `https://${host}:${port}`;
6
+ }
7
+
8
+ /** Derive etcd peer and client addresses from declared voting roles. */
9
+ export function etcdMembership(nodes, { clientPort, peerPort }) {
10
+ const voters = nodes.filter(({ voter }) => { return voter; });
11
+ return {
12
+ endpoints: voters.map(({ address }) => { return endpoint(address, clientPort); }).join(','),
13
+ initialCluster: voters.map(({ id, address }) => { return `${id}=${endpoint(address, peerPort)}`; }).join(',')
14
+ };
15
+ }
16
+
17
+ /** Build a stable catalog revision using exactly the scheduling inputs. */
18
+ export function versionedControlCatalog({ version, controlEpoch, nodes, tasks }) {
19
+ if (new Set(tasks.map(({ taskId }) => { return taskId; })).size !== tasks.length) {
20
+ throw new TypeError('Duplicate control task identity');
21
+ }
22
+ const content = { controlEpoch, nodes: nodes.map(({ id, capacity }) => { return { id, capacity }; }), tasks };
23
+ const digest = createHash('sha256').update(JSON.stringify(content)).digest('hex');
24
+ return { version: `${version}:${digest}`, ...content };
25
+ }
26
+
27
+ /** Validate the requests and limits object accepted by a Kubernetes chart. */
28
+ export function deploymentResources(value) {
29
+ if (value === undefined) { return; }
30
+ if (!value || typeof value !== 'object' || Array.isArray(value)
31
+ || ['requests', 'limits'].some((key) => {
32
+ return value[key] !== undefined && (!value[key] || typeof value[key] !== 'object' || Array.isArray(value[key]));
33
+ })) {
34
+ throw new TypeError('Invalid control resources');
35
+ }
36
+ }
37
+
38
+ function recoveryTimeout(value = 900000) {
39
+ if (!Number.isSafeInteger(value) || value < 1 || value > 2147483647) { throw new TypeError('Invalid collector recovery timeout'); }
40
+ return value;
41
+ }
42
+
43
+ function agentCapacity(config, node) {
44
+ if (node.agent !== undefined && (!node.agent || typeof node.agent !== 'object' || Array.isArray(node.agent))) {
45
+ throw new TypeError('Invalid collector capacity');
46
+ }
47
+ const result = {
48
+ storage: config.agentStorage, spoolMaxBytes: config.spoolMaxBytes, spoolMaxRecords: config.spoolMaxRecords,
49
+ recoveryTimeoutMs: config.recoveryTimeoutMs, resources: config.agentResources, ...node.agent
50
+ };
51
+ for (const key of ['spoolMaxBytes', 'spoolMaxRecords']) {
52
+ if (!Number.isSafeInteger(result[key]) || result[key] < 1) { throw new TypeError(`Invalid collector ${key}`); }
53
+ }
54
+ deploymentResources(result.resources);
55
+ if (result.heapMb !== undefined && (!Number.isSafeInteger(result.heapMb) || result.heapMb < 1)) {
56
+ throw new TypeError('Invalid collector heapMb');
57
+ }
58
+ return result;
59
+ }
60
+
61
+ function collectorStartupProbe(timeout) {
62
+ const periodSeconds = 5;
63
+ return {
64
+ httpGet: { path: '/startup', port: 9092 },
65
+ periodSeconds,
66
+ timeoutSeconds: 2,
67
+ failureThreshold: Math.ceil(timeout / (periodSeconds * 1000)) + 1
68
+ };
69
+ }
70
+
71
+ /** Render the standard SCADA collector agent runtime with caller-provided credential references. */
72
+ export function collectorControlDeployment(config, node, { endpoints, brokerEndpoints, hostDevices, deliverySecret, renderDeployment = false }) {
73
+ const capacity = agentCapacity(config, node);
74
+ const recoveryMs = recoveryTimeout(capacity.recoveryTimeoutMs);
75
+ return {
76
+ nodeId: node.id, renderDeployment, image: config.agentImage,
77
+ tlsSecret: node.clientTlsSecret ?? `${node.id}-control-client`,
78
+ authSecret: node.authSecret ?? `${node.id}-control-auth`,
79
+ authUsernameKey: config.authUsernameKey, authPasswordKey: config.authPasswordKey,
80
+ deliverySecret, storage: capacity.storage, resources: capacity.resources,
81
+ hostDevices, startupProbe: collectorStartupProbe(recoveryMs),
82
+ env: {
83
+ ...(capacity.heapMb !== undefined && { NODE_OPTIONS: `--max-old-space-size=${capacity.heapMb}` }),
84
+ COLLECTOR_RECOVERY_TIMEOUT_MS: String(recoveryMs), COLLECTOR_NODE_ID: node.id,
85
+ COLLECTOR_BROKER_ENDPOINTS: JSON.stringify(brokerEndpoints), COLLECTOR_CONTROL_ENDPOINTS: endpoints,
86
+ COLLECTOR_CONTROL_PREFIX: config.prefix, COLLECTOR_ASSIGNMENT_FILE: '/data/assignment.json',
87
+ COLLECTOR_CONTROL_CA: '/tls/ca.crt', COLLECTOR_CONTROL_CERT: '/tls/tls.crt', COLLECTOR_CONTROL_KEY: '/tls/tls.key',
88
+ COLLECTOR_HEALTH_HOST: '0.0.0.0', COLLECTOR_HEALTH_PORT: '9091', COLLECTOR_STARTUP_PORT: '9092',
89
+ COLLECTOR_LIVE_STALE_MS: '2147483647', COLLECTOR_SPOOL_DIR: '/data/spool',
90
+ COLLECTOR_SPOOL_MAX_BYTES: String(capacity.spoolMaxBytes), COLLECTOR_SPOOL_MAX_RECORDS: String(capacity.spoolMaxRecords)
91
+ }
92
+ };
93
+ }
@@ -0,0 +1,29 @@
1
+ function entries(configuration, plugins) {
2
+ if (!configuration || typeof configuration !== 'object' || Array.isArray(configuration)) {
3
+ throw new TypeError('Deployment commands must be a mapping');
4
+ }
5
+ return new Map(Object.entries(configuration).map(([name, declaration]) => {
6
+ const plugin = Object.hasOwn(plugins, declaration?.plugin) ? plugins[declaration.plugin] : undefined;
7
+ if (!plugin) { throw new TypeError(`Unknown deployment plugin for ${name}`); }
8
+ const methods = new Map(['plan', 'deploy'].filter((method) => {
9
+ return declaration[method] === true;
10
+ }).map((method) => {
11
+ if (typeof plugin[method] !== 'function') {
12
+ throw new TypeError(`Deployment plugin ${declaration.plugin} does not implement ${method}`);
13
+ }
14
+ return [method, plugin[method].bind(plugin)];
15
+ }));
16
+ if (!methods.size) { throw new TypeError(`Deployment command ${name} has no actions`); }
17
+ return [name, methods];
18
+ }));
19
+ }
20
+
21
+ /** Selects deployment ports from modules registered by the application. */
22
+ export default function deploymentCommands(configuration, plugins) {
23
+ const commands = entries(configuration, plugins);
24
+ return function run(name, method, options) {
25
+ const command = commands.get(name)?.get(method);
26
+ if (!command) { throw new TypeError(`Unsupported deployment command ${name} ${method}`); }
27
+ return command(options);
28
+ };
29
+ }
@@ -0,0 +1,84 @@
1
+ import { isIP } from 'node:net';
2
+ import expand from './expand.js';
3
+ import { releaseFor } from './releases.js';
4
+ import { serverFor } from './releaseNodes.js';
5
+
6
+ /** Resolve deployment inputs once for a plant module that builds chart values. */
7
+ export function deploymentContext(document, cluster) {
8
+ const expanded = expand(document);
9
+ const server = serverFor(expanded, cluster);
10
+ const profile = expanded.profiles[server.profile.id];
11
+ return { expanded, server, profile, ...releaseFor(expanded, server) };
12
+ }
13
+
14
+ /** Merge device mounts and assignments into one collector process for a node. */
15
+ export function collectorDeployment(processes, options) {
16
+ const { assignments, command, image, resources, environment, hostSecurity, healthPort = 9091 } = options;
17
+ if (!image) { throw new TypeError('Universal collector image required in DSL'); }
18
+ if (!processes.length) { return []; }
19
+ const hostDevices = [...new Set(processes.flatMap((process) => { return process.hostDevices ?? []; }))].sort();
20
+ return [{
21
+ name: 'collector',
22
+ adapter: 'collector',
23
+ health: { port: healthPort },
24
+ command,
25
+ image,
26
+ resources,
27
+ hostDevices,
28
+ ...(hostDevices.length && hostSecurity && { podSecurityContext: hostSecurity }),
29
+ env: {
30
+ ...environment,
31
+ COLLECTOR_HEALTH_PORT: String(healthPort),
32
+ COLLECTOR_HEALTH_HOST: '0.0.0.0',
33
+ COLLECTOR_LIVE_STALE_MS: '2147483647',
34
+ COLLECTOR_MANIFEST: JSON.stringify({ assignments })
35
+ }
36
+ }];
37
+ }
38
+
39
+ /** Convert predecessor names into exact workload and label bindings. */
40
+ export function retiredDeployments({ prefix, groups, desired = [], extra = [] }) {
41
+ const retired = new Set();
42
+ const replacements = groups.flatMap((names) => {
43
+ if (!Array.isArray(names)) { throw new TypeError('invalid replacement list'); }
44
+ return names.map((name) => {
45
+ if (typeof name !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(name)
46
+ || retired.has(name) || desired.some((item) => { return item.name === name; })) {
47
+ throw new TypeError('invalid replacement deployment');
48
+ }
49
+ retired.add(name);
50
+ return { workload: `deployment/${prefix}-${name}`, selector: `app=${name}` };
51
+ });
52
+ });
53
+ return [...replacements, ...extra.map(({ name, label }) => {
54
+ return { workload: `deployment/${prefix}-${name}`, selector: `app=${label}` };
55
+ })];
56
+ }
57
+
58
+ /** Bind a release target and default chart values across a sequence of stages. */
59
+ export function stageFor(common, values) {
60
+ return (id, fragment, workloads) => {
61
+ return { ...common, id, values: { ...values, ...fragment }, workloads };
62
+ };
63
+ }
64
+
65
+ /** Generate a node-port service and its peer-scoped ingress policy. */
66
+ export function peerNodePort({ name, namespace, selector, peerAddresses, portName, port, nodePort, additionalPorts = [], namespacePeers = [] }) {
67
+ if (!selector || !Object.keys(selector).length) { throw new TypeError('NodePort workload selector is required'); }
68
+ const metadata = { name, namespace };
69
+ const service = { apiVersion: 'v1', kind: 'Service', metadata, spec: {
70
+ type: 'NodePort', externalTrafficPolicy: 'Local', selector, ports: [{ name: portName, port, targetPort: port, nodePort }]
71
+ } };
72
+ const peers = [...namespacePeers.map((namespaceSelector) => { return { namespaceSelector }; }),
73
+ ...peerAddresses.map((address) => {
74
+ if (isIP(address) !== 4) { throw new TypeError('Peer ingress requires an IPv4 address'); }
75
+ return { ipBlock: { cidr: `${address}/32` } };
76
+ })];
77
+ const ingress = [
78
+ ...(peers.length ? [{ from: peers, ports: [{ protocol: 'TCP', port }] }] : []),
79
+ ...(additionalPorts.length ? [{ ports: additionalPorts.map((number) => { return { protocol: 'TCP', port: number }; }) }] : [])
80
+ ];
81
+ return [service, { apiVersion: 'networking.k8s.io/v1', kind: 'NetworkPolicy', metadata, spec: {
82
+ podSelector: { matchLabels: selector }, policyTypes: ['Ingress'], ingress
83
+ } }];
84
+ }
@@ -0,0 +1,28 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import readDocument from './readDocument.js';
5
+
6
+ /** Load one deployment document and resolve its includes beside the root document. */
7
+ export default function readDocumentFile(file, parse = readDocument) {
8
+ const path = file instanceof URL ? fileURLToPath(file) : file;
9
+ const directory = dirname(path);
10
+ return parse(readFileSync(path, 'utf8'), (name) => {
11
+ return readFileSync(join(directory, name), 'utf8');
12
+ });
13
+ }
14
+
15
+ /** Apply only declared boolean options when a deployment document selects a phase. */
16
+ export function selectDeploymentPhase(document, { selection, section, fields, label = section }) {
17
+ if (document[selection] === undefined) { return document; }
18
+ const configuration = document[section];
19
+ const phases = configuration?.phases;
20
+ const name = document[selection];
21
+ const selected = phases && Object.hasOwn(phases, name) ? phases[name] : undefined;
22
+ if (!selected || typeof selected !== 'object' || Array.isArray(selected)
23
+ || fields.some((field) => { return !Object.hasOwn(selected, field); })
24
+ || Object.entries(selected).some(([key, value]) => { return !fields.includes(key) || typeof value !== 'boolean'; })) {
25
+ throw new TypeError(`Invalid ${label} phase`);
26
+ }
27
+ return { ...document, [section]: { ...configuration, ...selected } };
28
+ }
@@ -94,6 +94,19 @@ function scadaRelease(document, server, profile, edges) {
94
94
  return withFlows(withProcess(values, profile, server), owned, routes, buses);
95
95
  }
96
96
 
97
+ /** Build the release values for a concrete server in an already expanded document. */
98
+ export function releaseFor(expanded, host) {
99
+ const links = edgesOf(expanded);
100
+ const profile = profileFor(expanded, host);
101
+ assertHeld(expanded, links);
102
+ return frozen({
103
+ ...(expanded.hmi !== undefined && { hmi: expanded.hmi }),
104
+ ...(profile.target && { target: profile.target }),
105
+ apps: passedApps(profile),
106
+ scada: scadaRelease(expanded, host, profile, links)
107
+ });
108
+ }
109
+
97
110
  /**
98
111
  * Cuts one cluster out of a system document.
99
112
  *
@@ -105,14 +118,5 @@ function scadaRelease(document, server, profile, edges) {
105
118
  */
106
119
  export default function releases(document, cluster) {
107
120
  const expanded = expand(document);
108
- const host = serverFor(expanded, cluster);
109
- const links = edgesOf(expanded);
110
- const profile = profileFor(expanded, host);
111
- assertHeld(expanded, links);
112
- return frozen({
113
- ...(expanded.hmi !== undefined && { hmi: expanded.hmi }),
114
- ...(profile.target && { target: profile.target }),
115
- apps: passedApps(profile),
116
- scada: scadaRelease(expanded, host, profile, links)
117
- });
121
+ return releaseFor(expanded, serverFor(expanded, cluster));
118
122
  }
@@ -5,7 +5,7 @@ function settings(options) {
5
5
  if (options.groupCommit !== undefined && (!options.groupCommit || typeof options.groupCommit !== 'object' || Array.isArray(options.groupCommit))) {
6
6
  throw new TypeError('groupCommit must be an object');
7
7
  }
8
- const { maxRecords = 64, maxBytes = 1048576, maxDelayMs = 25 } = options.groupCommit ?? {};
8
+ const { maxRecords = 64, maxBytes = 1048576, maxDelayMs = 0 } = options.groupCommit ?? {};
9
9
  const group = { maxRecords, maxBytes, maxDelayMs };
10
10
  const config = { ...group, maxOperations: options.maxOperations ?? 128, maxPendingBytes: options.maxPendingBytes ?? 4194304 };
11
11
  Object.entries(config).forEach(([name, value]) => { positive(value, name, name === 'maxDelayMs'); });
@@ -27,7 +27,10 @@ export default function deliveryOperations(apply, options = {}) {
27
27
  state.operations += 1;
28
28
  return true;
29
29
  }
30
- function wait() { return new Promise((resolve) => { waiters.push(resolve); }); }
30
+ function wait() {
31
+ if (waiters.length >= config.maxOperations) { return Promise.reject(new Error('Delivery operation capacity exceeded')); }
32
+ return new Promise((resolve) => { waiters.push(resolve); });
33
+ }
31
34
  function notifyIdle() {
32
35
  if (!state.operations && !state.running && !waiters.length) { state.wake?.(); Object.assign(state, { idle: null, wake: null }); }
33
36
  }
@@ -117,7 +120,7 @@ export default function deliveryOperations(apply, options = {}) {
117
120
  if (occupy()) {
118
121
  try { return hold(build).commit(); } catch (error) { return Promise.reject(error); }
119
122
  }
120
- return wait().then(() => { return hold(build).commit(); });
123
+ return Promise.reject(new Error('Delivery operation capacity exceeded'));
121
124
  },
122
125
  barrier(action) {
123
126
  if (occupy()) { return enqueue({ kind: 'barrier', action, bytes: 0 }); }
@@ -1,14 +1,17 @@
1
- /** A slot and its prospective durable receipt stay reserved until the actual writer settles. */
1
+ /** A slot and its prospective receipt stay reserved until the actual writer settles. */
2
2
  /* eslint max-lines-per-function: ["error", 80], max-statements: ["error", 25] */
3
3
  export default function deliveryPublications(commands, sessions, options) {
4
4
  const limit = options.maxInFlight ?? 32;
5
5
  if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive safe maxInFlight required'); }
6
- const active = new Map();
6
+ const active = new Set();
7
+ function keyOf(record, id) { return JSON.stringify([record.event.eventId, id, record.admission]); }
7
8
  function publish(record, id) {
8
- const key = JSON.stringify([record.event.eventId, id]);
9
+ const key = keyOf(record, id);
9
10
  if (active.has(key) || active.size >= limit) { throw new Error('Delivery publication capacity exceeded'); }
10
- const settled = Promise.resolve(commands.prepare((checkBytes) => {
11
- const operation = { kind: 'ack', eventId: record.event.eventId, recipient: id };
11
+ active.add(key);
12
+ let started = false;
13
+ return Promise.resolve(commands.prepare((checkBytes) => {
14
+ const operation = { kind: 'ack', eventId: record.event.eventId, recipient: id, ...(record.admission !== undefined && { admission: record.admission }) };
12
15
  const bytes = Buffer.byteLength(JSON.stringify(operation));
13
16
  const retainedBytes = Buffer.byteLength(JSON.stringify(record.event));
14
17
  checkBytes(bytes, retainedBytes); return { operation, bytes, retainedBytes };
@@ -19,18 +22,17 @@ export default function deliveryPublications(commands, sessions, options) {
19
22
  const event = record.event.observation;
20
23
  write = sessions.write(descriptor, { ...event, options: { ...event.options, persistent: true, mandatory: true, messageId: event.eventId } });
21
24
  } catch (error) { receipt.cancel(); throw error; }
25
+ started = true;
22
26
  const receiptLife = write.settled.then(() => { return receipt.commit(); }, (error) => { receipt.cancel(); throw error; })
23
27
  .finally(() => { active.delete(key); });
24
28
  void receiptLife.catch(() => {
25
29
  // The caller reports failures; late rejection still releases only the actual reservation.
26
30
  });
27
31
  return write.result.then(() => { return receiptLife; });
32
+ }).catch((error) => {
33
+ if (!started) { active.delete(key); }
34
+ throw error;
28
35
  });
29
- active.set(key, settled);
30
- void settled.catch(() => {
31
- // Prepare admission failures still release the publication slot.
32
- });
33
- return settled.finally(() => { active.delete(key); });
34
36
  }
35
- return { publish, limit };
37
+ return { publish, limit, available(record, id) { return active.size < limit && !active.has(keyOf(record, id)); } };
36
38
  }
@@ -1,4 +1,4 @@
1
- import spoolProcess from '../../infrastructure/persistence/runtime/spoolProcess.js';
1
+ import memoryDeliveryStore from '../../infrastructure/persistence/runtime/memoryDeliveryStore.js';
2
2
  import deliverySessions from './deliverySessions.js';
3
3
  import deliveryOperations from './deliveryOperations.js';
4
4
  import deliveryPublications from './deliveryPublications.js';
@@ -10,8 +10,8 @@ function snapshot(operation, checkBytes) {
10
10
  return { operation: frozen, bytes: Buffer.byteLength(JSON.stringify(frozen)) };
11
11
  }
12
12
  /* eslint max-lines-per-function: ["error", 125], max-statements: ["error", 25] */
13
- /** Node-owned queue: every point/receipt resolves only after its grouped FULL commit. */
14
- export default function deliveryQueue(directory, options, spool = spoolProcess(directory, options)) {
13
+ /** Node-owned delivery using an injectable store and bounded publication sessions. */
14
+ export default function deliveryQueue(options, spool = memoryDeliveryStore(options)) {
15
15
  const commands = deliveryOperations((operations) => { return spool.mutateMany(operations); }, options);
16
16
  const sessions = deliverySessions(options.factory, options.writeTimeoutMs);
17
17
  const batchSize = options.batchSize ?? 100;
@@ -45,7 +45,8 @@ export default function deliveryQueue(directory, options, spool = spoolProcess(d
45
45
  receipts.add(receipt);
46
46
  }
47
47
  async function advance(row, id) {
48
- if (!state.closed && (blocked.get(row.targets[id]) ?? -Infinity) <= clock()) { receive(row, id); }
48
+ if (!state.closed && publications.available(row, id) && (blocked.get(row.targets[id]) ?? -Infinity) <= clock()
49
+ && (spool.hasAdmission?.(row.event.eventId, row.admission, id) ?? true)) { receive(row, id); }
49
50
  if (receipts.size >= receiptWindow) { await Promise.race(receipts); }
50
51
  }
51
52
  try {
@@ -8,5 +8,4 @@ export { default as taskQueue } from './taskQueue.js';
8
8
  export { default as createRegistry } from './createRegistry.js';
9
9
  export { default as resolveSecrets } from './resolveSecrets.js';
10
10
  export { default as taskStatePg } from '../../infrastructure/persistence/runtime/taskStatePg.js';
11
- export { default as taskStateSqlite } from '../../infrastructure/persistence/runtime/taskStateSqlite.js';
12
11
  export { default as spooledOutput, amqpDestinations } from './spooledOutput.js';