@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,90 @@
|
|
|
1
|
+
/** Kubernetes inspection and reconciliation for one configured release. */
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import command from './command.js';
|
|
4
|
+
|
|
5
|
+
const chart = fileURLToPath(new URL('../../../charts/scada', import.meta.url));
|
|
6
|
+
const worker = fileURLToPath(new URL('./serverSideRelease.js', import.meta.url));
|
|
7
|
+
const workloads = 'deployments,statefulsets,daemonsets,jobs';
|
|
8
|
+
|
|
9
|
+
function jobState(status) {
|
|
10
|
+
function active(type) {
|
|
11
|
+
return status.conditions?.some((item) => {
|
|
12
|
+
return item.type === type && item.status === 'True';
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
if (active('Failed')) {
|
|
16
|
+
return 'failed';
|
|
17
|
+
}
|
|
18
|
+
return active('Complete') ? 'ready' : 'pending';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function workloadState({ kind, metadata, spec = {}, status = {} }) {
|
|
22
|
+
if (kind === 'Job') {
|
|
23
|
+
return jobState(status);
|
|
24
|
+
}
|
|
25
|
+
if ((status.observedGeneration ?? 0) < metadata.generation) {
|
|
26
|
+
return 'pending';
|
|
27
|
+
}
|
|
28
|
+
const daemon = kind === 'DaemonSet';
|
|
29
|
+
const desired = daemon ? status.desiredNumberScheduled : spec.replicas ?? 1;
|
|
30
|
+
const available = daemon ? status.numberAvailable : status.availableReplicas ?? status.readyReplicas;
|
|
31
|
+
if (desired === 0) {
|
|
32
|
+
return 'stopped';
|
|
33
|
+
}
|
|
34
|
+
const updated = daemon ? status.updatedNumberScheduled : status.updatedReplicas;
|
|
35
|
+
if (kind === 'Deployment' && (status.replicas ?? 0) > (updated ?? 0)) {
|
|
36
|
+
return 'pending';
|
|
37
|
+
}
|
|
38
|
+
const complete = (available ?? 0) >= desired && (updated ?? 0) >= desired;
|
|
39
|
+
return complete ? 'ready' : 'pending';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export default function kubernetes({ kubeContext, namespace, release, values, releasePlan }) {
|
|
43
|
+
function kubectl(action, args) {
|
|
44
|
+
return command('kubectl', [action, `--context=${kubeContext}`, `--namespace=${namespace}`, ...args]);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function components() {
|
|
48
|
+
const selector = `app.kubernetes.io/name=scada,app.kubernetes.io/instance=${release}`;
|
|
49
|
+
const { items } = JSON.parse(await kubectl('get', [workloads, '--selector', selector, '-o', 'json']));
|
|
50
|
+
return items.map((item) => {
|
|
51
|
+
return { id: `${item.kind.toLowerCase()}/${item.metadata.name}`, state: workloadState(item) };
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function logs(component, tail) {
|
|
56
|
+
if (!(await components()).some(({ id }) => { return id === component; })) {
|
|
57
|
+
throw new Error('unknown component');
|
|
58
|
+
}
|
|
59
|
+
return kubectl('logs', [component, `--tail=${tail}`, '--all-containers=true']);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function helm(options, timeout) {
|
|
63
|
+
if (!values) {
|
|
64
|
+
throw new Error('this context has no desired release values');
|
|
65
|
+
}
|
|
66
|
+
// Even with --kube-context, Helm honors environment overrides for its API server and TLS settings.
|
|
67
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => {
|
|
68
|
+
return !key.startsWith('HELM_KUBE');
|
|
69
|
+
}));
|
|
70
|
+
await command('helm', ['upgrade', '--install', release, chart, `--kube-context=${kubeContext}`,
|
|
71
|
+
`--namespace=${namespace}`, `--values=${values}`, '--timeout=5m', ...options], timeout, env);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function reconcile(action, options, timeout) {
|
|
75
|
+
if (releasePlan) {
|
|
76
|
+
// The executor bounds each subprocess. Wait for the worker to settle before releasing the write lock.
|
|
77
|
+
await command(process.execPath, [worker, action, releasePlan, kubeContext, namespace, release], 0)
|
|
78
|
+
.catch(() => { throw new Error('Kubernetes server-side release failed'); });
|
|
79
|
+
} else {
|
|
80
|
+
await helm(options, timeout);
|
|
81
|
+
}
|
|
82
|
+
return { changes: [{ id: release, action: 'reconcile' }] };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
components, logs,
|
|
87
|
+
plan() { return reconcile('check', ['--dry-run=server', '--hide-secret'], 30000); },
|
|
88
|
+
apply() { return reconcile('apply', ['--atomic'], 660000); }
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/** Versioned management protocol shared by the server, CLI and forwarding runtime. */
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
export const endpoint = '/api/management/v1/command';
|
|
5
|
+
export const contextName = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,79}$/u);
|
|
6
|
+
const scope = { forwarded: z.boolean().optional() };
|
|
7
|
+
export const request = z.discriminatedUnion('action', [
|
|
8
|
+
z.strictObject({ action: z.literal('contexts') }),
|
|
9
|
+
z.strictObject({ action: z.literal('components'), context: contextName.optional(), ...scope }),
|
|
10
|
+
z.strictObject({
|
|
11
|
+
action: z.literal('logs'), context: contextName, ...scope,
|
|
12
|
+
component: z.string().min(1).max(300), tail: z.int().min(1).max(1000).default(100)
|
|
13
|
+
}),
|
|
14
|
+
z.strictObject({ action: z.literal('plan'), context: contextName, ...scope }),
|
|
15
|
+
z.strictObject({ action: z.literal('apply'), context: contextName, ...scope })
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
export function loopback(host) {
|
|
19
|
+
return ['127.0.0.1', '::1', '[::1]'].includes(host);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function urlOf(value) {
|
|
23
|
+
const url = new URL(value);
|
|
24
|
+
if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback(url.hostname))) ||
|
|
25
|
+
url.username || url.password || url.search || url.hash || url.pathname !== '/') {
|
|
26
|
+
throw new Error('management server must be an HTTPS origin (HTTP is allowed on loopback)');
|
|
27
|
+
}
|
|
28
|
+
if (url.protocol === 'https:' && process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0') {
|
|
29
|
+
throw new Error('HTTPS management requires TLS certificate verification');
|
|
30
|
+
}
|
|
31
|
+
return new URL(endpoint, url);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const component = z.object({
|
|
35
|
+
id: z.string(), state: z.enum(['ready', 'stopped', 'pending', 'failed'])
|
|
36
|
+
});
|
|
37
|
+
const changes = z.object({ changes: z.array(z.object({ id: z.string(), action: z.string() })) });
|
|
38
|
+
const results = {
|
|
39
|
+
contexts: z.object({ contexts: z.array(z.object({ name: contextName, runtime: z.string() })) }),
|
|
40
|
+
components: z.object({ contexts: z.array(z.union([
|
|
41
|
+
z.object({ name: contextName, components: z.array(component) }),
|
|
42
|
+
z.object({ name: contextName, error: z.string() })
|
|
43
|
+
])) }),
|
|
44
|
+
logs: z.object({ logs: z.string() }),
|
|
45
|
+
plan: changes,
|
|
46
|
+
apply: changes
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export async function send(server, token, command) {
|
|
50
|
+
const url = urlOf(server);
|
|
51
|
+
const response = await fetch(url, {
|
|
52
|
+
method: 'POST',
|
|
53
|
+
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
|
54
|
+
body: JSON.stringify(command),
|
|
55
|
+
redirect: 'error',
|
|
56
|
+
signal: AbortSignal.timeout(command.action === 'apply' ? 720000 : 90000)
|
|
57
|
+
});
|
|
58
|
+
const data = await response.json().catch(() => { return null; });
|
|
59
|
+
if (!response.ok) {
|
|
60
|
+
throw new Error(typeof data?.error === 'string' ? data.error : `management HTTP ${response.status}`);
|
|
61
|
+
}
|
|
62
|
+
const result = results[command.action].safeParse(data);
|
|
63
|
+
if (!result.success) {
|
|
64
|
+
throw new Error('invalid response from management server');
|
|
65
|
+
}
|
|
66
|
+
return result.data;
|
|
67
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Expose a concrete context on another management endpoint as a local runtime. */
|
|
2
|
+
import { send } from './protocol.js';
|
|
3
|
+
|
|
4
|
+
export default function remote({ server, token, context }) {
|
|
5
|
+
function request(action, options = {}) {
|
|
6
|
+
return send(server, token, { action, context, forwarded: true, ...options });
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
async function components() {
|
|
10
|
+
const { contexts } = await request('components');
|
|
11
|
+
const target = contexts.find(({ name }) => { return name === context; });
|
|
12
|
+
if (!target) {
|
|
13
|
+
throw new Error('remote server did not return the requested context');
|
|
14
|
+
}
|
|
15
|
+
if (target.error) {
|
|
16
|
+
throw new Error(target.error);
|
|
17
|
+
}
|
|
18
|
+
return target.components;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function logs(component, tail) {
|
|
22
|
+
const result = await request('logs', { component, tail });
|
|
23
|
+
return result.logs;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return {
|
|
27
|
+
components, logs,
|
|
28
|
+
plan() { return request('plan'); },
|
|
29
|
+
apply() { return request('apply'); }
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/** Authenticated HTTP transport for the management application. */
|
|
2
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
3
|
+
import { once } from 'node:events';
|
|
4
|
+
import { createServer as httpServer } from 'node:http';
|
|
5
|
+
import { createServer as httpsServer } from 'node:https';
|
|
6
|
+
import { endpoint, loopback, request } from './protocol.js';
|
|
7
|
+
|
|
8
|
+
const maxBodyBytes = 8192;
|
|
9
|
+
|
|
10
|
+
function matches(value, token) {
|
|
11
|
+
const actual = Buffer.from(value ?? '');
|
|
12
|
+
const expected = Buffer.from(`Bearer ${token}`);
|
|
13
|
+
return Boolean(token) && actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function reply(res, status, data) {
|
|
17
|
+
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
18
|
+
res.end(JSON.stringify(data));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function readCommand(req) {
|
|
22
|
+
const chunks = [];
|
|
23
|
+
let bytes = 0;
|
|
24
|
+
for await (const chunk of req.iterator({ destroyOnReturn: false })) {
|
|
25
|
+
bytes += chunk.length;
|
|
26
|
+
if (bytes > maxBodyBytes) {
|
|
27
|
+
req.resume();
|
|
28
|
+
throw new Error('request too large');
|
|
29
|
+
}
|
|
30
|
+
chunks.push(chunk);
|
|
31
|
+
}
|
|
32
|
+
return request.parse(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function execute(res, service, command) {
|
|
36
|
+
try {
|
|
37
|
+
reply(res, 200, await service.execute(command));
|
|
38
|
+
} catch (error) {
|
|
39
|
+
reply(res, 422, { error: error.message });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function accept(req, res, service, credentials) {
|
|
44
|
+
if (req.url !== endpoint || req.method !== 'POST') {
|
|
45
|
+
reply(res, 404, { error: 'unknown management endpoint' });
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const admin = matches(req.headers.authorization, credentials.token);
|
|
49
|
+
if (!admin && !matches(req.headers.authorization, credentials.readToken)) {
|
|
50
|
+
reply(res, 401, { error: 'unauthorized' });
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const command = await readCommand(req).catch(() => { return null; });
|
|
54
|
+
if (!command) {
|
|
55
|
+
reply(res, 400, { error: 'invalid management command' });
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
if (command.action === 'apply' && !admin) {
|
|
59
|
+
reply(res, 403, { error: 'forbidden' });
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
await execute(res, service, command);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export default async function managementServer(service, { host, port, tls, token, readToken }) {
|
|
66
|
+
if (!tls && !loopback(host)) {
|
|
67
|
+
throw new Error('a non-loopback listener requires --cert and --key');
|
|
68
|
+
}
|
|
69
|
+
if (!token && !readToken) {
|
|
70
|
+
throw new Error('set SCADA_TOKEN or SCADA_READ_TOKEN for the management server');
|
|
71
|
+
}
|
|
72
|
+
if (token && token === readToken) {
|
|
73
|
+
throw new Error('read and write credentials must differ');
|
|
74
|
+
}
|
|
75
|
+
const options = { requestTimeout: 15000, headersTimeout: 10000 };
|
|
76
|
+
const server = tls ? httpsServer({ ...options, ...tls }) : httpServer(options);
|
|
77
|
+
server.on('request', (req, res) => { void accept(req, res, service, { token, readToken }); });
|
|
78
|
+
server.listen(port, host);
|
|
79
|
+
await once(server, 'listening');
|
|
80
|
+
const { address } = server.address();
|
|
81
|
+
const hostname = address.includes(':') ? `[${address}]` : address;
|
|
82
|
+
return { server, address: `${tls ? 'https' : 'http'}://${hostname}:${server.address().port}` };
|
|
83
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Run the synchronous deployment executor outside the HTTP process.
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import executeRelease from '../deploy/executeRelease.js';
|
|
6
|
+
|
|
7
|
+
const [, , action, planPath, context, namespace, release] = process.argv;
|
|
8
|
+
const { values, fieldManager, prerequisites, workloads, retirements, podsAbsentBeforeApply } =
|
|
9
|
+
JSON.parse(readFileSync(planPath, 'utf8'));
|
|
10
|
+
const chart = fileURLToPath(new URL('../../../charts/scada', import.meta.url));
|
|
11
|
+
|
|
12
|
+
function execute(binary, args, options) {
|
|
13
|
+
const stdout = !options.stdio || options.stdio[1] === 'pipe' ? 'pipe' : 'ignore';
|
|
14
|
+
return execFileSync(binary, args, {
|
|
15
|
+
...options, stdio: ['pipe', stdout, 'ignore'], maxBuffer: 4 * 1024 * 1024,
|
|
16
|
+
timeout: action === 'check' ? 30000 : 310000, killSignal: 'SIGKILL'
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
try {
|
|
21
|
+
executeRelease({ chart, release, context, namespace, values, fieldManager, prerequisites,
|
|
22
|
+
workloads, retirements, podsAbsentBeforeApply }, action, execute);
|
|
23
|
+
} catch {
|
|
24
|
+
process.exitCode = 1;
|
|
25
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/** Read and start explicitly managed systemd services on this host. */
|
|
2
|
+
import command from './command.js';
|
|
3
|
+
|
|
4
|
+
function unitState(text) {
|
|
5
|
+
const active = /^ActiveState=(?<state>[^\n]+)$/mu.exec(text)?.groups.state;
|
|
6
|
+
const load = /^LoadState=(?<state>[^\n]+)$/mu.exec(text)?.groups.state;
|
|
7
|
+
if (load !== 'loaded') {
|
|
8
|
+
return 'failed';
|
|
9
|
+
}
|
|
10
|
+
const states = new Map([['active', 'ready'], ['inactive', 'stopped'], ['failed', 'failed']]);
|
|
11
|
+
return states.get(active) ?? 'pending';
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export default function systemd({ units }) {
|
|
15
|
+
function components() {
|
|
16
|
+
return Promise.all(Object.keys(units).map(async (id) => {
|
|
17
|
+
const text = await command('systemctl', ['show', '--property=LoadState,ActiveState', '--', id]);
|
|
18
|
+
return { id, state: unitState(text) };
|
|
19
|
+
}));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function logs(id, tail) {
|
|
23
|
+
if (!Object.hasOwn(units, id)) {
|
|
24
|
+
throw new Error('unknown component');
|
|
25
|
+
}
|
|
26
|
+
return command('journalctl', ['--no-pager', '--unit', id, '--lines', String(tail)]);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function plan() {
|
|
30
|
+
const changes = (await components()).flatMap(({ id, state }) => {
|
|
31
|
+
if (units[id] === 'running' && state !== 'ready') {
|
|
32
|
+
return [{ id, action: 'start' }];
|
|
33
|
+
}
|
|
34
|
+
return [];
|
|
35
|
+
});
|
|
36
|
+
return { changes };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function apply() {
|
|
40
|
+
const result = await plan();
|
|
41
|
+
const ids = result.changes.map(({ id }) => { return id; });
|
|
42
|
+
if (ids.length > 0) {
|
|
43
|
+
await command('systemctl', ['start', '--', ...ids], 300000);
|
|
44
|
+
}
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return { components, logs, plan, apply };
|
|
49
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
package scada.stream.worker
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO, IOLocal}
|
|
4
|
+
|
|
5
|
+
/** Carries the durable worker output ID through decorators that emit multiple wire messages. */
|
|
6
|
+
final class OutputScope private (local: IOLocal[Option[OutputId]]):
|
|
7
|
+
def current: IO[Option[OutputId]] = local.get
|
|
8
|
+
|
|
9
|
+
def within[A](id: OutputId)(write: IO[A]): IO[A] =
|
|
10
|
+
local.get.bracket(previous => local.set(Some(id)) *> write)(local.set)
|
|
11
|
+
|
|
12
|
+
object OutputScope:
|
|
13
|
+
def create: IO[OutputScope] = IOLocal(Option.empty[OutputId]).map(new OutputScope(_))
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
package scada.stream.worker
|
|
2
2
|
|
|
3
|
-
import cats.effect.IO
|
|
3
|
+
import cats.effect.{IO, Ref}
|
|
4
4
|
import fs2.Stream
|
|
5
5
|
|
|
6
6
|
final case class TaskIdentity(taskId: String, inputId: String, runId: String)
|
|
@@ -56,6 +56,22 @@ trait CheckpointStore[S, O]:
|
|
|
56
56
|
/** Atomically validate ownership and revision, then replace the checkpoint. */
|
|
57
57
|
def commit(ownership: Long, expectedRevision: Long, next: Checkpoint[S, O]): IO[Unit]
|
|
58
58
|
|
|
59
|
+
object CheckpointStore:
|
|
60
|
+
/** A session store for sources that recover by reseeding and cannot resume by delivery position. */
|
|
61
|
+
def session[S, O](initial: Checkpoint[S, O], token: Long): IO[CheckpointStore[S, O]] =
|
|
62
|
+
Ref.of[IO, Checkpoint[S, O]](initial).map: ref =>
|
|
63
|
+
new CheckpointStore[S, O]:
|
|
64
|
+
def load(task: TaskIdentity, ownership: Long): IO[Checkpoint[S, O]] =
|
|
65
|
+
IO.raiseUnless(task == initial.task && ownership == token)(StaleOwnership(task, ownership)) *> ref.get
|
|
66
|
+
|
|
67
|
+
def commit(ownership: Long, expectedRevision: Long, next: Checkpoint[S, O]): IO[Unit] =
|
|
68
|
+
IO.raiseUnless(next.task == initial.task && ownership == token)(StaleOwnership(next.task, ownership)) *>
|
|
69
|
+
ref.modify: current =>
|
|
70
|
+
if current.revision == expectedRevision && next.revision == expectedRevision + 1 then
|
|
71
|
+
(next, IO.unit)
|
|
72
|
+
else (current, IO.raiseError(IllegalStateException("Session checkpoint revision changed")))
|
|
73
|
+
.flatten
|
|
74
|
+
|
|
59
75
|
/** Runtime for a deterministic processor. The sink checks ownership and deduplicates by OutputId. */
|
|
60
76
|
final class StreamWorker[C, S, I, O](
|
|
61
77
|
processor: Processor[C, S, I, O],
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
package scada.supervisor.core
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import fs2.Stream
|
|
6
|
+
import scada.stream.worker.*
|
|
7
|
+
import scada.supervisor.core.segmentation.Timeline.Interval
|
|
8
|
+
import scala.concurrent.duration.*
|
|
9
|
+
|
|
10
|
+
/** Assembles the MQTT session input and its segment output port. */
|
|
11
|
+
final class ReadingWorker(
|
|
12
|
+
segmentation: Segmentation[IO],
|
|
13
|
+
tagging: Tagging,
|
|
14
|
+
segments: Segments[IO],
|
|
15
|
+
phases: CyclePhases = CyclePhases.empty,
|
|
16
|
+
customRun: Option[(MachineConfig, Stream[IO, Reading], Segments[IO]) => IO[Unit]] = None,
|
|
17
|
+
outputs: Option[OutputScope] = None
|
|
18
|
+
):
|
|
19
|
+
import ReadingWorker.*
|
|
20
|
+
|
|
21
|
+
private val processor = new Processor[MachineConfig, State, Input, TaggedSegment]:
|
|
22
|
+
def step(machine: MachineConfig, state: State, input: Input): Either[ProcessingError, StepResult[State, TaggedSegment]] =
|
|
23
|
+
input match
|
|
24
|
+
case Input.Sample(reading) =>
|
|
25
|
+
segmentation.step(machine, state, reading).map(result =>
|
|
26
|
+
StepResult(result.state, result.outputs.map(emission => tagging.resolve(machine.tags, emission.value))))
|
|
27
|
+
case Input.Restore(cursor) =>
|
|
28
|
+
Right(StepResult(state, Vector(pending(cursor.name, cursor.start, cursor.end))))
|
|
29
|
+
case Input.Pulse(now, rows) =>
|
|
30
|
+
Right(StepResult(state, pulse(now, rows).toVector))
|
|
31
|
+
|
|
32
|
+
def run(machine: MachineConfig, readings: Stream[IO, Reading], initial: Option[SegmentCursor] = None): IO[Unit] =
|
|
33
|
+
if machine.mode.isDefined then
|
|
34
|
+
customRun.fold(IO.raiseError(IllegalStateException("Machine mode has no configured worker")))(_(machine, readings, segments))
|
|
35
|
+
else
|
|
36
|
+
for
|
|
37
|
+
id <- IO.randomUUID
|
|
38
|
+
task = TaskIdentity(machine.id.raw, "mqtt", id.toString)
|
|
39
|
+
// MQTT reseeds from the timeline checkpoint rather than replaying a stable broker position.
|
|
40
|
+
snapshot = Checkpoint[State, TaggedSegment](task, mqttVersion, 0, None, segmentation.seed(initial), Vector.empty)
|
|
41
|
+
store <- CheckpointStore.session(snapshot, 1)
|
|
42
|
+
worker = StreamWorker(processor, store, (_, row) =>
|
|
43
|
+
outputs.fold(write(machine, row.value))(_.within(row.id)(write(machine, row.value))))
|
|
44
|
+
_ <- worker.run(task, mqttVersion, machine, 1): _ =>
|
|
45
|
+
val samples = segmentation.gather(readings).map(reading => IO.pure(Input.Sample(reading)))
|
|
46
|
+
val beats = Stream.awakeEvery[IO](1.second).as(for
|
|
47
|
+
rows <- segments.list(machine.id)
|
|
48
|
+
now <- IO.realTime.map(value => Timestamp(value.toMillis.toDouble / 1000.0))
|
|
49
|
+
yield Input.Pulse(now, rows))
|
|
50
|
+
val restore = Stream.emits(initial.toList).map(cursor => IO.pure(Input.Restore(cursor)))
|
|
51
|
+
(restore ++ samples.mergeHaltL(beats)).evalMap(identity).zipWithIndex.map: (input, position) =>
|
|
52
|
+
Delivery(position, input, IO.unit)
|
|
53
|
+
yield ()
|
|
54
|
+
|
|
55
|
+
private def write(machine: MachineConfig, tagged: TaggedSegment): IO[Unit] = segments.atRevision(machine.id):
|
|
56
|
+
if phases.isEmpty then segments.upsert(machine.id, tagged)
|
|
57
|
+
else segments.list(machine.id).flatMap(all => segments.upsert(machine.id, phases.narrow(tagged, all)))
|
|
58
|
+
|
|
59
|
+
object ReadingWorker:
|
|
60
|
+
private type State = Option[Interval[Reading]]
|
|
61
|
+
private val mqttVersion = ProcessorVersion("mqtt-segments/1", "session", "timeline/1")
|
|
62
|
+
|
|
63
|
+
private enum Input:
|
|
64
|
+
case Sample(reading: Reading)
|
|
65
|
+
case Restore(cursor: SegmentCursor)
|
|
66
|
+
case Pulse(now: Timestamp, rows: List[TaggedSegment])
|
|
67
|
+
|
|
68
|
+
private def pending(name: String, start: Timestamp, end: Timestamp): TaggedSegment =
|
|
69
|
+
TaggedSegment(Segment(name, start, end, 0.0), Nil, Nil, Map.empty)
|
|
70
|
+
|
|
71
|
+
private def pulse(now: Timestamp, rows: List[TaggedSegment]): Option[TaggedSegment] =
|
|
72
|
+
rows.filter(_.segment.duration == 0).maxByOption(_.segment.start) match
|
|
73
|
+
case Some(open) =>
|
|
74
|
+
Option.when(now.isAfter(open.segment.end))(open.copy(segment = open.segment.copy(end = now)))
|
|
75
|
+
case None =>
|
|
76
|
+
rows.maxByOption(_.segment.end).filter(last => now.isAfter(last.segment.end))
|
|
77
|
+
.map(last => pending(last.segment.name, last.segment.end, now))
|