@yarkivaev/scada 2.12.1 → 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.
- package/README.md +1 -1
- package/db/migrations/E0013__history_staged_corrections.sql +1 -1
- package/db/migrations/E0017__history_live_covering.sql +1 -1
- package/db/migrations/E0025__history_processor_properties.sql +76 -0
- package/db/migrations/E0026__history_processor_properties_grants.sql +1 -0
- package/index.js +14 -2
- package/package.json +1 -1
- package/src/application/foldedMetricsSink.js +1 -1
- package/src/application/runtime/collectorStartup.js +23 -0
- package/src/application/runtime/index.js +2 -0
- package/src/application/runtime/queuedDelivery.js +1 -0
- package/src/application/runtime/runCollector.js +46 -9
- package/src/application/runtime/runtimeServices.js +20 -2
- package/src/application/runtime/spoolHistory.js +12 -12
- package/src/application/runtime/spoolSurface.js +2 -2
- package/src/application/runtime/spooledOutput.js +27 -0
- package/src/application/siteServer.js +2 -2
- package/src/application/supervisorSink.js +5 -6
- package/src/application/sync/publishingOperations.js +52 -0
- package/src/application/sync/siteSync.js +1 -1
- package/src/application/sync/siteSyncRows.js +1 -1
- package/src/application/sync/siteSyncSites.js +1 -1
- package/src/application/telemetry/telemetryBackfill.js +127 -0
- package/src/application/timelineOperatorFromEnv.js +1 -1
- package/src/domain/ingest/telemetryTimestamp.js +7 -0
- package/src/domain/segment/dispatch.js +19 -17
- package/src/domain/segment/historyFold.js +2 -1
- package/src/domain/segment/intervalFold.js +1 -1
- package/src/domain/segment/segmentContinue.js +1 -1
- package/src/infrastructure/catalog/tagCatalog.js +7 -11
- package/src/infrastructure/http/plant/json/decisionJson.js +1 -1
- package/src/infrastructure/http/plant/routes/timelineRoute.js +1 -1
- package/src/infrastructure/http/plant/timelineOperator.js +2 -2
- package/src/infrastructure/ingest/db/migrationProfile.js +2 -1
- package/src/infrastructure/ingest/pipelines/segmentPipeline.js +38 -14
- package/src/infrastructure/ingest/sinks/contiguousPhases.js +1 -1
- package/src/infrastructure/ingest/sinks/continuedSegments.js +9 -8
- package/src/infrastructure/ingest/sinks/decisionSegment.js +1 -1
- package/src/infrastructure/ingest/sinks/foldingSegments.js +16 -10
- package/src/infrastructure/ingest/sinks/{foldCastingPhases.js → repairPhaseOverlaps.js} +17 -29
- package/src/infrastructure/ingest/sinks/retagSink.js +1 -1
- package/src/infrastructure/ingest/sinks/userDecisionSink.js +1 -1
- package/src/infrastructure/ingest/telemetry/historyTelemetryMetrics.js +15 -0
- package/src/infrastructure/ingest/telemetry/opcuaLocate.js +2 -2
- package/src/infrastructure/ingest/telemetry/telemetryIngest.js +52 -0
- package/src/infrastructure/ingest/telemetry/telemetryReplay.js +15 -0
- package/src/infrastructure/messaging/stomp/retagBody.js +1 -1
- package/src/infrastructure/messaging/stomp/segmentRetags.js +1 -1
- package/src/infrastructure/persistence/clickhouse/historyObservations.js +149 -0
- package/src/infrastructure/persistence/clickhouse/historyRetention.js +94 -0
- package/src/infrastructure/persistence/clickhouse/historySourceIdentity.js +34 -0
- package/src/infrastructure/persistence/clickhouse/insertMetricRows.js +19 -0
- package/src/infrastructure/persistence/clickhouse/jsonMetrics.js +26 -0
- package/src/infrastructure/persistence/clickhouse/localHistory.js +51 -0
- package/src/infrastructure/persistence/clickhouse/metricsState.js +92 -0
- package/src/infrastructure/persistence/clickhouse/rowBinary.js +38 -0
- package/src/infrastructure/persistence/clickhouse/telemetryTarget.js +41 -0
- package/src/infrastructure/persistence/pg/checkpoints.js +35 -9
- package/src/infrastructure/persistence/pg/history.js +74 -56
- package/src/infrastructure/persistence/pg/historyContext.js +34 -17
- package/src/infrastructure/persistence/pg/historyCorrection.js +5 -2
- package/src/infrastructure/persistence/pg/historyFence.js +1 -1
- package/src/infrastructure/persistence/pg/historyNativeBounds.js +31 -0
- package/src/infrastructure/persistence/pg/historyPurge.js +26 -0
- package/src/infrastructure/persistence/pg/historySeed.js +3 -3
- package/src/infrastructure/persistence/pg/historySession.js +15 -0
- package/src/infrastructure/persistence/pg/intervalFoldPg.js +1 -1
- package/src/infrastructure/persistence/pg/telemetrySource.js +64 -0
- package/src/infrastructure/persistence/postgresPool.js +6 -1
- package/src/infrastructure/persistence/runtime/deliverySpool.js +11 -2
- package/src/infrastructure/persistence/runtime/spoolCheckpoints.js +65 -0
- package/src/infrastructure/persistence/runtime/spoolLimits.js +4 -2
- package/src/infrastructure/persistence/runtime/taskStateSqlite.js +37 -0
- package/src/infrastructure/persistence/stateDataFromPool.js +16 -2
- package/src/infrastructure/streams/modbusSource.js +1 -1
- package/src/infrastructure/streams/stompSend.js +1 -1
- package/src/infrastructure/sync/operationAmqp.js +26 -0
- package/src/infrastructure/sync/operationEvent.js +10 -0
- package/src/infrastructure/catalog/tag-catalog.json +0 -27
|
@@ -5,7 +5,7 @@ function startOf(row) {
|
|
|
5
5
|
return new Date(row.start_time).getTime();
|
|
6
6
|
}
|
|
7
7
|
|
|
8
|
-
function pinLive(rows) {
|
|
8
|
+
function pinLive(rows, preserveCoverage) {
|
|
9
9
|
if (!rows.length) {
|
|
10
10
|
return rows;
|
|
11
11
|
}
|
|
@@ -15,7 +15,7 @@ function pinLive(rows) {
|
|
|
15
15
|
return ordered.map((row, i, all) => {
|
|
16
16
|
const copy = { ...row };
|
|
17
17
|
if (i === all.length - 1) {
|
|
18
|
-
if (copy.duration === 0) {
|
|
18
|
+
if (!preserveCoverage && copy.duration === 0) {
|
|
19
19
|
copy.end_time = copy.start_time;
|
|
20
20
|
}
|
|
21
21
|
return copy;
|
|
@@ -74,10 +74,10 @@ function foldRows(rows) {
|
|
|
74
74
|
}, Promise.resolve([]));
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
-
async function foldMachine(runner, machine) {
|
|
77
|
+
async function foldMachine(runner, machine, preserveCoverage) {
|
|
78
78
|
await runner.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`history:${machine}`]);
|
|
79
79
|
const stored = await loadPhases(runner, machine);
|
|
80
|
-
const folded = pinLive(await foldRows(stored));
|
|
80
|
+
const folded = pinLive(await foldRows(stored), preserveCoverage);
|
|
81
81
|
const kept = new Set(folded.map(startOf));
|
|
82
82
|
await dropStarts(runner, machine, stored.filter((row) => {
|
|
83
83
|
return !kept.has(startOf(row));
|
|
@@ -88,15 +88,15 @@ async function foldMachine(runner, machine) {
|
|
|
88
88
|
}, Promise.resolve());
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
-
async function foldOwned(pool, machine) {
|
|
91
|
+
async function foldOwned(pool, machine, preserveCoverage) {
|
|
92
92
|
if (typeof pool.connect !== 'function') {
|
|
93
|
-
await foldMachine(pool, machine);
|
|
93
|
+
await foldMachine(pool, machine, preserveCoverage);
|
|
94
94
|
return;
|
|
95
95
|
}
|
|
96
96
|
const client = await pool.connect();
|
|
97
97
|
try {
|
|
98
98
|
await client.query('BEGIN');
|
|
99
|
-
await foldMachine(client, machine);
|
|
99
|
+
await foldMachine(client, machine, preserveCoverage);
|
|
100
100
|
await client.query('COMMIT');
|
|
101
101
|
} catch (error) {
|
|
102
102
|
await client.query('ROLLBACK');
|
|
@@ -106,9 +106,9 @@ async function foldOwned(pool, machine) {
|
|
|
106
106
|
}
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
-
async function foldOwnedRetry(pool, machine, attempt) {
|
|
109
|
+
async function foldOwnedRetry(pool, machine, attempt, preserveCoverage) {
|
|
110
110
|
try {
|
|
111
|
-
await foldOwned(pool, machine);
|
|
111
|
+
await foldOwned(pool, machine, preserveCoverage);
|
|
112
112
|
} catch (error) {
|
|
113
113
|
if (error?.code !== '40P01' || attempt >= 7) {
|
|
114
114
|
throw error;
|
|
@@ -116,32 +116,20 @@ async function foldOwnedRetry(pool, machine, attempt) {
|
|
|
116
116
|
await new Promise((resolve) => {
|
|
117
117
|
setTimeout(resolve, 40 * (attempt + 1));
|
|
118
118
|
});
|
|
119
|
-
await foldOwnedRetry(pool, machine, attempt + 1);
|
|
119
|
+
await foldOwnedRetry(pool, machine, attempt + 1, preserveCoverage);
|
|
120
120
|
}
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
-
/**
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
* @param {string[]} protectedTracks - driver machines with authoritative phases
|
|
128
|
-
* @returns {Promise<void>}
|
|
129
|
-
*
|
|
130
|
-
* @example
|
|
131
|
-
* await foldCastingPhases(pool);
|
|
132
|
-
*/
|
|
133
|
-
export default async function foldCastingPhases(pool, protectedTracks = []) {
|
|
134
|
-
const found = await pool.query(
|
|
135
|
-
`SELECT DISTINCT machine FROM segments WHERE machine LIKE 'cm%' AND kind='phase' AND NOT (machine = ANY($1::text[]))`,
|
|
136
|
-
[protectedTracks]
|
|
137
|
-
);
|
|
138
|
-
await found.rows.reduce(async (prior, row) => {
|
|
123
|
+
/** Repairs overlapping phases on application-selected machines outside authoritative tracks. */
|
|
124
|
+
export default async function repairPhaseOverlaps(pool, machines = [], protectedTracks = [], { preserveCoverage = false } = {}) {
|
|
125
|
+
const selected = [...new Set(machines)].filter((machine) => { return !protectedTracks.includes(machine); });
|
|
126
|
+
await selected.reduce(async (prior, machine) => {
|
|
139
127
|
await prior;
|
|
140
128
|
try {
|
|
141
|
-
await foldOwnedRetry(pool,
|
|
142
|
-
process.stderr.write(`[supervisor-sink] folded
|
|
129
|
+
await foldOwnedRetry(pool, machine, 0, preserveCoverage);
|
|
130
|
+
process.stderr.write(`[supervisor-sink] folded overlapping phases for ${machine}\n`);
|
|
143
131
|
} catch (error) {
|
|
144
|
-
processingErrorLog('
|
|
132
|
+
processingErrorLog('repair_phase_overlaps', error, { machine });
|
|
145
133
|
}
|
|
146
134
|
}, Promise.resolve());
|
|
147
135
|
}
|
|
@@ -11,7 +11,7 @@ import processingErrorLog from '../processingErrorLog.js';
|
|
|
11
11
|
* const pool = new pg.Pool({ connectionString: url });
|
|
12
12
|
* const sink = retagSink(pool);
|
|
13
13
|
* sink.accept({ machine: 'm2', start_time: '2024-01-01T00:00:00.000Z',
|
|
14
|
-
* tags: '["
|
|
14
|
+
* tags: '["needs_review"]', properties: '{}' });
|
|
15
15
|
*
|
|
16
16
|
* @param {object} pool - pg Pool (or compatible) with query() method
|
|
17
17
|
* @returns {object} Sink with accept() method
|
|
@@ -12,7 +12,7 @@ import { applyDecision } from './decisionSegment.js';
|
|
|
12
12
|
* sink.accept({ machine: 'm2', startTime: '2024-01-01T00:00:00.000Z',
|
|
13
13
|
* username: 'Ivan Petrov', operatorId: 2,
|
|
14
14
|
* decidedAt: '2024-01-01T00:01:00.000Z',
|
|
15
|
-
* payload: '{"tags":["
|
|
15
|
+
* payload: '{"tags":["needs_review"]}' });
|
|
16
16
|
*
|
|
17
17
|
* @param {object} pool - pg Pool (or compatible) with query() method
|
|
18
18
|
* @returns {object} Sink with accept() method
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Finish durable history work before acknowledging a telemetry write. */
|
|
2
|
+
export default function historyTelemetryMetrics(metrics, history) {
|
|
3
|
+
return {
|
|
4
|
+
...metrics,
|
|
5
|
+
requireTimestamp: true,
|
|
6
|
+
async insertRows(records, context = {}) {
|
|
7
|
+
context.signal?.throwIfAborted();
|
|
8
|
+
await history.prepare(records);
|
|
9
|
+
context.signal?.throwIfAborted();
|
|
10
|
+
await metrics.insertRows(records, context);
|
|
11
|
+
context.signal?.throwIfAborted();
|
|
12
|
+
await history.complete(records);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
* @returns {function(object): object|null} locator
|
|
6
6
|
*
|
|
7
7
|
* @example
|
|
8
|
-
* const locate = opcuaLocate({ 'tlc-
|
|
9
|
-
* locate({ topic: 'OPCUA/tlc-
|
|
8
|
+
* const locate = opcuaLocate({ 'tlc-line-8': 'line-8' });
|
|
9
|
+
* locate({ topic: 'OPCUA/tlc-line-8/GET/axis_moving/VALUE', value: 1, ts: 1 });
|
|
10
10
|
*/
|
|
11
11
|
export default function opcuaLocate(devices) {
|
|
12
12
|
const map = devices || {};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import amqpMetricsIngest from './amqpMetricsIngest.js';
|
|
2
|
+
|
|
3
|
+
function batchConfig(options) {
|
|
4
|
+
const config = { size: 256, prefetch: 512, maxWaitMs: 1000, writeTimeoutMs: 45000, ...options };
|
|
5
|
+
for (const key of ['size', 'prefetch', 'maxWaitMs', 'writeTimeoutMs']) {
|
|
6
|
+
if (!Number.isSafeInteger(config[key]) || config[key] <= 0) { throw new Error(`Invalid telemetry ${key}`); }
|
|
7
|
+
}
|
|
8
|
+
if (config.size > config.prefetch) { throw new Error('Telemetry batch exceeds the broker acknowledgement window'); }
|
|
9
|
+
return config;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function metricBatches(metrics, state, clock, failure, halt) {
|
|
13
|
+
return {
|
|
14
|
+
requireTimestamp: metrics.requireTimestamp === true,
|
|
15
|
+
async write(records, context) {
|
|
16
|
+
try {
|
|
17
|
+
await metrics.insertRows(records, context);
|
|
18
|
+
state.records += records.length;
|
|
19
|
+
state.batches += 1;
|
|
20
|
+
Object.assign(state, { lastWrite: new Date(clock()).toISOString(), error: '', failedAt: undefined });
|
|
21
|
+
} catch (error) {
|
|
22
|
+
failure(error);
|
|
23
|
+
if (error.code === 'WRITE_TIMEOUT') { halt?.(error); }
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Consume acknowledged telemetry and measure ingest health at the storage boundary. */
|
|
31
|
+
export default function telemetryIngest(url, queue, metrics, settings = {}) {
|
|
32
|
+
const { clock = Date.now, halt, connect = amqpMetricsIngest, report, ...options } = settings;
|
|
33
|
+
const config = batchConfig(options);
|
|
34
|
+
const state = { started: false, records: 0, batches: 0, lastWrite: undefined, error: '', failedAt: undefined };
|
|
35
|
+
function failure(error) {
|
|
36
|
+
state.failedAt ??= clock();
|
|
37
|
+
if (state.error !== error.message) { report?.(error); }
|
|
38
|
+
state.error = error.message;
|
|
39
|
+
}
|
|
40
|
+
const sink = metricBatches(metrics, state, clock, failure, halt);
|
|
41
|
+
const input = connect(url, queue, sink, { ...config,
|
|
42
|
+
exclusive: true, stopTimeoutMs: 50000, maxMessageBytes: 65536, maxPendingBytes: 8388608,
|
|
43
|
+
maxBytes: 1048576, maxRecords: 1024, onError: failure
|
|
44
|
+
});
|
|
45
|
+
return {
|
|
46
|
+
async start() { await input.start(); Object.assign(state, { started: true }); },
|
|
47
|
+
async stop() { state.started = false; await input.stop(); },
|
|
48
|
+
status() {
|
|
49
|
+
return { ...state, ready: state.started && !state.error, live: state.failedAt === undefined || clock() - state.failedAt < 60000 };
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import telemetryTimestamp from '../../../domain/ingest/telemetryTimestamp.js';
|
|
2
|
+
|
|
3
|
+
/** Encode a stored point as a persistent AMQP publish with its original millisecond timestamp. */
|
|
4
|
+
export default function telemetryReplay(row, exchange = 'scada.telemetry') {
|
|
5
|
+
const instant = Math.trunc(telemetryTimestamp(row.ts));
|
|
6
|
+
if (!Number.isSafeInteger(instant) || !Number.isFinite(row.value)) {
|
|
7
|
+
throw new Error(`Replay requires original integer timestamp and finite value topic=${row.topic} ts=${row.ts}`);
|
|
8
|
+
}
|
|
9
|
+
return {
|
|
10
|
+
exchange,
|
|
11
|
+
routingKey: String(row.topic).replaceAll('/', '.'),
|
|
12
|
+
payload: JSON.stringify({ ts: instant, value: row.value }),
|
|
13
|
+
persistent: true
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -18,7 +18,7 @@ function asList(raw) {
|
|
|
18
18
|
* @returns {object} STOMP JSON body
|
|
19
19
|
*
|
|
20
20
|
* @example
|
|
21
|
-
* retagBody('
|
|
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('
|
|
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,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
|
+
}
|