@yarkivaev/scada 2.5.7 → 2.6.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 (107) hide show
  1. package/README.md +136 -2
  2. package/charts/scada/templates/_helpers.tpl +18 -3
  3. package/charts/scada/templates/postgres.yaml +6 -0
  4. package/charts/scada/templates/rabbitmq-config.yaml +5 -1
  5. package/charts/scada/templates/rabbitmq.yaml +12 -1
  6. package/charts/scada/templates/supervisor-sink.yaml +5 -0
  7. package/charts/scada/values.schema.json +46 -1
  8. package/charts/scada/values.yaml +7 -0
  9. package/db/migrations/E0005__historical_telemetry_grants.sql +5 -0
  10. package/db/migrations/E0006__historical_telemetry.sql +64 -0
  11. package/db/migrations/E0007__metric_receipts.sql +7 -0
  12. package/db/migrations/E0008__metric_receipts_grants.sql +1 -0
  13. package/db/migrations/E0009__history_continuation.sql +20 -0
  14. package/db/migrations/E0010__history_admissions.sql +8 -0
  15. package/db/migrations/E0011__history_classifier_checkpoints.sql +18 -0
  16. package/db/migrations/E0012__external_history_grants.sql +4 -0
  17. package/db/migrations/E0013__history_staged_corrections.sql +104 -0
  18. package/db/migrations/E0014__history_correction_grants.sql +5 -0
  19. package/db/migrations/E0015__history_retention_frontier.sql +7 -0
  20. package/db/migrations/E0016__history_retention_grants.sql +1 -0
  21. package/index.js +7 -0
  22. package/package.json +5 -3
  23. package/src/application/control/agent.js +61 -0
  24. package/src/application/control/catalog.js +22 -0
  25. package/src/application/control/controlClient.js +75 -0
  26. package/src/application/control/controlStore.js +55 -0
  27. package/src/application/control/controller.js +22 -0
  28. package/src/application/control/executionSnapshot.js +32 -0
  29. package/src/application/control/index.js +7 -0
  30. package/src/application/control/localAssignment.js +13 -0
  31. package/src/application/control/schedule.js +103 -0
  32. package/src/application/control/snapshotFile.js +24 -0
  33. package/src/application/foldedMetricsSink.js +1 -0
  34. package/src/application/mcp/mcpResources.js +1 -1
  35. package/src/application/mcp/mcpSchema.js +8 -3
  36. package/src/application/runtime/additionalAdapters.js +13 -9
  37. package/src/application/runtime/deliveryQueue.js +62 -0
  38. package/src/application/runtime/deliverySessions.js +28 -0
  39. package/src/application/runtime/modbusDelivery.js +36 -0
  40. package/src/application/runtime/pipelineAdapters.js +12 -8
  41. package/src/application/runtime/queuedDelivery.js +25 -0
  42. package/src/application/runtime/runCollector.js +34 -3
  43. package/src/application/runtime/runtime.js +2 -2
  44. package/src/application/runtime/runtimeHealth.js +1 -1
  45. package/src/application/runtime/runtimeServices.js +6 -2
  46. package/src/application/runtime/streamTask.js +13 -4
  47. package/src/application/runtime/taskContext.js +1 -0
  48. package/src/application/runtime/taskSlot.js +2 -2
  49. package/src/application/runtime/telemetrySink.js +18 -0
  50. package/src/application/siteServer.js +19 -4
  51. package/src/application/siteTelemetry.js +2 -2
  52. package/src/application/supervisorSink.js +32 -12
  53. package/src/application/sync/siteSyncBind.js +2 -2
  54. package/src/bin/controller.js +8 -0
  55. package/src/infrastructure/http/edge/edgeApi.js +2 -0
  56. package/src/infrastructure/http/edge/routes/history/historyRoutes.js +33 -0
  57. package/src/infrastructure/http/plant/routes/measurementRead.js +3 -0
  58. package/src/infrastructure/ingest/db/migrate.js +16 -0
  59. package/src/infrastructure/ingest/db/migrationProfile.js +6 -1
  60. package/src/infrastructure/ingest/db/retainMetricReceipts.js +8 -0
  61. package/src/infrastructure/ingest/db/runRetention.js +2 -0
  62. package/src/infrastructure/ingest/mqtt/metricsTransformer.js +11 -2
  63. package/src/infrastructure/ingest/mqtt/modbusMqtt.js +1 -1
  64. package/src/infrastructure/ingest/mqtt/modbusPublish.js +2 -0
  65. package/src/infrastructure/ingest/mqtt/mqttMetrics.js +1 -1
  66. package/src/infrastructure/ingest/telemetry/amqpMetricsIngest.js +7 -3
  67. package/src/infrastructure/ingest/telemetry/centralEnvelope.js +46 -0
  68. package/src/infrastructure/ingest/telemetry/centralMetricsSink.js +64 -0
  69. package/src/infrastructure/ingest/telemetry/centralPoint.js +14 -0
  70. package/src/infrastructure/ingest/telemetry/centralPolicy.js +51 -0
  71. package/src/infrastructure/ingest/telemetry/centralQueueSession.js +29 -0
  72. package/src/infrastructure/ingest/telemetry/centralTelemetryPreflight.js +31 -0
  73. package/src/infrastructure/ingest/telemetry/foldingSink.js +3 -0
  74. package/src/infrastructure/ingest/telemetry/historyTelemetry.js +32 -0
  75. package/src/infrastructure/persistence/clickhouse/canonicalMetrics.js +26 -0
  76. package/src/infrastructure/persistence/clickhouse/changes.js +4 -2
  77. package/src/infrastructure/persistence/clickhouse/connection.js +6 -8
  78. package/src/infrastructure/persistence/clickhouse/holds.js +10 -7
  79. package/src/infrastructure/persistence/clickhouse/latest.js +1 -1
  80. package/src/infrastructure/persistence/clickhouse/metricsQuery.js +70 -0
  81. package/src/infrastructure/persistence/clickhouse/metricsRelation.js +110 -0
  82. package/src/infrastructure/persistence/clickhouse/nativeMetricPoints.js +26 -0
  83. package/src/infrastructure/persistence/clickhouse/nativeMetricsAdmission.js +91 -0
  84. package/src/infrastructure/persistence/clickhouse/nativeMetricsClock.js +9 -0
  85. package/src/infrastructure/persistence/clickhouse/nativeMetricsCompaction.js +82 -0
  86. package/src/infrastructure/persistence/clickhouse/nativeMetricsInsert.js +31 -0
  87. package/src/infrastructure/persistence/clickhouse/nativeMetricsOwnership.js +8 -0
  88. package/src/infrastructure/persistence/clickhouse/nativeMetricsSchema.js +44 -0
  89. package/src/infrastructure/persistence/clickhouse/pollTopicCursors.js +3 -1
  90. package/src/infrastructure/persistence/clickhouse/rises.js +4 -2
  91. package/src/infrastructure/persistence/clickhouse/samples.js +10 -0
  92. package/src/infrastructure/persistence/clickhouse/sensor.js +4 -0
  93. package/src/infrastructure/persistence/clickhouse/series.js +38 -21
  94. package/src/infrastructure/persistence/pg/history.js +169 -0
  95. package/src/infrastructure/persistence/pg/historyAdmission.js +81 -0
  96. package/src/infrastructure/persistence/pg/historyCheckpoint.js +56 -0
  97. package/src/infrastructure/persistence/pg/historyConfigure.js +28 -0
  98. package/src/infrastructure/persistence/pg/historyContext.js +65 -0
  99. package/src/infrastructure/persistence/pg/historyCorrection.js +34 -0
  100. package/src/infrastructure/persistence/pg/historyObservations.js +56 -0
  101. package/src/infrastructure/persistence/pg/historySeed.js +27 -0
  102. package/src/infrastructure/persistence/pg/metrics.js +5 -4
  103. package/src/infrastructure/persistence/pg/metricsInsertSql.js +12 -0
  104. package/src/infrastructure/persistence/runtime/deliverySpool.js +124 -0
  105. package/src/infrastructure/persistence/stateDataFromPool.js +2 -0
  106. package/src/infrastructure/streams/amqpSink/session.js +6 -0
  107. package/src/infrastructure/streams/amqpSource.js +17 -4
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.5.7",
3
+ "version": "2.6.0",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -19,12 +19,14 @@
19
19
  "./opcua": "./src/infrastructure/opcua/index.js",
20
20
  "./opcua/config": "./src/infrastructure/opcua/config.js",
21
21
  "./runtime": "./src/application/runtime/index.js",
22
- "./streams": "./src/infrastructure/streams/index.js"
22
+ "./streams": "./src/infrastructure/streams/index.js",
23
+ "./control": "./src/application/control/index.js"
23
24
  },
24
25
  "bin": {
25
26
  "modbus-to-mqtt": "./src/bin/modbus-to-mqtt.js",
26
27
  "supervisor-sink": "./src/bin/supervisor-sink.js",
27
- "scada-collector": "./src/bin/collector.js"
28
+ "scada-collector": "./src/bin/collector.js",
29
+ "scada-controller": "./src/bin/controller.js"
28
30
  },
29
31
  "scripts": {
30
32
  "test": "mocha --exit 'test/**/test*.js'",
@@ -0,0 +1,61 @@
1
+ import executionSnapshot, { remoteSnapshot, remoteStatus } from './executionSnapshot.js';
2
+ import localAssignment from './localAssignment.js';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { checkSnapshot, loadSnapshot, saveSnapshot } from './snapshotFile.js';
5
+ async function applyTasks(runtime,snapshot,nodeId,onError) {
6
+ const ids=new Set(snapshot.assignments.map((row)=>{return row.taskId;}));
7
+ const removals=runtime.status().tasks.filter((row)=>{return !ids.has(row.taskId);});
8
+ const operations=[...removals.map((row)=>{return ()=>{return runtime.remove({taskId:row.taskId,generation:Math.max(snapshot.localGeneration,row.generation??0)});};}),
9
+ ...snapshot.assignments.map((row)=>{return ()=>{return runtime.apply(localAssignment({...row,generation:snapshot.executionGenerations[row.taskId]},nodeId));};})];
10
+ let applied=true;
11
+ for (const operation of operations) {
12
+ // One unavailable source must not prevent independent assignments from starting.
13
+ // eslint-disable-next-line no-await-in-loop
14
+ try {await operation();} catch(error) {applied=false; onError(error);}
15
+ }
16
+ return applied;
17
+ }
18
+ /** Control connectivity never determines whether the saved assignment may execute. */
19
+ export default function assignmentAgent({ nodeId, file, store, runtime, validate, intervalMs = 5000, onError = () => {
20
+ // Optional diagnostic sink.
21
+ } }) {
22
+ if (!nodeId || !file) { throw new TypeError('Control node id and assignment file required'); }
23
+ const state = { desired: null, appliedGeneration: null, stopped: false, timer: null, pending: null, sequence: 0, bootId: randomUUID() };
24
+ // Serialized by tick and startup; mutations cannot overlap.
25
+ /* 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
+ }
34
+ const applied=await applyTasks(runtime,snapshot,nodeId,onError);
35
+ state.appliedGeneration=applied?snapshot.generation:null;
36
+ }
37
+ async function once() {
38
+ if (state.stopped) { return; }
39
+ let snapshot=state.desired;
40
+ try {snapshot=await store.assignment(nodeId)??snapshot;} catch(error) {onError(error);}
41
+ try {if(!state.stopped&&snapshot){await reconcile(snapshot);}} catch(error) {onError(error);}
42
+ try {
43
+ if (!state.stopped) { state.sequence += 1; await store.report(nodeId, { nodeId, bootId: state.bootId, sequence: state.sequence, receivedAt: Date.now(), receivedGeneration: state.desired?.generation ?? null, appliedGeneration: state.appliedGeneration, controlEpoch: state.desired?.controlEpoch ?? 'initial', ...remoteStatus(runtime.status(), state.desired) }); }
44
+ } catch (error) { onError(error); }
45
+ }
46
+ function tick() {
47
+ state.pending ??= once().finally(() => { state.pending = null; });
48
+ return state.pending;
49
+ }
50
+ return {
51
+ tick,
52
+ status() { return { hasAssignment: Boolean(state.desired), appliedGeneration: state.appliedGeneration }; },
53
+ async start({ waitForInitialTick = true } = {}) {
54
+ const saved = await loadSnapshot(file);
55
+ if (saved) { await reconcile(saved, true); }
56
+ if (waitForInitialTick) { await tick(); } else { void tick().catch(onError); }
57
+ state.timer = setInterval(() => { void tick(); }, intervalMs);
58
+ },
59
+ async stop() { state.stopped = true; clearInterval(state.timer); await state.pending; }
60
+ };
61
+ }
@@ -0,0 +1,22 @@
1
+ const identifier = /^[\w.:-]{1,200}$/u;
2
+ export default function validateCatalog(catalog) {
3
+ if (!catalog || typeof catalog.version !== 'string' || (catalog.controlEpoch !== undefined && (typeof catalog.controlEpoch !== 'string' || !catalog.controlEpoch.length)) || !Array.isArray(catalog.nodes) || !Array.isArray(catalog.tasks)) {
4
+ throw new TypeError('Invalid control catalog');
5
+ }
6
+ const nodes = new Set();
7
+ for (const node of catalog.nodes) {
8
+ if (typeof node.id !== 'string' || !identifier.test(node.id) || nodes.has(node.id) || !Number.isFinite(node.capacity) || node.capacity <= 0) { throw new TypeError('Invalid control node'); }
9
+ nodes.add(node.id);
10
+ }
11
+ const tasks = new Set();
12
+ for (const task of catalog.tasks) {
13
+ if (typeof task.taskId !== 'string' || tasks.has(task.taskId) || !task.spec?.adapter || !Number.isSafeInteger(task.copies ?? 2) || (task.copies ?? 2) < 1
14
+ || !Number.isFinite(task.cost ?? 1) || (task.cost ?? 1) <= 0 || (task.pinnedNode && !nodes.has(task.pinnedNode))
15
+ || (task.eligibleNodes && (!Array.isArray(task.eligibleNodes) || task.eligibleNodes.some((id) => { return !nodes.has(id); })))) {
16
+ throw new TypeError('Invalid control task');
17
+ }
18
+ if ((task.spec.adapter === 'serial' || String(task.spec.from ?? '').startsWith('rtu:')) && !task.pinnedNode) { throw new TypeError('Serial task requires pinnedNode'); }
19
+ tasks.add(task.taskId);
20
+ }
21
+ return catalog;
22
+ }
@@ -0,0 +1,75 @@
1
+ import http from 'node:http';
2
+ import https from 'node:https';
3
+ import { readFileSync } from 'node:fs';
4
+ function request(endpoint, route, body, options) {
5
+ return new Promise((resolve, reject) => {
6
+ const target = new URL(route, endpoint);
7
+ const transport = target.protocol === 'https:' ? https : http;
8
+ const req = transport.request(target, { method: 'POST', ...options.tls, headers: { 'content-type': 'application/json', ...(options.token && { Authorization: options.token }) } }, (res) => {
9
+ const chunks = [];
10
+ let bytes = 0;
11
+ res.on('data', (chunk) => {
12
+ bytes += chunk.length;
13
+ if (bytes > options.maxBytes) { req.destroy(new Error('Control response capacity exceeded')); } else { chunks.push(chunk); }
14
+ });
15
+ res.on('error', reject);
16
+ res.on('end', () => {
17
+ try {
18
+ const value = JSON.parse(Buffer.concat(chunks).toString());
19
+ if (res.statusCode !== 200 || value.error) { const error = new Error('Control request rejected'); error.gatewayCode = value.code; error.statusCode = res.statusCode; reject(error); } else { resolve(value); }
20
+ } catch { reject(new Error('Invalid control response')); }
21
+ });
22
+ });
23
+ const timer = setTimeout(() => { req.destroy(new Error('Control request deadline')); }, options.timeoutMs);
24
+ req.on('error', reject);
25
+ req.on('close', () => { clearTimeout(timer); });
26
+ req.end(JSON.stringify(body));
27
+ });
28
+ }
29
+ function authenticated(send, username, password) {
30
+ const state = { token: null, expiresAt: 0, pending: null };
31
+ function token() {
32
+ if (state.token && Date.now() < state.expiresAt) { return state.token; }
33
+ state.pending ??= send('/v3/auth/authenticate', { name: username, password }).then((result) => {
34
+ if (typeof result.token !== 'string' || !result.token) { throw new Error('Control authentication rejected'); }
35
+ Object.assign(state, { token: result.token, expiresAt: Date.now() + 60000 });
36
+ return result.token;
37
+ }).finally(() => { state.pending = null; });
38
+ return state.pending;
39
+ }
40
+ return async (route, body) => {
41
+ const current = await token();
42
+ try { return await send(route, body, current); } catch (error) {
43
+ if (Number(error.gatewayCode) !== 16 && error.statusCode !== 401) { throw error; }
44
+ if (state.token === current) { Object.assign(state, { token: null, expiresAt: 0 }); }
45
+ return send(route, body, await token());
46
+ }
47
+ };
48
+ }
49
+ export default function controlClient({ endpoints, timeoutMs = 2000, maxBytes = 8388608, tls = {}, username, password }) {
50
+ if (!Array.isArray(endpoints) || !endpoints.length || endpoints.some((endpoint) => { return !['http:', 'https:'].includes(new URL(endpoint).protocol); })) { throw new TypeError('Control endpoints required'); }
51
+ if ((username !== undefined || password !== undefined) && (typeof username !== 'string' || !username || typeof password !== 'string' || !password)) {
52
+ throw new TypeError('Complete control credentials required');
53
+ }
54
+ let cursor = 0;
55
+ async function send(route, body, token) {
56
+ for (let index = 0; index < endpoints.length; index += 1) {
57
+ try {
58
+ // eslint-disable-next-line no-await-in-loop
59
+ return await request(endpoints[cursor], route, body, { timeoutMs, maxBytes, tls, token });
60
+ } catch (error) {
61
+ cursor = (cursor + 1) % endpoints.length;
62
+ if (index === endpoints.length - 1) { throw error; }
63
+ }
64
+ }
65
+ throw new Error('No control endpoints');
66
+ }
67
+ return username === undefined ? send : authenticated(send, username, password);
68
+ }
69
+ export function clientFromEnv(env, prefix = 'CONTROL') {
70
+ const tls = {};
71
+ for (const [name, key] of [['CA', 'ca'], ['CERT', 'cert'], ['KEY', 'key']]) {
72
+ if (env[`${prefix}_${name}`]) { tls[key] = readFileSync(env[`${prefix}_${name}`]); }
73
+ }
74
+ return controlClient({ endpoints: (env[`${prefix}_ENDPOINTS`] ?? '').split(',').filter(Boolean), tls, username: env[`${prefix}_USERNAME`], password: env[`${prefix}_PASSWORD`] });
75
+ }
@@ -0,0 +1,55 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import validateCatalog from './catalog.js';
3
+ function encoded(value) { return Buffer.from(value).toString('base64'); }
4
+ function decoded(value) { return Buffer.from(value, 'base64').toString(); }
5
+ function put(key, value, lease) { return { request_put: { key: encoded(key), value: encoded(JSON.stringify(value)), ...(lease && { lease }) } }; }
6
+ function revision(key, value) { return { key: encoded(key), target: 'MOD', result: 'EQUAL', mod_revision: String(value) }; }
7
+ export default function controlStore(call, prefix = '/scada/control') {
8
+ const root = prefix.replace(/\/$/u, '');
9
+ const lock = `${root}/leader`;
10
+ const session = randomUUID();
11
+ async function range(key) { const result = await call('/v3/kv/range', { key: encoded(key) }); return result.kvs?.[0] ?? null; }
12
+ return {
13
+ async acquire() {
14
+ const grant = await call('/v3/lease/grant', { TTL: '15' });
15
+ const previous = await range(lock);
16
+ const own = previous && decoded(previous.value) === JSON.stringify(session);
17
+ const compare = own ? revision(lock, previous.mod_revision) : { key: encoded(lock), target: 'VERSION', result: 'EQUAL', version: '0' };
18
+ const result = await call('/v3/kv/txn', { compare: [compare], success: [put(lock, session, grant.ID)], failure: [] });
19
+ return result.succeeded ? { session, lease: grant.ID } : null;
20
+ },
21
+ async read() {
22
+ const result = await call('/v3/kv/range', { key: encoded(`${root}/`), range_end: encoded(`${root}0`) });
23
+ const view = { catalog: null, reports: [], assignments: {}, revisions: {} };
24
+ for (const row of result.kvs ?? []) {
25
+ const key = decoded(row.key).slice(root.length + 1);
26
+ const value = JSON.parse(decoded(row.value));
27
+ view.revisions[key] = row.mod_revision;
28
+ if (key === 'catalog') { view.catalog = value; }
29
+ if (key.startsWith('reports/')) { view.reports.push(value); }
30
+ if (key.startsWith('assignments/')) { view.assignments[key.slice(12)] = value; }
31
+ }
32
+ return view;
33
+ },
34
+ async commit(token, view, assignments) {
35
+ const compare = [{ key: encoded(lock), target: 'VALUE', result: 'EQUAL', value: encoded(JSON.stringify(token.session)) },
36
+ { key: encoded(lock), target: 'LEASE', result: 'EQUAL', lease: token.lease },
37
+ ...Object.entries(view.revisions).filter(([key]) => { return key !== 'leader'; }).map(([key, value]) => { return revision(`${root}/${key}`, value); })];
38
+ const changes = Object.entries(assignments).filter(([id, value]) => { return JSON.stringify(value) !== JSON.stringify(view.assignments[id]); });
39
+ if (!changes.length) { return true; }
40
+ const result = await call('/v3/kv/txn', { compare, success: changes.map(([id, value]) => { return put(`${root}/assignments/${id}`, value); }), failure: [] });
41
+ return Boolean(result.succeeded);
42
+ },
43
+ async assignment(id) { const row = await range(`${root}/assignments/${id}`); return row ? JSON.parse(decoded(row.value)) : null; },
44
+ report(id, value) { return call('/v3/kv/put', put(`${root}/reports/${id}`, value).request_put); },
45
+ async publish(catalog, expectedRevision) {
46
+ validateCatalog(catalog);
47
+ const key = `${root}/catalog`;
48
+ const existing = await range(key);
49
+ const expected = expectedRevision ?? existing?.mod_revision ?? '0';
50
+ const result = await call('/v3/kv/txn', { compare: [revision(key, expected)], success: [put(key, catalog)], failure: [] });
51
+ if (!result.succeeded) { throw new Error('Catalog publication conflict'); }
52
+ return { accepted: true, revision: result.header.revision, catalogVersion: catalog.version };
53
+ }
54
+ };
55
+ }
@@ -0,0 +1,22 @@
1
+ import schedule from './schedule.js';
2
+ export async function reconcile(store, nodeId, options = {}) {
3
+ const token = await store.acquire(nodeId);
4
+ if (!token) { return false; }
5
+ const view = await store.read();
6
+ if (!view.catalog) { return false; }
7
+ const desired = schedule(view.catalog, view.reports, view.assignments, options);
8
+ return store.commit(token, view, desired);
9
+ }
10
+ export default function controlLoop(store, nodeId, { intervalMs = 5000, onError = () => {
11
+ // Optional diagnostic sink.
12
+ }, ...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; } };
22
+ }
@@ -0,0 +1,32 @@
1
+ import { checkSnapshot } from './snapshotFile.js';
2
+ export function remoteSnapshot(snapshot) {
3
+ const remote = { ...snapshot };
4
+ delete remote.localGeneration;
5
+ delete remote.executionGenerations;
6
+ return remote;
7
+ }
8
+ function epoch(snapshot) { return snapshot?.controlEpoch ?? 'initial'; }
9
+ /** 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);
13
+ if (previous && epoch(previous) === epoch(remote)) {
14
+ if (remote.generation < previous.generation) { throw new Error('Stale assignment snapshot'); }
15
+ if (remote.generation === previous.generation && JSON.stringify(remote) !== JSON.stringify(remoteSnapshot(previous))) { throw new Error('Conflicting assignment snapshot'); }
16
+ if (remote.generation === previous.generation) { return previous; }
17
+ }
18
+ if (restored && Number.isSafeInteger(snapshot.localGeneration) && snapshot.executionGenerations) { return snapshot; }
19
+ const localGeneration = Math.max(previous?.localGeneration ?? 0, remote.generation, ...tasks.map((row) => { return row.generation ?? 0; })) + 1;
20
+ const executionGenerations = Object.fromEntries(remote.assignments.map((row) => {
21
+ const prior = previous?.assignments.find((item) => { return item.taskId === row.taskId; });
22
+ const unchanged = epoch(previous) === epoch(remote) && prior && prior.generation === row.generation && JSON.stringify(prior.spec) === JSON.stringify(row.spec);
23
+ return [row.taskId, unchanged ? previous.executionGenerations[row.taskId] : localGeneration];
24
+ }));
25
+ return { ...remote, localGeneration, executionGenerations };
26
+ }
27
+ export function remoteStatus(status, snapshot) {
28
+ return { ...status, tasks: status.tasks.map((row) => {
29
+ const assignment = snapshot?.assignments.find((item) => { return item.taskId === row.taskId; });
30
+ return { ...row, executionGeneration: row.generation, generation: assignment && row.generation === snapshot.executionGenerations[row.taskId] ? assignment.generation : null };
31
+ }) };
32
+ }
@@ -0,0 +1,7 @@
1
+ export { default as controlClient, clientFromEnv } from './controlClient.js';
2
+ export { default as controlStore } from './controlStore.js';
3
+ export { default as validateCatalog } from './catalog.js';
4
+ export { default as schedule } from './schedule.js';
5
+ export { default as assignmentAgent } from './agent.js';
6
+ export { default as controller, reconcile } from './controller.js';
7
+ export function publishCatalog(store, catalog, expectedRevision) { return store.publish(catalog, expectedRevision); }
@@ -0,0 +1,13 @@
1
+ import { createHash } from 'node:crypto';
2
+ /** Logical task identity is stable; broker client sessions belong to a replica. */
3
+ export default function localAssignment(input, nodeId) {
4
+ const output = structuredClone(input);
5
+ const suffix = createHash('sha256').update(`${nodeId}:${input.taskId}`).digest('hex').slice(0, 16);
6
+ const specs = [output.spec.config, output.spec.source?.options, ...(output.spec.sinks ?? []).map((sink) => { return sink.options; })];
7
+ let changed = false;
8
+ for (const spec of specs) {
9
+ if (typeof spec?.clientId === 'string') { spec.clientId = `${spec.clientId}-${suffix}`; changed = true; }
10
+ }
11
+ if (changed) { delete output.specHash; }
12
+ return output;
13
+ }
@@ -0,0 +1,103 @@
1
+ import validateCatalog from './catalog.js';
2
+ function same(left, right) { return JSON.stringify(left) === JSON.stringify(right); }
3
+ function eligible(task, node) { return (!task.pinnedNode || task.pinnedNode === node.id) && (!task.eligibleNodes || task.eligibleNodes.includes(node.id)); }
4
+ function wanted(task, node) { return !node.retired && eligible(task, node); }
5
+ function inEpoch(report, epoch) { return (report?.controlEpoch ?? 'initial') === epoch; }
6
+ function clockSkew(value) {
7
+ if (!Number.isFinite(value) || value <= 0) { throw new TypeError('Positive finite clock skew bound required'); }
8
+ }
9
+ function copies(task) { return task.pinnedNode ? 1 : task.copies ?? 2; }
10
+ function freshRead(report, input, { now, freshnessMs, controlEpoch, clockSkewMs }) {
11
+ return inEpoch(report, controlEpoch) && report?.tasks?.some((row) => {
12
+ return row.taskId === input.taskId && row.generation === input.generation && row.state === 'running' && !['degraded', 'failed'].includes(row.health)
13
+ && Number.isFinite(row.lastRead) && row.lastRead <= now + clockSkewMs && now - row.lastRead <= freshnessMs;
14
+ });
15
+ }
16
+ function failedRead(report, input, controlEpoch) {
17
+ return input && inEpoch(report, controlEpoch) && report?.tasks?.some((row) => {
18
+ return row.taskId === input.taskId && row.generation === input.generation && row.state === 'failed';
19
+ });
20
+ }
21
+ function updateAllowed(task, node, slots, reports, { now, freshnessMs, controlEpoch, clockSkewMs }) {
22
+ const owners = slots.filter((slot) => { return slot.live && slot.assignments.some((row) => { return row.taskId === task.taskId; }); });
23
+ const modern = owners.filter((slot) => { return slot.assignments.some((row) => { return row.taskId === task.taskId && same(row.spec, task.spec); }); });
24
+ const ready = modern.some((slot) => {
25
+ const input = slot.assignments.find((row) => { return row.taskId === task.taskId; });
26
+ return freshRead(reports.get(slot.id), input, { now, freshnessMs, controlEpoch, clockSkewMs });
27
+ });
28
+ const healthy = owners.filter((slot) => { return freshRead(reports.get(slot.id), slot.assignments.find((row) => { return row.taskId === task.taskId; }), { now, freshnessMs, controlEpoch, clockSkewMs }); });
29
+ function failed(slot) { return failedRead(reports.get(slot.id), slot.assignments.find((row) => { return row.taskId === task.taskId; }), controlEpoch); }
30
+ const outdated = owners.filter((slot) => { return wanted(task, slot) && !modern.includes(slot)
31
+ && (copies(task) === 1 || failed(slot) || healthy.some((other) => { return other.id !== slot.id; })); });
32
+ return (modern.length === 0 || ready || failed(node)) && outdated[0]?.id === node.id;
33
+ }
34
+ function snapshots(slots, taskMap, { version: catalogVersion, controlEpoch = 'initial' }, reports, timing) {
35
+ return Object.fromEntries(slots.map((node) => {
36
+ const base = node.assignments.map((row) => {
37
+ const task = taskMap.get(row.taskId);
38
+ const update = node.live && task && wanted(task, node) && !same(task.spec, row.spec) && updateAllowed(task, node, slots, reports, { ...timing, controlEpoch });
39
+ return update ? { ...row, spec: task.spec, assignedAt: timing.now } : row;
40
+ });
41
+ const complete = base.every((row) => { return same(row.spec, taskMap.get(row.taskId)?.spec); });
42
+ const appliedCatalog = complete ? catalogVersion : node.previous.catalogVersion;
43
+ const changed = node.live && (!same(base, node.previous.assignments) || node.previous.catalogVersion !== appliedCatalog || (node.previous.controlEpoch ?? 'initial') !== controlEpoch);
44
+ const generation = node.previous.generation + Number(changed);
45
+ const assignments = base.map((row) => {
46
+ const old = node.previous.assignments.find((item) => { return item.taskId === row.taskId; });
47
+ return { ...row, generation: old && same(old.spec, row.spec) ? old.generation : generation };
48
+ });
49
+ return [node.id, changed ? { generation, catalogVersion: appliedCatalog, controlEpoch, assignments } : node.previous];
50
+ }));
51
+ }
52
+ /** Conservative coverage-first placement. Unreachable executors retain their last snapshot. */
53
+ // eslint-disable-next-line max-statements
54
+ export default function schedule(catalog, reports, current, { now = Date.now(), freshnessMs = 15000, replacementDelayMs = 30000, clockSkewMs = 5000 } = {}) {
55
+ validateCatalog(catalog); clockSkew(clockSkewMs);
56
+ const controlEpoch = catalog.controlEpoch ?? 'initial';
57
+ const observed = new Map(reports.map((row) => { return [row.nodeId, row]; }));
58
+ function live(id) { const at = observed.get(id)?.receivedAt; return Number.isFinite(at) && at <= now + clockSkewMs && now - at <= freshnessMs; }
59
+ const taskMap = new Map(catalog.tasks.map((task) => { return [task.taskId, task]; }));
60
+ const declared = new Set(catalog.nodes.map((node) => { return node.id; }));
61
+ const nodes = [...catalog.nodes, ...Object.keys(current).filter((id) => { return !declared.has(id); }).map((id) => { return { id, capacity: 0, retired: true }; })];
62
+ const slots = nodes.map((node) => {
63
+ const previous = current[node.id] ?? { generation: 0, assignments: [] };
64
+ const assignments = previous.assignments.filter((row) => { return !live(node.id) || taskMap.has(row.taskId); });
65
+ return { ...node, previous, assignments: [...assignments], live: live(node.id), load: assignments.reduce((total, row) => { return total + (taskMap.get(row.taskId)?.cost ?? 1); }, 0) };
66
+ });
67
+ const tasks = [...catalog.tasks].sort((a, b) => { return Number(Boolean(b.pinnedNode)) - Number(Boolean(a.pinnedNode)) || a.taskId.localeCompare(b.taskId); });
68
+ function owners(task) {
69
+ return slots.filter((node) => {
70
+ const input = node.assignments.find((row) => { return row.taskId === task.taskId; });
71
+ const status = observed.get(node.id)?.tasks?.find((row) => { return row.taskId === task.taskId; });
72
+ const progressing = input && freshRead(observed.get(node.id), input, { now, freshnessMs, controlEpoch, clockSkewMs });
73
+ const starting = input && now - (input.assignedAt ?? now) <= replacementDelayMs;
74
+ return node.live && input && status?.state !== 'failed' && (progressing || starting);
75
+ });
76
+ }
77
+ for (let round = 0; round < Math.max(1, ...tasks.map(copies)); round += 1) {
78
+ for (const task of tasks) {
79
+ const active = owners(task).filter((node) => { return wanted(task, node); });
80
+ const missing = slots.filter((node) => { return !node.live && node.assignments.some((row) => { return row.taskId === task.taskId; }); });
81
+ const surviving = active.some((node) => { return freshRead(observed.get(node.id), node.assignments.find((row) => { return row.taskId === task.taskId; }), { now, freshnessMs, controlEpoch, clockSkewMs }); });
82
+ const waiting = surviving && missing.some((node) => { return now - (observed.get(node.id)?.receivedAt ?? 0) < replacementDelayMs; });
83
+ const candidates = slots.filter((node) => { return node.live && wanted(task, node) && !active.includes(node) && !node.assignments.some((row) => { return row.taskId === task.taskId; }) && node.load + (task.cost ?? 1) <= node.capacity; });
84
+ candidates.sort((a, b) => { return a.load / a.capacity - b.load / b.capacity || a.id.localeCompare(b.id); });
85
+ if (active.length <= round && active.length < copies(task) && !waiting && candidates.length) {
86
+ const node = candidates[0];
87
+ node.assignments.push({ taskId: task.taskId, specVersion: 1, generation: 0, assignedAt: now, spec: task.spec });
88
+ node.load += task.cost ?? 1;
89
+ }
90
+ }
91
+ }
92
+ for (const task of tasks) {
93
+ const active = owners(task);
94
+ const confirmed = active.filter((node) => { return wanted(task, node) && node.assignments.some((row) => { return row.taskId === task.taskId && same(row.spec, task.spec); }) && freshRead(observed.get(node.id), node.assignments.find((row) => { return row.taskId === task.taskId; }), { now, freshnessMs, controlEpoch, clockSkewMs }); });
95
+ if (confirmed.length >= copies(task)) {
96
+ const keep = new Set(confirmed.slice(0, copies(task)).map((node) => { return node.id; }));
97
+ slots.filter((node) => { return node.live && !keep.has(node.id); }).forEach((node) => {
98
+ node.assignments = node.assignments.filter((row) => { return row.taskId !== task.taskId; });
99
+ });
100
+ }
101
+ }
102
+ return snapshots(slots, taskMap, catalog, observed, { now, freshnessMs, clockSkewMs });
103
+ }
@@ -0,0 +1,24 @@
1
+ import { mkdir, open, readFile, rename, unlink } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ export function checkSnapshot(value) {
5
+ if (!value || !Number.isSafeInteger(value.generation) || value.generation < 0 || !Array.isArray(value.assignments)) { throw new TypeError('Invalid assignment snapshot'); }
6
+ return value;
7
+ }
8
+ export async function loadSnapshot(file) {
9
+ try { return checkSnapshot(JSON.parse(await readFile(file, 'utf8'))); } catch (error) { if (error.code === 'ENOENT') { return null; } throw error; }
10
+ }
11
+ export async function saveSnapshot(file, snapshot) {
12
+ checkSnapshot(snapshot);
13
+ await mkdir(path.dirname(file), { recursive: true });
14
+ const temporary = `${file}.${randomUUID()}.tmp`;
15
+ try {
16
+ const handle = await open(temporary, 'wx', 0o600);
17
+ try { await handle.writeFile(JSON.stringify(snapshot)); await handle.sync(); } finally { await handle.close(); }
18
+ await rename(temporary, file);
19
+ const directory = await open(path.dirname(file), 'r');
20
+ try { await directory.sync(); } finally { await directory.close(); }
21
+ } finally { await unlink(temporary).catch(() => {
22
+ // Rename may already have consumed the temporary file.
23
+ }); }
24
+ }
@@ -18,5 +18,6 @@ export default function foldedMetricsSink(inner, pool, devices) {
18
18
  if (!devices || Object.keys(devices).length === 0) {
19
19
  return inner;
20
20
  }
21
+ if (inner.requireTimestamp) { throw new TypeError('Central telemetry policy cannot be combined with interval folding'); }
21
22
  return foldingSink(inner, intervalFold(intervalFoldPg(pool)), opcuaLocate(devices));
22
23
  }
@@ -144,5 +144,5 @@ export default function registerResources(server, tree, catalog) {
144
144
  return tags(catalog);
145
145
  });
146
146
  publish(server, 'schema-postgres', 'plant://schema/postgres', 'Postgres tables from scada migrations', postgresSchema);
147
- publish(server, 'schema-clickhouse', 'plant://schema/clickhouse', 'ClickHouse scada.metrics', clickhouseSchema);
147
+ publish(server, 'schema-clickhouse', 'plant://schema/clickhouse', 'ClickHouse adaptive and full canonical metric views', clickhouseSchema);
148
148
  }
@@ -78,7 +78,7 @@ export function postgresSchema() {
78
78
  }
79
79
 
80
80
  /**
81
- * ClickHouse metrics table. topic is the only series key.
81
+ * ClickHouse canonical metrics view. topic is the only series key.
82
82
  *
83
83
  * @returns {object} schema body
84
84
  *
@@ -88,11 +88,16 @@ export function postgresSchema() {
88
88
  export function clickhouseSchema() {
89
89
  return {
90
90
  tables: [
91
- table('scada.metrics', [
91
+ table('scada.metrics_read', [
92
92
  { name: 'topic', type: 'String' },
93
93
  { name: 'ts', type: 'DateTime64(3)' },
94
94
  { name: 'value', type: 'Float64' }
95
- ], ['topic is the only series key'])
95
+ ], ['topic is the only series key', 'Legacy history and canonical telemetry; one row per topic and timestamp']),
96
+ table('scada.metrics_raw_read', [
97
+ { name: 'topic', type: 'String' },
98
+ { name: 'ts', type: 'DateTime64(3)' },
99
+ { name: 'value', type: 'Float64' }
100
+ ], ['Retained canonical point rows; sealed constant interiors are physically removed. Use bounded clickhouseMetricsRawRange for count/gap analytics; unavailable density is rejected explicitly.'])
96
101
  ]
97
102
  };
98
103
  }
@@ -1,5 +1,5 @@
1
1
  import ingestHealth from '../ingestHealth.js';
2
- import { clickhouseSink } from '../../infrastructure/streams/index.js';
2
+ import telemetrySink, { validateTelemetryPolicy } from './telemetrySink.js';
3
3
  import mqttMetrics from '../../infrastructure/ingest/mqtt/mqttMetrics.js';
4
4
  import amqpMetricsIngest from '../../infrastructure/ingest/telemetry/amqpMetricsIngest.js';
5
5
  import operationSyncIngest from '../../infrastructure/sync/operationSyncIngest.js';
@@ -16,7 +16,7 @@ import resolveSecrets from './resolveSecrets.js';
16
16
 
17
17
  function urlOptions(spec) {
18
18
  const protocols = { mqtt: ['mqtt:', 'mqtts:', 'ws:', 'wss:'], amqp: ['amqp:', 'amqps:'], stomp: ['stomp:', 'stomps:'],
19
- postgres: ['postgres:', 'postgresql:'], clickhouse: ['http:', 'https:'] };
19
+ postgres: ['postgres:', 'postgresql:'], clickhouse: ['http:', 'https:'], telemetryAmqp: ['amqp:', 'amqps:'] };
20
20
  Object.entries(protocols).forEach(([key, allowed]) => {
21
21
  const value = spec[key];
22
22
  if (value === undefined || value?.$secret) { return; }
@@ -33,7 +33,7 @@ function boundedOptions(spec) {
33
33
  prefetch: Math.min(spec.options?.prefetch ?? 32, maxRecords) };
34
34
  }
35
35
  function ownedSink(pipeline, sink) {
36
- return { start() { return pipeline.start(); }, async stop() {
36
+ return { async start() { await sink.start?.(); return pipeline.start(); }, async stop() {
37
37
  try { await pipeline.stop(); } finally { await sink.stop?.(); }
38
38
  } };
39
39
  }
@@ -52,7 +52,7 @@ function borrowed(pool) {
52
52
  end() { return Promise.resolve(); } };
53
53
  }
54
54
  function telemetry(spec, pool) {
55
- const inner = spec.clickhouse ? clickhouseSink(spec.clickhouse, spec.table ?? 'scada.metrics') : metricsSinkFromPool(pool);
55
+ const inner = spec.clickhouse ? telemetrySink(spec) : metricsSinkFromPool(pool, { firstWins: spec.firstWins === true });
56
56
  return foldedMetricsSink(inner, pool, spec.devices);
57
57
  }
58
58
  function metrics(spec, pool, context) {
@@ -62,7 +62,8 @@ function metrics(spec, pool, context) {
62
62
  function mqttPostgres(spec, pool, context) {
63
63
  let failed = false;
64
64
  context.report?.({ state: 'degraded' });
65
- return mqttMetrics(spec.mqtt, metricsSinkFromPool(pool), spec.topic, {
65
+ const sink = telemetry(spec, pool);
66
+ return ownedSink(mqttMetrics(spec.mqtt, sink, spec.topic, {
66
67
  ...boundedOptions(spec), budget: context.budget,
67
68
  onReady() { if (!failed) { context.report?.({ state: 'running' }); } },
68
69
  onError(error) {
@@ -71,7 +72,7 @@ function mqttPostgres(spec, pool, context) {
71
72
  failed ||= ['WRITE_TIMEOUT', 'OPERATION_TIMEOUT'].includes(error.code);
72
73
  context.report?.({ state: failed ? 'failed' : 'degraded', fatal: failed });
73
74
  }
74
- });
75
+ }), sink);
75
76
  }
76
77
  function silent(spec, pool, context) {
77
78
  const sink = telemetry(spec, pool);
@@ -137,6 +138,9 @@ function task(factory, spec, context) {
137
138
  function required(spec, keys) {
138
139
  keys.forEach((key) => { if (!spec[key]) { throw new TypeError(`Missing ingest ${key}`); } });
139
140
  }
141
+ function silentConfigStorage(spec) {
142
+ if (!spec.clickhouse && !spec.postgres) { throw new TypeError('Missing metrics storage'); }
143
+ }
140
144
  function silentConfig(spec) {
141
145
  if (!spec.clickhouse && !spec.postgres) { throw new TypeError('Missing silent metrics storage'); }
142
146
  if (spec.devices && Object.keys(spec.devices).length && !spec.postgres) { throw new TypeError('Missing folding postgres'); }
@@ -148,7 +152,7 @@ function silentConfig(spec) {
148
152
  })) { throw new TypeError('Invalid silent source'); }
149
153
  }
150
154
  function descriptor(factory, keys, validate = () => { return undefined; }, resources = () => { return []; }) {
151
- return { validate(spec) { required(spec, keys); urlOptions(spec); boundedOptions(spec); validate(spec); }, resources,
155
+ return { validate(spec) { required(spec, keys); urlOptions(spec); boundedOptions(spec); validateTelemetryPolicy(spec); validate(spec); }, resources,
152
156
  create(spec, context) { return task(factory, spec, context); } };
153
157
  }
154
158
  /** Portable consumers previously embedded in site HTTP processes; migrations remain external. */
@@ -157,8 +161,8 @@ export default function additionalAdapters() {
157
161
  ['operation-sync', descriptor((spec, pool, context) => {
158
162
  return operationSyncIngest(spec.amqp, spec.queue, operationsFromPg(pool), { ...boundedOptions(spec), budget: context.budget });
159
163
  }, ['amqp', 'queue', 'postgres'])],
160
- ['amqp-pg-metrics', descriptor(metrics, ['amqp', 'queue', 'postgres'])],
161
- ['mqtt-pg-metrics', descriptor(mqttPostgres, ['mqtt', 'topic', 'postgres'])],
164
+ ['amqp-pg-metrics', descriptor(metrics, ['amqp', 'queue'], silentConfigStorage)],
165
+ ['mqtt-pg-metrics', descriptor(mqttPostgres, ['mqtt', 'topic'], silentConfigStorage)],
162
166
  ['silent-streams', descriptor(silent, ['amqp', 'queue', 'sources'], silentConfig, (spec) => {
163
167
  return [...new Set(spec.sources.map((source) => { return `modbus-tcp:${source.host}:${source.port}`; }))];
164
168
  })],