@yarkivaev/scada 2.6.0 → 2.6.1
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 +12 -0
- package/package.json +1 -1
- package/src/application/runtime/deliveryQueue.js +39 -21
- package/src/infrastructure/persistence/runtime/deliverySpool.js +39 -106
- package/src/infrastructure/persistence/runtime/spoolCodec.js +41 -0
- package/src/infrastructure/persistence/runtime/spoolDatabase.js +69 -0
- package/src/infrastructure/persistence/runtime/spoolFormat.js +37 -0
- package/src/infrastructure/persistence/runtime/spoolMigration.js +66 -0
- package/src/infrastructure/persistence/runtime/spoolRecords.js +50 -0
package/README.md
CHANGED
|
@@ -730,3 +730,15 @@ 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.
|
package/package.json
CHANGED
|
@@ -4,7 +4,7 @@ import deliverySessions from './deliverySessions.js';
|
|
|
4
4
|
function confirmed(event) {
|
|
5
5
|
return { ...event, options: { ...event.options, persistent: true, mandatory: true, messageId: event.eventId } };
|
|
6
6
|
}
|
|
7
|
-
/* eslint max-lines-per-function: ["error",
|
|
7
|
+
/* eslint max-lines-per-function: ["error", 90], max-statements: ["error", 20] */
|
|
8
8
|
/** Node-owned queue: removing a source does not remove its destination descriptors or receipts. */
|
|
9
9
|
export default function deliveryQueue(directory, options) {
|
|
10
10
|
const spool = deliverySpool(directory, options);
|
|
@@ -27,8 +27,30 @@ export default function deliveryQueue(directory, options) {
|
|
|
27
27
|
await serialized(() => { return spool.ack(record.event.eventId, id); });
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
async function drain() {
|
|
31
|
+
if (state.draining || state.closed) { return { delivered: 0, failed: 0 }; }
|
|
32
|
+
state.draining = true;
|
|
33
|
+
const result = { delivered: 0, failed: 0 };
|
|
34
|
+
try {
|
|
35
|
+
const rows = await serialized(() => { return spool.pending(options.batchSize ?? 100); });
|
|
36
|
+
for (const row of rows) {
|
|
37
|
+
for (const id of row.remaining) {
|
|
38
|
+
// Recipients fail independently; continue draining other destinations.
|
|
39
|
+
// eslint-disable-next-line no-await-in-loop, max-depth
|
|
40
|
+
try { await send(row, id); result.delivered += 1; } catch (error) {
|
|
41
|
+
result.failed += 1; options.onError?.(error);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return result;
|
|
46
|
+
} finally { Object.assign(state, { draining: false }); }
|
|
47
|
+
}
|
|
48
|
+
|
|
30
49
|
return {
|
|
31
|
-
open() {
|
|
50
|
+
open() {
|
|
51
|
+
if (state.closed) { return Promise.reject(new Error('Delivery queue closed')); }
|
|
52
|
+
return serialized(() => { return spool.open(); });
|
|
53
|
+
},
|
|
32
54
|
accept(event, destinations) {
|
|
33
55
|
if (state.closed) { return Promise.reject(new Error('Delivery queue closed')); }
|
|
34
56
|
if (!destinations?.length || destinations.some((item) => { return item.type !== 'amqp'; })) {
|
|
@@ -36,27 +58,23 @@ export default function deliveryQueue(directory, options) {
|
|
|
36
58
|
}
|
|
37
59
|
// Snapshot before asynchronous I/O; callers may reuse buffers/objects.
|
|
38
60
|
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; })); });
|
|
61
|
+
return serialized(() => { return spool.append(envelope, envelope.destinations.map((item) => { return item.id; })); });
|
|
40
62
|
},
|
|
41
|
-
|
|
42
|
-
if (state.draining || state.closed) { return { delivered:
|
|
43
|
-
state.
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
return result;
|
|
57
|
-
} finally { Object.assign(state, { draining: false }); }
|
|
63
|
+
drain() {
|
|
64
|
+
if (state.draining || state.closed) { return Promise.resolve({ delivered:0, failed:0 }); }
|
|
65
|
+
const result = drain(); state.activeDrain = result; return result;
|
|
66
|
+
},
|
|
67
|
+
close() {
|
|
68
|
+
state.closed = true;
|
|
69
|
+
state.closing ??= (async () => {
|
|
70
|
+
await state.activeDrain?.catch(() => {
|
|
71
|
+
// Drain caller receives the original error.
|
|
72
|
+
}); await chain;
|
|
73
|
+
try { await sessions.close(); } finally { await spool.close(); }
|
|
74
|
+
})();
|
|
75
|
+
return state.closing;
|
|
58
76
|
},
|
|
59
|
-
close() { state.closed = true; return sessions.close(); },
|
|
60
77
|
status() { return spool.status(); }
|
|
61
78
|
};
|
|
79
|
+
|
|
62
80
|
}
|
|
@@ -1,124 +1,57 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
1
|
+
import { capacity, checkpoint, counters, database } from './spoolDatabase.js';
|
|
2
|
+
import { acknowledge, insert, pending } from './spoolRecords.js';
|
|
3
|
+
import { encoded } from './spoolCodec.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
|
|
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
|
-
|
|
43
|
-
const state = {
|
|
44
|
-
|
|
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:
|
|
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; }
|
|
48
29
|
}
|
|
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
30
|
return {
|
|
52
31
|
open() {
|
|
53
32
|
return exclusive(async () => {
|
|
54
|
-
|
|
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; }
|
|
33
|
+
if (state.ready) { return; }
|
|
94
34
|
try {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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
|
-
});
|
|
35
|
+
Object.assign(state, await database(directory));
|
|
36
|
+
capacity(state.db, maxBytes, maxRecords);
|
|
37
|
+
await spoolMigration(directory, state.db, { maxBytes, maxRecords, legacyMigrationMaxBytes });
|
|
38
|
+
refresh(); Object.assign(state, { ready:true });
|
|
39
|
+
} catch (error) { release(); throw error; }
|
|
40
|
+
}, false);
|
|
105
41
|
},
|
|
42
|
+
append(event, recipients) { return exclusive(() => { return commit(() => { insert(state.db, encoded(event, recipients), maxBytes, maxRecords); }); }); },
|
|
43
|
+
ack(eventId, recipient) { return exclusive(() => { return commit(() => { acknowledge(state.db, eventId, recipient); }); }); },
|
|
106
44
|
pending(limit = 100) {
|
|
107
|
-
return exclusive(
|
|
108
|
-
current();
|
|
45
|
+
return exclusive(() => {
|
|
109
46
|
if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive pending limit required'); }
|
|
110
|
-
|
|
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;
|
|
47
|
+
return commit(() => { return pending(state.db, limit); });
|
|
120
48
|
});
|
|
121
49
|
},
|
|
122
|
-
|
|
50
|
+
close() {
|
|
51
|
+
return exclusive(() => {
|
|
52
|
+
try { if (state.db) { checkpoint(state.db); } } finally { release(); }
|
|
53
|
+
}, false);
|
|
54
|
+
},
|
|
55
|
+
status() { return { bytes: state.bytes, maxBytes, recordLimit: maxRecords, pending: state.records, ready: state.ready }; }
|
|
123
56
|
};
|
|
124
57
|
}
|
|
@@ -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,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); }
|