@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
@@ -0,0 +1,51 @@
1
+ import readDeploymentDocument from '../../application/deploy/readDeploymentDocument.js';
2
+ import centralTelemetryPolicy, { centralTelemetryVersion, normalizeCentralPolicy } from '../ingest/telemetry/centralPolicy.js';
3
+
4
+ const policyRuntime = { centralTelemetryPolicy, centralTelemetryVersion };
5
+ const metricsAdapters = new Set(['amqp-metrics', 'mqtt-metrics', 'amqp-pg-metrics', 'mqtt-pg-metrics', 'silent-streams']);
6
+
7
+ export function centralTelemetryValues(document) {
8
+ return normalizeCentralPolicy(document.centralTelemetry);
9
+ }
10
+
11
+ export function centralTelemetryChartEnv(document, file, previous = []) {
12
+ const value = JSON.stringify(centralTelemetryValues(document));
13
+ return [...previous.filter(({ name }) => { return !['CENTRAL_TELEMETRY_POLICY', 'CENTRAL_TELEMETRY_DSL'].includes(name); }),
14
+ { name: 'CENTRAL_TELEMETRY_POLICY', value }, { name: 'CENTRAL_TELEMETRY_DSL', value: file }];
15
+ }
16
+
17
+ function checkRuntime(policy, runtime) {
18
+ if (runtime.centralTelemetryVersion !== centralTelemetryVersion || typeof runtime.centralTelemetryPolicy !== 'function') {
19
+ throw new TypeError(`Matching central telemetry runtime version ${centralTelemetryVersion} is required`);
20
+ }
21
+ runtime.centralTelemetryPolicy(policy);
22
+ }
23
+
24
+ /** Resolve the declared archive policy before opening any telemetry consumers. */
25
+ export function centralTelemetryEnvironment(env, { file, runtime = policyRuntime } = {}) {
26
+ if (env.SINK_DB_PROFILE !== undefined && env.SINK_DB_PROFILE !== 'central') {
27
+ throw new TypeError('Central telemetry requires the central database profile');
28
+ }
29
+ const policy = centralTelemetryValues(readDeploymentDocument(env.CENTRAL_TELEMETRY_DSL ?? file));
30
+ const serialized = JSON.stringify(policy);
31
+ if (env.CENTRAL_TELEMETRY_POLICY && JSON.stringify(normalizeCentralPolicy(JSON.parse(env.CENTRAL_TELEMETRY_POLICY))) !== serialized) {
32
+ throw new TypeError('Environment telemetry policy disagrees with the DSL');
33
+ }
34
+ checkRuntime(policy, runtime);
35
+ return { ...env, SINK_DB_PROFILE: 'central', CENTRAL_TELEMETRY_POLICY: serialized };
36
+ }
37
+
38
+ /** Apply the archive's canonical admission policy to external ClickHouse telemetry writers. */
39
+ export function centralTelemetryTasks(tasks, document, runtime = policyRuntime) {
40
+ return tasks.map((task) => {
41
+ const { spec } = task;
42
+ if ((!spec.clickhouse && !spec.clickhouseUrl) || !metricsAdapters.has(spec.adapter)) { return task; }
43
+ const telemetryPolicy = centralTelemetryValues(document);
44
+ checkRuntime(telemetryPolicy, runtime);
45
+ if (spec.telemetryPolicy && JSON.stringify(normalizeCentralPolicy(spec.telemetryPolicy)) !== JSON.stringify(telemetryPolicy)) {
46
+ throw new TypeError('Collector telemetry policy disagrees with the DSL');
47
+ }
48
+ if (spec.table && spec.table !== 'scada.metrics') { throw new TypeError('Central telemetry executor requires the canonical metrics table'); }
49
+ return { ...task, spec: { ...spec, telemetryPolicy, telemetryAmqp: spec.telemetryAmqp ?? { $secret: 'AMQP_URL' }, table: 'scada.metrics' } };
50
+ });
51
+ }
@@ -0,0 +1,64 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { clickhouseHistoryComment as historyComment } from '../persistence/clickhouse/localHistory.js';
3
+
4
+ function schemaSql(settings) {
5
+ const { retentionDays, coordinatedRetention, ttlMergeSeconds } = settings;
6
+ const expiry = `TTL toDateTime(ts, 'UTC') + INTERVAL ${retentionDays} DAY DELETE`;
7
+ return `CREATE DATABASE IF NOT EXISTS scada;
8
+ CREATE TABLE IF NOT EXISTS scada.metrics (
9
+ topic LowCardinality(String),
10
+ ts DateTime64(6, 'UTC') CODEC(Delta, ZSTD(1)),
11
+ value Float64 CODEC(Gorilla, ZSTD(1))
12
+ ) ENGINE=MergeTree
13
+ PARTITION BY toDate(ts)
14
+ ORDER BY (topic, ts)
15
+ ${coordinatedRetention ? '' : expiry}
16
+ SETTINGS merge_with_ttl_timeout=${ttlMergeSeconds}, non_replicated_deduplication_window=10000;
17
+ ${coordinatedRetention ? '' : `ALTER TABLE scada.metrics MODIFY ${expiry};`}
18
+ ${coordinatedRetention ? `ALTER TABLE scada.metrics MODIFY COMMENT '${historyComment}';` : ''}
19
+ ALTER TABLE scada.metrics MODIFY SETTING merge_with_ttl_timeout=${ttlMergeSeconds}, non_replicated_deduplication_window=10000;
20
+ `;
21
+ }
22
+
23
+ const migrateRetention = `set -eu
24
+ has_ttl=$(clickhouse-client --config-file=/schema/client.xml --query="SELECT position(create_table_query, 'TTL ') > 0 FROM system.tables WHERE database='scada' AND name='metrics' FORMAT TabSeparatedRaw")
25
+ case "$has_ttl" in
26
+ 1) clickhouse-client --config-file=/schema/client.xml --query='ALTER TABLE scada.metrics REMOVE TTL' ;;
27
+ 0) ;;
28
+ *) echo 'Cannot verify raw history TTL state' >&2; exit 1 ;;
29
+ esac
30
+ `;
31
+
32
+ function serverConfig(settings) {
33
+ return `<clickhouse>
34
+ <max_server_memory_usage>${settings.memoryBytes}</max_server_memory_usage>
35
+ <mark_cache_size>268435456</mark_cache_size>
36
+ <uncompressed_cache_size>67108864</uncompressed_cache_size>
37
+ <logger><level>warning</level><console>1</console><size>10M</size><count>3</count></logger>
38
+ <query_log><ttl>event_date + INTERVAL 7 DAY DELETE</ttl></query_log>
39
+ <part_log><ttl>event_date + INTERVAL 7 DAY DELETE</ttl></part_log>
40
+ <metric_log remove="remove"/><asynchronous_metric_log remove="remove"/><query_thread_log remove="remove"/><trace_log remove="remove"/><text_log remove="remove"/><opentelemetry_span_log remove="remove"/><processors_profile_log remove="remove"/><query_views_log remove="remove"/><session_log remove="remove"/><zookeeper_log remove="remove"/><filesystem_cache_log remove="remove"/><asynchronous_insert_log remove="remove"/>
41
+ <storage_configuration><disks><default><keep_free_space_bytes>${settings.reserveBytes}</keep_free_space_bytes></default></disks></storage_configuration>
42
+ <prometheus><endpoint>/metrics</endpoint><port>9363</port><metrics>true</metrics><events>true</events><asynchronous_metrics>true</asynchronous_metrics></prometheus>
43
+ </clickhouse>`;
44
+ }
45
+
46
+ const users = `<clickhouse><profiles><default><max_threads>2</max_threads><max_memory_usage>1073741824</max_memory_usage><max_bytes_before_external_group_by>268435456</max_bytes_before_external_group_by><max_bytes_before_external_sort>268435456</max_bytes_before_external_sort><date_time_input_format>best_effort</date_time_input_format></default></profiles></clickhouse>`;
47
+
48
+ /** Compiles local telemetry storage policy without embedding credentials in desired state. */
49
+ export default function clickhouseTelemetryPolicy(settings, label = 'ClickHouse telemetry') {
50
+ if (settings.backend !== 'clickhouse' || !settings.image || !settings.serverImage || !settings.secret) {
51
+ throw new Error(`${label} requires ClickHouse images and a credential secret`);
52
+ }
53
+ for (const field of ['retentionDays', 'ttlMergeSeconds', 'reserveBytes', 'memoryBytes', 'batchSize', 'prefetch', 'maxWaitMs']) {
54
+ if (!Number.isSafeInteger(settings[field]) || settings[field] <= 0) { throw new Error(`Invalid ${label.toLowerCase()} ${field}`); }
55
+ }
56
+ if (settings.batchSize > settings.prefetch || settings.retentionDays > 365 || settings.reserveBytes < 1073741824) {
57
+ throw new Error(`Invalid ${label.toLowerCase()} retention or buffer policy`);
58
+ }
59
+ const schema = schemaSql(settings);
60
+ const retentionMigration = settings.coordinatedRetention ? migrateRetention : '';
61
+ const config = serverConfig(settings);
62
+ const schemaJob = `edge-clickhouse-schema-${createHash('sha256').update(schema + retentionMigration).digest('hex').slice(0, 12)}`;
63
+ return { ...settings, schema, retentionMigration, config, users, schemaJob };
64
+ }
@@ -0,0 +1,68 @@
1
+ import { collectorDeployment, deploymentContext, retiredDeployments } from '../../application/deploy/deploymentPlan.js';
2
+ import { brokerClientEnvironment } from './brokerSecurity.js';
3
+ import deploymentTemplate from './deploymentTemplate.js';
4
+ import { brokerPolicy } from './securityPolicy.js';
5
+
6
+ function collectorApp(profile, server, policy) {
7
+ const app = profile.apps.scada;
8
+ const companion = profile[policy.companion];
9
+ const image = server.profile.variables?.[policy.imageVariable];
10
+ return { ...app, ...(companion && { [policy.companion]: companion }),
11
+ ...(image && { collector: { ...app.collector, image } }) };
12
+ }
13
+
14
+ function compileCollectors(context, policy, ports) {
15
+ const { app, target, scada } = context;
16
+ const machines = scada.machines.filter(({ from }) => {
17
+ return !policy.excludedSources.some((prefix) => { return from.startsWith(prefix); });
18
+ });
19
+ const sources = ports.processes(machines, app);
20
+ const initial = sources[0];
21
+ const defaults = initial ? deploymentTemplate(policy.environment, target) : {};
22
+ const environment = Object.fromEntries(Object.entries(defaults).map(([key, value]) => {
23
+ return [key, Object.hasOwn(initial.env, key) ? initial.env[key] : value];
24
+ }));
25
+ const assignments = ports.assignments(context);
26
+ const { collector } = app;
27
+ const processes = collectorDeployment(sources, { image: collector?.image, resources: collector?.resources,
28
+ command: policy.command, hostSecurity: policy.hostSecurity, environment, assignments }).map((process) => {
29
+ return ports.control(process, context);
30
+ });
31
+ return { sources, processes };
32
+ }
33
+
34
+ function secureValues(rabbitmq, processes, broker, ports) {
35
+ if (!broker) { return rabbitmq; }
36
+ const secured = ports.brokerValues(rabbitmq, broker);
37
+ if (broker.phase !== 'prepare') {
38
+ const { AMQP_URL: amqp, MQTT_URL: mqtt } = brokerClientEnvironment(broker);
39
+ processes.forEach(({ env }) => { Object.assign(env, { AMQP_URL: amqp, MQTT_URL: mqtt }); });
40
+ }
41
+ return secured;
42
+ }
43
+
44
+ function chartPlan(context, policy, ports) {
45
+ const { app, cluster, scada, target, server, broker } = context;
46
+ const { namespace, ...settings } = target;
47
+ const { sources, processes } = compileCollectors(context, policy, ports);
48
+ const rabbitmq = secureValues({ ...scada.rabbitmq, extraConfig: { ...scada.rabbitmq.extraConfig, cluster_name: cluster },
49
+ definitions: ports.broker(context) }, processes, broker, ports);
50
+ const { values, extra } = ports.project({ ...context, values: { ...scada, ...settings, processes, rabbitmq } });
51
+ const adapters = sources.length ? ['collector', ...sources.map(({ adapter }) => { return adapter; })] : [];
52
+ const groups = adapters.map((adapter) => { return app[adapter]?.replaces || []; });
53
+ const nodeAddress = new URL(server.api.find(({ id }) => { return id === policy.address; }).url).hostname;
54
+ return { context: cluster, namespace, nodeAddress, release: cluster, chart: policy.chart, values,
55
+ retirements: retiredDeployments({ prefix: settings.prefix, groups, desired: processes, extra }) };
56
+ }
57
+
58
+ /** Compile collector and transport requirements for a chart with caller-supplied source and application ports. */
59
+ export default function collectorChartPlan(cluster, document, security, policy, ports) {
60
+ if (!policy.targets.includes(cluster)) { throw new Error(policy.targetError); }
61
+ const broker = brokerPolicy(security);
62
+ const plant = document || ports.read();
63
+ const context = deploymentContext(plant, cluster);
64
+ const { target, profile, server } = context;
65
+ if (target.namespace !== policy.namespace || target.prefix !== policy.prefix) { throw new Error(policy.scopeError); }
66
+ const app = collectorApp(profile, server, policy);
67
+ return chartPlan({ ...context, app, broker, plant, cluster, security }, policy, ports);
68
+ }
@@ -0,0 +1,25 @@
1
+ import appReleases from '../../application/deploy/appReleases.js';
2
+ import { liveChartApps, liveChartValues } from '../../application/deploy/liveReleaseOverlay.js';
3
+ import readDeploymentDocument from '../../application/deploy/readDeploymentDocument.js';
4
+ import releases from '../../application/deploy/releases.js';
5
+ import { centralTelemetryChartEnv } from './centralTelemetry.js';
6
+
7
+ /** Render a declared archive contour with its immutable live chart overlays. */
8
+ export default function configuredArchivePlan(file, policy) {
9
+ const declarations = readDeploymentDocument(file).liveReleases;
10
+ function withLive(values, target) {
11
+ return Object.hasOwn(declarations, target) ? liveChartValues(values, declarations[target].chart) : values;
12
+ }
13
+ function withLiveApps(apps, target) {
14
+ return Object.hasOwn(declarations, target) ? liveChartApps(apps, declarations[target].apps) : apps;
15
+ }
16
+ return { withLive, withLiveApps,
17
+ plan(target = policy.target) {
18
+ if (target !== policy.target) { throw new Error(policy.targetError); }
19
+ const document = readDeploymentDocument(file);
20
+ const projected = releases(document, target);
21
+ return { context: policy.context, namespace: policy.namespace, release: target,
22
+ scada: withLive({ ...projected.scada, env: centralTelemetryChartEnv(document, policy.file, projected.scada.env) }, target),
23
+ apps: withLiveApps(appReleases(projected.apps, target), target) };
24
+ } };
25
+ }
@@ -0,0 +1,34 @@
1
+ import { brokerStreamRoutes } from './brokerTopology.js';
2
+ import deploymentTemplate from './deploymentTemplate.js';
3
+
4
+ function routeBindings(row, policy) {
5
+ const machine = row.name.split('/')[policy.pathIndex];
6
+ const device = machine?.replace(policy.machinePrefix, policy.devicePrefix);
7
+ return { name: row.name, machine, device };
8
+ }
9
+
10
+ function compileRule(rule, bindings, row) {
11
+ const route = deploymentTemplate(rule.route, bindings);
12
+ const metrics = rule.metrics ?? (rule.mappingKeys && Object.keys(row.mapping));
13
+ if (!metrics) { return route; }
14
+ return { ...route, keys: metrics.map((metric) => { return deploymentTemplate(rule.key, { ...bindings, metric }); }) };
15
+ }
16
+
17
+ /** Project broker route keys from declared publisher, protocol and adapter policies. */
18
+ export default function configuredBrokerRoutes(policy, identifyAdapter) {
19
+ return function routes(source) {
20
+ return brokerStreamRoutes(source, { service: policy.service,
21
+ passive(row) {
22
+ const { contract } = row;
23
+ if (!Object.hasOwn(policy.publishers, contract)) {
24
+ throw new Error(deploymentTemplate(policy.contractError, { contract: String(contract) }));
25
+ }
26
+ return compileRule(policy.publishers[contract], routeBindings(row, policy), row);
27
+ },
28
+ local(row) {
29
+ const selected = policy.protocols.find(({ prefix }) => { return row.from.startsWith(prefix); });
30
+ const rule = selected ?? policy.adapters[identifyAdapter(row)];
31
+ return compileRule(rule, routeBindings(row, policy), row);
32
+ } });
33
+ };
34
+ }
@@ -0,0 +1,74 @@
1
+ import deploymentTemplate from './deploymentTemplate.js';
2
+ import { holdersFrom } from './highAvailability/classifyShovels.js';
3
+ import projectClassification from './projectClassification.js';
4
+
5
+ function localMachines(ids, rule) {
6
+ const pattern = new RegExp(rule.homePattern, 'u');
7
+ const nodes = ids.filter((id) => { return id.startsWith(rule.homePrefix); });
8
+ if (nodes.length < 2) { throw new TypeError(rule.minimumError); }
9
+ return nodes.map((home) => {
10
+ if (!pattern.test(home)) { throw new TypeError(deploymentTemplate(rule.targetError, { home })); }
11
+ return { machine: rule.machinePrefix + home.at(-1), home, eligibleNodes: [...ids], area: rule.homeArea };
12
+ });
13
+ }
14
+
15
+ function remoteMachines(ids, rule) {
16
+ const eligibleNodes = ids.filter((id) => { return rule.remoteEligible.includes(id); });
17
+ return rule.remoteMachines.map((machine) => {
18
+ return { machine, home: rule.remoteHome, eligibleNodes, area: rule.remoteArea };
19
+ });
20
+ }
21
+
22
+ /** Project classification tasks with the installation's declared home and spare groups. */
23
+ export function configuredClassification(policy, calculatePlacement) {
24
+ const { classification: rule } = policy;
25
+ return {
26
+ plan(ids, brokers, central, holders = {}) {
27
+ return projectClassification(localMachines(ids, rule), { ...rule, brokers, central, holders });
28
+ },
29
+ forControl(plant, config) {
30
+ const central = plant.servers.find(({ id }) => { return id === policy.central; })
31
+ ?.api.find(({ id }) => { return id === policy.brokerApi; })?.url;
32
+ if (!central) { throw new TypeError(rule.centralError); }
33
+ const ids = config.nodes.map(({ id }) => { return id; });
34
+ const declarations = [...localMachines(ids, rule), ...remoteMachines(ids, rule)].map(({ area, ...item }) => {
35
+ return { ...item, placement: calculatePlacement(config, area, item.home, ids) };
36
+ });
37
+ const brokers = Object.fromEntries(config.nodes.map(({ id, brokerEndpoint }) => { return [id, brokerEndpoint]; }));
38
+ return projectClassification(declarations, { ...rule, brokers, central,
39
+ holders: { ...holdersFrom(config.classifyRecord ?? {}), ...config.classificationHolders } });
40
+ }
41
+ };
42
+ }
43
+
44
+ function location(server, service) {
45
+ const endpoint = server.api?.find(({ id }) => { return id === service; });
46
+ if (!endpoint?.url) { return []; }
47
+ const url = new URL(endpoint.url);
48
+ return [[server.id, `${url.protocol}//${url.host}`]];
49
+ }
50
+
51
+ /** Resolve the peer directory behind an enabled classification service. */
52
+ export function classificationEnvironment(policy) {
53
+ return function environment(target, document) {
54
+ if (!document?.[policy.section]?.enabled) { return {}; }
55
+ const peers = Object.fromEntries((document.servers || []).flatMap((server) => { return location(server, policy.service); }));
56
+ return deploymentTemplate(policy.values, { target, peers });
57
+ };
58
+ }
59
+
60
+ /** Project classifier chart values using the declared profile and config renderer. */
61
+ export function configuredSupervisor(policy, render) {
62
+ return function supervisor(config, node, machines = null) {
63
+ const home = node.id.startsWith(policy.homePrefix);
64
+ const targetMachine = policy.machinePrefix + node.id.at(-1);
65
+ const defaults = home ? [targetMachine] : [];
66
+ const selected = machines?.length ? [...new Set(machines)] : defaults;
67
+ const credentials = home ? policy.homeSecret : policy.deliverySecret;
68
+ const env = Object.fromEntries(policy.secretKeys.map((key) => { return [key, { valueFrom: { secretKeyRef: { name: credentials, key } } }]; }));
69
+ return { chart: policy.chart, release: policy.releases[node.id] ?? policy.defaultRelease, values: {
70
+ image: config.supervisorImage ?? null, config: render(node.id, false, selected, policy.checkpoint),
71
+ writerEpoch: config.writerEpoch, machines: selected, env, history: { retentionDays: config.historyRetentionDays }
72
+ } };
73
+ };
74
+ }
@@ -0,0 +1,116 @@
1
+ import compileControlCatalog, { matchesDeviceInput, scopeControlSecrets } from '../../application/deploy/compileControlCatalog.js';
2
+ import controlReaderSpec from '../../application/deploy/controlReaderSpecs.js';
3
+ import expand from '../../application/deploy/expand.js';
4
+ import projectControlPlane from '../../application/deploy/projectControlPlane.js';
5
+ import { brokerSinkOptions } from './brokerTopology.js';
6
+ import deploymentTemplate from './deploymentTemplate.js';
7
+ import { reconciliationBundle } from './highAvailability/reconciliationBundle.js';
8
+
9
+ function serverFor(document, name) {
10
+ return document.servers.find(({ id }) => { return id === name; });
11
+ }
12
+
13
+ function historyBindings(expanded, server, policy) {
14
+ const app = expanded.profiles[server.profile.id].apps.scada;
15
+ const contracts = app.applicationContracts.filter(({ family }) => { return family === policy.historyFamily; });
16
+ const device = server.id.slice(policy.historyDeviceOffset);
17
+ return contracts.flatMap(({ publisherContracts, key }) => {
18
+ return publisherContracts ? publisherContracts.map((id) => {
19
+ if (!Object.hasOwn(policy.historyPublishers, id)) { throw new TypeError(`Unknown history publisher contract ${id}`); }
20
+ return deploymentTemplate(policy.historyPublishers[id], { device, machine: device.replace('-', '') });
21
+ }) : [key];
22
+ });
23
+ }
24
+
25
+ function combinedHistoryBindings(owner, document, policy, routes) {
26
+ const { historyOwnerPrefix, historySource, historyPeer } = policy;
27
+ if (!owner.startsWith(historyOwnerPrefix)) { return []; }
28
+ const expanded = expand(document);
29
+ const server = serverFor(expanded, owner);
30
+ const sensor = serverFor(expanded, historySource);
31
+ const names = new Set(server.fan_in.filter(({ from }) => { return from === sensor.id; }).map(({ name }) => { return name; }));
32
+ const remote = routes(sensor).filter(({ name, peer }) => { return names.has(name) && peer === historyPeer; });
33
+ return [...new Set([...historyBindings(expanded, server, policy), ...remote.flatMap(({ keys }) => { return keys; })])];
34
+ }
35
+
36
+ function readerOptions(spec, owner, config, document, { policy, ports }) {
37
+ return controlReaderSpec(spec, owner, config, {
38
+ delivery(task) { return task.adapter === policy.singleReader ? 'durable' : 'spooled'; },
39
+ pinCredentials(task) { return task.adapter === policy.serialAdapter || Boolean(task.config?.devices); },
40
+ readerExchanges: policy.readerExchanges,
41
+ sinkOptions(exchange) {
42
+ const expanded = expand(document);
43
+ const server = serverFor(expanded, owner);
44
+ const profile = expanded.profiles[server.profile.id];
45
+ return brokerSinkOptions(ports.readerBroker({ ...expanded, edgeControlPlane: config }, server, profile), exchange);
46
+ },
47
+ historyAdapter: policy.historyAdapter,
48
+ historyNodes(node) { return node.startsWith(policy.historyOwnerPrefix); },
49
+ historyExchange: policy.historyExchange,
50
+ historyBindings(node) { return combinedHistoryBindings(node, document, policy, ports.routes); },
51
+ keyPrefix(node) { return deploymentTemplate(policy.historyKeyPrefix, { device: node.slice(policy.historyDeviceOffset) }); }
52
+ });
53
+ }
54
+
55
+ function catalogPorts(policy, ports) {
56
+ return {
57
+ readers: ports.readers,
58
+ assignments(document, server, profile, readers) {
59
+ return server.id.startsWith(policy.historyOwnerPrefix) ? ports.localAssignments(document, server, profile.apps.scada) : readers;
60
+ },
61
+ pinned(spec) { return spec.adapter === policy.serialAdapter || spec.config?.devices?.includes('rtu:'); },
62
+ oneCopy(spec) { return spec.adapter === policy.singleReader; },
63
+ matchesInput(document, task, { from, name }, node) {
64
+ if (matchesDeviceInput(task.spec, from)) { return true; }
65
+ if (task.spec.adapter === policy.singleReader && from.startsWith(policy.hostMatchingScheme) && new URL(from).hostname === task.spec.source.host) { return true; }
66
+ return ports.readers(document, node.id, name).some(({ taskId }) => { return taskId === task.taskId; });
67
+ },
68
+ localSpec(spec, node) {
69
+ return scopeControlSecrets({ ...spec, ...(policy.localFirstWins.includes(spec.adapter) && { firstWins: true }) }, node);
70
+ },
71
+ readerSpec(spec, owner, config, document) { return readerOptions(spec, owner, config, document, { policy, ports }); },
72
+ placement: ports.placement
73
+ };
74
+ }
75
+
76
+ function checkpoint(config, node, policy) {
77
+ if (node.id !== policy.historyCheckpointNode || config.classifyApply !== true) { return {}; }
78
+ const { historyTokenSecret: name, historyTokenKey: key } = config;
79
+ if (![name, key].every((value) => { return typeof value === 'string' && value.length > 0; })) {
80
+ throw new TypeError('Collector checkpoint credential requires a Secret name and key');
81
+ }
82
+ return { [policy.historyCheckpointKey]: { valueFrom: { secretKeyRef: { name, key } } } };
83
+ }
84
+
85
+ function associatedTasks(classification, catalog) {
86
+ const tasks = classification.tasks.map((task) => {
87
+ const machine = task.spec.machine.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
88
+ const marker = new RegExp(`(?:/|"|')${machine}(?:/|"|')`, 'u');
89
+ const near = catalog.tasks.filter(({ spec }) => { return marker.test(JSON.stringify(spec)); }).map(({ taskId }) => { return taskId; });
90
+ return near.length ? { ...task, near } : task;
91
+ });
92
+ return { ...classification, tasks };
93
+ }
94
+
95
+ /** Bind reader, broker and supervisor ports to a declaratively configured control-plane release. */
96
+ export default function configuredControlPlane(policy, ports) {
97
+ function historyOwner(node) { return node.startsWith(policy.historyOwnerPrefix); }
98
+ const readers = catalogPorts(policy, ports);
99
+ return function plan(cluster, document = null) {
100
+ const source = document || ports.read();
101
+ return projectControlPlane(cluster, source, policy, {
102
+ catalog(input, config) { return compileControlCatalog(input, config, readers); },
103
+ classification(input, config, catalog) { return associatedTasks(ports.classification(input, config), catalog); },
104
+ replicas(config, input) {
105
+ const central = serverFor(input, policy.central);
106
+ const bus = central.api.find(({ id }) => { return id === policy.brokerApi; });
107
+ return ports.replicas(config.nodes, bus.url, config.writerEpoch);
108
+ },
109
+ supervisor: ports.supervisor,
110
+ historyBindings(node) { return historyOwner(node) ? ports.historyKeys() : []; },
111
+ historyMaintenance: historyOwner,
112
+ checkpoint(config, node) { return checkpoint(config, node, policy); },
113
+ reconcile(apply) { return reconciliationBundle(ports.classifierRules, { apply, catalogSecret: policy.catalogSecret }); }
114
+ });
115
+ };
116
+ }
@@ -0,0 +1,45 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import deploymentTemplate from './deploymentTemplate.js';
3
+
4
+ function sourceReader(execute, policy) {
5
+ const options = { encoding: 'utf8', timeout: 30000 };
6
+ const source = ['--context', policy.context, '--namespace', policy.namespace];
7
+ const deployment = JSON.parse(execute('kubectl', [...source, '--request-timeout=20s', 'get', policy.workload, '-o', 'json'], options));
8
+ const { env } = deployment.spec.template.spec.containers[policy.container];
9
+ return function credentials() {
10
+ return Object.fromEntries(policy.keys.map((name) => {
11
+ const field = env.find((item) => { return item.name === name; });
12
+ if (field?.value !== undefined) { return [name, field.value]; }
13
+ if (!field?.valueFrom?.secretKeyRef) { throw new Error(deploymentTemplate(policy.missingKey, { name })); }
14
+ const ref = field.valueFrom.secretKeyRef;
15
+ const secret = JSON.parse(execute('kubectl', [...source, 'get', `secret/${ref.name}`, '-o', 'json'], options));
16
+ return [name, Buffer.from(secret.data[ref.key], 'base64').toString('utf8')];
17
+ }));
18
+ };
19
+ }
20
+
21
+ /** Copy declared workload credentials and initialize absent database credentials. */
22
+ export default function configuredDeploymentCredentials(policy) {
23
+ return function prepare(execute, settings, cluster = policy.defaultTarget) {
24
+ const { namespace, fieldManager } = policy;
25
+ const postgres = settings[policy.databaseSetting];
26
+ const runtime = settings[policy.runtimeSetting];
27
+ const read = sourceReader(execute, policy.source);
28
+ function kube(args, input) {
29
+ return execute('kubectl', ['--context', cluster, '--namespace', namespace, '--request-timeout=20s', ...args],
30
+ { input, encoding: 'utf8', stdio: ['pipe', 'pipe', 'inherit'], timeout: 30000 });
31
+ }
32
+ function create(name, stringData) {
33
+ const object = { apiVersion: 'v1', kind: 'Secret', metadata: { name, namespace }, type: 'Opaque', stringData };
34
+ kube(['apply', '--server-side', `--field-manager=${fieldManager}`, '-f', '-'], JSON.stringify(object));
35
+ }
36
+ const raw = kube(['get', `secret/${postgres}`, '--ignore-not-found', '-o', 'json']).trim();
37
+ const credentials = read();
38
+ if (!raw) {
39
+ const password = randomBytes(24).toString('hex');
40
+ create(postgres, deploymentTemplate(policy.database, { password }));
41
+ }
42
+ create(runtime, credentials);
43
+ return { postgres, runtime };
44
+ };
45
+ }
@@ -0,0 +1,30 @@
1
+ import deploymentTemplate from './deploymentTemplate.js';
2
+
3
+ function membersOf(members, learner) {
4
+ return members.filter((item) => { return (item.learner === true) === learner; }).map(({ name }) => { return name; });
5
+ }
6
+
7
+ function grants(prefix, nodeIds, policy) {
8
+ return [...deploymentTemplate(policy.shared ?? [], { prefix }),
9
+ ...nodeIds.map((id) => { return deploymentTemplate(policy.node, { id, prefix }); })];
10
+ }
11
+
12
+ /** Inspect a quorum and compile declared namespaced grants. */
13
+ export default function configuredEtcdInventory(policy) {
14
+ const { members, client } = policy;
15
+ return {
16
+ inventory(snapshot) {
17
+ const services = snapshot.services ?? [];
18
+ const live = snapshot.members ?? [];
19
+ return { voters: membersOf(live, false), learners: membersOf(live, true),
20
+ localTraffic: services.length > 0 && services.every(({ externalTrafficPolicy }) => { return externalTrafficPolicy === 'Local'; }),
21
+ clientPort: snapshot.clientPort ?? members.clientPort, peerPort: snapshot.peerPort ?? members.peerPort };
22
+ },
23
+ nextLearner(liveVoters) { return members.voters.find((id) => { return !liveVoters.includes(id); }) ?? null; },
24
+ targetMembers() { return { ...members, voters: [...members.voters], agents: [...members.agents] }; },
25
+ roles(prefix, nodeIds) { return grants(prefix, nodeIds, policy.control); },
26
+ claimRoles(prefix, nodeIds) { return grants(prefix, nodeIds, policy.claims); },
27
+ clientSubject() { return client.subject; },
28
+ clientExtensions() { return client.extensions; }
29
+ };
30
+ }
@@ -0,0 +1,54 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import executeKubeSeed from './executeKubeSeed.js';
3
+ import deploymentTemplate from './deploymentTemplate.js';
4
+
5
+ function transfer({ table, columns, where, identity, exportQuery }, lock) {
6
+ const names = columns.join(',');
7
+ const exportSql = exportQuery ?? `COPY (SELECT ${names} FROM ${table} WHERE ${where}) TO STDOUT WITH CSV`;
8
+ const imported = columns.map((name) => { return `s.${name}`; }).join(',');
9
+ return { table, export: exportSql, import: [
10
+ `SELECT pg_advisory_xact_lock(hashtextextended('${lock}',0))`,
11
+ `CREATE TEMP TABLE seed_rows (LIKE ${table}) ON COMMIT DROP`,
12
+ `COPY seed_rows (${names}) FROM STDIN WITH CSV`,
13
+ `INSERT INTO ${table} (${names}) SELECT DISTINCT ${imported} FROM seed_rows s WHERE ${where} AND NOT EXISTS (SELECT 1 FROM ${table} d WHERE ${identity}) ON CONFLICT DO NOTHING`
14
+ ].join(';\n') };
15
+ }
16
+
17
+ function validateSeed(source, target, hours, maximumHours) {
18
+ if (!Number.isInteger(hours) || hours < 1 || hours > maximumHours) { throw new Error(`Seed hours must be 1..${maximumHours}`); }
19
+ if (!/^[a-zA-Z0-9_.-]+$/u.test(source) || source === target) { throw new Error('Separate exact central context required'); }
20
+ }
21
+
22
+ function seedTasks(tables, policy) {
23
+ const sql = policy.postgres;
24
+ return tables.map((table) => {
25
+ const { pod, command } = policy.readers[table.table] ?? policy.readers.default;
26
+ const statements = table.import.split(';\n').flatMap((statement) => { return ['-c', statement]; });
27
+ return { name: table.table, read: [pod, ...command, table.export],
28
+ write: [policy.destinationPod, ...sql, '--single-transaction', ...statements] };
29
+ });
30
+ }
31
+
32
+ /** Prepare and run a bounded read-only export and an idempotent history import. */
33
+ export default function configuredHistorySeed(policy, resolve) {
34
+ function plan(target, { hours = policy.defaultHours, centralContext = policy.sourceContext, document } = {}) {
35
+ const placement = resolve(target, document);
36
+ if (!placement.deploymentEnabled) { throw new Error('Target deployment is disabled'); }
37
+ validateSeed(centralContext, target, hours, policy.maximumHours);
38
+ const specs = deploymentTemplate(policy.tables, { ...placement, hours });
39
+ const tables = specs.map((table) => { return transfer(table, policy.lock); });
40
+ return { target, nodeAddress: placement.nodeAddress, machine: placement.machine, centralContext, hours, tables };
41
+ }
42
+ function run(target, action = 'plan', options = {}, execute = execFileSync) {
43
+ const desired = plan(target, options);
44
+ if (action === 'plan') { return desired; }
45
+ if (action !== 'apply') { throw new Error('Seed action must be plan or apply'); }
46
+ const tables = executeKubeSeed({
47
+ source: { context: desired.centralContext, namespace: policy.sourceNamespace },
48
+ destination: { context: target, namespace: policy.destinationNamespace, nodeAddress: desired.nodeAddress },
49
+ allowedPods: policy.allowedPods, transfers: seedTasks(desired.tables, policy)
50
+ }, execute);
51
+ return { target, machine: desired.machine, tables };
52
+ }
53
+ return { plan, run };
54
+ }
@@ -0,0 +1,23 @@
1
+ import expand from '../../application/deploy/expand.js';
2
+ import operatePostgresMaintenance from './operatePostgresMaintenance.js';
3
+ import postgresMaintenancePlan from './postgresMaintenancePlan.js';
4
+
5
+ /** Bind an existing chart's PostgreSQL workload and storage to the maintenance operations. */
6
+ export default function configuredPostgresMaintenance({ allowed, namespace, addressApi, fallbackClaim, pod, restore }, load, sourceFor) {
7
+ function plan(target, backupId, { attempt = 1, document } = {}) {
8
+ if (!allowed.includes(target)) { throw new TypeError('Exact database edge target required'); }
9
+ const input = document ?? load();
10
+ const { enabled, postgres } = sourceFor(target, input);
11
+ const server = expand(input).servers.find(({ id }) => { return id === target; });
12
+ const nodeAddress = new URL(server.api.find(({ id }) => { return id === addressApi; }).url).hostname;
13
+ return postgresMaintenancePlan({ ...restore, context: target, namespace, enabled, nodeAddress,
14
+ claim: postgres.existingClaim ?? fallbackClaim, pod }, backupId, attempt);
15
+ }
16
+ function operate(target, action, { execute, backupId, attempt = 1, document } = {}) {
17
+ if (!['plan', 'backup', 'verify-restore', 'status'].includes(action)) { throw new TypeError('Unknown edge data action'); }
18
+ const desired = plan(target, backupId ?? (action === 'status' ? '19700101-status' : undefined), { attempt, document });
19
+ const result = operatePostgresMaintenance(desired, action, execute);
20
+ return action === 'status' ? { ...result, backupId } : result;
21
+ }
22
+ return { plan, operate };
23
+ }
@@ -0,0 +1,14 @@
1
+ import deploymentTemplate, { deploymentCondition } from './deploymentTemplate.js';
2
+ import verifyRuntimeCapabilities from './verifyRuntimeCapabilities.js';
3
+
4
+ /** Check declared runtime roles only when the corresponding release feature is enabled. */
5
+ export default function configuredRuntimeCapabilities(policy) {
6
+ return function preflight(plan, execute) {
7
+ if (!deploymentCondition(policy.feature, plan)) { return; }
8
+ const { images, protocol } = deploymentTemplate(policy.selection, plan);
9
+ verifyRuntimeCapabilities({
10
+ candidates: Object.entries(policy.roles).map(([role, command]) => { return { role, image: images[role], ...command }; }),
11
+ required: [protocol], match: policy.match, subject: policy.subject, mismatch: policy.mismatch
12
+ }, execute);
13
+ };
14
+ }