@yarkivaev/scada 2.6.3 → 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 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 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.
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. 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.
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,6 +751,28 @@ 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. 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.
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
+
758
+ ### Bounded native history commits
759
+
760
+ Native history receivers advertise `nativeTailProtocol: preserve-known-suffix-v1`
761
+ on configuration. Workers must negotiate this before starting. A computed
762
+ terminal anchor must not clip an existing segment whose known end lies beyond
763
+ the observed page. An unchanged exterior anchor can be omitted entirely.
764
+
765
+ An exterior row requires `context.nativeTailMode` with that protocol and a
766
+ `preserveSuffix` object identifying a current segment by `kind`, `name`,
767
+ `start_time`, and `end_time`. Under the existing context revision lock, the
768
+ receiver checks its class, extent and current ownership. Archive-only rows
769
+ cannot justify exterior changes. Changing a current segment inside the page
770
+ must retain any unobserved suffix, potentially as a piece starting one
771
+ millisecond after the page end; unseen cut collisions fail atomically.
772
+ Conservative page-boundary cuts remain protected, so a paged transition can
773
+ leave additional adjacent same-class pieces. No new exterior observations or
774
+ classes are inferred. A rejected commit leaves both projection and work intact.
775
+
776
+ Applicable children carry operator metadata and `consumed`; existing rows keep
777
+ their stored consumed state. This native protocol is separate from the staged
778
+ stateful correction protocol used with external raw observation stores.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.6.3",
3
+ "version": "2.6.5",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -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; }, failure).finally(() => { receipts.delete(receipt); });
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 rows = await commands.barrier(() => { return spool.pending(batchSize); });
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
- 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 });
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.pending.delete(settled); }).catch(() => {
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?.failed === 0 && result.delivered > 0 && status?.ready !== false && status?.drainFull && status.pending > 0) {
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,3 +1,4 @@
1
+ import nativeHistoryBounds, {nativeTailProtocol} from './historyNativeBounds.js';
1
2
  import retainMetricReceipts from '../../ingest/db/retainMetricReceipts.js';
2
3
  import historyContext from './historyContext.js';
3
4
  import historyAdmission, {assertHistoryReady} from './historyAdmission.js';
@@ -88,8 +89,12 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
88
89
  if (segments.length && !base?.revision) { throw new TypeError('History context revision required'); }
89
90
  if (observationSource) { await assertHistoryReady(client,machine); }
90
91
  const latest = base?.revision ? await unchanged(client, machine, base, {observationSource,timeScale}) : null;
91
- if (latest && segments.some((item) => { return new Date(item.end_time).getTime()>Math.round(latest.context.page.until/timeScale); })) {
92
- throw new TypeError('Segment extends beyond bounded history page; upgrade history worker');
92
+ const exteriors = nativeHistoryBounds(segments, latest, base, timeScale);
93
+ for (const item of exteriors) {
94
+ // An unseen existing cut must never be overwritten by a new exterior piece.
95
+ // eslint-disable-next-line no-await-in-loop
96
+ const conflict = await client.query('SELECT 1 FROM segments WHERE machine=$1 AND kind=$2 AND start_time=$3', [machine, item.kind ?? 'phase', item.start_time]);
97
+ if (conflict.rowCount) { throw new TypeError('History suffix collides with a cut outside the observed page'); }
93
98
  }
94
99
  if(base?.replace){
95
100
  const next=await historyCorrection(client,machine,work.rows[0],segments,{base,context:latest,timeScale});
@@ -103,8 +108,8 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
103
108
  for (const item of segments) {
104
109
  // Only computed fields change. User cuts/labels must be applied by caller before commit.
105
110
  // eslint-disable-next-line no-await-in-loop
106
- await client.query(`INSERT INTO segments(machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved)
107
- VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) ON CONFLICT(machine,kind,start_time) DO UPDATE
111
+ await client.query(`INSERT INTO segments(machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed)
112
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) ON CONFLICT(machine,kind,start_time) DO UPDATE
108
113
  SET name=EXCLUDED.name,end_time=EXCLUDED.end_time,duration=EXCLUDED.duration,options=EXCLUDED.options,updated_at=clock_timestamp(),
109
114
  tags=CASE WHEN segments.name=EXCLUDED.name THEN segments.tags ELSE EXCLUDED.tags END,
110
115
  properties=CASE WHEN segments.name=EXCLUDED.name THEN segments.properties ELSE EXCLUDED.properties END,
@@ -112,7 +117,7 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
112
117
  [machine, item.kind ?? 'phase', item.name, item.start_time, item.end_time, item.duration,
113
118
  typeof item.options === 'string' ? item.options : JSON.stringify(item.options ?? null),
114
119
  typeof item.tags === 'string' ? item.tags : JSON.stringify(item.tags ?? null),
115
- typeof item.properties === 'string' ? item.properties : JSON.stringify(item.properties ?? null), item.resolved ?? true]);
120
+ typeof item.properties === 'string' ? item.properties : JSON.stringify(item.properties ?? null), item.resolved ?? true, item.consumed ?? true]);
116
121
  }
117
122
  const converged=await saveCheckpoint(client,machine,base?.checkpoint,latest);
118
123
  await advance(client,machine,workId,converged ? {next:null} : latest?.context.page);
@@ -134,7 +139,7 @@ export default function historyPg(pool, { retentionDays = 30, now = Date.now, ob
134
139
  const source=observationSource?.(client);
135
140
  const result=await historyConfigure(client,machine,topics,bucketMs*timeScale,{retentionDays,observations:source});
136
141
  await configureClassifier(client,machine,classifierKey,source);
137
- return {...result,...((timeScale!==1 || classifierKey) && {timeScale}),...(classifierKey && {classifierProtocol:historyProtocol})};
142
+ return {...result,...((timeScale!==1 || classifierKey) && {timeScale}),...(!classifierKey && {nativeTailProtocol}),...(classifierKey && {classifierProtocol:historyProtocol})};
138
143
  },true);
139
144
  },
140
145
  async purge() {
@@ -50,7 +50,7 @@ export default async function historyContext(pool,machine,from,until,{padding,cu
50
50
  const annotations = await pool.query(`SELECT a.kind,a.name,a.start_time,a.end_time,a.duration,
51
51
  CASE WHEN s.machine IS NOT NULL THEN s.tags ELSE a.tags END AS tags,
52
52
  CASE WHEN s.machine IS NOT NULL THEN s.properties ELSE a.properties END AS properties,
53
- CASE WHEN s.machine IS NOT NULL THEN s.resolved ELSE a.resolved END AS resolved
53
+ CASE WHEN s.machine IS NOT NULL THEN s.resolved ELSE a.resolved END AS resolved,CASE WHEN s.machine IS NOT NULL THEN s.consumed ELSE NULL END AS consumed
54
54
  FROM history_annotations a LEFT JOIN segments s ON s.machine=a.machine AND s.kind=a.kind AND s.start_time=a.start_time AND s.name=a.name
55
55
  WHERE a.machine=$1 AND a.kind='phase' AND a.start_time<=$3 AND a.end_time>=$2
56
56
  AND (COALESCE(a.tags,'') NOT IN ('','null','[]') OR COALESCE(a.properties,'') NOT IN ('','null','{}')) ORDER BY a.start_time,a.name LIMIT 10001`,
@@ -0,0 +1,43 @@
1
+ export const nativeTailProtocol = 'preserve-known-suffix-v1';
2
+ function instant(value) { return new Date(value).getTime(); }
3
+ function kind(row) { return row.kind ?? 'phase'; }
4
+ function identity(left, right) {
5
+ return kind(left) === kind(right) && left.name === right.name
6
+ && instant(left.start_time) === instant(right.start_time) && instant(left.end_time) === instant(right.end_time);
7
+ }
8
+ function provedOwner(item, latest, base, until) {
9
+ const start = instant(item.start_time); const end = instant(item.end_time);
10
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start > end) { throw new TypeError('Invalid bounded history segment'); }
11
+ if (end <= until) { return null; }
12
+ const owner = base.nativeTailMode === nativeTailProtocol && (latest.segments ?? []).find(row => {
13
+ return item.preserveSuffix && identity(row, item.preserveSuffix)
14
+ && kind(row) === kind(item) && row.name === item.name
15
+ && instant(row.start_time) <= until && instant(row.start_time) <= start
16
+ && start <= until + 1 && instant(row.end_time) === end;
17
+ });
18
+ if (!owner) { throw new TypeError('Segment extends beyond bounded history page without a current suffix proof'); }
19
+ return owner;
20
+ }
21
+ function retainExterior(segments, current, owners, until) {
22
+ for (const owner of current) {
23
+ const change = segments.find(item => { return kind(item) === kind(owner) && instant(item.start_time) === instant(owner.start_time); });
24
+ if (change && instant(owner.end_time) > until
25
+ && (change.name !== owner.name || instant(change.end_time) < instant(owner.end_time))) {
26
+ const retained = [...owners].some(([item, proof]) => {
27
+ return identity(proof, owner) && instant(item.start_time) <= until + 1;
28
+ });
29
+ if (!retained) { throw new TypeError('Known history tail would be truncated; upgrade the history worker'); }
30
+ }
31
+ }
32
+ }
33
+ /** A bounded native correction may carry existing exterior, never classify new exterior. */
34
+ export default function nativeHistoryBounds(segments, latest, base, timeScale) {
35
+ if (!latest) { return []; }
36
+ const until = Math.round(latest.context.page.until / timeScale);
37
+ if (base.nativeTailMode !== undefined && (base.nativeTailMode !== nativeTailProtocol || base.replace)) {
38
+ throw new TypeError('Unsupported native history suffix protocol');
39
+ }
40
+ const owners = new Map(segments.map(item => { return [item, provedOwner(item, latest, base, until)]; }).filter(([, owner]) => { return owner; }));
41
+ if (!base.replace) { retainExterior(segments, latest.segments ?? [], owners, until); }
42
+ return [...owners.keys()].filter(item => { return instant(item.start_time) > until; });
43
+ }
@@ -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
+ }