@yarkivaev/scada 2.19.0 → 2.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -0
- package/index.js +4 -0
- package/package.json +1 -1
- package/src/application/control/controllerRuntime.js +14 -0
- package/src/application/deploy/collectorProcesses.js +1 -0
- package/src/application/deploy/collectorSourcePlan.js +41 -0
- package/src/application/deploy/compileCollectorTasks.js +2 -2
- package/src/application/deploy/fieldbusSourcePlan.js +17 -3
- package/src/application/runtime/applicationCommand.js +19 -0
- package/src/application/runtime/applicationDrivers.js +109 -0
- package/src/application/runtime/applicationRuntime.js +83 -0
- package/src/application/runtime/collectorLaunch.js +8 -3
- package/src/application/runtime/deploymentApplicationJob.js +34 -0
- package/src/application/runtime/historyPurgeJob.js +14 -0
- package/src/application/runtime/index.js +1 -0
- package/src/application/runtime/runApplication.js +9 -0
- package/src/application/runtime/storageApplicationJob.js +32 -0
- package/src/application/siteRuntime/history.js +2 -2
- package/src/bin/controller.js +3 -7
- package/src/bin/scada.js +7 -2
- package/src/domain/timeline/taggedCycleWindows.js +17 -0
- package/src/domain/timeline/taggedSegment.js +47 -0
- package/src/domain/timeline/taggedTimeline.js +98 -0
- package/src/domain/timeline/timelineSegment.js +25 -0
- package/src/infrastructure/deploy/applicationBundle.js +65 -0
- package/src/infrastructure/deploy/configuredCollectorChartDeployment.js +22 -0
- package/src/infrastructure/deploy/controlPlaneCli.js +17 -0
- package/src/infrastructure/deploy/edgeTelemetryApplication.js +31 -0
- package/src/infrastructure/deploy/executeRelease.js +6 -1
- package/src/infrastructure/deploy/highAvailability/catalogReconciler.js +2 -2
- package/src/infrastructure/deploy/highAvailability/historyWatermark.js +2 -2
- package/src/infrastructure/deploy/highAvailability/index.js +2 -1
- package/src/infrastructure/deploy/highAvailability/replicaHistoryStore.js +7 -0
- package/src/infrastructure/deploy/index.js +6 -3
- package/src/infrastructure/deploy/stagedSitePlan.js +1 -1
- package/src/infrastructure/deploy/verifyRuntimeCapabilities.js +2 -2
- package/src/infrastructure/streams/index.js +1 -0
- package/src/infrastructure/streams/pollSnapshot.js +11 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/ProcessingApp.scala +4 -3
- package/stream-processing/src/main/scala/scada/processing/runtime/RuntimeProfile.scala +11 -0
package/README.md
CHANGED
|
@@ -16,6 +16,32 @@
|
|
|
16
16
|
|
|
17
17
|
For high availability, agents can run collector copies and Stream Worker candidates can share a writer lease. With timeline replication v2, live writes and historical corrections publish committed changes and deletions through a PostgreSQL outbox. See [High availability](docs/architecture/high-availability.md).
|
|
18
18
|
|
|
19
|
+
## Application runtime
|
|
20
|
+
|
|
21
|
+
A trusted application bundle can declare named services and jobs in a runtime YAML document. Run one declaration with `scada run --dsl runtime.yaml --service NAME` or `scada run --dsl runtime.yaml --job NAME`. Arguments after `--` are passed to the selected driver. Services and jobs have separate driver registries. The launcher executes one declaration per process.
|
|
22
|
+
|
|
23
|
+
```yaml
|
|
24
|
+
modules:
|
|
25
|
+
- id: profile
|
|
26
|
+
entry: ./extension.mjs
|
|
27
|
+
services:
|
|
28
|
+
reader:
|
|
29
|
+
driver: core/collector
|
|
30
|
+
config:
|
|
31
|
+
registry:
|
|
32
|
+
$export: profile/collector-registry
|
|
33
|
+
jobs:
|
|
34
|
+
verify:
|
|
35
|
+
driver: core/telemetry
|
|
36
|
+
config:
|
|
37
|
+
command: backfill
|
|
38
|
+
mode: verify
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Module entries are local JS files relative to the declaring runtime document. The default extension export can contain `services`, `jobs`, and named `bindings`. Drivers accept `{ config, args, env, write, file }`. The `core` namespace is reserved for built-in drivers. Extension code runs in the service process with its permissions. Deploy only a bundle from a trusted publisher.
|
|
42
|
+
|
|
43
|
+
The release workflow publishes Node.js and JVM images and records their digests alongside the release revision. The Node image includes `scada-install-app URL SHA256 DESTINATION`, which verifies and extracts an application bundle for read-only mounting. The JVM image loads an optional profile JAR with the class named by `SCADA_RUNTIME_PROFILE`. The application selects compatible image and bundle digests in the deployment.
|
|
44
|
+
|
|
19
45
|
## Package boundary
|
|
20
46
|
|
|
21
47
|
SCADA owns the shared collection and processing engines, storage and APIs. Plant applications supply the deployment DSL, device mappings, business rules, routes and HMI. See the [package boundary](docs/architecture/package-boundary.md).
|
package/index.js
CHANGED
|
@@ -171,3 +171,7 @@ export { default as cycleTimelineFetch } from './src/application/cycleTimelineFe
|
|
|
171
171
|
export { default as textContentCatalog } from './src/application/mcp/textContentCatalog.js';
|
|
172
172
|
export { timelineSegments, measurementBounds, measurementPeaks } from './src/application/timelineMetrics.js';
|
|
173
173
|
export { default as projectPlantShops } from './src/application/projectPlantShops.js';
|
|
174
|
+
export { default as taggedTimeline } from './src/domain/timeline/taggedTimeline.js';
|
|
175
|
+
export { default as taggedSegment } from './src/domain/timeline/taggedSegment.js';
|
|
176
|
+
export { default as timelineSegment } from './src/domain/timeline/timelineSegment.js';
|
|
177
|
+
export { default as taggedCycleWindows } from './src/domain/timeline/taggedCycleWindows.js';
|
package/package.json
CHANGED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { clientFromEnv } from './controlClient.js';
|
|
2
|
+
import controller from './controller.js';
|
|
3
|
+
import controlStore from './controlStore.js';
|
|
4
|
+
|
|
5
|
+
export default function controllerRuntime(env) {
|
|
6
|
+
if (!env.CONTROL_NODE_ID) { throw new Error('CONTROL_NODE_ID required'); }
|
|
7
|
+
const store = controlStore(clientFromEnv(env), env.CONTROL_PREFIX);
|
|
8
|
+
const host = controller(store, env.CONTROL_NODE_ID, {
|
|
9
|
+
clockSkewMs: Number(env.CONTROL_CLOCK_SKEW_MS ?? 5000),
|
|
10
|
+
replacementDelayMs: Number(env.CONTROL_REPLACEMENT_DELAY_MS ?? 30000),
|
|
11
|
+
onError(error) { process.stderr.write(`controller: ${error.name}\n`); }
|
|
12
|
+
});
|
|
13
|
+
for (const signal of ['SIGTERM', 'SIGINT']) { process.once(signal, () => { void host.stop(); }); }
|
|
14
|
+
}
|
|
@@ -38,6 +38,7 @@ export default function collectorProcesses(machines, describe, project) {
|
|
|
38
38
|
});
|
|
39
39
|
return { name: descriptor.name, command: descriptor.command, env: { ...descriptor.env, ...settings.env },
|
|
40
40
|
hostDevices, resources: descriptor.resources,
|
|
41
|
+
...(settings.spec === undefined ? {} : { spec: settings.spec, identity: settings.identity }),
|
|
41
42
|
...(descriptor.image === undefined ? {} : { image: descriptor.image }) };
|
|
42
43
|
});
|
|
43
44
|
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import deploymentTemplate, { deploymentCondition } from '../../infrastructure/deploy/deploymentTemplate.js';
|
|
2
2
|
import expand from './expand.js';
|
|
3
|
+
import compileCollectorTasks from './compileCollectorTasks.js';
|
|
4
|
+
import { deploymentContext } from './deploymentPlan.js';
|
|
3
5
|
import releases from './releases.js';
|
|
4
6
|
import collectorProcesses from './collectorProcesses.js';
|
|
5
7
|
|
|
@@ -86,6 +88,45 @@ export function collectorConsumerTasks(declarations, cluster, bindings, generati
|
|
|
86
88
|
});
|
|
87
89
|
}
|
|
88
90
|
|
|
91
|
+
/**
|
|
92
|
+
* Use the same assignment compiler from rollout, control catalog and collector CLI.
|
|
93
|
+
* Device projections provide typed specs and stable logical identities.
|
|
94
|
+
*/
|
|
95
|
+
export function configuredCollectorAssignments(policy, collect, validateBindings) {
|
|
96
|
+
const settings = {
|
|
97
|
+
rules: policy.adapters, sourceTypes: policy.sourceTypes ?? [], collect,
|
|
98
|
+
compile(processes, generation) { return compileCollectorTasks(processes, {}, generation); }
|
|
99
|
+
};
|
|
100
|
+
const pattern = new RegExp(policy.site.pattern, 'u');
|
|
101
|
+
|
|
102
|
+
function devices(document, selection = {}) {
|
|
103
|
+
return collectorDeviceAssignments(document, selection, settings);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function site(document, server, app, generation = 1) {
|
|
107
|
+
const cluster = server.id;
|
|
108
|
+
const match = pattern.exec(cluster);
|
|
109
|
+
if (!match) { throw new TypeError(`Unknown collector site ${cluster}`); }
|
|
110
|
+
const bindings = deploymentTemplate(policy.site.bindings, { cluster, app, ...match.groups });
|
|
111
|
+
validateBindings?.(bindings);
|
|
112
|
+
const consumers = collectorConsumerTasks(policy.consumers, cluster, bindings, generation);
|
|
113
|
+
const readers = settings.sourceTypes.length ? devices(document, { cluster, generation }) : [];
|
|
114
|
+
return [...readers, ...consumers];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function manifest(document, selection) {
|
|
118
|
+
const { cluster, stream, adapter, generation } = selection;
|
|
119
|
+
if (!pattern.test(cluster ?? '') || stream || adapter) { return devices(document, selection); }
|
|
120
|
+
if (document.edgeControlPlane?.enabled) {
|
|
121
|
+
throw new TypeError('Control-mode assignments are managed through the declarative control catalog');
|
|
122
|
+
}
|
|
123
|
+
const { server, profile } = deploymentContext(document, cluster);
|
|
124
|
+
return site(document, server, profile.apps.scada, generation);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return { devices, site, manifest };
|
|
128
|
+
}
|
|
129
|
+
|
|
89
130
|
/** Project release mappings with an injected fieldbus point decoder. */
|
|
90
131
|
export function mapCollectorRelease(values, decode) {
|
|
91
132
|
const machines = (values.machines || []).map((machine) => {
|
|
@@ -22,10 +22,10 @@ function declaredTasks(input, generation) {
|
|
|
22
22
|
}
|
|
23
23
|
|
|
24
24
|
/** Compile source-derived descriptors to stable assignments or use explicitly declared identities. */
|
|
25
|
-
export default function compileCollectorTasks(input, { describe, identity }, generation = 1) {
|
|
25
|
+
export default function compileCollectorTasks(input, { describe, identity } = {}, generation = 1) {
|
|
26
26
|
if (!Array.isArray(input)) { return declaredTasks(input, generation); }
|
|
27
27
|
return input.map((process) => {
|
|
28
28
|
const spec = process.spec ? structuredClone(process.spec) : describe(process);
|
|
29
|
-
return { taskId: `${spec.adapter}:${digest(identity(spec)).slice(0, 20)}`, generation, specVersion: 1, spec };
|
|
29
|
+
return { taskId: `${spec.adapter}:${digest(process.identity ?? identity(spec)).slice(0, 20)}`, generation, specVersion: 1, spec };
|
|
30
30
|
});
|
|
31
31
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { parseSerialSource } from './collectorSourcePlan.js';
|
|
2
|
+
import serialLine from '../../infrastructure/streams/serialLine.js';
|
|
2
3
|
|
|
3
4
|
function registerOrigin(address) {
|
|
4
5
|
const text = new URL(address).searchParams.get('at');
|
|
@@ -55,8 +56,7 @@ export function sharedRegisterBus(rows, { label, count }) {
|
|
|
55
56
|
return { at, count: size, ports };
|
|
56
57
|
}
|
|
57
58
|
|
|
58
|
-
|
|
59
|
-
export function rawSerialDeviceList(rows, { label, name }) {
|
|
59
|
+
function rawSerialPorts(rows, label) {
|
|
60
60
|
const ports = rows.map(({ from }) => { return parseSerialSource(from); });
|
|
61
61
|
if (new Set(ports.map(({ path }) => { return path; })).size !== ports.length) {
|
|
62
62
|
throw new Error(`duplicate ${label} port`);
|
|
@@ -64,7 +64,21 @@ export function rawSerialDeviceList(rows, { label, name }) {
|
|
|
64
64
|
if (ports.some(({ slave, query }) => { return slave || query.toString(); })) {
|
|
65
65
|
throw new Error(`${label} serial sources cannot specify a Modbus slave or register range`);
|
|
66
66
|
}
|
|
67
|
-
return ports
|
|
67
|
+
return ports;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Validate independent inputs and produce typed serial settings. */
|
|
71
|
+
export function rawSerialDevices(rows, { label, name }) {
|
|
72
|
+
return rawSerialPorts(rows, label).map(({ path, baud, line }, index) => {
|
|
73
|
+
const baudRate = Number(baud);
|
|
74
|
+
if (!Number.isFinite(baudRate) || baudRate <= 0) { throw new Error(`Invalid ${label} baud rate`); }
|
|
75
|
+
return { name: name(rows[index]), path, baudRate, ...serialLine(line) };
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Validate independent raw serial inputs and produce the runtime's device-list ABI. */
|
|
80
|
+
export function rawSerialDeviceList(rows, { label, name }) {
|
|
81
|
+
return rawSerialPorts(rows, label).map(({ path, baud, line }, index) => { return `${name(rows[index])}:${path}:${baud}:${line}`; }).join(',');
|
|
68
82
|
}
|
|
69
83
|
|
|
70
84
|
/** Group stream URLs by database endpoint in source order, ignoring URL query selectors. */
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { parseArgs } from 'node:util';
|
|
2
|
+
import runApplication from './runApplication.js';
|
|
3
|
+
|
|
4
|
+
const options = {
|
|
5
|
+
dsl: { type: 'string' },
|
|
6
|
+
service: { type: 'string' },
|
|
7
|
+
job: { type: 'string' }
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export default async function applicationCommand(argv) {
|
|
11
|
+
const separator = argv.indexOf('--');
|
|
12
|
+
const args = separator < 0 ? [] : argv.slice(separator + 1);
|
|
13
|
+
const { values: { dsl, service, job } } = parseArgs({
|
|
14
|
+
args: separator < 0 ? argv : argv.slice(0, separator), options
|
|
15
|
+
});
|
|
16
|
+
if (Boolean(service) === Boolean(job)) { throw new Error('choose exactly one --service or --job'); }
|
|
17
|
+
if (!dsl) { throw new Error('scada run requires --dsl'); }
|
|
18
|
+
await runApplication(dsl, { kind: service ? 'service' : 'job', name: service ?? job, args });
|
|
19
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { dirname, resolve } from 'node:path';
|
|
2
|
+
|
|
3
|
+
function writeJson(write, value) {
|
|
4
|
+
write(`${JSON.stringify(value)}\n`);
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
async function collector({ config, args, env, write, file, bounded }) {
|
|
8
|
+
const { default: createRegistry } = await import('./createRegistry.js');
|
|
9
|
+
const { default: collectorDslManifest } = await import('./collectorDslManifest.js');
|
|
10
|
+
const { launchCollectorCommand } = await import('./collectorLaunch.js');
|
|
11
|
+
const { registry = createRegistry, manifest = collectorDslManifest(), document, task, ...options } = config;
|
|
12
|
+
const declared = document ? ['--dsl', resolve(dirname(file), document)] : [];
|
|
13
|
+
if (task) { declared.push('--task', task); }
|
|
14
|
+
if ((document && args.includes('--dsl')) || (task && args.includes('--task'))) {
|
|
15
|
+
throw new Error('collector document or task is fixed by the workload');
|
|
16
|
+
}
|
|
17
|
+
return launchCollectorCommand([...declared, ...args], { registry, manifest, ...options, env, write, requireOnce: bounded });
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function postgresRuntime({ config, env, write }) {
|
|
21
|
+
const { verificationSql, ...role } = config;
|
|
22
|
+
if (typeof verificationSql !== 'string' || !verificationSql.trim()) {
|
|
23
|
+
throw new TypeError('postgres-runtime requires verificationSql');
|
|
24
|
+
}
|
|
25
|
+
const { default: prepareRuntimeRole } = await import('../../infrastructure/persistence/pg/prepareRuntimeRole.js');
|
|
26
|
+
try {
|
|
27
|
+
const output = await prepareRuntimeRole(env.POSTGRES_ADMIN_URL, env.POSTGRES_URL, {
|
|
28
|
+
...role, verify(client) { return client.query(verificationSql); }
|
|
29
|
+
});
|
|
30
|
+
writeJson(write, output);
|
|
31
|
+
} catch (error) {
|
|
32
|
+
throw new Error(`PostgreSQL runtime authentication failed (${error.code ?? error.name})`, { cause: error });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function telemetry({ args, config, env, write }) {
|
|
37
|
+
if ((config.command && args.length) || (config.mode && args.length > 1)) {
|
|
38
|
+
throw new Error('telemetry command or mode is fixed by the job');
|
|
39
|
+
}
|
|
40
|
+
const [command = config.command, mode = config.mode, ...rest] = args;
|
|
41
|
+
if (command === 'replay' && !mode) {
|
|
42
|
+
const { default: replay } = await import('../../infrastructure/ingest/telemetry/replayStoredTelemetry.js');
|
|
43
|
+
writeJson(write, await replay(env));
|
|
44
|
+
} else if (command === 'backfill' && !rest.length) {
|
|
45
|
+
const { default: backfill } = await import('../siteRuntime/telemetryBackfillCommand.js');
|
|
46
|
+
await backfill(env, mode, { admission: config.admission, usage: 'scada run --job telemetry' });
|
|
47
|
+
} else {
|
|
48
|
+
throw new TypeError('telemetry requires backfill or replay');
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function site(context) {
|
|
53
|
+
const { default: siteServer } = await import('../siteServer.js');
|
|
54
|
+
const { options, ready } = await context.config.configure(context);
|
|
55
|
+
const running = await siteServer(options);
|
|
56
|
+
await ready?.(running);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export default {
|
|
60
|
+
services: {
|
|
61
|
+
site,
|
|
62
|
+
collector,
|
|
63
|
+
async 'catalog-controller'() {
|
|
64
|
+
const { startCatalogController } = await import('../../infrastructure/deploy/highAvailability/catalogReconciler.js');
|
|
65
|
+
return startCatalogController();
|
|
66
|
+
},
|
|
67
|
+
async controller({ env }) {
|
|
68
|
+
const { default: controllerRuntime } = await import('../control/controllerRuntime.js');
|
|
69
|
+
return controllerRuntime(env);
|
|
70
|
+
},
|
|
71
|
+
async 'supervisor-sink'({ env }) {
|
|
72
|
+
const { default: sink } = await import('../runSupervisorSink.js');
|
|
73
|
+
return sink(env);
|
|
74
|
+
},
|
|
75
|
+
async 'edge-telemetry'(context) {
|
|
76
|
+
const { default: edgeTelemetry } = await import('../../infrastructure/deploy/edgeTelemetryApplication.js');
|
|
77
|
+
return edgeTelemetry(context);
|
|
78
|
+
},
|
|
79
|
+
async 'history-receiver'({ config, env }) {
|
|
80
|
+
const { runHistoryReceiver, replicaHistoryStore } = await import('../../infrastructure/deploy/highAvailability/index.js');
|
|
81
|
+
const { historyOptions, history = (pool, options) => {
|
|
82
|
+
return replicaHistoryStore(pool, { ...historyOptions, ...options });
|
|
83
|
+
}, ...settings } = config;
|
|
84
|
+
return runHistoryReceiver(env, { ...settings, history });
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
jobs: {
|
|
88
|
+
collector(context) { return collector({ ...context, bounded: true }); },
|
|
89
|
+
async 'control-plane'({ config, file, args, env }) {
|
|
90
|
+
const { default: controlPlaneCli } = await import('../../infrastructure/deploy/controlPlaneCli.js');
|
|
91
|
+
const defaultFile = resolve(dirname(file), config.document);
|
|
92
|
+
return controlPlaneCli(config.plan, { defaultFile, defaultTarget: config.target }, args, env);
|
|
93
|
+
},
|
|
94
|
+
'postgres-runtime': postgresRuntime,
|
|
95
|
+
telemetry,
|
|
96
|
+
async 'history-purge'(context) {
|
|
97
|
+
const { default: purge } = await import('./historyPurgeJob.js');
|
|
98
|
+
return purge(context);
|
|
99
|
+
},
|
|
100
|
+
async deployment(context) {
|
|
101
|
+
const { default: execute } = await import('./deploymentApplicationJob.js');
|
|
102
|
+
return execute(context);
|
|
103
|
+
},
|
|
104
|
+
async storage(context) {
|
|
105
|
+
const { default: execute } = await import('./storageApplicationJob.js');
|
|
106
|
+
return execute(context);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { dirname, extname, resolve } from 'node:path';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import readDocumentFile from '../deploy/readDocumentFile.js';
|
|
5
|
+
|
|
6
|
+
const identifier = z.string().regex(/^[a-z0-9][a-z0-9-]*$/u);
|
|
7
|
+
const qualified = /^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/u;
|
|
8
|
+
const workload = z.strictObject({
|
|
9
|
+
driver: z.string().regex(qualified),
|
|
10
|
+
config: z.record(z.string(), z.unknown()).default({}),
|
|
11
|
+
args: z.array(z.string()).default([])
|
|
12
|
+
});
|
|
13
|
+
const runtimeDocument = z.strictObject({
|
|
14
|
+
modules: z.array(z.strictObject({ id: identifier, entry: z.string().min(1) })).default([]),
|
|
15
|
+
services: z.record(identifier, workload).default({}),
|
|
16
|
+
jobs: z.record(identifier, workload).default({})
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
function moduleEntries(modules) {
|
|
20
|
+
const entries = new Map();
|
|
21
|
+
for (const { id, entry } of modules) {
|
|
22
|
+
if (id === 'core' || entries.has(id)) { throw new Error(`reserved or duplicate module ${id}`); }
|
|
23
|
+
if (!['.js', '.mjs'].includes(extname(entry)) || /^[a-z]+:/iu.test(entry)) {
|
|
24
|
+
throw new Error(`module ${id} must name a local JavaScript file`);
|
|
25
|
+
}
|
|
26
|
+
entries.set(id, entry);
|
|
27
|
+
}
|
|
28
|
+
return entries;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function moduleResolver(file, entries, core) {
|
|
32
|
+
const moduleCache = new Map([['core', Promise.resolve(core)]]);
|
|
33
|
+
return (id) => {
|
|
34
|
+
if (!moduleCache.has(id)) {
|
|
35
|
+
const entry = entries.get(id);
|
|
36
|
+
if (!entry) { throw new Error(`unknown module ${id}`); }
|
|
37
|
+
const url = pathToFileURL(resolve(dirname(file), entry));
|
|
38
|
+
moduleCache.set(id, import(url).then(({ default: extension }) => {
|
|
39
|
+
if (!extension || typeof extension !== 'object') {
|
|
40
|
+
throw new TypeError(`module ${id} requires a default extension export`);
|
|
41
|
+
}
|
|
42
|
+
return extension;
|
|
43
|
+
}));
|
|
44
|
+
}
|
|
45
|
+
return moduleCache.get(id);
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function resolveExport(name, field, load) {
|
|
50
|
+
if (typeof name !== 'string' || !qualified.test(name)) { throw new TypeError(`invalid ${field} reference`); }
|
|
51
|
+
const [module, key] = name.split('/');
|
|
52
|
+
const values = (await load(module))[field];
|
|
53
|
+
if (!values || !Object.hasOwn(values, key)) { throw new Error(`unknown ${field} reference ${name}`); }
|
|
54
|
+
return values[key];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function configuration(value, load) {
|
|
58
|
+
if (Array.isArray(value)) { return Promise.all(value.map((item) => { return configuration(item, load); })); }
|
|
59
|
+
if (!value || typeof value !== 'object') { return value; }
|
|
60
|
+
if (Object.keys(value).length === 1 && Object.hasOwn(value, '$export')) {
|
|
61
|
+
return resolveExport(value.$export, 'bindings', load);
|
|
62
|
+
}
|
|
63
|
+
const entries = await Promise.all(Object.entries(value).map(async ([key, item]) => {
|
|
64
|
+
return [key, await configuration(item, load)];
|
|
65
|
+
}));
|
|
66
|
+
return Object.fromEntries(entries);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Execute exactly one service or job declared by a trusted application bundle. */
|
|
70
|
+
export default async function applicationRuntime(file, { kind, name, args = [] }, {
|
|
71
|
+
core, env = process.env, write = (body) => { process.stdout.write(body); }
|
|
72
|
+
}) {
|
|
73
|
+
if (!['service', 'job'].includes(kind)) { throw new TypeError('expected service or job'); }
|
|
74
|
+
const { modules, services, jobs } = runtimeDocument.parse(readDocumentFile(file));
|
|
75
|
+
const declarations = kind === 'service' ? services : jobs;
|
|
76
|
+
if (!Object.hasOwn(declarations, name)) { throw new Error(`unknown ${kind} ${name}`); }
|
|
77
|
+
const selected = declarations[name];
|
|
78
|
+
const load = moduleResolver(file, moduleEntries(modules), core);
|
|
79
|
+
const driver = await resolveExport(selected.driver, `${kind}s`, load);
|
|
80
|
+
if (typeof driver !== 'function') { throw new TypeError(`driver ${selected.driver} must be a function`); }
|
|
81
|
+
const config = await configuration(selected.config, load);
|
|
82
|
+
return driver({ config, args: [...selected.args, ...args], env, write, file });
|
|
83
|
+
}
|
|
@@ -3,9 +3,10 @@ import collectorOptions from './collectorOptions.js';
|
|
|
3
3
|
import controlDeliveryEnvironment from './controlDeliveryEnvironment.js';
|
|
4
4
|
|
|
5
5
|
/** Run a live or bounded manifest while preserving the same reload path. */
|
|
6
|
-
export async function collectorLaunch(options, registry, manifest, { run = runCollector, env = process.env } = {}) {
|
|
6
|
+
export async function collectorLaunch(options, registry, manifest, { run = runCollector, env = process.env, requireOnce = false } = {}) {
|
|
7
7
|
if (env.COLLECTOR_MANIFEST || env.COLLECTOR_MANIFEST_PATH) { throw new TypeError('Choose DSL or compiled manifest, not both'); }
|
|
8
8
|
const initial = manifest(options);
|
|
9
|
+
if (requireOnce && initial.execution?.mode !== 'once') { throw new Error('collector jobs require an explicit one-shot task'); }
|
|
9
10
|
if (options.render) {
|
|
10
11
|
for (const { spec } of initial.assignments) {
|
|
11
12
|
// Match runtime validation order and stop on the first invalid assignment.
|
|
@@ -23,12 +24,16 @@ export async function collectorLaunch(options, registry, manifest, { run = runCo
|
|
|
23
24
|
/** Run the collector command with the application's registry and manifest bindings. */
|
|
24
25
|
export async function launchCollectorCommand(argv, {
|
|
25
26
|
registry, manifest, delivery, env = process.env, run = runCollector,
|
|
27
|
+
requireOnce = false,
|
|
26
28
|
write = (body) => { process.stdout.write(body); }
|
|
27
29
|
}) {
|
|
28
30
|
controlDeliveryEnvironment(env, delivery);
|
|
29
31
|
const adapters = registry();
|
|
30
32
|
if (argv.some((arg) => { return arg.startsWith('--'); })) {
|
|
31
|
-
const result = await collectorLaunch(collectorOptions(argv), adapters, manifest, { run, env });
|
|
33
|
+
const result = await collectorLaunch(collectorOptions(argv), adapters, manifest, { run, env, requireOnce });
|
|
32
34
|
if (result) { write(`${JSON.stringify(result, null, 2)}\n`); }
|
|
33
|
-
} else {
|
|
35
|
+
} else {
|
|
36
|
+
if (requireOnce) { throw new Error('collector jobs require explicit DSL selection'); }
|
|
37
|
+
await run({ registry: adapters, env, argv });
|
|
38
|
+
}
|
|
34
39
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import readDeploymentDocument from '../deploy/readDeploymentDocument.js';
|
|
4
|
+
|
|
5
|
+
const options = { document: { type: 'string' }, 'backend-only': { type: 'boolean' } };
|
|
6
|
+
|
|
7
|
+
function input([target, action, cluster, artifact], { positionals, values }, config) {
|
|
8
|
+
if (!target || !Object.hasOwn(config.targets, target) || positionals.length > 4) {
|
|
9
|
+
throw new Error('deployment requires a declared target and accepts [action] [cluster] [artifact]');
|
|
10
|
+
}
|
|
11
|
+
const policy = config.targets[target] ?? {};
|
|
12
|
+
if (values['backend-only'] && !policy.backendOnly) { throw new Error(`--backend-only is unavailable for ${target}`); }
|
|
13
|
+
if (values.document && !policy.document) { throw new Error(`--document is unavailable for ${target}`); }
|
|
14
|
+
if (artifact && !policy.artifact) { throw new Error(`artifact is unavailable for ${target}`); }
|
|
15
|
+
return { target, action: action ?? config.action ?? 'render', cluster, artifact, policy };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Dispatch configured deployment commands with evidence and scope kept explicit. */
|
|
19
|
+
export default async function deploymentApplicationJob({ args, config, write }) {
|
|
20
|
+
const parsed = parseArgs({ args, options, allowPositionals: true });
|
|
21
|
+
const { target, action, cluster, artifact, policy } = input(parsed.positionals, parsed, config);
|
|
22
|
+
const document = parsed.values.document ? readDeploymentDocument(parsed.values.document) : undefined;
|
|
23
|
+
const handler = policy.actions && Object.hasOwn(policy.actions, action) ? policy.actions[action] : undefined;
|
|
24
|
+
if (handler) {
|
|
25
|
+
write(`${JSON.stringify(await handler({ cluster, document }))}\n`);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
const evidence = policy.artifact === 'evidence' && artifact ? JSON.parse(readFileSync(artifact, 'utf8')) : undefined;
|
|
29
|
+
const output = await config.run(target, action === 'plan' ? 'plan' : 'deploy', {
|
|
30
|
+
cluster, action, document, evidence, backendOnly: parsed.values['backend-only'],
|
|
31
|
+
release: policy.artifact === 'release' ? artifact : undefined
|
|
32
|
+
});
|
|
33
|
+
if (action === 'plan') { write(`${JSON.stringify(output, null, 2)}\n`); } else if (output) { write(output); }
|
|
34
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Run the configured history maintenance request from a bounded job. */
|
|
2
|
+
export default async function historyPurgeJob({ config, env }) {
|
|
3
|
+
if (!env.HISTORY_URL || !env.HISTORY_TOKEN || !config.machine) {
|
|
4
|
+
throw new Error('history purge requires HISTORY_URL, HISTORY_TOKEN and a machine selector');
|
|
5
|
+
}
|
|
6
|
+
const endpoint = new URL('v1/history/purge', `${env.HISTORY_URL.replace(/\/$/u, '')}/`);
|
|
7
|
+
const response = await fetch(endpoint, {
|
|
8
|
+
method: 'POST',
|
|
9
|
+
signal: AbortSignal.timeout(config.timeoutMs ?? 240000),
|
|
10
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${env.HISTORY_TOKEN}` },
|
|
11
|
+
body: JSON.stringify({ machine: config.machine })
|
|
12
|
+
});
|
|
13
|
+
if (!response.ok) { throw new Error(`History purge failed: ${response.status}`); }
|
|
14
|
+
}
|
|
@@ -15,3 +15,4 @@ export { default as controlDeliveryEnvironment } from './controlDeliveryEnvironm
|
|
|
15
15
|
export { default as embeddedCollectors } from './embeddedCollectors.js';
|
|
16
16
|
export { collectorLaunch, launchCollectorCommand } from './collectorLaunch.js';
|
|
17
17
|
export { default as pagedDelivery } from './pagedDelivery.js';
|
|
18
|
+
export { default as runApplication } from './runApplication.js';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import applicationRuntime from './applicationRuntime.js';
|
|
3
|
+
import core from './applicationDrivers.js';
|
|
4
|
+
|
|
5
|
+
/** Start one workload from an application manifest and the built-in capability registry. */
|
|
6
|
+
export default function runApplication(file, selection, { env, write } = {}) {
|
|
7
|
+
const path = file instanceof URL ? fileURLToPath(file) : file;
|
|
8
|
+
return applicationRuntime(path, selection, { core, env, write });
|
|
9
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
function argument(declaration, raw) {
|
|
4
|
+
const value = raw ?? declaration.default;
|
|
5
|
+
if (value === undefined) { return undefined; }
|
|
6
|
+
if (declaration.type === 'json-file') { return JSON.parse(readFileSync(value, 'utf8')); }
|
|
7
|
+
if (declaration.type === 'number') {
|
|
8
|
+
const number = Number(value);
|
|
9
|
+
if (!Number.isFinite(number)) { throw new TypeError(`invalid number for ${declaration.key}`); }
|
|
10
|
+
return number;
|
|
11
|
+
}
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Execute declared maintenance operations, mapping positional values to typed parameters. */
|
|
16
|
+
export default async function storageApplicationJob({ args, config, write }) {
|
|
17
|
+
const [command, target, action, ...values] = args;
|
|
18
|
+
if (!target || !Object.hasOwn(config.operations, command)) {
|
|
19
|
+
throw new Error('storage requires a declared operation and a target');
|
|
20
|
+
}
|
|
21
|
+
const { run, defaultAction, parameters = [], errorSummary } = config.operations[command];
|
|
22
|
+
if (values.length > parameters.length) { throw new Error(`too many arguments for storage operation ${command}`); }
|
|
23
|
+
const options = Object.fromEntries(parameters.map((declaration, index) => {
|
|
24
|
+
return [declaration.key, argument(declaration, values[index])];
|
|
25
|
+
}));
|
|
26
|
+
try {
|
|
27
|
+
write(`${JSON.stringify(await run(target, action ?? defaultAction, options))}\n`);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if (!errorSummary) { throw error; }
|
|
30
|
+
throw new Error(`${errorSummary}: ${error.code ?? error.name}`, { cause: error });
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -8,8 +8,8 @@ export function historyCapabilities(role, requiredProtocol = historyProtocol) {
|
|
|
8
8
|
return { role, historyProtocols };
|
|
9
9
|
}
|
|
10
10
|
|
|
11
|
-
export function capabilityExit(role, requiredProtocol) {
|
|
12
|
-
if (
|
|
11
|
+
export function capabilityExit(role, requiredProtocol, argv = process.argv) {
|
|
12
|
+
if (argv.includes('--capabilities')) {
|
|
13
13
|
process.stdout.write(`${JSON.stringify(historyCapabilities(role, requiredProtocol))}\n`);
|
|
14
14
|
process.exit(0);
|
|
15
15
|
}
|
package/src/bin/controller.js
CHANGED
|
@@ -1,8 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
const store = controlStore(clientFromEnv(process.env), process.env.CONTROL_PREFIX);
|
|
6
|
-
const host = controller(store, process.env.CONTROL_NODE_ID, { clockSkewMs: Number(process.env.CONTROL_CLOCK_SKEW_MS ?? 5000), replacementDelayMs: Number(process.env.CONTROL_REPLACEMENT_DELAY_MS ?? 30000), onError(error) { process.stderr.write(`controller: ${error.name}\n`); } });
|
|
7
|
-
for (const signal of ['SIGTERM', 'SIGINT']) { process.once(signal, () => { void host.stop(); }); }
|
|
8
|
-
} catch (error) { process.stderr.write(`controller: ${error.name}\n`); process.exitCode = 1; }
|
|
2
|
+
import controllerRuntime from '../application/control/controllerRuntime.js';
|
|
3
|
+
|
|
4
|
+
try { controllerRuntime(process.env); } catch (error) { process.stderr.write(`controller: ${error.name}\n`); process.exitCode = 1; }
|
package/src/bin/scada.js
CHANGED
|
@@ -16,6 +16,8 @@ const usage = `Usage:
|
|
|
16
16
|
scada logs COMPONENT --context NAME [--tail LINES]
|
|
17
17
|
scada plan --context NAME
|
|
18
18
|
scada apply --context NAME
|
|
19
|
+
scada run --dsl PATH --service NAME [-- ARGUMENTS]
|
|
20
|
+
scada run --dsl PATH --job NAME [-- ARGUMENTS]
|
|
19
21
|
|
|
20
22
|
Client options: --server URL (or SCADA_SERVER), --output text|json
|
|
21
23
|
Client credential: SCADA_TOKEN
|
|
@@ -127,8 +129,11 @@ async function serve(args) {
|
|
|
127
129
|
|
|
128
130
|
const args = process.argv.slice(2);
|
|
129
131
|
try {
|
|
130
|
-
if (args.length === 0 || args.includes('--help') || args[0] === 'help') {
|
|
132
|
+
if (args.length === 0 || (args[0] !== 'run' && args.includes('--help')) || args[0] === 'help') {
|
|
131
133
|
process.stdout.write(usage);
|
|
134
|
+
} else if (args[0] === 'run') {
|
|
135
|
+
const { default: applicationCommand } = await import('../application/runtime/applicationCommand.js');
|
|
136
|
+
await applicationCommand(args.slice(1));
|
|
132
137
|
} else if (args[0] === 'serve') {
|
|
133
138
|
await serve(args.slice(1));
|
|
134
139
|
} else {
|
|
@@ -136,5 +141,5 @@ try {
|
|
|
136
141
|
}
|
|
137
142
|
} catch (error) {
|
|
138
143
|
process.stderr.write(`scada: ${error.message}\n`);
|
|
139
|
-
process.exitCode = 1;
|
|
144
|
+
process.exitCode = Number.isInteger(error.status) && error.status > 0 ? error.status : 1;
|
|
140
145
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Resolve cycles intersecting a half-open window using configured start and stop tags. */
|
|
2
|
+
export default function taggedCycleWindows(timeline, range, { start, stops }) {
|
|
3
|
+
const from = new Date(range.from).getTime();
|
|
4
|
+
const to = new Date(range.to).getTime();
|
|
5
|
+
const now = range.now === undefined ? Date.now() : new Date(range.now).getTime();
|
|
6
|
+
const windowEnd = Math.min(to, now);
|
|
7
|
+
const starts = timeline.anchorStarts(start, -1, Number.MAX_SAFE_INTEGER);
|
|
8
|
+
return starts.flatMap((cycleStart, index) => {
|
|
9
|
+
const nextStart = starts[index + 1];
|
|
10
|
+
const nextStop = Math.min(...stops.map((tag) => {
|
|
11
|
+
return timeline.anchorStarts(tag, cycleStart, Number.MAX_SAFE_INTEGER)[0] ?? Infinity;
|
|
12
|
+
}));
|
|
13
|
+
const closedEnd = Math.min(nextStart > cycleStart ? nextStart : Infinity, nextStop);
|
|
14
|
+
const end = Math.min(closedEnd, windowEnd);
|
|
15
|
+
return end > from && cycleStart < windowEnd ? [{ start: cycleStart, end, open: closedEnd > windowEnd }] : [];
|
|
16
|
+
});
|
|
17
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import timelineSegment from './timelineSegment.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Parses tag names from timeline segment tags JSON string.
|
|
5
|
+
*
|
|
6
|
+
* @param {string|undefined} raw - tags JSON string from persistence
|
|
7
|
+
* @returns {Array<string>} tag names
|
|
8
|
+
*/
|
|
9
|
+
function parseTags(raw) {
|
|
10
|
+
if (!raw) {
|
|
11
|
+
return [];
|
|
12
|
+
}
|
|
13
|
+
if (typeof raw !== 'string') {
|
|
14
|
+
throw new Error('segment tags must be a JSON string from timeline');
|
|
15
|
+
}
|
|
16
|
+
const parsed = JSON.parse(raw);
|
|
17
|
+
if (!Array.isArray(parsed)) {
|
|
18
|
+
throw new Error('segment tags JSON must decode to an array');
|
|
19
|
+
}
|
|
20
|
+
return parsed;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Immutable tagged timeline segment with anchor tag checks.
|
|
25
|
+
*
|
|
26
|
+
* @param {object} row - segment with ISO timestamps and tags JSON string
|
|
27
|
+
* @returns {object} tagged segment with segment, tags, has
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* const item = taggedSegment({ start: '2026-01-01T00:00:00.000Z', end: '2026-01-01T01:00:00.000Z', tags: '["ready"]' });
|
|
31
|
+
* item.has('ready');
|
|
32
|
+
*/
|
|
33
|
+
export default function taggedSegment(row) {
|
|
34
|
+
const base = timelineSegment(row);
|
|
35
|
+
const names = parseTags(row.tags);
|
|
36
|
+
return {
|
|
37
|
+
segment() {
|
|
38
|
+
return base;
|
|
39
|
+
},
|
|
40
|
+
tags() {
|
|
41
|
+
return names;
|
|
42
|
+
},
|
|
43
|
+
has(name) {
|
|
44
|
+
return names.includes(name);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import taggedSegment from './taggedSegment.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Sorts tagged segments by start time ascending.
|
|
5
|
+
*
|
|
6
|
+
* @param {object} left - left tagged segment
|
|
7
|
+
* @param {object} right - right tagged segment
|
|
8
|
+
* @returns {number} sort order
|
|
9
|
+
*/
|
|
10
|
+
function sortByStart(left, right) {
|
|
11
|
+
return left.segment().startMs() - right.segment().startMs();
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Sorts anchor start times ascending.
|
|
16
|
+
*
|
|
17
|
+
* @param {number} left - left start time
|
|
18
|
+
* @param {number} right - right start time
|
|
19
|
+
* @returns {number} sort order
|
|
20
|
+
*/
|
|
21
|
+
function sortStarts(left, right) {
|
|
22
|
+
return left - right;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Ordered collection of tagged segments for anchor-based derivation.
|
|
27
|
+
*
|
|
28
|
+
* @param {Array<object>} rows - raw timeline segments
|
|
29
|
+
* @returns {object} timeline with anchorStarts, firstAtOrAfter, operationStarts
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* const timeline = taggedTimeline([{ start: '2026-01-01T00:00:00.000Z', end: '2026-01-01T01:00:00.000Z', tags: '["inspection"]' }]);
|
|
33
|
+
* timeline.anchorStarts('inspection', -1, Number.MAX_SAFE_INTEGER);
|
|
34
|
+
*/
|
|
35
|
+
export default function taggedTimeline(rows) {
|
|
36
|
+
const items = [];
|
|
37
|
+
const source = rows || [];
|
|
38
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
39
|
+
items.push(taggedSegment(source[index]));
|
|
40
|
+
}
|
|
41
|
+
items.sort(sortByStart);
|
|
42
|
+
return {
|
|
43
|
+
/**
|
|
44
|
+
* Returns sorted anchor start times inside half-open bounds.
|
|
45
|
+
*
|
|
46
|
+
* @param {string} tag - anchor tag name
|
|
47
|
+
* @param {number} after - exclusive lower bound in epoch ms
|
|
48
|
+
* @param {number} before - exclusive upper bound in epoch ms
|
|
49
|
+
* @returns {Array<number>} anchor start times in epoch ms
|
|
50
|
+
*/
|
|
51
|
+
anchorStarts(tag, after, before) {
|
|
52
|
+
const times = [];
|
|
53
|
+
for (let index = 0; index < items.length; index += 1) {
|
|
54
|
+
const item = items[index];
|
|
55
|
+
if (item.has(tag)) {
|
|
56
|
+
const start = item.segment().startMs();
|
|
57
|
+
if (start > after && start < before) {
|
|
58
|
+
times.push(start);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
times.sort(sortStarts);
|
|
63
|
+
return times;
|
|
64
|
+
},
|
|
65
|
+
/**
|
|
66
|
+
* Returns first start time at or after bound.
|
|
67
|
+
*
|
|
68
|
+
* @param {Array<number>} starts - sorted start times in epoch ms
|
|
69
|
+
* @param {number} bound - inclusive lower bound in epoch ms
|
|
70
|
+
* @returns {number|undefined} first matching start time
|
|
71
|
+
*/
|
|
72
|
+
firstAtOrAfter(starts, bound) {
|
|
73
|
+
for (let index = 0; index < starts.length; index += 1) {
|
|
74
|
+
if (starts[index] >= bound) {
|
|
75
|
+
return starts[index];
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return undefined;
|
|
79
|
+
},
|
|
80
|
+
/**
|
|
81
|
+
* Returns ISO start timestamps for segments intersecting a cycle window.
|
|
82
|
+
*
|
|
83
|
+
* @param {number} cycleStart - inclusive cycle start in epoch ms
|
|
84
|
+
* @param {number} cycleEnd - exclusive cycle end in epoch ms
|
|
85
|
+
* @returns {Array<string>} segment start ISO timestamps
|
|
86
|
+
*/
|
|
87
|
+
operationStarts(cycleStart, cycleEnd) {
|
|
88
|
+
const starts = [];
|
|
89
|
+
for (let index = 0; index < items.length; index += 1) {
|
|
90
|
+
const item = items[index];
|
|
91
|
+
if (item.segment().intersects(cycleStart, cycleEnd)) {
|
|
92
|
+
starts.push(new Date(item.segment().startMs()).toISOString());
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return starts;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Immutable timeline segment with half-open time bounds.
|
|
3
|
+
*
|
|
4
|
+
* @param {object} row - segment with ISO start and end timestamps
|
|
5
|
+
* @returns {object} segment with startMs, endMs, intersects
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const item = timelineSegment({ start: '2026-01-01T00:00:00.000Z', end: '2026-01-01T01:00:00.000Z' });
|
|
9
|
+
* item.intersects(0, Date.parse('2026-01-01T00:30:00.000Z'));
|
|
10
|
+
*/
|
|
11
|
+
export default function timelineSegment(row) {
|
|
12
|
+
const start = new Date(row.start).getTime();
|
|
13
|
+
const end = new Date(row.end).getTime();
|
|
14
|
+
return {
|
|
15
|
+
startMs() {
|
|
16
|
+
return start;
|
|
17
|
+
},
|
|
18
|
+
endMs() {
|
|
19
|
+
return end;
|
|
20
|
+
},
|
|
21
|
+
intersects(windowStart, windowEnd) {
|
|
22
|
+
return end > windowStart && start < windowEnd;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
const volumeName = 'scada-application';
|
|
2
|
+
const installerName = 'install-scada-application';
|
|
3
|
+
const installPath = '/opt/scada/app';
|
|
4
|
+
const installUser = 1000;
|
|
5
|
+
const pinnedImage = /^[a-z0-9][a-z0-9_.:/-]*(?::[a-zA-Z0-9_.-]+)?@sha256:[a-f0-9]{64}$/u;
|
|
6
|
+
const dnsName = /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/u;
|
|
7
|
+
|
|
8
|
+
/** Validate a complete immutable installation input before building a release. */
|
|
9
|
+
export function applicationBundle({ image, url, sha256, tokenSecret }) {
|
|
10
|
+
const source = URL.canParse(url) ? new URL(url) : null;
|
|
11
|
+
if (!source || source.protocol !== 'https:' || source.username || source.password || source.search || source.hash) {
|
|
12
|
+
throw new TypeError('Application bundle requires an HTTPS URL without embedded credentials, query or fragment');
|
|
13
|
+
}
|
|
14
|
+
if (!/^[a-f0-9]{64}$/u.test(sha256)) { throw new TypeError('Application bundle requires a SHA-256 digest'); }
|
|
15
|
+
if (!pinnedImage.test(image)) { throw new TypeError('Application bundle installer requires a digest-pinned image'); }
|
|
16
|
+
if (tokenSecret && (!dnsName.test(tokenSecret.name) || tokenSecret.name.length > 253
|
|
17
|
+
|| !/^[a-zA-Z0-9._-]+$/u.test(tokenSecret.key ?? '') || !['Authorization', 'Deploy-Token'].includes(tokenSecret.header))) {
|
|
18
|
+
throw new TypeError('Application bundle token requires a Secret name, key and supported HTTP header');
|
|
19
|
+
}
|
|
20
|
+
return { image, url, sha256, tokenSecret };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function installer(bundle) {
|
|
24
|
+
const { image, url, sha256, tokenSecret } = bundle;
|
|
25
|
+
return {
|
|
26
|
+
name: installerName, image, imagePullPolicy: 'IfNotPresent',
|
|
27
|
+
command: ['scada-install-app'], args: [url, sha256, installPath],
|
|
28
|
+
...(tokenSecret && { env: [
|
|
29
|
+
{ name: 'SCADA_APP_BUNDLE_TOKEN', valueFrom: { secretKeyRef: { name: tokenSecret.name, key: tokenSecret.key } } },
|
|
30
|
+
{ name: 'SCADA_APP_BUNDLE_TOKEN_HEADER', value: tokenSecret.header }
|
|
31
|
+
] }),
|
|
32
|
+
securityContext: { runAsNonRoot: true, runAsUser: installUser, runAsGroup: installUser, allowPrivilegeEscalation: false,
|
|
33
|
+
capabilities: { drop: ['ALL'] } },
|
|
34
|
+
volumeMounts: [{ name: volumeName, mountPath: installPath }]
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function projectContainer(container, { image, mountPath = installPath, subPath, env = [], volumeMounts, ...runtime }) {
|
|
39
|
+
if (!pinnedImage.test(image)) { throw new TypeError('Application runtime requires a digest-pinned image'); }
|
|
40
|
+
const mounts = volumeMounts ?? container.volumeMounts ?? [];
|
|
41
|
+
if (mounts.some((mount) => { return mount.name === volumeName || mount.mountPath === mountPath; })) {
|
|
42
|
+
throw new Error('Application bundle mount conflicts with a container volume');
|
|
43
|
+
}
|
|
44
|
+
return { ...container, ...runtime, image, env: [...(container.env ?? []), ...env],
|
|
45
|
+
volumeMounts: [...mounts, { name: volumeName, mountPath, ...(subPath && { subPath }), readOnly: true }] };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Mount one verified application bundle into the explicitly selected containers in a Pod spec. */
|
|
49
|
+
export function projectApplicationBundle(pod, bundle, select) {
|
|
50
|
+
let selected = false;
|
|
51
|
+
const containers = pod.containers.map((container) => {
|
|
52
|
+
const runtime = select(container);
|
|
53
|
+
if (!runtime) { return container; }
|
|
54
|
+
selected = true;
|
|
55
|
+
return projectContainer(container, runtime);
|
|
56
|
+
});
|
|
57
|
+
if (!selected) { return pod; }
|
|
58
|
+
const { volumes = [], initContainers = [], securityContext = {} } = pod;
|
|
59
|
+
if (volumes.some(({ name }) => { return name === volumeName; }) || initContainers.some(({ name }) => { return name === installerName; })) {
|
|
60
|
+
throw new Error('Application bundle conflicts with existing Pod setup');
|
|
61
|
+
}
|
|
62
|
+
return { ...pod, containers, initContainers: [installer(bundle), ...initContainers],
|
|
63
|
+
volumes: [...volumes, { name: volumeName, emptyDir: {} }],
|
|
64
|
+
securityContext: { fsGroup: installUser, fsGroupChangePolicy: 'OnRootMismatch', ...securityContext } };
|
|
65
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import publicBrokerPlan from './publicBrokerPlan.js';
|
|
3
|
+
import executeConfiguredChartDeployment from './executeConfiguredChartDeployment.js';
|
|
4
|
+
import { brokerPolicy } from './securityPolicy.js';
|
|
5
|
+
|
|
6
|
+
/** Apply the common broker preparation, preflight and reconciliation around a collector chart. */
|
|
7
|
+
export default function configuredCollectorChartDeployment(policy, { chartRoot, resolveSecurity, plan, preflight, reconcile }) {
|
|
8
|
+
return function deploy(action, execute = execFileSync, cluster = policy.defaultTarget, inputSecurity = null, document = null) {
|
|
9
|
+
let broker;
|
|
10
|
+
return executeConfiguredChartDeployment(policy, action, {
|
|
11
|
+
chartRoot, execute,
|
|
12
|
+
create() {
|
|
13
|
+
const security = resolveSecurity(action, cluster, execute, inputSecurity);
|
|
14
|
+
broker = brokerPolicy(security);
|
|
15
|
+
const compiled = plan(cluster, document, security);
|
|
16
|
+
return { plan: action === 'render' ? publicBrokerPlan(compiled) : compiled, bindings: { security, broker } };
|
|
17
|
+
},
|
|
18
|
+
preflight(current, kube) { preflight(current, execute, kube); },
|
|
19
|
+
afterReady(current, kube) { reconcile(current, kube, broker, execute); }
|
|
20
|
+
});
|
|
21
|
+
};
|
|
22
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { writeSync } from 'node:fs';
|
|
2
|
+
import { clientFromEnv, controlStore, publishCatalog } from '../../application/control/index.js';
|
|
3
|
+
import publishControlCatalog from '../../application/control/publishControlCatalog.js';
|
|
4
|
+
import readDeploymentDocument from '../../application/deploy/readDeploymentDocument.js';
|
|
5
|
+
|
|
6
|
+
/** Render or publish the configured control catalog from a deployment document. */
|
|
7
|
+
export default async function controlPlaneCli(planFor, { defaultTarget, defaultFile }, argv = process.argv.slice(2), env = process.env) {
|
|
8
|
+
const [operation = 'plan', target = defaultTarget, file = defaultFile] = argv;
|
|
9
|
+
if (!['plan', 'catalog', 'publish'].includes(operation)) { throw new TypeError('Expected plan, catalog or publish'); }
|
|
10
|
+
const plan = planFor(target, readDeploymentDocument(file));
|
|
11
|
+
let result = operation === 'catalog' ? plan.catalog : plan;
|
|
12
|
+
if (operation === 'publish') {
|
|
13
|
+
const store = controlStore(clientFromEnv(env), env.CONTROL_PREFIX ?? plan.values.prefix);
|
|
14
|
+
result = await publishControlCatalog(plan, store, publishCatalog);
|
|
15
|
+
}
|
|
16
|
+
writeSync(1, `${JSON.stringify(result, null, 2)}\n`);
|
|
17
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import edgeTelemetryRuntime from '../ingest/telemetry/edgeTelemetryRuntime.js';
|
|
2
|
+
import { capabilityExit, historySettings } from '../../application/siteRuntime/history.js';
|
|
3
|
+
import { processTelemetryIngest } from '../../application/siteRuntime/telemetry.js';
|
|
4
|
+
|
|
5
|
+
function required(env, name) {
|
|
6
|
+
if (!env[name]) { throw new Error(`${name} is required for edge telemetry`); }
|
|
7
|
+
return env[name];
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Start a dedicated reader with an optional history port supplied by an extension. */
|
|
11
|
+
export default async function edgeTelemetryApplication({ env, config, args }) {
|
|
12
|
+
const { history, protocol } = config;
|
|
13
|
+
capabilityExit('telemetry', protocol, args);
|
|
14
|
+
const settings = historySettings(env, protocol);
|
|
15
|
+
await edgeTelemetryRuntime({
|
|
16
|
+
clickhouse: {
|
|
17
|
+
url: required(env, 'CLICKHOUSE_URL'), username: required(env, 'CLICKHOUSE_USER'), password: required(env, 'CLICKHOUSE_PASSWORD')
|
|
18
|
+
},
|
|
19
|
+
broker: required(env, 'AMQP_URL'),
|
|
20
|
+
queues: [required(env, 'AMQP_METRICS_QUEUE'), ...(settings ? JSON.parse(env.HISTORY_LEGACY_QUEUES ?? '[]') : [])],
|
|
21
|
+
...(settings && {
|
|
22
|
+
postgres: required(env, 'POSTGRES_URL'),
|
|
23
|
+
history(client, pool) { return history(client, pool, settings); }
|
|
24
|
+
}),
|
|
25
|
+
createInput: processTelemetryIngest,
|
|
26
|
+
inputOptions: {
|
|
27
|
+
size: Number(env.BATCH_SIZE || 256), prefetch: Number(env.AMQP_PREFETCH || 512), maxWaitMs: Number(env.BATCH_WAIT_MS || 1000)
|
|
28
|
+
},
|
|
29
|
+
port: Number(env.TELEMETRY_HEALTH_PORT || 9093)
|
|
30
|
+
});
|
|
31
|
+
}
|
|
@@ -31,6 +31,9 @@ function validate(plan, action) {
|
|
|
31
31
|
|| plan.podsAbsentBeforeApply.some((selector) => {
|
|
32
32
|
return typeof selector !== 'string' || !/^[A-Za-z0-9_./-]+=[A-Za-z0-9_.-]+(?:,[A-Za-z0-9_./-]+=[A-Za-z0-9_.-]+)*$/u.test(selector);
|
|
33
33
|
}))) { throw new Error('podsAbsentBeforeApply requires exact equality label selectors'); }
|
|
34
|
+
if (plan.transformManifests !== undefined && typeof plan.transformManifests !== 'function') {
|
|
35
|
+
throw new TypeError('transformManifests must be a function');
|
|
36
|
+
}
|
|
34
37
|
if (plan.beforeApply !== undefined && typeof plan.beforeApply !== 'function') {
|
|
35
38
|
throw new Error('beforeApply must be a function');
|
|
36
39
|
}
|
|
@@ -97,8 +100,9 @@ function applyRelease(plan, action, kube, manifests) {
|
|
|
97
100
|
}
|
|
98
101
|
|
|
99
102
|
export function renderRelease(plan, execute = execFileSync) {
|
|
100
|
-
|
|
103
|
+
const manifests = execute('helm', ['template', plan.release, plan.chart, '--namespace', plan.namespace, '-f', '-'],
|
|
101
104
|
{ input: JSON.stringify(plan.values), encoding: 'utf8' });
|
|
105
|
+
return plan.transformManifests ? plan.transformManifests(manifests) : manifests;
|
|
102
106
|
}
|
|
103
107
|
|
|
104
108
|
/**
|
|
@@ -109,6 +113,7 @@ export function renderRelease(plan, execute = execFileSync) {
|
|
|
109
113
|
* selector: "app=label" }; callers bind these to the old declarative app. They are
|
|
110
114
|
* removed after preflight and before any writes, with no selected pods remaining.
|
|
111
115
|
* podsAbsentBeforeApply equality selectors must have no pods before any mutation.
|
|
116
|
+
* transformManifests(manifests) projects the same Helm output for all actions.
|
|
112
117
|
* beforeApply(plan, kube) provides caller-owned live gates; throwing stops writes.
|
|
113
118
|
* afterReady(plan, kube) runs after a successful apply.
|
|
114
119
|
*/
|
|
@@ -43,7 +43,7 @@ async function brokerFederation(record, rules) {
|
|
|
43
43
|
central: process.env.CONTROL_CENTRAL_BUS || 'amqp://central.invalid' }, rules);
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
-
function
|
|
46
|
+
export function startCatalogController() {
|
|
47
47
|
if (!process.env.CONTROL_NODE_ID || !process.env.CONTROL_CATALOG_FILE) { throw new Error('Catalog reconciler requires a node id and catalog file'); }
|
|
48
48
|
const catalog = JSON.parse(fs.readFileSync(process.env.CONTROL_CATALOG_FILE, 'utf8'));
|
|
49
49
|
const rules = process.env.CONTROL_CLASSIFY_RULES && JSON.parse(fs.readFileSync(process.env.CONTROL_CLASSIFY_RULES, 'utf8'));
|
|
@@ -57,5 +57,5 @@ function start() {
|
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
if (process.argv[1] && existsSync(process.argv[1]) && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
|
|
60
|
-
try {
|
|
60
|
+
try { startCatalogController(); } catch (error) { process.stderr.write(`catalog reconciler: ${error.name}\n`); process.exitCode = 1; }
|
|
61
61
|
}
|
|
@@ -27,8 +27,8 @@ export function watermark(history, pool) {
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
/** GET /v1/history/watermark for the restored home's classify loop. */
|
|
30
|
-
export function watermarkRoute(history) {
|
|
31
|
-
return route('GET',
|
|
30
|
+
export function watermarkRoute(history, basePath = '/v1') {
|
|
31
|
+
return route('GET', `${basePath}/history/watermark`, async (req, res) => {
|
|
32
32
|
jsonResponse(await watermark(history)).send(res);
|
|
33
33
|
});
|
|
34
34
|
}
|
|
@@ -10,6 +10,7 @@ export { reconcileBrokerThroughController } from './reconcileBrokerThroughContro
|
|
|
10
10
|
export { reconciliationBundle } from './reconciliationBundle.js';
|
|
11
11
|
export { acceptEpoch, admitWriter, applyReplica, readyToLead, restored } from './supervisorReplica.js';
|
|
12
12
|
export { default as runHistoryReceiver, segmentCollector } from './historyReceiver.js';
|
|
13
|
-
export { fromPool as replicaWatermarkFromPool, watermark as replicaWatermark } from './historyWatermark.js';
|
|
13
|
+
export { fromPool as replicaWatermarkFromPool, watermark as replicaWatermark, watermarkRoute as replicaWatermarkRoute } from './historyWatermark.js';
|
|
14
14
|
export { default as segmentAdmit, grantedEpoch } from './segmentAdmit.js';
|
|
15
15
|
export { default as configuredBrokerReconciliation } from './configuredBrokerReconciliation.js';
|
|
16
|
+
export { default as replicaHistoryStore } from './replicaHistoryStore.js';
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import historyPg from '../../persistence/pg/history.js';
|
|
2
|
+
import { fromPool } from './historyWatermark.js';
|
|
3
|
+
|
|
4
|
+
/** Attach the replica watermark to the shared history store for a configured receiver. */
|
|
5
|
+
export default function replicaHistoryStore(pool, options) {
|
|
6
|
+
return { ...historyPg(pool, options), watermark() { return fromPool(pool); } };
|
|
7
|
+
}
|
|
@@ -22,6 +22,7 @@ export { default as readDocument } from '../../application/deploy/readDocument.j
|
|
|
22
22
|
export { default as expand } from '../../application/deploy/expand.js';
|
|
23
23
|
export { deploymentKube, readKube, verifyKubeNode, preserveKubeRestart } from './deploymentKube.js';
|
|
24
24
|
export { default as executeRelease } from './executeRelease.js';
|
|
25
|
+
export { applicationBundle, projectApplicationBundle } from './applicationBundle.js';
|
|
25
26
|
export { default as verifyCollectorCoverage } from './verifyCollectorCoverage.js';
|
|
26
27
|
export { default as verifyPeerBrokerPerimeter } from './verifyPeerBrokerPerimeter.js';
|
|
27
28
|
export { default as preflightKubeStorage } from './preflightKubeStorage.js';
|
|
@@ -40,7 +41,7 @@ export { default as clickhouseTelemetryPolicy } from './clickhouseTelemetryPolic
|
|
|
40
41
|
export { default as compileControlCatalog, matchesDeviceInput, scopeControlSecrets } from '../../application/deploy/compileControlCatalog.js';
|
|
41
42
|
export { default as projectControlPlane } from '../../application/deploy/projectControlPlane.js';
|
|
42
43
|
export { brokerUri, brokerEndpoint, attachBrokerMesh, brokerStreamRoutes, brokerStreamBindings, brokerStreams, brokerPeerOutboxes, brokerOutboxes, brokerShovel, appendBrokerResources, brokerSinkOptions } from './brokerTopology.js';
|
|
43
|
-
export { default as deploymentTemplate } from './deploymentTemplate.js';
|
|
44
|
+
export { default as deploymentTemplate, deploymentCondition } from './deploymentTemplate.js';
|
|
44
45
|
export { default as deploymentRecovery } from './deploymentRecovery.js';
|
|
45
46
|
export { default as kioskDeployment } from '../management/kiosk/kioskDeployment.js';
|
|
46
47
|
export { default as compileCollectorTasks, portableCollectorSpec } from '../../application/deploy/compileCollectorTasks.js';
|
|
@@ -56,12 +57,12 @@ export { liveChartValues, liveChartApps } from '../../application/deploy/liveRel
|
|
|
56
57
|
export { default as executeConfiguredChartDeployment } from './executeConfiguredChartDeployment.js';
|
|
57
58
|
export { default as configuredHistorySeed } from './configuredHistorySeed.js';
|
|
58
59
|
export { centralTelemetryValues, centralTelemetryChartEnv, centralTelemetryEnvironment, centralTelemetryTasks } from './centralTelemetry.js';
|
|
59
|
-
export { collectorCommand, collectorPublisherCommand, collectorConsumerTasks, collectorDeviceAssignments, collectorSourceProcesses, mapCollectorRelease, parseSerialSource } from '../../application/deploy/collectorSourcePlan.js';
|
|
60
|
+
export { collectorCommand, collectorPublisherCommand, collectorConsumerTasks, collectorDeviceAssignments, configuredCollectorAssignments, collectorSourceProcesses, mapCollectorRelease, parseSerialSource } from '../../application/deploy/collectorSourcePlan.js';
|
|
60
61
|
export { default as collectorChartPlan } from './collectorChartPlan.js';
|
|
61
62
|
export { default as configuredPostgresMaintenance } from './configuredPostgresMaintenance.js';
|
|
62
63
|
export { default as brokerFleetPolicy } from './brokerFleetPolicy.js';
|
|
63
64
|
export { publisherBrokerDefinitions, subscriberBrokerDefinitions } from './siteBrokerDefinitions.js';
|
|
64
|
-
export { projectRegisterMaps, sharedRegisterBus, rawSerialDeviceList, databaseSourceGroups } from '../../application/deploy/fieldbusSourcePlan.js';
|
|
65
|
+
export { projectRegisterMaps, sharedRegisterBus, rawSerialDeviceList, rawSerialDevices, databaseSourceGroups } from '../../application/deploy/fieldbusSourcePlan.js';
|
|
65
66
|
export { default as stagedSitePlan } from './stagedSitePlan.js';
|
|
66
67
|
export { default as topologyGraph } from '../../application/deploy/topologyGraph.js';
|
|
67
68
|
export { default as edgeDescriptors } from '../../application/deploy/edgeDescriptors.js';
|
|
@@ -78,3 +79,5 @@ export { default as configuredArchivePlan } from './configuredArchivePlan.js';
|
|
|
78
79
|
export { default as configuredEtcdInventory } from './configuredEtcdInventory.js';
|
|
79
80
|
export { configuredSiteAssets } from './configuredSiteAssets.js';
|
|
80
81
|
export { default as configuredBrokerRoutes } from './configuredBrokerRoutes.js';
|
|
82
|
+
export { default as controlPlaneCli } from './controlPlaneCli.js';
|
|
83
|
+
export { default as configuredCollectorChartDeployment } from './configuredCollectorChartDeployment.js';
|
|
@@ -36,7 +36,7 @@ function buildSiteState(context, policy, ports) {
|
|
|
36
36
|
const controlCatalog = document.edgeControlPlane?.enabled ? ports.catalog(cluster, document) : null;
|
|
37
37
|
const brokerEnvironment = broker && broker.phase !== 'prepare' && brokerClientEnvironment(broker);
|
|
38
38
|
const peers = peerResources(context, policy);
|
|
39
|
-
const authorizationJob = ports.authorizationJob(target.namespace, app);
|
|
39
|
+
const authorizationJob = ports.authorizationJob(target.namespace, app, cluster);
|
|
40
40
|
const address = nodeAddress(server, policy.target.address);
|
|
41
41
|
return { ...context, assignments, controlCatalog, brokerEnvironment, nodeAddress: address,
|
|
42
42
|
kiosk: ports.kioskPlan(cluster, address, profile.kiosk),
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { execFileSync } from 'node:child_process';
|
|
2
2
|
|
|
3
|
-
function capabilities({ image, role, entrypoint, args = [] }, subject, execute) {
|
|
3
|
+
function capabilities({ image, role, entrypoint, args = [], runArgs = [] }, subject, execute) {
|
|
4
4
|
let result;
|
|
5
5
|
try {
|
|
6
6
|
const options = { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 120000 };
|
|
7
|
-
const output = execute('docker', ['run', '--rm', '--read-only', '--network=none', '--tmpfs', '/tmp', '--entrypoint', entrypoint, image, ...args], options);
|
|
7
|
+
const output = execute('docker', ['run', '--rm', '--read-only', '--network=none', '--tmpfs', '/tmp', ...runArgs, '--entrypoint', entrypoint, image, ...args], options);
|
|
8
8
|
result = JSON.parse(String(output));
|
|
9
9
|
} catch {
|
|
10
10
|
throw new Error(`Unable to verify ${subject} ${role} candidate`);
|
|
@@ -18,3 +18,4 @@ export { default as namedSerialDevices } from './namedSerialDevices.js';
|
|
|
18
18
|
export { default as boundedTextFrames } from './boundedTextFrames.js';
|
|
19
19
|
export { default as windowPublication } from './windowPublication.js';
|
|
20
20
|
export { default as watchCurrentReading } from './watchCurrentReading.js';
|
|
21
|
+
export { default as pollSnapshot } from './pollSnapshot.js';
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Periodically read and apply a snapshot, with at most one poll in flight. */
|
|
2
|
+
export default function pollSnapshot({ read, apply, onError, intervalMs }) {
|
|
3
|
+
let running = false;
|
|
4
|
+
const timer = setInterval(() => {
|
|
5
|
+
if (running) { return; }
|
|
6
|
+
running = true;
|
|
7
|
+
Promise.resolve().then(read).then(apply).catch(onError).finally(() => { running = false; });
|
|
8
|
+
}, intervalMs);
|
|
9
|
+
timer.unref();
|
|
10
|
+
return { stop() { clearInterval(timer); } };
|
|
11
|
+
}
|
|
@@ -2,7 +2,8 @@ package scada.processing.runtime
|
|
|
2
2
|
|
|
3
3
|
import cats.effect.{ExitCode, IO, IOApp}
|
|
4
4
|
|
|
5
|
-
/**
|
|
5
|
+
/** Entry point for the configured runtime profile or the built-in rules-based worker. */
|
|
6
6
|
object ProcessingApp extends IOApp:
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
def run(args: List[String]): IO[ExitCode] =
|
|
8
|
+
IO.delay(RuntimeProfile.load(sys.env.get("SCADA_RUNTIME_PROFILE"), getClass.getClassLoader))
|
|
9
|
+
.flatMap(profile => ProcessingApplication(profile).run(args))
|
|
@@ -28,3 +28,14 @@ trait RuntimeProfile:
|
|
|
28
28
|
|
|
29
29
|
object RuntimeProfile:
|
|
30
30
|
val default: RuntimeProfile = new RuntimeProfile {}
|
|
31
|
+
|
|
32
|
+
private[runtime] def load(className: Option[String], loader: ClassLoader): RuntimeProfile =
|
|
33
|
+
className.fold(default): name =>
|
|
34
|
+
try
|
|
35
|
+
Class.forName(name, false, loader).asSubclass(classOf[RuntimeProfile]).getConstructor().newInstance()
|
|
36
|
+
catch
|
|
37
|
+
case error @ (_: ReflectiveOperationException | _: ClassCastException | _: LinkageError) =>
|
|
38
|
+
throw IllegalArgumentException(
|
|
39
|
+
s"Cannot load SCADA_RUNTIME_PROFILE '$name': expected a RuntimeProfile class with a public no-argument constructor",
|
|
40
|
+
error
|
|
41
|
+
)
|