@yarkivaev/scada 2.14.0 → 2.16.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 (66) hide show
  1. package/charts/scada/templates/processes.yaml +6 -1
  2. package/charts/scada/values.schema.json +1 -0
  3. package/db/bootstrap/apply-hba.sh +11 -0
  4. package/db/bootstrap/entrypoint.sh +6 -0
  5. package/db/bootstrap/ownership.sql +18 -0
  6. package/db/bootstrap/zz-auth.sh +3 -0
  7. package/index.js +1 -0
  8. package/package.json +3 -2
  9. package/src/application/control/agent.js +8 -14
  10. package/src/application/control/controller.js +2 -9
  11. package/src/application/control/executionSnapshot.js +4 -5
  12. package/src/application/control/periodicReconciliation.js +19 -0
  13. package/src/application/control/publishControlCatalog.js +25 -0
  14. package/src/application/control/reconcileStoredChoice.js +10 -0
  15. package/src/application/deploy/controlPlan.js +93 -0
  16. package/src/application/deploy/deploymentCommands.js +29 -0
  17. package/src/application/deploy/deploymentPlan.js +84 -0
  18. package/src/application/deploy/readDocumentFile.js +28 -0
  19. package/src/application/deploy/releases.js +14 -10
  20. package/src/application/runtime/deliveryOperations.js +6 -3
  21. package/src/application/runtime/deliveryPublications.js +13 -11
  22. package/src/application/runtime/deliveryQueue.js +5 -4
  23. package/src/application/runtime/index.js +0 -1
  24. package/src/application/runtime/queuedDelivery.js +6 -5
  25. package/src/application/runtime/runCollector.js +8 -6
  26. package/src/application/runtime/runtime.js +1 -0
  27. package/src/application/runtime/runtimeServices.js +6 -26
  28. package/src/infrastructure/deploy/applyHelmResources.js +17 -0
  29. package/src/infrastructure/deploy/bootstrapKubeStorage.js +28 -0
  30. package/src/infrastructure/deploy/deploymentChecks.js +68 -0
  31. package/src/infrastructure/deploy/deploymentPatch.js +36 -0
  32. package/src/infrastructure/deploy/executeChartDeployment.js +19 -0
  33. package/src/infrastructure/deploy/executeRelease.js +6 -2
  34. package/src/infrastructure/deploy/executeStagedDeployment.js +31 -0
  35. package/src/infrastructure/deploy/index.js +29 -0
  36. package/src/infrastructure/deploy/postgresBootstrap.js +79 -0
  37. package/src/infrastructure/deploy/reconcileDeployments.js +47 -0
  38. package/src/infrastructure/deploy/requestFromWorkload.js +30 -0
  39. package/src/infrastructure/deploy/verifyRuntimeCapabilities.js +34 -0
  40. package/src/infrastructure/management/kiosk/kiosk-browser.py +91 -0
  41. package/src/infrastructure/management/kiosk/kiosk-volume.sh +105 -0
  42. package/src/infrastructure/management/kiosk/listen.mjs.txt +14 -0
  43. package/src/infrastructure/management/kiosk/operateKiosk.js +74 -0
  44. package/src/infrastructure/management/kiosk/renderKioskResources.js +41 -0
  45. package/src/infrastructure/management/kiosk/shellArgument.js +4 -0
  46. package/src/infrastructure/management/kiosk/wait-x11.sh +1 -0
  47. package/src/infrastructure/management/kiosk/watchdog-liveness.sh +1 -0
  48. package/src/infrastructure/management/kiosk/watchdog-readiness.sh +1 -0
  49. package/src/infrastructure/management/kiosk/watchdog.sh +137 -0
  50. package/src/infrastructure/management/serveReconciliation.js +17 -0
  51. package/src/infrastructure/persistence/runtime/memoryDeliveryStore.js +186 -0
  52. package/src/infrastructure/persistence/runtime/spoolCodec.js +0 -27
  53. package/src/infrastructure/persistence/runtime/taskStateMemory.js +40 -0
  54. package/src/application/control/snapshotFile.js +0 -24
  55. package/src/infrastructure/persistence/runtime/deliverySpool.js +0 -86
  56. package/src/infrastructure/persistence/runtime/spoolCheckpoints.js +0 -65
  57. package/src/infrastructure/persistence/runtime/spoolDatabase.js +0 -69
  58. package/src/infrastructure/persistence/runtime/spoolFormat.js +0 -63
  59. package/src/infrastructure/persistence/runtime/spoolLimits.js +0 -8
  60. package/src/infrastructure/persistence/runtime/spoolMigration.js +0 -66
  61. package/src/infrastructure/persistence/runtime/spoolMutations.js +0 -19
  62. package/src/infrastructure/persistence/runtime/spoolProcess.js +0 -89
  63. package/src/infrastructure/persistence/runtime/spoolProcessChild.js +0 -32
  64. package/src/infrastructure/persistence/runtime/spoolRecords.js +0 -56
  65. package/src/infrastructure/persistence/runtime/spoolReplay.js +0 -55
  66. package/src/infrastructure/persistence/runtime/taskStateSqlite.js +0 -37
@@ -1,19 +0,0 @@
1
- import { acknowledge, insert } from './spoolRecords.js';
2
- import { encoded } from './spoolCodec.js';
3
-
4
- function apply(db, operation, limits) {
5
- if (operation?.kind === 'append') { insert(db, encoded(operation.event, operation.recipients), limits.maxBytes, limits.maxRecords); }
6
- else if (operation?.kind === 'ack') { acknowledge(db, operation.eventId, operation.recipient); }
7
- else { throw new TypeError('Unknown spool mutation'); }
8
- }
9
- /** Ordinary admission failures are isolated; SQLite failures abort the outer durable transaction. */
10
- export default function spoolMutations(db, operations, limits) {
11
- if (!Array.isArray(operations) || operations.length === 0) { throw new TypeError('Nonempty spool mutations required'); }
12
- return operations.map((operation) => {
13
- try { db.transaction(() => { apply(db, operation, limits); })(); return { ok: true }; }
14
- catch (error) {
15
- if (error.code?.startsWith('SQLITE_')) { throw error; }
16
- return { ok: false, error };
17
- }
18
- });
19
- }
@@ -1,89 +0,0 @@
1
- import { fork } from 'node:child_process';
2
- import spoolLimits from './spoolLimits.js';
3
-
4
- function remoteError({ name, message, code }) {
5
- const error = name === 'TypeError' ? new TypeError(message) : new Error(message);
6
- error.name = name;
7
- if (code !== undefined) { error.code = code; }
8
- return error;
9
- }
10
-
11
- /* eslint max-lines-per-function: ["error", 90], max-statements: ["error", 24] */
12
- export default function spoolProcess(directory, options) {
13
- const limits = spoolLimits(options);
14
- const state = {
15
- child: null, stopped: null, pending: null,
16
- status: { bytes: 0, maxBytes: limits.maxBytes, recordLimit: limits.maxRecords, pending: 0, ready: false }
17
- };
18
- function unavailable(error = new Error('Delivery spool process disconnected')) {
19
- state.status.ready = false;
20
- const { pending } = state;
21
- state.pending = null;
22
- pending?.reject(error);
23
- }
24
- function receive({ status, value, error }) {
25
- const { pending } = state;
26
- state.pending = null;
27
- state.status = status;
28
- if (error) { pending?.reject(remoteError(error)); }
29
- else { pending?.resolve(value); }
30
- }
31
- function start() {
32
- const child = fork(new URL('./spoolProcessChild.js', import.meta.url), [directory, JSON.stringify(limits)], {
33
- serialization: 'advanced', execArgv: [], stdio: ['ignore', 'ignore', 'inherit', 'ipc']
34
- });
35
- state.child = child;
36
- // An exited child's IPC can still deliver events after its replacement is running.
37
- function whileCurrent(handler) {
38
- return value => { if (state.child === child) { handler(value); } };
39
- }
40
- state.stopped = new Promise(resolve => {
41
- function stopped() { unavailable(); state.child = null; resolve(); }
42
- child.once('exit', whileCurrent(stopped));
43
- child.on('error', whileCurrent(error => {
44
- unavailable(error);
45
- if (!child.pid) { stopped(); }
46
- }));
47
- });
48
- child.once('disconnect', whileCurrent(() => { unavailable(); }));
49
- child.on('message', whileCurrent(receive));
50
- }
51
- function call(method, ...args) {
52
- if (!state.child?.connected) { return Promise.reject(new Error('Delivery spool process disconnected')); }
53
- if (state.pending) { return Promise.reject(new Error('Spool operation in progress')); }
54
- return new Promise((resolve, reject) => {
55
- const pending = { resolve, reject };
56
- state.pending = pending;
57
- state.child.send({ method, args }, error => {
58
- if (error && state.pending === pending) {
59
- unavailable(error);
60
- if (state.child?.connected) { state.child.disconnect(); }
61
- }
62
- });
63
- });
64
- }
65
- return {
66
- async open() {
67
- // The previous process must release its file lock before ownership can be reacquired.
68
- if (state.child && !state.child.connected) { await state.stopped; }
69
- if (!state.child) { start(); }
70
- return call('open');
71
- },
72
- async mutateMany(operations) {
73
- const result = await call('mutateMany', operations);
74
- return result.map(item => { return item.ok ? item : { ...item, error: remoteError(item.error) }; });
75
- },
76
- pendingFair(limit, blocked) { return call('pendingFair', limit, [...blocked]); },
77
- peek(limit) { return call('peek', limit); },
78
- async close() {
79
- if (!state.child) { return; }
80
- try {
81
- if (state.child.connected) { await call('close'); }
82
- } finally {
83
- if (state.child?.connected) { state.child.disconnect(); }
84
- await state.stopped;
85
- }
86
- },
87
- status() { return { ...state.status }; }
88
- };
89
- }
@@ -1,32 +0,0 @@
1
- import deliverySpool from './deliverySpool.js';
2
-
3
- const [, , directory, options] = process.argv;
4
- const spool = deliverySpool(directory, JSON.parse(options));
5
-
6
- function errorDetails({ name, message, code }) {
7
- return { name, message, code };
8
- }
9
-
10
- async function run({ method, args }) {
11
- try {
12
- const result = await spool[method](...args);
13
- const value = method === 'mutateMany'
14
- ? result.map(item => { return item.ok ? item : { ...item, error: errorDetails(item.error) }; })
15
- : result;
16
- return { value };
17
- } catch (error) {
18
- return { error: errorDetails(error) };
19
- }
20
- }
21
-
22
- async function receive(message) {
23
- const response = await run(message);
24
- if (process.connected) {
25
- process.send({ ...response, status: spool.status() }, error => {
26
- if (error && process.connected) { process.disconnect(); }
27
- });
28
- }
29
- }
30
-
31
- process.on('message', receive);
32
- process.once('disconnect', () => { process.off('message', receive); });
@@ -1,56 +0,0 @@
1
- import { capacity, counters } from './spoolDatabase.js';
2
- import { decoded, encoded } from './spoolCodec.js';
3
- import { indexAck, indexInsert } from './spoolReplay.js';
4
-
5
- export function insert(db, value, maxBytes, maxRecords) {
6
- const existing = db.prepare('SELECT fingerprint FROM events WHERE id=?').get(value.id);
7
- if (existing) {
8
- if (existing.fingerprint !== value.fingerprint) { throw new Error('Conflicting event identity'); }
9
- return;
10
- }
11
- const totals = counters(db);
12
- if (totals.records >= maxRecords) { throw new Error('Spool record capacity exceeded'); }
13
- if (totals.bytes + value.bytes > maxBytes) { throw new Error('Spool capacity exceeded'); }
14
- for (const descriptor of value.destinations ?? []) {
15
- db.prepare('INSERT INTO destinations VALUES (?,?,1) ON CONFLICT(id) DO UPDATE SET refs=refs+1').run(descriptor.id, descriptor.json);
16
- }
17
- db.prepare('INSERT INTO events VALUES (@id,@fingerprint,@payload,@destinations,@recipients,@remaining,@bytes,@sequence)').run({
18
- ...value, destinations: value.destinations ? JSON.stringify(value.destinations.map((item) => { return item.id; })) : null,
19
- sequence: totals.sequence + 1
20
- });
21
- indexInsert(db, value, totals.sequence + 1);
22
- db.prepare('UPDATE counters SET bytes=bytes+?,records=records+1,sequence=sequence+1 WHERE id=1').run(value.bytes);
23
- }
24
- function remove(db, row) {
25
- db.prepare('DELETE FROM events WHERE id=?').run(row.id);
26
- db.prepare('UPDATE counters SET bytes=bytes-?,records=records-1 WHERE id=1').run(row.bytes);
27
- for (const id of JSON.parse(row.destinations ?? '[]')) {
28
- db.prepare('UPDATE destinations SET refs=refs-1 WHERE id=?').run(id);
29
- db.prepare('DELETE FROM destinations WHERE id=? AND refs=0').run(id);
30
- }
31
- }
32
- export function acknowledge(db, id, recipient) {
33
- const row = db.prepare('SELECT * FROM events WHERE id=?').get(id);
34
- if (!row) { return; }
35
- if (!JSON.parse(row.recipients).includes(recipient)) { throw new Error('Unknown recipient'); }
36
- indexAck(db, id, recipient);
37
- const remaining = JSON.parse(row.remaining).filter((item) => { return item !== recipient; });
38
- if (!remaining.length) { remove(db, row); return; }
39
- const record = decoded(row, db);
40
- const value = encoded(record.event, JSON.parse(row.recipients), remaining);
41
- db.prepare('UPDATE events SET remaining=?,bytes=? WHERE id=?').run(value.remaining, value.bytes, id);
42
- db.prepare('UPDATE counters SET bytes=bytes+? WHERE id=1').run(value.bytes - row.bytes);
43
- }
44
- export function pending(db, limit) {
45
- const rows = db.prepare('SELECT * FROM events ORDER BY sequence LIMIT ?').all(limit);
46
- let { sequence } = counters(db);
47
- for (const row of rows) {
48
- sequence += 1; db.prepare('UPDATE events SET sequence=? WHERE id=?').run(sequence, row.id);
49
- }
50
- db.prepare('UPDATE counters SET sequence=? WHERE id=1').run(sequence);
51
- return rows.map((row) => { return decoded(row, db); });
52
- }
53
- export function listed(db, limit) {
54
- return db.prepare('SELECT * FROM events ORDER BY sequence LIMIT ?').all(limit).map((row) => { return decoded(row, db); });
55
- }
56
- export function admission(db, maxBytes, maxRecords) { return capacity(db, maxBytes, maxRecords); }
@@ -1,55 +0,0 @@
1
- import { decoded } from './spoolCodec.js';
2
-
3
- export function indexInsert(db, value, sequence) {
4
- const recipients = JSON.parse(value.recipients);
5
- for (const recipient of JSON.parse(value.remaining)) {
6
- const target = value.destinations?.[recipients.indexOf(recipient)]?.id ?? `legacy:${recipient}`;
7
- db.prepare('INSERT INTO replay_pending VALUES (?,?,?,?)').run(target, value.id, recipient, sequence);
8
- db.prepare('INSERT OR IGNORE INTO replay_targets VALUES (?,?)').run(target, sequence);
9
- }
10
- }
11
- export function indexAck(db, id, recipient) {
12
- const row = db.prepare('SELECT target FROM replay_pending WHERE event_id=? AND recipient=?').get(id, recipient);
13
- if (!row) { return; }
14
- db.prepare('DELETE FROM replay_pending WHERE event_id=? AND recipient=?').run(id, recipient);
15
- if (!db.prepare('SELECT 1 FROM replay_pending WHERE target=? LIMIT 1').get(row.target)) {
16
- db.prepare('DELETE FROM replay_targets WHERE id=?').run(row.target);
17
- }
18
- }
19
- /* eslint max-depth: ["error", 4] */
20
- function interleaved(pages, limit) {
21
- const selected = new Map();
22
- for (let offset = 0; offset < limit; offset += 1) {
23
- for (const page of pages) {
24
- const item = page[offset];
25
- if (item && (selected.has(item.event_id) || selected.size < limit)) {
26
- const pairs = selected.get(item.event_id) ?? [];
27
- pairs.push(item); selected.set(item.event_id, pairs);
28
- }
29
- }
30
- }
31
- return selected;
32
- }
33
- /* eslint max-statements: ["error", 20] */
34
- /** Bounded destination and event pages; no payload decoding or scan proportional to an offline backlog. */
35
- export function pendingFair(db, limit, blocked) {
36
- const excluded = [...blocked];
37
- const where = excluded.length ? `WHERE id NOT IN (${excluded.map(() => { return '?'; }).join(',')})` : '';
38
- const targets = db.prepare(`SELECT id FROM replay_targets ${where} ORDER BY sequence LIMIT ?`).all(...excluded, Math.min(limit, 64));
39
- const pages = targets.map(({id}) => { return db.prepare('SELECT event_id,recipient,target FROM replay_pending WHERE target=? ORDER BY sequence LIMIT ?').all(id, limit); });
40
- const selected = interleaved(pages, limit);
41
- let {sequence} = db.prepare('SELECT sequence FROM counters WHERE id=1').get();
42
- const rows = [...selected].map(([id, pairs]) => {
43
- for (const pair of pairs) {
44
- sequence += 1;
45
- db.prepare('UPDATE replay_pending SET sequence=? WHERE event_id=? AND recipient=?').run(sequence, id, pair.recipient);
46
- }
47
- const row = decoded(db.prepare('SELECT * FROM events WHERE id=?').get(id), db);
48
- return {...row, remaining:pairs.map(pair => { return pair.recipient; }), targets:Object.fromEntries(pairs.map(pair => { return [pair.recipient,pair.target]; }))};
49
- });
50
- for (const {id} of targets) {
51
- sequence += 1; db.prepare('UPDATE replay_targets SET sequence=? WHERE id=?').run(sequence, id);
52
- }
53
- db.prepare('UPDATE counters SET sequence=? WHERE id=1').run(sequence);
54
- return rows;
55
- }
@@ -1,37 +0,0 @@
1
- import Database from 'better-sqlite3';
2
-
3
- function documentOf(input) {
4
- return { taskId: input.taskId, stateVersion: input.stateVersion, compatibilityKey: input.compatibilityKey,
5
- checkpoint: input.checkpoint, pending: input.pending };
6
- }
7
-
8
- function taskState(db, maxBytes) {
9
- db.exec('CREATE TABLE IF NOT EXISTS collector_task_state (task_id TEXT PRIMARY KEY, version INTEGER NOT NULL, document TEXT NOT NULL)');
10
- const select = db.prepare('SELECT version, document FROM collector_task_state WHERE task_id = ?');
11
- const insert = db.prepare('INSERT INTO collector_task_state (task_id, version, document) VALUES (?, 1, ?) ON CONFLICT(task_id) DO NOTHING');
12
- const update = db.prepare('UPDATE collector_task_state SET version = version + 1, document = ? WHERE task_id = ? AND version = ?');
13
- return {
14
- load(taskId) {
15
- const row = select.get(taskId);
16
- if (!row) { return Promise.resolve(null); }
17
- return Promise.resolve({ ...JSON.parse(row.document), version: Number(row.version) });
18
- },
19
- commit(input) {
20
- if (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 0) { throw new TypeError('Invalid expectedVersion'); }
21
- if (input.ownership !== undefined) { throw new Error('This store has no external ownership integration'); }
22
- const json = JSON.stringify(documentOf(input));
23
- if (Buffer.byteLength(json) > maxBytes) { throw new Error('Task state capacity exceeded'); }
24
- const result = input.expectedVersion === 0 ? insert.run(input.taskId, json) : update.run(json, input.taskId, input.expectedVersion);
25
- if (!result.changes) { throw new Error('Task state conflict'); }
26
- return Promise.resolve(input.expectedVersion + 1);
27
- },
28
- close() { db.close(); }
29
- };
30
- }
31
-
32
- /** SQLite CAS store with the same load/commit shape as the PostgreSQL runtime table. */
33
- export default function taskStateSqlite(file, { maxBytes = 1048576 } = {}) {
34
- const db = new Database(file);
35
- try { return taskState(db, maxBytes); }
36
- catch (error) { db.close(); throw error; }
37
- }