@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
@@ -67,20 +67,43 @@ async function bindings(api, path, desired, ownsBinding) {
67
67
  return missing.length + stale.length;
68
68
  }
69
69
 
70
- async function shovels(api, path, desired, ownsShovel) {
71
- const current = await api('GET', path);
70
+ async function upsertNamed(api, path, desired, body) {
71
+ const current = await api('GET', path) || [];
72
72
  const changed = desired.filter((item) => {
73
73
  const found = current.find((row) => { return row.name === item.name; });
74
- return !same(found, { value: item.value });
75
- });
76
- const stale = current.filter((item) => {
77
- return ownsShovel?.(item) && !desired.some((row) => { return row.name === item.name; });
74
+ return !same(found, body(item));
78
75
  });
79
76
  await Promise.all(changed.map((item) => {
80
- return api('PUT', `${path}/${encodeURIComponent(item.name)}`, { value: item.value });
77
+ return api('PUT', `${path}/${encodeURIComponent(item.name)}`, body(item));
81
78
  }));
79
+ return { count: changed.length, current };
80
+ }
81
+
82
+ async function pruneNamed(api, path, current, desired, owns) {
83
+ const stale = current.filter((item) => {
84
+ return owns?.(item) && !desired.some((row) => { return row.name === item.name; });
85
+ });
82
86
  await Promise.all(stale.map((item) => { return api('DELETE', `${path}/${encodeURIComponent(item.name)}`); }));
83
- return changed.length + stale.length;
87
+ return stale.length;
88
+ }
89
+
90
+ function parameter(item) {
91
+ return { value: item.value };
92
+ }
93
+
94
+ function policy(item) {
95
+ return { pattern: item.pattern, definition: item.definition, priority: item.priority, 'apply-to': item['apply-to'] };
96
+ }
97
+
98
+ function ensureVirtualHost(objects, vhost) {
99
+ if (objects.some((item) => { return item.vhost !== undefined && item.vhost !== vhost; })) {
100
+ throw new Error('topology contains a different virtual host');
101
+ }
102
+ }
103
+
104
+ async function reconcileShovels(api, path, desired, owns) {
105
+ const shovels = await upsertNamed(api, path, desired, parameter);
106
+ return shovels.count + await pruneNamed(api, path, shovels.current, desired, owns);
84
107
  }
85
108
 
86
109
  /** Apply only topology belonging to the selected virtual host. Users and permissions are bootstrap data. */
@@ -90,15 +113,51 @@ export default async function reconcileRabbitmq(desired, options) {
90
113
  const api = apiAt(options);
91
114
  const host = encodeURIComponent(vhost);
92
115
  const objects = [...desired.exchanges, ...desired.queues, ...desired.bindings, ...desired.parameters];
93
- if (objects.some((item) => { return item.vhost !== undefined && item.vhost !== vhost; })) {
94
- throw new Error('topology contains a different virtual host');
95
- }
116
+ ensureVirtualHost(objects, vhost);
96
117
  if (desired.parameters.some((item) => { return item.component !== 'shovel'; })) {
97
118
  throw new Error('only shovel parameters can be reconciled');
98
119
  }
99
120
  const exchanges = await declare(api, `exchanges/${host}`, desired.exchanges);
100
121
  const queues = await declare(api, `queues/${host}`, desired.queues);
101
122
  const links = await bindings(api, `bindings/${host}`, desired.bindings, ownsBinding);
102
- const parameters = await shovels(api, `parameters/shovel/${host}`, desired.parameters, ownsShovel);
123
+ const parameters = await reconcileShovels(api, `parameters/shovel/${host}`, desired.parameters, ownsShovel);
103
124
  return exchanges + queues + links + parameters;
104
125
  }
126
+
127
+ /** Apply only dynamic shovels managed by a caller. */
128
+ export function reconcileRabbitmqShovels(desired, options) {
129
+ const { vhost, ownsShovel, api = apiAt(options) } = options;
130
+ if (!vhost) { throw new Error('a virtual host is required'); }
131
+ ensureVirtualHost(desired, vhost);
132
+ if (desired.some((item) => { return item.component !== 'shovel'; })) {
133
+ throw new Error('only shovel parameters can be reconciled');
134
+ }
135
+ return reconcileShovels(api, `parameters/shovel/${encodeURIComponent(vhost)}`, desired, ownsShovel);
136
+ }
137
+
138
+ /** Reconcile federation objects for one vhost. Only owned objects are eligible for deletion. */
139
+ export async function reconcileRabbitmqFederation(desired, options) {
140
+ const { vhost, ownsUpstream, ownsPolicy } = options;
141
+ if (!vhost) { throw new Error('a virtual host is required'); }
142
+ const upstreams = (desired.parameters || []).filter((row) => { return row.component === 'federation-upstream'; });
143
+ const policies = desired.policies || [];
144
+ ensureVirtualHost([...upstreams, ...policies], vhost);
145
+ const host = encodeURIComponent(vhost);
146
+ const api = apiAt(options);
147
+ const upstreamPath = `parameters/federation-upstream/${host}`;
148
+ const policyPath = `policies/${host}`;
149
+ const links = await upsertNamed(api, upstreamPath, upstreams, parameter);
150
+ const rules = await upsertNamed(api, policyPath, policies, policy);
151
+ const dropped = await pruneNamed(api, upstreamPath, links.current, upstreams, ownsUpstream);
152
+ const retired = await pruneNamed(api, policyPath, rules.current, policies, ownsPolicy);
153
+ return links.count + rules.count + dropped + retired;
154
+ }
155
+
156
+ /** Apply queue bindings and shovels before changing federation. */
157
+ export async function reconcileRabbitmqTopology(desired, options) {
158
+ const parameters = desired.parameters || [];
159
+ ensureVirtualHost([...parameters, ...(desired.policies || [])], options.vhost);
160
+ const shovels = parameters.filter((row) => { return row.component === 'shovel'; });
161
+ const topology = await reconcileRabbitmq({ ...desired, parameters: shovels }, options);
162
+ return topology + await reconcileRabbitmqFederation(desired, options);
163
+ }
@@ -18,7 +18,7 @@ function asList(raw) {
18
18
  * @returns {object} STOMP JSON body
19
19
  *
20
20
  * @example
21
- * retagBody('icht1', row, ['to_ladle'], {})
21
+ * retagBody('drive1', row, ['inspection'], {})
22
22
  */
23
23
  export default function retagBody(machine, row, tags, properties) {
24
24
  const options = asList(row.options);
@@ -15,7 +15,7 @@ const DEFAULT_DESTINATION = '/exchange/scada.segments';
15
15
  *
16
16
  * @example
17
17
  * const retags = segmentRetags({ stompUrl });
18
- * await retags.publish(retagBody('icht1', row, ['to_ladle'], {}));
18
+ * await retags.publish(retagBody('drive1', row, ['inspection'], {}));
19
19
  */
20
20
  export default function segmentRetags(config) {
21
21
  if (!config.stompUrl) {
@@ -0,0 +1,91 @@
1
+ function pulseOutput(pulse, now, pulseIntervalMs) {
2
+ const devices = new Map();
3
+ function send(device, state) {
4
+ const time = now();
5
+ if (state.busy || state.value === undefined || time < state.nextAt) { return; }
6
+ const { value } = state;
7
+ Object.assign(state, { busy: true, value: undefined, nextAt: time + pulseIntervalMs });
8
+ try {
9
+ void Promise.resolve(pulse?.(value, device)).then(
10
+ () => { state.busy = false; }, () => { state.busy = false; }
11
+ );
12
+ } catch {
13
+ state.busy = false;
14
+ }
15
+ }
16
+ return {
17
+ mark(value, device) {
18
+ const state = devices.get(device) ?? { busy: false, nextAt: -Infinity };
19
+ state.value = value;
20
+ devices.set(device, state);
21
+ },
22
+ flush() { devices.forEach((state, device) => { send(device, state); }); }
23
+ };
24
+ }
25
+
26
+ function staleCount(channels, now) {
27
+ return [...channels.values()].filter((channel) => {
28
+ return channel.required && (channel.last === undefined || now() - channel.last > channel.maxAge);
29
+ }).length;
30
+ }
31
+
32
+ function channelStates(connections, minimumMaxAgeMs, heartbeatMultiplier) {
33
+ const states = new Map(connections.flatMap((connection) => {
34
+ return connection.channels.map((channel) => {
35
+ return [channel, { url: connection.url, required: connection.healthRequired !== false, last: undefined, maxAge: Math.max(minimumMaxAgeMs, heartbeatMultiplier * (connection.heartbeatMs ?? 1000)) }];
36
+ });
37
+ }));
38
+ const requiredDevices = new Set();
39
+ states.forEach((entry, channel) => { if (entry.required) { requiredDevices.add(channel.device); } });
40
+ states.forEach((entry, channel) => { entry.markDevice = entry.required || !requiredDevices.has(channel.device); });
41
+ return states;
42
+ }
43
+
44
+ /** Bad OPC values are not delivered by the source; silence therefore expires per channel. */
45
+ export default function opcuaHealth(connections, report, { now, schedule, pulse, minimumMaxAgeMs = 15000, heartbeatMultiplier = 3, pulseIntervalMs = 1000 }) {
46
+ const channels = channelStates(connections, minimumMaxAgeMs, heartbeatMultiplier);
47
+ const output = pulseOutput(pulse, now, pulseIntervalMs);
48
+ let stopped = false;
49
+ let previous;
50
+ function check(progress = false) {
51
+ if (stopped) { return; }
52
+ const stale = staleCount(channels, now);
53
+ const state = stale ? 'degraded' : 'running';
54
+ if (previous !== state || (!stale && progress)) {
55
+ previous = state;
56
+ report({ state, message: stale ? `OPC UA: ${stale} channels await fresh Good delivery` : 'OPC UA channels fresh', fatal: false, ...(!stale && progress && { read: true }) });
57
+ }
58
+ for (const [channel, entry] of channels) {
59
+ if (entry.required && entry.last !== undefined && now() - entry.last > entry.maxAge) {
60
+ output.mark(0, channel.device);
61
+ }
62
+ }
63
+ output.flush();
64
+ }
65
+ const cancel = schedule(check);
66
+ check();
67
+ return {
68
+ good(channel) {
69
+ if (stopped) { return; }
70
+ const entry = channels.get(channel);
71
+ if (entry) {
72
+ entry.last = now();
73
+ if (entry.markDevice) { output.mark(1, channel.device); }
74
+ }
75
+ check(Boolean(entry));
76
+ },
77
+ failed(error, connection) {
78
+ if (stopped) { return; }
79
+ const devices = new Set();
80
+ for (const [channel, entry] of channels) {
81
+ if (!connection || entry.url === connection.url) {
82
+ entry.last = undefined;
83
+ if (entry.markDevice) { devices.add(channel.device); }
84
+ }
85
+ }
86
+ for (const device of devices) { output.mark(0, device); }
87
+ check();
88
+ },
89
+ stop() { stopped = true; cancel(); }
90
+ };
91
+ }
@@ -8,3 +8,4 @@ export default function opcuaConnections(connections, publish, options = {}) {
8
8
  }
9
9
 
10
10
  export { default as opcuaSource } from './source.js';
11
+ export { default as opcuaHealth } from './health.js';
@@ -0,0 +1,149 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { assertSource, retentionFloor, usableCutoff } from './historySourceIdentity.js';
3
+
4
+ async function query(client, sql, params) {
5
+ const result = await client.query({ query: sql, query_params: params, format: 'JSONEachRow' });
6
+ return result.json();
7
+ }
8
+
9
+ function integer(value) {
10
+ const result = Number(value);
11
+ if (!Number.isSafeInteger(result)) { throw new Error('Historical timestamp exceeds exact supported coordinates'); }
12
+ return result;
13
+ }
14
+
15
+ function groups(rows, left, end) {
16
+ let size = 0;
17
+ const selected = [];
18
+ for (const row of rows) {
19
+ if (selected.length === 250 || size + Number(row.size) > 10000) { break; }
20
+ selected.push(row);
21
+ size += Number(row.size);
22
+ }
23
+ if (rows.length && !selected.length) { throw new Error('One history timestamp group exceeds bounded context capacity'); }
24
+ const next = rows[selected.length] ? integer(rows[selected.length].time) : null;
25
+ return { from: left, until: next === null ? end : integer(selected.at(-1).time), next, end };
26
+ }
27
+
28
+ const canonical = `SELECT topic,toUnixTimestamp64Micro(ts) AS time,max(value) AS value FROM scada.metrics
29
+ WHERE topic IN {topics:Array(String)} AND ts >= fromUnixTimestamp64Micro({left:Int64})
30
+ AND ts <= fromUnixTimestamp64Micro({right:Int64}) GROUP BY topic,ts`;
31
+
32
+ function coverage(items, gap) {
33
+ const continuity = [];
34
+ for (const time of new Set(items.map((item) => { return item.time; }))) {
35
+ const last = continuity.at(-1);
36
+ if (last && time - last.until <= gap) {
37
+ last.until = time;
38
+ } else {
39
+ continuity.push({ from: time, until: time });
40
+ }
41
+ }
42
+ return continuity;
43
+ }
44
+
45
+ function sampleContext(rows, mapped, gap) {
46
+ const byTopic = new Map(mapped.map(({ topic, channel }) => { return [topic, channel]; }));
47
+ const canonicalChannels = new Map();
48
+ for (const row of rows) {
49
+ const channel = byTopic.get(row.topic);
50
+ const time = integer(row.time);
51
+ const value = Number(row.value);
52
+ if (!Number.isFinite(value)) { throw new Error('Finite historical value required'); }
53
+ const key = JSON.stringify([channel, time]);
54
+ const old = canonicalChannels.get(key);
55
+ if (!old || value > old.value) {
56
+ const eventId = createHash('sha256').update(JSON.stringify([channel, time, value])).digest('hex');
57
+ canonicalChannels.set(key, { eventId, channel, time, value });
58
+ }
59
+ }
60
+ const items = [...canonicalChannels.values()].sort((left, right) => { return left.time - right.time || left.channel.localeCompare(right.channel); });
61
+ return { items, continuity: coverage(items, gap) };
62
+ }
63
+
64
+ async function predecessor(client, { mapped, params, gap }) {
65
+ const boundary = await query(client, `WITH times AS (SELECT DISTINCT time FROM (${canonical})), ordered AS (
66
+ SELECT time,lagInFrame(toNullable(time),1) OVER(ORDER BY time ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS prior FROM times
67
+ ) SELECT time FROM ordered WHERE isNull(prior) OR time-prior>{gap:Int64} ORDER BY time DESC LIMIT 1`, { ...params, gap });
68
+ if (!boundary.length) { return null; }
69
+ const since = integer(boundary[0].time);
70
+ const rows = await query(client, `SELECT c.topic,argMax(c.value,c.time) AS value,max(c.time) AS time FROM (${canonical}) AS c GROUP BY c.topic`,
71
+ { ...params, left: since });
72
+ const channels = new Map(mapped.map(({ topic, channel }) => { return [topic, channel]; }));
73
+ return {
74
+ since, time: Math.max(...rows.map((row) => { return integer(row.time); })),
75
+ values: Object.fromEntries(rows.map((row) => { return [channels.get(row.topic), Number(row.value)]; }))
76
+ };
77
+ }
78
+
79
+ async function mappings(pool, machine) {
80
+ await assertSource(pool, machine);
81
+ const result = await pool.query('SELECT topic,channel,bucket_ms,retention_days FROM history_topics WHERE machine=$1 ORDER BY topic', [machine]);
82
+ return result.rows;
83
+ }
84
+
85
+ async function extremes(client, pool, machine, direction, cutoff = null) {
86
+ const mapped = await mappings(pool, machine);
87
+ const filter = cutoff === null ? '' : ' AND ts >= fromUnixTimestamp64Micro({cutoff:Int64})';
88
+ const samples = await Promise.all(mapped.map(async ({ topic }) => {
89
+ const rows = await query(client, `SELECT toUnixTimestamp64Micro(ts) AS time FROM scada.metrics WHERE topic={topic:String}
90
+ ${filter} ORDER BY ts ${direction} LIMIT 1`, { topic, ...(cutoff !== null && { cutoff }) });
91
+ return rows.length ? integer(rows[0].time) : null;
92
+ }));
93
+ return samples.filter((value) => { return value !== null; });
94
+ }
95
+
96
+ async function parameters(pool, machine, left, right) {
97
+ const mapped = await mappings(pool, machine);
98
+ const floor = usableCutoff(await retentionFloor(pool));
99
+ const topics = mapped.map(({ topic }) => { return topic; });
100
+ return { mapped, params: { topics, left: floor === null ? left : Math.max(left, floor), right } };
101
+ }
102
+
103
+ async function registerSource(client, pool, machine, added, { now, reset }) {
104
+ await assertSource(pool, machine, true);
105
+ if (!reset && !added.length) { return; }
106
+ const mapped = await mappings(pool, machine);
107
+ const days = Math.max(...mapped.map(({ retention_days: retainedDays }) => { return Number(retainedDays); }));
108
+ const floor = usableCutoff(await retentionFloor(pool));
109
+ const window = (now() - days * 86400000) * 1000;
110
+ const starts = await extremes(client, pool, machine, 'ASC', floor === null ? window : Math.max(window, floor));
111
+ if (!starts.length) { return; }
112
+ const from = Math.min(...starts);
113
+ const until = Math.max(...await extremes(client, pool, machine, 'DESC'));
114
+ await pool.query(`INSERT INTO history_work(id,machine,from_ms,until_ms) VALUES(md5($1||':external-bootstrap')::uuid,$1,$2,$3)
115
+ ON CONFLICT(id) DO UPDATE SET from_ms=least(history_work.from_ms,excluded.from_ms),until_ms=greatest(history_work.until_ms,excluded.until_ms)`,
116
+ [machine, from, until]);
117
+ }
118
+
119
+ /** Raw measurements stay in ClickHouse; only topic mappings and correction state are in PostgreSQL. */
120
+ export default function historyObservations(client, pool, { now = Date.now } = {}) {
121
+ return {
122
+ async start(machine) {
123
+ const times = await extremes(client, pool, machine, 'ASC', usableCutoff(await retentionFloor(pool)));
124
+ if (!times.length) { throw new Error('Raw ClickHouse history is unavailable; correction remains pending'); }
125
+ return Math.min(...times);
126
+ },
127
+ async boundary(machine, from, until) {
128
+ return Math.max(until, ...await extremes(client, pool, machine, 'DESC'));
129
+ },
130
+ async page(machine, left, end) {
131
+ const { params } = await parameters(pool, machine, left, end);
132
+ const rows = await query(client, `SELECT time,count() AS size FROM (${canonical}) GROUP BY time ORDER BY time LIMIT 251`, params);
133
+ return groups(rows, left, end);
134
+ },
135
+ async read(machine, left, right, gap) {
136
+ const { mapped, params } = await parameters(pool, machine, left, right);
137
+ const rows = await query(client, `SELECT topic,time,value FROM (${canonical}) ORDER BY time,topic LIMIT 10001`, params);
138
+ if (rows.length > 10000) { throw new Error('History context exceeds bounded observation capacity'); }
139
+ return sampleContext(rows, mapped, gap);
140
+ },
141
+ async seed(machine, before, gap) {
142
+ const { mapped, params } = await parameters(pool, machine, Date.UTC(1900, 0, 1) * 1000, before - 1);
143
+ return predecessor(client, { mapped, params, gap });
144
+ },
145
+ registered(machine, added, { reset = false } = {}) {
146
+ return registerSource(client, pool, machine, added, { now, reset });
147
+ }
148
+ };
149
+ }
@@ -0,0 +1,94 @@
1
+ import { sourceId } from './historySourceIdentity.js';
2
+
3
+ function coordinate(value) {
4
+ const number = Number(value);
5
+ if (!Number.isSafeInteger(number)) { throw new Error('Exact retention coordinate required'); }
6
+ return number;
7
+ }
8
+ async function unseeded(pool) {
9
+ const result = await pool.query(`SELECT 1 FROM history_work w JOIN history_classifiers k ON k.machine=w.machine
10
+ WHERE NOT EXISTS(SELECT 1 FROM history_checkpoints c WHERE c.machine=w.machine AND c.classifier_key=k.classifier_key
11
+ AND c.valid AND c.time_ms<COALESCE(w.cursor_ms,w.from_ms)) LIMIT 1`);
12
+ return result.rowCount > 0;
13
+ }
14
+ async function watermark(pool, cutoff) {
15
+ const result = await pool.query(`SELECT least($1::bigint,
16
+ COALESCE((SELECT min(from_ms-86400000000) FROM history_work),$1),
17
+ COALESCE((SELECT min(time_ms) FROM history_admissions),$1),
18
+ COALESCE((SELECT min(seed.time_ms) FROM history_work w JOIN history_classifiers k ON k.machine=w.machine
19
+ CROSS JOIN LATERAL (SELECT time_ms FROM history_checkpoints c WHERE c.machine=w.machine AND c.classifier_key=k.classifier_key
20
+ AND c.valid AND c.time_ms<COALESCE(w.cursor_ms,w.from_ms) ORDER BY time_ms DESC LIMIT 1) seed),$1)) AS fence`, [cutoff]);
21
+ return coordinate(result.rows[0].fence);
22
+ }
23
+ function compactCheckpoints(pool, fence) {
24
+ return pool.query(`WITH ranked AS (
25
+ SELECT c.machine,c.classifier_key,c.time_ms,row_number() OVER(PARTITION BY c.machine,c.classifier_key,c.valid,c.time_ms/COALESCE(t.bucket_ms,30000000) ORDER BY c.time_ms DESC) AS n
26
+ FROM history_checkpoints c LEFT JOIN (SELECT machine,max(bucket_ms) AS bucket_ms FROM history_topics GROUP BY machine) t ON t.machine=c.machine
27
+ ), protected AS (
28
+ SELECT machine,classifier_key,max(time_ms) AS time_ms FROM history_checkpoints WHERE valid AND time_ms<$1 GROUP BY machine,classifier_key
29
+ UNION SELECT c.machine,c.classifier_key,c.time_ms FROM history_work w JOIN history_classifiers k ON k.machine=w.machine
30
+ CROSS JOIN LATERAL (SELECT machine,classifier_key,time_ms FROM history_checkpoints c WHERE c.machine=w.machine AND c.classifier_key=k.classifier_key
31
+ AND c.valid AND c.time_ms<COALESCE(w.cursor_ms,w.from_ms) ORDER BY time_ms DESC LIMIT 1) c
32
+ ) DELETE FROM history_checkpoints c USING ranked r
33
+ WHERE c.machine=r.machine AND c.classifier_key=r.classifier_key AND c.time_ms=r.time_ms AND (r.n>1 OR c.time_ms<$1)
34
+ AND NOT EXISTS(SELECT 1 FROM protected p WHERE p.machine=c.machine AND p.classifier_key=c.classifier_key AND p.time_ms=c.time_ms)`, [fence]);
35
+ }
36
+ async function pruneRaw(client, fence) {
37
+ const result = await client.query({
38
+ query: `SELECT topic,toUnixTimestamp64Micro(max(ts)) AS time FROM scada.metrics
39
+ WHERE ts<fromUnixTimestamp64Micro({fence:Int64}) GROUP BY topic`,
40
+ query_params: { fence }, format: 'JSONEachRow'
41
+ });
42
+ const anchors = (await result.json()).map(({ topic, time }) => { return `${Buffer.byteLength(topic)}:${topic}:${time}`; });
43
+ await client.command({
44
+ query: `ALTER TABLE scada.metrics DELETE WHERE ts<fromUnixTimestamp64Micro({fence:Int64})
45
+ AND concat(toString(length(topic)),':',topic,':',toString(toUnixTimestamp64Micro(ts))) NOT IN {anchors:Array(String)}`,
46
+ query_params: { fence, anchors }, clickhouse_settings: { mutations_sync: 1 }
47
+ });
48
+ }
49
+ async function lockSources(pool) {
50
+ await pool.query("SELECT pg_advisory_xact_lock(hashtextextended('history:configuration',0))");
51
+ const machines = await pool.query('SELECT DISTINCT machine FROM history_topics ORDER BY machine');
52
+ for (const { machine } of machines.rows) {
53
+ // eslint-disable-next-line no-await-in-loop
54
+ await pool.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [`history:${machine}`]);
55
+ }
56
+ }
57
+ async function transaction(pool, action) {
58
+ const connection = await pool.connect();
59
+ try {
60
+ await connection.query('BEGIN');
61
+ await connection.query("SET LOCAL statement_timeout = '20s'");
62
+ await lockSources(connection);
63
+ const result = await action(connection);
64
+ await connection.query('COMMIT');
65
+ return result;
66
+ } catch (error) {
67
+ await connection.query('ROLLBACK').catch(() => { return undefined; });
68
+ throw error;
69
+ } finally {
70
+ connection.release();
71
+ }
72
+ }
73
+ /** Persist a monotone raw-history floor BEFORE any independent ClickHouse command.
74
+ * New registrations/late admissions respect this floor even after coordinator restart.
75
+ * A delayed/repeated older mutation can therefore never delete a newly registered dependency.
76
+ */
77
+ export default async function clickhouseHistoryRetention(client, pool, { retentionDays, now, ready }) {
78
+ const fence = await transaction(pool, async (connection) => {
79
+ await ready(connection);
80
+ if (await unseeded(connection)) { return null; }
81
+ const proposed = await watermark(connection, (now() - retentionDays * 86400000) * 1000);
82
+ const result = await connection.query(`INSERT INTO history_retention(source_id,retained_from) VALUES($1,$2)
83
+ ON CONFLICT(source_id) DO UPDATE SET retained_from=greatest(history_retention.retained_from,excluded.retained_from) RETURNING retained_from`, [sourceId, proposed]);
84
+ return coordinate(result.rows[0].retained_from);
85
+ });
86
+ if (fence === null) { return { deferred: 'unseeded correction', checkpointsRemoved: 0 }; }
87
+ await pruneRaw(client, fence);
88
+ const compacted = await transaction(pool, async (connection) => {
89
+ await connection.query('DELETE FROM history_corrections c USING history_work w WHERE c.work_id=w.id AND c.generation<>w.generation');
90
+ await connection.query('DELETE FROM history_staged_checkpoints c USING history_work w WHERE c.work_id=w.id AND c.generation<>w.generation');
91
+ return compactCheckpoints(connection, fence);
92
+ });
93
+ return { retainedFrom: fence, checkpointsRemoved: compacted.rowCount };
94
+ }
@@ -0,0 +1,34 @@
1
+ export const sourceId = 'local-clickhouse-raw-v1';
2
+
3
+ const migrationRequired = 'Explicit history source identity migration required before ClickHouse activation';
4
+
5
+ export async function assertSource(pool, machine, initialize = false) {
6
+ const result = await pool.query('SELECT source_id,time_scale FROM history_sources WHERE machine=$1', [machine]);
7
+ if (!result.rowCount && initialize) {
8
+ const previous = await pool.query(`SELECT 1 FROM history_work WHERE machine=$1
9
+ UNION ALL SELECT 1 FROM history_observations WHERE machine=$1 LIMIT 1`, [machine]);
10
+ if (previous.rowCount) { throw new Error(migrationRequired); }
11
+ await pool.query('INSERT INTO history_sources(machine,source_id,time_scale) VALUES($1,$2,1000)', [machine, sourceId]);
12
+ return;
13
+ }
14
+ if (result.rows[0]?.source_id !== sourceId || result.rows[0]?.time_scale !== 1000) {
15
+ throw new Error(migrationRequired);
16
+ }
17
+ }
18
+
19
+ export async function assertSources(pool) {
20
+ const result = await pool.query(`SELECT 1 FROM history_topics t LEFT JOIN history_sources s ON s.machine=t.machine
21
+ WHERE s.source_id IS DISTINCT FROM $1 OR s.time_scale IS DISTINCT FROM 1000 LIMIT 1`, [sourceId]);
22
+ if (result.rowCount) { throw new Error(migrationRequired); }
23
+ }
24
+
25
+ /** A durable backend floor survives loss of the pruning session and cannot move backwards. */
26
+ export async function retentionFloor(pool) {
27
+ const result = await pool.query('SELECT retained_from FROM history_retention WHERE source_id=$1', [sourceId]);
28
+ return result.rowCount ? Number(result.rows[0].retained_from) : -Number.MAX_SAFE_INTEGER;
29
+ }
30
+
31
+ /** ClickHouse cannot scan from an empty or negative sentinel floor. */
32
+ export function usableCutoff(floor) {
33
+ return Number.isSafeInteger(floor) && floor >= 0 ? floor : null;
34
+ }
@@ -0,0 +1,19 @@
1
+ import { addAbortSignal, Readable } from 'node:stream';
2
+ import rowBinary from './rowBinary.js';
3
+
4
+ /** Write exact telemetry rows and wait for ClickHouse to finish the response. */
5
+ export default async function insertMetricRows(client, rows, { signal } = {}) {
6
+ if (!rows.length) { return; }
7
+ signal?.throwIfAborted();
8
+ const response = await client.exec({
9
+ query: 'INSERT INTO scada.metrics (topic, ts, value) FORMAT RowBinary',
10
+ values: Readable.from(rowBinary(rows), { objectMode: false }),
11
+ abort_signal: signal,
12
+ clickhouse_settings: { wait_end_of_query: 1, async_insert: 0 }
13
+ });
14
+ if (signal) { addAbortSignal(signal, response.stream); }
15
+ for await (const chunk of response.stream) {
16
+ if (chunk.length) { throw new Error('Unexpected ClickHouse telemetry insertion response'); }
17
+ }
18
+ signal?.throwIfAborted();
19
+ }
@@ -0,0 +1,26 @@
1
+ import telemetryTimestamp from '../../../domain/ingest/telemetryTimestamp.js';
2
+
3
+ export function requireTelemetryTimestamps(rows, {
4
+ clock = Date.now,
5
+ minTimestamp = -Infinity,
6
+ maxFutureMs = Infinity
7
+ } = {}) {
8
+ const now = clock();
9
+ for (const row of rows) {
10
+ const instant = telemetryTimestamp(row.ts);
11
+ if (!Number.isFinite(instant) || instant > now + maxFutureMs || instant < minTimestamp) {
12
+ throw new Error(`Telemetry timestamp is outside the admitted window topic=${row.topic} ts=${row.ts}`);
13
+ }
14
+ }
15
+ }
16
+
17
+ /** Write original raw timestamps to ClickHouse without rounding or synthesizing timestamps. */
18
+ export default function clickhouseJsonMetrics(client, { table = 'scada.metrics', ...window } = {}) {
19
+ return {
20
+ requireTimestamp: true,
21
+ async insertRows(rows, context) {
22
+ requireTelemetryTimestamps(rows, window);
23
+ return await client.insert({ table, values: rows, format: 'JSONEachRow', abort_signal: context?.signal });
24
+ }
25
+ };
26
+ }
@@ -0,0 +1,51 @@
1
+ import historyPg, { historyProtocol } from '../pg/history.js';
2
+ import historyObservations from './historyObservations.js';
3
+ import historyRetention from './historyRetention.js';
4
+ import { assertSources } from './historySourceIdentity.js';
5
+ import { micros } from './rowBinary.js';
6
+
7
+ export const clickhouseHistoryComment = `scada.local-history:${historyProtocol}`;
8
+
9
+ async function checkStorage(client, connection) {
10
+ const result = await client.query({
11
+ query: "SELECT create_table_query,comment FROM system.tables WHERE database='scada' AND name='metrics'",
12
+ format: 'JSONEachRow'
13
+ });
14
+ const rows = await result.json();
15
+ if (rows.length !== 1 || rows[0].comment !== clickhouseHistoryComment || /\bTTL\b/u.test(rows[0].create_table_query)) {
16
+ throw new Error('Local history requires coordinated retention without autonomous ClickHouse TTL');
17
+ }
18
+ await connection.query('SELECT 1 FROM history_admissions LIMIT 0');
19
+ await connection.query('SELECT 1 FROM history_checkpoints LIMIT 0');
20
+ await connection.query('SELECT 1 FROM history_corrections LIMIT 0');
21
+ await connection.query('SELECT 1 FROM history_staged_checkpoints LIMIT 0');
22
+ await connection.query('SELECT 1 FROM history_retention LIMIT 0');
23
+ await assertSources(connection);
24
+ }
25
+
26
+ async function historyWatermark(pool, observations) {
27
+ const result = await pool.query('SELECT DISTINCT machine FROM history_topics');
28
+ const machines = result.rows.map(({ machine }) => { return machine; });
29
+ if (!machines.length) { return { observationMs: 0, segmentEndMs: 0 }; }
30
+ const source = observations(pool);
31
+ const times = await Promise.all(machines.map(async (machine) => { return Math.floor((await source.boundary(machine, 0, 0)) / 1000); }));
32
+ const segments = await pool.query(`SELECT COALESCE((EXTRACT(EPOCH FROM max(end_time))*1000)::bigint,0) AS ms
33
+ FROM segments WHERE kind='phase' AND machine=ANY($1)`, [machines]);
34
+ return { observationMs: Math.min(...times), segmentEndMs: Number(segments.rows[0].ms) };
35
+ }
36
+
37
+ /** ClickHouse raw observations with transactional PostgreSQL correction and retention. */
38
+ export default function clickhouseLocalHistory(client, pool, { retentionDays = 30, now = Date.now, processorProperties = [], workPolicy } = {}) {
39
+ function observations(connection) { return historyObservations(client, connection, { now }); }
40
+ function ready(connection = pool) { return checkStorage(client, connection); }
41
+ const history = historyPg(pool, {
42
+ retentionDays, now, timeScale: 1000, processorProperties, observations, workPolicy,
43
+ timestamp(value) { return Number(micros(value)); }
44
+ });
45
+ return {
46
+ ...history, ready,
47
+ watermark() { return historyWatermark(pool, observations); },
48
+ purge() { return historyRetention(client, pool, { retentionDays, now, ready }); },
49
+ async configure(...args) { await ready(); return history.configure(...args); }
50
+ };
51
+ }