@yarkivaev/scada 2.6.28 → 2.6.38
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/package.json +1 -1
- package/src/application/gateTimelineBuses.js +79 -0
- 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/sync/siteSyncTargets.js +3 -2
- package/src/domain/segment/dispatch.js +97 -8
- package/src/domain/segment/historyFold.js +227 -0
- package/src/infrastructure/ingest/pipelines/segmentBatch.js +25 -7
- package/src/infrastructure/ingest/pipelines/segmentPipeline.js +25 -10
- package/src/infrastructure/ingest/sinks/continuedSegments.js +31 -6
- package/src/infrastructure/ingest/sinks/foldCastingPhases.js +145 -0
- package/src/infrastructure/ingest/sinks/foldingSegments.js +86 -0
- package/src/infrastructure/ingest/sinks/segmentTransaction.js +6 -2
- package/src/infrastructure/ingest/sinks/userDecisionSink.js +10 -1
- package/src/infrastructure/persistence/pg/history.js +5 -3
- package/src/infrastructure/persistence/pg/historyAbsorb.js +111 -13
package/README.md
CHANGED
|
@@ -747,7 +747,7 @@ Use `node --expose-gc scripts/measure-delivery-spool.mjs FIXTURE.json 120000` wi
|
|
|
747
747
|
|
|
748
748
|
`deliverySpool.mutateMany(operations)` adds ordered append/receipt mutations to one WAL/FULL outer transaction. Entries are `{kind:'append', event, recipients}` or `{kind:'ack', eventId, recipient}`. The returned array contains `{ok:true}` or `{ok:false,error}` for each entry, and becomes available only after COMMIT. Validation, identity and capacity errors roll back that entry's savepoint; SQLite or COMMIT errors reject the entire call and fail the spool closed. Existing `append()` and `ack()` still perform immediate durable single-operation calls. Format version1 and legacy recovery are unchanged.
|
|
749
749
|
|
|
750
|
-
`deliveryQueue()` accumulates frozen operations before its database serialization barrier. Defaults are `groupCommit: {maxRecords:64, maxBytes:1048576, maxDelayMs:25}`, `maxOperations:128` and `maxPendingBytes:4194304`. Limits must be positive safe integers; the delay may be zero and cannot exceed the platform timer range. Every submitted operation must fit both byte limits. Increase these explicit options within the process memory budget for larger generic envelopes.
|
|
750
|
+
`deliveryQueue()` accumulates frozen operations before its database serialization barrier. Defaults are `groupCommit: {maxRecords:64, maxBytes:1048576, maxDelayMs:25}`, `maxOperations:128` and `maxPendingBytes:4194304`. Limits must be positive safe integers; the delay may be zero and cannot exceed the platform timer range. Every submitted operation must fit both byte limits. Increase these explicit options within the process memory budget for larger generic envelopes. A full operation window waits for a released slot before snapshot construction; oversized serialized inputs are still rejected before decoding their queue snapshot. Count and bytes remain reserved through the actual grouped operation, including an in-flight commit, even if an upstream caller stops waiting.
|
|
751
751
|
|
|
752
752
|
No observation is merged, sampled or discarded by batching. An `accept()` promise succeeds only after durable commit. A sparse group flushes on its timer; capacity thresholds, reads and close force earlier flushing. The delay bounds the coalescing window, not disk latency or end-to-end completion. Queue status retains durable `pending`/`bytes` and adds `queuedOperations`, `queuedBytes` and `drainFull` diagnostics.
|
|
753
753
|
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
CREATE TEMP TABLE fold_islands AS
|
|
2
|
+
WITH src AS (
|
|
3
|
+
SELECT ctid, machine, kind, name, start_time, end_time, duration, tags,
|
|
4
|
+
max(end_time) OVER (
|
|
5
|
+
PARTITION BY machine, kind, name, coalesce(tags, '')
|
|
6
|
+
ORDER BY start_time, end_time
|
|
7
|
+
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
|
|
8
|
+
) AS prev_max
|
|
9
|
+
FROM segments
|
|
10
|
+
WHERE kind = 'phase'
|
|
11
|
+
AND coalesce(properties, '') NOT LIKE '%"split_of"%'
|
|
12
|
+
),
|
|
13
|
+
flagged AS (
|
|
14
|
+
SELECT *,
|
|
15
|
+
sum(CASE WHEN prev_max IS NULL OR start_time >= prev_max THEN 1 ELSE 0 END)
|
|
16
|
+
OVER (PARTITION BY machine, kind, name, coalesce(tags, '')
|
|
17
|
+
ORDER BY start_time, end_time) AS island
|
|
18
|
+
FROM src
|
|
19
|
+
),
|
|
20
|
+
bounds AS (
|
|
21
|
+
SELECT machine, kind, name, coalesce(tags, '') AS tags, island,
|
|
22
|
+
max(end_time) AS keep_end,
|
|
23
|
+
(array_agg(ctid ORDER BY start_time, end_time))[1] AS keep_ctid
|
|
24
|
+
FROM flagged
|
|
25
|
+
GROUP BY 1, 2, 3, 4, 5
|
|
26
|
+
)
|
|
27
|
+
SELECT flagged.ctid AS row_ctid, bounds.keep_ctid, bounds.keep_end
|
|
28
|
+
FROM flagged
|
|
29
|
+
JOIN bounds
|
|
30
|
+
ON flagged.machine = bounds.machine
|
|
31
|
+
AND flagged.kind = bounds.kind
|
|
32
|
+
AND flagged.name = bounds.name
|
|
33
|
+
AND coalesce(flagged.tags, '') = bounds.tags
|
|
34
|
+
AND flagged.island = bounds.island;
|
|
35
|
+
|
|
36
|
+
UPDATE segments
|
|
37
|
+
SET end_time = fold_islands.keep_end,
|
|
38
|
+
duration = CASE WHEN segments.duration = 0 THEN 0
|
|
39
|
+
ELSE extract(epoch FROM fold_islands.keep_end - segments.start_time) END,
|
|
40
|
+
updated_at = clock_timestamp()
|
|
41
|
+
FROM fold_islands
|
|
42
|
+
WHERE segments.ctid = fold_islands.keep_ctid
|
|
43
|
+
AND segments.end_time IS DISTINCT FROM fold_islands.keep_end;
|
|
44
|
+
|
|
45
|
+
DELETE FROM segments
|
|
46
|
+
WHERE ctid IN (
|
|
47
|
+
SELECT row_ctid FROM fold_islands WHERE row_ctid <> keep_ctid
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
DROP TABLE fold_islands;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
CREATE OR REPLACE FUNCTION skip_covered_unsplit_phase() RETURNS trigger
|
|
2
|
+
LANGUAGE plpgsql AS $$
|
|
3
|
+
BEGIN
|
|
4
|
+
IF NEW.kind IS DISTINCT FROM 'phase' THEN
|
|
5
|
+
RETURN NEW;
|
|
6
|
+
END IF;
|
|
7
|
+
IF coalesce(NEW.properties, '') LIKE '%"split_of"%' THEN
|
|
8
|
+
RETURN NEW;
|
|
9
|
+
END IF;
|
|
10
|
+
UPDATE segments AS host
|
|
11
|
+
SET end_time = GREATEST(host.end_time, NEW.end_time),
|
|
12
|
+
duration = CASE WHEN host.duration = 0 THEN 0
|
|
13
|
+
ELSE extract(epoch FROM GREATEST(host.end_time, NEW.end_time) - host.start_time) END,
|
|
14
|
+
updated_at = clock_timestamp()
|
|
15
|
+
WHERE host.machine = NEW.machine AND host.kind = 'phase'
|
|
16
|
+
AND host.name = NEW.name
|
|
17
|
+
AND coalesce(host.tags, '') = coalesce(NEW.tags, '')
|
|
18
|
+
AND coalesce(host.properties, '') NOT LIKE '%"split_of"%'
|
|
19
|
+
AND NEW.start_time > host.start_time
|
|
20
|
+
AND NEW.start_time < host.end_time;
|
|
21
|
+
IF FOUND THEN
|
|
22
|
+
RETURN NULL;
|
|
23
|
+
END IF;
|
|
24
|
+
RETURN NEW;
|
|
25
|
+
END;
|
|
26
|
+
$$;
|
|
27
|
+
|
|
28
|
+
DROP TRIGGER IF EXISTS skip_covered_unsplit_phase ON segments;
|
|
29
|
+
CREATE TRIGGER skip_covered_unsplit_phase
|
|
30
|
+
BEFORE INSERT ON segments
|
|
31
|
+
FOR EACH ROW
|
|
32
|
+
EXECUTE PROCEDURE skip_covered_unsplit_phase();
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
DROP TRIGGER IF EXISTS skip_covered_unsplit_phase ON segments;
|
|
2
|
+
DROP TRIGGER IF EXISTS keep_unsplit_phase_span ON segments;
|
|
3
|
+
DROP TRIGGER IF EXISTS keep_repaired_phase_row ON segments;
|
|
4
|
+
DROP FUNCTION IF EXISTS skip_covered_unsplit_phase();
|
|
5
|
+
DROP FUNCTION IF EXISTS keep_unsplit_phase_span();
|
|
6
|
+
DROP FUNCTION IF EXISTS keep_repaired_phase_row();
|
package/package.json
CHANGED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import historyFold from '../domain/segment/historyFold.js';
|
|
2
|
+
|
|
3
|
+
function instant(value) {
|
|
4
|
+
return new Date(value).getTime();
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function own(folded, seg) {
|
|
8
|
+
const start = instant(seg.start_time);
|
|
9
|
+
const end = instant(seg.end_time);
|
|
10
|
+
return folded.some((row) => {
|
|
11
|
+
return instant(row.start_time) === start && instant(row.end_time) === end;
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function staleOpen(seg, stored) {
|
|
16
|
+
return Number(seg.duration) === 0 && stored.some((row) => {
|
|
17
|
+
return instant(row.start_time) > instant(seg.start_time);
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function overlapSql() {
|
|
22
|
+
return `SELECT kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed
|
|
23
|
+
FROM segments WHERE machine=$1 AND kind='phase'
|
|
24
|
+
AND ((start_time<$3 AND end_time>$2) OR ($4 = 0 AND start_time>$2))`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function covered(pool, machine, seg) {
|
|
28
|
+
const start = seg.start_time;
|
|
29
|
+
const finish = seg.end_time || seg.start_time;
|
|
30
|
+
return pool.query(overlapSql(), [machine, start, finish, Number(seg.duration)]).then((result) => {
|
|
31
|
+
const stored = result.rows;
|
|
32
|
+
if (staleOpen(seg, stored)) {
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
return !own(historyFold(stored, [seg]), seg);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function gatedBus(bus, pool, machine) {
|
|
40
|
+
return {
|
|
41
|
+
emit(event) {
|
|
42
|
+
const seg = event && event.segment;
|
|
43
|
+
if (!seg) {
|
|
44
|
+
bus.emit(event);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
covered(pool, machine, seg).then((skip) => {
|
|
48
|
+
if (!skip) {
|
|
49
|
+
bus.emit(event);
|
|
50
|
+
}
|
|
51
|
+
}).catch(() => {
|
|
52
|
+
return undefined;
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Drops STOMP timeline events whose start would not survive historyFold.
|
|
60
|
+
*
|
|
61
|
+
* Covered starts, stale duration-0 covers, and empty spans that fold
|
|
62
|
+
* clips away never reach HMI or monitoring SSE. SELECT errors stay closed.
|
|
63
|
+
*
|
|
64
|
+
* @param {object} buses - machine id to timeline bus
|
|
65
|
+
* @param {object} pool - postgres pool with query()
|
|
66
|
+
* @returns {object} buses that skip unpersisted segment events
|
|
67
|
+
* @example
|
|
68
|
+
* stompTimelineSegments(source, gateTimelineBuses(buses, pool));
|
|
69
|
+
*/
|
|
70
|
+
export default function gateTimelineBuses(buses, pool) {
|
|
71
|
+
if (!pool) {
|
|
72
|
+
return buses;
|
|
73
|
+
}
|
|
74
|
+
const gated = {};
|
|
75
|
+
for (const [id, bus] of Object.entries(buses)) {
|
|
76
|
+
gated[id] = gatedBus(bus, pool, id);
|
|
77
|
+
}
|
|
78
|
+
return gated;
|
|
79
|
+
}
|
|
@@ -9,6 +9,7 @@ import userDecisions from '../infrastructure/messaging/stomp/userDecisions.js';
|
|
|
9
9
|
import segmentRetags from '../infrastructure/messaging/stomp/segmentRetags.js';
|
|
10
10
|
import { parseRequestTimeoutMs, virtualClock } from '@yarkivaev/simple-server';
|
|
11
11
|
import inspectUpgrade from '../infrastructure/http/plant/inspect/inspectUpgrade.js';
|
|
12
|
+
import gateTimelineBuses from './gateTimelineBuses.js';
|
|
12
13
|
|
|
13
14
|
function stompCollectorFactory(stompUrl, destination, credentials) {
|
|
14
15
|
return (collector) => {
|
|
@@ -49,7 +50,7 @@ function wireTimelineSegments(stomp, plant) {
|
|
|
49
50
|
const credentials = { login: stomp.login, passcode: stomp.passcode, host: stomp.host };
|
|
50
51
|
return stompTimelineSegments(
|
|
51
52
|
stompCollectorFactory(stomp.url, timelineSegmentDestination, credentials),
|
|
52
|
-
buses
|
|
53
|
+
gateTimelineBuses(buses, postgresPool({}))
|
|
53
54
|
);
|
|
54
55
|
}
|
|
55
56
|
|
|
@@ -13,19 +13,25 @@ function settings(options) {
|
|
|
13
13
|
return config;
|
|
14
14
|
}
|
|
15
15
|
/** Bounded FIFO admission precedes serialization; every reservation includes actual in-flight writes. */
|
|
16
|
-
/* eslint max-lines-per-function: ["error",
|
|
16
|
+
/* eslint max-lines-per-function: ["error", 145], max-statements: ["error", 22] */
|
|
17
17
|
export default function deliveryOperations(apply, options = {}) {
|
|
18
18
|
const config = settings(options);
|
|
19
19
|
const jobs = [];
|
|
20
|
+
const waiters = [];
|
|
20
21
|
const state = { operations: 0, bytes: 0, running: false, timer: null, idle: null, wake: null };
|
|
21
|
-
function
|
|
22
|
-
if (state.operations
|
|
22
|
+
function notifyWait() {
|
|
23
|
+
if (waiters.length && state.operations < config.maxOperations) { state.operations += 1; waiters.shift()(); }
|
|
24
|
+
}
|
|
25
|
+
function occupy() {
|
|
26
|
+
if (state.operations >= config.maxOperations) { return false; }
|
|
23
27
|
state.operations += 1;
|
|
28
|
+
return true;
|
|
24
29
|
}
|
|
30
|
+
function wait() { return new Promise((resolve) => { waiters.push(resolve); }); }
|
|
25
31
|
function notifyIdle() {
|
|
26
|
-
if (!state.operations && !state.running) { state.wake?.(); Object.assign(state, { idle: null, wake: null }); }
|
|
32
|
+
if (!state.operations && !state.running && !waiters.length) { state.wake?.(); Object.assign(state, { idle: null, wake: null }); }
|
|
27
33
|
}
|
|
28
|
-
function release(bytes) { state.operations -= 1; state.bytes -= bytes; notifyIdle(); }
|
|
34
|
+
function release(bytes) { state.operations -= 1; state.bytes -= bytes; notifyWait(); notifyIdle(); }
|
|
29
35
|
function settle(job, result) {
|
|
30
36
|
release(job.reservedBytes ?? job.bytes);
|
|
31
37
|
if (result.ok) { job.resolve(result.value); } else { job.reject(result.error); }
|
|
@@ -83,8 +89,7 @@ export default function deliveryOperations(apply, options = {}) {
|
|
|
83
89
|
if (state.bytes + bytes + retainedBytes > config.maxPendingBytes) { throw new Error('Delivery pending byte capacity exceeded'); }
|
|
84
90
|
if (bytes > config.maxBytes) { throw new Error('Delivery group byte capacity exceeded'); }
|
|
85
91
|
}
|
|
86
|
-
function
|
|
87
|
-
reserve();
|
|
92
|
+
function hold(build) {
|
|
88
93
|
let value;
|
|
89
94
|
try {
|
|
90
95
|
value = build(checkBytes); checkBytes(value.bytes, value.retainedBytes);
|
|
@@ -100,14 +105,23 @@ export default function deliveryOperations(apply, options = {}) {
|
|
|
100
105
|
cancel() { if (!settled) { settled = true; release(reservedBytes); } }
|
|
101
106
|
};
|
|
102
107
|
}
|
|
108
|
+
function prepare(build) {
|
|
109
|
+
if (occupy()) {
|
|
110
|
+
try { return hold(build); } catch (error) { return Promise.reject(error); }
|
|
111
|
+
}
|
|
112
|
+
return wait().then(() => { return hold(build); });
|
|
113
|
+
}
|
|
103
114
|
return {
|
|
104
115
|
prepare,
|
|
105
116
|
mutate(build) {
|
|
106
|
-
|
|
117
|
+
if (occupy()) {
|
|
118
|
+
try { return hold(build).commit(); } catch (error) { return Promise.reject(error); }
|
|
119
|
+
}
|
|
120
|
+
return wait().then(() => { return hold(build).commit(); });
|
|
107
121
|
},
|
|
108
122
|
barrier(action) {
|
|
109
|
-
|
|
110
|
-
|
|
123
|
+
if (occupy()) { return enqueue({ kind: 'barrier', action, bytes: 0 }); }
|
|
124
|
+
return wait().then(() => { return enqueue({ kind: 'barrier', action, bytes: 0 }); });
|
|
111
125
|
},
|
|
112
126
|
flush() { if (jobs.length) { schedule(0); } },
|
|
113
127
|
idle() {
|
|
@@ -7,25 +7,30 @@ export default function deliveryPublications(commands, sessions, options) {
|
|
|
7
7
|
function publish(record, id) {
|
|
8
8
|
const key = JSON.stringify([record.event.eventId, id]);
|
|
9
9
|
if (active.has(key) || active.size >= limit) { throw new Error('Delivery publication capacity exceeded'); }
|
|
10
|
-
const
|
|
10
|
+
const settled = Promise.resolve(commands.prepare((checkBytes) => {
|
|
11
11
|
const operation = { kind: 'ack', eventId: record.event.eventId, recipient: id };
|
|
12
12
|
const bytes = Buffer.byteLength(JSON.stringify(operation));
|
|
13
13
|
const retainedBytes = Buffer.byteLength(JSON.stringify(record.event));
|
|
14
14
|
checkBytes(bytes, retainedBytes); return { operation, bytes, retainedBytes };
|
|
15
|
+
})).then((receipt) => {
|
|
16
|
+
let write;
|
|
17
|
+
try {
|
|
18
|
+
const descriptor = record.event.destinations.find((item) => { return item.id === id; });
|
|
19
|
+
const event = record.event.observation;
|
|
20
|
+
write = sessions.write(descriptor, { ...event, options: { ...event.options, persistent: true, mandatory: true, messageId: event.eventId } });
|
|
21
|
+
} catch (error) { receipt.cancel(); throw error; }
|
|
22
|
+
const receiptLife = write.settled.then(() => { return receipt.commit(); }, (error) => { receipt.cancel(); throw error; })
|
|
23
|
+
.finally(() => { active.delete(key); });
|
|
24
|
+
void receiptLife.catch(() => {
|
|
25
|
+
// The caller reports failures; late rejection still releases only the actual reservation.
|
|
26
|
+
});
|
|
27
|
+
return write.result.then(() => { return receiptLife; });
|
|
15
28
|
});
|
|
16
|
-
let write;
|
|
17
|
-
try {
|
|
18
|
-
const descriptor = record.event.destinations.find((item) => { return item.id === id; });
|
|
19
|
-
const event = record.event.observation;
|
|
20
|
-
write = sessions.write(descriptor, { ...event, options: { ...event.options, persistent: true, mandatory: true, messageId: event.eventId } });
|
|
21
|
-
} catch (error) { receipt.cancel(); throw error; }
|
|
22
|
-
const settled = write.settled.then(() => { return receipt.commit(); }, (error) => { receipt.cancel(); throw error; })
|
|
23
|
-
.finally(() => { active.delete(key); });
|
|
24
29
|
active.set(key, settled);
|
|
25
30
|
void settled.catch(() => {
|
|
26
|
-
//
|
|
31
|
+
// Prepare admission failures still release the publication slot.
|
|
27
32
|
});
|
|
28
|
-
return
|
|
33
|
+
return settled.finally(() => { active.delete(key); });
|
|
29
34
|
}
|
|
30
35
|
return { publish, limit };
|
|
31
36
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { postgresSink } from '../../infrastructure/streams/index.js';
|
|
2
|
+
import foldingSegments from '../../infrastructure/ingest/sinks/foldingSegments.js';
|
|
2
3
|
import {
|
|
3
4
|
alertRow,
|
|
4
5
|
listedItems,
|
|
@@ -22,11 +23,11 @@ import {
|
|
|
22
23
|
* siteSyncTargets({ operations, postgres, pool, alerts, metrics, topic });
|
|
23
24
|
*/
|
|
24
25
|
function segmentTarget(postgres, pool) {
|
|
25
|
-
const sink = postgresSink(postgres, 'segments', segmentColumns, {
|
|
26
|
+
const sink = foldingSegments(postgresSink(postgres, 'segments', segmentColumns, {
|
|
26
27
|
pool,
|
|
27
28
|
conflict: segmentConflict,
|
|
28
29
|
update: segmentUpdateColumns
|
|
29
|
-
});
|
|
30
|
+
}), pool);
|
|
30
31
|
return {
|
|
31
32
|
async write(machine, body) {
|
|
32
33
|
const rows = listedItems(body).map((item) => {
|
|
@@ -1,4 +1,54 @@
|
|
|
1
1
|
import { replaceSplit } from './splitFamily.js';
|
|
2
|
+
import historyFold from './historyFold.js';
|
|
3
|
+
import segmentContinue from './segmentContinue.js';
|
|
4
|
+
|
|
5
|
+
function pointed(record) {
|
|
6
|
+
if (record.duration !== 0) {
|
|
7
|
+
return record;
|
|
8
|
+
}
|
|
9
|
+
return { ...record, end_time: record.start_time };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function uniqueStarts(records) {
|
|
13
|
+
const kept = new Map();
|
|
14
|
+
for (const row of records) {
|
|
15
|
+
const key = `${row.machine}\0${row.kind || 'phase'}\0${new Date(row.start_time).toISOString()}`;
|
|
16
|
+
const prev = kept.get(key);
|
|
17
|
+
if (!prev || Date.parse(row.end_time) >= Date.parse(prev.end_time)) {
|
|
18
|
+
kept.set(key, row);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return [...kept.values()];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function grouped(records) {
|
|
25
|
+
const groups = new Map();
|
|
26
|
+
for (const record of records) {
|
|
27
|
+
const batch = groups.get(record.machine) ?? [];
|
|
28
|
+
batch.push(record);
|
|
29
|
+
groups.set(record.machine, batch);
|
|
30
|
+
}
|
|
31
|
+
return groups;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function continued(records) {
|
|
35
|
+
const apply = segmentContinue(30);
|
|
36
|
+
const seen = new Map();
|
|
37
|
+
return records.map((record) => {
|
|
38
|
+
const key = `${record.machine}\0${record.kind || 'phase'}`;
|
|
39
|
+
const row = apply(record, seen.get(key));
|
|
40
|
+
seen.set(key, row);
|
|
41
|
+
return row;
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function collapsed(records) {
|
|
46
|
+
const next = [];
|
|
47
|
+
for (const batch of grouped(continued(records)).values()) {
|
|
48
|
+
next.push(...uniqueStarts(historyFold([], batch)).map(pointed));
|
|
49
|
+
}
|
|
50
|
+
return next;
|
|
51
|
+
}
|
|
2
52
|
|
|
3
53
|
/**
|
|
4
54
|
* Persists a pending heartbeat, optionally inside one pool transaction.
|
|
@@ -10,21 +60,23 @@ import { replaceSplit } from './splitFamily.js';
|
|
|
10
60
|
* @returns {Promise<void>}
|
|
11
61
|
*/
|
|
12
62
|
async function pendingInClient(segmentSink, closer, record, transaction) {
|
|
13
|
-
|
|
14
|
-
await
|
|
63
|
+
const live = pointed(record);
|
|
64
|
+
await closer.close(live.machine, live.start_time, live.kind || 'phase', transaction, live.name);
|
|
65
|
+
await segmentSink.write([live], transaction);
|
|
15
66
|
}
|
|
16
67
|
async function persistPending(segmentSink, closer, pool, record) {
|
|
17
|
-
const
|
|
68
|
+
const live = pointed(record);
|
|
69
|
+
const kind = live.kind || 'phase';
|
|
18
70
|
if (!pool || typeof pool.connect !== 'function') {
|
|
19
|
-
await closer.close(
|
|
20
|
-
await segmentSink.write([
|
|
71
|
+
await closer.close(live.machine, live.start_time, kind, null, live.name);
|
|
72
|
+
await segmentSink.write([live]);
|
|
21
73
|
return;
|
|
22
74
|
}
|
|
23
75
|
const client = await pool.connect();
|
|
24
76
|
try {
|
|
25
77
|
await client.query('BEGIN');
|
|
26
|
-
await closer.close(
|
|
27
|
-
await segmentSink.write([
|
|
78
|
+
await closer.close(live.machine, live.start_time, kind, client, live.name);
|
|
79
|
+
await segmentSink.write([live], client);
|
|
28
80
|
await client.query('COMMIT');
|
|
29
81
|
} catch (error) {
|
|
30
82
|
await client.query('ROLLBACK').catch((ignored) => { return ignored; });
|
|
@@ -58,6 +110,29 @@ async function acceptFamily(pool, record, transaction) {
|
|
|
58
110
|
await replaceSplit(pool, record, transaction);
|
|
59
111
|
}
|
|
60
112
|
|
|
113
|
+
/** Closes orphan opens before a batched upsert. */
|
|
114
|
+
async function closePending(closer, records, transaction) {
|
|
115
|
+
for (const record of records) {
|
|
116
|
+
// eslint-disable-next-line no-await-in-loop
|
|
117
|
+
await closer.close(record.machine, record.start_time, record.kind || 'phase', transaction || null, record.name);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function writeCompleted(segmentSink, closer, record, transaction) {
|
|
122
|
+
await closer.close(record.machine, record.start_time, record.kind || 'phase', transaction || null, record.name);
|
|
123
|
+
await segmentSink.write([record], transaction);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Writes a consecutive run of phase records through one sink call. */
|
|
127
|
+
async function writeOwned(segmentSink, closer, records, transaction) {
|
|
128
|
+
if (!records.length) {
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
const folded = collapsed(records);
|
|
132
|
+
await closePending(closer, folded, transaction);
|
|
133
|
+
await segmentSink.write(folded, transaction);
|
|
134
|
+
}
|
|
135
|
+
|
|
61
136
|
export default function segmentDispatch(segmentSink, retag, splitSink, closer, pool) {
|
|
62
137
|
return {
|
|
63
138
|
async accept(record, transaction) {
|
|
@@ -77,10 +152,24 @@ export default function segmentDispatch(segmentSink, retag, splitSink, closer, p
|
|
|
77
152
|
throw new Error(`Segment command type ${record.type} is not defined`);
|
|
78
153
|
}
|
|
79
154
|
if (record.duration !== 0) {
|
|
80
|
-
await segmentSink
|
|
155
|
+
await writeCompleted(segmentSink, closer, record, transaction);
|
|
81
156
|
return;
|
|
82
157
|
}
|
|
83
158
|
await (transaction ? pendingInClient(segmentSink, closer, record, transaction) : persistPending(segmentSink, closer, pool, record));
|
|
159
|
+
},
|
|
160
|
+
async acceptMany(records, transaction) {
|
|
161
|
+
const phases = [];
|
|
162
|
+
for (const record of records) {
|
|
163
|
+
if (record.type === 'segment') {
|
|
164
|
+
phases.push(record);
|
|
165
|
+
} else {
|
|
166
|
+
// eslint-disable-next-line no-await-in-loop
|
|
167
|
+
await writeOwned(segmentSink, closer, phases.splice(0), transaction);
|
|
168
|
+
// eslint-disable-next-line no-await-in-loop
|
|
169
|
+
await this.accept(record, transaction);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
await writeOwned(segmentSink, closer, phases, transaction);
|
|
84
173
|
}
|
|
85
174
|
};
|
|
86
175
|
}
|