@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,171 @@
|
|
|
1
|
+
/** An opted-in track advances only from its certified anchor or its current visible tail. */
|
|
2
|
+
export function phaseAnchors(raw) {
|
|
3
|
+
if (raw === undefined) {
|
|
4
|
+
return new Map();
|
|
5
|
+
}
|
|
6
|
+
const values = JSON.parse(raw);
|
|
7
|
+
if (!values || typeof values !== 'object' || Array.isArray(values)) {
|
|
8
|
+
throw new TypeError('CONTIGUOUS_PHASE_ANCHORS must map machine ids to UTC timestamps');
|
|
9
|
+
}
|
|
10
|
+
return new Map(Object.entries(values).map(([machine, value]) => {
|
|
11
|
+
if (!machine || typeof value !== 'string' || !/^\d{4}-\d\d-\d\dT.*Z$/u.test(value) || !Number.isFinite(Date.parse(value))) {
|
|
12
|
+
throw new TypeError('Invalid contiguous phase anchor');
|
|
13
|
+
}
|
|
14
|
+
return [machine, new Date(value).toISOString()];
|
|
15
|
+
}));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const stage = `
|
|
19
|
+
INSERT INTO contiguous_phase_inbox (machine, start_time, phase)
|
|
20
|
+
VALUES ($1,$2,$3)
|
|
21
|
+
ON CONFLICT (machine, start_time) DO UPDATE SET phase=EXCLUDED.phase
|
|
22
|
+
WHERE (contiguous_phase_inbox.phase->>'duration')::numeric = 0
|
|
23
|
+
AND ((EXCLUDED.phase->>'duration')::numeric > 0
|
|
24
|
+
OR (EXCLUDED.phase->>'end_time')::timestamptz >=
|
|
25
|
+
(contiguous_phase_inbox.phase->>'end_time')::timestamptz)`;
|
|
26
|
+
|
|
27
|
+
const visible = `
|
|
28
|
+
INSERT INTO segments (machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,updated_at)
|
|
29
|
+
VALUES ($1,'phase',$2,$3,$4,$5,$6,$7,$8,$9,now())
|
|
30
|
+
ON CONFLICT (machine,kind,start_time) DO UPDATE SET
|
|
31
|
+
name=EXCLUDED.name,end_time=EXCLUDED.end_time,duration=EXCLUDED.duration,
|
|
32
|
+
options=EXCLUDED.options,properties=EXCLUDED.properties,updated_at=EXCLUDED.updated_at
|
|
33
|
+
WHERE segments.duration=0
|
|
34
|
+
AND (EXCLUDED.duration>0 OR
|
|
35
|
+
((segments.name=EXCLUDED.name OR segments.start_time=segments.end_time)
|
|
36
|
+
AND segments.end_time<=EXCLUDED.end_time))`;
|
|
37
|
+
|
|
38
|
+
function invalid(message) {
|
|
39
|
+
return Object.assign(new RangeError(message), { permanent: true });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function check(row) {
|
|
43
|
+
const span = Date.parse(row.end_time) - Date.parse(row.start_time);
|
|
44
|
+
if (!Number.isSafeInteger(span) || span < 0 ||
|
|
45
|
+
(row.duration !== 0 && (span === 0 || row.duration !== span / 1000))) {
|
|
46
|
+
throw invalid('Invalid phase duration or bounds');
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function write(runner, row) {
|
|
51
|
+
return runner.query(visible, [row.machine,row.name,row.start_time,row.end_time,row.duration,
|
|
52
|
+
row.options ?? null,row.tags ?? null,row.properties ?? null,row.resolved ?? true]);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function drain(runner, machine, start) {
|
|
56
|
+
let next = start;
|
|
57
|
+
for (;;) {
|
|
58
|
+
// Rows ahead of the tail survive in the inbox until the preceding phase commits.
|
|
59
|
+
// eslint-disable-next-line no-await-in-loop
|
|
60
|
+
const { rows: [item] } = await runner.query(
|
|
61
|
+
'DELETE FROM contiguous_phase_inbox WHERE machine=$1 AND start_time=$2 RETURNING phase',
|
|
62
|
+
[machine,next]);
|
|
63
|
+
if (!item) {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
// eslint-disable-next-line no-await-in-loop
|
|
67
|
+
await write(runner, item.phase);
|
|
68
|
+
if (item.phase.duration === 0) {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
next = item.phase.end_time;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function commit(runner, row, anchor) {
|
|
76
|
+
check(row);
|
|
77
|
+
const { machine } = row;
|
|
78
|
+
await runner.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`history:${machine}`]);
|
|
79
|
+
const { rows: [latest] } = await runner.query(`
|
|
80
|
+
SELECT start_time, end_time, duration FROM segments
|
|
81
|
+
WHERE machine=$1 AND kind='phase' AND start_time >= $2
|
|
82
|
+
ORDER BY start_time DESC LIMIT 1`, [machine, anchor]);
|
|
83
|
+
let next = anchor;
|
|
84
|
+
if (latest) {
|
|
85
|
+
next = Number(latest.duration) > 0 ? latest.end_time : latest.start_time;
|
|
86
|
+
}
|
|
87
|
+
if (Date.parse(row.start_time) >= Date.parse(next)) {
|
|
88
|
+
await runner.query(stage, [machine, row.start_time, JSON.stringify(row)]);
|
|
89
|
+
await drain(runner, machine, next);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function apply(runner, rows, anchor) {
|
|
94
|
+
return rows.reduce(async (previous, row) => {
|
|
95
|
+
await previous;
|
|
96
|
+
await commit(runner, row, anchor);
|
|
97
|
+
}, Promise.resolve());
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function transaction(pool, rows, anchor) {
|
|
101
|
+
const client = await pool.connect();
|
|
102
|
+
try {
|
|
103
|
+
await client.query('BEGIN');
|
|
104
|
+
await apply(client, rows, anchor);
|
|
105
|
+
await client.query('COMMIT');
|
|
106
|
+
} catch (error) {
|
|
107
|
+
await client.query('ROLLBACK');
|
|
108
|
+
throw error;
|
|
109
|
+
} finally {
|
|
110
|
+
client.release();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Adds durable out-of-order staging for explicitly anchored phase tracks. */
|
|
115
|
+
export default function contiguousPhases(pool, anchors, dispatch) {
|
|
116
|
+
if (!anchors?.size) {
|
|
117
|
+
return dispatch;
|
|
118
|
+
}
|
|
119
|
+
function routed(row) {
|
|
120
|
+
return anchors.has(row.machine) && (row.kind ?? 'phase') === 'phase' &&
|
|
121
|
+
['segment', 'split', 'split-family', 'phase-transition'].includes(row.type);
|
|
122
|
+
}
|
|
123
|
+
function accept(row, client) {
|
|
124
|
+
if (!routed(row)) {
|
|
125
|
+
return dispatch.accept(row, client);
|
|
126
|
+
}
|
|
127
|
+
if (row.type === 'split-family') {
|
|
128
|
+
throw invalid('An anchored phase track cannot change geometry via split-family');
|
|
129
|
+
}
|
|
130
|
+
if (row.type === 'split') {
|
|
131
|
+
// Casting publishers send a compatibility split before each authoritative segment.
|
|
132
|
+
return Promise.resolve();
|
|
133
|
+
}
|
|
134
|
+
const anchor = anchors.get(row.machine);
|
|
135
|
+
const rows = row.type === 'phase-transition' ? row.pieces : [row];
|
|
136
|
+
return client ? apply(client, rows, anchor) : transaction(pool, rows, anchor);
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
accept,
|
|
140
|
+
acceptMany(records, client) {
|
|
141
|
+
if (!records.some(routed)) {
|
|
142
|
+
return dispatch.acceptMany(records, client);
|
|
143
|
+
}
|
|
144
|
+
return records.reduce(async (pending, row) => {
|
|
145
|
+
await pending;
|
|
146
|
+
return accept(row, client);
|
|
147
|
+
}, Promise.resolve());
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Refuse to adopt an existing noncontiguous suffix as a certified prefix. */
|
|
153
|
+
export async function validatePhaseAnchors(pool, anchors = new Map()) {
|
|
154
|
+
for (const [machine, anchor] of anchors) {
|
|
155
|
+
// eslint-disable-next-line no-await-in-loop
|
|
156
|
+
const { rows: [status] } = await pool.query(`
|
|
157
|
+
WITH suffix AS (
|
|
158
|
+
SELECT start_time,end_time,duration,
|
|
159
|
+
lag(end_time,1,$2::timestamptz) OVER (ORDER BY start_time) AS expected,
|
|
160
|
+
lead(start_time) OVER (ORDER BY start_time) AS next
|
|
161
|
+
FROM segments WHERE machine=$1 AND kind='phase' AND start_time >= $2
|
|
162
|
+
)
|
|
163
|
+
SELECT EXISTS (SELECT 1 FROM suffix WHERE start_time<>expected OR end_time<start_time
|
|
164
|
+
OR (duration=0 AND next IS NOT NULL)) OR EXISTS (
|
|
165
|
+
SELECT 1 FROM segments WHERE machine=$1 AND kind='phase' AND start_time<$2 AND end_time>$2
|
|
166
|
+
) AS invalid`, [machine,anchor]);
|
|
167
|
+
if (status.invalid) {
|
|
168
|
+
throw new Error(`Cannot adopt noncontiguous phase history for ${machine}`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
import segmentContinue from '../../../domain/segment/segmentContinue.js';
|
|
2
2
|
|
|
3
|
+
function pointed(record) {
|
|
4
|
+
if (record.duration !== 0) {
|
|
5
|
+
return record;
|
|
6
|
+
}
|
|
7
|
+
return { ...record, end_time: record.start_time };
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function behind(record, prior) {
|
|
11
|
+
return record.duration === 0 && Boolean(prior) && prior.name !== record.name
|
|
12
|
+
&& Date.parse(record.start_time) < Date.parse(prior.start_time);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function placed(record, prior, apply) {
|
|
16
|
+
if (behind(record, prior)) {
|
|
17
|
+
const start = new Date(prior.end_time).toISOString();
|
|
18
|
+
return { ...record, start_time: start, end_time: start, duration: 0 };
|
|
19
|
+
}
|
|
20
|
+
return pointed(apply(record, prior));
|
|
21
|
+
}
|
|
22
|
+
|
|
3
23
|
/**
|
|
4
24
|
* Loads the latest segment row visible to this write.
|
|
5
25
|
*
|
|
@@ -9,7 +29,7 @@ import segmentContinue from '../../../domain/segment/segmentContinue.js';
|
|
|
9
29
|
*/
|
|
10
30
|
async function latest(runner, record) {
|
|
11
31
|
const result = await runner.query(
|
|
12
|
-
`SELECT name, start_time, end_time
|
|
32
|
+
`SELECT name, start_time, end_time, duration
|
|
13
33
|
FROM segments
|
|
14
34
|
WHERE machine = $1 AND kind = $2
|
|
15
35
|
ORDER BY start_time DESC
|
|
@@ -19,6 +39,23 @@ async function latest(runner, record) {
|
|
|
19
39
|
return result.rows[0];
|
|
20
40
|
}
|
|
21
41
|
|
|
42
|
+
async function reopenContinuation(client, record, prior, next) {
|
|
43
|
+
// The original start proves this heartbeat follows the closed row. A replay
|
|
44
|
+
// at the old start alone cannot reopen it after conversion to a pending point.
|
|
45
|
+
if (client && record.duration === 0 && prior?.duration > 0 &&
|
|
46
|
+
Date.parse(record.start_time) > Date.parse(prior.end_time) &&
|
|
47
|
+
Date.parse(next.start_time) === Date.parse(prior.start_time)) {
|
|
48
|
+
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`history:${record.machine}`]);
|
|
49
|
+
await client.query(
|
|
50
|
+
`UPDATE segments SET duration=0,end_time=start_time,updated_at=clock_timestamp()
|
|
51
|
+
WHERE machine=$1 AND kind=$2 AND start_time=$3 AND end_time=$4 AND name=$5 AND duration>0
|
|
52
|
+
AND NOT EXISTS (SELECT 1 FROM segments later
|
|
53
|
+
WHERE later.machine=$1 AND later.kind=$2 AND later.start_time>$3)`,
|
|
54
|
+
[record.machine, record.kind || 'phase', prior.start_time, prior.end_time, prior.name]
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
22
59
|
/**
|
|
23
60
|
* Segment sink that continues the previous row across a restart
|
|
24
61
|
* when metric samples never left the continuity budget.
|
|
@@ -38,12 +75,19 @@ export default function continuedSegments(inner, pool, budgetSeconds) {
|
|
|
38
75
|
async write(records, client) {
|
|
39
76
|
const runner = client && typeof client.query === 'function' ? client : pool;
|
|
40
77
|
const next = await records.reduce(async (prior, record) => {
|
|
41
|
-
const rows = await prior;
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
78
|
+
const { rows, seen } = await prior;
|
|
79
|
+
const key = `${record.machine}\0${record.kind || 'phase'}`;
|
|
80
|
+
if (!seen.has(key)) {
|
|
81
|
+
seen.set(key, await latest(runner, record));
|
|
82
|
+
}
|
|
83
|
+
const previous = seen.get(key);
|
|
84
|
+
const row = placed(record, previous, apply);
|
|
85
|
+
await reopenContinuation(client, record, previous, row);
|
|
86
|
+
seen.set(key, row);
|
|
87
|
+
rows.push(row);
|
|
88
|
+
return { rows, seen };
|
|
89
|
+
}, Promise.resolve({ rows: [], seen: new Map() }));
|
|
90
|
+
return inner.write(next.rows, client);
|
|
47
91
|
}
|
|
48
92
|
};
|
|
49
93
|
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import historyFold from '../../../domain/segment/historyFold.js';
|
|
2
|
+
import processingErrorLog from '../processingErrorLog.js';
|
|
3
|
+
|
|
4
|
+
function startOf(row) {
|
|
5
|
+
return new Date(row.start_time).getTime();
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function pinLive(rows) {
|
|
9
|
+
if (!rows.length) {
|
|
10
|
+
return rows;
|
|
11
|
+
}
|
|
12
|
+
const ordered = [...rows].sort((left, right) => {
|
|
13
|
+
return startOf(left) - startOf(right);
|
|
14
|
+
});
|
|
15
|
+
return ordered.map((row, i, all) => {
|
|
16
|
+
const copy = { ...row };
|
|
17
|
+
if (i === all.length - 1) {
|
|
18
|
+
if (copy.duration === 0) {
|
|
19
|
+
copy.end_time = copy.start_time;
|
|
20
|
+
}
|
|
21
|
+
return copy;
|
|
22
|
+
}
|
|
23
|
+
if (copy.duration === 0) {
|
|
24
|
+
copy.duration = Math.max(1, (Date.parse(copy.end_time) - Date.parse(copy.start_time)) / 1000);
|
|
25
|
+
}
|
|
26
|
+
return copy;
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function loadPhases(runner, machine) {
|
|
31
|
+
const stored = await runner.query(
|
|
32
|
+
'SELECT machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed FROM segments WHERE machine=$1 AND kind=\'phase\' ORDER BY start_time',
|
|
33
|
+
[machine]
|
|
34
|
+
);
|
|
35
|
+
return stored.rows;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function dropStarts(runner, machine, dropped) {
|
|
39
|
+
if (!dropped.length) {
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
await runner.query(
|
|
43
|
+
'DELETE FROM segments WHERE machine=$1 AND kind=\'phase\' AND start_time = ANY($2::timestamptz[])',
|
|
44
|
+
[machine, dropped.map((row) => { return row.start_time; })]
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function putPhase(runner, row) {
|
|
49
|
+
await runner.query(
|
|
50
|
+
`INSERT INTO segments (machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,updated_at)
|
|
51
|
+
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,clock_timestamp())
|
|
52
|
+
ON CONFLICT (machine,kind,start_time) DO UPDATE SET
|
|
53
|
+
name=EXCLUDED.name,end_time=EXCLUDED.end_time,duration=EXCLUDED.duration,
|
|
54
|
+
options=EXCLUDED.options,resolved=EXCLUDED.resolved,updated_at=EXCLUDED.updated_at`,
|
|
55
|
+
[row.machine, row.kind || 'phase', row.name, row.start_time, row.end_time, row.duration,
|
|
56
|
+
row.options, row.tags, row.properties, row.resolved]
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function foldRows(rows) {
|
|
61
|
+
const size = 4;
|
|
62
|
+
const groups = [];
|
|
63
|
+
let offset = 0;
|
|
64
|
+
while (offset < rows.length) {
|
|
65
|
+
groups.push(rows.slice(offset, offset + size));
|
|
66
|
+
offset += size;
|
|
67
|
+
}
|
|
68
|
+
return groups.reduce(async (prior, group) => {
|
|
69
|
+
const acc = await prior;
|
|
70
|
+
await new Promise((resolve) => {
|
|
71
|
+
setImmediate(resolve);
|
|
72
|
+
});
|
|
73
|
+
return historyFold(acc, group);
|
|
74
|
+
}, Promise.resolve([]));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function foldMachine(runner, machine) {
|
|
78
|
+
await runner.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`history:${machine}`]);
|
|
79
|
+
const stored = await loadPhases(runner, machine);
|
|
80
|
+
const folded = pinLive(await foldRows(stored));
|
|
81
|
+
const kept = new Set(folded.map(startOf));
|
|
82
|
+
await dropStarts(runner, machine, stored.filter((row) => {
|
|
83
|
+
return !kept.has(startOf(row));
|
|
84
|
+
}));
|
|
85
|
+
await folded.reduce(async (prior, row) => {
|
|
86
|
+
await prior;
|
|
87
|
+
return putPhase(runner, row);
|
|
88
|
+
}, Promise.resolve());
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function foldOwned(pool, machine) {
|
|
92
|
+
if (typeof pool.connect !== 'function') {
|
|
93
|
+
await foldMachine(pool, machine);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const client = await pool.connect();
|
|
97
|
+
try {
|
|
98
|
+
await client.query('BEGIN');
|
|
99
|
+
await foldMachine(client, machine);
|
|
100
|
+
await client.query('COMMIT');
|
|
101
|
+
} catch (error) {
|
|
102
|
+
await client.query('ROLLBACK');
|
|
103
|
+
throw error;
|
|
104
|
+
} finally {
|
|
105
|
+
client.release();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function foldOwnedRetry(pool, machine, attempt) {
|
|
110
|
+
try {
|
|
111
|
+
await foldOwned(pool, machine);
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (error?.code !== '40P01' || attempt >= 7) {
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
await new Promise((resolve) => {
|
|
117
|
+
setTimeout(resolve, 40 * (attempt + 1));
|
|
118
|
+
});
|
|
119
|
+
await foldOwnedRetry(pool, machine, attempt + 1);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Folds overlapping phases on casting machines into a unique timeline.
|
|
125
|
+
*
|
|
126
|
+
* @param {object} pool - pg pool
|
|
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) => {
|
|
139
|
+
await prior;
|
|
140
|
+
try {
|
|
141
|
+
await foldOwnedRetry(pool, row.machine, 0);
|
|
142
|
+
process.stderr.write(`[supervisor-sink] folded casting phases for ${row.machine}\n`);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
processingErrorLog('fold_casting_phases', error, { machine: row.machine });
|
|
145
|
+
}
|
|
146
|
+
}, Promise.resolve());
|
|
147
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import historyFold from '../../../domain/segment/historyFold.js';
|
|
2
|
+
import historyAbsorb from '../../persistence/pg/historyAbsorb.js';
|
|
3
|
+
|
|
4
|
+
function uniqueStarts(records) {
|
|
5
|
+
const kept = new Map();
|
|
6
|
+
for (const row of records) {
|
|
7
|
+
const key = `${row.machine}\0${row.kind || 'phase'}\0${new Date(row.start_time).toISOString()}`;
|
|
8
|
+
const prev = kept.get(key);
|
|
9
|
+
if (!prev || Date.parse(row.end_time) >= Date.parse(prev.end_time)) {
|
|
10
|
+
kept.set(key, row);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
return [...kept.values()];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function foldMachine(runner, machine, batch) {
|
|
17
|
+
await runner.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`history:${machine}`]);
|
|
18
|
+
return historyAbsorb(runner, machine, uniqueStarts(historyFold([], batch)));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function grouped(records) {
|
|
22
|
+
const groups = new Map();
|
|
23
|
+
for (const record of records) {
|
|
24
|
+
const batch = groups.get(record.machine) ?? [];
|
|
25
|
+
batch.push(record);
|
|
26
|
+
groups.set(record.machine, batch);
|
|
27
|
+
}
|
|
28
|
+
return groups;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function foldAll(runner, groups) {
|
|
32
|
+
return [...groups].reduce(async (prior, [machine, batch]) => {
|
|
33
|
+
const acc = await prior;
|
|
34
|
+
acc.push(...await foldMachine(runner, machine, batch));
|
|
35
|
+
return acc;
|
|
36
|
+
}, Promise.resolve([]));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function stamped(records) {
|
|
40
|
+
const now = new Date().toISOString();
|
|
41
|
+
return records.map((row) => {
|
|
42
|
+
return { ...row, updated_at: row.updated_at ?? now };
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function writeOwned(pool, inner, records) {
|
|
47
|
+
if (typeof pool.connect !== 'function') {
|
|
48
|
+
const next = stamped(uniqueStarts(await foldAll(pool, grouped(records))));
|
|
49
|
+
return inner.write(next, pool);
|
|
50
|
+
}
|
|
51
|
+
const client = await pool.connect();
|
|
52
|
+
try {
|
|
53
|
+
await client.query('BEGIN');
|
|
54
|
+
const next = stamped(uniqueStarts(await foldAll(client, grouped(records))));
|
|
55
|
+
const result = await inner.write(next, client);
|
|
56
|
+
await client.query('COMMIT');
|
|
57
|
+
return result;
|
|
58
|
+
} catch (error) {
|
|
59
|
+
await client.query('ROLLBACK');
|
|
60
|
+
throw error;
|
|
61
|
+
} finally {
|
|
62
|
+
client.release();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Folds overlapping phases into stored rows before the inner postgres write.
|
|
68
|
+
*
|
|
69
|
+
* @param {object} inner - postgres segment sink
|
|
70
|
+
* @param {object} pool - pg pool used when no transaction client is passed
|
|
71
|
+
* @returns {object} sink with write(records, client)
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* const sink = foldingSegments(segmentSink, pool);
|
|
75
|
+
* await sink.write([record], client);
|
|
76
|
+
*/
|
|
77
|
+
export default function foldingSegments(inner, pool) {
|
|
78
|
+
return {
|
|
79
|
+
async write(records, client) {
|
|
80
|
+
if (client && typeof client.query === 'function') {
|
|
81
|
+
return inner.write(stamped(uniqueStarts(await foldAll(client, grouped(records)))), client);
|
|
82
|
+
}
|
|
83
|
+
return writeOwned(pool, inner, records);
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
}
|
|
@@ -17,6 +17,7 @@ async function prepare(pool, state, token) {
|
|
|
17
17
|
token.client.on?.('error', token.onError);
|
|
18
18
|
await token.runner.query('BEGIN');
|
|
19
19
|
await token.runner.query("SELECT set_config('statement_timeout', $1, true)", [String(state.timeoutMs)]);
|
|
20
|
+
if (token.cancelled || state.stopped) { throw state.failure ?? new Error('Segment transaction stopped'); }
|
|
20
21
|
}
|
|
21
22
|
async function rollback(token) {
|
|
22
23
|
if (!token.client || token.cancelled) { return false; }
|
|
@@ -27,21 +28,25 @@ async function rollback(token) {
|
|
|
27
28
|
}
|
|
28
29
|
}
|
|
29
30
|
async function apply(dispatch, records, token) {
|
|
31
|
+
token.writing = true;
|
|
32
|
+
if (typeof dispatch.acceptMany === 'function') {
|
|
33
|
+
await dispatch.acceptMany(records, token.runner);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
30
36
|
for (const record of records) {
|
|
31
37
|
// eslint-disable-next-line no-await-in-loop
|
|
32
38
|
await dispatch.accept(record, token.runner);
|
|
33
39
|
}
|
|
34
40
|
}
|
|
35
41
|
async function execute(pool, dispatch, records, state, token) {
|
|
36
|
-
let phase = 'prepare';
|
|
37
42
|
try {
|
|
38
43
|
await prepare(pool, state, token);
|
|
39
|
-
|
|
40
|
-
|
|
44
|
+
await apply(dispatch, records, token);
|
|
45
|
+
await token.runner.query('COMMIT');
|
|
41
46
|
return { sqlCalls: token.calls };
|
|
42
47
|
} catch (error) {
|
|
43
48
|
const confirmed = await rollback(token);
|
|
44
|
-
if (confirmed &&
|
|
49
|
+
if (confirmed && token.writing && permanent(error)) { error.permanent = true; }
|
|
45
50
|
else if (!state.stopped && !token.cancelled) { state.fail(error); }
|
|
46
51
|
throw error;
|
|
47
52
|
} finally {
|
|
@@ -65,7 +70,8 @@ export default function segmentTransaction(pool, dispatch, { timeoutMs = 10000,
|
|
|
65
70
|
state.active.add(token);
|
|
66
71
|
return deadline(execute(pool, dispatch, records, state, token), timeoutMs, 'Segment transaction', error => {
|
|
67
72
|
token.cancelled = true;
|
|
68
|
-
try { release(token, true); }
|
|
73
|
+
try { release(token, true); }
|
|
74
|
+
finally { if (token.writing) { state.fail(error); } }
|
|
69
75
|
});
|
|
70
76
|
},
|
|
71
77
|
abort(error = new Error('Segment transaction stopped')) {
|
|
@@ -28,14 +28,23 @@ export default function userDecisionSink(pool) {
|
|
|
28
28
|
* @param {object} record - machine, startTime, username, operatorId, decidedAt, payload
|
|
29
29
|
*/
|
|
30
30
|
async accept({ machine, startTime, username, operatorId, decidedAt, payload }) {
|
|
31
|
+
const context = { machine, startTime, username, operatorId, decidedAt, payload };
|
|
31
32
|
try {
|
|
32
33
|
await applyDecision(pool, machine, startTime, payload);
|
|
34
|
+
} catch (error) {
|
|
35
|
+
if (!(error instanceof RangeError)) {
|
|
36
|
+
processingErrorLog('decision_sink_insert', error, context);
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
processingErrorLog('decision_sink_refused', error, context);
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
33
42
|
await pool.query(
|
|
34
43
|
'INSERT INTO user_decisions (machine, start_time, username, operator_id, decided_at, payload) VALUES ($1, $2, $3, $4, $5, $6)',
|
|
35
44
|
[machine, startTime, username, operatorId ?? null, decidedAt, payload]
|
|
36
45
|
);
|
|
37
46
|
} catch (error) {
|
|
38
|
-
processingErrorLog('decision_sink_insert', error,
|
|
47
|
+
processingErrorLog('decision_sink_insert', error, context);
|
|
39
48
|
throw error;
|
|
40
49
|
}
|
|
41
50
|
}
|
|
@@ -44,13 +44,17 @@ function segmentRow(parsed, startTime, endTime) {
|
|
|
44
44
|
|
|
45
45
|
function emitPiece(bus, piece) {
|
|
46
46
|
const times = timestamps(piece);
|
|
47
|
-
|
|
47
|
+
const event = { type: 'created', segment: segmentRow(piece, times.startTime, times.endTime) };
|
|
48
|
+
if (piece.type === 'retag') {
|
|
49
|
+
event.retag = true;
|
|
50
|
+
}
|
|
51
|
+
bus.emit(event);
|
|
48
52
|
}
|
|
49
53
|
|
|
50
54
|
function consume(raw, buses) {
|
|
51
55
|
const parsed = JSON.parse(raw.payload);
|
|
52
56
|
const bus = buses[parsed.machine];
|
|
53
|
-
if (!bus) {
|
|
57
|
+
if (!bus || parsed.type === 'phase-transition') {
|
|
54
58
|
return;
|
|
55
59
|
}
|
|
56
60
|
if (parsed.type === 'split-family' && Array.isArray(parsed.pieces)) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import nativeHistoryBounds, {nativeTailProtocol} from './historyNativeBounds.js';
|
|
2
|
-
import historyAbsorb from './historyAbsorb.js';
|
|
2
|
+
import historyAbsorb, {historyDedupe, span} from './historyAbsorb.js';
|
|
3
3
|
import historyFence from './historyFence.js';
|
|
4
4
|
import retainMetricReceipts from '../../ingest/db/retainMetricReceipts.js';
|
|
5
5
|
import historyContext from './historyContext.js';
|
|
@@ -111,6 +111,7 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
|
|
|
111
111
|
}
|
|
112
112
|
if(base?.replace){
|
|
113
113
|
const next=await historyCorrection(client,machine,work.rows[0],segments,{base,context:latest,timeScale});
|
|
114
|
+
if (segments.length) { await historyDedupe(client, machine, span(segments)); }
|
|
114
115
|
await advance(client,machine,workId,next);
|
|
115
116
|
return {applied:true};
|
|
116
117
|
}
|
|
@@ -118,8 +119,10 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
|
|
|
118
119
|
SELECT machine,kind,start_time,name,end_time,duration,tags,properties,resolved FROM segments
|
|
119
120
|
WHERE machine=$1 AND start_time<=$3 AND end_time>=$2
|
|
120
121
|
ON CONFLICT(machine,kind,start_time,name) DO UPDATE SET end_time=greatest(history_annotations.end_time,EXCLUDED.end_time),duration=EXCLUDED.duration,tags=EXCLUDED.tags,properties=EXCLUDED.properties,resolved=EXCLUDED.resolved`, [machine,new Date((latest?.context.page.from ?? base.from)/timeScale),new Date((latest?.context.page.until ?? base.until)/timeScale)]);
|
|
121
|
-
|
|
122
|
-
|
|
122
|
+
// A CAS-validated native page supplies its own phase boundaries and exterior.
|
|
123
|
+
const nativePage = base?.nativeTailMode === nativeTailProtocol;
|
|
124
|
+
const folded = nativePage ? segments : await historyAbsorb(client, machine, segments);
|
|
125
|
+
for (const item of folded) {
|
|
123
126
|
// Only computed fields change. User cuts/labels must be applied by caller before commit.
|
|
124
127
|
// eslint-disable-next-line no-await-in-loop
|
|
125
128
|
await client.query(`INSERT INTO segments(machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed)
|
|
@@ -133,6 +136,7 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
|
|
|
133
136
|
typeof item.tags === 'string' ? item.tags : JSON.stringify(item.tags ?? null),
|
|
134
137
|
typeof item.properties === 'string' ? item.properties : JSON.stringify(item.properties ?? null), item.resolved ?? true, item.consumed ?? true]);
|
|
135
138
|
}
|
|
139
|
+
if (!nativePage && segments.length) { await historyDedupe(client, machine, span(segments)); }
|
|
136
140
|
const converged=await saveCheckpoint(client,machine,base?.checkpoint,latest);
|
|
137
141
|
await advance(client,machine,workId,converged ? {next:null} : latest?.context.page);
|
|
138
142
|
return { applied: true };
|