@yarkivaev/scada 2.6.4 → 2.6.5
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 +4 -4
- package/package.json +1 -1
- package/src/application/runtime/deliveryQueue.js +13 -3
- package/src/application/runtime/deliverySessions.js +21 -9
- package/src/application/runtime/queuedDelivery.js +1 -1
- package/src/infrastructure/persistence/runtime/deliverySpool.js +7 -0
- package/src/infrastructure/persistence/runtime/spoolDatabase.js +3 -1
- package/src/infrastructure/persistence/runtime/spoolRecords.js +3 -0
- package/src/infrastructure/persistence/runtime/spoolReplay.js +82 -0
package/README.md
CHANGED
|
@@ -732,9 +732,9 @@ Spooled destination descriptors retain secret references. Draining a recovered q
|
|
|
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
733
|
|
|
734
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
|
|
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 validates canonical counters and rebuilds a disposable disk-backed recipient replay index from event metadata; it does not decode every observation or build an in-memory backlog. Recovery therefore includes linear metadata IO and must be qualified at the configured capacity. Replay interleaves bounded indexed pages across immutable destination descriptors, so a large offline-only prefix cannot hide a healthy destination. The reserved private `replay-index.sqlite` and its sidecars are disposable: every open rebuilds them under exclusive ownership, including after corruption or a rollback to an older runtime. They never provide acceptance or acknowledgement evidence; canonical format version1 remains unchanged.
|
|
736
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.
|
|
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. Canonical and replay page caches are each 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
738
|
|
|
739
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
740
|
|
|
@@ -751,9 +751,9 @@ Use `node --expose-gc scripts/measure-delivery-spool.mjs FIXTURE.json 120000` wi
|
|
|
751
751
|
|
|
752
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
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.
|
|
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. The64-entry session pool reuses least-recently-used fully settled idle sessions, including after descriptor or credential-reference rotation; active or reserved sessions are never evicted. 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
755
|
|
|
756
|
-
Healthy full drain pages with durable progress continue on subsequent event-loop turns; after four pages the scheduler pauses 25 ms.
|
|
756
|
+
Healthy full drain pages with durable progress continue on subsequent event-loop turns; after four pages the scheduler pauses 25 ms. Pages with healthy durable progress continue even if a different recipient failed. A failed immutable destination descriptor has a10s monotonic retry cooldown (`failureCooldownMs`, nonnegative safe integer, default10000; zero disables), tracked in a bounded128-entry map; other destinations remain eligible. Empty or zero-progress pages back off1s. 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.
|
|
757
757
|
|
|
758
758
|
### Bounded native history commits
|
|
759
759
|
|
package/package.json
CHANGED
|
@@ -19,6 +19,10 @@ export default function deliveryQueue(directory, options) {
|
|
|
19
19
|
if (!Number.isSafeInteger(batchSize) || batchSize <= 0) { throw new TypeError('Positive safe batchSize required'); }
|
|
20
20
|
const publications = deliveryPublications(commands, sessions, options);
|
|
21
21
|
const receiptWindow = Math.min(publications.limit, options.maxOperations ?? 128);
|
|
22
|
+
const clock = options.clock ?? (() => { return performance.now(); });
|
|
23
|
+
const cooldown = options.failureCooldownMs ?? 10000;
|
|
24
|
+
if (!Number.isSafeInteger(cooldown) || cooldown < 0) { throw new TypeError('Nonnegative safe failureCooldownMs required'); }
|
|
25
|
+
const blocked = new Map();
|
|
22
26
|
const state = { draining: false, closed: false, full: false };
|
|
23
27
|
async function drain() {
|
|
24
28
|
state.draining = true;
|
|
@@ -32,16 +36,22 @@ export default function deliveryQueue(directory, options) {
|
|
|
32
36
|
}
|
|
33
37
|
async function flush() { commands.flush(); await Promise.all(receipts); }
|
|
34
38
|
function receive(row, id) {
|
|
39
|
+
const target = row.targets[id];
|
|
35
40
|
const receipt = Promise.resolve().then(() => { return publications.publish(row, id); })
|
|
36
|
-
.then(() => { result.delivered += 1;
|
|
41
|
+
.then(() => { result.delivered += 1; blocked.delete(target); }, error => {
|
|
42
|
+
blocked.delete(target); blocked.set(target, clock() + cooldown);
|
|
43
|
+
if (blocked.size > 128) { blocked.delete(blocked.keys().next().value); }
|
|
44
|
+
failure(error);
|
|
45
|
+
}).finally(() => { receipts.delete(receipt); });
|
|
37
46
|
receipts.add(receipt);
|
|
38
47
|
}
|
|
39
48
|
async function advance(row, id) {
|
|
40
|
-
if (!state.closed) { receive(row, id); }
|
|
49
|
+
if (!state.closed && (blocked.get(row.targets[id]) ?? -Infinity) <= clock()) { receive(row, id); }
|
|
41
50
|
if (receipts.size >= receiptWindow) { await Promise.race(receipts); }
|
|
42
51
|
}
|
|
43
52
|
try {
|
|
44
|
-
const
|
|
53
|
+
for (const [target, until] of blocked) { if (until <= clock()) { blocked.delete(target); } }
|
|
54
|
+
const rows = await commands.barrier(() => { return spool.pendingFair(batchSize, blocked.keys()); });
|
|
45
55
|
Object.assign(state, { full: rows.length === batchSize });
|
|
46
56
|
for (const row of rows) {
|
|
47
57
|
for (const id of row.remaining) {
|
|
@@ -17,40 +17,52 @@ export default function deliverySessions(factory, timeoutMs = 10000) {
|
|
|
17
17
|
})();
|
|
18
18
|
return entry.closing;
|
|
19
19
|
}
|
|
20
|
-
function session(key, descriptor) {
|
|
20
|
+
async function session(key, descriptor, signal) {
|
|
21
|
+
while (!sessions.has(key) && sessions.size >= 64) {
|
|
22
|
+
const idle = [...sessions].find(([, item]) => { return item.opened && !item.closing && item.reserved === 0 && item.pending.size === 0; });
|
|
23
|
+
if (!idle) { throw new Error('Delivery session capacity exceeded'); }
|
|
24
|
+
// Evict only actually settled sessions; never release active publication reservations.
|
|
25
|
+
// eslint-disable-next-line no-await-in-loop
|
|
26
|
+
await retire(...idle);
|
|
27
|
+
}
|
|
28
|
+
if (state.closed || signal.aborted) { throw signal.reason || new Error('Delivery sessions closed'); }
|
|
21
29
|
let entry = sessions.get(key);
|
|
22
30
|
if (entry?.closing) { throw new Error('Delivery session is closing'); }
|
|
23
31
|
if (!entry) {
|
|
24
32
|
if (sessions.size >= 64) { throw new Error('Delivery session capacity exceeded'); }
|
|
25
33
|
const sink = factory(descriptor);
|
|
26
|
-
entry = { sink, pending: new Set(), opened: false };
|
|
34
|
+
entry = { sink, pending: new Set(), opened: false, reserved: 0 };
|
|
27
35
|
entry.opening = Promise.resolve().then(() => { return sink.start?.(); }).finally(() => { entry.opened = true; });
|
|
28
36
|
sessions.set(key, entry);
|
|
29
37
|
void entry.opening.catch(() => { return retire(key, entry); }).catch(() => {
|
|
30
38
|
// Failed shutdown keeps the failed opening fenced.
|
|
31
39
|
});
|
|
32
40
|
}
|
|
41
|
+
entry.reserved += 1;
|
|
42
|
+
sessions.delete(key); sessions.set(key, entry);
|
|
33
43
|
return entry;
|
|
34
44
|
}
|
|
35
45
|
return {
|
|
36
46
|
write(descriptor, event) {
|
|
37
47
|
if (state.closed) { throw new Error('Delivery sessions closed'); }
|
|
38
48
|
const key = JSON.stringify(descriptor);
|
|
39
|
-
const entry = session(key, descriptor);
|
|
40
49
|
const controller = new AbortController();
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
50
|
+
let entry;
|
|
51
|
+
const settled = session(key, descriptor, controller.signal).then(current => {
|
|
52
|
+
entry = current; entry.pending.add(settled); entry.reserved -= 1;
|
|
53
|
+
return entry.opening.then(() => {
|
|
54
|
+
if (controller.signal.aborted || entry.closing) { throw controller.signal.reason || new Error('Delivery session is closing'); }
|
|
55
|
+
return entry.sink.write([event], { signal: controller.signal });
|
|
56
|
+
});
|
|
44
57
|
});
|
|
45
|
-
entry.pending.add(settled);
|
|
46
58
|
let completed = false;
|
|
47
|
-
void settled.finally(() => { completed = true; entry
|
|
59
|
+
void settled.finally(() => { completed = true; entry?.pending.delete(settled); }).catch(() => {
|
|
48
60
|
// A publication rejection is independent of other confirms on this session.
|
|
49
61
|
});
|
|
50
62
|
const result = deadline(() => { return settled; }, timeoutMs).catch((error) => {
|
|
51
63
|
if (!completed) {
|
|
52
64
|
controller.abort(error);
|
|
53
|
-
void retire(key, entry).catch(() => {
|
|
65
|
+
void (entry ? retire(key, entry) : Promise.resolve()).catch(() => {
|
|
54
66
|
// Actual work and ownership remain fenced if stop cannot complete.
|
|
55
67
|
});
|
|
56
68
|
}
|
|
@@ -12,7 +12,7 @@ export default function queuedDelivery(env, secrets, supplied) {
|
|
|
12
12
|
}) : undefined);
|
|
13
13
|
function nextDelay(result) {
|
|
14
14
|
const status = queue.status?.();
|
|
15
|
-
if (result?.
|
|
15
|
+
if (result?.delivered > 0 && status?.ready !== false && status?.drainFull && status.pending > 0) {
|
|
16
16
|
burst += 1;
|
|
17
17
|
const delay = burst < 4 ? 0 : 25;
|
|
18
18
|
if (burst === 4) { burst = 0; }
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { capacity, checkpoint, counters, database } from './spoolDatabase.js';
|
|
2
2
|
import { pending } from './spoolRecords.js';
|
|
3
|
+
import { pendingFair } from './spoolReplay.js';
|
|
3
4
|
import spoolMutations from './spoolMutations.js';
|
|
4
5
|
import spoolMigration from './spoolMigration.js';
|
|
5
6
|
|
|
@@ -55,6 +56,12 @@ export default function deliverySpool(directory, { maxBytes, maxRecords = 100000
|
|
|
55
56
|
return commit(() => { return pending(state.db, limit); });
|
|
56
57
|
});
|
|
57
58
|
},
|
|
59
|
+
pendingFair(limit = 100, blocked = []) {
|
|
60
|
+
return exclusive(() => {
|
|
61
|
+
if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive pending limit required'); }
|
|
62
|
+
return commit(() => { return pendingFair(state.db, limit, blocked); });
|
|
63
|
+
});
|
|
64
|
+
},
|
|
58
65
|
close() {
|
|
59
66
|
return exclusive(() => {
|
|
60
67
|
try { if (state.db) { checkpoint(state.db); } } finally { release(); }
|
|
@@ -3,13 +3,14 @@ import path from 'node:path';
|
|
|
3
3
|
import { lstat, mkdir, open } from 'node:fs/promises';
|
|
4
4
|
import { constants } from 'node:fs';
|
|
5
5
|
import { format, initialize } from './spoolFormat.js';
|
|
6
|
+
import { replayFiles, replayIndex } from './spoolReplay.js';
|
|
6
7
|
|
|
7
8
|
// POSIX closes release this process's advisory locks for an inode, even from unrelated descriptors.
|
|
8
9
|
// Reserve directory identity before opening ANY owner descriptor, including rejected contenders.
|
|
9
10
|
const registry = Symbol.for('@yarkivaev/scada/delivery-spool-owners');
|
|
10
11
|
globalThis[registry] ??= new Set();
|
|
11
12
|
const owners = globalThis[registry];
|
|
12
|
-
const files = ['owner.sqlite', 'delivery.sqlite'].flatMap((name) => { return [name, `${name}-journal`, `${name}-wal`, `${name}-shm`]; });
|
|
13
|
+
const files = [...['owner.sqlite', 'delivery.sqlite'].flatMap((name) => { return [name, `${name}-journal`, `${name}-wal`, `${name}-shm`]; }), ...replayFiles];
|
|
13
14
|
export async function regular(file) {
|
|
14
15
|
try {
|
|
15
16
|
const info = await lstat(file);
|
|
@@ -60,6 +61,7 @@ export async function database(directory) {
|
|
|
60
61
|
db.pragma('cache_size = -2048'); db.pragma('wal_autocheckpoint = 256');
|
|
61
62
|
db.pragma('journal_size_limit = 1048576'); db.pragma('secure_delete = FAST');
|
|
62
63
|
if (!existing) { initialize(db); }
|
|
64
|
+
await replayIndex(db, directory);
|
|
63
65
|
return { db, owner: { close() { try { owner.close(); } finally { owners.delete(key); } } } };
|
|
64
66
|
} catch (error) {
|
|
65
67
|
try { db?.close(); } finally { try { owner?.close(); } finally { owners.delete(key); } }
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { capacity, counters } from './spoolDatabase.js';
|
|
2
2
|
import { decoded, encoded } from './spoolCodec.js';
|
|
3
|
+
import { indexAck, indexInsert } from './spoolReplay.js';
|
|
3
4
|
|
|
4
5
|
export function insert(db, value, maxBytes, maxRecords) {
|
|
5
6
|
const existing = db.prepare('SELECT fingerprint FROM events WHERE id=?').get(value.id);
|
|
@@ -17,6 +18,7 @@ export function insert(db, value, maxBytes, maxRecords) {
|
|
|
17
18
|
...value, destinations: value.destinations ? JSON.stringify(value.destinations.map((item) => { return item.id; })) : null,
|
|
18
19
|
sequence: totals.sequence + 1
|
|
19
20
|
});
|
|
21
|
+
indexInsert(db, value, totals.sequence + 1);
|
|
20
22
|
db.prepare('UPDATE counters SET bytes=bytes+?,records=records+1,sequence=sequence+1 WHERE id=1').run(value.bytes);
|
|
21
23
|
}
|
|
22
24
|
function remove(db, row) {
|
|
@@ -31,6 +33,7 @@ export function acknowledge(db, id, recipient) {
|
|
|
31
33
|
const row = db.prepare('SELECT * FROM events WHERE id=?').get(id);
|
|
32
34
|
if (!row) { return; }
|
|
33
35
|
if (!JSON.parse(row.recipients).includes(recipient)) { throw new Error('Unknown recipient'); }
|
|
36
|
+
indexAck(db, id, recipient);
|
|
34
37
|
const remaining = JSON.parse(row.remaining).filter((item) => { return item !== recipient; });
|
|
35
38
|
if (!remaining.length) { remove(db, row); return; }
|
|
36
39
|
const record = decoded(row, db);
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { open, unlink } from 'node:fs/promises';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import { decoded } from './spoolCodec.js';
|
|
5
|
+
|
|
6
|
+
export const replayFiles = ['replay-index.sqlite', 'replay-index.sqlite-journal', 'replay-index.sqlite-wal', 'replay-index.sqlite-shm'];
|
|
7
|
+
/** Disposable routing index. Every open rebuilds from canonical FULL-committed event metadata. */
|
|
8
|
+
export async function replayIndex(db, directory) {
|
|
9
|
+
for (const name of replayFiles) {
|
|
10
|
+
// Caller holds the directory owner and has rejected aliases before any mutation.
|
|
11
|
+
// eslint-disable-next-line no-await-in-loop
|
|
12
|
+
await unlink(path.join(directory, name)).catch(error => { if (error.code !== 'ENOENT') { throw error; } });
|
|
13
|
+
}
|
|
14
|
+
const file = path.join(directory, replayFiles[0]);
|
|
15
|
+
const handle = await open(file, constants.O_RDWR + constants.O_CREAT + constants.O_EXCL + constants.O_NOFOLLOW, 0o600);
|
|
16
|
+
await handle.close();
|
|
17
|
+
db.prepare('ATTACH DATABASE ? AS replay').run(file);
|
|
18
|
+
db.exec(`PRAGMA replay.journal_mode=MEMORY; PRAGMA replay.synchronous=OFF; PRAGMA replay.cache_size=-2048;
|
|
19
|
+
CREATE TABLE replay.targets (id TEXT PRIMARY KEY, sequence INTEGER NOT NULL);
|
|
20
|
+
CREATE INDEX replay.target_sequence ON targets(sequence);
|
|
21
|
+
CREATE TABLE replay.pending (target TEXT NOT NULL, event_id TEXT NOT NULL, recipient TEXT NOT NULL, sequence INTEGER NOT NULL,
|
|
22
|
+
PRIMARY KEY(target,sequence,event_id,recipient)) WITHOUT ROWID;
|
|
23
|
+
CREATE UNIQUE INDEX replay.event_recipient ON pending(event_id,recipient);
|
|
24
|
+
INSERT INTO replay.pending
|
|
25
|
+
SELECT COALESCE(json_extract(e.destinations,'$['||r.key||']'),'legacy:'||r.value), e.id, r.value, e.sequence
|
|
26
|
+
FROM main.events e, json_each(e.recipients) r
|
|
27
|
+
WHERE r.value IN (SELECT value FROM json_each(e.remaining));
|
|
28
|
+
INSERT INTO replay.targets SELECT target,MIN(sequence) FROM replay.pending GROUP BY target;`);
|
|
29
|
+
}
|
|
30
|
+
export function indexInsert(db, value, sequence) {
|
|
31
|
+
const recipients = JSON.parse(value.recipients);
|
|
32
|
+
for (const recipient of JSON.parse(value.remaining)) {
|
|
33
|
+
const target = value.destinations?.[recipients.indexOf(recipient)]?.id ?? `legacy:${recipient}`;
|
|
34
|
+
db.prepare('INSERT INTO replay.pending VALUES (?,?,?,?)').run(target, value.id, recipient, sequence);
|
|
35
|
+
db.prepare('INSERT OR IGNORE INTO replay.targets VALUES (?,?)').run(target, sequence);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export function indexAck(db, id, recipient) {
|
|
39
|
+
const row = db.prepare('SELECT target FROM replay.pending WHERE event_id=? AND recipient=?').get(id, recipient);
|
|
40
|
+
if (!row) { return; }
|
|
41
|
+
db.prepare('DELETE FROM replay.pending WHERE event_id=? AND recipient=?').run(id, recipient);
|
|
42
|
+
if (!db.prepare('SELECT 1 FROM replay.pending WHERE target=? LIMIT 1').get(row.target)) {
|
|
43
|
+
db.prepare('DELETE FROM replay.targets WHERE id=?').run(row.target);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/* eslint max-depth: ["error", 4] */
|
|
47
|
+
function interleaved(pages, limit) {
|
|
48
|
+
const selected = new Map();
|
|
49
|
+
for (let offset = 0; offset < limit; offset += 1) {
|
|
50
|
+
for (const page of pages) {
|
|
51
|
+
const item = page[offset];
|
|
52
|
+
if (item && (selected.has(item.event_id) || selected.size < limit)) {
|
|
53
|
+
const pairs = selected.get(item.event_id) ?? [];
|
|
54
|
+
pairs.push(item); selected.set(item.event_id, pairs);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return selected;
|
|
59
|
+
}
|
|
60
|
+
/* eslint max-statements: ["error", 20] */
|
|
61
|
+
/** Bounded destination and event pages; no payload decoding or scan proportional to an offline backlog. */
|
|
62
|
+
export function pendingFair(db, limit, blocked) {
|
|
63
|
+
const excluded = [...blocked];
|
|
64
|
+
const where = excluded.length ? `WHERE id NOT IN (${excluded.map(() => { return '?'; }).join(',')})` : '';
|
|
65
|
+
const targets = db.prepare(`SELECT id FROM replay.targets ${where} ORDER BY sequence LIMIT ?`).all(...excluded, Math.min(limit, 64));
|
|
66
|
+
const pages = targets.map(({id}) => { return db.prepare('SELECT event_id,recipient,target FROM replay.pending WHERE target=? ORDER BY sequence LIMIT ?').all(id, limit); });
|
|
67
|
+
const selected = interleaved(pages, limit);
|
|
68
|
+
let {sequence} = db.prepare('SELECT sequence FROM counters WHERE id=1').get();
|
|
69
|
+
const rows = [...selected].map(([id, pairs]) => {
|
|
70
|
+
for (const pair of pairs) {
|
|
71
|
+
sequence += 1;
|
|
72
|
+
db.prepare('UPDATE replay.pending SET sequence=? WHERE event_id=? AND recipient=?').run(sequence, id, pair.recipient);
|
|
73
|
+
}
|
|
74
|
+
const row = decoded(db.prepare('SELECT * FROM events WHERE id=?').get(id), db);
|
|
75
|
+
return {...row, remaining:pairs.map(pair => { return pair.recipient; }), targets:Object.fromEntries(pairs.map(pair => { return [pair.recipient,pair.target]; }))};
|
|
76
|
+
});
|
|
77
|
+
for (const {id} of targets) {
|
|
78
|
+
sequence += 1; db.prepare('UPDATE replay.targets SET sequence=? WHERE id=?').run(sequence, id);
|
|
79
|
+
}
|
|
80
|
+
db.prepare('UPDATE counters SET sequence=? WHERE id=1').run(sequence);
|
|
81
|
+
return rows;
|
|
82
|
+
}
|