@yarkivaev/scada 2.12.2 → 2.13.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 (75) hide show
  1. package/README.md +1 -1
  2. package/db/migrations/E0013__history_staged_corrections.sql +1 -1
  3. package/db/migrations/E0017__history_live_covering.sql +1 -1
  4. package/db/migrations/E0025__history_processor_properties.sql +76 -0
  5. package/db/migrations/E0026__history_processor_properties_grants.sql +1 -0
  6. package/index.js +14 -2
  7. package/package.json +1 -1
  8. package/src/application/foldedMetricsSink.js +1 -1
  9. package/src/application/runtime/collectorStartup.js +23 -0
  10. package/src/application/runtime/index.js +2 -0
  11. package/src/application/runtime/runCollector.js +46 -9
  12. package/src/application/runtime/runtimeServices.js +20 -2
  13. package/src/application/runtime/spoolHistory.js +12 -12
  14. package/src/application/runtime/spoolSurface.js +2 -2
  15. package/src/application/runtime/spooledOutput.js +27 -0
  16. package/src/application/siteServer.js +2 -2
  17. package/src/application/supervisorSink.js +5 -6
  18. package/src/application/sync/publishingOperations.js +52 -0
  19. package/src/application/sync/siteSync.js +1 -1
  20. package/src/application/sync/siteSyncRows.js +1 -1
  21. package/src/application/sync/siteSyncSites.js +1 -1
  22. package/src/application/telemetry/telemetryBackfill.js +127 -0
  23. package/src/application/timelineOperatorFromEnv.js +1 -1
  24. package/src/domain/ingest/telemetryTimestamp.js +7 -0
  25. package/src/domain/segment/dispatch.js +19 -17
  26. package/src/domain/segment/historyFold.js +2 -1
  27. package/src/domain/segment/intervalFold.js +1 -1
  28. package/src/domain/segment/segmentContinue.js +1 -1
  29. package/src/infrastructure/catalog/tagCatalog.js +7 -11
  30. package/src/infrastructure/http/plant/json/decisionJson.js +1 -1
  31. package/src/infrastructure/http/plant/routes/timelineRoute.js +1 -1
  32. package/src/infrastructure/http/plant/timelineOperator.js +2 -2
  33. package/src/infrastructure/ingest/db/migrationProfile.js +2 -1
  34. package/src/infrastructure/ingest/pipelines/segmentPipeline.js +38 -14
  35. package/src/infrastructure/ingest/sinks/contiguousPhases.js +1 -1
  36. package/src/infrastructure/ingest/sinks/continuedSegments.js +9 -8
  37. package/src/infrastructure/ingest/sinks/decisionSegment.js +1 -1
  38. package/src/infrastructure/ingest/sinks/foldingSegments.js +16 -10
  39. package/src/infrastructure/ingest/sinks/{foldCastingPhases.js → repairPhaseOverlaps.js} +17 -29
  40. package/src/infrastructure/ingest/sinks/retagSink.js +1 -1
  41. package/src/infrastructure/ingest/sinks/userDecisionSink.js +1 -1
  42. package/src/infrastructure/ingest/telemetry/historyTelemetryMetrics.js +15 -0
  43. package/src/infrastructure/ingest/telemetry/opcuaLocate.js +2 -2
  44. package/src/infrastructure/ingest/telemetry/telemetryIngest.js +52 -0
  45. package/src/infrastructure/ingest/telemetry/telemetryReplay.js +15 -0
  46. package/src/infrastructure/messaging/stomp/retagBody.js +1 -1
  47. package/src/infrastructure/messaging/stomp/segmentRetags.js +1 -1
  48. package/src/infrastructure/persistence/clickhouse/historyObservations.js +149 -0
  49. package/src/infrastructure/persistence/clickhouse/historyRetention.js +94 -0
  50. package/src/infrastructure/persistence/clickhouse/historySourceIdentity.js +34 -0
  51. package/src/infrastructure/persistence/clickhouse/insertMetricRows.js +19 -0
  52. package/src/infrastructure/persistence/clickhouse/jsonMetrics.js +26 -0
  53. package/src/infrastructure/persistence/clickhouse/localHistory.js +51 -0
  54. package/src/infrastructure/persistence/clickhouse/metricsState.js +92 -0
  55. package/src/infrastructure/persistence/clickhouse/rowBinary.js +38 -0
  56. package/src/infrastructure/persistence/clickhouse/telemetryTarget.js +41 -0
  57. package/src/infrastructure/persistence/pg/checkpoints.js +35 -9
  58. package/src/infrastructure/persistence/pg/history.js +74 -56
  59. package/src/infrastructure/persistence/pg/historyContext.js +34 -17
  60. package/src/infrastructure/persistence/pg/historyCorrection.js +5 -2
  61. package/src/infrastructure/persistence/pg/historyFence.js +1 -1
  62. package/src/infrastructure/persistence/pg/historyNativeBounds.js +31 -0
  63. package/src/infrastructure/persistence/pg/historyPurge.js +26 -0
  64. package/src/infrastructure/persistence/pg/historySeed.js +3 -3
  65. package/src/infrastructure/persistence/pg/historySession.js +15 -0
  66. package/src/infrastructure/persistence/pg/intervalFoldPg.js +1 -1
  67. package/src/infrastructure/persistence/pg/telemetrySource.js +64 -0
  68. package/src/infrastructure/persistence/postgresPool.js +6 -1
  69. package/src/infrastructure/persistence/runtime/taskStateSqlite.js +37 -0
  70. package/src/infrastructure/persistence/stateDataFromPool.js +16 -2
  71. package/src/infrastructure/streams/modbusSource.js +1 -1
  72. package/src/infrastructure/streams/stompSend.js +1 -1
  73. package/src/infrastructure/sync/operationAmqp.js +26 -0
  74. package/src/infrastructure/sync/operationEvent.js +10 -0
  75. package/src/infrastructure/catalog/tag-catalog.json +0 -27
package/README.md CHANGED
@@ -18,6 +18,6 @@ For high availability, agents can run collector copies and Stream Worker candida
18
18
 
19
19
  ## Package boundary
20
20
 
21
- SCADA owns the shared collection and processing engines, storage and APIs. Plant packages such as `sokol-scada` supply the deployment DSL, device mappings, business rules, routes and HMI. See the [package boundary](docs/architecture/package-boundary.md).
21
+ SCADA owns the shared collection and processing engines, storage and APIs. Plant applications supply the deployment DSL, device mappings, business rules, routes and HMI. See the [package boundary](docs/architecture/package-boundary.md).
22
22
 
23
23
  [MIT license](LICENSE)
@@ -32,7 +32,7 @@ CREATE OR REPLACE FUNCTION history_apply_correction(p_work UUID,p_machine TEXT,p
32
32
  RETURNS INTEGER LANGUAGE plpgsql AS $$
33
33
  DECLARE w history_work%ROWTYPE; item history_corrections%ROWTYPE; owner history_annotations%ROWTYPE;
34
34
  tail segments%ROWTYPE; lo TIMESTAMPTZ; hi TIMESTAMPTZ; a TIMESTAMPTZ; b TIMESTAMPTZ;
35
- incoming JSONB; inherited JSONB; endpoint_cut BOOLEAN; inserted INTEGER := 0; keys TEXT[] := ARRAY['casting','cadence_rule','cadence_threshold_ms','casting_detected_at','source_interrupted'];
35
+ incoming JSONB; inherited JSONB; endpoint_cut BOOLEAN; inserted INTEGER := 0; keys TEXT[] := ARRAY[]::TEXT[];
36
36
  BEGIN
37
37
  SELECT * INTO STRICT w FROM history_work WHERE id=p_work AND machine=p_machine;
38
38
  IF p_converged THEN
@@ -3,7 +3,7 @@ CREATE OR REPLACE FUNCTION history_apply_correction(p_work UUID,p_machine TEXT,p
3
3
  RETURNS INTEGER LANGUAGE plpgsql AS $$
4
4
  DECLARE w history_work%ROWTYPE; item history_corrections%ROWTYPE; owner history_annotations%ROWTYPE;
5
5
  tail segments%ROWTYPE; lo TIMESTAMPTZ; hi TIMESTAMPTZ; a TIMESTAMPTZ; b TIMESTAMPTZ;
6
- incoming JSONB; inherited JSONB; endpoint_cut BOOLEAN; inserted INTEGER := 0; keys TEXT[] := ARRAY['casting','cadence_rule','cadence_threshold_ms','casting_detected_at','source_interrupted'];
6
+ incoming JSONB; inherited JSONB; endpoint_cut BOOLEAN; inserted INTEGER := 0; keys TEXT[] := ARRAY[]::TEXT[];
7
7
  BEGIN
8
8
  SELECT * INTO STRICT w FROM history_work WHERE id=p_work AND machine=p_machine;
9
9
  IF p_converged THEN
@@ -0,0 +1,76 @@
1
+ -- The caller declares processor-owned fields for each correction transaction.
2
+ -- Keep the four-argument function for clients deployed before this migration.
3
+ CREATE OR REPLACE FUNCTION history_apply_correction(p_work UUID,p_machine TEXT,p_scale INTEGER,p_converged BOOLEAN,p_processor_properties TEXT[])
4
+ RETURNS INTEGER LANGUAGE plpgsql AS $$
5
+ DECLARE w history_work%ROWTYPE; item history_corrections%ROWTYPE; owner history_annotations%ROWTYPE;
6
+ tail segments%ROWTYPE; lo TIMESTAMPTZ; hi TIMESTAMPTZ; a TIMESTAMPTZ; b TIMESTAMPTZ;
7
+ incoming JSONB; inherited JSONB; endpoint_cut BOOLEAN; inserted INTEGER := 0; keys TEXT[] := COALESCE(p_processor_properties, ARRAY[]::TEXT[]);
8
+ BEGIN
9
+ SELECT * INTO STRICT w FROM history_work WHERE id=p_work AND machine=p_machine;
10
+ IF p_converged THEN
11
+ FOR item IN SELECT * FROM history_corrections WHERE work_id=w.id AND generation=w.generation AND duration=0 LOOP
12
+ SELECT * INTO tail FROM segments WHERE machine=p_machine AND kind=item.kind AND name=item.name
13
+ AND start_time<=item.end_time AND end_time>item.end_time ORDER BY end_time DESC LIMIT 1;
14
+ IF FOUND THEN
15
+ UPDATE history_corrections SET end_time=tail.end_time,
16
+ duration=CASE WHEN tail.duration=0 THEN 0 ELSE extract(epoch FROM tail.end_time-item.start_time) END
17
+ WHERE work_id=w.id AND generation=w.generation AND kind=item.kind AND start_time=item.start_time;
18
+ END IF;
19
+ END LOOP;
20
+ END IF;
21
+ lo := 'epoch'::timestamptz+(w.correction_from/p_scale)*interval '1 millisecond';
22
+ hi := 'epoch'::timestamptz+(w.correction_until/p_scale)*interval '1 millisecond';
23
+ SELECT least(lo,COALESCE(min(start_time),lo)),greatest(hi,COALESCE(max(end_time),hi)) INTO lo,hi
24
+ FROM history_corrections WHERE work_id=w.id AND generation=w.generation;
25
+ INSERT INTO history_annotations(machine,kind,start_time,name,end_time,duration,tags,properties,resolved,consumed)
26
+ SELECT machine,kind,start_time,name,end_time,duration,tags,properties,resolved,consumed FROM segments
27
+ WHERE machine=p_machine AND kind='phase' AND start_time<=hi AND end_time>=lo
28
+ ON CONFLICT(machine,kind,start_time,name) DO UPDATE SET end_time=greatest(history_annotations.end_time,EXCLUDED.end_time),
29
+ duration=EXCLUDED.duration,tags=EXCLUDED.tags,properties=EXCLUDED.properties,resolved=EXCLUDED.resolved,consumed=EXCLUDED.consumed;
30
+ UPDATE segments SET end_time=lo,duration=greatest(0,extract(epoch FROM lo-start_time)),updated_at=clock_timestamp()
31
+ WHERE machine=p_machine AND kind='phase' AND start_time<lo AND end_time>lo AND duration>0;
32
+ DELETE FROM segments WHERE machine=p_machine AND kind='phase' AND start_time>=lo
33
+ AND (start_time<hi OR (start_time=hi AND end_time=hi));
34
+ FOR item IN SELECT * FROM history_corrections WHERE work_id=w.id AND generation=w.generation ORDER BY start_time LOOP
35
+ SELECT EXISTS(SELECT 1 FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name
36
+ AND start_time=item.end_time AND end_time=item.end_time) INTO endpoint_cut;
37
+ a := item.start_time;
38
+ FOR b IN SELECT cut FROM (
39
+ SELECT start_time AS cut FROM history_annotations WHERE machine=p_machine AND kind=item.kind
40
+ AND start_time>item.start_time AND start_time<item.end_time
41
+ UNION SELECT item.end_time
42
+ ) boundaries ORDER BY cut LOOP
43
+ SELECT * INTO owner FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name
44
+ AND start_time<=a AND start_time<=item.end_time AND end_time>=item.start_time ORDER BY start_time DESC LIMIT 1;
45
+ IF NOT FOUND THEN
46
+ SELECT * INTO owner FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name
47
+ AND start_time>a AND start_time<=item.end_time AND end_time>=item.start_time ORDER BY start_time LIMIT 1;
48
+ END IF;
49
+ incoming := COALESCE(NULLIF(NULLIF(item.properties,''),'null')::jsonb,'{}'::jsonb);
50
+ inherited := COALESCE(NULLIF(NULLIF(owner.properties,''),'null')::jsonb,'{}'::jsonb);
51
+ IF jsonb_typeof(incoming)<>'object' THEN incoming:='{}'::jsonb; END IF;
52
+ IF jsonb_typeof(inherited)<>'object' THEN inherited:='{}'::jsonb; END IF;
53
+ INSERT INTO segments(machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed,updated_at)
54
+ VALUES(p_machine,item.kind,item.name,a,b,CASE WHEN item.duration=0 AND b=item.end_time AND NOT endpoint_cut THEN 0 ELSE extract(epoch FROM b-a) END,
55
+ item.options,COALESCE(owner.tags,item.tags),(incoming||(inherited-keys))::text,COALESCE(owner.resolved,item.resolved),COALESCE(owner.consumed,true),clock_timestamp())
56
+ ON CONFLICT(machine,kind,start_time) DO UPDATE SET name=EXCLUDED.name,end_time=EXCLUDED.end_time,duration=EXCLUDED.duration,
57
+ options=EXCLUDED.options,tags=EXCLUDED.tags,properties=EXCLUDED.properties,resolved=EXCLUDED.resolved,consumed=EXCLUDED.consumed,updated_at=EXCLUDED.updated_at;
58
+ inserted:=inserted+1; a:=b;
59
+ END LOOP;
60
+ IF item.start_time<item.end_time AND endpoint_cut THEN
61
+ SELECT * INTO owner FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name AND start_time=item.end_time;
62
+ incoming := COALESCE(NULLIF(NULLIF(item.properties,''),'null')::jsonb,'{}'::jsonb);
63
+ inherited := COALESCE(NULLIF(NULLIF(owner.properties,''),'null')::jsonb,'{}'::jsonb);
64
+ IF jsonb_typeof(incoming)<>'object' THEN incoming:='{}'::jsonb; END IF;
65
+ IF jsonb_typeof(inherited)<>'object' THEN inherited:='{}'::jsonb; END IF;
66
+ INSERT INTO segments(machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed)
67
+ VALUES(p_machine,item.kind,item.name,item.end_time,item.end_time,0,item.options,owner.tags,(incoming||(inherited-keys))::text,owner.resolved,COALESCE(owner.consumed,true))
68
+ ON CONFLICT(machine,kind,start_time) DO NOTHING;
69
+ END IF;
70
+ END LOOP;
71
+ INSERT INTO history_checkpoints(machine,classifier_key,time_ms,state,valid)
72
+ SELECT machine,classifier_key,time_ms,state,true FROM history_staged_checkpoints WHERE work_id=w.id AND generation=w.generation
73
+ ON CONFLICT(machine,classifier_key,time_ms) DO UPDATE SET state=EXCLUDED.state,valid=true;
74
+ RETURN inserted;
75
+ END $$;
76
+ REVOKE ALL ON FUNCTION history_apply_correction(UUID,TEXT,INTEGER,BOOLEAN,TEXT[]) FROM PUBLIC;
@@ -0,0 +1 @@
1
+ GRANT EXECUTE ON FUNCTION history_apply_correction(UUID,TEXT,INTEGER,BOOLEAN,TEXT[]) TO supervisor_sink;
package/index.js CHANGED
@@ -52,7 +52,7 @@ export { default as clickhouseMetricsRelation } from './src/infrastructure/persi
52
52
  export const centralTelemetryVersion = 4;
53
53
  export { default as centralTelemetryPolicy } from './src/infrastructure/ingest/telemetry/centralPolicy.js';
54
54
  export { default as clickhouseSensor } from './src/infrastructure/persistence/clickhouse/sensor.js';
55
- export { default as postgresPool } from './src/infrastructure/persistence/postgresPool.js';
55
+ export { default as postgresPool, holdClient as holdPostgresClient, openPostgresPool } from './src/infrastructure/persistence/postgresPool.js';
56
56
  export { metricsSinkFromPool as pgMetricsSink } from './src/infrastructure/persistence/pg/metrics.js';
57
57
  export { pgMetricsSensor } from './src/infrastructure/persistence/metricsSensor.js';
58
58
  export { default as stompTimeline } from './src/infrastructure/messaging/stomp/timeline.js';
@@ -61,7 +61,7 @@ export { default as machineOwners } from './src/infrastructure/messaging/ownersh
61
61
  export { default as httpTimeline } from './src/infrastructure/messaging/ownership/httpTimeline.js';
62
62
  export { default as httpOperations } from './src/infrastructure/messaging/ownership/httpOperations.js';
63
63
  export { default as ownerTimeline } from './src/infrastructure/messaging/ownership/ownerTimeline.js';
64
- export { default as stateDataFromPool } from './src/infrastructure/persistence/stateDataFromPool.js';
64
+ export { default as stateDataFromPool, withTelemetryState } from './src/infrastructure/persistence/stateDataFromPool.js';
65
65
  export { default as stateDataFromMemory } from './src/infrastructure/persistence/stateDataFromMemory.js';
66
66
  export { default as stateDataFake } from './src/infrastructure/persistence/stateDataFromMemory.js';
67
67
  export { default as supervisorSink, readDeploymentConfig } from './src/application/supervisorSink.js';
@@ -82,6 +82,9 @@ export { default as activityTracking } from './src/infrastructure/ingest/activit
82
82
  export { default as amqpMetricsIngest } from './src/infrastructure/ingest/telemetry/amqpMetricsIngest.js';
83
83
  export { default as amqpMqttRelay } from './src/infrastructure/ingest/telemetry/amqpMqttRelay.js';
84
84
  export { default as operationSyncIngest } from './src/infrastructure/sync/operationSyncIngest.js';
85
+ export { default as operationEvent } from './src/infrastructure/sync/operationEvent.js';
86
+ export { default as operationAmqp } from './src/infrastructure/sync/operationAmqp.js';
87
+ export { default as publishingOperations } from './src/application/sync/publishingOperations.js';
85
88
  export { default as ingestCheckpointMemory, ingestCheckpointPg } from './src/infrastructure/ingest/ingestCheckpoint.js';
86
89
  export { default as bindSilentStreams } from './src/application/bindSilentStreams.js';
87
90
  export { default as exportQuery } from './src/application/export/exportQuery.js';
@@ -114,6 +117,15 @@ export { default as collectorProcesses } from './src/application/deploy/collecto
114
117
  export { default as executeStages } from './src/infrastructure/deploy/executeStages.js';
115
118
 
116
119
  export { default as historyPg, historyProtocol } from './src/infrastructure/persistence/pg/history.js';
120
+ export { default as clickhouseLocalHistory, clickhouseHistoryComment } from './src/infrastructure/persistence/clickhouse/localHistory.js';
117
121
  export { historyReplicaProtocol } from './src/infrastructure/persistence/pg/historyReplicaOutbox.js';
118
122
 
119
123
  export { historyWriteFence } from './src/infrastructure/persistence/pg/segmentWriteFence.js';
124
+ export { default as telemetryBackfill } from './src/application/telemetry/telemetryBackfill.js';
125
+ export { default as telemetryIngest } from './src/infrastructure/ingest/telemetry/telemetryIngest.js';
126
+ export { default as telemetryReplay } from './src/infrastructure/ingest/telemetry/telemetryReplay.js';
127
+ export { default as clickhouseJsonMetrics } from './src/infrastructure/persistence/clickhouse/jsonMetrics.js';
128
+ export { default as postgresTelemetrySource } from './src/infrastructure/persistence/pg/telemetrySource.js';
129
+ export { default as clickhouseTelemetryTarget, assertClickhouseBackfillMode } from './src/infrastructure/persistence/clickhouse/telemetryTarget.js';
130
+ export { default as clickhouseMetricsState } from './src/infrastructure/persistence/clickhouse/metricsState.js';
131
+ export { default as historyTelemetryMetrics } from './src/infrastructure/ingest/telemetry/historyTelemetryMetrics.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.12.2",
3
+ "version": "2.13.0",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -12,7 +12,7 @@ import opcuaLocate from '../infrastructure/ingest/telemetry/opcuaLocate.js';
12
12
  * @returns {object} sink
13
13
  *
14
14
  * @example
15
- * const sink = foldedMetricsSink(pgMetrics, pool, { 'tlc-cm8': 'cm8' });
15
+ * const sink = foldedMetricsSink(pgMetrics, pool, { 'tlc-line-8': 'line-8' });
16
16
  */
17
17
  export default function foldedMetricsSink(inner, pool, devices) {
18
18
  if (!devices || Object.keys(devices).length === 0) {
@@ -0,0 +1,23 @@
1
+ import { createServer } from 'node:http';
2
+
3
+ /** Starts only after local recovery. The readiness endpoint tracks individual tasks. */
4
+ export default async function collectorStartup(runtime, { port, host }) {
5
+ const server = createServer((request, response) => {
6
+ if (request.url !== '/startup') { response.writeHead(404).end(); return; }
7
+ const state = runtime.status();
8
+ const ready = !state.fatal && !state.stopping;
9
+ response.writeHead(ready ? 200 : 503, { 'content-type': 'application/json', 'cache-control': 'no-store' });
10
+ response.end(JSON.stringify({ localRecoveryComplete: ready }));
11
+ });
12
+ server.requestTimeout = 2000;
13
+ server.headersTimeout = 2000;
14
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve); });
15
+ let closing;
16
+ return { stop() {
17
+ closing ??= new Promise((resolve, reject) => {
18
+ server.closeAllConnections();
19
+ server.close(error => { if (error) { reject(error); } else { resolve(); } });
20
+ });
21
+ return closing;
22
+ } };
23
+ }
@@ -8,3 +8,5 @@ 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
+ export { default as spooledOutput, amqpDestinations } from './spooledOutput.js';
@@ -1,4 +1,5 @@
1
1
  import { readManifest, validateManifest } from './manifest.js';
2
+ import collectorStartup from './collectorStartup.js';
2
3
  import collectorSignals from './collectorSignals.js';
3
4
  import createRuntime from './runtime.js';
4
5
  import runtimeServices from './runtimeServices.js';
@@ -30,6 +31,7 @@ function healthView(runtime, state) {
30
31
  }
31
32
  async function initialize(collector, owned, state, { env, registry, store }) {
32
33
  const { runtime } = collector;
34
+ if (state.stopped) { throw new Error('Collector stopped during recovery'); }
33
35
  await owned.open?.();
34
36
  if (state.stopped) { throw new Error('Collector stopped during recovery'); }
35
37
  if (store) {
@@ -41,13 +43,46 @@ async function initialize(collector, owned, state, { env, registry, store }) {
41
43
  if (state.stopped) { throw new Error('Collector stopped during recovery'); }
42
44
  state.initialized = true;
43
45
  }
46
+ function startupPort(env) {
47
+ if (env.COLLECTOR_STARTUP_PORT === undefined) { return null; }
48
+ const port = Number(env.COLLECTOR_STARTUP_PORT);
49
+ if (!Number.isInteger(port) || port < 1 || port > 65535) { throw new TypeError('Invalid collector startup port'); }
50
+ return port;
51
+ }
52
+ async function startProbe(runtime, state, port, host) {
53
+ if (state.stopped) { throw new Error('Collector stopped during recovery'); }
54
+ if (port === null) { return; }
55
+ Object.assign(state, { startup: collectorStartup(healthView(runtime, state), { port, host }) });
56
+ await state.startup;
57
+ if (state.stopped) { throw new Error('Collector stopped during recovery'); }
58
+ }
59
+ async function stopListener(listener) {
60
+ const server = await listener?.catch(() => { return null; });
61
+ await server?.stop();
62
+ }
63
+ async function shutdown(runtime, state, owned) {
64
+ state.stopped = true;
65
+ state.detach?.();
66
+ try { await state.agent?.stop(); } finally {
67
+ try { await runtime.stop(); } finally {
68
+ await Promise.all([owned.close(), stopListener(state.health), stopListener(state.startup)]);
69
+ }
70
+ }
71
+ }
44
72
  /** Local executable host. The external agent can instead use createRuntime directly. */
45
73
  // eslint-disable-next-line max-statements
46
74
  export default async function runCollector({ registry, env = process.env, argv = process.argv.slice(2), signals = true, manifestReader = readManifest, ...services }) {
75
+ const probePort = startupPort(env);
76
+ const host = env.COLLECTOR_HEALTH_HOST ?? '127.0.0.1';
47
77
  const store = env.COLLECTOR_CONTROL_ENDPOINTS
48
78
  ? controlStore(clientFromEnv(env, 'COLLECTOR_CONTROL'), env.COLLECTOR_CONTROL_PREFIX) : null;
49
79
  const owned = runtimeServices(env, { ...services, cursor: services.cursor ?? store?.cursor });
50
- const runtime = createRuntime({ registry, ...owned });
80
+ let runtime;
81
+ try { runtime = createRuntime({ registry, ...owned }); }
82
+ catch (error) {
83
+ try { await owned.close(); } catch (cleanup) { throw new AggregateError([error, cleanup], 'Collector startup cleanup failed'); }
84
+ throw error;
85
+ }
51
86
  const state = { initialized: false, failed: false, health: null, reloading: false, stopped: false, detach: null, agent: null };
52
87
  const collector = {
53
88
  runtime,
@@ -60,21 +95,23 @@ export default async function runCollector({ registry, env = process.env, argv =
60
95
  await apply(runtime, document);
61
96
  } finally { Object.assign(state, { reloading: false }); }
62
97
  },
63
- async stop() {
64
- state.stopped = true;
65
- state.detach?.();
66
- await state.agent?.stop();
67
- try { await runtime.stop(); } finally { await Promise.all([owned.close(), state.health?.stop()]); }
98
+ stop() {
99
+ state.shutdown ??= shutdown(runtime, state, owned);
100
+ return state.shutdown;
68
101
  }
69
102
  };
70
103
  if (signals) { state.detach = collectorSignals(collector); }
71
104
  try {
72
- if (env.COLLECTOR_HEALTH_PORT) { Object.assign(state, { health: await runtimeHealth(healthView(runtime, state), {
73
- port: Number(env.COLLECTOR_HEALTH_PORT), host: env.COLLECTOR_HEALTH_HOST ?? '127.0.0.1',
74
- handle: spoolSurface(owned.deliveryQueue, env.STATE_HTTP_TOKEN), staleMs: Number(env.COLLECTOR_LIVE_STALE_MS ?? 30000) }) }); }
105
+ if (env.COLLECTOR_HEALTH_PORT) {
106
+ Object.assign(state, { health: runtimeHealth(healthView(runtime, state), {
107
+ port: Number(env.COLLECTOR_HEALTH_PORT), host,
108
+ handle: spoolSurface(owned.deliveryQueue, env.STATE_HTTP_TOKEN, services.spoolMachine), staleMs: Number(env.COLLECTOR_LIVE_STALE_MS ?? 30000) }) });
109
+ await state.health;
110
+ }
75
111
  const recoveryMs = Number(env.COLLECTOR_RECOVERY_TIMEOUT_MS ?? 900000);
76
112
  if (!Number.isSafeInteger(recoveryMs) || recoveryMs < 1) { throw new TypeError('Positive collector recovery timeout required'); }
77
113
  await deadline(() => { return initialize(collector, owned, state, { env, registry, store }); }, recoveryMs);
114
+ await startProbe(runtime, state, probePort, host);
78
115
  } catch (error) {
79
116
  Object.assign(state, { failed: true });
80
117
  try { await collector.stop(); } catch (cleanup) { throw new AggregateError([error, cleanup], 'Collector startup cleanup failed'); }
@@ -1,8 +1,19 @@
1
1
  import pg from 'pg';
2
+ import { mkdirSync } from 'node:fs';
3
+ import { join } from 'node:path';
2
4
  import taskStatePg from '../../infrastructure/persistence/runtime/taskStatePg.js';
5
+ import taskStateSqlite from '../../infrastructure/persistence/runtime/taskStateSqlite.js';
3
6
  import deadline from './deadline.js';
4
7
  import queuedDelivery from './queuedDelivery.js';
5
8
 
9
+ function localStore(env, supplied) {
10
+ if (!supplied.localTaskState || supplied.stateStore || env.COLLECTOR_STATE_URL || !env.COLLECTOR_SPOOL_DIR) {
11
+ return undefined;
12
+ }
13
+ mkdirSync(env.COLLECTOR_SPOOL_DIR, { recursive: true });
14
+ return taskStateSqlite(join(env.COLLECTOR_SPOOL_DIR, 'task-state.sqlite'));
15
+ }
16
+
6
17
  /** Storage is optional for live-only tasks and mandatory for durable adapters. */
7
18
  export default function runtimeServices(env, supplied) {
8
19
  const pool = !supplied.stateStore && env.COLLECTOR_STATE_URL ? new pg.Pool({
@@ -11,9 +22,16 @@ export default function runtimeServices(env, supplied) {
11
22
  }) : null;
12
23
  const secrets = supplied.secrets ?? { get(name) { return env[name]; } };
13
24
  const delivery = queuedDelivery(env, secrets, supplied.deliveryQueue);
25
+ const local = localStore(env, supplied);
14
26
  return { ...supplied, secrets, deliveryQueue: delivery.queue,
15
27
  open() { return delivery.open(); },
16
- stateStore: supplied.stateStore ?? (pool ? taskStatePg(pool) : undefined),
17
- async close() { await delivery.stop(); if (pool) { await deadline(() => { return pool.end(); }, 10000); } }
28
+ stateStore: supplied.stateStore ?? (pool ? taskStatePg(pool) : local),
29
+ async close() {
30
+ try { await delivery.stop(); }
31
+ finally {
32
+ local?.close();
33
+ if (pool) { await deadline(() => { return pool.end(); }, 10000); }
34
+ }
35
+ }
18
36
  };
19
37
  }
@@ -2,42 +2,42 @@
2
2
  * HistoryRun and SupervisorSinkCheckpoint view of undelivered collector samples.
3
3
  *
4
4
  * {{{
5
- * spoolHistory({ peek() { return []; } }).work('icht2')
5
+ * spoolHistory({ peek() { return []; } }).work('device-2')
6
6
  * }}}
7
7
  */
8
8
 
9
9
  import { nativeTailProtocol } from '../../infrastructure/persistence/pg/historyNativeBounds.js';
10
10
  import { randomUUID } from 'node:crypto';
11
11
 
12
- function machineOf(key) {
13
- const match = /icht-?(?<n>\d)/iu.exec(String(key).replaceAll('/', '.'));
14
- return match ? `icht${match.groups.n}` : null;
12
+ function machineOf(topic) {
13
+ return topic.split('/')[1] || null;
15
14
  }
16
15
  function channelOf(key) {
17
16
  const parts = String(key).replaceAll('/', '.').split('.');
18
17
  return parts.at(-2) ?? key;
19
18
  }
20
- function sample(record) {
19
+ function sample(record, locate) {
21
20
  const key = record.routingKey ?? record.topic;
22
21
  const raw = record.body ? JSON.parse(Buffer.isBuffer(record.body) ? record.body.toString() : record.body) : record;
23
22
  const time = Number(raw.ts ?? raw.time ?? raw.timestamp);
24
23
  const value = Number(raw.value);
25
24
  if (!key || !Number.isFinite(time) || !Number.isFinite(value)) { return []; }
26
- return [{ eventId: record.eventId ?? `${key}:${time}`, channel: channelOf(key), topic: key.replaceAll('.', '/'),
27
- time, timestamp: time / 1000, value, machine: machineOf(key) }];
25
+ const topic = key.replaceAll('.', '/');
26
+ return [{ eventId: record.eventId ?? `${key}:${time}`, channel: channelOf(key), topic,
27
+ time, timestamp: time / 1000, value, machine: locate(topic) }];
28
28
  }
29
- function unpack(event) {
29
+ function unpack(event, locate) {
30
30
  const payload = event.observation ?? event;
31
- if (Array.isArray(payload.records)) { return payload.records.flatMap(sample); }
32
- return sample({ ...payload, eventId: payload.eventId ?? event.eventId });
31
+ if (Array.isArray(payload.records)) { return payload.records.flatMap((record) => { return sample(record, locate); }); }
32
+ return sample({ ...payload, eventId: payload.eventId ?? event.eventId }, locate);
33
33
  }
34
34
 
35
35
  /** Collector spool as a checkpoint and history receiver. */
36
- export default function spoolHistory(queue) {
36
+ export default function spoolHistory(queue, locate = machineOf) {
37
37
  async function rows() {
38
38
  if (!queue?.peek) { return []; }
39
39
  const listed = await queue.peek(1000);
40
- return listed.flatMap((item) => { return unpack(item.event ?? item); });
40
+ return listed.flatMap((item) => { return unpack(item.event ?? item, locate); });
41
41
  }
42
42
  async function owned(machine) {
43
43
  return (await rows()).filter((row) => { return row.machine === machine; });
@@ -12,9 +12,9 @@ import historyRoutes from '../../infrastructure/http/edge/routes/history/history
12
12
  import spoolHistory from './spoolHistory.js';
13
13
 
14
14
  /** True when the request was a spool history or checkpoint path. */
15
- export default function spoolSurface(queue, token) {
15
+ export default function spoolSurface(queue, token, locate) {
16
16
  if (!queue) { return null; }
17
- const history = spoolHistory(queue);
17
+ const history = spoolHistory(queue, locate);
18
18
  const api = routes([...checkpointRoutes(token ?? null, history), ...historyRoutes(token ?? null, history)]);
19
19
  return (request, result) => {
20
20
  if (!request.url?.startsWith('/v1/')) { return false; }
@@ -0,0 +1,27 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
3
+ /** Persist wire observations without opening a broker connection in the source lifecycle. */
4
+ export default function spooledOutput(context, destinations) {
5
+ if (!context.deliveryQueue) { throw new TypeError('Spooled output requires node deliveryQueue'); }
6
+ return {
7
+ start() { return Promise.resolve(); },
8
+ stop() { return Promise.resolve(); },
9
+ write(records) {
10
+ return records.reduce((pending, record) => {
11
+ return pending.then(async () => {
12
+ context.signal.throwIfAborted();
13
+ const eventId = record.eventId ?? randomUUID();
14
+ const payload = JSON.parse(Buffer.isBuffer(record.body) ? record.body.toString() : record.body);
15
+ const body = Buffer.from(JSON.stringify({ ...payload, eventId,
16
+ collectorId: context.nodeId ?? process.env.COLLECTOR_NODE_ID ?? 'local', taskId: context.taskId }));
17
+ await context.deliveryQueue.accept({ ...record, eventId, body }, destinations);
18
+ context.report?.({ state: 'running' });
19
+ });
20
+ }, Promise.resolve());
21
+ }
22
+ };
23
+ }
24
+ export function amqpDestinations(url, exchange) {
25
+ return [{ id: exchange, type: 'amqp', url,
26
+ options: { exchanges: [{ name: exchange, type: 'topic', options: { durable: true } }] } }];
27
+ }
@@ -21,7 +21,7 @@ function stompFromEnv(env) {
21
21
  login: env.STOMP_LOGIN || 'guest',
22
22
  passcode: env.STOMP_PASSCODE || 'guest',
23
23
  host: env.STOMP_HOST || '/',
24
- operatorUser: env.HMI_OPERATOR_USER || 'hmi-kiosk'
24
+ operatorUser: env.HMI_OPERATOR_USER
25
25
  };
26
26
  }
27
27
 
@@ -135,7 +135,7 @@ async function runSiteSink(sink, http, env) {
135
135
  */
136
136
  export default async function siteServer(config) {
137
137
  const env = collectionEnvironment(config);
138
- const sink = supervisorSink(env, { stateData: config.stateData });
138
+ const sink = supervisorSink(env, { ...config.sinkOptions, stateData: config.stateData });
139
139
  const ops = bindSiteOperations(sink, config.kindSources || config.operationSources);
140
140
  const http = edgeApi(sink.dataAccess, {
141
141
  port: sink.apiPort,
@@ -62,10 +62,7 @@ export function readDeploymentConfig(env) {
62
62
  postgres: env.POSTGRES_URL,
63
63
  postgresAdmin: env.POSTGRES_ADMIN_URL,
64
64
  migrationsMode: migrationMode(env.SUPERVISOR_MIGRATIONS),
65
- apiPort: parseInt(
66
- env.STATE_HTTP_PORT || env.INTERNAL_API_PORT || '8081',
67
- 10
68
- ),
65
+ apiPort: parseInt(env.STATE_HTTP_PORT || env.INTERNAL_API_PORT || '8081', 10),
69
66
  apiToken: env.STATE_HTTP_TOKEN || env.INTERNAL_API_TOKEN,
70
67
  sinkDbProfile: env.SINK_DB_PROFILE === 'central' ? 'central' : 'edge',
71
68
  retentionEnabled: env.RETENTION_ENABLED === 'true',
@@ -75,6 +72,7 @@ export function readDeploymentConfig(env) {
75
72
  pipelines: env.COLLECTOR_MODE !== 'external' && env.SINK_PIPELINES !== 'false',
76
73
  pipeline: {
77
74
  acceptReplicaSegments: env.SINK_DB_PROFILE === 'central' || env.SEGMENT_REPLICA_WRITES === 'true',
75
+ phaseRepairMachines: env.SEGMENT_PHASE_REPAIR_MACHINES === undefined ? undefined : JSON.parse(env.SEGMENT_PHASE_REPAIR_MACHINES),
78
76
  phaseAnchors: phaseAnchors(env.CONTIGUOUS_PHASE_ANCHORS),
79
77
  repairHistoryOnStart: historyRepair(env.SEGMENT_REPAIR_HISTORY_ON_START),
80
78
  transactions: segmentTransactionConfig(env, dbPoolMax),
@@ -133,11 +131,12 @@ async function prepareDatabase(cfg, pool) {
133
131
  export default function supervisorSink(env = process.env, options = {}) {
134
132
  const cfg = readDeploymentConfig(env);
135
133
  const health = ingestHealth(options);
136
- cfg.pipeline.onFatal = (error) => { health.fail(error); };
134
+ Object.assign(cfg.pipeline, options.segmentPolicy, { onFatal(error) { health.fail(error); } });
137
135
  if (cfg.pipeline.transactions.enabled) { cfg.pipeline.onBatch = segmentBatchStats(cfg.pipeline.transactions.statsIntervalMs); }
138
136
  const pool = holdClient(new pg.Pool({ connectionString: cfg.postgres, max: cfg.dbPoolMax }));
139
137
  const metricsEnabled = cfg.sinkDbProfile === 'edge';
140
- const data = stateDataFromPool(pool, { metricsEnabled, historyRetentionDays: Number(env.HISTORY_RETENTION_DAYS ?? 30) });
138
+ const data = stateDataFromPool(pool, { metricsEnabled, historyRetentionDays: Number(env.HISTORY_RETENTION_DAYS ?? 30),
139
+ historyPolicy: options.historyPolicy, checkpointPolicy: options.checkpointPolicy });
141
140
  let recipient;
142
141
  function segments() {
143
142
  recipient ??= segmentRecipient(cfg.postgres,pool,cfg.pipeline);
@@ -0,0 +1,52 @@
1
+ async function publishMany(operations, publish, items) {
2
+ if (typeof operations.upsertMany !== 'function') {
3
+ throw new Error('Operations port must have an upsertMany() method');
4
+ }
5
+ await operations.upsertMany(items);
6
+ for (const item of items) {
7
+ // Preserve request order even when confirmation is asynchronous.
8
+ // eslint-disable-next-line no-await-in-loop
9
+ await publish(item);
10
+ }
11
+ }
12
+
13
+ /** Publish operation changes once the local write succeeds. */
14
+ export default function publishingOperations(operations, publish) {
15
+ if (!operations || typeof operations.upsert !== 'function') {
16
+ throw new Error('Operations port must have an upsert() method');
17
+ }
18
+ if (typeof publish !== 'function') { throw new Error('Publish must be a function'); }
19
+ return {
20
+ listForMachine(machineId, kinds, range) {
21
+ return operations.listForMachine(machineId, kinds, range);
22
+ },
23
+ latestForMachine(machineId, kind, bound) {
24
+ if (typeof operations.latestForMachine !== 'function') {
25
+ throw new Error('Operations port must have a latestForMachine() method');
26
+ }
27
+ return operations.latestForMachine(machineId, kind, bound);
28
+ },
29
+ stream: operations.stream,
30
+ get(machineId, key) {
31
+ return operations.get(machineId, key);
32
+ },
33
+ async upsert(item) {
34
+ await operations.upsert(item);
35
+ await publish(item);
36
+ },
37
+ upsertMany(items) {
38
+ return publishMany(operations, publish, items);
39
+ },
40
+ async remove(machineId, key) {
41
+ const removed = await operations.remove(machineId, key);
42
+ await publish({
43
+ type: 'deleted',
44
+ machine: removed.machine,
45
+ kind: removed.kind,
46
+ key: removed.key,
47
+ occurred_at: removed.occurred_at
48
+ });
49
+ return removed;
50
+ }
51
+ };
52
+ }
@@ -9,7 +9,7 @@ import { siteById } from './siteSyncSites.js';
9
9
  *
10
10
  * @example
11
11
  * const sync = siteSync({ sites, queryFor, targets });
12
- * await sync.run({ site: 'edge-icht-1', from, to, machines: ['icht1'], kinds: ['segments'] });
12
+ * await sync.run({ site: 'edge-drive-1', from, to, machines: ['drive1'], kinds: ['segments'] });
13
13
  */
14
14
  function pull(query, kind, machine, range) {
15
15
  if (kind === 'segments') {
@@ -2,7 +2,7 @@
2
2
  * Maps plant API JSON into local persistence rows for site sync.
3
3
  *
4
4
  * @example
5
- * segmentRow('icht1', { name: 'on', start: '2026-01-01T00:00:00.000Z', end: '...', duration: 60 });
5
+ * segmentRow('drive1', { name: 'on', start: '2026-01-01T00:00:00.000Z', end: '...', duration: 60 });
6
6
  */
7
7
 
8
8
  /**
@@ -7,7 +7,7 @@
7
7
  * @returns {object[]} frozen sites with id, url, optional token and machines
8
8
  *
9
9
  * @example
10
- * siteSyncSites({ SYNC_SITES: '[{"id":"edge-icht-1","url":"http://edge/api/v1"}]' });
10
+ * siteSyncSites({ SYNC_SITES: '[{"id":"edge-drive-1","url":"http://edge/api/v1"}]' });
11
11
  */
12
12
  function parseJson(raw, label) {
13
13
  try {