@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,49 @@
1
+ import runRetention from '../../ingest/db/runRetention.js';
2
+ import supervisorSink from '../../../application/supervisorSink.js';
3
+ import historyApi from './historyWatermark.js';
4
+ import amqpSource from '../../streams/amqpSource.js';
5
+ import segmentAdmit, { grantedEpoch } from './segmentAdmit.js';
6
+ import segmentPublish from './segmentPublish.js';
7
+ import abutSegments from '../../ingest/sinks/abutSegments.js';
8
+ import silenceBudget from '../../../domain/segment/silenceBudget.js';
9
+
10
+ function apiOptions(sink) {
11
+ return {
12
+ port: sink.apiPort, token: sink.apiToken, metricsEnabled: sink.metricsEnabled,
13
+ retentionEnabled: sink.retentionEnabled, retentionDays: sink.retentionDays,
14
+ requestTimeoutMs: sink.requestTimeoutMs, pool: sink.pool, runRetention, health: sink.health
15
+ };
16
+ }
17
+
18
+ /** AMQP delivery adapter. A string payload is the same body the tests pass through. */
19
+ export function segmentCollector(epoch, publish) {
20
+ const admit = segmentAdmit(epoch, publish);
21
+ return {
22
+ accept(delivery) {
23
+ const payload = delivery.content ? delivery.content.toString() : delivery;
24
+ return admit(payload);
25
+ }
26
+ };
27
+ }
28
+
29
+ function historyData(env, ports, history) {
30
+ return (data, pool) => {
31
+ const next = ports.sinkOptions?.stateData?.(data, pool) ?? data;
32
+ return { ...next, history: history(pool, { retentionDays: Number(env.HISTORY_RETENTION_DAYS ?? 30) }) };
33
+ };
34
+ }
35
+
36
+ /** Starts the admit consumer, then the history API. Pipelines cannot be turned back on here. */
37
+ export default async function runHistoryReceiver(env, { sinkOptions, history, destinationQueue, sourceQueue }, ports = {}) {
38
+ const epoch = grantedEpoch(env.SUPERVISOR_WRITER_EPOCH);
39
+ const sink = (ports.sinkFactory ?? supervisorSink)({ ...env, SINK_PIPELINES: 'false' }, { ...sinkOptions, ...ports.sinkOptions, stateData: historyData(env, ports, history) });
40
+ const http = (ports.apiFactory ?? historyApi)(sink.dataAccess, apiOptions(sink));
41
+ const destination = env.SEGMENT_ADMIT_DESTINATION ?? destinationQueue;
42
+ const outbound = ports.outbound ?? segmentPublish(env.HISTORY_AMQP_URL, destination);
43
+ await outbound.start();
44
+ const source = (ports.sourceFactory ?? amqpSource)(env.HISTORY_AMQP_URL, env.SEGMENT_ADMIT_QUEUE ?? sourceQueue,
45
+ segmentCollector(epoch, (body) => { return outbound.write(body); }), { prefetch: 16 });
46
+ await source.start();
47
+ await sink.run(http);
48
+ await abutSegments(sink.pool, silenceBudget(Number(env.SEGMENT_WINDOW || 15)));
49
+ }
@@ -0,0 +1,42 @@
1
+ import http from 'node:http';
2
+ import { jsonResponse, route, routes } from '@yarkivaev/simple-server';
3
+ import { createEdgeApi } from '../../http/edge/edgeApi.js';
4
+
5
+ /** Observation and segment ends stored for every configured machine. */
6
+ export async function fromPool(pool) {
7
+ const machines = (await pool.query('SELECT DISTINCT machine FROM history_topics')).rows.map((row) => { return row.machine; });
8
+ if (!machines.length) { return { observationMs: 0, segmentEndMs: 0 }; }
9
+ const obs = await pool.query(
10
+ `SELECT COALESCE(min(mx), 0)::bigint AS ms FROM (
11
+ SELECT COALESCE((SELECT max(time_ms) FROM history_observations o WHERE o.machine = m.machine), 0) AS mx
12
+ FROM unnest($1::text[]) AS m(machine)) t`,
13
+ [machines]
14
+ );
15
+ const seg = await pool.query(
16
+ `SELECT COALESCE((EXTRACT(EPOCH FROM max(end_time)) * 1000)::bigint, 0) AS ms FROM segments WHERE kind = 'phase' AND machine = ANY($1)`,
17
+ [machines]
18
+ );
19
+ return { observationMs: Number(obs.rows[0].ms), segmentEndMs: Number(seg.rows[0].ms) };
20
+ }
21
+
22
+ /** Observation and segment ends this process already stored. */
23
+ export function watermark(history, pool) {
24
+ if (typeof history?.watermark === 'function') { return history.watermark(); }
25
+ if (pool) { return fromPool(pool); }
26
+ return Promise.resolve({ observationMs: 0, segmentEndMs: 0 });
27
+ }
28
+
29
+ /** GET /v1/history/watermark for the restored home's classify loop. */
30
+ export function watermarkRoute(history) {
31
+ return route('GET', '/v1/history/watermark', async (req, res) => {
32
+ jsonResponse(await watermark(history)).send(res);
33
+ });
34
+ }
35
+
36
+ /** History API plus the failback watermark. */
37
+ export default function historyApi(dataAccess, options) {
38
+ const inner = createEdgeApi(dataAccess, options);
39
+ const api = routes([watermarkRoute(dataAccess.history), ...inner.list()], { requestTimeoutMs: options.requestTimeoutMs });
40
+ const server = http.createServer((req, res) => { return api.handle(req, res); });
41
+ return { start() { server.listen(options.port); }, stop() { server.close(); } };
42
+ }
@@ -0,0 +1,14 @@
1
+ export { brokerOwnership } from './brokerOwnership.js';
2
+ export { readable, withCatalog } from './catalogReconciler.js';
3
+ export { classifierFederation, federationOwnership } from './classifyFederation.js';
4
+ export { alive, decide, groupAck, permit, prepared, steps, visible, writers } from './classifyGate.js';
5
+ export { compileClassifierRules } from './compileClassifierRules.js';
6
+ export { cycle, noted, openClassify, operation, released, reply } from './classifyLoop.js';
7
+ export { applyShovels, holdersFrom, shovelsFor } from './classifyShovels.js';
8
+ export { stamp, tagged } from './classifyWatermark.js';
9
+ export { reconcileBrokerThroughController } from './reconcileBrokerThroughController.js';
10
+ export { reconciliationBundle } from './reconciliationBundle.js';
11
+ export { acceptEpoch, admitWriter, applyReplica, readyToLead, restored } from './supervisorReplica.js';
12
+ export { default as runHistoryReceiver, segmentCollector } from './historyReceiver.js';
13
+ export { fromPool as replicaWatermarkFromPool, watermark as replicaWatermark } from './historyWatermark.js';
14
+ export { default as segmentAdmit, grantedEpoch } from './segmentAdmit.js';
@@ -0,0 +1,18 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ const script = fileURLToPath(new URL('./controllerReconcile.js', import.meta.url));
5
+
6
+ /** Reconcile from the deployment controller, sending credentials through standard input. */
7
+ export function reconcileBrokerThroughController(plan, options, { mesh, brokerPruning }, execute = execFileSync) {
8
+ const input = {
9
+ desired: plan.values.rabbitmq.definitions, options, pruneShovels: plan.brokerPruneShovels ?? [],
10
+ context: plan.context, namespace: plan.namespace, prefix: plan.values.prefix,
11
+ rules: { mesh: { upstreamPrefix: mesh.upstreamPrefix, policy: mesh.policy }, brokerPruning }
12
+ };
13
+ try {
14
+ return execute(process.execPath, [script], {
15
+ input: JSON.stringify(input), encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 120000
16
+ });
17
+ } catch { throw new Error('Controller broker reconciliation failed'); }
18
+ }
@@ -0,0 +1,28 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { basename } from 'node:path';
3
+
4
+ const modules = [
5
+ 'catalogReconciler.js', 'classifyGate.js', 'classifyLoop.js', 'classifyWatermark.js',
6
+ 'classifyFederation.js', 'classifyShovels.js', 'supervisorReplica.js',
7
+ '../deploymentPatch.js', '../reconcileDeployments.js',
8
+ '../../management/kubeServiceAccount.js', '../../management/serveReconciliation.js',
9
+ '../../messaging/rabbitmq/reconcile.js',
10
+ '../../../application/control/catalog.js', '../../../application/control/controlClient.js',
11
+ '../../../application/control/controller.js', '../../../application/control/controlStore.js',
12
+ '../../../application/control/jsonAssignments.js', '../../../application/control/periodicReconciliation.js',
13
+ '../../../application/control/reconcileStoredChoice.js', '../../../application/control/schedule.js'
14
+ ];
15
+
16
+ function mountedSource(name) {
17
+ const source = readFileSync(new URL(name, import.meta.url), 'utf8');
18
+ return source.replace(/^(?<declaration>import[^\n]+from )'(?<path>\.\.\/[^']+)'/gmu, (_match, declaration, path) => {
19
+ return `${declaration}'./${basename(path)}'`;
20
+ });
21
+ }
22
+
23
+ /** Build a self-contained controller for images that may have an older runtime. */
24
+ export function reconciliationBundle(rules, { apply = false, catalogSecret, port = '8091', delayMs = '60000' } = {}) {
25
+ const files = Object.fromEntries(modules.map((name) => { return [basename(name), mountedSource(name)]; }));
26
+ files['rules.json'] = typeof rules === 'string' ? rules : JSON.stringify(rules);
27
+ return { catalogSecret, port, delayMs, apply: String(apply === true || apply === 'true'), files };
28
+ }
@@ -0,0 +1,24 @@
1
+ import { admitWriter } from './supervisorReplica.js';
2
+
3
+ /** The epoch the quorum granted this receiver. Never a second hardcoded leader. */
4
+ export function grantedEpoch(value) {
5
+ const epoch = Number(value);
6
+ if (!Number.isSafeInteger(epoch) || epoch < 1) {
7
+ throw new TypeError(`Writer epoch must be positive, message ${value}`);
8
+ }
9
+ return epoch;
10
+ }
11
+
12
+ /** Publish only when admitWriter accepts the body. */
13
+ export default function segmentAdmit(currentEpoch, publish) {
14
+ if (typeof publish !== 'function') { throw new TypeError('Segment publish port required'); }
15
+ const epoch = grantedEpoch(currentEpoch);
16
+ return async function accept(message) {
17
+ const decision = admitWriter(message, epoch);
18
+ if (decision.admitted) {
19
+ await publish(decision.body);
20
+ return { applied: true };
21
+ }
22
+ return { applied: false };
23
+ };
24
+ }
@@ -0,0 +1,27 @@
1
+ import amqp from 'amqplib';
2
+
3
+ /** Durable confirm publisher for admitted segment bodies. */
4
+ export default function segmentPublish(url, queue) {
5
+ if (typeof url !== 'string' || url.length === 0 || typeof queue !== 'string' || queue.length === 0) {
6
+ throw new TypeError('Segment admit destination required');
7
+ }
8
+ let channel = null;
9
+ return {
10
+ async start() {
11
+ const connection = await amqp.connect(url);
12
+ const confirmed = await connection.createConfirmChannel();
13
+ await confirmed.assertQueue(queue, { durable: true });
14
+ channel = confirmed;
15
+ },
16
+ write(body) {
17
+ const payload = Buffer.from(JSON.stringify(body));
18
+ const current = channel;
19
+ return new Promise((resolve, reject) => {
20
+ current.sendToQueue(queue, payload, { persistent: true }, (error) => {
21
+ if (error) { reject(error); return; }
22
+ resolve();
23
+ });
24
+ });
25
+ }
26
+ };
27
+ }
@@ -0,0 +1,36 @@
1
+ /** True only for the epoch the quorum currently grants. */
2
+ export function acceptEpoch(messageEpoch, currentEpoch) {
3
+ if (!Number.isSafeInteger(messageEpoch) || !Number.isSafeInteger(currentEpoch) || messageEpoch < 1 || currentEpoch < 1) {
4
+ throw new TypeError(`Writer epoch must be positive, message ${messageEpoch} current ${currentEpoch}`);
5
+ }
6
+ return messageEpoch === currentEpoch;
7
+ }
8
+ /** One Recreate supervisor already owns the machine. A stamped epoch is not a fence. */
9
+ export function admitWriter(message) {
10
+ const body = typeof message === 'string' ? JSON.parse(message) : message;
11
+ return { admitted: true, body };
12
+ }
13
+ /** Apply one replica body through the matching history port. */
14
+ export async function applyReplica(message, currentEpoch, ports) {
15
+ const decision = admitWriter(message, currentEpoch);
16
+ if (!decision.admitted) { return { applied: false }; }
17
+ const { body } = decision;
18
+ if (body.type === 'segment') { await ports.segments(body); return { applied: true }; }
19
+ if (body.type === 'observations') { await ports.observations(body); return { applied: true }; }
20
+ throw new TypeError(`Replica message ${body.type} is not defined`);
21
+ }
22
+ /** The standby may classify only after its telemetry covers the replicated segment. */
23
+ export function readyToLead(observationMs, segmentEndMs) {
24
+ if (!Number.isSafeInteger(observationMs) || !Number.isSafeInteger(segmentEndMs) || observationMs < 0 || segmentEndMs < 0) {
25
+ throw new TypeError(`Replica watermarks must be non-negative integers, telemetry ${observationMs} segment ${segmentEndMs}`);
26
+ }
27
+ return observationMs >= segmentEndMs;
28
+ }
29
+ /** True when a restored home has live observations covering a real replicated segment. */
30
+ export function restored(mark, now, timing) {
31
+ if (!Number.isSafeInteger(mark?.observationMs) || !Number.isSafeInteger(mark?.segmentEndMs) || mark.observationMs < 0 || mark.segmentEndMs < 0) {
32
+ throw new TypeError(`Replica watermarks must be non-negative integers, telemetry ${mark?.observationMs} segment ${mark?.segmentEndMs}`);
33
+ }
34
+ return mark.segmentEndMs > 0 && mark.observationMs + timing.replacementDelayMs >= mark.segmentEndMs
35
+ && Number.isFinite(now) && mark.observationMs <= now + timing.clockSkewMs && now - mark.observationMs <= timing.replacementDelayMs;
36
+ }
@@ -1,5 +1,5 @@
1
1
  export { collectorDeployment, deploymentContext, peerNodePort, retiredDeployments, stageFor } from '../../application/deploy/deploymentPlan.js';
2
- export { collectorControlDeployment, collectorMemoryDeployment, withCollectorScratch, deploymentResources, etcdMembership, versionedControlCatalog } from '../../application/deploy/controlPlan.js';
2
+ export { applyControlCollector, collectorControlDeployment, collectorMemoryDeployment, withCollectorScratch, deploymentResources, etcdMembership, versionedControlCatalog } from '../../application/deploy/controlPlan.js';
3
3
  export { default as executeStagedDeployment } from './executeStagedDeployment.js';
4
4
  export { default as executeChartDeployment } from './executeChartDeployment.js';
5
5
  export { requireWorkloadEnvironment, validateDeploymentEvidence, verifyPostgresReadiness, waitForJob } from './deploymentChecks.js';
@@ -28,9 +28,34 @@ export { default as preflightKubeStorage } from './preflightKubeStorage.js';
28
28
  export { default as applyWhenChanged } from './applyWhenChanged.js';
29
29
  export { default as prepareKubePrerequisites } from './prepareKubePrerequisites.js';
30
30
  export { default as readDeploymentDocument } from '../../application/deploy/readDeploymentDocument.js';
31
- export { appendReplicaTopology, replicaShovels } from './brokerReplicaTopology.js';
31
+ export { appendReplicaTopology, replicaShovels, brokerReplicaPlan, appendBrokerReplicas } from './brokerReplicaTopology.js';
32
32
  export { default as compileDeploymentHooks } from './compileDeploymentHooks.js';
33
33
  export { default as stagedStoragePreflight } from './stagedStoragePreflight.js';
34
34
  export { default as validateStagedDeploymentEvidence } from './validateStagedDeploymentEvidence.js';
35
35
  export { default as controlPlacement } from '../../application/deploy/controlPlacement.js';
36
36
  export { default as buildDeploymentStages } from './buildDeploymentStages.js';
37
+ export { default as projectTopology } from '../../application/deploy/projectTopology.js';
38
+ export { default as controlPlaneConfiguration, migrationMode } from '../../application/deploy/controlPlaneConfiguration.js';
39
+ export { default as clickhouseTelemetryPolicy } from './clickhouseTelemetryPolicy.js';
40
+ export { default as compileControlCatalog, matchesDeviceInput, scopeControlSecrets } from '../../application/deploy/compileControlCatalog.js';
41
+ export { default as projectControlPlane } from '../../application/deploy/projectControlPlane.js';
42
+ export { brokerUri, brokerEndpoint, attachBrokerMesh, brokerStreamRoutes, brokerStreamBindings, brokerStreams, brokerPeerOutboxes, brokerOutboxes, brokerShovel, appendBrokerResources, brokerSinkOptions } from './brokerTopology.js';
43
+ export { default as deploymentTemplate } from './deploymentTemplate.js';
44
+ export { default as deploymentRecovery } from './deploymentRecovery.js';
45
+ export { default as kioskDeployment } from '../management/kiosk/kioskDeployment.js';
46
+ export { default as compileCollectorTasks, portableCollectorSpec } from '../../application/deploy/compileCollectorTasks.js';
47
+ export { default as projectOpcuaSources } from '../opcua/projectSources.js';
48
+ export { default as controlReaderSpec } from '../../application/deploy/controlReaderSpecs.js';
49
+ export { default as projectClassification } from './projectClassification.js';
50
+ export { databaseEnvironment, databaseSecurity, databaseValues } from './databaseSecurity.js';
51
+ export { brokerPolicy } from './securityPolicy.js';
52
+ export { brokerClientEnvironment, brokerManagement, brokerUri as credentialedBrokerUri, secureBrokerDefinitions, secureBrokerValues } from './brokerSecurity.js';
53
+ export { default as readBrokerSecurityFile, readDeployedBrokerSecurity } from './brokerSecurityInput.js';
54
+ export { default as executeManagedDeployment } from './executeManagedDeployment.js';
55
+ export { liveChartValues, liveChartApps } from '../../application/deploy/liveReleaseOverlay.js';
56
+ export { default as executeConfiguredChartDeployment } from './executeConfiguredChartDeployment.js';
57
+ export { default as configuredHistorySeed } from './configuredHistorySeed.js';
58
+ export { centralTelemetryValues, centralTelemetryChartEnv, centralTelemetryEnvironment, centralTelemetryTasks } from './centralTelemetry.js';
59
+ export { collectorCommand, collectorPublisherCommand, collectorConsumerTasks, collectorDeviceAssignments, collectorSourceProcesses, mapCollectorRelease, parseSerialSource } from '../../application/deploy/collectorSourcePlan.js';
60
+ export { default as collectorChartPlan } from './collectorChartPlan.js';
61
+ export { default as configuredPostgresMaintenance } from './configuredPostgresMaintenance.js';
@@ -0,0 +1,42 @@
1
+ import { brokerShovel, brokerUri } from './brokerTopology.js';
2
+
3
+ function task({ machine, home, eligibleNodes, placement }, { adapter, queuePrefix }) {
4
+ return { taskId: `classify/${machine}`, specVersion: 1, copies: 1, cost: 1, eligibleNodes,
5
+ spec: { adapter, delivery: 'durable', machine, home, queue: queuePrefix + machine }, ...placement };
6
+ }
7
+
8
+ function place(taskValue, holders) {
9
+ const { spec, eligibleNodes, copies } = taskValue;
10
+ const owner = holders[taskValue.taskId] ?? spec.home;
11
+ if (copies !== 1 || !eligibleNodes.includes(owner)) { throw new TypeError(`Supervisor ${owner} cannot classify ${spec.machine}`); }
12
+ return { ...taskValue, owner };
13
+ }
14
+
15
+ function endpoint(uri, central, identity) {
16
+ const { host, username } = new URL(uri);
17
+ if (host === new URL(central).host) { throw new TypeError(`Classification shovel must stay off the central broker ${host}`); }
18
+ return username ? uri : brokerUri(uri, identity);
19
+ }
20
+
21
+ function shovels(tasks, { brokers, central, identity, reconnectDelay }) {
22
+ return tasks.filter(({ spec, owner }) => { return spec.home !== owner; }).map(({ spec, owner }) => {
23
+ const source = brokers[spec.home];
24
+ const destination = brokers[owner];
25
+ if (!source || !destination) { throw new TypeError(`Missing broker for ${spec.machine}`); }
26
+ return brokerShovel({
27
+ name: `classify-${spec.machine}-to-${owner}`, queue: spec.queue, destinationQueue: spec.queue,
28
+ sourceUri: endpoint(source, central, identity), destinationUri: endpoint(destination, central, identity), reconnectDelay
29
+ });
30
+ });
31
+ }
32
+
33
+ /** Project classification ownership, machine lists and direct peer-broker shovels. */
34
+ export default function projectClassification(declarations, options) {
35
+ const tasks = declarations.map((declaration) => { return place(task(declaration, options), options.holders ?? {}); });
36
+ const machines = {};
37
+ for (const { owner, spec } of tasks) {
38
+ if (!Object.hasOwn(machines, owner)) { Object.defineProperty(machines, owner, { value: [], enumerable: true }); }
39
+ machines[owner].push(spec.machine);
40
+ }
41
+ return { tasks, shovels: shovels(tasks, options), machines };
42
+ }
@@ -0,0 +1,16 @@
1
+ import {databaseSecurity} from './databaseSecurity.js';
2
+
3
+ /** Extract broker policy without treating metadata-only DB protection as a broker migration. */
4
+ export function brokerPolicy(security) {
5
+ if (security === undefined || security === null) { return undefined; }
6
+ if (typeof security !== 'object' || Array.isArray(security)) { throw new TypeError('Security policy must be an object'); }
7
+ databaseSecurity(security);
8
+ if (security.phase === undefined) {
9
+ if (!security.database || Object.keys(security).some((key) => { return key !== 'database'; })) {
10
+ throw new TypeError('Database-only security policy accepts only database metadata');
11
+ }
12
+ return undefined;
13
+ }
14
+ if (!['prepare','switch','retire'].includes(security.phase)) { throw new TypeError('Explicit broker migration phase required'); }
15
+ return security;
16
+ }
@@ -1,3 +1,5 @@
1
+ export const centralTelemetryVersion = 4;
2
+
1
3
  function keys(value, allowed) {
2
4
  if (!value || typeof value !== 'object' || Array.isArray(value)
3
5
  || Object.keys(value).some((key) => { return !allowed.includes(key); })) {
@@ -22,20 +24,20 @@ export function centralRule(value, fallback = ruleDefaults) {
22
24
  }
23
25
  return rule;
24
26
  }
25
- /** Native point storage with a bounded immutable archive. */
26
- export default function centralPolicy(input = {}) {
27
- const config = typeof input === 'string' ? JSON.parse(input) : input;
27
+ function parsePolicy(config, strict = false) {
28
28
  keys(config, ['enabled', 'default', 'topics', 'queue', 'queueMaxBytes', 'maxPendingBatches', 'batchSize']);
29
- if (config.enabled !== undefined && typeof config.enabled !== 'boolean') { throw new TypeError('Invalid central policy enabled'); }
29
+ if ((strict || config.enabled !== undefined) && typeof config.enabled !== 'boolean') { throw new TypeError('Invalid central policy enabled'); }
30
30
  keys(config.default ?? {}, CENTRAL_RULE_FIELDS);
31
31
  const defaults = centralRule(config.default ?? {});
32
- if (!Array.isArray(config.topics ?? [])) { throw new TypeError('Invalid central policy topics'); }
32
+ const entries = config.topics === undefined || (!strict && config.topics === null) ? [] : config.topics;
33
+ if (!Array.isArray(entries)) { throw new TypeError('Invalid central policy topics'); }
33
34
  const topics = new Map();
34
- (config.topics ?? []).forEach((entry) => {
35
+ entries.forEach((entry) => {
35
36
  keys(entry, ['topic', ...CENTRAL_RULE_FIELDS]);
36
37
  if (typeof entry.topic !== 'string' || !entry.topic || entry.topic.length > 1024
37
38
  // eslint-disable-next-line no-control-regex
38
- || /[\s\u0000-\u001f\u007f#+*]/u.test(entry.topic) || topics.has(entry.topic)) {
39
+ || /[\s\u0000-\u001f\u007f#+*]/u.test(entry.topic) || topics.has(entry.topic)
40
+ || (strict && /[\p{Cc}{}]/u.test(entry.topic))) {
39
41
  throw new TypeError('Invalid or duplicate central policy topic');
40
42
  }
41
43
  topics.set(entry.topic, centralRule(entry, defaults));
@@ -44,8 +46,27 @@ export default function centralPolicy(input = {}) {
44
46
  if (typeof queue !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,254}$/u.test(queue) || queue.startsWith('amq.')) {
45
47
  throw new TypeError('Invalid central policy queue');
46
48
  }
47
- return { enabled: config.enabled === true, queue, forTopic(topic) { return topics.get(topic) ?? defaults; },
49
+ return { enabled: config.enabled === true, defaults, topics, queue,
48
50
  queueMaxBytes: positive(config.queueMaxBytes ?? 1073741824, 'queue bytes'),
49
51
  maxPendingBatches: positive(config.maxPendingBatches ?? 100000, 'pending batches', 2147483647),
50
52
  batchSize: positive(config.batchSize ?? 500, 'batch size', 1000) };
51
53
  }
54
+
55
+
56
+ function serializedRule({ compactWindowMs, maxGapMs, ...rest }) {
57
+ return { compactWindowMs, maxGapMs, ...rest };
58
+ }
59
+
60
+ /** Normalize and validate the policy object serialized into deployment values and collector specs. */
61
+ export function normalizeCentralPolicy(config) {
62
+ const { enabled, defaults, topics, ...options } = parsePolicy(config, true);
63
+ return { enabled, default: serializedRule(defaults),
64
+ topics: [...topics].map(([topic, rule]) => { return { topic, ...serializedRule(rule) }; }), ...options };
65
+ }
66
+
67
+ /** Native point storage with a bounded immutable archive. */
68
+ export default function centralPolicy(input = {}) {
69
+ const config = typeof input === 'string' ? JSON.parse(input) : input;
70
+ const { enabled, defaults, topics, queue, ...limits } = parsePolicy(config);
71
+ return { enabled, queue, forTopic(topic) { return topics.get(topic) ?? defaults; }, ...limits };
72
+ }
@@ -0,0 +1,60 @@
1
+ import { createHash } from 'node:crypto';
2
+ import operateRemote from './operateKiosk.js';
3
+ import renderResources from './renderKioskResources.js';
4
+
5
+ const restartAnnotation = 'kubectl.kubernetes.io/restartedAt';
6
+
7
+ function between(value, minimum, maximum) {
8
+ return Number.isInteger(value) && value >= minimum && value <= maximum;
9
+ }
10
+
11
+ function checkSettings(config) {
12
+ if (!config || !/^[a-z_][a-z0-9_-]*$/u.test(config.audioUser ?? '') || !between(config.volumePercent, 0, 100)
13
+ || !between(config.audioCard, 0, 32) || !between(config.debugPort, 1, 65535)) {
14
+ throw new TypeError('Invalid kiosk audio/browser settings');
15
+ }
16
+ }
17
+
18
+ function browserTarget(host, nodeAddress, config, policy, targetPattern) {
19
+ const match = targetPattern.exec(host ?? '');
20
+ if (!match) { throw new TypeError('Exact kiosk target required'); }
21
+ checkSettings(config);
22
+ const url = new URL(config.url.replace('{number}', match[1]));
23
+ if (url.protocol !== 'http:' || !['localhost', '127.0.0.1', nodeAddress].includes(url.hostname)
24
+ || url.username || url.password || url.port !== policy.port || url.hash
25
+ || (url.search && url.search !== policy.query.replace('{number}', match[1])) || !/^[\w/.-]*$/u.test(url.pathname)) {
26
+ throw new TypeError('Invalid kiosk HMI URL');
27
+ }
28
+ if (!/^\d{1,3}(?:\.\d{1,3}){3}$/u.test(nodeAddress ?? '')) { throw new TypeError('Invalid kiosk node address'); }
29
+ return { ...config, url: url.href, host, nodeAddress };
30
+ }
31
+
32
+ function browserObjects(plan, declaration, policy) {
33
+ const objects = renderResources(declaration);
34
+ for (const object of objects.filter(({ kind }) => { return kind === 'DaemonSet'; })) {
35
+ const pod = object.spec.template.metadata;
36
+ for (const metadata of [object.metadata, pod]) {
37
+ metadata.labels = { ...metadata.labels, [policy.workloadLabel]: plan.host };
38
+ }
39
+ delete pod.annotations?.[restartAnnotation];
40
+ }
41
+ objects.find(({ metadata }) => { return metadata.name === policy.urlConfigMap; }).data.url = plan.url;
42
+ const browser = objects.find(({ metadata }) => { return metadata.name === policy.browser; });
43
+ browser.spec.template.metadata.annotations[policy.checksumAnnotation] = createHash('sha256').update(plan.url).digest('hex');
44
+ return objects;
45
+ }
46
+
47
+ /** Project the declared browser resources and connect per-installation SSH credentials. */
48
+ export default function kioskDeployment(policy, declaration) {
49
+ const targetPattern = new RegExp(policy.targetPattern, 'u');
50
+ return {
51
+ kioskPlan(host, nodeAddress, config) { return browserTarget(host, nodeAddress, config, policy, targetPattern); },
52
+ kioskObjects(plan) { return browserObjects(plan, declaration, policy); },
53
+ operateKiosk(plan, action, execute, environment = process.env) {
54
+ const ssh = Object.fromEntries(Object.entries(policy.sshEnvironment ?? {}).map(([key, name]) => {
55
+ return [key, environment[name]];
56
+ }));
57
+ return operateRemote(plan, action, { execute, environment, ssh });
58
+ }
59
+ };
60
+ }
@@ -0,0 +1,47 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+
4
+ function hash(input) {
5
+ return createHash('sha1').update(`${createHash('md5').update(input).digest('hex').toUpperCase()}5YdSYHyg2U`).digest('hex');
6
+ }
7
+
8
+ function password() { return randomBytes(32).toString('base64url'); }
9
+
10
+ function connectionSecret(name, namespace, declared) {
11
+ const admin = declared?.password || password();
12
+ const api = password();
13
+ const monitor = password();
14
+ const values = {
15
+ DB_USER: 'mdmesh', DB_PASSWORD: password(), HASH_SECRET: randomBytes(32).toString('hex'), JWT_SECRET: randomBytes(64).toString('hex'),
16
+ ADMIN_PASSWORD: admin, ADMIN_PASSWORD_HASH: hash(admin), ADMIN_RESET_TOKEN: randomBytes(20).toString('hex'),
17
+ API_LOGIN: 'hmi-controller', API_PASSWORD: api, API_PASSWORD_HASH: hash(api),
18
+ MONITOR_LOGIN: 'hmi-monitor', MONITOR_PASSWORD: monitor, MONITOR_PASSWORD_HASH: hash(monitor), CONTROL_TOKEN: password()
19
+ };
20
+ return { apiVersion: 'v1', kind: 'Secret', metadata: { name, namespace }, type: 'Opaque',
21
+ data: Object.fromEntries(Object.entries(values).map(([key, value]) => { return [key, Buffer.from(value).toString('base64')]; })) };
22
+ }
23
+
24
+ function registrySecret(name, namespace, registryFile, policy) {
25
+ if (!registryFile) { throw new Error('HMI bootstrap requires a dedicated read-only registry credential file'); }
26
+ const config = JSON.parse(readFileSync(registryFile, 'utf8'));
27
+ const token = new RegExp(policy.registryIdentityPattern, 'u');
28
+ const entries = Object.entries(config.auths || {});
29
+ if (!entries.length || entries.some(([repository, value]) => {
30
+ return !policy.registryRepositories.includes(repository) || !token.test(Buffer.from(value.auth || '', 'base64').toString())
31
+ || Object.keys(value).some((key) => { return key !== 'auth'; });
32
+ })) { throw new Error('HMI registry credentials require project-scoped deploy tokens'); }
33
+ const data = Buffer.from(JSON.stringify({ auths: Object.fromEntries(entries) })).toString('base64');
34
+ return { apiVersion: 'v1', kind: 'Secret', metadata: { name, namespace }, type: 'kubernetes.io/dockerconfigjson',
35
+ data: { '.dockerconfigjson': data } };
36
+ }
37
+
38
+ /** Initialize absent MDMesh and registry credentials without replacing existing passwords. */
39
+ export default function bootstrapMdmeshCredentials(plan, kube, policy, registryFile = process.env[policy.registryFileEnvironment]) {
40
+ const { namespace, values } = plan;
41
+ function apply(object) { kube(['apply', '--server-side', `--field-manager=${policy.fieldManager}`, '-f', '-'], JSON.stringify(object)); }
42
+ function missing(name) { return !kube(['get', 'secret', name, '--ignore-not-found', '-o', 'name']).trim(); }
43
+ apply({ apiVersion: 'v1', kind: 'Namespace', metadata: { name: namespace } });
44
+ if (missing(values.secret)) { apply(connectionSecret(values.secret, namespace, values.admin)); }
45
+ if (missing(values.pullSecret)) { apply(registrySecret(values.pullSecret, namespace, registryFile, policy)); }
46
+ return { namespace, credentialSecret: values.secret };
47
+ }
@@ -6,3 +6,5 @@ export { default as hmiReconcile } from './hmiReconcile.js';
6
6
  export { default as hmiRuntime } from './hmiRuntime.js';
7
7
  export { default as mdmeshClient } from './mdmeshClient.js';
8
8
  export { default as hmiPlan } from './hmiPlan.js';
9
+ export { default as mdmeshServerRelease } from './mdmeshServerRelease.js';
10
+ export { default as bootstrapMdmeshCredentials } from './bootstrapMdmeshCredentials.js';
@@ -0,0 +1,58 @@
1
+ import deploymentTemplate from '../deploy/deploymentTemplate.js';
2
+
3
+ function label(value, context) {
4
+ if (typeof value !== 'string' || value.length > 63 || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(value)) {
5
+ throw new Error(`Invalid HMI ${context}`);
6
+ }
7
+ }
8
+
9
+ function databaseSettings({ postgresNamespace, postgresHost }, namespace) {
10
+ label(postgresNamespace, 'database namespace');
11
+ const database = postgresHost?.split('.');
12
+ if (postgresNamespace === namespace || database?.length !== 5 || database[1] !== postgresNamespace || database.slice(2).join('.') !== 'svc.cluster.local') {
13
+ throw new Error('HMI database must use a cluster Service outside its namespace');
14
+ }
15
+ label(database[0], 'database service');
16
+ }
17
+
18
+ function authenticationSettings({ authentication }, { namespace, authenticationProvider }) {
19
+ if (authentication?.provider !== authenticationProvider || authentication.namespace === namespace) {
20
+ throw new Error('HMI authentication must remain outside the application namespace');
21
+ }
22
+ label(authentication.namespace, 'authentication namespace');
23
+ if (new URL(authentication.portalUrl).protocol !== 'https:') { throw new Error('HMI authentication requires HTTPS'); }
24
+ }
25
+
26
+ function imageSettings(values) {
27
+ for (const key of ['serverImage', 'webImage', 'supervisorImage']) {
28
+ if (typeof values[key] !== 'string' || !/@sha256:[a-f0-9]{64}$/u.test(values[key])) {
29
+ throw new Error(`HMI ${key} requires an immutable digest`);
30
+ }
31
+ }
32
+ if (values.publicConsole?.enabled && !/@sha256:[a-f0-9]{64}$/u.test(values.publicConsole.image || '')) {
33
+ throw new Error('HMI public console requires an immutable digest');
34
+ }
35
+ }
36
+
37
+ function settings(values, policy) {
38
+ const url = new URL(values.baseUrl);
39
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || url.pathname !== '/') {
40
+ throw new Error('HMI orchestrator requires a public HTTPS origin');
41
+ }
42
+ imageSettings(values);
43
+ for (const key of ['secret', 'pullSecret']) { label(values[key], key); }
44
+ if (values.admin && (values.admin.login !== 'admin' || typeof values.admin.password !== 'string' || !values.admin.password.length)) {
45
+ throw new Error('Managed MDMesh administrator requires login admin and a nonempty password');
46
+ }
47
+ authenticationSettings(values, policy);
48
+ databaseSettings(values, policy.namespace);
49
+ }
50
+
51
+ /** Compile an isolated MDMesh release from the supplied catalog and service policy. */
52
+ export default function mdmeshServerRelease(target, catalog, values, policy) {
53
+ if (catalog.namespace !== policy.namespace) { throw new Error(`HMI workloads require their dedicated ${policy.namespace} namespace`); }
54
+ settings(values, policy);
55
+ return { context: target, namespace: catalog.namespace, release: deploymentTemplate(policy.release, { target }),
56
+ chart: policy.chart, fieldManager: policy.fieldManager,
57
+ values: { ...values, platformResources: false, catalog, planJSON: JSON.stringify(catalog) } };
58
+ }
@@ -1,3 +1,13 @@
1
+ /** AMQP 0-9-1 forwarder with persistent messages, supporting queues and exchanges. */
2
+ export function brokerShovel({ name, sourceUri, queue, destinationUri, exchange, destinationQueue, reconnectDelay, vhost = '/' }) {
3
+ return { vhost, component: 'shovel', name, value: {
4
+ 'src-protocol': 'amqp091', 'src-uri': sourceUri, 'src-queue': queue,
5
+ 'dest-protocol': 'amqp091', 'dest-uri': destinationUri,
6
+ ...(destinationQueue === undefined ? { 'dest-exchange': exchange } : { 'dest-queue': destinationQueue }),
7
+ 'reconnect-delay': reconnectDelay, 'dest-publish-properties': { delivery_mode: 2 }
8
+ } };
9
+ }
10
+
1
11
  /** Builds durable topic exchanges, queues and AMQP 0-9-1 outboxes for one virtual host. */
2
12
  export default function rabbitmqDefinitions({ vhost, users = [], permissions = [], exchanges = [],
3
13
  queues = [], bindings = [], outboxes = [] }) {
@@ -13,12 +23,8 @@ export default function rabbitmqDefinitions({ vhost, users = [], permissions = [
13
23
  return { source, vhost, destination, destination_type: 'queue', routing_key: key, arguments: {} };
14
24
  }),
15
25
  parameters: outboxes.filter(({ shovel }) => { return shovel; }).map(({ queue, shovel }) => {
16
- return { vhost, component: 'shovel', name: shovel.name, value: {
17
- 'src-protocol': 'amqp091', 'src-uri': shovel.sourceUri, 'src-queue': queue,
18
- 'dest-protocol': 'amqp091', 'dest-uri': shovel.destinationUri,
19
- 'dest-exchange': shovel.destinationExchange, 'reconnect-delay': shovel.reconnectDelay,
20
- 'dest-publish-properties': { delivery_mode: 2 }
21
- } };
26
+ const { name, sourceUri, destinationUri, destinationExchange, reconnectDelay } = shovel;
27
+ return brokerShovel({ name, vhost, queue, sourceUri, destinationUri, exchange: destinationExchange, reconnectDelay });
22
28
  })
23
29
  };
24
30
  }