@yarkivaev/scada 2.6.1 → 2.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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
+ Receipt admission is reserved before network publication, then queued only after mandatory confirmation. Confirmed receipts accumulate in a bounded window; `drain()` counts them delivered only after their FULL commit. Graceful close rejects new source submissions, flushes existing submissions, waits for the active drain and its receipts, then closes sessions and persistence. The existing crash-after-confirm/before-local-receipt replay contract remains unchanged.
755
+
756
+ Healthy full drain pages with durable progress continue on subsequent event-loop turns; after four pages the scheduler pauses 25 ms. Failed, empty or zero-progress pages back off 1s. This removes the former 100-event/s scheduling ceiling without spinning on an offline recipient. Actual append and online catch-up throughput still require qualification on the target filesystem; a serial producer awaiting every individual acceptance cannot benefit from concurrent group formation.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.6.1",
3
+ "version": "2.6.2",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,119 @@
1
+ function positive(value, name, zero = false) {
2
+ if (!Number.isSafeInteger(value) || value < (zero ? 0 : 1)) { throw new TypeError(`${name} must be a ${zero ? 'nonnegative' : 'positive'} safe integer`); }
3
+ }
4
+ function settings(options) {
5
+ if (options.groupCommit !== undefined && (!options.groupCommit || typeof options.groupCommit !== 'object' || Array.isArray(options.groupCommit))) {
6
+ throw new TypeError('groupCommit must be an object');
7
+ }
8
+ const { maxRecords = 64, maxBytes = 1048576, maxDelayMs = 25 } = options.groupCommit ?? {};
9
+ const group = { maxRecords, maxBytes, maxDelayMs };
10
+ const config = { ...group, maxOperations: options.maxOperations ?? 128, maxPendingBytes: options.maxPendingBytes ?? 4194304 };
11
+ Object.entries(config).forEach(([name, value]) => { positive(value, name, name === 'maxDelayMs'); });
12
+ if (config.maxDelayMs > 2147483647) { throw new TypeError('maxDelayMs must be a safe timer duration'); }
13
+ return config;
14
+ }
15
+ /** Bounded FIFO admission precedes serialization; every reservation includes actual in-flight writes. */
16
+ /* eslint max-lines-per-function: ["error", 135], max-statements: ["error", 20] */
17
+ export default function deliveryOperations(apply, options = {}) {
18
+ const config = settings(options);
19
+ const jobs = [];
20
+ const state = { operations: 0, bytes: 0, running: false, timer: null, idle: null, wake: null };
21
+ function reserve() {
22
+ if (state.operations >= config.maxOperations) { throw new Error('Delivery operation capacity exceeded'); }
23
+ state.operations += 1;
24
+ }
25
+ function notifyIdle() {
26
+ if (!state.operations && !state.running) { state.wake?.(); Object.assign(state, { idle: null, wake: null }); }
27
+ }
28
+ function release(bytes) { state.operations -= 1; state.bytes -= bytes; notifyIdle(); }
29
+ function settle(job, result) {
30
+ release(job.bytes);
31
+ if (result.ok) { job.resolve(result.value); } else { job.reject(result.error); }
32
+ }
33
+ function group() {
34
+ const selected = []; let bytes = 0;
35
+ while (jobs.length && jobs[0].kind === 'mutation' && selected.length < config.maxRecords
36
+ && bytes + jobs[0].bytes <= config.maxBytes) {
37
+ const job = jobs.shift(); selected.push(job); bytes += job.bytes;
38
+ }
39
+ return selected;
40
+ }
41
+ async function executeBarrier() {
42
+ const job = jobs.shift();
43
+ try { const value = await job.action(); settle(job, { ok: true, value }); }
44
+ catch (error) { settle(job, { ok: false, error }); }
45
+ }
46
+ async function executeGroup() {
47
+ const selected = group();
48
+ try {
49
+ const results = await apply(selected.map((job) => { return job.operation; }));
50
+ if (!Array.isArray(results) || results.length !== selected.length
51
+ || results.some((result) => { return typeof result?.ok !== 'boolean'; })) { throw new Error('Invalid grouped mutation result'); }
52
+ selected.forEach((job, index) => { settle(job, results[index]); });
53
+ } catch (error) { selected.forEach((job) => { settle(job, { ok: false, error }); }); }
54
+ }
55
+ async function execute() {
56
+ clearTimeout(state.timer); state.timer = null;
57
+ if (state.running) { return; }
58
+ state.running = true;
59
+ try {
60
+ while (jobs.length) {
61
+ // eslint-disable-next-line no-await-in-loop
62
+ await (jobs[0].kind === 'barrier' ? executeBarrier() : executeGroup());
63
+ // Every group yields so sustained backlog cannot monopolize the event loop.
64
+ // eslint-disable-next-line no-await-in-loop
65
+ if (jobs.length) { await new Promise((resolve) => { setImmediate(resolve); }); }
66
+ }
67
+ } finally { Object.assign(state, { running: false }); notifyIdle(); }
68
+ }
69
+ function schedule(delay) {
70
+ if (state.running) { return; }
71
+ if (state.timer && delay !== 0) { return; }
72
+ clearTimeout(state.timer); state.timer = setTimeout(execute, delay);
73
+ }
74
+ function enqueue(job) {
75
+ return new Promise((resolve, reject) => {
76
+ jobs.push({ ...job, resolve, reject });
77
+ schedule(job.kind === 'barrier' || state.operations >= Math.min(config.maxRecords, config.maxOperations) ? 0 : config.maxDelayMs);
78
+ });
79
+ }
80
+ function checkBytes(bytes) {
81
+ positive(bytes, 'Mutation bytes', true);
82
+ if (state.bytes + bytes > config.maxPendingBytes) { throw new Error('Delivery pending byte capacity exceeded'); }
83
+ if (bytes > config.maxBytes) { throw new Error('Delivery group byte capacity exceeded'); }
84
+ }
85
+ function prepare(build) {
86
+ reserve();
87
+ let value;
88
+ try {
89
+ value = build(checkBytes); checkBytes(value.bytes);
90
+ } catch (error) { release(0); throw error; }
91
+ state.bytes += value.bytes;
92
+ let settled = false;
93
+ return {
94
+ commit() {
95
+ if (settled) { return Promise.reject(new Error('Delivery reservation already settled')); }
96
+ settled = true; return enqueue({ kind: 'mutation', ...value });
97
+ },
98
+ cancel() { if (!settled) { settled = true; release(value.bytes); } }
99
+ };
100
+ }
101
+ return {
102
+ prepare,
103
+ mutate(build) {
104
+ try { return prepare(build).commit(); } catch (error) { return Promise.reject(error); }
105
+ },
106
+ barrier(action) {
107
+ try { reserve(); return enqueue({ kind: 'barrier', action, bytes: 0 }); }
108
+ catch (error) { return Promise.reject(error); }
109
+ },
110
+ flush() { if (jobs.length) { schedule(0); } },
111
+ idle() {
112
+ if (!state.operations && !state.running) { return Promise.resolve(); }
113
+ schedule(0);
114
+ state.idle ??= new Promise((resolve) => { state.wake = resolve; });
115
+ return state.idle;
116
+ },
117
+ status() { return { operations: state.operations, bytes: state.bytes }; }
118
+ };
119
+ }
@@ -1,80 +1,96 @@
1
1
  import deliverySpool from '../../infrastructure/persistence/runtime/deliverySpool.js';
2
2
  import deliverySessions from './deliverySessions.js';
3
+ import deliveryOperations from './deliveryOperations.js';
3
4
 
4
5
  function confirmed(event) {
5
6
  return { ...event, options: { ...event.options, persistent: true, mandatory: true, messageId: event.eventId } };
6
7
  }
7
- /* eslint max-lines-per-function: ["error", 90], max-statements: ["error", 20] */
8
- /** Node-owned queue: removing a source does not remove its destination descriptors or receipts. */
8
+ function snapshot(operation, checkBytes) {
9
+ const json = JSON.stringify(operation); checkBytes(Buffer.byteLength(json));
10
+ const frozen = JSON.parse(json);
11
+ if (frozen.kind === 'append') { frozen.recipients = frozen.event.destinations.map((item) => { return item.id; }); }
12
+ return { operation: frozen, bytes: Buffer.byteLength(JSON.stringify(frozen)) };
13
+ }
14
+ /* eslint max-lines-per-function: ["error", 125], max-statements: ["error", 25] */
15
+ /** Node-owned queue: every point/receipt resolves only after its grouped FULL commit. */
9
16
  export default function deliveryQueue(directory, options) {
10
17
  const spool = deliverySpool(directory, options);
18
+ const commands = deliveryOperations((operations) => { return spool.mutateMany(operations); }, options);
11
19
  const sessions = deliverySessions(options.factory, options.writeTimeoutMs);
12
- let chain = Promise.resolve();
13
- const state = { pending: 0, draining: false, closed: false };
14
- function serialized(action) {
15
- if (state.pending >= (options.maxOperations ?? 32)) { return Promise.reject(new Error('Delivery operation capacity exceeded')); }
16
- state.pending += 1;
17
- const result = chain.then(action).finally(() => { state.pending -= 1; });
18
- chain = result.catch(() => {
19
- // Individual callers receive rejection; preserve serialization.
20
- });
21
- return result;
22
- }
23
- async function send(record, id) {
20
+ const batchSize = options.batchSize ?? 100;
21
+ if (!Number.isSafeInteger(batchSize) || batchSize <= 0) { throw new TypeError('Positive safe batchSize required'); }
22
+ const receiptWindow = Math.min(options.groupCommit?.maxRecords ?? 64, options.maxOperations ?? 128);
23
+ const state = { draining: false, closed: false, full: false };
24
+ async function publish(record, id) {
24
25
  if (state.closed) { throw new Error('Delivery queue closed'); }
25
- const descriptor = record.event.destinations.find((item) => { return item.id === id; });
26
- await sessions.write(descriptor, confirmed(record.event.observation));
27
- await serialized(() => { return spool.ack(record.event.eventId, id); });
26
+ // Reserve the eventual receipt BEFORE publication; confirmation can never lose its admission slot.
27
+ const receipt = commands.prepare((checkBytes) => { return snapshot({ kind: 'ack', eventId: record.event.eventId, recipient: id }, checkBytes); });
28
+ try {
29
+ const descriptor = record.event.destinations.find((item) => { return item.id === id; });
30
+ await sessions.write(descriptor, confirmed(record.event.observation));
31
+ return { receipt: receipt.commit() };
32
+ } catch (error) { receipt.cancel(); throw error; }
28
33
  }
29
-
30
34
  async function drain() {
31
- if (state.draining || state.closed) { return { delivered: 0, failed: 0 }; }
32
35
  state.draining = true;
33
36
  const result = { delivered: 0, failed: 0 };
37
+ const receipts = [];
38
+ function failure(error) {
39
+ result.failed += 1;
40
+ try { options.onError?.(error); } catch {
41
+ // Observers cannot prevent independent recipient progress or release.
42
+ }
43
+ }
44
+ async function flush() { commands.flush(); await Promise.all(receipts.splice(0)); }
45
+ async function receive(row, id) {
46
+ try {
47
+ const sent = await publish(row, id);
48
+ receipts.push(sent.receipt.then(() => { result.delivered += 1; }, failure));
49
+ } catch (error) { failure(error); }
50
+ if (receipts.length >= receiptWindow) { await flush(); }
51
+ }
34
52
  try {
35
- const rows = await serialized(() => { return spool.pending(options.batchSize ?? 100); });
53
+ const rows = await commands.barrier(() => { return spool.pending(batchSize); });
54
+ Object.assign(state, { full: rows.length === batchSize });
36
55
  for (const row of rows) {
37
56
  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
- }
57
+ // eslint-disable-next-line no-await-in-loop
58
+ await receive(row, id);
43
59
  }
44
60
  }
45
61
  return result;
46
- } finally { Object.assign(state, { draining: false }); }
62
+ } finally { try { await flush(); } finally { Object.assign(state, { draining: false }); } }
47
63
  }
48
-
49
64
  return {
50
65
  open() {
51
66
  if (state.closed) { return Promise.reject(new Error('Delivery queue closed')); }
52
- return serialized(() => { return spool.open(); });
67
+ return commands.barrier(() => { return spool.open(); });
53
68
  },
54
69
  accept(event, destinations) {
55
70
  if (state.closed) { return Promise.reject(new Error('Delivery queue closed')); }
56
71
  if (!destinations?.length || destinations.some((item) => { return item.type !== 'amqp'; })) {
57
72
  return Promise.reject(new TypeError('Queued delivery requires confirmed AMQP destinations'));
58
73
  }
59
- // Snapshot before asynchronous I/O; callers may reuse buffers/objects.
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; })); });
74
+ return commands.mutate((checkBytes) => { return snapshot({ kind: 'append', event: { eventId: event.eventId, observation: event, destinations } }, checkBytes); });
62
75
  },
63
76
  drain() {
64
- if (state.draining || state.closed) { return Promise.resolve({ delivered:0, failed:0 }); }
77
+ if (state.draining || state.closed) { return Promise.resolve({ delivered: 0, failed: 0 }); }
65
78
  const result = drain(); state.activeDrain = result; return result;
66
79
  },
67
80
  close() {
68
- state.closed = true;
81
+ state.closed = true; commands.flush();
69
82
  state.closing ??= (async () => {
70
83
  await state.activeDrain?.catch(() => {
71
84
  // Drain caller receives the original error.
72
- }); await chain;
85
+ });
86
+ await commands.idle();
73
87
  try { await sessions.close(); } finally { await spool.close(); }
74
88
  })();
75
89
  return state.closing;
76
90
  },
77
- status() { return spool.status(); }
91
+ status() {
92
+ const usage = commands.status();
93
+ return { ...spool.status(), queuedOperations: usage.operations, queuedBytes: usage.bytes, drainFull: state.full };
94
+ }
78
95
  };
79
-
80
96
  }
@@ -5,17 +5,29 @@ import { sinks } from './streamPorts.js';
5
5
  export default function queuedDelivery(env, secrets, supplied) {
6
6
  let timer;
7
7
  let stopped = false;
8
+ let burst = 0;
8
9
  const queue = supplied ?? (env.COLLECTOR_SPOOL_DIR ? deliveryQueue(env.COLLECTOR_SPOOL_DIR, {
9
10
  maxBytes: Number(env.COLLECTOR_SPOOL_MAX_BYTES), maxRecords: Number(env.COLLECTOR_SPOOL_MAX_RECORDS ?? 100000), factory(spec) { return sinks().get(spec.type)(spec, { secrets }); },
10
11
  onError(error) { process.stderr.write(`Collector delivery delayed: ${error.message}\n`); }
11
12
  }) : undefined);
13
+ function nextDelay(result) {
14
+ const status = queue.status?.();
15
+ if (result?.failed === 0 && result.delivered > 0 && status?.ready !== false && status?.drainFull && status.pending > 0) {
16
+ burst += 1;
17
+ const delay = burst < 4 ? 0 : 25;
18
+ if (burst === 4) { burst = 0; }
19
+ return delay;
20
+ }
21
+ burst = 0; return 1000;
22
+ }
12
23
  async function tick() {
13
24
  if (stopped || !queue) { return; }
25
+ let delay = 1000;
14
26
  try {
15
27
  if (queue.status?.().ready === false) { await queue.open(); }
16
- await queue.drain();
17
- } catch (error) { process.stderr.write(`Collector spool: ${error.message}\n`); }
18
- if (!stopped) { timer = setTimeout(tick, 1000); timer.unref(); }
28
+ delay = nextDelay(await queue.drain());
29
+ } catch (error) { burst = 0; process.stderr.write(`Collector spool: ${error.message}\n`); }
30
+ if (!stopped) { timer = setTimeout(tick, delay); timer.unref(); }
19
31
  }
20
32
  return {
21
33
  queue,
@@ -1,6 +1,6 @@
1
1
  import { capacity, checkpoint, counters, database } from './spoolDatabase.js';
2
- import { acknowledge, insert, pending } from './spoolRecords.js';
3
- import { encoded } from './spoolCodec.js';
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 exclusive(() => { return commit(() => { insert(state.db, encoded(event, recipients), maxBytes, maxRecords); }); }); },
43
- ack(eventId, recipient) { return exclusive(() => { return commit(() => { acknowledge(state.db, eventId, recipient); }); }); },
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
+ }