@yarkivaev/scada 2.26.0 → 2.28.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/README.md CHANGED
@@ -42,6 +42,12 @@ Module entries are local JS files relative to the declaring runtime document. Th
42
42
 
43
43
  The release workflow publishes Node.js and JVM images and records their digests alongside the release revision. The Node image includes `scada-install-app URL SHA256 DESTINATION`, which verifies and extracts an application bundle for read-only mounting. The JVM image loads an optional profile JAR with the class named by `SCADA_RUNTIME_PROFILE`. The application selects compatible image and bundle digests in the deployment.
44
44
 
45
+ ## Collection deployment DSL
46
+
47
+ A deployment document can declare equipment endpoints in `sources`, logical inputs in `streams`, and assignment policy in `controlPlane.readers`. Each reader refers to one stream through its key or to a list under `streams`. Its ordered `eligible` nodes and requested `copies` guide the controller. The `delivery` map names destinations by stream. Archive destinations can receive readings without joining the set of eligible reader nodes.
48
+
49
+ `readDeploymentDocument` loads additional `controlPlane.fragments` relative to the root document and rejects duplicate control-plane keys across those files. `resolveCollection` resolves input and delivery references, and `compileNamedControlCatalog` combines placement with adapter specifications supplied by the application. Nodes default to a scheduling capacity of 100 and can select a shared agent resource profile from `controlPlane.deployment.agentProfiles`.
50
+
45
51
  ## Package boundary
46
52
 
47
53
  SCADA owns the shared collection and processing engines, storage and APIs. Plant applications supply the deployment DSL, device mappings, business rules, routes and HMI. See the [package boundary](docs/architecture/package-boundary.md).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.26.0",
3
+ "version": "2.28.0",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -76,7 +76,8 @@ export function collectorDeviceAssignments(document, selection, { rules, sourceT
76
76
  const profile = profileDefinitionFor(expanded, server);
77
77
  const rows = (releases(document, server.id).scada.machines || []).filter((row) => { return accepts(row, selection, rules); });
78
78
  const processes = sourceTypes.flatMap(({ schemes, projection }) => {
79
- return collect[projection](rows.filter((row) => { return schemes.includes(sourceScheme(row.from)); }), profile.apps.scada);
79
+ return collect[projection](rows.filter((row) => { return schemes.includes(sourceScheme(row.from)); }),
80
+ profile.apps.scada, document.sources);
80
81
  });
81
82
  return compile(processes, generation);
82
83
  });
@@ -0,0 +1,42 @@
1
+ import { collectorConsumerTasks } from './collectorSourcePlan.js';
2
+ import deploymentTemplate from '../../infrastructure/deploy/deploymentTemplate.js';
3
+
4
+ function ownedPath(document, prefix, cluster) {
5
+ const paths = Object.entries(document.objectOwners ?? {}).filter(([path, owner]) => {
6
+ return owner === cluster && path.startsWith(prefix) && path.length > prefix.length;
7
+ });
8
+ if (paths.length > 1) { throw new TypeError(`Local consumer site ${cluster} owns multiple objects under ${prefix}`); }
9
+ return paths[0]?.[0];
10
+ }
11
+
12
+ function withBatchDefaults(declarations, defaults) {
13
+ const ids = new Set();
14
+ return declarations.map(({ id, when, batchTarget, spec }) => {
15
+ if (typeof id !== 'string' || !id || ids.has(id) || typeof spec?.adapter !== 'string' || !spec.adapter) {
16
+ throw new TypeError('Invalid or duplicate consumer declaration');
17
+ }
18
+ ids.add(id);
19
+ const configuration = batchTarget === undefined ? spec : {
20
+ ...spec, [batchTarget]: { ...defaults, ...spec[batchTarget] }
21
+ };
22
+ return { id, when, spec: configuration };
23
+ });
24
+ }
25
+
26
+ /** Resolve local task templates against the object and profile of their declared owner. */
27
+ export default function compileLocalConsumers(document, server, app, { generation = 1, bindings, validate } = {}) {
28
+ const policy = document.controlPlane?.localConsumers;
29
+ if (policy === undefined) { return []; }
30
+ const { objectOwnerPrefix, consumers, batchDefaults = {} } = policy;
31
+ if (typeof objectOwnerPrefix !== 'string' || !objectOwnerPrefix.endsWith('/') || !Array.isArray(consumers)) {
32
+ throw new TypeError('Local consumers require an object owner prefix and declarations');
33
+ }
34
+ const cluster = server.id;
35
+ const path = ownedPath(document, objectOwnerPrefix, cluster);
36
+ if (!path) { return []; }
37
+ const declarations = withBatchDefaults(consumers, batchDefaults);
38
+ const context = { path, machine: path.slice(objectOwnerPrefix.length), cluster, server, app, document };
39
+ const values = { ...context, ...bindings?.(context), ...deploymentTemplate(policy.bindings ?? {}, context) };
40
+ validate?.(values);
41
+ return collectorConsumerTasks(declarations, cluster, values, generation);
42
+ }
@@ -0,0 +1,23 @@
1
+ import { versionedControlCatalog } from './controlPlan.js';
2
+ import { resolveCollection } from './namedCollection.js';
3
+
4
+ /** Compile assignment specs from readers and pin consumers to their local state. */
5
+ export default function compileNamedControlCatalog(document, config, { readerTasks, localTasks = () => { return []; } }) {
6
+ const { readers } = resolveCollection(document);
7
+ const physical = readers.flatMap((reader) => {
8
+ const { eligible, copies, cost } = reader;
9
+ return readerTasks(reader).map(({ taskId, spec, specVersion, pinnedNode }) => {
10
+ if (pinnedNode !== undefined && (copies !== 1 || eligible.length !== 1 || pinnedNode !== eligible[0])) {
11
+ throw new TypeError(`Reader ${reader.id} pins a task outside its placement policy`);
12
+ }
13
+ return { taskId, spec, specVersion, copies, cost, eligibleNodes: eligible,
14
+ ...(pinnedNode === undefined ? { preference: eligible } : { pinnedNode }) };
15
+ });
16
+ });
17
+ const local = config.nodes.flatMap((node) => {
18
+ return localTasks(node).map(({ taskId, spec, specVersion }) => {
19
+ return { taskId, spec, specVersion, copies: 1, cost: 1, eligibleNodes: [node.id], pinnedNode: node.id };
20
+ });
21
+ });
22
+ return versionedControlCatalog({ version: config.version, controlEpoch: config.controlEpoch, nodes: config.nodes, tasks: [...physical, ...local] });
23
+ }
@@ -0,0 +1,79 @@
1
+ const routeFields = ['fan_in', 'fan_out', 'objects', 'ownership'];
2
+
3
+ function isMap(value) {
4
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
5
+ }
6
+
7
+ /** Resolve a catalog source. Route parameters select a stream from a shared endpoint. */
8
+ export function sourceAddress(sources, id, query) {
9
+ if (typeof id !== 'string' || !Object.hasOwn(sources ?? {}, id)) {
10
+ throw new TypeError(`Unknown source ${id}`);
11
+ }
12
+ const { address } = sources[id] ?? {};
13
+ if (typeof address !== 'string' || !address.includes('://')) {
14
+ throw new TypeError(`Source ${id} must declare an address`);
15
+ }
16
+ if (query === undefined) { return address; }
17
+ if (!isMap(query)) { throw new TypeError(`Source ${id} query must be a map`); }
18
+ const url = new URL(address);
19
+ for (const [key, value] of Object.entries(query)) {
20
+ if (!['string', 'number', 'boolean'].includes(typeof value)) {
21
+ throw new TypeError(`Invalid query value for source ${id}: ${key}`);
22
+ }
23
+ url.searchParams.set(key, String(value));
24
+ }
25
+ return url.href;
26
+ }
27
+
28
+ function resolveInput(input, sources) {
29
+ if (!Object.hasOwn(input, 'source')) {
30
+ if (Object.hasOwn(input, 'query')) { throw new TypeError('Routing query requires a source reference'); }
31
+ return input;
32
+ }
33
+ const { source, query, ...flow } = input;
34
+ if (Object.hasOwn(flow, 'from')) { throw new TypeError('Routing input cannot declare both source and from'); }
35
+ return { from: sourceAddress(sources, source, query), ...flow };
36
+ }
37
+
38
+ function apiPublications(server, publications) {
39
+ if (!isMap(publications)) { throw new TypeError(`Routing publications for ${server.id} must be a map`); }
40
+ const api = server.api ?? [];
41
+ for (const id of Object.keys(publications)) {
42
+ if (!api.some((entry) => { return entry.id === id; })) { throw new TypeError(`Unknown routing API ${id} on ${server.id}`); }
43
+ }
44
+ return api.map((entry) => {
45
+ if (!Object.hasOwn(publications, entry.id)) { return entry; }
46
+ if (Object.hasOwn(entry, 'publishes')) { throw new TypeError(`Server ${server.id} declares publishes twice for ${entry.id}`); }
47
+ return { ...entry, publishes: publications[entry.id] };
48
+ });
49
+ }
50
+
51
+ function withRoutes(server, route, sources) {
52
+ if (!isMap(route)) { throw new TypeError(`Routing for ${server.id} must be a map`); }
53
+ const result = { ...server };
54
+ for (const [key, value] of Object.entries(route)) {
55
+ if (key === 'publishes') {
56
+ result.api = apiPublications(server, value);
57
+ } else {
58
+ if (!routeFields.includes(key)) { throw new TypeError(`Unknown routing field ${key} on ${server.id}`); }
59
+ if (Object.hasOwn(server, key)) { throw new TypeError(`Server ${server.id} declares ${key} twice`); }
60
+ if (!Array.isArray(value)) { throw new TypeError(`Routing ${key} for ${server.id} must be a list`); }
61
+ result[key] = key === 'fan_in' ? value.map((input) => { return resolveInput(input, sources); }) : value;
62
+ }
63
+ }
64
+ return result;
65
+ }
66
+
67
+ /** Project separately declared routes into the existing system-document shape. */
68
+ export default function resolveDeploymentRouting(document) {
69
+ const { routes, ...rest } = document;
70
+ if (routes === undefined) { return document; }
71
+ if (!isMap(routes)) { throw new TypeError('Deployment routes must be a map'); }
72
+ const servers = document.servers ?? [];
73
+ for (const id of Object.keys(routes)) {
74
+ if (!servers.some((server) => { return server.id === id; })) { throw new TypeError(`Unknown routing server ${id}`); }
75
+ }
76
+ return { ...rest, servers: servers.map((server) => {
77
+ return Object.hasOwn(routes, server.id) ? withRoutes(server, routes[server.id], document.sources) : server;
78
+ }) };
79
+ }
@@ -1,6 +1,8 @@
1
1
  import { expandTree, treePaths } from './expandNamespace.js';
2
2
  import { expandProfiles } from './expandProfiles.js';
3
3
  import { expandServers } from './expandFlows.js';
4
+ import resolveDeploymentRouting from './deploymentRouting.js';
5
+ import projectCollectionRoutes from './projectCollectionRoutes.js';
4
6
  import frozen from './frozen.js';
5
7
 
6
8
  /**
@@ -35,14 +37,15 @@ export default function expand(document) {
35
37
  if (!document || typeof document !== 'object' || Array.isArray(document)) {
36
38
  throw new Error('system document is empty');
37
39
  }
38
- const namespace = expandTree(document.namespace, document.templates || {});
40
+ const input = projectCollectionRoutes(resolveDeploymentRouting(document));
41
+ const namespace = expandTree(input.namespace, input.templates || {});
39
42
  const paths = treePaths(namespace);
40
- const profiles = expandProfiles(document.profiles || {});
41
- assertProfiles(document.servers || [], profiles);
42
- const servers = expandServers(document.servers || [], paths, document.mappings || {});
43
+ const profiles = expandProfiles(input.profiles || {});
44
+ assertProfiles(input.servers || [], profiles);
45
+ const servers = expandServers(input.servers || [], paths, input.mappings || {});
43
46
  return frozen({
44
- ...(document.hmi !== undefined && { hmi: document.hmi }),
45
- mappings: document.mappings || {},
47
+ ...(input.hmi !== undefined && { hmi: input.hmi }),
48
+ mappings: input.mappings || {},
46
49
  namespace,
47
50
  profiles,
48
51
  servers
@@ -88,6 +88,9 @@ export default function mergeDocuments(base, extra) {
88
88
  if (base.mappings || extra.mappings) {
89
89
  document.mappings = mergeMaps(base.mappings, extra.mappings);
90
90
  }
91
+ for (const key of ['sources', 'streams', 'delivery', 'objectOwners', 'externalPublications', 'routes']) {
92
+ if (base[key] || extra[key]) { document[key] = mergeMaps(base[key], extra[key]); }
93
+ }
91
94
  if (base.profiles || extra.profiles) {
92
95
  document.profiles = mergeMaps(base.profiles, extra.profiles);
93
96
  }
@@ -0,0 +1,68 @@
1
+ import { sourceAddress } from './deploymentRouting.js';
2
+
3
+ function asMap(value, label) {
4
+ if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new TypeError(`${label} must be a map`); }
5
+ return value;
6
+ }
7
+
8
+ function ids(value, label, known) {
9
+ const list = typeof value === 'string' ? [value] : value;
10
+ if (!Array.isArray(list) || list.length === 0 || new Set(list).size !== list.length
11
+ || list.some((id) => { return typeof id !== 'string' || !known.has(id); })) {
12
+ throw new TypeError(`Invalid ${label}`);
13
+ }
14
+ return list;
15
+ }
16
+
17
+ function resolveStream(id, declaration, sources, mappings) {
18
+ const { source, path, query, mapping } = asMap(declaration, `Stream ${id}`);
19
+ const from = sourceAddress(sources, source, query);
20
+ if (typeof path !== 'string' || path.split('/').some((part) => { return !part; })) {
21
+ throw new TypeError(`Invalid path for stream ${id}`);
22
+ }
23
+ if (typeof mapping === 'string' && !Object.hasOwn(mappings, mapping)) {
24
+ throw new TypeError(`Unknown mapping ${mapping} for stream ${id}`);
25
+ }
26
+ const resolvedMapping = typeof mapping === 'string' ? mappings[mapping] : mapping;
27
+ return { ...declaration, id, source: sources[source], address: sources[source].address, from, path, name: path, resolvedMapping };
28
+ }
29
+
30
+ function resolveReaders(declarations, streams, controlNodes) {
31
+ const readers = [];
32
+ const assigned = new Set();
33
+ for (const [id, declaration] of Object.entries(asMap(declarations, 'Control readers'))) {
34
+ const { streams: included = [id], eligible, copies = 1, cost = 1 } = asMap(declaration, `Reader ${id}`);
35
+ const nodes = ids(eligible, `eligible nodes for reader ${id}`, controlNodes);
36
+ if (!Number.isSafeInteger(copies) || copies < 1 || copies > nodes.length || !Number.isSafeInteger(cost) || cost < 1) {
37
+ throw new TypeError(`Invalid copies or cost for reader ${id}`);
38
+ }
39
+ const reading = ids(included, `streams for reader ${id}`, streams).map((stream) => {
40
+ if (assigned.has(stream)) { throw new TypeError(`Stream ${stream} has more than one reader`); }
41
+ assigned.add(stream);
42
+ return streams.get(stream);
43
+ });
44
+ readers.push({ id, eligible: nodes, copies, cost, streams: reading });
45
+ }
46
+ for (const id of streams.keys()) {
47
+ if (!assigned.has(id)) { throw new TypeError(`Stream ${id} has no reader`); }
48
+ }
49
+ return readers;
50
+ }
51
+
52
+ /** Resolve named collection inputs without assigning readers to machines. */
53
+ export function resolveCollection(document) {
54
+ const { controlPlane, sources, streams, mappings = {}, servers = [], delivery = {}, objectOwners = {}, externalPublications = {} } = document;
55
+ const serverIds = new Set(servers.map(({ id }) => { return id; }));
56
+ const controlNodes = new Set(controlPlane?.nodes?.map(({ id }) => { return id; }));
57
+ if ([...controlNodes].some((id) => { return !serverIds.has(id); })) { throw new TypeError('Unknown control node'); }
58
+ const resolved = new Map(Object.entries(asMap(streams, 'Streams')).map(([id, stream]) => {
59
+ return [id, resolveStream(id, stream, sources, mappings)];
60
+ }));
61
+ const destinations = Object.fromEntries(Object.entries(asMap(delivery, 'Delivery')).map(([stream, route]) => {
62
+ if (!resolved.has(stream)) { throw new TypeError(`Unknown delivery stream ${stream}`); }
63
+ const { to, viaApi } = asMap(route, `Delivery ${stream}`);
64
+ if (viaApi !== undefined && (typeof viaApi !== 'string' || !viaApi)) { throw new TypeError(`Invalid delivery API for ${stream}`); }
65
+ return [stream, { to: ids(to, `destinations for stream ${stream}`, serverIds), viaApi }];
66
+ }));
67
+ return { readers: resolveReaders(controlPlane?.readers, resolved, controlNodes), delivery: destinations, objectOwners, externalPublications };
68
+ }
@@ -0,0 +1,37 @@
1
+ import deploymentTemplate from '../../infrastructure/deploy/deploymentTemplate.js';
2
+
3
+ function nodeSettings(node, deployment) {
4
+ const profile = node.agentProfile;
5
+ const profiles = deployment.agentProfiles ?? {};
6
+ if (profile !== undefined && !Object.hasOwn(profiles, profile)) {
7
+ throw new TypeError(`Unknown control agent profile ${profile}`);
8
+ }
9
+ const clientTlsSecret = node.clientTlsSecret ?? (deployment.nodeTlsSecretTemplate
10
+ && deploymentTemplate(deployment.nodeTlsSecretTemplate, { node: node.id }));
11
+ return {
12
+ ...node,
13
+ capacity: node.capacity ?? 100,
14
+ ...(profile !== undefined && { agent: { ...profiles[profile], ...node.agent } }),
15
+ ...(clientTlsSecret && { clientTlsSecret })
16
+ };
17
+ }
18
+
19
+ /** Supply runtime defaults for a named control-plane declaration. */
20
+ export default function normalizeControlPlane(raw) {
21
+ if (raw?.readers === undefined) { return raw; }
22
+ const { deployment = {}, nodes = [], ...control } = raw;
23
+ const { images = {} } = deployment;
24
+ return {
25
+ version: 1, controlEpoch: 'initial', writerEpoch: 1, defaultCopies: 1,
26
+ etcdImage: images.etcd,
27
+ controllerImage: images.control,
28
+ agentImage: images.control,
29
+ supervisorImage: images.supervisor,
30
+ receiverImage: images.historyReceiver,
31
+ classifyApply: raw.classification !== undefined,
32
+ historyEnabled: raw.history !== undefined,
33
+ ...control,
34
+ deployment,
35
+ nodes: nodes.map((node) => { return nodeSettings(node, deployment); })
36
+ };
37
+ }
@@ -0,0 +1,99 @@
1
+ import { resolveCollection } from './namedCollection.js';
2
+ import { fits, zipped } from './expandPattern.js';
3
+
4
+ function addPublications(servers, declarations) {
5
+ for (const [node, publications] of Object.entries(declarations)) {
6
+ const server = servers.get(node);
7
+ if (!server) { throw new TypeError(`Unknown publication node ${node}`); }
8
+ for (const [id, publishes] of Object.entries(publications)) {
9
+ if (!server.api?.some((api) => { return api.id === id; })) { throw new TypeError(`Unknown publication API ${id} on ${node}`); }
10
+ if (!Array.isArray(publishes)) { throw new TypeError(`Invalid publications on ${node} API ${id}`); }
11
+ server.api = server.api.map((api) => { return api.id === id ? { ...api, publishes: [...(api.publishes ?? []), ...publishes] } : api; });
12
+ }
13
+ }
14
+ }
15
+
16
+ function addRoute(servers, origin, stream, route, brokerApi) {
17
+ if (!route) { return; }
18
+ const api = route.viaApi ?? origin.api?.find((entry) => { return entry.id === brokerApi; })?.id;
19
+ for (const id of route.to.filter((target) => { return target !== origin.id; })) {
20
+ const target = servers.get(id);
21
+ target.fan_in.push({ from: origin.id, name: stream.path, ...(api && { api }) });
22
+ origin.fan_out.push({ name: stream.path, to: id });
23
+ }
24
+ }
25
+
26
+ function publicationApi(publications, path, viaApi) {
27
+ return Object.entries(publications).find(([name, entries]) => {
28
+ return (!viaApi || viaApi === name) && entries.some(({ name: pattern }) => {
29
+ return zipped(pattern).some((part) => { return fits(part, path); });
30
+ });
31
+ })?.[0];
32
+ }
33
+
34
+ function addExternalRoutes(servers, primary, stream, route, declarations) {
35
+ if (!route) { return; }
36
+ for (const [id, publications] of Object.entries(declarations)) {
37
+ if (id !== primary) {
38
+ const api = publicationApi(publications, stream.path, route.viaApi);
39
+ if (api) { addRoute(servers, servers.get(id), stream, { ...route, viaApi: api }); }
40
+ }
41
+ }
42
+ }
43
+
44
+ function deliveryApi(plane, objectOwners, origin, path) {
45
+ const { addressApi, brokerApi } = plane.deployment ?? {};
46
+ const owns = Object.entries(objectOwners).some(([object, owner]) => {
47
+ return owner === origin && (path === object || path.startsWith(`${object}/`));
48
+ });
49
+ return owns ? addressApi : brokerApi;
50
+ }
51
+
52
+ function brokerServices(servers, plane) {
53
+ const { addressApi, brokerApi } = plane.deployment ?? {};
54
+ const port = plane.brokerService?.nodePort;
55
+ if (!addressApi || !brokerApi || !port) { return; }
56
+ const nodes = plane.nodes.map(({ id }) => { return servers.get(id); });
57
+ const missing = nodes.filter((server) => { return !server.api?.some(({ id }) => { return id === brokerApi; }); });
58
+ for (const server of missing) {
59
+ const address = server.api?.find(({ id }) => { return id === addressApi; });
60
+ if (address) {
61
+ const { hostname } = new URL(address.url);
62
+ server.api = [...server.api, { id: brokerApi, url: `amqp://${hostname}:${port}` }];
63
+ }
64
+ }
65
+ }
66
+
67
+ function routeServers(declarations, objectOwners) {
68
+ const servers = new Map(declarations.map((server) => {
69
+ if (Object.hasOwn(server, 'fan_in') || Object.hasOwn(server, 'fan_out')) {
70
+ throw new TypeError(`Server ${server.id} cannot declare flows alongside control readers`);
71
+ }
72
+ return [server.id, { ...server, fan_in: [], fan_out: [], objects: [...(server.objects ?? [])] }];
73
+ }));
74
+ for (const [path, id] of Object.entries(objectOwners)) {
75
+ const server = servers.get(id);
76
+ if (!server) { throw new TypeError(`Unknown owner ${id} for ${path}`); }
77
+ if (!server.objects.includes(path)) { server.objects.push(path); }
78
+ }
79
+ return servers;
80
+ }
81
+
82
+ /** Derive the static transport view used by runtime and broker plan consumers. */
83
+ export default function projectCollectionRoutes(document) {
84
+ if (document.controlPlane?.readers === undefined) { return document; }
85
+ const { readers, delivery, objectOwners, externalPublications } = resolveCollection(document);
86
+ const servers = routeServers(document.servers, objectOwners);
87
+ brokerServices(servers, document.controlPlane);
88
+ addPublications(servers, externalPublications);
89
+ for (const { eligible: [primary], streams } of readers) {
90
+ const origin = servers.get(primary);
91
+ for (const stream of streams) {
92
+ origin.fan_in.push({ from: stream.from, name: stream.path, ...(stream.mapping !== undefined && { mapping: stream.mapping }) });
93
+ const route = delivery[stream.id];
94
+ addRoute(servers, origin, stream, route, deliveryApi(document.controlPlane, objectOwners, origin.id, stream.path));
95
+ addExternalRoutes(servers, primary, stream, route, externalPublications);
96
+ }
97
+ }
98
+ return { ...document, servers: [...servers.values()] };
99
+ }
@@ -1,6 +1,8 @@
1
1
  import { collectorMemoryDeployment, etcdMembership } from './controlPlan.js';
2
2
  import controlPlaneConfiguration from './controlPlaneConfiguration.js';
3
3
  import { controlSecretKey } from './compileControlCatalog.js';
4
+ import projectCollectionRoutes from './projectCollectionRoutes.js';
5
+ import normalizeControlPlane from './normalizeControlPlane.js';
4
6
 
5
7
  function hostDevices(servers, node) {
6
8
  const streams = servers.find(({ id }) => { return id === node; })?.fan_in ?? [];
@@ -33,10 +35,10 @@ function chartValues(config, server, servers, policy, ports) {
33
35
 
34
36
  /** Project one control release from a plant document and supplied policy and runtime bindings. */
35
37
  export default function projectControlPlane(cluster, document, policy, ports) {
36
- const { servers } = document;
37
- const config = controlPlaneConfiguration(document[policy.section], servers, policy);
38
+ const config = controlPlaneConfiguration(normalizeControlPlane(document[policy.section]), document.servers, policy);
38
39
  const server = config.nodes.find(({ id }) => { return id === cluster; });
39
40
  if (!server) { throw new TypeError(`Unknown edge ${cluster}`); }
41
+ const { servers } = projectCollectionRoutes(document);
40
42
  const catalog = ports.catalog(document, config);
41
43
  const classification = ports.classification(document, config, catalog);
42
44
  return {
@@ -1,4 +1,6 @@
1
1
  import readDocumentFile, { selectDeploymentPhase } from './readDocumentFile.js';
2
+ import readDocument from './readDocument.js';
3
+ import resolveDeploymentRouting from './deploymentRouting.js';
2
4
 
3
5
  function fileSelection(file) {
4
6
  if (file instanceof URL) {
@@ -8,10 +10,33 @@ function fileSelection(file) {
8
10
  return fragment < 0 ? { path: file } : { path: file.slice(0, fragment), phase: file.slice(fragment + 1) };
9
11
  }
10
12
 
13
+ function controlFragments(document, load, parse) {
14
+ const { fragments, ...controlPlane } = document.controlPlane ?? {};
15
+ if (fragments === undefined) { return document; }
16
+ if (!Array.isArray(fragments) || fragments.some((name) => { return typeof name !== 'string' || !name.trim(); })) {
17
+ throw new TypeError('Control plane fragments must be paths');
18
+ }
19
+ for (const name of fragments) {
20
+ const fragment = parse(load(name), load);
21
+ const section = fragment?.controlPlane;
22
+ if (Object.keys(fragment ?? {}).length !== 1 || !section || typeof section !== 'object' || Array.isArray(section)) {
23
+ throw new TypeError(`Control plane fragment ${name} must declare controlPlane`);
24
+ }
25
+ for (const [key, value] of Object.entries(section)) {
26
+ if (key === 'fragments' || Object.hasOwn(controlPlane, key)) {
27
+ throw new TypeError(`Duplicate control plane key ${key} in ${name}`);
28
+ }
29
+ Object.defineProperty(controlPlane, key, { value, enumerable: true, configurable: true, writable: true });
30
+ }
31
+ }
32
+ return { ...document, controlPlane };
33
+ }
34
+
11
35
  /** A deployment document can declare its phase policy and be opened as path#phase. */
12
- export default function readDeploymentDocument(file, parse) {
36
+ export default function readDeploymentDocument(file, parse = readDocument) {
13
37
  const { path, phase } = fileSelection(file);
14
- const { deploymentPhase: policy, ...document } = readDocumentFile(path, parse);
38
+ const loaded = readDocumentFile(path, (text, load) => { return controlFragments(parse(text, load), load, parse); });
39
+ const { deploymentPhase: policy, ...document } = resolveDeploymentRouting(loaded);
15
40
  if (policy === undefined) {
16
41
  if (phase !== undefined) { throw new TypeError('Deployment phase policy is missing'); }
17
42
  return document;
@@ -21,16 +21,32 @@ export async function collectorLaunch(options, registry, manifest, { run = runCo
21
21
  return null;
22
22
  }
23
23
 
24
+ function checkAssignmentSource(source, options, argv, env) {
25
+ if (source === undefined) { return; }
26
+ if (source !== 'controlPlane') { throw new TypeError('Unknown collector assignment source'); }
27
+ if (options) {
28
+ if (!options.tasks.length) { throw new TypeError('Control-managed collectors only support explicit DSL selection for named tasks'); }
29
+ if (!options.render && env.COLLECTOR_CONTROL_ENDPOINTS) { throw new TypeError('Cannot combine a named task with a controller'); }
30
+ return;
31
+ }
32
+ if (argv.length || env.COLLECTOR_MANIFEST || env.COLLECTOR_MANIFEST_PATH) {
33
+ throw new TypeError('Control-managed collectors cannot start an independent assignment manifest');
34
+ }
35
+ if (!env.COLLECTOR_CONTROL_ENDPOINTS) { throw new TypeError('Control-managed collectors require control endpoints'); }
36
+ }
37
+
24
38
  /** Run the collector command with the application's registry and manifest bindings. */
25
39
  export async function launchCollectorCommand(argv, {
26
- registry, manifest, delivery, env = process.env, run = runCollector,
40
+ registry, manifest, delivery, assignmentSource, env = process.env, run = runCollector,
27
41
  requireOnce = false,
28
42
  write = (body) => { process.stdout.write(body); }
29
43
  }) {
44
+ const options = argv.some((arg) => { return arg.startsWith('--'); }) ? collectorOptions(argv) : undefined;
45
+ checkAssignmentSource(assignmentSource, options, argv, env);
30
46
  controlDeliveryEnvironment(env, delivery);
31
47
  const adapters = registry();
32
- if (argv.some((arg) => { return arg.startsWith('--'); })) {
33
- const result = await collectorLaunch(collectorOptions(argv), adapters, manifest, { run, env, requireOnce });
48
+ if (options) {
49
+ const result = await collectorLaunch(options, adapters, manifest, { run, env, requireOnce });
34
50
  if (result) { write(`${JSON.stringify(result, null, 2)}\n`); }
35
51
  } else {
36
52
  if (requireOnce) { throw new Error('collector jobs require explicit DSL selection'); }
@@ -100,7 +100,9 @@ export default function configuredControlPlane(policy, ports) {
100
100
  return function plan(cluster, document = null) {
101
101
  const source = document || ports.read();
102
102
  return projectControlPlane(cluster, source, policy, {
103
- catalog(input, config) { return compileControlCatalog(input, config, readers); },
103
+ catalog(input, config) {
104
+ return (ports.catalog ?? compileControlCatalog)(input, config, readers);
105
+ },
104
106
  classification(input, config, catalog) { return associatedTasks(ports.classification(input, config), catalog); },
105
107
  replicas(config, input) {
106
108
  const central = serverFor(input, policy.central);
@@ -29,6 +29,12 @@ export { default as preflightKubeStorage } from './preflightKubeStorage.js';
29
29
  export { default as applyWhenChanged } from './applyWhenChanged.js';
30
30
  export { default as prepareKubePrerequisites } from './prepareKubePrerequisites.js';
31
31
  export { default as readDeploymentDocument } from '../../application/deploy/readDeploymentDocument.js';
32
+ export { resolveCollection } from '../../application/deploy/namedCollection.js';
33
+ export { default as compileNamedControlCatalog } from '../../application/deploy/compileNamedControlCatalog.js';
34
+ export { default as compileLocalConsumers } from '../../application/deploy/compileLocalConsumers.js';
35
+ export { default as normalizeControlPlane } from '../../application/deploy/normalizeControlPlane.js';
36
+ export { profileDefinitionFor } from '../../application/deploy/releaseNodes.js';
37
+ export { sourceAddress } from '../../application/deploy/deploymentRouting.js';
32
38
  export { appendReplicaTopology, replicaShovels, brokerReplicaPlan, appendBrokerReplicas } from './brokerReplicaTopology.js';
33
39
  export { default as compileDeploymentHooks } from './compileDeploymentHooks.js';
34
40
  export { default as stagedStoragePreflight } from './stagedStoragePreflight.js';
@@ -67,7 +67,9 @@ function collector(state, policy, ports) {
67
67
  const process = deploymentTemplate(policy.collectorProcess, { app, collectorEnv, collectorResources: resources });
68
68
  return { values: { processes: [ports.controlCollector(document, cluster, process)] },
69
69
  ...(controlCatalog && { controlCatalog, cutoverTasks: controlCatalog.tasks.filter((task) => {
70
- return !task.pinnedNode && assignments.some(({ taskId }) => { return taskId === task.taskId; });
70
+ if (task.pinnedNode) { return false; }
71
+ return document.controlPlane?.readers ? task.preference?.[0] === cluster
72
+ : assignments.some(({ taskId }) => { return taskId === task.taskId; });
71
73
  }) }) };
72
74
  }
73
75