@yarkivaev/scada 2.3.114 → 2.3.116

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 (42) hide show
  1. package/README.md +109 -0
  2. package/charts/scada/Chart.yaml +2 -2
  3. package/charts/scada/templates/_helpers.tpl +12 -4
  4. package/charts/scada/templates/clickhouse.yaml +3 -3
  5. package/charts/scada/templates/collector.yaml +2 -2
  6. package/charts/scada/templates/namespace.yaml +6 -0
  7. package/charts/scada/templates/postgres.yaml +3 -3
  8. package/charts/scada/templates/processes.yaml +88 -0
  9. package/charts/scada/templates/rabbitmq-config.yaml +91 -0
  10. package/charts/scada/templates/rabbitmq.yaml +54 -113
  11. package/charts/scada/templates/site-server.yaml +5 -3
  12. package/charts/scada/templates/supervisor-sink.yaml +4 -2
  13. package/charts/scada/values.schema.json +22 -0
  14. package/charts/scada/values.yaml +21 -0
  15. package/index.js +3 -0
  16. package/package.json +8 -3
  17. package/src/application/deploy/collectorProcesses.js +43 -0
  18. package/src/application/deploy/expandFlows.js +21 -10
  19. package/src/application/deploy/publishedStreams.js +30 -0
  20. package/src/application/deploy/releaseEdges.js +13 -16
  21. package/src/application/deploy/releaseNodes.js +13 -0
  22. package/src/application/deploy/releaseValues.js +4 -15
  23. package/src/application/deploy/releases.js +3 -1
  24. package/src/application/deploy/subscriptions.js +20 -0
  25. package/src/infrastructure/deploy/executeRelease.js +102 -0
  26. package/src/infrastructure/ingest/durableConsume.js +2 -169
  27. package/src/infrastructure/ingest/modbus/silentStreams.js +9 -11
  28. package/src/infrastructure/ingest/silentOpenWatch.js +5 -42
  29. package/src/infrastructure/ingest/telemetry/amqpMetricsIngest.js +7 -18
  30. package/src/infrastructure/ingest/telemetry/amqpMqttRelay.js +8 -17
  31. package/src/infrastructure/messaging/rabbitmq/definitions.js +24 -0
  32. package/src/infrastructure/messaging/rabbitmq/reconcile.js +104 -0
  33. package/src/infrastructure/opcua/config.js +38 -0
  34. package/src/infrastructure/opcua/endpoint.js +80 -0
  35. package/src/infrastructure/opcua/index.js +10 -0
  36. package/src/infrastructure/opcua/session.js +60 -0
  37. package/src/infrastructure/opcua/source.js +35 -0
  38. package/src/infrastructure/opcua/subscriptionHealth.js +28 -0
  39. package/src/infrastructure/operators/operatorsSync.js +5 -29
  40. package/src/infrastructure/persistence/clickhouse/streamHub.js +21 -15
  41. package/src/infrastructure/persistence/metricsSensor.js +9 -6
  42. package/src/infrastructure/sync/operationSyncIngest.js +4 -16
@@ -1,7 +1,8 @@
1
+ {{- if .Values.site.enabled }}
1
2
  apiVersion: apps/v1
2
3
  kind: Deployment
3
4
  metadata:
4
- name: {{ .Release.Name }}-site-server
5
+ name: {{ include "scada.prefix" . }}-site-server
5
6
  namespace: {{ .Release.Namespace }}
6
7
  labels:
7
8
  {{- include "scada.labels" . | nindent 4 }}
@@ -70,7 +71,7 @@ spec:
70
71
  apiVersion: v1
71
72
  kind: Service
72
73
  metadata:
73
- name: {{ .Release.Name }}-site-server
74
+ name: {{ include "scada.prefix" . }}-site-server
74
75
  namespace: {{ .Release.Namespace }}
75
76
  labels:
76
77
  {{- include "scada.labels" . | nindent 4 }}
@@ -90,7 +91,7 @@ spec:
90
91
  apiVersion: v1
91
92
  kind: Service
92
93
  metadata:
93
- name: {{ .Release.Name }}-site-server-plant-lan
94
+ name: {{ include "scada.prefix" . }}-site-server-plant-lan
94
95
  namespace: {{ .Release.Namespace }}
95
96
  labels:
96
97
  {{- include "scada.labels" . | nindent 4 }}
@@ -105,3 +106,4 @@ spec:
105
106
  selector:
106
107
  {{- include "scada.match" (dict "app" "site-server" "ctx" .) | nindent 4 }}
107
108
  {{- end }}
109
+ {{- end }}
@@ -1,7 +1,8 @@
1
+ {{- if .Values.sink.enabled }}
1
2
  apiVersion: apps/v1
2
3
  kind: Deployment
3
4
  metadata:
4
- name: {{ .Release.Name }}-supervisor-sink
5
+ name: {{ include "scada.prefix" . }}-supervisor-sink
5
6
  namespace: {{ .Release.Namespace }}
6
7
  labels:
7
8
  {{- include "scada.labels" . | nindent 4 }}
@@ -52,7 +53,7 @@ spec:
52
53
  apiVersion: v1
53
54
  kind: Service
54
55
  metadata:
55
- name: {{ .Release.Name }}-supervisor-sink
56
+ name: {{ include "scada.prefix" . }}-supervisor-sink
56
57
  namespace: {{ .Release.Namespace }}
57
58
  labels:
58
59
  {{- include "scada.labels" . | nindent 4 }}
@@ -64,3 +65,4 @@ spec:
64
65
  targetPort: state
65
66
  selector:
66
67
  {{- include "scada.match" (dict "app" "supervisor-sink" "ctx" .) | nindent 4 }}
68
+ {{- end }}
@@ -0,0 +1,22 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "type": "object",
4
+ "properties": {
5
+ "processes": {
6
+ "type": "array",
7
+ "items": {
8
+ "type": "object",
9
+ "required": ["name", "command"],
10
+ "properties": {
11
+ "name": { "type": "string", "pattern": "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" },
12
+ "command": { "type": "array", "minItems": 1, "items": { "type": "string" } },
13
+ "env": { "type": "object", "additionalProperties": { "type": ["string", "number", "boolean"] } },
14
+ "hostDevices": {
15
+ "type": "array", "uniqueItems": true,
16
+ "items": { "type": "string", "pattern": "^/dev/([a-zA-Z0-9_-][a-zA-Z0-9_.-]*/)*[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$" }
17
+ }
18
+ }
19
+ }
20
+ }
21
+ }
22
+ }
@@ -1,4 +1,15 @@
1
1
  role: edge
2
+ # Override the resource name prefix when adopting an existing installation.
3
+ prefix: ""
4
+ createNamespace: false
5
+ site:
6
+ enabled: true
7
+ sink:
8
+ enabled: true
9
+ # Labels for workloads that must stay outside immutable selectors.
10
+ workloadLabels: {}
11
+ # Named deployments with command, env, optional resources and hostDevices.
12
+ processes: []
2
13
  image: ""
3
14
  command: []
4
15
  pullSecret: ""
@@ -22,6 +33,16 @@ postgres:
22
33
  rabbitmq:
23
34
  enabled: true
24
35
  deadLetter: null
36
+ # A named standalone PVC replaces the default volumeClaimTemplates when set.
37
+ claimName: ""
38
+ configName: ""
39
+ rolloutOnConfigChange: false
40
+ definitions: null
41
+ plugins: [rabbitmq_stomp, rabbitmq_mqtt, rabbitmq_management]
42
+ extraConfig: {}
43
+ resources: {}
44
+ readinessProbe: {}
45
+ livenessProbe: {}
25
46
  image: rabbitmq:3.13-management
26
47
  storage: 5Gi
27
48
  storageClass: ""
package/index.js CHANGED
@@ -96,9 +96,12 @@ export { default as analyticsMcp } from './src/application/mcp/analyticsMcp.js';
96
96
  export { default as expand } from './src/application/deploy/expand.js';
97
97
  export { default as readDocument } from './src/application/deploy/readDocument.js';
98
98
  export { default as mergeDocuments } from './src/application/deploy/mergeDocuments.js';
99
+ export { default as subscriptions } from './src/application/deploy/subscriptions.js';
99
100
  export { default as releases } from './src/application/deploy/releases.js';
100
101
  export { default as paths } from './src/application/deploy/paths.js';
101
102
  export { default as appReleases } from './src/application/deploy/appReleases.js';
102
103
  export { default as withCollectors } from './src/application/deploy/withCollectors.js';
103
104
  export { default as pointPaths } from './src/application/deploy/pointPaths.js';
104
105
  export { clusterOf, serverFor } from './src/application/deploy/releaseNodes.js';
106
+ export { default as executeRelease } from './src/infrastructure/deploy/executeRelease.js';
107
+ export { default as collectorProcesses } from './src/application/deploy/collectorProcesses.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.3.114",
3
+ "version": "2.3.116",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -13,7 +13,11 @@
13
13
  "./client": "./src/infrastructure/client/index.js",
14
14
  "./stateDataFake": "./src/infrastructure/persistence/stateDataFromMemory.js",
15
15
  "./startTestEdgeApi": "./src/infrastructure/http/edge/startTestEdgeApi.js",
16
- "./package.json": "./package.json"
16
+ "./package.json": "./package.json",
17
+ "./rabbitmq/definitions": "./src/infrastructure/messaging/rabbitmq/definitions.js",
18
+ "./rabbitmq/reconcile": "./src/infrastructure/messaging/rabbitmq/reconcile.js",
19
+ "./opcua": "./src/infrastructure/opcua/index.js",
20
+ "./opcua/config": "./src/infrastructure/opcua/config.js"
17
21
  },
18
22
  "bin": {
19
23
  "modbus-to-mqtt": "./src/bin/modbus-to-mqtt.js",
@@ -31,8 +35,9 @@
31
35
  "@clickhouse/client": "^1.0.0",
32
36
  "@modelcontextprotocol/sdk": "^1.24.3",
33
37
  "@yarkivaev/simple-server": "1.0.2",
34
- "@yarkivaev/source-to-sink": "1.3.10",
38
+ "@yarkivaev/source-to-sink": "1.3.11",
35
39
  "amqplib": "^0.10.9",
40
+ "node-opcua": "2.179.0",
36
41
  "pg": "^8.0.0",
37
42
  "stompit": "^1.0.0",
38
43
  "zod": "^4.6.7"
@@ -0,0 +1,43 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+
3
+ /** Group rows in first-seen order, keeping source order within each process. */
4
+ function grouped(machines, describe) {
5
+ const groups = new Map();
6
+ const claimed = new Set();
7
+ for (const row of machines) {
8
+ if (claimed.has(row.name)) { throw new Error(`duplicate source ${row.name}`); }
9
+ claimed.add(row.name);
10
+ const descriptor = describe(row);
11
+ if (typeof descriptor?.name !== 'string' || !descriptor.name.trim()) {
12
+ throw new Error(`unassigned source ${row.name}`);
13
+ }
14
+ const group = groups.get(descriptor.name) || { descriptor, rows: [] };
15
+ if (!isDeepStrictEqual(group.descriptor, descriptor)) {
16
+ throw new Error(`conflicting descriptions for process ${descriptor.name}`);
17
+ }
18
+ group.rows.push(row);
19
+ groups.set(descriptor.name, group);
20
+ }
21
+ return [...groups.values()];
22
+ }
23
+
24
+ /**
25
+ * describe(row) returns a process descriptor with a name, command and optional
26
+ * env, resources and image. All sources describing the same process must agree.
27
+ * project(descriptor, rows) supplies adapter-specific env and optional hostDevices.
28
+ * A physical device may appear in many source rows but belongs to only one process.
29
+ */
30
+ export default function collectorProcesses(machines, describe, project) {
31
+ const devices = new Set();
32
+ return grouped(machines, describe).map(({ descriptor, rows }) => {
33
+ const settings = project(descriptor, rows);
34
+ const hostDevices = [...new Set(settings.hostDevices || [])].sort();
35
+ hostDevices.forEach((device) => {
36
+ if (devices.has(device)) { throw new Error(`serial port or device ${device} is shared between processes`); }
37
+ devices.add(device);
38
+ });
39
+ return { name: descriptor.name, command: descriptor.command, env: { ...descriptor.env, ...settings.env },
40
+ hostDevices, resources: descriptor.resources,
41
+ ...(descriptor.image === undefined ? {} : { image: descriptor.image }) };
42
+ });
43
+ }
@@ -1,4 +1,6 @@
1
1
  import { assertLeaf, deviceFlows, expandObjects } from './expandDevices.js';
2
+ import { availableNames, expandApis, publishedNames } from './publishedStreams.js';
3
+ import { serviceOf } from './releaseNodes.js';
2
4
  import { isAddress, picked } from './expandPattern.js';
3
5
 
4
6
  /**
@@ -32,18 +34,17 @@ function chosen(pattern, pool, strict) {
32
34
  * @example
33
35
  * poolOf({ fanIn: [], fanOut: [] }, 'archive');
34
36
  */
35
- function poolOf(source, receiverId) {
37
+ function poolOf(source, receiverId, api) {
38
+ const available = availableNames(source, api);
36
39
  const aimed = source.fanOut.filter((flow) => {
37
40
  return flow.to === receiverId;
38
41
  }).map((flow) => {
39
42
  return flow.name;
40
43
  });
41
44
  if (aimed.length > 0) {
42
- return aimed;
45
+ return aimed.filter((name) => { return available.includes(name); });
43
46
  }
44
- return source.fanIn.map((flow) => {
45
- return flow.name;
46
- });
47
+ return available;
47
48
  }
48
49
 
49
50
  /**
@@ -60,9 +61,7 @@ function poolOf(source, receiverId) {
60
61
  */
61
62
  function expandOut(server, ids, strict) {
62
63
  const rows = [];
63
- const streams = server.fanIn.map((flow) => {
64
- return flow.name;
65
- });
64
+ const streams = availableNames(server);
66
65
  server.patternsOut.forEach((flow) => {
67
66
  const destinations = picked(flow.to, ids, 'server', true);
68
67
  const names = picked(flow.name, streams, 'path', strict);
@@ -76,6 +75,18 @@ function expandOut(server, ids, strict) {
76
75
  return rows;
77
76
  }
78
77
 
78
+ /* A fixed object path can be held implicitly, but an API-only stream requires its service. */
79
+ function incomingNames(source, receiver, flow, strict) {
80
+ const api = serviceOf(source, flow.api)?.id;
81
+ const pool = poolOf(source, receiver, api);
82
+ const names = chosen(flow.name, pool, strict);
83
+ if (strict && api && publishedNames(source).includes(flow.name)
84
+ && !availableNames(source, api).includes(flow.name)) {
85
+ throw new Error(`system document stream ${flow.name} is unavailable on api ${flow.api}`);
86
+ }
87
+ return names;
88
+ }
89
+
79
90
  /**
80
91
  * Expands fan-in whose source is a server.
81
92
  *
@@ -101,7 +112,7 @@ function expandIn(server, drafts, strict) {
101
112
  const source = drafts.find((item) => {
102
113
  return item.id === sourceId;
103
114
  });
104
- chosen(flow.name, poolOf(source, server.id), strict).forEach((path) => {
115
+ incomingNames(source, server.id, flow, strict).forEach((path) => {
105
116
  assertLeaf(server.objects, path);
106
117
  const copy = { from: sourceId, name: path };
107
118
  if (flow.api) {
@@ -144,7 +155,7 @@ function draftOne(server, paths, mappings) {
144
155
  remote.push(flow);
145
156
  });
146
157
  return {
147
- api: server.api,
158
+ api: expandApis(server.api, paths, objects),
148
159
  fanIn: local,
149
160
  id: server.id,
150
161
  objects,
@@ -0,0 +1,30 @@
1
+ import { assertLeaf } from './expandDevices.js';
2
+ import { picked } from './expandPattern.js';
3
+
4
+ /** Resolve each API's published stream names, preserving its opaque contract metadata. */
5
+ export function expandApis(apis, paths, objects) {
6
+ return apis?.map((api) => {
7
+ if (!api.publishes) { return api; }
8
+ const publishes = api.publishes.flatMap((entry) => {
9
+ return picked(entry.name, paths, 'path', true).map((name) => {
10
+ assertLeaf(objects, name);
11
+ return { ...entry, name };
12
+ });
13
+ });
14
+ return { ...api, publishes };
15
+ });
16
+ }
17
+
18
+ /** Streams made available by publishers on the selected service. */
19
+ export function publishedNames(server, api) {
20
+ return (server.api || []).filter((item) => {
21
+ return !api || item.id === api;
22
+ }).flatMap((item) => {
23
+ return (item.publishes || []).map(({ name }) => { return name; });
24
+ });
25
+ }
26
+
27
+ /** Locally collected and forwarded streams stay available through the server's services. */
28
+ export function availableNames(source, api) {
29
+ return [...new Set([...source.fanIn.map(({ name }) => { return name; }), ...publishedNames(source, api)])];
30
+ }
@@ -1,3 +1,4 @@
1
+ import { publishedNames } from './publishedStreams.js';
1
2
  import { isAddress } from './expandPattern.js';
2
3
  import { asPath, objectPath, serverById } from './releaseNodes.js';
3
4
 
@@ -28,28 +29,22 @@ function sameObjects(left, right) {
28
29
  * remember([], { from: 'cell', object: 'unit', side: 'out', to: 'archive' });
29
30
  */
30
31
  function remember(edges, edge) {
31
- const found = edges.find((item) => {
32
+ let found = edges.find((item) => {
32
33
  return item.from === edge.from && item.to === edge.to;
33
34
  });
34
35
  if (!found) {
35
- edges.push({
36
- api: edge.api,
37
- from: edge.from,
38
- objects: [edge.object],
39
- sides: { [edge.side]: [edge.object] },
40
- to: edge.to
41
- });
42
- return;
43
- }
44
- const prior = found.sides[edge.side] ? found.sides[edge.side].slice() : [];
45
- if (!prior.includes(edge.object)) {
46
- prior.push(edge.object);
36
+ found = { from: edge.from, to: edge.to, sides: {}, streams: new Map() };
37
+ edges.push(found);
47
38
  }
48
- found.sides[edge.side] = prior;
49
- found.objects = (found.sides.out || found.sides.in).slice();
39
+ found.sides[edge.side] ||= [];
40
+ const objects = found.sides[edge.side];
41
+ if (!objects.includes(edge.object)) { objects.push(edge.object); }
42
+ const services = found.streams.get(edge.name) || new Set();
50
43
  if (edge.api) {
44
+ services.add(edge.api);
51
45
  found.api = edge.api;
52
46
  }
47
+ found.streams.set(edge.name, services);
53
48
  }
54
49
 
55
50
  /**
@@ -67,6 +62,7 @@ export function edgesOf(document) {
67
62
  const dest = serverById(document, flow.to);
68
63
  remember(edges, {
69
64
  from: server.id,
65
+ name: flow.name,
70
66
  object: objectPath(server, flow.name),
71
67
  side: 'out',
72
68
  to: dest.id
@@ -80,6 +76,7 @@ export function edgesOf(document) {
80
76
  remember(edges, {
81
77
  api: flow.api,
82
78
  from: source.id,
79
+ name: flow.name,
83
80
  object: objectPath(source, flow.name),
84
81
  side: 'in',
85
82
  to: server.id
@@ -119,7 +116,7 @@ function covers(held, objectId) {
119
116
  * direct({ fan_in: [], id: 'cell' });
120
117
  */
121
118
  function direct(server) {
122
- const names = [];
119
+ const names = publishedNames(server);
123
120
  (server.fan_in || []).forEach((flow) => {
124
121
  if (isAddress(flow.from)) {
125
122
  names.push(flow.name);
@@ -116,3 +116,16 @@ export function profileFor(document, server) {
116
116
  const values = { ...(profile.variables || {}), ...(server.profile.variables || {}) };
117
117
  return { ...profile, variables: values };
118
118
  }
119
+
120
+ /** Selects an explicitly named service or the sole service of the source. */
121
+ export function serviceOf(source, api) {
122
+ const listed = source.api || [];
123
+ if (!api && listed.length > 1) {
124
+ throw new Error(`system document server ${source.id} must name one api`);
125
+ }
126
+ const service = api ? listed.find((item) => { return item.id === api; }) : listed[0];
127
+ if (api && !service) {
128
+ throw new Error(`system document server ${source.id} provides no api ${api}`);
129
+ }
130
+ return service;
131
+ }
@@ -1,5 +1,5 @@
1
1
  import { isAddress } from './expandPattern.js';
2
- import { clusterOf, objectPath, serverById } from './releaseNodes.js';
2
+ import { clusterOf, objectPath, serverById, serviceOf } from './releaseNodes.js';
3
3
 
4
4
  /**
5
5
  * Maps one module name onto a chart product.
@@ -16,7 +16,7 @@ function bindOne(name, spec, secret) {
16
16
  return ['postgres', { enabled: spec.enabled !== false, secret: secret || 'scada-postgres' }];
17
17
  }
18
18
  if (name === 'message_bus') {
19
- return ['rabbitmq', { enabled: spec.enabled !== false,
19
+ return ['rabbitmq', { ...spec.chart, enabled: spec.enabled !== false,
20
20
  ...(spec.dead_letter ? { deadLetter: spec.dead_letter } : {}) }];
21
21
  }
22
22
  if (name === 'telemetry_store') {
@@ -103,19 +103,8 @@ export function machinesOf(server) {
103
103
  * plantUrl({ api: [{ id: 'plant', url: 'http://192.0.2.10/api/v1' }], id: 'cell' });
104
104
  */
105
105
  function plantUrl(source, api) {
106
- const listed = source.api || [];
107
- if (api && !listed.some((item) => {
108
- return item.id === api;
109
- })) {
110
- throw new Error(`system document server ${source.id} provides no api ${api}`);
111
- }
112
- if (!api && listed.length > 1) {
113
- throw new Error(`system document server ${source.id} must name one api`);
114
- }
115
- const plant = listed.find((item) => {
116
- return item.id === 'plant';
117
- });
118
- return plant ? plant.url : '';
106
+ const service = serviceOf(source, api);
107
+ return service?.id === 'plant' ? service.url : '';
119
108
  }
120
109
 
121
110
  /**
@@ -18,7 +18,8 @@ function withImage(profile) {
18
18
  if (!image) {
19
19
  throw new Error('system document has no scada image');
20
20
  }
21
- return { image, ...bindModules(profile, app.secret) };
21
+ return { image, ...(app.site && { site: app.site }), ...(app.sink && { sink: app.sink }),
22
+ ...bindModules(profile, app.secret) };
22
23
  }
23
24
 
24
25
  /**
@@ -109,6 +110,7 @@ export default function releases(document, cluster) {
109
110
  const profile = profileFor(expanded, host);
110
111
  assertHeld(expanded, links);
111
112
  return frozen({
113
+ ...(profile.target && { target: profile.target }),
112
114
  apps: passedApps(profile),
113
115
  scada: scadaRelease(expanded, host, profile, links)
114
116
  });
@@ -0,0 +1,20 @@
1
+ import { assertHeld, edgesOf } from './releaseEdges.js';
2
+ import { serverById } from './releaseNodes.js';
3
+
4
+ /**
5
+ * Lists directed stream subscriptions for a source server in an expanded document.
6
+ * A receiver may explicitly select a service. A sender-only declaration has none.
7
+ */
8
+ export default function subscriptions(document, sourceId) {
9
+ serverById(document, sourceId);
10
+ const edges = edgesOf(document);
11
+ assertHeld(document, edges);
12
+ const rows = [];
13
+ for (const { from, to, streams } of edges.filter((edge) => { return edge.from === sourceId; })) {
14
+ for (const [name, services] of streams) {
15
+ if (!services.size) { rows.push({ from, to, name }); }
16
+ services.forEach((api) => { rows.push({ from, to, name, api }); });
17
+ }
18
+ }
19
+ return rows;
20
+ }
@@ -0,0 +1,102 @@
1
+ import { execFileSync } from 'node:child_process';
2
+
3
+ /** Retire only explicit Deployments with a single exact app label selector. */
4
+ function validateRetirements(plan) {
5
+ if (plan.retirements !== undefined && !Array.isArray(plan.retirements)) {
6
+ throw new Error('retirements must be an array');
7
+ }
8
+ for (const retirement of plan.retirements || []) {
9
+ const name = retirement?.workload?.match(/^deployment\/(?<name>[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?)$/u)?.groups.name;
10
+ const label = retirement?.selector?.match(/^app=(?<label>[A-Za-z0-9](?:[A-Za-z0-9_.-]*[A-Za-z0-9])?)$/u)?.groups.label;
11
+ if (!name || name.length > 253 || name.split('.').some((part) => { return !part || part.length > 63; })
12
+ || !label || label.length > 63 || (plan.workloads || []).includes(retirement.workload)) {
13
+ throw new Error('retirement requires an exact old deployment and app label outside desired workloads');
14
+ }
15
+ }
16
+ }
17
+
18
+ /** Validates the target before helm or kubectl can fall back to a default. */
19
+ function validate(plan, action) {
20
+ if (!['render', 'check', 'diff', 'apply', 'adopt', 'check-adoption'].includes(action)) {
21
+ throw new Error('action must be render, check, diff or apply (adopt/check-adoption for migration)');
22
+ }
23
+ const fields = action === 'render' ? ['chart', 'release', 'namespace'] : ['chart', 'release', 'namespace', 'context', 'fieldManager'];
24
+ validateRetirements(plan);
25
+ fields.forEach((key) => {
26
+ if (typeof plan[key] !== 'string' || !plan[key].trim()) { throw new Error(`release requires ${key}`); }
27
+ });
28
+ }
29
+
30
+ /** Every Kubernetes command, including the post-rollout hook, shares this target. */
31
+ function kubeAt(plan, execute) {
32
+ return (args, input, capture = false) => {
33
+ return execute('kubectl', ['--context', plan.context, '--namespace', plan.namespace, ...args],
34
+ { input, encoding: 'utf8', stdio: ['pipe', capture ? 'pipe' : 'inherit', 'inherit'] });
35
+ };
36
+ }
37
+
38
+ function applyWith(kube, manifests, flags, checkOnly) {
39
+ const args = ['apply', ...flags, '-f', '-'];
40
+ kube([...args, '--dry-run=server'], manifests);
41
+ if (!checkOnly) { kube(args, manifests); }
42
+ }
43
+
44
+ /** A missing Deployment can still have terminating pods from an interrupted attempt. */
45
+ function retireWorkloads(plan, kube) {
46
+ for (const { workload, selector } of plan.retirements || []) {
47
+ if (kube(['get', workload, '--ignore-not-found', '-o', 'name'], undefined, true).trim()) {
48
+ kube(['delete', workload, '--cascade=foreground', '--wait=true', '--timeout=300s']);
49
+ }
50
+ if (kube(['get', 'pods', '-l', selector, '-o', 'name'], undefined, true).trim()) {
51
+ throw new Error(`retirement pods remain for ${workload} (${selector})`);
52
+ }
53
+ }
54
+ }
55
+
56
+ function preflightRetirements(plan, action, kube, manifests) {
57
+ if (['apply', 'adopt'].includes(action) && plan.retirements?.length) {
58
+ if (action === 'adopt') {
59
+ applyWith(kube, manifests, ['--field-manager=kubectl-client-side-apply'], true);
60
+ }
61
+ applyWith(kube, manifests, ['--server-side', `--field-manager=${plan.fieldManager}`], true);
62
+ retireWorkloads(plan, kube);
63
+ }
64
+ }
65
+
66
+ /** Adopt legacy fields, then enforce the complete manifest before waiting for rollouts. */
67
+ function applyRelease(plan, action, kube, manifests) {
68
+ preflightRetirements(plan, action, kube, manifests);
69
+ if (['adopt', 'check-adoption'].includes(action)) {
70
+ applyWith(kube, manifests, ['--field-manager=kubectl-client-side-apply'], action === 'check-adoption');
71
+ if (action === 'check-adoption') { return ''; }
72
+ }
73
+ applyWith(kube, manifests, ['--server-side', `--field-manager=${plan.fieldManager}`], action === 'check');
74
+ if (action === 'check') { return ''; }
75
+ for (const workload of plan.workloads || []) {
76
+ kube(['rollout', 'status', workload, '--timeout=300s']);
77
+ }
78
+ plan.afterReady?.(plan, kube);
79
+ return '';
80
+ }
81
+
82
+ /**
83
+ * Renders a Helm release and executes the selected kubectl action synchronously.
84
+ * Supply chart, release, namespace and values. Cluster actions additionally require
85
+ * an explicit context and fieldManager. prerequisites and workloads are kubectl
86
+ * resource/name references. Optional retirements are { workload: "deployment/name",
87
+ * selector: "app=label" }; callers bind these to the old declarative app. They are
88
+ * removed after preflight and before any writes, with no selected pods remaining.
89
+ * afterReady(plan, kube) runs after a successful apply.
90
+ */
91
+ export default function executeRelease(plan, action = 'render', execute = execFileSync) {
92
+ validate(plan, action);
93
+ const manifests = execute('helm', ['template', plan.release, plan.chart, '--namespace', plan.namespace, '-f', '-'],
94
+ { input: JSON.stringify(plan.values), encoding: 'utf8' });
95
+ if (action === 'render') { return manifests; }
96
+ const kube = kubeAt(plan, execute);
97
+ for (const resource of plan.prerequisites || []) { kube(['get', resource, '-o', 'name']); }
98
+ if (action === 'diff') {
99
+ return kube(['diff', '--server-side', `--field-manager=${plan.fieldManager}`, '-f', '-'], manifests);
100
+ }
101
+ return applyRelease(plan, action, kube, manifests);
102
+ }