@yarkivaev/scada 2.16.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.
- package/index.js +1 -2
- package/package.json +3 -2
- package/src/application/deploy/collectorSourcePlan.js +97 -0
- package/src/application/deploy/compileCollectorTasks.js +31 -0
- package/src/application/deploy/compileControlCatalog.js +66 -0
- package/src/application/deploy/controlPlacement.js +71 -0
- package/src/application/deploy/controlPlan.js +51 -4
- package/src/application/deploy/controlPlaneConfiguration.js +62 -0
- package/src/application/deploy/controlReaderSpecs.js +37 -0
- package/src/application/deploy/liveReleaseOverlay.js +17 -0
- package/src/application/deploy/projectControlPlane.js +48 -0
- package/src/application/deploy/projectTopology.js +41 -0
- package/src/application/deploy/readDeploymentDocument.js +25 -0
- package/src/infrastructure/deploy/brokerReplicaTopology.js +97 -0
- package/src/infrastructure/deploy/brokerSecurity.js +89 -0
- package/src/infrastructure/deploy/brokerSecurityInput.js +85 -0
- package/src/infrastructure/deploy/brokerTopology.js +125 -0
- package/src/infrastructure/deploy/buildDeploymentStages.js +23 -0
- package/src/infrastructure/deploy/centralTelemetry.js +51 -0
- package/src/infrastructure/deploy/clickhouseTelemetryPolicy.js +64 -0
- package/src/infrastructure/deploy/collectorChartPlan.js +68 -0
- package/src/infrastructure/deploy/compileDeploymentHooks.js +48 -0
- package/src/infrastructure/deploy/configuredHistorySeed.js +54 -0
- package/src/infrastructure/deploy/configuredPostgresMaintenance.js +23 -0
- package/src/infrastructure/deploy/databaseSecurity.js +39 -0
- package/src/infrastructure/deploy/deploymentRecovery.js +49 -0
- package/src/infrastructure/deploy/deploymentTemplate.js +67 -0
- package/src/infrastructure/deploy/executeConfiguredChartDeployment.js +65 -0
- package/src/infrastructure/deploy/executeManagedDeployment.js +46 -0
- package/src/infrastructure/deploy/highAvailability/brokerOwnership.js +19 -0
- package/src/infrastructure/deploy/highAvailability/catalogReconciler.js +61 -0
- package/src/infrastructure/deploy/highAvailability/classifyFederation.js +57 -0
- package/src/infrastructure/deploy/highAvailability/classifyGate.js +114 -0
- package/src/infrastructure/deploy/highAvailability/classifyLoop.js +139 -0
- package/src/infrastructure/deploy/highAvailability/classifyShovels.js +70 -0
- package/src/infrastructure/deploy/highAvailability/classifyWatermark.js +45 -0
- package/src/infrastructure/deploy/highAvailability/compileClassifierRules.js +21 -0
- package/src/infrastructure/deploy/highAvailability/controllerReconcile.js +14 -0
- package/src/infrastructure/deploy/highAvailability/historyReceiver.js +49 -0
- package/src/infrastructure/deploy/highAvailability/historyWatermark.js +42 -0
- package/src/infrastructure/deploy/highAvailability/index.js +14 -0
- package/src/infrastructure/deploy/highAvailability/reconcileBrokerThroughController.js +18 -0
- package/src/infrastructure/deploy/highAvailability/reconciliationBundle.js +28 -0
- package/src/infrastructure/deploy/highAvailability/segmentAdmit.js +24 -0
- package/src/infrastructure/deploy/highAvailability/segmentPublish.js +27 -0
- package/src/infrastructure/deploy/highAvailability/supervisorReplica.js +36 -0
- package/src/infrastructure/deploy/index.js +33 -1
- package/src/infrastructure/deploy/projectClassification.js +42 -0
- package/src/infrastructure/deploy/securityPolicy.js +16 -0
- package/src/infrastructure/deploy/stagedStoragePreflight.js +72 -0
- package/src/infrastructure/deploy/validateStagedDeploymentEvidence.js +16 -0
- package/src/infrastructure/ingest/telemetry/centralPolicy.js +29 -8
- package/src/infrastructure/management/kiosk/kioskDeployment.js +60 -0
- package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +47 -0
- package/src/infrastructure/mdmesh/hmiPlan.js +123 -0
- package/src/infrastructure/mdmesh/index.js +3 -0
- package/src/infrastructure/mdmesh/mdmeshServerRelease.js +58 -0
- package/src/infrastructure/messaging/rabbitmq/definitions.js +12 -6
- package/src/infrastructure/opcua/projectSources.js +36 -0
package/index.js
CHANGED
|
@@ -49,8 +49,7 @@ export { default as clickhouseConnection } from './src/infrastructure/persistenc
|
|
|
49
49
|
export { rawMetricsRange as clickhouseMetricsRawRange } from './src/infrastructure/persistence/clickhouse/metricsRelation.js';
|
|
50
50
|
export { rawMetricsRelation as clickhouseMetricsRawRelation } from './src/infrastructure/persistence/clickhouse/metricsRelation.js';
|
|
51
51
|
export { default as clickhouseMetricsRelation } from './src/infrastructure/persistence/clickhouse/metricsRelation.js';
|
|
52
|
-
export
|
|
53
|
-
export { default as centralTelemetryPolicy } from './src/infrastructure/ingest/telemetry/centralPolicy.js';
|
|
52
|
+
export { default as centralTelemetryPolicy, centralTelemetryVersion } from './src/infrastructure/ingest/telemetry/centralPolicy.js';
|
|
54
53
|
export { default as clickhouseSensor } from './src/infrastructure/persistence/clickhouse/sensor.js';
|
|
55
54
|
export { default as postgresPool, holdClient as holdPostgresClient, openPostgresPool } from './src/infrastructure/persistence/postgresPool.js';
|
|
56
55
|
export { metricsSinkFromPool as pgMetricsSink } from './src/infrastructure/persistence/pg/metrics.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yarkivaev/scada",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.18.0",
|
|
4
4
|
"description": "SCADA domain objects, state persistence, and plant monitoring",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -22,7 +22,8 @@
|
|
|
22
22
|
"./streams": "./src/infrastructure/streams/index.js",
|
|
23
23
|
"./control": "./src/application/control/index.js",
|
|
24
24
|
"./mdmesh": "./src/infrastructure/mdmesh/index.js",
|
|
25
|
-
"./deployment": "./src/infrastructure/deploy/index.js"
|
|
25
|
+
"./deployment": "./src/infrastructure/deploy/index.js",
|
|
26
|
+
"./deployment/high-availability": "./src/infrastructure/deploy/highAvailability/index.js"
|
|
26
27
|
},
|
|
27
28
|
"bin": {
|
|
28
29
|
"modbus-to-mqtt": "./src/bin/modbus-to-mqtt.js",
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import deploymentTemplate, { deploymentCondition } from '../../infrastructure/deploy/deploymentTemplate.js';
|
|
2
|
+
import expand from './expand.js';
|
|
3
|
+
import releases from './releases.js';
|
|
4
|
+
import collectorProcesses from './collectorProcesses.js';
|
|
5
|
+
|
|
6
|
+
function sourceScheme(from) {
|
|
7
|
+
const text = String(from);
|
|
8
|
+
const mark = text.indexOf('://');
|
|
9
|
+
return mark < 0 ? '' : text.slice(0, mark);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function sourceRule(from, name, rules) {
|
|
13
|
+
const scheme = sourceScheme(from);
|
|
14
|
+
return rules.find((rule) => {
|
|
15
|
+
return (rule.scheme === undefined || rule.scheme === scheme)
|
|
16
|
+
&& (rule.suffix === undefined || String(name).endsWith(rule.suffix))
|
|
17
|
+
&& (rule.leaf === undefined || String(name).split('/').at(-1) === rule.leaf);
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function invocation(policy, args, bindings, dsl = policy.dsl) {
|
|
22
|
+
return deploymentTemplate([...policy.cli, '--dsl', dsl, ...args], bindings);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Build a declared protocol's publisher invocation. */
|
|
26
|
+
export function collectorPublisherCommand(adapter, policy) {
|
|
27
|
+
return invocation(policy, policy.publishers[adapter], {});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Build a collector CLI invocation by matching the first declared source rule. */
|
|
31
|
+
export function collectorCommand(from, name, policy) {
|
|
32
|
+
const scheme = sourceScheme(from);
|
|
33
|
+
if (!scheme) { throw new Error(`plant collector address ${from} has no scheme`); }
|
|
34
|
+
const selected = sourceRule(from, name, policy.commands);
|
|
35
|
+
if (!selected) { throw new Error(`plant collector has no command for ${scheme} at ${name}`); }
|
|
36
|
+
return selected.publisher ? collectorPublisherCommand(selected.publisher, policy) : invocation(policy, selected.args, { name }, selected.dsl);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Parse the serial address used by RTU-backed collector sources. */
|
|
40
|
+
export function parseSerialSource(from) {
|
|
41
|
+
const match = /^rtu:\/\/(?<path>\/dev\/tty[A-Za-z0-9]+):(?<baud>\d+):(?<line>[78][NEO][12])(?::(?<slave>\d+))?(?:\?(?<query>.*))?$/u.exec(from);
|
|
42
|
+
if (!match) { throw new Error(`invalid sensors serial address: ${from}`); }
|
|
43
|
+
return { ...match.groups, query: new URLSearchParams(match.groups.query || '') };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Group source rows by the declared descriptor and project the chosen protocol settings. */
|
|
47
|
+
export function collectorSourceProcesses(rows, { descriptions, describe, project, cli }) {
|
|
48
|
+
const adapters = new Map();
|
|
49
|
+
const processes = collectorProcesses(rows, (row) => {
|
|
50
|
+
const { adapter, bindings } = describe(row);
|
|
51
|
+
const spec = deploymentTemplate(descriptions[adapter], bindings);
|
|
52
|
+
adapters.set(spec.name, adapter);
|
|
53
|
+
return { ...spec, command: collectorPublisherCommand(adapter, cli), adapter };
|
|
54
|
+
}, (descriptor, sources) => { return project(descriptor.adapter, sources); });
|
|
55
|
+
return processes.map((process) => { return { ...process, adapter: adapters.get(process.name) }; });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function accepts(row, { adapter, stream }, rules) {
|
|
59
|
+
if (stream && row.name !== stream) { return false; }
|
|
60
|
+
if (!adapter) { return true; }
|
|
61
|
+
const rule = sourceRule(row.from, row.name, rules);
|
|
62
|
+
if (!rule) { throw new TypeError(`Unsupported device source ${row.from}`); }
|
|
63
|
+
return rule.adapter === adapter;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Compile only owned device fan-in rows, with deployment-specific protocol projection. */
|
|
67
|
+
export function collectorDeviceAssignments(document, selection, { rules, sourceTypes, collect, compile }) {
|
|
68
|
+
const { cluster, generation = 1 } = selection;
|
|
69
|
+
const expanded = expand(document);
|
|
70
|
+
const servers = expanded.servers.filter((server) => { return !cluster || server.id === cluster; });
|
|
71
|
+
if (cluster && !servers.length) { throw new TypeError(`Unknown collector cluster ${cluster}`); }
|
|
72
|
+
return servers.flatMap((server) => {
|
|
73
|
+
const profile = expanded.profiles[server.profile.id];
|
|
74
|
+
const rows = (releases(document, server.id).scada.machines || []).filter((row) => { return accepts(row, selection, rules); });
|
|
75
|
+
const processes = sourceTypes.flatMap(({ schemes, projection }) => {
|
|
76
|
+
return collect[projection](rows.filter((row) => { return schemes.includes(sourceScheme(row.from)); }), profile.apps.scada);
|
|
77
|
+
});
|
|
78
|
+
return compile(processes, generation);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Render declared consumer assignments in order using the deployment's typed bindings. */
|
|
83
|
+
export function collectorConsumerTasks(declarations, cluster, bindings, generation = 1) {
|
|
84
|
+
return declarations.filter(({ when }) => { return !when || deploymentCondition(when, bindings); }).map(({ id, spec }) => {
|
|
85
|
+
return { taskId: `${cluster}/${id}`, specVersion: 1, generation, spec: { ...deploymentTemplate(spec, bindings), delivery: 'durable' } };
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Project release mappings with an injected fieldbus point decoder. */
|
|
90
|
+
export function mapCollectorRelease(values, decode) {
|
|
91
|
+
const machines = (values.machines || []).map((machine) => {
|
|
92
|
+
if (!machine.mapping) { return machine; }
|
|
93
|
+
const decoded = decode([machine.mapping], [machine.from]);
|
|
94
|
+
return { ...machine, mapping: decoded === null ? machine.mapping : decoded[0] };
|
|
95
|
+
});
|
|
96
|
+
return { ...values, machines };
|
|
97
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
function digest(value) {
|
|
4
|
+
return createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/** Bind a portable durable task to a deterministic source compatibility fingerprint. */
|
|
8
|
+
export function portableCollectorSpec(spec, identity) {
|
|
9
|
+
return { ...spec, delivery: 'durable', stateVersion: 1, compatibilityKey: digest(identity) };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function declaredTasks(input, generation) {
|
|
13
|
+
if (!Array.isArray(input?.collectorTasks)) { throw new TypeError('collectorTasks declarations required'); }
|
|
14
|
+
const ids = new Set();
|
|
15
|
+
return input.collectorTasks.map(({ taskId, spec }) => {
|
|
16
|
+
if (typeof taskId !== 'string' || !taskId || ids.has(taskId) || typeof spec?.adapter !== 'string') {
|
|
17
|
+
throw new TypeError('Invalid or duplicate collector task declaration');
|
|
18
|
+
}
|
|
19
|
+
ids.add(taskId);
|
|
20
|
+
return { taskId, generation, specVersion: 1, spec: structuredClone(spec) };
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Compile source-derived descriptors to stable assignments or use explicitly declared identities. */
|
|
25
|
+
export default function compileCollectorTasks(input, { describe, identity }, generation = 1) {
|
|
26
|
+
if (!Array.isArray(input)) { return declaredTasks(input, generation); }
|
|
27
|
+
return input.map((process) => {
|
|
28
|
+
const spec = process.spec ? structuredClone(process.spec) : describe(process);
|
|
29
|
+
return { taskId: `${spec.adapter}:${digest(identity(spec)).slice(0, 20)}`, generation, specVersion: 1, spec };
|
|
30
|
+
});
|
|
31
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import expand from './expand.js';
|
|
2
|
+
import { versionedControlCatalog } from './controlPlan.js';
|
|
3
|
+
|
|
4
|
+
function readerPolicy(config, node, task, rows, { placement, pinned, oneCopy, matchesInput }) {
|
|
5
|
+
const matched = rows.filter(({ from }) => { return from.includes('://'); }).filter((row) => { return matchesInput(task, row, node); });
|
|
6
|
+
const policies = matched.map(({ name }) => { return config.inputs?.[name]; }).filter(Boolean);
|
|
7
|
+
if (new Set(policies.map((policy) => { return JSON.stringify(policy); })).size > 1) {
|
|
8
|
+
throw new TypeError('Conflicting replication policy for grouped reader');
|
|
9
|
+
}
|
|
10
|
+
const area = !policies[0] && (!pinned || oneCopy)
|
|
11
|
+
? placement.readPlacement(config, matched.map(({ name }) => { return name; }), node.id, config.nodes.map(({ id }) => { return id; }))
|
|
12
|
+
: null;
|
|
13
|
+
if (!policies[0] && oneCopy) {
|
|
14
|
+
const preference = area?.preference ?? [node.id];
|
|
15
|
+
return { copies: 1, cost: 1, eligibleNodes: preference, preference };
|
|
16
|
+
}
|
|
17
|
+
return placement.taskPlacement(policies[0] ?? area ?? {}, node, config, { task, pinned });
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function nodeTasks(document, expanded, config, node, ports) {
|
|
21
|
+
const server = expanded.servers.find(({ id }) => { return id === node.id; });
|
|
22
|
+
const profile = expanded.profiles[server.profile.id];
|
|
23
|
+
const readers = ports.readers(document, node.id);
|
|
24
|
+
const readerIds = new Set(readers.map(({ taskId }) => { return taskId; }));
|
|
25
|
+
const tasks = ports.assignments(document, server, profile, readers);
|
|
26
|
+
return tasks.map((task) => {
|
|
27
|
+
const { taskId, spec, specVersion } = task;
|
|
28
|
+
const local = !readerIds.has(taskId);
|
|
29
|
+
const policy = local ? { copies: 1, cost: 1, eligibleNodes: [node.id], pinnedNode: node.id }
|
|
30
|
+
: readerPolicy(config, node, task, server.fan_in, {
|
|
31
|
+
placement: ports.placement, pinned: ports.pinned(spec), oneCopy: ports.oneCopy(spec),
|
|
32
|
+
matchesInput: (item, row) => { return ports.matchesInput(document, item, row, node); }
|
|
33
|
+
});
|
|
34
|
+
return { taskId, spec: local ? ports.localSpec(spec, node.id) : ports.readerSpec(spec, node.id, config, document), specVersion, ...policy };
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Compile placement and task revisions while the application supplies protocol bindings. */
|
|
39
|
+
export default function compileControlCatalog(document, config, ports) {
|
|
40
|
+
const expanded = expand(document);
|
|
41
|
+
const known = new Set(expanded.servers.flatMap(({ fan_in: inputs = [] }) => { return inputs.map(({ name }) => { return name; }); }));
|
|
42
|
+
for (const name of Object.keys(config.inputs ?? {})) {
|
|
43
|
+
if (!known.has(name)) { throw new TypeError(`Unknown replication input ${name}`); }
|
|
44
|
+
}
|
|
45
|
+
const tasks = config.nodes.flatMap((node) => { return nodeTasks(document, expanded, config, node, ports); });
|
|
46
|
+
return versionedControlCatalog({ version: config.version, controlEpoch: config.controlEpoch, nodes: config.nodes, tasks });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Match a portable device descriptor against an input endpoint. */
|
|
50
|
+
export function matchesDeviceInput(spec, from) {
|
|
51
|
+
return Boolean(spec.config?.devices?.includes(from.replace('rtu://', 'rtu:').split('?')[0])
|
|
52
|
+
|| spec.source?.devices?.some(({ path }) => { return from.startsWith(`rtu://${path}:`); })
|
|
53
|
+
|| spec.source?.connections?.some(({ url }) => { return url === from; }));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function controlSecretKey(prefix, node) {
|
|
57
|
+
return `${prefix}_${node.replaceAll('-', '_').toUpperCase()}`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Scope broker credential references to a single control node. */
|
|
61
|
+
export function scopeControlSecrets(value, owner, secrets = ['AMQP_URL', 'MQTT_URL']) {
|
|
62
|
+
if (Array.isArray(value)) { return value.map((item) => { return scopeControlSecrets(item, owner, secrets); }); }
|
|
63
|
+
if (!value || typeof value !== 'object') { return value; }
|
|
64
|
+
if (secrets.includes(value.$secret)) { return { $secret: controlSecretKey(value.$secret, owner) }; }
|
|
65
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => { return [key, scopeControlSecrets(item, owner, secrets)]; }));
|
|
66
|
+
}
|
|
@@ -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
|
-
|
|
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
|
|
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,50 @@ 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
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Turn a chart collector into the single control-managed agent for its node. */
|
|
127
|
+
export function applyControlCollector(collector, agent) {
|
|
128
|
+
if (!agent.image) { throw new TypeError('Candidate agentImage required when edge control is enabled'); }
|
|
129
|
+
const originalEnv = Object.fromEntries(Object.entries(collector.env).filter(([name]) => { return name !== 'COLLECTOR_MANIFEST'; }));
|
|
130
|
+
const env = { ...originalEnv, ...agent.env };
|
|
131
|
+
for (const [name, field] of [['COLLECTOR_CONTROL_USERNAME', 'authUsernameKey'], ['COLLECTOR_CONTROL_PASSWORD', 'authPasswordKey']]) {
|
|
132
|
+
env[name] = { valueFrom: { secretKeyRef: { name: agent.authSecret, key: agent[field] ?? name } } };
|
|
133
|
+
}
|
|
134
|
+
return withCollectorScratch({
|
|
135
|
+
...collector, image: agent.image, startupProbe: agent.startupProbe, ...(agent.resources && { resources: agent.resources }), env,
|
|
136
|
+
envFrom: [...(collector.envFrom ?? []), { secretRef: { name: agent.deliverySecret } }],
|
|
137
|
+
volumeMounts: [...(collector.volumeMounts ?? []), { name: 'control-tls', mountPath: '/tls', readOnly: true }],
|
|
138
|
+
volumes: [...(collector.volumes ?? []), { name: 'control-tls', secret: { secretName: agent.tlsSecret } }]
|
|
139
|
+
});
|
|
140
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { isIP } from 'node:net';
|
|
2
|
+
import { deploymentResources } from './controlPlan.js';
|
|
3
|
+
|
|
4
|
+
const voteCounts = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'];
|
|
5
|
+
|
|
6
|
+
export function migrationMode(value = 'verify') {
|
|
7
|
+
if (!['apply', 'verify'].includes(value)) { throw new TypeError('Invalid history receiver migration mode'); }
|
|
8
|
+
return value;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function modes(config) {
|
|
12
|
+
for (const key of ['agentResources', 'memberResources', 'controllerResources', 'historyResources']) {
|
|
13
|
+
deploymentResources(config[key]);
|
|
14
|
+
}
|
|
15
|
+
for (const key of ['controllerEnabled', 'historyEnabled']) {
|
|
16
|
+
if (config[key] !== undefined && typeof config[key] !== 'boolean') { throw new TypeError(`Invalid ${key}`); }
|
|
17
|
+
}
|
|
18
|
+
if (!Number.isSafeInteger(config.writerEpoch) || config.writerEpoch < 1) {
|
|
19
|
+
throw new TypeError(`Writer epoch must be positive, message ${config.writerEpoch}`);
|
|
20
|
+
}
|
|
21
|
+
config.receiverMigrationsMode = migrationMode(config.receiverMigrationsMode);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function resolveNode(node, servers, policy, port) {
|
|
25
|
+
const api = servers.find(({ id }) => { return id === node.id; })?.api ?? [];
|
|
26
|
+
const addressApi = api.find(({ id }) => { return id === policy.addressApi; });
|
|
27
|
+
const address = addressApi ? new URL(addressApi.url).hostname : node.address;
|
|
28
|
+
const broker = api.find(({ id }) => { return id === policy.brokerApi; });
|
|
29
|
+
const host = isIP(address) === 6 ? `[${address}]` : address;
|
|
30
|
+
return { ...node, address, brokerEndpoint: broker?.url ?? `amqp://${host}:${port}` };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function membership(nodes, { voterCount, requiredVoters = [], nodePattern = '^[a-z0-9-]+$', addressPattern = '^[a-z0-9.:-]+$' }) {
|
|
34
|
+
if (nodes?.some(({ voter }) => { return typeof voter !== 'boolean'; })) { throw new TypeError('Boolean voter flags required'); }
|
|
35
|
+
const voters = (nodes ?? []).filter(({ voter }) => { return voter; });
|
|
36
|
+
if (!nodes || (voterCount !== undefined && voters.length !== voterCount)) {
|
|
37
|
+
throw new TypeError(voterCount === undefined ? 'Missing etcd members' : `Exactly ${voteCounts[voterCount] ?? voterCount} etcd voters required`);
|
|
38
|
+
}
|
|
39
|
+
const ids = nodes.map(({ id }) => { return id; });
|
|
40
|
+
if (new Set(ids).size !== ids.length || !requiredVoters.every((id) => { return voters.some((node) => { return node.id === id; }); })) {
|
|
41
|
+
throw new TypeError('Invalid edge membership');
|
|
42
|
+
}
|
|
43
|
+
const nodeId = new RegExp(nodePattern, 'u');
|
|
44
|
+
const host = new RegExp(addressPattern, 'u');
|
|
45
|
+
nodes.forEach(({ id, address, capacity }) => {
|
|
46
|
+
if (!nodeId.test(id) || typeof address !== 'string' || !host.test(address) || !Number.isSafeInteger(capacity) || capacity < 1) {
|
|
47
|
+
throw new TypeError('Invalid edge node');
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Resolve control members and validate a site's declared quorum constraints. */
|
|
53
|
+
export default function controlPlaneConfiguration(raw, servers, policy) {
|
|
54
|
+
const config = raw && { ...raw, nodes: raw.nodes?.map((node) => { return resolveNode(node, servers, policy, raw.brokerService?.nodePort); }) };
|
|
55
|
+
membership(config?.nodes, policy);
|
|
56
|
+
modes(config);
|
|
57
|
+
if (!Number.isSafeInteger(config.version) || config.version < 1 || !Number.isSafeInteger(config.defaultCopies)
|
|
58
|
+
|| config.defaultCopies < 1 || config.defaultCopies > config.nodes.length) {
|
|
59
|
+
throw new TypeError('Invalid control catalog version or copies');
|
|
60
|
+
}
|
|
61
|
+
return config;
|
|
62
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { scopeControlSecrets } from './compileControlCatalog.js';
|
|
2
|
+
|
|
3
|
+
function historySink(node, queue, { groups, exchange, target }) {
|
|
4
|
+
return {
|
|
5
|
+
id: `telemetry-${node}`, type: 'amqp',
|
|
6
|
+
url: target ? scopeControlSecrets({ $secret: 'AMQP_URL' }, node) : { $secret: 'AMQP_URL' },
|
|
7
|
+
...(target && { routingKeyPrefix: target }),
|
|
8
|
+
options: {
|
|
9
|
+
exchanges: [{ name: exchange, type: 'topic', options: { durable: true } }],
|
|
10
|
+
queues: [{ name: queue, options: { durable: true, autoDelete: false } }],
|
|
11
|
+
bindings: groups.map((pattern) => { return { queue, exchange, pattern }; })
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function historySinks(spec, node, config, { historyNodes, keyPrefix, historyBindings, historyExchange }) {
|
|
17
|
+
if (!spec.config.devices) {
|
|
18
|
+
return [historySink(node, config.historyQueue, { exchange: historyExchange, groups: historyBindings(node) })];
|
|
19
|
+
}
|
|
20
|
+
return config.nodes.filter(({ id }) => { return historyNodes(id); }).map(({ id }) => {
|
|
21
|
+
return historySink(id, config.historyQueue, { exchange: historyExchange, groups: historyBindings(id), target: keyPrefix(id) });
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Bind a deployed reader to its declared sink topology and delivery mode. */
|
|
26
|
+
export default function controlReaderSpec(spec, node, config, ports) {
|
|
27
|
+
const { delivery, pinCredentials, readerExchanges, sinkOptions, historyAdapter } = ports;
|
|
28
|
+
const result = { ...(pinCredentials(spec) ? scopeControlSecrets(spec, node) : spec), delivery: delivery(spec) };
|
|
29
|
+
if (Object.hasOwn(readerExchanges, spec.adapter)) {
|
|
30
|
+
const exchange = readerExchanges[spec.adapter];
|
|
31
|
+
const options = sinkOptions(exchange);
|
|
32
|
+
result.sink = { ...result.sink, options };
|
|
33
|
+
result.sinks = [{ id: `${node}-${exchange}`, type: 'amqp', url: result.sink.url, options }];
|
|
34
|
+
}
|
|
35
|
+
if (spec.adapter === historyAdapter) { result.sinks = historySinks(spec, node, config, ports); }
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Apply live chart values while retaining generated fields inside selected components. */
|
|
2
|
+
export function liveChartValues(values, { replace, components } = {}) {
|
|
3
|
+
const result = { ...values, ...replace };
|
|
4
|
+
for (const [key, overlay] of Object.entries(components ?? {})) {
|
|
5
|
+
result[key] = { ...values[key], ...overlay };
|
|
6
|
+
}
|
|
7
|
+
return result;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Overlay immutable release names and chart values by chart kind. */
|
|
11
|
+
export function liveChartApps(apps, declarations = {}) {
|
|
12
|
+
return (apps ?? []).map((app) => {
|
|
13
|
+
if (!Object.hasOwn(declarations, app.chart)) { return app; }
|
|
14
|
+
const { values, ...identity } = declarations[app.chart];
|
|
15
|
+
return { ...app, ...identity, values: { ...app.values, ...values } };
|
|
16
|
+
});
|
|
17
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { collectorMemoryDeployment, etcdMembership } from './controlPlan.js';
|
|
2
|
+
import controlPlaneConfiguration from './controlPlaneConfiguration.js';
|
|
3
|
+
import { controlSecretKey } from './compileControlCatalog.js';
|
|
4
|
+
|
|
5
|
+
function hostDevices(servers, node) {
|
|
6
|
+
const streams = servers.find(({ id }) => { return id === node; })?.fan_in ?? [];
|
|
7
|
+
return [...new Set(streams.filter(({ from }) => { return from.startsWith('rtu://'); }).map(({ from }) => {
|
|
8
|
+
return from.slice(6).split(':')[0];
|
|
9
|
+
}))].sort();
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function chartValues(config, server, servers, policy, ports) {
|
|
13
|
+
const { endpoints, initialCluster } = etcdMembership(config.nodes, config);
|
|
14
|
+
const brokerEndpoints = Object.fromEntries(config.nodes.map(({ id, brokerEndpoint }) => { return [id, brokerEndpoint]; }));
|
|
15
|
+
return {
|
|
16
|
+
...config,
|
|
17
|
+
historyBindings: ports.historyBindings(server.id),
|
|
18
|
+
historyAmqpKey: controlSecretKey('AMQP_URL', server.id),
|
|
19
|
+
historyMaintenance: config.historyEnabled !== false && ports.historyMaintenance(server.id),
|
|
20
|
+
initialCluster, endpoints,
|
|
21
|
+
member: server.voter ? { ...server, tlsSecret: server.serverTlsSecret ?? `${server.id}-control-server` } : null,
|
|
22
|
+
agent: collectorMemoryDeployment(config, server, {
|
|
23
|
+
brokerEndpoints: Object.fromEntries(Object.entries(brokerEndpoints).map(([id, url]) => {
|
|
24
|
+
return [controlSecretKey('AMQP_URL', id), url];
|
|
25
|
+
})),
|
|
26
|
+
endpoints, hostDevices: hostDevices(servers, server.id), deliverySecret: policy.deliverySecret, extraEnv: ports.checkpoint(config, server)
|
|
27
|
+
}),
|
|
28
|
+
reconcile: ports.reconcile(config.classifyApply),
|
|
29
|
+
brokerEndpoints: JSON.stringify(brokerEndpoints),
|
|
30
|
+
rabbitmqManagement: policy.rabbitmqManagement
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Project one control release from a plant document and supplied policy and runtime bindings. */
|
|
35
|
+
export default function projectControlPlane(cluster, document, policy, ports) {
|
|
36
|
+
const { servers } = document;
|
|
37
|
+
const config = controlPlaneConfiguration(document[policy.section], servers, policy);
|
|
38
|
+
const server = config.nodes.find(({ id }) => { return id === cluster; });
|
|
39
|
+
if (!server) { throw new TypeError(`Unknown edge ${cluster}`); }
|
|
40
|
+
const catalog = ports.catalog(document, config);
|
|
41
|
+
const classification = ports.classification(document, config, catalog);
|
|
42
|
+
return {
|
|
43
|
+
context: cluster, namespace: config.namespace, release: config.release, chart: policy.chart,
|
|
44
|
+
supervisor: ports.supervisor(config, server, classification.machines[server.id]), classification,
|
|
45
|
+
replicas: ports.replicas(config, document), catalog,
|
|
46
|
+
values: chartValues(config, server, servers, policy, ports)
|
|
47
|
+
};
|
|
48
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import freezeDeploymentDocument from './frozen.js';
|
|
2
|
+
|
|
3
|
+
function node(kind, parent, id, title, { silence, binding }) {
|
|
4
|
+
return Object.freeze({ ...(binding && { binding }), kind, parent, path: parent ? `${parent}/${id}` : id, silence, title });
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function metricNodes(machine, parent, topics, silence) {
|
|
8
|
+
return Object.entries(topics).flatMap(([source, template]) => {
|
|
9
|
+
return (machine.sensors?.[source] ?? []).map((sensor) => {
|
|
10
|
+
const values = { ...machine, ...sensor };
|
|
11
|
+
const topic = template.replace(/\{(?<field>\w+)\}/gu, (token, key) => {
|
|
12
|
+
if (!Object.hasOwn(values, key)) { throw new TypeError(`Unknown topology binding field ${key}`); }
|
|
13
|
+
return String(values[key]);
|
|
14
|
+
});
|
|
15
|
+
return node('metric', parent, sensor.key, sensor.label,
|
|
16
|
+
{ silence, binding: Object.freeze({ topic, unit: sensor.unit }) });
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Project a plant topology and a flat namespace using declared sensor binding templates. */
|
|
22
|
+
export default function projectTopology(document, topics = {}) {
|
|
23
|
+
const { sensorProfiles, silenceSeconds, ...layout } = freezeDeploymentDocument(document);
|
|
24
|
+
const machines = layout.machines.map(({ sensorProfile, ...machine }) => {
|
|
25
|
+
return Object.freeze({ ...machine, ...(sensorProfile && { sensors: sensorProfiles?.[sensorProfile] }) });
|
|
26
|
+
});
|
|
27
|
+
const projected = Object.freeze({ ...layout, machines: Object.freeze(machines) });
|
|
28
|
+
return {
|
|
29
|
+
topology() { return projected; },
|
|
30
|
+
namespace() {
|
|
31
|
+
return Object.freeze([
|
|
32
|
+
node('plant', '', layout.plant, layout.title, { silence: silenceSeconds }),
|
|
33
|
+
...layout.shops.map(({ id, label }) => { return node('shop', layout.plant, id, label, { silence: silenceSeconds }); }),
|
|
34
|
+
...machines.flatMap((machine) => {
|
|
35
|
+
const equipment = node(machine.kind, `${layout.plant}/${machine.shop}`, machine.id, machine.label, { silence: silenceSeconds });
|
|
36
|
+
return [equipment, ...metricNodes(machine, equipment.path, topics, silenceSeconds)];
|
|
37
|
+
})
|
|
38
|
+
]);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
@@ -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
|
+
}
|