@yarkivaev/scada 2.6.0 → 2.6.2

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/README.md CHANGED
@@ -730,3 +730,27 @@ Collector health opens before local spool recovery; `/live` remains responsive a
730
730
  Spooled destination descriptors retain secret references. Draining a recovered queue resolves the current secret for each logical recipient, so credential rotation does not freeze a password in queued observations. Source connection credentials are still resolved at resource construction. Scheduler updates preserve a potentially working replica until another matching reader reports fresh progress, except explicit current-generation failure.
731
731
 
732
732
  Central canonical ingestion propagates the receiver session ownership predicate through schema initialization and admission. It checks ownership again after authoritative state/clock reads and before writes; a lost session cannot allocate a newer revision from a delayed SELECT. Already submitted old-revision inserts remain safe under canonical winner ordering.
733
+
734
+
735
+ Collector delivery storage uses version1 SQLite with WAL and synchronous FULL. Acceptance and recipient acknowledgements return after commit. Event payloads are compressed; destination descriptors (including raw Secret references) are interned and retained until their last pending event is confirmed. Startup reads counters and bounded directory entries, rather than building an in-memory event index. Pending batches rotate durably through an indexed sequence so an offline recipient cannot starve later records.
736
+
737
+ `maxBytes` limits the logical UTF-8 JSON size of `{event, recipients, remaining}`; it does not describe disk allocation. `maxRecords` independently limits retained observations. SQLite pages, indexes and WAL require additional capacity planning. The page cache is 2 MiB; automatic checkpoints run every 256 WAL pages and keep at most 1 MiB after checkpoint. A single large transaction may temporarily exceed that checkpoint target. Deleted pages are reused by later observations; database files retain their high-water allocation. Do not delete/vacuum an active spool to reclaim space.
738
+
739
+ Only one process may own a spool directory on a local filesystem with SQLite WAL/locking semantics. Stop an older JSON-based collector before upgrading; its writer does not participate in the new ownership lock. The spool directory must remain private to the collector. Call `close()` before reopening it elsewhere; a killed process releases its SQLite ownership lock automatically. Queue shutdown waits for accepted operations and its current drain before closing sessions and storage. Legacy committed SHA256-named JSON records import one at a time: commit and verify the exact event/receipts before unlinking and syncing the directory. An interrupted import reconciles on the next open; corrupt, ambiguous or over-limit files fail startup and remain recoverable. Unrelated files are untouched and symlinked committed records and symlinked/hard-linked SQLite main files or sidecars are rejected. Existing databases must match the versioned schema and contain valid counters; ambiguous state is rejected rather than repaired. Correct the underlying file/capacity problem before retrying recovery; never discard pending files to make readiness green.
740
+
741
+ Use `node --expose-gc scripts/measure-delivery-spool.mjs FIXTURE.json 120000` with actual adapter `{event,destinations}` samples to measure a target environment. The benchmark reports logical/compressed/page/index bytes, heap/RSS, recovery, append/drain and page reuse separately; its sink stand-in does not measure broker latency.
742
+
743
+
744
+ `legacyMigrationMaxBytes` is a separate positive safe-integer option on `deliverySpool()` / `deliveryQueue()`, defaulting to **16 MiB per committed legacy JSON file**. The queue-wide `maxBytes` may be many GiB; it does not increase this migration allocation budget. Recovery checks both limits from the open file descriptor before allocating or reading its body, including the post-commit verification read. A file exceeding either limit stops recovery and remains untouched. For a legitimate larger legacy record, raise `legacyMigrationMaxBytes` explicitly within the collector's available memory budget and retry; parsing, serialization and compression require additional memory beyond the read buffer. This option applies only to legacy JSON migration. Newly appended generic events and existing SQLite records keep their existing logical queue/record-cap semantics.
745
+
746
+ ### Durable queue group commit
747
+
748
+ `deliverySpool.mutateMany(operations)` adds ordered append/receipt mutations to one WAL/FULL outer transaction. Entries are `{kind:'append', event, recipients}` or `{kind:'ack', eventId, recipient}`. The returned array contains `{ok:true}` or `{ok:false,error}` for each entry, and becomes available only after COMMIT. Validation, identity and capacity errors roll back that entry's savepoint; SQLite or COMMIT errors reject the entire call and fail the spool closed. Existing `append()` and `ack()` still perform immediate durable single-operation calls. Format version1 and legacy recovery are unchanged.
749
+
750
+ `deliveryQueue()` accumulates frozen operations before its database serialization barrier. Defaults are `groupCommit: {maxRecords:64, maxBytes:1048576, maxDelayMs:25}`, `maxOperations:128` and `maxPendingBytes:4194304`. Limits must be positive safe integers; the delay may be zero and cannot exceed the platform timer range. Every submitted operation must fit both byte limits. Increase these explicit options within the process memory budget for larger generic envelopes. Count admission is checked before snapshot construction; oversized serialized inputs are rejected before decoding their queue snapshot. Count and bytes remain reserved through the actual grouped operation, including an in-flight commit, even if an upstream caller stops waiting.
751
+
752
+ No observation is merged, sampled or discarded by batching. An `accept()` promise succeeds only after durable commit. A sparse group flushes on its timer; capacity thresholds, reads and close force earlier flushing. The delay bounds the coalescing window, not disk latency or end-to-end completion. Queue status retains durable `pending`/`bytes` and adds `queuedOperations`, `queuedBytes` and `drainFull` diagnostics.
753
+
754
+ Receipt admission is reserved before network publication, then queued only after mandatory confirmation. Confirmed receipts accumulate in a bounded window; `drain()` counts them delivered only after their FULL commit. Graceful close rejects new source submissions, flushes existing submissions, waits for the active drain and its receipts, then closes sessions and persistence. The existing crash-after-confirm/before-local-receipt replay contract remains unchanged.
755
+
756
+ Healthy full drain pages with durable progress continue on subsequent event-loop turns; after four pages the scheduler pauses 25 ms. Failed, empty or zero-progress pages back off 1s. This removes the former 100-event/s scheduling ceiling without spinning on an offline recipient. Actual append and online catch-up throughput still require qualification on the target filesystem; a serial producer awaiting every individual acceptance cannot benefit from concurrent group formation.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.6.0",
3
+ "version": "2.6.2",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,119 @@
1
+ function positive(value, name, zero = false) {
2
+ if (!Number.isSafeInteger(value) || value < (zero ? 0 : 1)) { throw new TypeError(`${name} must be a ${zero ? 'nonnegative' : 'positive'} safe integer`); }
3
+ }
4
+ function settings(options) {
5
+ if (options.groupCommit !== undefined && (!options.groupCommit || typeof options.groupCommit !== 'object' || Array.isArray(options.groupCommit))) {
6
+ throw new TypeError('groupCommit must be an object');
7
+ }
8
+ const { maxRecords = 64, maxBytes = 1048576, maxDelayMs = 25 } = options.groupCommit ?? {};
9
+ const group = { maxRecords, maxBytes, maxDelayMs };
10
+ const config = { ...group, maxOperations: options.maxOperations ?? 128, maxPendingBytes: options.maxPendingBytes ?? 4194304 };
11
+ Object.entries(config).forEach(([name, value]) => { positive(value, name, name === 'maxDelayMs'); });
12
+ if (config.maxDelayMs > 2147483647) { throw new TypeError('maxDelayMs must be a safe timer duration'); }
13
+ return config;
14
+ }
15
+ /** Bounded FIFO admission precedes serialization; every reservation includes actual in-flight writes. */
16
+ /* eslint max-lines-per-function: ["error", 135], max-statements: ["error", 20] */
17
+ export default function deliveryOperations(apply, options = {}) {
18
+ const config = settings(options);
19
+ const jobs = [];
20
+ const state = { operations: 0, bytes: 0, running: false, timer: null, idle: null, wake: null };
21
+ function reserve() {
22
+ if (state.operations >= config.maxOperations) { throw new Error('Delivery operation capacity exceeded'); }
23
+ state.operations += 1;
24
+ }
25
+ function notifyIdle() {
26
+ if (!state.operations && !state.running) { state.wake?.(); Object.assign(state, { idle: null, wake: null }); }
27
+ }
28
+ function release(bytes) { state.operations -= 1; state.bytes -= bytes; notifyIdle(); }
29
+ function settle(job, result) {
30
+ release(job.bytes);
31
+ if (result.ok) { job.resolve(result.value); } else { job.reject(result.error); }
32
+ }
33
+ function group() {
34
+ const selected = []; let bytes = 0;
35
+ while (jobs.length && jobs[0].kind === 'mutation' && selected.length < config.maxRecords
36
+ && bytes + jobs[0].bytes <= config.maxBytes) {
37
+ const job = jobs.shift(); selected.push(job); bytes += job.bytes;
38
+ }
39
+ return selected;
40
+ }
41
+ async function executeBarrier() {
42
+ const job = jobs.shift();
43
+ try { const value = await job.action(); settle(job, { ok: true, value }); }
44
+ catch (error) { settle(job, { ok: false, error }); }
45
+ }
46
+ async function executeGroup() {
47
+ const selected = group();
48
+ try {
49
+ const results = await apply(selected.map((job) => { return job.operation; }));
50
+ if (!Array.isArray(results) || results.length !== selected.length
51
+ || results.some((result) => { return typeof result?.ok !== 'boolean'; })) { throw new Error('Invalid grouped mutation result'); }
52
+ selected.forEach((job, index) => { settle(job, results[index]); });
53
+ } catch (error) { selected.forEach((job) => { settle(job, { ok: false, error }); }); }
54
+ }
55
+ async function execute() {
56
+ clearTimeout(state.timer); state.timer = null;
57
+ if (state.running) { return; }
58
+ state.running = true;
59
+ try {
60
+ while (jobs.length) {
61
+ // eslint-disable-next-line no-await-in-loop
62
+ await (jobs[0].kind === 'barrier' ? executeBarrier() : executeGroup());
63
+ // Every group yields so sustained backlog cannot monopolize the event loop.
64
+ // eslint-disable-next-line no-await-in-loop
65
+ if (jobs.length) { await new Promise((resolve) => { setImmediate(resolve); }); }
66
+ }
67
+ } finally { Object.assign(state, { running: false }); notifyIdle(); }
68
+ }
69
+ function schedule(delay) {
70
+ if (state.running) { return; }
71
+ if (state.timer && delay !== 0) { return; }
72
+ clearTimeout(state.timer); state.timer = setTimeout(execute, delay);
73
+ }
74
+ function enqueue(job) {
75
+ return new Promise((resolve, reject) => {
76
+ jobs.push({ ...job, resolve, reject });
77
+ schedule(job.kind === 'barrier' || state.operations >= Math.min(config.maxRecords, config.maxOperations) ? 0 : config.maxDelayMs);
78
+ });
79
+ }
80
+ function checkBytes(bytes) {
81
+ positive(bytes, 'Mutation bytes', true);
82
+ if (state.bytes + bytes > config.maxPendingBytes) { throw new Error('Delivery pending byte capacity exceeded'); }
83
+ if (bytes > config.maxBytes) { throw new Error('Delivery group byte capacity exceeded'); }
84
+ }
85
+ function prepare(build) {
86
+ reserve();
87
+ let value;
88
+ try {
89
+ value = build(checkBytes); checkBytes(value.bytes);
90
+ } catch (error) { release(0); throw error; }
91
+ state.bytes += value.bytes;
92
+ let settled = false;
93
+ return {
94
+ commit() {
95
+ if (settled) { return Promise.reject(new Error('Delivery reservation already settled')); }
96
+ settled = true; return enqueue({ kind: 'mutation', ...value });
97
+ },
98
+ cancel() { if (!settled) { settled = true; release(value.bytes); } }
99
+ };
100
+ }
101
+ return {
102
+ prepare,
103
+ mutate(build) {
104
+ try { return prepare(build).commit(); } catch (error) { return Promise.reject(error); }
105
+ },
106
+ barrier(action) {
107
+ try { reserve(); return enqueue({ kind: 'barrier', action, bytes: 0 }); }
108
+ catch (error) { return Promise.reject(error); }
109
+ },
110
+ flush() { if (jobs.length) { schedule(0); } },
111
+ idle() {
112
+ if (!state.operations && !state.running) { return Promise.resolve(); }
113
+ schedule(0);
114
+ state.idle ??= new Promise((resolve) => { state.wake = resolve; });
115
+ return state.idle;
116
+ },
117
+ status() { return { operations: state.operations, bytes: state.bytes }; }
118
+ };
119
+ }
@@ -1,62 +1,96 @@
1
1
  import deliverySpool from '../../infrastructure/persistence/runtime/deliverySpool.js';
2
2
  import deliverySessions from './deliverySessions.js';
3
+ import deliveryOperations from './deliveryOperations.js';
3
4
 
4
5
  function confirmed(event) {
5
6
  return { ...event, options: { ...event.options, persistent: true, mandatory: true, messageId: event.eventId } };
6
7
  }
7
- /* eslint max-lines-per-function: ["error", 60] */
8
- /** Node-owned queue: removing a source does not remove its destination descriptors or receipts. */
8
+ function snapshot(operation, checkBytes) {
9
+ const json = JSON.stringify(operation); checkBytes(Buffer.byteLength(json));
10
+ const frozen = JSON.parse(json);
11
+ if (frozen.kind === 'append') { frozen.recipients = frozen.event.destinations.map((item) => { return item.id; }); }
12
+ return { operation: frozen, bytes: Buffer.byteLength(JSON.stringify(frozen)) };
13
+ }
14
+ /* eslint max-lines-per-function: ["error", 125], max-statements: ["error", 25] */
15
+ /** Node-owned queue: every point/receipt resolves only after its grouped FULL commit. */
9
16
  export default function deliveryQueue(directory, options) {
10
17
  const spool = deliverySpool(directory, options);
18
+ const commands = deliveryOperations((operations) => { return spool.mutateMany(operations); }, options);
11
19
  const sessions = deliverySessions(options.factory, options.writeTimeoutMs);
12
- let chain = Promise.resolve();
13
- const state = { pending: 0, draining: false, closed: false };
14
- function serialized(action) {
15
- if (state.pending >= (options.maxOperations ?? 32)) { return Promise.reject(new Error('Delivery operation capacity exceeded')); }
16
- state.pending += 1;
17
- const result = chain.then(action).finally(() => { state.pending -= 1; });
18
- chain = result.catch(() => {
19
- // Individual callers receive rejection; preserve serialization.
20
- });
21
- return result;
22
- }
23
- async function send(record, id) {
20
+ const batchSize = options.batchSize ?? 100;
21
+ if (!Number.isSafeInteger(batchSize) || batchSize <= 0) { throw new TypeError('Positive safe batchSize required'); }
22
+ const receiptWindow = Math.min(options.groupCommit?.maxRecords ?? 64, options.maxOperations ?? 128);
23
+ const state = { draining: false, closed: false, full: false };
24
+ async function publish(record, id) {
24
25
  if (state.closed) { throw new Error('Delivery queue closed'); }
25
- const descriptor = record.event.destinations.find((item) => { return item.id === id; });
26
- await sessions.write(descriptor, confirmed(record.event.observation));
27
- await serialized(() => { return spool.ack(record.event.eventId, id); });
26
+ // Reserve the eventual receipt BEFORE publication; confirmation can never lose its admission slot.
27
+ const receipt = commands.prepare((checkBytes) => { return snapshot({ kind: 'ack', eventId: record.event.eventId, recipient: id }, checkBytes); });
28
+ try {
29
+ const descriptor = record.event.destinations.find((item) => { return item.id === id; });
30
+ await sessions.write(descriptor, confirmed(record.event.observation));
31
+ return { receipt: receipt.commit() };
32
+ } catch (error) { receipt.cancel(); throw error; }
33
+ }
34
+ async function drain() {
35
+ state.draining = true;
36
+ const result = { delivered: 0, failed: 0 };
37
+ const receipts = [];
38
+ function failure(error) {
39
+ result.failed += 1;
40
+ try { options.onError?.(error); } catch {
41
+ // Observers cannot prevent independent recipient progress or release.
42
+ }
43
+ }
44
+ async function flush() { commands.flush(); await Promise.all(receipts.splice(0)); }
45
+ async function receive(row, id) {
46
+ try {
47
+ const sent = await publish(row, id);
48
+ receipts.push(sent.receipt.then(() => { result.delivered += 1; }, failure));
49
+ } catch (error) { failure(error); }
50
+ if (receipts.length >= receiptWindow) { await flush(); }
51
+ }
52
+ try {
53
+ const rows = await commands.barrier(() => { return spool.pending(batchSize); });
54
+ Object.assign(state, { full: rows.length === batchSize });
55
+ for (const row of rows) {
56
+ for (const id of row.remaining) {
57
+ // eslint-disable-next-line no-await-in-loop
58
+ await receive(row, id);
59
+ }
60
+ }
61
+ return result;
62
+ } finally { try { await flush(); } finally { Object.assign(state, { draining: false }); } }
28
63
  }
29
-
30
64
  return {
31
- open() { return serialized(() => { return spool.open(); }); },
65
+ open() {
66
+ if (state.closed) { return Promise.reject(new Error('Delivery queue closed')); }
67
+ return commands.barrier(() => { return spool.open(); });
68
+ },
32
69
  accept(event, destinations) {
33
70
  if (state.closed) { return Promise.reject(new Error('Delivery queue closed')); }
34
71
  if (!destinations?.length || destinations.some((item) => { return item.type !== 'amqp'; })) {
35
72
  return Promise.reject(new TypeError('Queued delivery requires confirmed AMQP destinations'));
36
73
  }
37
- // Snapshot before asynchronous I/O; callers may reuse buffers/objects.
38
- const envelope = JSON.parse(JSON.stringify({ eventId: event.eventId, observation: event, destinations }));
39
- return serialized(() => { return spool.append(envelope, destinations.map((item) => { return item.id; })); });
74
+ return commands.mutate((checkBytes) => { return snapshot({ kind: 'append', event: { eventId: event.eventId, observation: event, destinations } }, checkBytes); });
40
75
  },
41
- async drain() {
42
- if (state.draining || state.closed) { return { delivered: 0, failed: 0 }; }
43
- state.draining = true;
44
- const result = { delivered: 0, failed: 0 };
45
- try {
46
- const rows = await serialized(() => { return spool.pending(options.batchSize ?? 100); });
47
- for (const row of rows) {
48
- for (const id of row.remaining) {
49
- // Recipients fail independently; continue draining other destinations.
50
- // eslint-disable-next-line no-await-in-loop, max-depth
51
- try { await send(row, id); result.delivered += 1; } catch (error) {
52
- result.failed += 1; options.onError?.(error);
53
- }
54
- }
55
- }
56
- return result;
57
- } finally { Object.assign(state, { draining: false }); }
76
+ drain() {
77
+ if (state.draining || state.closed) { return Promise.resolve({ delivered: 0, failed: 0 }); }
78
+ const result = drain(); state.activeDrain = result; return result;
79
+ },
80
+ close() {
81
+ state.closed = true; commands.flush();
82
+ state.closing ??= (async () => {
83
+ await state.activeDrain?.catch(() => {
84
+ // Drain caller receives the original error.
85
+ });
86
+ await commands.idle();
87
+ try { await sessions.close(); } finally { await spool.close(); }
88
+ })();
89
+ return state.closing;
58
90
  },
59
- close() { state.closed = true; return sessions.close(); },
60
- status() { return spool.status(); }
91
+ status() {
92
+ const usage = commands.status();
93
+ return { ...spool.status(), queuedOperations: usage.operations, queuedBytes: usage.bytes, drainFull: state.full };
94
+ }
61
95
  };
62
96
  }
@@ -5,17 +5,29 @@ import { sinks } from './streamPorts.js';
5
5
  export default function queuedDelivery(env, secrets, supplied) {
6
6
  let timer;
7
7
  let stopped = false;
8
+ let burst = 0;
8
9
  const queue = supplied ?? (env.COLLECTOR_SPOOL_DIR ? deliveryQueue(env.COLLECTOR_SPOOL_DIR, {
9
10
  maxBytes: Number(env.COLLECTOR_SPOOL_MAX_BYTES), maxRecords: Number(env.COLLECTOR_SPOOL_MAX_RECORDS ?? 100000), factory(spec) { return sinks().get(spec.type)(spec, { secrets }); },
10
11
  onError(error) { process.stderr.write(`Collector delivery delayed: ${error.message}\n`); }
11
12
  }) : undefined);
13
+ function nextDelay(result) {
14
+ const status = queue.status?.();
15
+ if (result?.failed === 0 && result.delivered > 0 && status?.ready !== false && status?.drainFull && status.pending > 0) {
16
+ burst += 1;
17
+ const delay = burst < 4 ? 0 : 25;
18
+ if (burst === 4) { burst = 0; }
19
+ return delay;
20
+ }
21
+ burst = 0; return 1000;
22
+ }
12
23
  async function tick() {
13
24
  if (stopped || !queue) { return; }
25
+ let delay = 1000;
14
26
  try {
15
27
  if (queue.status?.().ready === false) { await queue.open(); }
16
- await queue.drain();
17
- } catch (error) { process.stderr.write(`Collector spool: ${error.message}\n`); }
18
- if (!stopped) { timer = setTimeout(tick, 1000); timer.unref(); }
28
+ delay = nextDelay(await queue.drain());
29
+ } catch (error) { burst = 0; process.stderr.write(`Collector spool: ${error.message}\n`); }
30
+ if (!stopped) { timer = setTimeout(tick, delay); timer.unref(); }
19
31
  }
20
32
  return {
21
33
  queue,
@@ -1,124 +1,65 @@
1
- import { createHash, randomUUID } from 'node:crypto';
2
- import { mkdir, open, opendir, readFile, rename, stat, unlink } from 'node:fs/promises';
3
- import path from 'node:path';
1
+ import { capacity, checkpoint, counters, database } from './spoolDatabase.js';
2
+ import { pending } from './spoolRecords.js';
3
+ import spoolMutations from './spoolMutations.js';
4
+ import spoolMigration from './spoolMigration.js';
4
5
 
5
- function filename(id) { return `${createHash('sha256').update(id).digest('hex')}.json`; }
6
- async function syncDirectory(directory) {
7
- const handle = await open(directory, 'r');
8
- try { await handle.sync(); } finally { await handle.close(); }
9
- }
10
- async function replace(directory, name, value) {
11
- const temporary = path.join(directory, `${name}.${randomUUID()}.tmp`);
12
- const handle = await open(temporary, 'wx', 0o600);
13
- try { await handle.writeFile(value); await handle.sync(); } finally { await handle.close(); }
14
- await rename(temporary, path.join(directory, name));
15
- await syncDirectory(directory);
16
- }
17
- function revive(key, value) {
18
- return value?.type === 'Buffer' && Array.isArray(value.data) ? Buffer.from(value.data) : value;
19
- }
20
- async function restore(directory, entries, maxRecords, load) {
21
- let bytes = 0;
22
- const files = await opendir(directory);
23
- for await (const file of files) {
24
- const { name } = file;
25
- if (/^[a-f0-9]{64}\.json$/u.test(name)) {
26
- if (entries.size >= maxRecords) { throw new Error('Spool record capacity exceeded during recovery'); }
27
- // Read one committed entry at a time; memory never holds the directory listing.
28
- const record = await load(name);
29
- if (typeof record.event?.eventId !== 'string' || filename(record.event.eventId) !== name
30
- || !Array.isArray(record.remaining) || !Array.isArray(record.recipients)) { throw new Error('Corrupt spool record'); }
31
- const { size } = await stat(path.join(directory, name));
32
- entries.set(record.event.eventId, { name, size }); bytes += size;
33
- }
34
- }
35
- return bytes;
36
- }
37
6
  /* eslint max-lines-per-function: ["error", 100], max-statements: ["error", 25] */
38
- /** Single writer on a persistent local volume. Failed/ambiguous acknowledgements retain data. */
39
- export default function deliverySpool(directory, { maxBytes, maxRecords = 100000 } = {}) {
7
+ /** Single owner, bounded cache and indexed reads. Caps count logical JSON bytes, not allocated pages. */
8
+ export default function deliverySpool(directory, { maxBytes, maxRecords = 100000, legacyMigrationMaxBytes = 16 * 1024 * 1024 } = {}) {
40
9
  if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) { throw new TypeError('Explicit positive spool maxBytes required'); }
41
10
  if (!Number.isSafeInteger(maxRecords) || maxRecords <= 0) { throw new TypeError('Positive safe spool maxRecords required'); }
42
- const entries = new Map();
43
- const state = { bytes: 0, ready: false, busy: false };
44
- async function exclusive(action) {
11
+ if (!Number.isSafeInteger(legacyMigrationMaxBytes) || legacyMigrationMaxBytes <= 0) { throw new TypeError('Positive safe legacyMigrationMaxBytes required'); }
12
+ const state = { db: null, owner: null, ready: false, busy: false, bytes: 0, records: 0 };
13
+ function release() {
14
+ state.ready = false;
15
+ try { state.db?.close(); } finally { state.owner?.close(); state.db = null; state.owner = null; }
16
+ }
17
+ function refresh() {
18
+ const totals = counters(state.db); state.bytes = totals.bytes; state.records = totals.records;
19
+ }
20
+ async function exclusive(action, requireReady = true) {
45
21
  if (state.busy) { throw new Error('Spool operation in progress'); }
22
+ if (requireReady && !state.ready) { throw new Error('Spool not opened'); }
46
23
  state.busy = true;
47
- try { return await action(); } finally { Object.assign(state, { busy: false }); }
24
+ try { return await action(); } finally { Object.assign(state, { busy:false }); }
25
+ }
26
+ function commit(action) {
27
+ try { const result = state.db.transaction(action)(); refresh(); return result; }
28
+ catch (error) { if (error.code?.startsWith('SQLITE_')) { release(); } throw error; }
29
+ }
30
+ function mutateMany(operations) {
31
+ return exclusive(() => { return commit(() => { return spoolMutations(state.db, operations, { maxBytes, maxRecords }); }); });
32
+ }
33
+ async function single(operation) {
34
+ const [result] = await mutateMany([operation]);
35
+ if (!result.ok) { throw result.error; }
48
36
  }
49
- function current() { if (!state.ready) { throw new Error('Spool not opened'); } }
50
- async function load(name) { return JSON.parse(await readFile(path.join(directory, name), 'utf8'), revive); }
51
37
  return {
38
+ mutateMany,
52
39
  open() {
53
40
  return exclusive(async () => {
54
- Object.assign(state, { ready: false }); entries.clear(); state.bytes = 0;
55
- await mkdir(directory, { recursive: true, mode: 0o700 });
56
- const bytes = await restore(directory, entries, maxRecords, load);
57
- Object.assign(state, { bytes });
58
- Object.assign(state, { ready: true });
59
- });
60
- },
61
- append(event, recipients) {
62
- return exclusive(async () => {
63
- current();
64
- if (typeof event.eventId !== 'string' || !event.eventId || !Array.isArray(recipients) || !recipients.length
65
- || recipients.some((item) => { return typeof item !== 'string' || !item; })
66
- || new Set(recipients).size !== recipients.length) { throw new TypeError('Event identity and unique recipients required'); }
67
- const existing = entries.get(event.eventId);
68
- if (existing) {
69
- const saved = await load(existing.name);
70
- if (JSON.stringify(saved.event) !== JSON.stringify(event) || JSON.stringify(saved.recipients) !== JSON.stringify(recipients)) {
71
- throw new Error('Conflicting event identity');
72
- }
73
- return;
74
- }
75
- if (entries.size >= maxRecords) { throw new Error('Spool record capacity exceeded'); }
76
- const value = JSON.stringify({ event, recipients, remaining: recipients });
77
- const size = Buffer.byteLength(value);
78
- if (state.bytes + size > maxBytes) { throw new Error('Spool capacity exceeded'); }
79
- const name = filename(event.eventId);
80
- // Reserve against ambiguous fsync outcomes; reopen reconciles actual files.
81
- entries.set(event.eventId, { name, size }); state.bytes += size;
82
- try { await replace(directory, name, value); } catch (error) { Object.assign(state, { ready: false }); throw error; }
83
- });
84
- },
85
- ack(eventId, recipient) {
86
- return exclusive(async () => {
87
- current();
88
- const entry = entries.get(eventId);
89
- if (!entry) { return; }
90
- const saved = await load(entry.name);
91
- if (!saved.recipients.includes(recipient)) { throw new Error('Unknown recipient'); }
92
- const remaining = saved.remaining.filter((item) => { return item !== recipient; });
93
- if (remaining.length === saved.remaining.length) { return; }
41
+ if (state.ready) { return; }
94
42
  try {
95
- if (remaining.length === 0) {
96
- await unlink(path.join(directory, entry.name)); await syncDirectory(directory);
97
- entries.delete(eventId); state.bytes -= entry.size;
98
- } else {
99
- const value = JSON.stringify({ ...saved, remaining });
100
- await replace(directory, entry.name, value);
101
- const size = Buffer.byteLength(value); state.bytes += size - entry.size; entry.size = size;
102
- }
103
- } catch (error) { Object.assign(state, { ready: false }); throw error; }
104
- });
43
+ Object.assign(state, await database(directory));
44
+ capacity(state.db, maxBytes, maxRecords);
45
+ await spoolMigration(directory, state.db, { maxBytes, maxRecords, legacyMigrationMaxBytes });
46
+ refresh(); Object.assign(state, { ready:true });
47
+ } catch (error) { release(); throw error; }
48
+ }, false);
105
49
  },
50
+ append(event, recipients) { return single({ kind: 'append', event, recipients }); },
51
+ ack(eventId, recipient) { return single({ kind: 'ack', eventId, recipient }); },
106
52
  pending(limit = 100) {
107
- return exclusive(async () => {
108
- current();
53
+ return exclusive(() => {
109
54
  if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive pending limit required'); }
110
- const rows = [];
111
- for (const entry of Array.from(entries.values()).slice(0, limit)) {
112
- // Read sequentially to bound decoded records in memory.
113
- // eslint-disable-next-line no-await-in-loop
114
- const { event, remaining } = await load(entry.name);
115
- rows.push({ event, remaining });
116
- // Rotate the window so an offline recipient cannot starve later destinations.
117
- entries.delete(event.eventId); entries.set(event.eventId, entry);
118
- }
119
- return rows;
55
+ return commit(() => { return pending(state.db, limit); });
120
56
  });
121
57
  },
122
- status() { return { bytes: state.bytes, maxBytes, recordLimit: maxRecords, pending: entries.size, ready: state.ready }; }
58
+ close() {
59
+ return exclusive(() => {
60
+ try { if (state.db) { checkpoint(state.db); } } finally { release(); }
61
+ }, false);
62
+ },
63
+ status() { return { bytes: state.bytes, maxBytes, recordLimit: maxRecords, pending: state.records, ready: state.ready }; }
123
64
  };
124
65
  }
@@ -0,0 +1,41 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { deflateSync, inflateSync } from 'node:zlib';
3
+
4
+ export function digest(value) { return createHash('sha256').update(value).digest('hex'); }
5
+ export function revive(key, value) {
6
+ return value?.type === 'Buffer' && Array.isArray(value.data) ? Buffer.from(value.data) : value;
7
+ }
8
+ export function validate(event, recipients, remaining = recipients) {
9
+ if (typeof event?.eventId !== 'string' || !event.eventId || !Array.isArray(recipients) || !recipients.length
10
+ || recipients.some((item) => { return typeof item !== 'string' || !item; })
11
+ || new Set(recipients).size !== recipients.length || !Array.isArray(remaining) || !remaining.length
12
+ || new Set(remaining).size !== remaining.length || remaining.some((item) => { return !recipients.includes(item); })) {
13
+ throw new TypeError('Event identity and unique recipients required; corrupt spool record');
14
+ }
15
+ }
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,69 @@
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 existing = 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 (!existing) { initialize(db); }
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)'); }
@@ -0,0 +1,37 @@
1
+ const statements = [
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
+ function metadata(db) {
10
+ return db.prepare("SELECT type,name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' ORDER BY name LIMIT 6").all();
11
+ }
12
+ function validCounters(db) {
13
+ const rows = db.prepare('SELECT id,bytes,records,sequence FROM counters LIMIT 2').all();
14
+ const row = rows[0];
15
+ return rows.length === 1 && row.id === 1
16
+ && [row.bytes, row.records, row.sequence].every((value) => { return Number.isSafeInteger(value) && value >= 0; })
17
+ && row.sequence >= row.records && row.bytes >= row.records
18
+ && (row.records === 0) === (row.bytes === 0)
19
+ && (row.records > 0) === Boolean(db.prepare('SELECT 1 FROM events LIMIT 1').get());
20
+ }
21
+ /** Validate bounded metadata before changing existing data or journal settings. Never repair ambiguous storage. */
22
+ export function format(db) {
23
+ const version = db.pragma('user_version', { simple: true });
24
+ const schema = metadata(db);
25
+ if (version === 0 && schema.length === 0) { return false; }
26
+ if (version !== 1) { throw new Error('Unsupported spool format version or nonempty database'); }
27
+ const expected = statements.map((sql) => { return sql.replaceAll(/\s+/gu, ' '); }).sort();
28
+ const actual = schema.map((row) => { return row.sql.replaceAll(/\s+/gu, ' '); }).sort();
29
+ if (JSON.stringify(actual) !== JSON.stringify(expected) || !validCounters(db)) { throw new Error('Corrupt spool format or counters'); }
30
+ return true;
31
+ }
32
+ export function initialize(db) {
33
+ db.transaction(() => {
34
+ db.exec(statements.join(';'));
35
+ db.prepare('INSERT INTO counters VALUES (1,0,0,0)').run(); db.pragma('user_version=1');
36
+ })();
37
+ }
@@ -0,0 +1,66 @@
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
+ }
@@ -0,0 +1,19 @@
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
+ }
@@ -0,0 +1,50 @@
1
+ import { capacity, counters } from './spoolDatabase.js';
2
+ import { decoded, encoded } from './spoolCodec.js';
3
+
4
+ export function insert(db, value, maxBytes, maxRecords) {
5
+ const existing = db.prepare('SELECT fingerprint FROM events WHERE id=?').get(value.id);
6
+ if (existing) {
7
+ if (existing.fingerprint !== value.fingerprint) { throw new Error('Conflicting event identity'); }
8
+ return;
9
+ }
10
+ const totals = counters(db);
11
+ if (totals.records >= maxRecords) { throw new Error('Spool record capacity exceeded'); }
12
+ if (totals.bytes + value.bytes > maxBytes) { throw new Error('Spool capacity exceeded'); }
13
+ for (const descriptor of value.destinations ?? []) {
14
+ db.prepare('INSERT INTO destinations VALUES (?,?,1) ON CONFLICT(id) DO UPDATE SET refs=refs+1').run(descriptor.id, descriptor.json);
15
+ }
16
+ db.prepare('INSERT INTO events VALUES (@id,@fingerprint,@payload,@destinations,@recipients,@remaining,@bytes,@sequence)').run({
17
+ ...value, destinations: value.destinations ? JSON.stringify(value.destinations.map((item) => { return item.id; })) : null,
18
+ sequence: totals.sequence + 1
19
+ });
20
+ db.prepare('UPDATE counters SET bytes=bytes+?,records=records+1,sequence=sequence+1 WHERE id=1').run(value.bytes);
21
+ }
22
+ function remove(db, row) {
23
+ db.prepare('DELETE FROM events WHERE id=?').run(row.id);
24
+ db.prepare('UPDATE counters SET bytes=bytes-?,records=records-1 WHERE id=1').run(row.bytes);
25
+ for (const id of JSON.parse(row.destinations ?? '[]')) {
26
+ db.prepare('UPDATE destinations SET refs=refs-1 WHERE id=?').run(id);
27
+ db.prepare('DELETE FROM destinations WHERE id=? AND refs=0').run(id);
28
+ }
29
+ }
30
+ export function acknowledge(db, id, recipient) {
31
+ const row = db.prepare('SELECT * FROM events WHERE id=?').get(id);
32
+ if (!row) { return; }
33
+ if (!JSON.parse(row.recipients).includes(recipient)) { throw new Error('Unknown recipient'); }
34
+ const remaining = JSON.parse(row.remaining).filter((item) => { return item !== recipient; });
35
+ if (!remaining.length) { remove(db, row); return; }
36
+ const record = decoded(row, db);
37
+ const value = encoded(record.event, JSON.parse(row.recipients), remaining);
38
+ db.prepare('UPDATE events SET remaining=?,bytes=? WHERE id=?').run(value.remaining, value.bytes, id);
39
+ db.prepare('UPDATE counters SET bytes=bytes+? WHERE id=1').run(value.bytes - row.bytes);
40
+ }
41
+ export function pending(db, limit) {
42
+ const rows = db.prepare('SELECT * FROM events ORDER BY sequence LIMIT ?').all(limit);
43
+ let { sequence } = counters(db);
44
+ for (const row of rows) {
45
+ sequence += 1; db.prepare('UPDATE events SET sequence=? WHERE id=?').run(sequence, row.id);
46
+ }
47
+ db.prepare('UPDATE counters SET sequence=? WHERE id=1').run(sequence);
48
+ return rows.map((row) => { return decoded(row, db); });
49
+ }
50
+ export function admission(db, maxBytes, maxRecords) { return capacity(db, maxBytes, maxRecords); }