@yarkivaev/scada 2.7.0 → 2.8.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.
- package/README.md +4 -4
- package/db/migrations/C0008__segment_write_receipts_grants.sql +1 -0
- package/db/migrations/E0019__segment_write_fence.sql +36 -0
- package/db/migrations/E0020__segment_write_fence_grants.sql +4 -0
- package/db/migrations/V0015__segment_write_receipts.sql +7 -0
- package/index.js +2 -0
- package/package.json +6 -3
- package/src/application/supervisorSink.js +15 -5
- package/src/domain/segment/segmentCoalesce.js +2 -1
- package/src/infrastructure/http/edge/edgeApi.js +1 -1
- package/src/infrastructure/http/edge/routes/history/historyRoutes.js +8 -3
- package/src/infrastructure/ingest/codecs/segmentCodec.js +26 -4
- package/src/infrastructure/ingest/db/migrationProfile.js +4 -1
- package/src/infrastructure/ingest/pipelines/segmentPipeline.js +11 -5
- package/src/infrastructure/ingest/sinks/fencedSegments.js +117 -0
- package/src/infrastructure/persistence/pg/history.js +4 -3
- package/src/infrastructure/persistence/pg/segmentWriteFence.js +112 -0
- package/stream-processing/dependencies/stream-worker.jar +0 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Condition.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/CyclePhases.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Decision.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Emission.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineConfig.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineId.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineMode.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Params.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Reading.scala +1 -1
- package/stream-processing/src/main/scala/scada/processing/core/ReadingWorker.scala +82 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Segment.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/SegmentDef.scala +1 -1
- package/stream-processing/src/main/scala/scada/processing/core/Segmentation.scala +47 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Segments.scala +3 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/SplitFollow.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/SplitPieces.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/TagDef.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/TaggedSegment.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Tagging.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Timestamp.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/segmentation/Timeline.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/Checkpoint.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/SupervisorSinkCheckpoint.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/AppConfig.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/ConfigLoad.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/ConfigProfile.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/mqtt/Mqtt.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/mqtt/Sessions.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/AtomicStateFile.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/CheckpointSegments.scala +7 -5
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/SegmentStatePolicy.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/Segments.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/ClassifyQueue.scala +4 -4
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/DecisionMessage.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/DurableStomp.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SegmentMessage.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SegmentWirePolicy.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SplitFamily.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompConnection.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompDecisions.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompFrame.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompMachineDecisions.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompQueue.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompReadings.scala +3 -4
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompSegments.scala +20 -13
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ClassifyHistory.scala +3 -3
- package/stream-processing/src/main/scala/scada/processing/runtime/ClassifyStreams.scala +128 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Close.scala +4 -4
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HealthServer.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryBus.scala +40 -8
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryClient.scala +11 -4
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryRun.scala +42 -40
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/LocalHistory.scala +122 -36
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ObservationLead.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Orphans.scala +4 -4
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/PendingIsland.scala +3 -3
- package/stream-processing/src/main/scala/scada/processing/runtime/ProcessingApp.scala +8 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor/runtime/SupervisorRuntime.scala → stream-processing/src/main/scala/scada/processing/runtime/ProcessingApplication.scala} +108 -106
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/RuntimeProfile.scala +10 -12
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Seeding.scala +4 -4
- package/stream-processing/src/main/scala/scada/processing/runtime/TimelineWriter.scala +81 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/WorkerDatabase.scala +7 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterEpoch.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterGate.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterLease.scala +11 -9
- package/{supervisor-engine → stream-processing}/src/main/scala/scada/stream/replay/Replay.scala +1 -1
- package/stream-processing/stream-worker.lock +2 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/Processor.scala +0 -8
- package/supervisor-engine/src/main/scala/scada/stream/worker/StreamWorker.scala +0 -119
- package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/PgCheckpointStore.scala +0 -83
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +0 -52
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +0 -66
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +0 -58
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +0 -67
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +0 -4
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/LICENSE +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/UPSTREAM +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/LICENSE +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/UPSTREAM +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +0 -0
package/README.md
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
# SCADA
|
|
2
2
|
|
|
3
|
-
`@yarkivaev/scada` provides the collector runtime, Scala
|
|
3
|
+
`@yarkivaev/scada` provides the collector runtime, Scala stream processing, state sink and plant API for industrial monitoring.
|
|
4
4
|
|
|
5
5
|
- [Quick-start guide](docs/quick-start.md) — install the package and run a local API.
|
|
6
6
|
- [Documentation](docs/README.md) — installation, architecture, collection, operations and reference.
|
|
7
7
|
|
|
8
8
|
## Architecture
|
|
9
9
|
|
|
10
|
-

|
|
11
11
|
|
|
12
12
|
- **Collect near the equipment.** `scada-collector` runs device and stream adapters and delivers readings to their configured destinations.
|
|
13
|
-
- **Process readings with plant rules.** [
|
|
13
|
+
- **Process readings with plant rules.** [Stream processing](stream-processing/README.md) turns telemetry into timeline segments. The [state sink](docs/architecture/README.md#state-sink) persists segments, decisions and alerts, and the site API serves them to clients.
|
|
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 on eligible nodes, prepare a standby
|
|
17
|
+
For high availability, run collector copies on eligible nodes, prepare a standby stream processor and persist historical work so another worker can resume it. See [High availability](docs/architecture/high-availability.md) for the guarantees and their prerequisites.
|
|
18
18
|
|
|
19
19
|
## Package boundary
|
|
20
20
|
|
|
@@ -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;
|
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.
|
|
3
|
+
"version": "2.8.0",
|
|
4
4
|
"description": "SCADA domain objects, state persistence, and plant monitoring",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -33,6 +33,7 @@
|
|
|
33
33
|
"test": "mocha --exit 'test/**/test*.js'",
|
|
34
34
|
"test:deep": "mocha --exit 'test/domain/**/test*.js' 'test/infrastructure/ingest/**/test*.js'",
|
|
35
35
|
"coverage": "c8 --all --src src npm test",
|
|
36
|
+
"prepack": "sh stream-processing/resolve-worker.sh",
|
|
36
37
|
"lint": "eslint . && node scripts/check-eo-names.mjs",
|
|
37
38
|
"lint:fix": "eslint . --fix",
|
|
38
39
|
"lint:eo": "node scripts/check-eo-names.mjs"
|
|
@@ -65,8 +66,10 @@
|
|
|
65
66
|
"index.js",
|
|
66
67
|
"charts/",
|
|
67
68
|
"db/",
|
|
68
|
-
"
|
|
69
|
-
"
|
|
69
|
+
"stream-processing/src/main/scala/",
|
|
70
|
+
"stream-processing/vendor/",
|
|
71
|
+
"stream-processing/dependencies/stream-worker.jar",
|
|
72
|
+
"stream-processing/stream-worker.lock",
|
|
70
73
|
"src/"
|
|
71
74
|
]
|
|
72
75
|
}
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 {
|
|
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 (
|
|
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
|
+
}
|
|
Binary file
|