@yarkivaev/scada 2.14.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 (29) hide show
  1. package/charts/scada/templates/processes.yaml +6 -1
  2. package/charts/scada/values.schema.json +1 -0
  3. package/package.json +1 -1
  4. package/src/application/control/agent.js +8 -14
  5. package/src/application/control/executionSnapshot.js +4 -5
  6. package/src/application/runtime/deliveryOperations.js +6 -3
  7. package/src/application/runtime/deliveryPublications.js +13 -11
  8. package/src/application/runtime/deliveryQueue.js +5 -4
  9. package/src/application/runtime/index.js +0 -1
  10. package/src/application/runtime/queuedDelivery.js +6 -5
  11. package/src/application/runtime/runCollector.js +8 -6
  12. package/src/application/runtime/runtime.js +1 -0
  13. package/src/application/runtime/runtimeServices.js +6 -26
  14. package/src/infrastructure/persistence/runtime/memoryDeliveryStore.js +186 -0
  15. package/src/infrastructure/persistence/runtime/spoolCodec.js +0 -27
  16. package/src/infrastructure/persistence/runtime/taskStateMemory.js +40 -0
  17. package/src/application/control/snapshotFile.js +0 -24
  18. package/src/infrastructure/persistence/runtime/deliverySpool.js +0 -86
  19. package/src/infrastructure/persistence/runtime/spoolCheckpoints.js +0 -65
  20. package/src/infrastructure/persistence/runtime/spoolDatabase.js +0 -69
  21. package/src/infrastructure/persistence/runtime/spoolFormat.js +0 -63
  22. package/src/infrastructure/persistence/runtime/spoolLimits.js +0 -8
  23. package/src/infrastructure/persistence/runtime/spoolMigration.js +0 -66
  24. package/src/infrastructure/persistence/runtime/spoolMutations.js +0 -19
  25. package/src/infrastructure/persistence/runtime/spoolProcess.js +0 -89
  26. package/src/infrastructure/persistence/runtime/spoolProcessChild.js +0 -32
  27. package/src/infrastructure/persistence/runtime/spoolRecords.js +0 -56
  28. package/src/infrastructure/persistence/runtime/spoolReplay.js +0 -55
  29. package/src/infrastructure/persistence/runtime/taskStateSqlite.js +0 -37
@@ -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
- }
@@ -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
- }