@yarkivaev/scada 2.6.41 → 2.7.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.
@@ -0,0 +1,9 @@
1
+ CREATE TABLE IF NOT EXISTS stream_worker_checkpoint (
2
+ task_id text NOT NULL,
3
+ input_id text NOT NULL,
4
+ run_id text NOT NULL,
5
+ ownership bigint NOT NULL,
6
+ revision bigint NOT NULL CHECK (revision >= 0),
7
+ document jsonb NOT NULL,
8
+ PRIMARY KEY (task_id, input_id, run_id)
9
+ );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.6.41",
3
+ "version": "2.7.0",
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
+ }
@@ -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
+ }
@@ -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
+ }
@@ -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
+ }
@@ -0,0 +1,149 @@
1
+ package scada.stream.replay
2
+
3
+ import cats.effect.IO
4
+ import cats.syntax.all.*
5
+ import fs2.Stream
6
+ import scada.stream.worker.{ProcessingError, Processor}
7
+
8
+ /** A half-open range of offsets in the input snapshot. */
9
+ final case class ReplayRange(from: Int, until: Int)
10
+
11
+ /** The adapter assigns an identity that uniquely names this immutable, ordered event vector.
12
+ * Event timestamps need not be unique because replay positions are vector offsets.
13
+ */
14
+ final case class ReplayInput[I](id: String, events: Vector[I])
15
+
16
+ final case class ReplayManifest(
17
+ timeline: String,
18
+ range: ReplayRange,
19
+ rulesVersion: String,
20
+ inputId: String,
21
+ initialSeedId: String,
22
+ baseRevision: String,
23
+ runId: String
24
+ )
25
+
26
+ /** State immediately before the event at position. */
27
+ final case class ReplaySeed[+S](
28
+ id: String,
29
+ timeline: String,
30
+ rulesVersion: String,
31
+ inputId: String,
32
+ position: Int,
33
+ state: S
34
+ )
35
+
36
+ final case class ReplayOutput[O](position: Int, ordinal: Int, value: O)
37
+
38
+ final case class ReplayResult[S, O](
39
+ manifest: ReplayManifest,
40
+ outputs: Vector[ReplayOutput[O]],
41
+ terminalState: S
42
+ )
43
+
44
+ enum ReplayFailure:
45
+ case InvalidManifest(reason: String)
46
+ case InvalidSections
47
+ case BoundaryMismatch(position: Int)
48
+ case ProcessingFailed(position: Int, error: ProcessingError)
49
+
50
+ final class ReplayPlan[I, S] private[replay] (
51
+ val manifest: ReplayManifest,
52
+ private[replay] val input: ReplayInput[I],
53
+ private[replay] val sections: Vector[(ReplayRange, ReplaySeed[S])]
54
+ ):
55
+ def ranges: Vector[ReplayRange] = sections.map(_._1)
56
+
57
+ private[replay] final case class SectionResult[I, S, O](
58
+ plan: ReplayPlan[I, S],
59
+ range: ReplayRange,
60
+ outputs: Vector[ReplayOutput[O]],
61
+ terminalState: S
62
+ )
63
+
64
+ object Replay:
65
+ def plan[I, S](
66
+ manifest: ReplayManifest,
67
+ input: ReplayInput[I],
68
+ initial: ReplaySeed[S],
69
+ cuts: Set[Int] = Set.empty,
70
+ boundarySeeds: Vector[ReplaySeed[S]] = Vector.empty
71
+ ): Either[ReplayFailure, ReplayPlan[I, S]] =
72
+ val range = manifest.range
73
+ def compatible(seed: ReplaySeed[S]): Boolean =
74
+ seed.timeline == manifest.timeline && seed.rulesVersion == manifest.rulesVersion && seed.inputId == input.id
75
+
76
+ if manifest.inputId != input.id then
77
+ Left(ReplayFailure.InvalidManifest("Input identity does not match the manifest"))
78
+ else if range.from < 0 || range.from > range.until || range.until > input.events.size then
79
+ Left(ReplayFailure.InvalidManifest("Replay range is outside the input snapshot"))
80
+ else if !compatible(initial) || initial.id != manifest.initialSeedId || initial.position != range.from then
81
+ Left(ReplayFailure.InvalidManifest("Initial seed does not match the manifest"))
82
+ else if cuts.exists(position => position < range.from || position > range.until) then
83
+ Left(ReplayFailure.InvalidManifest("Section cut is outside the replay range"))
84
+ else
85
+ val boundaries = boundarySeeds.filter: seed =>
86
+ compatible(seed) && cuts(seed.position) && seed.position > range.from && seed.position < range.until
87
+ // A cut without a unique compatible seed stays in the preceding section.
88
+ val seededCuts = boundaries.groupBy(_.position).values.collect:
89
+ case Vector(seed) => seed
90
+ val starts = initial +: seededCuts.toVector.sortBy(_.position)
91
+ val ends = starts.tail.map(_.position) :+ range.until
92
+ val sections = starts.zip(ends).map: (seed, until) =>
93
+ ReplayRange(seed.position, until) -> seed
94
+ Right(new ReplayPlan(manifest, input, sections))
95
+
96
+ /** Returns a proposal after every section succeeds and all boundaries agree.
97
+ * The processor, versioned configuration, input, and states must be deterministic and
98
+ * immutable. State equality must compare every value that can affect a later step.
99
+ */
100
+ def run[C, S, I, O](
101
+ plan: ReplayPlan[I, S],
102
+ config: C,
103
+ processor: Processor[C, S, I, O],
104
+ parallelism: Int = 1
105
+ ): IO[Either[ReplayFailure, ReplayResult[S, O]]] =
106
+ if parallelism < 1 then IO.pure(Left(ReplayFailure.InvalidManifest("Parallelism must be positive")))
107
+ else
108
+ Stream.emits(plan.ranges).covary[IO]
109
+ .parEvalMap(parallelism)(range => runSection(plan, range, config, processor))
110
+ .compile.toVector
111
+ .map(_.sequence.flatMap(results => gather(plan, results)))
112
+
113
+ private[replay] def runSection[C, S, I, O](
114
+ plan: ReplayPlan[I, S],
115
+ range: ReplayRange,
116
+ config: C,
117
+ processor: Processor[C, S, I, O]
118
+ ): IO[Either[ReplayFailure, SectionResult[I, S, O]]] =
119
+ plan.sections.find(_._1 == range) match
120
+ case None => IO.pure(Left(ReplayFailure.InvalidSections))
121
+ case Some((_, seed)) =>
122
+ IO.defer:
123
+ val outputs = Vector.newBuilder[ReplayOutput[O]]
124
+ def advance(position: Int, state: S): IO[Either[ReplayFailure, SectionResult[I, S, O]]] =
125
+ if position == range.until then
126
+ IO.pure(Right(SectionResult(plan, range, outputs.result(), state)))
127
+ else
128
+ IO.defer:
129
+ processor.step(config, state, plan.input.events(position)) match
130
+ case Left(error) => IO.pure(Left(ReplayFailure.ProcessingFailed(position, error)))
131
+ case Right(result) =>
132
+ outputs ++= result.outputs.iterator.zipWithIndex.map: (value, ordinal) =>
133
+ ReplayOutput(position, ordinal, value)
134
+ advance(position + 1, result.state)
135
+ advance(range.from, seed.state)
136
+
137
+ private[replay] def gather[I, S, O](
138
+ plan: ReplayPlan[I, S],
139
+ results: Vector[SectionResult[I, S, O]]
140
+ ): Either[ReplayFailure, ReplayResult[S, O]] =
141
+ val ordered = results.sortBy(_.range.from)
142
+ if ordered.map(_.range) != plan.ranges || ordered.exists(result => result.plan ne plan) then
143
+ Left(ReplayFailure.InvalidSections)
144
+ else
145
+ val mismatched = ordered.zip(plan.sections.drop(1)).collectFirst:
146
+ case (result, (range, seed)) if result.terminalState != seed.state => range.from
147
+ mismatched match
148
+ case Some(position) => Left(ReplayFailure.BoundaryMismatch(position))
149
+ case None => Right(ReplayResult(plan.manifest, ordered.flatMap(_.outputs), ordered.last.terminalState))
@@ -0,0 +1,8 @@
1
+ package scada.stream.worker
2
+
3
+ final case class ProcessingError(message: String)
4
+ final case class StepResult[S, O](state: S, outputs: Vector[O])
5
+
6
+ /** A deterministic step over inputs already ordered by the source adapter. */
7
+ trait Processor[C, S, I, O]:
8
+ def step(config: C, state: S, event: I): Either[ProcessingError, StepResult[S, O]]
@@ -0,0 +1,119 @@
1
+ package scada.stream.worker
2
+
3
+ import cats.effect.IO
4
+ import fs2.Stream
5
+
6
+ final case class TaskIdentity(taskId: String, inputId: String, runId: String)
7
+ final case class ProcessorVersion(implementation: String, rules: String, stateSchema: String)
8
+
9
+ final case class OutputId(task: TaskIdentity, position: Long, index: Int)
10
+ final case class Output[O](id: OutputId, value: O)
11
+
12
+ /** Positions identify immutable records in one ordered input. An adapter must not skip unseen records. */
13
+ final case class Delivery[I](position: Long, value: I, acknowledge: IO[Unit])
14
+
15
+ final case class Checkpoint[S, O](
16
+ task: TaskIdentity,
17
+ version: ProcessorVersion,
18
+ revision: Long,
19
+ position: Option[Long],
20
+ state: S,
21
+ pendingOutputs: Vector[Output[O]]
22
+ )
23
+
24
+ final case class StaleOwnership(task: TaskIdentity, ownership: Long)
25
+ extends RuntimeException(s"Ownership $ownership is stale for $task")
26
+
27
+ final case class IncompatibleCheckpoint(
28
+ expectedTask: TaskIdentity,
29
+ expectedVersion: ProcessorVersion,
30
+ actualTask: TaskIdentity,
31
+ actualVersion: ProcessorVersion
32
+ ) extends RuntimeException(
33
+ s"Expected checkpoint for $expectedTask at $expectedVersion, found $actualTask at $actualVersion"
34
+ )
35
+
36
+ final case class StepFailed(error: ProcessingError) extends RuntimeException(error.message)
37
+ final case class UnconfirmedOutputs(task: TaskIdentity)
38
+ extends RuntimeException(s"Checkpoint for $task still has unconfirmed outputs")
39
+
40
+ private[worker] object CheckpointCompatibility:
41
+ def check(task: TaskIdentity, version: ProcessorVersion, actualTask: TaskIdentity, actualVersion: ProcessorVersion)
42
+ : IO[Unit] =
43
+ IO.raiseUnless(actualTask == task && actualVersion == version)(
44
+ IncompatibleCheckpoint(task, version, actualTask, actualVersion)
45
+ )
46
+
47
+ trait CheckpointStore[S, O]:
48
+ /** Load the checkpoint while validating current ownership. */
49
+ def load(task: TaskIdentity, ownership: Long): IO[Checkpoint[S, O]]
50
+
51
+ /** Validate the checkpoint version before consumption. Serialized stores can check the header first. */
52
+ def loadCompatible(task: TaskIdentity, version: ProcessorVersion, ownership: Long): IO[Checkpoint[S, O]] =
53
+ load(task, ownership).flatMap: checkpoint =>
54
+ CheckpointCompatibility.check(task, version, checkpoint.task, checkpoint.version).as(checkpoint)
55
+
56
+ /** Atomically validate ownership and revision, then replace the checkpoint. */
57
+ def commit(ownership: Long, expectedRevision: Long, next: Checkpoint[S, O]): IO[Unit]
58
+
59
+ /** Runtime for a deterministic processor. The sink checks ownership and deduplicates by OutputId. */
60
+ final class StreamWorker[C, S, I, O](
61
+ processor: Processor[C, S, I, O],
62
+ store: CheckpointStore[S, O],
63
+ publish: (Long, Output[O]) => IO[Unit]
64
+ ):
65
+ def run(task: TaskIdentity, version: ProcessorVersion, config: C, ownership: Long)(
66
+ input: Option[Long] => Stream[IO, Delivery[I]]
67
+ ): IO[Checkpoint[S, O]] =
68
+ for
69
+ checkpoint <- store.loadCompatible(task, version, ownership)
70
+ start <- deliver(ownership, checkpoint)
71
+ end <- input(start.position)
72
+ .evalMapAccumulate(start): (current, event) =>
73
+ process(config, ownership, current, event).map(next => (next, next))
74
+ .map(_._2)
75
+ .compile
76
+ .last
77
+ yield end.getOrElse(start)
78
+
79
+ /** Change rules while input consumption is stopped, after confirming the previous version's outputs.
80
+ * The current codec must be able to read the previous state.
81
+ */
82
+ def reconfigure(task: TaskIdentity, previous: ProcessorVersion, next: ProcessorVersion, ownership: Long)(
83
+ migrate: S => Either[ProcessingError, S]
84
+ ): IO[Checkpoint[S, O]] =
85
+ for
86
+ current <- store.loadCompatible(task, previous, ownership)
87
+ _ <- IO.raiseWhen(current.pendingOutputs.nonEmpty)(UnconfirmedOutputs(task))
88
+ migrated <- IO.defer(IO.fromEither(migrate(current.state).left.map(StepFailed.apply)))
89
+ updated = current.copy(version = next, revision = current.revision + 1, state = migrated)
90
+ _ <- store.commit(ownership, current.revision, updated)
91
+ yield updated
92
+
93
+ private def process(config: C, ownership: Long, current: Checkpoint[S, O], event: Delivery[I])
94
+ : IO[Checkpoint[S, O]] =
95
+ if current.position.exists(_ >= event.position) then event.acknowledge.as(current)
96
+ else
97
+ for
98
+ result <- IO.defer(IO.fromEither(
99
+ processor.step(config, current.state, event.value).left.map(StepFailed.apply)
100
+ ))
101
+ outputs = result.outputs.zipWithIndex.map: (value, index) =>
102
+ Output(OutputId(current.task, event.position, index), value)
103
+ updated = current.copy(
104
+ revision = current.revision + 1,
105
+ position = Some(event.position),
106
+ state = result.state,
107
+ pendingOutputs = outputs
108
+ )
109
+ _ <- store.commit(ownership, current.revision, updated)
110
+ _ <- event.acknowledge
111
+ delivered <- deliver(ownership, updated)
112
+ yield delivered
113
+
114
+ private def deliver(ownership: Long, current: Checkpoint[S, O]): IO[Checkpoint[S, O]] =
115
+ if current.pendingOutputs.isEmpty then IO.pure(current)
116
+ else
117
+ val updated = current.copy(revision = current.revision + 1, pendingOutputs = Vector.empty[Output[O]])
118
+ Stream.emits(current.pendingOutputs).evalMap(row => publish(ownership, row)).compile.drain *>
119
+ store.commit(ownership, current.revision, updated).as(updated)
@@ -0,0 +1,83 @@
1
+ package scada.stream.worker.postgres
2
+
3
+ import cats.effect.IO
4
+ import cats.syntax.all.*
5
+ import doobie.*
6
+ import doobie.implicits.*
7
+ import io.circe.{Decoder, Encoder, Json}
8
+ import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder}
9
+ import io.circe.parser.parse
10
+ import io.circe.syntax.*
11
+ import scada.stream.worker.*
12
+
13
+ final case class CheckpointConflict(task: TaskIdentity, expectedRevision: Long)
14
+ extends RuntimeException(s"Checkpoint for $task is no longer at revision $expectedRevision")
15
+
16
+ /** Shared storage for workers. The coordinator supplies strictly increasing ownership tokens. */
17
+ final class PgCheckpointStore[S: Encoder: Decoder, O: Encoder: Decoder](xa: Transactor[IO])
18
+ extends CheckpointStore[S, O]:
19
+ private given CodecForTask: Encoder[TaskIdentity] = deriveEncoder
20
+ private given DecodeTask: Decoder[TaskIdentity] = deriveDecoder
21
+ private given EncodeVersion: Encoder[ProcessorVersion] = deriveEncoder
22
+ private given DecodeVersion: Decoder[ProcessorVersion] = deriveDecoder
23
+ private given EncodeId: Encoder[OutputId] = deriveEncoder
24
+ private given DecodeId: Decoder[OutputId] = deriveDecoder
25
+ private given EncodeOutput: Encoder[Output[O]] = deriveEncoder
26
+ private given DecodeOutput: Decoder[Output[O]] = deriveDecoder
27
+ private given EncodeCheckpoint: Encoder[Checkpoint[S, O]] = deriveEncoder
28
+ private given DecodeCheckpoint: Decoder[Checkpoint[S, O]] = deriveDecoder
29
+
30
+ /** Activate the coordinator's grant. A takeover keeps the previous checkpoint and pending output. */
31
+ def claim(ownership: Long, initial: Checkpoint[S, O]): IO[Unit] =
32
+ val task = initial.task
33
+ val document = initial.asJson.noSpaces
34
+ sql"""
35
+ INSERT INTO stream_worker_checkpoint (task_id, input_id, run_id, ownership, revision, document)
36
+ VALUES (${task.taskId}, ${task.inputId}, ${task.runId}, $ownership, ${initial.revision}, $document::jsonb)
37
+ ON CONFLICT (task_id, input_id, run_id) DO UPDATE SET ownership = EXCLUDED.ownership
38
+ WHERE stream_worker_checkpoint.ownership <= EXCLUDED.ownership
39
+ """.update.run.transact(xa).flatMap(rows => IO.raiseWhen(rows != 1)(StaleOwnership(task, ownership)))
40
+
41
+ def load(task: TaskIdentity, ownership: Long): IO[Checkpoint[S, O]] =
42
+ document(task, ownership).flatMap(value => IO.fromEither(value.as[Checkpoint[S, O]]))
43
+
44
+ override def loadCompatible(task: TaskIdentity, version: ProcessorVersion, ownership: Long)
45
+ : IO[Checkpoint[S, O]] =
46
+ for
47
+ value <- document(task, ownership)
48
+ actualTask <- IO.fromEither(value.hcursor.get[TaskIdentity]("task"))
49
+ actualVersion <- IO.fromEither(value.hcursor.get[ProcessorVersion]("version"))
50
+ _ <- CheckpointCompatibility.check(task, version, actualTask, actualVersion)
51
+ checkpoint <- IO.fromEither(value.as[Checkpoint[S, O]])
52
+ yield checkpoint
53
+
54
+ private def document(task: TaskIdentity, ownership: Long): IO[Json] =
55
+ sql"""
56
+ SELECT document::text FROM stream_worker_checkpoint
57
+ WHERE task_id = ${task.taskId} AND input_id = ${task.inputId} AND run_id = ${task.runId}
58
+ AND ownership = $ownership
59
+ """.query[String].option.transact(xa).flatMap:
60
+ case Some(document) => IO.fromEither(parse(document))
61
+ case None => IO.raiseError(StaleOwnership(task, ownership))
62
+
63
+ def commit(ownership: Long, expectedRevision: Long, next: Checkpoint[S, O]): IO[Unit] =
64
+ val task = next.task
65
+ val document = next.asJson.noSpaces
66
+ val update = sql"""
67
+ UPDATE stream_worker_checkpoint SET revision = ${next.revision}, document = $document::jsonb
68
+ WHERE task_id = ${task.taskId} AND input_id = ${task.inputId} AND run_id = ${task.runId}
69
+ AND ownership = $ownership AND revision = $expectedRevision
70
+ """.update.run
71
+ if next.revision != expectedRevision + 1 then IO.raiseError(CheckpointConflict(task, expectedRevision))
72
+ else
73
+ val checked = update.flatMap:
74
+ case 1 => ().pure[ConnectionIO]
75
+ case _ =>
76
+ sql"""
77
+ SELECT ownership FROM stream_worker_checkpoint
78
+ WHERE task_id = ${task.taskId} AND input_id = ${task.inputId} AND run_id = ${task.runId}
79
+ """.query[Long].option.flatMap:
80
+ case Some(active) if active == ownership =>
81
+ CheckpointConflict(task, expectedRevision).raiseError[ConnectionIO, Unit]
82
+ case _ => StaleOwnership(task, ownership).raiseError[ConnectionIO, Unit]
83
+ checked.transact(xa)
@@ -1,54 +1,34 @@
1
1
  package scada.supervisor.core
2
2
 
3
- import cats.Applicative
4
- import cats.effect.{Async, Ref}
3
+ import cats.effect.Async
5
4
  import fs2.{Pipe, Stream}
6
5
  import scala.concurrent.duration.*
7
- import yarkivaev.gapsandislands.api.*
6
+ import scada.supervisor.core.segmentation.Timeline
7
+ import scada.supervisor.core.segmentation.Timeline.{Boundary, Event, Interval, Output}
8
8
 
9
- /**
10
- * Stateless classifier building an `fs2.Pipe` from readings to
11
- * [[Emission]]s of [[Segment]]s. Delegates the event-loop entirely to
12
- * `gaps-and-islands`; no per-machine state leaks outside the returned
13
- * pipe.
14
- *
15
- * Classification picks the first [[SegmentDef]] whose condition
16
- * matches; a missing match extends the currently open segment (or
17
- * emits the `unclassified` sentinel at stream start). Same-timestamp
18
- * MQTT metrics are merged before classification so a voltage heartbeat
19
- * cannot hide a low `power` that arrived in the same instant.
20
- * Island identity follows classification and a gap longer than
21
- * `machine.window * 2` seconds. A kind change holds the closed island
22
- * until the next sample so a 5 s sensor polling period cannot punch a hole in
23
- * the tape. A timestamp jump without an `off` in the stream does not
24
- * open a downtime island: the previous island closes and a new pending
25
- * island of the same kind starts at the later reading. A site can override
26
- * the class and properties of a reading before rules are evaluated.
27
- *
28
- * {{{
29
- * readings.through(Segmentation[F]().flow(machine, None))
30
- * }}}
31
- */
32
9
  final case class ReadingOverride(name: String, properties: Map[String, String])
33
10
 
11
+ /** Merges same-time readings and applies the live interval policy.
12
+ * Class changes close at the next phase's first sample. A gap over twice
13
+ * the machine's window splits equal phases without inventing downtime.
14
+ */
34
15
  final class Segmentation[F[_]: Async](overrideReading: Reading => Option[ReadingOverride] = _ => None):
35
- import Segmentation.{Evidence, Kind, unclassified}
16
+ private val unclassified = "unclassified"
36
17
 
37
18
  def flow(machine: MachineConfig, initial: Option[SegmentCursor] = None): Pipe[F, Reading, Emission[Segment]] =
38
- (in: Stream[F, Reading]) =>
39
- Stream.eval(Ref.of[F, Int](0)).flatMap: gap =>
40
- val maxGap = machine.window.toDouble * 2.0
41
- val evidence: (Option[Island[Reading, Kind]], Reading) => Evidence = (prev, r) => (prev, r)
42
- gather(in).through(
43
- IslandsFlow.pipe(
44
- policy(machine.segments, gap, maxGap),
45
- evidence,
46
- initial.map(Segmentation.toIsland)
47
- )
48
- )
49
- .through(abutKindChange)
50
- .map(toEmission)
51
- .unNone
19
+ val classify = Timeline.classifier(machine.segments)
20
+ val maxGap = machine.window.toDouble * 2.0
21
+ val seed = initial.map: cursor =>
22
+ Interval(cursor.name, Reading(cursor.start, Params(Map.empty)), Reading(cursor.end, Params(Map.empty)))
23
+
24
+ input =>
25
+ gather(input).mapAccumulate(seed): (open, reading) =>
26
+ val name = overrideReading(reading).map(_.name).orElse(classify(reading.params))
27
+ .orElse(open.map(_.name)).getOrElse(unclassified)
28
+ val continuous = open.exists(interval => !(reading.timestamp.minus(interval.end.timestamp) > maxGap))
29
+ val step = Timeline.step(Boundary.Live, open, Event.Sample(reading, name, continuous))
30
+ (step.open, step.outputs.flatMap(toEmission))
31
+ .flatMap((_, emissions) => Stream.emits(emissions))
52
32
 
53
33
  private def gather(in: Stream[F, Reading]): Stream[F, Reading] =
54
34
  in.groupWithin(32, 50.millis).flatMap: chunk =>
@@ -56,82 +36,17 @@ final class Segmentation[F[_]: Async](overrideReading: Reading => Option[Reading
56
36
  chunk.toList.groupBy(_.timestamp.epoch).toList.sortBy(_._1).map: (_, rows) =>
57
37
  rows.reduce((left, right) => Reading(right.timestamp, left.params.merge(right.params)))
58
38
 
59
- private def policy(defs: List[SegmentDef], gap: Ref[F, Int], maxGap: Double): IslandsPolicy[F, Evidence, Kind] =
60
- for
61
- name <- classification(defs)
62
- session <- gapSession(gap, maxGap)
63
- yield (name, session)
64
-
65
- private def classification(defs: List[SegmentDef]): IslandsPolicy[F, Evidence, String] =
66
- val lookup: String => Option[Condition] = name => defs.find(_.name == name).map(_.condition)
67
- IslandsPolicy: (prev, reading) =>
68
- Applicative[F].pure:
69
- overrideReading(reading).map(_.name)
70
- .orElse(defs.find(_.condition.matches(reading.params, lookup)).map(_.name))
71
- .orElse(prev.map(_.kind._1)).getOrElse(unclassified)
72
-
73
- private def gapSession(gap: Ref[F, Int], maxGap: Double): IslandsPolicy[F, Evidence, Int] =
74
- IslandsPolicy: (prev, reading) =>
75
- prev match
76
- case None => gap.get
77
- case Some(island) =>
78
- val delta = reading.timestamp.minus(island.last.timestamp)
79
- if delta > maxGap then gap.updateAndGet(_ + 1)
80
- else gap.get
81
-
82
- private def abutKindChange(in: Stream[F, IslandEvent[Reading, Kind]]): Stream[F, IslandEvent[Reading, Kind]] =
83
- Stream.eval(Ref.of[F, Option[Island[Reading, Kind]]](None)).flatMap: held =>
84
- val body: Stream[F, IslandEvent[Reading, Kind]] = in.flatMap: event =>
85
- event match
86
- case IslandEvent.IslandClosed(closed) =>
87
- Stream.exec(held.set(Some(closed)))
88
- case started @ IslandEvent.IslandStarted(open) =>
89
- Stream.eval(held.getAndSet(None)).flatMap:
90
- case Some(closed) if closed.kind._1 != open.kind._1 =>
91
- Stream.emit(IslandEvent.IslandClosed(Island(closed.kind, closed.first, open.first)))
92
- ++ Stream.emit(started)
93
- case Some(closed) =>
94
- Stream.emit(IslandEvent.IslandClosed(closed)) ++ Stream.emit(started)
95
- case None =>
96
- Stream.emit(started)
97
- case other =>
98
- Stream.eval(held.getAndSet(None)).flatMap:
99
- case Some(closed) => Stream.emit(IslandEvent.IslandClosed(closed)) ++ Stream.emit(other)
100
- case None => Stream.emit(other)
101
- val rest: Stream[F, IslandEvent[Reading, Kind]] = Stream.eval(held.get).flatMap:
102
- case Some(closed) => Stream.emit(IslandEvent.IslandClosed(closed))
103
- case None => Stream.empty
104
- body ++ rest
105
-
106
- private def toEmission(event: IslandEvent[Reading, Kind]): Option[Emission[Segment]] =
107
- event match
108
- case IslandEvent.IslandStarted(island) if island.kind._1 != unclassified =>
109
- Some(Emission.Started(toPending(island)))
110
- case IslandEvent.IslandExtended(island) if island.kind._1 != unclassified =>
111
- Some(Emission.Started(toPending(island)))
112
- case IslandEvent.IslandClosed(island) if island.kind._1 != unclassified =>
113
- Some(Emission.Emitted(toSegment(island)))
39
+ private def toEmission(output: Output[Reading]): Option[Emission[Segment]] =
40
+ def segment(interval: Interval[Reading], closed: Boolean): Segment =
41
+ val start = interval.start.timestamp
42
+ val end = interval.end.timestamp
43
+ val duration = if closed then end.minus(start) else 0.0
44
+ val properties = overrideReading(interval.end).fold(Map.empty[String, String])(_.properties)
45
+ Segment(interval.name, start, end, duration, properties)
46
+
47
+ output match
48
+ case Output.Pending(interval) if interval.name != unclassified =>
49
+ Some(Emission.Started(segment(interval, closed = false)))
50
+ case Output.Closed(interval) if interval.name != unclassified =>
51
+ Some(Emission.Emitted(segment(interval, closed = true)))
114
52
  case _ => None
115
-
116
- private def toPending(island: Island[Reading, Kind]): Segment =
117
- val start = island.first.timestamp
118
- val end = island.last.timestamp
119
- Segment(island.kind._1, start, end, 0.0, cover(island.last))
120
-
121
- private def toSegment(island: Island[Reading, Kind]): Segment =
122
- val start = island.first.timestamp
123
- val end = island.last.timestamp
124
- Segment(island.kind._1, start, end, end.minus(start), cover(island.last))
125
-
126
- private def cover(reading: Reading): Map[String, String] =
127
- overrideReading(reading).fold(Map.empty[String, String])(_.properties)
128
-
129
- object Segmentation:
130
- private type Kind = (String, Int)
131
- private type Evidence = (Option[Island[Reading, Kind]], Reading)
132
- private val unclassified: String = "unclassified"
133
-
134
- private def toIsland(cursor: SegmentCursor): Island[Reading, Kind] =
135
- val first = Reading(cursor.start, Params(Map.empty))
136
- val last = Reading(cursor.end, Params(Map.empty))
137
- Island((cursor.name, 0), first, last)
@@ -0,0 +1,43 @@
1
+ package scada.supervisor.core.segmentation
2
+
3
+ import scada.supervisor.core.{Params, SegmentDef}
4
+
5
+ /** Transitions over classified samples in input order. The coordinate type is
6
+ * chosen by the caller and is never rounded or compared here.
7
+ */
8
+ object Timeline:
9
+ enum Boundary:
10
+ case Live, Observed
11
+
12
+ final case class Interval[+A](name: String, start: A, end: A)
13
+
14
+ enum Event[+A]:
15
+ case Sample(at: A, name: String, continuous: Boolean)
16
+ case DeadlineExpired(at: A)
17
+ case EndOfInput
18
+
19
+ enum Output[+A]:
20
+ case Pending(interval: Interval[A])
21
+ case Closed(interval: Interval[A])
22
+
23
+ final case class Result[A](open: Option[Interval[A]], outputs: Vector[Output[A]])
24
+
25
+ def classifier(definitions: List[SegmentDef]): Params => Option[String] =
26
+ val lookup = (name: String) => definitions.find(_.name == name).map(_.condition)
27
+ params => definitions.find(_.condition.matches(params, lookup)).map(_.name)
28
+
29
+ def step[A](boundary: Boundary, open: Option[Interval[A]], event: Event[A]): Result[A] =
30
+ event match
31
+ case Event.Sample(at, name, continuous) =>
32
+ open match
33
+ case Some(previous) if continuous && previous.name == name =>
34
+ val updated = previous.copy(end = at)
35
+ Result(Some(updated), Vector(Output.Pending(updated)))
36
+ case _ =>
37
+ val next = Interval(name, at, at)
38
+ val closed = open.map: previous =>
39
+ val end = if boundary == Boundary.Live && previous.name != name then at else previous.end
40
+ Output.Closed(previous.copy(end = end))
41
+ Result(Some(next), closed.toVector :+ Output.Pending(next))
42
+ // The existing policies keep the last interval open through silence and finite EOF.
43
+ case Event.DeadlineExpired(_) | Event.EndOfInput => Result(open, Vector.empty)
@@ -10,6 +10,8 @@ import java.net.URLEncoder
10
10
  import java.nio.charset.StandardCharsets
11
11
  import java.time.Instant
12
12
  import scada.supervisor.core.*
13
+ import scada.supervisor.core.segmentation.Timeline
14
+ import scada.supervisor.core.segmentation.Timeline.{Boundary, Event, Interval, Output}
13
15
  import scada.supervisor.infra.config.{AliasMapping, CheckpointApiConfig}
14
16
  import scala.concurrent.duration.*
15
17
 
@@ -42,27 +44,27 @@ object LocalHistory:
42
44
  /** Finite event-time classification: never inject wall-clock silence into past data. */
43
45
  def classify(machine: MachineConfig, points: Vector[Observation], seed: Option[HistorySeed] = None, continuity: Vector[HistoryRange] = Vector.empty): Vector[HistorySegment] =
44
46
  val gap = machine.window.toLong * 2000
45
- val lookup = (name: String) => machine.segments.find(_.name == name).map(_.condition)
47
+ val classifyParams = Timeline.classifier(machine.segments)
46
48
  val groups = points.groupBy(_.time).toVector.sortBy(_._1)
47
49
  val initialSegment = seed.flatMap: initial =>
48
50
  val stored = initial.segment.filter(_.start <= initial.time)
49
- val evaluated = machine.segments.find(_.condition.matches(Params(initial.values),lookup)).map(_.name)
50
- evaluated match
51
+ classifyParams(Params(initial.values)) match
51
52
  case Some(name) => Some(stored.filter(_.name == name).getOrElse(HistorySegment(name,initial.time,initial.time)))
52
53
  case None => stored
53
- groups.foldLeft((seed.fold(Map.empty[String,Double])(_.values),seed.map(_.time),initialSegment.toVector)):
54
- case ((prior,previous,segments),(time,group)) =>
54
+ val initialOpen = initialSegment.map(row => Interval(row.name, row.start, row.end))
55
+ val initial = (seed.fold(Map.empty[String,Double])(_.values), seed.map(_.time), initialOpen, Vector.empty[Interval[Long]])
56
+ val (_, _, open, closed) = groups.foldLeft(initial):
57
+ case ((prior, previous, current, completed), (time, group)) =>
55
58
  val continuous = previous.exists(t => connected(t,time,gap,continuity))
56
59
  val values = (if continuous then prior else Map.empty) ++ group.map(p => p.channel -> p.value)
57
- val name = machine.segments.find(_.condition.matches(Params(values),lookup)).map(_.name)
58
- .orElse(if continuous then segments.lastOption.map(_.name) else None)
59
- val next = name.fold(segments): n =>
60
- segments.lastOption match
61
- case Some(last) if continuous && last.name == n => segments.init :+ last.copy(end = time)
62
- case Some(_) if continuous => segments :+ HistorySegment(n,time,time)
63
- case _ => segments :+ HistorySegment(n,time,time)
64
- (values,Some(time),next)
65
- ._3
60
+ val name = classifyParams(Params(values)).orElse(if continuous then current.map(_.name) else None)
61
+ name match
62
+ case Some(n) =>
63
+ val next = Timeline.step(Boundary.Observed, current, Event.Sample(time, n, continuous))
64
+ val finished = next.outputs.collect { case Output.Closed(row) => row }
65
+ (values, Some(time), next.open, completed ++ finished)
66
+ case None => (values, Some(time), current, completed)
67
+ (closed ++ open).map(row => HistorySegment(row.name, row.start, row.end))
66
68
 
67
69
  def sources(context: Json): Vector[Json] =
68
70
  val current = context.hcursor.get[Vector[Json]]("segments").getOrElse(Vector.empty)