@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.
@@ -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
+ }
@@ -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 && !packet.ready && packet.bytes + bytes > state.policy.maxBytes) { ready(state, lane, packet, 'bytes'); }
68
- packet = lane.packets.at(-1);
69
- if (!packet || packet.ready) {
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
- const pending = packet;
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);
@@ -11,9 +11,11 @@ import segmentCodec from '../codecs/segmentCodec.js';
11
11
  import processingErrorLog from '../processingErrorLog.js';
12
12
  import silentOpenWatch from '../silentOpenWatch.js';
13
13
  import abutSegments from '../sinks/abutSegments.js';
14
+ import foldCastingPhases from '../sinks/foldCastingPhases.js';
14
15
  import closeOrphanOpen from '../sinks/closeOrphanOpen.js';
15
16
  import closeSilentOpen from '../sinks/closeSilentOpen.js';
16
17
  import continuedSegments from '../sinks/continuedSegments.js';
18
+ import foldingSegments from '../sinks/foldingSegments.js';
17
19
  import retagSink from '../sinks/retagSink.js';
18
20
 
19
21
  export const segmentColumns = ['machine', 'kind', 'name', 'start_time', 'end_time', 'duration',
@@ -21,7 +23,7 @@ export const segmentColumns = ['machine', 'kind', 'name', 'start_time', 'end_tim
21
23
  export const segmentConflict = ['machine', 'kind', 'start_time'];
22
24
  export const segmentUpdateColumns = ['name', 'end_time', 'duration', 'options', 'resolved', 'updated_at'];
23
25
  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"%\'))';
26
+ 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)';
25
27
  export const segmentsIngestDestination = '/queue/scada.segments.ingest';
26
28
 
27
29
  export { default as segmentDispatch } from '../../../domain/segment/dispatch.js';
@@ -36,10 +38,10 @@ export { default as segmentDispatch } from '../../../domain/segment/dispatch.js'
36
38
  function segmentSinks(postgres, pool) {
37
39
  const shared = { pool, conflict: segmentConflict, updateWhere: segmentUpdateWhere };
38
40
  return {
39
- segmentSink: postgresSink(postgres, 'segments', segmentColumns,
40
- { ...shared, update: segmentUpdateColumns }),
41
- splitSink: postgresSink(postgres, 'segments', segmentColumns,
42
- { ...shared, update: splitUpdateColumns })
41
+ segmentSink: foldingSegments(postgresSink(postgres, 'segments', segmentColumns,
42
+ { ...shared, update: segmentUpdateColumns }), pool),
43
+ splitSink: foldingSegments(postgresSink(postgres, 'segments', segmentColumns,
44
+ { ...shared, update: splitUpdateColumns }), pool)
43
45
  };
44
46
  }
45
47
 
@@ -51,6 +53,20 @@ function pipelineSettings(config) {
51
53
  return settings;
52
54
  }
53
55
 
56
+ async function repairHistory(pool, budget) {
57
+ try {
58
+ await abutSegments(pool, budget);
59
+ } catch (error) {
60
+ processingErrorLog('abut_segments', error, { budgetSeconds: budget });
61
+ }
62
+ }
63
+
64
+ function repairCasting(pool) {
65
+ foldCastingPhases(pool).catch((error) => {
66
+ processingErrorLog('fold_casting_phases', error, {});
67
+ });
68
+ }
69
+
54
70
  /**
55
71
  * Pipeline for streaming STOMP segment data to PostgreSQL segments table.
56
72
  * Subscribes to the durable ingest queue so shovel traffic survives consumer gaps.
@@ -98,14 +114,13 @@ export default function segmentPipeline(stomp, postgres, pool, config) {
98
114
  destination,
99
115
  async start() {
100
116
  if (settings.repairHistoryOnStart !== false) {
101
- try {
102
- await abutSegments(pool, budget);
103
- } catch (error) {
104
- processingErrorLog('abut_segments', error, { budgetSeconds: budget });
105
- }
117
+ await repairHistory(pool, budget);
106
118
  }
107
119
  await source.start();
108
120
  await silence.start();
121
+ if (settings.repairHistoryOnStart !== false) {
122
+ repairCasting(pool);
123
+ }
109
124
  },
110
125
  stop() {
111
126
  return stopSegmentPipeline(source, coalesce, silence, pool, settings.stopTimeoutMs ?? 5000);
@@ -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 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
  *
@@ -38,12 +58,17 @@ export default function continuedSegments(inner, pool, budgetSeconds) {
38
58
  async write(records, client) {
39
59
  const runner = client && typeof client.query === 'function' ? client : pool;
40
60
  const next = await records.reduce(async (prior, record) => {
41
- const rows = await prior;
42
- const previous = await latest(runner, record);
43
- rows.push(apply(record, previous));
44
- return rows;
45
- }, Promise.resolve([]));
46
- return inner.write(next, client);
61
+ const { rows, seen } = await prior;
62
+ const key = `${record.machine}\0${record.kind || 'phase'}`;
63
+ if (!seen.has(key)) {
64
+ seen.set(key, await latest(runner, record));
65
+ }
66
+ const row = placed(record, seen.get(key), apply);
67
+ seen.set(key, row);
68
+ rows.push(row);
69
+ return { rows, seen };
70
+ }, Promise.resolve({ rows: [], seen: new Map() }));
71
+ return inner.write(next.rows, client);
47
72
  }
48
73
  };
49
74
  }
@@ -0,0 +1,145 @@
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
+ * @returns {Promise<void>}
128
+ *
129
+ * @example
130
+ * await foldCastingPhases(pool);
131
+ */
132
+ export default async function foldCastingPhases(pool) {
133
+ const found = await pool.query(
134
+ `SELECT DISTINCT machine FROM segments WHERE machine LIKE 'cm%' AND kind='phase'`
135
+ );
136
+ await found.rows.reduce(async (prior, row) => {
137
+ await prior;
138
+ try {
139
+ await foldOwnedRetry(pool, row.machine, 0);
140
+ process.stderr.write(`[supervisor-sink] folded casting phases for ${row.machine}\n`);
141
+ } catch (error) {
142
+ processingErrorLog('fold_casting_phases', error, { machine: row.machine });
143
+ }
144
+ }, Promise.resolve());
145
+ }
@@ -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
+ }
@@ -27,6 +27,10 @@ async function rollback(token) {
27
27
  }
28
28
  }
29
29
  async function apply(dispatch, records, token) {
30
+ if (typeof dispatch.acceptMany === 'function') {
31
+ await dispatch.acceptMany(records, token.runner);
32
+ return;
33
+ }
30
34
  for (const record of records) {
31
35
  // eslint-disable-next-line no-await-in-loop
32
36
  await dispatch.accept(record, token.runner);
@@ -63,9 +67,9 @@ export default function segmentTransaction(pool, dispatch, { timeoutMs = 10000,
63
67
  const token = { client: null, released: false, cancelled: false, calls: 0 };
64
68
  token.runner = { query(...args) { token.calls += 1;return token.client.query(...args); } };
65
69
  state.active.add(token);
66
- return deadline(execute(pool, dispatch, records, state, token), timeoutMs, 'Segment transaction', error => {
70
+ return deadline(execute(pool, dispatch, records, state, token), timeoutMs, 'Segment transaction', () => {
67
71
  token.cancelled = true;
68
- try { release(token, true); } finally { state.fail(error); }
72
+ release(token, true);
69
73
  });
70
74
  },
71
75
  abort(error = new Error('Segment transaction stopped')) {