@yarkivaev/scada 2.12.2 → 2.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/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/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
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
64
|
-
await
|
|
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
|
|
69
|
-
const kind = live.kind || 'phase';
|
|
68
|
+
const kind = record.kind || 'phase';
|
|
70
69
|
if (!pool || typeof pool.connect !== 'function') {
|
|
71
|
-
await closer.close(
|
|
72
|
-
await segmentSink.write([
|
|
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(
|
|
79
|
-
await segmentSink.write([
|
|
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
|
-
|
|
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)
|
|
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: '
|
|
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
|
|
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
|
|
@@ -1,25 +1,21 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs';
|
|
2
|
-
import { fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname, join } from 'node:path';
|
|
4
2
|
|
|
5
3
|
/**
|
|
6
|
-
* Loads hierarchical tag catalog entries from
|
|
4
|
+
* Loads hierarchical tag catalog entries from a configured JSON file.
|
|
7
5
|
*
|
|
8
|
-
*
|
|
9
|
-
* package copy without rebuilding the image.
|
|
6
|
+
* Uses an empty catalog when TAG_CATALOG_PATH is unset.
|
|
10
7
|
*
|
|
11
8
|
* @example
|
|
12
|
-
* const catalog = tagCatalog();
|
|
13
|
-
* catalog.labels()
|
|
9
|
+
* const catalog = tagCatalog({ TAG_CATALOG_PATH: '/etc/scada/tag-catalog.json' });
|
|
10
|
+
* catalog.labels();
|
|
14
11
|
*
|
|
15
12
|
* @param {object} [env] - environment map, defaults to process.env
|
|
16
|
-
* @returns {object} catalog with entries(), labels(),
|
|
13
|
+
* @returns {object} catalog with entries(), labels(), children(parent)
|
|
17
14
|
*/
|
|
18
15
|
export default function tagCatalog(env) {
|
|
19
16
|
const source = env || process.env;
|
|
20
|
-
const path = source.TAG_CATALOG_PATH
|
|
21
|
-
|
|
22
|
-
const raw = JSON.parse(readFileSync(path, 'utf8'));
|
|
17
|
+
const path = source.TAG_CATALOG_PATH;
|
|
18
|
+
const raw = path ? JSON.parse(readFileSync(path, 'utf8')) : [];
|
|
23
19
|
if (!Array.isArray(raw)) {
|
|
24
20
|
throw new Error('tag catalog must be a JSON array');
|
|
25
21
|
}
|
|
@@ -22,7 +22,7 @@ function body(raw) {
|
|
|
22
22
|
* decisionJson({
|
|
23
23
|
* username: 'Elena Volkov', operatorId: 2,
|
|
24
24
|
* decidedAt: new Date('2024-06-01T12:05:00.000Z'),
|
|
25
|
-
* payload: '{"tags":["
|
|
25
|
+
* payload: '{"tags":["needs_review"]}'
|
|
26
26
|
* });
|
|
27
27
|
*/
|
|
28
28
|
export default function decisionJson(row) {
|
|
@@ -73,7 +73,7 @@ async function respondToRequest(gate, timeline, requestId, req, res) {
|
|
|
73
73
|
* @returns {array} route objects
|
|
74
74
|
*
|
|
75
75
|
* @example
|
|
76
|
-
* timelineRoute('/api/v1', plant, { provider, requireOperator: true, defaultUser: '
|
|
76
|
+
* timelineRoute('/api/v1', plant, { provider, requireOperator: true, defaultUser: 'example-workstation' });
|
|
77
77
|
*/
|
|
78
78
|
export default function timelineRoute(basePath, plant, operatorOptions, decorate, currentPhase) {
|
|
79
79
|
const gate = timelineOperator(operatorOptions);
|
|
@@ -21,7 +21,7 @@ function anonymousName(body, cfg) {
|
|
|
21
21
|
if (typeof key === 'string' && Object.hasOwn(map, key)) {
|
|
22
22
|
return map[key];
|
|
23
23
|
}
|
|
24
|
-
return cfg.defaultUser || '
|
|
24
|
+
return cfg.defaultUser || 'anonymous';
|
|
25
25
|
}
|
|
26
26
|
|
|
27
27
|
/**
|
|
@@ -32,7 +32,7 @@ function anonymousName(body, cfg) {
|
|
|
32
32
|
*
|
|
33
33
|
* @example
|
|
34
34
|
* const gate = timelineOperator({
|
|
35
|
-
* provider, requireOperator: true, defaultUser: '
|
|
35
|
+
* provider, requireOperator: true, defaultUser: 'example-workstation',
|
|
36
36
|
* anonymousUsers: { hmi: 'Anonymous HMI user' }
|
|
37
37
|
* });
|
|
38
38
|
* const audit = await gate.resolve({ operatorId: 2 });
|
|
@@ -33,7 +33,8 @@ const privilegedOnly = new Set([
|
|
|
33
33
|
'E0019__segment_write_fence.sql',
|
|
34
34
|
'E0020__segment_write_fence_grants.sql',
|
|
35
35
|
'E0022__history_replica_outbox_grants.sql',
|
|
36
|
-
'E0024__timeline_replica_origin_grants.sql'
|
|
36
|
+
'E0024__timeline_replica_origin_grants.sql',
|
|
37
|
+
'E0026__history_processor_properties_grants.sql'
|
|
37
38
|
]);
|
|
38
39
|
|
|
39
40
|
/**
|
|
@@ -13,7 +13,7 @@ import segmentCodec from '../codecs/segmentCodec.js';
|
|
|
13
13
|
import processingErrorLog from '../processingErrorLog.js';
|
|
14
14
|
import silentOpenWatch from '../silentOpenWatch.js';
|
|
15
15
|
import abutSegments from '../sinks/abutSegments.js';
|
|
16
|
-
import
|
|
16
|
+
import repairPhaseOverlaps from '../sinks/repairPhaseOverlaps.js';
|
|
17
17
|
import closeOrphanOpen from '../sinks/closeOrphanOpen.js';
|
|
18
18
|
import closeSilentOpen from '../sinks/closeSilentOpen.js';
|
|
19
19
|
import continuedSegments from '../sinks/continuedSegments.js';
|
|
@@ -26,6 +26,7 @@ export const segmentConflict = ['machine', 'kind', 'start_time'];
|
|
|
26
26
|
export const segmentUpdateColumns = ['name', 'end_time', 'duration', 'options', 'resolved', 'updated_at'];
|
|
27
27
|
export const splitUpdateColumns = ['name', 'end_time', 'duration', 'tags', 'options', 'properties', 'resolved'];
|
|
28
28
|
export const segmentUpdateWhere = '(segments.duration = 0 OR EXCLUDED.duration > 0 OR EXCLUDED.end_time > segments.end_time) AND NOT (segments.duration > 0 AND EXCLUDED.duration = 0 AND COALESCE(segments.properties, \'\') LIKE \'%"split_of"%\' AND EXISTS (SELECT 1 FROM segments AS kin WHERE kin.machine = segments.machine AND kin.kind = segments.kind AND kin.start_time > segments.start_time AND COALESCE(kin.properties, \'\') LIKE \'%"split_of"%\')) AND (NOT EXISTS (SELECT 1 FROM segments AS later WHERE later.machine = segments.machine AND later.kind = segments.kind AND later.start_time > segments.start_time) OR (segments.duration > 0 AND EXCLUDED.duration = segments.duration AND EXCLUDED.name = segments.name AND EXCLUDED.end_time = segments.end_time))';
|
|
29
|
+
const coveringSegmentUpdateWhere = '(segments.duration = 0 OR EXCLUDED.duration > 0 OR EXCLUDED.end_time > segments.end_time) AND NOT (EXCLUDED.duration = 0 AND EXCLUDED.end_time < segments.end_time) AND NOT (segments.duration > 0 AND EXCLUDED.duration = 0 AND COALESCE(segments.properties, \'\') LIKE \'%"split_of"%\' AND EXISTS (SELECT 1 FROM segments AS kin WHERE kin.machine = segments.machine AND kin.kind = segments.kind AND kin.start_time > segments.start_time AND COALESCE(kin.properties, \'\') LIKE \'%"split_of"%\')) AND NOT EXISTS (SELECT 1 FROM segments AS later WHERE later.machine = segments.machine AND later.kind = segments.kind AND later.start_time > segments.start_time)';
|
|
29
30
|
export const segmentsIngestDestination = '/queue/scada.segments.ingest';
|
|
30
31
|
|
|
31
32
|
export { default as segmentDispatch } from '../../../domain/segment/dispatch.js';
|
|
@@ -37,13 +38,15 @@ export { default as segmentDispatch } from '../../../domain/segment/dispatch.js'
|
|
|
37
38
|
* @param {object} pool - shared pg pool
|
|
38
39
|
* @returns {{ segmentSink: object, splitSink: object }}
|
|
39
40
|
*/
|
|
40
|
-
function segmentSinks(postgres, pool) {
|
|
41
|
-
const
|
|
41
|
+
function segmentSinks(postgres, pool, policy) {
|
|
42
|
+
const updateWhere = policy.preserveCoverage ? coveringSegmentUpdateWhere : segmentUpdateWhere;
|
|
43
|
+
const shared = { pool, conflict: segmentConflict, updateWhere };
|
|
44
|
+
const update = policy.preserveCoverage ? [...segmentUpdateColumns, 'properties'] : segmentUpdateColumns;
|
|
42
45
|
return {
|
|
43
46
|
segmentSink: foldingSegments(postgresSink(postgres, 'segments', segmentColumns,
|
|
44
|
-
{ ...shared, update
|
|
47
|
+
{ ...shared, update }), pool, policy),
|
|
45
48
|
splitSink: foldingSegments(postgresSink(postgres, 'segments', segmentColumns,
|
|
46
|
-
{ ...shared, update: splitUpdateColumns }), pool)
|
|
49
|
+
{ ...shared, update: splitUpdateColumns }), pool, policy)
|
|
47
50
|
};
|
|
48
51
|
}
|
|
49
52
|
|
|
@@ -52,6 +55,11 @@ function pipelineSettings(config) {
|
|
|
52
55
|
if (settings.repairHistoryOnStart !== undefined && typeof settings.repairHistoryOnStart !== 'boolean') {
|
|
53
56
|
throw new TypeError('repairHistoryOnStart must be boolean');
|
|
54
57
|
}
|
|
58
|
+
const { phaseRepairMachines } = settings;
|
|
59
|
+
if (phaseRepairMachines !== undefined && (!Array.isArray(phaseRepairMachines)
|
|
60
|
+
|| phaseRepairMachines.some((machine) => { return typeof machine !== 'string' || !machine.trim(); }))) {
|
|
61
|
+
throw new TypeError('phaseRepairMachines must be an array of machine ids');
|
|
62
|
+
}
|
|
55
63
|
return settings;
|
|
56
64
|
}
|
|
57
65
|
|
|
@@ -63,18 +71,34 @@ async function repairHistory(pool, budget, protectedTracks) {
|
|
|
63
71
|
}
|
|
64
72
|
}
|
|
65
73
|
|
|
66
|
-
function
|
|
67
|
-
|
|
68
|
-
processingErrorLog('
|
|
74
|
+
function repairConfiguredPhases(pool, settings, protectedTracks) {
|
|
75
|
+
repairPhaseOverlaps(pool, settings.phaseRepairMachines, protectedTracks, settings).catch((error) => {
|
|
76
|
+
processingErrorLog('repair_phase_overlaps', error, {});
|
|
69
77
|
});
|
|
70
78
|
}
|
|
71
79
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
80
|
+
function phasePolicy({ preserveCoverage, authoritativeProperty }) {
|
|
81
|
+
if (authoritativeProperty !== undefined && (typeof authoritativeProperty?.key !== 'string'
|
|
82
|
+
|| !authoritativeProperty.key || typeof authoritativeProperty.value !== 'string')) {
|
|
83
|
+
throw new TypeError('authoritativeProperty must specify a property key and string value');
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
preserveCoverage,
|
|
87
|
+
isAuthoritative(row) {
|
|
88
|
+
if (!authoritativeProperty) { return false; }
|
|
89
|
+
const properties = typeof row.properties === 'string' ? JSON.parse(row.properties) : row.properties;
|
|
90
|
+
return properties?.[authoritativeProperty.key] === authoritativeProperty.value;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function segmentRecipient(postgres, pool, config) {
|
|
96
|
+
const policy = phasePolicy(config);
|
|
97
|
+
const { segmentSink, splitSink } = segmentSinks(postgres, pool, policy);
|
|
98
|
+
const continued = continuedSegments(segmentSink, pool, silenceBudget(config.segmentWindow || 15), policy);
|
|
75
99
|
const dispatch = contiguousPhases(pool, config.phaseAnchors,
|
|
76
|
-
segmentDispatch(continued, retagSink(pool), splitSink, closeOrphanOpen(pool), pool));
|
|
77
|
-
return fencedSegments(pool,dispatch,config);
|
|
100
|
+
segmentDispatch(continued, retagSink(pool), splitSink, closeOrphanOpen(pool), pool, policy));
|
|
101
|
+
return fencedSegments(pool, dispatch, config);
|
|
78
102
|
}
|
|
79
103
|
|
|
80
104
|
/**
|
|
@@ -129,7 +153,7 @@ export default function segmentPipeline(stomp, postgres, pool, config, recipient
|
|
|
129
153
|
await source.start();
|
|
130
154
|
await silence.start();
|
|
131
155
|
if (settings.repairHistoryOnStart !== false) {
|
|
132
|
-
|
|
156
|
+
repairConfiguredPhases(pool, settings, protectedTracks);
|
|
133
157
|
}
|
|
134
158
|
},
|
|
135
159
|
stop() {
|
|
@@ -138,7 +138,7 @@ export default function contiguousPhases(pool, anchors, dispatch) {
|
|
|
138
138
|
throw invalid('An anchored phase track cannot change geometry via split-family');
|
|
139
139
|
}
|
|
140
140
|
if (row.type === 'split') {
|
|
141
|
-
//
|
|
141
|
+
// Legacy publishers send a compatibility split before each authoritative segment.
|
|
142
142
|
return Promise.resolve();
|
|
143
143
|
}
|
|
144
144
|
const anchor = anchors.get(row.machine);
|
|
@@ -7,17 +7,18 @@ function pointed(record) {
|
|
|
7
7
|
return { ...record, end_time: record.start_time };
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
-
function behind(record, prior) {
|
|
11
|
-
return record.duration === 0 && Boolean(prior) && prior.name !== record.name
|
|
10
|
+
function behind(record, prior, preserveCoverage) {
|
|
11
|
+
return (preserveCoverage || record.duration === 0) && Boolean(prior) && prior.name !== record.name
|
|
12
12
|
&& Date.parse(record.start_time) < Date.parse(prior.start_time);
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
-
function placed(record, prior, apply) {
|
|
16
|
-
if (behind(record, prior)) {
|
|
15
|
+
function placed(record, prior, apply, preserveCoverage) {
|
|
16
|
+
if (behind(record, prior, preserveCoverage)) {
|
|
17
17
|
const start = new Date(prior.end_time).toISOString();
|
|
18
18
|
return { ...record, start_time: start, end_time: start, duration: 0 };
|
|
19
19
|
}
|
|
20
|
-
|
|
20
|
+
const row = apply(record, prior);
|
|
21
|
+
return preserveCoverage ? row : pointed(row);
|
|
21
22
|
}
|
|
22
23
|
|
|
23
24
|
/**
|
|
@@ -69,7 +70,7 @@ async function reopenContinuation(client, record, prior, next) {
|
|
|
69
70
|
* const sink = continuedSegments(segmentSink, pool, 30);
|
|
70
71
|
* await sink.write([record], client);
|
|
71
72
|
*/
|
|
72
|
-
export default function continuedSegments(inner, pool, budgetSeconds) {
|
|
73
|
+
export default function continuedSegments(inner, pool, budgetSeconds, { preserveCoverage = false, isAuthoritative = () => { return false; } } = {}) {
|
|
73
74
|
const apply = segmentContinue(budgetSeconds);
|
|
74
75
|
return {
|
|
75
76
|
async write(records, client) {
|
|
@@ -81,8 +82,8 @@ export default function continuedSegments(inner, pool, budgetSeconds) {
|
|
|
81
82
|
seen.set(key, await latest(runner, record));
|
|
82
83
|
}
|
|
83
84
|
const previous = seen.get(key);
|
|
84
|
-
const row = placed(record, previous, apply);
|
|
85
|
-
await reopenContinuation(client, record, previous, row);
|
|
85
|
+
const row = isAuthoritative(record) ? record : placed(record, previous, apply, preserveCoverage);
|
|
86
|
+
if (!preserveCoverage) { await reopenContinuation(client, record, previous, row); }
|
|
86
87
|
seen.set(key, row);
|
|
87
88
|
rows.push(row);
|
|
88
89
|
return { rows, seen };
|
|
@@ -31,7 +31,7 @@ async function applySplit(pool, machine, start, splits) {
|
|
|
31
31
|
* @returns {Promise<void>}
|
|
32
32
|
*
|
|
33
33
|
* @example
|
|
34
|
-
* await applyDecision(pool, '
|
|
34
|
+
* await applyDecision(pool, 'drive2', '2026-11-17T07:17:09.930Z', '{"tags":["inspection"]}');
|
|
35
35
|
*/
|
|
36
36
|
export async function applyDecision(pool, machine, startTime, payload) {
|
|
37
37
|
const body = JSON.parse(payload);
|
|
@@ -13,9 +13,14 @@ function uniqueStarts(records) {
|
|
|
13
13
|
return [...kept.values()];
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
-
async function foldMachine(runner, machine, batch) {
|
|
16
|
+
async function foldMachine(runner, machine, batch, { preserveCoverage, isAuthoritative }) {
|
|
17
|
+
const inferred = batch.filter((row) => { return !isAuthoritative(row); });
|
|
18
|
+
if (!inferred.length || (preserveCoverage && inferred.every((row) => { return row.duration === 0; }))) {
|
|
19
|
+
return uniqueStarts(batch);
|
|
20
|
+
}
|
|
17
21
|
await runner.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`history:${machine}`]);
|
|
18
|
-
|
|
22
|
+
const folded = await historyAbsorb(runner, machine, uniqueStarts(historyFold([], inferred)));
|
|
23
|
+
return folded.concat(batch.filter(isAuthoritative));
|
|
19
24
|
}
|
|
20
25
|
|
|
21
26
|
function grouped(records) {
|
|
@@ -28,10 +33,10 @@ function grouped(records) {
|
|
|
28
33
|
return groups;
|
|
29
34
|
}
|
|
30
35
|
|
|
31
|
-
function foldAll(runner, groups) {
|
|
36
|
+
function foldAll(runner, groups, policy) {
|
|
32
37
|
return [...groups].reduce(async (prior, [machine, batch]) => {
|
|
33
38
|
const acc = await prior;
|
|
34
|
-
acc.push(...await foldMachine(runner, machine, batch));
|
|
39
|
+
acc.push(...await foldMachine(runner, machine, batch, policy));
|
|
35
40
|
return acc;
|
|
36
41
|
}, Promise.resolve([]));
|
|
37
42
|
}
|
|
@@ -43,15 +48,15 @@ function stamped(records) {
|
|
|
43
48
|
});
|
|
44
49
|
}
|
|
45
50
|
|
|
46
|
-
async function writeOwned(pool, inner, records) {
|
|
51
|
+
async function writeOwned(pool, inner, records, policy) {
|
|
47
52
|
if (typeof pool.connect !== 'function') {
|
|
48
|
-
const next = stamped(uniqueStarts(await foldAll(pool, grouped(records))));
|
|
53
|
+
const next = stamped(uniqueStarts(await foldAll(pool, grouped(records), policy)));
|
|
49
54
|
return inner.write(next, pool);
|
|
50
55
|
}
|
|
51
56
|
const client = await pool.connect();
|
|
52
57
|
try {
|
|
53
58
|
await client.query('BEGIN');
|
|
54
|
-
const next = stamped(uniqueStarts(await foldAll(client, grouped(records))));
|
|
59
|
+
const next = stamped(uniqueStarts(await foldAll(client, grouped(records), policy)));
|
|
55
60
|
const result = await inner.write(next, client);
|
|
56
61
|
await client.query('COMMIT');
|
|
57
62
|
return result;
|
|
@@ -74,13 +79,14 @@ async function writeOwned(pool, inner, records) {
|
|
|
74
79
|
* const sink = foldingSegments(segmentSink, pool);
|
|
75
80
|
* await sink.write([record], client);
|
|
76
81
|
*/
|
|
77
|
-
export default function foldingSegments(inner, pool) {
|
|
82
|
+
export default function foldingSegments(inner, pool, { preserveCoverage = false, isAuthoritative = () => { return false; } } = {}) {
|
|
83
|
+
const policy = { preserveCoverage, isAuthoritative };
|
|
78
84
|
return {
|
|
79
85
|
async write(records, client) {
|
|
80
86
|
if (client && typeof client.query === 'function') {
|
|
81
|
-
return inner.write(stamped(uniqueStarts(await foldAll(client, grouped(records)))), client);
|
|
87
|
+
return inner.write(stamped(uniqueStarts(await foldAll(client, grouped(records), policy))), client);
|
|
82
88
|
}
|
|
83
|
-
return writeOwned(pool, inner, records);
|
|
89
|
+
return writeOwned(pool, inner, records, policy);
|
|
84
90
|
}
|
|
85
91
|
};
|
|
86
92
|
}
|