@yarkivaev/scada 2.17.0 → 2.19.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 (132) hide show
  1. package/index.js +14 -2
  2. package/package.json +5 -2
  3. package/src/application/cycleTimelineFetch.js +56 -0
  4. package/src/application/deploy/collectorSourcePlan.js +97 -0
  5. package/src/application/deploy/compileCollectorTasks.js +31 -0
  6. package/src/application/deploy/compileControlCatalog.js +66 -0
  7. package/src/application/deploy/controlPlan.js +16 -0
  8. package/src/application/deploy/controlPlaneConfiguration.js +62 -0
  9. package/src/application/deploy/controlReaderSpecs.js +37 -0
  10. package/src/application/deploy/edgeDescriptors.js +31 -0
  11. package/src/application/deploy/fieldbusSourcePlan.js +79 -0
  12. package/src/application/deploy/liveReleaseOverlay.js +17 -0
  13. package/src/application/deploy/plantBindingProfile.js +24 -0
  14. package/src/application/deploy/projectControlPlane.js +48 -0
  15. package/src/application/deploy/projectTopology.js +41 -0
  16. package/src/application/deploy/topologyGraph.js +81 -0
  17. package/src/application/edgeOperatorCatalog.js +9 -7
  18. package/src/application/mcp/analyticsMcpPort.js +20 -0
  19. package/src/application/mcp/analyticsNamespaceNodes.js +29 -0
  20. package/src/application/mcp/analyticsTextContent.js +13 -0
  21. package/src/application/mcp/plantReadPorts.js +168 -0
  22. package/src/application/mcp/textContentCatalog.js +7 -0
  23. package/src/application/operationPrefixes.js +67 -0
  24. package/src/application/operatorCatalogView.js +8 -0
  25. package/src/application/projectPlantShops.js +17 -0
  26. package/src/application/runtime/collectorDslManifest.js +44 -0
  27. package/src/application/runtime/collectorLaunch.js +34 -0
  28. package/src/application/runtime/collectorOptions.js +21 -0
  29. package/src/application/runtime/controlDeliveryEnvironment.js +19 -0
  30. package/src/application/runtime/embeddedCollectors.js +6 -0
  31. package/src/application/runtime/index.js +7 -1
  32. package/src/application/runtime/pagedDelivery.js +87 -0
  33. package/src/application/runtime/resolveSecrets.js +9 -0
  34. package/src/application/siteOperatorCatalog.js +8 -7
  35. package/src/application/siteRuntime/checkpointedOperationPoll.js +77 -0
  36. package/src/application/siteRuntime/cutoverOperations.js +25 -0
  37. package/src/application/siteRuntime/databaseMigrations.js +27 -0
  38. package/src/application/siteRuntime/edgeMetricsStore.js +35 -0
  39. package/src/application/siteRuntime/history.js +29 -0
  40. package/src/application/siteRuntime/index.js +16 -0
  41. package/src/application/siteRuntime/measurementTopic.js +9 -0
  42. package/src/application/siteRuntime/operationFederation.js +15 -0
  43. package/src/application/siteRuntime/operationSnapshot.js +18 -0
  44. package/src/application/siteRuntime/operatorField.js +49 -0
  45. package/src/application/siteRuntime/operatorUpdates.js +37 -0
  46. package/src/application/siteRuntime/telemetry.js +31 -0
  47. package/src/application/siteRuntime/telemetryBackfillCommand.js +64 -0
  48. package/src/application/timelineMetrics.js +36 -0
  49. package/src/domain/timeline/cyclePhases.js +191 -0
  50. package/src/infrastructure/deploy/brokerFleetPolicy.js +91 -0
  51. package/src/infrastructure/deploy/brokerReplicaTopology.js +34 -12
  52. package/src/infrastructure/deploy/brokerSecurity.js +89 -0
  53. package/src/infrastructure/deploy/brokerSecurityInput.js +85 -0
  54. package/src/infrastructure/deploy/brokerTopology.js +125 -0
  55. package/src/infrastructure/deploy/centralTelemetry.js +51 -0
  56. package/src/infrastructure/deploy/clickhouseTelemetryPolicy.js +64 -0
  57. package/src/infrastructure/deploy/collectorChartPlan.js +68 -0
  58. package/src/infrastructure/deploy/configuredArchivePlan.js +25 -0
  59. package/src/infrastructure/deploy/configuredBrokerRoutes.js +34 -0
  60. package/src/infrastructure/deploy/configuredClassification.js +74 -0
  61. package/src/infrastructure/deploy/configuredControlPlane.js +116 -0
  62. package/src/infrastructure/deploy/configuredDeploymentCredentials.js +45 -0
  63. package/src/infrastructure/deploy/configuredEtcdInventory.js +30 -0
  64. package/src/infrastructure/deploy/configuredHistorySeed.js +54 -0
  65. package/src/infrastructure/deploy/configuredPostgresMaintenance.js +23 -0
  66. package/src/infrastructure/deploy/configuredRuntimeCapabilities.js +14 -0
  67. package/src/infrastructure/deploy/configuredSiteAssets.js +50 -0
  68. package/src/infrastructure/deploy/configuredStagedDeployment.js +48 -0
  69. package/src/infrastructure/deploy/databaseSecurity.js +39 -0
  70. package/src/infrastructure/deploy/deploymentRecovery.js +49 -0
  71. package/src/infrastructure/deploy/deploymentTemplate.js +67 -0
  72. package/src/infrastructure/deploy/executeConfiguredChartDeployment.js +65 -0
  73. package/src/infrastructure/deploy/executeManagedDeployment.js +46 -0
  74. package/src/infrastructure/deploy/highAvailability/brokerOwnership.js +19 -0
  75. package/src/infrastructure/deploy/highAvailability/catalogReconciler.js +61 -0
  76. package/src/infrastructure/deploy/highAvailability/classifyFederation.js +57 -0
  77. package/src/infrastructure/deploy/highAvailability/classifyGate.js +114 -0
  78. package/src/infrastructure/deploy/highAvailability/classifyLoop.js +139 -0
  79. package/src/infrastructure/deploy/highAvailability/classifyShovels.js +70 -0
  80. package/src/infrastructure/deploy/highAvailability/classifyWatermark.js +45 -0
  81. package/src/infrastructure/deploy/highAvailability/compileClassifierRules.js +21 -0
  82. package/src/infrastructure/deploy/highAvailability/configuredBrokerReconciliation.js +21 -0
  83. package/src/infrastructure/deploy/highAvailability/controllerReconcile.js +14 -0
  84. package/src/infrastructure/deploy/highAvailability/historyReceiver.js +49 -0
  85. package/src/infrastructure/deploy/highAvailability/historyWatermark.js +42 -0
  86. package/src/infrastructure/deploy/highAvailability/index.js +15 -0
  87. package/src/infrastructure/deploy/highAvailability/reconcileBrokerThroughController.js +18 -0
  88. package/src/infrastructure/deploy/highAvailability/reconciliationBundle.js +28 -0
  89. package/src/infrastructure/deploy/highAvailability/segmentAdmit.js +24 -0
  90. package/src/infrastructure/deploy/highAvailability/segmentPublish.js +27 -0
  91. package/src/infrastructure/deploy/highAvailability/supervisorReplica.js +36 -0
  92. package/src/infrastructure/deploy/index.js +46 -2
  93. package/src/infrastructure/deploy/mixedStoreHistory.js +27 -0
  94. package/src/infrastructure/deploy/projectClassification.js +42 -0
  95. package/src/infrastructure/deploy/publicBrokerPlan.js +15 -0
  96. package/src/infrastructure/deploy/securityPolicy.js +16 -0
  97. package/src/infrastructure/deploy/siteBrokerDefinitions.js +97 -0
  98. package/src/infrastructure/deploy/stagedSitePlan.js +132 -0
  99. package/src/infrastructure/deploy/supervisedServicePlan.js +82 -0
  100. package/src/infrastructure/http/edge/attachClassify.js +30 -0
  101. package/src/infrastructure/http/edge/classifyProxy.js +72 -0
  102. package/src/infrastructure/http/edge/classifyRecord.js +32 -0
  103. package/src/infrastructure/http/edge/classifyRouting.js +14 -0
  104. package/src/infrastructure/http/edge/siteAccess.js +7 -0
  105. package/src/infrastructure/http/edge/writeGuard.js +84 -0
  106. package/src/infrastructure/http/plant/routes/machineOperationList.js +18 -0
  107. package/src/infrastructure/http/plant/routes/operationRoute.js +2 -11
  108. package/src/infrastructure/http/plant/routes/operatorRoute.js +25 -0
  109. package/src/infrastructure/http/plant/streams/operationStream.js +25 -37
  110. package/src/infrastructure/ingest/mqtt/modbusDeviceSpec.js +5 -28
  111. package/src/infrastructure/ingest/mqtt/registerPoint.js +2 -2
  112. package/src/infrastructure/ingest/telemetry/centralPolicy.js +29 -8
  113. package/src/infrastructure/management/kiosk/kioskDeployment.js +60 -0
  114. package/src/infrastructure/mdmesh/adminReconciliation.js +19 -0
  115. package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +47 -0
  116. package/src/infrastructure/mdmesh/controllerOperation.js +17 -0
  117. package/src/infrastructure/mdmesh/index.js +5 -0
  118. package/src/infrastructure/mdmesh/mdmeshServerRelease.js +58 -0
  119. package/src/infrastructure/mdmesh/publishApk.js +30 -0
  120. package/src/infrastructure/messaging/rabbitmq/definitions.js +12 -6
  121. package/src/infrastructure/opcua/projectSources.js +36 -0
  122. package/src/infrastructure/persistence/clickhouse/metricBursts.js +73 -0
  123. package/src/infrastructure/persistence/pg/cyclePhaseQuery.js +168 -0
  124. package/src/infrastructure/persistence/pg/cyclePrior.js +96 -0
  125. package/src/infrastructure/persistence/pg/operatorFieldStore.js +50 -0
  126. package/src/infrastructure/streams/boundedTextFrames.js +27 -0
  127. package/src/infrastructure/streams/framedSerialSource.js +25 -0
  128. package/src/infrastructure/streams/index.js +5 -0
  129. package/src/infrastructure/streams/namedSerialDevices.js +26 -0
  130. package/src/infrastructure/streams/serialLine.js +26 -0
  131. package/src/infrastructure/streams/watchCurrentReading.js +31 -0
  132. package/src/infrastructure/streams/windowPublication.js +73 -0
@@ -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,21 @@
1
+ import { brokerManagement } from '../brokerSecurity.js';
2
+ import { brokerPolicy } from '../securityPolicy.js';
3
+ import { reconcileRabbitmqTopology } from '../../messaging/rabbitmq/reconcile.js';
4
+ import { brokerOwnership } from './brokerOwnership.js';
5
+ import { reconcileBrokerThroughController } from './reconcileBrokerThroughController.js';
6
+
7
+ /** Bind broker reconciliation to its declared management identity and classifier ownership. */
8
+ export default function configuredBrokerReconciliation(identity, classifierRules) {
9
+ function management(base, security) {
10
+ const broker = brokerPolicy(security);
11
+ return broker ? brokerManagement(base, broker) : { base, ...identity };
12
+ }
13
+ return {
14
+ reconcile(desired, base, security) {
15
+ return reconcileRabbitmqTopology(desired, { ...management(base, security), ...brokerOwnership(desired, classifierRules) });
16
+ },
17
+ reconcileDeployment(plan, _kube, security, execute) {
18
+ return reconcileBrokerThroughController(plan, management('', security), classifierRules, execute);
19
+ }
20
+ };
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
+ }
@@ -0,0 +1,49 @@
1
+ import runRetention from '../../ingest/db/runRetention.js';
2
+ import supervisorSink from '../../../application/supervisorSink.js';
3
+ import historyApi from './historyWatermark.js';
4
+ import amqpSource from '../../streams/amqpSource.js';
5
+ import segmentAdmit, { grantedEpoch } from './segmentAdmit.js';
6
+ import segmentPublish from './segmentPublish.js';
7
+ import abutSegments from '../../ingest/sinks/abutSegments.js';
8
+ import silenceBudget from '../../../domain/segment/silenceBudget.js';
9
+
10
+ function apiOptions(sink) {
11
+ return {
12
+ port: sink.apiPort, token: sink.apiToken, metricsEnabled: sink.metricsEnabled,
13
+ retentionEnabled: sink.retentionEnabled, retentionDays: sink.retentionDays,
14
+ requestTimeoutMs: sink.requestTimeoutMs, pool: sink.pool, runRetention, health: sink.health
15
+ };
16
+ }
17
+
18
+ /** AMQP delivery adapter. A string payload is the same body the tests pass through. */
19
+ export function segmentCollector(epoch, publish) {
20
+ const admit = segmentAdmit(epoch, publish);
21
+ return {
22
+ accept(delivery) {
23
+ const payload = delivery.content ? delivery.content.toString() : delivery;
24
+ return admit(payload);
25
+ }
26
+ };
27
+ }
28
+
29
+ function historyData(env, ports, history) {
30
+ return (data, pool) => {
31
+ const next = ports.sinkOptions?.stateData?.(data, pool) ?? data;
32
+ return { ...next, history: history(pool, { retentionDays: Number(env.HISTORY_RETENTION_DAYS ?? 30) }) };
33
+ };
34
+ }
35
+
36
+ /** Starts the admit consumer, then the history API. Pipelines cannot be turned back on here. */
37
+ export default async function runHistoryReceiver(env, { sinkOptions, history, destinationQueue, sourceQueue }, ports = {}) {
38
+ const epoch = grantedEpoch(env.SUPERVISOR_WRITER_EPOCH);
39
+ const sink = (ports.sinkFactory ?? supervisorSink)({ ...env, SINK_PIPELINES: 'false' }, { ...sinkOptions, ...ports.sinkOptions, stateData: historyData(env, ports, history) });
40
+ const http = (ports.apiFactory ?? historyApi)(sink.dataAccess, apiOptions(sink));
41
+ const destination = env.SEGMENT_ADMIT_DESTINATION ?? destinationQueue;
42
+ const outbound = ports.outbound ?? segmentPublish(env.HISTORY_AMQP_URL, destination);
43
+ await outbound.start();
44
+ const source = (ports.sourceFactory ?? amqpSource)(env.HISTORY_AMQP_URL, env.SEGMENT_ADMIT_QUEUE ?? sourceQueue,
45
+ segmentCollector(epoch, (body) => { return outbound.write(body); }), { prefetch: 16 });
46
+ await source.start();
47
+ await sink.run(http);
48
+ await abutSegments(sink.pool, silenceBudget(Number(env.SEGMENT_WINDOW || 15)));
49
+ }
@@ -0,0 +1,42 @@
1
+ import http from 'node:http';
2
+ import { jsonResponse, route, routes } from '@yarkivaev/simple-server';
3
+ import { createEdgeApi } from '../../http/edge/edgeApi.js';
4
+
5
+ /** Observation and segment ends stored for every configured machine. */
6
+ export async function fromPool(pool) {
7
+ const machines = (await pool.query('SELECT DISTINCT machine FROM history_topics')).rows.map((row) => { return row.machine; });
8
+ if (!machines.length) { return { observationMs: 0, segmentEndMs: 0 }; }
9
+ const obs = await pool.query(
10
+ `SELECT COALESCE(min(mx), 0)::bigint AS ms FROM (
11
+ SELECT COALESCE((SELECT max(time_ms) FROM history_observations o WHERE o.machine = m.machine), 0) AS mx
12
+ FROM unnest($1::text[]) AS m(machine)) t`,
13
+ [machines]
14
+ );
15
+ const seg = await pool.query(
16
+ `SELECT COALESCE((EXTRACT(EPOCH FROM max(end_time)) * 1000)::bigint, 0) AS ms FROM segments WHERE kind = 'phase' AND machine = ANY($1)`,
17
+ [machines]
18
+ );
19
+ return { observationMs: Number(obs.rows[0].ms), segmentEndMs: Number(seg.rows[0].ms) };
20
+ }
21
+
22
+ /** Observation and segment ends this process already stored. */
23
+ export function watermark(history, pool) {
24
+ if (typeof history?.watermark === 'function') { return history.watermark(); }
25
+ if (pool) { return fromPool(pool); }
26
+ return Promise.resolve({ observationMs: 0, segmentEndMs: 0 });
27
+ }
28
+
29
+ /** GET /v1/history/watermark for the restored home's classify loop. */
30
+ export function watermarkRoute(history) {
31
+ return route('GET', '/v1/history/watermark', async (req, res) => {
32
+ jsonResponse(await watermark(history)).send(res);
33
+ });
34
+ }
35
+
36
+ /** History API plus the failback watermark. */
37
+ export default function historyApi(dataAccess, options) {
38
+ const inner = createEdgeApi(dataAccess, options);
39
+ const api = routes([watermarkRoute(dataAccess.history), ...inner.list()], { requestTimeoutMs: options.requestTimeoutMs });
40
+ const server = http.createServer((req, res) => { return api.handle(req, res); });
41
+ return { start() { server.listen(options.port); }, stop() { server.close(); } };
42
+ }
@@ -0,0 +1,15 @@
1
+ export { brokerOwnership } from './brokerOwnership.js';
2
+ export { readable, withCatalog } from './catalogReconciler.js';
3
+ export { classifierFederation, federationOwnership } from './classifyFederation.js';
4
+ export { alive, decide, groupAck, permit, prepared, steps, visible, writers } from './classifyGate.js';
5
+ export { compileClassifierRules } from './compileClassifierRules.js';
6
+ export { cycle, noted, openClassify, operation, released, reply } from './classifyLoop.js';
7
+ export { applyShovels, holdersFrom, shovelsFor } from './classifyShovels.js';
8
+ export { stamp, tagged } from './classifyWatermark.js';
9
+ export { reconcileBrokerThroughController } from './reconcileBrokerThroughController.js';
10
+ export { reconciliationBundle } from './reconciliationBundle.js';
11
+ export { acceptEpoch, admitWriter, applyReplica, readyToLead, restored } from './supervisorReplica.js';
12
+ export { default as runHistoryReceiver, segmentCollector } from './historyReceiver.js';
13
+ export { fromPool as replicaWatermarkFromPool, watermark as replicaWatermark } from './historyWatermark.js';
14
+ export { default as segmentAdmit, grantedEpoch } from './segmentAdmit.js';
15
+ export { default as configuredBrokerReconciliation } from './configuredBrokerReconciliation.js';
@@ -0,0 +1,18 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ const script = fileURLToPath(new URL('./controllerReconcile.js', import.meta.url));
5
+
6
+ /** Reconcile from the deployment controller, sending credentials through standard input. */
7
+ export function reconcileBrokerThroughController(plan, options, { mesh, brokerPruning }, execute = execFileSync) {
8
+ const input = {
9
+ desired: plan.values.rabbitmq.definitions, options, pruneShovels: plan.brokerPruneShovels ?? [],
10
+ context: plan.context, namespace: plan.namespace, prefix: plan.values.prefix,
11
+ rules: { mesh: { upstreamPrefix: mesh.upstreamPrefix, policy: mesh.policy }, brokerPruning }
12
+ };
13
+ try {
14
+ return execute(process.execPath, [script], {
15
+ input: JSON.stringify(input), encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 120000
16
+ });
17
+ } catch { throw new Error('Controller broker reconciliation failed'); }
18
+ }
@@ -0,0 +1,28 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { basename } from 'node:path';
3
+
4
+ const modules = [
5
+ 'catalogReconciler.js', 'classifyGate.js', 'classifyLoop.js', 'classifyWatermark.js',
6
+ 'classifyFederation.js', 'classifyShovels.js', 'supervisorReplica.js',
7
+ '../deploymentPatch.js', '../reconcileDeployments.js',
8
+ '../../management/kubeServiceAccount.js', '../../management/serveReconciliation.js',
9
+ '../../messaging/rabbitmq/reconcile.js',
10
+ '../../../application/control/catalog.js', '../../../application/control/controlClient.js',
11
+ '../../../application/control/controller.js', '../../../application/control/controlStore.js',
12
+ '../../../application/control/jsonAssignments.js', '../../../application/control/periodicReconciliation.js',
13
+ '../../../application/control/reconcileStoredChoice.js', '../../../application/control/schedule.js'
14
+ ];
15
+
16
+ function mountedSource(name) {
17
+ const source = readFileSync(new URL(name, import.meta.url), 'utf8');
18
+ return source.replace(/^(?<declaration>import[^\n]+from )'(?<path>\.\.\/[^']+)'/gmu, (_match, declaration, path) => {
19
+ return `${declaration}'./${basename(path)}'`;
20
+ });
21
+ }
22
+
23
+ /** Build a self-contained controller for images that may have an older runtime. */
24
+ export function reconciliationBundle(rules, { apply = false, catalogSecret, port = '8091', delayMs = '60000' } = {}) {
25
+ const files = Object.fromEntries(modules.map((name) => { return [basename(name), mountedSource(name)]; }));
26
+ files['rules.json'] = typeof rules === 'string' ? rules : JSON.stringify(rules);
27
+ return { catalogSecret, port, delayMs, apply: String(apply === true || apply === 'true'), files };
28
+ }
@@ -0,0 +1,24 @@
1
+ import { admitWriter } from './supervisorReplica.js';
2
+
3
+ /** The epoch the quorum granted this receiver. Never a second hardcoded leader. */
4
+ export function grantedEpoch(value) {
5
+ const epoch = Number(value);
6
+ if (!Number.isSafeInteger(epoch) || epoch < 1) {
7
+ throw new TypeError(`Writer epoch must be positive, message ${value}`);
8
+ }
9
+ return epoch;
10
+ }
11
+
12
+ /** Publish only when admitWriter accepts the body. */
13
+ export default function segmentAdmit(currentEpoch, publish) {
14
+ if (typeof publish !== 'function') { throw new TypeError('Segment publish port required'); }
15
+ const epoch = grantedEpoch(currentEpoch);
16
+ return async function accept(message) {
17
+ const decision = admitWriter(message, epoch);
18
+ if (decision.admitted) {
19
+ await publish(decision.body);
20
+ return { applied: true };
21
+ }
22
+ return { applied: false };
23
+ };
24
+ }
@@ -0,0 +1,27 @@
1
+ import amqp from 'amqplib';
2
+
3
+ /** Durable confirm publisher for admitted segment bodies. */
4
+ export default function segmentPublish(url, queue) {
5
+ if (typeof url !== 'string' || url.length === 0 || typeof queue !== 'string' || queue.length === 0) {
6
+ throw new TypeError('Segment admit destination required');
7
+ }
8
+ let channel = null;
9
+ return {
10
+ async start() {
11
+ const connection = await amqp.connect(url);
12
+ const confirmed = await connection.createConfirmChannel();
13
+ await confirmed.assertQueue(queue, { durable: true });
14
+ channel = confirmed;
15
+ },
16
+ write(body) {
17
+ const payload = Buffer.from(JSON.stringify(body));
18
+ const current = channel;
19
+ return new Promise((resolve, reject) => {
20
+ current.sendToQueue(queue, payload, { persistent: true }, (error) => {
21
+ if (error) { reject(error); return; }
22
+ resolve();
23
+ });
24
+ });
25
+ }
26
+ };
27
+ }
@@ -0,0 +1,36 @@
1
+ /** True only for the epoch the quorum currently grants. */
2
+ export function acceptEpoch(messageEpoch, currentEpoch) {
3
+ if (!Number.isSafeInteger(messageEpoch) || !Number.isSafeInteger(currentEpoch) || messageEpoch < 1 || currentEpoch < 1) {
4
+ throw new TypeError(`Writer epoch must be positive, message ${messageEpoch} current ${currentEpoch}`);
5
+ }
6
+ return messageEpoch === currentEpoch;
7
+ }
8
+ /** One Recreate supervisor already owns the machine. A stamped epoch is not a fence. */
9
+ export function admitWriter(message) {
10
+ const body = typeof message === 'string' ? JSON.parse(message) : message;
11
+ return { admitted: true, body };
12
+ }
13
+ /** Apply one replica body through the matching history port. */
14
+ export async function applyReplica(message, currentEpoch, ports) {
15
+ const decision = admitWriter(message, currentEpoch);
16
+ if (!decision.admitted) { return { applied: false }; }
17
+ const { body } = decision;
18
+ if (body.type === 'segment') { await ports.segments(body); return { applied: true }; }
19
+ if (body.type === 'observations') { await ports.observations(body); return { applied: true }; }
20
+ throw new TypeError(`Replica message ${body.type} is not defined`);
21
+ }
22
+ /** The standby may classify only after its telemetry covers the replicated segment. */
23
+ export function readyToLead(observationMs, segmentEndMs) {
24
+ if (!Number.isSafeInteger(observationMs) || !Number.isSafeInteger(segmentEndMs) || observationMs < 0 || segmentEndMs < 0) {
25
+ throw new TypeError(`Replica watermarks must be non-negative integers, telemetry ${observationMs} segment ${segmentEndMs}`);
26
+ }
27
+ return observationMs >= segmentEndMs;
28
+ }
29
+ /** True when a restored home has live observations covering a real replicated segment. */
30
+ export function restored(mark, now, timing) {
31
+ if (!Number.isSafeInteger(mark?.observationMs) || !Number.isSafeInteger(mark?.segmentEndMs) || mark.observationMs < 0 || mark.segmentEndMs < 0) {
32
+ throw new TypeError(`Replica watermarks must be non-negative integers, telemetry ${mark?.observationMs} segment ${mark?.segmentEndMs}`);
33
+ }
34
+ return mark.segmentEndMs > 0 && mark.observationMs + timing.replacementDelayMs >= mark.segmentEndMs
35
+ && Number.isFinite(now) && mark.observationMs <= now + timing.clockSkewMs && now - mark.observationMs <= timing.replacementDelayMs;
36
+ }
@@ -1,5 +1,5 @@
1
1
  export { collectorDeployment, deploymentContext, peerNodePort, retiredDeployments, stageFor } from '../../application/deploy/deploymentPlan.js';
2
- export { collectorControlDeployment, collectorMemoryDeployment, withCollectorScratch, deploymentResources, etcdMembership, versionedControlCatalog } from '../../application/deploy/controlPlan.js';
2
+ export { applyControlCollector, collectorControlDeployment, collectorMemoryDeployment, withCollectorScratch, deploymentResources, etcdMembership, versionedControlCatalog } from '../../application/deploy/controlPlan.js';
3
3
  export { default as executeStagedDeployment } from './executeStagedDeployment.js';
4
4
  export { default as executeChartDeployment } from './executeChartDeployment.js';
5
5
  export { requireWorkloadEnvironment, validateDeploymentEvidence, verifyPostgresReadiness, waitForJob } from './deploymentChecks.js';
@@ -28,9 +28,53 @@ export { default as preflightKubeStorage } from './preflightKubeStorage.js';
28
28
  export { default as applyWhenChanged } from './applyWhenChanged.js';
29
29
  export { default as prepareKubePrerequisites } from './prepareKubePrerequisites.js';
30
30
  export { default as readDeploymentDocument } from '../../application/deploy/readDeploymentDocument.js';
31
- export { appendReplicaTopology, replicaShovels } from './brokerReplicaTopology.js';
31
+ export { appendReplicaTopology, replicaShovels, brokerReplicaPlan, appendBrokerReplicas } from './brokerReplicaTopology.js';
32
32
  export { default as compileDeploymentHooks } from './compileDeploymentHooks.js';
33
33
  export { default as stagedStoragePreflight } from './stagedStoragePreflight.js';
34
34
  export { default as validateStagedDeploymentEvidence } from './validateStagedDeploymentEvidence.js';
35
35
  export { default as controlPlacement } from '../../application/deploy/controlPlacement.js';
36
36
  export { default as buildDeploymentStages } from './buildDeploymentStages.js';
37
+ export { default as projectTopology } from '../../application/deploy/projectTopology.js';
38
+ export { default as controlPlaneConfiguration, migrationMode } from '../../application/deploy/controlPlaneConfiguration.js';
39
+ export { default as clickhouseTelemetryPolicy } from './clickhouseTelemetryPolicy.js';
40
+ export { default as compileControlCatalog, matchesDeviceInput, scopeControlSecrets } from '../../application/deploy/compileControlCatalog.js';
41
+ export { default as projectControlPlane } from '../../application/deploy/projectControlPlane.js';
42
+ export { brokerUri, brokerEndpoint, attachBrokerMesh, brokerStreamRoutes, brokerStreamBindings, brokerStreams, brokerPeerOutboxes, brokerOutboxes, brokerShovel, appendBrokerResources, brokerSinkOptions } from './brokerTopology.js';
43
+ export { default as deploymentTemplate } from './deploymentTemplate.js';
44
+ export { default as deploymentRecovery } from './deploymentRecovery.js';
45
+ export { default as kioskDeployment } from '../management/kiosk/kioskDeployment.js';
46
+ export { default as compileCollectorTasks, portableCollectorSpec } from '../../application/deploy/compileCollectorTasks.js';
47
+ export { default as projectOpcuaSources } from '../opcua/projectSources.js';
48
+ export { default as controlReaderSpec } from '../../application/deploy/controlReaderSpecs.js';
49
+ export { default as projectClassification } from './projectClassification.js';
50
+ export { databaseEnvironment, databaseSecurity, databaseValues } from './databaseSecurity.js';
51
+ export { brokerPolicy } from './securityPolicy.js';
52
+ export { brokerClientEnvironment, brokerManagement, brokerUri as credentialedBrokerUri, secureBrokerDefinitions, secureBrokerValues } from './brokerSecurity.js';
53
+ export { default as readBrokerSecurityFile, readDeployedBrokerSecurity } from './brokerSecurityInput.js';
54
+ export { default as executeManagedDeployment } from './executeManagedDeployment.js';
55
+ export { liveChartValues, liveChartApps } from '../../application/deploy/liveReleaseOverlay.js';
56
+ export { default as executeConfiguredChartDeployment } from './executeConfiguredChartDeployment.js';
57
+ export { default as configuredHistorySeed } from './configuredHistorySeed.js';
58
+ export { centralTelemetryValues, centralTelemetryChartEnv, centralTelemetryEnvironment, centralTelemetryTasks } from './centralTelemetry.js';
59
+ export { collectorCommand, collectorPublisherCommand, collectorConsumerTasks, collectorDeviceAssignments, collectorSourceProcesses, mapCollectorRelease, parseSerialSource } from '../../application/deploy/collectorSourcePlan.js';
60
+ export { default as collectorChartPlan } from './collectorChartPlan.js';
61
+ export { default as configuredPostgresMaintenance } from './configuredPostgresMaintenance.js';
62
+ export { default as brokerFleetPolicy } from './brokerFleetPolicy.js';
63
+ export { publisherBrokerDefinitions, subscriberBrokerDefinitions } from './siteBrokerDefinitions.js';
64
+ export { projectRegisterMaps, sharedRegisterBus, rawSerialDeviceList, databaseSourceGroups } from '../../application/deploy/fieldbusSourcePlan.js';
65
+ export { default as stagedSitePlan } from './stagedSitePlan.js';
66
+ export { default as topologyGraph } from '../../application/deploy/topologyGraph.js';
67
+ export { default as edgeDescriptors } from '../../application/deploy/edgeDescriptors.js';
68
+ export { default as configuredControlPlane } from './configuredControlPlane.js';
69
+ export { standbySupervisor, supervisedServicePlan } from './supervisedServicePlan.js';
70
+ export { default as configuredStagedDeployment } from './configuredStagedDeployment.js';
71
+ export { default as publicBrokerPlan } from './publicBrokerPlan.js';
72
+ export { default as plantBindingProfile } from '../../application/deploy/plantBindingProfile.js';
73
+ export { default as configuredDeploymentCredentials } from './configuredDeploymentCredentials.js';
74
+ export { default as mixedStoreHistory } from './mixedStoreHistory.js';
75
+ export { default as configuredRuntimeCapabilities } from './configuredRuntimeCapabilities.js';
76
+ export { classificationEnvironment, configuredClassification, configuredSupervisor } from './configuredClassification.js';
77
+ export { default as configuredArchivePlan } from './configuredArchivePlan.js';
78
+ export { default as configuredEtcdInventory } from './configuredEtcdInventory.js';
79
+ export { configuredSiteAssets } from './configuredSiteAssets.js';
80
+ export { default as configuredBrokerRoutes } from './configuredBrokerRoutes.js';