@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.
Files changed (98) hide show
  1. package/index.js +17 -0
  2. package/package.json +4 -2
  3. package/src/application/cycleTimelineFetch.js +56 -0
  4. package/src/application/deploy/collectorProcesses.js +1 -0
  5. package/src/application/deploy/collectorSourcePlan.js +41 -0
  6. package/src/application/deploy/compileCollectorTasks.js +2 -2
  7. package/src/application/deploy/edgeDescriptors.js +31 -0
  8. package/src/application/deploy/fieldbusSourcePlan.js +93 -0
  9. package/src/application/deploy/plantBindingProfile.js +24 -0
  10. package/src/application/deploy/topologyGraph.js +81 -0
  11. package/src/application/edgeOperatorCatalog.js +9 -7
  12. package/src/application/mcp/analyticsMcpPort.js +20 -0
  13. package/src/application/mcp/analyticsNamespaceNodes.js +29 -0
  14. package/src/application/mcp/analyticsTextContent.js +13 -0
  15. package/src/application/mcp/plantReadPorts.js +168 -0
  16. package/src/application/mcp/textContentCatalog.js +7 -0
  17. package/src/application/operationPrefixes.js +67 -0
  18. package/src/application/operatorCatalogView.js +8 -0
  19. package/src/application/projectPlantShops.js +17 -0
  20. package/src/application/runtime/collectorDslManifest.js +44 -0
  21. package/src/application/runtime/collectorLaunch.js +34 -0
  22. package/src/application/runtime/collectorOptions.js +21 -0
  23. package/src/application/runtime/controlDeliveryEnvironment.js +19 -0
  24. package/src/application/runtime/embeddedCollectors.js +6 -0
  25. package/src/application/runtime/index.js +7 -1
  26. package/src/application/runtime/pagedDelivery.js +87 -0
  27. package/src/application/runtime/resolveSecrets.js +9 -0
  28. package/src/application/siteOperatorCatalog.js +8 -7
  29. package/src/application/siteRuntime/checkpointedOperationPoll.js +77 -0
  30. package/src/application/siteRuntime/cutoverOperations.js +25 -0
  31. package/src/application/siteRuntime/databaseMigrations.js +27 -0
  32. package/src/application/siteRuntime/edgeMetricsStore.js +35 -0
  33. package/src/application/siteRuntime/history.js +29 -0
  34. package/src/application/siteRuntime/index.js +16 -0
  35. package/src/application/siteRuntime/measurementTopic.js +9 -0
  36. package/src/application/siteRuntime/operationFederation.js +15 -0
  37. package/src/application/siteRuntime/operationSnapshot.js +18 -0
  38. package/src/application/siteRuntime/operatorField.js +49 -0
  39. package/src/application/siteRuntime/operatorUpdates.js +37 -0
  40. package/src/application/siteRuntime/telemetry.js +31 -0
  41. package/src/application/siteRuntime/telemetryBackfillCommand.js +64 -0
  42. package/src/application/timelineMetrics.js +36 -0
  43. package/src/domain/timeline/cyclePhases.js +191 -0
  44. package/src/domain/timeline/taggedCycleWindows.js +17 -0
  45. package/src/domain/timeline/taggedSegment.js +47 -0
  46. package/src/domain/timeline/taggedTimeline.js +98 -0
  47. package/src/domain/timeline/timelineSegment.js +25 -0
  48. package/src/infrastructure/deploy/brokerFleetPolicy.js +91 -0
  49. package/src/infrastructure/deploy/configuredArchivePlan.js +25 -0
  50. package/src/infrastructure/deploy/configuredBrokerRoutes.js +34 -0
  51. package/src/infrastructure/deploy/configuredClassification.js +74 -0
  52. package/src/infrastructure/deploy/configuredCollectorChartDeployment.js +22 -0
  53. package/src/infrastructure/deploy/configuredControlPlane.js +116 -0
  54. package/src/infrastructure/deploy/configuredDeploymentCredentials.js +45 -0
  55. package/src/infrastructure/deploy/configuredEtcdInventory.js +30 -0
  56. package/src/infrastructure/deploy/configuredRuntimeCapabilities.js +14 -0
  57. package/src/infrastructure/deploy/configuredSiteAssets.js +50 -0
  58. package/src/infrastructure/deploy/configuredStagedDeployment.js +48 -0
  59. package/src/infrastructure/deploy/controlPlaneCli.js +17 -0
  60. package/src/infrastructure/deploy/highAvailability/configuredBrokerReconciliation.js +21 -0
  61. package/src/infrastructure/deploy/highAvailability/historyWatermark.js +2 -2
  62. package/src/infrastructure/deploy/highAvailability/index.js +3 -1
  63. package/src/infrastructure/deploy/highAvailability/replicaHistoryStore.js +7 -0
  64. package/src/infrastructure/deploy/index.js +22 -1
  65. package/src/infrastructure/deploy/mixedStoreHistory.js +27 -0
  66. package/src/infrastructure/deploy/publicBrokerPlan.js +15 -0
  67. package/src/infrastructure/deploy/siteBrokerDefinitions.js +97 -0
  68. package/src/infrastructure/deploy/stagedSitePlan.js +132 -0
  69. package/src/infrastructure/deploy/supervisedServicePlan.js +82 -0
  70. package/src/infrastructure/http/edge/attachClassify.js +30 -0
  71. package/src/infrastructure/http/edge/classifyProxy.js +72 -0
  72. package/src/infrastructure/http/edge/classifyRecord.js +32 -0
  73. package/src/infrastructure/http/edge/classifyRouting.js +14 -0
  74. package/src/infrastructure/http/edge/siteAccess.js +7 -0
  75. package/src/infrastructure/http/edge/writeGuard.js +84 -0
  76. package/src/infrastructure/http/plant/routes/machineOperationList.js +18 -0
  77. package/src/infrastructure/http/plant/routes/operationRoute.js +2 -11
  78. package/src/infrastructure/http/plant/routes/operatorRoute.js +25 -0
  79. package/src/infrastructure/http/plant/streams/operationStream.js +25 -37
  80. package/src/infrastructure/ingest/mqtt/modbusDeviceSpec.js +5 -28
  81. package/src/infrastructure/ingest/mqtt/registerPoint.js +2 -2
  82. package/src/infrastructure/mdmesh/adminReconciliation.js +19 -0
  83. package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +4 -4
  84. package/src/infrastructure/mdmesh/controllerOperation.js +17 -0
  85. package/src/infrastructure/mdmesh/index.js +3 -0
  86. package/src/infrastructure/mdmesh/publishApk.js +30 -0
  87. package/src/infrastructure/persistence/clickhouse/metricBursts.js +73 -0
  88. package/src/infrastructure/persistence/pg/cyclePhaseQuery.js +168 -0
  89. package/src/infrastructure/persistence/pg/cyclePrior.js +96 -0
  90. package/src/infrastructure/persistence/pg/operatorFieldStore.js +50 -0
  91. package/src/infrastructure/streams/boundedTextFrames.js +27 -0
  92. package/src/infrastructure/streams/framedSerialSource.js +25 -0
  93. package/src/infrastructure/streams/index.js +6 -0
  94. package/src/infrastructure/streams/namedSerialDevices.js +26 -0
  95. package/src/infrastructure/streams/pollSnapshot.js +11 -0
  96. package/src/infrastructure/streams/serialLine.js +26 -0
  97. package/src/infrastructure/streams/watchCurrentReading.js +31 -0
  98. package/src/infrastructure/streams/windowPublication.js +73 -0
@@ -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
+ }
@@ -0,0 +1,73 @@
1
+ /* eslint camelcase: off */
2
+ import { rawMetricsRange } from './metricsRelation.js';
3
+
4
+ function formatDateTime(value) {
5
+ return value.toISOString().replace('Z', '').replace('T', ' ');
6
+ }
7
+
8
+ /** Find peak samples in topic bursts using only retained raw observations. */
9
+ export const metricBurstSql = `
10
+ SELECT
11
+ topic,
12
+ peak,
13
+ occurred_at
14
+ FROM (
15
+ SELECT
16
+ topic,
17
+ max(value) AS peak,
18
+ argMax(ts, value) AS occurred_at,
19
+ max(ts) AS ended_at,
20
+ count() AS points
21
+ FROM (
22
+ SELECT
23
+ topic,
24
+ ts,
25
+ value,
26
+ sum(is_start) OVER (
27
+ PARTITION BY topic
28
+ ORDER BY ts
29
+ ROWS UNBOUNDED PRECEDING
30
+ ) AS burst_id
31
+ FROM (
32
+ SELECT
33
+ topic,
34
+ ts,
35
+ value,
36
+ if(
37
+ dateDiff(
38
+ 'second',
39
+ lagInFrame(ts) OVER (
40
+ PARTITION BY topic
41
+ ORDER BY ts
42
+ ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
43
+ ),
44
+ ts
45
+ ) > {gapSeconds:UInt32},
46
+ toUInt8(1),
47
+ toUInt8(0)
48
+ ) AS is_start
49
+ FROM ${rawMetricsRange('toUnixTimestamp64Milli({rangeFrom:DateTime64(3)})', 'toUnixTimestamp64Milli({rangeTo:DateTime64(3)})')}
50
+ WHERE topic IN {topics:Array(String)}
51
+ AND ts >= {rangeFrom:DateTime64(3)}
52
+ AND ts <= {rangeTo:DateTime64(3)}
53
+ )
54
+ )
55
+ GROUP BY topic, burst_id
56
+ )
57
+ WHERE points >= {minPoints:UInt32}
58
+ AND peak >= {minPeak:Float64}
59
+ AND dateDiff('second', ended_at, now64(3)) > {gapSeconds:UInt32}
60
+ ORDER BY topic, occurred_at
61
+ `;
62
+
63
+ /** Bounded peak queries across topics. The quiet window excludes incomplete bursts. */
64
+ export default function metricBursts(connection, { gapSeconds, minPoints, minPeak }) {
65
+ if (typeof connection?.query !== 'function') { throw new TypeError('ClickHouse connection with query() is required for metric bursts'); }
66
+ return {
67
+ list(topics, { from, to }) {
68
+ return connection.query(metricBurstSql, {
69
+ topics, rangeFrom: formatDateTime(from), rangeTo: formatDateTime(to), gapSeconds, minPoints, minPeak
70
+ });
71
+ }
72
+ };
73
+ }
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Asks Postgres for the cycle phase at each off-segment start.
3
+ * The (machine, kind, start_time) index walks backward to the nearest
4
+ * cycle anchor and returns one phase id per instant, not the history.
5
+ *
6
+ * @param {object} pool - pg pool
7
+ * @param {string} machineId - machine id
8
+ * @param {Array<object>} rows - window rows, including ones not stored yet
9
+ * @param {object} anchors - start id and stop ids
10
+ * @param {Array<string>} enters - phase enter ids
11
+ * @returns {Promise<Map<number, string>>} start epoch ms to phase id
12
+ *
13
+ * @example
14
+ * const phases = await cyclePhaseQuery(pool, 'meter-a', rows, anchors, enters);
15
+ */
16
+ const phaseSql = `WITH incoming AS (
17
+ SELECT u.start_time, u.tags
18
+ FROM unnest($2::timestamptz[], $3::text[]) AS u(start_time, tags)
19
+ ), ask AS (
20
+ SELECT DISTINCT asked.moment
21
+ FROM unnest($4::timestamptz[]) AS asked(moment)
22
+ ), bounds AS (
23
+ SELECT min(moment) AS oldest, max(moment) AS newest FROM ask
24
+ ), stored_anchor AS (
25
+ SELECT hit.start_time, hit.tags
26
+ FROM bounds
27
+ LEFT JOIN LATERAL (
28
+ SELECT s.start_time, s.tags
29
+ FROM segments s
30
+ WHERE s.machine = $1 AND s.kind = 'phase' AND s.start_time < bounds.oldest
31
+ AND EXISTS (
32
+ SELECT 1 FROM unnest($9::text[]) AS needle
33
+ WHERE position(needle in s.tags) > 0
34
+ )
35
+ ORDER BY s.start_time DESC
36
+ LIMIT 1
37
+ ) hit ON true
38
+ ), memory_anchor AS (
39
+ SELECT i.start_time, i.tags
40
+ FROM incoming i
41
+ CROSS JOIN bounds
42
+ WHERE i.start_time < bounds.oldest
43
+ AND EXISTS (
44
+ SELECT 1 FROM unnest($9::text[]) AS needle
45
+ WHERE position(needle in i.tags) > 0
46
+ )
47
+ ORDER BY i.start_time DESC
48
+ LIMIT 1
49
+ ), anchor AS (
50
+ SELECT picked.start_time, picked.tags
51
+ FROM (
52
+ SELECT start_time, tags FROM stored_anchor WHERE start_time IS NOT NULL
53
+ UNION ALL
54
+ SELECT start_time, tags FROM memory_anchor
55
+ ) AS picked
56
+ ORDER BY picked.start_time DESC
57
+ LIMIT 1
58
+ ), events AS (
59
+ SELECT start_time, tags FROM anchor
60
+ UNION ALL
61
+ SELECT s.start_time, s.tags
62
+ FROM segments s
63
+ WHERE s.machine = $1 AND s.kind = 'phase'
64
+ AND s.start_time < (SELECT newest FROM bounds)
65
+ AND s.start_time >= COALESCE((SELECT start_time FROM anchor), (SELECT oldest FROM bounds))
66
+ AND ((SELECT start_time FROM anchor) IS NULL OR s.start_time > (SELECT start_time FROM anchor))
67
+ AND NOT EXISTS (
68
+ SELECT 1 FROM incoming i WHERE i.start_time = s.start_time
69
+ )
70
+ AND EXISTS (
71
+ SELECT 1 FROM unnest($8::text[]) AS needle
72
+ WHERE position(needle in s.tags) > 0
73
+ )
74
+ UNION ALL
75
+ SELECT i.start_time, i.tags
76
+ FROM incoming i
77
+ WHERE i.start_time < (SELECT newest FROM bounds)
78
+ AND i.start_time >= COALESCE((SELECT start_time FROM anchor), (SELECT oldest FROM bounds))
79
+ AND ((SELECT start_time FROM anchor) IS NULL OR i.start_time > (SELECT start_time FROM anchor))
80
+ AND EXISTS (
81
+ SELECT 1 FROM unnest($8::text[]) AS needle
82
+ WHERE position(needle in i.tags) > 0
83
+ )
84
+ ), expanded AS (
85
+ SELECT e.start_time, t.ord, t.elem
86
+ FROM events e
87
+ CROSS JOIN LATERAL jsonb_array_elements_text(
88
+ CASE
89
+ WHEN e.tags IS NOT NULL AND left(btrim(e.tags), 1) = '[' THEN e.tags::jsonb
90
+ ELSE '[]'::jsonb
91
+ END
92
+ ) WITH ORDINALITY AS t(elem, ord)
93
+ WHERE t.elem = $5 OR t.elem = ANY($6::text[]) OR t.elem = ANY($7::text[])
94
+ )
95
+ SELECT ask.moment,
96
+ CASE
97
+ WHEN anchor_hit.elem IS NULL OR anchor_hit.elem <> $5 THEN 'idle'
98
+ WHEN enter_hit.elem IS NULL THEN $5
99
+ ELSE enter_hit.elem
100
+ END AS phase
101
+ FROM ask
102
+ LEFT JOIN LATERAL (
103
+ SELECT e.elem, e.start_time, e.ord
104
+ FROM expanded e
105
+ WHERE e.start_time < ask.moment
106
+ AND (e.elem = $5 OR e.elem = ANY($6::text[]))
107
+ ORDER BY e.start_time DESC, e.ord DESC
108
+ LIMIT 1
109
+ ) anchor_hit ON true
110
+ LEFT JOIN LATERAL (
111
+ SELECT e.elem
112
+ FROM expanded e
113
+ WHERE anchor_hit.elem = $5
114
+ AND e.start_time < ask.moment
115
+ AND (e.start_time > anchor_hit.start_time OR (e.start_time = anchor_hit.start_time AND e.ord > anchor_hit.ord))
116
+ AND e.elem = ANY($7::text[])
117
+ ORDER BY e.start_time DESC, e.ord DESC
118
+ LIMIT 1
119
+ ) enter_hit ON true`;
120
+
121
+ function momentOf(row) {
122
+ const raw = row.start || row.start_time || row.startTime;
123
+ return raw instanceof Date ? raw : new Date(raw);
124
+ }
125
+
126
+ function tagText(tags) {
127
+ if (Array.isArray(tags)) {
128
+ return JSON.stringify(tags);
129
+ }
130
+ if (typeof tags === 'string' && tags.startsWith('[')) {
131
+ return tags;
132
+ }
133
+ return '[]';
134
+ }
135
+
136
+ function quoted(ids) {
137
+ return ids.map((id) => {
138
+ return `"${id}"`;
139
+ });
140
+ }
141
+
142
+ export default async function cyclePhaseQuery(pool, machineId, rows, anchors, enters) {
143
+ const offs = rows.filter((row) => {
144
+ return row.name === 'off';
145
+ });
146
+ if (offs.length === 0) {
147
+ return new Map();
148
+ }
149
+ const anchorIds = [anchors.start, ...anchors.stops];
150
+ const result = await pool.query(phaseSql, [
151
+ machineId,
152
+ rows.map(momentOf),
153
+ rows.map((row) => {
154
+ return tagText(row.tags);
155
+ }),
156
+ offs.map(momentOf),
157
+ anchors.start,
158
+ anchors.stops,
159
+ enters,
160
+ quoted([...anchorIds, ...enters]),
161
+ quoted(anchorIds)
162
+ ]);
163
+ const found = new Map();
164
+ result.rows.forEach((row) => {
165
+ found.set(new Date(row.moment).getTime(), row.phase);
166
+ });
167
+ return found;
168
+ }