@yarkivaev/scada 2.28.0 → 2.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +14 -2
  2. package/charts/scada-workloads/templates/_collector.tpl +3 -0
  3. package/charts/scada-workloads/templates/_control-agent.tpl +4 -1
  4. package/charts/scada-workloads/templates/_controller.tpl +3 -0
  5. package/charts/scada-workloads/templates/_history-maintenance.tpl +3 -0
  6. package/charts/scada-workloads/templates/_history-receiver.tpl +4 -1
  7. package/charts/scada-workloads/templates/_journal-supervisor.tpl +3 -0
  8. package/charts/scada-workloads/templates/_runtime.tpl +13 -0
  9. package/charts/scada-workloads/templates/_site-server.tpl +4 -1
  10. package/charts/scada-workloads/templates/_supervisor.tpl +3 -0
  11. package/charts/scada-workloads/templates/_telemetry.tpl +4 -1
  12. package/package.json +1 -1
  13. package/src/application/deploy/collectionEvents.js +50 -0
  14. package/src/application/deploy/collectionPlacement.js +42 -0
  15. package/src/application/deploy/compileLocalConsumers.js +42 -0
  16. package/src/application/deploy/expand.js +1 -0
  17. package/src/application/deploy/historyPlacement.js +61 -0
  18. package/src/application/deploy/mergeDocuments.js +9 -1
  19. package/src/application/deploy/namedCollection.js +119 -21
  20. package/src/application/deploy/namedProcessing.js +145 -0
  21. package/src/application/deploy/normalizeControlPlane.js +43 -0
  22. package/src/application/deploy/paths.js +3 -1
  23. package/src/application/deploy/projectCollectionRoutes.js +22 -18
  24. package/src/application/deploy/projectControlPlane.js +2 -2
  25. package/src/application/deploy/readDeploymentDocument.js +9 -3
  26. package/src/application/deploy/releaseValues.js +5 -3
  27. package/src/application/deploy/streamNamespace.js +32 -0
  28. package/src/application/deploy/workloadDeclarations.js +26 -0
  29. package/src/application/plantServer.js +1 -0
  30. package/src/application/runtime/applicationRuntime.js +2 -1
  31. package/src/application/siteServer.js +1 -0
  32. package/src/infrastructure/catalog/tagCatalog.js +4 -3
  33. package/src/infrastructure/deploy/centralTelemetry.js +10 -1
  34. package/src/infrastructure/deploy/collectorChartPlan.js +1 -1
  35. package/src/infrastructure/deploy/configuredBundleCapabilities.js +1 -1
  36. package/src/infrastructure/deploy/configuredRuntimeArtifacts.js +98 -25
  37. package/src/infrastructure/deploy/index.js +5 -2
  38. package/src/infrastructure/opcua/projectSources.js +3 -3
package/README.md CHANGED
@@ -42,11 +42,23 @@ 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
+ The optional `artifacts` section selects the bundle deployment targets and a JVM profile when needed. Kubernetes chart templates can declare the runtime in a resource annotation. The following binding runs `collector` through the application manifest and keeps the installed bundle read-only in the container.
46
+
47
+ ```yaml
48
+ metadata:
49
+ annotations:
50
+ scada.io/runtime: '{"reader":{"service":"collector"}}'
51
+ ```
52
+
53
+ The map keys identify containers. Use `service` or `job` for a named declaration, or `jvm: true` for a JVM profile. An optional `args` array supplies application arguments. Unannotated manifests can still use conventional `node bin/<name>.js` commands or explicit compatibility aliases.
54
+
45
55
  ## Collection deployment DSL
46
56
 
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.
57
+ 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. A source address can be a `$secret` reference that the executing adapter resolves. Push sources declare their API and event type through a stream.
58
+
59
+ `delivery` can group streams and processing outputs with the same destination under a `streams` list and a `to` target. It derives senders from reader or workload placement. A `$ref: localState` target uses the machine's home from `controlPlane.localState.placements`. Archive destinations may receive data without participating in reads.
48
60
 
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`.
61
+ `readDeploymentDocument` loads `controlPlane.fragments` and machine type processing profiles relative to the root document. It rejects duplicate control-plane keys across fragments. `resolveCollection` resolves inputs and delivery references. `compileNamedControlCatalog` combines placement with application adapter specifications. `bindControlInstallation` joins topology with installation settings and agent options from server profiles. The default node scheduling capacity is 100.
50
62
 
51
63
  ## Package boundary
52
64
 
@@ -13,6 +13,9 @@ apiVersion: apps/v1
13
13
  kind: Deployment
14
14
  metadata:
15
15
  name: {{ .name }}
16
+ {{- with .runtime }}
17
+ {{- include "scada.workloads.runtimeBinding" (dict "container" "collector" "binding" .) | nindent 2 }}
18
+ {{- end }}
16
19
  labels:
17
20
  {{- .labels | nindent 4 }}
18
21
  spec:
@@ -3,6 +3,9 @@ apiVersion: apps/v1
3
3
  kind: Deployment
4
4
  metadata:
5
5
  name: {{ .name }}
6
+ {{- with .runtime }}
7
+ {{- include "scada.workloads.runtimeBinding" (dict "container" "collector" "binding" .) | nindent 2 }}
8
+ {{- end }}
6
9
  spec:
7
10
  replicas: 1
8
11
  strategy: {type: Recreate}
@@ -19,7 +22,7 @@ spec:
19
22
  containers:
20
23
  - name: collector
21
24
  image: {{ required "agent image required" .values.agent.image | quote }}
22
- command: {{ .command | toJson }}
25
+ command: {{ include "scada.workloads.runtimeCommand" . }}
23
26
  env:
24
27
  {{- range $key, $value := .values.agent.env }}
25
28
  - name: {{ $key }}
@@ -4,6 +4,9 @@ apiVersion: apps/v1
4
4
  kind: Deployment
5
5
  metadata:
6
6
  name: {{ .name }}
7
+ {{- with .runtime }}
8
+ {{- include "scada.workloads.runtimeBinding" (dict "container" "controller" "binding" .) | nindent 2 }}
9
+ {{- end }}
7
10
  spec:
8
11
  replicas: 1
9
12
  strategy: {type: Recreate}
@@ -3,6 +3,9 @@ apiVersion: batch/v1
3
3
  kind: CronJob
4
4
  metadata:
5
5
  name: {{ .name }}
6
+ {{- with .runtime }}
7
+ {{- include "scada.workloads.runtimeBinding" (dict "container" "history-retention" "binding" .) | nindent 2 }}
8
+ {{- end }}
6
9
  spec:
7
10
  schedule: {{ .schedule | quote }}
8
11
  concurrencyPolicy: Forbid
@@ -14,6 +14,9 @@ apiVersion: apps/v1
14
14
  kind: Deployment
15
15
  metadata:
16
16
  name: {{ .name }}
17
+ {{- with .runtime }}
18
+ {{- include "scada.workloads.runtimeBinding" (dict "container" "history-api" "binding" .) | nindent 2 }}
19
+ {{- end }}
17
20
  spec:
18
21
  replicas: 1
19
22
  strategy: {type: Recreate}
@@ -30,7 +33,7 @@ spec:
30
33
  containers:
31
34
  - name: history-api
32
35
  image: {{ required "receiverImage required for local history API" .values.receiverImage | quote }}
33
- command: {{ .command | toJson }}
36
+ command: {{ include "scada.workloads.runtimeCommand" . }}
34
37
  env:
35
38
  - name: POSTGRES_URL
36
39
  valueFrom:
@@ -22,6 +22,9 @@ apiVersion: apps/v1
22
22
  kind: Deployment
23
23
  metadata:
24
24
  name: {{ .name }}
25
+ {{- with .runtime }}
26
+ {{- include "scada.workloads.runtimeBinding" (dict "container" "supervisor" "binding" .) | nindent 2 }}
27
+ {{- end }}
25
28
  spec:
26
29
  replicas: 1
27
30
  strategy:
@@ -0,0 +1,13 @@
1
+ {{- define "scada.workloads.runtimeBinding" -}}
2
+ annotations:
3
+ scada.io/runtime: {{ dict .container .binding | toJson | quote }}
4
+ {{- end -}}
5
+
6
+ {{- define "scada.workloads.runtimeCommand" -}}
7
+ {{- if .command -}}
8
+ {{- .command | toJson -}}
9
+ {{- else -}}
10
+ {{- $runtime := .runtime | default dict -}}
11
+ {{- list "node" (printf "bin/%s.js" (required "runtime service or command required" $runtime.service)) | toJson -}}
12
+ {{- end -}}
13
+ {{- end -}}
@@ -3,6 +3,9 @@ apiVersion: apps/v1
3
3
  kind: Deployment
4
4
  metadata:
5
5
  name: {{ .name }}
6
+ {{- with .runtime }}
7
+ {{- include "scada.workloads.runtimeBinding" (dict "container" "site-server" "binding" .) | nindent 2 }}
8
+ {{- end }}
6
9
  labels:
7
10
  {{- toYaml .labels | nindent 4 }}
8
11
  spec:
@@ -21,7 +24,7 @@ spec:
21
24
  containers:
22
25
  - name: site-server
23
26
  image: {{ .site.image | quote }}
24
- command: {{ .command | toJson }}
27
+ command: {{ include "scada.workloads.runtimeCommand" . }}
25
28
  ports:
26
29
  - {name: http, containerPort: 3000}
27
30
  - {name: state-http, containerPort: 8081}
@@ -14,6 +14,9 @@ apiVersion: apps/v1
14
14
  kind: Deployment
15
15
  metadata:
16
16
  name: {{ .release.Name }}
17
+ {{- with .runtime }}
18
+ {{- include "scada.workloads.runtimeBinding" (dict "container" "supervisor" "binding" .) | nindent 2 }}
19
+ {{- end }}
17
20
  namespace: {{ .release.Namespace }}
18
21
  labels:
19
22
  app: {{ .values.app | default .release.Name }}
@@ -93,6 +93,9 @@ apiVersion: apps/v1
93
93
  kind: Deployment
94
94
  metadata:
95
95
  name: {{ .ingesterName }}
96
+ {{- with .runtime }}
97
+ {{- include "scada.workloads.runtimeBinding" (dict "container" "telemetry" "binding" .) | nindent 2 }}
98
+ {{- end }}
96
99
  spec:
97
100
  replicas: 1
98
101
  strategy: {type: Recreate}
@@ -109,7 +112,7 @@ spec:
109
112
  containers:
110
113
  - name: telemetry
111
114
  image: {{ $telemetry.image | quote }}
112
- command: {{ .command | toJson }}
115
+ command: {{ include "scada.workloads.runtimeCommand" . }}
113
116
  env:
114
117
  {{- with .extraEnv }}
115
118
  {{- . | nindent 12 }}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.28.0",
3
+ "version": "2.30.0",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,50 @@
1
+ import { localOwner } from './collectionPlacement.js';
2
+
3
+ function eventRoute({ id, type, node, machine, api, path }, route, owners) {
4
+ const home = route.localState && localOwner(owners, machine);
5
+ const to = home && !route.to.includes(home) ? [...route.to, home] : route.to;
6
+ const viaApi = route.viaApi ?? api;
7
+ return { id, type, node, machine, ...(path !== undefined && { path }), to, ...(viaApi && { viaApi }) };
8
+ }
9
+
10
+ function pushRoutes(stream, route, machines, owners, servers) {
11
+ const { api } = stream.source;
12
+ const assigned = stream.path ? [stream.path] : [...machines.keys()];
13
+ return assigned.flatMap((machine) => {
14
+ const node = localOwner(owners, machine) ?? machines.get(machine);
15
+ if (!node || (api && !servers.get(node)?.api?.some(({ id }) => { return id === api; }))) { return []; }
16
+ return [eventRoute({ id: stream.output ?? stream.id, type: stream.type, node, machine, api }, route, owners)];
17
+ });
18
+ }
19
+
20
+ export function readerEvents(readers, deliverable, delivery, owners) {
21
+ return readers.filter(({ output }) => { return output !== undefined; }).flatMap((reader) => {
22
+ const { output, eligible, streams } = reader;
23
+ const type = deliverable.get(output)?.type;
24
+ if (!type) { throw new TypeError(`Unknown event output ${output} for reader ${reader.id}`); }
25
+ if (!Object.hasOwn(delivery, output)) { return []; }
26
+ return streams.flatMap(({ path }) => {
27
+ return eligible.map((node) => { return eventRoute({ id: output, type, node, machine: path }, delivery[output], owners); });
28
+ });
29
+ });
30
+ }
31
+
32
+ export function eventRoutes({ document, streams, outputs, delivery, owners, workloads }) {
33
+ const machines = new Map(Object.entries(owners));
34
+ for (const { assignments } of Object.values(workloads)) {
35
+ for (const { machines: selected, nodes: [primary], scope } of assignments) {
36
+ const paths = scope ? [scope] : selected.map(({ path }) => { return path; });
37
+ paths.forEach((path) => { if (!machines.has(path)) { machines.set(path, primary); } });
38
+ }
39
+ }
40
+ const servers = new Map(document.servers?.map((server) => { return [server.id, server]; }));
41
+ const processing = Object.entries(outputs).filter(([id]) => { return Object.hasOwn(delivery, id); }).flatMap(([id, { type, path, producers }]) => {
42
+ return producers.flatMap(({ machine, nodes }) => {
43
+ return nodes.map((node) => { return eventRoute({ id, type, node, machine, path }, delivery[id], owners); });
44
+ });
45
+ });
46
+ const pushed = [...streams.values()].filter(({ source, output, id }) => {
47
+ return source.mode === 'push' && Object.hasOwn(delivery, output ?? id);
48
+ }).flatMap((stream) => { return pushRoutes(stream, delivery[stream.output ?? stream.id], machines, owners, servers); });
49
+ return [...processing, ...pushed];
50
+ }
@@ -0,0 +1,42 @@
1
+ import { treePaths } from './expandNamespace.js';
2
+
3
+ function machinePath(paths, machine) {
4
+ const matches = paths.filter((path) => { return path === machine || path.split('/').at(-1) === machine; });
5
+ if (matches.length !== 1) { throw new TypeError(`Invalid local state machine ${machine}`); }
6
+ return matches[0];
7
+ }
8
+
9
+ function placementEntries(placements) {
10
+ if (!placements || typeof placements !== 'object' || Array.isArray(placements)) {
11
+ throw new TypeError('Local state placements must be a map');
12
+ }
13
+ return Object.entries(placements);
14
+ }
15
+
16
+ export function placementMap(document, servers) {
17
+ const placements = document.controlPlane?.localState?.placements;
18
+ if (placements === undefined) { return document.objectOwners ?? {}; }
19
+ const paths = treePaths(document.namespace);
20
+ const owners = new Map(Object.entries(document.objectOwners ?? {}));
21
+ for (const [node, machines] of placementEntries(placements)) {
22
+ if (!servers.has(node) || !Array.isArray(machines) || machines.length === 0) {
23
+ throw new TypeError(`Invalid local state placement on ${node}`);
24
+ }
25
+ for (const machine of machines) {
26
+ const path = machinePath(paths, machine);
27
+ if (owners.has(path)) { throw new TypeError(`Duplicate local state machine ${machine}`); }
28
+ owners.set(path, node);
29
+ }
30
+ }
31
+ return Object.fromEntries(owners);
32
+ }
33
+
34
+ export function localOwner(owners, path) {
35
+ if (path === undefined) { return undefined; }
36
+ return Object.entries(owners).filter(([prefix]) => { return path === prefix || path.startsWith(`${prefix}/`); })
37
+ .sort(([left], [right]) => { return right.length - left.length; })[0]?.[1];
38
+ }
39
+
40
+ export function localStateReference(value) {
41
+ return value?.$ref === 'localState' && Object.keys(value).length === 1;
42
+ }
@@ -1,5 +1,47 @@
1
1
  import { collectorConsumerTasks } from './collectorSourcePlan.js';
2
2
  import deploymentTemplate from '../../infrastructure/deploy/deploymentTemplate.js';
3
+ import { resolveCollection } from './namedCollection.js';
4
+
5
+ const batchOptions = { size: 50, interval: 2, threshold: 5, timeout: 60 };
6
+ const postgres = { $secret: 'POSTGRES_URL' };
7
+ const amqp = { $secret: 'AMQP_URL' };
8
+ const stompEventTypes = ['segments', 'alerts', 'user_decisions'];
9
+
10
+ function incomingEventTypes(node, delivery, events) {
11
+ const legacy = ['operations', ...stompEventTypes].filter((id) => {
12
+ return delivery[id]?.localState || delivery[id]?.to.includes(node);
13
+ });
14
+ return new Set([...legacy, ...events.filter(({ to }) => { return to.includes(node); }).map(({ type }) => { return type; })]);
15
+ }
16
+
17
+ function localReceivers({ eventTypes, topics, devices, clientId, localState, preferences }) {
18
+ const { operations, telemetry, stomp } = preferences;
19
+ return [
20
+ topics.length && { id: 'mqtt', spec: { adapter: 'mqtt-pg-metrics', mqtt: { $secret: 'MQTT_URL' },
21
+ postgres, devices, topic: topics.join(','), firstWins: true, options: { ...batchOptions, clientId } } },
22
+ eventTypes.has('operations') && operations?.enabled !== false && { id: 'operations', spec: { adapter: 'operation-sync', amqp,
23
+ postgres, queue: operations?.queue ?? 'scada.operations.from-sensors', options: batchOptions } },
24
+ stompEventTypes.some((type) => { return eventTypes.has(type); }) && { id: 'stomp', spec: { adapter: 'stomp-ingest',
25
+ stomp: { $secret: 'STOMP_URL' }, postgres, config: { ...batchOptions, ...localState,
26
+ prefetch: 128, repairHistoryOnStart: false, deadLetter: false, ...stomp } } },
27
+ topics.length && telemetry?.enabled !== false && { id: 'amqp-metrics', spec: { adapter: 'amqp-pg-metrics', amqp,
28
+ postgres, devices, queue: telemetry?.queue ?? 'scada.telemetry.ingest', firstWins: true, options: batchOptions } }
29
+ ].filter(Boolean);
30
+ }
31
+
32
+ /** Build the ingress assignments for state owned by one node using collection and delivery. */
33
+ export function namedLocalConsumers(document, node, { generation = 1, wire, preferences = {} }) {
34
+ const { objectOwners, delivery, events, readers } = resolveCollection(document);
35
+ const paths = Object.keys(objectOwners).filter((path) => { return objectOwners[path] === node; });
36
+ if (!paths.length || wire === undefined) { return []; }
37
+ const targets = readers.flatMap(({ streams }) => { return streams; }).filter(({ id, path }) => {
38
+ return delivery[id]?.to.includes(node) && paths.some((home) => { return path === home || path.startsWith(`${home}/`); });
39
+ });
40
+ const configuration = wire(paths, targets);
41
+ const eventTypes = incomingEventTypes(node, delivery, events);
42
+ return collectorConsumerTasks(localReceivers({ ...configuration, eventTypes, preferences,
43
+ localState: document.controlPlane.history?.sink?.segmentPolicy }), node, {}, generation);
44
+ }
3
45
 
4
46
  function ownedPath(document, prefix, cluster) {
5
47
  const paths = Object.entries(document.objectOwners ?? {}).filter(([path, owner]) => {
@@ -45,6 +45,7 @@ export default function expand(document) {
45
45
  const servers = expandServers(input.servers || [], paths, input.mappings || {});
46
46
  return frozen({
47
47
  ...(input.hmi !== undefined && { hmi: input.hmi }),
48
+ ...(input.eventDelivery !== undefined && { eventDelivery: input.eventDelivery }),
48
49
  mappings: input.mappings || {},
49
50
  namespace,
50
51
  profiles,
@@ -0,0 +1,61 @@
1
+ function validateCache(cache, node) {
2
+ if (!cache || typeof cache !== 'object' || Array.isArray(cache)) {
3
+ throw new TypeError(`History cache must map groups to streams on ${node}`);
4
+ }
5
+ for (const [group, streams] of Object.entries(cache)) {
6
+ if (!Array.isArray(streams) || !streams.length || new Set(streams).size !== streams.length
7
+ || streams.some((id) => { return typeof id !== 'string' || !id; })) {
8
+ throw new TypeError(`Invalid cache streams for ${group} on ${node}`);
9
+ }
10
+ }
11
+ }
12
+
13
+ function storageRules(document) {
14
+ const servers = new Set(document.servers.map(({ id }) => { return id; }));
15
+ return Object.entries(document.history).map(([node, { state, cache = {}, restore, retentionDays }]) => {
16
+ if (!servers.has(node)) { throw new TypeError(`Unknown history node ${node}`); }
17
+ if (retentionDays !== undefined && (!Number.isSafeInteger(retentionDays) || retentionDays < 1)) {
18
+ throw new TypeError(`History retentionDays must be a positive integer for ${node}`);
19
+ }
20
+ validateCache(cache, node);
21
+ return { node, state: state === undefined ? [] : [state].flat(), cache, restore };
22
+ });
23
+ }
24
+
25
+ function historyReplicas(rules, placements) {
26
+ const entries = rules.flatMap(({ node, cache, restore }) => {
27
+ return Object.keys(cache)
28
+ .map((group) => { return [group, { ...restore?.[group], standby: node }]; });
29
+ });
30
+ const cached = new Map(entries);
31
+ if (cached.size !== entries.length) { throw new TypeError('A history group can have only one standby'); }
32
+ const groups = new Set([...Object.values(placements).flat(), ...cached.keys()]);
33
+ return Object.fromEntries([...groups].filter((group) => { return cached.has(group); })
34
+ .map((group) => { return [group, cached.get(group)]; }));
35
+ }
36
+
37
+ /** Adapt the node storage rules to state owners and standby replicas. */
38
+ export function resolveHistoryPlacement(document) {
39
+ if (!document?.history) { return document; }
40
+ const rules = storageRules(document);
41
+ const placements = Object.fromEntries(rules.filter(({ state }) => { return state.length; })
42
+ .map(({ node, state }) => { return [node, state]; }));
43
+ const replicas = historyReplicas(rules, placements);
44
+ const { controlPlane } = document;
45
+ return { ...document, controlPlane: { ...controlPlane,
46
+ ...(Object.keys(placements).length && { localState: { ...controlPlane?.localState, placements } }),
47
+ ...(Object.keys(replicas).length && { history: { ...controlPlane?.history, replicas } }) } };
48
+ }
49
+
50
+ export function archiveNode(document, fallback) {
51
+ if (!document.history && fallback) { return fallback; }
52
+ const archives = document.history
53
+ ? Object.keys(document.history).filter((id) => { return document.history[id].archive === 'delivered'; })
54
+ : document.servers.filter(({ profile }) => { return profile?.id === 'archive'; }).map(({ id }) => { return id; });
55
+ if (archives.length !== 1) { throw new TypeError('Control plane requires exactly one archive server'); }
56
+ return archives[0];
57
+ }
58
+
59
+ export function retentionFor(document, node) {
60
+ return document.history?.[node]?.retentionDays;
61
+ }
@@ -68,6 +68,13 @@ function mergeNodes(left, right) {
68
68
  return Array.from(value.values());
69
69
  }
70
70
 
71
+ function mergeDelivery(left, right) {
72
+ if (!Array.isArray(left) && !Array.isArray(right)) { return mergeMaps(left, right); }
73
+ const groups = [left, right].filter((value) => { return value !== undefined; });
74
+ if (!groups.every(Array.isArray)) { throw new TypeError('Cannot mix delivery lists and maps'); }
75
+ return groups.flat();
76
+ }
77
+
71
78
  /**
72
79
  * Overlays one system document on another.
73
80
  *
@@ -88,9 +95,10 @@ export default function mergeDocuments(base, extra) {
88
95
  if (base.mappings || extra.mappings) {
89
96
  document.mappings = mergeMaps(base.mappings, extra.mappings);
90
97
  }
91
- for (const key of ['sources', 'streams', 'delivery', 'objectOwners', 'externalPublications', 'routes']) {
98
+ for (const key of ['sources', 'streams', 'objectOwners', 'externalPublications', 'routes', 'machineTypes']) {
92
99
  if (base[key] || extra[key]) { document[key] = mergeMaps(base[key], extra[key]); }
93
100
  }
101
+ if (base.delivery || extra.delivery) { document.delivery = mergeDelivery(base.delivery, extra.delivery); }
94
102
  if (base.profiles || extra.profiles) {
95
103
  document.profiles = mergeMaps(base.profiles, extra.profiles);
96
104
  }
@@ -1,4 +1,7 @@
1
1
  import { sourceAddress } from './deploymentRouting.js';
2
+ import { processingOutputs, resolveWorkloads } from './namedProcessing.js';
3
+ import { eventRoutes, readerEvents } from './collectionEvents.js';
4
+ import { localOwner, localStateReference, placementMap } from './collectionPlacement.js';
2
5
 
3
6
  function asMap(value, label) {
4
7
  if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new TypeError(`${label} must be a map`); }
@@ -14,9 +17,10 @@ function ids(value, label, known) {
14
17
  return list;
15
18
  }
16
19
 
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
+ function pullStream(id, declaration, sources, mappings) {
21
+ const { source, path, query, mapping } = declaration;
22
+ const input = sources[source];
23
+ const { address } = input;
20
24
  if (typeof path !== 'string' || path.split('/').some((part) => { return !part; })) {
21
25
  throw new TypeError(`Invalid path for stream ${id}`);
22
26
  }
@@ -24,24 +28,47 @@ function resolveStream(id, declaration, sources, mappings) {
24
28
  throw new TypeError(`Unknown mapping ${mapping} for stream ${id}`);
25
29
  }
26
30
  const resolvedMapping = typeof mapping === 'string' ? mappings[mapping] : mapping;
27
- return { ...declaration, id, source: sources[source], address: sources[source].address, from, path, name: path, resolvedMapping };
31
+ const secret = address && typeof address === 'object' && Object.keys(address).length === 1
32
+ && typeof address.$secret === 'string' && address.$secret;
33
+ if (secret && query !== undefined) { throw new TypeError(`Source ${source} cannot add query parameters to a secret address`); }
34
+ return { ...declaration, id, source: input, address, from: secret ? address : sourceAddress(sources, source, query), path, name: path, resolvedMapping };
35
+ }
36
+
37
+ function resolveStream(id, declaration, sources, mappings) {
38
+ const { source, type, query } = asMap(declaration, `Stream ${id}`);
39
+ if (typeof source !== 'string' || !Object.hasOwn(sources ?? {}, source)) { throw new TypeError(`Unknown source ${source}`); }
40
+ const input = asMap(sources[source], `Source ${source}`);
41
+ if (input.mode !== 'push') { return pullStream(id, declaration, sources, mappings); }
42
+ if (typeof type !== 'string' || !type || query !== undefined) { throw new TypeError(`Invalid push stream ${id}`); }
43
+ return { ...declaration, id, source: input };
28
44
  }
29
45
 
30
- function resolveReaders(declarations, streams, controlNodes) {
46
+ function readerNodes(id, eligible, reading, controlNodes, owners) {
47
+ const list = Array.isArray(eligible) ? eligible : [eligible];
48
+ return ids(list.map((node) => {
49
+ if (!localStateReference(node)) { return node; }
50
+ const homes = new Set(reading.map(({ path }) => { return localOwner(owners, path); }));
51
+ if (homes.size !== 1 || homes.has(undefined)) { throw new TypeError(`Reader ${id} requires one local state placement`); }
52
+ return [...homes][0];
53
+ }), `eligible nodes for reader ${id}`, controlNodes);
54
+ }
55
+
56
+ function resolveReaders(declarations, streams, controlNodes, owners) {
31
57
  const readers = [];
32
58
  const assigned = new Set();
33
59
  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
- }
60
+ const { streams: included = [id], eligible, copies = 1, cost = 1, adapter, output } = asMap(declaration, `Reader ${id}`);
39
61
  const reading = ids(included, `streams for reader ${id}`, streams).map((stream) => {
40
62
  if (assigned.has(stream)) { throw new TypeError(`Stream ${stream} has more than one reader`); }
41
63
  assigned.add(stream);
42
64
  return streams.get(stream);
43
65
  });
44
- readers.push({ id, eligible: nodes, copies, cost, streams: reading });
66
+ const nodes = readerNodes(id, eligible, reading, controlNodes, owners);
67
+ if (!Number.isSafeInteger(copies) || copies < 1 || copies > nodes.length || !Number.isSafeInteger(cost) || cost < 1) {
68
+ throw new TypeError(`Invalid copies or cost for reader ${id}`);
69
+ }
70
+ readers.push({ id, eligible: nodes, copies, cost, streams: reading,
71
+ ...(adapter !== undefined && { adapter }), ...(output !== undefined && { output }) });
45
72
  }
46
73
  for (const id of streams.keys()) {
47
74
  if (!assigned.has(id)) { throw new TypeError(`Stream ${id} has no reader`); }
@@ -49,20 +76,91 @@ function resolveReaders(declarations, streams, controlNodes) {
49
76
  return readers;
50
77
  }
51
78
 
79
+ function routeEntries(delivery, known) {
80
+ if (!Array.isArray(delivery)) { return Object.entries(asMap(delivery, 'Delivery')); }
81
+ return delivery.flatMap((route) => {
82
+ return ids(asMap(route, 'Delivery group').streams, 'streams in delivery group', known).map((stream) => {
83
+ return [stream, route];
84
+ });
85
+ });
86
+ }
87
+
88
+ function deliveryObjectPath({ path, producers }) {
89
+ if (path === undefined || producers?.length > 1) { return undefined; }
90
+ return producers?.[0]?.machine ?? path;
91
+ }
92
+
93
+ function localDelivery(targets, stream, owners) {
94
+ if (!targets.some(localStateReference)) { return { dynamic: false }; }
95
+ const path = deliveryObjectPath(stream);
96
+ return { dynamic: path === undefined, home: localOwner(owners, path) };
97
+ }
98
+
99
+ function routeDestinations(id, route, stream, servers, owners) {
100
+ const { to, viaApi } = asMap(route, `Delivery ${id}`);
101
+ if (Object.hasOwn(route, 'from')) { throw new TypeError(`Delivery ${id} cannot declare from`); }
102
+ if (viaApi !== undefined && (typeof viaApi !== 'string' || !viaApi)) { throw new TypeError(`Invalid delivery API for ${id}`); }
103
+ const targets = Array.isArray(to) ? to : [to];
104
+ const { dynamic, home } = localDelivery(targets, stream, owners);
105
+ const resolved = targets.filter((target) => { return !localStateReference(target); });
106
+ if (home !== undefined && !resolved.includes(home)) { resolved.push(home); }
107
+ if (!dynamic || resolved.length > 0) { ids(resolved, `destinations for stream ${id}`, servers); }
108
+ return { to: resolved, viaApi, ...(dynamic && { localState: true }) };
109
+ }
110
+
111
+ function routes(delivery, streams, servers, owners) {
112
+ const destinations = new Map();
113
+ for (const [id, route] of routeEntries(delivery, streams)) {
114
+ const stream = streams.get(id);
115
+ if (!stream) { throw new TypeError(`Unknown delivery stream ${id}`); }
116
+ if (destinations.has(id)) { throw new TypeError(`Stream ${id} has more than one delivery declaration`); }
117
+ destinations.set(id, routeDestinations(id, route, stream, servers, owners));
118
+ }
119
+ return Object.fromEntries(destinations);
120
+ }
121
+
122
+ function outputStreams(streams, outputs) {
123
+ const deliverable = new Map(streams);
124
+ for (const [id, output] of Object.entries(outputs)) {
125
+ if (deliverable.has(id)) { throw new TypeError(`Processing output conflicts with stream ${id}`); }
126
+ deliverable.set(id, output);
127
+ }
128
+ const aliases = [...streams.values()].filter(({ output }) => { return output !== undefined; });
129
+ for (const stream of aliases) {
130
+ const prior = deliverable.get(stream.output);
131
+ if (typeof stream.output !== 'string' || !stream.output || (prior && prior.type !== stream.type)) {
132
+ throw new TypeError(`Invalid output alias for stream ${stream.id}`);
133
+ }
134
+ if (!prior) { deliverable.set(stream.output, { type: stream.type }); }
135
+ }
136
+ return deliverable;
137
+ }
138
+
139
+ function knownControlNodes(nodes, serverIds) {
140
+ const members = new Set(nodes.map(({ id }) => { return id; }));
141
+ if (members.size !== nodes.length) { throw new TypeError('Invalid control membership'); }
142
+ if ([...members].some((id) => { return !serverIds.has(id); })) { throw new TypeError('Unknown control node'); }
143
+ return members;
144
+ }
145
+
52
146
  /** Resolve named collection inputs without assigning readers to machines. */
53
147
  export function resolveCollection(document) {
54
- const { controlPlane, sources, streams, mappings = {}, servers = [], delivery = {}, objectOwners = {}, externalPublications = {} } = document;
148
+ const { controlPlane, sources, streams, mappings = {}, servers = [], delivery = {}, externalPublications = {} } = document;
55
149
  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'); }
150
+ const controlNodes = knownControlNodes(controlPlane?.nodes ?? [], serverIds);
58
151
  const resolved = new Map(Object.entries(asMap(streams, 'Streams')).map(([id, stream]) => {
59
152
  return [id, resolveStream(id, stream, sources, mappings)];
60
153
  }));
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 };
154
+ const physical = new Map([...resolved].filter(([, stream]) => { return stream.source.mode !== 'push'; }));
155
+ const objectOwners = placementMap(document, serverIds);
156
+ const workloads = resolveWorkloads(document);
157
+ const outputs = processingOutputs(document, workloads);
158
+ const deliverable = outputStreams(resolved, outputs);
159
+ const destinations = routes(delivery, deliverable, serverIds, objectOwners);
160
+ const readers = resolveReaders(controlPlane?.readers, physical, controlNodes, objectOwners);
161
+ return {
162
+ readers, delivery: destinations, objectOwners, externalPublications, outputs,
163
+ events: [...eventRoutes({ document, streams: resolved, outputs, delivery: destinations, owners: objectOwners, workloads }),
164
+ ...readerEvents(readers, deliverable, destinations, objectOwners)]
165
+ };
68
166
  }