@yarkivaev/scada 2.13.0 → 2.14.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 +29 -0
- package/package.json +3 -2
- package/src/application/control/controlClient.js +1 -1
- package/src/application/control/createOnlyJSON.js +50 -0
- package/src/application/control/index.js +2 -0
- package/src/application/control/jsonAssignments.js +30 -0
- package/src/application/mcp/loadMetricSeries.js +69 -0
- package/src/application/mcp/locateMachineMetric.js +25 -0
- package/src/application/mcp/metricQueryPorts.js +78 -0
- package/src/application/mcp/parseBearerTokens.js +43 -0
- package/src/application/runtime/assignment.js +4 -1
- package/src/infrastructure/deploy/applyWhenChanged.js +15 -0
- package/src/infrastructure/deploy/deploymentKube.js +35 -0
- package/src/infrastructure/deploy/executeKubeSeed.js +24 -0
- package/src/infrastructure/deploy/executeRelease.js +8 -11
- package/src/infrastructure/deploy/operatePostgresMaintenance.js +85 -0
- package/src/infrastructure/deploy/postgresMaintenancePlan.js +54 -0
- package/src/infrastructure/deploy/postgresRestoreObjects.js +73 -0
- package/src/infrastructure/deploy/preflightKubeStorage.js +76 -0
- package/src/infrastructure/deploy/prepareKubePrerequisites.js +95 -0
- package/src/infrastructure/deploy/verifyCollectorCoverage.js +43 -0
- package/src/infrastructure/deploy/verifyPeerBrokerPerimeter.js +24 -0
- package/src/infrastructure/ingest/mysql40/byteReader.js +51 -0
- package/src/infrastructure/ingest/mysql40/mysql40.js +116 -0
- package/src/infrastructure/ingest/mysql40/packets.js +72 -0
- package/src/infrastructure/ingest/mysql40/resultRows.js +92 -0
- package/src/infrastructure/ingest/mysql40/scramble.js +89 -0
- package/src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js +83 -0
- package/src/infrastructure/ingest/telemetry/replayStoredTelemetry.js +125 -0
- package/src/infrastructure/management/kubeServiceAccount.js +43 -0
- package/src/infrastructure/management/kubectlPortForward.js +27 -0
- package/src/infrastructure/mdmesh/hmiApplication.js +64 -0
- package/src/infrastructure/mdmesh/hmiControl.js +85 -0
- package/src/infrastructure/mdmesh/hmiFile.js +69 -0
- package/src/infrastructure/mdmesh/hmiMonitor.js +53 -0
- package/src/infrastructure/mdmesh/hmiReconcile.js +170 -0
- package/src/infrastructure/mdmesh/hmiRuntime.js +33 -0
- package/src/infrastructure/mdmesh/index.js +7 -0
- package/src/infrastructure/mdmesh/mdmeshClient.js +72 -0
- package/src/infrastructure/messaging/ownership/edgeSitesFromEnv.js +137 -0
- package/src/infrastructure/messaging/rabbitmq/reconcile.js +71 -12
- package/src/infrastructure/opcua/health.js +91 -0
- package/src/infrastructure/opcua/index.js +1 -0
- package/src/infrastructure/persistence/pg/prepareRuntimeRole.js +67 -0
- package/src/infrastructure/replication/canonicalJSON.js +15 -0
- package/src/infrastructure/replication/postgresSnapshotReplica.js +129 -0
- package/src/infrastructure/replication/postgresSnapshotRuntime.js +40 -0
- package/src/infrastructure/replication/snapshotSync.js +61 -0
- package/src/infrastructure/replication/tableSnapshotFormat.js +50 -0
- package/src/infrastructure/tls/mirrorTLSSecret.js +37 -0
- package/src/infrastructure/tls/mutualJSON.js +79 -0
- package/src/infrastructure/tls/tlsMaterial.js +57 -0
- package/stream-processing/src/main/scala/scada/processing/infra/state/AtomicStateFile.scala +7 -0
- package/stream-processing/src/main/scala/scada/processing/infra/state/StateJournal.scala +22 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/HistoryClient.scala +10 -1
- package/stream-processing/src/main/scala/scada/processing/runtime/LiveWorker.scala +70 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +2 -8
- package/stream-processing/src/main/scala/scada/processing/runtime/StatefulHistory.scala +108 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/TimelinePublication.scala +43 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +43 -0
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import hmiApplication from './hmiApplication.js';
|
|
2
|
+
import hmiFile, { fileChecksum } from './hmiFile.js';
|
|
3
|
+
|
|
4
|
+
function settings(profile) {
|
|
5
|
+
if (typeof profile.kiosk !== 'boolean' || !['landscape', 'portrait'].includes(profile.orientation)) {
|
|
6
|
+
throw new Error('HMI profile has invalid native settings');
|
|
7
|
+
}
|
|
8
|
+
return { kioskMode: profile.kiosk, orientation: profile.orientation === 'landscape' ? 2 : 1, ...profile.native };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
async function defaults(client, rows, kiosk) {
|
|
12
|
+
if (!rows.some((row) => { return row.id === 1 && !row.name.startsWith(`${kiosk.ownershipPrefix}:`); })) {
|
|
13
|
+
throw new Error('MDMesh requires its default configuration template to create managed profiles');
|
|
14
|
+
}
|
|
15
|
+
const template = await client.request('/private/configurations/1');
|
|
16
|
+
if (!template || !Array.isArray(template.applications)
|
|
17
|
+
|| ['downloadUpdates', 'requestUpdates', 'appPermissions', 'iconSize', 'desktopHeader'].some((key) => { return typeof template[key] !== 'string' || !template[key]; })) {
|
|
18
|
+
throw new Error('MDMesh default configuration template is incomplete');
|
|
19
|
+
}
|
|
20
|
+
const base = { ...template, applications: [] };
|
|
21
|
+
delete base.id;
|
|
22
|
+
return base;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function sameApplication(row, desired) {
|
|
26
|
+
return ['id', 'usedVersionId', 'action', 'showIcon', 'remove'].every(field => { return row[field] === desired[field]; });
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function sameFile(row, desired) {
|
|
30
|
+
return ['fileId', 'path', 'remove'].every((field) => { return row[field] === desired[field]; })
|
|
31
|
+
&& fileChecksum(row) === desired.checksum;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function mergeFiles(current, owned, devicePath) {
|
|
35
|
+
const rest = (current || []).filter((row) => { return row.path !== devicePath; });
|
|
36
|
+
return owned ? rest.concat(owned) : current;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function differs(current, native, devicePath) {
|
|
40
|
+
return Object.entries(native).some(([key, value]) => {
|
|
41
|
+
if (key === 'applications') {
|
|
42
|
+
return current.applications.length !== value.length || value.some(app => {
|
|
43
|
+
return !current.applications.some(row => { return sameApplication(row, app); });
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
if (key === 'files') {
|
|
47
|
+
const wanted = (value || []).filter((row) => { return row.path === devicePath; });
|
|
48
|
+
const actual = (current.files || []).filter((row) => { return row.path === devicePath; });
|
|
49
|
+
return wanted.length !== actual.length || wanted.some((file) => { return !actual.some((row) => { return sameFile(row, file); }); });
|
|
50
|
+
}
|
|
51
|
+
return current[key] !== value;
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function details(client, id) {
|
|
56
|
+
const current = await client.request(`/private/configurations/${encodeURIComponent(id)}`);
|
|
57
|
+
const applications = await client.request(`/private/configurations/applications/${encodeURIComponent(id)}`);
|
|
58
|
+
if (!Array.isArray(applications)) { throw new Error('MDMesh configuration application list is incomplete'); }
|
|
59
|
+
return { ...current, applications: applications.filter(row => { return row.selected === true; }).map(row => {
|
|
60
|
+
const application = { ...row };
|
|
61
|
+
delete application.selected;
|
|
62
|
+
return application;
|
|
63
|
+
}) };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function configuration(client, rows, id, profile, kiosk) {
|
|
67
|
+
const name = `${kiosk.ownershipPrefix}:${id}`;
|
|
68
|
+
const matches = rows.filter((row) => { return row.name === name; });
|
|
69
|
+
if (matches.length > 1) { throw new Error('MDMesh has ambiguous managed configurations'); }
|
|
70
|
+
const current = matches.length ? await details(client, matches[0].id) : undefined;
|
|
71
|
+
if (current && (current.name !== name || !Array.isArray(current.applications))) { throw new Error('MDMesh full configuration is incomplete'); }
|
|
72
|
+
const native = settings(profile);
|
|
73
|
+
const base = current || { ...await defaults(client, rows, kiosk), name, description: name };
|
|
74
|
+
return { id, current, desired: { ...base, ...native, files: mergeFiles(base.files, native.files, kiosk.devicePath) },
|
|
75
|
+
drift: !current || differs(current, native, kiosk.devicePath) };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function configurations(plan, client) {
|
|
79
|
+
const rows = await client.request('/private/configurations/search');
|
|
80
|
+
if (!Array.isArray(rows)) { throw new Error('MDMesh configuration search returned invalid data'); }
|
|
81
|
+
return Promise.all(Object.entries(plan.profiles).map(([id, profile]) => { return configuration(client, rows, id, profile, plan.kiosk); }));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function devicesFor(plan, inventory) {
|
|
85
|
+
return plan.devices.map((device) => {
|
|
86
|
+
const matches = device.deviceRef ? inventory.filter((row) => { return row.number === device.deviceRef; }) : [];
|
|
87
|
+
const state = device.deviceRef ? 'unknown-reference' : 'planned-unbound';
|
|
88
|
+
if (matches.length > 1) { throw new Error('MDMesh has ambiguous enrolled device references'); }
|
|
89
|
+
if (matches.length && (!Number.isSafeInteger(matches[0].id) || matches[0].id <= 0)) { throw new Error('MDMesh enrolled device has invalid identity'); }
|
|
90
|
+
return { ...device, actual: matches[0], state: matches.length ? 'enrolled' : state };
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function save(client, changes, index = 0) {
|
|
95
|
+
if (index < changes.length) {
|
|
96
|
+
await client.request('/private/configurations', 'PUT', changes[index].desired);
|
|
97
|
+
await save(client, changes, index + 1);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function assign(client, devices, configs, index = 0) {
|
|
102
|
+
if (index < devices.length) {
|
|
103
|
+
const device = devices[index];
|
|
104
|
+
const config = configs.find((entry) => { return entry.id === device.profile; });
|
|
105
|
+
if (device.actual && config?.current?.id && device.actual.configurationId !== config.current.id) {
|
|
106
|
+
await client.request('/private/devices', 'PUT', { ids: [device.actual.id], configurationId: config.current.id });
|
|
107
|
+
}
|
|
108
|
+
await assign(client, devices, configs, index + 1);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function applicationState(device, applied) {
|
|
113
|
+
if (!device.application.autoStart) { return 'waiting-app-configuration'; }
|
|
114
|
+
if (applied) { return 'native-config-stored'; }
|
|
115
|
+
return device.launchReady ? 'planned' : 'missing-apk';
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function report(devices, configs, blocked, applied) {
|
|
119
|
+
return { blocked, applied, profiles: configs.map((entry) => { return { id: entry.id, configurationId: entry.current?.id,
|
|
120
|
+
drift: entry.drift, state: applied ? 'native-settings-stored' : 'planned',
|
|
121
|
+
unsupported: ['orientation-delivery', 'keepScreenOnWhileCharging', 'alarmSound'] }; }),
|
|
122
|
+
devices: devices.map((device) => { return { id: device.id, machine: device.machine, state: device.state,
|
|
123
|
+
configurationDrift: device.actual ? device.actual.configurationId !== configs.find((entry) => { return entry.id === device.profile; })?.current?.id : undefined,
|
|
124
|
+
application: { state: applicationState(device, applied), desired: device.application } }; }) };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function confirmed(devices, configs) {
|
|
128
|
+
const matched = devices.every((device) => {
|
|
129
|
+
const config = configs.find((entry) => { return entry.id === device.profile; });
|
|
130
|
+
return !device.deviceRef || device.actual && device.actual.configurationId === config?.current?.id;
|
|
131
|
+
});
|
|
132
|
+
if (!matched) { throw new Error('MDMesh device assignment readback did not match the desired configuration'); }
|
|
133
|
+
return devices;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function persist(plan, client, devices, configs) {
|
|
137
|
+
await save(client, configs.filter((entry) => { return entry.drift; }));
|
|
138
|
+
const refreshed = await configurations(plan, client);
|
|
139
|
+
if (refreshed.some((entry) => { return entry.drift || !Number.isSafeInteger(entry.current?.id) || entry.current.id <= 0; })) {
|
|
140
|
+
throw new Error('MDMesh configuration readback did not match the desired native settings');
|
|
141
|
+
}
|
|
142
|
+
await assign(client, devices, refreshed);
|
|
143
|
+
const inventory = devicesFor(plan, await client.inventory());
|
|
144
|
+
return report(confirmed(inventory, refreshed), refreshed, false, true);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function launchPlan(plan, client, apply) {
|
|
148
|
+
const entries = await Promise.all(plan.devices.map(async device => {
|
|
149
|
+
if (!device.application.autoStart) { return { device }; }
|
|
150
|
+
const application = await hmiApplication(device, client, apply, plan.kiosk);
|
|
151
|
+
const stored = await hmiFile(device, client, apply, plan.kiosk);
|
|
152
|
+
const profile = `${device.profile}:${device.id}`;
|
|
153
|
+
return { device: { ...device, profile, launchReady: application.ready && stored.ready }, profile,
|
|
154
|
+
settings: { ...plan.profiles[device.profile], native: { ...application.settings, files: stored.file ? [stored.file] : undefined } } };
|
|
155
|
+
}));
|
|
156
|
+
return { ...plan, profiles: { ...plan.profiles, ...Object.fromEntries(entries.filter(entry => { return entry.profile; }).map(entry => { return [entry.profile, entry.settings]; })) },
|
|
157
|
+
devices: entries.map(entry => { return entry.device; }) };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Store only owned native fields, preserving complete upstream documents and enrolled identities. */
|
|
161
|
+
export default async function hmiReconcile(source, client, apply, kiosk) {
|
|
162
|
+
const initial = devicesFor(source, await client.inventory());
|
|
163
|
+
const missing = initial.some(device => {return device.state === 'unknown-reference'});
|
|
164
|
+
const plan = await launchPlan({ ...source, kiosk }, client, apply && !missing);
|
|
165
|
+
const devices = devicesFor(plan, await client.inventory());
|
|
166
|
+
const configs = await configurations(plan, client);
|
|
167
|
+
const blocked = devices.some((device) => { return device.state === 'unknown-reference' || device.application.autoStart && !device.launchReady; });
|
|
168
|
+
if (apply && !blocked) { return persist(plan, client, devices, configs); }
|
|
169
|
+
return report(devices, configs, blocked, false);
|
|
170
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import hmiControl from './hmiControl.js';
|
|
3
|
+
import mdmeshClient from './mdmeshClient.js';
|
|
4
|
+
|
|
5
|
+
function required(environment, key) {
|
|
6
|
+
const value = environment[key];
|
|
7
|
+
if (typeof value !== 'string' || !value.trim()) { throw new Error(`HMI runtime requires ${key}`); }
|
|
8
|
+
return value;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function load(file) {
|
|
12
|
+
let plan;
|
|
13
|
+
try { plan = JSON.parse(readFileSync(file, 'utf8')); } catch { throw new Error('HMI runtime cannot read its validated plan file'); }
|
|
14
|
+
if (!plan || typeof plan.server !== 'string' || !plan.server || !Array.isArray(plan.devices)
|
|
15
|
+
|| !plan.profiles || typeof plan.profiles !== 'object' || Array.isArray(plan.profiles)) {
|
|
16
|
+
throw new Error('HMI runtime requires a validated server catalog');
|
|
17
|
+
}
|
|
18
|
+
return plan;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function client(environment, prefix, url) {
|
|
22
|
+
return mdmeshClient({ url, login: required(environment, `${prefix}_LOGIN`), password: required(environment, `${prefix}_PASSWORD`) });
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Build the HTTP runtime from a mounted validated plan and separate Secret-backed identities. */
|
|
26
|
+
export default function hmiRuntime(environment, { kiosk, planFile, mdmeshURL }) {
|
|
27
|
+
const plan = load(environment.HMI_PLAN_FILE || planFile);
|
|
28
|
+
const token = required(environment, 'HMI_CONTROL_TOKEN');
|
|
29
|
+
const url = environment.MDMESH_URL || mdmeshURL;
|
|
30
|
+
const address = new URL(url);
|
|
31
|
+
if (!['http:', 'https:'].includes(address.protocol) || address.username || address.password) { throw new Error('HMI runtime requires an HTTP MDMesh address without credentials'); }
|
|
32
|
+
return hmiControl({ plan, token, kiosk, control: client(environment, 'MDMESH_API', url), monitor: client(environment, 'MDMESH_MONITOR', url) });
|
|
33
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { default as hmiApplication } from './hmiApplication.js';
|
|
2
|
+
export { default as hmiControl } from './hmiControl.js';
|
|
3
|
+
export { default as hmiFile } from './hmiFile.js';
|
|
4
|
+
export { default as hmiMonitor, metrics } from './hmiMonitor.js';
|
|
5
|
+
export { default as hmiReconcile } from './hmiReconcile.js';
|
|
6
|
+
export { default as hmiRuntime } from './hmiRuntime.js';
|
|
7
|
+
export { default as mdmeshClient } from './mdmeshClient.js';
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
async function exchange(url, route, options) {
|
|
4
|
+
try {
|
|
5
|
+
return await fetch(`${url.replace(/\/$/u, '')}/rest${route}`, { ...options, redirect: 'error', signal: AbortSignal.timeout(8000) });
|
|
6
|
+
} catch { throw new Error('MDMesh transport failed'); }
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
async function payload(response, context) {
|
|
10
|
+
if (!response.ok) { throw new Error(`MDMesh ${context} refused with HTTP ${response.status}`); }
|
|
11
|
+
let value;
|
|
12
|
+
try { value = await response.json(); } catch { throw new Error(`MDMesh ${context} returned invalid JSON`); }
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function expire(session) {
|
|
17
|
+
delete session.authentication;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function authenticate(settings) {
|
|
21
|
+
if (!settings.login || !settings.password) { throw new Error('MDMesh credentials are missing'); }
|
|
22
|
+
const response = await exchange(settings.url, '/public/jwt/login', { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
23
|
+
body: JSON.stringify({ login: settings.login, password: createHash('md5').update(settings.password).digest('hex').toUpperCase() }) });
|
|
24
|
+
const value = await payload(response, 'authentication');
|
|
25
|
+
if (typeof value.id_token !== 'string' || !value.id_token) { throw new Error('MDMesh authentication returned no JWT'); }
|
|
26
|
+
return value.id_token;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function inventory(request, page = 1, devices = []) {
|
|
30
|
+
if (page > 200) { throw new Error('MDMesh inventory exceeded bounded pagination'); }
|
|
31
|
+
const value = await request('/private/devices/search', 'POST', { value: '', pageNum: page, pageSize: 50 });
|
|
32
|
+
if (!Array.isArray(value?.devices?.items) || !Number.isSafeInteger(value.devices.totalItemsCount)
|
|
33
|
+
|| value.devices.totalItemsCount < 0) { throw new Error('MDMesh inventory returned invalid pagination'); }
|
|
34
|
+
const combined = [...devices, ...value.devices.items];
|
|
35
|
+
if (page * 50 >= value.devices.totalItemsCount) { return combined; }
|
|
36
|
+
return inventory(request, page + 1, combined);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function form(filename, content) {
|
|
40
|
+
const body = new FormData();
|
|
41
|
+
body.append('file', new Blob([content], { type: 'text/plain' }), filename);
|
|
42
|
+
return body;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function envelope(value) {
|
|
46
|
+
if (value?.status !== 'OK') { throw new Error('MDMesh request returned an unsuccessful envelope'); }
|
|
47
|
+
return value.data;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function bearer(settings, session) {
|
|
51
|
+
session.authentication ||= authenticate(settings).catch(() => { expire(session); throw new Error('MDMesh authentication failed'); });
|
|
52
|
+
return await session.authentication;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Authenticated v0.4.0 REST adapter; upstream messages and credentials never enter errors. */
|
|
56
|
+
export default function mdmeshClient(settings) {
|
|
57
|
+
const session = {};
|
|
58
|
+
async function request(route, method = 'GET', body = undefined, retry = true) {
|
|
59
|
+
const token = await bearer(settings, session);
|
|
60
|
+
const response = await exchange(settings.url, route, { method, headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
|
61
|
+
...(body !== undefined && { body: JSON.stringify(body) }) });
|
|
62
|
+
if (retry && [401, 403].includes(response.status)) { expire(session); return request(route, method, body, false); }
|
|
63
|
+
return envelope(await payload(response, 'request'));
|
|
64
|
+
}
|
|
65
|
+
async function upload(filename, content, retry = true) {
|
|
66
|
+
const token = await bearer(settings, session);
|
|
67
|
+
const response = await exchange(settings.url, '/private/web-ui-files/raw', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: form(filename, content) });
|
|
68
|
+
if (retry && [401, 403].includes(response.status)) { expire(session); return upload(filename, content, false); }
|
|
69
|
+
return envelope(await payload(response, 'upload'));
|
|
70
|
+
}
|
|
71
|
+
return { request, upload, inventory: () => { return inventory(request); } };
|
|
72
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parses EDGE_SITES JSON; empty array or blank → undefined (all-local STOMP).
|
|
3
|
+
*
|
|
4
|
+
* @param {string} raw - EDGE_SITES value
|
|
5
|
+
* @returns {Array|{sites: object}|undefined} array sites, legacy map, or undefined
|
|
6
|
+
*/
|
|
7
|
+
function parseEdgeSites(raw) {
|
|
8
|
+
let parsed;
|
|
9
|
+
try {
|
|
10
|
+
parsed = JSON.parse(raw);
|
|
11
|
+
} catch (cause) {
|
|
12
|
+
throw new Error(`EDGE_SITES must be valid JSON: ${cause.message}`);
|
|
13
|
+
}
|
|
14
|
+
if (Array.isArray(parsed)) {
|
|
15
|
+
return parsed.length === 0 ? undefined : parsed;
|
|
16
|
+
}
|
|
17
|
+
if (parsed && typeof parsed === 'object') {
|
|
18
|
+
return { sites: parsed };
|
|
19
|
+
}
|
|
20
|
+
throw new Error('EDGE_SITES must be a JSON array of { baseUrl, machines, token? }');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Builds machineOwners site list from legacy EDGE_SITES + MACHINE_OWNERS maps.
|
|
25
|
+
*
|
|
26
|
+
* @param {object} sites - siteId → { baseUrl, token? }
|
|
27
|
+
* @param {object} owners - machineId → siteId
|
|
28
|
+
* @returns {Array<{baseUrl: string, token?: string, machines: string[]}>} site list
|
|
29
|
+
*/
|
|
30
|
+
function sitesFromMaps(sites, owners) {
|
|
31
|
+
const buckets = new Map();
|
|
32
|
+
for (const [machineId, siteId] of Object.entries(owners)) {
|
|
33
|
+
if (typeof siteId === 'string' && siteId.length > 0 && siteId !== 'local') {
|
|
34
|
+
const site = sites[siteId];
|
|
35
|
+
if (!site || typeof site.baseUrl !== 'string' || site.baseUrl.length === 0) {
|
|
36
|
+
throw new Error(`MACHINE_OWNERS machine ${machineId} references unknown site ${siteId}`);
|
|
37
|
+
}
|
|
38
|
+
if (!buckets.has(siteId)) {
|
|
39
|
+
buckets.set(siteId, {
|
|
40
|
+
baseUrl: site.baseUrl,
|
|
41
|
+
token: site.token,
|
|
42
|
+
machines: []
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
buckets.get(siteId).machines.push(machineId);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return [...buckets.values()];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Validates one EDGE_SITES array entry for machineOwners.
|
|
53
|
+
*
|
|
54
|
+
* @param {object} site - site descriptor
|
|
55
|
+
* @param {number} index - array index for error context
|
|
56
|
+
* @returns {object} site with baseUrl, machines, optional token
|
|
57
|
+
*/
|
|
58
|
+
function normalizeSite(site, index) {
|
|
59
|
+
if (!site || typeof site !== 'object' || Array.isArray(site)) {
|
|
60
|
+
throw new Error(`EDGE_SITES[${index}] must be an object`);
|
|
61
|
+
}
|
|
62
|
+
if (typeof site.baseUrl !== 'string' || site.baseUrl.length === 0) {
|
|
63
|
+
throw new Error(`EDGE_SITES[${index}] requires baseUrl`);
|
|
64
|
+
}
|
|
65
|
+
if (!Array.isArray(site.machines) || site.machines.length === 0) {
|
|
66
|
+
throw new Error(`EDGE_SITES[${index}] requires non-empty machines`);
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
baseUrl: site.baseUrl,
|
|
70
|
+
machines: site.machines,
|
|
71
|
+
token: site.token
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Parses legacy MACHINE_OWNERS object map.
|
|
77
|
+
*
|
|
78
|
+
* @param {string} raw - MACHINE_OWNERS JSON
|
|
79
|
+
* @returns {object} machineId → siteId map
|
|
80
|
+
*/
|
|
81
|
+
function parseOwnersMap(raw) {
|
|
82
|
+
let owners;
|
|
83
|
+
try {
|
|
84
|
+
owners = JSON.parse(raw);
|
|
85
|
+
} catch (cause) {
|
|
86
|
+
throw new Error(`MACHINE_OWNERS must be valid JSON: ${cause.message}`);
|
|
87
|
+
}
|
|
88
|
+
if (!owners || typeof owners !== 'object' || Array.isArray(owners)) {
|
|
89
|
+
throw new Error('MACHINE_OWNERS must be a JSON object');
|
|
90
|
+
}
|
|
91
|
+
return owners;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Legacy two-map form: EDGE_SITES object + MACHINE_OWNERS.
|
|
96
|
+
*
|
|
97
|
+
* @param {object} sites - siteId → { baseUrl, token? }
|
|
98
|
+
* @param {NodeJS.ProcessEnv} env - process environment
|
|
99
|
+
* @returns {Array<{baseUrl: string, token?: string, machines: string[]}>} site list
|
|
100
|
+
*/
|
|
101
|
+
function legacyFromMaps(sites, env) {
|
|
102
|
+
const ownersRaw = env.MACHINE_OWNERS;
|
|
103
|
+
if (typeof ownersRaw !== 'string' || ownersRaw.length === 0) {
|
|
104
|
+
throw new Error('legacy EDGE_SITES object map requires MACHINE_OWNERS');
|
|
105
|
+
}
|
|
106
|
+
return sitesFromMaps(sites, parseOwnersMap(ownersRaw));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Reads EDGE_SITES into a machineOwners site list.
|
|
111
|
+
*
|
|
112
|
+
* Primary (infra / scada): JSON array of { baseUrl, machines, token? }.
|
|
113
|
+
* Unset, empty string, or `[]` → undefined (legacy all-local STOMP).
|
|
114
|
+
* Optional legacy: EDGE_SITES object map + MACHINE_OWNERS machine→siteId map.
|
|
115
|
+
*
|
|
116
|
+
* @param {NodeJS.ProcessEnv} [env] - process environment
|
|
117
|
+
* @returns {Array<{baseUrl: string, token?: string, machines: string[]}>|undefined} sites
|
|
118
|
+
*
|
|
119
|
+
* @example
|
|
120
|
+
* edgeSitesFromEnv({
|
|
121
|
+
* EDGE_SITES: '[{"baseUrl":"http://edge:30300/api/v1","machines":["fixture-pump"]}]'
|
|
122
|
+
* });
|
|
123
|
+
*/
|
|
124
|
+
export default function edgeSitesFromEnv(env = process.env) {
|
|
125
|
+
const sitesRaw = env.EDGE_SITES;
|
|
126
|
+
if (typeof sitesRaw !== 'string' || sitesRaw.length === 0) {
|
|
127
|
+
return undefined;
|
|
128
|
+
}
|
|
129
|
+
const parsed = parseEdgeSites(sitesRaw);
|
|
130
|
+
if (!parsed) {
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
if (Array.isArray(parsed)) {
|
|
134
|
+
return parsed.map(normalizeSite);
|
|
135
|
+
}
|
|
136
|
+
return legacyFromMaps(parsed.sites, env);
|
|
137
|
+
}
|
|
@@ -67,20 +67,43 @@ async function bindings(api, path, desired, ownsBinding) {
|
|
|
67
67
|
return missing.length + stale.length;
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
-
async function
|
|
71
|
-
const current = await api('GET', path);
|
|
70
|
+
async function upsertNamed(api, path, desired, body) {
|
|
71
|
+
const current = await api('GET', path) || [];
|
|
72
72
|
const changed = desired.filter((item) => {
|
|
73
73
|
const found = current.find((row) => { return row.name === item.name; });
|
|
74
|
-
return !same(found,
|
|
75
|
-
});
|
|
76
|
-
const stale = current.filter((item) => {
|
|
77
|
-
return ownsShovel?.(item) && !desired.some((row) => { return row.name === item.name; });
|
|
74
|
+
return !same(found, body(item));
|
|
78
75
|
});
|
|
79
76
|
await Promise.all(changed.map((item) => {
|
|
80
|
-
return api('PUT', `${path}/${encodeURIComponent(item.name)}`,
|
|
77
|
+
return api('PUT', `${path}/${encodeURIComponent(item.name)}`, body(item));
|
|
81
78
|
}));
|
|
79
|
+
return { count: changed.length, current };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function pruneNamed(api, path, current, desired, owns) {
|
|
83
|
+
const stale = current.filter((item) => {
|
|
84
|
+
return owns?.(item) && !desired.some((row) => { return row.name === item.name; });
|
|
85
|
+
});
|
|
82
86
|
await Promise.all(stale.map((item) => { return api('DELETE', `${path}/${encodeURIComponent(item.name)}`); }));
|
|
83
|
-
return
|
|
87
|
+
return stale.length;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function parameter(item) {
|
|
91
|
+
return { value: item.value };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function policy(item) {
|
|
95
|
+
return { pattern: item.pattern, definition: item.definition, priority: item.priority, 'apply-to': item['apply-to'] };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function ensureVirtualHost(objects, vhost) {
|
|
99
|
+
if (objects.some((item) => { return item.vhost !== undefined && item.vhost !== vhost; })) {
|
|
100
|
+
throw new Error('topology contains a different virtual host');
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function reconcileShovels(api, path, desired, owns) {
|
|
105
|
+
const shovels = await upsertNamed(api, path, desired, parameter);
|
|
106
|
+
return shovels.count + await pruneNamed(api, path, shovels.current, desired, owns);
|
|
84
107
|
}
|
|
85
108
|
|
|
86
109
|
/** Apply only topology belonging to the selected virtual host. Users and permissions are bootstrap data. */
|
|
@@ -90,15 +113,51 @@ export default async function reconcileRabbitmq(desired, options) {
|
|
|
90
113
|
const api = apiAt(options);
|
|
91
114
|
const host = encodeURIComponent(vhost);
|
|
92
115
|
const objects = [...desired.exchanges, ...desired.queues, ...desired.bindings, ...desired.parameters];
|
|
93
|
-
|
|
94
|
-
throw new Error('topology contains a different virtual host');
|
|
95
|
-
}
|
|
116
|
+
ensureVirtualHost(objects, vhost);
|
|
96
117
|
if (desired.parameters.some((item) => { return item.component !== 'shovel'; })) {
|
|
97
118
|
throw new Error('only shovel parameters can be reconciled');
|
|
98
119
|
}
|
|
99
120
|
const exchanges = await declare(api, `exchanges/${host}`, desired.exchanges);
|
|
100
121
|
const queues = await declare(api, `queues/${host}`, desired.queues);
|
|
101
122
|
const links = await bindings(api, `bindings/${host}`, desired.bindings, ownsBinding);
|
|
102
|
-
const parameters = await
|
|
123
|
+
const parameters = await reconcileShovels(api, `parameters/shovel/${host}`, desired.parameters, ownsShovel);
|
|
103
124
|
return exchanges + queues + links + parameters;
|
|
104
125
|
}
|
|
126
|
+
|
|
127
|
+
/** Apply only dynamic shovels managed by a caller. */
|
|
128
|
+
export function reconcileRabbitmqShovels(desired, options) {
|
|
129
|
+
const { vhost, ownsShovel, api = apiAt(options) } = options;
|
|
130
|
+
if (!vhost) { throw new Error('a virtual host is required'); }
|
|
131
|
+
ensureVirtualHost(desired, vhost);
|
|
132
|
+
if (desired.some((item) => { return item.component !== 'shovel'; })) {
|
|
133
|
+
throw new Error('only shovel parameters can be reconciled');
|
|
134
|
+
}
|
|
135
|
+
return reconcileShovels(api, `parameters/shovel/${encodeURIComponent(vhost)}`, desired, ownsShovel);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Reconcile federation objects for one vhost. Only owned objects are eligible for deletion. */
|
|
139
|
+
export async function reconcileRabbitmqFederation(desired, options) {
|
|
140
|
+
const { vhost, ownsUpstream, ownsPolicy } = options;
|
|
141
|
+
if (!vhost) { throw new Error('a virtual host is required'); }
|
|
142
|
+
const upstreams = (desired.parameters || []).filter((row) => { return row.component === 'federation-upstream'; });
|
|
143
|
+
const policies = desired.policies || [];
|
|
144
|
+
ensureVirtualHost([...upstreams, ...policies], vhost);
|
|
145
|
+
const host = encodeURIComponent(vhost);
|
|
146
|
+
const api = apiAt(options);
|
|
147
|
+
const upstreamPath = `parameters/federation-upstream/${host}`;
|
|
148
|
+
const policyPath = `policies/${host}`;
|
|
149
|
+
const links = await upsertNamed(api, upstreamPath, upstreams, parameter);
|
|
150
|
+
const rules = await upsertNamed(api, policyPath, policies, policy);
|
|
151
|
+
const dropped = await pruneNamed(api, upstreamPath, links.current, upstreams, ownsUpstream);
|
|
152
|
+
const retired = await pruneNamed(api, policyPath, rules.current, policies, ownsPolicy);
|
|
153
|
+
return links.count + rules.count + dropped + retired;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Apply queue bindings and shovels before changing federation. */
|
|
157
|
+
export async function reconcileRabbitmqTopology(desired, options) {
|
|
158
|
+
const parameters = desired.parameters || [];
|
|
159
|
+
ensureVirtualHost([...parameters, ...(desired.policies || [])], options.vhost);
|
|
160
|
+
const shovels = parameters.filter((row) => { return row.component === 'shovel'; });
|
|
161
|
+
const topology = await reconcileRabbitmq({ ...desired, parameters: shovels }, options);
|
|
162
|
+
return topology + await reconcileRabbitmqFederation(desired, options);
|
|
163
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
function pulseOutput(pulse, now, pulseIntervalMs) {
|
|
2
|
+
const devices = new Map();
|
|
3
|
+
function send(device, state) {
|
|
4
|
+
const time = now();
|
|
5
|
+
if (state.busy || state.value === undefined || time < state.nextAt) { return; }
|
|
6
|
+
const { value } = state;
|
|
7
|
+
Object.assign(state, { busy: true, value: undefined, nextAt: time + pulseIntervalMs });
|
|
8
|
+
try {
|
|
9
|
+
void Promise.resolve(pulse?.(value, device)).then(
|
|
10
|
+
() => { state.busy = false; }, () => { state.busy = false; }
|
|
11
|
+
);
|
|
12
|
+
} catch {
|
|
13
|
+
state.busy = false;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return {
|
|
17
|
+
mark(value, device) {
|
|
18
|
+
const state = devices.get(device) ?? { busy: false, nextAt: -Infinity };
|
|
19
|
+
state.value = value;
|
|
20
|
+
devices.set(device, state);
|
|
21
|
+
},
|
|
22
|
+
flush() { devices.forEach((state, device) => { send(device, state); }); }
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function staleCount(channels, now) {
|
|
27
|
+
return [...channels.values()].filter((channel) => {
|
|
28
|
+
return channel.required && (channel.last === undefined || now() - channel.last > channel.maxAge);
|
|
29
|
+
}).length;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function channelStates(connections, minimumMaxAgeMs, heartbeatMultiplier) {
|
|
33
|
+
const states = new Map(connections.flatMap((connection) => {
|
|
34
|
+
return connection.channels.map((channel) => {
|
|
35
|
+
return [channel, { url: connection.url, required: connection.healthRequired !== false, last: undefined, maxAge: Math.max(minimumMaxAgeMs, heartbeatMultiplier * (connection.heartbeatMs ?? 1000)) }];
|
|
36
|
+
});
|
|
37
|
+
}));
|
|
38
|
+
const requiredDevices = new Set();
|
|
39
|
+
states.forEach((entry, channel) => { if (entry.required) { requiredDevices.add(channel.device); } });
|
|
40
|
+
states.forEach((entry, channel) => { entry.markDevice = entry.required || !requiredDevices.has(channel.device); });
|
|
41
|
+
return states;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Bad OPC values are not delivered by the source; silence therefore expires per channel. */
|
|
45
|
+
export default function opcuaHealth(connections, report, { now, schedule, pulse, minimumMaxAgeMs = 15000, heartbeatMultiplier = 3, pulseIntervalMs = 1000 }) {
|
|
46
|
+
const channels = channelStates(connections, minimumMaxAgeMs, heartbeatMultiplier);
|
|
47
|
+
const output = pulseOutput(pulse, now, pulseIntervalMs);
|
|
48
|
+
let stopped = false;
|
|
49
|
+
let previous;
|
|
50
|
+
function check(progress = false) {
|
|
51
|
+
if (stopped) { return; }
|
|
52
|
+
const stale = staleCount(channels, now);
|
|
53
|
+
const state = stale ? 'degraded' : 'running';
|
|
54
|
+
if (previous !== state || (!stale && progress)) {
|
|
55
|
+
previous = state;
|
|
56
|
+
report({ state, message: stale ? `OPC UA: ${stale} channels await fresh Good delivery` : 'OPC UA channels fresh', fatal: false, ...(!stale && progress && { read: true }) });
|
|
57
|
+
}
|
|
58
|
+
for (const [channel, entry] of channels) {
|
|
59
|
+
if (entry.required && entry.last !== undefined && now() - entry.last > entry.maxAge) {
|
|
60
|
+
output.mark(0, channel.device);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
output.flush();
|
|
64
|
+
}
|
|
65
|
+
const cancel = schedule(check);
|
|
66
|
+
check();
|
|
67
|
+
return {
|
|
68
|
+
good(channel) {
|
|
69
|
+
if (stopped) { return; }
|
|
70
|
+
const entry = channels.get(channel);
|
|
71
|
+
if (entry) {
|
|
72
|
+
entry.last = now();
|
|
73
|
+
if (entry.markDevice) { output.mark(1, channel.device); }
|
|
74
|
+
}
|
|
75
|
+
check(Boolean(entry));
|
|
76
|
+
},
|
|
77
|
+
failed(error, connection) {
|
|
78
|
+
if (stopped) { return; }
|
|
79
|
+
const devices = new Set();
|
|
80
|
+
for (const [channel, entry] of channels) {
|
|
81
|
+
if (!connection || entry.url === connection.url) {
|
|
82
|
+
entry.last = undefined;
|
|
83
|
+
if (entry.markDevice) { devices.add(channel.device); }
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
for (const device of devices) { output.mark(0, device); }
|
|
87
|
+
check();
|
|
88
|
+
},
|
|
89
|
+
stop() { stopped = true; cancel(); }
|
|
90
|
+
};
|
|
91
|
+
}
|