@yarkivaev/scada 2.17.0 → 2.18.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 (52) hide show
  1. package/index.js +1 -2
  2. package/package.json +3 -2
  3. package/src/application/deploy/collectorSourcePlan.js +97 -0
  4. package/src/application/deploy/compileCollectorTasks.js +31 -0
  5. package/src/application/deploy/compileControlCatalog.js +66 -0
  6. package/src/application/deploy/controlPlan.js +16 -0
  7. package/src/application/deploy/controlPlaneConfiguration.js +62 -0
  8. package/src/application/deploy/controlReaderSpecs.js +37 -0
  9. package/src/application/deploy/liveReleaseOverlay.js +17 -0
  10. package/src/application/deploy/projectControlPlane.js +48 -0
  11. package/src/application/deploy/projectTopology.js +41 -0
  12. package/src/infrastructure/deploy/brokerReplicaTopology.js +34 -12
  13. package/src/infrastructure/deploy/brokerSecurity.js +89 -0
  14. package/src/infrastructure/deploy/brokerSecurityInput.js +85 -0
  15. package/src/infrastructure/deploy/brokerTopology.js +125 -0
  16. package/src/infrastructure/deploy/centralTelemetry.js +51 -0
  17. package/src/infrastructure/deploy/clickhouseTelemetryPolicy.js +64 -0
  18. package/src/infrastructure/deploy/collectorChartPlan.js +68 -0
  19. package/src/infrastructure/deploy/configuredHistorySeed.js +54 -0
  20. package/src/infrastructure/deploy/configuredPostgresMaintenance.js +23 -0
  21. package/src/infrastructure/deploy/databaseSecurity.js +39 -0
  22. package/src/infrastructure/deploy/deploymentRecovery.js +49 -0
  23. package/src/infrastructure/deploy/deploymentTemplate.js +67 -0
  24. package/src/infrastructure/deploy/executeConfiguredChartDeployment.js +65 -0
  25. package/src/infrastructure/deploy/executeManagedDeployment.js +46 -0
  26. package/src/infrastructure/deploy/highAvailability/brokerOwnership.js +19 -0
  27. package/src/infrastructure/deploy/highAvailability/catalogReconciler.js +61 -0
  28. package/src/infrastructure/deploy/highAvailability/classifyFederation.js +57 -0
  29. package/src/infrastructure/deploy/highAvailability/classifyGate.js +114 -0
  30. package/src/infrastructure/deploy/highAvailability/classifyLoop.js +139 -0
  31. package/src/infrastructure/deploy/highAvailability/classifyShovels.js +70 -0
  32. package/src/infrastructure/deploy/highAvailability/classifyWatermark.js +45 -0
  33. package/src/infrastructure/deploy/highAvailability/compileClassifierRules.js +21 -0
  34. package/src/infrastructure/deploy/highAvailability/controllerReconcile.js +14 -0
  35. package/src/infrastructure/deploy/highAvailability/historyReceiver.js +49 -0
  36. package/src/infrastructure/deploy/highAvailability/historyWatermark.js +42 -0
  37. package/src/infrastructure/deploy/highAvailability/index.js +14 -0
  38. package/src/infrastructure/deploy/highAvailability/reconcileBrokerThroughController.js +18 -0
  39. package/src/infrastructure/deploy/highAvailability/reconciliationBundle.js +28 -0
  40. package/src/infrastructure/deploy/highAvailability/segmentAdmit.js +24 -0
  41. package/src/infrastructure/deploy/highAvailability/segmentPublish.js +27 -0
  42. package/src/infrastructure/deploy/highAvailability/supervisorReplica.js +36 -0
  43. package/src/infrastructure/deploy/index.js +27 -2
  44. package/src/infrastructure/deploy/projectClassification.js +42 -0
  45. package/src/infrastructure/deploy/securityPolicy.js +16 -0
  46. package/src/infrastructure/ingest/telemetry/centralPolicy.js +29 -8
  47. package/src/infrastructure/management/kiosk/kioskDeployment.js +60 -0
  48. package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +47 -0
  49. package/src/infrastructure/mdmesh/index.js +2 -0
  50. package/src/infrastructure/mdmesh/mdmeshServerRelease.js +58 -0
  51. package/src/infrastructure/messaging/rabbitmq/definitions.js +12 -6
  52. package/src/infrastructure/opcua/projectSources.js +36 -0
@@ -0,0 +1,85 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import { databaseSecurity } from './databaseSecurity.js';
3
+ import { brokerPolicy } from './securityPolicy.js';
4
+
5
+ /** Deployment supplies an ephemeral 0600 file decrypted from its existing secret store. */
6
+ export default function brokerSecurityInput(path) {
7
+ if (!path) { return undefined; }
8
+ try {
9
+ const metadata = statSync(path);
10
+ // eslint-disable-next-line no-bitwise -- Inspect POSIX group/other permission bits.
11
+ if (!metadata.isFile() || (metadata.mode & 0o077)) { throw new Error(); }
12
+ const security = JSON.parse(readFileSync(path, 'utf8'));
13
+ if (!security || typeof security !== 'object' || Array.isArray(security)) { throw new Error(); }
14
+ brokerPolicy(security);
15
+ return security;
16
+ } catch {
17
+ // Never allow JSON parser diagnostics to echo a secret fragment.
18
+ throw new TypeError('Broker security input must be a valid protected 0600 JSON file');
19
+ }
20
+ }
21
+
22
+ const phases = { prepare: 1, switch: 2, retire: 3 };
23
+ function captured(execute, { cluster, namespace }, args) {
24
+ try {
25
+ return String(execute('kubectl', ['--context', cluster, '--namespace', namespace, ...args],
26
+ { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }) || '').trim();
27
+ } catch { throw new Error('Cannot verify persisted broker controller state'); }
28
+ }
29
+ function namedBrokerUsers(users, ignorePattern) {
30
+ return users.split('\n').map(row => { return row.trim().split(/\s+/u)[0]; }).filter(name => { return name && name !== 'guest' && !ignorePattern?.test(name); });
31
+ }
32
+ function livePhase(state) {
33
+ const annotations = { ...state.metadata?.annotations, ...state.spec?.template?.metadata?.annotations };
34
+ const recorded = Object.entries(annotations).filter(([name]) => { return name.includes('broker-security-phase'); });
35
+ const volumes = state.spec?.template?.spec?.volumes || [];
36
+ const mounts = (state.spec?.template?.spec?.containers || []).flatMap(row => { return row.volumeMounts || []; });
37
+ const definitions = new Set(mounts.filter(row => { return row.mountPath?.endsWith('/definitions.json'); }).map(row => { return row.name; }));
38
+ const mounted = volumes.some(row => { return row.secret && (definitions.has(row.name) || row.name.includes('definitions')); });
39
+ return Math.max(mounted ? 1 : 0, ...recorded.map(([, phase]) => { return phases[phase] || 0; }));
40
+ }
41
+ function verifyLiveDatabase(state, canonical) {
42
+ const verified = (state.spec?.template?.spec?.containers || []).filter((container) => {
43
+ return (container.env || []).some((field) => { return field.name === 'SUPERVISOR_MIGRATIONS' && field.value === 'verify'; });
44
+ });
45
+ for (const container of verified) {
46
+ const env = Object.fromEntries((container.env || []).map((field) => { return [field.name,field]; }));
47
+ const reference = env.POSTGRES_URL?.valueFrom?.secretKeyRef;
48
+ if (!canonical || !reference || reference.name !== canonical.runtimeSecret || reference.key !== canonical.runtimeKey) {
49
+ throw new Error('Persisted database verification policy missing or mismatched');
50
+ }
51
+ }
52
+ }
53
+
54
+ /** Private reads precede every deploy mutation; render remains strictly offline. */
55
+ // eslint-disable-next-line max-statements -- Resolve persisted credentials and reject downgrade before the first deployment write.
56
+ export function readDeployedBrokerSecurity(action, target, execute, explicit) {
57
+ if (action === 'render') { brokerPolicy(explicit); return explicit; }
58
+ const { controllerSecret, brokerWorkload, applicationWorkload, ignoreUserPrefix, repairMessage } = target;
59
+ try {
60
+ const raw = captured(execute, target, ['get', controllerSecret, '--ignore-not-found', '-o', 'json']);
61
+ const controller = raw ? JSON.parse(Buffer.from(JSON.parse(raw).data['security.json'], 'base64').toString('utf8')) : undefined;
62
+ const workload = captured(execute, target, ['get', brokerWorkload, '--ignore-not-found', '-o', 'json']);
63
+ const state = workload ? JSON.parse(workload) : {};
64
+ const persisted = livePhase(state);
65
+ const security = explicit || controller;
66
+ const broker = brokerPolicy(security);
67
+ const previousBroker = brokerPolicy(controller);
68
+ const previousDatabase = databaseSecurity(controller);
69
+ const application = captured(execute, target, ['get', applicationWorkload, '--ignore-not-found', '-o', 'json']);
70
+ verifyLiveDatabase(application ? JSON.parse(application) : {}, previousDatabase);
71
+ if (previousDatabase && JSON.stringify(previousDatabase) !== JSON.stringify(databaseSecurity(security))) { throw new Error(); }
72
+ if (!previousBroker && persisted) { throw new Error(); }
73
+ const minimum = Math.max(persisted, phases[previousBroker?.phase] || 0);
74
+ if (minimum && !broker) { throw new Error(); }
75
+ if (!previousBroker && workload) {
76
+ const users = captured(execute, target, ['exec', brokerWorkload, '--', 'rabbitmqctl', '-s', 'list_users']);
77
+ if (namedBrokerUsers(users, ignoreUserPrefix).length) { throw new Error(); }
78
+ }
79
+ if (broker && phases[broker.phase] < minimum) { throw new Error(); }
80
+ return security;
81
+ } catch {
82
+ // Captured stdout/stderr, parser errors and decoded JSON must never escape.
83
+ throw new Error(repairMessage ?? 'Broker controller Secret missing, invalid, or migration phase would downgrade');
84
+ }
85
+ }
@@ -0,0 +1,125 @@
1
+ import subscriptions from '../../application/deploy/subscriptions.js';
2
+ import rabbitmqDefinitions from '../messaging/rabbitmq/definitions.js';
3
+
4
+ export { brokerShovel } from '../messaging/rabbitmq/definitions.js';
5
+
6
+ /** Normalize an AMQP URL with an optional fallback or overriding identity. */
7
+ export function brokerUri(uri, { username, password, override = false } = {}) {
8
+ const parsed = new URL(uri);
9
+ if (username && (override || !parsed.username)) {
10
+ parsed.username = username;
11
+ parsed.password = password;
12
+ }
13
+ return parsed.toString().replace(/\/$/u, '');
14
+ }
15
+
16
+ /** Resolve a declared service or a broker NodePort on the host of another service. */
17
+ export function brokerEndpoint(document, node, { service, fallbackService, fallbackPort, identity } = {}) {
18
+ const services = document.servers?.find(({ id }) => { return id === node; })?.api || [];
19
+ const direct = services.find(({ id }) => { return id === service; })?.url;
20
+ if (direct) { return identity ? brokerUri(direct, identity) : direct; }
21
+ const fallback = services.find(({ id }) => { return id === fallbackService; })?.url;
22
+ if (!fallback || !fallbackPort) { throw new TypeError(`Missing broker endpoint for ${node}`); }
23
+ const uri = `amqp://${new URL(fallback).hostname}:${fallbackPort}`;
24
+ return identity ? brokerUri(uri, identity) : uri;
25
+ }
26
+
27
+ /** Merge federation resources and restrict bindings to keys published at this node. */
28
+ export function attachBrokerMesh(document, node, topology, { peers, endpoint, federation, restrict }) {
29
+ const present = new Set((document.servers || []).map(({ id }) => { return id; }));
30
+ if (!peers.includes(node) || !present.has(node)) { return topology; }
31
+ const endpoints = Object.fromEntries(peers.filter((id) => { return present.has(id); }).flatMap((id) => {
32
+ try { return [[id, endpoint(document, id)]]; } catch { return []; }
33
+ }));
34
+ const extra = federation(node, endpoints);
35
+ for (const kind of ['parameters', 'policies', 'bindings']) {
36
+ topology[kind] = [...topology[kind] || [], ...extra[kind] || []];
37
+ }
38
+ for (const kind of ['queues', 'exchanges']) {
39
+ const names = new Set((topology[kind] || []).map(({ name }) => { return name; }));
40
+ topology[kind] = [...topology[kind] || [], ...(extra[kind] || []).filter(({ name }) => { return !names.has(name); })];
41
+ }
42
+ if (restrict) {
43
+ topology.bindings = topology.bindings.map((row) => {
44
+ if (row.destination !== restrict.queue || !Object.hasOwn(restrict.keys, row.routing_key)) { return row; }
45
+ return { ...row, routing_key: restrict.keys[row.routing_key] };
46
+ });
47
+ }
48
+ return topology;
49
+ }
50
+
51
+ /** Publishers on an API and physical inputs local to the broker. */
52
+ export function brokerStreamRoutes(source, { service, passive, local }) {
53
+ const publishers = source.api.find(({ id }) => { return id === service; })?.publishes || [];
54
+ return [...publishers.map(passive), ...source.fan_in.filter(({ from }) => { return from.includes('://'); }).map(local)];
55
+ }
56
+
57
+ /** Use a family wildcard when every declared route in that family is subscribed. */
58
+ export function brokerStreamBindings(routes, subscribed) {
59
+ const families = new Map();
60
+ routes.forEach((row) => {
61
+ if (!row.family) { return; }
62
+ if (!families.has(row.family)) { families.set(row.family, []); }
63
+ families.get(row.family).push(row);
64
+ });
65
+ return [...new Set([...families].flatMap(([family, rows]) => {
66
+ const selected = rows.filter(({ name }) => { return subscribed.has(name); });
67
+ return selected.length === rows.length ? [`${family}.#`] : selected.flatMap(({ keys }) => { return keys; });
68
+ }))];
69
+ }
70
+
71
+ /** Effective physical inputs and subscriptions when one broker also hosts a peer's inputs. */
72
+ export function brokerStreams(document, source, { service, additionalSource }) {
73
+ const additional = additionalSource && document.servers.find(({ id }) => { return id === additionalSource; });
74
+ const host = additional ? { ...source, fan_in: [...source.fan_in,
75
+ ...additional.fan_in.filter(({ from }) => { return from.includes('://'); })] } : source;
76
+ const links = [...subscriptions(document, source.id), ...(additional ? subscriptions(document, additional.id) : [])]
77
+ .filter(({ api }) => { return !api || api === service; });
78
+ return {
79
+ host,
80
+ subscriptionsTo(to) {
81
+ return new Set(links.filter((row) => { return row.to === to; }).map(({ name }) => { return name; }));
82
+ }
83
+ };
84
+ }
85
+
86
+ /** One outbox per route group selected by the downstream subscription. */
87
+ export function brokerPeerOutboxes(peer, routes, subscribed, outbox) {
88
+ const rows = routes.filter(({ peer: group, name }) => { return group && subscribed.has(name); });
89
+ return [...new Set(rows.map(({ peer: group }) => { return group; }))].map((group) => {
90
+ const selected = rows.filter((row) => { return row.peer === group; });
91
+ return { ...outbox(group, peer), keys: [...new Set(selected.flatMap(({ keys }) => { return keys; }))] };
92
+ });
93
+ }
94
+
95
+ /** Durable forwarders to a declared endpoint, skipping families with no subscribed keys. */
96
+ export function brokerOutboxes(families, { sourceUri, destinationUri, reconnectDelay, exchange, destination }) {
97
+ return families.filter(({ keys }) => { return keys.length; }).map(({ family, keys }) => {
98
+ const name = exchange(family);
99
+ return { exchange: name, queue: `${name}.outbox`, keys,
100
+ shovel: { name: `${family.replaceAll('_', '-')}-to-${destination}`, sourceUri, destinationUri,
101
+ destinationExchange: name, reconnectDelay } };
102
+ });
103
+ }
104
+
105
+ /** Add durable queues, typed bindings, and missing topic exchanges to a definition. */
106
+ export function appendBrokerResources(result, { vhost = '/', exchanges = [], queues = [], bindings = [] }) {
107
+ const resources = rabbitmqDefinitions({ vhost, queues, exchanges });
108
+ const names = new Set(result.exchanges.filter((row) => { return row.vhost === vhost; }).map(({ name }) => { return name; }));
109
+ result.exchanges.push(...resources.exchanges.filter(({ name }) => { return !names.has(name); })
110
+ .map((row) => { return { ...row, arguments: {} }; }));
111
+ result.queues.push(...resources.queues);
112
+ result.bindings.push(...bindings.map(({ source, destination, key, type = 'queue' }) => {
113
+ return { source, vhost, destination, destination_type: type, routing_key: key, arguments: {} };
114
+ }));
115
+ return result;
116
+ }
117
+
118
+ /** Declare topic exchanges and the queue bindings needed by a collector. */
119
+ export function brokerSinkOptions(broker, exchange) {
120
+ const bindings = broker.bindings.filter(({ source }) => { return source === exchange; });
121
+ const queues = new Set(bindings.map(({ destination }) => { return destination; }));
122
+ return { exchanges: [{ name: exchange, type: 'topic', options: { durable: true } }],
123
+ queues: [...queues].map((name) => { return { name, options: { durable: true, autoDelete: false } }; }),
124
+ bindings: bindings.map(({ destination, source, routing_key: pattern }) => { return { queue: destination, exchange: source, pattern }; }) };
125
+ }
@@ -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,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,39 @@
1
+ function secretName(value) {
2
+ return typeof value === 'string' && value.length <= 253 && !/[^a-z0-9.-]/u.test(value)
3
+ && value.split('.').every((label) => { return label.length <= 63 && /^[a-z0-9](?:[-a-z0-9]*[a-z0-9])?$/u.test(label); });
4
+ }
5
+
6
+ /** Only public Secret references belong in database deployment policy. */
7
+ export function databaseSecurity(security) {
8
+ const database = security?.database;
9
+ if (database === undefined) { return undefined; }
10
+ if (!database || typeof database !== 'object' || Array.isArray(database)
11
+ || Object.keys(database).some((key) => { return !['migrationsMode','runtimeSecret','runtimeKey'].includes(key); })
12
+ || database.migrationsMode !== 'verify'
13
+ || !secretName(database.runtimeSecret)) { throw new TypeError('Database security requires verify mode and a named runtime Secret'); }
14
+ const runtimeKey = database.runtimeKey === undefined ? 'url' : database.runtimeKey;
15
+ if (typeof runtimeKey !== 'string' || !runtimeKey || runtimeKey.length > 253 || /[^-._a-zA-Z0-9]/u.test(runtimeKey)
16
+ || ['postgres_admin_url','adminurl'].includes(runtimeKey.toLowerCase())) { throw new TypeError('Database runtime key must name a restricted connection URL'); }
17
+ return {migrationsMode:database.migrationsMode,runtimeSecret:database.runtimeSecret,runtimeKey};
18
+ }
19
+
20
+ export function databaseEnvironment(environment, security, apiSecret) {
21
+ const database = databaseSecurity(security);
22
+ if (!database) { return environment; }
23
+ if (database.runtimeSecret === apiSecret && database.runtimeKey !== 'POSTGRES_URL') {
24
+ throw new TypeError('Database runtime reference in the application Secret must use POSTGRES_URL');
25
+ }
26
+ const result = {...environment,SUPERVISOR_MIGRATIONS:'verify',POSTGRES_URL:{valueFrom:{secretKeyRef:{
27
+ name:database.runtimeSecret,key:database.runtimeKey}}}};
28
+ delete result.POSTGRES_ADMIN_URL;
29
+ return result;
30
+ }
31
+
32
+ export function databaseValues(postgres, security) {
33
+ const database = databaseSecurity(security);
34
+ if (!database) { return postgres; }
35
+ if (database.runtimeSecret === postgres.secret || database.runtimeKey !== 'url') {
36
+ throw new TypeError('Database chart runtime Secret must be distinct from bootstrap and use the url key');
37
+ }
38
+ return {...postgres,runtimeSecret:database.runtimeSecret,migrationsMode:'verify'};
39
+ }
@@ -0,0 +1,49 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import bootstrapKubeStorage from './bootstrapKubeStorage.js';
3
+ import { deploymentStage } from './compileDeploymentHooks.js';
4
+ import { waitForJob } from './deploymentChecks.js';
5
+ import prepareKubePrerequisites from './prepareKubePrerequisites.js';
6
+
7
+ function prerequisiteObjects(plan, policy, objects, podCidrs) {
8
+ const storage = deploymentStage(plan, policy.storageStage).values;
9
+ const namespaces = policy.namespaces.map((name) => { return { apiVersion: 'v1', kind: 'Namespace', metadata: { name } }; });
10
+ const claims = Object.entries(policy.claims).map(([name, role]) => {
11
+ const { storageClass, storage: size } = storage[role];
12
+ return { apiVersion: 'v1', kind: 'PersistentVolumeClaim', metadata: { name, namespace: plan.namespace },
13
+ spec: { accessModes: ['ReadWriteOnce'], storageClassName: storageClass, resources: { requests: { storage: size } } } };
14
+ });
15
+ return [...namespaces, ...objects(podCidrs), ...claims];
16
+ }
17
+
18
+ function preparePlan(plan, policy, objects, action, { execute, secrets }) {
19
+ return prepareKubePrerequisites({
20
+ context: plan.context, enabled: plan.deploymentEnabled, nodeAddress: plan.nodeAddress,
21
+ requirePodCidrs: policy.requirePodCidrs, namespaces: policy.namespaces, credentials: policy.credentials,
22
+ objects(podCidrs) { return prerequisiteObjects(plan, policy, objects, podCidrs); }
23
+ }, action, { execute, secrets });
24
+ }
25
+
26
+ function bootstrap(plan, policy, objects, action, execute) {
27
+ if (!plan.deploymentEnabled) { throw new Error(`${plan.context} deployment disabled: target is offline`); }
28
+ const { missing } = preparePlan(plan, policy, objects, 'check', { execute });
29
+ if (missing.length) { throw new Error(`Prepare prerequisites first: ${missing.join(', ')}`); }
30
+ const stage = { ...deploymentStage(plan, policy.storageStage) };
31
+ if (policy.job) { stage.afterReady = (_ready, kube) => { waitForJob(kube, plan.prerequisites[policy.job]); }; }
32
+ return bootstrapKubeStorage({ context: plan.context, namespace: plan.namespace, storage: policy.workloads, stage }, action, execute);
33
+ }
34
+
35
+ /** Prepare prerequisites and stage durable storage without starting application readers. */
36
+ export default function deploymentRecovery({ policy, planFor, objects }) {
37
+ return {
38
+ prerequisites(target, document, podCidrs = []) {
39
+ return prerequisiteObjects(planFor(target, document), policy, objects, podCidrs);
40
+ },
41
+ prepare(target, action = 'check', { execute, secrets, document } = {}) {
42
+ return preparePlan(planFor(target, document), policy, objects, action, { execute, secrets });
43
+ },
44
+ bootstrap(target, action = 'check', { execute = execFileSync, document } = {}) {
45
+ if (!['check', 'apply'].includes(action)) { throw new TypeError('Storage bootstrap action must be check or apply'); }
46
+ return bootstrap(planFor(target, document), policy, objects, action, execute);
47
+ }
48
+ };
49
+ }
@@ -0,0 +1,67 @@
1
+ function reference(bindings, path, optional = false) {
2
+ if (typeof path !== 'string' || !path.length) { throw new TypeError('Invalid template reference'); }
3
+ let value = bindings;
4
+ for (const key of path.split('.')) {
5
+ if (value === null || value === undefined || !Object.hasOwn(value, key)) {
6
+ if (optional) { return undefined; }
7
+ throw new TypeError(`Unknown template reference ${path}`);
8
+ }
9
+ value = value[key];
10
+ }
11
+ return value;
12
+ }
13
+
14
+ function interpolate(source, bindings) {
15
+ return source.replace(/\{\{(?<path>[\w.-]+)\}\}/gu, (_match, path) => {
16
+ const value = reference(bindings, path);
17
+ if (!['string', 'number', 'boolean'].includes(typeof value)) { throw new TypeError(`Template reference ${path} must be scalar`); }
18
+ return String(value);
19
+ });
20
+ }
21
+
22
+ function directives(bindings, text, render) {
23
+ return {
24
+ $ref(path) { return reference(bindings, path); },
25
+ $string(value) { return String(render(value)); },
26
+ $json(value) { return JSON.stringify(render(value)); },
27
+ $text(value) {
28
+ if (!text) { throw new TypeError('Deployment template requires an asset reader'); }
29
+ return text(render(value));
30
+ }
31
+ };
32
+ }
33
+
34
+ /** Resolve typed references and text placeholders using explicitly supplied bindings. */
35
+ export default function deploymentTemplate(template, bindings, { text } = {}) {
36
+ function render(value) {
37
+ if (typeof value === 'string') { return interpolate(value, bindings); }
38
+ if (Array.isArray(value)) { return value.map(render); }
39
+ if (value === null || typeof value !== 'object') { return value; }
40
+ const entries = Object.entries(value);
41
+ const [key, parameter] = entries[0] ?? [];
42
+ const operations = directives(bindings, text, render);
43
+ if (entries.length === 1 && Object.hasOwn(operations, key)) { return operations[key](parameter); }
44
+ return Object.fromEntries(entries.map(([name, item]) => { return [name, render(item)]; }));
45
+ }
46
+ return render(template);
47
+ }
48
+
49
+ /** Check whether a binding enables a declarative deployment item. */
50
+ export function deploymentCondition(path, bindings) {
51
+ return Boolean(reference(bindings, path, true));
52
+ }
53
+
54
+ function expandReferences(entry, bindings) {
55
+ if (typeof entry === 'string') { return [deploymentTemplate(entry, bindings)]; }
56
+ if (entry.when && !deploymentCondition(entry.when, bindings)) { return []; }
57
+ const rows = entry.each === undefined ? [bindings] : reference(bindings, entry.each).map((item) => { return { ...bindings, item }; });
58
+ const resources = rows.flatMap((row) => {
59
+ return entry.group ? entry.group.flatMap((child) => { return expandReferences(child, row); }) : deploymentTemplate(entry.resources, row);
60
+ });
61
+ return entry.unique ? [...new Set(resources)] : resources;
62
+ }
63
+
64
+ /** Expand required and conditionally enabled resource references in declared order. */
65
+ export function deploymentReferences(entries, bindings) {
66
+ return entries.flatMap((entry) => { return expandReferences(entry, bindings); });
67
+ }