@yarkivaev/scada 2.17.0 → 2.19.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.
Files changed (132) hide show
  1. package/index.js +14 -2
  2. package/package.json +5 -2
  3. package/src/application/cycleTimelineFetch.js +56 -0
  4. package/src/application/deploy/collectorSourcePlan.js +97 -0
  5. package/src/application/deploy/compileCollectorTasks.js +31 -0
  6. package/src/application/deploy/compileControlCatalog.js +66 -0
  7. package/src/application/deploy/controlPlan.js +16 -0
  8. package/src/application/deploy/controlPlaneConfiguration.js +62 -0
  9. package/src/application/deploy/controlReaderSpecs.js +37 -0
  10. package/src/application/deploy/edgeDescriptors.js +31 -0
  11. package/src/application/deploy/fieldbusSourcePlan.js +79 -0
  12. package/src/application/deploy/liveReleaseOverlay.js +17 -0
  13. package/src/application/deploy/plantBindingProfile.js +24 -0
  14. package/src/application/deploy/projectControlPlane.js +48 -0
  15. package/src/application/deploy/projectTopology.js +41 -0
  16. package/src/application/deploy/topologyGraph.js +81 -0
  17. package/src/application/edgeOperatorCatalog.js +9 -7
  18. package/src/application/mcp/analyticsMcpPort.js +20 -0
  19. package/src/application/mcp/analyticsNamespaceNodes.js +29 -0
  20. package/src/application/mcp/analyticsTextContent.js +13 -0
  21. package/src/application/mcp/plantReadPorts.js +168 -0
  22. package/src/application/mcp/textContentCatalog.js +7 -0
  23. package/src/application/operationPrefixes.js +67 -0
  24. package/src/application/operatorCatalogView.js +8 -0
  25. package/src/application/projectPlantShops.js +17 -0
  26. package/src/application/runtime/collectorDslManifest.js +44 -0
  27. package/src/application/runtime/collectorLaunch.js +34 -0
  28. package/src/application/runtime/collectorOptions.js +21 -0
  29. package/src/application/runtime/controlDeliveryEnvironment.js +19 -0
  30. package/src/application/runtime/embeddedCollectors.js +6 -0
  31. package/src/application/runtime/index.js +7 -1
  32. package/src/application/runtime/pagedDelivery.js +87 -0
  33. package/src/application/runtime/resolveSecrets.js +9 -0
  34. package/src/application/siteOperatorCatalog.js +8 -7
  35. package/src/application/siteRuntime/checkpointedOperationPoll.js +77 -0
  36. package/src/application/siteRuntime/cutoverOperations.js +25 -0
  37. package/src/application/siteRuntime/databaseMigrations.js +27 -0
  38. package/src/application/siteRuntime/edgeMetricsStore.js +35 -0
  39. package/src/application/siteRuntime/history.js +29 -0
  40. package/src/application/siteRuntime/index.js +16 -0
  41. package/src/application/siteRuntime/measurementTopic.js +9 -0
  42. package/src/application/siteRuntime/operationFederation.js +15 -0
  43. package/src/application/siteRuntime/operationSnapshot.js +18 -0
  44. package/src/application/siteRuntime/operatorField.js +49 -0
  45. package/src/application/siteRuntime/operatorUpdates.js +37 -0
  46. package/src/application/siteRuntime/telemetry.js +31 -0
  47. package/src/application/siteRuntime/telemetryBackfillCommand.js +64 -0
  48. package/src/application/timelineMetrics.js +36 -0
  49. package/src/domain/timeline/cyclePhases.js +191 -0
  50. package/src/infrastructure/deploy/brokerFleetPolicy.js +91 -0
  51. package/src/infrastructure/deploy/brokerReplicaTopology.js +34 -12
  52. package/src/infrastructure/deploy/brokerSecurity.js +89 -0
  53. package/src/infrastructure/deploy/brokerSecurityInput.js +85 -0
  54. package/src/infrastructure/deploy/brokerTopology.js +125 -0
  55. package/src/infrastructure/deploy/centralTelemetry.js +51 -0
  56. package/src/infrastructure/deploy/clickhouseTelemetryPolicy.js +64 -0
  57. package/src/infrastructure/deploy/collectorChartPlan.js +68 -0
  58. package/src/infrastructure/deploy/configuredArchivePlan.js +25 -0
  59. package/src/infrastructure/deploy/configuredBrokerRoutes.js +34 -0
  60. package/src/infrastructure/deploy/configuredClassification.js +74 -0
  61. package/src/infrastructure/deploy/configuredControlPlane.js +116 -0
  62. package/src/infrastructure/deploy/configuredDeploymentCredentials.js +45 -0
  63. package/src/infrastructure/deploy/configuredEtcdInventory.js +30 -0
  64. package/src/infrastructure/deploy/configuredHistorySeed.js +54 -0
  65. package/src/infrastructure/deploy/configuredPostgresMaintenance.js +23 -0
  66. package/src/infrastructure/deploy/configuredRuntimeCapabilities.js +14 -0
  67. package/src/infrastructure/deploy/configuredSiteAssets.js +50 -0
  68. package/src/infrastructure/deploy/configuredStagedDeployment.js +48 -0
  69. package/src/infrastructure/deploy/databaseSecurity.js +39 -0
  70. package/src/infrastructure/deploy/deploymentRecovery.js +49 -0
  71. package/src/infrastructure/deploy/deploymentTemplate.js +67 -0
  72. package/src/infrastructure/deploy/executeConfiguredChartDeployment.js +65 -0
  73. package/src/infrastructure/deploy/executeManagedDeployment.js +46 -0
  74. package/src/infrastructure/deploy/highAvailability/brokerOwnership.js +19 -0
  75. package/src/infrastructure/deploy/highAvailability/catalogReconciler.js +61 -0
  76. package/src/infrastructure/deploy/highAvailability/classifyFederation.js +57 -0
  77. package/src/infrastructure/deploy/highAvailability/classifyGate.js +114 -0
  78. package/src/infrastructure/deploy/highAvailability/classifyLoop.js +139 -0
  79. package/src/infrastructure/deploy/highAvailability/classifyShovels.js +70 -0
  80. package/src/infrastructure/deploy/highAvailability/classifyWatermark.js +45 -0
  81. package/src/infrastructure/deploy/highAvailability/compileClassifierRules.js +21 -0
  82. package/src/infrastructure/deploy/highAvailability/configuredBrokerReconciliation.js +21 -0
  83. package/src/infrastructure/deploy/highAvailability/controllerReconcile.js +14 -0
  84. package/src/infrastructure/deploy/highAvailability/historyReceiver.js +49 -0
  85. package/src/infrastructure/deploy/highAvailability/historyWatermark.js +42 -0
  86. package/src/infrastructure/deploy/highAvailability/index.js +15 -0
  87. package/src/infrastructure/deploy/highAvailability/reconcileBrokerThroughController.js +18 -0
  88. package/src/infrastructure/deploy/highAvailability/reconciliationBundle.js +28 -0
  89. package/src/infrastructure/deploy/highAvailability/segmentAdmit.js +24 -0
  90. package/src/infrastructure/deploy/highAvailability/segmentPublish.js +27 -0
  91. package/src/infrastructure/deploy/highAvailability/supervisorReplica.js +36 -0
  92. package/src/infrastructure/deploy/index.js +46 -2
  93. package/src/infrastructure/deploy/mixedStoreHistory.js +27 -0
  94. package/src/infrastructure/deploy/projectClassification.js +42 -0
  95. package/src/infrastructure/deploy/publicBrokerPlan.js +15 -0
  96. package/src/infrastructure/deploy/securityPolicy.js +16 -0
  97. package/src/infrastructure/deploy/siteBrokerDefinitions.js +97 -0
  98. package/src/infrastructure/deploy/stagedSitePlan.js +132 -0
  99. package/src/infrastructure/deploy/supervisedServicePlan.js +82 -0
  100. package/src/infrastructure/http/edge/attachClassify.js +30 -0
  101. package/src/infrastructure/http/edge/classifyProxy.js +72 -0
  102. package/src/infrastructure/http/edge/classifyRecord.js +32 -0
  103. package/src/infrastructure/http/edge/classifyRouting.js +14 -0
  104. package/src/infrastructure/http/edge/siteAccess.js +7 -0
  105. package/src/infrastructure/http/edge/writeGuard.js +84 -0
  106. package/src/infrastructure/http/plant/routes/machineOperationList.js +18 -0
  107. package/src/infrastructure/http/plant/routes/operationRoute.js +2 -11
  108. package/src/infrastructure/http/plant/routes/operatorRoute.js +25 -0
  109. package/src/infrastructure/http/plant/streams/operationStream.js +25 -37
  110. package/src/infrastructure/ingest/mqtt/modbusDeviceSpec.js +5 -28
  111. package/src/infrastructure/ingest/mqtt/registerPoint.js +2 -2
  112. package/src/infrastructure/ingest/telemetry/centralPolicy.js +29 -8
  113. package/src/infrastructure/management/kiosk/kioskDeployment.js +60 -0
  114. package/src/infrastructure/mdmesh/adminReconciliation.js +19 -0
  115. package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +47 -0
  116. package/src/infrastructure/mdmesh/controllerOperation.js +17 -0
  117. package/src/infrastructure/mdmesh/index.js +5 -0
  118. package/src/infrastructure/mdmesh/mdmeshServerRelease.js +58 -0
  119. package/src/infrastructure/mdmesh/publishApk.js +30 -0
  120. package/src/infrastructure/messaging/rabbitmq/definitions.js +12 -6
  121. package/src/infrastructure/opcua/projectSources.js +36 -0
  122. package/src/infrastructure/persistence/clickhouse/metricBursts.js +73 -0
  123. package/src/infrastructure/persistence/pg/cyclePhaseQuery.js +168 -0
  124. package/src/infrastructure/persistence/pg/cyclePrior.js +96 -0
  125. package/src/infrastructure/persistence/pg/operatorFieldStore.js +50 -0
  126. package/src/infrastructure/streams/boundedTextFrames.js +27 -0
  127. package/src/infrastructure/streams/framedSerialSource.js +25 -0
  128. package/src/infrastructure/streams/index.js +5 -0
  129. package/src/infrastructure/streams/namedSerialDevices.js +26 -0
  130. package/src/infrastructure/streams/serialLine.js +26 -0
  131. package/src/infrastructure/streams/watchCurrentReading.js +31 -0
  132. package/src/infrastructure/streams/windowPublication.js +73 -0
package/index.js CHANGED
@@ -49,8 +49,7 @@ export { default as clickhouseConnection } from './src/infrastructure/persistenc
49
49
  export { rawMetricsRange as clickhouseMetricsRawRange } from './src/infrastructure/persistence/clickhouse/metricsRelation.js';
50
50
  export { rawMetricsRelation as clickhouseMetricsRawRelation } from './src/infrastructure/persistence/clickhouse/metricsRelation.js';
51
51
  export { default as clickhouseMetricsRelation } from './src/infrastructure/persistence/clickhouse/metricsRelation.js';
52
- export const centralTelemetryVersion = 4;
53
- export { default as centralTelemetryPolicy } from './src/infrastructure/ingest/telemetry/centralPolicy.js';
52
+ export { default as centralTelemetryPolicy, centralTelemetryVersion } from './src/infrastructure/ingest/telemetry/centralPolicy.js';
54
53
  export { default as clickhouseSensor } from './src/infrastructure/persistence/clickhouse/sensor.js';
55
54
  export { default as postgresPool, holdClient as holdPostgresClient, openPostgresPool } from './src/infrastructure/persistence/postgresPool.js';
56
55
  export { metricsSinkFromPool as pgMetricsSink } from './src/infrastructure/persistence/pg/metrics.js';
@@ -159,3 +158,16 @@ export { default as executeKubeSeed } from './src/infrastructure/deploy/executeK
159
158
  export { default as edgeTelemetryRuntime } from './src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js';
160
159
  export { default as kubeServiceAccount } from './src/infrastructure/management/kubeServiceAccount.js';
161
160
  export * from './src/infrastructure/deploy/index.js';
161
+ export { default as plantReadPorts } from './src/application/mcp/plantReadPorts.js';
162
+ export { default as analyticsMcpPort } from './src/application/mcp/analyticsMcpPort.js';
163
+ export { default as analyticsNamespaceNodes } from './src/application/mcp/analyticsNamespaceNodes.js';
164
+ export { default as analyticsTextContent } from './src/application/mcp/analyticsTextContent.js';
165
+ export { modbusFloat } from './src/infrastructure/ingest/mqtt/registerPoint.js';
166
+ export { default as cyclePrior } from './src/infrastructure/persistence/pg/cyclePrior.js';
167
+ export { default as cyclePhaseQuery } from './src/infrastructure/persistence/pg/cyclePhaseQuery.js';
168
+ export { default as operationPrefixes } from './src/application/operationPrefixes.js';
169
+ export { default as cyclePhases } from './src/domain/timeline/cyclePhases.js';
170
+ export { default as cycleTimelineFetch } from './src/application/cycleTimelineFetch.js';
171
+ export { default as textContentCatalog } from './src/application/mcp/textContentCatalog.js';
172
+ export { timelineSegments, measurementBounds, measurementPeaks } from './src/application/timelineMetrics.js';
173
+ export { default as projectPlantShops } from './src/application/projectPlantShops.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.17.0",
3
+ "version": "2.19.0",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -22,7 +22,10 @@
22
22
  "./streams": "./src/infrastructure/streams/index.js",
23
23
  "./control": "./src/application/control/index.js",
24
24
  "./mdmesh": "./src/infrastructure/mdmesh/index.js",
25
- "./deployment": "./src/infrastructure/deploy/index.js"
25
+ "./deployment": "./src/infrastructure/deploy/index.js",
26
+ "./deployment/high-availability": "./src/infrastructure/deploy/highAvailability/index.js",
27
+ "./site/runtime": "./src/application/siteRuntime/index.js",
28
+ "./http/site-access": "./src/infrastructure/http/edge/siteAccess.js"
26
29
  },
27
30
  "bin": {
28
31
  "modbus-to-mqtt": "./src/bin/modbus-to-mqtt.js",
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Sorts timeline rows by start time ascending.
3
+ *
4
+ * @param {object} leftRow - left timeline row
5
+ * @param {object} rightRow - right timeline row
6
+ * @returns {number} sort order
7
+ */
8
+ function sortByStartTime(leftRow, rightRow) {
9
+ return leftRow.start_time.getTime() - rightRow.start_time.getTime();
10
+ }
11
+
12
+ /**
13
+ * Merges timeline rows by start time without duplicates.
14
+ *
15
+ * @param {Array<object>} left - first timeline row batch
16
+ * @param {Array<object>} right - second timeline row batch
17
+ * @returns {Array<object>} sorted unique rows
18
+ */
19
+ function mergeSegmentRows(left, right) {
20
+ const seen = new Set();
21
+ const merged = [];
22
+ const all = left.concat(right);
23
+ all.sort(sortByStartTime);
24
+ for (let index = 0; index < all.length; index += 1) {
25
+ const row = all[index];
26
+ const key = row.start_time.toISOString();
27
+ if (!seen.has(key)) {
28
+ seen.add(key);
29
+ merged.push(row);
30
+ }
31
+ }
32
+ return merged;
33
+ }
34
+
35
+ /**
36
+ * Loads timeline rows needed to derive cycles intersecting a query window.
37
+ *
38
+ * @param {object} timeline - machine timeline with list method
39
+ * @param {object} range - query window with from and to Date values
40
+ * @returns {Promise<Array<object>>} rows spanning cycle anchors before from
41
+ *
42
+ * @example
43
+ * const rows = await cycleTimelineFetch(machine.timeline, { from, to });
44
+ */
45
+ export default async function cycleTimelineFetch(timeline, range, lookbackMs) {
46
+ const lookbackFrom = new Date(range.from.getTime() - lookbackMs);
47
+ const beforeRows = await timeline.list({
48
+ from: lookbackFrom.toISOString(),
49
+ to: range.from.toISOString()
50
+ });
51
+ const windowRows = await timeline.list({
52
+ from: range.from.toISOString(),
53
+ to: range.to.toISOString()
54
+ });
55
+ return mergeSegmentRows(beforeRows, windowRows);
56
+ }
@@ -0,0 +1,97 @@
1
+ import deploymentTemplate, { deploymentCondition } from '../../infrastructure/deploy/deploymentTemplate.js';
2
+ import expand from './expand.js';
3
+ import releases from './releases.js';
4
+ import collectorProcesses from './collectorProcesses.js';
5
+
6
+ function sourceScheme(from) {
7
+ const text = String(from);
8
+ const mark = text.indexOf('://');
9
+ return mark < 0 ? '' : text.slice(0, mark);
10
+ }
11
+
12
+ function sourceRule(from, name, rules) {
13
+ const scheme = sourceScheme(from);
14
+ return rules.find((rule) => {
15
+ return (rule.scheme === undefined || rule.scheme === scheme)
16
+ && (rule.suffix === undefined || String(name).endsWith(rule.suffix))
17
+ && (rule.leaf === undefined || String(name).split('/').at(-1) === rule.leaf);
18
+ });
19
+ }
20
+
21
+ function invocation(policy, args, bindings, dsl = policy.dsl) {
22
+ return deploymentTemplate([...policy.cli, '--dsl', dsl, ...args], bindings);
23
+ }
24
+
25
+ /** Build a declared protocol's publisher invocation. */
26
+ export function collectorPublisherCommand(adapter, policy) {
27
+ return invocation(policy, policy.publishers[adapter], {});
28
+ }
29
+
30
+ /** Build a collector CLI invocation by matching the first declared source rule. */
31
+ export function collectorCommand(from, name, policy) {
32
+ const scheme = sourceScheme(from);
33
+ if (!scheme) { throw new Error(`plant collector address ${from} has no scheme`); }
34
+ const selected = sourceRule(from, name, policy.commands);
35
+ if (!selected) { throw new Error(`plant collector has no command for ${scheme} at ${name}`); }
36
+ return selected.publisher ? collectorPublisherCommand(selected.publisher, policy) : invocation(policy, selected.args, { name }, selected.dsl);
37
+ }
38
+
39
+ /** Parse the serial address used by RTU-backed collector sources. */
40
+ export function parseSerialSource(from) {
41
+ const match = /^rtu:\/\/(?<path>\/dev\/tty[A-Za-z0-9]+):(?<baud>\d+):(?<line>[78][NEO][12])(?::(?<slave>\d+))?(?:\?(?<query>.*))?$/u.exec(from);
42
+ if (!match) { throw new Error(`invalid sensors serial address: ${from}`); }
43
+ return { ...match.groups, query: new URLSearchParams(match.groups.query || '') };
44
+ }
45
+
46
+ /** Group source rows by the declared descriptor and project the chosen protocol settings. */
47
+ export function collectorSourceProcesses(rows, { descriptions, describe, project, cli }) {
48
+ const adapters = new Map();
49
+ const processes = collectorProcesses(rows, (row) => {
50
+ const { adapter, bindings } = describe(row);
51
+ const spec = deploymentTemplate(descriptions[adapter], bindings);
52
+ adapters.set(spec.name, adapter);
53
+ return { ...spec, command: collectorPublisherCommand(adapter, cli), adapter };
54
+ }, (descriptor, sources) => { return project(descriptor.adapter, sources); });
55
+ return processes.map((process) => { return { ...process, adapter: adapters.get(process.name) }; });
56
+ }
57
+
58
+ function accepts(row, { adapter, stream }, rules) {
59
+ if (stream && row.name !== stream) { return false; }
60
+ if (!adapter) { return true; }
61
+ const rule = sourceRule(row.from, row.name, rules);
62
+ if (!rule) { throw new TypeError(`Unsupported device source ${row.from}`); }
63
+ return rule.adapter === adapter;
64
+ }
65
+
66
+ /** Compile only owned device fan-in rows, with deployment-specific protocol projection. */
67
+ export function collectorDeviceAssignments(document, selection, { rules, sourceTypes, collect, compile }) {
68
+ const { cluster, generation = 1 } = selection;
69
+ const expanded = expand(document);
70
+ const servers = expanded.servers.filter((server) => { return !cluster || server.id === cluster; });
71
+ if (cluster && !servers.length) { throw new TypeError(`Unknown collector cluster ${cluster}`); }
72
+ return servers.flatMap((server) => {
73
+ const profile = expanded.profiles[server.profile.id];
74
+ const rows = (releases(document, server.id).scada.machines || []).filter((row) => { return accepts(row, selection, rules); });
75
+ const processes = sourceTypes.flatMap(({ schemes, projection }) => {
76
+ return collect[projection](rows.filter((row) => { return schemes.includes(sourceScheme(row.from)); }), profile.apps.scada);
77
+ });
78
+ return compile(processes, generation);
79
+ });
80
+ }
81
+
82
+ /** Render declared consumer assignments in order using the deployment's typed bindings. */
83
+ export function collectorConsumerTasks(declarations, cluster, bindings, generation = 1) {
84
+ return declarations.filter(({ when }) => { return !when || deploymentCondition(when, bindings); }).map(({ id, spec }) => {
85
+ return { taskId: `${cluster}/${id}`, specVersion: 1, generation, spec: { ...deploymentTemplate(spec, bindings), delivery: 'durable' } };
86
+ });
87
+ }
88
+
89
+ /** Project release mappings with an injected fieldbus point decoder. */
90
+ export function mapCollectorRelease(values, decode) {
91
+ const machines = (values.machines || []).map((machine) => {
92
+ if (!machine.mapping) { return machine; }
93
+ const decoded = decode([machine.mapping], [machine.from]);
94
+ return { ...machine, mapping: decoded === null ? machine.mapping : decoded[0] };
95
+ });
96
+ return { ...values, machines };
97
+ }
@@ -0,0 +1,31 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ function digest(value) {
4
+ return createHash('sha256').update(JSON.stringify(value)).digest('hex');
5
+ }
6
+
7
+ /** Bind a portable durable task to a deterministic source compatibility fingerprint. */
8
+ export function portableCollectorSpec(spec, identity) {
9
+ return { ...spec, delivery: 'durable', stateVersion: 1, compatibilityKey: digest(identity) };
10
+ }
11
+
12
+ function declaredTasks(input, generation) {
13
+ if (!Array.isArray(input?.collectorTasks)) { throw new TypeError('collectorTasks declarations required'); }
14
+ const ids = new Set();
15
+ return input.collectorTasks.map(({ taskId, spec }) => {
16
+ if (typeof taskId !== 'string' || !taskId || ids.has(taskId) || typeof spec?.adapter !== 'string') {
17
+ throw new TypeError('Invalid or duplicate collector task declaration');
18
+ }
19
+ ids.add(taskId);
20
+ return { taskId, generation, specVersion: 1, spec: structuredClone(spec) };
21
+ });
22
+ }
23
+
24
+ /** Compile source-derived descriptors to stable assignments or use explicitly declared identities. */
25
+ export default function compileCollectorTasks(input, { describe, identity }, generation = 1) {
26
+ if (!Array.isArray(input)) { return declaredTasks(input, generation); }
27
+ return input.map((process) => {
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 };
30
+ });
31
+ }
@@ -0,0 +1,66 @@
1
+ import expand from './expand.js';
2
+ import { versionedControlCatalog } from './controlPlan.js';
3
+
4
+ function readerPolicy(config, node, task, rows, { placement, pinned, oneCopy, matchesInput }) {
5
+ const matched = rows.filter(({ from }) => { return from.includes('://'); }).filter((row) => { return matchesInput(task, row, node); });
6
+ const policies = matched.map(({ name }) => { return config.inputs?.[name]; }).filter(Boolean);
7
+ if (new Set(policies.map((policy) => { return JSON.stringify(policy); })).size > 1) {
8
+ throw new TypeError('Conflicting replication policy for grouped reader');
9
+ }
10
+ const area = !policies[0] && (!pinned || oneCopy)
11
+ ? placement.readPlacement(config, matched.map(({ name }) => { return name; }), node.id, config.nodes.map(({ id }) => { return id; }))
12
+ : null;
13
+ if (!policies[0] && oneCopy) {
14
+ const preference = area?.preference ?? [node.id];
15
+ return { copies: 1, cost: 1, eligibleNodes: preference, preference };
16
+ }
17
+ return placement.taskPlacement(policies[0] ?? area ?? {}, node, config, { task, pinned });
18
+ }
19
+
20
+ function nodeTasks(document, expanded, config, node, ports) {
21
+ const server = expanded.servers.find(({ id }) => { return id === node.id; });
22
+ const profile = expanded.profiles[server.profile.id];
23
+ const readers = ports.readers(document, node.id);
24
+ const readerIds = new Set(readers.map(({ taskId }) => { return taskId; }));
25
+ const tasks = ports.assignments(document, server, profile, readers);
26
+ return tasks.map((task) => {
27
+ const { taskId, spec, specVersion } = task;
28
+ const local = !readerIds.has(taskId);
29
+ const policy = local ? { copies: 1, cost: 1, eligibleNodes: [node.id], pinnedNode: node.id }
30
+ : readerPolicy(config, node, task, server.fan_in, {
31
+ placement: ports.placement, pinned: ports.pinned(spec), oneCopy: ports.oneCopy(spec),
32
+ matchesInput: (item, row) => { return ports.matchesInput(document, item, row, node); }
33
+ });
34
+ return { taskId, spec: local ? ports.localSpec(spec, node.id) : ports.readerSpec(spec, node.id, config, document), specVersion, ...policy };
35
+ });
36
+ }
37
+
38
+ /** Compile placement and task revisions while the application supplies protocol bindings. */
39
+ export default function compileControlCatalog(document, config, ports) {
40
+ const expanded = expand(document);
41
+ const known = new Set(expanded.servers.flatMap(({ fan_in: inputs = [] }) => { return inputs.map(({ name }) => { return name; }); }));
42
+ for (const name of Object.keys(config.inputs ?? {})) {
43
+ if (!known.has(name)) { throw new TypeError(`Unknown replication input ${name}`); }
44
+ }
45
+ const tasks = config.nodes.flatMap((node) => { return nodeTasks(document, expanded, config, node, ports); });
46
+ return versionedControlCatalog({ version: config.version, controlEpoch: config.controlEpoch, nodes: config.nodes, tasks });
47
+ }
48
+
49
+ /** Match a portable device descriptor against an input endpoint. */
50
+ export function matchesDeviceInput(spec, from) {
51
+ return Boolean(spec.config?.devices?.includes(from.replace('rtu://', 'rtu:').split('?')[0])
52
+ || spec.source?.devices?.some(({ path }) => { return from.startsWith(`rtu://${path}:`); })
53
+ || spec.source?.connections?.some(({ url }) => { return url === from; }));
54
+ }
55
+
56
+ export function controlSecretKey(prefix, node) {
57
+ return `${prefix}_${node.replaceAll('-', '_').toUpperCase()}`;
58
+ }
59
+
60
+ /** Scope broker credential references to a single control node. */
61
+ export function scopeControlSecrets(value, owner, secrets = ['AMQP_URL', 'MQTT_URL']) {
62
+ if (Array.isArray(value)) { return value.map((item) => { return scopeControlSecrets(item, owner, secrets); }); }
63
+ if (!value || typeof value !== 'object') { return value; }
64
+ if (secrets.includes(value.$secret)) { return { $secret: controlSecretKey(value.$secret, owner) }; }
65
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => { return [key, scopeControlSecrets(item, owner, secrets)]; }));
66
+ }
@@ -122,3 +122,19 @@ export function collectorMemoryDeployment(config, node, options) {
122
122
  }
123
123
  });
124
124
  }
125
+
126
+ /** Turn a chart collector into the single control-managed agent for its node. */
127
+ export function applyControlCollector(collector, agent) {
128
+ if (!agent.image) { throw new TypeError('Candidate agentImage required when edge control is enabled'); }
129
+ const originalEnv = Object.fromEntries(Object.entries(collector.env).filter(([name]) => { return name !== 'COLLECTOR_MANIFEST'; }));
130
+ const env = { ...originalEnv, ...agent.env };
131
+ for (const [name, field] of [['COLLECTOR_CONTROL_USERNAME', 'authUsernameKey'], ['COLLECTOR_CONTROL_PASSWORD', 'authPasswordKey']]) {
132
+ env[name] = { valueFrom: { secretKeyRef: { name: agent.authSecret, key: agent[field] ?? name } } };
133
+ }
134
+ return withCollectorScratch({
135
+ ...collector, image: agent.image, startupProbe: agent.startupProbe, ...(agent.resources && { resources: agent.resources }), env,
136
+ envFrom: [...(collector.envFrom ?? []), { secretRef: { name: agent.deliverySecret } }],
137
+ volumeMounts: [...(collector.volumeMounts ?? []), { name: 'control-tls', mountPath: '/tls', readOnly: true }],
138
+ volumes: [...(collector.volumes ?? []), { name: 'control-tls', secret: { secretName: agent.tlsSecret } }]
139
+ });
140
+ }
@@ -0,0 +1,62 @@
1
+ import { isIP } from 'node:net';
2
+ import { deploymentResources } from './controlPlan.js';
3
+
4
+ const voteCounts = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'];
5
+
6
+ export function migrationMode(value = 'verify') {
7
+ if (!['apply', 'verify'].includes(value)) { throw new TypeError('Invalid history receiver migration mode'); }
8
+ return value;
9
+ }
10
+
11
+ function modes(config) {
12
+ for (const key of ['agentResources', 'memberResources', 'controllerResources', 'historyResources']) {
13
+ deploymentResources(config[key]);
14
+ }
15
+ for (const key of ['controllerEnabled', 'historyEnabled']) {
16
+ if (config[key] !== undefined && typeof config[key] !== 'boolean') { throw new TypeError(`Invalid ${key}`); }
17
+ }
18
+ if (!Number.isSafeInteger(config.writerEpoch) || config.writerEpoch < 1) {
19
+ throw new TypeError(`Writer epoch must be positive, message ${config.writerEpoch}`);
20
+ }
21
+ config.receiverMigrationsMode = migrationMode(config.receiverMigrationsMode);
22
+ }
23
+
24
+ function resolveNode(node, servers, policy, port) {
25
+ const api = servers.find(({ id }) => { return id === node.id; })?.api ?? [];
26
+ const addressApi = api.find(({ id }) => { return id === policy.addressApi; });
27
+ const address = addressApi ? new URL(addressApi.url).hostname : node.address;
28
+ const broker = api.find(({ id }) => { return id === policy.brokerApi; });
29
+ const host = isIP(address) === 6 ? `[${address}]` : address;
30
+ return { ...node, address, brokerEndpoint: broker?.url ?? `amqp://${host}:${port}` };
31
+ }
32
+
33
+ function membership(nodes, { voterCount, requiredVoters = [], nodePattern = '^[a-z0-9-]+$', addressPattern = '^[a-z0-9.:-]+$' }) {
34
+ if (nodes?.some(({ voter }) => { return typeof voter !== 'boolean'; })) { throw new TypeError('Boolean voter flags required'); }
35
+ const voters = (nodes ?? []).filter(({ voter }) => { return voter; });
36
+ if (!nodes || (voterCount !== undefined && voters.length !== voterCount)) {
37
+ throw new TypeError(voterCount === undefined ? 'Missing etcd members' : `Exactly ${voteCounts[voterCount] ?? voterCount} etcd voters required`);
38
+ }
39
+ const ids = nodes.map(({ id }) => { return id; });
40
+ if (new Set(ids).size !== ids.length || !requiredVoters.every((id) => { return voters.some((node) => { return node.id === id; }); })) {
41
+ throw new TypeError('Invalid edge membership');
42
+ }
43
+ const nodeId = new RegExp(nodePattern, 'u');
44
+ const host = new RegExp(addressPattern, 'u');
45
+ nodes.forEach(({ id, address, capacity }) => {
46
+ if (!nodeId.test(id) || typeof address !== 'string' || !host.test(address) || !Number.isSafeInteger(capacity) || capacity < 1) {
47
+ throw new TypeError('Invalid edge node');
48
+ }
49
+ });
50
+ }
51
+
52
+ /** Resolve control members and validate a site's declared quorum constraints. */
53
+ export default function controlPlaneConfiguration(raw, servers, policy) {
54
+ const config = raw && { ...raw, nodes: raw.nodes?.map((node) => { return resolveNode(node, servers, policy, raw.brokerService?.nodePort); }) };
55
+ membership(config?.nodes, policy);
56
+ modes(config);
57
+ if (!Number.isSafeInteger(config.version) || config.version < 1 || !Number.isSafeInteger(config.defaultCopies)
58
+ || config.defaultCopies < 1 || config.defaultCopies > config.nodes.length) {
59
+ throw new TypeError('Invalid control catalog version or copies');
60
+ }
61
+ return config;
62
+ }
@@ -0,0 +1,37 @@
1
+ import { scopeControlSecrets } from './compileControlCatalog.js';
2
+
3
+ function historySink(node, queue, { groups, exchange, target }) {
4
+ return {
5
+ id: `telemetry-${node}`, type: 'amqp',
6
+ url: target ? scopeControlSecrets({ $secret: 'AMQP_URL' }, node) : { $secret: 'AMQP_URL' },
7
+ ...(target && { routingKeyPrefix: target }),
8
+ options: {
9
+ exchanges: [{ name: exchange, type: 'topic', options: { durable: true } }],
10
+ queues: [{ name: queue, options: { durable: true, autoDelete: false } }],
11
+ bindings: groups.map((pattern) => { return { queue, exchange, pattern }; })
12
+ }
13
+ };
14
+ }
15
+
16
+ function historySinks(spec, node, config, { historyNodes, keyPrefix, historyBindings, historyExchange }) {
17
+ if (!spec.config.devices) {
18
+ return [historySink(node, config.historyQueue, { exchange: historyExchange, groups: historyBindings(node) })];
19
+ }
20
+ return config.nodes.filter(({ id }) => { return historyNodes(id); }).map(({ id }) => {
21
+ return historySink(id, config.historyQueue, { exchange: historyExchange, groups: historyBindings(id), target: keyPrefix(id) });
22
+ });
23
+ }
24
+
25
+ /** Bind a deployed reader to its declared sink topology and delivery mode. */
26
+ export default function controlReaderSpec(spec, node, config, ports) {
27
+ const { delivery, pinCredentials, readerExchanges, sinkOptions, historyAdapter } = ports;
28
+ const result = { ...(pinCredentials(spec) ? scopeControlSecrets(spec, node) : spec), delivery: delivery(spec) };
29
+ if (Object.hasOwn(readerExchanges, spec.adapter)) {
30
+ const exchange = readerExchanges[spec.adapter];
31
+ const options = sinkOptions(exchange);
32
+ result.sink = { ...result.sink, options };
33
+ result.sinks = [{ id: `${node}-${exchange}`, type: 'amqp', url: result.sink.url, options }];
34
+ }
35
+ if (spec.adapter === historyAdapter) { result.sinks = historySinks(spec, node, config, ports); }
36
+ return result;
37
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Edge machine list from EDGE_MACHINES or the plant profile.
3
+ *
4
+ * @example
5
+ * const rows = edgeDescriptors(process.env, profile);
6
+ *
7
+ * @param {object} env - process environment
8
+ * @param {{ machines: function(): Array }} profile - plant profile
9
+ * @returns {Array<{device: string, id: string, shop?: string, kind?: string}>}
10
+ */
11
+ export default function edgeDescriptors(env, profile) {
12
+ const raw = env.EDGE_MACHINES;
13
+ if (typeof raw === 'string' && raw.length > 0) {
14
+ return JSON.parse(raw).map((entry) => {
15
+ return {
16
+ device: entry.device,
17
+ id: entry.id,
18
+ shop: entry.shop,
19
+ kind: entry.kind
20
+ };
21
+ });
22
+ }
23
+ return profile.machines().map((entry) => {
24
+ return {
25
+ device: entry.device,
26
+ id: entry.machine,
27
+ shop: entry.shop,
28
+ kind: entry.kind
29
+ };
30
+ });
31
+ }
@@ -0,0 +1,79 @@
1
+ import { parseSerialSource } from './collectorSourcePlan.js';
2
+
3
+ function registerOrigin(address) {
4
+ const text = new URL(address).searchParams.get('at');
5
+ if (text === null) { return undefined; }
6
+ const origin = parseInt(text, 10);
7
+ if (Number.isNaN(origin)) { throw new Error(`Address at must be a number, got: ${text}`); }
8
+ return origin;
9
+ }
10
+
11
+ function holdingPoint(value, address, profiles) {
12
+ const channel = String(value);
13
+ if (channel.startsWith('holding:')) { return channel; }
14
+ const origin = registerOrigin(address);
15
+ for (const profile of profiles) {
16
+ const entry = profile.layout.find((row) => { return row.channel === channel; });
17
+ if (entry) { return `holding:${(origin ?? profile.origin) + entry.offset}:${profile.order}`; }
18
+ }
19
+ return null;
20
+ }
21
+
22
+ function registerMap(mapping, address, profiles) {
23
+ const next = {};
24
+ for (const [key, value] of Object.entries(mapping || {})) {
25
+ const point = holdingPoint(value, address, profiles);
26
+ if (point === null) { return null; }
27
+ next[key] = point;
28
+ }
29
+ return next;
30
+ }
31
+
32
+ /** Convert named device channels into portable holding points using declared register profiles. */
33
+ export function projectRegisterMaps(maps, addresses, profiles) {
34
+ if (!Array.isArray(maps) || !Array.isArray(addresses) || maps.length !== addresses.length) { return null; }
35
+ const rows = maps.map((mapping, index) => { return registerMap(mapping, addresses[index], profiles); });
36
+ return rows.includes(null) ? null : rows;
37
+ }
38
+
39
+ /** Validate the ordered RTU sources sharing one serial port and register window. */
40
+ export function sharedRegisterBus(rows, { label, count }) {
41
+ const ports = rows.map(({ from }) => { return parseSerialSource(from); });
42
+ const [first] = ports;
43
+ if (!first) { throw new TypeError(`${label} requires at least one serial source`); }
44
+ if (new Set(ports.map(({ slave }) => { return slave; })).size !== ports.length) {
45
+ throw new Error('duplicate Modbus slave address');
46
+ }
47
+ const at = first.query.get('at');
48
+ const size = first.query.get('count');
49
+ if (!/^\d+$/u.test(at || '') || size !== String(count)) {
50
+ throw new Error(`${label} requires a numeric address and ${count} registers`);
51
+ }
52
+ if (ports.some(({ path, baud, line, query, slave }) => {
53
+ return path !== first.path || baud !== first.baud || line !== first.line || query.toString() !== first.query.toString() || !slave;
54
+ })) { throw new Error(`${label} sources must share one serial bus and register range`); }
55
+ return { at, count: size, ports };
56
+ }
57
+
58
+ /** Validate independent raw serial inputs and produce the runtime's device-list ABI. */
59
+ export function rawSerialDeviceList(rows, { label, name }) {
60
+ const ports = rows.map(({ from }) => { return parseSerialSource(from); });
61
+ if (new Set(ports.map(({ path }) => { return path; })).size !== ports.length) {
62
+ throw new Error(`duplicate ${label} port`);
63
+ }
64
+ if (ports.some(({ slave, query }) => { return slave || query.toString(); })) {
65
+ throw new Error(`${label} serial sources cannot specify a Modbus slave or register range`);
66
+ }
67
+ return ports.map(({ path, baud, line }, index) => { return `${name(rows[index])}:${path}:${baud}:${line}`; }).join(',');
68
+ }
69
+
70
+ /** Group stream URLs by database endpoint in source order, ignoring URL query selectors. */
71
+ export function databaseSourceGroups(rows, { port, identity }) {
72
+ const sources = new Map();
73
+ rows.forEach(({ from }) => {
74
+ const address = new URL(from);
75
+ const source = { host: address.hostname, port: Number(address.port || port), database: address.pathname.slice(1), ...identity };
76
+ sources.set(JSON.stringify(source), source);
77
+ });
78
+ return [...sources.values()];
79
+ }
@@ -0,0 +1,17 @@
1
+ /** Apply live chart values while retaining generated fields inside selected components. */
2
+ export function liveChartValues(values, { replace, components } = {}) {
3
+ const result = { ...values, ...replace };
4
+ for (const [key, overlay] of Object.entries(components ?? {})) {
5
+ result[key] = { ...values[key], ...overlay };
6
+ }
7
+ return result;
8
+ }
9
+
10
+ /** Overlay immutable release names and chart values by chart kind. */
11
+ export function liveChartApps(apps, declarations = {}) {
12
+ return (apps ?? []).map((app) => {
13
+ if (!Object.hasOwn(declarations, app.chart)) { return app; }
14
+ const { values, ...identity } = declarations[app.chart];
15
+ return { ...app, ...identity, values: { ...app.values, ...values } };
16
+ });
17
+ }
@@ -0,0 +1,24 @@
1
+ function taxonomy(declarations) {
2
+ return Object.freeze(Object.fromEntries(Object.entries(declarations).map(([section, value]) => {
3
+ const declared = Array.isArray(value) ? Object.freeze([...value]) : value;
4
+ return [section, () => { return declared; }];
5
+ })));
6
+ }
7
+
8
+ /** Combine an installation's topology, taxonomy and application-supplied integrations. */
9
+ export default function plantBindingProfile({ topology, taxonomy: declarations, integrations }) {
10
+ return function profile() {
11
+ const layout = topology();
12
+ const tags = taxonomy(declarations);
13
+ const links = integrations();
14
+ return Object.freeze({
15
+ name() { return layout.plant; },
16
+ topology() { return layout; },
17
+ taxonomy() { return tags; },
18
+ integrations() { return links; },
19
+ machines() {
20
+ return layout.machines.map(({ device, id: machine, shop, kind }) => { return Object.freeze({ device, machine, shop, kind }); });
21
+ }
22
+ });
23
+ };
24
+ }
@@ -0,0 +1,48 @@
1
+ import { collectorMemoryDeployment, etcdMembership } from './controlPlan.js';
2
+ import controlPlaneConfiguration from './controlPlaneConfiguration.js';
3
+ import { controlSecretKey } from './compileControlCatalog.js';
4
+
5
+ function hostDevices(servers, node) {
6
+ const streams = servers.find(({ id }) => { return id === node; })?.fan_in ?? [];
7
+ return [...new Set(streams.filter(({ from }) => { return from.startsWith('rtu://'); }).map(({ from }) => {
8
+ return from.slice(6).split(':')[0];
9
+ }))].sort();
10
+ }
11
+
12
+ function chartValues(config, server, servers, policy, ports) {
13
+ const { endpoints, initialCluster } = etcdMembership(config.nodes, config);
14
+ const brokerEndpoints = Object.fromEntries(config.nodes.map(({ id, brokerEndpoint }) => { return [id, brokerEndpoint]; }));
15
+ return {
16
+ ...config,
17
+ historyBindings: ports.historyBindings(server.id),
18
+ historyAmqpKey: controlSecretKey('AMQP_URL', server.id),
19
+ historyMaintenance: config.historyEnabled !== false && ports.historyMaintenance(server.id),
20
+ initialCluster, endpoints,
21
+ member: server.voter ? { ...server, tlsSecret: server.serverTlsSecret ?? `${server.id}-control-server` } : null,
22
+ agent: collectorMemoryDeployment(config, server, {
23
+ brokerEndpoints: Object.fromEntries(Object.entries(brokerEndpoints).map(([id, url]) => {
24
+ return [controlSecretKey('AMQP_URL', id), url];
25
+ })),
26
+ endpoints, hostDevices: hostDevices(servers, server.id), deliverySecret: policy.deliverySecret, extraEnv: ports.checkpoint(config, server)
27
+ }),
28
+ reconcile: ports.reconcile(config.classifyApply),
29
+ brokerEndpoints: JSON.stringify(brokerEndpoints),
30
+ rabbitmqManagement: policy.rabbitmqManagement
31
+ };
32
+ }
33
+
34
+ /** Project one control release from a plant document and supplied policy and runtime bindings. */
35
+ export default function projectControlPlane(cluster, document, policy, ports) {
36
+ const { servers } = document;
37
+ const config = controlPlaneConfiguration(document[policy.section], servers, policy);
38
+ const server = config.nodes.find(({ id }) => { return id === cluster; });
39
+ if (!server) { throw new TypeError(`Unknown edge ${cluster}`); }
40
+ const catalog = ports.catalog(document, config);
41
+ const classification = ports.classification(document, config, catalog);
42
+ return {
43
+ context: cluster, namespace: config.namespace, release: config.release, chart: policy.chart,
44
+ supervisor: ports.supervisor(config, server, classification.machines[server.id]), classification,
45
+ replicas: ports.replicas(config, document), catalog,
46
+ values: chartValues(config, server, servers, policy, ports)
47
+ };
48
+ }