@yarkivaev/scada 2.16.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.16.0",
3
+ "version": "2.17.0",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,71 @@
1
+ function places(tokens, home, nodes, groups) {
2
+ const selected = tokens.flatMap((token) => {
3
+ if (token === 'home') { return home ? [home] : []; }
4
+ if (Object.hasOwn(groups, token)) {
5
+ const { prefix, excludeHome } = groups[token];
6
+ if (typeof prefix !== 'string' || !prefix) { throw new TypeError(`Invalid placement group ${token}`); }
7
+ return nodes.filter((node) => {
8
+ return node.startsWith(prefix) && !(excludeHome && node === home);
9
+ }).sort();
10
+ }
11
+ if (!nodes.includes(token)) { throw new TypeError(`Unknown placement place ${token}`); }
12
+ return [token];
13
+ });
14
+ return [...new Set(selected)];
15
+ }
16
+
17
+ function policy(copies, preference) {
18
+ return { copies, cost: 1, eligibleNodes: preference, preference };
19
+ }
20
+
21
+ function validated(policyInput, node, config, { task, pinned, validateAdapter }) {
22
+ const nodeIds = config.nodes.map(({ id }) => { return id; });
23
+ const eligibleNodes = policyInput.eligibleNodes ?? nodeIds;
24
+ const copies = policyInput.copies ?? config.defaultCopies;
25
+ const cost = policyInput.cost ?? 1;
26
+ if (!Number.isSafeInteger(copies) || copies < 1 || copies > eligibleNodes.length
27
+ || new Set(eligibleNodes).size !== eligibleNodes.length
28
+ || eligibleNodes.some((id) => { return !nodeIds.includes(id); }) || !Number.isFinite(cost) || cost <= 0) {
29
+ throw new TypeError('Invalid input replication policy');
30
+ }
31
+ validateAdapter?.(task, copies);
32
+ if (pinned && ((policyInput.copies !== undefined && policyInput.copies !== 1)
33
+ || (policyInput.eligibleNodes && (eligibleNodes.length !== 1 || eligibleNodes[0] !== node.id)))) {
34
+ throw new TypeError('Serial reader must remain pinned to its physical owner');
35
+ }
36
+ return { copies: pinned ? 1 : copies, cost, eligibleNodes: pinned ? [node.id] : eligibleNodes,
37
+ ...(policyInput.preference && !pinned && { preference: policyInput.preference }), ...(pinned && { pinnedNode: node.id }) };
38
+ }
39
+
40
+ /** Build read and calculation placement from named node groups and declared priorities. */
41
+ export default function controlPlacement({ groups = {}, validateAdapter } = {}) {
42
+ return {
43
+ readPlacement(config, streams, home, nodeIds) {
44
+ const rules = config.placement?.areas ?? [];
45
+ const matches = [...new Set(streams.map((stream) => {
46
+ return rules.find(({ match }) => { return stream?.includes(`/${match}/`); });
47
+ }).filter(Boolean))];
48
+ if (matches.length > 1) { throw new TypeError('Conflicting placement area for grouped reader'); }
49
+ const [rule] = matches;
50
+ if (!rule?.read) { return null; }
51
+ const preference = places(rule.read, home, nodeIds, groups);
52
+ const copies = Math.min(config.placement.readCopies ?? config.defaultCopies, preference.length);
53
+ if (copies < 1) { throw new TypeError(`Invalid placement preference for ${home}`); }
54
+ return policy(copies, preference);
55
+ },
56
+ calculatePlacement(config, areaMatch, home, nodeIds) {
57
+ const rule = config.placement?.areas?.find(({ match }) => { return match === areaMatch; });
58
+ if (!rule?.calculate) { return null; }
59
+ if (rule.calculate.includes('cache') && !rule.read) {
60
+ throw new TypeError(`Calculation cache for ${areaMatch} needs a read list`);
61
+ }
62
+ const tokens = rule.calculate.flatMap((token) => { return token === 'cache' ? rule.read : [token]; });
63
+ const preference = places(tokens, home, nodeIds, groups);
64
+ if (!preference.length) { throw new TypeError(`Invalid calculation preference for ${home}`); }
65
+ return policy(1, preference);
66
+ },
67
+ taskPlacement(policyInput, node, config, { task, pinned } = {}) {
68
+ return validated(policyInput, node, config, { task, pinned, validateAdapter });
69
+ }
70
+ };
71
+ }
@@ -40,15 +40,15 @@ function recoveryTimeout(value = 900000) {
40
40
  return value;
41
41
  }
42
42
 
43
- function agentCapacity(config, node) {
43
+ function agentCapacity(config, node, limits, extra = {}) {
44
44
  if (node.agent !== undefined && (!node.agent || typeof node.agent !== 'object' || Array.isArray(node.agent))) {
45
45
  throw new TypeError('Invalid collector capacity');
46
46
  }
47
47
  const result = {
48
- storage: config.agentStorage, spoolMaxBytes: config.spoolMaxBytes, spoolMaxRecords: config.spoolMaxRecords,
48
+ ...extra, ...Object.fromEntries(limits.map((key) => { return [key, config[key]]; })),
49
49
  recoveryTimeoutMs: config.recoveryTimeoutMs, resources: config.agentResources, ...node.agent
50
50
  };
51
- for (const key of ['spoolMaxBytes', 'spoolMaxRecords']) {
51
+ for (const key of limits) {
52
52
  if (!Number.isSafeInteger(result[key]) || result[key] < 1) { throw new TypeError(`Invalid collector ${key}`); }
53
53
  }
54
54
  deploymentResources(result.resources);
@@ -70,7 +70,7 @@ function collectorStartupProbe(timeout) {
70
70
 
71
71
  /** Render the standard SCADA collector agent runtime with caller-provided credential references. */
72
72
  export function collectorControlDeployment(config, node, { endpoints, brokerEndpoints, hostDevices, deliverySecret, renderDeployment = false }) {
73
- const capacity = agentCapacity(config, node);
73
+ const capacity = agentCapacity(config, node, ['spoolMaxBytes', 'spoolMaxRecords'], { storage: config.agentStorage });
74
74
  const recoveryMs = recoveryTimeout(capacity.recoveryTimeoutMs);
75
75
  return {
76
76
  nodeId: node.id, renderDeployment, image: config.agentImage,
@@ -91,3 +91,34 @@ export function collectorControlDeployment(config, node, { endpoints, brokerEndp
91
91
  }
92
92
  };
93
93
  }
94
+
95
+ /** Mount writable temporary storage in a collector with a read-only root filesystem. */
96
+ export function withCollectorScratch(collector) {
97
+ return { ...collector, readOnlyRootFilesystem: true,
98
+ env: { ...collector.env, TMPDIR: '/tmp', XDG_CONFIG_HOME: '/tmp/config' },
99
+ volumeMounts: [...(collector.volumeMounts ?? []), { name: 'collector-tmp', mountPath: '/tmp' }],
100
+ volumes: [...(collector.volumes ?? []), { name: 'collector-tmp', emptyDir: { medium: 'Memory', sizeLimit: '64Mi' } }] };
101
+ }
102
+
103
+ /** Render a control agent using bounded in-memory queues and temporary storage. */
104
+ export function collectorMemoryDeployment(config, node, options) {
105
+ const { endpoints, brokerEndpoints, hostDevices, deliverySecret, extraEnv = {}, renderDeployment = false } = options;
106
+ const capacity = agentCapacity(config, node, ['queueMaxBytes', 'queueMaxRecords']);
107
+ const recoveryMs = recoveryTimeout(capacity.recoveryTimeoutMs);
108
+ return withCollectorScratch({
109
+ nodeId: node.id, renderDeployment, image: config.agentImage,
110
+ tlsSecret: node.clientTlsSecret ?? `${node.id}-control-client`, authSecret: node.authSecret ?? `${node.id}-control-auth`,
111
+ authUsernameKey: config.authUsernameKey, authPasswordKey: config.authPasswordKey, deliverySecret, resources: capacity.resources,
112
+ hostDevices, startupProbe: collectorStartupProbe(recoveryMs),
113
+ env: {
114
+ ...extraEnv, ...(capacity.heapMb !== undefined && { NODE_OPTIONS: `--max-old-space-size=${capacity.heapMb}` }),
115
+ COLLECTOR_RECOVERY_TIMEOUT_MS: String(recoveryMs), COLLECTOR_NODE_ID: node.id,
116
+ COLLECTOR_BROKER_ENDPOINTS: JSON.stringify(brokerEndpoints), COLLECTOR_CONTROL_ENDPOINTS: endpoints,
117
+ COLLECTOR_CONTROL_PREFIX: config.prefix,
118
+ COLLECTOR_CONTROL_CA: '/tls/ca.crt', COLLECTOR_CONTROL_CERT: '/tls/tls.crt', COLLECTOR_CONTROL_KEY: '/tls/tls.key',
119
+ COLLECTOR_HEALTH_HOST: '0.0.0.0', COLLECTOR_HEALTH_PORT: '9091', COLLECTOR_STARTUP_PORT: '9092',
120
+ COLLECTOR_LIVE_STALE_MS: '2147483647',
121
+ COLLECTOR_QUEUE_MAX_BYTES: String(capacity.queueMaxBytes), COLLECTOR_QUEUE_MAX_RECORDS: String(capacity.queueMaxRecords)
122
+ }
123
+ });
124
+ }
@@ -0,0 +1,25 @@
1
+ import readDocumentFile, { selectDeploymentPhase } from './readDocumentFile.js';
2
+
3
+ function fileSelection(file) {
4
+ if (file instanceof URL) {
5
+ return { path: file, phase: file.hash ? decodeURIComponent(file.hash.slice(1)) : undefined };
6
+ }
7
+ const fragment = file.lastIndexOf('#');
8
+ return fragment < 0 ? { path: file } : { path: file.slice(0, fragment), phase: file.slice(fragment + 1) };
9
+ }
10
+
11
+ /** A deployment document can declare its phase policy and be opened as path#phase. */
12
+ export default function readDeploymentDocument(file, parse) {
13
+ const { path, phase } = fileSelection(file);
14
+ const { deploymentPhase: policy, ...document } = readDocumentFile(path, parse);
15
+ if (policy === undefined) {
16
+ if (phase !== undefined) { throw new TypeError('Deployment phase policy is missing'); }
17
+ return document;
18
+ }
19
+ if (typeof policy?.section !== 'string' || typeof policy.selection !== 'string'
20
+ || !Array.isArray(policy.fields) || !policy.fields.length
21
+ || policy.fields.some((field) => { return typeof field !== 'string'; })) {
22
+ throw new TypeError('Invalid deployment phase policy');
23
+ }
24
+ return selectDeploymentPhase(phase === undefined ? document : { ...document, [policy.selection]: phase }, policy);
25
+ }
@@ -0,0 +1,75 @@
1
+ import rabbitmqDefinitions from '../messaging/rabbitmq/definitions.js';
2
+
3
+ function endpoint(value, blockedHost) {
4
+ const url = new URL(value);
5
+ if (url.host === blockedHost) { throw new TypeError(`Replica shovel must stay off the blocked broker ${url.host}`); }
6
+ if (!url.username) {
7
+ url.username = 'guest';
8
+ url.password = 'guest';
9
+ }
10
+ return url.toString().replace(/\/$/u, '');
11
+ }
12
+
13
+ function shovel(stream, source, target, options, restore) {
14
+ const queue = `${stream.queue}.to-${target.node}`;
15
+ const exchange = restore ? stream.restore.exchange : undefined;
16
+ const outbox = stream.forwardOutbox ? queue : stream.queue;
17
+ const landing = restore ? stream.restore.queue : outbox;
18
+ return {
19
+ vhost: options.vhost,
20
+ component: 'shovel',
21
+ name: `${stream.name}-to-${target.node}`,
22
+ value: {
23
+ 'src-protocol': 'amqp091', 'src-uri': source.uri, 'src-queue': queue,
24
+ 'dest-protocol': 'amqp091', 'dest-uri': target.uri,
25
+ ...(exchange === undefined ? { 'dest-queue': landing } : { 'dest-exchange': exchange }),
26
+ 'reconnect-delay': options.reconnectDelay, 'dest-publish-properties': { delivery_mode: 2 }
27
+ }
28
+ };
29
+ }
30
+
31
+ /** Plan primary-to-standby copies and standby-to-primary restoration for declared streams. */
32
+ export function replicaShovels({ leader, standby, brokers, blocked, streams, vhost = '/', reconnectDelay = 30 }) {
33
+ if (leader === standby) { throw new TypeError('Replica endpoints cannot use the same node'); }
34
+ const blockedHost = blocked ? new URL(blocked).host : undefined;
35
+ const primary = { node: leader, uri: endpoint(brokers[leader], blockedHost) };
36
+ const secondary = { node: standby, uri: endpoint(brokers[standby], blockedHost) };
37
+ return streams.flatMap((stream) => {
38
+ return [
39
+ shovel(stream, primary, secondary, { vhost, reconnectDelay }, false),
40
+ shovel(stream, secondary, primary, { vhost, reconnectDelay }, true)
41
+ ];
42
+ });
43
+ }
44
+
45
+ function appendDistinct(target, rows) {
46
+ rows.forEach((row) => {
47
+ if (!target.some((item) => { return item.name === row.name && item.vhost === row.vhost; })) {
48
+ target.push(row);
49
+ }
50
+ });
51
+ }
52
+
53
+ function append(result, input) {
54
+ const { exchanges, queues, bindings } = rabbitmqDefinitions(input);
55
+ appendDistinct(result.exchanges, exchanges);
56
+ appendDistinct(result.queues, queues);
57
+ result.bindings.push(...bindings);
58
+ }
59
+
60
+ function routes(source, destination, keys = []) {
61
+ return keys.map((key) => { return { source, destination, key }; });
62
+ }
63
+
64
+ /** Add replica resources to an existing broker definition without replacing its declarations. */
65
+ export function appendReplicaTopology(result, { landings = [], copies = [], vhost = '/' }) {
66
+ landings.forEach(({ exchange, queue, keys, bindings = [] }) => {
67
+ append(result, { vhost, exchanges: [exchange], queues: [queue], bindings: [...routes(exchange, queue, keys), ...bindings] });
68
+ });
69
+ copies.forEach(({ shovel: copy, source, keys }) => {
70
+ const queue = copy.value['src-queue'];
71
+ result.parameters.push(copy);
72
+ append(result, { vhost, queues: [queue], bindings: routes(source, queue, keys) });
73
+ });
74
+ return result;
75
+ }
@@ -0,0 +1,23 @@
1
+ function checkDeclarations(declarations, ports) {
2
+ if (!Array.isArray(declarations) || !declarations.length) { throw new TypeError('Deployment stages must be a nonempty list'); }
3
+ const known = new Set();
4
+ for (const { id } of declarations) {
5
+ if (typeof id !== 'string' || !id) { throw new TypeError('Deployment stage id is required'); }
6
+ if (known.has(id)) { throw new TypeError(`Duplicate deployment stage ${id}`); }
7
+ if (!Object.hasOwn(ports, id) || typeof ports[id] !== 'function') {
8
+ throw new TypeError(`Unknown deployment stage binding ${id}`);
9
+ }
10
+ known.add(id);
11
+ }
12
+ }
13
+
14
+ /** Assemble ordered releases from declarative identity and caller-provided stage values. */
15
+ export default function buildDeploymentStages(declarations, { common = {}, defaults = {}, ports }) {
16
+ checkDeclarations(declarations, ports);
17
+ return declarations.flatMap(({ id, inheritValues = true, ...declaration }) => {
18
+ const binding = ports[id]();
19
+ if (binding === null) { return []; }
20
+ const { values, ...options } = binding;
21
+ return [{ ...common, id, ...declaration, ...options, values: { ...(inheritValues ? defaults : {}), ...values } }];
22
+ });
23
+ }
@@ -0,0 +1,48 @@
1
+ import { requireWorkloadEnvironment, verifyPostgresReadiness, waitForJob } from './deploymentChecks.js';
2
+ import verifyCollectorCoverage from './verifyCollectorCoverage.js';
3
+
4
+ const timings = new Set(['beforeApply', 'afterReady']);
5
+
6
+ export function deploymentStage(plan, id) {
7
+ const stage = plan.stages.find((candidate) => { return candidate.id === id; });
8
+ if (!stage) { throw new TypeError(`Unknown deployment stage ${id}`); }
9
+ return stage;
10
+ }
11
+
12
+ function builtInChecks({ plan, evidence, execute }) {
13
+ return {
14
+ collectorCoverage(_stage, _kube, { stage: id, workloads, namespace = plan.namespace, freshnessMs, clockSkewMs, container, statusUrl }) {
15
+ const { controlCatalog, cutoverTasks } = deploymentStage(plan, id);
16
+ if (controlCatalog) {
17
+ verifyCollectorCoverage({ cluster: plan.context, namespace, evidence, execute,
18
+ tasks: cutoverTasks, workloads, freshnessMs, clockSkewMs, container, statusUrl });
19
+ }
20
+ },
21
+ environment(_stage, kube, declaration) { requireWorkloadEnvironment(kube, declaration); },
22
+ job(_stage, kube, { prerequisite, name, timeout }) {
23
+ waitForJob(kube, prerequisite ? plan.prerequisites?.[prerequisite] : name, timeout);
24
+ },
25
+ postgresReadiness(_stage, kube, declaration) { verifyPostgresReadiness(kube, declaration); }
26
+ };
27
+ }
28
+
29
+ function compileTiming(timing, steps, checks) {
30
+ if (!timings.has(timing) || !Array.isArray(steps)) { throw new TypeError(`Invalid deployment hook ${timing}`); }
31
+ const handlers = steps.map((step) => {
32
+ if (!Object.hasOwn(checks, step?.check) || typeof checks[step.check] !== 'function') {
33
+ throw new TypeError(`Unknown deployment check ${step?.check}`);
34
+ }
35
+ return (stage, kube) => { checks[step.check](stage, kube, step); };
36
+ });
37
+ return (stage, kube) => { handlers.forEach((handler) => { handler(stage, kube); }); };
38
+ }
39
+
40
+ /** Compile ordered stage checks using built-in operations and explicitly registered application ports. */
41
+ export default function compileDeploymentHooks(declarations, { plan, evidence, execute, ports = {} }) {
42
+ const checks = { ...ports, ...builtInChecks({ plan, evidence, execute }) };
43
+ return Object.fromEntries(Object.entries(declarations ?? {}).map(([stage, hooks]) => {
44
+ return [stage, Object.fromEntries(Object.entries(hooks).map(([timing, steps]) => {
45
+ return [timing, compileTiming(timing, steps, checks)];
46
+ }))];
47
+ }));
48
+ }
@@ -1,5 +1,5 @@
1
1
  export { collectorDeployment, deploymentContext, peerNodePort, retiredDeployments, stageFor } from '../../application/deploy/deploymentPlan.js';
2
- export { collectorControlDeployment, deploymentResources, etcdMembership, versionedControlCatalog } from '../../application/deploy/controlPlan.js';
2
+ export { 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';
@@ -27,3 +27,10 @@ export { default as verifyPeerBrokerPerimeter } from './verifyPeerBrokerPerimete
27
27
  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
+ export { default as readDeploymentDocument } from '../../application/deploy/readDeploymentDocument.js';
31
+ export { appendReplicaTopology, replicaShovels } from './brokerReplicaTopology.js';
32
+ export { default as compileDeploymentHooks } from './compileDeploymentHooks.js';
33
+ export { default as stagedStoragePreflight } from './stagedStoragePreflight.js';
34
+ export { default as validateStagedDeploymentEvidence } from './validateStagedDeploymentEvidence.js';
35
+ export { default as controlPlacement } from '../../application/deploy/controlPlacement.js';
36
+ export { default as buildDeploymentStages } from './buildDeploymentStages.js';
@@ -0,0 +1,72 @@
1
+ import { deploymentStage } from './compileDeploymentHooks.js';
2
+ import { preserveKubeRestart } from './deploymentKube.js';
3
+ import preflightKubeStorage from './preflightKubeStorage.js';
4
+ import verifyPeerBrokerPerimeter from './verifyPeerBrokerPerimeter.js';
5
+
6
+ function preserveRestart(plan, declarations, kube) {
7
+ for (const declaration of declarations) {
8
+ const stage = plan.stages.find(({ id }) => { return id === declaration.stage; });
9
+ if (stage && declaration.workload) {
10
+ stage.values.podAnnotations = preserveKubeRestart(kube, declaration.workload, stage.values.podAnnotations);
11
+ }
12
+ for (const object of stage?.values.extraObjects ?? []) {
13
+ if (declaration.objectKind && object.kind === declaration.objectKind) {
14
+ const { metadata } = object.spec.template;
15
+ metadata.annotations = preserveKubeRestart(kube, `${object.kind.toLowerCase()}/${object.metadata.name}`, metadata.annotations, stage.namespace);
16
+ }
17
+ }
18
+ }
19
+ }
20
+
21
+ function secrets({ postgresSecret, brokerSecrets, runtimeSecret, requiredSecretKeys, databaseRuntime }, database) {
22
+ return [
23
+ ...(brokerSecrets ?? []).map((name) => { return { name }; }),
24
+ { name: runtimeSecret, keys: requiredSecretKeys },
25
+ { name: postgresSecret, keys: database.secretKeys },
26
+ ...(databaseRuntime ? [{ name: databaseRuntime.runtimeSecret, keys: [databaseRuntime.runtimeKey] }] : [])
27
+ ];
28
+ }
29
+
30
+ function storageTemplates(plan, database, postgres, broker, rabbitmq) {
31
+ if (!plan.preserveStoragePodTemplates) { return []; }
32
+ return [{ name: database.name, values: postgres }, ...(plan.brokerSecurity ? [] : [{ name: broker.name, values: rabbitmq }])];
33
+ }
34
+
35
+ function checkPerimeter(plan, evidence, selector, kube) {
36
+ const policy = plan.prerequisites.peerBrokerPerimeter;
37
+ if (!policy) { return; }
38
+ const allowedPeers = policy.spec.ingress[0].from.filter((peer) => { return peer.ipBlock; }).map((peer) => {
39
+ return peer.ipBlock.cidr.replace(/\/(?:32|128)$/u, '');
40
+ });
41
+ verifyPeerBrokerPerimeter({ context: plan.context, policy, allowedPeers, selector, proof: evidence.peerBrokerPerimeter }, kube);
42
+ }
43
+
44
+ function storageResources(plan, policy) {
45
+ const declared = (policy.requiredResources ?? []).filter(({ stage }) => {
46
+ return !stage || plan.stages.some(({ id }) => { return stage === id; });
47
+ }).map(({ name, namespace }) => { return { name, namespace }; });
48
+ return [...plan.prerequisites.preservedConfigMaps.map((name) => { return { name: `configmap/${name}` }; }), ...declared];
49
+ }
50
+
51
+ /** Bind rollout storage checks to the projected resources and supplied identity evidence. */
52
+ export default function stagedStoragePreflight(plan, policy, { evidence, execute, action }) {
53
+ const stage = deploymentStage(plan, policy.stage);
54
+ const { postgres, rabbitmq } = stage.values;
55
+ const { database, broker } = policy;
56
+ return preflightKubeStorage({
57
+ context: plan.context,
58
+ namespace: plan.namespace,
59
+ nodeAddress: plan.nodeAddress,
60
+ secrets: secrets(plan.prerequisites, database),
61
+ beforeStorage: evidence && ((kube) => { checkPerimeter(plan, evidence, broker.selector, kube); }),
62
+ layouts: [{ name: database.name, volume: database.volume, mountPath: database.mountPath, claim: postgres.existingClaim,
63
+ env: database.environment, environmentValue: postgres.data }],
64
+ preserveTemplates: storageTemplates(plan, database, postgres, broker, rabbitmq),
65
+ preserveAnnotations(kube) { preserveRestart(plan, policy.preserveRestart ?? [], kube); },
66
+ verifyTemplates: evidence && { stage, workloads: rabbitmq.definitionsSecret ? [database.name] : [database.name, broker.name] },
67
+ claims: plan.prerequisites.existingClaims.map((name) => {
68
+ return { name, claimUid: evidence?.claims[name], volumeName: evidence?.volumes[name].name, volumeUid: evidence?.volumes[name].uid };
69
+ }),
70
+ resources: storageResources(plan, policy)
71
+ }, action, execute);
72
+ }
@@ -0,0 +1,16 @@
1
+ import { deploymentStage } from './compileDeploymentHooks.js';
2
+ import { validateDeploymentEvidence } from './deploymentChecks.js';
3
+
4
+ /** Validate rollout proof against the readers assigned by the prepared plan. */
5
+ export default function validateStagedDeploymentEvidence(plan, policy, evidence, now) {
6
+ const collector = deploymentStage(plan, policy.collectorStage);
7
+ const { controlCatalog } = collector;
8
+ const tasks = controlCatalog ? controlCatalog.tasks.filter(({ pinnedNode }) => {
9
+ return pinnedNode === plan.context;
10
+ }) : JSON.parse(collector.values.processes[0].env.COLLECTOR_MANIFEST).assignments;
11
+ const readers = Object.fromEntries(Object.entries(policy.optionalReaders ?? {}).map(([key, adapter]) => {
12
+ return [key, tasks.some((task) => { return task.spec.adapter === adapter; })];
13
+ }));
14
+ return validateDeploymentEvidence({ context: plan.context, required: policy.required,
15
+ claims: plan.prerequisites.existingClaims, catalogVersion: controlCatalog?.version, readers }, evidence, now);
16
+ }
@@ -0,0 +1,123 @@
1
+ import paths from '../../application/deploy/paths.js';
2
+
3
+ function record(value, context) {
4
+ if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new TypeError(`HMI ${context} must be an object`); }
5
+ return value;
6
+ }
7
+
8
+ function text(value, context) {
9
+ if (typeof value !== 'string' || !value.trim()) { throw new TypeError(`HMI ${context} must be a nonempty string`); }
10
+ return value;
11
+ }
12
+
13
+ function credentials(value) {
14
+ Object.entries(value).forEach(([key, entry]) => {
15
+ if (/password|secret|token|credential|command/iu.test(key)) { throw new TypeError(`HMI catalog cannot embed ${key}`); }
16
+ if (entry && typeof entry === 'object') { credentials(entry); }
17
+ });
18
+ }
19
+
20
+ function moduleFor(servers, id) {
21
+ const server = servers.find((entry) => { return entry.id === id; });
22
+ const module = server?.modules?.mdmesh;
23
+ if (!module || module.enabled !== true) { throw new TypeError(`HMI server ${id} requires enabled mdmesh module`); }
24
+ if (typeof module.namespace !== 'string' || module.namespace.length > 63
25
+ || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(module.namespace)) {
26
+ throw new TypeError(`HMI server ${id} requires a DNS namespace`);
27
+ }
28
+ return module;
29
+ }
30
+
31
+ function profilesFor(profiles) {
32
+ Object.entries(record(profiles, 'profiles')).forEach(([id, profile]) => {
33
+ record(profile, `profile ${id}`);
34
+ if (!['landscape', 'portrait'].includes(profile.orientation)) { throw new TypeError(`HMI profile ${id} has invalid orientation`); }
35
+ ['kiosk', 'keepScreenOnWhileCharging', 'alarmSound'].forEach((key) => {
36
+ if (typeof profile[key] !== 'boolean') { throw new TypeError(`HMI profile ${id} requires boolean ${key}`); }
37
+ });
38
+ });
39
+ return profiles;
40
+ }
41
+
42
+ function unique(value, seen, context) {
43
+ text(value, context);
44
+ if (seen.has(value)) { throw new TypeError(`HMI duplicate ${context} ${value}`); }
45
+ seen.add(value);
46
+ }
47
+
48
+ function artifactFor(apk, { packageName, downloadPrefix }) {
49
+ if (apk.package !== packageName || !/^\d+\.\d+\.\d+$/u.test(apk.version)
50
+ || !Number.isSafeInteger(apk.versionCode) || apk.versionCode < 1 || !/^[a-f0-9]{64}$/u.test(apk.sha256)) { throw new TypeError('HMI APK requires a package, version and SHA-256'); }
51
+ const url = new URL(apk.url);
52
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash
53
+ || (!url.pathname.startsWith(downloadPrefix) || !/^[a-z0-9-]+\.apk$/u.test(url.pathname.slice(downloadPrefix.length)))) { throw new TypeError('HMI APK requires its dedicated HTTPS download path'); }
54
+ if (apk.retire && (!Array.isArray(apk.retire) || apk.retire.some((pkg) => { return typeof pkg !== 'string' || !pkg.startsWith(`${packageName}.`) || !/^[a-z][a-z0-9_]*$/u.test(pkg.slice(packageName.length + 1)); }))) {
55
+ throw new TypeError('HMI APK retire list requires former machine packages');
56
+ }
57
+ }
58
+
59
+ function applicationFor(device, policy) {
60
+ const app = device.application;
61
+ if (!Object.hasOwn(app, 'autoStart')) { return; }
62
+ if (typeof app.autoStart !== 'boolean') { throw new TypeError('HMI autoStart must be boolean'); }
63
+ if (!app.autoStart) { return; }
64
+ const href = new URL(policy.address(app.href));
65
+ if (href.searchParams.get('machine') !== device.machine) { throw new TypeError('HMI autoStart requires a matching machine URL'); }
66
+ artifactFor(record(app.apk, 'application APK'), policy);
67
+ }
68
+
69
+ function shared(devices) {
70
+ const apks = devices.filter((device) => { return device.application.autoStart; }).map((device) => { return device.application.apk; });
71
+ if (apks.some((apk) => { return ['package', 'version', 'versionCode', 'url', 'sha256'].some((key) => { return apk[key] !== apks[0][key]; }); })) {
72
+ throw new TypeError('HMI autoStart devices must share one APK');
73
+ }
74
+ }
75
+
76
+ function binding(device, document, machines, profiles, policy) {
77
+ record(device, 'device');
78
+ record(device.orchestrator, `device ${device.id} orchestrator`);
79
+ record(device.application, `device ${device.id} application`);
80
+ if (device.orchestrator.module !== 'mdmesh') { throw new TypeError(`HMI device ${device.id} requires mdmesh orchestrator`); }
81
+ moduleFor(document.servers, device.orchestrator.server);
82
+ if (!document.servers.some((server) => { return server.id === device.application.server; })) {
83
+ throw new TypeError(`HMI device ${device.id} references unknown application server ${device.application.server}`);
84
+ }
85
+ applicationFor(device, policy);
86
+ if (device.application.autoStart && !profiles[device.profile]?.kiosk) { throw new TypeError('Automatic HMI requires a kiosk profile'); }
87
+ if (!Object.hasOwn(profiles, device.profile)) { throw new TypeError(`HMI device ${device.id} references unknown profile ${device.profile}`); }
88
+ if (!machines.has(device.machine) || device.application.machine !== device.machine) {
89
+ throw new TypeError(`HMI device ${device.id} requires a matching namespace machine ${device.machine}`);
90
+ }
91
+ }
92
+
93
+ function devicesFor(catalog) {
94
+ if (!Array.isArray(catalog.devices)) { throw new TypeError('HMI devices must be an array'); }
95
+ if (catalog.apk === undefined) { return catalog.devices; }
96
+ const apk = record(catalog.apk, 'shared APK');
97
+ return catalog.devices.map((device) => {
98
+ if (device?.application?.autoStart !== true) { return device; }
99
+ const app = device.application;
100
+ const override = app.apk === undefined ? {} : record(app.apk, 'application APK');
101
+ return { ...device, application: { ...app, apk: { ...apk, ...override } } };
102
+ });
103
+ }
104
+
105
+ /** Validate the complete declarative tablet catalog before selecting one orchestrator server. */
106
+ export default function hmiPlan(serverId, document, policy) {
107
+ const catalog = record(document.hmi, 'catalog');
108
+ credentials(catalog);
109
+ const profiles = profilesFor(catalog.profiles);
110
+ const module = moduleFor(document.servers || [], serverId);
111
+ const machines = new Set(paths(document).filter((name) => { return name.split('/').length === 3; }).map((name) => { return name.split('/').at(-1); }));
112
+ const identifiers = new Set();
113
+ const references = new Set();
114
+ const devices = devicesFor(catalog);
115
+ devices.forEach((device) => {
116
+ binding(device, document, machines, profiles, policy);
117
+ unique(device.id, identifiers, 'device id');
118
+ if (Object.hasOwn(device, 'deviceRef')) { unique(device.deviceRef, references, 'device reference'); }
119
+ });
120
+ shared(devices);
121
+ return { server: serverId, namespace: module.namespace, profiles,
122
+ devices: devices.filter((device) => { return device.orchestrator.server === serverId; }) };
123
+ }
@@ -5,3 +5,4 @@ export { default as hmiMonitor, metrics } from './hmiMonitor.js';
5
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
+ export { default as hmiPlan } from './hmiPlan.js';