@yarkivaev/scada 2.11.0 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,52 @@
1
+ ALTER TABLE history_replica_outbox ADD COLUMN origin UUID;
2
+
3
+ CREATE TABLE timeline_replica_origin (
4
+ singleton BOOLEAN PRIMARY KEY CHECK (singleton),
5
+ id UUID NOT NULL DEFAULT gen_random_uuid()
6
+ );
7
+ INSERT INTO timeline_replica_origin(singleton) VALUES(true);
8
+
9
+ CREATE OR REPLACE FUNCTION history_capture_replica() RETURNS trigger LANGUAGE plpgsql AS $$
10
+ DECLARE setting TEXT; target JSONB; identity TEXT; persisted JSONB; key RECORD; source UUID; sequence BIGINT;
11
+ BEGIN
12
+ setting := current_setting('scada.history_replica', true);
13
+ IF setting IS NULL OR setting = '' THEN RETURN NULL; END IF;
14
+ target := setting::jsonb;
15
+ IF target->>'protocol' = 'transactional-history-outbox-v2' THEN
16
+ SELECT id INTO STRICT source FROM timeline_replica_origin WHERE singleton;
17
+ END IF;
18
+
19
+ FOR key IN
20
+ SELECT DISTINCT touched.machine, touched.kind, touched.start_time
21
+ FROM (VALUES (NEW.machine,NEW.kind,NEW.start_time), (OLD.machine,OLD.kind,OLD.start_time))
22
+ AS touched(machine,kind,start_time)
23
+ WHERE touched.machine=target->>'machine'
24
+ AND (source IS NOT NULL OR (TG_OP<>'DELETE' AND touched.kind=NEW.kind AND touched.start_time=NEW.start_time))
25
+ LOOP
26
+ SELECT to_jsonb(s) INTO persisted FROM segments s
27
+ WHERE s.machine=key.machine AND s.kind=key.kind AND s.start_time=key.start_time;
28
+ IF NOT FOUND THEN
29
+ IF source IS NULL THEN CONTINUE; END IF;
30
+ persisted := jsonb_build_object('kind',key.kind,'start_time',key.start_time);
31
+ END IF;
32
+ identity := 'history:' || encode(sha256(convert_to(jsonb_build_array(
33
+ target->>'outputId', key.kind, extract(epoch FROM key.start_time)
34
+ )::text, 'UTF8')), 'hex');
35
+ INSERT INTO history_replica_outbox(machine,exchange,routing_key,output_id,epoch,segment,origin)
36
+ VALUES(key.machine,target->>'exchange',target->>'routingKey',identity,(target->>'epoch')::bigint,persisted,source)
37
+ ON CONFLICT(machine,output_id) DO UPDATE SET segment=EXCLUDED.segment
38
+ RETURNING id INTO sequence;
39
+ IF source IS NOT NULL THEN
40
+ INSERT INTO timeline_replica_positions(machine,kind,start_time,origin,position)
41
+ VALUES(key.machine,key.kind,key.start_time,source,sequence)
42
+ ON CONFLICT(machine,kind,start_time,origin) DO UPDATE
43
+ SET position=greatest(timeline_replica_positions.position,EXCLUDED.position);
44
+ END IF;
45
+ END LOOP;
46
+ RETURN NULL;
47
+ END $$;
48
+
49
+ DROP TRIGGER history_capture_replica ON segments;
50
+ CREATE CONSTRAINT TRIGGER history_capture_replica
51
+ AFTER INSERT OR UPDATE OR DELETE ON segments DEFERRABLE INITIALLY DEFERRED
52
+ FOR EACH ROW EXECUTE FUNCTION history_capture_replica();
@@ -0,0 +1 @@
1
+ GRANT SELECT ON timeline_replica_origin TO supervisor_sink;
@@ -0,0 +1,8 @@
1
+ CREATE TABLE timeline_replica_positions (
2
+ machine TEXT NOT NULL,
3
+ kind TEXT NOT NULL,
4
+ start_time TIMESTAMPTZ NOT NULL,
5
+ origin UUID NOT NULL,
6
+ position BIGINT NOT NULL,
7
+ PRIMARY KEY (machine,kind,start_time,origin)
8
+ );
@@ -0,0 +1 @@
1
+ GRANT SELECT, INSERT, UPDATE ON timeline_replica_positions TO supervisor_sink;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.11.0",
3
+ "version": "2.12.0",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,4 +1,4 @@
1
- import deliverySpool from '../../infrastructure/persistence/runtime/deliverySpool.js';
1
+ import spoolProcess from '../../infrastructure/persistence/runtime/spoolProcess.js';
2
2
  import deliverySessions from './deliverySessions.js';
3
3
  import deliveryOperations from './deliveryOperations.js';
4
4
  import deliveryPublications from './deliveryPublications.js';
@@ -11,8 +11,7 @@ function snapshot(operation, checkBytes) {
11
11
  }
12
12
  /* eslint max-lines-per-function: ["error", 125], max-statements: ["error", 25] */
13
13
  /** Node-owned queue: every point/receipt resolves only after its grouped FULL commit. */
14
- export default function deliveryQueue(directory, options) {
15
- const spool = deliverySpool(directory, options);
14
+ export default function deliveryQueue(directory, options, spool = spoolProcess(directory, options)) {
16
15
  const commands = deliveryOperations((operations) => { return spool.mutateMany(operations); }, options);
17
16
  const sessions = deliverySessions(options.factory, options.writeTimeoutMs);
18
17
  const batchSize = options.batchSize ?? 100;
@@ -147,7 +147,8 @@ export default function supervisorSink(env = process.env, options = {}) {
147
147
  const replicaRelay = metricsEnabled && state.history && cfg.replicaBroker ? historyReplicaRelay(cfg.replicaBroker, pool) : undefined;
148
148
  const dataAccess = metricsEnabled ? {...state,...(replicaRelay && {history:replicaRelay.history(state.history)}),liveSegments:{
149
149
  revision(machine) { return segments().live.revision(machine); },
150
- apply(input) { return segments().live.apply(input); }
150
+ apply(input) { return segments().live.apply(input); },
151
+ ...(replicaRelay && {applyOutbox(input, replication) { return segments().live.applyOutbox(input, replication); }})
151
152
  }} : state;
152
153
  const localTelemetry = historyTelemetry(env, pool);
153
154
  return {
@@ -1,4 +1,5 @@
1
1
  import { errorResponse, jsonResponse, readBody, route } from '@yarkivaev/simple-server';
2
+ import { historyReplicaProtocol } from '../../../../persistence/pg/historyReplicaOutbox.js';
2
3
  import { hasAccess, sendForbidden } from '../../stateAccess.js';
3
4
 
4
5
  function endpoint(method, suffix, token, action) {
@@ -21,7 +22,11 @@ function endpoint(method, suffix, token, action) {
21
22
  export default function historyRoutes(token, history, liveSegments) {
22
23
  const live = liveSegments ? [
23
24
  endpoint('GET', 'live-revision', token, input => {return liveSegments.revision(input.machine)}),
24
- endpoint('POST', 'live-apply', token, input => {return liveSegments.apply(input)})
25
+ endpoint('POST', 'live-apply', token, input => {return liveSegments.apply(input)}),
26
+ ...(liveSegments.applyOutbox ? [endpoint('POST', 'live-apply-outbox', token, input => {
27
+ const {replication,...segment} = input;
28
+ return liveSegments.applyOutbox(segment,replication);
29
+ })] : [])
25
30
  ] : [];
26
31
  if (!history) { return live; }
27
32
  return [
@@ -37,8 +42,15 @@ export default function historyRoutes(token, history, liveSegments) {
37
42
  if (input.context?.replication !== undefined) { throw new TypeError('Use the history outbox endpoint'); }
38
43
  return history.commit(input.machine, input.workId, input.segments, input.context);
39
44
  }),
40
- ...(history.commitOutbox ? [endpoint('POST', 'commit-outbox', token, input => {
41
- return history.commitOutbox(input.machine, input.workId, input.segments, input.context, input.replication);
42
- })] : [])
45
+ ...(history.commitOutbox ? [
46
+ endpoint('POST', 'commit-outbox', token, input => {
47
+ return history.commitOutbox(input.machine, input.workId, input.segments, input.context,
48
+ {...input.replication,protocol:undefined});
49
+ }),
50
+ endpoint('POST', 'commit-outbox-v2', token, input => {
51
+ return history.commitOutbox(input.machine, input.workId, input.segments, input.context,
52
+ {...input.replication,protocol:historyReplicaProtocol});
53
+ })
54
+ ] : [])
43
55
  ];
44
56
  }
@@ -1,5 +1,6 @@
1
1
  import segmentNormalize from '../../../domain/segment/normalize.js';
2
2
  import { writeFence } from '../../persistence/pg/segmentWriteFence.js';
3
+ import { decodeTimelineChange } from '../../persistence/pg/timelineReplica.js';
3
4
  import processingErrorLog from '../processingErrorLog.js';
4
5
 
5
6
  /**
@@ -50,9 +51,18 @@ function persistedRecord(parsed) {
50
51
  return segmentNormalize(parsed);
51
52
  }
52
53
 
54
+ function timelineDelivery(body, committedOutputId, hasFence) {
55
+ if (hasFence) { throw new TypeError('A timeline change must be a replica delivery'); }
56
+ writeFence({outputId:committedOutputId});
57
+ return {...decodeTimelineChange(body),committedOutputId,body};
58
+ }
59
+
53
60
  export function decodeSegmentBody(parsed) {
54
61
  const {fence,committedOutputId,...body} = parsed;
55
62
  delete body.epoch;
63
+ if (Object.hasOwn(body,'timelineChange') || body.type === 'segment-delete') {
64
+ return timelineDelivery(body,committedOutputId,Object.hasOwn(parsed,'fence'));
65
+ }
56
66
  const record = persistedRecord(body);
57
67
  if (Object.hasOwn(parsed,'fence')) {
58
68
  writeFence(fence);
@@ -32,7 +32,8 @@ const privilegedOnly = new Set([
32
32
  'E0016__history_retention_grants.sql',
33
33
  'E0019__segment_write_fence.sql',
34
34
  'E0020__segment_write_fence_grants.sql',
35
- 'E0022__history_replica_outbox_grants.sql'
35
+ 'E0022__history_replica_outbox_grants.sql',
36
+ 'E0024__timeline_replica_origin_grants.sql'
36
37
  ]);
37
38
 
38
39
  /**
@@ -1,3 +1,5 @@
1
+ import applyTimelineReplica from '../../persistence/pg/timelineReplica.js';
2
+ import { enableHistoryReplicaCapture, historyReplicaProtocol } from '../../persistence/pg/historyReplicaOutbox.js';
1
3
  import { decodeSegmentBody } from '../codecs/segmentCodec.js';
2
4
  import writeFencedSegment, {
3
5
  activeSegmentLease, checkSegmentRevision, segmentLeaseMatches, segmentRevision, serialSegmentTransaction, storeWriteReceipt, writeReceipt
@@ -48,6 +50,12 @@ async function applyLive(dispatch, record, client, {phaseAnchors,computedPropert
48
50
  },Promise.resolve());
49
51
  }
50
52
 
53
+ async function applyReplicaChange(dispatch, record, client, settings) {
54
+ if (record.timelineChange) { return applyTimelineReplica(client,record.machine,record.timelineChange); }
55
+ await applyLive(dispatch, record, client, settings);
56
+ return true;
57
+ }
58
+
51
59
  async function applyReplica(dispatch, record, client, settings) {
52
60
  const receipt = await writeReceipt(client,record.machine,record.committedOutputId,record.body);
53
61
  if (receipt) { return receipt; }
@@ -58,9 +66,9 @@ async function applyReplica(dispatch, record, client, settings) {
58
66
  ? await segmentLeaseMatches(client,record.machine,undefined)
59
67
  : !await activeSegmentLease(client,record.machine);
60
68
  if (!eligible) { return {applied:false}; }
61
- await applyLive(dispatch, record, client, settings);
69
+ const applied = await applyReplicaChange(dispatch,record,client,settings);
62
70
  const revision = storage.local_revision ? await segmentRevision(client,record.machine) : {};
63
- const outcome = {applied:true,...revision};
71
+ const outcome = {applied,...revision};
64
72
  await storeWriteReceipt(client,record.machine,record.committedOutputId,record.body,outcome);
65
73
  return outcome;
66
74
  }
@@ -69,6 +77,9 @@ function persist(dispatch, record, client, settings) {
69
77
  if (record.fence) {
70
78
  return writeFencedSegment(client,record.machine,record.fence,record.body,async () => {
71
79
  await checkSegmentRevision(client,record.machine,record.fence.revision);
80
+ if (record.replication) {
81
+ await enableHistoryReplicaCapture(client,record.machine,record.fence,record.replication);
82
+ }
72
83
  await applyLive(dispatch, record, client, settings);
73
84
  return {applied:true,...await segmentRevision(client,record.machine)};
74
85
  });
@@ -93,6 +104,13 @@ export default function fencedSegments(pool, dispatch, settings) {
93
104
  return client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))',[ `history:${record.machine}` ])
94
105
  .then(() => {return persist(dispatch,record,client,policy)});
95
106
  }
107
+ async function apply(input, replication) {
108
+ let record;
109
+ try { record = decodeSegmentBody(input); }
110
+ catch (error) { throw new TypeError(error.message); }
111
+ if (!record.fence) { throw new TypeError('A segment write fence is required'); }
112
+ return await accept({...record,replication});
113
+ }
96
114
  return {
97
115
  dispatch: {
98
116
  accept,
@@ -103,12 +121,9 @@ export default function fencedSegments(pool, dispatch, settings) {
103
121
  },
104
122
  live: {
105
123
  revision(machine) { return segmentRevision(pool,machine); },
106
- async apply(input) {
107
- let record;
108
- try { record = decodeSegmentBody(input); }
109
- catch (error) { throw new TypeError(error.message); }
110
- if (!record.fence) { throw new TypeError('A segment write fence is required'); }
111
- return await accept(record);
124
+ apply(input) { return apply(input); },
125
+ applyOutbox(input, replication) {
126
+ return apply(input,{...replication,protocol:historyReplicaProtocol});
112
127
  }
113
128
  }
114
129
  };
@@ -54,7 +54,7 @@ function emitPiece(bus, piece) {
54
54
  function consume(raw, buses) {
55
55
  const parsed = JSON.parse(raw.payload);
56
56
  const bus = buses[parsed.machine];
57
- if (!bus || parsed.type === 'phase-transition') {
57
+ if (!bus || parsed.type === 'phase-transition' || parsed.type === 'segment-delete') {
58
58
  return;
59
59
  }
60
60
  if (parsed.type === 'split-family' && Array.isArray(parsed.pieces)) {
@@ -1,7 +1,8 @@
1
- export const historyReplicaProtocol = 'transactional-history-outbox-v1';
1
+ export const historyReplicaProtocol = 'transactional-history-outbox-v2';
2
2
 
3
3
  export function historyReplication(value) {
4
4
  if (!value || typeof value.exchange !== 'string' || !/^[\w.-]{1,255}$/u.test(value.exchange) ||
5
+ (value.protocol !== undefined && value.protocol !== historyReplicaProtocol) ||
5
6
  typeof value.routingKey !== 'string' || Buffer.byteLength(value.routingKey) > 255 ||
6
7
  (value.epoch !== undefined && (!Number.isSafeInteger(value.epoch) || value.epoch < 1))) {
7
8
  throw new TypeError('Invalid history replication destination or epoch');
@@ -22,23 +23,31 @@ function metadata(value, expected) {
22
23
  } catch { return null; }
23
24
  }
24
25
 
25
- function envelope({machine, segment: row, output_id: committedOutputId, epoch}) {
26
+ function envelope({id, machine, segment: row, output_id: committedOutputId, epoch, origin}) {
27
+ const deleted = !Object.hasOwn(row, 'name');
28
+ const timelineChange = origin ? {
29
+ origin, position: id, kind: row.kind, startTime: row.start_time, row: deleted ? null : row
30
+ } : undefined;
31
+ if (deleted) {
32
+ return JSON.stringify({ type: 'segment-delete', machine, committedOutputId, timelineChange,
33
+ ...(epoch !== null && { epoch: Number(epoch) }) });
34
+ }
26
35
  const tags = metadata(row.tags, 'array');
27
36
  return JSON.stringify({
28
37
  type: 'segment', kind: row.kind ?? 'phase', machine, name: row.name,
29
38
  start: new Date(row.start_time).getTime(), end: new Date(row.end_time).getTime(),
30
39
  duration: row.duration ?? 0, status: row.duration ? 'completed' : 'pending', tags,
31
40
  options: metadata(row.options, 'array'), properties: metadata(row.properties, 'object'),
32
- ...(tags && { resolved: true }), ...(epoch !== null && { epoch: Number(epoch) }), committedOutputId
41
+ ...(tags && { resolved: true }), ...(epoch !== null && { epoch: Number(epoch) }), committedOutputId, timelineChange
33
42
  });
34
43
  }
35
44
 
36
45
  export async function enableHistoryReplicaCapture(client, machine, fence, replication) {
37
- const { exchange, routingKey, epoch } = historyReplication(replication);
46
+ const { exchange, routingKey, epoch, protocol } = historyReplication(replication);
38
47
  if (fence.generation !== undefined && epoch !== fence.generation) {
39
48
  throw new TypeError('History replication epoch must match the writer generation');
40
49
  }
41
- const setting = JSON.stringify({ machine, outputId: fence.outputId, exchange, routingKey, epoch });
50
+ const setting = JSON.stringify({ machine, outputId: fence.outputId, exchange, routingKey, epoch, protocol });
42
51
  await client.query("SELECT set_config('scada.history_replica',$1,true)", [setting]);
43
52
  }
44
53
 
@@ -65,7 +74,7 @@ export async function deliverHistoryReplica(pool, publish, retryMs = 1000) {
65
74
  let delivered;
66
75
  try {
67
76
  await client.query('BEGIN');
68
- const { rows: [row] } = await client.query(`SELECT queued.id,queued.machine,queued.exchange,queued.routing_key,queued.output_id,queued.epoch,queued.segment
77
+ const { rows: [row] } = await client.query(`SELECT queued.id,queued.machine,queued.exchange,queued.routing_key,queued.output_id,queued.epoch,queued.segment,queued.origin
69
78
  FROM history_replica_outbox queued WHERE queued.retry_at <= clock_timestamp()
70
79
  AND NOT EXISTS (SELECT 1 FROM history_replica_outbox prior WHERE prior.machine=queued.machine AND prior.id<queued.id)
71
80
  ORDER BY queued.id LIMIT 1 FOR UPDATE OF queued SKIP LOCKED`);
@@ -0,0 +1,39 @@
1
+ const uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/u;
2
+ const position = /^[1-9][0-9]{0,18}$/u;
3
+
4
+ export function decodeTimelineChange(body) {
5
+ const change = body.timelineChange;
6
+ if (!change || !['segment', 'segment-delete'].includes(body.type) || typeof body.machine !== 'string' ||
7
+ !uuid.test(change.origin) || typeof change.position !== 'string' || !position.test(change.position) ||
8
+ BigInt(change.position) > 9223372036854775807n || typeof change.kind !== 'string' || !change.kind ||
9
+ typeof change.startTime !== 'string' || !Number.isFinite(Date.parse(change.startTime))) {
10
+ throw new TypeError('Invalid timeline change');
11
+ }
12
+ const {row} = change;
13
+ if (body.type === 'segment-delete' ? row !== null :
14
+ (!row || row.machine !== body.machine || row.kind !== change.kind || row.start_time !== change.startTime ||
15
+ typeof row.name !== 'string' || !Number.isFinite(Date.parse(row.end_time)) || !Number.isFinite(Date.parse(row.updated_at)))) {
16
+ throw new TypeError('Invalid timeline change row');
17
+ }
18
+ return { machine: body.machine, type: body.type, timelineChange: change };
19
+ }
20
+
21
+ async function upsert(client, row) {
22
+ const columns = 'machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed,updated_at';
23
+ await client.query(`INSERT INTO segments(${columns}) SELECT ${columns} FROM jsonb_populate_record(NULL::segments,$1::jsonb)
24
+ ON CONFLICT(machine,kind,start_time) DO UPDATE SET name=EXCLUDED.name,end_time=EXCLUDED.end_time,
25
+ duration=EXCLUDED.duration,options=EXCLUDED.options,tags=EXCLUDED.tags,properties=EXCLUDED.properties,
26
+ resolved=EXCLUDED.resolved,consumed=EXCLUDED.consumed,updated_at=EXCLUDED.updated_at`,[JSON.stringify(row)]);
27
+ }
28
+
29
+ export default async function applyTimelineReplica(client, machine, {origin,position: sequence,kind,startTime,row}) {
30
+ const key = [machine,kind,startTime];
31
+ const claimed = await client.query(`INSERT INTO timeline_replica_positions(machine,kind,start_time,origin,position)
32
+ VALUES($1,$2,$3,$4,$5) ON CONFLICT(machine,kind,start_time,origin)
33
+ DO UPDATE SET position=EXCLUDED.position WHERE timeline_replica_positions.position < EXCLUDED.position`,
34
+ [...key, origin, sequence]);
35
+ if (!claimed.rowCount) { return false; }
36
+ if (row) { await upsert(client,row); }
37
+ else { await client.query('DELETE FROM segments WHERE machine=$1 AND kind=$2 AND start_time=$3',key); }
38
+ return true;
39
+ }
@@ -3,13 +3,12 @@ import { listed, pending } from './spoolRecords.js';
3
3
  import { pendingFair } from './spoolReplay.js';
4
4
  import spoolMutations from './spoolMutations.js';
5
5
  import spoolMigration from './spoolMigration.js';
6
+ import spoolLimits from './spoolLimits.js';
6
7
 
7
8
  /* eslint max-lines-per-function: ["error", 100], max-statements: ["error", 25] */
8
9
  /** Single owner, bounded cache and indexed reads. Caps count logical JSON bytes, not allocated pages. */
9
- export default function deliverySpool(directory, { maxBytes, maxRecords = 100000, legacyMigrationMaxBytes = 16 * 1024 * 1024 } = {}) {
10
- if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) { throw new TypeError('Explicit positive spool maxBytes required'); }
11
- if (!Number.isSafeInteger(maxRecords) || maxRecords <= 0) { throw new TypeError('Positive safe spool maxRecords required'); }
12
- if (!Number.isSafeInteger(legacyMigrationMaxBytes) || legacyMigrationMaxBytes <= 0) { throw new TypeError('Positive safe legacyMigrationMaxBytes required'); }
10
+ export default function deliverySpool(directory, options) {
11
+ const { maxBytes, maxRecords, legacyMigrationMaxBytes } = spoolLimits(options);
13
12
  const state = { db: null, owner: null, ready: false, busy: false, bytes: 0, records: 0 };
14
13
  function release() {
15
14
  state.ready = false;
@@ -0,0 +1,6 @@
1
+ export default function spoolLimits({ maxBytes, maxRecords = 100000, legacyMigrationMaxBytes = 16 * 1024 * 1024 } = {}) {
2
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) { throw new TypeError('Explicit positive spool maxBytes required'); }
3
+ if (!Number.isSafeInteger(maxRecords) || maxRecords <= 0) { throw new TypeError('Positive safe spool maxRecords required'); }
4
+ if (!Number.isSafeInteger(legacyMigrationMaxBytes) || legacyMigrationMaxBytes <= 0) { throw new TypeError('Positive safe legacyMigrationMaxBytes required'); }
5
+ return { maxBytes, maxRecords, legacyMigrationMaxBytes };
6
+ }
@@ -0,0 +1,89 @@
1
+ import { fork } from 'node:child_process';
2
+ import spoolLimits from './spoolLimits.js';
3
+
4
+ function remoteError({ name, message, code }) {
5
+ const error = name === 'TypeError' ? new TypeError(message) : new Error(message);
6
+ error.name = name;
7
+ if (code !== undefined) { error.code = code; }
8
+ return error;
9
+ }
10
+
11
+ /* eslint max-lines-per-function: ["error", 90], max-statements: ["error", 24] */
12
+ export default function spoolProcess(directory, options) {
13
+ const limits = spoolLimits(options);
14
+ const state = {
15
+ child: null, stopped: null, pending: null,
16
+ status: { bytes: 0, maxBytes: limits.maxBytes, recordLimit: limits.maxRecords, pending: 0, ready: false }
17
+ };
18
+ function unavailable(error = new Error('Delivery spool process disconnected')) {
19
+ state.status.ready = false;
20
+ const { pending } = state;
21
+ state.pending = null;
22
+ pending?.reject(error);
23
+ }
24
+ function receive({ status, value, error }) {
25
+ const { pending } = state;
26
+ state.pending = null;
27
+ state.status = status;
28
+ if (error) { pending?.reject(remoteError(error)); }
29
+ else { pending?.resolve(value); }
30
+ }
31
+ function start() {
32
+ const child = fork(new URL('./spoolProcessChild.js', import.meta.url), [directory, JSON.stringify(limits)], {
33
+ serialization: 'advanced', execArgv: [], stdio: ['ignore', 'ignore', 'inherit', 'ipc']
34
+ });
35
+ state.child = child;
36
+ // An exited child's IPC can still deliver events after its replacement is running.
37
+ function whileCurrent(handler) {
38
+ return value => { if (state.child === child) { handler(value); } };
39
+ }
40
+ state.stopped = new Promise(resolve => {
41
+ function stopped() { unavailable(); state.child = null; resolve(); }
42
+ child.once('exit', whileCurrent(stopped));
43
+ child.on('error', whileCurrent(error => {
44
+ unavailable(error);
45
+ if (!child.pid) { stopped(); }
46
+ }));
47
+ });
48
+ child.once('disconnect', whileCurrent(() => { unavailable(); }));
49
+ child.on('message', whileCurrent(receive));
50
+ }
51
+ function call(method, ...args) {
52
+ if (!state.child?.connected) { return Promise.reject(new Error('Delivery spool process disconnected')); }
53
+ if (state.pending) { return Promise.reject(new Error('Spool operation in progress')); }
54
+ return new Promise((resolve, reject) => {
55
+ const pending = { resolve, reject };
56
+ state.pending = pending;
57
+ state.child.send({ method, args }, error => {
58
+ if (error && state.pending === pending) {
59
+ unavailable(error);
60
+ if (state.child?.connected) { state.child.disconnect(); }
61
+ }
62
+ });
63
+ });
64
+ }
65
+ return {
66
+ async open() {
67
+ // The previous process must release its file lock before ownership can be reacquired.
68
+ if (state.child && !state.child.connected) { await state.stopped; }
69
+ if (!state.child) { start(); }
70
+ return call('open');
71
+ },
72
+ async mutateMany(operations) {
73
+ const result = await call('mutateMany', operations);
74
+ return result.map(item => { return item.ok ? item : { ...item, error: remoteError(item.error) }; });
75
+ },
76
+ pendingFair(limit, blocked) { return call('pendingFair', limit, [...blocked]); },
77
+ peek(limit) { return call('peek', limit); },
78
+ async close() {
79
+ if (!state.child) { return; }
80
+ try {
81
+ if (state.child.connected) { await call('close'); }
82
+ } finally {
83
+ if (state.child?.connected) { state.child.disconnect(); }
84
+ await state.stopped;
85
+ }
86
+ },
87
+ status() { return { ...state.status }; }
88
+ };
89
+ }
@@ -0,0 +1,32 @@
1
+ import deliverySpool from './deliverySpool.js';
2
+
3
+ const [, , directory, options] = process.argv;
4
+ const spool = deliverySpool(directory, JSON.parse(options));
5
+
6
+ function errorDetails({ name, message, code }) {
7
+ return { name, message, code };
8
+ }
9
+
10
+ async function run({ method, args }) {
11
+ try {
12
+ const result = await spool[method](...args);
13
+ const value = method === 'mutateMany'
14
+ ? result.map(item => { return item.ok ? item : { ...item, error: errorDetails(item.error) }; })
15
+ : result;
16
+ return { value };
17
+ } catch (error) {
18
+ return { error: errorDetails(error) };
19
+ }
20
+ }
21
+
22
+ async function receive(message) {
23
+ const response = await run(message);
24
+ if (process.connected) {
25
+ process.send({ ...response, status: spool.status() }, error => {
26
+ if (error && process.connected) { process.disconnect(); }
27
+ });
28
+ }
29
+ }
30
+
31
+ process.on('message', receive);
32
+ process.once('disconnect', () => { process.off('message', receive); });
@@ -45,7 +45,7 @@ final class HistoryClient(config: CheckpointApiConfig):
45
45
  /** Retry a lost commit response with the same fenced body and receipt identity. */
46
46
  def commitHistory(body: Json, replication: Option[HistoryReplication] = None): IO[Json] =
47
47
  val (path, payload) = replication.fold(("/v1/history/commit", body)): target =>
48
- ("/v1/history/commit-outbox", body.deepMerge(Json.obj("replication" -> target.json)))
48
+ ("/v1/history/commit-outbox-v2", body.deepMerge(Json.obj("replication" -> target.json)))
49
49
  def attempt(retries: Int): IO[Json] =
50
50
  request("POST", path, payload).handleErrorWith:
51
51
  case error: HistoryHttpError if error.status < 500 => IO.raiseError(error)
@@ -129,7 +129,7 @@ final class ProcessingApplication(profile: RuntimeProfile):
129
129
  val grant = current.get(machine)
130
130
  IO.raiseWhen(config.leaseUrl.isDefined && grant.isEmpty)(
131
131
  IllegalStateException(s"No active timeline writer for $machine")).as(grant)
132
- TimelineWriter.create(HistoryClient(api), owner, outputs, publish)
132
+ TimelineWriter.create(HistoryClient(api), owner, outputs, publish, config.localHistory, config.writerEpoch)
133
133
 
134
134
  private def track(owners: Ref[IO, Map[String, Long]])(machine: String, generation: Option[Long]): Resource[IO, Unit] =
135
135
  generation.fold(Resource.unit[IO])(value => Resource.make(owners.update(_.updated(machine, value)))(_ =>
@@ -17,7 +17,9 @@ final class TimelineWriter private (
17
17
  generation: String => IO[Option[Long]],
18
18
  scope: OutputScope,
19
19
  relay: Option[StompSender],
20
- revisionScope: IOLocal[Option[(String, String)]]
20
+ revisionScope: IOLocal[Option[(String, String)]],
21
+ transactionalReplica: Boolean,
22
+ writerEpoch: Option[Long]
21
23
  ) extends StompSender:
22
24
  def atRevision[A](machine: String)(prepareAndWrite: IO[A]): IO[A] =
23
25
  revisionScope.get.flatMap:
@@ -54,14 +56,17 @@ final class TimelineWriter private (
54
56
  IllegalStateException(s"Timeline revision is missing for $machine"))
55
57
  metadata = List("outputId" -> outputId.asJson, "revision" -> revision.asJson) ++
56
58
  owner.toList.map(value => "generation" -> value.asJson)
57
- answer <- api.request("POST", "/v1/history/live-apply", payload.deepMerge(Json.obj("fence" -> Json.obj(metadata*))))
59
+ input = payload.deepMerge(Json.obj("fence" -> Json.obj(metadata*)))
60
+ replication = Option.when(transactionalReplica)(destination).flatten.map(HistoryReplication.fromDestination(_, owner.orElse(writerEpoch)))
61
+ answer <- replication.fold(api.request("POST", "/v1/history/live-apply", input)): target =>
62
+ api.request("POST", "/v1/history/live-apply-outbox", input.deepMerge(Json.obj("replication" -> target.json)))
58
63
  _ <- IO.raiseUnless(answer.hcursor.get[Boolean]("applied").contains(true))(
59
64
  IllegalStateException(s"Timeline sink did not confirm output $outputId"))
60
65
  after <- IO.fromEither(answer.hcursor.get[String]("revision"))
61
66
  // An idempotent retry may return the original receipt, whose revision predates this scope.
62
67
  next <- IO(BigInt(revision).max(BigInt(after)).toString)
63
68
  _ <- revisionScope.set(Some((machine, next)))
64
- _ <- (relay, destination) match
69
+ _ <- (relay.filter(_ => replication.isEmpty), destination) match
65
70
  case (Some(sender), Some(path)) =>
66
71
  val committed = payload.deepMerge(Json.obj("committedOutputId" -> outputId.asJson))
67
72
  val frame = StompFrame.send(path, "", committed.noSpaces)
@@ -71,8 +76,8 @@ final class TimelineWriter private (
71
76
 
72
77
  object TimelineWriter:
73
78
  def create(api: HistoryClient, generation: String => IO[Option[Long]], scope: OutputScope,
74
- relay: Option[StompSender]): IO[TimelineWriter] =
75
- IOLocal(Option.empty[(String, String)]).map(new TimelineWriter(api, generation, scope, relay, _))
79
+ relay: Option[StompSender], transactionalReplica: Boolean = false, writerEpoch: Option[Long] = None): IO[TimelineWriter] =
80
+ IOLocal(Option.empty[(String, String)]).map(new TimelineWriter(api, generation, scope, relay, _, transactionalReplica, writerEpoch))
76
81
 
77
82
  private val canonical = Printer.noSpaces.copy(sortKeys = true)
78
83