@yarkivaev/scada 2.6.1 → 2.6.3
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/deliveryOperations.js +121 -0
- package/src/application/runtime/deliveryPublications.js +31 -0
- package/src/application/runtime/deliveryQueue.js +51 -42
- package/src/application/runtime/deliverySessions.js +54 -16
- package/src/application/runtime/queuedDelivery.js +15 -3
- package/src/infrastructure/persistence/runtime/deliverySpool.js +12 -4
- package/src/infrastructure/persistence/runtime/spoolMutations.js +19 -0
package/README.md
CHANGED
|
@@ -742,3 +742,15 @@ Use `node --expose-gc scripts/measure-delivery-spool.mjs FIXTURE.json 120000` wi
|
|
|
742
742
|
|
|
743
743
|
|
|
744
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
|
+
The positive safe-integer `maxInFlight` option defaults to32. A drain initiates at most that many publications concurrently, in stored order per logical AMQP session. All concurrent writers await the same session opening; one mandatory return does not retire independent confirms. Receipt admission and serialized publication bytes are reserved before network publication, then the receipt is queued only after its individual mandatory confirmation. The retained publication bytes count toward `maxPendingBytes`, separately from receipt mutation bytes counted toward the group byte limit. 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. Caller write deadlines abort the actual AMQP writer and retire its session. A caller timeout alone does not release a publication slot or its prospective ACK reservation; late actual success still commits its receipt, and late callbacks from an aborted AMQP generation cannot ACK a retry. A custom factory that ignores both AbortSignal and stop remains fenced and bounded until actual settlement. Close fails after its bounded session wait and retains spool ownership if that work cannot quiesce; retry close after settlement. 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
|
@@ -0,0 +1,121 @@
|
|
|
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.reservedBytes ?? 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, retainedBytes = 0) {
|
|
81
|
+
positive(bytes, 'Mutation bytes', true);
|
|
82
|
+
positive(retainedBytes, 'Retained bytes', true);
|
|
83
|
+
if (state.bytes + bytes + retainedBytes > config.maxPendingBytes) { throw new Error('Delivery pending byte capacity exceeded'); }
|
|
84
|
+
if (bytes > config.maxBytes) { throw new Error('Delivery group byte capacity exceeded'); }
|
|
85
|
+
}
|
|
86
|
+
function prepare(build) {
|
|
87
|
+
reserve();
|
|
88
|
+
let value;
|
|
89
|
+
try {
|
|
90
|
+
value = build(checkBytes); checkBytes(value.bytes, value.retainedBytes);
|
|
91
|
+
} catch (error) { release(0); throw error; }
|
|
92
|
+
const reservedBytes = value.bytes + (value.retainedBytes ?? 0);
|
|
93
|
+
state.bytes += reservedBytes;
|
|
94
|
+
let settled = false;
|
|
95
|
+
return {
|
|
96
|
+
commit() {
|
|
97
|
+
if (settled) { return Promise.reject(new Error('Delivery reservation already settled')); }
|
|
98
|
+
settled = true; return enqueue({ kind: 'mutation', ...value, reservedBytes });
|
|
99
|
+
},
|
|
100
|
+
cancel() { if (!settled) { settled = true; release(reservedBytes); } }
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
prepare,
|
|
105
|
+
mutate(build) {
|
|
106
|
+
try { return prepare(build).commit(); } catch (error) { return Promise.reject(error); }
|
|
107
|
+
},
|
|
108
|
+
barrier(action) {
|
|
109
|
+
try { reserve(); return enqueue({ kind: 'barrier', action, bytes: 0 }); }
|
|
110
|
+
catch (error) { return Promise.reject(error); }
|
|
111
|
+
},
|
|
112
|
+
flush() { if (jobs.length) { schedule(0); } },
|
|
113
|
+
idle() {
|
|
114
|
+
if (!state.operations && !state.running) { return Promise.resolve(); }
|
|
115
|
+
schedule(0);
|
|
116
|
+
state.idle ??= new Promise((resolve) => { state.wake = resolve; });
|
|
117
|
+
return state.idle;
|
|
118
|
+
},
|
|
119
|
+
status() { return { operations: state.operations, bytes: state.bytes }; }
|
|
120
|
+
};
|
|
121
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** A slot and its prospective durable receipt stay reserved until the actual writer settles. */
|
|
2
|
+
/* eslint max-lines-per-function: ["error", 80], max-statements: ["error", 25] */
|
|
3
|
+
export default function deliveryPublications(commands, sessions, options) {
|
|
4
|
+
const limit = options.maxInFlight ?? 32;
|
|
5
|
+
if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive safe maxInFlight required'); }
|
|
6
|
+
const active = new Map();
|
|
7
|
+
function publish(record, id) {
|
|
8
|
+
const key = JSON.stringify([record.event.eventId, id]);
|
|
9
|
+
if (active.has(key) || active.size >= limit) { throw new Error('Delivery publication capacity exceeded'); }
|
|
10
|
+
const receipt = commands.prepare((checkBytes) => {
|
|
11
|
+
const operation = { kind: 'ack', eventId: record.event.eventId, recipient: id };
|
|
12
|
+
const bytes = Buffer.byteLength(JSON.stringify(operation));
|
|
13
|
+
const retainedBytes = Buffer.byteLength(JSON.stringify(record.event));
|
|
14
|
+
checkBytes(bytes, retainedBytes); return { operation, bytes, retainedBytes };
|
|
15
|
+
});
|
|
16
|
+
let write;
|
|
17
|
+
try {
|
|
18
|
+
const descriptor = record.event.destinations.find((item) => { return item.id === id; });
|
|
19
|
+
const event = record.event.observation;
|
|
20
|
+
write = sessions.write(descriptor, { ...event, options: { ...event.options, persistent: true, mandatory: true, messageId: event.eventId } });
|
|
21
|
+
} catch (error) { receipt.cancel(); throw error; }
|
|
22
|
+
const settled = write.settled.then(() => { return receipt.commit(); }, (error) => { receipt.cancel(); throw error; })
|
|
23
|
+
.finally(() => { active.delete(key); });
|
|
24
|
+
active.set(key, settled);
|
|
25
|
+
void settled.catch(() => {
|
|
26
|
+
// The caller reports failures; late rejection still releases only the actual reservation.
|
|
27
|
+
});
|
|
28
|
+
return write.result.then(() => { return settled; });
|
|
29
|
+
}
|
|
30
|
+
return { publish, limit };
|
|
31
|
+
}
|
|
@@ -1,80 +1,89 @@
|
|
|
1
1
|
import deliverySpool from '../../infrastructure/persistence/runtime/deliverySpool.js';
|
|
2
2
|
import deliverySessions from './deliverySessions.js';
|
|
3
|
+
import deliveryOperations from './deliveryOperations.js';
|
|
4
|
+
import deliveryPublications from './deliveryPublications.js';
|
|
3
5
|
|
|
4
|
-
function
|
|
5
|
-
|
|
6
|
+
function snapshot(operation, checkBytes) {
|
|
7
|
+
const json = JSON.stringify(operation); checkBytes(Buffer.byteLength(json));
|
|
8
|
+
const frozen = JSON.parse(json);
|
|
9
|
+
if (frozen.kind === 'append') { frozen.recipients = frozen.event.destinations.map((item) => { return item.id; }); }
|
|
10
|
+
return { operation: frozen, bytes: Buffer.byteLength(JSON.stringify(frozen)) };
|
|
6
11
|
}
|
|
7
|
-
/* eslint max-lines-per-function: ["error",
|
|
8
|
-
/** Node-owned queue:
|
|
12
|
+
/* eslint max-lines-per-function: ["error", 125], max-statements: ["error", 25] */
|
|
13
|
+
/** Node-owned queue: every point/receipt resolves only after its grouped FULL commit. */
|
|
9
14
|
export default function deliveryQueue(directory, options) {
|
|
10
15
|
const spool = deliverySpool(directory, options);
|
|
16
|
+
const commands = deliveryOperations((operations) => { return spool.mutateMany(operations); }, options);
|
|
11
17
|
const sessions = deliverySessions(options.factory, options.writeTimeoutMs);
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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) {
|
|
24
|
-
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); });
|
|
28
|
-
}
|
|
29
|
-
|
|
18
|
+
const batchSize = options.batchSize ?? 100;
|
|
19
|
+
if (!Number.isSafeInteger(batchSize) || batchSize <= 0) { throw new TypeError('Positive safe batchSize required'); }
|
|
20
|
+
const publications = deliveryPublications(commands, sessions, options);
|
|
21
|
+
const receiptWindow = Math.min(publications.limit, options.maxOperations ?? 128);
|
|
22
|
+
const state = { draining: false, closed: false, full: false };
|
|
30
23
|
async function drain() {
|
|
31
|
-
if (state.draining || state.closed) { return { delivered: 0, failed: 0 }; }
|
|
32
24
|
state.draining = true;
|
|
33
25
|
const result = { delivered: 0, failed: 0 };
|
|
26
|
+
const receipts = new Set();
|
|
27
|
+
function failure(error) {
|
|
28
|
+
result.failed += 1;
|
|
29
|
+
try { options.onError?.(error); } catch {
|
|
30
|
+
// Observers cannot prevent independent recipient progress or release.
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
async function flush() { commands.flush(); await Promise.all(receipts); }
|
|
34
|
+
function receive(row, id) {
|
|
35
|
+
const receipt = Promise.resolve().then(() => { return publications.publish(row, id); })
|
|
36
|
+
.then(() => { result.delivered += 1; }, failure).finally(() => { receipts.delete(receipt); });
|
|
37
|
+
receipts.add(receipt);
|
|
38
|
+
}
|
|
39
|
+
async function advance(row, id) {
|
|
40
|
+
if (!state.closed) { receive(row, id); }
|
|
41
|
+
if (receipts.size >= receiptWindow) { await Promise.race(receipts); }
|
|
42
|
+
}
|
|
34
43
|
try {
|
|
35
|
-
const rows = await
|
|
44
|
+
const rows = await commands.barrier(() => { return spool.pending(batchSize); });
|
|
45
|
+
Object.assign(state, { full: rows.length === batchSize });
|
|
36
46
|
for (const row of rows) {
|
|
37
47
|
for (const id of row.remaining) {
|
|
38
|
-
//
|
|
39
|
-
// eslint-disable-next-line no-await-in-loop
|
|
40
|
-
|
|
41
|
-
result.failed += 1; options.onError?.(error);
|
|
42
|
-
}
|
|
48
|
+
// Actual timed-out publications retain their global slots across page/caller completion.
|
|
49
|
+
// eslint-disable-next-line no-await-in-loop
|
|
50
|
+
await advance(row, id);
|
|
43
51
|
}
|
|
44
52
|
}
|
|
45
53
|
return result;
|
|
46
|
-
} finally { Object.assign(state, { draining: false }); }
|
|
54
|
+
} finally { try { await flush(); } finally { Object.assign(state, { draining: false }); } }
|
|
47
55
|
}
|
|
48
|
-
|
|
49
56
|
return {
|
|
50
57
|
open() {
|
|
51
58
|
if (state.closed) { return Promise.reject(new Error('Delivery queue closed')); }
|
|
52
|
-
return
|
|
59
|
+
return commands.barrier(() => { return spool.open(); });
|
|
53
60
|
},
|
|
54
61
|
accept(event, destinations) {
|
|
55
62
|
if (state.closed) { return Promise.reject(new Error('Delivery queue closed')); }
|
|
56
63
|
if (!destinations?.length || destinations.some((item) => { return item.type !== 'amqp'; })) {
|
|
57
64
|
return Promise.reject(new TypeError('Queued delivery requires confirmed AMQP destinations'));
|
|
58
65
|
}
|
|
59
|
-
|
|
60
|
-
const envelope = JSON.parse(JSON.stringify({ eventId: event.eventId, observation: event, destinations }));
|
|
61
|
-
return serialized(() => { return spool.append(envelope, envelope.destinations.map((item) => { return item.id; })); });
|
|
66
|
+
return commands.mutate((checkBytes) => { return snapshot({ kind: 'append', event: { eventId: event.eventId, observation: event, destinations } }, checkBytes); });
|
|
62
67
|
},
|
|
63
68
|
drain() {
|
|
64
|
-
if (state.draining || state.closed) { return Promise.resolve({ delivered:0, failed:0 }); }
|
|
69
|
+
if (state.draining || state.closed) { return Promise.resolve({ delivered: 0, failed: 0 }); }
|
|
65
70
|
const result = drain(); state.activeDrain = result; return result;
|
|
66
71
|
},
|
|
67
72
|
close() {
|
|
68
|
-
state.closed = true;
|
|
73
|
+
state.closed = true; commands.flush();
|
|
69
74
|
state.closing ??= (async () => {
|
|
70
75
|
await state.activeDrain?.catch(() => {
|
|
71
76
|
// Drain caller receives the original error.
|
|
72
|
-
});
|
|
73
|
-
|
|
74
|
-
|
|
77
|
+
});
|
|
78
|
+
await sessions.close();
|
|
79
|
+
await commands.idle();
|
|
80
|
+
await spool.close();
|
|
81
|
+
})().catch((error) => { state.closing = null; throw error; });
|
|
75
82
|
return state.closing;
|
|
76
83
|
},
|
|
77
|
-
status() {
|
|
84
|
+
status() {
|
|
85
|
+
const usage = commands.status();
|
|
86
|
+
return { ...spool.status(), queuedOperations: usage.operations, queuedBytes: usage.bytes, drainFull: state.full };
|
|
87
|
+
}
|
|
78
88
|
};
|
|
79
|
-
|
|
80
89
|
}
|
|
@@ -1,28 +1,66 @@
|
|
|
1
1
|
import deadline from './deadline.js';
|
|
2
2
|
|
|
3
|
-
/**
|
|
3
|
+
/** Shared opening and actual settlement outlive caller deadlines; stop fences failed sessions. */
|
|
4
|
+
/* eslint max-lines-per-function: ["error", 100], max-statements: ["error", 25] */
|
|
4
5
|
export default function deliverySessions(factory, timeoutMs = 10000) {
|
|
5
6
|
const sessions = new Map();
|
|
7
|
+
const state = { closed: false };
|
|
8
|
+
function retire(key, entry) {
|
|
9
|
+
entry.closing ??= (async () => {
|
|
10
|
+
if (!entry.opened) { await entry.sink.stop?.(); }
|
|
11
|
+
await entry.opening.catch(() => {
|
|
12
|
+
// A failed opening must still be stopped; a late successful one may own new resources.
|
|
13
|
+
});
|
|
14
|
+
await entry.sink.stop?.();
|
|
15
|
+
await Promise.allSettled(entry.pending);
|
|
16
|
+
if (sessions.get(key) === entry) { sessions.delete(key); }
|
|
17
|
+
})();
|
|
18
|
+
return entry.closing;
|
|
19
|
+
}
|
|
20
|
+
function session(key, descriptor) {
|
|
21
|
+
let entry = sessions.get(key);
|
|
22
|
+
if (entry?.closing) { throw new Error('Delivery session is closing'); }
|
|
23
|
+
if (!entry) {
|
|
24
|
+
if (sessions.size >= 64) { throw new Error('Delivery session capacity exceeded'); }
|
|
25
|
+
const sink = factory(descriptor);
|
|
26
|
+
entry = { sink, pending: new Set(), opened: false };
|
|
27
|
+
entry.opening = Promise.resolve().then(() => { return sink.start?.(); }).finally(() => { entry.opened = true; });
|
|
28
|
+
sessions.set(key, entry);
|
|
29
|
+
void entry.opening.catch(() => { return retire(key, entry); }).catch(() => {
|
|
30
|
+
// Failed shutdown keeps the failed opening fenced.
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
return entry;
|
|
34
|
+
}
|
|
6
35
|
return {
|
|
7
|
-
|
|
36
|
+
write(descriptor, event) {
|
|
37
|
+
if (state.closed) { throw new Error('Delivery sessions closed'); }
|
|
8
38
|
const key = JSON.stringify(descriptor);
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
39
|
+
const entry = session(key, descriptor);
|
|
40
|
+
const controller = new AbortController();
|
|
41
|
+
const settled = entry.opening.then(() => {
|
|
42
|
+
if (controller.signal.aborted || entry.closing) { throw controller.signal.reason || new Error('Delivery session is closing'); }
|
|
43
|
+
return entry.sink.write([event], { signal: controller.signal });
|
|
44
|
+
});
|
|
45
|
+
entry.pending.add(settled);
|
|
46
|
+
let completed = false;
|
|
47
|
+
void settled.finally(() => { completed = true; entry.pending.delete(settled); }).catch(() => {
|
|
48
|
+
// A publication rejection is independent of other confirms on this session.
|
|
49
|
+
});
|
|
50
|
+
const result = deadline(() => { return settled; }, timeoutMs).catch((error) => {
|
|
51
|
+
if (!completed) {
|
|
52
|
+
controller.abort(error);
|
|
53
|
+
void retire(key, entry).catch(() => {
|
|
54
|
+
// Actual work and ownership remain fenced if stop cannot complete.
|
|
17
55
|
});
|
|
18
|
-
throw error;
|
|
19
56
|
}
|
|
20
|
-
|
|
21
|
-
|
|
57
|
+
throw error;
|
|
58
|
+
});
|
|
59
|
+
return { result, settled };
|
|
22
60
|
},
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
61
|
+
close() {
|
|
62
|
+
state.closed = true;
|
|
63
|
+
return deadline(() => { return Promise.all(Array.from(sessions, ([key, entry]) => { return retire(key, entry); })); }, timeoutMs);
|
|
26
64
|
}
|
|
27
65
|
};
|
|
28
66
|
}
|
|
@@ -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,
|
|
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,6 +1,6 @@
|
|
|
1
1
|
import { capacity, checkpoint, counters, database } from './spoolDatabase.js';
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
2
|
+
import { pending } from './spoolRecords.js';
|
|
3
|
+
import spoolMutations from './spoolMutations.js';
|
|
4
4
|
import spoolMigration from './spoolMigration.js';
|
|
5
5
|
|
|
6
6
|
/* eslint max-lines-per-function: ["error", 100], max-statements: ["error", 25] */
|
|
@@ -27,7 +27,15 @@ export default function deliverySpool(directory, { maxBytes, maxRecords = 100000
|
|
|
27
27
|
try { const result = state.db.transaction(action)(); refresh(); return result; }
|
|
28
28
|
catch (error) { if (error.code?.startsWith('SQLITE_')) { release(); } throw error; }
|
|
29
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; }
|
|
36
|
+
}
|
|
30
37
|
return {
|
|
38
|
+
mutateMany,
|
|
31
39
|
open() {
|
|
32
40
|
return exclusive(async () => {
|
|
33
41
|
if (state.ready) { return; }
|
|
@@ -39,8 +47,8 @@ export default function deliverySpool(directory, { maxBytes, maxRecords = 100000
|
|
|
39
47
|
} catch (error) { release(); throw error; }
|
|
40
48
|
}, false);
|
|
41
49
|
},
|
|
42
|
-
append(event, recipients) { return
|
|
43
|
-
ack(eventId, recipient) { return
|
|
50
|
+
append(event, recipients) { return single({ kind: 'append', event, recipients }); },
|
|
51
|
+
ack(eventId, recipient) { return single({ kind: 'ack', eventId, recipient }); },
|
|
44
52
|
pending(limit = 100) {
|
|
45
53
|
return exclusive(() => {
|
|
46
54
|
if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive pending limit required'); }
|
|
@@ -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
|
+
}
|