@yarkivaev/scada 2.18.0 → 2.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/index.js +13 -0
  2. package/package.json +4 -2
  3. package/src/application/cycleTimelineFetch.js +56 -0
  4. package/src/application/deploy/edgeDescriptors.js +31 -0
  5. package/src/application/deploy/fieldbusSourcePlan.js +79 -0
  6. package/src/application/deploy/plantBindingProfile.js +24 -0
  7. package/src/application/deploy/topologyGraph.js +81 -0
  8. package/src/application/edgeOperatorCatalog.js +9 -7
  9. package/src/application/mcp/analyticsMcpPort.js +20 -0
  10. package/src/application/mcp/analyticsNamespaceNodes.js +29 -0
  11. package/src/application/mcp/analyticsTextContent.js +13 -0
  12. package/src/application/mcp/plantReadPorts.js +168 -0
  13. package/src/application/mcp/textContentCatalog.js +7 -0
  14. package/src/application/operationPrefixes.js +67 -0
  15. package/src/application/operatorCatalogView.js +8 -0
  16. package/src/application/projectPlantShops.js +17 -0
  17. package/src/application/runtime/collectorDslManifest.js +44 -0
  18. package/src/application/runtime/collectorLaunch.js +34 -0
  19. package/src/application/runtime/collectorOptions.js +21 -0
  20. package/src/application/runtime/controlDeliveryEnvironment.js +19 -0
  21. package/src/application/runtime/embeddedCollectors.js +6 -0
  22. package/src/application/runtime/index.js +7 -1
  23. package/src/application/runtime/pagedDelivery.js +87 -0
  24. package/src/application/runtime/resolveSecrets.js +9 -0
  25. package/src/application/siteOperatorCatalog.js +8 -7
  26. package/src/application/siteRuntime/checkpointedOperationPoll.js +77 -0
  27. package/src/application/siteRuntime/cutoverOperations.js +25 -0
  28. package/src/application/siteRuntime/databaseMigrations.js +27 -0
  29. package/src/application/siteRuntime/edgeMetricsStore.js +35 -0
  30. package/src/application/siteRuntime/history.js +29 -0
  31. package/src/application/siteRuntime/index.js +16 -0
  32. package/src/application/siteRuntime/measurementTopic.js +9 -0
  33. package/src/application/siteRuntime/operationFederation.js +15 -0
  34. package/src/application/siteRuntime/operationSnapshot.js +18 -0
  35. package/src/application/siteRuntime/operatorField.js +49 -0
  36. package/src/application/siteRuntime/operatorUpdates.js +37 -0
  37. package/src/application/siteRuntime/telemetry.js +31 -0
  38. package/src/application/siteRuntime/telemetryBackfillCommand.js +64 -0
  39. package/src/application/timelineMetrics.js +36 -0
  40. package/src/domain/timeline/cyclePhases.js +191 -0
  41. package/src/infrastructure/deploy/brokerFleetPolicy.js +91 -0
  42. package/src/infrastructure/deploy/configuredArchivePlan.js +25 -0
  43. package/src/infrastructure/deploy/configuredBrokerRoutes.js +34 -0
  44. package/src/infrastructure/deploy/configuredClassification.js +74 -0
  45. package/src/infrastructure/deploy/configuredControlPlane.js +116 -0
  46. package/src/infrastructure/deploy/configuredDeploymentCredentials.js +45 -0
  47. package/src/infrastructure/deploy/configuredEtcdInventory.js +30 -0
  48. package/src/infrastructure/deploy/configuredRuntimeCapabilities.js +14 -0
  49. package/src/infrastructure/deploy/configuredSiteAssets.js +50 -0
  50. package/src/infrastructure/deploy/configuredStagedDeployment.js +48 -0
  51. package/src/infrastructure/deploy/highAvailability/configuredBrokerReconciliation.js +21 -0
  52. package/src/infrastructure/deploy/highAvailability/index.js +1 -0
  53. package/src/infrastructure/deploy/index.js +19 -0
  54. package/src/infrastructure/deploy/mixedStoreHistory.js +27 -0
  55. package/src/infrastructure/deploy/publicBrokerPlan.js +15 -0
  56. package/src/infrastructure/deploy/siteBrokerDefinitions.js +97 -0
  57. package/src/infrastructure/deploy/stagedSitePlan.js +132 -0
  58. package/src/infrastructure/deploy/supervisedServicePlan.js +82 -0
  59. package/src/infrastructure/http/edge/attachClassify.js +30 -0
  60. package/src/infrastructure/http/edge/classifyProxy.js +72 -0
  61. package/src/infrastructure/http/edge/classifyRecord.js +32 -0
  62. package/src/infrastructure/http/edge/classifyRouting.js +14 -0
  63. package/src/infrastructure/http/edge/siteAccess.js +7 -0
  64. package/src/infrastructure/http/edge/writeGuard.js +84 -0
  65. package/src/infrastructure/http/plant/routes/machineOperationList.js +18 -0
  66. package/src/infrastructure/http/plant/routes/operationRoute.js +2 -11
  67. package/src/infrastructure/http/plant/routes/operatorRoute.js +25 -0
  68. package/src/infrastructure/http/plant/streams/operationStream.js +25 -37
  69. package/src/infrastructure/ingest/mqtt/modbusDeviceSpec.js +5 -28
  70. package/src/infrastructure/ingest/mqtt/registerPoint.js +2 -2
  71. package/src/infrastructure/mdmesh/adminReconciliation.js +19 -0
  72. package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +4 -4
  73. package/src/infrastructure/mdmesh/controllerOperation.js +17 -0
  74. package/src/infrastructure/mdmesh/index.js +3 -0
  75. package/src/infrastructure/mdmesh/publishApk.js +30 -0
  76. package/src/infrastructure/persistence/clickhouse/metricBursts.js +73 -0
  77. package/src/infrastructure/persistence/pg/cyclePhaseQuery.js +168 -0
  78. package/src/infrastructure/persistence/pg/cyclePrior.js +96 -0
  79. package/src/infrastructure/persistence/pg/operatorFieldStore.js +50 -0
  80. package/src/infrastructure/streams/boundedTextFrames.js +27 -0
  81. package/src/infrastructure/streams/framedSerialSource.js +25 -0
  82. package/src/infrastructure/streams/index.js +5 -0
  83. package/src/infrastructure/streams/namedSerialDevices.js +26 -0
  84. package/src/infrastructure/streams/serialLine.js +26 -0
  85. package/src/infrastructure/streams/watchCurrentReading.js +31 -0
  86. package/src/infrastructure/streams/windowPublication.js +73 -0
@@ -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
+ }
@@ -0,0 +1,14 @@
1
+ import { permit } from '../../deploy/highAvailability/classifyGate.js';
2
+
3
+ /** Select the request owner given the application's mapping from request URL to group. */
4
+ export default function classifyRouting(groupFor) {
5
+ return (nodeId, record, urls, path) => {
6
+ const group = groupFor(path);
7
+ if (!group) { return { kind: 'local' }; }
8
+ const row = record?.[group];
9
+ if (permit(nodeId, row) === 'run') { return { kind: 'local' }; }
10
+ if (row?.pending === nodeId) { return { kind: 'wait' }; }
11
+ if (row?.active && row.active !== nodeId && urls[row.active]) { return { kind: 'proxy', node: row.active }; }
12
+ return { kind: 'wait' };
13
+ };
14
+ }
@@ -0,0 +1,7 @@
1
+ export { default as attachClassify } from './attachClassify.js';
2
+ export { default as classifyRecord } from './classifyRecord.js';
3
+ export { installClassifyProxy } from './classifyProxy.js';
4
+ export { default as writeGuard, proxyPolicy, trustedGroups } from './writeGuard.js';
5
+ export { default as classifyRouting } from './classifyRouting.js';
6
+ export { operationEvents } from '../plant/streams/operationStream.js';
7
+ export { default as machineOperationList } from '../plant/routes/machineOperationList.js';
@@ -0,0 +1,84 @@
1
+ import { timingSafeEqual } from 'node:crypto';
2
+ import { errorResponse } from '@yarkivaev/simple-server';
3
+
4
+ function strongProxyToken(value) {
5
+ return typeof value === 'string' && value.length === 64 && /^[a-fA-F0-9]{64}$/u.test(value);
6
+ }
7
+
8
+ /** Explicit rollout gate: legacy callers retain current behavior until enabled. */
9
+ export function proxyPolicy(environment = process.env) {
10
+ const required = environment.SCADA_TRUSTED_PROXY_REQUIRED ?? 'false';
11
+ if (!['true','false'].includes(required)) { throw new Error('SCADA_TRUSTED_PROXY_REQUIRED must be true or false'); }
12
+ const token = environment.SCADA_TRUSTED_PROXY_TOKEN || '';
13
+ if (required === 'true' && !strongProxyToken(token)) {
14
+ throw new Error('SCADA_TRUSTED_PROXY_TOKEN must contain 64 hexadecimal characters');
15
+ }
16
+ return {required:required === 'true',token};
17
+ }
18
+
19
+ function identityTrusted(headers, policy) {
20
+ if (!policy.required) { return true; }
21
+ const presented = headers['x-scada-proxy-token'];
22
+ return strongProxyToken(presented)
23
+ && timingSafeEqual(Buffer.from(presented),Buffer.from(policy.token));
24
+ }
25
+
26
+ export function trustedGroups(headers, policy) {
27
+ return identityTrusted(headers,policy) ? headers['remote-groups'] || '' : '';
28
+ }
29
+
30
+ function sanitizeIdentity(headers, policy) {
31
+ if (!identityTrusted(headers,policy)) {
32
+ for (const header of ['remote-groups','remote-user','remote-email','remote-name']) { delete headers[header]; }
33
+ }
34
+ }
35
+
36
+ /** Build authorization for configured groups and an optional service bearer. */
37
+ export default function writeGuard(roles) {
38
+ const roleSet = new Set(roles);
39
+ function granted(groups) {
40
+ return String(groups || '').split(',').some((group) => { return roleSet.has(group.trim()); });
41
+ }
42
+
43
+ /**
44
+ * Returns whether this method and caller may change plant state.
45
+ *
46
+ * @param {string} method - HTTP method
47
+ * @param {string} groups - Remote-Groups header
48
+ * @param {string} authorization - Authorization header
49
+ * @param {string} serviceToken - expected bearer for owner-routed writes
50
+ * @returns {boolean} true when the call may proceed
51
+ */
52
+ function allowsMutation(method, groups, authorization, serviceToken) {
53
+ if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') {
54
+ return true;
55
+ }
56
+ if (granted(groups)) {
57
+ return true;
58
+ }
59
+ return Boolean(serviceToken) && authorization === `Bearer ${serviceToken}`;
60
+ }
61
+
62
+ /**
63
+ * Replaces the plant server request listener with the write role check.
64
+ *
65
+ * @param {object} httpServer - Node HTTP server from plantServer
66
+ * @param {object} api - plant API with handle()
67
+ * @param {string} serviceToken - bearer accepted for service writes
68
+ */
69
+ function installWriteGuard(httpServer, api, serviceToken, environment = process.env) {
70
+ const policy = proxyPolicy(environment);
71
+ httpServer.removeAllListeners('request');
72
+ httpServer.on('request', (req, res) => {
73
+ sanitizeIdentity(req.headers,policy);
74
+ const groups = trustedGroups(req.headers,policy);
75
+ const authorization = req.headers.authorization || '';
76
+ if (allowsMutation(req.method, groups, authorization, serviceToken)) {
77
+ api.handle(req, res);
78
+ return;
79
+ }
80
+ errorResponse('FORBIDDEN', `write role required for ${req.method}`, 403).send(res);
81
+ });
82
+ }
83
+ return { granted, allowsMutation, installWriteGuard };
84
+ }
@@ -0,0 +1,18 @@
1
+ import { jsonResponse, route } from '@yarkivaev/simple-server';
2
+ import machineInPlant from '../../../../application/machineInPlant.js';
3
+
4
+ export function operationRange(query) {
5
+ return { ...(query.from && { from: new Date(query.from) }), ...(query.to && { to: new Date(query.to) }) };
6
+ }
7
+
8
+ /** Read a fixed operation kind through its application projection. */
9
+ export default function machineOperationList(path, plant, { kind, project }) {
10
+ return route('GET', path, async (req, res, { machineId }, query) => {
11
+ if (!machineInPlant(plant, machineId) || !plant.operations) {
12
+ jsonResponse({ items: [] }).send(res);
13
+ return;
14
+ }
15
+ const rows = await plant.operations.listForMachine(machineId, kind, operationRange(query));
16
+ jsonResponse({ items: rows.map(project) }).send(res);
17
+ });
18
+ }
@@ -5,16 +5,7 @@ import operationWrites from './operationWrites.js';
5
5
  import httpOperations from '../../../messaging/ownership/httpOperations.js';
6
6
  import { jsonResponse, route, sendRouteError } from '@yarkivaev/simple-server';
7
7
 
8
- function parseRange(query) {
9
- const range = {};
10
- if (query.from) {
11
- range.from = new Date(query.from);
12
- }
13
- if (query.to) {
14
- range.to = new Date(query.to);
15
- }
16
- return range;
17
- }
8
+ import { operationRange } from './machineOperationList.js';
18
9
 
19
10
  function resolveKinds(query) {
20
11
  if (query.kinds) {
@@ -45,7 +36,7 @@ async function listLocal(plant, machineId, query) {
45
36
  const rows = await plant.operations.listForMachine(
46
37
  machineId,
47
38
  resolveKinds(query),
48
- parseRange(query)
39
+ operationRange(query)
49
40
  );
50
41
  return { items: rows.map(operationJson) };
51
42
  }
@@ -141,3 +141,28 @@ export default function operatorRoute(basePath, provider, logger) {
141
141
  })
142
142
  ];
143
143
  }
144
+
145
+ function fieldFromBody(parsed, field, validate) {
146
+ if (!parsed || typeof parsed !== 'object') {
147
+ throw routeFailure('BAD_REQUEST', 'operator body must be a JSON object', 400);
148
+ }
149
+ if (!Object.hasOwn(parsed, field)) {
150
+ throw routeFailure('BAD_REQUEST', `operator body must include ${field}`, 400);
151
+ }
152
+ return { [field]: validate(parsed[field]) };
153
+ }
154
+
155
+ /** Add a PATCH route for a separately managed operator field. */
156
+ export function operatorFieldRoute(basePath, provider, { field, validate }, logger) {
157
+ return [route('PATCH', `${basePath}/operators/:id`, async (req, res, params) => {
158
+ try {
159
+ const fields = fieldFromBody(JSON.parse(await readBody(req)), field, validate);
160
+ const updated = await provider.update(params.id, fields);
161
+ jsonResponse(operatorJson(updated)).send(res);
162
+ } catch (error) {
163
+ if (sendKnown(res, error)) { return; }
164
+ report(logger, `PATCH ${basePath}/operators/${params.id} failed: ${error?.message || 'unknown error'}`, error);
165
+ sendRouteError(res, error);
166
+ }
167
+ })];
168
+ }
@@ -1,42 +1,30 @@
1
1
  import operationJson from '../json/operationJson.js';
2
2
  import { route, sseResponse } from '@yarkivaev/simple-server';
3
3
 
4
- /**
5
- * Operations SSE route for plant-wide create, update, and delete events.
6
- *
7
- * @param {string} basePath - base URL path
8
- * @param {object} plant - plant domain object
9
- * @param {function} clock - time provider
10
- * @returns {array} route objects
11
- *
12
- * @example
13
- * operationStream('/api/v1', plant, clock);
14
- */
4
+ /** Serve operation events with one heartbeat and subscription per connection. */
5
+ export function operationEvents(path, plant, clock, { names, project, filter = () => { return true; }, available = () => { return true; } }) {
6
+ return route('GET', path, (req, res, params) => {
7
+ const sse = sseResponse(res, clock);
8
+ sse.heartbeat();
9
+ if (!plant.operations || !available(params)) {
10
+ sse.close();
11
+ return;
12
+ }
13
+ const subscription = plant.operations.stream(({ type, operation }) => {
14
+ if (!operation || !filter(operation, params)) { return; }
15
+ if (Object.hasOwn(names, type)) { sse.emit(names[type], project(operation)); }
16
+ });
17
+ const heartbeat = setInterval(() => { sse.heartbeat(); }, 30000);
18
+ req.on('close', () => {
19
+ clearInterval(heartbeat);
20
+ subscription.cancel();
21
+ });
22
+ });
23
+ }
24
+
25
+ /** Plant-wide create, update, and delete events. */
15
26
  export default function operationStream(basePath, plant, clock) {
16
- return [
17
- route('GET', `${basePath}/operations/stream`, (req, res) => {
18
- const sse = sseResponse(res, clock);
19
- sse.heartbeat();
20
- if (!plant.operations) {
21
- sse.close();
22
- return;
23
- }
24
- const subscription = plant.operations.stream((event) => {
25
- if (event.type === 'created' && event.operation) {
26
- sse.emit('operation_created', operationJson(event.operation));
27
- } else if (event.type === 'updated' && event.operation) {
28
- sse.emit('operation_updated', operationJson(event.operation));
29
- } else if (event.type === 'deleted' && event.operation) {
30
- sse.emit('operation_deleted', operationJson(event.operation));
31
- }
32
- });
33
- const heartbeat = setInterval(() => {
34
- sse.heartbeat();
35
- }, 30000);
36
- req.on('close', () => {
37
- clearInterval(heartbeat);
38
- subscription.cancel();
39
- });
40
- })
41
- ];
27
+ return [operationEvents(`${basePath}/operations/stream`, plant, clock, {
28
+ names: { created: 'operation_created', updated: 'operation_updated', deleted: 'operation_deleted' }, project: operationJson
29
+ })];
42
30
  }
@@ -1,3 +1,7 @@
1
+ import serialLine from '../../streams/serialLine.js';
2
+
3
+ export { serialLine as parseModbusLineFormat };
4
+
1
5
  /**
2
6
  * Parses Modbus device connection specs from MODBUS_DEVICES entries.
3
7
  *
@@ -9,33 +13,6 @@
9
13
  * parseModbusDeviceSpec('m-2:192.0.2.11:502');
10
14
  */
11
15
 
12
- /**
13
- * Parses serial line format such as 8N1 into modbus-serial options.
14
- *
15
- * @param {string} line - Data bits, parity letter, stop bits (e.g. 8N1)
16
- * @returns {object} dataBits, parity, stopBits
17
- */
18
- export function parseModbusLineFormat(line) {
19
- if (typeof line !== 'string' || line.length !== 3) {
20
- throw new Error(`Serial line format must be three characters such as 8N1, got: ${line}`);
21
- }
22
- const dataBits = parseInt(line.charAt(0), 10);
23
- const parityLetter = line.charAt(1).toUpperCase();
24
- const stopBits = parseInt(line.charAt(2), 10);
25
- let parity = '';
26
- if (parityLetter === 'N') {
27
- parity = 'none';
28
- } else if (parityLetter === 'E') {
29
- parity = 'even';
30
- } else if (parityLetter === 'O') {
31
- parity = 'odd';
32
- }
33
- if (parity.length === 0 || Number.isNaN(dataBits) || Number.isNaN(stopBits)) {
34
- throw new Error(`Serial line format must be such as 8N1, got: ${line}`);
35
- }
36
- return { dataBits, parity, stopBits };
37
- }
38
-
39
16
  /**
40
17
  * Parses RTU device spec parts into connection parameters.
41
18
  *
@@ -65,7 +42,7 @@ function parseRtuDeviceSpec(spec, parts) {
65
42
  serial: {
66
43
  baudRate,
67
44
  slaveId,
68
- ...parseModbusLineFormat(line)
45
+ ...serialLine(line)
69
46
  }
70
47
  };
71
48
  }
@@ -57,7 +57,7 @@ function placed(order, first, second) {
57
57
  * @param {number} second - second register in the window
58
58
  * @returns {number} decoded float
59
59
  */
60
- function floatOf(order, first, second) {
60
+ export function modbusFloat(order, first, second) {
61
61
  const pair = placed(order, first, second);
62
62
  const buffer = new ArrayBuffer(4);
63
63
  const view = new DataView(buffer);
@@ -86,5 +86,5 @@ export function decodePoint(point, origin, registers) {
86
86
  if (parsed.order === orders.uint16) {
87
87
  return registers[index];
88
88
  }
89
- return floatOf(parsed.order, registers[index], registers[index + 1]);
89
+ return modbusFloat(parsed.order, registers[index], registers[index + 1]);
90
90
  }
@@ -0,0 +1,19 @@
1
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { mdmeshPasswordHash } from './bootstrapMdmeshCredentials.js';
5
+
6
+ /** Restore the declared native administrator before its release job runs. */
7
+ export default function adminReconciliation(plan, kube, policy) {
8
+ if (!plan.values.admin) { return; }
9
+ const { password } = plan.values.admin;
10
+ const hash = mdmeshPasswordHash(password);
11
+ const data = { ADMIN_PASSWORD: Buffer.from(password).toString('base64'), ADMIN_PASSWORD_HASH: Buffer.from(hash).toString('base64') };
12
+ const directory = mkdtempSync(path.join(tmpdir(), 'hmi-admin-'));
13
+ try {
14
+ const file = path.join(directory, 'patch.json');
15
+ writeFileSync(file, JSON.stringify({ data }), { mode: 0o600 });
16
+ kube(['patch', 'secret', plan.values.secret, '--type=merge', `--patch-file=${file}`]);
17
+ } finally { rmSync(directory, { recursive: true, force: true }); }
18
+ kube(['delete', 'job', '-l', policy.selector, '--ignore-not-found=true', '--wait=true', '--timeout=60s']);
19
+ }
@@ -1,7 +1,7 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
2
  import { readFileSync } from 'node:fs';
3
3
 
4
- function hash(input) {
4
+ export function mdmeshPasswordHash(input) {
5
5
  return createHash('sha1').update(`${createHash('md5').update(input).digest('hex').toUpperCase()}5YdSYHyg2U`).digest('hex');
6
6
  }
7
7
 
@@ -13,9 +13,9 @@ function connectionSecret(name, namespace, declared) {
13
13
  const monitor = password();
14
14
  const values = {
15
15
  DB_USER: 'mdmesh', DB_PASSWORD: password(), HASH_SECRET: randomBytes(32).toString('hex'), JWT_SECRET: randomBytes(64).toString('hex'),
16
- ADMIN_PASSWORD: admin, ADMIN_PASSWORD_HASH: hash(admin), ADMIN_RESET_TOKEN: randomBytes(20).toString('hex'),
17
- API_LOGIN: 'hmi-controller', API_PASSWORD: api, API_PASSWORD_HASH: hash(api),
18
- MONITOR_LOGIN: 'hmi-monitor', MONITOR_PASSWORD: monitor, MONITOR_PASSWORD_HASH: hash(monitor), CONTROL_TOKEN: password()
16
+ ADMIN_PASSWORD: admin, ADMIN_PASSWORD_HASH: mdmeshPasswordHash(admin), ADMIN_RESET_TOKEN: randomBytes(20).toString('hex'),
17
+ API_LOGIN: 'hmi-controller', API_PASSWORD: api, API_PASSWORD_HASH: mdmeshPasswordHash(api),
18
+ MONITOR_LOGIN: 'hmi-monitor', MONITOR_PASSWORD: monitor, MONITOR_PASSWORD_HASH: mdmeshPasswordHash(monitor), CONTROL_TOKEN: password()
19
19
  };
20
20
  return { apiVersion: 'v1', kind: 'Secret', metadata: { name, namespace }, type: 'Opaque',
21
21
  data: Object.fromEntries(Object.entries(values).map(([key, value]) => { return [key, Buffer.from(value).toString('base64')]; })) };
@@ -0,0 +1,17 @@
1
+ import requestFromWorkload from '../deploy/requestFromWorkload.js';
2
+
3
+ /** Route controller operations to the running workload with catalog and target validation. */
4
+ export default function controllerOperation(action, plan, kube, device, policy) {
5
+ const operation = Object.hasOwn(policy.actions, action) && policy.actions[action];
6
+ if (!operation) { throw new Error('Unknown HMI operation'); }
7
+ const { catalog } = plan.values;
8
+ if (operation.device && !catalog.devices.some(({ id }) => { return id === device; })) {
9
+ throw new Error('HMI action requires a declared tablet');
10
+ }
11
+ return requestFromWorkload(kube, {
12
+ workload: policy.workload, url: `${policy.baseUrl}/${operation.path}`, method: operation.method,
13
+ tokenEnv: policy.tokenEnv, configuration: { ...policy.configuration, expected: catalog },
14
+ body: operation.device ? { device, action } : undefined,
15
+ requireApplied: operation.requireApplied === true
16
+ });
17
+ }
@@ -8,3 +8,6 @@ export { default as mdmeshClient } from './mdmeshClient.js';
8
8
  export { default as hmiPlan } from './hmiPlan.js';
9
9
  export { default as mdmeshServerRelease } from './mdmeshServerRelease.js';
10
10
  export { default as bootstrapMdmeshCredentials } from './bootstrapMdmeshCredentials.js';
11
+ export { default as adminReconciliation } from './adminReconciliation.js';
12
+ export { default as controllerOperation } from './controllerOperation.js';
13
+ export { default as publishApk } from './publishApk.js';
@@ -0,0 +1,30 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import deploymentTemplate from '../deploy/deploymentTemplate.js';
5
+
6
+ function validatedArtifact(plan, device, artifact) {
7
+ const target = plan.values.catalog.devices.find(({ id }) => { return id === device; })?.application?.apk;
8
+ const filename = target && path.basename(new URL(target.url).pathname);
9
+ if (!filename || !/^[a-z0-9-]+\.apk$/u.test(filename)) { throw new Error('HMI publishing requires a declared APK'); }
10
+ if (createHash('sha256').update(readFileSync(artifact)).digest('hex') !== target.sha256) {
11
+ throw new Error('HMI APK does not match its DSL SHA-256');
12
+ }
13
+ return { filename, sha256: target.sha256 };
14
+ }
15
+
16
+ /** Copy a pinned APK to a declared volume via a temporary Pod and verify before publication. */
17
+ export default function publishApk(plan, device, artifact, kube, policy) {
18
+ const { filename, sha256 } = validatedArtifact(plan, device, artifact);
19
+ const { podName: name } = policy;
20
+ const { directory } = policy;
21
+ if (!/^\/[a-z0-9-]+(?:\/[a-z0-9-]+)*$/u.test(directory)) { throw new TypeError('Invalid APK volume path'); }
22
+ const pod = deploymentTemplate(policy.pod, { name, values: plan.values });
23
+ kube(['create', '-f', '-'], JSON.stringify(pod));
24
+ try {
25
+ kube(['wait', '--for=condition=Ready', `pod/${name}`, '--timeout=120s']);
26
+ kube(['cp', artifact, `${name}:/tmp/artifact.apk`]);
27
+ return kube(['exec', name, '--', 'sh', '-ec',
28
+ `printf '%s /tmp/artifact.apk\\n' '${sha256}' | sha256sum -c -; mkdir -p ${directory}; cp /tmp/artifact.apk ${directory}/${filename}.tmp; chmod 644 ${directory}/${filename}.tmp; mv ${directory}/${filename}.tmp ${directory}/${filename}`]);
29
+ } finally { kube(['delete', 'pod', name, '--wait=true', '--timeout=30s']); }
30
+ }