@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.
- package/index.js +14 -2
- package/package.json +5 -2
- package/src/application/cycleTimelineFetch.js +56 -0
- package/src/application/deploy/collectorSourcePlan.js +97 -0
- package/src/application/deploy/compileCollectorTasks.js +31 -0
- package/src/application/deploy/compileControlCatalog.js +66 -0
- package/src/application/deploy/controlPlan.js +16 -0
- package/src/application/deploy/controlPlaneConfiguration.js +62 -0
- package/src/application/deploy/controlReaderSpecs.js +37 -0
- package/src/application/deploy/edgeDescriptors.js +31 -0
- package/src/application/deploy/fieldbusSourcePlan.js +79 -0
- package/src/application/deploy/liveReleaseOverlay.js +17 -0
- package/src/application/deploy/plantBindingProfile.js +24 -0
- package/src/application/deploy/projectControlPlane.js +48 -0
- package/src/application/deploy/projectTopology.js +41 -0
- package/src/application/deploy/topologyGraph.js +81 -0
- package/src/application/edgeOperatorCatalog.js +9 -7
- package/src/application/mcp/analyticsMcpPort.js +20 -0
- package/src/application/mcp/analyticsNamespaceNodes.js +29 -0
- package/src/application/mcp/analyticsTextContent.js +13 -0
- package/src/application/mcp/plantReadPorts.js +168 -0
- package/src/application/mcp/textContentCatalog.js +7 -0
- package/src/application/operationPrefixes.js +67 -0
- package/src/application/operatorCatalogView.js +8 -0
- package/src/application/projectPlantShops.js +17 -0
- package/src/application/runtime/collectorDslManifest.js +44 -0
- package/src/application/runtime/collectorLaunch.js +34 -0
- package/src/application/runtime/collectorOptions.js +21 -0
- package/src/application/runtime/controlDeliveryEnvironment.js +19 -0
- package/src/application/runtime/embeddedCollectors.js +6 -0
- package/src/application/runtime/index.js +7 -1
- package/src/application/runtime/pagedDelivery.js +87 -0
- package/src/application/runtime/resolveSecrets.js +9 -0
- package/src/application/siteOperatorCatalog.js +8 -7
- package/src/application/siteRuntime/checkpointedOperationPoll.js +77 -0
- package/src/application/siteRuntime/cutoverOperations.js +25 -0
- package/src/application/siteRuntime/databaseMigrations.js +27 -0
- package/src/application/siteRuntime/edgeMetricsStore.js +35 -0
- package/src/application/siteRuntime/history.js +29 -0
- package/src/application/siteRuntime/index.js +16 -0
- package/src/application/siteRuntime/measurementTopic.js +9 -0
- package/src/application/siteRuntime/operationFederation.js +15 -0
- package/src/application/siteRuntime/operationSnapshot.js +18 -0
- package/src/application/siteRuntime/operatorField.js +49 -0
- package/src/application/siteRuntime/operatorUpdates.js +37 -0
- package/src/application/siteRuntime/telemetry.js +31 -0
- package/src/application/siteRuntime/telemetryBackfillCommand.js +64 -0
- package/src/application/timelineMetrics.js +36 -0
- package/src/domain/timeline/cyclePhases.js +191 -0
- package/src/infrastructure/deploy/brokerFleetPolicy.js +91 -0
- package/src/infrastructure/deploy/brokerReplicaTopology.js +34 -12
- package/src/infrastructure/deploy/brokerSecurity.js +89 -0
- package/src/infrastructure/deploy/brokerSecurityInput.js +85 -0
- package/src/infrastructure/deploy/brokerTopology.js +125 -0
- package/src/infrastructure/deploy/centralTelemetry.js +51 -0
- package/src/infrastructure/deploy/clickhouseTelemetryPolicy.js +64 -0
- package/src/infrastructure/deploy/collectorChartPlan.js +68 -0
- package/src/infrastructure/deploy/configuredArchivePlan.js +25 -0
- package/src/infrastructure/deploy/configuredBrokerRoutes.js +34 -0
- package/src/infrastructure/deploy/configuredClassification.js +74 -0
- package/src/infrastructure/deploy/configuredControlPlane.js +116 -0
- package/src/infrastructure/deploy/configuredDeploymentCredentials.js +45 -0
- package/src/infrastructure/deploy/configuredEtcdInventory.js +30 -0
- package/src/infrastructure/deploy/configuredHistorySeed.js +54 -0
- package/src/infrastructure/deploy/configuredPostgresMaintenance.js +23 -0
- package/src/infrastructure/deploy/configuredRuntimeCapabilities.js +14 -0
- package/src/infrastructure/deploy/configuredSiteAssets.js +50 -0
- package/src/infrastructure/deploy/configuredStagedDeployment.js +48 -0
- package/src/infrastructure/deploy/databaseSecurity.js +39 -0
- package/src/infrastructure/deploy/deploymentRecovery.js +49 -0
- package/src/infrastructure/deploy/deploymentTemplate.js +67 -0
- package/src/infrastructure/deploy/executeConfiguredChartDeployment.js +65 -0
- package/src/infrastructure/deploy/executeManagedDeployment.js +46 -0
- package/src/infrastructure/deploy/highAvailability/brokerOwnership.js +19 -0
- package/src/infrastructure/deploy/highAvailability/catalogReconciler.js +61 -0
- package/src/infrastructure/deploy/highAvailability/classifyFederation.js +57 -0
- package/src/infrastructure/deploy/highAvailability/classifyGate.js +114 -0
- package/src/infrastructure/deploy/highAvailability/classifyLoop.js +139 -0
- package/src/infrastructure/deploy/highAvailability/classifyShovels.js +70 -0
- package/src/infrastructure/deploy/highAvailability/classifyWatermark.js +45 -0
- package/src/infrastructure/deploy/highAvailability/compileClassifierRules.js +21 -0
- package/src/infrastructure/deploy/highAvailability/configuredBrokerReconciliation.js +21 -0
- package/src/infrastructure/deploy/highAvailability/controllerReconcile.js +14 -0
- package/src/infrastructure/deploy/highAvailability/historyReceiver.js +49 -0
- package/src/infrastructure/deploy/highAvailability/historyWatermark.js +42 -0
- package/src/infrastructure/deploy/highAvailability/index.js +15 -0
- package/src/infrastructure/deploy/highAvailability/reconcileBrokerThroughController.js +18 -0
- package/src/infrastructure/deploy/highAvailability/reconciliationBundle.js +28 -0
- package/src/infrastructure/deploy/highAvailability/segmentAdmit.js +24 -0
- package/src/infrastructure/deploy/highAvailability/segmentPublish.js +27 -0
- package/src/infrastructure/deploy/highAvailability/supervisorReplica.js +36 -0
- package/src/infrastructure/deploy/index.js +46 -2
- package/src/infrastructure/deploy/mixedStoreHistory.js +27 -0
- package/src/infrastructure/deploy/projectClassification.js +42 -0
- package/src/infrastructure/deploy/publicBrokerPlan.js +15 -0
- package/src/infrastructure/deploy/securityPolicy.js +16 -0
- package/src/infrastructure/deploy/siteBrokerDefinitions.js +97 -0
- package/src/infrastructure/deploy/stagedSitePlan.js +132 -0
- package/src/infrastructure/deploy/supervisedServicePlan.js +82 -0
- package/src/infrastructure/http/edge/attachClassify.js +30 -0
- package/src/infrastructure/http/edge/classifyProxy.js +72 -0
- package/src/infrastructure/http/edge/classifyRecord.js +32 -0
- package/src/infrastructure/http/edge/classifyRouting.js +14 -0
- package/src/infrastructure/http/edge/siteAccess.js +7 -0
- package/src/infrastructure/http/edge/writeGuard.js +84 -0
- package/src/infrastructure/http/plant/routes/machineOperationList.js +18 -0
- package/src/infrastructure/http/plant/routes/operationRoute.js +2 -11
- package/src/infrastructure/http/plant/routes/operatorRoute.js +25 -0
- package/src/infrastructure/http/plant/streams/operationStream.js +25 -37
- package/src/infrastructure/ingest/mqtt/modbusDeviceSpec.js +5 -28
- package/src/infrastructure/ingest/mqtt/registerPoint.js +2 -2
- package/src/infrastructure/ingest/telemetry/centralPolicy.js +29 -8
- package/src/infrastructure/management/kiosk/kioskDeployment.js +60 -0
- package/src/infrastructure/mdmesh/adminReconciliation.js +19 -0
- package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +47 -0
- package/src/infrastructure/mdmesh/controllerOperation.js +17 -0
- package/src/infrastructure/mdmesh/index.js +5 -0
- package/src/infrastructure/mdmesh/mdmeshServerRelease.js +58 -0
- package/src/infrastructure/mdmesh/publishApk.js +30 -0
- package/src/infrastructure/messaging/rabbitmq/definitions.js +12 -6
- package/src/infrastructure/opcua/projectSources.js +36 -0
- package/src/infrastructure/persistence/clickhouse/metricBursts.js +73 -0
- package/src/infrastructure/persistence/pg/cyclePhaseQuery.js +168 -0
- package/src/infrastructure/persistence/pg/cyclePrior.js +96 -0
- package/src/infrastructure/persistence/pg/operatorFieldStore.js +50 -0
- package/src/infrastructure/streams/boundedTextFrames.js +27 -0
- package/src/infrastructure/streams/framedSerialSource.js +25 -0
- package/src/infrastructure/streams/index.js +5 -0
- package/src/infrastructure/streams/namedSerialDevices.js +26 -0
- package/src/infrastructure/streams/serialLine.js +26 -0
- package/src/infrastructure/streams/watchCurrentReading.js +31 -0
- package/src/infrastructure/streams/windowPublication.js +73 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Returns epoch ms for a tagged row used in phase lookup.
|
|
3
|
+
*
|
|
4
|
+
* @param {object} item - row with start, start_time, or startTime
|
|
5
|
+
* @returns {number} epoch milliseconds
|
|
6
|
+
*/
|
|
7
|
+
function startOf(item) {
|
|
8
|
+
const raw = item.start || item.start_time || item.startTime;
|
|
9
|
+
if (raw instanceof Date) {
|
|
10
|
+
return raw.getTime();
|
|
11
|
+
}
|
|
12
|
+
return new Date(raw).getTime();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Normalizes stored tags to an id list.
|
|
17
|
+
*
|
|
18
|
+
* @param {object} item - row with tags array or JSON string
|
|
19
|
+
* @returns {Array<string>} tag ids
|
|
20
|
+
*/
|
|
21
|
+
function tagList(item) {
|
|
22
|
+
const raw = item.tags;
|
|
23
|
+
if (Array.isArray(raw)) {
|
|
24
|
+
return raw;
|
|
25
|
+
}
|
|
26
|
+
if (typeof raw === 'string' && raw.length > 0) {
|
|
27
|
+
return JSON.parse(raw);
|
|
28
|
+
}
|
|
29
|
+
return [];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Finds the last index matching pred, or -1.
|
|
34
|
+
*
|
|
35
|
+
* @param {Array<string>} tags - chronological tag ids
|
|
36
|
+
* @param {function} match - predicate
|
|
37
|
+
* @returns {number} last matching index
|
|
38
|
+
*/
|
|
39
|
+
function lastIndex(tags, match) {
|
|
40
|
+
for (let i = tags.length - 1; i >= 0; i -= 1) {
|
|
41
|
+
if (match(tags[i])) {
|
|
42
|
+
return i;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return -1;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Finds the most recent declared phase entry after a cycle start.
|
|
50
|
+
*
|
|
51
|
+
* @param {Array<string>} after - tags after the last start anchor
|
|
52
|
+
* @param {object} idle - idle block
|
|
53
|
+
* @param {Array<object>} blocks - all phase blocks
|
|
54
|
+
* @param {string} start - start anchor id
|
|
55
|
+
* @returns {object} matching phase block
|
|
56
|
+
*/
|
|
57
|
+
function entered(after, idle, blocks, start) {
|
|
58
|
+
const last = [...after].reverse().find((id) => {
|
|
59
|
+
return blocks.some((block) => {
|
|
60
|
+
return block.enter === id;
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
if (!last) {
|
|
64
|
+
return blocks.find((block) => {
|
|
65
|
+
return block.enter === start;
|
|
66
|
+
}) || idle;
|
|
67
|
+
}
|
|
68
|
+
return blocks.find((block) => {
|
|
69
|
+
return block.enter === last;
|
|
70
|
+
}) || idle;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Resolves the open cycle phase from earlier tagged segments.
|
|
75
|
+
*
|
|
76
|
+
* @param {Array<object>} others - earlier rows
|
|
77
|
+
* @param {object} anchors - start and stops
|
|
78
|
+
* @param {Array<object>} blocks - phase blocks
|
|
79
|
+
* @returns {object} current phase block
|
|
80
|
+
*/
|
|
81
|
+
function phaseOf(others, anchors, blocks) {
|
|
82
|
+
const idle = blocks.find((block) => {
|
|
83
|
+
return !block.enter;
|
|
84
|
+
}) || { allow: [] };
|
|
85
|
+
const tags = others.slice().sort((left, right) => {
|
|
86
|
+
return startOf(left) - startOf(right);
|
|
87
|
+
}).flatMap(tagList);
|
|
88
|
+
const lastStop = lastIndex(tags, (id) => {
|
|
89
|
+
return anchors.stops.includes(id);
|
|
90
|
+
});
|
|
91
|
+
const lastStart = lastIndex(tags, (id) => {
|
|
92
|
+
return id === anchors.start;
|
|
93
|
+
});
|
|
94
|
+
if (lastStart < 0 || lastStart < lastStop) {
|
|
95
|
+
return idle;
|
|
96
|
+
}
|
|
97
|
+
return entered(tags.slice(lastStart + 1), idle, blocks, anchors.start);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Allow list of one phase block.
|
|
102
|
+
*
|
|
103
|
+
* @param {Array<string>} flat - tag ids in display order
|
|
104
|
+
* @param {object} block - phase block
|
|
105
|
+
* @returns {Array<string>} allowed tag ids
|
|
106
|
+
*/
|
|
107
|
+
function allowOf(flat, block) {
|
|
108
|
+
const allowed = new Set((block || { allow: [] }).allow);
|
|
109
|
+
return flat.filter((id) => {
|
|
110
|
+
return allowed.has(id);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Allow list for a phase id returned by the database.
|
|
116
|
+
*
|
|
117
|
+
* @param {Array<string>} flat - tag ids in display order
|
|
118
|
+
* @param {Array<object>} blocks - phase blocks
|
|
119
|
+
* @param {string} key - phase id
|
|
120
|
+
* @returns {Array<string>} allowed tag ids
|
|
121
|
+
*/
|
|
122
|
+
function paintOf(flat, blocks, key) {
|
|
123
|
+
const named = blocks.find((item) => {
|
|
124
|
+
return item.enter === key;
|
|
125
|
+
});
|
|
126
|
+
const idle = blocks.find((item) => {
|
|
127
|
+
return !item.enter;
|
|
128
|
+
});
|
|
129
|
+
return allowOf(flat, named || idle);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Phase id at one instant, for tests and fakes.
|
|
134
|
+
*
|
|
135
|
+
* @param {object} anchors - start id and stop ids
|
|
136
|
+
* @param {Array<object>} blocks - phase blocks
|
|
137
|
+
* @param {Array<object>} rows - earlier rows plus the window
|
|
138
|
+
* @param {Date|string|number} at - instant
|
|
139
|
+
* @returns {string} phase id
|
|
140
|
+
*/
|
|
141
|
+
function keyOf(anchors, blocks, rows, at) {
|
|
142
|
+
const moment = at instanceof Date ? at.getTime() : new Date(at).getTime();
|
|
143
|
+
const others = rows.filter((item) => {
|
|
144
|
+
return startOf(item) < moment;
|
|
145
|
+
});
|
|
146
|
+
return phaseOf(others, anchors, blocks).enter || 'idle';
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Resolve cycle phase and allowed tags from declared anchors and phase blocks.
|
|
151
|
+
*
|
|
152
|
+
* @param {object} config - ordered display tags, anchors and phase blocks
|
|
153
|
+
* @returns {object} options, accept, narrow, paint, key
|
|
154
|
+
*
|
|
155
|
+
* @example
|
|
156
|
+
* cyclePhases(config).options([])
|
|
157
|
+
*/
|
|
158
|
+
export default function cyclePhases(config) {
|
|
159
|
+
const { flat, anchors, blocks } = config;
|
|
160
|
+
function options(others) {
|
|
161
|
+
return allowOf(flat, phaseOf(others, anchors, blocks));
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
enters: blocks.flatMap((block) => {
|
|
165
|
+
return block.enter ? [block.enter] : [];
|
|
166
|
+
}),
|
|
167
|
+
options,
|
|
168
|
+
paint(key) {
|
|
169
|
+
return paintOf(flat, blocks, key);
|
|
170
|
+
},
|
|
171
|
+
key(rows, at) {
|
|
172
|
+
return keyOf(anchors, blocks, rows, at);
|
|
173
|
+
},
|
|
174
|
+
accept(others, standing, tags) {
|
|
175
|
+
const ok = new Set([...options(others), ...standing]);
|
|
176
|
+
return tags.every((id) => {
|
|
177
|
+
return ok.has(id);
|
|
178
|
+
});
|
|
179
|
+
},
|
|
180
|
+
narrow(row, all) {
|
|
181
|
+
if (row.name !== 'off') {
|
|
182
|
+
return row;
|
|
183
|
+
}
|
|
184
|
+
const own = startOf(row);
|
|
185
|
+
const others = all.filter((item) => {
|
|
186
|
+
return startOf(item) < own;
|
|
187
|
+
});
|
|
188
|
+
return { ...row, options: options(others) };
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { appendBrokerReplicas, brokerReplicaPlan } from './brokerReplicaTopology.js';
|
|
2
|
+
import { attachBrokerMesh, brokerEndpoint } from './brokerTopology.js';
|
|
3
|
+
import deploymentTemplate from './deploymentTemplate.js';
|
|
4
|
+
|
|
5
|
+
function pairsFor(machines, rules) {
|
|
6
|
+
return rules.flatMap((rule) => {
|
|
7
|
+
const rows = machines.filter(({ kind }) => { return kind === rule.kind; });
|
|
8
|
+
const homes = rows.map((row) => { return deploymentTemplate(rule.leader, row); });
|
|
9
|
+
return rows.map(({ id: machine }, index) => {
|
|
10
|
+
return { machine, leader: homes[index], standby: rule.standby ?? homes[(index + 1) % homes.length] };
|
|
11
|
+
});
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function streamPolicy(policy, machine, forwardOutbox) {
|
|
16
|
+
const rule = policy.streams.find(({ prefix }) => { return machine.startsWith(prefix); }) ?? policy.defaultStreams;
|
|
17
|
+
return deploymentTemplate(rule.templates, { machine, suffix: machine.slice(rule.prefix?.length ?? 0), forwardOutbox });
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function landingBindings(result, machine, exchange, policy) {
|
|
21
|
+
const rule = policy.restoreBindings;
|
|
22
|
+
if (!rule || !machine.startsWith(rule.prefix)) { return []; }
|
|
23
|
+
const queue = deploymentTemplate(rule.queue, { machine });
|
|
24
|
+
const live = result.bindings.find(({ source, destination, routing_key: key }) => {
|
|
25
|
+
return source === rule.source && destination === queue && key.endsWith(rule.keySuffix);
|
|
26
|
+
});
|
|
27
|
+
return live ? rule.metrics.map((metric) => {
|
|
28
|
+
return { source: exchange, destination: queue, key: live.routing_key.replace('*', metric) };
|
|
29
|
+
}) : [];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function attachReplicas(policy, pairs, document, node, result) {
|
|
33
|
+
if (document.edgeControlPlane?.historyEnabled !== true) { return result; }
|
|
34
|
+
const { brokerService, writerEpoch: epoch } = document.edgeControlPlane;
|
|
35
|
+
const options = { ...policy.access, fallbackPort: brokerService.nodePort };
|
|
36
|
+
const ids = new Set(pairs.flatMap(({ leader, standby }) => { return [leader, standby]; }));
|
|
37
|
+
const brokers = Object.fromEntries([...ids].map((id) => { return [id, brokerEndpoint(document, id, options)]; }));
|
|
38
|
+
const replicas = pairs.map((pair) => {
|
|
39
|
+
const streams = streamPolicy(policy, pair.machine, true);
|
|
40
|
+
const telemetry = streams.find(({ landing }) => { return landing; });
|
|
41
|
+
const { exchange } = telemetry.restore;
|
|
42
|
+
return { ...pair, epoch, streams, landings: [{ exchange, queue: telemetry.landing, keys: ['#'],
|
|
43
|
+
bindings: landingBindings(result, pair.machine, exchange, policy) }] };
|
|
44
|
+
});
|
|
45
|
+
const blocked = brokers[node] && brokerEndpoint(document, policy.archive, options);
|
|
46
|
+
return appendBrokerReplicas(result, { node, brokers, blocked, replicas });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function meshRestriction(rules, policy, node) {
|
|
50
|
+
const home = rules.groups.find(({ history, preference }) => { return history && preference[0] === node; });
|
|
51
|
+
const keys = home?.keys.filter((key) => { return policy.restrictPrefixes.some((prefix) => { return key.startsWith(prefix); }); });
|
|
52
|
+
return keys && { queue: policy.restrictQueue, keys: Object.fromEntries(keys.map((key) => {
|
|
53
|
+
return [`${key.split('.')[0]}.#`, key];
|
|
54
|
+
})) };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Compile replica streams and peer mesh from the installation's topology and broker declarations. */
|
|
58
|
+
export default function brokerFleetPolicy(policy, { machines, classifierRules: rules, federation }) {
|
|
59
|
+
const pairs = pairsFor(machines, policy.pairs);
|
|
60
|
+
const meshIds = Object.freeze([...new Set([
|
|
61
|
+
...rules.groups.filter(({ history }) => { return history; }).flatMap(({ preference }) => { return preference; }),
|
|
62
|
+
...rules.mesh.originCopies,
|
|
63
|
+
...rules.groups.flatMap(({ preference }) => { return preference; })
|
|
64
|
+
])]);
|
|
65
|
+
function replicaPlan({ machine, leader, standby, epoch, brokers, central, forwardOutbox = false }) {
|
|
66
|
+
if (leader === standby) { throw new TypeError(deploymentTemplate(policy.sameTargetError, { machine })); }
|
|
67
|
+
if (!brokers[leader] || !brokers[standby]) { throw new TypeError(deploymentTemplate(policy.missingBrokerError, { machine })); }
|
|
68
|
+
return brokerReplicaPlan({ leader, standby, epoch, brokers, blocked: central,
|
|
69
|
+
exchange: policy.exchange, streams: streamPolicy(policy, machine, forwardOutbox) });
|
|
70
|
+
}
|
|
71
|
+
function edgeReplicas(brokers, central, epoch, forwardOutbox = false) {
|
|
72
|
+
return pairs.map((pair) => { return replicaPlan({ ...pair, epoch, brokers, central, forwardOutbox }); });
|
|
73
|
+
}
|
|
74
|
+
function meshEndpoint(document, node) {
|
|
75
|
+
return brokerEndpoint(document, node, { ...policy.access, ...policy.meshAccess,
|
|
76
|
+
fallbackPort: document.edgeControlPlane?.brokerService?.nodePort ?? policy.meshAccess.fallbackPort });
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
replicaPlan, edgeReplicas, meshEndpoint, meshIds,
|
|
80
|
+
edgePairs() { return pairs.map((pair) => { return { ...pair }; }); },
|
|
81
|
+
fleetFor(nodes, central, epoch) {
|
|
82
|
+
const brokers = Object.fromEntries(nodes.map(({ id, brokerEndpoint: endpoint }) => { return [id, endpoint]; }));
|
|
83
|
+
return edgeReplicas(brokers, central, epoch);
|
|
84
|
+
},
|
|
85
|
+
attachReplicas(document, node, result) { return attachReplicas(policy, pairs, document, node, result); },
|
|
86
|
+
attachTelemetryMesh(document, node, result) {
|
|
87
|
+
return attachBrokerMesh(document, node, result, { peers: meshIds, endpoint: meshEndpoint,
|
|
88
|
+
restrict: meshRestriction(rules, policy, node), federation });
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { acceptEpoch } from './highAvailability/supervisorReplica.js';
|
|
2
|
+
import rabbitmqDefinitions, { brokerShovel } from '../messaging/rabbitmq/definitions.js';
|
|
2
3
|
|
|
3
4
|
function endpoint(value, blockedHost) {
|
|
4
5
|
const url = new URL(value);
|
|
@@ -15,17 +16,9 @@ function shovel(stream, source, target, options, restore) {
|
|
|
15
16
|
const exchange = restore ? stream.restore.exchange : undefined;
|
|
16
17
|
const outbox = stream.forwardOutbox ? queue : stream.queue;
|
|
17
18
|
const landing = restore ? stream.restore.queue : outbox;
|
|
18
|
-
return {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
name: `${stream.name}-to-${target.node}`,
|
|
22
|
-
value: {
|
|
23
|
-
'src-protocol': 'amqp091', 'src-uri': source.uri, 'src-queue': queue,
|
|
24
|
-
'dest-protocol': 'amqp091', 'dest-uri': target.uri,
|
|
25
|
-
...(exchange === undefined ? { 'dest-queue': landing } : { 'dest-exchange': exchange }),
|
|
26
|
-
'reconnect-delay': options.reconnectDelay, 'dest-publish-properties': { delivery_mode: 2 }
|
|
27
|
-
}
|
|
28
|
-
};
|
|
19
|
+
return brokerShovel({ vhost: options.vhost, reconnectDelay: options.reconnectDelay, name: `${stream.name}-to-${target.node}`,
|
|
20
|
+
sourceUri: source.uri, queue, destinationUri: target.uri, exchange,
|
|
21
|
+
destinationQueue: exchange === undefined ? landing : undefined });
|
|
29
22
|
}
|
|
30
23
|
|
|
31
24
|
/** Plan primary-to-standby copies and standby-to-primary restoration for declared streams. */
|
|
@@ -42,6 +35,16 @@ export function replicaShovels({ leader, standby, brokers, blocked, streams, vho
|
|
|
42
35
|
});
|
|
43
36
|
}
|
|
44
37
|
|
|
38
|
+
/** Describe pair ownership, ingest queues and restoration targets for configured streams. */
|
|
39
|
+
export function brokerReplicaPlan({ leader, standby, epoch, brokers, blocked, exchange, streams, vhost, reconnectDelay }) {
|
|
40
|
+
if (!brokers[leader] || !brokers[standby]) { throw new TypeError('Missing replica broker'); }
|
|
41
|
+
if (!acceptEpoch(epoch, epoch)) { throw new TypeError(`Writer epoch must be positive, message ${epoch} current ${epoch}`); }
|
|
42
|
+
const shovels = replicaShovels({ leader, standby, brokers, blocked, streams, vhost, reconnectDelay });
|
|
43
|
+
const ingest = Object.fromEntries(streams.map(({ id, queue }) => { return [id, queue]; }));
|
|
44
|
+
const restore = Object.fromEntries(streams.map(({ id, restore: target }) => { return [id, target.exchange ?? target.queue]; }));
|
|
45
|
+
return { writer: leader, standby, epoch, exchange, shovels, ingest: { node: standby, ...ingest }, restore: { node: leader, ...restore } };
|
|
46
|
+
}
|
|
47
|
+
|
|
45
48
|
function appendDistinct(target, rows) {
|
|
46
49
|
rows.forEach((row) => {
|
|
47
50
|
if (!target.some((item) => { return item.name === row.name && item.vhost === row.vhost; })) {
|
|
@@ -73,3 +76,22 @@ export function appendReplicaTopology(result, { landings = [], copies = [], vhos
|
|
|
73
76
|
});
|
|
74
77
|
return result;
|
|
75
78
|
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
function replicaCopies(replica, { brokers, blocked, vhost, host }) {
|
|
82
|
+
const { shovels } = brokerReplicaPlan({ ...replica, brokers, blocked, vhost });
|
|
83
|
+
return replica.streams.flatMap(({ source, keys }, index) => {
|
|
84
|
+
return shovels.slice(index * 2, index * 2 + 2).filter(({ value }) => {
|
|
85
|
+
return new URL(value['src-uri']).host === host;
|
|
86
|
+
}).map((copy) => { return { shovel: copy, source, keys }; });
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Attach local landings and the copies published by a broker in an ordered fleet. */
|
|
91
|
+
export function appendBrokerReplicas(result, { node, brokers, blocked, replicas, vhost = '/' }) {
|
|
92
|
+
const landings = replicas.filter(({ leader }) => { return leader === node; })
|
|
93
|
+
.flatMap((replica) => { return replica.landings; });
|
|
94
|
+
const host = brokers[node] && new URL(brokers[node]).host;
|
|
95
|
+
const copies = host ? replicas.flatMap((replica) => { return replicaCopies(replica, { brokers, blocked, vhost, host }); }) : [];
|
|
96
|
+
return appendReplicaTopology(result, { landings, copies, vhost });
|
|
97
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
function account(value) {
|
|
4
|
+
if (!value || typeof value.name !== 'string' || !value.name || value.name === 'guest'
|
|
5
|
+
|| typeof value.password !== 'string' || value.password.length < 16) {
|
|
6
|
+
throw new TypeError('Broker credentials require a named non-guest identity and password of at least 16 characters');
|
|
7
|
+
}
|
|
8
|
+
return value;
|
|
9
|
+
}
|
|
10
|
+
/** Preserve encoded vhost/path while replacing, never concatenating, credentials. */
|
|
11
|
+
export function brokerUri(uri, credentials) {
|
|
12
|
+
const target = new URL(uri);
|
|
13
|
+
const { name, password } = account(credentials);
|
|
14
|
+
if (!['amqp:', 'amqps:'].includes(target.protocol)) { throw new TypeError('Expected AMQP broker URI'); }
|
|
15
|
+
target.username = encodeURIComponent(name);
|
|
16
|
+
target.password = encodeURIComponent(password);
|
|
17
|
+
return target.toString();
|
|
18
|
+
}
|
|
19
|
+
function user(credentials, tags) {
|
|
20
|
+
const { name, password, password_hash: passwordHash } = account(credentials);
|
|
21
|
+
// Stable public per-identity salt keeps pure desired-state rendering idempotent.
|
|
22
|
+
// Production passwords must be random; callers may instead supply a precomputed RabbitMQ hash.
|
|
23
|
+
const salt = createHash('sha256').update(name).digest().subarray(0, 4);
|
|
24
|
+
const digest = createHash('sha256').update(salt).update(password).digest();
|
|
25
|
+
return { name, 'password_hash': passwordHash || Buffer.concat([salt, digest]).toString('base64'),
|
|
26
|
+
'hashing_algorithm': 'rabbit_password_hashing_sha256', tags };
|
|
27
|
+
}
|
|
28
|
+
function credential(uri, security) {
|
|
29
|
+
const parsed = new URL(uri);
|
|
30
|
+
const port = parsed.port || (parsed.protocol === 'amqps:' ? '5671' : '5672');
|
|
31
|
+
if (['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname)) { return security.federation; }
|
|
32
|
+
return security.peers?.[`${parsed.hostname}:${port}`];
|
|
33
|
+
}
|
|
34
|
+
function switchShovels(result, security) {
|
|
35
|
+
for (const parameter of result.parameters || []) {
|
|
36
|
+
const fields = [];
|
|
37
|
+
if (parameter.component === 'shovel') { fields.push('src-uri', 'dest-uri'); }
|
|
38
|
+
if (parameter.component === 'federation-upstream') { fields.push('uri'); }
|
|
39
|
+
for (const field of fields) {
|
|
40
|
+
const uri = new URL(parameter.value[field]);
|
|
41
|
+
const credentials = credential(parameter.value[field], security);
|
|
42
|
+
if (!credentials) { throw new TypeError(`Missing peer credentials for ${parameter.component} ${parameter.name || ''}`); }
|
|
43
|
+
parameter.value[field] = brokerUri(uri, credentials);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Credentials enter memory from the deployment's encrypted source; never serialize this into a ConfigMap. */
|
|
48
|
+
// eslint-disable-next-line max-statements -- One staged transformation preserves the complete durable topology.
|
|
49
|
+
export function secureBrokerDefinitions(desired, security, { resources, messaging }) {
|
|
50
|
+
if (!security) { return desired; }
|
|
51
|
+
if (!['prepare', 'switch', 'retire'].includes(security.phase)) { throw new TypeError('Explicit broker migration phase required'); }
|
|
52
|
+
const roles = ['runtime', 'federation', 'maintenance'];
|
|
53
|
+
roles.forEach(role => { return account(security[role]); });
|
|
54
|
+
if (new Set(roles.map(role => { return security[role].name; })).size !== roles.length) { throw new TypeError('Broker role identities must be distinct'); }
|
|
55
|
+
const result = structuredClone(desired);
|
|
56
|
+
const replaced = new Set(roles.map(role => { return security[role].name; }));
|
|
57
|
+
if (security.phase === 'retire') { replaced.add('guest'); }
|
|
58
|
+
result.users = (result.users || []).filter(row => { return !replaced.has(row.name); });
|
|
59
|
+
result.permissions = (result.permissions || []).filter(row => { return !replaced.has(row.user); });
|
|
60
|
+
for (const role of roles) {
|
|
61
|
+
result.users.push(user(security[role], role === 'maintenance' ? ['policymaker'] : []));
|
|
62
|
+
result.permissions.push({ user: security[role].name, vhost: '/', configure: resources, read: messaging, write: messaging });
|
|
63
|
+
}
|
|
64
|
+
if (security.phase !== 'prepare') { switchShovels(result, security); }
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
/** Reconciliation must move to this identity before retiring guest's management access. */
|
|
68
|
+
export function brokerManagement(base, security) {
|
|
69
|
+
const credentials = account(security.maintenance);
|
|
70
|
+
return { base, vhost: '/', username: credentials.name, password: credentials.password };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Requires chart Secret-mount support; no shovel password may enter a ConfigMap. */
|
|
74
|
+
export function secureBrokerValues(values, security, permissions) {
|
|
75
|
+
if (!security) { return values; }
|
|
76
|
+
if (!security.definitionsSecret || !security.runtimeSecret) { throw new TypeError('Broker definitions Secret and runtime Secret required'); }
|
|
77
|
+
return { ...values, definitions: secureBrokerDefinitions(values.definitions, security, permissions), definitionsSecret: security.definitionsSecret,
|
|
78
|
+
podAnnotations: { ...values.podAnnotations, 'scada/broker-security-phase': security.phase },
|
|
79
|
+
...(security.phase !== 'prepare' && { runtimeSecret: security.runtimeSecret }),
|
|
80
|
+
extraConfig: { ...values.extraConfig, ...(security.phase === 'retire' && {
|
|
81
|
+
'mqtt.allow_anonymous': 'false', 'loopback_users.guest': 'true'
|
|
82
|
+
}) } };
|
|
83
|
+
}
|
|
84
|
+
export function brokerClientEnvironment(security) {
|
|
85
|
+
if (!security?.runtimeSecret) { throw new TypeError('Broker runtime Secret required'); }
|
|
86
|
+
return Object.fromEntries(['AMQP_URL', 'MQTT_URL', 'MQTT_USERNAME', 'MQTT_PASSWORD', 'STOMP_LOGIN', 'STOMP_PASSCODE'].map(name => {
|
|
87
|
+
return [name, { valueFrom: { secretKeyRef: { name: security.runtimeSecret, key: name } } }];
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { databaseSecurity } from './databaseSecurity.js';
|
|
3
|
+
import { brokerPolicy } from './securityPolicy.js';
|
|
4
|
+
|
|
5
|
+
/** Deployment supplies an ephemeral 0600 file decrypted from its existing secret store. */
|
|
6
|
+
export default function brokerSecurityInput(path) {
|
|
7
|
+
if (!path) { return undefined; }
|
|
8
|
+
try {
|
|
9
|
+
const metadata = statSync(path);
|
|
10
|
+
// eslint-disable-next-line no-bitwise -- Inspect POSIX group/other permission bits.
|
|
11
|
+
if (!metadata.isFile() || (metadata.mode & 0o077)) { throw new Error(); }
|
|
12
|
+
const security = JSON.parse(readFileSync(path, 'utf8'));
|
|
13
|
+
if (!security || typeof security !== 'object' || Array.isArray(security)) { throw new Error(); }
|
|
14
|
+
brokerPolicy(security);
|
|
15
|
+
return security;
|
|
16
|
+
} catch {
|
|
17
|
+
// Never allow JSON parser diagnostics to echo a secret fragment.
|
|
18
|
+
throw new TypeError('Broker security input must be a valid protected 0600 JSON file');
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const phases = { prepare: 1, switch: 2, retire: 3 };
|
|
23
|
+
function captured(execute, { cluster, namespace }, args) {
|
|
24
|
+
try {
|
|
25
|
+
return String(execute('kubectl', ['--context', cluster, '--namespace', namespace, ...args],
|
|
26
|
+
{ encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }) || '').trim();
|
|
27
|
+
} catch { throw new Error('Cannot verify persisted broker controller state'); }
|
|
28
|
+
}
|
|
29
|
+
function namedBrokerUsers(users, ignorePattern) {
|
|
30
|
+
return users.split('\n').map(row => { return row.trim().split(/\s+/u)[0]; }).filter(name => { return name && name !== 'guest' && !ignorePattern?.test(name); });
|
|
31
|
+
}
|
|
32
|
+
function livePhase(state) {
|
|
33
|
+
const annotations = { ...state.metadata?.annotations, ...state.spec?.template?.metadata?.annotations };
|
|
34
|
+
const recorded = Object.entries(annotations).filter(([name]) => { return name.includes('broker-security-phase'); });
|
|
35
|
+
const volumes = state.spec?.template?.spec?.volumes || [];
|
|
36
|
+
const mounts = (state.spec?.template?.spec?.containers || []).flatMap(row => { return row.volumeMounts || []; });
|
|
37
|
+
const definitions = new Set(mounts.filter(row => { return row.mountPath?.endsWith('/definitions.json'); }).map(row => { return row.name; }));
|
|
38
|
+
const mounted = volumes.some(row => { return row.secret && (definitions.has(row.name) || row.name.includes('definitions')); });
|
|
39
|
+
return Math.max(mounted ? 1 : 0, ...recorded.map(([, phase]) => { return phases[phase] || 0; }));
|
|
40
|
+
}
|
|
41
|
+
function verifyLiveDatabase(state, canonical) {
|
|
42
|
+
const verified = (state.spec?.template?.spec?.containers || []).filter((container) => {
|
|
43
|
+
return (container.env || []).some((field) => { return field.name === 'SUPERVISOR_MIGRATIONS' && field.value === 'verify'; });
|
|
44
|
+
});
|
|
45
|
+
for (const container of verified) {
|
|
46
|
+
const env = Object.fromEntries((container.env || []).map((field) => { return [field.name,field]; }));
|
|
47
|
+
const reference = env.POSTGRES_URL?.valueFrom?.secretKeyRef;
|
|
48
|
+
if (!canonical || !reference || reference.name !== canonical.runtimeSecret || reference.key !== canonical.runtimeKey) {
|
|
49
|
+
throw new Error('Persisted database verification policy missing or mismatched');
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Private reads precede every deploy mutation; render remains strictly offline. */
|
|
55
|
+
// eslint-disable-next-line max-statements -- Resolve persisted credentials and reject downgrade before the first deployment write.
|
|
56
|
+
export function readDeployedBrokerSecurity(action, target, execute, explicit) {
|
|
57
|
+
if (action === 'render') { brokerPolicy(explicit); return explicit; }
|
|
58
|
+
const { controllerSecret, brokerWorkload, applicationWorkload, ignoreUserPrefix, repairMessage } = target;
|
|
59
|
+
try {
|
|
60
|
+
const raw = captured(execute, target, ['get', controllerSecret, '--ignore-not-found', '-o', 'json']);
|
|
61
|
+
const controller = raw ? JSON.parse(Buffer.from(JSON.parse(raw).data['security.json'], 'base64').toString('utf8')) : undefined;
|
|
62
|
+
const workload = captured(execute, target, ['get', brokerWorkload, '--ignore-not-found', '-o', 'json']);
|
|
63
|
+
const state = workload ? JSON.parse(workload) : {};
|
|
64
|
+
const persisted = livePhase(state);
|
|
65
|
+
const security = explicit || controller;
|
|
66
|
+
const broker = brokerPolicy(security);
|
|
67
|
+
const previousBroker = brokerPolicy(controller);
|
|
68
|
+
const previousDatabase = databaseSecurity(controller);
|
|
69
|
+
const application = captured(execute, target, ['get', applicationWorkload, '--ignore-not-found', '-o', 'json']);
|
|
70
|
+
verifyLiveDatabase(application ? JSON.parse(application) : {}, previousDatabase);
|
|
71
|
+
if (previousDatabase && JSON.stringify(previousDatabase) !== JSON.stringify(databaseSecurity(security))) { throw new Error(); }
|
|
72
|
+
if (!previousBroker && persisted) { throw new Error(); }
|
|
73
|
+
const minimum = Math.max(persisted, phases[previousBroker?.phase] || 0);
|
|
74
|
+
if (minimum && !broker) { throw new Error(); }
|
|
75
|
+
if (!previousBroker && workload) {
|
|
76
|
+
const users = captured(execute, target, ['exec', brokerWorkload, '--', 'rabbitmqctl', '-s', 'list_users']);
|
|
77
|
+
if (namedBrokerUsers(users, ignoreUserPrefix).length) { throw new Error(); }
|
|
78
|
+
}
|
|
79
|
+
if (broker && phases[broker.phase] < minimum) { throw new Error(); }
|
|
80
|
+
return security;
|
|
81
|
+
} catch {
|
|
82
|
+
// Captured stdout/stderr, parser errors and decoded JSON must never escape.
|
|
83
|
+
throw new Error(repairMessage ?? 'Broker controller Secret missing, invalid, or migration phase would downgrade');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import subscriptions from '../../application/deploy/subscriptions.js';
|
|
2
|
+
import rabbitmqDefinitions from '../messaging/rabbitmq/definitions.js';
|
|
3
|
+
|
|
4
|
+
export { brokerShovel } from '../messaging/rabbitmq/definitions.js';
|
|
5
|
+
|
|
6
|
+
/** Normalize an AMQP URL with an optional fallback or overriding identity. */
|
|
7
|
+
export function brokerUri(uri, { username, password, override = false } = {}) {
|
|
8
|
+
const parsed = new URL(uri);
|
|
9
|
+
if (username && (override || !parsed.username)) {
|
|
10
|
+
parsed.username = username;
|
|
11
|
+
parsed.password = password;
|
|
12
|
+
}
|
|
13
|
+
return parsed.toString().replace(/\/$/u, '');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Resolve a declared service or a broker NodePort on the host of another service. */
|
|
17
|
+
export function brokerEndpoint(document, node, { service, fallbackService, fallbackPort, identity } = {}) {
|
|
18
|
+
const services = document.servers?.find(({ id }) => { return id === node; })?.api || [];
|
|
19
|
+
const direct = services.find(({ id }) => { return id === service; })?.url;
|
|
20
|
+
if (direct) { return identity ? brokerUri(direct, identity) : direct; }
|
|
21
|
+
const fallback = services.find(({ id }) => { return id === fallbackService; })?.url;
|
|
22
|
+
if (!fallback || !fallbackPort) { throw new TypeError(`Missing broker endpoint for ${node}`); }
|
|
23
|
+
const uri = `amqp://${new URL(fallback).hostname}:${fallbackPort}`;
|
|
24
|
+
return identity ? brokerUri(uri, identity) : uri;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Merge federation resources and restrict bindings to keys published at this node. */
|
|
28
|
+
export function attachBrokerMesh(document, node, topology, { peers, endpoint, federation, restrict }) {
|
|
29
|
+
const present = new Set((document.servers || []).map(({ id }) => { return id; }));
|
|
30
|
+
if (!peers.includes(node) || !present.has(node)) { return topology; }
|
|
31
|
+
const endpoints = Object.fromEntries(peers.filter((id) => { return present.has(id); }).flatMap((id) => {
|
|
32
|
+
try { return [[id, endpoint(document, id)]]; } catch { return []; }
|
|
33
|
+
}));
|
|
34
|
+
const extra = federation(node, endpoints);
|
|
35
|
+
for (const kind of ['parameters', 'policies', 'bindings']) {
|
|
36
|
+
topology[kind] = [...topology[kind] || [], ...extra[kind] || []];
|
|
37
|
+
}
|
|
38
|
+
for (const kind of ['queues', 'exchanges']) {
|
|
39
|
+
const names = new Set((topology[kind] || []).map(({ name }) => { return name; }));
|
|
40
|
+
topology[kind] = [...topology[kind] || [], ...(extra[kind] || []).filter(({ name }) => { return !names.has(name); })];
|
|
41
|
+
}
|
|
42
|
+
if (restrict) {
|
|
43
|
+
topology.bindings = topology.bindings.map((row) => {
|
|
44
|
+
if (row.destination !== restrict.queue || !Object.hasOwn(restrict.keys, row.routing_key)) { return row; }
|
|
45
|
+
return { ...row, routing_key: restrict.keys[row.routing_key] };
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
return topology;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Publishers on an API and physical inputs local to the broker. */
|
|
52
|
+
export function brokerStreamRoutes(source, { service, passive, local }) {
|
|
53
|
+
const publishers = source.api.find(({ id }) => { return id === service; })?.publishes || [];
|
|
54
|
+
return [...publishers.map(passive), ...source.fan_in.filter(({ from }) => { return from.includes('://'); }).map(local)];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Use a family wildcard when every declared route in that family is subscribed. */
|
|
58
|
+
export function brokerStreamBindings(routes, subscribed) {
|
|
59
|
+
const families = new Map();
|
|
60
|
+
routes.forEach((row) => {
|
|
61
|
+
if (!row.family) { return; }
|
|
62
|
+
if (!families.has(row.family)) { families.set(row.family, []); }
|
|
63
|
+
families.get(row.family).push(row);
|
|
64
|
+
});
|
|
65
|
+
return [...new Set([...families].flatMap(([family, rows]) => {
|
|
66
|
+
const selected = rows.filter(({ name }) => { return subscribed.has(name); });
|
|
67
|
+
return selected.length === rows.length ? [`${family}.#`] : selected.flatMap(({ keys }) => { return keys; });
|
|
68
|
+
}))];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Effective physical inputs and subscriptions when one broker also hosts a peer's inputs. */
|
|
72
|
+
export function brokerStreams(document, source, { service, additionalSource }) {
|
|
73
|
+
const additional = additionalSource && document.servers.find(({ id }) => { return id === additionalSource; });
|
|
74
|
+
const host = additional ? { ...source, fan_in: [...source.fan_in,
|
|
75
|
+
...additional.fan_in.filter(({ from }) => { return from.includes('://'); })] } : source;
|
|
76
|
+
const links = [...subscriptions(document, source.id), ...(additional ? subscriptions(document, additional.id) : [])]
|
|
77
|
+
.filter(({ api }) => { return !api || api === service; });
|
|
78
|
+
return {
|
|
79
|
+
host,
|
|
80
|
+
subscriptionsTo(to) {
|
|
81
|
+
return new Set(links.filter((row) => { return row.to === to; }).map(({ name }) => { return name; }));
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** One outbox per route group selected by the downstream subscription. */
|
|
87
|
+
export function brokerPeerOutboxes(peer, routes, subscribed, outbox) {
|
|
88
|
+
const rows = routes.filter(({ peer: group, name }) => { return group && subscribed.has(name); });
|
|
89
|
+
return [...new Set(rows.map(({ peer: group }) => { return group; }))].map((group) => {
|
|
90
|
+
const selected = rows.filter((row) => { return row.peer === group; });
|
|
91
|
+
return { ...outbox(group, peer), keys: [...new Set(selected.flatMap(({ keys }) => { return keys; }))] };
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Durable forwarders to a declared endpoint, skipping families with no subscribed keys. */
|
|
96
|
+
export function brokerOutboxes(families, { sourceUri, destinationUri, reconnectDelay, exchange, destination }) {
|
|
97
|
+
return families.filter(({ keys }) => { return keys.length; }).map(({ family, keys }) => {
|
|
98
|
+
const name = exchange(family);
|
|
99
|
+
return { exchange: name, queue: `${name}.outbox`, keys,
|
|
100
|
+
shovel: { name: `${family.replaceAll('_', '-')}-to-${destination}`, sourceUri, destinationUri,
|
|
101
|
+
destinationExchange: name, reconnectDelay } };
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Add durable queues, typed bindings, and missing topic exchanges to a definition. */
|
|
106
|
+
export function appendBrokerResources(result, { vhost = '/', exchanges = [], queues = [], bindings = [] }) {
|
|
107
|
+
const resources = rabbitmqDefinitions({ vhost, queues, exchanges });
|
|
108
|
+
const names = new Set(result.exchanges.filter((row) => { return row.vhost === vhost; }).map(({ name }) => { return name; }));
|
|
109
|
+
result.exchanges.push(...resources.exchanges.filter(({ name }) => { return !names.has(name); })
|
|
110
|
+
.map((row) => { return { ...row, arguments: {} }; }));
|
|
111
|
+
result.queues.push(...resources.queues);
|
|
112
|
+
result.bindings.push(...bindings.map(({ source, destination, key, type = 'queue' }) => {
|
|
113
|
+
return { source, vhost, destination, destination_type: type, routing_key: key, arguments: {} };
|
|
114
|
+
}));
|
|
115
|
+
return result;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Declare topic exchanges and the queue bindings needed by a collector. */
|
|
119
|
+
export function brokerSinkOptions(broker, exchange) {
|
|
120
|
+
const bindings = broker.bindings.filter(({ source }) => { return source === exchange; });
|
|
121
|
+
const queues = new Set(bindings.map(({ destination }) => { return destination; }));
|
|
122
|
+
return { exchanges: [{ name: exchange, type: 'topic', options: { durable: true } }],
|
|
123
|
+
queues: [...queues].map((name) => { return { name, options: { durable: true, autoDelete: false } }; }),
|
|
124
|
+
bindings: bindings.map(({ destination, source, routing_key: pattern }) => { return { queue: destination, exchange: source, pattern }; }) };
|
|
125
|
+
}
|