@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.
- package/charts/scada/templates/processes.yaml +6 -1
- package/charts/scada/values.schema.json +1 -0
- package/db/bootstrap/apply-hba.sh +11 -0
- package/db/bootstrap/entrypoint.sh +6 -0
- package/db/bootstrap/ownership.sql +18 -0
- package/db/bootstrap/zz-auth.sh +3 -0
- package/index.js +1 -0
- package/package.json +3 -2
- package/src/application/control/agent.js +8 -14
- package/src/application/control/controller.js +2 -9
- package/src/application/control/executionSnapshot.js +4 -5
- package/src/application/control/periodicReconciliation.js +19 -0
- package/src/application/control/publishControlCatalog.js +25 -0
- package/src/application/control/reconcileStoredChoice.js +10 -0
- package/src/application/deploy/controlPlan.js +93 -0
- package/src/application/deploy/deploymentCommands.js +29 -0
- package/src/application/deploy/deploymentPlan.js +84 -0
- package/src/application/deploy/readDocumentFile.js +28 -0
- package/src/application/deploy/releases.js +14 -10
- package/src/application/runtime/deliveryOperations.js +6 -3
- package/src/application/runtime/deliveryPublications.js +13 -11
- package/src/application/runtime/deliveryQueue.js +5 -4
- package/src/application/runtime/index.js +0 -1
- package/src/application/runtime/queuedDelivery.js +6 -5
- package/src/application/runtime/runCollector.js +8 -6
- package/src/application/runtime/runtime.js +1 -0
- package/src/application/runtime/runtimeServices.js +6 -26
- package/src/infrastructure/deploy/applyHelmResources.js +17 -0
- package/src/infrastructure/deploy/bootstrapKubeStorage.js +28 -0
- package/src/infrastructure/deploy/deploymentChecks.js +68 -0
- package/src/infrastructure/deploy/deploymentPatch.js +36 -0
- package/src/infrastructure/deploy/executeChartDeployment.js +19 -0
- package/src/infrastructure/deploy/executeRelease.js +6 -2
- package/src/infrastructure/deploy/executeStagedDeployment.js +31 -0
- package/src/infrastructure/deploy/index.js +29 -0
- package/src/infrastructure/deploy/postgresBootstrap.js +79 -0
- package/src/infrastructure/deploy/reconcileDeployments.js +47 -0
- package/src/infrastructure/deploy/requestFromWorkload.js +30 -0
- package/src/infrastructure/deploy/verifyRuntimeCapabilities.js +34 -0
- package/src/infrastructure/management/kiosk/kiosk-browser.py +91 -0
- package/src/infrastructure/management/kiosk/kiosk-volume.sh +105 -0
- package/src/infrastructure/management/kiosk/listen.mjs.txt +14 -0
- package/src/infrastructure/management/kiosk/operateKiosk.js +74 -0
- package/src/infrastructure/management/kiosk/renderKioskResources.js +41 -0
- package/src/infrastructure/management/kiosk/shellArgument.js +4 -0
- package/src/infrastructure/management/kiosk/wait-x11.sh +1 -0
- package/src/infrastructure/management/kiosk/watchdog-liveness.sh +1 -0
- package/src/infrastructure/management/kiosk/watchdog-readiness.sh +1 -0
- package/src/infrastructure/management/kiosk/watchdog.sh +137 -0
- package/src/infrastructure/management/serveReconciliation.js +17 -0
- package/src/infrastructure/persistence/runtime/memoryDeliveryStore.js +186 -0
- package/src/infrastructure/persistence/runtime/spoolCodec.js +0 -27
- package/src/infrastructure/persistence/runtime/taskStateMemory.js +40 -0
- package/src/application/control/snapshotFile.js +0 -24
- package/src/infrastructure/persistence/runtime/deliverySpool.js +0 -86
- package/src/infrastructure/persistence/runtime/spoolCheckpoints.js +0 -65
- package/src/infrastructure/persistence/runtime/spoolDatabase.js +0 -69
- package/src/infrastructure/persistence/runtime/spoolFormat.js +0 -63
- package/src/infrastructure/persistence/runtime/spoolLimits.js +0 -8
- package/src/infrastructure/persistence/runtime/spoolMigration.js +0 -66
- package/src/infrastructure/persistence/runtime/spoolMutations.js +0 -19
- package/src/infrastructure/persistence/runtime/spoolProcess.js +0 -89
- package/src/infrastructure/persistence/runtime/spoolProcessChild.js +0 -32
- package/src/infrastructure/persistence/runtime/spoolRecords.js +0 -56
- package/src/infrastructure/persistence/runtime/spoolReplay.js +0 -55
- 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
|
+
}
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { mkdir, open, readFile, rename, unlink } from 'node:fs/promises';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { randomUUID } from 'node:crypto';
|
|
4
|
-
export function checkSnapshot(value) {
|
|
5
|
-
if (!value || !Number.isSafeInteger(value.generation) || value.generation < 0 || !Array.isArray(value.assignments)) { throw new TypeError('Invalid assignment snapshot'); }
|
|
6
|
-
return value;
|
|
7
|
-
}
|
|
8
|
-
export async function loadSnapshot(file) {
|
|
9
|
-
try { return checkSnapshot(JSON.parse(await readFile(file, 'utf8'))); } catch (error) { if (error.code === 'ENOENT') { return null; } throw error; }
|
|
10
|
-
}
|
|
11
|
-
export async function saveSnapshot(file, snapshot) {
|
|
12
|
-
checkSnapshot(snapshot);
|
|
13
|
-
await mkdir(path.dirname(file), { recursive: true });
|
|
14
|
-
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
15
|
-
try {
|
|
16
|
-
const handle = await open(temporary, 'wx', 0o600);
|
|
17
|
-
try { await handle.writeFile(JSON.stringify(snapshot)); await handle.sync(); } finally { await handle.close(); }
|
|
18
|
-
await rename(temporary, file);
|
|
19
|
-
const directory = await open(path.dirname(file), 'r');
|
|
20
|
-
try { await directory.sync(); } finally { await directory.close(); }
|
|
21
|
-
} finally { await unlink(temporary).catch(() => {
|
|
22
|
-
// Rename may already have consumed the temporary file.
|
|
23
|
-
}); }
|
|
24
|
-
}
|
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
import { capacity, checkpoint, counters, database } from './spoolDatabase.js';
|
|
2
|
-
import { listed, pending } from './spoolRecords.js';
|
|
3
|
-
import { pendingFair } from './spoolReplay.js';
|
|
4
|
-
import spoolMutations from './spoolMutations.js';
|
|
5
|
-
import spoolMigration from './spoolMigration.js';
|
|
6
|
-
import spoolLimits from './spoolLimits.js';
|
|
7
|
-
import spoolCheckpoints from './spoolCheckpoints.js';
|
|
8
|
-
|
|
9
|
-
/* eslint max-lines-per-function: ["error", 100], max-statements: ["error", 25] */
|
|
10
|
-
/** Single owner, bounded cache and indexed reads. Caps count logical JSON bytes, not allocated pages. */
|
|
11
|
-
export default function deliverySpool(directory, options) {
|
|
12
|
-
const { maxBytes, maxRecords, legacyMigrationMaxBytes, walCheckpoint } = spoolLimits(options);
|
|
13
|
-
const state = { db: null, owner: null, ready: false, busy: false, bytes: 0, records: 0 };
|
|
14
|
-
let maintenance;
|
|
15
|
-
function release() {
|
|
16
|
-
maintenance?.cancel(); maintenance = undefined;
|
|
17
|
-
state.ready = false;
|
|
18
|
-
try { state.db?.close(); } finally { state.owner?.close(); state.db = null; state.owner = null; }
|
|
19
|
-
}
|
|
20
|
-
function refresh() {
|
|
21
|
-
const totals = counters(state.db); state.bytes = totals.bytes; state.records = totals.records;
|
|
22
|
-
}
|
|
23
|
-
async function exclusive(action, requireReady = true) {
|
|
24
|
-
if (state.busy) { throw new Error('Spool operation in progress'); }
|
|
25
|
-
if (requireReady && !state.ready) { throw new Error('Spool not opened'); }
|
|
26
|
-
state.busy = true;
|
|
27
|
-
try { return await action(); } finally { Object.assign(state, { busy:false }); }
|
|
28
|
-
}
|
|
29
|
-
function commit(action) {
|
|
30
|
-
try {
|
|
31
|
-
maintenance?.beforeWrite();
|
|
32
|
-
const result = state.db.transaction(action)();
|
|
33
|
-
refresh(); maintenance?.schedule();
|
|
34
|
-
return result;
|
|
35
|
-
}
|
|
36
|
-
catch (error) { if (error.code?.startsWith('SQLITE_')) { release(); } throw error; }
|
|
37
|
-
}
|
|
38
|
-
function mutateMany(operations) {
|
|
39
|
-
return exclusive(() => { return commit(() => { return spoolMutations(state.db, operations, { maxBytes, maxRecords }); }); });
|
|
40
|
-
}
|
|
41
|
-
async function single(operation) {
|
|
42
|
-
const [result] = await mutateMany([operation]);
|
|
43
|
-
if (!result.ok) { throw result.error; }
|
|
44
|
-
}
|
|
45
|
-
return {
|
|
46
|
-
mutateMany,
|
|
47
|
-
open() {
|
|
48
|
-
return exclusive(async () => {
|
|
49
|
-
if (state.ready) { return; }
|
|
50
|
-
try {
|
|
51
|
-
Object.assign(state, await database(directory));
|
|
52
|
-
capacity(state.db, maxBytes, maxRecords);
|
|
53
|
-
await spoolMigration(directory, state.db, { maxBytes, maxRecords, legacyMigrationMaxBytes });
|
|
54
|
-
if (walCheckpoint) { maintenance = spoolCheckpoints(state.db, directory, walCheckpoint); maintenance.schedule(); }
|
|
55
|
-
refresh(); Object.assign(state, { ready:true });
|
|
56
|
-
} catch (error) { release(); throw error; }
|
|
57
|
-
}, false);
|
|
58
|
-
},
|
|
59
|
-
append(event, recipients) { return single({ kind: 'append', event, recipients }); },
|
|
60
|
-
ack(eventId, recipient) { return single({ kind: 'ack', eventId, recipient }); },
|
|
61
|
-
pending(limit = 100) {
|
|
62
|
-
return exclusive(() => {
|
|
63
|
-
if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive pending limit required'); }
|
|
64
|
-
return commit(() => { return pending(state.db, limit); });
|
|
65
|
-
});
|
|
66
|
-
},
|
|
67
|
-
pendingFair(limit = 100, blocked = []) {
|
|
68
|
-
return exclusive(() => {
|
|
69
|
-
if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive pending limit required'); }
|
|
70
|
-
return commit(() => { return pendingFair(state.db, limit, blocked); });
|
|
71
|
-
});
|
|
72
|
-
},
|
|
73
|
-
peek(limit = 1000) {
|
|
74
|
-
return exclusive(() => {
|
|
75
|
-
if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive peek limit required'); }
|
|
76
|
-
return listed(state.db, limit);
|
|
77
|
-
});
|
|
78
|
-
},
|
|
79
|
-
close() {
|
|
80
|
-
return exclusive(() => {
|
|
81
|
-
try { if (state.db) { checkpoint(state.db); } } finally { release(); }
|
|
82
|
-
}, false);
|
|
83
|
-
},
|
|
84
|
-
status() { return { bytes: state.bytes, maxBytes, recordLimit: maxRecords, pending: state.records, ready: state.ready }; }
|
|
85
|
-
};
|
|
86
|
-
}
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import { statSync } from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
|
|
4
|
-
const idleMs = 150;
|
|
5
|
-
const maxDelayMs = 2000;
|
|
6
|
-
|
|
7
|
-
export function spoolCheckpointLimits(options) {
|
|
8
|
-
if (options === undefined) { return undefined; }
|
|
9
|
-
if (!options || typeof options !== 'object' || Array.isArray(options)) { throw new TypeError('Invalid spool WAL checkpoint options'); }
|
|
10
|
-
const { targetBytes = 2 * 1024 * 1024, maxBytes = 8 * 1024 * 1024 } = options;
|
|
11
|
-
if (!Number.isSafeInteger(targetBytes) || targetBytes <= 0 || !Number.isSafeInteger(maxBytes) || maxBytes <= targetBytes) {
|
|
12
|
-
throw new TypeError('Spool WAL limit must be greater than its positive checkpoint target');
|
|
13
|
-
}
|
|
14
|
-
return { targetBytes, maxBytes };
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export default function spoolCheckpoints(db, directory, { targetBytes, maxBytes }) {
|
|
18
|
-
const file = path.join(directory, 'delivery.sqlite-wal');
|
|
19
|
-
db.pragma('wal_autocheckpoint = 0');
|
|
20
|
-
let timer;
|
|
21
|
-
let deadline;
|
|
22
|
-
let failure;
|
|
23
|
-
|
|
24
|
-
function bytes() { return statSync(file, { throwIfNoEntry: false })?.size ?? 0; }
|
|
25
|
-
function cancel() {
|
|
26
|
-
clearTimeout(timer);
|
|
27
|
-
timer = undefined;
|
|
28
|
-
deadline = undefined;
|
|
29
|
-
}
|
|
30
|
-
function checkpoint(mode) { return db.pragma(`wal_checkpoint(${mode})`)[0]; }
|
|
31
|
-
function maintenance() {
|
|
32
|
-
cancel();
|
|
33
|
-
try {
|
|
34
|
-
const size = bytes();
|
|
35
|
-
if (size >= maxBytes) { checkpoint('TRUNCATE'); }
|
|
36
|
-
else if (size >= targetBytes) { checkpoint('PASSIVE'); }
|
|
37
|
-
} catch (error) { failure = error; }
|
|
38
|
-
}
|
|
39
|
-
return {
|
|
40
|
-
beforeWrite() {
|
|
41
|
-
if (failure) {
|
|
42
|
-
const error = failure;
|
|
43
|
-
failure = undefined;
|
|
44
|
-
throw error;
|
|
45
|
-
}
|
|
46
|
-
// A durable group may cross the limit. A later writer cannot extend that WAL.
|
|
47
|
-
if (bytes() < maxBytes) { return; }
|
|
48
|
-
cancel();
|
|
49
|
-
if (checkpoint('TRUNCATE').busy !== 0) { throw new Error('Spool WAL growth limit reached while checkpoint is busy'); }
|
|
50
|
-
},
|
|
51
|
-
schedule() {
|
|
52
|
-
try {
|
|
53
|
-
if (bytes() < targetBytes) { cancel(); return; }
|
|
54
|
-
const now = performance.now();
|
|
55
|
-
deadline ??= now + maxDelayMs;
|
|
56
|
-
// Keep the timer runnable under sustained writes once its maximum deferral expires.
|
|
57
|
-
if (timer && now >= deadline) { return; }
|
|
58
|
-
clearTimeout(timer);
|
|
59
|
-
timer = setTimeout(maintenance, Math.min(idleMs, deadline - now));
|
|
60
|
-
timer.unref();
|
|
61
|
-
} catch (error) { failure = error; }
|
|
62
|
-
},
|
|
63
|
-
cancel
|
|
64
|
-
};
|
|
65
|
-
}
|
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
import Database from 'better-sqlite3';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { lstat, mkdir, open } from 'node:fs/promises';
|
|
4
|
-
import { constants } from 'node:fs';
|
|
5
|
-
import { format, initialize } from './spoolFormat.js';
|
|
6
|
-
|
|
7
|
-
// POSIX closes release this process's advisory locks for an inode, even from unrelated descriptors.
|
|
8
|
-
// Reserve directory identity before opening ANY owner descriptor, including rejected contenders.
|
|
9
|
-
const registry = Symbol.for('@yarkivaev/scada/delivery-spool-owners');
|
|
10
|
-
globalThis[registry] ??= new Set();
|
|
11
|
-
const owners = globalThis[registry];
|
|
12
|
-
const files = ['owner.sqlite', 'delivery.sqlite'].flatMap((name) => { return [name, `${name}-journal`, `${name}-wal`, `${name}-shm`]; });
|
|
13
|
-
export async function regular(file) {
|
|
14
|
-
try {
|
|
15
|
-
const info = await lstat(file);
|
|
16
|
-
if (!info.isFile() || info.nlink !== 1) { throw new Error('Spool requires private regular files; symlink/hardlink refused'); }
|
|
17
|
-
} catch (error) { if (error.code !== 'ENOENT') { throw error; } }
|
|
18
|
-
}
|
|
19
|
-
async function privateFile(file) {
|
|
20
|
-
const handle = await open(file, constants.O_RDWR + constants.O_CREAT + constants.O_NOFOLLOW, 0o600);
|
|
21
|
-
try {
|
|
22
|
-
const info = await handle.stat();
|
|
23
|
-
if (!info.isFile() || info.nlink !== 1) { throw new Error('Spool requires a private regular file'); }
|
|
24
|
-
await handle.chmod(0o600);
|
|
25
|
-
} finally { await handle.close(); }
|
|
26
|
-
}
|
|
27
|
-
export function counters(db) { return db.prepare('SELECT bytes, records, sequence FROM counters WHERE id=1').get(); }
|
|
28
|
-
export function capacity(db, maxBytes, maxRecords) {
|
|
29
|
-
const totals = counters(db);
|
|
30
|
-
if (totals.records > maxRecords) { throw new Error('Spool record capacity exceeded'); }
|
|
31
|
-
if (totals.bytes > maxBytes) { throw new Error('Spool capacity exceeded'); }
|
|
32
|
-
return totals;
|
|
33
|
-
}
|
|
34
|
-
async function reservation(directory) {
|
|
35
|
-
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
36
|
-
const info = await lstat(directory, { bigint: true });
|
|
37
|
-
if (!info.isDirectory() || info.isSymbolicLink()) { throw new Error('Spool directory symlink refused'); }
|
|
38
|
-
const key = `${info.dev}:${info.ino}`;
|
|
39
|
-
if (owners.has(key)) { throw new Error('Spool already has an owner'); }
|
|
40
|
-
owners.add(key); return key;
|
|
41
|
-
}
|
|
42
|
-
/* eslint max-statements: ["error", 30] */
|
|
43
|
-
export async function database(directory) {
|
|
44
|
-
const key = await reservation(directory);
|
|
45
|
-
let owner;
|
|
46
|
-
let db;
|
|
47
|
-
try {
|
|
48
|
-
for (const suffix of files) {
|
|
49
|
-
// Check all main files and SQLite sidecars before SQLite can modify an alias.
|
|
50
|
-
// eslint-disable-next-line no-await-in-loop
|
|
51
|
-
await regular(path.join(directory, suffix));
|
|
52
|
-
}
|
|
53
|
-
await privateFile(path.join(directory, 'owner.sqlite'));
|
|
54
|
-
owner = new Database(path.join(directory, 'owner.sqlite'), { timeout: 0 });
|
|
55
|
-
owner.exec('BEGIN EXCLUSIVE; CREATE TABLE IF NOT EXISTS owner (id INTEGER)');
|
|
56
|
-
await privateFile(path.join(directory, 'delivery.sqlite'));
|
|
57
|
-
db = new Database(path.join(directory, 'delivery.sqlite'), { timeout: 0 });
|
|
58
|
-
const version = format(db);
|
|
59
|
-
db.pragma('journal_mode = WAL'); db.pragma('synchronous = FULL');
|
|
60
|
-
db.pragma('cache_size = -2048'); db.pragma('wal_autocheckpoint = 256');
|
|
61
|
-
db.pragma('journal_size_limit = 1048576'); db.pragma('secure_delete = FAST');
|
|
62
|
-
if (version < 2) { initialize(db, version); }
|
|
63
|
-
return { db, owner: { close() { try { owner.close(); } finally { owners.delete(key); } } } };
|
|
64
|
-
} catch (error) {
|
|
65
|
-
try { db?.close(); } finally { try { owner?.close(); } finally { owners.delete(key); } }
|
|
66
|
-
throw error;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
export function checkpoint(db) { db.pragma('wal_checkpoint(TRUNCATE)'); }
|
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
const canonical = [
|
|
2
|
-
'CREATE TABLE counters (id INTEGER PRIMARY KEY CHECK(id=1), bytes INTEGER NOT NULL, records INTEGER NOT NULL, sequence INTEGER NOT NULL)',
|
|
3
|
-
'CREATE TABLE destinations (id TEXT PRIMARY KEY, json TEXT NOT NULL, refs INTEGER NOT NULL)',
|
|
4
|
-
`CREATE TABLE events (id TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, payload BLOB NOT NULL,
|
|
5
|
-
destinations TEXT, recipients TEXT NOT NULL, remaining TEXT NOT NULL, bytes INTEGER NOT NULL, sequence INTEGER NOT NULL)`,
|
|
6
|
-
'CREATE INDEX event_sequence ON events(sequence)',
|
|
7
|
-
'CREATE TABLE imports (name TEXT PRIMARY KEY, digest TEXT NOT NULL, event_id TEXT NOT NULL)'
|
|
8
|
-
];
|
|
9
|
-
const replayPending = `CREATE TABLE replay_pending (target TEXT NOT NULL, event_id TEXT NOT NULL, recipient TEXT NOT NULL, sequence INTEGER NOT NULL,
|
|
10
|
-
PRIMARY KEY(target,sequence,event_id,recipient)) WITHOUT ROWID`;
|
|
11
|
-
const replayIndexes = [
|
|
12
|
-
'CREATE UNIQUE INDEX replay_event_recipient ON replay_pending(event_id,recipient)',
|
|
13
|
-
'CREATE TABLE replay_targets (id TEXT PRIMARY KEY, sequence INTEGER NOT NULL)',
|
|
14
|
-
'CREATE INDEX replay_target_sequence ON replay_targets(sequence)'
|
|
15
|
-
];
|
|
16
|
-
const current = [...canonical, replayPending, ...replayIndexes];
|
|
17
|
-
|
|
18
|
-
function metadata(db) {
|
|
19
|
-
return db.prepare("SELECT sql FROM sqlite_schema WHERE name NOT GLOB 'sqlite_*' LIMIT ?").all(current.length + 1);
|
|
20
|
-
}
|
|
21
|
-
function validCounters(db) {
|
|
22
|
-
const rows = db.prepare('SELECT id,bytes,records,sequence FROM counters LIMIT 2').all();
|
|
23
|
-
const row = rows[0];
|
|
24
|
-
return rows.length === 1 && row.id === 1
|
|
25
|
-
&& [row.bytes, row.records, row.sequence].every((value) => { return Number.isSafeInteger(value) && value >= 0; })
|
|
26
|
-
&& row.sequence >= row.records && row.bytes >= row.records
|
|
27
|
-
&& (row.records === 0) === (row.bytes === 0)
|
|
28
|
-
&& (row.records > 0) === Boolean(db.prepare('SELECT 1 FROM events LIMIT 1').get());
|
|
29
|
-
}
|
|
30
|
-
/** Validate bounded metadata before changing existing data or journal settings. Never repair ambiguous storage. */
|
|
31
|
-
export function format(db) {
|
|
32
|
-
const version = db.pragma('user_version', { simple: true });
|
|
33
|
-
const schema = metadata(db);
|
|
34
|
-
if (version === 0 && schema.length === 0) { return 0; }
|
|
35
|
-
if (version !== 1 && version !== 2) { throw new Error('Unsupported spool format version or nonempty database'); }
|
|
36
|
-
const expected = (version === 1 ? canonical : current).map((sql) => { return sql.replaceAll(/\s+/gu, ' '); }).sort();
|
|
37
|
-
const actual = schema.map((row) => { return row.sql.replaceAll(/\s+/gu, ' '); }).sort();
|
|
38
|
-
if (JSON.stringify(actual) !== JSON.stringify(expected) || !validCounters(db)) { throw new Error('Corrupt spool format or counters'); }
|
|
39
|
-
return version;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function populateReplay(db) {
|
|
43
|
-
db.exec(`INSERT INTO replay_pending
|
|
44
|
-
SELECT COALESCE(json_extract(e.destinations,'$['||r.key||']'),'legacy:'||r.value) AS target, e.id, r.value, e.sequence
|
|
45
|
-
FROM events e, json_each(e.recipients) r
|
|
46
|
-
WHERE r.value IN (SELECT value FROM json_each(e.remaining))
|
|
47
|
-
ORDER BY target, e.sequence, e.id, r.value`);
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export function initialize(db, version) {
|
|
51
|
-
// The schema version and derived rows commit together under the spool owner's lock.
|
|
52
|
-
db.transaction(() => {
|
|
53
|
-
if (version === 0) {
|
|
54
|
-
db.exec(canonical.join(';'));
|
|
55
|
-
db.prepare('INSERT INTO counters VALUES (1,0,0,0)').run();
|
|
56
|
-
}
|
|
57
|
-
db.exec(replayPending);
|
|
58
|
-
if (version === 1) { populateReplay(db); }
|
|
59
|
-
db.exec(replayIndexes.join(';'));
|
|
60
|
-
db.exec('INSERT INTO replay_targets SELECT target,MIN(sequence) FROM replay_pending GROUP BY target');
|
|
61
|
-
db.pragma('user_version=2');
|
|
62
|
-
})();
|
|
63
|
-
}
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { spoolCheckpointLimits } from './spoolCheckpoints.js';
|
|
2
|
-
|
|
3
|
-
export default function spoolLimits({ maxBytes, maxRecords = 100000, legacyMigrationMaxBytes = 16 * 1024 * 1024, walCheckpoint } = {}) {
|
|
4
|
-
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) { throw new TypeError('Explicit positive spool maxBytes required'); }
|
|
5
|
-
if (!Number.isSafeInteger(maxRecords) || maxRecords <= 0) { throw new TypeError('Positive safe spool maxRecords required'); }
|
|
6
|
-
if (!Number.isSafeInteger(legacyMigrationMaxBytes) || legacyMigrationMaxBytes <= 0) { throw new TypeError('Positive safe legacyMigrationMaxBytes required'); }
|
|
7
|
-
return { maxBytes, maxRecords, legacyMigrationMaxBytes, walCheckpoint: spoolCheckpointLimits(walCheckpoint) };
|
|
8
|
-
}
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
import { open, opendir, unlink } from 'node:fs/promises';
|
|
2
|
-
import { constants } from 'node:fs';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { decoded, digest, encoded, revive } from './spoolCodec.js';
|
|
5
|
-
import { insert } from './spoolRecords.js';
|
|
6
|
-
|
|
7
|
-
async function load(directory, name, limits) {
|
|
8
|
-
const handle = await open(path.join(directory, name), constants.O_RDONLY + constants.O_NOFOLLOW);
|
|
9
|
-
try {
|
|
10
|
-
const info = await handle.stat();
|
|
11
|
-
if (!info.isFile()) { throw new Error('Spool requires regular legacy file'); }
|
|
12
|
-
if (info.size > limits.maxBytes) { throw new Error('Spool capacity exceeded by legacy file'); }
|
|
13
|
-
if (info.size > limits.legacyMigrationMaxBytes) { throw new Error('Legacy migration record capacity exceeded: legacyMigrationMaxBytes'); }
|
|
14
|
-
const buffer = Buffer.alloc(info.size + 1);
|
|
15
|
-
let offset = 0;
|
|
16
|
-
while (offset < buffer.length) {
|
|
17
|
-
// The read itself is bounded even if a noncompliant writer grows the file after stat.
|
|
18
|
-
// eslint-disable-next-line no-await-in-loop
|
|
19
|
-
const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, null);
|
|
20
|
-
if (!bytesRead) { break; }
|
|
21
|
-
offset += bytesRead;
|
|
22
|
-
}
|
|
23
|
-
if (offset !== info.size) { throw new Error('Corrupt spool legacy file changed while reading'); }
|
|
24
|
-
return buffer.subarray(0, offset).toString('utf8');
|
|
25
|
-
} finally { await handle.close(); }
|
|
26
|
-
}
|
|
27
|
-
function verify(db, value) {
|
|
28
|
-
const row = db.prepare('SELECT * FROM events WHERE id=?').get(value.id);
|
|
29
|
-
if (!row || row.fingerprint !== value.fingerprint || row.remaining !== value.remaining
|
|
30
|
-
|| encoded(decoded(row, db).event, JSON.parse(row.recipients), JSON.parse(row.remaining)).fingerprint !== value.fingerprint) {
|
|
31
|
-
throw new Error('Legacy import verification failed');
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
/* eslint max-statements: ["error", 20] */
|
|
35
|
-
async function migrateFile(directory, name, db, limits) {
|
|
36
|
-
const text = await load(directory, name, limits);
|
|
37
|
-
const record = JSON.parse(text, revive);
|
|
38
|
-
if (!Array.isArray(record.remaining)) { throw new Error('Corrupt spool receipt state'); }
|
|
39
|
-
const value = encoded(record.event, record.recipients, record.remaining);
|
|
40
|
-
if (`${digest(record.event.eventId)}.json` !== name) { throw new Error('Corrupt spool record filename'); }
|
|
41
|
-
const hash = digest(text);
|
|
42
|
-
db.transaction(() => {
|
|
43
|
-
const imported = db.prepare('SELECT digest FROM imports WHERE name=?').get(name);
|
|
44
|
-
if (imported && imported.digest !== hash) { throw new Error('Conflicting legacy import'); }
|
|
45
|
-
insert(db, value, limits.maxBytes, limits.maxRecords);
|
|
46
|
-
db.prepare('INSERT OR IGNORE INTO imports VALUES (?,?,?)').run(name, hash, value.id);
|
|
47
|
-
})();
|
|
48
|
-
verify(db, value);
|
|
49
|
-
// Verify source unchanged after commit before unlink; owner excludes compliant concurrent writers.
|
|
50
|
-
if (digest(await load(directory, name, limits)) !== hash) { throw new Error('Legacy import source changed'); }
|
|
51
|
-
await unlink(path.join(directory, name));
|
|
52
|
-
const handle = await open(directory, 'r');
|
|
53
|
-
try { await handle.sync(); } finally { await handle.close(); }
|
|
54
|
-
}
|
|
55
|
-
export default async function spoolMigration(directory, db, limits) {
|
|
56
|
-
const files = await opendir(directory);
|
|
57
|
-
for await (const file of files) {
|
|
58
|
-
if (/^[a-f0-9]{64}\.json$/u.test(file.name)) {
|
|
59
|
-
if (!file.isFile()) { throw new Error('Spool requires regular legacy file; symlink refused'); }
|
|
60
|
-
// Bound migration memory independently of legacy directory size.
|
|
61
|
-
await migrateFile(directory, file.name, db, limits);
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
// Import ledger is no longer needed once every original is durably removed.
|
|
65
|
-
db.prepare('DELETE FROM imports').run();
|
|
66
|
-
}
|