@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,186 @@
1
+ /* eslint max-lines-per-function: ["error", 120], max-statements: ["error", 24] */
2
+ import { digest, revive, validate } from './spoolCodec.js';
3
+
4
+ const replayPageBytes = 4 * 1024 * 1024;
5
+ const remainingKeyBytes = Buffer.byteLength(',"remaining":');
6
+
7
+ function recordOf(event, recipients) {
8
+ const json = JSON.stringify(event) ?? 'null';
9
+ const snapshot = JSON.parse(json);
10
+ validate(snapshot, recipients);
11
+ const descriptorHashes = Array.isArray(snapshot.destinations)
12
+ ? snapshot.destinations.map(item => { return digest(JSON.stringify(item)); }) : [];
13
+ const destinations = new Map(recipients.map((id, index) => {
14
+ return [id, descriptorHashes[index] ?? `legacy:${id}`];
15
+ }));
16
+ const recipientJson = JSON.stringify(recipients);
17
+ const identity = `{"event":${json},"recipients":${recipientJson}}`;
18
+ return { id: snapshot.eventId, json, fingerprint: digest(identity), destinations, pending: new Map(),
19
+ bytes: Buffer.byteLength(identity) + remainingKeyBytes + Buffer.byteLength(recipientJson) };
20
+ }
21
+
22
+ function limitOf(limit, operation) {
23
+ if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError(`Positive ${operation} limit required`); }
24
+ }
25
+
26
+ function pagesOf(targets, limit, blocked) {
27
+ const pages = [];
28
+ for (const [target, pairs] of targets) {
29
+ if (!blocked.has(target)) { pages.push({ target, pairs, cursor: pairs.values() }); }
30
+ if (pages.length >= Math.min(limit, 64)) { break; }
31
+ }
32
+ return pages;
33
+ }
34
+
35
+ function select(pages, limit) {
36
+ const selected = new Map();
37
+ let bytes = 0;
38
+ function add(pair) {
39
+ const { record } = pair;
40
+ if (!selected.has(record)) {
41
+ // Always admit the first row so a large record can make progress alone.
42
+ if (selected.size >= limit || (selected.size && bytes + record.bytes > replayPageBytes)) { return; }
43
+ selected.set(record, []);
44
+ bytes += record.bytes;
45
+ }
46
+ selected.get(record).push(pair);
47
+ }
48
+ for (let offset = 0; offset < limit; offset += 1) {
49
+ let advanced = false;
50
+ for (const page of pages) {
51
+ const { value: pair } = page.cursor.next();
52
+ if (pair) { advanced = true; add(pair); }
53
+ }
54
+ if (!advanced) { break; }
55
+ }
56
+ return selected;
57
+ }
58
+
59
+ function decoded(record, remaining) {
60
+ return { event: JSON.parse(record.json, revive), remaining };
61
+ }
62
+
63
+ function visibleRecords(records, limit) {
64
+ limitOf(limit, 'peek');
65
+ const output = [];
66
+ let bytes = 0;
67
+ for (const record of records.values()) {
68
+ if (output.length && bytes + record.bytes > replayPageBytes) { break; }
69
+ bytes += record.bytes;
70
+ output.push(decoded(record, [...record.pending.keys()]));
71
+ if (output.length === limit) { break; }
72
+ }
73
+ return output;
74
+ }
75
+
76
+ /** The FIFO is independent of per-target replay order. Accepted observations live only in this process. */
77
+ export default function memoryDeliveryStore({ maxBytes, maxRecords = 100000 } = {}) {
78
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) { throw new TypeError('Explicit positive spool maxBytes required'); }
79
+ if (!Number.isSafeInteger(maxRecords) || maxRecords <= 0) { throw new TypeError('Positive safe spool maxRecords required'); }
80
+ const records = new Map();
81
+ const targets = new Map();
82
+ const state = { ready: false, bytes: 0, sequence: 0n, droppedRecords: 0, droppedBytes: 0 };
83
+ function forget(pair) {
84
+ const { recipient, record, target } = pair;
85
+ record.pending.delete(recipient);
86
+ const group = targets.get(target);
87
+ group.delete(pair);
88
+ if (!group.size) { targets.delete(target); }
89
+ }
90
+ function remove(record) {
91
+ for (const pair of record.pending.values()) { forget(pair); }
92
+ records.delete(record.id);
93
+ state.bytes -= record.bytes;
94
+ }
95
+ function evict() {
96
+ const oldest = records.values().next().value;
97
+ state.droppedRecords += 1;
98
+ state.droppedBytes += oldest.bytes;
99
+ remove(oldest);
100
+ }
101
+ function append(event, recipients) {
102
+ const incoming = recordOf(event, recipients);
103
+ const existing = records.get(incoming.id);
104
+ if (existing) {
105
+ if (existing.fingerprint !== incoming.fingerprint) { throw new Error('Conflicting event identity'); }
106
+ return;
107
+ }
108
+ if (incoming.bytes > maxBytes) { throw new Error('Spool capacity exceeded'); }
109
+ while (records.size >= maxRecords || incoming.bytes > maxBytes - state.bytes) { evict(); }
110
+ state.sequence += 1n;
111
+ Object.assign(incoming, { admission: state.sequence.toString() });
112
+ for (const [recipient, target] of incoming.destinations) {
113
+ const group = targets.get(target) ?? new Set();
114
+ const pair = { recipient, target, record: incoming };
115
+ group.add(pair);
116
+ targets.set(target, group);
117
+ incoming.pending.set(recipient, pair);
118
+ }
119
+ records.set(incoming.id, incoming);
120
+ state.bytes += incoming.bytes;
121
+ }
122
+ function acknowledge({ eventId, recipient, admission }) {
123
+ const record = records.get(eventId);
124
+ if (!record || (admission !== undefined && admission !== record.admission)) { return; }
125
+ if (!record.destinations.has(recipient)) { throw new Error('Unknown recipient'); }
126
+ const pair = record.pending.get(recipient);
127
+ if (!pair) { return; }
128
+ if (record.pending.size === 1) { remove(record); return; }
129
+ forget(pair);
130
+ const removedBytes = Buffer.byteLength(JSON.stringify(recipient)) + 1;
131
+ record.bytes -= removedBytes;
132
+ state.bytes -= removedBytes;
133
+ }
134
+ function ready(action) {
135
+ try {
136
+ if (!state.ready) { throw new Error('Spool not opened'); }
137
+ return Promise.resolve(action());
138
+ } catch (error) { return Promise.reject(error); }
139
+ }
140
+ function mutation(operation) {
141
+ try {
142
+ if (operation?.kind === 'append') { append(operation.event, operation.recipients); }
143
+ else if (operation?.kind === 'ack') { acknowledge(operation); }
144
+ else { throw new TypeError('Unknown spool mutation'); }
145
+ return { ok: true };
146
+ } catch (error) { return { ok: false, error }; }
147
+ }
148
+ function pendingFair(limit, blocked) {
149
+ limitOf(limit, 'pending');
150
+ const pages = pagesOf(targets, limit, new Set(blocked));
151
+ const selected = select(pages, limit);
152
+ for (const { target, pairs } of pages) { targets.delete(target); targets.set(target, pairs); }
153
+ return [...selected].map(([record, pairs]) => {
154
+ for (const pair of pairs) {
155
+ const group = targets.get(pair.target);
156
+ group.delete(pair); group.add(pair);
157
+ }
158
+ return { ...decoded(record, pairs.map(({ recipient }) => { return recipient; })), admission: record.admission,
159
+ targets: Object.fromEntries(pairs.map(({ recipient, target }) => { return [recipient, target]; })) };
160
+ });
161
+ }
162
+ return {
163
+ open() { state.ready = true; return Promise.resolve(); },
164
+ mutateMany(operations) {
165
+ return ready(() => {
166
+ if (!Array.isArray(operations) || !operations.length) { throw new TypeError('Nonempty spool mutations required'); }
167
+ return operations.map(mutation);
168
+ });
169
+ },
170
+ pendingFair(limit = 100, blocked = []) { return ready(() => { return pendingFair(limit, blocked); }); },
171
+ hasAdmission(eventId, admission, recipient) {
172
+ const record = records.get(eventId);
173
+ return record?.admission === admission && Boolean(record?.pending.has(recipient));
174
+ },
175
+ peek(limit = 1000) { return ready(() => { return visibleRecords(records, limit); }); },
176
+ close() {
177
+ records.clear(); targets.clear();
178
+ Object.assign(state, { ready: false, bytes: 0 });
179
+ return Promise.resolve();
180
+ },
181
+ status() {
182
+ return { bytes: state.bytes, maxBytes, recordLimit: maxRecords, pending: records.size, ready: state.ready,
183
+ droppedRecords: state.droppedRecords, droppedBytes: state.droppedBytes };
184
+ }
185
+ };
186
+ }
@@ -1,5 +1,4 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { deflateSync, inflateSync } from 'node:zlib';
3
2
 
4
3
  export function digest(value) { return createHash('sha256').update(value).digest('hex'); }
5
4
  export function revive(key, value) {
@@ -13,29 +12,3 @@ export function validate(event, recipients, remaining = recipients) {
13
12
  throw new TypeError('Event identity and unique recipients required; corrupt spool record');
14
13
  }
15
14
  }
16
- export function encoded(event, recipients, remaining = recipients) {
17
- validate(event, recipients, remaining);
18
- const original = JSON.stringify(event);
19
- const snapshot = JSON.parse(original);
20
- const destinations = Array.isArray(snapshot.destinations) ? snapshot.destinations.map((item) => {
21
- const json = JSON.stringify(item); return { id: digest(json), json };
22
- }) : null;
23
- if (destinations) { snapshot.destinations = []; }
24
- return {
25
- id: event.eventId, fingerprint: digest(JSON.stringify({ event, recipients })),
26
- payload: deflateSync(JSON.stringify(snapshot)), destinations,
27
- recipients: JSON.stringify(recipients), remaining: JSON.stringify(remaining),
28
- bytes: Buffer.byteLength(JSON.stringify({ event, recipients, remaining }))
29
- };
30
- }
31
- export function decoded(row, db) {
32
- const event = JSON.parse(inflateSync(row.payload).toString(), revive);
33
- if (row.destinations !== null) {
34
- event.destinations = JSON.parse(row.destinations).map((id) => {
35
- const descriptor = db.prepare('SELECT json FROM destinations WHERE id = ?').get(id);
36
- if (!descriptor) { throw new Error('Corrupt spool destination'); }
37
- return JSON.parse(descriptor.json, revive);
38
- });
39
- }
40
- return { event, remaining: JSON.parse(row.remaining) };
41
- }
@@ -0,0 +1,40 @@
1
+ /** Process-local compare-and-swap state with a shared byte and record limit. */
2
+ export default function taskStateMemory({ maxBytes = 4 * 1024 * 1024, maxRecords = 1024 } = {}) {
3
+ if (![maxBytes, maxRecords].every(value => { return Number.isSafeInteger(value) && value > 0; })) {
4
+ throw new TypeError('Positive task state limits required');
5
+ }
6
+ const entries = new Map();
7
+ let used = 0;
8
+ let version = 0;
9
+ function remove(taskId) {
10
+ used -= entries.get(taskId).bytes;
11
+ entries.delete(taskId);
12
+ }
13
+ function save(taskId, json, bytes) {
14
+ if (entries.has(taskId)) { remove(taskId); }
15
+ version += 1;
16
+ entries.set(taskId, { json, bytes, version });
17
+ used += bytes;
18
+ return version;
19
+ }
20
+ return {
21
+ load(taskId) {
22
+ const item = entries.get(taskId);
23
+ return Promise.resolve(item ? { ...JSON.parse(item.json), version: item.version } : null);
24
+ },
25
+ commit({ taskId, expectedVersion, ownership, stateVersion, compatibilityKey, checkpoint, pending }) {
26
+ if (!Number.isSafeInteger(expectedVersion) || expectedVersion < 0) { throw new TypeError('Invalid expectedVersion'); }
27
+ if (ownership !== undefined) { throw new Error('This store has no external ownership integration'); }
28
+ const current = entries.get(taskId);
29
+ if (expectedVersion !== (current?.version ?? 0)) { throw new Error('Task state conflict'); }
30
+ const json = JSON.stringify({ taskId, stateVersion, compatibilityKey, checkpoint, pending });
31
+ const bytes = Buffer.byteLength(json);
32
+ if ((!current && entries.size >= maxRecords) || used - (current?.bytes ?? 0) + bytes > maxBytes) {
33
+ throw new Error('Task state capacity exceeded');
34
+ }
35
+ return Promise.resolve(save(taskId, json, bytes));
36
+ },
37
+ forget(taskId) { if (entries.has(taskId)) { remove(taskId); } },
38
+ close() { entries.clear(); used = 0; }
39
+ };
40
+ }
@@ -0,0 +1,15 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ export function canonicalJSON(value) {
4
+ if (Array.isArray(value)) { return `[${value.map(canonicalJSON).join(',')}]`; }
5
+ if (value && typeof value === 'object') {
6
+ return `{${Object.keys(value).sort().map((key) => {
7
+ return `${JSON.stringify(key)}:${canonicalJSON(value[key])}`;
8
+ }).join(',')}}`;
9
+ }
10
+ return JSON.stringify(value);
11
+ }
12
+
13
+ export function jsonDigest(value) {
14
+ return createHash('sha256').update(canonicalJSON(value)).digest('hex');
15
+ }
@@ -0,0 +1,129 @@
1
+ import { canonicalJSON } from './canonicalJSON.js';
2
+
3
+ function identifier(name) {
4
+ if (typeof name !== 'string' || !name || name.includes('\0')) { throw new Error('Invalid PostgreSQL identifier'); }
5
+ return `"${name.replaceAll('"', '""')}"`;
6
+ }
7
+
8
+ async function transaction(pool, begin, operation) {
9
+ const client = await pool.connect();
10
+ try {
11
+ await client.query(begin);
12
+ const result = await operation(client);
13
+ await client.query('COMMIT');
14
+ return result;
15
+ } catch (error) {
16
+ await client.query('ROLLBACK').catch(() => { return undefined; });
17
+ throw error;
18
+ } finally { client.release(); }
19
+ }
20
+
21
+ function validateRows(snapshot) {
22
+ snapshot.schema.forEach(({ table, columns }) => {
23
+ const keys = canonicalJSON(columns.map((column) => { return column.name; }).sort());
24
+ if (snapshot.tables[table].some((row) => { return !row || canonicalJSON(Object.keys(row).sort()) !== keys; })) {
25
+ throw new Error('Snapshot columns do not match');
26
+ }
27
+ });
28
+ }
29
+
30
+ async function schemaFor(client, namespace, tables) {
31
+ const result = await client.query(`SELECT c.relname AS "table", a.attname AS name,
32
+ pg_catalog.format_type(a.atttypid,a.atttypmod) AS type, NOT a.attnotnull AS nullable
33
+ FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid=a.attrelid
34
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
35
+ WHERE n.nspname=$1 AND c.relname=ANY($2::text[]) AND a.attnum>0 AND NOT a.attisdropped
36
+ ORDER BY c.relname,a.attnum`, [namespace, tables]);
37
+ return [...tables].sort().map((table) => {
38
+ return { table, columns: result.rows.filter((row) => { return row.table === table; })
39
+ .map(({ name, type, nullable }) => { return { name, type, nullable }; }) };
40
+ });
41
+ }
42
+
43
+ function checkpointStatements(table) {
44
+ return {
45
+ latest: `SELECT hash,exported_at AS "exportedAt",imported_at AS "importedAt" FROM ${table} WHERE id=1`,
46
+ ensure: `CREATE TABLE IF NOT EXISTS ${table}
47
+ (id integer PRIMARY KEY CHECK(id=1), hash text NOT NULL, exported_at timestamptz NOT NULL, imported_at timestamptz NOT NULL)`,
48
+ save: `INSERT INTO ${table} (id,hash,exported_at,imported_at)
49
+ VALUES (1,$1,$2,clock_timestamp()) ON CONFLICT(id) DO UPDATE
50
+ SET hash=EXCLUDED.hash,exported_at=EXCLUDED.exported_at,imported_at=EXCLUDED.imported_at
51
+ RETURNING hash,exported_at AS "exportedAt",imported_at AS "importedAt"`
52
+ };
53
+ }
54
+
55
+ function tableReader(client, qualified) {
56
+ return async (table) => {
57
+ if (!qualified.has(table)) { throw new Error('Table outside snapshot schema'); }
58
+ const result = await client.query(`SELECT row_to_json(row) AS value FROM ${qualified.get(table)} row`);
59
+ return result.rows.map((row) => { return row.value; });
60
+ };
61
+ }
62
+
63
+ async function replaceRows(client, snapshot, qualified, { cascade, disableTriggers }) {
64
+ if (disableTriggers) { await client.query('SET LOCAL session_replication_role=replica'); }
65
+ await client.query(`TRUNCATE ${[...qualified.values()].join(',')}${cascade ? ' CASCADE' : ''}`);
66
+ for (const [name, table] of qualified) {
67
+ // Insert in catalog order because later tables can reference earlier tables.
68
+ // eslint-disable-next-line no-await-in-loop
69
+ await client.query(`INSERT INTO ${table} SELECT * FROM json_populate_recordset(NULL::${table}, $1::json)`,
70
+ [JSON.stringify(snapshot.tables[name])]);
71
+ }
72
+ }
73
+
74
+ /** Replicate an explicit table catalog and atomically record its checkpoint in PostgreSQL. */
75
+ export function postgresSnapshotReplica({
76
+ namespace = 'public', tables, format, checkpoint, lock, compatible, cascade = false, disableTriggers = false
77
+ }) {
78
+ function qualify(name) { return `${identifier(namespace)}.${identifier(name)}`; }
79
+ if (tables.includes(checkpoint)) { throw new Error('Checkpoint table must be outside snapshot schema'); }
80
+ const qualified = new Map(tables.map((name) => { return [name, qualify(name)]; }));
81
+ const state = checkpointStatements(qualify(checkpoint));
82
+ function schema(client) { return schemaFor(client, namespace, tables); }
83
+
84
+ function exportSnapshot(pool) {
85
+ return transaction(pool, 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY', async (client) => {
86
+ await client.query("SET LOCAL TIME ZONE 'UTC'");
87
+ await client.query("SET LOCAL bytea_output='hex'");
88
+ const localSchema = await schema(client);
89
+ const read = tableReader(client, qualified);
90
+ const rows = [];
91
+ for (const name of tables) {
92
+ // The transaction's PostgreSQL client supports one query at a time.
93
+ // eslint-disable-next-line no-await-in-loop
94
+ rows.push([name, await read(name)]);
95
+ }
96
+ return format.seal({ schema: localSchema, tables: Object.fromEntries(rows) });
97
+ });
98
+ }
99
+
100
+ function importSnapshot(pool, input) {
101
+ const snapshot = format.validate(input);
102
+ validateRows(snapshot);
103
+ return transaction(pool, 'BEGIN', async (client) => {
104
+ await client.query('SELECT pg_advisory_xact_lock($1::bigint)', [lock]);
105
+ if (canonicalJSON(await schema(client)) !== canonicalJSON(snapshot.schema)
106
+ || compatible && !await compatible(snapshot, tableReader(client, qualified))) {
107
+ throw new Error('Snapshot does not match the local PostgreSQL schema or identity');
108
+ }
109
+ await client.query(state.ensure);
110
+ const previous = await client.query(state.latest);
111
+ if (previous.rows[0]?.hash !== snapshot.hash) {
112
+ await replaceRows(client, snapshot, qualified, { cascade, disableTriggers });
113
+ }
114
+ const result = await client.query(state.save, [snapshot.hash, snapshot.createdAt]);
115
+ return result.rows[0];
116
+ });
117
+ }
118
+
119
+ async function checkpointFor(pool) {
120
+ const result = await transaction(pool, 'BEGIN', async (client) => {
121
+ await client.query('SELECT pg_advisory_xact_lock($1::bigint)', [lock]);
122
+ await client.query(state.ensure);
123
+ return client.query(state.latest);
124
+ });
125
+ return result.rows[0] || null;
126
+ }
127
+
128
+ return { schema, exportSnapshot, importSnapshot, checkpointFor };
129
+ }
@@ -0,0 +1,40 @@
1
+ import pg from 'pg';
2
+
3
+ function connect({ connectionString, onDatabaseError, poolOptions }) {
4
+ const pool = new pg.Pool({ connectionString, max: 2, options: '-c statement_timeout=20000', connectionTimeoutMillis: 10000, ...poolOptions });
5
+ pool.on('error', () => { onDatabaseError?.(); });
6
+ return pool;
7
+ }
8
+
9
+ function listen(server, { port, host = '127.0.0.1' }, pool, worker) {
10
+ const number = Number(port);
11
+ if (!Number.isSafeInteger(number) || number < 1 || number > 65535) { throw new Error('PostgreSQL snapshot server port is invalid'); }
12
+ server.listen(number, host);
13
+ function close() { server.close(); }
14
+ async function release() {
15
+ process.off('SIGTERM', close);
16
+ process.off('SIGINT', close);
17
+ if (worker) { await worker.stop(); }
18
+ await pool.end();
19
+ }
20
+ server.once('close', () => { void release(); });
21
+ process.once('SIGTERM', close);
22
+ process.once('SIGINT', close);
23
+ return server;
24
+ }
25
+
26
+ export function servePostgresSnapshot(settings, createServer) {
27
+ const pool = connect(settings);
28
+ try { return listen(createServer(pool), settings, pool); }
29
+ catch (error) { void pool.end(); throw error; }
30
+ }
31
+
32
+ export async function followPostgresSnapshot(settings, createWorker) {
33
+ const pool = connect(settings);
34
+ try {
35
+ const worker = await createWorker(pool);
36
+ const server = listen(worker.server, settings, pool, worker);
37
+ worker.start();
38
+ return server;
39
+ } catch (error) { await pool.end(); throw error; }
40
+ }
@@ -0,0 +1,61 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ import { createServer } from 'node:http';
3
+
4
+ function samples(state) {
5
+ const imported = state.checkpoint ? Date.parse(state.checkpoint.importedAt) / 1000 : 0;
6
+ const exported = state.checkpoint ? Date.parse(state.checkpoint.exportedAt) / 1000 : 0;
7
+ return {
8
+ ready: state.checkpoint ? 1 : 0,
9
+ last_success_timestamp_seconds: imported,
10
+ snapshot_timestamp_seconds: exported,
11
+ snapshot_age_seconds: exported ? Math.max(0, Date.now() / 1000 - exported) : 0,
12
+ sync_errors_total: state.errors,
13
+ last_attempt_success: state.lastAttempt ? 1 : 0,
14
+ tls_renewal_errors_total: state.tlsErrors,
15
+ tls_last_success_timestamp_seconds: state.tlsSuccess
16
+ };
17
+ }
18
+
19
+ function status(state, prefix, incoming, response) {
20
+ if (incoming.method !== 'GET') { response.writeHead(405).end(); }
21
+ else if (incoming.url === '/healthz') {
22
+ response.writeHead(state.checkpoint ? 200 : 503, { 'Content-Type': 'application/json' })
23
+ .end(JSON.stringify({ ready: Boolean(state.checkpoint) }));
24
+ } else if (incoming.url === '/metrics') {
25
+ const metrics = Object.entries(samples(state)).map(([name, value]) => { return `${prefix}_${name} ${value}`; });
26
+ response.writeHead(200, { 'Content-Type': 'text/plain; version=0.0.4' }).end(`${metrics.join('\n')}\n`);
27
+ } else { response.writeHead(404).end(); }
28
+ }
29
+
30
+ /** Readiness follows the local checkpoint. Remote failures are reported separately. */
31
+ export async function snapshotSync({
32
+ checkpoint, fetchSnapshot, applySnapshot, renewTLS, stateFile, interval = 60000, metricPrefix = 'snapshot_replica'
33
+ }) {
34
+ if (!/^[a-zA-Z_:][a-zA-Z0-9_:]*$/u.test(metricPrefix)) { throw new Error('Invalid replica metric prefix'); }
35
+ const state = { checkpoint: await checkpoint(), errors: 0, lastAttempt: false, tlsErrors: 0, tlsSuccess: 0 };
36
+ const server = createServer((incoming, response) => { status(state, metricPrefix, incoming, response); });
37
+ let timer;
38
+ let stopped = false;
39
+ let running;
40
+ async function update() {
41
+ try {
42
+ state.checkpoint = await applySnapshot(await fetchSnapshot());
43
+ state.lastAttempt = true;
44
+ if (stateFile) { await writeFile(stateFile, JSON.stringify(state.checkpoint), { mode: 0o600 }); }
45
+ } catch { state.errors += 1; state.lastAttempt = false; }
46
+ }
47
+ async function renewal() {
48
+ try {
49
+ if (renewTLS && await renewTLS()) { state.tlsSuccess = Date.now() / 1000; }
50
+ } catch { state.tlsErrors += 1; }
51
+ }
52
+ async function poll() {
53
+ await Promise.all([update(), renewal()]);
54
+ if (!stopped) { timer = setTimeout(() => { running = poll(); }, interval); }
55
+ }
56
+ return {
57
+ server,
58
+ start() { if (!running && !stopped) { running = poll(); } },
59
+ async stop() { stopped = true; clearTimeout(timer); await running; }
60
+ };
61
+ }
@@ -0,0 +1,50 @@
1
+ import { canonicalJSON, jsonDigest } from './canonicalJSON.js';
2
+
3
+ export const tableSnapshotLimit = 64 * 1024 * 1024;
4
+
5
+ function compareRows(first, second) {
6
+ const before = canonicalJSON(first);
7
+ const after = canonicalJSON(second);
8
+ if (before < after) { return -1; }
9
+ if (before > after) { return 1; }
10
+ return 0;
11
+ }
12
+
13
+ function fail() { throw new Error('Table snapshot is invalid or incompatible'); }
14
+
15
+ function tableSet(value, names, sortedNames) {
16
+ if (!value || typeof value !== 'object' || Array.isArray(value)
17
+ || canonicalJSON(Object.keys(value).sort()) !== sortedNames) { fail(); }
18
+ if (names.some((table) => { return !Array.isArray(value[table]); })) { fail(); }
19
+ }
20
+
21
+ function schemaValid(schema, sortedNames) {
22
+ if (!Array.isArray(schema)
23
+ || canonicalJSON(schema.map((item) => { return item?.table; }).sort()) !== sortedNames) { fail(); }
24
+ if (schema.some((item) => { return !Array.isArray(item.columns) || !item.columns.length
25
+ || item.columns.some((column) => { return typeof column?.name !== 'string' || typeof column.type !== 'string'
26
+ || typeof column.nullable !== 'boolean'; }); })) { fail(); }
27
+ }
28
+
29
+ /** Sorts opaque table rows and hashes the content independently of the export timestamp. */
30
+ export function tableSnapshotFormat({ tables: names, format, metadata = () => { return {}; } }) {
31
+ const sortedNames = canonicalJSON([...names].sort());
32
+ function seal({ schema, tables, createdAt = new Date().toISOString() }) {
33
+ tableSet(tables, names, sortedNames);
34
+ schemaValid(schema, sortedNames);
35
+ if (!Number.isFinite(Date.parse(createdAt))) { fail(); }
36
+ const sorted = Object.fromEntries(names.map((name) => {
37
+ return [name, [...tables[name]].sort(compareRows)];
38
+ }));
39
+ const content = { ...metadata(sorted), format, schemaHash: jsonDigest(schema), tables: sorted };
40
+ return { ...content, schema, createdAt, hash: jsonDigest(content) };
41
+ }
42
+ function validate(value, { maxBytes = tableSnapshotLimit } = {}) {
43
+ if (!value || Buffer.byteLength(JSON.stringify(value)) > maxBytes) { fail(); }
44
+ const expected = seal(value);
45
+ const fields = Object.keys(expected).filter((key) => { return !['schema', 'createdAt', 'tables'].includes(key); });
46
+ if (fields.some((key) => { return canonicalJSON(value[key]) !== canonicalJSON(expected[key]); })) { fail(); }
47
+ return expected;
48
+ }
49
+ return { seal, validate };
50
+ }
@@ -0,0 +1,37 @@
1
+ import kubeServiceAccount from '../management/kubeServiceAccount.js';
2
+ import { tlsMaterialLimit, validateTLSMaterial } from './tlsMaterial.js';
3
+
4
+ function targetPath({namespace,name}) {
5
+ if (![namespace,name].every(value => { return typeof value === 'string' && /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/u.test(value); })) {
6
+ throw new Error('TLS Secret target is invalid');
7
+ }
8
+ return `/api/v1/namespaces/${namespace}/secrets/${name}`;
9
+ }
10
+
11
+ export function kubernetesTLSAPI(environment) {
12
+ const host = environment.KUBERNETES_SERVICE_HOST;
13
+ const port = environment.KUBERNETES_SERVICE_PORT_HTTPS || '443';
14
+ if (!host) { throw new Error('TLS Secret API address is missing'); }
15
+ const address = `https://${host.includes(':') ? `[${host}]` : host}:${port}`;
16
+ const request = kubeServiceAccount(address, { limit: tlsMaterialLimit, timeoutMs: 10000 });
17
+ async function exchange(path, method, body) {
18
+ try {
19
+ const result = await request(method, path, body);
20
+ if (result.status !== 200) { throw new Error('Refused'); }
21
+ return JSON.parse(result.body);
22
+ } catch { throw new Error('TLS Secret API request failed'); }
23
+ }
24
+ return {get:target => { return exchange(targetPath(target),'GET'); },update:(target,body) => { return exchange(targetPath(target),'PUT',body); }};
25
+ }
26
+
27
+ /** Update an already-existing named Secret only; RBAC grants no create or namespace discovery. */
28
+ export async function mirrorTLSSecret(payload, { target, hosts, api, roots, format }) {
29
+ const data = validateTLSMaterial(payload, { hosts, roots, format });
30
+ targetPath(target);
31
+ const secret = await api.get(target);
32
+ if (secret.metadata?.name !== target.name || secret.metadata?.namespace !== target.namespace
33
+ || !secret.metadata?.resourceVersion || secret.type !== 'kubernetes.io/tls') { throw new Error('TLS Secret target does not match'); }
34
+ if (secret.data?.['tls.crt'] === data['tls.crt'] && secret.data?.['tls.key'] === data['tls.key']) { return false; }
35
+ await api.update(target,{...secret,data:{...secret.data,...data}});
36
+ return true;
37
+ }