@yarkivaev/scada 2.6.28 → 2.6.39
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/V0010__fold_phase_overlaps.sql +50 -0
- package/db/migrations/V0011__skip_covered_unsplit_phase.sql +32 -0
- package/db/migrations/V0012__drop_phase_geometry_triggers.sql +6 -0
- package/db/migrations/V0013__contiguous_phase_inbox.sql +6 -0
- package/db/migrations/V0014__contiguous_phase_inbox_grants.sql +1 -0
- package/package.json +1 -1
- package/src/application/gateTimelineBuses.js +79 -0
- package/src/application/plantApi.js +20 -2
- package/src/application/plantServer.js +2 -1
- package/src/application/runtime/deliveryOperations.js +24 -10
- package/src/application/runtime/deliveryPublications.js +16 -11
- package/src/application/supervisorSink.js +2 -0
- package/src/application/sync/siteSyncTargets.js +3 -2
- package/src/domain/segment/dispatch.js +97 -8
- package/src/domain/segment/historyFold.js +227 -0
- package/src/infrastructure/http/plant/routes/timelineRoute.js +2 -2
- package/src/infrastructure/http/plant/streams/timelineStream.js +32 -3
- package/src/infrastructure/ingest/codecs/segmentCodec.js +19 -0
- package/src/infrastructure/ingest/pipelines/segmentBatch.js +25 -7
- package/src/infrastructure/ingest/pipelines/segmentPipeline.js +31 -12
- package/src/infrastructure/ingest/sinks/abutSegments.js +8 -4
- package/src/infrastructure/ingest/sinks/closeSilentOpen.js +4 -3
- package/src/infrastructure/ingest/sinks/contiguousPhases.js +171 -0
- package/src/infrastructure/ingest/sinks/continuedSegments.js +51 -7
- package/src/infrastructure/ingest/sinks/foldCastingPhases.js +147 -0
- package/src/infrastructure/ingest/sinks/foldingSegments.js +86 -0
- package/src/infrastructure/ingest/sinks/segmentTransaction.js +11 -5
- package/src/infrastructure/ingest/sinks/userDecisionSink.js +10 -1
- package/src/infrastructure/messaging/stomp/stompTimelineSegments.js +6 -2
- package/src/infrastructure/persistence/pg/history.js +7 -3
- package/src/infrastructure/persistence/pg/historyAbsorb.js +111 -13
- package/src/infrastructure/persistence/pg/segments.js +7 -0
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
function instant(value) {
|
|
2
|
+
return new Date(value).getTime();
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
function copy(row) {
|
|
6
|
+
return { ...row };
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function tagsOf(row) {
|
|
10
|
+
const raw = typeof row.tags === 'string' ? row.tags : JSON.stringify(row.tags ?? null);
|
|
11
|
+
if (raw === '' || raw === 'null' || raw === '[]') {
|
|
12
|
+
return '[]';
|
|
13
|
+
}
|
|
14
|
+
return raw;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function parsed(row) {
|
|
18
|
+
const raw = row.properties;
|
|
19
|
+
if (typeof raw !== 'string') {
|
|
20
|
+
return raw ?? {};
|
|
21
|
+
}
|
|
22
|
+
return JSON.parse(raw || 'null') ?? {};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function splitKey(row) {
|
|
26
|
+
const value = parsed(row).split_of;
|
|
27
|
+
return value ? String(value) : '';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function emptyUnsplit(row) {
|
|
31
|
+
return tagsOf(row) === '[]' && !splitKey(row);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function overlaps(left, right) {
|
|
35
|
+
return instant(left.start_time) < instant(right.end_time) && instant(right.start_time) < instant(left.end_time);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function liveJoin(left, right) {
|
|
39
|
+
return left.name === right.name && (left.duration === 0 || right.duration === 0)
|
|
40
|
+
&& instant(left.start_time) <= instant(right.start_time);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function covers(outer, inner) {
|
|
44
|
+
return instant(outer.start_time) <= instant(inner.start_time) && instant(outer.end_time) >= instant(inner.end_time);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function stamp(ms, sample) {
|
|
48
|
+
if (sample.start_time instanceof Date) {
|
|
49
|
+
return new Date(ms);
|
|
50
|
+
}
|
|
51
|
+
return new Date(ms).toISOString();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function stretch(host, item) {
|
|
55
|
+
const start = Math.min(instant(host.start_time), instant(item.start_time));
|
|
56
|
+
const end = Math.max(instant(host.end_time), instant(item.end_time));
|
|
57
|
+
host.start_time = stamp(start, host);
|
|
58
|
+
host.end_time = stamp(end, host);
|
|
59
|
+
if (host.duration !== 0 || item.duration !== 0) {
|
|
60
|
+
host.duration = (end - start) / 1000;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function extendTail(host, item) {
|
|
65
|
+
if (instant(item.end_time) <= instant(host.end_time)) {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
host.end_time = stamp(instant(item.end_time), host);
|
|
69
|
+
if (host.duration !== 0) {
|
|
70
|
+
host.duration = (instant(host.end_time) - instant(host.start_time)) / 1000;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function tail(rows, piece) {
|
|
75
|
+
const key = splitKey(piece);
|
|
76
|
+
return rows.filter((row) => {
|
|
77
|
+
return row.name === piece.name && splitKey(row) === key;
|
|
78
|
+
}).reduce((best, row) => {
|
|
79
|
+
return instant(row.start_time) >= instant(best.start_time) ? row : best;
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function subtract(piece, block) {
|
|
84
|
+
if (!overlaps(piece, block)) {
|
|
85
|
+
return [piece];
|
|
86
|
+
}
|
|
87
|
+
const start = instant(piece.start_time);
|
|
88
|
+
const end = instant(piece.end_time);
|
|
89
|
+
const left = instant(block.start_time);
|
|
90
|
+
const right = instant(block.end_time);
|
|
91
|
+
const parts = [];
|
|
92
|
+
if (start < left) {
|
|
93
|
+
parts.push({ ...piece, start_time: stamp(start, piece), end_time: stamp(left, piece),
|
|
94
|
+
duration: piece.duration === 0 ? 0 : (left - start) / 1000 });
|
|
95
|
+
}
|
|
96
|
+
if (end > right) {
|
|
97
|
+
parts.push({ ...piece, start_time: stamp(right, piece), end_time: stamp(end, piece),
|
|
98
|
+
duration: piece.duration === 0 ? 0 : (end - right) / 1000 });
|
|
99
|
+
}
|
|
100
|
+
return parts;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function clip(item, blockers) {
|
|
104
|
+
return blockers.reduce((parts, block) => {
|
|
105
|
+
return parts.flatMap((piece) => {
|
|
106
|
+
return subtract(piece, block);
|
|
107
|
+
});
|
|
108
|
+
}, [item]);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function collapse(rows) {
|
|
112
|
+
const ordered = [...rows].sort((left, right) => {
|
|
113
|
+
return instant(left.start_time) - instant(right.start_time);
|
|
114
|
+
});
|
|
115
|
+
return ordered.reduce((kept, row) => {
|
|
116
|
+
const host = kept.find((prev) => {
|
|
117
|
+
return prev.name === row.name && tagsOf(prev) === tagsOf(row)
|
|
118
|
+
&& !splitKey(prev) && !splitKey(row) && (overlaps(prev, row) || liveJoin(prev, row));
|
|
119
|
+
});
|
|
120
|
+
if (host) {
|
|
121
|
+
stretch(host, row);
|
|
122
|
+
return kept;
|
|
123
|
+
}
|
|
124
|
+
kept.push(copy(row));
|
|
125
|
+
return kept;
|
|
126
|
+
}, []);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function dropEmptyCovers(rows, item) {
|
|
130
|
+
if (emptyUnsplit(item)) {
|
|
131
|
+
return rows;
|
|
132
|
+
}
|
|
133
|
+
return rows.flatMap((row) => {
|
|
134
|
+
if (row.name !== item.name || !overlaps(row, item) || !emptyUnsplit(row)) {
|
|
135
|
+
return [row];
|
|
136
|
+
}
|
|
137
|
+
return subtract(row, item);
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function clipForeign(rows, item) {
|
|
142
|
+
if (emptyUnsplit(item)) {
|
|
143
|
+
return rows.flatMap((row) => {
|
|
144
|
+
if (row.name === item.name || !emptyUnsplit(row)) {
|
|
145
|
+
return [row];
|
|
146
|
+
}
|
|
147
|
+
return subtract(row, item);
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
return rows.flatMap((row) => {
|
|
151
|
+
return row.name === item.name ? [row] : subtract(row, item);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function hostOf(rows, item) {
|
|
156
|
+
const same = rows.filter((row) => {
|
|
157
|
+
return row.name === item.name && (overlaps(row, item) || liveJoin(row, item));
|
|
158
|
+
});
|
|
159
|
+
const covered = same.find((row) => {
|
|
160
|
+
return covers(row, item) && tagsOf(row) === tagsOf(item);
|
|
161
|
+
});
|
|
162
|
+
if (covered) {
|
|
163
|
+
return { kind: 'cover', host: covered };
|
|
164
|
+
}
|
|
165
|
+
const split = same.find((row) => {
|
|
166
|
+
return splitKey(row);
|
|
167
|
+
});
|
|
168
|
+
if (split) {
|
|
169
|
+
return { kind: 'split', host: tail(rows, split) };
|
|
170
|
+
}
|
|
171
|
+
const mergeable = same.filter((row) => {
|
|
172
|
+
return !splitKey(row) && tagsOf(row) === tagsOf(item);
|
|
173
|
+
});
|
|
174
|
+
if (mergeable.length) {
|
|
175
|
+
return { kind: 'merge', host: mergeable.reduce((best, row) => {
|
|
176
|
+
return instant(row.start_time) < instant(best.start_time) ? row : best;
|
|
177
|
+
}) };
|
|
178
|
+
}
|
|
179
|
+
return { kind: 'new' };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function carve(rows, host) {
|
|
183
|
+
const blockers = rows.filter((row) => {
|
|
184
|
+
return row !== host && (row.name !== host.name || tagsOf(row) !== tagsOf(host));
|
|
185
|
+
});
|
|
186
|
+
return rows.filter((row) => {
|
|
187
|
+
return row !== host;
|
|
188
|
+
}).concat(clip(copy(host), blockers));
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function place(rows, item) {
|
|
192
|
+
const pruned = dropEmptyCovers(rows, item);
|
|
193
|
+
const found = hostOf(pruned, item);
|
|
194
|
+
if (found.kind === 'cover') {
|
|
195
|
+
return carve(pruned, found.host);
|
|
196
|
+
}
|
|
197
|
+
if (found.kind === 'split') {
|
|
198
|
+
extendTail(found.host, item);
|
|
199
|
+
return pruned;
|
|
200
|
+
}
|
|
201
|
+
if (found.kind === 'merge') {
|
|
202
|
+
stretch(found.host, item);
|
|
203
|
+
return carve(pruned, found.host);
|
|
204
|
+
}
|
|
205
|
+
const clipped = clipForeign(pruned, item);
|
|
206
|
+
const blockers = clipped.filter((row) => {
|
|
207
|
+
return row.name !== item.name || tagsOf(row) !== tagsOf(item);
|
|
208
|
+
});
|
|
209
|
+
return clipped.concat(clip(copy(item), blockers));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Merges a later classification pass into stored phases without replacing
|
|
214
|
+
* operator tags or split cuts.
|
|
215
|
+
*
|
|
216
|
+
* @param {Array<object>} stored - already persisted phase rows
|
|
217
|
+
* @param {Array<object>} incoming - phases from the later stream
|
|
218
|
+
* @returns {Array<object>} phases after the later stream
|
|
219
|
+
*
|
|
220
|
+
* @example
|
|
221
|
+
* historyFold(stored, incoming);
|
|
222
|
+
*/
|
|
223
|
+
export default function historyFold(stored, incoming) {
|
|
224
|
+
return incoming.reduce((rows, item) => {
|
|
225
|
+
return collapse(place(rows, item));
|
|
226
|
+
}, collapse(stored.map(copy)));
|
|
227
|
+
}
|
|
@@ -75,7 +75,7 @@ async function respondToRequest(gate, timeline, requestId, req, res) {
|
|
|
75
75
|
* @example
|
|
76
76
|
* timelineRoute('/api/v1', plant, { provider, requireOperator: true, defaultUser: 'hmi-kiosk' });
|
|
77
77
|
*/
|
|
78
|
-
export default function timelineRoute(basePath, plant, operatorOptions, decorate) {
|
|
78
|
+
export default function timelineRoute(basePath, plant, operatorOptions, decorate, currentPhase) {
|
|
79
79
|
const gate = timelineOperator(operatorOptions);
|
|
80
80
|
return [
|
|
81
81
|
route('GET', `${basePath}/machines/:machineId/segments`, async (req, res, params, query) => {
|
|
@@ -97,7 +97,7 @@ export default function timelineRoute(basePath, plant, operatorOptions, decorate
|
|
|
97
97
|
});
|
|
98
98
|
}
|
|
99
99
|
const rows = await decorate(params.machineId, await result.machine.timeline.list(options));
|
|
100
|
-
jsonResponse({ items: segmentItems(rows) }).send(res);
|
|
100
|
+
jsonResponse({ items: segmentItems(currentPhase ? currentPhase(params.machineId, rows) : rows) }).send(res);
|
|
101
101
|
}),
|
|
102
102
|
route('PATCH', `${basePath}/machines/:machineId/segments`, async (req, res, params) => {
|
|
103
103
|
const result = machineInPlant(plant, params.machineId);
|
|
@@ -56,6 +56,32 @@ async function emitRequest(sse, event, decorate, machineId) {
|
|
|
56
56
|
}
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
function watchPhase(timeline, sse) {
|
|
60
|
+
const state = { closed: false, version: undefined, timer: undefined };
|
|
61
|
+
async function read() {
|
|
62
|
+
try {
|
|
63
|
+
const rows = await timeline.latest(['phase']);
|
|
64
|
+
const version = JSON.stringify(rows[0] ?? null);
|
|
65
|
+
if (!state.closed && version !== state.version) {
|
|
66
|
+
state.version = version;
|
|
67
|
+
sse.emit('timeline_changed', {});
|
|
68
|
+
}
|
|
69
|
+
} catch {
|
|
70
|
+
// A later read can detect a change after the database reconnects.
|
|
71
|
+
} finally {
|
|
72
|
+
if (!state.closed) {
|
|
73
|
+
state.timer = setTimeout(read, 1000);
|
|
74
|
+
state.timer.unref?.();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
void read();
|
|
79
|
+
return function stop() {
|
|
80
|
+
state.closed = true;
|
|
81
|
+
clearTimeout(state.timer);
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
59
85
|
/**
|
|
60
86
|
* Timeline SSE routes for segments and label requests.
|
|
61
87
|
*
|
|
@@ -68,7 +94,7 @@ async function emitRequest(sse, event, decorate, machineId) {
|
|
|
68
94
|
* @example
|
|
69
95
|
* timelineStream('/api/v1', plant, clock);
|
|
70
96
|
*/
|
|
71
|
-
export default function timelineStream(basePath, plant, clock, decorate) {
|
|
97
|
+
export default function timelineStream(basePath, plant, clock, decorate, watchedPhases = new Set()) {
|
|
72
98
|
return [
|
|
73
99
|
route('GET', `${basePath}/machines/:machineId/segments/stream`, (req, res, params) => {
|
|
74
100
|
const sse = sseResponse(res, clock);
|
|
@@ -78,14 +104,17 @@ export default function timelineStream(basePath, plant, clock, decorate) {
|
|
|
78
104
|
sse.close();
|
|
79
105
|
return;
|
|
80
106
|
}
|
|
107
|
+
const watched = watchedPhases.has(params.machineId);
|
|
108
|
+
const stop = watched ? watchPhase(result.machine.timeline, sse) : undefined;
|
|
81
109
|
const subscription = result.machine.timeline.stream((event) => {
|
|
82
|
-
return emitSegment(sse, event, decorate, params.machineId);
|
|
110
|
+
return watched && event.type === 'created' && !event.retag ? undefined : emitSegment(sse, event, decorate, params.machineId);
|
|
83
111
|
});
|
|
84
112
|
const heartbeat = setInterval(() => {
|
|
85
113
|
sse.heartbeat();
|
|
86
114
|
}, 30000);
|
|
87
|
-
req.on('close', () => {
|
|
115
|
+
(typeof res.once === 'function' ? res : req).on('close', () => {
|
|
88
116
|
clearInterval(heartbeat);
|
|
117
|
+
stop?.();
|
|
89
118
|
subscription.cancel();
|
|
90
119
|
});
|
|
91
120
|
}),
|
|
@@ -25,11 +25,30 @@ function familyRecord(parsed) {
|
|
|
25
25
|
};
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
+
const maxTransitionPieces = 128;
|
|
29
|
+
|
|
30
|
+
function transitionRecord(parsed) {
|
|
31
|
+
if (typeof parsed.machine !== 'string' || !Array.isArray(parsed.pieces) ||
|
|
32
|
+
parsed.pieces.length < 2 || parsed.pieces.length > maxTransitionPieces) {
|
|
33
|
+
throw new Error('Invalid phase transition envelope');
|
|
34
|
+
}
|
|
35
|
+
const pieces = parsed.pieces.map((piece) => {
|
|
36
|
+
return segmentNormalize({ ...piece, type: 'segment', kind: 'phase', machine: parsed.machine });
|
|
37
|
+
});
|
|
38
|
+
if (pieces.at(-1).duration !== 0 || pieces.slice(0, -1).some((piece, index) => {
|
|
39
|
+
return piece.duration <= 0 || piece.end_time !== pieces[index + 1].start_time;
|
|
40
|
+
})) {
|
|
41
|
+
throw new Error('A phase transition must close adjacent phases and open the next');
|
|
42
|
+
}
|
|
43
|
+
return { type: 'phase-transition', machine: parsed.machine, pieces };
|
|
44
|
+
}
|
|
45
|
+
|
|
28
46
|
/** Decode once before admission so invalid envelopes never enter a transaction batch. */
|
|
29
47
|
export function decodeSegment(raw) {
|
|
30
48
|
try {
|
|
31
49
|
const parsed = JSON.parse(raw.payload);
|
|
32
50
|
if (parsed.type === 'split-family') { return familyRecord(parsed); }
|
|
51
|
+
if (parsed.type === 'phase-transition') { return transitionRecord(parsed); }
|
|
33
52
|
return segmentNormalize(parsed);
|
|
34
53
|
} catch (error) {
|
|
35
54
|
error.permanent = true;
|
|
@@ -62,14 +62,25 @@ function ready(state, lane, packet, reason) {
|
|
|
62
62
|
if (state.stopped || packet.ready) { return; }
|
|
63
63
|
packet.ready = true;packet.reason = reason;clearTimeout(packet.timer);queueReady(state, lane);
|
|
64
64
|
}
|
|
65
|
+
function scheduleAge(state, lane, packet) {
|
|
66
|
+
packet.timer = setTimeout(() => {
|
|
67
|
+
if (state.stopped || packet.ready) { return; }
|
|
68
|
+
if (lane.running) { scheduleAge(state, lane, packet);return; }
|
|
69
|
+
ready(state, lane, packet, 'age');
|
|
70
|
+
}, state.policy.maxWaitMs);
|
|
71
|
+
}
|
|
65
72
|
function packetFor(state, lane, bytes) {
|
|
66
73
|
let packet = lane.packets.at(-1);
|
|
67
|
-
if (packet &&
|
|
68
|
-
|
|
69
|
-
|
|
74
|
+
if (packet && packet.bytes + bytes > state.policy.maxBytes) {
|
|
75
|
+
ready(state, lane, packet, 'bytes');
|
|
76
|
+
packet = null;
|
|
77
|
+
} else if (packet && packet.messages >= state.policy.maxMessages) {
|
|
78
|
+
ready(state, lane, packet, 'messages');
|
|
79
|
+
packet = null;
|
|
80
|
+
}
|
|
81
|
+
if (!packet) {
|
|
70
82
|
packet = { entries: [], messages: 0, bytes: 0, completed: new Set(), ready: false, createdAt: Date.now() };
|
|
71
|
-
|
|
72
|
-
packet.timer = setTimeout(() => { ready(state, lane, pending, 'age'); }, state.policy.maxWaitMs);
|
|
83
|
+
scheduleAge(state, lane, packet);
|
|
73
84
|
lane.packets.push(packet);
|
|
74
85
|
}
|
|
75
86
|
return packet;
|
|
@@ -99,12 +110,18 @@ async function persistOne(state, entry, packet) {
|
|
|
99
110
|
refuse(state, entry, failure);
|
|
100
111
|
}
|
|
101
112
|
}
|
|
113
|
+
function retryable(error) {
|
|
114
|
+
return error.code === 'OPERATION_TIMEOUT' || /timed out/u.test(error.message);
|
|
115
|
+
}
|
|
102
116
|
async function runPacket(state, packet) {
|
|
103
117
|
try { await persist(state, packet.entries, packet); }
|
|
104
118
|
catch (error) {
|
|
119
|
+
if (retryable(error) && !state.stopped) {
|
|
120
|
+
packet.entries.forEach((entry) => { refuse(state, entry, error); });
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
105
123
|
if (!error.permanent || state.stopped) { throw error; }
|
|
106
124
|
notify(state.onBatch, { committed: false, messages: packet.messages, records: packet.entries.length, reason: 'rollback' });
|
|
107
|
-
// Confirmed permanent failure: isolate the bad command after the batch rollback.
|
|
108
125
|
for (const entry of packet.entries) {
|
|
109
126
|
// eslint-disable-next-line no-await-in-loop
|
|
110
127
|
await persistOne(state, entry, packet);
|
|
@@ -117,7 +134,8 @@ function startPacket(state, lane) {
|
|
|
117
134
|
const task = Promise.resolve().then(() => { return runPacket(state, packet); }).catch(error => { fail(state, error); }).finally(() => {
|
|
118
135
|
state.active -= 1;lane.running = false;state.tasks.delete(task);state.inflight.delete(packet);
|
|
119
136
|
if (lane.packets.length === 0) { state.lanes.delete(lane.machine); }
|
|
120
|
-
else { queueReady(state, lane); }
|
|
137
|
+
else if (lane.packets[0].ready) { queueReady(state, lane); }
|
|
138
|
+
else { ready(state, lane, lane.packets[0], 'age'); }
|
|
121
139
|
state.pump();
|
|
122
140
|
});
|
|
123
141
|
state.tasks.add(task);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import contiguousPhases, { validatePhaseAnchors } from '../sinks/contiguousPhases.js';
|
|
1
2
|
import stompOptions from './stompOptions.js';
|
|
2
3
|
import segmentTransactions from './segmentTransactions.js';
|
|
3
4
|
import segmentBatchPolicy from './segmentBatchPolicy.js';
|
|
@@ -11,9 +12,11 @@ import segmentCodec from '../codecs/segmentCodec.js';
|
|
|
11
12
|
import processingErrorLog from '../processingErrorLog.js';
|
|
12
13
|
import silentOpenWatch from '../silentOpenWatch.js';
|
|
13
14
|
import abutSegments from '../sinks/abutSegments.js';
|
|
15
|
+
import foldCastingPhases from '../sinks/foldCastingPhases.js';
|
|
14
16
|
import closeOrphanOpen from '../sinks/closeOrphanOpen.js';
|
|
15
17
|
import closeSilentOpen from '../sinks/closeSilentOpen.js';
|
|
16
18
|
import continuedSegments from '../sinks/continuedSegments.js';
|
|
19
|
+
import foldingSegments from '../sinks/foldingSegments.js';
|
|
17
20
|
import retagSink from '../sinks/retagSink.js';
|
|
18
21
|
|
|
19
22
|
export const segmentColumns = ['machine', 'kind', 'name', 'start_time', 'end_time', 'duration',
|
|
@@ -21,7 +24,7 @@ export const segmentColumns = ['machine', 'kind', 'name', 'start_time', 'end_tim
|
|
|
21
24
|
export const segmentConflict = ['machine', 'kind', 'start_time'];
|
|
22
25
|
export const segmentUpdateColumns = ['name', 'end_time', 'duration', 'options', 'resolved', 'updated_at'];
|
|
23
26
|
export const splitUpdateColumns = ['name', 'end_time', 'duration', 'tags', 'options', 'properties', 'resolved'];
|
|
24
|
-
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"%\'))';
|
|
27
|
+
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))';
|
|
25
28
|
export const segmentsIngestDestination = '/queue/scada.segments.ingest';
|
|
26
29
|
|
|
27
30
|
export { default as segmentDispatch } from '../../../domain/segment/dispatch.js';
|
|
@@ -36,10 +39,10 @@ export { default as segmentDispatch } from '../../../domain/segment/dispatch.js'
|
|
|
36
39
|
function segmentSinks(postgres, pool) {
|
|
37
40
|
const shared = { pool, conflict: segmentConflict, updateWhere: segmentUpdateWhere };
|
|
38
41
|
return {
|
|
39
|
-
segmentSink: postgresSink(postgres, 'segments', segmentColumns,
|
|
40
|
-
{ ...shared, update: segmentUpdateColumns }),
|
|
41
|
-
splitSink: postgresSink(postgres, 'segments', segmentColumns,
|
|
42
|
-
{ ...shared, update: splitUpdateColumns })
|
|
42
|
+
segmentSink: foldingSegments(postgresSink(postgres, 'segments', segmentColumns,
|
|
43
|
+
{ ...shared, update: segmentUpdateColumns }), pool),
|
|
44
|
+
splitSink: foldingSegments(postgresSink(postgres, 'segments', segmentColumns,
|
|
45
|
+
{ ...shared, update: splitUpdateColumns }), pool)
|
|
43
46
|
};
|
|
44
47
|
}
|
|
45
48
|
|
|
@@ -51,6 +54,20 @@ function pipelineSettings(config) {
|
|
|
51
54
|
return settings;
|
|
52
55
|
}
|
|
53
56
|
|
|
57
|
+
async function repairHistory(pool, budget, protectedTracks) {
|
|
58
|
+
try {
|
|
59
|
+
await abutSegments(pool, budget, protectedTracks);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
processingErrorLog('abut_segments', error, { budgetSeconds: budget });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function repairCasting(pool, protectedTracks) {
|
|
66
|
+
foldCastingPhases(pool, protectedTracks).catch((error) => {
|
|
67
|
+
processingErrorLog('fold_casting_phases', error, {});
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
54
71
|
/**
|
|
55
72
|
* Pipeline for streaming STOMP segment data to PostgreSQL segments table.
|
|
56
73
|
* Subscribes to the durable ingest queue so shovel traffic survives consumer gaps.
|
|
@@ -68,7 +85,8 @@ export default function segmentPipeline(stomp, postgres, pool, config) {
|
|
|
68
85
|
const budget = silenceBudget(settings.segmentWindow || 15);
|
|
69
86
|
const { segmentSink, splitSink } = segmentSinks(postgres, pool);
|
|
70
87
|
const continued = continuedSegments(segmentSink, pool, budget);
|
|
71
|
-
const dispatch =
|
|
88
|
+
const dispatch = contiguousPhases(pool, settings.phaseAnchors,
|
|
89
|
+
segmentDispatch(continued, retagSink(pool), splitSink, closeOrphanOpen(pool), pool));
|
|
72
90
|
// eslint-disable-next-line prefer-const -- The timer codec closes over the source constructed with that codec.
|
|
73
91
|
let source;
|
|
74
92
|
const codec = segmentCodec(dispatch);
|
|
@@ -90,22 +108,23 @@ export default function segmentPipeline(stomp, postgres, pool, config) {
|
|
|
90
108
|
stompOptions(settings, { serial: false, manualAck: true, deliveryTimeoutMs, onFatal(error) {
|
|
91
109
|
coalesce.abort?.(error);settings.onFatal?.(error);
|
|
92
110
|
} }));
|
|
93
|
-
const silence = silentOpenWatch(closeSilentOpen(pool), budget, {
|
|
111
|
+
const silence = silentOpenWatch(closeSilentOpen(pool, [...(settings.phaseAnchors?.keys() ?? [])]), budget, {
|
|
94
112
|
intervalMs: (settings.poll || 5) * 1000
|
|
95
113
|
});
|
|
96
114
|
return {
|
|
97
115
|
health() { return source.health(); },
|
|
98
116
|
destination,
|
|
99
117
|
async start() {
|
|
118
|
+
const protectedTracks = [...(settings.phaseAnchors?.keys() ?? [])];
|
|
119
|
+
await validatePhaseAnchors(pool, settings.phaseAnchors);
|
|
100
120
|
if (settings.repairHistoryOnStart !== false) {
|
|
101
|
-
|
|
102
|
-
await abutSegments(pool, budget);
|
|
103
|
-
} catch (error) {
|
|
104
|
-
processingErrorLog('abut_segments', error, { budgetSeconds: budget });
|
|
105
|
-
}
|
|
121
|
+
await repairHistory(pool, budget, protectedTracks);
|
|
106
122
|
}
|
|
107
123
|
await source.start();
|
|
108
124
|
await silence.start();
|
|
125
|
+
if (settings.repairHistoryOnStart !== false) {
|
|
126
|
+
repairCasting(pool, protectedTracks);
|
|
127
|
+
}
|
|
109
128
|
},
|
|
110
129
|
stop() {
|
|
111
130
|
return stopSegmentPipeline(source, coalesce, silence, pool, settings.stopTimeoutMs ?? 5000);
|
|
@@ -6,6 +6,7 @@ const GAP_SQL = `UPDATE segments AS left_row
|
|
|
6
6
|
lead(start_time) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_start,
|
|
7
7
|
lead(name) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_name
|
|
8
8
|
FROM segments
|
|
9
|
+
WHERE kind <> 'phase' OR NOT (machine = ANY($2::text[]))
|
|
9
10
|
) AS next_row
|
|
10
11
|
WHERE left_row.machine = next_row.machine
|
|
11
12
|
AND left_row.kind = next_row.kind
|
|
@@ -37,6 +38,7 @@ const ABSORB_SQL = `UPDATE segments AS left_row
|
|
|
37
38
|
lead(end_time) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_end,
|
|
38
39
|
lead(duration) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_duration
|
|
39
40
|
FROM segments
|
|
41
|
+
WHERE kind <> 'phase' OR NOT (machine = ANY($2::text[]))
|
|
40
42
|
) AS next_row
|
|
41
43
|
WHERE left_row.machine = next_row.machine
|
|
42
44
|
AND left_row.kind = next_row.kind
|
|
@@ -51,6 +53,7 @@ const COLLAPSE_SQL = `DELETE FROM segments AS later
|
|
|
51
53
|
lead(start_time) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_start,
|
|
52
54
|
lead(name) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_name
|
|
53
55
|
FROM segments
|
|
56
|
+
WHERE kind <> 'phase' OR NOT (machine = ANY($2::text[]))
|
|
54
57
|
) AS pair
|
|
55
58
|
WHERE later.machine = pair.machine
|
|
56
59
|
AND later.kind = pair.kind
|
|
@@ -65,13 +68,14 @@ const COLLAPSE_SQL = `DELETE FROM segments AS later
|
|
|
65
68
|
*
|
|
66
69
|
* @param {object} pool - pg pool
|
|
67
70
|
* @param {number} budgetSeconds - maximum gap that still counts as continuous
|
|
71
|
+
* @param {string[]} protectedTracks - machines whose phase boundaries are authoritative
|
|
68
72
|
* @returns {Promise<void>}
|
|
69
73
|
*
|
|
70
74
|
* @example
|
|
71
75
|
* await abutSegments(pool, 30);
|
|
72
76
|
*/
|
|
73
|
-
export default async function abutSegments(pool, budgetSeconds) {
|
|
74
|
-
await pool.query(GAP_SQL, [budgetSeconds]);
|
|
75
|
-
await pool.query(ABSORB_SQL, [budgetSeconds]);
|
|
76
|
-
await pool.query(COLLAPSE_SQL, [budgetSeconds]);
|
|
77
|
+
export default async function abutSegments(pool, budgetSeconds, protectedTracks = []) {
|
|
78
|
+
await pool.query(GAP_SQL, [budgetSeconds, protectedTracks]);
|
|
79
|
+
await pool.query(ABSORB_SQL, [budgetSeconds, protectedTracks]);
|
|
80
|
+
await pool.query(COLLAPSE_SQL, [budgetSeconds, protectedTracks]);
|
|
77
81
|
}
|
|
@@ -13,7 +13,7 @@ import processingErrorLog from '../processingErrorLog.js';
|
|
|
13
13
|
* const closer = closeSilentOpen(pool);
|
|
14
14
|
* await closer.close(30);
|
|
15
15
|
*/
|
|
16
|
-
export default function closeSilentOpen(pool) {
|
|
16
|
+
export default function closeSilentOpen(pool, excludedMachines = []) {
|
|
17
17
|
if (!pool || typeof pool.query !== 'function') {
|
|
18
18
|
throw new Error('Pool must have a query() method');
|
|
19
19
|
}
|
|
@@ -28,8 +28,9 @@ export default function closeSilentOpen(pool) {
|
|
|
28
28
|
)
|
|
29
29
|
WHERE duration = 0
|
|
30
30
|
AND end_time > start_time
|
|
31
|
-
AND updated_at < NOW() - make_interval(secs => $1)
|
|
32
|
-
|
|
31
|
+
AND updated_at < NOW() - make_interval(secs => $1)
|
|
32
|
+
${excludedMachines.length ? "AND NOT (machine = ANY($2::text[]))" : ""}`,
|
|
33
|
+
excludedMachines.length ? [budgetSeconds, excludedMachines] : [budgetSeconds]
|
|
33
34
|
);
|
|
34
35
|
} catch (error) {
|
|
35
36
|
processingErrorLog('close_silent_open', error, { budgetSeconds });
|