@yarkivaev/scada 2.7.0 → 2.7.1

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.
Files changed (37) hide show
  1. package/db/migrations/C0008__segment_write_receipts_grants.sql +1 -0
  2. package/db/migrations/E0019__segment_write_fence.sql +36 -0
  3. package/db/migrations/E0020__segment_write_fence_grants.sql +4 -0
  4. package/db/migrations/V0015__segment_write_receipts.sql +7 -0
  5. package/index.js +2 -0
  6. package/package.json +1 -1
  7. package/src/application/supervisorSink.js +15 -5
  8. package/src/domain/segment/segmentCoalesce.js +2 -1
  9. package/src/infrastructure/http/edge/edgeApi.js +1 -1
  10. package/src/infrastructure/http/edge/routes/history/historyRoutes.js +8 -3
  11. package/src/infrastructure/ingest/codecs/segmentCodec.js +26 -4
  12. package/src/infrastructure/ingest/db/migrationProfile.js +4 -1
  13. package/src/infrastructure/ingest/pipelines/segmentPipeline.js +11 -5
  14. package/src/infrastructure/ingest/sinks/fencedSegments.js +117 -0
  15. package/src/infrastructure/persistence/pg/history.js +4 -3
  16. package/src/infrastructure/persistence/pg/segmentWriteFence.js +112 -0
  17. package/supervisor-engine/src/main/scala/scada/stream/worker/OutputScope.scala +13 -0
  18. package/supervisor-engine/src/main/scala/scada/stream/worker/StreamWorker.scala +17 -1
  19. package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/WorkerDatabase.scala +7 -0
  20. package/supervisor-engine/src/main/scala/scada/supervisor/core/ReadingWorker.scala +77 -0
  21. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +24 -13
  22. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segments.scala +2 -0
  23. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala +2 -0
  24. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/ClassifyQueue.scala +2 -2
  25. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompReadings.scala +0 -1
  26. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompSegments.scala +17 -10
  27. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +57 -20
  28. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +6 -2
  29. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryBus.scala +37 -5
  30. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryClient.scala +9 -2
  31. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryRun.scala +28 -30
  32. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/LocalHistory.scala +117 -31
  33. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/{SupervisorRuntime.scala → ProcessingApplication.scala} +101 -98
  34. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/RuntimeProfile.scala +5 -6
  35. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/TimelineWriter.scala +81 -0
  36. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterLease.scala +24 -5
  37. package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +0 -66
@@ -0,0 +1 @@
1
+ GRANT SELECT, INSERT ON segment_write_receipts TO supervisor_sink;
@@ -0,0 +1,36 @@
1
+ CREATE TABLE IF NOT EXISTS classifier_generation (
2
+ machine text PRIMARY KEY,
3
+ generation bigint NOT NULL
4
+ );
5
+ ALTER TABLE classifier_generation ADD COLUMN IF NOT EXISTS holder_pid integer;
6
+
7
+ CREATE TABLE IF NOT EXISTS segment_timeline_revisions (
8
+ machine text PRIMARY KEY,
9
+ revision bigint NOT NULL
10
+ );
11
+
12
+ CREATE OR REPLACE FUNCTION bump_segment_timeline_revision() RETURNS trigger
13
+ LANGUAGE plpgsql AS $$
14
+ BEGIN
15
+ IF TG_OP = 'UPDATE' AND OLD IS NOT DISTINCT FROM NEW THEN
16
+ RETURN NULL;
17
+ END IF;
18
+ IF TG_OP <> 'INSERT' THEN
19
+ INSERT INTO segment_timeline_revisions VALUES (OLD.machine, 1)
20
+ ON CONFLICT (machine) DO UPDATE SET revision = segment_timeline_revisions.revision + 1;
21
+ END IF;
22
+ IF TG_OP = 'INSERT' OR (TG_OP = 'UPDATE' AND NEW.machine <> OLD.machine) THEN
23
+ INSERT INTO segment_timeline_revisions VALUES (NEW.machine, 1)
24
+ ON CONFLICT (machine) DO UPDATE SET revision = segment_timeline_revisions.revision + 1;
25
+ END IF;
26
+ RETURN NULL;
27
+ END;
28
+ $$;
29
+
30
+ CREATE TRIGGER segments_timeline_revision
31
+ AFTER INSERT OR UPDATE OR DELETE ON segments
32
+ FOR EACH ROW EXECUTE FUNCTION bump_segment_timeline_revision();
33
+
34
+ CREATE TRIGGER contiguous_inbox_timeline_revision
35
+ AFTER INSERT OR UPDATE OR DELETE ON contiguous_phase_inbox
36
+ FOR EACH ROW EXECUTE FUNCTION bump_segment_timeline_revision();
@@ -0,0 +1,4 @@
1
+ GRANT SELECT, INSERT, UPDATE ON classifier_generation TO supervisor_sink;
2
+ GRANT SELECT, INSERT ON segment_write_receipts TO supervisor_sink;
3
+ GRANT SELECT, INSERT, UPDATE ON segment_timeline_revisions TO supervisor_sink;
4
+ GRANT SELECT, INSERT, UPDATE ON stream_worker_checkpoint TO supervisor_sink;
@@ -0,0 +1,7 @@
1
+ CREATE TABLE IF NOT EXISTS segment_write_receipts (
2
+ machine text NOT NULL,
3
+ output_id text NOT NULL,
4
+ fingerprint text NOT NULL,
5
+ outcome jsonb NOT NULL,
6
+ PRIMARY KEY (machine, output_id)
7
+ );
package/index.js CHANGED
@@ -114,3 +114,5 @@ export { default as collectorProcesses } from './src/application/deploy/collecto
114
114
  export { default as executeStages } from './src/infrastructure/deploy/executeStages.js';
115
115
 
116
116
  export { default as historyPg, historyProtocol } from './src/infrastructure/persistence/pg/history.js';
117
+
118
+ export { historyWriteFence } from './src/infrastructure/persistence/pg/segmentWriteFence.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.7.0",
3
+ "version": "2.7.1",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -4,7 +4,7 @@ import segmentTransactionConfig from './segmentTransactionConfig.js';
4
4
  import segmentBatchStats from './segmentBatchStats.js';
5
5
  import historyTelemetry from '../infrastructure/ingest/telemetry/historyTelemetry.js';
6
6
  import segmentPipeline, {
7
- segmentsIngestDestination
7
+ segmentRecipient, segmentsIngestDestination
8
8
  } from '../infrastructure/ingest/pipelines/segmentPipeline.js';
9
9
  import decisionPipeline from '../infrastructure/ingest/pipelines/decisionPipeline.js';
10
10
  import alertPipeline from '../infrastructure/ingest/pipelines/alertPipeline.js';
@@ -72,6 +72,7 @@ export function readDeploymentConfig(env) {
72
72
  requestTimeoutMs: parseRequestTimeoutMs(env.REQUEST_TIMEOUT_MS),
73
73
  pipelines: env.COLLECTOR_MODE !== 'external' && env.SINK_PIPELINES !== 'false',
74
74
  pipeline: {
75
+ acceptReplicaSegments: env.SINK_DB_PROFILE === 'central' || env.SEGMENT_REPLICA_WRITES === 'true',
75
76
  phaseAnchors: phaseAnchors(env.CONTIGUOUS_PHASE_ANCHORS),
76
77
  repairHistoryOnStart: historyRepair(env.SEGMENT_REPAIR_HISTORY_ON_START),
77
78
  transactions: segmentTransactionConfig(env, dbPoolMax),
@@ -96,8 +97,8 @@ export function readDeploymentConfig(env) {
96
97
  };
97
98
  }
98
99
 
99
- function startPipelines(cfg, pool, health) {
100
- const pipelines = [segmentPipeline(cfg.stomp, cfg.postgres, pool, cfg.pipeline),
100
+ function startPipelines(cfg, pool, health, recipient) {
101
+ const pipelines = [segmentPipeline(cfg.stomp, cfg.postgres, pool, cfg.pipeline, recipient),
101
102
  decisionPipeline(cfg.stomp, pool, cfg.pipeline), alertPipeline(cfg.stomp, pool, cfg.pipeline)];
102
103
  health.track(pipelines);
103
104
  return Promise.all(pipelines.map((pipeline) => { return pipeline.start(); }));
@@ -135,7 +136,16 @@ export default function supervisorSink(env = process.env, options = {}) {
135
136
  const pool = holdClient(new pg.Pool({ connectionString: cfg.postgres, max: cfg.dbPoolMax }));
136
137
  const metricsEnabled = cfg.sinkDbProfile === 'edge';
137
138
  const data = stateDataFromPool(pool, { metricsEnabled, historyRetentionDays: Number(env.HISTORY_RETENTION_DAYS ?? 30) });
138
- const dataAccess = options.stateData ? options.stateData(data, pool) : data;
139
+ let recipient;
140
+ function segments() {
141
+ recipient ??= segmentRecipient(cfg.postgres,pool,cfg.pipeline);
142
+ return recipient;
143
+ }
144
+ const state = options.stateData ? options.stateData(data, pool) : data;
145
+ const dataAccess = metricsEnabled ? {...state,liveSegments:{
146
+ revision(machine) { return segments().live.revision(machine); },
147
+ apply(input) { return segments().live.apply(input); }
148
+ }} : state;
139
149
  const localTelemetry = historyTelemetry(env, pool);
140
150
  return {
141
151
  health: () => {return health.status()},
@@ -153,7 +163,7 @@ export default function supervisorSink(env = process.env, options = {}) {
153
163
  await prepareDatabase(cfg, pool);
154
164
  await localTelemetry?.start();
155
165
  if (cfg.pipelines) {
156
- await startPipelines(cfg, pool, health);
166
+ await startPipelines(cfg, pool, health, segments());
157
167
  }
158
168
  health.started();
159
169
  if (httpServer) {
@@ -30,7 +30,8 @@ function heartbeatKey(parsed) {
30
30
  * @returns {boolean}
31
31
  */
32
32
  function isHeartbeat(parsed) {
33
- return parsed.type === 'segment' && parsed.duration === 0 && parsed.properties?.phase_revision === undefined;
33
+ return parsed.type === 'segment' && parsed.duration === 0 && parsed.properties?.phase_revision === undefined &&
34
+ !Object.hasOwn(parsed,'fence') && !Object.hasOwn(parsed,'committedOutputId');
34
35
  }
35
36
 
36
37
  /**
@@ -29,7 +29,7 @@ export function createEdgeApi(dataAccess, options) {
29
29
  return routes([
30
30
  ...(opt.health ? ingestHealthRoutes(opt.health) : []),
31
31
  ...admin,
32
- ...historyRoutes(token, dataAccess.history),
32
+ ...historyRoutes(token, dataAccess.history, dataAccess.liveSegments),
33
33
  ...checkpointRoutes(token, checkpoints),
34
34
  ...metricRoutes
35
35
  ], { requestTimeoutMs: opt.requestTimeoutMs });
@@ -11,16 +11,21 @@ function endpoint(method, suffix, token, action) {
11
11
  if (typeof input.machine !== 'string' || !input.machine) { throw new TypeError('machine required'); }
12
12
  } catch (error) { errorResponse('BAD_REQUEST', error.message, 400).send(res); return; }
13
13
  try { jsonResponse(await action(input)).send(res); } catch (error) {
14
- if (error.statusCode === 409) { errorResponse('CONFLICT', error.message, 409).send(res); return; }
14
+ if (error.statusCode === 409) { errorResponse(error.writeCode ?? 'CONFLICT', error.message, 409).send(res); return; }
15
15
  if (error instanceof TypeError) { errorResponse('BAD_REQUEST', error.message, 400).send(res); return; }
16
16
  throw error;
17
17
  }
18
18
  });
19
19
  }
20
20
  /** Uses the existing checkpoint API authentication and persistence lifecycle. */
21
- export default function historyRoutes(token, history) {
22
- if (!history) { return []; }
21
+ export default function historyRoutes(token, history, liveSegments) {
22
+ const live = liveSegments ? [
23
+ endpoint('GET', 'live-revision', token, input => {return liveSegments.revision(input.machine)}),
24
+ endpoint('POST', 'live-apply', token, input => {return liveSegments.apply(input)})
25
+ ] : [];
26
+ if (!history) { return live; }
23
27
  return [
28
+ ...live,
24
29
  endpoint('POST', 'config', token, (input) => { return history.configure(input.machine, input.topics, input.bucketMs, input.classifierKey); }),
25
30
  endpoint('POST', 'purge', token, () => { return history.purge(); }),
26
31
  endpoint('POST', 'observations', token, (input) => { return history.accept(input.machine, input.observations); }),
@@ -1,4 +1,5 @@
1
1
  import segmentNormalize from '../../../domain/segment/normalize.js';
2
+ import { writeFence } from '../../persistence/pg/segmentWriteFence.js';
2
3
  import processingErrorLog from '../processingErrorLog.js';
3
4
 
4
5
  /**
@@ -43,13 +44,34 @@ function transitionRecord(parsed) {
43
44
  return { type: 'phase-transition', machine: parsed.machine, pieces };
44
45
  }
45
46
 
47
+ function persistedRecord(parsed) {
48
+ if (parsed.type === 'split-family') { return familyRecord(parsed); }
49
+ if (parsed.type === 'phase-transition') { return transitionRecord(parsed); }
50
+ return segmentNormalize(parsed);
51
+ }
52
+
53
+ export function decodeSegmentBody(parsed) {
54
+ const {fence,committedOutputId,...body} = parsed;
55
+ delete body.epoch;
56
+ const record = persistedRecord(body);
57
+ if (Object.hasOwn(parsed,'fence')) {
58
+ writeFence(fence);
59
+ if (typeof fence.revision !== 'string' || !/^[0-9]+$/u.test(fence.revision)) {
60
+ throw new TypeError('Expected segment revision required');
61
+ }
62
+ return {...record,fence,body};
63
+ }
64
+ if (Object.hasOwn(parsed,'committedOutputId')) {
65
+ writeFence({outputId:committedOutputId});
66
+ return {...record,committedOutputId,body};
67
+ }
68
+ return record;
69
+ }
70
+
46
71
  /** Decode once before admission so invalid envelopes never enter a transaction batch. */
47
72
  export function decodeSegment(raw) {
48
73
  try {
49
- const parsed = JSON.parse(raw.payload);
50
- if (parsed.type === 'split-family') { return familyRecord(parsed); }
51
- if (parsed.type === 'phase-transition') { return transitionRecord(parsed); }
52
- return segmentNormalize(parsed);
74
+ return decodeSegmentBody(JSON.parse(raw.payload));
53
75
  } catch (error) {
54
76
  error.permanent = true;
55
77
  throw error;
@@ -21,6 +21,7 @@ const privilegedOnly = new Set([
21
21
  'C0005__central_operators_grants.sql',
22
22
  'C0006__central_operators_registration.sql',
23
23
  'C0007__central_segment_replace_delete.sql',
24
+ 'C0008__segment_write_receipts_grants.sql',
24
25
  'E0002__edge_retention_delete.sql',
25
26
  'E0003__edge_operations_grants.sql',
26
27
  'E0004__edge_operations_delete.sql',
@@ -28,7 +29,9 @@ const privilegedOnly = new Set([
28
29
  'E0008__metric_receipts_grants.sql',
29
30
  'E0012__external_history_grants.sql',
30
31
  'E0014__history_correction_grants.sql',
31
- 'E0016__history_retention_grants.sql'
32
+ 'E0016__history_retention_grants.sql',
33
+ 'E0019__segment_write_fence.sql',
34
+ 'E0020__segment_write_fence_grants.sql'
32
35
  ]);
33
36
 
34
37
  /**
@@ -1,3 +1,4 @@
1
+ import fencedSegments from '../sinks/fencedSegments.js';
1
2
  import contiguousPhases, { validatePhaseAnchors } from '../sinks/contiguousPhases.js';
2
3
  import stompOptions from './stompOptions.js';
3
4
  import segmentTransactions from './segmentTransactions.js';
@@ -68,6 +69,14 @@ function repairCasting(pool, protectedTracks) {
68
69
  });
69
70
  }
70
71
 
72
+ export function segmentRecipient(postgres,pool,config) {
73
+ const { segmentSink, splitSink } = segmentSinks(postgres, pool);
74
+ const continued = continuedSegments(segmentSink, pool, silenceBudget(config.segmentWindow || 15));
75
+ const dispatch = contiguousPhases(pool, config.phaseAnchors,
76
+ segmentDispatch(continued, retagSink(pool), splitSink, closeOrphanOpen(pool), pool));
77
+ return fencedSegments(pool,dispatch,config);
78
+ }
79
+
71
80
  /**
72
81
  * Pipeline for streaming STOMP segment data to PostgreSQL segments table.
73
82
  * Subscribes to the durable ingest queue so shovel traffic survives consumer gaps.
@@ -80,13 +89,10 @@ function repairCasting(pool, protectedTracks) {
80
89
  * @param {object} config - Pipeline configuration
81
90
  * @returns {object} Pipeline with start() and stop() methods
82
91
  */
83
- export default function segmentPipeline(stomp, postgres, pool, config) {
92
+ export default function segmentPipeline(stomp, postgres, pool, config, recipient) {
84
93
  const settings = pipelineSettings(config);
85
94
  const budget = silenceBudget(settings.segmentWindow || 15);
86
- const { segmentSink, splitSink } = segmentSinks(postgres, pool);
87
- const continued = continuedSegments(segmentSink, pool, budget);
88
- const dispatch = contiguousPhases(pool, settings.phaseAnchors,
89
- segmentDispatch(continued, retagSink(pool), splitSink, closeOrphanOpen(pool), pool));
95
+ const {dispatch} = recipient ?? segmentRecipient(postgres,pool,settings);
90
96
  // eslint-disable-next-line prefer-const -- The timer codec closes over the source constructed with that codec.
91
97
  let source;
92
98
  const codec = segmentCodec(dispatch);
@@ -0,0 +1,117 @@
1
+ import { decodeSegmentBody } from '../codecs/segmentCodec.js';
2
+ import writeFencedSegment, {
3
+ activeSegmentLease, checkSegmentRevision, segmentLeaseMatches, segmentRevision, serialSegmentTransaction, storeWriteReceipt, writeReceipt
4
+ } from '../../persistence/pg/segmentWriteFence.js';
5
+
6
+ const computedProperties = new Set(['phase_revision', 'casting', 'cadence_rule', 'cadence_threshold_ms',
7
+ 'casting_detected_at', 'casting_silence_at', 'source_interrupted']);
8
+
9
+ function properties(value) {
10
+ const decoded = JSON.parse(value ?? 'null');
11
+ return decoded && typeof decoded === 'object' && !Array.isArray(decoded) ? decoded : {};
12
+ }
13
+
14
+ function keepOperatorFields(row, prior) {
15
+ if (!prior) { return row; }
16
+ const tagged = prior.tags && !['[]','null'].includes(prior.tags.trim());
17
+ const preserved = tagged ? {...row,options:prior.options,resolved:prior.resolved} : row;
18
+ if (!prior.properties) { return preserved; }
19
+ try {
20
+ const stored = properties(prior.properties);
21
+ const incoming = properties(row.properties);
22
+ const annotations = Object.fromEntries(Object.entries(stored).filter(([key]) => {
23
+ return !computedProperties.has(key);
24
+ }));
25
+ return {...preserved,properties:JSON.stringify({...incoming,...annotations})};
26
+ } catch {
27
+ // Older rows may carry a non-JSON operator value.
28
+ return {...preserved,properties:prior.properties};
29
+ }
30
+ }
31
+
32
+ async function preparePhases(client, rows) {
33
+ const {rows:previous} = await client.query(
34
+ "SELECT start_time,properties,tags,options,resolved FROM segments WHERE machine=$1 AND kind='phase' AND start_time=ANY($2::timestamptz[])",
35
+ [rows[0].machine,rows.map(row => { return row.start_time; })]);
36
+ const byStart = new Map(previous.map(row => { return [new Date(row.start_time).toISOString(),row]; }));
37
+ return rows.map(row => { return keepOperatorFields(row,byStart.get(row.start_time)); });
38
+ }
39
+
40
+ async function applyLive(dispatch, record, client, phaseAnchors) {
41
+ const transition = record.type === 'phase-transition';
42
+ if (!transition && (record.type !== 'segment' || record.kind !== 'phase')) {
43
+ return dispatch.accept(record,client);
44
+ }
45
+ const rows = await preparePhases(client,transition ? record.pieces : [record]);
46
+ if (!transition) { return dispatch.accept(rows[0],client); }
47
+ if (phaseAnchors?.has(record.machine)) { return dispatch.accept({...record,pieces:rows},client); }
48
+ // The ordinary recipient has no transition envelope. Its ordered writes still share this transaction.
49
+ return rows.reduce((previous,row) => {
50
+ return previous.then(() => { return dispatch.accept(row,client); });
51
+ },Promise.resolve());
52
+ }
53
+
54
+ async function applyReplica(dispatch,record,client,{acceptReplicaSegments,phaseAnchors}) {
55
+ const receipt = await writeReceipt(client,record.machine,record.committedOutputId,record.body);
56
+ if (receipt) { return receipt; }
57
+ // Authority can acknowledge a relay of its own receipt without accepting new replica writes.
58
+ if (!acceptReplicaSegments) { return {applied:false}; }
59
+ const {rows:[storage]} = await client.query("SELECT to_regclass('segment_timeline_revisions') AS local_revision");
60
+ const eligible = storage.local_revision
61
+ ? await segmentLeaseMatches(client,record.machine,undefined)
62
+ : !await activeSegmentLease(client,record.machine);
63
+ if (!eligible) { return {applied:false}; }
64
+ await applyLive(dispatch,record,client,phaseAnchors);
65
+ const revision = storage.local_revision ? await segmentRevision(client,record.machine) : {};
66
+ const outcome = {applied:true,...revision};
67
+ await storeWriteReceipt(client,record.machine,record.committedOutputId,record.body,outcome);
68
+ return outcome;
69
+ }
70
+
71
+ function persist(dispatch, record, client, settings) {
72
+ if (record.fence) {
73
+ return writeFencedSegment(client,record.machine,record.fence,record.body,async () => {
74
+ await checkSegmentRevision(client,record.machine,record.fence.revision);
75
+ await applyLive(dispatch,record,client,settings.phaseAnchors);
76
+ return {applied:true,...await segmentRevision(client,record.machine)};
77
+ });
78
+ }
79
+ return applyReplica(dispatch,record,client,settings);
80
+ }
81
+
82
+ function protectedRecord(record) {
83
+ return record.fence || record.committedOutputId;
84
+ }
85
+
86
+ /** Uses the same configured dispatch for broker deliveries and synchronous HTTP writes. */
87
+ export default function fencedSegments(pool, dispatch, settings) {
88
+ function accept(record, client) {
89
+ if (!protectedRecord(record)) { return dispatch.accept(record,client); }
90
+ if (!client) {
91
+ return serialSegmentTransaction(pool,record.machine,runner => {
92
+ return persist(dispatch,record,runner,settings);
93
+ },settings.acceptTimeoutMs);
94
+ }
95
+ return client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))',[ `history:${record.machine}` ])
96
+ .then(() => {return persist(dispatch,record,client,settings)});
97
+ }
98
+ return {
99
+ dispatch: {
100
+ accept,
101
+ acceptMany(records,client) {
102
+ if (!records.some(protectedRecord)) { return dispatch.acceptMany(records,client); }
103
+ return records.reduce((previous,record) => {return previous.then(() => {return accept(record,client)})},Promise.resolve());
104
+ }
105
+ },
106
+ live: {
107
+ revision(machine) { return segmentRevision(pool,machine); },
108
+ async apply(input) {
109
+ let record;
110
+ try { record = decodeSegmentBody(input); }
111
+ catch (error) { throw new TypeError(error.message); }
112
+ if (!record.fence) { throw new TypeError('A segment write fence is required'); }
113
+ return await accept(record);
114
+ }
115
+ }
116
+ };
117
+ }
@@ -1,3 +1,4 @@
1
+ import { historyWriteFence } from './segmentWriteFence.js';
1
2
  import nativeHistoryBounds, {nativeTailProtocol} from './historyNativeBounds.js';
2
3
  import historyAbsorb, {historyDedupe, span} from './historyAbsorb.js';
3
4
  import historyFence from './historyFence.js';
@@ -74,7 +75,7 @@ async function unchanged(client, machine, base, {observationSource,timeScale}) {
74
75
  await client.query('LOCK TABLE segments IN SHARE ROW EXCLUSIVE MODE');
75
76
  const latest = await context(client, machine, base.from, base.until, { padding: base.paddingMs, cutoff: -Infinity,cursor:base.cursor ?? null,end:base.end ?? null,classifierKey:base.classifierKey,workId:base.workId,workToken:base.workToken,timeScale,observations:observationSource?.(client) });
76
77
  if (latest.revision !== base.revision) {
77
- const error = new Error('History context changed');
78
+ const error = Object.assign(new Error('History context changed'), {writeCode:'REVISION_CONFLICT'});
78
79
  error.statusCode = 409;
79
80
  throw error;
80
81
  }
@@ -95,7 +96,7 @@ async function advance(client,machine,workId,page) {
95
96
  function commit(pool, machine, workId, segments, {base, observationSource,timeScale}) {
96
97
  if (!Array.isArray(segments) || segments.length > 1000) { throw new TypeError('Bounded segments required'); }
97
98
  // eslint-disable-next-line max-statements -- Claim, correction, checkpoint and advancement share one atomic boundary.
98
- return transaction(pool, machine, async (client) => {
99
+ return transaction(pool, machine, client => {return historyWriteFence(client,machine,{base,workId,segments},async () => {
99
100
  const work = await client.query(`SELECT id,token,from_ms,until_ms,cursor_ms,end_ms${base?.replace?',generation':''} FROM history_work WHERE id=$1 AND machine=$2 FOR UPDATE`, [workId, machine]);
100
101
  if (!work.rowCount) { return { applied: false }; }
101
102
  checkClaim(work.rows[0],base);
@@ -140,7 +141,7 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
140
141
  const converged=await saveCheckpoint(client,machine,base?.checkpoint,latest);
141
142
  await advance(client,machine,workId,converged ? {next:null} : latest?.context.page);
142
143
  return { applied: true };
143
- });
144
+ })});
144
145
  }
145
146
  /** Local telemetry history and durable classification work; no cross-edge database dependency. */
146
147
  export default function historyPg(pool, { retentionDays = 30, now = Date.now, observations: observationSource,timeScale=1,timestamp } = {}) {
@@ -0,0 +1,112 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ function conflict(writeCode, message) {
4
+ return Object.assign(new Error(message), {statusCode: 409, writeCode, permanent: true});
5
+ }
6
+
7
+ function stableJson(value) {
8
+ if (value instanceof Date) { return value.toJSON(); }
9
+ if (Array.isArray(value)) { return value.map(stableJson); }
10
+ if (value && typeof value === 'object') {
11
+ return Object.fromEntries(Object.keys(value).sort().map(key => { return [key, stableJson(value[key])]; }));
12
+ }
13
+ return value;
14
+ }
15
+
16
+ export function writeFence(input) {
17
+ if (!input || typeof input.outputId !== 'string' || !input.outputId || input.outputId.length > 512 ||
18
+ (input.generation !== undefined && (!Number.isSafeInteger(input.generation) || input.generation < 1))) {
19
+ throw new TypeError('A segment write requires an output ID and a valid generation when supplied');
20
+ }
21
+ return input;
22
+ }
23
+
24
+ export async function activeSegmentLease(client,machine) {
25
+ const {rows:[active]} = await client.query(
26
+ `SELECT pid FROM pg_locks
27
+ WHERE locktype='advisory' AND database=(SELECT oid FROM pg_database WHERE datname=current_database())
28
+ AND classid=hashtext('scada-classify')::oid AND objid=hashtext($1)::oid
29
+ AND objsubid=2 AND mode='ExclusiveLock' AND granted`, [machine]);
30
+ return active;
31
+ }
32
+
33
+ export async function segmentLeaseMatches(client, machine, generation) {
34
+ // The placeholder serializes an unleased write with the first grant for this machine.
35
+ await client.query('INSERT INTO classifier_generation(machine,generation) VALUES($1,0) ON CONFLICT DO NOTHING', [machine]);
36
+ const {rows:[owner]} = await client.query('SELECT generation,holder_pid FROM classifier_generation WHERE machine=$1 FOR SHARE', [machine]);
37
+ const active = await activeSegmentLease(client,machine);
38
+ return generation === undefined
39
+ ? !active
40
+ : Boolean(active && active.pid === owner.holder_pid && String(owner.generation) === String(generation));
41
+ }
42
+
43
+ function digest(body) {
44
+ return createHash('sha256').update(JSON.stringify(stableJson(body))).digest('hex');
45
+ }
46
+
47
+ export async function writeReceipt(client, machine, outputId, body) {
48
+ const {rows:[prior]} = await client.query(
49
+ 'SELECT fingerprint,outcome FROM segment_write_receipts WHERE machine=$1 AND output_id=$2',
50
+ [machine,outputId]);
51
+ if (prior && prior.fingerprint !== digest(body)) {
52
+ throw conflict('OUTPUT_CONFLICT', 'Output ID already identifies a different segment write');
53
+ }
54
+ return prior?.outcome;
55
+ }
56
+
57
+ export function storeWriteReceipt(client,machine,outputId,body,outcome) {
58
+ return client.query('INSERT INTO segment_write_receipts VALUES($1,$2,$3,$4::jsonb)',
59
+ [machine,outputId,digest(body),JSON.stringify(outcome)]);
60
+ }
61
+
62
+ /** Uses the caller's transaction, serialized on its machine, for the receipt and authoritative write. */
63
+ export default async function writeFencedSegment(client, machine, input, body, apply) {
64
+ const fence = writeFence(input);
65
+ const prior = await writeReceipt(client,machine,fence.outputId,body);
66
+ if (prior) { return prior; }
67
+ if (!await segmentLeaseMatches(client,machine,fence.generation)) {
68
+ throw conflict('STALE_OWNER', 'Classifier no longer holds the generation');
69
+ }
70
+ const outcome = await apply();
71
+ if (outcome.applied) {
72
+ await storeWriteReceipt(client,machine,fence.outputId,body,outcome);
73
+ }
74
+ return outcome;
75
+ }
76
+
77
+ export function historyWriteFence(client,machine,{base,workId,segments},apply) {
78
+ if (!base || !Object.hasOwn(base,'fence')) { return apply(); }
79
+ const {fence,...context} = base;
80
+ if (typeof context.revision !== 'string' || !context.revision) {
81
+ throw new TypeError('History context revision required');
82
+ }
83
+ return writeFencedSegment(client,machine,fence,{workId,segments,context},apply);
84
+ }
85
+
86
+ export async function segmentRevision(client, machine) {
87
+ const result = await client.query('SELECT revision::text FROM segment_timeline_revisions WHERE machine=$1', [machine]);
88
+ return {revision: result.rows[0]?.revision ?? '0'};
89
+ }
90
+
91
+ export async function checkSegmentRevision(client, machine, expected) {
92
+ await client.query('LOCK TABLE segments, contiguous_phase_inbox IN SHARE ROW EXCLUSIVE MODE');
93
+ const {revision} = await segmentRevision(client, machine);
94
+ if (revision !== expected) { throw conflict('REVISION_CONFLICT', 'Segment timeline revision changed'); }
95
+ }
96
+
97
+ export async function serialSegmentTransaction(pool, machine, apply, timeoutMs = 10000) {
98
+ const client = await pool.connect();
99
+ try {
100
+ await client.query('BEGIN');
101
+ await client.query("SELECT set_config('statement_timeout',$1,true)",[String(timeoutMs)]);
102
+ await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`history:${machine}`]);
103
+ const result = await apply(client);
104
+ await client.query('COMMIT');
105
+ return result;
106
+ } catch (error) {
107
+ await client.query('ROLLBACK');
108
+ throw error;
109
+ } finally {
110
+ client.release();
111
+ }
112
+ }
@@ -0,0 +1,13 @@
1
+ package scada.stream.worker
2
+
3
+ import cats.effect.{IO, IOLocal}
4
+
5
+ /** Carries the durable worker output ID through decorators that emit multiple wire messages. */
6
+ final class OutputScope private (local: IOLocal[Option[OutputId]]):
7
+ def current: IO[Option[OutputId]] = local.get
8
+
9
+ def within[A](id: OutputId)(write: IO[A]): IO[A] =
10
+ local.get.bracket(previous => local.set(Some(id)) *> write)(local.set)
11
+
12
+ object OutputScope:
13
+ def create: IO[OutputScope] = IOLocal(Option.empty[OutputId]).map(new OutputScope(_))
@@ -1,6 +1,6 @@
1
1
  package scada.stream.worker
2
2
 
3
- import cats.effect.IO
3
+ import cats.effect.{IO, Ref}
4
4
  import fs2.Stream
5
5
 
6
6
  final case class TaskIdentity(taskId: String, inputId: String, runId: String)
@@ -56,6 +56,22 @@ trait CheckpointStore[S, O]:
56
56
  /** Atomically validate ownership and revision, then replace the checkpoint. */
57
57
  def commit(ownership: Long, expectedRevision: Long, next: Checkpoint[S, O]): IO[Unit]
58
58
 
59
+ object CheckpointStore:
60
+ /** A session store for sources that recover by reseeding and cannot resume by delivery position. */
61
+ def session[S, O](initial: Checkpoint[S, O], token: Long): IO[CheckpointStore[S, O]] =
62
+ Ref.of[IO, Checkpoint[S, O]](initial).map: ref =>
63
+ new CheckpointStore[S, O]:
64
+ def load(task: TaskIdentity, ownership: Long): IO[Checkpoint[S, O]] =
65
+ IO.raiseUnless(task == initial.task && ownership == token)(StaleOwnership(task, ownership)) *> ref.get
66
+
67
+ def commit(ownership: Long, expectedRevision: Long, next: Checkpoint[S, O]): IO[Unit] =
68
+ IO.raiseUnless(next.task == initial.task && ownership == token)(StaleOwnership(next.task, ownership)) *>
69
+ ref.modify: current =>
70
+ if current.revision == expectedRevision && next.revision == expectedRevision + 1 then
71
+ (next, IO.unit)
72
+ else (current, IO.raiseError(IllegalStateException("Session checkpoint revision changed")))
73
+ .flatten
74
+
59
75
  /** Runtime for a deterministic processor. The sink checks ownership and deduplicates by OutputId. */
60
76
  final class StreamWorker[C, S, I, O](
61
77
  processor: Processor[C, S, I, O],
@@ -0,0 +1,7 @@
1
+ package scada.stream.worker.postgres
2
+
3
+ import cats.effect.IO
4
+ import doobie.Transactor
5
+
6
+ /** Database and token supplied together by an acquired task lease. */
7
+ final case class WorkerDatabase(transactor: Transactor[IO], generation: Long)