@yarkivaev/scada 2.18.0 → 2.20.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 +17 -0
- package/package.json +4 -2
- package/src/application/cycleTimelineFetch.js +56 -0
- package/src/application/deploy/collectorProcesses.js +1 -0
- package/src/application/deploy/collectorSourcePlan.js +41 -0
- package/src/application/deploy/compileCollectorTasks.js +2 -2
- package/src/application/deploy/edgeDescriptors.js +31 -0
- package/src/application/deploy/fieldbusSourcePlan.js +93 -0
- package/src/application/deploy/plantBindingProfile.js +24 -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/domain/timeline/taggedCycleWindows.js +17 -0
- package/src/domain/timeline/taggedSegment.js +47 -0
- package/src/domain/timeline/taggedTimeline.js +98 -0
- package/src/domain/timeline/timelineSegment.js +25 -0
- package/src/infrastructure/deploy/brokerFleetPolicy.js +91 -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/configuredCollectorChartDeployment.js +22 -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/configuredRuntimeCapabilities.js +14 -0
- package/src/infrastructure/deploy/configuredSiteAssets.js +50 -0
- package/src/infrastructure/deploy/configuredStagedDeployment.js +48 -0
- package/src/infrastructure/deploy/controlPlaneCli.js +17 -0
- package/src/infrastructure/deploy/highAvailability/configuredBrokerReconciliation.js +21 -0
- package/src/infrastructure/deploy/highAvailability/historyWatermark.js +2 -2
- package/src/infrastructure/deploy/highAvailability/index.js +3 -1
- package/src/infrastructure/deploy/highAvailability/replicaHistoryStore.js +7 -0
- package/src/infrastructure/deploy/index.js +22 -1
- package/src/infrastructure/deploy/mixedStoreHistory.js +27 -0
- package/src/infrastructure/deploy/publicBrokerPlan.js +15 -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/mdmesh/adminReconciliation.js +19 -0
- package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +4 -4
- package/src/infrastructure/mdmesh/controllerOperation.js +17 -0
- package/src/infrastructure/mdmesh/index.js +3 -0
- package/src/infrastructure/mdmesh/publishApk.js +30 -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 +6 -0
- package/src/infrastructure/streams/namedSerialDevices.js +26 -0
- package/src/infrastructure/streams/pollSnapshot.js +11 -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,48 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import compileDeploymentHooks, { deploymentStage } from './compileDeploymentHooks.js';
|
|
3
|
+
import executeStagedDeployment from './executeStagedDeployment.js';
|
|
4
|
+
import stagedStoragePreflight from './stagedStoragePreflight.js';
|
|
5
|
+
import validateStagedDeploymentEvidence from './validateStagedDeploymentEvidence.js';
|
|
6
|
+
|
|
7
|
+
function registeredHooks(plan, policy, evidence, execute, ports) {
|
|
8
|
+
return compileDeploymentHooks(policy.hooks, { plan, evidence, execute, ports: {
|
|
9
|
+
reconcileBroker(ready, kube, { process, pruneShovels }) {
|
|
10
|
+
const { rabbitmq } = deploymentStage(plan, policy.storage.stage).values;
|
|
11
|
+
const input = { ...ready, brokerReconcileProcess: process, brokerPruneShovels: pruneShovels,
|
|
12
|
+
values: { ...ready.values, rabbitmq } };
|
|
13
|
+
ports.reconcile(input, kube, plan.brokerSecurity, execute);
|
|
14
|
+
}
|
|
15
|
+
} });
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function operations(plan, policy, execute, operate) {
|
|
19
|
+
return Object.fromEntries(Object.entries(policy.operations ?? {}).map(([command, action]) => {
|
|
20
|
+
return [command, () => { return operate(plan.kiosk, action, execute); }];
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Execute isolation and evidence guards around a declared staged deployment. */
|
|
25
|
+
export default function configuredStagedDeployment(policy, ports) {
|
|
26
|
+
return function deploy(cluster, action = 'render', options = {}) {
|
|
27
|
+
const { execute = execFileSync, evidence, document, security: input, now = Date.now(), backendOnly = false } = options;
|
|
28
|
+
if (backendOnly && action.startsWith(policy.backendOnlyActionPrefix)) { throw new Error(policy.backendOnlyError); }
|
|
29
|
+
const plan = ports.plan(cluster, document, input);
|
|
30
|
+
return executeStagedDeployment({
|
|
31
|
+
plan, action,
|
|
32
|
+
disabledActions: plan.deploymentEnabled ? [] : policy.disabledActions,
|
|
33
|
+
omitStages: backendOnly ? policy.backendOnlyOmit : [],
|
|
34
|
+
actions: operations(plan, policy, execute, ports.operate),
|
|
35
|
+
prepare(mode) {
|
|
36
|
+
const security = ports.security(mode, cluster, execute, input);
|
|
37
|
+
const prepared = ports.plan(cluster, document, security);
|
|
38
|
+
return mode === 'render' ? ports.publicOutput(prepared) : prepared;
|
|
39
|
+
},
|
|
40
|
+
validateMutation(current) { validateStagedDeploymentEvidence(current, policy.evidence, evidence, now); },
|
|
41
|
+
preflight(current, mode, mutate) {
|
|
42
|
+
stagedStoragePreflight(current, policy.storage, { evidence: mutate ? evidence : null, execute, action: mode });
|
|
43
|
+
},
|
|
44
|
+
stageHooks(current) { return registeredHooks(current, policy, evidence, execute, ports); },
|
|
45
|
+
afterApply: backendOnly ? undefined : (current) => { return ports.operate(current.kiosk, policy.afterApply, execute); }
|
|
46
|
+
}, execute);
|
|
47
|
+
};
|
|
48
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { writeSync } from 'node:fs';
|
|
2
|
+
import { clientFromEnv, controlStore, publishCatalog } from '../../application/control/index.js';
|
|
3
|
+
import publishControlCatalog from '../../application/control/publishControlCatalog.js';
|
|
4
|
+
import readDeploymentDocument from '../../application/deploy/readDeploymentDocument.js';
|
|
5
|
+
|
|
6
|
+
/** Render or publish the configured control catalog from a deployment document. */
|
|
7
|
+
export default async function controlPlaneCli(planFor, { defaultTarget, defaultFile }, argv = process.argv.slice(2), env = process.env) {
|
|
8
|
+
const [operation = 'plan', target = defaultTarget, file = defaultFile] = argv;
|
|
9
|
+
if (!['plan', 'catalog', 'publish'].includes(operation)) { throw new TypeError('Expected plan, catalog or publish'); }
|
|
10
|
+
const plan = planFor(target, readDeploymentDocument(file));
|
|
11
|
+
let result = operation === 'catalog' ? plan.catalog : plan;
|
|
12
|
+
if (operation === 'publish') {
|
|
13
|
+
const store = controlStore(clientFromEnv(env), env.CONTROL_PREFIX ?? plan.values.prefix);
|
|
14
|
+
result = await publishControlCatalog(plan, store, publishCatalog);
|
|
15
|
+
}
|
|
16
|
+
writeSync(1, `${JSON.stringify(result, null, 2)}\n`);
|
|
17
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -27,8 +27,8 @@ export function watermark(history, pool) {
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
/** GET /v1/history/watermark for the restored home's classify loop. */
|
|
30
|
-
export function watermarkRoute(history) {
|
|
31
|
-
return route('GET',
|
|
30
|
+
export function watermarkRoute(history, basePath = '/v1') {
|
|
31
|
+
return route('GET', `${basePath}/history/watermark`, async (req, res) => {
|
|
32
32
|
jsonResponse(await watermark(history)).send(res);
|
|
33
33
|
});
|
|
34
34
|
}
|
|
@@ -10,5 +10,7 @@ export { reconcileBrokerThroughController } from './reconcileBrokerThroughContro
|
|
|
10
10
|
export { reconciliationBundle } from './reconciliationBundle.js';
|
|
11
11
|
export { acceptEpoch, admitWriter, applyReplica, readyToLead, restored } from './supervisorReplica.js';
|
|
12
12
|
export { default as runHistoryReceiver, segmentCollector } from './historyReceiver.js';
|
|
13
|
-
export { fromPool as replicaWatermarkFromPool, watermark as replicaWatermark } from './historyWatermark.js';
|
|
13
|
+
export { fromPool as replicaWatermarkFromPool, watermark as replicaWatermark, watermarkRoute as replicaWatermarkRoute } from './historyWatermark.js';
|
|
14
14
|
export { default as segmentAdmit, grantedEpoch } from './segmentAdmit.js';
|
|
15
|
+
export { default as configuredBrokerReconciliation } from './configuredBrokerReconciliation.js';
|
|
16
|
+
export { default as replicaHistoryStore } from './replicaHistoryStore.js';
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import historyPg from '../../persistence/pg/history.js';
|
|
2
|
+
import { fromPool } from './historyWatermark.js';
|
|
3
|
+
|
|
4
|
+
/** Attach the replica watermark to the shared history store for a configured receiver. */
|
|
5
|
+
export default function replicaHistoryStore(pool, options) {
|
|
6
|
+
return { ...historyPg(pool, options), watermark() { return fromPool(pool); } };
|
|
7
|
+
}
|
|
@@ -56,6 +56,27 @@ export { liveChartValues, liveChartApps } from '../../application/deploy/liveRel
|
|
|
56
56
|
export { default as executeConfiguredChartDeployment } from './executeConfiguredChartDeployment.js';
|
|
57
57
|
export { default as configuredHistorySeed } from './configuredHistorySeed.js';
|
|
58
58
|
export { centralTelemetryValues, centralTelemetryChartEnv, centralTelemetryEnvironment, centralTelemetryTasks } from './centralTelemetry.js';
|
|
59
|
-
export { collectorCommand, collectorPublisherCommand, collectorConsumerTasks, collectorDeviceAssignments, collectorSourceProcesses, mapCollectorRelease, parseSerialSource } from '../../application/deploy/collectorSourcePlan.js';
|
|
59
|
+
export { collectorCommand, collectorPublisherCommand, collectorConsumerTasks, collectorDeviceAssignments, configuredCollectorAssignments, collectorSourceProcesses, mapCollectorRelease, parseSerialSource } from '../../application/deploy/collectorSourcePlan.js';
|
|
60
60
|
export { default as collectorChartPlan } from './collectorChartPlan.js';
|
|
61
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, rawSerialDevices, 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';
|
|
81
|
+
export { default as controlPlaneCli } from './controlPlaneCli.js';
|
|
82
|
+
export { default as configuredCollectorChartDeployment } from './configuredCollectorChartDeployment.js';
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
function validateSettings(settings, policy) {
|
|
2
|
+
const { rawBackend, stateBackend, errors } = policy;
|
|
3
|
+
if (settings.rawBackend !== rawBackend || settings.stateBackend !== stateBackend) { throw new Error(errors.backends); }
|
|
4
|
+
if (!Number.isSafeInteger(settings.retentionDays) || settings.retentionDays < 1 || settings.retentionDays > 365) {
|
|
5
|
+
throw new Error(errors.retention);
|
|
6
|
+
}
|
|
7
|
+
if (!/^[a-z0-9][a-z0-9.-]*$/u.test(settings.tokenSecret ?? '') || !/^[A-Za-z0-9._-]+$/u.test(settings.tokenKey ?? '')) {
|
|
8
|
+
throw new Error(errors.secret);
|
|
9
|
+
}
|
|
10
|
+
if (!/^(?:\*|\d+(?:[-/,]\d+)*)(?:\s+(?:\*|\d+(?:[-/,]\d+)*)){4}$/u.test(settings.purgeSchedule ?? '')) {
|
|
11
|
+
throw new Error(errors.schedule);
|
|
12
|
+
}
|
|
13
|
+
const missing = policy.roles.find((role) => { return !/^\S+@sha256:[a-f0-9]{64}$/u.test(settings.images?.[role] ?? ''); });
|
|
14
|
+
if (missing) { throw new Error(errors.image.replace('{role}', missing)); }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Verify the declared immutable candidates and retention policy for an optional mixed-store history. */
|
|
18
|
+
export default function mixedStoreHistory(policy) {
|
|
19
|
+
return function normalize(settings = { enabled: false }) {
|
|
20
|
+
if (typeof settings.enabled !== 'boolean') { throw new Error(policy.errors.enabled); }
|
|
21
|
+
if (!settings.enabled) { return { ...settings, enabled: false }; }
|
|
22
|
+
validateSettings(settings, policy);
|
|
23
|
+
const writerEpoch = settings.writerEpoch ?? 1;
|
|
24
|
+
if (!Number.isSafeInteger(writerEpoch) || writerEpoch < 1) { throw new Error(policy.errors.epoch); }
|
|
25
|
+
return { ...settings, protocol: policy.protocol, writerEpoch };
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Public deployment output excludes controller credentials and Secret-backed definitions. */
|
|
2
|
+
export default function publicBrokerPlan(value) {
|
|
3
|
+
if (Array.isArray(value)) { return value.map(publicBrokerPlan); }
|
|
4
|
+
if (!value || typeof value !== 'object') {
|
|
5
|
+
return typeof value === 'string' ? value.replace(/(?<protocol>amqps?|mqtts?|stomps?):\/\/[^@\s"]+@/gu, '$<protocol>://[redacted]@') : value;
|
|
6
|
+
}
|
|
7
|
+
return Object.fromEntries(Object.entries(value).flatMap(([key, entry]) => {
|
|
8
|
+
if (key === 'definitions' && value.definitionsSecret) { return []; }
|
|
9
|
+
if (key === 'brokerSecurity') {
|
|
10
|
+
const { phase, definitionsSecret, runtimeSecret } = entry;
|
|
11
|
+
return [[key, { phase, definitionsSecret, runtimeSecret }]];
|
|
12
|
+
}
|
|
13
|
+
return [[key, publicBrokerPlan(entry)]];
|
|
14
|
+
}));
|
|
15
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import rabbitmqDefinitions from '../messaging/rabbitmq/definitions.js';
|
|
2
|
+
import { appendBrokerResources, brokerEndpoint, brokerOutboxes, brokerPeerOutboxes, brokerShovel, brokerStreamBindings, brokerStreams } from './brokerTopology.js';
|
|
3
|
+
import deploymentTemplate from './deploymentTemplate.js';
|
|
4
|
+
|
|
5
|
+
function archiveOutboxes(document, families, policy, reconnectDelay) {
|
|
6
|
+
const { archive, local, access, exchange } = policy;
|
|
7
|
+
return brokerOutboxes(families, { sourceUri: local, destinationUri: brokerEndpoint(document, archive, access),
|
|
8
|
+
reconnectDelay, destination: archive, exchange(family) { return deploymentTemplate(exchange, { family }); } });
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function publisherKeys(contract, patterns) {
|
|
12
|
+
return contract.publisherContracts ? contract.publisherContracts.map((id) => {
|
|
13
|
+
if (!Object.hasOwn(patterns, id)) { throw new TypeError(`Unknown publisher contract ${id}`); }
|
|
14
|
+
return patterns[id];
|
|
15
|
+
}) : [contract.key];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function inboundShovels(document, server, context, policy) {
|
|
19
|
+
const peers = server.fan_in.filter(({ from }) => { return from === policy.peerSource; });
|
|
20
|
+
const sourceUri = brokerEndpoint(document, policy.peerSource, policy.access);
|
|
21
|
+
return policy.inbound.filter(({ suffix }) => {
|
|
22
|
+
return peers.some(({ name }) => { return name.endsWith(`/${suffix}`); });
|
|
23
|
+
}).map((item) => {
|
|
24
|
+
return brokerShovel({ ...deploymentTemplate(item, context), sourceUri, destinationUri: policy.local, reconnectDelay: policy.reconnectDelay });
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function retargetArchive(document, result, policy) {
|
|
29
|
+
const { archiveRetarget } = policy;
|
|
30
|
+
if (document.edgeControlPlane?.historyEnabled !== true) { return; }
|
|
31
|
+
const shovel = result.parameters.find(({ name }) => { return name === archiveRetarget.shovel; });
|
|
32
|
+
if (shovel) {
|
|
33
|
+
shovel.value['src-queue'] = archiveRetarget.queue;
|
|
34
|
+
appendBrokerResources(result, { queues: [archiveRetarget.queue] });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Project a subscriber broker with local publishers, incoming shovels and replicated resources. */
|
|
39
|
+
export function subscriberBrokerDefinitions(document, server, app, policy, ports) {
|
|
40
|
+
const contracts = app.applicationContracts;
|
|
41
|
+
const families = contracts.map((contract) => { return { family: contract.family, keys: publisherKeys(contract, policy.publishers) }; });
|
|
42
|
+
const exchanges = [...new Set([...families.map(({ family }) => { return deploymentTemplate(policy.exchange, { family }); }), ...policy.base.exchanges])];
|
|
43
|
+
const context = { app, device: server.id.slice(policy.nodePrefix.length), suffix: server.id.replace(policy.shortPrefix, '') };
|
|
44
|
+
const outboxes = archiveOutboxes(document, families, policy, policy.reconnectDelay);
|
|
45
|
+
const result = rabbitmqDefinitions({ ...deploymentTemplate(policy.base, context), exchanges, outboxes });
|
|
46
|
+
result.parameters.push(...inboundShovels(document, server, context, policy));
|
|
47
|
+
result.policies = deploymentTemplate(policy.policies, context);
|
|
48
|
+
retargetArchive(document, result, policy);
|
|
49
|
+
const replicated = ports.replicate(document, server.id, result);
|
|
50
|
+
return appendBrokerResources(replicated, deploymentTemplate(policy.resources, context));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function routeQueues(target, host, policy) {
|
|
54
|
+
const pattern = new RegExp(policy.pattern, 'u');
|
|
55
|
+
const rows = host.fan_in.filter(({ name }) => { return pattern.test(name); });
|
|
56
|
+
const fragments = rows.map(({ from, name }) => {
|
|
57
|
+
const machine = name.split('/')[policy.pathIndex];
|
|
58
|
+
const device = deploymentTemplate(from.startsWith(policy.specialSource.prefix) ? policy.specialSource.device : policy.device, { machine });
|
|
59
|
+
return deploymentTemplate(policy.instance, { machine, device });
|
|
60
|
+
});
|
|
61
|
+
return appendBrokerResources(target, {
|
|
62
|
+
queues: [...fragments.flatMap(({ queues }) => { return queues; }), ...policy.extraQueues],
|
|
63
|
+
bindings: [...fragments.flatMap(({ bindings }) => { return bindings; }), ...fragments.map(({ extraBinding }) => { return extraBinding; })]
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function outboundPeers(document, routes, streams, policy) {
|
|
68
|
+
return document.servers.filter(({ id }) => { return id.startsWith(policy.peerPrefix); }).flatMap(({ id }) => {
|
|
69
|
+
return brokerPeerOutboxes(id, routes, streams.subscriptionsTo(id), (group, peer) => {
|
|
70
|
+
const { queue, exchanges, defaultExchange } = policy.peerOutboxes;
|
|
71
|
+
return { queue: deploymentTemplate(queue, { group, device: peer.slice(policy.peerDeviceOffset) }),
|
|
72
|
+
exchange: exchanges[group] ?? defaultExchange };
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function publishedExchanges(config, policy) {
|
|
78
|
+
return [...config.centralExchanges, ...policy.extraExchanges].map((family) => {
|
|
79
|
+
return deploymentTemplate(policy.exchange, { family });
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Build a publisher broker and its downstream outboxes from subscriptions. */
|
|
84
|
+
export function publisherBrokerDefinitions(document, source, config, policy, ports) {
|
|
85
|
+
const additionalSource = document.edgeControlPlane?.enabled === true && source.id === policy.additionalHost ? policy.additionalSource : undefined;
|
|
86
|
+
const streams = brokerStreams(document, source, { service: policy.access.service, additionalSource });
|
|
87
|
+
const routes = ports.routes(streams.host);
|
|
88
|
+
const archive = streams.subscriptionsTo(policy.archive);
|
|
89
|
+
const keys = brokerStreamBindings(routes, archive);
|
|
90
|
+
const families = config.centralExchanges.map((family) => { return { family, keys: family === policy.archiveFilteredFamily ? keys : ['#'] }; });
|
|
91
|
+
const outboxes = [...archive.size ? archiveOutboxes(document, families, policy, config.reconnectDelay) : [],
|
|
92
|
+
...outboundPeers(document, routes, streams, policy)];
|
|
93
|
+
const result = rabbitmqDefinitions({ ...policy.base, exchanges: publishedExchanges(config, policy), outboxes });
|
|
94
|
+
const expanded = routeQueues(result, streams.host, policy.routeQueues);
|
|
95
|
+
const module = document.profiles?.[source.profile?.id];
|
|
96
|
+
return ports.replicate(document, source.id, ports.transform(expanded, module));
|
|
97
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { deploymentContext, peerNodePort } from '../../application/deploy/deploymentPlan.js';
|
|
2
|
+
import { brokerClientEnvironment } from './brokerSecurity.js';
|
|
3
|
+
import buildDeploymentStages from './buildDeploymentStages.js';
|
|
4
|
+
import { databaseSecurity } from './databaseSecurity.js';
|
|
5
|
+
import deploymentTemplate from './deploymentTemplate.js';
|
|
6
|
+
import { brokerPolicy } from './securityPolicy.js';
|
|
7
|
+
|
|
8
|
+
function nodeAddress(server, service) {
|
|
9
|
+
return new URL(server.api.find(({ id }) => { return id === service; }).url).hostname;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function peerResources({ document, target }, policy) {
|
|
13
|
+
if (!document.edgeControlPlane?.enabled) { return []; }
|
|
14
|
+
const { brokerService: service, nodes } = document.edgeControlPlane;
|
|
15
|
+
const peerAddresses = nodes.map(({ id }) => {
|
|
16
|
+
const server = document.servers.find((row) => { return row.id === id; });
|
|
17
|
+
return nodeAddress(server, policy.target.address);
|
|
18
|
+
});
|
|
19
|
+
return peerNodePort({ ...policy.peerBroker, name: service.name, namespace: target.namespace, peerAddresses,
|
|
20
|
+
port: service.port, nodePort: service.nodePort });
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function secretBindings(assignments, secret) {
|
|
24
|
+
const names = new Set();
|
|
25
|
+
JSON.stringify(assignments, (key, value) => {
|
|
26
|
+
if (key === '$secret') { names.add(value); }
|
|
27
|
+
return value;
|
|
28
|
+
});
|
|
29
|
+
return Object.fromEntries([...names].map((name) => { return [name, { valueFrom: { secretKeyRef: { name: secret, key: name } } }]; }));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function buildSiteState(context, policy, ports) {
|
|
33
|
+
const { app, broker, cluster, document, server, target, profile } = context;
|
|
34
|
+
const assignments = ports.assignments(document, server, app);
|
|
35
|
+
const secretEnvironment = secretBindings(assignments, app.api.secret);
|
|
36
|
+
const controlCatalog = document.edgeControlPlane?.enabled ? ports.catalog(cluster, document) : null;
|
|
37
|
+
const brokerEnvironment = broker && broker.phase !== 'prepare' && brokerClientEnvironment(broker);
|
|
38
|
+
const peers = peerResources(context, policy);
|
|
39
|
+
const authorizationJob = ports.authorizationJob(target.namespace, app);
|
|
40
|
+
const address = nodeAddress(server, policy.target.address);
|
|
41
|
+
return { ...context, assignments, controlCatalog, brokerEnvironment, nodeAddress: address,
|
|
42
|
+
kiosk: ports.kioskPlan(cluster, address, profile.kiosk),
|
|
43
|
+
collectorEnv: { ...deploymentTemplate(policy.collectorEnvironment, { assignments }), ...secretEnvironment, ...brokerEnvironment },
|
|
44
|
+
peers, secretNames: Object.keys(secretEnvironment), authorizationJob };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function storage(state, ports) {
|
|
48
|
+
const { app, authorizationJob, broker, cluster, document, expanded, peers, scada, server } = state;
|
|
49
|
+
const definitions = ports.broker({ ...expanded, edgeControlPlane: document.edgeControlPlane }, server, app);
|
|
50
|
+
const rabbitmq = ports.brokerValues({ ...scada.rabbitmq, extraConfig: { ...scada.rabbitmq.extraConfig, cluster_name: cluster }, definitions }, broker);
|
|
51
|
+
return { values: { extraObjects: [authorizationJob, ...peers], postgres: { ...scada.postgres }, rabbitmq } };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function api(state, policy, ports) {
|
|
55
|
+
const { app, brokerEnvironment, cluster, document, profile, security, server, target } = state;
|
|
56
|
+
const image = server.profile.variables?.siteImage ?? profile.variables?.siteImage ?? app.collector.image;
|
|
57
|
+
const environment = { ...ports.siteEnvironment(cluster, app, security), ...ports.classifyEnvironment(cluster, document), ...brokerEnvironment };
|
|
58
|
+
const process = deploymentTemplate(policy.apiProcess, { app, image, environment });
|
|
59
|
+
return { values: { processes: [process], extraObjects: ports.siteObjects(target.namespace, app) } };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function collector(state, policy, ports) {
|
|
63
|
+
const { app, assignments, cluster, collectorEnv, controlCatalog, document } = state;
|
|
64
|
+
const plane = document.edgeControlPlane;
|
|
65
|
+
const resources = (plane?.historyEnabled === true && plane.agentResources) || app.collector.resources;
|
|
66
|
+
const process = deploymentTemplate(policy.collectorProcess, { app, collectorEnv, collectorResources: resources });
|
|
67
|
+
return { values: { processes: [ports.controlCollector(document, cluster, process)] },
|
|
68
|
+
...(controlCatalog && { controlCatalog, cutoverTasks: controlCatalog.tasks.filter((task) => {
|
|
69
|
+
return !task.pinnedNode && assignments.some(({ taskId }) => { return taskId === task.taskId; });
|
|
70
|
+
}) }) };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function supervisorImage(document, fallback, cluster, policy) {
|
|
74
|
+
const pin = document.servers?.find(({ id }) => { return id === cluster; })?.profile?.variables?.supervisorImage;
|
|
75
|
+
if (pin) { return pin; }
|
|
76
|
+
if (!document.edgeControlPlane?.enabled) { return fallback; }
|
|
77
|
+
if (!document.edgeControlPlane.supervisorImage) { throw new TypeError(policy.supervisorImageError); }
|
|
78
|
+
return document.edgeControlPlane.supervisorImage;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function supervisor(state, policy, ports) {
|
|
82
|
+
const { app, brokerEnvironment, cluster, document, profile } = state;
|
|
83
|
+
const image = supervisorImage(document, profile.apps.supervisor.image, cluster, policy);
|
|
84
|
+
const machine = deploymentTemplate(policy.supervisor.machineId, { number: cluster.at(-1) });
|
|
85
|
+
const config = ports.supervisorConfig(cluster, Boolean(brokerEnvironment), [machine], policy.supervisor.checkpointUrl);
|
|
86
|
+
const environment = { ...(document.edgeControlPlane && { [policy.supervisor.groupVariable]: machine }),
|
|
87
|
+
...deploymentTemplate(policy.supervisorEnvironment, { app }), ...brokerEnvironment };
|
|
88
|
+
return { values: { ...profile.apps.supervisor, ...deploymentTemplate(policy.supervisorValues, { app, image, config, environment }) } };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function stagesFor(state, policy, rollout, ports) {
|
|
92
|
+
const { app, cluster, profile, target, kiosk } = state;
|
|
93
|
+
const common = { context: cluster, namespace: target.namespace, release: cluster, ...rollout.release };
|
|
94
|
+
const defaults = deploymentTemplate(policy.defaults, { app, edgeId: cluster.slice(policy.target.labelOffset) });
|
|
95
|
+
return buildDeploymentStages(rollout.stages, { common, defaults, ports: {
|
|
96
|
+
storage() { return storage(state, ports); },
|
|
97
|
+
api() { return api(state, policy, ports); },
|
|
98
|
+
collector() { return collector(state, policy, ports); },
|
|
99
|
+
supervisor() { return supervisor(state, policy, ports); },
|
|
100
|
+
frontend() { return { values: { ...profile.apps.frontend, ...deploymentTemplate(policy.frontendValues, { app }) } }; },
|
|
101
|
+
kiosk() { return profile.kiosk.browserTargets.includes(cluster) ? { values: { extraObjects: ports.kioskObjects(kiosk) } } : null; }
|
|
102
|
+
} });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function sitePlan(state, policy, stages) {
|
|
106
|
+
const { app, broker, cluster, document, kiosk, nodeAddress: address, server, target, peers, security } = state;
|
|
107
|
+
return { ...(broker && { brokerSecurity: broker }), deploymentEnabled: server.profile.variables?.deployEnabled !== false,
|
|
108
|
+
kiosk, context: cluster, namespace: target.namespace, nodeAddress: address, preserveStoragePodTemplates: app.adoption.freezeStoragePodTemplates,
|
|
109
|
+
prerequisites: {
|
|
110
|
+
...(document.edgeControlPlane?.enabled && { peerBrokerPerimeter: peers[1] }),
|
|
111
|
+
...(security?.database && { databaseRuntime: databaseSecurity(security) }),
|
|
112
|
+
...(broker && { brokerSecrets: [broker.definitionsSecret, broker.runtimeSecret] }),
|
|
113
|
+
runtimeAuthJob: state.authorizationJob.metadata.name, runtimeSecret: app.api.secret, postgresSecret: state.scada.postgres.secret,
|
|
114
|
+
...policy.prerequisites, requiredSecretKeys: [...new Set([...state.secretNames, ...policy.prerequisites.requiredSecretKeys])].sort()
|
|
115
|
+
}, stages };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Compile an isolated storage/API/reader release from chart templates, runtime policy and plant ports. */
|
|
119
|
+
export default function stagedSitePlan(policy, rollout, ports) {
|
|
120
|
+
const targetPattern = new RegExp(policy.target.pattern, 'u');
|
|
121
|
+
return function plan(cluster, input, security) {
|
|
122
|
+
if (!targetPattern.test(cluster ?? '')) { throw new TypeError(policy.target.invalidTarget); }
|
|
123
|
+
const broker = brokerPolicy(security);
|
|
124
|
+
const document = input ?? ports.read();
|
|
125
|
+
const context = deploymentContext(document, cluster);
|
|
126
|
+
if (context.target.namespace !== policy.target.namespace || context.target.prefix !== policy.target.prefix) {
|
|
127
|
+
throw new TypeError(policy.target.invalidScope);
|
|
128
|
+
}
|
|
129
|
+
const state = buildSiteState({ ...context, app: context.profile.apps.scada, cluster, document, security, broker }, policy, ports);
|
|
130
|
+
return sitePlan(state, policy, stagesFor(state, policy, rollout, ports));
|
|
131
|
+
};
|
|
132
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import clickhouseTelemetryPolicy from './clickhouseTelemetryPolicy.js';
|
|
2
|
+
import { databaseValues } from './databaseSecurity.js';
|
|
3
|
+
import deploymentTemplate from './deploymentTemplate.js';
|
|
4
|
+
import { brokerPolicy } from './securityPolicy.js';
|
|
5
|
+
|
|
6
|
+
function aliases(rows, policy, bindings) {
|
|
7
|
+
return Object.fromEntries(rows.map((row) => {
|
|
8
|
+
const variable = { ...bindings, row };
|
|
9
|
+
const metrics = deploymentTemplate(policy.metrics, variable);
|
|
10
|
+
const routes = [...new Set(metrics)].map((metric) => {
|
|
11
|
+
return deploymentTemplate(policy.alias, { ...variable, metric });
|
|
12
|
+
});
|
|
13
|
+
return [row.id, routes];
|
|
14
|
+
}));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function configuration(rows, policy, context) {
|
|
18
|
+
return deploymentTemplate(policy.config, { ...context, aliases: aliases(rows, policy, context),
|
|
19
|
+
machines: rows.map((row) => { return deploymentTemplate(policy.machine, { ...context, row }); }) });
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function jsonWithReferences(config, declarations = {}) {
|
|
23
|
+
const text = JSON.stringify(config);
|
|
24
|
+
return Object.entries(declarations).reduce((value, [key, reference]) => {
|
|
25
|
+
return value.replace(JSON.stringify(key), () => { return reference; });
|
|
26
|
+
}, text);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function processImages(settings, history) {
|
|
30
|
+
return history.enabled ? history.images : { site: settings.image, telemetry: settings.telemetry?.image, supervisor: settings.supervisorImage };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function serviceValues(base, settings, history, { images, security, policy }) {
|
|
34
|
+
const repair = settings.repairHistoryOnStart;
|
|
35
|
+
if (typeof repair !== 'boolean') { throw new TypeError(policy.repairPolicyError); }
|
|
36
|
+
const context = { settings, history, images, repair };
|
|
37
|
+
const scada = { ...base, ...deploymentTemplate(policy.site, { ...context,
|
|
38
|
+
machines: settings.machines.map((row) => { return deploymentTemplate(policy.siteMachine, { row }); }),
|
|
39
|
+
machineIds: settings.machines.map(({ id }) => { return id; }) }) };
|
|
40
|
+
const telemetry = settings.telemetry ? clickhouseTelemetryPolicy({ ...settings.telemetry, image: images.telemetry,
|
|
41
|
+
...(history.enabled && { retentionDays: history.retentionDays, coordinatedRetention: true }) }, policy.telemetrySubject) : undefined;
|
|
42
|
+
if (telemetry) { scada.env.push(...deploymentTemplate(policy.telemetryEnvironment, { telemetry })); }
|
|
43
|
+
if (history.enabled) { scada.env.push(...deploymentTemplate(policy.historyEnvironment, { history })); }
|
|
44
|
+
scada.postgres = databaseValues(scada.postgres, security);
|
|
45
|
+
if (security?.database) {
|
|
46
|
+
scada.env = scada.env.filter(({ name }) => { return !policy.databaseEnvironment.includes(name); });
|
|
47
|
+
}
|
|
48
|
+
return { scada, telemetry };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function supervisor(base, settings, history, security, policy) {
|
|
52
|
+
const broker = brokerPolicy(security);
|
|
53
|
+
const authenticated = broker && broker.phase !== 'prepare';
|
|
54
|
+
const dialect = history.enabled ? policy.historyDialect : policy.defaultDialect;
|
|
55
|
+
const config = configuration(settings.machines, { ...policy.supervisor, alias: policy.supervisor.aliases[dialect] },
|
|
56
|
+
{ host: deploymentTemplate(policy.host, base), history });
|
|
57
|
+
const selected = history.enabled ? { history: deploymentTemplate(policy.historyConfiguration, { history }), ...config } : config;
|
|
58
|
+
if (authenticated) { selected.rabbitmq.credentials = policy.credentialVariables; }
|
|
59
|
+
return { config: jsonWithReferences(selected, authenticated ? policy.credentials : undefined), broker, authenticated };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Compiles local service and supervisor values from templates and a validated history policy. */
|
|
63
|
+
export function supervisedServicePlan(base, settings, security, policy, ports) {
|
|
64
|
+
if (!settings?.machines?.length) { throw new Error(policy.machinesError); }
|
|
65
|
+
const history = { ...ports.history(settings.localHistory), legacyQueues: [] };
|
|
66
|
+
if (history.enabled && !settings.telemetry) { throw new Error(policy.historyTelemetryError); }
|
|
67
|
+
const images = processImages(settings, history);
|
|
68
|
+
const rendered = supervisor(base, settings, history, security, policy);
|
|
69
|
+
const { scada, telemetry } = serviceValues(base, settings, history, { images, security, policy });
|
|
70
|
+
const collector = { ...base.processes[0] };
|
|
71
|
+
const control = { ...settings, localHistory: history, supervisorImage: images.supervisor, ...(telemetry && { telemetry }),
|
|
72
|
+
config: rendered.config, collector, enabled: true, lease: history.enabled, leaseName: policy.leaseName,
|
|
73
|
+
...(rendered.authenticated && { brokerSecret: rendered.broker.runtimeSecret }) };
|
|
74
|
+
return { ...base, ...(history.enabled && { rabbitmq: { ...base.rabbitmq, definitions: ports.broker(base.rabbitmq.definitions, control) } }),
|
|
75
|
+
processes: [collector], collector, scada, [policy.valuesKey]: control };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Projects one standby supervisor using the same machine and alias contracts as its primary. */
|
|
79
|
+
export function standbySupervisor(settings, bindings, policy) {
|
|
80
|
+
const config = configuration(settings.machines, policy.supervisor, bindings);
|
|
81
|
+
return deploymentTemplate(policy.values, { settings, ...bindings, config: jsonWithReferences(config, policy.credentials) });
|
|
82
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import classifyRecord from './classifyRecord.js';
|
|
2
|
+
import { installClassifyProxy } from './classifyProxy.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Wires plant HTTP to the same classify-record the controller stores.
|
|
6
|
+
*
|
|
7
|
+
* Missing CLASSIFY_RECORD_URL leaves the server unchanged.
|
|
8
|
+
*
|
|
9
|
+
* @param {object} httpServer - Node HTTP server from plantServer
|
|
10
|
+
* @param {object} env - process environment
|
|
11
|
+
* @param {function} decide - application route selector
|
|
12
|
+
* @returns {{stop: function}} poll handle
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* attachClassify(ctx.plant.server, process.env)
|
|
16
|
+
*/
|
|
17
|
+
export default function attachClassify(httpServer, env, decide) {
|
|
18
|
+
if (!env.CLASSIFY_RECORD_URL) { return { stop() { return false; } }; }
|
|
19
|
+
if (!env.CLASSIFY_NODE_ID) { throw new Error('CLASSIFY_NODE_ID is required for classify API'); }
|
|
20
|
+
const urls = JSON.parse(env.CLASSIFY_PLANT_URLS || '{}');
|
|
21
|
+
const store = classifyRecord(env.CLASSIFY_RECORD_URL);
|
|
22
|
+
const running = store.start(Number(env.CLASSIFY_POLL_MS || 2000));
|
|
23
|
+
installClassifyProxy(httpServer, {
|
|
24
|
+
decide(path) {
|
|
25
|
+
const snap = store.snapshot();
|
|
26
|
+
return decide(env.CLASSIFY_NODE_ID, snap.ready ? snap.value : null, urls, path);
|
|
27
|
+
}
|
|
28
|
+
}, urls);
|
|
29
|
+
return running;
|
|
30
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import { errorResponse } from '@yarkivaev/simple-server';
|
|
3
|
+
|
|
4
|
+
const hop = 'x-scada-classify-hop';
|
|
5
|
+
const skipped = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
|
|
6
|
+
'te', 'trailers', 'transfer-encoding', 'upgrade', 'host', hop]);
|
|
7
|
+
|
|
8
|
+
function headers(req) {
|
|
9
|
+
const out = { [hop]: '1' };
|
|
10
|
+
Object.entries(req.headers).forEach(([name, value]) => {
|
|
11
|
+
if (!skipped.has(name)) { out[name] = value; }
|
|
12
|
+
});
|
|
13
|
+
return out;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function wait(res) {
|
|
17
|
+
errorResponse('UNAVAILABLE', 'classify owner is pending', 503).send(res);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function pump(req, res, target) {
|
|
21
|
+
const url = new URL(req.url, target);
|
|
22
|
+
const sent = http.request({
|
|
23
|
+
protocol: url.protocol,
|
|
24
|
+
hostname: url.hostname,
|
|
25
|
+
port: url.port,
|
|
26
|
+
path: `${url.pathname}${url.search}`,
|
|
27
|
+
method: req.method,
|
|
28
|
+
headers: headers(req)
|
|
29
|
+
}, (incoming) => {
|
|
30
|
+
res.writeHead(incoming.statusCode, incoming.headers);
|
|
31
|
+
incoming.pipe(res);
|
|
32
|
+
});
|
|
33
|
+
sent.on('error', () => {
|
|
34
|
+
if (!res.headersSent) { wait(res); }
|
|
35
|
+
});
|
|
36
|
+
req.on('aborted', () => { sent.destroy(); });
|
|
37
|
+
req.pipe(sent);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Replaces the plant request listener with classify routing.
|
|
42
|
+
*
|
|
43
|
+
* Local ownership keeps the previous handler. Foreign machines are proxied to
|
|
44
|
+
* the active node's plant origin. A pending candidate answers 503.
|
|
45
|
+
*
|
|
46
|
+
* @param {object} httpServer - Node HTTP server from plantServer
|
|
47
|
+
* @param {{decide: function}} owner - routing choice from classify-record
|
|
48
|
+
* @param {object} urls - nodeId to plant origin
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* installClassifyProxy(server, { decide() { return { kind: 'local' }; } }, {})
|
|
52
|
+
*/
|
|
53
|
+
export function installClassifyProxy(httpServer, owner, urls) {
|
|
54
|
+
const previous = httpServer.listeners('request').slice();
|
|
55
|
+
httpServer.removeAllListeners('request');
|
|
56
|
+
httpServer.on('request', (req, res) => {
|
|
57
|
+
if (req.headers[hop] === '1') {
|
|
58
|
+
previous.forEach((fn) => { fn(req, res); });
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const choice = owner.decide(req.url);
|
|
62
|
+
if (choice.kind === 'local') {
|
|
63
|
+
previous.forEach((fn) => { fn(req, res); });
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (choice.kind === 'proxy' && urls[choice.node]) {
|
|
67
|
+
pump(req, res, urls[choice.node]);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
wait(res);
|
|
71
|
+
});
|
|
72
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Polls the controller copy of assignments/classify-record.
|
|
3
|
+
*
|
|
4
|
+
* A failed fetch keeps the last snapshot. The first failure stays unread so
|
|
5
|
+
* the site-server cannot elect itself.
|
|
6
|
+
*
|
|
7
|
+
* @param {string} url - GET /record on the local classify gate
|
|
8
|
+
* @param {function} load - fetch-like function
|
|
9
|
+
* @returns {{snapshot: function, refresh: function, start: function}} store
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* const store = classifyRecord('http://edge-classify:8091/record')
|
|
13
|
+
*/
|
|
14
|
+
export default function classifyRecord(url, load = fetch) {
|
|
15
|
+
let snapshot = { ready: false, value: {} };
|
|
16
|
+
async function refresh() {
|
|
17
|
+
try {
|
|
18
|
+
const response = await load(url);
|
|
19
|
+
if (!response.ok) { return snapshot; }
|
|
20
|
+
snapshot = { ready: true, value: await response.json() };
|
|
21
|
+
return snapshot;
|
|
22
|
+
} catch {
|
|
23
|
+
return snapshot;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function start(delay) {
|
|
27
|
+
const timer = setInterval(() => { refresh().catch(() => { return snapshot; }); }, delay);
|
|
28
|
+
refresh().catch(() => { return snapshot; });
|
|
29
|
+
return { stop() { clearInterval(timer); } };
|
|
30
|
+
}
|
|
31
|
+
return { snapshot() { return snapshot; }, refresh, start };
|
|
32
|
+
}
|