@yarkivaev/scada 2.13.0 → 2.15.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 (88) hide show
  1. package/charts/scada/templates/processes.yaml +6 -1
  2. package/charts/scada/values.schema.json +1 -0
  3. package/index.js +29 -0
  4. package/package.json +3 -2
  5. package/src/application/control/agent.js +8 -14
  6. package/src/application/control/controlClient.js +1 -1
  7. package/src/application/control/createOnlyJSON.js +50 -0
  8. package/src/application/control/executionSnapshot.js +4 -5
  9. package/src/application/control/index.js +2 -0
  10. package/src/application/control/jsonAssignments.js +30 -0
  11. package/src/application/mcp/loadMetricSeries.js +69 -0
  12. package/src/application/mcp/locateMachineMetric.js +25 -0
  13. package/src/application/mcp/metricQueryPorts.js +78 -0
  14. package/src/application/mcp/parseBearerTokens.js +43 -0
  15. package/src/application/runtime/assignment.js +4 -1
  16. package/src/application/runtime/deliveryOperations.js +6 -3
  17. package/src/application/runtime/deliveryPublications.js +13 -11
  18. package/src/application/runtime/deliveryQueue.js +5 -4
  19. package/src/application/runtime/index.js +0 -1
  20. package/src/application/runtime/queuedDelivery.js +6 -5
  21. package/src/application/runtime/runCollector.js +8 -6
  22. package/src/application/runtime/runtime.js +1 -0
  23. package/src/application/runtime/runtimeServices.js +6 -26
  24. package/src/infrastructure/deploy/applyWhenChanged.js +15 -0
  25. package/src/infrastructure/deploy/deploymentKube.js +35 -0
  26. package/src/infrastructure/deploy/executeKubeSeed.js +24 -0
  27. package/src/infrastructure/deploy/executeRelease.js +8 -11
  28. package/src/infrastructure/deploy/operatePostgresMaintenance.js +85 -0
  29. package/src/infrastructure/deploy/postgresMaintenancePlan.js +54 -0
  30. package/src/infrastructure/deploy/postgresRestoreObjects.js +73 -0
  31. package/src/infrastructure/deploy/preflightKubeStorage.js +76 -0
  32. package/src/infrastructure/deploy/prepareKubePrerequisites.js +95 -0
  33. package/src/infrastructure/deploy/verifyCollectorCoverage.js +43 -0
  34. package/src/infrastructure/deploy/verifyPeerBrokerPerimeter.js +24 -0
  35. package/src/infrastructure/ingest/mysql40/byteReader.js +51 -0
  36. package/src/infrastructure/ingest/mysql40/mysql40.js +116 -0
  37. package/src/infrastructure/ingest/mysql40/packets.js +72 -0
  38. package/src/infrastructure/ingest/mysql40/resultRows.js +92 -0
  39. package/src/infrastructure/ingest/mysql40/scramble.js +89 -0
  40. package/src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js +83 -0
  41. package/src/infrastructure/ingest/telemetry/replayStoredTelemetry.js +125 -0
  42. package/src/infrastructure/management/kubeServiceAccount.js +43 -0
  43. package/src/infrastructure/management/kubectlPortForward.js +27 -0
  44. package/src/infrastructure/mdmesh/hmiApplication.js +64 -0
  45. package/src/infrastructure/mdmesh/hmiControl.js +85 -0
  46. package/src/infrastructure/mdmesh/hmiFile.js +69 -0
  47. package/src/infrastructure/mdmesh/hmiMonitor.js +53 -0
  48. package/src/infrastructure/mdmesh/hmiReconcile.js +170 -0
  49. package/src/infrastructure/mdmesh/hmiRuntime.js +33 -0
  50. package/src/infrastructure/mdmesh/index.js +7 -0
  51. package/src/infrastructure/mdmesh/mdmeshClient.js +72 -0
  52. package/src/infrastructure/messaging/ownership/edgeSitesFromEnv.js +137 -0
  53. package/src/infrastructure/messaging/rabbitmq/reconcile.js +71 -12
  54. package/src/infrastructure/opcua/health.js +91 -0
  55. package/src/infrastructure/opcua/index.js +1 -0
  56. package/src/infrastructure/persistence/pg/prepareRuntimeRole.js +67 -0
  57. package/src/infrastructure/persistence/runtime/memoryDeliveryStore.js +186 -0
  58. package/src/infrastructure/persistence/runtime/spoolCodec.js +0 -27
  59. package/src/infrastructure/persistence/runtime/taskStateMemory.js +40 -0
  60. package/src/infrastructure/replication/canonicalJSON.js +15 -0
  61. package/src/infrastructure/replication/postgresSnapshotReplica.js +129 -0
  62. package/src/infrastructure/replication/postgresSnapshotRuntime.js +40 -0
  63. package/src/infrastructure/replication/snapshotSync.js +61 -0
  64. package/src/infrastructure/replication/tableSnapshotFormat.js +50 -0
  65. package/src/infrastructure/tls/mirrorTLSSecret.js +37 -0
  66. package/src/infrastructure/tls/mutualJSON.js +79 -0
  67. package/src/infrastructure/tls/tlsMaterial.js +57 -0
  68. package/stream-processing/src/main/scala/scada/processing/infra/state/AtomicStateFile.scala +7 -0
  69. package/stream-processing/src/main/scala/scada/processing/infra/state/StateJournal.scala +22 -0
  70. package/stream-processing/src/main/scala/scada/processing/runtime/HistoryClient.scala +10 -1
  71. package/stream-processing/src/main/scala/scada/processing/runtime/LiveWorker.scala +70 -0
  72. package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +2 -8
  73. package/stream-processing/src/main/scala/scada/processing/runtime/StatefulHistory.scala +108 -0
  74. package/stream-processing/src/main/scala/scada/processing/runtime/TimelinePublication.scala +43 -0
  75. package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +43 -0
  76. package/src/application/control/snapshotFile.js +0 -24
  77. package/src/infrastructure/persistence/runtime/deliverySpool.js +0 -86
  78. package/src/infrastructure/persistence/runtime/spoolCheckpoints.js +0 -65
  79. package/src/infrastructure/persistence/runtime/spoolDatabase.js +0 -69
  80. package/src/infrastructure/persistence/runtime/spoolFormat.js +0 -63
  81. package/src/infrastructure/persistence/runtime/spoolLimits.js +0 -8
  82. package/src/infrastructure/persistence/runtime/spoolMigration.js +0 -66
  83. package/src/infrastructure/persistence/runtime/spoolMutations.js +0 -19
  84. package/src/infrastructure/persistence/runtime/spoolProcess.js +0 -89
  85. package/src/infrastructure/persistence/runtime/spoolProcessChild.js +0 -32
  86. package/src/infrastructure/persistence/runtime/spoolRecords.js +0 -56
  87. package/src/infrastructure/persistence/runtime/spoolReplay.js +0 -55
  88. package/src/infrastructure/persistence/runtime/taskStateSqlite.js +0 -37
@@ -0,0 +1,125 @@
1
+ import pg from 'pg';
2
+ import amqp from 'amqplib';
3
+ import {createClient} from '@clickhouse/client';
4
+ import replay from './telemetryReplay.js';
5
+
6
+ function required(env, name) {
7
+ const value = env[name];
8
+ if (!value) { throw new Error(`${name} is required`); }
9
+ return value;
10
+ }
11
+ function bound(env, name, fallback) {
12
+ return env[name] || fallback;
13
+ }
14
+ async function* pages(pool, from, to, size) {
15
+ const client = await pool.connect();
16
+ let committed = false;
17
+ try {
18
+ await client.query('BEGIN READ ONLY');
19
+ await client.query(
20
+ "DECLARE telemetry_replay NO SCROLL CURSOR FOR SELECT topic,to_char(ts AT TIME ZONE 'UTC','YYYY-MM-DD HH24:MI:SS.US') AS ts,value FROM metrics WHERE ts >= $1::timestamptz AND ts < $2::timestamptz ORDER BY topic,ts,float8send(value)",
21
+ [from, to]
22
+ );
23
+ let batch;
24
+ do {
25
+ // eslint-disable-next-line no-await-in-loop
26
+ batch = await client.query(`FETCH FORWARD ${size} FROM telemetry_replay`);
27
+ if (batch.rows.length > 0) {
28
+ yield batch.rows;
29
+ }
30
+ } while (batch.rows.length !== 0);
31
+ await client.query('COMMIT');
32
+ committed = true;
33
+ } finally {
34
+ const error = committed ? undefined : await client.query('ROLLBACK').then(() => {return undefined}, (failure) => {return failure});
35
+ client.release(error);
36
+ }
37
+ }
38
+ async function pull(client, from, to, size, offset) {
39
+ const result = await client.query({
40
+ query: `SELECT stored.topic,formatDateTime(stored.ts,'%F %T.%f','UTC') AS ts,stored.value
41
+ FROM scada.metrics AS stored
42
+ WHERE stored.ts >= parseDateTime64BestEffort({from:String},6,'UTC')
43
+ AND stored.ts < parseDateTime64BestEffort({to:String},6,'UTC')
44
+ ORDER BY stored.topic,stored.ts,stored.value LIMIT {size:UInt32} OFFSET {offset:UInt32}`,
45
+ 'query_params': {from, to, size, offset},
46
+ format: 'JSONEachRow'
47
+ });
48
+ return result.json();
49
+ }
50
+ async function* clickhousePages(env, from, to, size) {
51
+ const client = createClient({
52
+ url: env.CLICKHOUSE_URL,
53
+ username: bound(env, 'CLICKHOUSE_USER', 'default'),
54
+ password: env.CLICKHOUSE_PASSWORD || '',
55
+ 'request_timeout': 120000
56
+ });
57
+ try {
58
+ let offset = 0;
59
+ let rows;
60
+ do {
61
+ // eslint-disable-next-line no-await-in-loop
62
+ rows = await pull(client, from, to, size, offset);
63
+ if (rows.length > 0) {
64
+ yield rows;
65
+ }
66
+ offset += rows.length;
67
+ } while (rows.length !== 0);
68
+ } finally {
69
+ await client.close();
70
+ }
71
+ }
72
+ async function publish(channel, row) {
73
+ const message = replay(row);
74
+ await new Promise((resolve, reject) => {
75
+ channel.publish(message.exchange, message.routingKey, Buffer.from(message.payload), {
76
+ persistent: true,
77
+ contentType: 'application/json'
78
+ }, (error) => { if (error) { reject(error); } else { resolve(); } });
79
+ });
80
+ }
81
+ async function* load(env, from, to, size) {
82
+ if (env.CLICKHOUSE_URL) {
83
+ yield* clickhousePages(env, from, to, size);
84
+ return;
85
+ }
86
+ const pool = new pg.Pool({connectionString: required(env, 'POSTGRES_URL'), max: 1});
87
+ try {
88
+ yield* pages(pool, from, to, size);
89
+ } finally {
90
+ await pool.end();
91
+ }
92
+ }
93
+ function replayWindow(env) {
94
+ const now = Date.now();
95
+ const from = env.SOURCE_FROM || new Date(now - Number(bound(env, 'LOOKBACK_MS', '28800000'))).toISOString();
96
+ const to = env.SOURCE_TO || new Date(now).toISOString();
97
+ const size = Number(bound(env, 'SOURCE_PAGE_SIZE', '2000'));
98
+ if (!Number.isSafeInteger(size) || size < 1 || size > 100000) {
99
+ throw new RangeError('Invalid telemetry replay page size');
100
+ }
101
+ return { from, to, size };
102
+ }
103
+
104
+ /** Republishes stored metrics onto the local telemetry exchange in bounded batches. */
105
+ export default async function replayStoredTelemetry(env) {
106
+ const { from, to, size } = replayWindow(env);
107
+ const connection = await amqp.connect(required(env, 'AMQP_URL'));
108
+ let channel;
109
+ let records = 0;
110
+ try {
111
+ channel = await connection.createConfirmChannel();
112
+ for await (const page of load(env, from, to, size)) {
113
+ // Wait for publisher confirms before reading another page.
114
+ await Promise.all(page.map((row) => {return publish(channel, row)}));
115
+ records += page.length;
116
+ }
117
+ } finally {
118
+ try {
119
+ await channel?.close();
120
+ } finally {
121
+ await connection.close();
122
+ }
123
+ }
124
+ return { from, to, records };
125
+ }
@@ -0,0 +1,43 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { request } from 'node:https';
3
+
4
+ const identity = '/var/run/secrets/kubernetes.io/serviceaccount';
5
+
6
+ function collect(response, limit, resolve, reject) {
7
+ const chunks = [];
8
+ let size = 0;
9
+ response.on('data', (chunk) => {
10
+ size += chunk.length;
11
+ if (size > limit) {
12
+ response.destroy(new Error('Kubernetes API response is too large'));
13
+ } else {
14
+ chunks.push(chunk);
15
+ }
16
+ });
17
+ response.on('error', reject);
18
+ response.on('end', () => {
19
+ resolve({ status: response.statusCode, body: Buffer.concat(chunks).toString('utf8') });
20
+ });
21
+ }
22
+
23
+ /** Authenticated JSON request to the cluster API using the mounted service account. */
24
+ export default function kubeServiceAccount(address, { limit = 1048576, timeoutMs = 8000 } = {}) {
25
+ const base = new URL(address);
26
+ if (base.protocol !== 'https:') { throw new TypeError('Kubernetes API requires HTTPS'); }
27
+ return function exchange(method, path, body, contentType = 'application/json') {
28
+ const target = new URL(path, base);
29
+ if (target.origin !== base.origin) { throw new TypeError('Invalid Kubernetes API path'); }
30
+ const token = readFileSync(`${identity}/token`, 'utf8').trim();
31
+ const headers = { Authorization: `Bearer ${token}`, Accept: 'application/json', 'Content-Type': contentType };
32
+ const ca = readFileSync(`${identity}/ca.crt`);
33
+ return new Promise((resolve, reject) => {
34
+ const connection = request(target, { method, headers, ca, rejectUnauthorized: true }, (response) => {
35
+ collect(response, limit, resolve, reject);
36
+ });
37
+ const timer = setTimeout(() => { connection.destroy(new Error('Kubernetes API request timed out')); }, timeoutMs);
38
+ connection.on('error', reject);
39
+ connection.on('close', () => { clearTimeout(timer); });
40
+ connection.end(body === undefined ? undefined : JSON.stringify(body));
41
+ });
42
+ };
43
+ }
@@ -0,0 +1,27 @@
1
+ import { spawn } from 'node:child_process';
2
+
3
+ function forwardedPort(child, timeout) {
4
+ return new Promise((resolve, reject) => {
5
+ const timer = setTimeout(() => { reject(new Error('Port forward timeout')); }, timeout);
6
+ let output = '';
7
+ function failed() { clearTimeout(timer); reject(new Error('Port forward stopped')); }
8
+ child.once('error', failed);
9
+ child.once('exit', failed);
10
+ child.stdout.on('data', (chunk) => {
11
+ output = (output + chunk.toString()).slice(-4096);
12
+ const match = /Forwarding from 127[.]0[.]0[.]1:(?<port>\d+)/u.exec(output);
13
+ if (match) { clearTimeout(timer); resolve(Number(match.groups.port)); }
14
+ });
15
+ });
16
+ }
17
+
18
+ /** Invoke an operation over a temporary, loopback-only port owned by this process. */
19
+ export async function kubectlPortForward({ context, namespace, target, port, timeout = 15000 }, use) {
20
+ const child = spawn('kubectl', ['--context', context, '--namespace', namespace, 'port-forward',
21
+ target, `:${port}`, '--address=127.0.0.1'], { stdio: ['ignore', 'pipe', 'pipe'] });
22
+ child.stderr.resume();
23
+ try {
24
+ const forwarded = await forwardedPort(child, timeout);
25
+ return await use(`http://127.0.0.1:${forwarded}`);
26
+ } finally { child.kill('SIGTERM'); }
27
+ }
@@ -0,0 +1,64 @@
1
+ function native(device, kiosk) {
2
+ const { apk } = device.application;
3
+ return { name: kiosk.applicationName, pkg: apk.package, version: apk.version, versionCode: apk.versionCode,
4
+ url: apk.url, sha256: apk.sha256, type: 'app', showIcon: true, runAfterInstall: true };
5
+ }
6
+
7
+ async function existing(client, desired) {
8
+ const rows = await client.request('/private/configurations/applications');
9
+ if (!Array.isArray(rows)) { throw new Error('MDMesh application inventory is invalid'); }
10
+ const found = rows.filter(row => { return row.pkg === desired.pkg; });
11
+ if (found.length > 1 || found.some(row => { return row.name !== desired.name; })) { throw new Error('HMI application package is ambiguous or unmanaged'); }
12
+ if (!found[0]) { return undefined; }
13
+ const current = await client.request(`/private/applications/${found[0].id}`);
14
+ const versions = await client.request(`/private/applications/${found[0].id}/versions`);
15
+ const version = versions.find(row => {return row.id === current.latestVersion});
16
+ return { ...current, sha256: version?.apkHash ? Buffer.from(version.apkHash, 'base64url').toString('hex') : '' };
17
+ }
18
+
19
+ function matches(current, desired) {
20
+ return current && ['pkg', 'version', 'versionCode', 'url', 'sha256'].every(key => { return current[key] === desired[key]; });
21
+ }
22
+
23
+ async function store(client, current, desired) {
24
+ if (current) {
25
+ await client.request('/private/applications/versions', 'PUT', { applicationId: current.id,
26
+ version: desired.version, versionCode: desired.versionCode, url: desired.url,
27
+ apkHash: Buffer.from(desired.sha256, 'hex').toString('base64url'), split: false });
28
+ } else { await client.request('/private/applications/android', 'PUT', desired); }
29
+ }
30
+
31
+ function removal(row) {
32
+ if (!Number.isSafeInteger(row.id) || row.id <= 0) { throw new Error('HMI retired package has invalid identity'); }
33
+ return { id: row.id, usedVersionId: row.latestVersion || row.usedVersionId || row.id, action: 1, showIcon: false, remove: true };
34
+ }
35
+
36
+ async function retired(device, client) {
37
+ const names = device.application.apk.retire || [];
38
+ if (!names.length) { return []; }
39
+ const rows = await client.request('/private/configurations/applications');
40
+ if (!Array.isArray(rows)) { throw new Error('MDMesh application inventory is invalid'); }
41
+ return names.flatMap((pkg) => {
42
+ const found = rows.filter((row) => { return row.pkg === pkg; });
43
+ if (found.length > 1) { throw new Error('HMI retired package is ambiguous'); }
44
+ return found[0] ? [removal(found[0])] : [];
45
+ });
46
+ }
47
+
48
+ /** Reconcile a signed, immutable HMI APK before using its VERSION identity in a kiosk configuration. */
49
+ export default async function hmiApplication(device, client, apply, kiosk) {
50
+ const desired = native(device, kiosk);
51
+ let current = await existing(client, desired);
52
+ if (current && !matches(current, desired) && (current.version === desired.version || desired.versionCode <= current.versionCode)) {
53
+ throw new Error('HMI APK identity is immutable; publish a new version with an increased versionCode');
54
+ }
55
+ if (apply && !matches(current, desired)) {
56
+ await store(client, current, desired);
57
+ current = await existing(client, desired);
58
+ if (!matches(current, desired)) { throw new Error('MDMesh HMI application readback did not match its immutable APK'); }
59
+ }
60
+ if (!current || !matches(current, desired)) { return { ready: false, settings: {} }; }
61
+ if (!Number.isSafeInteger(current.latestVersion) || current.latestVersion <= 0) { throw new Error('MDMesh HMI application has no version identity'); }
62
+ const applications = [{ id: current.id, usedVersionId: current.latestVersion, action: 1, showIcon: true, remove: false }, ...await retired(device, client)];
63
+ return { ready: true, settings: { mainAppId: current.latestVersion, autostartForeground: true, applications } };
64
+ }
@@ -0,0 +1,85 @@
1
+ import http from 'node:http';
2
+ import { timingSafeEqual } from 'node:crypto';
3
+ import hmiMonitor, { metrics } from './hmiMonitor.js';
4
+ import hmiReconcile from './hmiReconcile.js';
5
+
6
+ function fault(status, message) {
7
+ return Object.assign(new Error(message), { status });
8
+ }
9
+
10
+ function authorized(request, token) {
11
+ const actual = Buffer.from(request.headers.authorization || '');
12
+ const expected = Buffer.from(`Bearer ${token}`);
13
+ return Boolean(token) && actual.length === expected.length && timingSafeEqual(actual, expected);
14
+ }
15
+
16
+ function json(response, status, value) {
17
+ response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }).end(JSON.stringify(value));
18
+ }
19
+
20
+ async function body(request) {
21
+ const chunks = [];
22
+ let length = 0;
23
+ for await (const chunk of request) {
24
+ length += chunk.length;
25
+ if (length > 4096) { throw fault(413, 'HMI request body is too large'); }
26
+ chunks.push(chunk);
27
+ }
28
+ try { return JSON.parse(Buffer.concat(chunks).toString()); } catch { throw fault(400, 'HMI action requires JSON'); }
29
+ }
30
+
31
+ async function action(settings, request) {
32
+ const input = await body(request);
33
+ if (!input || typeof input !== 'object' || !['sync', 'reboot'].includes(input.action)
34
+ || Object.keys(input).some((key) => { return !['device', 'action'].includes(key); })) {
35
+ throw fault(400, 'HMI action must be explicit sync or reboot');
36
+ }
37
+ const device = settings.plan.devices.find((entry) => { return entry.id === input.device; });
38
+ if (!device?.deviceRef) { throw fault(409, 'HMI action requires a declared enrolled tablet'); }
39
+ if (input.action === 'reboot') { throw fault(422, 'HMI reboot unsupported without discoverable device capability evidence'); }
40
+ const matches = (await settings.control.inventory()).filter((entry) => { return entry.number === device.deviceRef; });
41
+ if (matches.length !== 1) { throw fault(409, 'HMI action references an unknown enrolled tablet'); }
42
+ await settings.control.request(`/private/agent/v1/devices/${encodeURIComponent(device.deviceRef)}/sync`, 'POST', {});
43
+ return { device: device.id, action: 'sync', state: 'wake-requested', hmiHealth: 'unknown' };
44
+ }
45
+
46
+ async function metricResponse(settings, response) {
47
+ let status;
48
+ try { status = await hmiMonitor(settings.plan, settings.monitor); } catch { status = { server: settings.plan.server, up: false, devices: [] }; }
49
+ response.writeHead(200, { 'Content-Type': 'text/plain; version=0.0.4' }).end(metrics(status));
50
+ }
51
+
52
+ async function observe(settings, response, route) {
53
+ if (route === '/healthz') { json(response, 200, { status: 'ok' }); return; }
54
+ if (route === '/v1/hmi/diff') { json(response, 200, await hmiReconcile(settings.plan, settings.control, false, settings.kiosk)); return; }
55
+ if (route === '/v1/hmi/status') { json(response, 200, await hmiMonitor(settings.plan, settings.monitor)); return; }
56
+ if (route === '/metrics') { await metricResponse(settings, response); return; }
57
+ throw fault(404, 'HMI route was not found');
58
+ }
59
+
60
+ function unlock(state) {
61
+ state.busy = false;
62
+ }
63
+
64
+ async function mutate(settings, request, response, state) {
65
+ if (!['/v1/hmi/reconcile', '/v1/hmi/actions'].includes(request.url)) { throw fault(404, 'HMI route was not found'); }
66
+ if (!authorized(request, settings.token)) { throw fault(401, 'HMI control authorization required'); }
67
+ if (state.busy) { throw fault(409, 'HMI control operation already in progress'); }
68
+ state.busy = true;
69
+ try {
70
+ if (request.url === '/v1/hmi/actions') { json(response, 202, await action(settings, request)); }
71
+ else { json(response, 200, await hmiReconcile(settings.plan, settings.control, true, settings.kiosk)); }
72
+ } finally { unlock(state); }
73
+ }
74
+
75
+ /** HTTP boundary separates read-only observations from explicitly authorized mutations. */
76
+ export default function hmiControl(settings) {
77
+ const state = { busy: false };
78
+ return http.createServer(async (request, response) => {
79
+ try {
80
+ if (request.method === 'GET') { await observe(settings, response, request.url); }
81
+ else if (request.method === 'POST') { await mutate(settings, request, response, state); }
82
+ else { throw fault(405, 'HMI HTTP method is unsupported'); }
83
+ } catch (error) { json(response, error.status || 502, { error: error.status ? error.message : 'MDMesh operation failed' }); }
84
+ });
85
+ }
@@ -0,0 +1,69 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ function checksum(value) {
4
+ return createHash('sha256').update(value).digest('hex');
5
+ }
6
+
7
+ function label(file) {
8
+ return `${file.prefix}${checksum(file.href)}`;
9
+ }
10
+
11
+ function owned(row, file) {
12
+ return typeof row.description === 'string' && row.description.startsWith(file.prefix);
13
+ }
14
+
15
+ export function fileChecksum(row) {
16
+ if (typeof row.checksum === 'string' && /^[a-f0-9]{64}$/u.test(row.checksum)) { return row.checksum; }
17
+ return String(row.description || '').split(':').at(-1);
18
+ }
19
+
20
+ function descriptor(row, path) {
21
+ if (!Number.isSafeInteger(row.id) || row.id <= 0 || typeof row.url !== 'string' || !row.url) {
22
+ throw new Error('MDMesh HMI file identity is incomplete');
23
+ }
24
+ // MDMesh assigns an association id; fileId identifies the uploaded file it links.
25
+ return { fileId: row.id, path, overridePath: true, url: row.url, checksum: fileChecksum(row), remove: false };
26
+ }
27
+
28
+ async function locate(client, file) {
29
+ const rows = await client.request('/private/web-ui-files/search');
30
+ if (!Array.isArray(rows)) { throw new Error('MDMesh file inventory is invalid'); }
31
+ return rows.find((row) => { return owned(row, file); });
32
+ }
33
+
34
+ async function commit(client, file, upload, current) {
35
+ const body = { tmpPath: upload.serverPath, filePath: file.name, description: label(file),
36
+ devicePath: file.path, checksum: checksum(file.href) };
37
+ if (Number.isSafeInteger(current?.id) && current.id > 0) { body.id = current.id; }
38
+ await client.request('/private/web-ui-files/update', 'POST', body);
39
+ const stored = await locate(client, file);
40
+ if (!stored || stored.description !== label(file)) {
41
+ throw new Error('MDMesh HMI file readback did not match the catalog address');
42
+ }
43
+ return descriptor(stored, file.path);
44
+ }
45
+
46
+ /**
47
+ * Store one per-tablet kiosk URL as a configuration file without embedding it in the APK.
48
+ *
49
+ * @example
50
+ * await hmiFile(device, client, true, kiosk);
51
+ *
52
+ * @param {object} device - catalog tablet
53
+ * @param {object} client - MDMesh adapter with request and upload
54
+ * @param {boolean} apply - write when true
55
+ * @param {object} kiosk - ownership prefix, destination path and URL validator
56
+ * @returns {Promise<{ready: boolean, file?: object}>} configuration file fragment
57
+ */
58
+ export default async function hmiFile(device, client, apply, kiosk) {
59
+ const file = { href: kiosk.validateAddress(device.application.href), name: `${device.id}.url`,
60
+ path: kiosk.devicePath, prefix: `${kiosk.ownershipPrefix}:${device.id}:` };
61
+ const current = await locate(client, file);
62
+ if (current && current.description === label(file) && current.devicePath === file.path) {
63
+ return { ready: true, file: descriptor(current, file.path) };
64
+ }
65
+ if (!apply) { return { ready: false }; }
66
+ const upload = await client.upload(file.name, file.href);
67
+ if (typeof upload?.serverPath !== 'string' || !upload.serverPath) { throw new Error('MDMesh HMI file upload returned no path'); }
68
+ return { ready: true, file: await commit(client, file, upload, current) };
69
+ }
@@ -0,0 +1,53 @@
1
+ function applicationState(device, sync) {
2
+ if (!device.application.autoStart) { return 'waiting-app-configuration'; }
3
+ return sync?.inSync === true ? 'configuration-in-sync' : 'awaiting-device';
4
+ }
5
+
6
+ function observed(device, actual, snapshot, now) {
7
+ const [state, sync, telemetry] = snapshot;
8
+ const lastSeen = state?.updatedAt || actual.lastUpdate;
9
+ return { id: device.id, machine: device.machine, state: 'enrolled',
10
+ ...(Number.isFinite(lastSeen) && lastSeen > 0 && { lastSeen, mdmOnline: now >= lastSeen && now - lastSeen <= 600000 }),
11
+ battery: state?.battery ?? actual.info?.batteryLevel, charging: state?.charging,
12
+ network: telemetry?.dynamic?.networkType, agentVersion: state?.agentVersion ?? actual.launcherVersion,
13
+ configurationSync: { supported: sync?.supported, inSync: sync?.inSync }, hmiHealth: 'unknown',
14
+ application: { state: applicationState(device, sync) } };
15
+ }
16
+
17
+ async function deviceStatus(device, inventory, client, now) {
18
+ const matches = inventory.filter((row) => { return row.number === device.deviceRef; });
19
+ if (!device.deviceRef || matches.length !== 1) {
20
+ return { id: device.id, machine: device.machine, state: device.deviceRef ? 'unknown-reference' : 'planned-unbound', hmiHealth: 'unknown' };
21
+ }
22
+ const route = `/private/agent/v1/devices/${encodeURIComponent(device.deviceRef)}`;
23
+ const [state, sync, telemetry] = await Promise.all(['/state', '/configStatus', '/telemetry'].map((suffix) => { return client.request(`${route}${suffix}`); }));
24
+ return observed(device, matches[0], [state, sync, telemetry], now);
25
+ }
26
+
27
+ /** Observe only declared tablets with the read-only MDMesh identity, without inferring app health. */
28
+ export default async function hmiMonitor(plan, client, now = Date.now()) {
29
+ const inventory = await client.inventory();
30
+ const devices = await Promise.all(plan.devices.map((device) => { return deviceStatus(device, inventory, client, now); }));
31
+ return { server: plan.server, up: true, devices };
32
+ }
33
+
34
+ function label(value) {
35
+ return String(value).replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('\n', '\\n');
36
+ }
37
+
38
+ function samples(status, device) {
39
+ const labels = `server="${label(status.server)}",device="${label(device.id)}"`;
40
+ return [
41
+ ...(typeof device.mdmOnline === 'boolean' ? [`hmi_mdm_device_online{${labels}} ${Number(device.mdmOnline)}`] : []),
42
+ ...(Number.isFinite(device.lastSeen) ? [`hmi_device_last_seen_seconds{${labels}} ${device.lastSeen / 1000}`] : []),
43
+ ...(typeof device.configurationSync?.inSync === 'boolean' && device.configurationSync.supported === true
44
+ ? [`hmi_config_drift{${labels}} ${Number(!device.configurationSync.inSync)}`] : [])
45
+ ];
46
+ }
47
+
48
+ /** Prometheus labels come exclusively from the validated DSL catalog. */
49
+ export function metrics(status) {
50
+ return [`# TYPE hmi_up gauge`, `hmi_up{server="${label(status.server)}"} ${Number(status.up)}`,
51
+ '# TYPE hmi_mdm_device_online gauge', '# TYPE hmi_device_last_seen_seconds gauge', '# TYPE hmi_config_drift gauge',
52
+ ...status.devices.flatMap((device) => { return samples(status, device); }), ''].join('\n');
53
+ }
@@ -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
+ }