@yarkivaev/scada 2.11.1 → 2.12.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.
- package/README.md +1 -1
- package/db/migrations/E0023__timeline_replica_changes.sql +52 -0
- package/db/migrations/E0024__timeline_replica_origin_grants.sql +1 -0
- package/db/migrations/V0016__timeline_replica_positions.sql +8 -0
- package/db/migrations/V0017__timeline_replica_positions_grants.sql +1 -0
- package/package.json +1 -1
- package/src/application/supervisorSink.js +2 -1
- package/src/infrastructure/http/edge/routes/history/historyRoutes.js +16 -4
- package/src/infrastructure/ingest/codecs/segmentCodec.js +10 -0
- package/src/infrastructure/ingest/db/migrationProfile.js +2 -1
- package/src/infrastructure/ingest/sinks/fencedSegments.js +23 -8
- package/src/infrastructure/messaging/stomp/stompTimelineSegments.js +1 -1
- package/src/infrastructure/persistence/pg/historyReplicaOutbox.js +15 -6
- package/src/infrastructure/persistence/pg/timelineReplica.js +39 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/HistoryClient.scala +1 -1
- package/stream-processing/src/main/scala/scada/processing/runtime/ProcessingApplication.scala +1 -1
- package/stream-processing/src/main/scala/scada/processing/runtime/TimelineWriter.scala +10 -5
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
- **Keep plant state local.** An edge site can store its metrics and state in PostgreSQL. A central site can archive selected metrics from multiple edge sites in ClickHouse.
|
|
15
15
|
- **Manage placement separately.** Agents can run from local manifests. An optional `scada-controller` assigns work through etcd, and agents can continue running saved assignments during a control-plane outage.
|
|
16
16
|
|
|
17
|
-
For high availability, run collector copies
|
|
17
|
+
For high availability, agents can run collector copies and Stream Worker candidates can share a writer lease. With timeline replication v2, live writes and historical corrections publish committed changes and deletions through a PostgreSQL outbox. See [High availability](docs/architecture/high-availability.md).
|
|
18
18
|
|
|
19
19
|
## Package boundary
|
|
20
20
|
|
|
@@ -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 @@
|
|
|
1
|
+
GRANT SELECT, INSERT, UPDATE ON timeline_replica_positions TO supervisor_sink;
|
package/package.json
CHANGED
|
@@ -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 ? [
|
|
41
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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-
|
|
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
|
+
}
|
|
@@ -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)
|
package/stream-processing/src/main/scala/scada/processing/runtime/ProcessingApplication.scala
CHANGED
|
@@ -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
|
-
|
|
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
|
|