@yarkivaev/scada 2.12.2 → 2.14.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 (133) 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 +43 -2
  7. package/package.json +3 -2
  8. package/src/application/control/controlClient.js +1 -1
  9. package/src/application/control/createOnlyJSON.js +50 -0
  10. package/src/application/control/index.js +2 -0
  11. package/src/application/control/jsonAssignments.js +30 -0
  12. package/src/application/foldedMetricsSink.js +1 -1
  13. package/src/application/mcp/loadMetricSeries.js +69 -0
  14. package/src/application/mcp/locateMachineMetric.js +25 -0
  15. package/src/application/mcp/metricQueryPorts.js +78 -0
  16. package/src/application/mcp/parseBearerTokens.js +43 -0
  17. package/src/application/runtime/assignment.js +4 -1
  18. package/src/application/runtime/collectorStartup.js +23 -0
  19. package/src/application/runtime/index.js +2 -0
  20. package/src/application/runtime/runCollector.js +46 -9
  21. package/src/application/runtime/runtimeServices.js +20 -2
  22. package/src/application/runtime/spoolHistory.js +12 -12
  23. package/src/application/runtime/spoolSurface.js +2 -2
  24. package/src/application/runtime/spooledOutput.js +27 -0
  25. package/src/application/siteServer.js +2 -2
  26. package/src/application/supervisorSink.js +5 -6
  27. package/src/application/sync/publishingOperations.js +52 -0
  28. package/src/application/sync/siteSync.js +1 -1
  29. package/src/application/sync/siteSyncRows.js +1 -1
  30. package/src/application/sync/siteSyncSites.js +1 -1
  31. package/src/application/telemetry/telemetryBackfill.js +127 -0
  32. package/src/application/timelineOperatorFromEnv.js +1 -1
  33. package/src/domain/ingest/telemetryTimestamp.js +7 -0
  34. package/src/domain/segment/dispatch.js +19 -17
  35. package/src/domain/segment/historyFold.js +2 -1
  36. package/src/domain/segment/intervalFold.js +1 -1
  37. package/src/domain/segment/segmentContinue.js +1 -1
  38. package/src/infrastructure/catalog/tagCatalog.js +7 -11
  39. package/src/infrastructure/deploy/applyWhenChanged.js +15 -0
  40. package/src/infrastructure/deploy/deploymentKube.js +35 -0
  41. package/src/infrastructure/deploy/executeKubeSeed.js +24 -0
  42. package/src/infrastructure/deploy/executeRelease.js +8 -11
  43. package/src/infrastructure/deploy/operatePostgresMaintenance.js +85 -0
  44. package/src/infrastructure/deploy/postgresMaintenancePlan.js +54 -0
  45. package/src/infrastructure/deploy/postgresRestoreObjects.js +73 -0
  46. package/src/infrastructure/deploy/preflightKubeStorage.js +76 -0
  47. package/src/infrastructure/deploy/prepareKubePrerequisites.js +95 -0
  48. package/src/infrastructure/deploy/verifyCollectorCoverage.js +43 -0
  49. package/src/infrastructure/deploy/verifyPeerBrokerPerimeter.js +24 -0
  50. package/src/infrastructure/http/plant/json/decisionJson.js +1 -1
  51. package/src/infrastructure/http/plant/routes/timelineRoute.js +1 -1
  52. package/src/infrastructure/http/plant/timelineOperator.js +2 -2
  53. package/src/infrastructure/ingest/db/migrationProfile.js +2 -1
  54. package/src/infrastructure/ingest/mysql40/byteReader.js +51 -0
  55. package/src/infrastructure/ingest/mysql40/mysql40.js +116 -0
  56. package/src/infrastructure/ingest/mysql40/packets.js +72 -0
  57. package/src/infrastructure/ingest/mysql40/resultRows.js +92 -0
  58. package/src/infrastructure/ingest/mysql40/scramble.js +89 -0
  59. package/src/infrastructure/ingest/pipelines/segmentPipeline.js +38 -14
  60. package/src/infrastructure/ingest/sinks/contiguousPhases.js +1 -1
  61. package/src/infrastructure/ingest/sinks/continuedSegments.js +9 -8
  62. package/src/infrastructure/ingest/sinks/decisionSegment.js +1 -1
  63. package/src/infrastructure/ingest/sinks/foldingSegments.js +16 -10
  64. package/src/infrastructure/ingest/sinks/{foldCastingPhases.js → repairPhaseOverlaps.js} +17 -29
  65. package/src/infrastructure/ingest/sinks/retagSink.js +1 -1
  66. package/src/infrastructure/ingest/sinks/userDecisionSink.js +1 -1
  67. package/src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js +83 -0
  68. package/src/infrastructure/ingest/telemetry/historyTelemetryMetrics.js +15 -0
  69. package/src/infrastructure/ingest/telemetry/opcuaLocate.js +2 -2
  70. package/src/infrastructure/ingest/telemetry/replayStoredTelemetry.js +125 -0
  71. package/src/infrastructure/ingest/telemetry/telemetryIngest.js +52 -0
  72. package/src/infrastructure/ingest/telemetry/telemetryReplay.js +15 -0
  73. package/src/infrastructure/management/kubeServiceAccount.js +43 -0
  74. package/src/infrastructure/management/kubectlPortForward.js +27 -0
  75. package/src/infrastructure/mdmesh/hmiApplication.js +64 -0
  76. package/src/infrastructure/mdmesh/hmiControl.js +85 -0
  77. package/src/infrastructure/mdmesh/hmiFile.js +69 -0
  78. package/src/infrastructure/mdmesh/hmiMonitor.js +53 -0
  79. package/src/infrastructure/mdmesh/hmiReconcile.js +170 -0
  80. package/src/infrastructure/mdmesh/hmiRuntime.js +33 -0
  81. package/src/infrastructure/mdmesh/index.js +7 -0
  82. package/src/infrastructure/mdmesh/mdmeshClient.js +72 -0
  83. package/src/infrastructure/messaging/ownership/edgeSitesFromEnv.js +137 -0
  84. package/src/infrastructure/messaging/rabbitmq/reconcile.js +71 -12
  85. package/src/infrastructure/messaging/stomp/retagBody.js +1 -1
  86. package/src/infrastructure/messaging/stomp/segmentRetags.js +1 -1
  87. package/src/infrastructure/opcua/health.js +91 -0
  88. package/src/infrastructure/opcua/index.js +1 -0
  89. package/src/infrastructure/persistence/clickhouse/historyObservations.js +149 -0
  90. package/src/infrastructure/persistence/clickhouse/historyRetention.js +94 -0
  91. package/src/infrastructure/persistence/clickhouse/historySourceIdentity.js +34 -0
  92. package/src/infrastructure/persistence/clickhouse/insertMetricRows.js +19 -0
  93. package/src/infrastructure/persistence/clickhouse/jsonMetrics.js +26 -0
  94. package/src/infrastructure/persistence/clickhouse/localHistory.js +51 -0
  95. package/src/infrastructure/persistence/clickhouse/metricsState.js +92 -0
  96. package/src/infrastructure/persistence/clickhouse/rowBinary.js +38 -0
  97. package/src/infrastructure/persistence/clickhouse/telemetryTarget.js +41 -0
  98. package/src/infrastructure/persistence/pg/checkpoints.js +35 -9
  99. package/src/infrastructure/persistence/pg/history.js +74 -56
  100. package/src/infrastructure/persistence/pg/historyContext.js +34 -17
  101. package/src/infrastructure/persistence/pg/historyCorrection.js +5 -2
  102. package/src/infrastructure/persistence/pg/historyFence.js +1 -1
  103. package/src/infrastructure/persistence/pg/historyNativeBounds.js +31 -0
  104. package/src/infrastructure/persistence/pg/historyPurge.js +26 -0
  105. package/src/infrastructure/persistence/pg/historySeed.js +3 -3
  106. package/src/infrastructure/persistence/pg/historySession.js +15 -0
  107. package/src/infrastructure/persistence/pg/intervalFoldPg.js +1 -1
  108. package/src/infrastructure/persistence/pg/prepareRuntimeRole.js +67 -0
  109. package/src/infrastructure/persistence/pg/telemetrySource.js +64 -0
  110. package/src/infrastructure/persistence/postgresPool.js +6 -1
  111. package/src/infrastructure/persistence/runtime/taskStateSqlite.js +37 -0
  112. package/src/infrastructure/persistence/stateDataFromPool.js +16 -2
  113. package/src/infrastructure/replication/canonicalJSON.js +15 -0
  114. package/src/infrastructure/replication/postgresSnapshotReplica.js +129 -0
  115. package/src/infrastructure/replication/postgresSnapshotRuntime.js +40 -0
  116. package/src/infrastructure/replication/snapshotSync.js +61 -0
  117. package/src/infrastructure/replication/tableSnapshotFormat.js +50 -0
  118. package/src/infrastructure/streams/modbusSource.js +1 -1
  119. package/src/infrastructure/streams/stompSend.js +1 -1
  120. package/src/infrastructure/sync/operationAmqp.js +26 -0
  121. package/src/infrastructure/sync/operationEvent.js +10 -0
  122. package/src/infrastructure/tls/mirrorTLSSecret.js +37 -0
  123. package/src/infrastructure/tls/mutualJSON.js +79 -0
  124. package/src/infrastructure/tls/tlsMaterial.js +57 -0
  125. package/stream-processing/src/main/scala/scada/processing/infra/state/AtomicStateFile.scala +7 -0
  126. package/stream-processing/src/main/scala/scada/processing/infra/state/StateJournal.scala +22 -0
  127. package/stream-processing/src/main/scala/scada/processing/runtime/HistoryClient.scala +10 -1
  128. package/stream-processing/src/main/scala/scada/processing/runtime/LiveWorker.scala +70 -0
  129. package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +2 -8
  130. package/stream-processing/src/main/scala/scada/processing/runtime/StatefulHistory.scala +108 -0
  131. package/stream-processing/src/main/scala/scada/processing/runtime/TimelinePublication.scala +43 -0
  132. package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +43 -0
  133. package/src/infrastructure/catalog/tag-catalog.json +0 -27
@@ -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 {
@@ -0,0 +1,127 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { micros as epochMicro } from '../../infrastructure/persistence/clickhouse/rowBinary.js';
3
+
4
+ function valueBits(value) {
5
+ if (typeof value !== 'number' || !Number.isFinite(value)) { throw new Error('Telemetry backfill requires finite Float64 values'); }
6
+ const bytes = Buffer.alloc(8);
7
+ bytes.writeDoubleBE(value);
8
+ return bytes;
9
+ }
10
+
11
+ function appendDigest(hash, row) {
12
+ const topic = Buffer.from(row.topic, 'utf8');
13
+ const size = Buffer.alloc(4);
14
+ size.writeUInt32BE(topic.length);
15
+ const timestamp = Buffer.alloc(8);
16
+ timestamp.writeBigInt64BE(epochMicro(row.ts));
17
+ hash.update(size).update(topic).update(timestamp).update(valueBits(row.value));
18
+ }
19
+
20
+ function failure(message, report) {
21
+ return Object.assign(new Error(message), { report: { ...report } });
22
+ }
23
+
24
+ function indexed(rows, report) {
25
+ const map = new Map();
26
+ for (const row of rows) {
27
+ const key = row.epochMicro === undefined ? epochMicro(row.ts).toString() : String(row.epochMicro);
28
+ if (map.has(key)) { throw failure('Canonical query returned a duplicate telemetry key', report); }
29
+ map.set(key, new Set(row.valueBits.map(String)));
30
+ }
31
+ return map;
32
+ }
33
+
34
+ function missingRows(page, rows, report) {
35
+ const map = indexed(rows, report);
36
+ return page.filter((row) => {
37
+ const stored = map.get(epochMicro(row.ts).toString());
38
+ return !stored?.has(valueBits(row.value).readBigUInt64BE().toString());
39
+ });
40
+ }
41
+
42
+ async function verifyPage(target, page, repair, report) {
43
+ const { topic, ts: first } = page[0];
44
+ const last = page.at(-1).ts;
45
+ const missing = missingRows(page, await target.canonical(topic, first, last), report);
46
+ if (!missing.length) { return; }
47
+ if (!repair) { throw failure('Missing source telemetry keys in target', report); }
48
+ await target.insertRows(missing);
49
+ if (missingRows(page, await target.canonical(topic, first, last), report).length) {
50
+ throw failure('Missing source telemetry keys after repair', report);
51
+ }
52
+ report.missingRepaired += missing.length;
53
+ }
54
+
55
+ function checkPage(page, topic, cursor, upper, pageSize) {
56
+ if (page.length > pageSize) { throw new Error('Source page exceeded configured bound'); }
57
+ let prior = cursor === null ? null : epochMicro(cursor);
58
+ const limit = epochMicro(upper);
59
+ for (const row of page) {
60
+ const timestamp = epochMicro(row.ts);
61
+ if (row.topic !== topic || (prior !== null && timestamp < prior) || timestamp > limit) {
62
+ throw new Error('Source page is outside its ordered topic fence');
63
+ }
64
+ valueBits(row.value);
65
+ prior = timestamp;
66
+ }
67
+ }
68
+
69
+ function topics(source) {
70
+ let previous = null;
71
+ return {
72
+ [Symbol.asyncIterator]() { return this; },
73
+ async next() {
74
+ const topic = await source.nextTopic(previous);
75
+ if (topic === null || topic === undefined) { return { done: true }; }
76
+ if (topic === previous) { throw new Error('Source topic discovery did not advance'); }
77
+ previous = topic;
78
+ return { done: false, value: topic };
79
+ }
80
+ };
81
+ }
82
+
83
+ function pages(source, topic, upper, pageSize) {
84
+ let cursor = null;
85
+ return {
86
+ [Symbol.asyncIterator]() { return this; },
87
+ async next() {
88
+ const page = await source.page(topic, cursor, upper, pageSize);
89
+ checkPage(page, topic, cursor, upper, pageSize);
90
+ if (!page.length) { return { done: true }; }
91
+ cursor = page.at(-1).ts;
92
+ return { done: false, value: page };
93
+ }
94
+ };
95
+ }
96
+
97
+ async function progress(state, topic, cursor, upper) {
98
+ if (state.report.sourceCount < state.nextProgress) { return; }
99
+ await state.onProgress({ ...state.report, topic, cursor, upper });
100
+ state.nextProgress = (Math.floor(state.report.sourceCount / 1000000) + 1) * 1000000;
101
+ }
102
+
103
+ async function topicBackfill(state, topic) {
104
+ const upper = await state.source.upper(topic);
105
+ if (!upper) { return; }
106
+ state.report.topics += 1;
107
+ for await (const page of pages(state.source, topic, upper, state.pageSize)) {
108
+ if (state.mode === 'copy') { await state.target.insertRows(page); }
109
+ else { await verifyPage(state.target, page, state.mode === 'repair', state.report); }
110
+ for (const row of page) { appendDigest(state.hash, row); }
111
+ state.report.sourceCount += page.length;
112
+ await progress(state, topic, page.at(-1).ts, upper);
113
+ }
114
+ }
115
+
116
+ /** Copy or reconcile ordered measurement pages while preserving the source's exact raw values. */
117
+ export default async function telemetryBackfill({ source, target }, { mode = 'copy', pageSize = 20000, onProgress = () => { return undefined; } } = {}) {
118
+ const operation = mode.toLowerCase();
119
+ if (!['copy', 'verify', 'repair'].includes(operation)) { throw new Error('Mode must be copy, verify or repair'); }
120
+ if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > 100000) { throw new Error('Page size must be between 1 and 100000'); }
121
+ const report = { mode: operation, sourceCount: 0, topics: 0, missingRepaired: 0, conflictCount: 0 };
122
+ const hash = createHash('sha256');
123
+ const state = { source, target, report, hash, mode: operation, pageSize, onProgress, nextProgress: 1000000 };
124
+ for await (const topic of topics(source)) { await topicBackfill(state, topic); }
125
+ return { ...report, digest: hash.digest('hex'),
126
+ digestEncoding: 'sha256(length32be(topicUTF8),topicUTF8,epochMicroInt64be,valueFloat64be)' };
127
+ }
@@ -10,7 +10,7 @@ export default function timelineOperatorFromEnv(catalog, env, config) {
10
10
  const options = {
11
11
  provider: catalog.provider,
12
12
  requireOperator: env.REQUIRE_OPERATOR === 'true',
13
- defaultUser: env.HMI_OPERATOR_USER || 'hmi-kiosk'
13
+ defaultUser: env.HMI_OPERATOR_USER
14
14
  };
15
15
  if (config && config.anonymousUsers) {
16
16
  options.anonymousUsers = config.anonymousUsers;
@@ -0,0 +1,7 @@
1
+ /** Legacy metrics tables can supply epoch seconds, epoch milliseconds, or UTC text. */
2
+ export default function telemetryTimestamp(timestamp) {
3
+ if (typeof timestamp === 'number') {
4
+ return timestamp < 1e12 ? timestamp * 1000 : timestamp;
5
+ }
6
+ return Date.parse(`${String(timestamp).trim().replace(' ', 'T').replace(/Z$/u, '')}Z`);
7
+ }
@@ -42,10 +42,11 @@ function continued(records) {
42
42
  });
43
43
  }
44
44
 
45
- function collapsed(records) {
45
+ function collapsed(records, preserveCoverage) {
46
46
  const next = [];
47
47
  for (const batch of grouped(continued(records)).values()) {
48
- next.push(...uniqueStarts(historyFold([], batch)).map(pointed));
48
+ const rows = uniqueStarts(historyFold([], batch));
49
+ next.push(...(preserveCoverage ? rows : rows.map(pointed)));
49
50
  }
50
51
  return next;
51
52
  }
@@ -60,23 +61,21 @@ function collapsed(records) {
60
61
  * @returns {Promise<void>}
61
62
  */
62
63
  async function pendingInClient(segmentSink, closer, record, transaction) {
63
- const live = pointed(record);
64
- await closer.close(live.machine, live.start_time, live.kind || 'phase', transaction, live.name);
65
- await segmentSink.write([live], transaction);
64
+ await closer.close(record.machine, record.start_time, record.kind || 'phase', transaction, record.name);
65
+ await segmentSink.write([record], transaction);
66
66
  }
67
67
  async function persistPending(segmentSink, closer, pool, record) {
68
- const live = pointed(record);
69
- const kind = live.kind || 'phase';
68
+ const kind = record.kind || 'phase';
70
69
  if (!pool || typeof pool.connect !== 'function') {
71
- await closer.close(live.machine, live.start_time, kind, null, live.name);
72
- await segmentSink.write([live]);
70
+ await closer.close(record.machine, record.start_time, kind, null, record.name);
71
+ await segmentSink.write([record]);
73
72
  return;
74
73
  }
75
74
  const client = await pool.connect();
76
75
  try {
77
76
  await client.query('BEGIN');
78
- await closer.close(live.machine, live.start_time, kind, client, live.name);
79
- await segmentSink.write([live], client);
77
+ await closer.close(record.machine, record.start_time, kind, client, record.name);
78
+ await segmentSink.write([record], client);
80
79
  await client.query('COMMIT');
81
80
  } catch (error) {
82
81
  await client.query('ROLLBACK').catch((ignored) => { return ignored; });
@@ -124,16 +123,18 @@ async function writeCompleted(segmentSink, closer, record, transaction) {
124
123
  }
125
124
 
126
125
  /** Writes a consecutive run of phase records through one sink call. */
127
- async function writeOwned(segmentSink, closer, records, transaction) {
126
+ async function writeOwned(segmentSink, closer, records, transaction, preserveCoverage) {
128
127
  if (!records.length) {
129
128
  return;
130
129
  }
131
- const folded = collapsed(records);
130
+ const folded = collapsed(records, preserveCoverage);
132
131
  await closePending(closer, folded, transaction);
133
132
  await segmentSink.write(folded, transaction);
134
133
  }
135
134
 
136
- export default function segmentDispatch(segmentSink, retag, splitSink, closer, pool) {
135
+ // eslint-disable-next-line max-params -- Existing sink ports and pool retain their public call convention.
136
+ export default function segmentDispatch(segmentSink, retag, splitSink, closer, pool, { preserveCoverage = false } = {}) {
137
+ function normalize(record) { return preserveCoverage ? record : pointed(record); }
137
138
  return {
138
139
  async accept(record, transaction) {
139
140
  if (record.type === 'retag') {
@@ -155,7 +156,8 @@ export default function segmentDispatch(segmentSink, retag, splitSink, closer, p
155
156
  await writeCompleted(segmentSink, closer, record, transaction);
156
157
  return;
157
158
  }
158
- await (transaction ? pendingInClient(segmentSink, closer, record, transaction) : persistPending(segmentSink, closer, pool, record));
159
+ await (transaction ? pendingInClient(segmentSink, closer, normalize(record), transaction)
160
+ : persistPending(segmentSink, closer, pool, normalize(record)));
159
161
  },
160
162
  async acceptMany(records, transaction) {
161
163
  const phases = [];
@@ -164,12 +166,12 @@ export default function segmentDispatch(segmentSink, retag, splitSink, closer, p
164
166
  phases.push(record);
165
167
  } else {
166
168
  // eslint-disable-next-line no-await-in-loop
167
- await writeOwned(segmentSink, closer, phases.splice(0), transaction);
169
+ await writeOwned(segmentSink, closer, phases.splice(0), transaction, preserveCoverage);
168
170
  // eslint-disable-next-line no-await-in-loop
169
171
  await this.accept(record, transaction);
170
172
  }
171
173
  }
172
- await writeOwned(segmentSink, closer, phases, transaction);
174
+ await writeOwned(segmentSink, closer, phases, transaction, preserveCoverage);
173
175
  }
174
176
  };
175
177
  }
@@ -37,7 +37,8 @@ function overlaps(left, right) {
37
37
 
38
38
  function liveJoin(left, right) {
39
39
  return left.name === right.name && (left.duration === 0 || right.duration === 0)
40
- && instant(left.start_time) <= instant(right.start_time);
40
+ && instant(left.start_time) <= instant(right.start_time)
41
+ && instant(left.end_time) >= instant(right.start_time);
41
42
  }
42
43
 
43
44
  function covers(outer, inner) {
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * @example
8
8
  * const fold = intervalFold(port);
9
- * await fold.accept({ machine: 'cm8', kind: 'ladle_moving', value: 1, ts: Date.now() });
9
+ * await fold.accept({ machine: 'line-8', kind: 'axis_moving', value: 1, ts: Date.now() });
10
10
  */
11
11
  export default function intervalFold(port) {
12
12
  return {
@@ -2,7 +2,7 @@
2
2
  * Pulls a later fragment of the same segment back onto the previous row
3
3
  * when the uncovered gap is still inside the segmentation continuity budget.
4
4
  * An overlapping island that starts before the pending heartbeat end stays
5
- * one segment instead of a second heating.
5
+ * one segment instead of starting a second span.
6
6
  *
7
7
  * @param {number} budgetSeconds - maximum uncovered gap that stays one segment
8
8
  * @returns {function} apply(record, prior) -> record