@yarkivaev/scada 2.6.42 → 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.
- 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 +3 -2
- package/src/application/management/management.js +57 -0
- package/src/application/supervisorSink.js +15 -5
- package/src/bin/scada.js +122 -0
- 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/management/command.js +18 -0
- package/src/infrastructure/management/inventory.js +63 -0
- package/src/infrastructure/management/kubernetes.js +90 -0
- package/src/infrastructure/management/protocol.js +67 -0
- package/src/infrastructure/management/remote.js +31 -0
- package/src/infrastructure/management/server.js +83 -0
- package/src/infrastructure/management/serverSideRelease.js +25 -0
- package/src/infrastructure/management/systemd.js +49 -0
- package/src/infrastructure/persistence/pg/history.js +4 -3
- package/src/infrastructure/persistence/pg/segmentWriteFence.js +112 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/OutputScope.scala +13 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/StreamWorker.scala +17 -1
- package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/WorkerDatabase.scala +7 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/ReadingWorker.scala +77 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +24 -13
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segments.scala +2 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala +2 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/ClassifyQueue.scala +2 -2
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompReadings.scala +0 -1
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompSegments.scala +17 -10
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +57 -20
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +6 -2
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryBus.scala +37 -5
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryClient.scala +9 -2
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryRun.scala +28 -30
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/LocalHistory.scala +117 -31
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/{SupervisorRuntime.scala → ProcessingApplication.scala} +101 -98
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/RuntimeProfile.scala +5 -6
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/TimelineWriter.scala +81 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterLease.scala +24 -5
- 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;
|
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.7.1",
|
|
4
4
|
"description": "SCADA domain objects, state persistence, and plant monitoring",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -26,7 +26,8 @@
|
|
|
26
26
|
"modbus-to-mqtt": "./src/bin/modbus-to-mqtt.js",
|
|
27
27
|
"supervisor-sink": "./src/bin/supervisor-sink.js",
|
|
28
28
|
"scada-collector": "./src/bin/collector.js",
|
|
29
|
-
"scada-controller": "./src/bin/controller.js"
|
|
29
|
+
"scada-controller": "./src/bin/controller.js",
|
|
30
|
+
"scada": "./src/bin/scada.js"
|
|
30
31
|
},
|
|
31
32
|
"scripts": {
|
|
32
33
|
"test": "mocha --exit 'test/**/test*.js'",
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime port: components(), logs(id, tail), plan(), apply().
|
|
3
|
+
* The application only knows context names and normalized results.
|
|
4
|
+
*/
|
|
5
|
+
export default function management(targets) {
|
|
6
|
+
const applying = new Set();
|
|
7
|
+
|
|
8
|
+
function targetOf(name, forwarded) {
|
|
9
|
+
const target = targets.get(name);
|
|
10
|
+
if (!target) {
|
|
11
|
+
throw new Error('unknown context');
|
|
12
|
+
}
|
|
13
|
+
if (forwarded && target.forwards) {
|
|
14
|
+
throw new Error('remote contexts support one forwarding hop');
|
|
15
|
+
}
|
|
16
|
+
return target;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function describe(name, forwarded) {
|
|
20
|
+
try {
|
|
21
|
+
return { name, components: await targetOf(name, forwarded).adapter.components() };
|
|
22
|
+
} catch (error) {
|
|
23
|
+
return { name, error: error.message };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function apply({ adapter, locks }) {
|
|
28
|
+
if (locks.some((key) => { return applying.has(key); })) {
|
|
29
|
+
throw new Error('apply already in progress for this target');
|
|
30
|
+
}
|
|
31
|
+
locks.forEach((key) => { applying.add(key); });
|
|
32
|
+
try {
|
|
33
|
+
return await adapter.apply();
|
|
34
|
+
} finally {
|
|
35
|
+
locks.forEach((key) => { applying.delete(key); });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function execute({ action, context, component, tail, forwarded }) {
|
|
40
|
+
if (action === 'contexts') {
|
|
41
|
+
return { contexts: Array.from(targets, ([name, target]) => {
|
|
42
|
+
return { name, runtime: target.runtime };
|
|
43
|
+
}) };
|
|
44
|
+
}
|
|
45
|
+
if (action === 'components') {
|
|
46
|
+
const names = context ? [context] : Array.from(targets.keys());
|
|
47
|
+
return { contexts: await Promise.all(names.map((name) => { return describe(name, forwarded); })) };
|
|
48
|
+
}
|
|
49
|
+
const target = targetOf(context, forwarded);
|
|
50
|
+
if (action === 'logs') {
|
|
51
|
+
return { logs: await target.adapter.logs(component, tail) };
|
|
52
|
+
}
|
|
53
|
+
return action === 'plan' ? target.adapter.plan() : apply(target);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return { execute };
|
|
57
|
+
}
|
|
@@ -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) {
|
package/src/bin/scada.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import management from '../application/management/management.js';
|
|
5
|
+
import readInventory from '../infrastructure/management/inventory.js';
|
|
6
|
+
import managementServer from '../infrastructure/management/server.js';
|
|
7
|
+
import { request, send } from '../infrastructure/management/protocol.js';
|
|
8
|
+
|
|
9
|
+
const usage = `Usage:
|
|
10
|
+
scada contexts
|
|
11
|
+
scada status [--context NAME]
|
|
12
|
+
scada get components [--context NAME]
|
|
13
|
+
scada logs COMPONENT --context NAME [--tail LINES]
|
|
14
|
+
scada plan --context NAME
|
|
15
|
+
scada apply --context NAME
|
|
16
|
+
|
|
17
|
+
Client options: --server URL (or SCADA_SERVER), --output text|json
|
|
18
|
+
Client credential: SCADA_TOKEN
|
|
19
|
+
|
|
20
|
+
scada serve --config PATH [--host HOST] [--port PORT] [--cert PATH --key PATH]
|
|
21
|
+
|
|
22
|
+
Server credentials: SCADA_TOKEN (read/write), SCADA_READ_TOKEN (read only)
|
|
23
|
+
`;
|
|
24
|
+
|
|
25
|
+
const clientOptions = {
|
|
26
|
+
server: { type: 'string' },
|
|
27
|
+
context: { type: 'string' },
|
|
28
|
+
output: { type: 'string', default: 'text' },
|
|
29
|
+
tail: { type: 'string' }
|
|
30
|
+
};
|
|
31
|
+
const serverOptions = {
|
|
32
|
+
config: { type: 'string' },
|
|
33
|
+
host: { type: 'string', default: '127.0.0.1' },
|
|
34
|
+
port: { type: 'string', default: '8080' },
|
|
35
|
+
cert: { type: 'string' },
|
|
36
|
+
key: { type: 'string' }
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
function commandOf([verb, arg, ...rest], { context, tail }) {
|
|
40
|
+
if (rest.length || (verb === 'get' && arg !== 'components') ||
|
|
41
|
+
(arg !== undefined && !['logs', 'get'].includes(verb)) || (tail !== undefined && verb !== 'logs') ||
|
|
42
|
+
(verb === 'contexts' && context !== undefined)) {
|
|
43
|
+
throw new Error('invalid command arguments; see scada --help');
|
|
44
|
+
}
|
|
45
|
+
const action = ['get', 'status'].includes(verb) ? 'components' : verb;
|
|
46
|
+
const result = request.safeParse({
|
|
47
|
+
action,
|
|
48
|
+
...(context !== undefined && { context }),
|
|
49
|
+
...(verb === 'logs' && { component: arg, tail: tail === undefined ? undefined : Number(tail) })
|
|
50
|
+
});
|
|
51
|
+
if (!result.success) {
|
|
52
|
+
throw new Error('invalid command arguments; see scada --help');
|
|
53
|
+
}
|
|
54
|
+
return result.data;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function textOf({ contexts, changes, logs }) {
|
|
58
|
+
if (contexts) {
|
|
59
|
+
return contexts.flatMap(({ name, runtime, components, error }) => {
|
|
60
|
+
if (components?.length) {
|
|
61
|
+
return components.map(({ id, state }) => { return `${name}\t${id}\t${state}`; });
|
|
62
|
+
}
|
|
63
|
+
return [`${name}\t${runtime ?? error ?? 'no components'}`];
|
|
64
|
+
}).join('\n');
|
|
65
|
+
}
|
|
66
|
+
if (changes) {
|
|
67
|
+
return changes.length ? changes.map(({ id, action }) => { return `${id}\t${action}`; }).join('\n') : 'no changes';
|
|
68
|
+
}
|
|
69
|
+
return logs;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function unhealthy({ error, components }) {
|
|
73
|
+
return Boolean(error) || !components.length || components.some(({ state }) => { return state !== 'ready'; });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function client(args) {
|
|
77
|
+
const { positionals, values } = parseArgs({ args, allowPositionals: true, options: clientOptions });
|
|
78
|
+
const command = commandOf(positionals, values);
|
|
79
|
+
const url = values.server ?? process.env.SCADA_SERVER;
|
|
80
|
+
const { SCADA_TOKEN: token } = process.env;
|
|
81
|
+
if (!url || !token || !['text', 'json'].includes(values.output)) {
|
|
82
|
+
throw new Error('set --server (or SCADA_SERVER), SCADA_TOKEN and use text or json output');
|
|
83
|
+
}
|
|
84
|
+
const result = await send(url, token, command);
|
|
85
|
+
const text = values.output === 'json' ? JSON.stringify(result) : textOf(result);
|
|
86
|
+
process.stdout.write(text.endsWith('\n') ? text : `${text}\n`);
|
|
87
|
+
if (positionals[0] === 'status' && result.contexts.some(unhealthy)) {
|
|
88
|
+
process.exitCode = 1;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function serve(args) {
|
|
93
|
+
const { values: { config, host, port, cert, key } } = parseArgs({ args, options: serverOptions });
|
|
94
|
+
if (!config || Boolean(cert) !== Boolean(key) || !/^\d{1,5}$/u.test(port) || Number(port) > 65535) {
|
|
95
|
+
throw new Error('serve requires --config and accepts --port 0-65535 and a --cert/--key pair');
|
|
96
|
+
}
|
|
97
|
+
const targets = await readInventory(config, process.env);
|
|
98
|
+
const tls = cert ? { cert: await readFile(cert), key: await readFile(key) } : undefined;
|
|
99
|
+
const { address, server } = await managementServer(management(targets), {
|
|
100
|
+
host, port: Number(port), tls, token: process.env.SCADA_TOKEN, readToken: process.env.SCADA_READ_TOKEN
|
|
101
|
+
});
|
|
102
|
+
function close() {
|
|
103
|
+
server.close();
|
|
104
|
+
}
|
|
105
|
+
process.once('SIGTERM', close);
|
|
106
|
+
process.once('SIGINT', close);
|
|
107
|
+
process.stdout.write(`${address}\n`);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const args = process.argv.slice(2);
|
|
111
|
+
try {
|
|
112
|
+
if (args.length === 0 || args.includes('--help') || args[0] === 'help') {
|
|
113
|
+
process.stdout.write(usage);
|
|
114
|
+
} else if (args[0] === 'serve') {
|
|
115
|
+
await serve(args.slice(1));
|
|
116
|
+
} else {
|
|
117
|
+
await client(args);
|
|
118
|
+
}
|
|
119
|
+
} catch (error) {
|
|
120
|
+
process.stderr.write(`scada: ${error.message}\n`);
|
|
121
|
+
process.exitCode = 1;
|
|
122
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Invoke a trusted binary without a shell. Keep subprocess diagnostics out of
|
|
5
|
+
* API responses because tools may include runtime credentials or rendered values.
|
|
6
|
+
*/
|
|
7
|
+
export default function command(binary, args, timeout = 30000, env = process.env) {
|
|
8
|
+
return new Promise((resolve, reject) => {
|
|
9
|
+
execFile(binary, args, { timeout, env, maxBuffer: 4 * 1024 * 1024 },
|
|
10
|
+
(error, stdout) => {
|
|
11
|
+
if (error) {
|
|
12
|
+
reject(new Error(`${binary} ${args[0]} failed (${error.code ?? error.signal ?? 'runtime error'})`));
|
|
13
|
+
} else {
|
|
14
|
+
resolve(stdout);
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/** Load the host-owned inventory and compose its runtime adapters. */
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { dirname, resolve } from 'node:path';
|
|
5
|
+
import kubernetes from './kubernetes.js';
|
|
6
|
+
import systemd from './systemd.js';
|
|
7
|
+
import remote from './remote.js';
|
|
8
|
+
import { contextName, urlOf } from './protocol.js';
|
|
9
|
+
|
|
10
|
+
const name = z.string().regex(/^[a-z0-9][a-z0-9.-]{0,62}$/u);
|
|
11
|
+
const unit = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.@:-]*\.service$/u);
|
|
12
|
+
const target = z.discriminatedUnion('runtime', [
|
|
13
|
+
z.strictObject({
|
|
14
|
+
runtime: z.literal('kubernetes'), kubeContext: z.string().min(1), namespace: name, release: name,
|
|
15
|
+
values: z.string().min(1).optional(), releasePlan: z.string().min(1).optional()
|
|
16
|
+
}).refine(({ values, releasePlan }) => { return !values || !releasePlan; }),
|
|
17
|
+
z.strictObject({ runtime: z.literal('systemd'), units: z.record(unit, z.literal('running')) }),
|
|
18
|
+
z.strictObject({
|
|
19
|
+
runtime: z.literal('remote'), server: z.string(), context: contextName,
|
|
20
|
+
tokenEnv: z.string().regex(/^[A-Z_][A-Z0-9_]*$/u)
|
|
21
|
+
})
|
|
22
|
+
]);
|
|
23
|
+
const inventory = z.strictObject({ contexts: z.record(contextName, target) });
|
|
24
|
+
|
|
25
|
+
function adapter(config, directory, env) {
|
|
26
|
+
if (config.runtime === 'systemd') {
|
|
27
|
+
return systemd(config);
|
|
28
|
+
}
|
|
29
|
+
if (config.runtime === 'kubernetes') {
|
|
30
|
+
return kubernetes({
|
|
31
|
+
...config, values: config.values && resolve(directory, config.values),
|
|
32
|
+
releasePlan: config.releasePlan && resolve(directory, config.releasePlan)
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
const token = env[config.tokenEnv];
|
|
36
|
+
if (!token) {
|
|
37
|
+
throw new Error(`missing credential ${config.tokenEnv}`);
|
|
38
|
+
}
|
|
39
|
+
return remote({ ...config, token });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function writeLocks(config) {
|
|
43
|
+
if (config.runtime === 'systemd') {
|
|
44
|
+
return Object.keys(config.units).map((id) => { return `systemd:${id}`; });
|
|
45
|
+
}
|
|
46
|
+
if (config.runtime === 'kubernetes') {
|
|
47
|
+
return [JSON.stringify(['kubernetes', config.kubeContext, config.namespace])];
|
|
48
|
+
}
|
|
49
|
+
return [JSON.stringify(['remote', urlOf(config.server).origin, config.context])];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export default async function readInventory(path, env) {
|
|
53
|
+
const result = inventory.safeParse(JSON.parse(await readFile(path, 'utf8')));
|
|
54
|
+
if (!result.success) {
|
|
55
|
+
throw new Error(`invalid inventory at ${result.error.issues[0].path.join('.') || 'root'}`);
|
|
56
|
+
}
|
|
57
|
+
return new Map(Object.entries(result.data.contexts).map(([id, config]) => {
|
|
58
|
+
return [id, {
|
|
59
|
+
runtime: config.runtime, forwards: config.runtime === 'remote', locks: writeLocks(config),
|
|
60
|
+
adapter: adapter(config, dirname(resolve(path)), env)
|
|
61
|
+
}];
|
|
62
|
+
}));
|
|
63
|
+
}
|