@yarkivaev/scada 2.17.0 → 2.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/index.js +1 -2
  2. package/package.json +3 -2
  3. package/src/application/deploy/collectorSourcePlan.js +97 -0
  4. package/src/application/deploy/compileCollectorTasks.js +31 -0
  5. package/src/application/deploy/compileControlCatalog.js +66 -0
  6. package/src/application/deploy/controlPlan.js +16 -0
  7. package/src/application/deploy/controlPlaneConfiguration.js +62 -0
  8. package/src/application/deploy/controlReaderSpecs.js +37 -0
  9. package/src/application/deploy/liveReleaseOverlay.js +17 -0
  10. package/src/application/deploy/projectControlPlane.js +48 -0
  11. package/src/application/deploy/projectTopology.js +41 -0
  12. package/src/infrastructure/deploy/brokerReplicaTopology.js +34 -12
  13. package/src/infrastructure/deploy/brokerSecurity.js +89 -0
  14. package/src/infrastructure/deploy/brokerSecurityInput.js +85 -0
  15. package/src/infrastructure/deploy/brokerTopology.js +125 -0
  16. package/src/infrastructure/deploy/centralTelemetry.js +51 -0
  17. package/src/infrastructure/deploy/clickhouseTelemetryPolicy.js +64 -0
  18. package/src/infrastructure/deploy/collectorChartPlan.js +68 -0
  19. package/src/infrastructure/deploy/configuredHistorySeed.js +54 -0
  20. package/src/infrastructure/deploy/configuredPostgresMaintenance.js +23 -0
  21. package/src/infrastructure/deploy/databaseSecurity.js +39 -0
  22. package/src/infrastructure/deploy/deploymentRecovery.js +49 -0
  23. package/src/infrastructure/deploy/deploymentTemplate.js +67 -0
  24. package/src/infrastructure/deploy/executeConfiguredChartDeployment.js +65 -0
  25. package/src/infrastructure/deploy/executeManagedDeployment.js +46 -0
  26. package/src/infrastructure/deploy/highAvailability/brokerOwnership.js +19 -0
  27. package/src/infrastructure/deploy/highAvailability/catalogReconciler.js +61 -0
  28. package/src/infrastructure/deploy/highAvailability/classifyFederation.js +57 -0
  29. package/src/infrastructure/deploy/highAvailability/classifyGate.js +114 -0
  30. package/src/infrastructure/deploy/highAvailability/classifyLoop.js +139 -0
  31. package/src/infrastructure/deploy/highAvailability/classifyShovels.js +70 -0
  32. package/src/infrastructure/deploy/highAvailability/classifyWatermark.js +45 -0
  33. package/src/infrastructure/deploy/highAvailability/compileClassifierRules.js +21 -0
  34. package/src/infrastructure/deploy/highAvailability/controllerReconcile.js +14 -0
  35. package/src/infrastructure/deploy/highAvailability/historyReceiver.js +49 -0
  36. package/src/infrastructure/deploy/highAvailability/historyWatermark.js +42 -0
  37. package/src/infrastructure/deploy/highAvailability/index.js +14 -0
  38. package/src/infrastructure/deploy/highAvailability/reconcileBrokerThroughController.js +18 -0
  39. package/src/infrastructure/deploy/highAvailability/reconciliationBundle.js +28 -0
  40. package/src/infrastructure/deploy/highAvailability/segmentAdmit.js +24 -0
  41. package/src/infrastructure/deploy/highAvailability/segmentPublish.js +27 -0
  42. package/src/infrastructure/deploy/highAvailability/supervisorReplica.js +36 -0
  43. package/src/infrastructure/deploy/index.js +27 -2
  44. package/src/infrastructure/deploy/projectClassification.js +42 -0
  45. package/src/infrastructure/deploy/securityPolicy.js +16 -0
  46. package/src/infrastructure/ingest/telemetry/centralPolicy.js +29 -8
  47. package/src/infrastructure/management/kiosk/kioskDeployment.js +60 -0
  48. package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +47 -0
  49. package/src/infrastructure/mdmesh/index.js +2 -0
  50. package/src/infrastructure/mdmesh/mdmeshServerRelease.js +58 -0
  51. package/src/infrastructure/messaging/rabbitmq/definitions.js +12 -6
  52. package/src/infrastructure/opcua/projectSources.js +36 -0
@@ -0,0 +1,65 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { waitForJob } from './deploymentChecks.js';
3
+ import { preserveKubeRestart } from './deploymentKube.js';
4
+ import deploymentTemplate, { deploymentCondition, deploymentReferences } from './deploymentTemplate.js';
5
+ import executeChartDeployment from './executeChartDeployment.js';
6
+ import { requireReleaseAction } from './executeRelease.js';
7
+
8
+ function writeValue(values, path, update) {
9
+ const parts = path.split('.');
10
+ const key = parts.pop();
11
+ const target = parts.reduce((current, part) => {
12
+ if (!current || !Object.hasOwn(current, part)) { throw new TypeError(`Unknown deployment value ${path}`); }
13
+ return current[part];
14
+ }, values);
15
+ if (['__proto__', 'constructor', 'prototype'].includes(key)) { throw new TypeError(`Invalid deployment value ${path}`); }
16
+ update(target, key);
17
+ }
18
+
19
+ function preserveRestarts(plan, declarations, kube) {
20
+ for (const { when, workload, annotations } of declarations ?? []) {
21
+ if (!when || deploymentCondition(when, plan)) {
22
+ writeValue(plan, annotations, (row, key) => { row[key] = preserveKubeRestart(kube, workload, row[key]); });
23
+ }
24
+ }
25
+ }
26
+
27
+ function overrideValues(values, settings) {
28
+ for (const [path, value] of Object.entries(settings.set ?? {})) {
29
+ writeValue(values, path, (row, key) => { row[key] = deploymentTemplate(value, { values }); });
30
+ }
31
+ for (const path of settings.remove ?? []) {
32
+ writeValue(values, path, (row, key) => { delete row[key]; });
33
+ }
34
+ }
35
+
36
+ function release(plan, policy, settings, { bindings, afterReady }) {
37
+ overrideValues(plan.values, settings);
38
+ const current = { ...bindings, ...plan };
39
+ return { fieldManager: policy.fieldManager, ...(settings.retirements && { retirements: settings.retirements }),
40
+ prerequisites: deploymentReferences(policy.prerequisites, current),
41
+ workloads: deploymentReferences(policy.workloads, current),
42
+ afterReady: policy.afterReady && deploymentCondition(policy.afterReady.when, current) ? (ready, kube) => {
43
+ const { job } = policy.afterReady;
44
+ if (job && (!job.when || deploymentCondition(job.when, ready))) {
45
+ waitForJob(kube, deploymentTemplate(job.target, ready), job.timeout);
46
+ }
47
+ afterReady?.(ready, kube);
48
+ } : undefined };
49
+ }
50
+
51
+ /** Apply configured chart actions with scoped runtime ports and declarative release gates. */
52
+ export default function executeConfiguredChartDeployment(policy, action, { create, chartRoot, preflight, afterReady, execute = execFileSync }) {
53
+ const overrides = policy.actionOverrides;
54
+ const settings = overrides && Object.hasOwn(overrides, action) ? overrides[action] : {};
55
+ const mode = settings.action ?? action;
56
+ try { requireReleaseAction(mode); } catch (error) { throw new Error(policy.actionError ?? error.message); }
57
+ const { plan, bindings } = create();
58
+ return executeChartDeployment({ plan, action: mode, chartRoot,
59
+ preflight(current, kube) {
60
+ preserveRestarts(current, policy.preserveRestarts, kube);
61
+ preflight?.(current, kube);
62
+ },
63
+ release(current) { return release(current, policy, settings, { bindings, afterReady }); }
64
+ }, execute);
65
+ }
@@ -0,0 +1,46 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import path from 'node:path';
3
+ import applyHelmResources from './applyHelmResources.js';
4
+ import { waitForJob } from './deploymentChecks.js';
5
+ import { deploymentKube } from './deploymentKube.js';
6
+ import { deploymentCondition, deploymentReferences } from './deploymentTemplate.js';
7
+ import executeRelease from './executeRelease.js';
8
+
9
+ const releaseActions = ['render', 'check', 'diff', 'apply'];
10
+
11
+ function applyPlatform(plan, policy, ports, kube, execute) {
12
+ applyHelmResources({ ...plan, fieldManager: policy.fieldManager, values: { ...plan.values, ...policy.values } }, {
13
+ kinds: policy.kinds, decode: ports.decode, encode: ports.encode
14
+ }, execute);
15
+ return `${JSON.stringify(ports.bootstrap(plan, kube))}\n`;
16
+ }
17
+
18
+ function applyRelease(plan, policy, action, ports, { kube, execute }) {
19
+ const release = { ...plan, prerequisites: deploymentReferences(policy.release.prerequisites, plan),
20
+ workloads: deploymentReferences(policy.release.workloads, plan),
21
+ beforeApply() { ports.beforeApply?.(plan, kube); },
22
+ afterReady() {
23
+ const { job } = policy.release;
24
+ if (job && (!job.when || deploymentCondition(job.when, plan))) {
25
+ waitForJob(kube, job.target, job.timeout);
26
+ }
27
+ } };
28
+ const output = executeRelease(release, action, execute);
29
+ return action === 'apply' && policy.afterApply ? ports.operate(policy.afterApply, plan, kube) : output;
30
+ }
31
+
32
+ /** Execute application releases, platform bootstrap, and explicitly registered operations. */
33
+ export default function executeManagedDeployment(planFor, policy, action, { chartRoot, execute = execFileSync, device, ...ports }) {
34
+ const operations = policy.operations ?? {};
35
+ const platform = policy.platform && action === policy.platform.action;
36
+ if (!releaseActions.includes(action) && !platform && !Object.hasOwn(operations, action)) {
37
+ throw new Error(policy.actionError ?? 'Unknown deployment action');
38
+ }
39
+ const selected = planFor();
40
+ const plan = { ...selected, chart: path.resolve(chartRoot, selected.chart) };
41
+ const target = deploymentKube(plan, execute, { stdio: ['pipe', 'pipe', 'inherit'] });
42
+ function kube(args, input) { return String(target(args, input)); }
43
+ if (platform) { return applyPlatform(plan, policy.platform, ports, kube, execute); }
44
+ if (Object.hasOwn(operations, action)) { return ports.operate(operations[action], plan, kube, device); }
45
+ return applyRelease(plan, policy, action, ports, { kube, execute });
46
+ }
@@ -0,0 +1,19 @@
1
+ import { federationOwnership } from './classifyFederation.js';
2
+
3
+ /** Limit topology pruning to definitions owned by the specified deployment. */
4
+ export function brokerOwnership(desired, rules, pruneShovels = []) {
5
+ const { sourcePrefix, outboxPattern, shovelSuffix } = rules.brokerPruning;
6
+ const outboxes = new RegExp(outboxPattern, 'u');
7
+ const queues = new Set(desired.queues.map(({ name }) => { return name; }));
8
+ return {
9
+ ...federationOwnership(rules),
10
+ ownsBinding(row) {
11
+ return row.destination_type === 'queue' && row.source.startsWith(sourcePrefix)
12
+ && (queues.has(row.destination) || outboxes.test(row.destination));
13
+ },
14
+ ownsShovel(row) {
15
+ return (row.name.endsWith(shovelSuffix) || pruneShovels.includes(row.name))
16
+ && String(row.value['src-queue']).startsWith(sourcePrefix);
17
+ }
18
+ };
19
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Reconciles collector assignments from a mounted catalog.
3
+ *
4
+ * The controller identity can write assignments and the leader key, not the
5
+ * catalog key. The desired catalog is therefore a file, and collector tasks
6
+ * stay separate from classification.
7
+ *
8
+ * {{{
9
+ * withCatalog(store, { version: 'v', nodes: [], tasks: [] })
10
+ * }}}
11
+ */
12
+ import fs, { existsSync, realpathSync } from 'node:fs';
13
+ import { pathToFileURL } from 'node:url';
14
+ import { clientFromEnv } from '../../../application/control/controlClient.js';
15
+ import controller from '../../../application/control/controller.js';
16
+ import controlStore from '../../../application/control/controlStore.js';
17
+ import { visible } from './classifyGate.js';
18
+ import { openClassify } from './classifyLoop.js';
19
+ import { classifierFederation, federationOwnership } from './classifyFederation.js';
20
+ import { reconcileRabbitmqFederation } from '../../messaging/rabbitmq/reconcile.js';
21
+ import { applyShovels } from './classifyShovels.js';
22
+
23
+ /** Collector tasks only. A classification adapter must not reach a collector. */
24
+ export function readable(catalog, managedAdapter = 'supervisor-classify') {
25
+ const tasks = catalog.tasks.filter((task) => { return task.spec?.adapter !== managedAdapter; });
26
+ return { ...catalog, tasks };
27
+ }
28
+
29
+ /** Read path that substitutes the mounted catalog for the stored one. */
30
+ export function withCatalog(store, catalog, managedAdapter) {
31
+ const selected = readable(catalog, managedAdapter);
32
+ return { ...store, async read() { const view = await store.read(); return visible({ ...view, catalog: selected }); } };
33
+ }
34
+
35
+ async function brokerFederation(record, rules) {
36
+ const base = process.env.RABBITMQ_MANAGEMENT;
37
+ if (!base || !rules.mesh) { return; }
38
+ const endpoints = JSON.parse(process.env.CONTROL_BROKER_ENDPOINTS || '{}');
39
+ const options = { base, username: process.env.RABBITMQ_USERNAME || 'guest',
40
+ password: process.env.RABBITMQ_PASSWORD || 'guest', vhost: '/' };
41
+ await reconcileRabbitmqFederation(classifierFederation(process.env.CONTROL_NODE_ID, endpoints, rules), { ...options, ...federationOwnership(rules) });
42
+ await applyShovels(record, endpoints, { ...options, nodeId: process.env.CONTROL_NODE_ID,
43
+ central: process.env.CONTROL_CENTRAL_BUS || 'amqp://central.invalid' }, rules);
44
+ }
45
+
46
+ function start() {
47
+ if (!process.env.CONTROL_NODE_ID || !process.env.CONTROL_CATALOG_FILE) { throw new Error('Catalog reconciler requires a node id and catalog file'); }
48
+ const catalog = JSON.parse(fs.readFileSync(process.env.CONTROL_CATALOG_FILE, 'utf8'));
49
+ const rules = process.env.CONTROL_CLASSIFY_RULES && JSON.parse(fs.readFileSync(process.env.CONTROL_CLASSIFY_RULES, 'utf8'));
50
+ const call = clientFromEnv(process.env);
51
+ const raw = controlStore(call, process.env.CONTROL_PREFIX);
52
+ const host = controller(withCatalog(raw, catalog, rules?.managedAdapter), process.env.CONTROL_NODE_ID, { clockSkewMs: Number(process.env.CONTROL_CLOCK_SKEW_MS ?? 5000), replacementDelayMs: Number(process.env.CONTROL_REPLACEMENT_DELAY_MS ?? 30000), onError(error) { process.stderr.write(`catalog reconciler: ${error.name}\n`); } });
53
+ const gate = rules ? openClassify({ env: process.env, call, rules, read: () => { return raw.read(); },
54
+ prefix: process.env.CONTROL_PREFIX, namespace: process.env.CONTROL_CLASSIFY_APPLY === 'true' ? rules.namespace : undefined,
55
+ federate(record) { return brokerFederation(record, rules); } }) : { stop() { return undefined; } };
56
+ for (const signal of ['SIGTERM', 'SIGINT']) { process.once(signal, () => { void host.stop(); gate.stop(); }); }
57
+ }
58
+
59
+ if (process.argv[1] && existsSync(process.argv[1]) && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
60
+ try { start(); } catch (error) { process.stderr.write(`catalog reconciler: ${error.name}\n`); process.exitCode = 1; }
61
+ }
@@ -0,0 +1,57 @@
1
+ function upstream(peer, uri, mesh) {
2
+ return { vhost: '/', component: 'federation-upstream', name: `${mesh.upstreamPrefix}${peer}`,
3
+ value: { uri, 'ack-mode': 'on-confirm', 'max-hops': 1 } };
4
+ }
5
+
6
+ function policy(mesh) {
7
+ const pattern = mesh.meshExchange.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
8
+ return { vhost: '/', name: mesh.policy, pattern: `^${pattern}$`, 'apply-to': 'exchanges',
9
+ definition: { 'federation-upstream-set': 'all' }, priority: 0 };
10
+ }
11
+
12
+ function durable(name) {
13
+ return { vhost: '/', name, durable: true, 'auto_delete': false, arguments: {} };
14
+ }
15
+
16
+ function binding(source, destination, type, key) {
17
+ return { source, vhost: '/', destination, 'destination_type': type, 'routing_key': key, arguments: {} };
18
+ }
19
+
20
+ function bindings(nodeId, groups, keys, mesh) {
21
+ const local = new Set(groups.filter((group) => {
22
+ return (group.home ?? group.preference[0]) === nodeId || (mesh.originCopies ?? []).includes(nodeId);
23
+ }).flatMap((group) => { return group.keys ?? []; }));
24
+ return [
25
+ ...[...local].map((key) => { return binding(mesh.exchange, mesh.meshExchange, 'exchange', key); }),
26
+ ...keys.map((key) => { return binding(mesh.meshExchange, mesh.sharedQueue, 'queue', key); }),
27
+ ...groups.flatMap((group) => {
28
+ return (group.keys ?? []).map((key) => { return binding(mesh.meshExchange, mesh.groupQueuePrefix + group.id, 'queue', key); });
29
+ }),
30
+ ...keys.filter((key) => { return !local.has(key); }).map((key) => {
31
+ return binding(mesh.meshExchange, mesh.exchange, 'exchange', key);
32
+ })
33
+ ];
34
+ }
35
+
36
+ /** Broker mesh for every declared group, with a local feed for remote keys. */
37
+ export function classifierFederation(nodeId, endpoints, { groups, mesh }) {
38
+ const peers = Object.keys(endpoints).filter((id) => { return id !== nodeId && endpoints[id]; });
39
+ const keys = [...new Set(groups.flatMap((group) => { return group.keys ?? []; }))];
40
+ return {
41
+ parameters: peers.map((peer) => { return upstream(peer, endpoints[peer], mesh); }),
42
+ policies: peers.length ? [policy(mesh)] : [],
43
+ exchanges: keys.length ? [{ ...durable(mesh.meshExchange), type: 'topic' }] : [],
44
+ queues: keys.length ? [durable(mesh.sharedQueue), ...groups.map((group) => {
45
+ return durable(mesh.groupQueuePrefix + group.id);
46
+ })] : [],
47
+ bindings: bindings(nodeId, groups, keys, mesh)
48
+ };
49
+ }
50
+
51
+ /** Limit pruning to the declared mesh's upstreams and policy. */
52
+ export function federationOwnership({ mesh }) {
53
+ return {
54
+ ownsUpstream(row) { return row.name.startsWith(mesh.upstreamPrefix); },
55
+ ownsPolicy(row) { return row.name === mesh.policy; }
56
+ };
57
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Chooses the one node allowed to calculate and the local deployment steps.
3
+ *
4
+ * Store beats a surviving spool, and a spool beats any Ready supervisor. A
5
+ * missing report is a dead node. Failover changes the machine set on the
6
+ * already running writer, never the replica count. Failback waits until the
7
+ * restored home has live observations covering a real replicated segment.
8
+ *
9
+ * {{{
10
+ * decide({}, ['preferred', 'standby'], [], 0, { replacementDelayMs: 30, clockSkewMs: 5 })
11
+ * }}}
12
+ */
13
+ import { restored } from './supervisorReplica.js';
14
+
15
+ /** True when a node report is recent enough to keep its calculator. */
16
+ export function alive(report, now, timing) {
17
+ const at = report?.receivedAt;
18
+ return Number.isFinite(at) && at <= now + timing.clockSkewMs && now - at <= timing.replacementDelayMs;
19
+ }
20
+
21
+ function capable(id, found, now, options) {
22
+ const mark = found.get(id);
23
+ if (!Number.isSafeInteger(mark?.observationMs) || !Number.isSafeInteger(mark?.segmentEndMs)) { return true; }
24
+ return restored(mark, now, options);
25
+ }
26
+
27
+ function handoff(desired, active, silent, ready, released) {
28
+ if (desired === active || silent) { return { active: silent ? desired : active, pending: null }; }
29
+ if (!ready) { return { active, pending: null }; }
30
+ return released ? { active: desired, pending: null } : { active, pending: desired };
31
+ }
32
+
33
+ function rankOf(id, stores, near) {
34
+ if (stores.includes(id)) { return 2; }
35
+ if (near.includes(id)) { return 1; }
36
+ return 0;
37
+ }
38
+
39
+ /** Next classifier record for one group. */
40
+ export function decide(record, preference, reports, now, options) {
41
+ const found = new Map(reports.map((row) => { return [row.nodeId, row]; }));
42
+ const stores = options.stores ?? [preference[0]];
43
+ const near = options.near ?? preference.slice(1, 2);
44
+ const ready = preference.filter((id) => { return alive(found.get(id), now, options); });
45
+ const ranked = [...ready].sort((left, right) => {
46
+ return rankOf(right, stores, near) - rankOf(left, stores, near) || preference.indexOf(left) - preference.indexOf(right);
47
+ });
48
+ const inside = preference.includes(record.active);
49
+ const desired = ranked.find((id) => { return capable(id, found, now, options); }) ?? ranked[0] ?? (inside ? record.active : undefined) ?? preference[0];
50
+ const active = inside ? record.active : preference[0];
51
+ const silent = !inside || !alive(found.get(record.active), now, options);
52
+ const released = Boolean(record.pending && options.ack?.pending === record.pending
53
+ && Number(options.ack.revision) > Number(options.revision));
54
+ return handoff(desired, active, silent, capable(desired, found, now, options), released);
55
+ }
56
+
57
+ /** Run the active node, arm the incoming node, wait otherwise. */
58
+ export function permit(nodeId, record) {
59
+ if (record?.active === nodeId) { return 'run'; }
60
+ return record?.pending === nodeId ? 'arm' : 'wait';
61
+ }
62
+
63
+ /** Ordered local changes. The warm writer stays at one replica. */
64
+ export function steps(nodeId, local, record = {}) {
65
+ const role = permit(nodeId, record);
66
+ const lease = role === 'run' || role === 'arm' ? 'present' : 'absent';
67
+ return local.map((row) => { return { name: row.name, replicas: 1, lease }; });
68
+ }
69
+
70
+ function merge(deploys, name, group, owned) {
71
+ const current = deploys.get(name) ?? { name, replicas: 1, lease: 'absent', groups: '', role: 'standby' };
72
+ if (owned) {
73
+ current.lease = 'present';
74
+ current.role = 'leader';
75
+ current.groups = current.groups ? `${current.groups},${group}` : group;
76
+ }
77
+ deploys.set(name, current);
78
+ }
79
+
80
+ /** One step per Deployment: lease present if any owned group shares that writer. */
81
+ export function writers(nodeId, local, record = {}) {
82
+ const deploys = new Map();
83
+ Object.entries(local).forEach(([group, rows]) => {
84
+ const role = permit(nodeId, record[group]);
85
+ const owned = role === 'run' || role === 'arm';
86
+ rows.forEach((row) => { merge(deploys, row.name, group, owned); });
87
+ });
88
+ return [...deploys.values()];
89
+ }
90
+
91
+ /** Hide classifier keys from the collector scheduler. */
92
+ export function visible(view) {
93
+ const assignments = Object.fromEntries(Object.entries(view.assignments ?? {}).filter(([id]) => { return !id.startsWith('classify-'); }));
94
+ const revisions = Object.fromEntries(Object.entries(view.revisions ?? {}).filter(([key]) => { return !key.startsWith('assignments/classify-'); }));
95
+ return { ...view, assignments, revisions };
96
+ }
97
+
98
+ /** True when the writer lease is held, the group is in env, and the rollout has finished. */
99
+ export function prepared(body, group) {
100
+ const env = body.spec?.template?.spec?.containers?.[0]?.env ?? [];
101
+ const lease = env.find((row) => { return row.name === 'SUPERVISOR_LEASE_URL' || row.name === 'SUPERVISOR_LEASE_URL_HELD'; });
102
+ const groups = env.find((row) => { return row.name === 'CLASSIFY_GROUP'; })?.value ?? '';
103
+ const want = body.spec?.replicas ?? 0;
104
+ return lease?.name === 'SUPERVISOR_LEASE_URL' && !env.some((row) => { return row.name === 'SUPERVISOR_LEASE_URL_HELD'; })
105
+ && groups.split(',').includes(group) && body.status?.updatedReplicas === want;
106
+ }
107
+
108
+ /** Ready note from the node that is arming the group. */
109
+ export function groupAck(assignments, group, pending, revisions = {}) {
110
+ if (!pending) { return null; }
111
+ const id = `classify-ready~${pending}~${group}`;
112
+ const value = assignments[id];
113
+ return value ? { pending: value.pending, revision: revisions[`assignments/${id}`] } : null;
114
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Publishes the calculator choice and starts only the local writer that owns it.
3
+ *
4
+ * Missing state waits. The living active writer keeps the group until the
5
+ * incoming node has armed, then the stored choice flips.
6
+ *
7
+ * {{{
8
+ * openClassify(ctx)
9
+ * }}}
10
+ */
11
+ import deploymentPatch from '../deploymentPatch.js';
12
+ import reconcileDeployments from '../reconcileDeployments.js';
13
+ import reconcileStoredChoice from '../../../application/control/reconcileStoredChoice.js';
14
+ import serveReconciliation from '../../management/serveReconciliation.js';
15
+ import jsonAssignments from '../../../application/control/jsonAssignments.js';
16
+ import { decide, groupAck, permit, prepared, writers } from './classifyGate.js';
17
+ import { stamp, tagged } from './classifyWatermark.js';
18
+
19
+ const leaseNames = ['SUPERVISOR_LEASE_URL', 'SUPERVISOR_LEASE_URL_HELD'];
20
+
21
+ /** Describe the environment and replica change for one classifier workload. */
22
+ export function operation(body, step) {
23
+ const name = step.lease === 'absent' ? leaseNames[1] : leaseNames[0];
24
+ return deploymentPatch(body, {
25
+ rename: step.lease ? { aliases: leaseNames, name } : undefined,
26
+ environment: { CLASSIFY_GROUP: step.groups, SUPERVISOR_WRITER_ROLE: step.role },
27
+ replicas: step.replicas
28
+ });
29
+ }
30
+
31
+ /** True when the writer lease is unheld and the rollout has finished. */
32
+ export function released(body) {
33
+ const env = body.spec?.template?.spec?.containers?.[0]?.env ?? [];
34
+ const lease = env.find((row) => { return leaseNames.includes(row.name); });
35
+ const want = body.spec?.replicas ?? 0;
36
+ const status = body.status ?? {};
37
+ return lease?.name === 'SUPERVISOR_LEASE_URL_HELD' && !env.some((row) => { return row.name === 'SUPERVISOR_LEASE_URL'; })
38
+ && status.updatedReplicas === want;
39
+ }
40
+
41
+ /** True when the incoming node already posted a ready note newer than the stored choice. */
42
+ export function noted(ack, pending, ackRev, recordRev) {
43
+ return ack?.pending === pending && Number(ackRev) > Number(recordRev);
44
+ }
45
+
46
+ async function ready(ctx, deployments, rows, group) {
47
+ if (ctx.armed) { return ctx.armed(rows, group); }
48
+ const found = await Promise.all(rows.map(async (row) => {
49
+ const current = await deployments.get(row.name);
50
+ return current !== null && prepared(current, group);
51
+ }));
52
+ return found.every(Boolean);
53
+ }
54
+
55
+ async function note(ctx, group, record, { deployments, rows, view }) {
56
+ if (!record?.pending || record.pending !== ctx.env.CONTROL_NODE_ID) { return; }
57
+ const quiet = await ready(ctx, deployments, rows, group);
58
+ const key = `classify-ready~${ctx.env.CONTROL_NODE_ID}~${group}`;
59
+ const ack = view.assignments[key];
60
+ const ackRev = view.revisions[`assignments/${key}`];
61
+ const recordRev = view.revisions['assignments/classify-record'];
62
+ if (!quiet || noted(ack, record.pending, ackRev, recordRev)) { return; }
63
+ await jsonAssignments(ctx.call, ctx.prefix).write(key, { pending: record.pending });
64
+ }
65
+
66
+ function choice(ctx, previous, view) {
67
+ const now = Date.now();
68
+ const timing = { replacementDelayMs: Number(ctx.env.CONTROL_CLASSIFY_DELAY_MS ?? 60000), clockSkewMs: Number(ctx.env.CONTROL_CLOCK_SKEW_MS ?? 5000) };
69
+ return Object.fromEntries(ctx.rules.groups.map((group) => {
70
+ const current = previous[group.id] ?? {};
71
+ const ack = groupAck(view.assignments, group.id, current.pending, view.revisions);
72
+ return [group.id, decide(current, group.preference, tagged(view.reports, view.assignments, group.id), now, {
73
+ ...timing, ack, revision: view.revisions['assignments/classify-record'], stores: group.stores, near: group.near
74
+ })];
75
+ }));
76
+ }
77
+
78
+ async function enforce(ctx, record, view) {
79
+ const planned = writers(ctx.env.CONTROL_NODE_ID, ctx.local, record);
80
+ const deployments = reconcileDeployments({
81
+ namespace: ctx.namespace,
82
+ onPatch(step, patch) { process.stderr.write(`classify gate: ${step.name} ${patch.path}\n`); }
83
+ });
84
+ const apply = ctx.patch ?? ((step) => { return deployments.apply(step, operation); });
85
+ await planned.reduce(async (prior, step) => { await prior; await apply(step); }, Promise.resolve());
86
+ await Object.entries(ctx.local).reduce(async (done, [group, rows]) => {
87
+ await done;
88
+ await note(ctx, group, record[group], { deployments, rows, view });
89
+ }, Promise.resolve());
90
+ }
91
+
92
+ /** Read reports, publish one stored choice, and apply only that record. */
93
+ export async function cycle(box, ctx) {
94
+ await stamp(ctx);
95
+ const key = 'classify-record';
96
+ const assignments = jsonAssignments(ctx.call, ctx.prefix);
97
+ const { record, view } = await reconcileStoredChoice({
98
+ key,
99
+ read() { return ctx.read(); },
100
+ choose(previous, snapshot) { return choice(ctx, previous, snapshot); },
101
+ compareAndSet(revision, next) { return assignments.compareAndSet(key, revision, next); }
102
+ });
103
+ box.record = record;
104
+ box.ready = true;
105
+ if (ctx.federate) { await ctx.federate(record); }
106
+ if (ctx.namespace && ctx.env.CONTROL_CLASSIFY_APPLY === 'true') { await enforce(ctx, record, view); }
107
+ }
108
+
109
+ /** Serve permit text or the stored classify-record JSON. */
110
+ export function reply(req, res, nodeId, state) {
111
+ const path = (req.url ?? '').split('?')[0];
112
+ if (path === '/record') {
113
+ if (!state.ready) {
114
+ res.writeHead(503, { 'content-type': 'text/plain; charset=utf-8' });
115
+ res.end('wait');
116
+ return;
117
+ }
118
+ res.writeHead(200, { 'content-type': 'application/json' });
119
+ res.end(JSON.stringify(state.record));
120
+ return;
121
+ }
122
+ const group = decodeURIComponent(path.split('/')[2] ?? '');
123
+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
124
+ res.end(state.ready ? permit(nodeId, state.record[group]) : 'wait');
125
+ }
126
+
127
+ function failed(error) { process.stderr.write(`classify gate: ${error.name}\n`); }
128
+
129
+ /** Read reports, publish one choice per group, and apply this node's steps. */
130
+ export function openClassify(ctx) {
131
+ const state = { record: {}, ready: false };
132
+ const local = ctx.rules.local?.[ctx.env.CONTROL_NODE_ID] ?? {};
133
+ return serveReconciliation({
134
+ run() { return cycle(state, { ...ctx, local }); },
135
+ respond(req, res) { reply(req, res, ctx.env.CONTROL_NODE_ID, state); },
136
+ port: Number(ctx.env.CONTROL_CLASSIFY_PORT),
137
+ onError: failed
138
+ });
139
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Classification shovels from the live classify-record.
3
+ *
4
+ * The home group's queue moves to the owner's broker while
5
+ * `active` is not home. A home owner has no shovel.
6
+ *
7
+ * {{{
8
+ * shovelsFor({ mix: { active: 'beta' } }, brokers, central, rules)
9
+ * }}}
10
+ */
11
+ import { reconcileRabbitmqShovels } from '../../messaging/rabbitmq/reconcile.js';
12
+
13
+ function guest(uri) {
14
+ const parsed = new URL(uri);
15
+ if (parsed.username) { return uri; }
16
+ parsed.username = 'guest';
17
+ parsed.password = 'guest';
18
+ return parsed.toString().replace(/\/$/u, '');
19
+ }
20
+ function assertEdge(uri, central) {
21
+ const { host } = new URL(uri);
22
+ if (host === new URL(central).host) { throw new TypeError(`Classification shovel must stay off the central broker ${host}`); }
23
+ return uri;
24
+ }
25
+ function homeOf(group, rules) {
26
+ const rule = rules.groups.find(({ id }) => { return id === group; });
27
+ if (!rule) { throw new TypeError(`Unknown classify group ${group}`); }
28
+ return rule.home ?? rule.preference[0];
29
+ }
30
+ function ownerOf(row) {
31
+ return row?.pending ?? row?.active;
32
+ }
33
+
34
+ /** Task holders from the pending owner, else classify-record.active. */
35
+ export function holdersFrom(record) {
36
+ return Object.fromEntries(Object.entries(record).flatMap(([group, row]) => {
37
+ const owner = ownerOf(row);
38
+ return owner ? [[`classify/${group}`, owner]] : [];
39
+ }));
40
+ }
41
+ function shovel(group, home, owner, brokers, { central, prefix }) {
42
+ const source = brokers[home];
43
+ const destination = brokers[owner];
44
+ if (!source || !destination) { throw new TypeError(`Missing broker for ${group}`); }
45
+ assertEdge(source, central);
46
+ assertEdge(destination, central);
47
+ return { vhost: '/', component: 'shovel', name: `classify-${group}-to-${owner}`, value: {
48
+ 'src-protocol': 'amqp091', 'src-uri': guest(source), 'src-queue': prefix + group,
49
+ 'dest-protocol': 'amqp091', 'dest-uri': guest(destination), 'dest-queue': prefix + group,
50
+ 'reconnect-delay': 30, 'dest-publish-properties': { 'delivery_mode': 2 }
51
+ } };
52
+ }
53
+ /** Edge-to-edge classify shovels for groups whose queue owner is not home. */
54
+ export function shovelsFor(record, brokers, central, rules) {
55
+ return Object.entries(record).flatMap(([group, row]) => {
56
+ const owner = ownerOf(row);
57
+ if (!owner) { return []; }
58
+ const home = homeOf(group, rules);
59
+ return owner === home ? [] : [shovel(group, home, owner, brokers, { central, prefix: rules.mesh.groupQueuePrefix })];
60
+ });
61
+ }
62
+ function belongs(row, uri) {
63
+ return uri && new URL(row.value['src-uri']).host === new URL(uri).host;
64
+ }
65
+ /** Reconcile home-owned classification shovels on this broker. */
66
+ export function applyShovels(record, brokers, options, rules) {
67
+ const desired = shovelsFor(record, brokers, options.central, rules).filter((row) => { return belongs(row, brokers[options.nodeId]); });
68
+ return reconcileRabbitmqShovels(desired, { ...options, vhost: options.vhost || '/',
69
+ ownsShovel(row) { return /^classify-/u.test(row.name); } });
70
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Publishes this node's history watermarks so failback waits for catch-up.
3
+ *
4
+ * {{{
5
+ * tagged([{ nodeId: 'alpha' }], { 'classify-watermark~alpha~mix': { observationMs: 8, segmentEndMs: 8 } }, 'mix')
6
+ * }}}
7
+ */
8
+
9
+ import jsonAssignments from '../../../application/control/jsonAssignments.js';
10
+
11
+ async function fetchWatermark(url) {
12
+ if (!url) { return undefined; }
13
+ try {
14
+ const response = await fetch(url, { signal: AbortSignal.timeout(2000) });
15
+ if (!response.ok) { return undefined; }
16
+ const body = await response.json();
17
+ const observationMs = Number(body.observationMs);
18
+ const segmentEndMs = Number(body.segmentEndMs);
19
+ if (!Number.isSafeInteger(observationMs) || !Number.isSafeInteger(segmentEndMs)) { return undefined; }
20
+ return { observationMs, segmentEndMs };
21
+ } catch {
22
+ return undefined;
23
+ }
24
+ }
25
+
26
+ /** Merge the stored watermark onto the report the gate already uses. */
27
+ export function tagged(reports, assignments, group) {
28
+ return reports.map((row) => {
29
+ const mark = assignments[`classify-watermark~${row.nodeId}~${group}`] ?? assignments[`classify-watermark~${row.nodeId}`];
30
+ return mark ? { ...row, observationMs: mark.observationMs, segmentEndMs: mark.segmentEndMs } : row;
31
+ });
32
+ }
33
+
34
+ /** Write this node's observation and segment watermarks for every local group. */
35
+ export async function stamp(ctx) {
36
+ const node = ctx.env.CONTROL_NODE_ID;
37
+ const url = ctx.env.CONTROL_WATERMARK_URL ?? ctx.rules?.watermarkUrls?.[node];
38
+ const mark = ctx.watermark ? await ctx.watermark(ctx) : await fetchWatermark(url);
39
+ if (!mark) { return; }
40
+ const groups = Object.keys(ctx.local ?? {});
41
+ const assignments = jsonAssignments(ctx.call, ctx.prefix);
42
+ await Promise.all([node, ...groups.map((group) => { return `${node}~${group}`; })].map((suffix) => {
43
+ return assignments.write(`classify-watermark~${suffix}`, mark);
44
+ }));
45
+ }
@@ -0,0 +1,21 @@
1
+ /** Expand reusable group workloads and shared watermark URLs into the mounted rules. */
2
+ export function compileClassifierRules({ workloads, watermarks, ...rules }) {
3
+ const groups = new Set(rules.groups.map(({ id }) => { return id; }));
4
+ const local = { ...rules.local };
5
+ for (const { name, nodes, groups: owned } of workloads ?? []) {
6
+ for (const group of owned) {
7
+ if (!groups.has(group)) { throw new TypeError(`Unknown classify group ${group}`); }
8
+ for (const node of nodes) {
9
+ const current = local[node]?.[group] ?? [];
10
+ local[node] = { ...local[node], [group]: [...current, { name }] };
11
+ }
12
+ }
13
+ }
14
+ const watermarkUrls = { ...rules.watermarkUrls };
15
+ for (const { url, nodes } of watermarks ?? []) {
16
+ for (const node of nodes) {
17
+ watermarkUrls[node] = url;
18
+ }
19
+ }
20
+ return { ...rules, local, watermarkUrls };
21
+ }
@@ -0,0 +1,14 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { kubectlPortForward } from '../../management/kubectlPortForward.js';
3
+ import { reconcileRabbitmqTopology } from '../../messaging/rabbitmq/reconcile.js';
4
+ import { brokerOwnership } from './brokerOwnership.js';
5
+
6
+ try {
7
+ const { context, namespace, prefix, options, desired, pruneShovels, rules } = JSON.parse(readFileSync(0, 'utf8'));
8
+ const changed = await kubectlPortForward({ context, namespace, target: `statefulset/${prefix}-rabbitmq`, port: 15672 },
9
+ (base) => { return reconcileRabbitmqTopology(desired, { ...options, base, ...brokerOwnership(desired, rules, pruneShovels) }); });
10
+ process.stdout.write(JSON.stringify({ brokerChanges: changed }));
11
+ } catch {
12
+ process.stderr.write('Controller broker reconciliation failed\n');
13
+ process.exitCode = 1;
14
+ }