@yarkivaev/scada 2.13.0 → 2.15.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 (88) hide show
  1. package/charts/scada/templates/processes.yaml +6 -1
  2. package/charts/scada/values.schema.json +1 -0
  3. package/index.js +29 -0
  4. package/package.json +3 -2
  5. package/src/application/control/agent.js +8 -14
  6. package/src/application/control/controlClient.js +1 -1
  7. package/src/application/control/createOnlyJSON.js +50 -0
  8. package/src/application/control/executionSnapshot.js +4 -5
  9. package/src/application/control/index.js +2 -0
  10. package/src/application/control/jsonAssignments.js +30 -0
  11. package/src/application/mcp/loadMetricSeries.js +69 -0
  12. package/src/application/mcp/locateMachineMetric.js +25 -0
  13. package/src/application/mcp/metricQueryPorts.js +78 -0
  14. package/src/application/mcp/parseBearerTokens.js +43 -0
  15. package/src/application/runtime/assignment.js +4 -1
  16. package/src/application/runtime/deliveryOperations.js +6 -3
  17. package/src/application/runtime/deliveryPublications.js +13 -11
  18. package/src/application/runtime/deliveryQueue.js +5 -4
  19. package/src/application/runtime/index.js +0 -1
  20. package/src/application/runtime/queuedDelivery.js +6 -5
  21. package/src/application/runtime/runCollector.js +8 -6
  22. package/src/application/runtime/runtime.js +1 -0
  23. package/src/application/runtime/runtimeServices.js +6 -26
  24. package/src/infrastructure/deploy/applyWhenChanged.js +15 -0
  25. package/src/infrastructure/deploy/deploymentKube.js +35 -0
  26. package/src/infrastructure/deploy/executeKubeSeed.js +24 -0
  27. package/src/infrastructure/deploy/executeRelease.js +8 -11
  28. package/src/infrastructure/deploy/operatePostgresMaintenance.js +85 -0
  29. package/src/infrastructure/deploy/postgresMaintenancePlan.js +54 -0
  30. package/src/infrastructure/deploy/postgresRestoreObjects.js +73 -0
  31. package/src/infrastructure/deploy/preflightKubeStorage.js +76 -0
  32. package/src/infrastructure/deploy/prepareKubePrerequisites.js +95 -0
  33. package/src/infrastructure/deploy/verifyCollectorCoverage.js +43 -0
  34. package/src/infrastructure/deploy/verifyPeerBrokerPerimeter.js +24 -0
  35. package/src/infrastructure/ingest/mysql40/byteReader.js +51 -0
  36. package/src/infrastructure/ingest/mysql40/mysql40.js +116 -0
  37. package/src/infrastructure/ingest/mysql40/packets.js +72 -0
  38. package/src/infrastructure/ingest/mysql40/resultRows.js +92 -0
  39. package/src/infrastructure/ingest/mysql40/scramble.js +89 -0
  40. package/src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js +83 -0
  41. package/src/infrastructure/ingest/telemetry/replayStoredTelemetry.js +125 -0
  42. package/src/infrastructure/management/kubeServiceAccount.js +43 -0
  43. package/src/infrastructure/management/kubectlPortForward.js +27 -0
  44. package/src/infrastructure/mdmesh/hmiApplication.js +64 -0
  45. package/src/infrastructure/mdmesh/hmiControl.js +85 -0
  46. package/src/infrastructure/mdmesh/hmiFile.js +69 -0
  47. package/src/infrastructure/mdmesh/hmiMonitor.js +53 -0
  48. package/src/infrastructure/mdmesh/hmiReconcile.js +170 -0
  49. package/src/infrastructure/mdmesh/hmiRuntime.js +33 -0
  50. package/src/infrastructure/mdmesh/index.js +7 -0
  51. package/src/infrastructure/mdmesh/mdmeshClient.js +72 -0
  52. package/src/infrastructure/messaging/ownership/edgeSitesFromEnv.js +137 -0
  53. package/src/infrastructure/messaging/rabbitmq/reconcile.js +71 -12
  54. package/src/infrastructure/opcua/health.js +91 -0
  55. package/src/infrastructure/opcua/index.js +1 -0
  56. package/src/infrastructure/persistence/pg/prepareRuntimeRole.js +67 -0
  57. package/src/infrastructure/persistence/runtime/memoryDeliveryStore.js +186 -0
  58. package/src/infrastructure/persistence/runtime/spoolCodec.js +0 -27
  59. package/src/infrastructure/persistence/runtime/taskStateMemory.js +40 -0
  60. package/src/infrastructure/replication/canonicalJSON.js +15 -0
  61. package/src/infrastructure/replication/postgresSnapshotReplica.js +129 -0
  62. package/src/infrastructure/replication/postgresSnapshotRuntime.js +40 -0
  63. package/src/infrastructure/replication/snapshotSync.js +61 -0
  64. package/src/infrastructure/replication/tableSnapshotFormat.js +50 -0
  65. package/src/infrastructure/tls/mirrorTLSSecret.js +37 -0
  66. package/src/infrastructure/tls/mutualJSON.js +79 -0
  67. package/src/infrastructure/tls/tlsMaterial.js +57 -0
  68. package/stream-processing/src/main/scala/scada/processing/infra/state/AtomicStateFile.scala +7 -0
  69. package/stream-processing/src/main/scala/scada/processing/infra/state/StateJournal.scala +22 -0
  70. package/stream-processing/src/main/scala/scada/processing/runtime/HistoryClient.scala +10 -1
  71. package/stream-processing/src/main/scala/scada/processing/runtime/LiveWorker.scala +70 -0
  72. package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +2 -8
  73. package/stream-processing/src/main/scala/scada/processing/runtime/StatefulHistory.scala +108 -0
  74. package/stream-processing/src/main/scala/scada/processing/runtime/TimelinePublication.scala +43 -0
  75. package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +43 -0
  76. package/src/application/control/snapshotFile.js +0 -24
  77. package/src/infrastructure/persistence/runtime/deliverySpool.js +0 -86
  78. package/src/infrastructure/persistence/runtime/spoolCheckpoints.js +0 -65
  79. package/src/infrastructure/persistence/runtime/spoolDatabase.js +0 -69
  80. package/src/infrastructure/persistence/runtime/spoolFormat.js +0 -63
  81. package/src/infrastructure/persistence/runtime/spoolLimits.js +0 -8
  82. package/src/infrastructure/persistence/runtime/spoolMigration.js +0 -66
  83. package/src/infrastructure/persistence/runtime/spoolMutations.js +0 -19
  84. package/src/infrastructure/persistence/runtime/spoolProcess.js +0 -89
  85. package/src/infrastructure/persistence/runtime/spoolProcessChild.js +0 -32
  86. package/src/infrastructure/persistence/runtime/spoolRecords.js +0 -56
  87. package/src/infrastructure/persistence/runtime/spoolReplay.js +0 -55
  88. 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,
package/index.js CHANGED
@@ -129,3 +129,32 @@ export { default as postgresTelemetrySource } from './src/infrastructure/persist
129
129
  export { default as clickhouseTelemetryTarget, assertClickhouseBackfillMode } from './src/infrastructure/persistence/clickhouse/telemetryTarget.js';
130
130
  export { default as clickhouseMetricsState } from './src/infrastructure/persistence/clickhouse/metricsState.js';
131
131
  export { default as historyTelemetryMetrics } from './src/infrastructure/ingest/telemetry/historyTelemetryMetrics.js';
132
+
133
+ export { default as applyWhenChanged } from './src/infrastructure/deploy/applyWhenChanged.js';
134
+ export { deploymentKube, readKube, verifyKubeNode, preserveKubeRestart } from './src/infrastructure/deploy/deploymentKube.js';
135
+ export { default as preflightKubeStorage } from './src/infrastructure/deploy/preflightKubeStorage.js';
136
+ export { default as postgresMaintenancePlan } from './src/infrastructure/deploy/postgresMaintenancePlan.js';
137
+ export { default as postgresRestoreObjects } from './src/infrastructure/deploy/postgresRestoreObjects.js';
138
+ export { default as operatePostgresMaintenance } from './src/infrastructure/deploy/operatePostgresMaintenance.js';
139
+ export { fetchMutualJSON, readMutualTLS, serveMutualTLS } from './src/infrastructure/tls/mutualJSON.js';
140
+ export { readTLSMaterial, sealTLSMaterial, tlsMaterialLimit, validateTLSMaterial } from './src/infrastructure/tls/tlsMaterial.js';
141
+ export { kubernetesTLSAPI, mirrorTLSSecret } from './src/infrastructure/tls/mirrorTLSSecret.js';
142
+ export { tableSnapshotFormat, tableSnapshotLimit } from './src/infrastructure/replication/tableSnapshotFormat.js';
143
+ export { postgresSnapshotReplica } from './src/infrastructure/replication/postgresSnapshotReplica.js';
144
+ export { snapshotSync } from './src/infrastructure/replication/snapshotSync.js';
145
+ export { default as verifyCollectorCoverage } from './src/infrastructure/deploy/verifyCollectorCoverage.js';
146
+ export { default as verifyPeerBrokerPerimeter } from './src/infrastructure/deploy/verifyPeerBrokerPerimeter.js';
147
+ export { default as mysql40 } from './src/infrastructure/ingest/mysql40/mysql40.js';
148
+ export { default as prepareRuntimeRole } from './src/infrastructure/persistence/pg/prepareRuntimeRole.js';
149
+ export { kubectlPortForward } from './src/infrastructure/management/kubectlPortForward.js';
150
+ export { default as replayStoredTelemetry } from './src/infrastructure/ingest/telemetry/replayStoredTelemetry.js';
151
+ export { followPostgresSnapshot, servePostgresSnapshot } from './src/infrastructure/replication/postgresSnapshotRuntime.js';
152
+ export { default as edgeSitesFromEnv } from './src/infrastructure/messaging/ownership/edgeSitesFromEnv.js';
153
+ export { default as locateMachineMetric } from './src/application/mcp/locateMachineMetric.js';
154
+ export { default as loadMetricSeries } from './src/application/mcp/loadMetricSeries.js';
155
+ export { default as parseBearerTokens } from './src/application/mcp/parseBearerTokens.js';
156
+ export { clickhousePort, cursorPort, postgresPort } from './src/application/mcp/metricQueryPorts.js';
157
+ export { default as prepareKubePrerequisites } from './src/infrastructure/deploy/prepareKubePrerequisites.js';
158
+ export { default as executeKubeSeed } from './src/infrastructure/deploy/executeKubeSeed.js';
159
+ export { default as edgeTelemetryRuntime } from './src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js';
160
+ export { default as kubeServiceAccount } from './src/infrastructure/management/kubeServiceAccount.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.13.0",
3
+ "version": "2.15.0",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -20,7 +20,8 @@
20
20
  "./opcua/config": "./src/infrastructure/opcua/config.js",
21
21
  "./runtime": "./src/application/runtime/index.js",
22
22
  "./streams": "./src/infrastructure/streams/index.js",
23
- "./control": "./src/application/control/index.js"
23
+ "./control": "./src/application/control/index.js",
24
+ "./mdmesh": "./src/infrastructure/mdmesh/index.js"
24
25
  },
25
26
  "bin": {
26
27
  "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
  },
@@ -71,5 +71,5 @@ export function clientFromEnv(env, prefix = 'CONTROL') {
71
71
  for (const [name, key] of [['CA', 'ca'], ['CERT', 'cert'], ['KEY', 'key']]) {
72
72
  if (env[`${prefix}_${name}`]) { tls[key] = readFileSync(env[`${prefix}_${name}`]); }
73
73
  }
74
- return controlClient({ endpoints: (env[`${prefix}_ENDPOINTS`] ?? '').split(',').filter(Boolean), tls, username: env[`${prefix}_USERNAME`], password: env[`${prefix}_PASSWORD`] });
74
+ return controlClient({ endpoints: (env[`${prefix}_ENDPOINTS`] ?? '').split(',').map((endpoint) => { return endpoint.trim(); }).filter(Boolean), tls, username: env[`${prefix}_USERNAME`], password: env[`${prefix}_PASSWORD`] });
75
75
  }
@@ -0,0 +1,50 @@
1
+ function encode(value) {
2
+ return Buffer.from(value).toString('base64');
3
+ }
4
+
5
+ function decode(value) {
6
+ return Buffer.from(value, 'base64').toString('utf8');
7
+ }
8
+
9
+ function rangeEnd(prefix) {
10
+ const bytes = Buffer.from(prefix);
11
+ let index = bytes.length - 1;
12
+ while (index >= 0 && bytes[index] === 255) {
13
+ index -= 1;
14
+ }
15
+ if (index < 0) {
16
+ return encode(Buffer.of(0));
17
+ }
18
+ bytes[index] += 1;
19
+ return encode(bytes.subarray(0, index + 1));
20
+ }
21
+
22
+ /** Stores the first JSON value written for each key under a caller-owned prefix. */
23
+ export default function createOnlyJSON(call, prefix) {
24
+ if (typeof prefix !== 'string' || !prefix) {
25
+ throw new TypeError('A nonempty key prefix is required');
26
+ }
27
+ const end = rangeEnd(prefix);
28
+ return {
29
+ async reserve(id, record) {
30
+ const key = encode(`${prefix}${id}`);
31
+ const body = await call('/v3/kv/txn', {
32
+ compare: [{ key, target: 'VERSION', result: 'EQUAL', version: '0' }],
33
+ success: [{ requestPut: { key, value: encode(JSON.stringify(record)) } }],
34
+ failure: [{ requestRange: { key } }]
35
+ });
36
+ if (body.succeeded === true) {
37
+ return { won: true, record };
38
+ }
39
+ const response = body.responses?.[0];
40
+ const existing = (response?.response_range ?? response?.responseRange)?.kvs?.[0]?.value;
41
+ return { won: false, record: existing ? JSON.parse(decode(existing)) : record };
42
+ },
43
+ async list() {
44
+ const body = await call('/v3/kv/range', { key: encode(prefix), rangeEnd: end });
45
+ return (body.kvs ?? []).map(({ key, value }) => {
46
+ return { id: decode(key).slice(prefix.length), record: JSON.parse(decode(value)) };
47
+ });
48
+ }
49
+ };
50
+ }
@@ -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; });
@@ -5,3 +5,5 @@ export { default as schedule } from './schedule.js';
5
5
  export { default as assignmentAgent } from './agent.js';
6
6
  export { default as controller, reconcile } from './controller.js';
7
7
  export function publishCatalog(store, catalog, expectedRevision) { return store.publish(catalog, expectedRevision); }
8
+ export { default as createOnlyJSON } from './createOnlyJSON.js';
9
+ export { default as jsonAssignments } from './jsonAssignments.js';
@@ -0,0 +1,30 @@
1
+ function encoded(value) {
2
+ return Buffer.from(value).toString('base64');
3
+ }
4
+
5
+ function put(key, value) {
6
+ return { key: encoded(key), value: encoded(JSON.stringify(value)) };
7
+ }
8
+
9
+ /** Writes independent application records under a caller-owned assignment prefix. */
10
+ export default function jsonAssignments(call, prefix) {
11
+ function key(id) {
12
+ return `${prefix.replace(/\/$/u, '')}/assignments/${id}`;
13
+ }
14
+ return {
15
+ write(id, value) {
16
+ return call('/v3/kv/put', put(key(id), value));
17
+ },
18
+ async compareAndSet(id, revision, value) {
19
+ const path = key(id);
20
+ const version = revision ? { target: 'MOD', 'mod_revision': String(revision) }
21
+ : { target: 'VERSION', version: '0' };
22
+ const result = await call('/v3/kv/txn', {
23
+ compare: [{ key: encoded(path), result: 'EQUAL', ...version }],
24
+ success: [{ 'request_put': put(path, value) }],
25
+ failure: []
26
+ });
27
+ return result?.succeeded === true;
28
+ }
29
+ };
30
+ }
@@ -0,0 +1,69 @@
1
+ import locate from './locateMachineMetric.js';
2
+
3
+ /**
4
+ * Reads a sensor series for one measurement mode.
5
+ *
6
+ * @param {object} sensor - plant sensor
7
+ * @param {object} args - from, to, step, mode
8
+ * @returns {Promise<Array>} series rows
9
+ *
10
+ * @example
11
+ * seriesOf(sensor, { from, to, step: 60 });
12
+ */
13
+ function seriesOf(sensor, args) {
14
+ const range = { end: new Date(args.to), start: new Date(args.from) };
15
+ const step = args.step * 1000;
16
+ if (args.mode === 'samples') {
17
+ if (typeof sensor.samples !== 'function') {
18
+ throw Object.assign(new Error('Historical raw density is unavailable: this sensor does not support raw samples'), { code: 'SCADA_HISTORY_DENSITY_UNAVAILABLE', status: 409, statusCode: 409 });
19
+ }
20
+ return sensor.samples(range);
21
+ }
22
+ if (args.mode === 'rises') {
23
+ return sensor.rises(range);
24
+ }
25
+ if (args.mode === 'changes') {
26
+ return sensor.changes(range);
27
+ }
28
+ if (args.mode === 'holds') {
29
+ return sensor.holds(range, step);
30
+ }
31
+ return sensor.measurements(range, step);
32
+ }
33
+
34
+ /**
35
+ * Maps a sensor row to a coverage or measurement point.
36
+ *
37
+ * @param {object} row - sensor sample
38
+ * @returns {object} point with ts
39
+ *
40
+ * @example
41
+ * pointOf({ timestamp: new Date(), value: 1 });
42
+ */
43
+ function pointOf(row) {
44
+ const stamp = row.timestamp instanceof Date ? row.timestamp.toISOString() : row.timestamp;
45
+ const point = { ts: stamp, value: row.value };
46
+ if (typeof row.continuous === 'boolean') { point.continuous = row.continuous; }
47
+ return point;
48
+ }
49
+
50
+ /**
51
+ * Loads points for one namespace path.
52
+ *
53
+ * @param {object} plant - plant hierarchy
54
+ * @param {string} path - namespace path
55
+ * @param {object} args - from, to, step, mode
56
+ * @returns {Promise<Array>} points
57
+ *
58
+ * @example
59
+ * loadSeries(plant, 'site/unit/power', args);
60
+ */
61
+ export default async function loadSeries(plant, path, args) {
62
+ const found = locate(plant, path);
63
+ const sensor = found.metric ? found.machine.sensors[found.metric] : undefined;
64
+ if (!sensor) {
65
+ return [];
66
+ }
67
+ const rows = await seriesOf(sensor, args);
68
+ return rows.map(pointOf);
69
+ }
@@ -0,0 +1,25 @@
1
+ import machineInPlant from '../machineInPlant.js';
2
+
3
+ /**
4
+ * Finds a plant machine from a namespace path or a bare machine id.
5
+ *
6
+ * @param {object} plant - plant hierarchy
7
+ * @param {string} path - namespace path or machine id
8
+ * @returns {object} machine and optional metric key
9
+ *
10
+ * @example
11
+ * locate(plant, 'fixture/site/pump/power').metric;
12
+ */
13
+ export default function locate(plant, path) {
14
+ const parts = path.split('/');
15
+ for (let index = parts.length - 1; index >= 0; index -= 1) {
16
+ const found = machineInPlant(plant, parts[index]);
17
+ if (found) {
18
+ return {
19
+ machine: found.machine,
20
+ metric: index === parts.length - 1 ? '' : parts[parts.length - 1]
21
+ };
22
+ }
23
+ }
24
+ throw new Error(`Namespace machine is missing: ${path}`);
25
+ }
@@ -0,0 +1,78 @@
1
+ import coverageCursor from './coverageCursor.js';
2
+ import locate from './locateMachineMetric.js';
3
+
4
+ /**
5
+ * Wraps a ClickHouse connection as the query_clickhouse port.
6
+ *
7
+ * @param {object} connection - clickhouseConnection
8
+ * @returns {Function} SQL port
9
+ *
10
+ * @example
11
+ * clickhousePort(connection)('SELECT 1');
12
+ */
13
+ export function clickhousePort(connection) {
14
+ return function queryClickhouse(sql) {
15
+ return connection.query(sql);
16
+ };
17
+ }
18
+
19
+ /**
20
+ * Wraps a Postgres pool as the query_postgres port.
21
+ *
22
+ * @param {object} pool - pg pool
23
+ * @returns {Function} SQL port
24
+ *
25
+ * @example
26
+ * postgresPort(pool)('SELECT 1');
27
+ */
28
+ export function postgresPort(pool) {
29
+ return function queryPostgres(sql) {
30
+ return pool.query(sql).then((result) => {
31
+ return result.rows;
32
+ });
33
+ };
34
+ }
35
+
36
+ /**
37
+ * Latest sensor instants for the machine or metric on a path.
38
+ *
39
+ * @param {object} site - plant hierarchy
40
+ * @param {object} args - path
41
+ * @returns {Promise<Array>} samples with ts
42
+ *
43
+ * @example
44
+ * latestSamples(site, { path: 'site/unit/power' });
45
+ */
46
+ async function latestSamples(site, args) {
47
+ const found = locate(site, args.path);
48
+ if (found.metric && found.machine.sensors[found.metric]) {
49
+ const row = await found.machine.sensors[found.metric].current();
50
+ return row.found ? [{ ts: row.timestamp }] : [];
51
+ }
52
+ const keys = Object.keys(found.machine.sensors || {});
53
+ const rows = await Promise.all(keys.map(async (key) => {
54
+ const row = await found.machine.sensors[key].current();
55
+ return row.found ? { ts: row.timestamp } : null;
56
+ }));
57
+ return rows.filter(Boolean);
58
+ }
59
+
60
+ /**
61
+ * Coverage cursor: ingest checkpoint, else latest ClickHouse sample.
62
+ *
63
+ * @param {object|undefined} pool - pg pool
64
+ * @param {object} site - plant hierarchy
65
+ * @returns {Function} cursor port
66
+ *
67
+ * @example
68
+ * cursorPort(pool, site)({ path: 'site/unit' });
69
+ */
70
+ export function cursorPort(pool, site) {
71
+ const bound = coverageCursor(pool, (args) => {
72
+ return latestSamples(site, args);
73
+ });
74
+ return function cursor(args) {
75
+ const found = locate(site, args.path);
76
+ return bound({ machine: found.machine.name(), path: args.path });
77
+ };
78
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Reads a JSON bearer-to-name map when the env value is an object.
3
+ *
4
+ * @param {string} raw - ANALYTICS_MCP_TOKEN value
5
+ * @returns {object|undefined} map or undefined when the value is a single token
6
+ *
7
+ * @example
8
+ * parsedMap('{"secret":"analyst"}').analyst;
9
+ */
10
+ function parsedMap(raw) {
11
+ if (!raw.startsWith('{')) {
12
+ return undefined;
13
+ }
14
+ const parsed = JSON.parse(raw);
15
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
16
+ return parsed;
17
+ }
18
+ return undefined;
19
+ }
20
+
21
+ /**
22
+ * Builds the analyticsMcp bearer map from ANALYTICS_MCP_TOKEN.
23
+ *
24
+ * A JSON object is bearer → caller name. A single token becomes one named
25
+ * caller `agent`.
26
+ *
27
+ * @param {string} raw - environment value
28
+ * @returns {object} token to caller name
29
+ *
30
+ * @example
31
+ * mcpTokens('fixture-token')['fixture-token'];
32
+ */
33
+ export default function mcpTokens(raw) {
34
+ if (typeof raw !== 'string' || raw.length === 0) {
35
+ throw new Error('ANALYTICS_MCP_TOKEN is missing');
36
+ }
37
+ const trimmed = raw.trim();
38
+ const mapped = parsedMap(trimmed);
39
+ if (mapped) {
40
+ return mapped;
41
+ }
42
+ return { [trimmed]: 'agent' };
43
+ }
@@ -7,6 +7,9 @@ function canonical(value) {
7
7
  }
8
8
  return value;
9
9
  }
10
+ export function taskSpecHash(spec) {
11
+ return createHash('sha256').update(JSON.stringify(canonical(spec))).digest('hex');
12
+ }
10
13
  export function identity(input) {
11
14
  if (!input || typeof input.taskId !== 'string' || !/^[\w./:-]{1,200}$/u.test(input.taskId)) {
12
15
  throw new TypeError('Invalid taskId');
@@ -24,7 +27,7 @@ export default function assignment(input, registry) {
24
27
  });
25
28
  const adapter = registry.get(spec.adapter);
26
29
  if (!adapter) { throw new TypeError('Unknown task adapter'); }
27
- const hash = createHash('sha256').update(JSON.stringify(canonical(spec))).digest('hex');
30
+ const hash = taskSpecHash(spec);
28
31
  if (input.specHash && input.specHash !== hash) { throw new TypeError('Invalid specHash'); }
29
32
  return { ...input, spec, specHash: hash, adapter };
30
33
  }
@@ -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';
@@ -2,15 +2,16 @@ import deliveryQueue from './deliveryQueue.js';
2
2
  import { sinks } from './streamPorts.js';
3
3
 
4
4
  /** Configured once per node; queue draining outlives any individual assignment. */
5
- export default function queuedDelivery(env, secrets, supplied) {
5
+ export default function queuedDelivery(env, secrets, supplied, store) {
6
6
  let timer;
7
7
  let stopped = false;
8
8
  let burst = 0;
9
- const queue = supplied ?? (env.COLLECTOR_SPOOL_DIR ? deliveryQueue(env.COLLECTOR_SPOOL_DIR, {
10
- maxBytes: Number(env.COLLECTOR_SPOOL_MAX_BYTES), maxRecords: Number(env.COLLECTOR_SPOOL_MAX_RECORDS ?? 100000), factory(spec) { return sinks().get(spec.type)(spec, { secrets }); },
11
- walCheckpoint: env.COLLECTOR_SPOOL_WAL_CHECKPOINT === 'managed' ? {} : undefined,
9
+ const queue = supplied ?? deliveryQueue({
10
+ maxBytes: Number(env.COLLECTOR_QUEUE_MAX_BYTES ?? 16 * 1024 * 1024),
11
+ maxRecords: Number(env.COLLECTOR_QUEUE_MAX_RECORDS ?? 4096),
12
+ factory(spec) { return sinks().get(spec.type)(spec, { secrets }); },
12
13
  onError(error) { process.stderr.write(`Collector delivery delayed: ${error.message}\n`); }
13
- }) : undefined);
14
+ }, store);
14
15
  function nextDelay(result) {
15
16
  const status = queue.status?.();
16
17
  if (result?.delivered > 0 && status?.ready !== false && status?.drainFull && status.pending > 0) {