@yarkivaev/scada 2.19.0 → 2.20.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/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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.19.0",
3
+ "version": "2.20.0",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -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
- /** Validate independent raw serial inputs and produce the runtime's device-list ABI. */
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.map(({ path, baud, line }, index) => { return `${name(rows[index])}:${path}:${baud}:${line}`; }).join(',');
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,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,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) { preflight(current, execute); },
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
+ }
@@ -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', '/v1/history/watermark', async (req, res) => {
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
+ }
@@ -56,12 +56,12 @@ export { liveChartValues, liveChartApps } from '../../application/deploy/liveRel
56
56
  export { default as executeConfiguredChartDeployment } from './executeConfiguredChartDeployment.js';
57
57
  export { default as configuredHistorySeed } from './configuredHistorySeed.js';
58
58
  export { centralTelemetryValues, centralTelemetryChartEnv, centralTelemetryEnvironment, centralTelemetryTasks } from './centralTelemetry.js';
59
- export { collectorCommand, collectorPublisherCommand, collectorConsumerTasks, collectorDeviceAssignments, collectorSourceProcesses, mapCollectorRelease, parseSerialSource } from '../../application/deploy/collectorSourcePlan.js';
59
+ export { collectorCommand, collectorPublisherCommand, collectorConsumerTasks, collectorDeviceAssignments, configuredCollectorAssignments, collectorSourceProcesses, mapCollectorRelease, parseSerialSource } from '../../application/deploy/collectorSourcePlan.js';
60
60
  export { default as collectorChartPlan } from './collectorChartPlan.js';
61
61
  export { default as configuredPostgresMaintenance } from './configuredPostgresMaintenance.js';
62
62
  export { default as brokerFleetPolicy } from './brokerFleetPolicy.js';
63
63
  export { publisherBrokerDefinitions, subscriberBrokerDefinitions } from './siteBrokerDefinitions.js';
64
- export { projectRegisterMaps, sharedRegisterBus, rawSerialDeviceList, databaseSourceGroups } from '../../application/deploy/fieldbusSourcePlan.js';
64
+ export { projectRegisterMaps, sharedRegisterBus, rawSerialDeviceList, rawSerialDevices, databaseSourceGroups } from '../../application/deploy/fieldbusSourcePlan.js';
65
65
  export { default as stagedSitePlan } from './stagedSitePlan.js';
66
66
  export { default as topologyGraph } from '../../application/deploy/topologyGraph.js';
67
67
  export { default as edgeDescriptors } from '../../application/deploy/edgeDescriptors.js';
@@ -78,3 +78,5 @@ export { default as configuredArchivePlan } from './configuredArchivePlan.js';
78
78
  export { default as configuredEtcdInventory } from './configuredEtcdInventory.js';
79
79
  export { configuredSiteAssets } from './configuredSiteAssets.js';
80
80
  export { default as configuredBrokerRoutes } from './configuredBrokerRoutes.js';
81
+ export { default as controlPlaneCli } from './controlPlaneCli.js';
82
+ export { default as configuredCollectorChartDeployment } from './configuredCollectorChartDeployment.js';
@@ -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
+ }