@aria-framework/db-worker 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +12 -0
  2. package/client.js +35 -6
  3. package/package.json +1 -1
  4. package/worker.js +17 -12
package/README.md CHANGED
@@ -112,6 +112,18 @@ Model methods may be sync or async (thenables are awaited). BigInts in results
112
112
 
113
113
  ## Changelog
114
114
 
115
+ - **0.4.1** — third-review fixes (all in the 0.4.0 additions). (1) Boot-crash
116
+ suppression latched: a hard boot crash emits 'error' AND 'exit'; the exit
117
+ handler no longer fires the death policy after the error handler consumed
118
+ the boot state. (2) init() resets the death latch and closing flag, so the
119
+ respawn pattern works (worker #2's death notifies again) and close()+re-init
120
+ doesn't inherit stale flags. (3) Queue warnings coalesce: first occurrence
121
+ logs, then at most one summary line per 10s with the suppressed count —
122
+ saturation no longer floods the log it's reporting into; wording clarifies
123
+ the wait includes IPC/event-loop overhead, not pure queue time.
124
+ (4) Sanitizer memoizes shared references (obj → sanitized node): linear
125
+ time on diamond-shaped graphs AND sharing is preserved through structured
126
+ clone; true cycles still throw via a separate ancestor set.
115
127
  - **0.4.0** — second-review fixes. (1) sanitizeForTransfer tracks the ancestor
116
128
  PATH (unwind delete), so shared/diamond references in results are legal
117
129
  again — only true cycles throw; the error path is also guarded so an
package/client.js CHANGED
@@ -48,6 +48,12 @@ class DbClient {
48
48
  this._queueWarnMs = queueWarnMs === undefined ? 1000 : queueWarnMs;
49
49
  this._onWorkerDeath = typeof onWorkerDeath === 'function' ? onWorkerDeath : null;
50
50
  this._deathNotified = false;
51
+ // Queue-warn coalescing: under real saturation EVERY completed call crosses
52
+ // the threshold — one line each would flood the log (disk I/O during the
53
+ // very pile-up being reported). Log the first, then at most one summary
54
+ // line per window carrying the suppressed count.
55
+ this._queueWarnLastAt = 0;
56
+ this._queueWarnSuppressed = 0;
51
57
  this._worker = null;
52
58
  this._pending = new Map();
53
59
  this._nextId = 0;
@@ -63,6 +69,12 @@ class DbClient {
63
69
  */
64
70
  init(workerData) {
65
71
  return new Promise((resolve, reject) => {
72
+ // Fresh lifecycle state per worker: a respawn policy re-init()s after a
73
+ // death, and a close()+re-init must not inherit the previous worker's
74
+ // latch/closing flags (they would suppress the NEW worker's crash
75
+ // handling and death notification).
76
+ this._deathNotified = false;
77
+ this._closing = false;
66
78
  this._worker = new Worker(this._workerPath, { workerData });
67
79
  this._initReject = reject;
68
80
 
@@ -94,9 +106,21 @@ class DbClient {
94
106
  // the queue-wait pile-up.
95
107
  this._logger.warn(`Slow DB call (${msg.execMs}ms exec, ${total}ms total): ${pending.label}`);
96
108
  } else if (this._queueWarnMs && (total - msg.execMs) >= this._queueWarnMs) {
97
- // Saturation signal: this call executed fast but sat in the queue —
98
- // a worker drowning in fast queries would otherwise log nothing.
99
- this._logger.warn(`Slow DB queue (${total - msg.execMs}ms wait, ${msg.execMs}ms exec): ${pending.label} — calls backing up behind other queries`);
109
+ // Saturation signal: this call executed fast but its round trip was
110
+ // dominated by wait (worker queue + IPC/event-loop overhead — NOT
111
+ // pure DB queue time; a stalled client event loop shows here too).
112
+ // A worker drowning in fast queries would otherwise log nothing.
113
+ const now = Date.now();
114
+ if (now - this._queueWarnLastAt >= 10_000) {
115
+ const suppressed = this._queueWarnSuppressed;
116
+ this._queueWarnLastAt = now;
117
+ this._queueWarnSuppressed = 0;
118
+ this._logger.warn(`Slow DB queue (${total - msg.execMs}ms wait, ${msg.execMs}ms exec): ${pending.label}` +
119
+ (suppressed ? ` (+${suppressed} more delayed calls in the last 10s)` : '') +
120
+ ' — calls backing up behind other work');
121
+ } else {
122
+ this._queueWarnSuppressed++;
123
+ }
100
124
  }
101
125
  }
102
126
  if (msg.error) {
@@ -127,8 +151,12 @@ class DbClient {
127
151
  }
128
152
  this._pending.clear();
129
153
  // Boot failures reject init() — the app's startup error handling owns
130
- // logging + exit; firing the death policy here would preempt it.
131
- if (!wasBooting) this._notifyDeath({ reason: 'error', error: err });
154
+ // logging + exit; firing the death policy here would preempt it. Latch
155
+ // the suppression: a boot crash emits 'error' AND 'exit', and by the
156
+ // time 'exit' runs _initReject is already cleared — without the latch
157
+ // the exit handler would fire the policy the boot guard just skipped.
158
+ if (wasBooting) this._deathNotified = true;
159
+ else this._notifyDeath({ reason: 'error', error: err });
132
160
  });
133
161
 
134
162
  this._worker.on('exit', (code) => {
@@ -148,7 +176,8 @@ class DbClient {
148
176
  p.reject(new Error(`Database worker exited with code ${code}`));
149
177
  }
150
178
  this._pending.clear();
151
- if (!wasBooting) this._notifyDeath({ reason: 'exit', code });
179
+ if (wasBooting) this._deathNotified = true;
180
+ else this._notifyDeath({ reason: 'exit', code });
152
181
  }
153
182
  });
154
183
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "Aria App Framework — db-worker module. Async RPC bridge over synchronous better-sqlite3: a worker-thread dispatcher (runWorker), a main-thread client with per-call timeouts and crash handling (DbClient), and a SQLite layer with WAL pragmas + a numbered-migration runner (database).",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
package/worker.js CHANGED
@@ -84,31 +84,36 @@ function runWorker({ init }) {
84
84
  * props → {}; a Buffer would become a numeric-keyed plain object). Circular
85
85
  * result graphs throw a clear error instead of a RangeError stack overflow.
86
86
  */
87
- function sanitizeForTransfer(obj, seen) {
87
+ function sanitizeForTransfer(obj, ctx) {
88
88
  if (obj === null || obj === undefined) return obj;
89
89
  if (typeof obj === 'bigint') return Number(obj);
90
90
  if (typeof obj !== 'object') return obj;
91
91
  if (obj instanceof Date || Buffer.isBuffer(obj) || ArrayBuffer.isView(obj)) return obj;
92
- // Ancestor-PATH tracking (add before recursing into children, remove on
93
- // unwind): a shared/diamond reference — the same object appearing under two
94
- // siblings — is a legal DAG that structured clone handles fine; only a true
95
- // cycle (an object containing itself) must throw. A plain visited-set would
96
- // falsely flag the shared case.
97
- seen = seen || new WeakSet();
98
- if (seen.has(obj)) {
92
+ // Two structures: `path` (ancestor set) detects TRUE cycles — an object
93
+ // containing itself must throw; `memo` (obj → sanitized copy) makes shared/
94
+ // diamond references legal AND linear-time: the same source object always
95
+ // maps to the SAME sanitized node, so sharing survives structured clone and
96
+ // a diamond-shaped graph isn't re-walked once per referencing edge
97
+ // (unwind-only tracking was worst-case exponential on nested shared trees).
98
+ ctx = ctx || { path: new WeakSet(), memo: new WeakMap() };
99
+ if (ctx.path.has(obj)) {
99
100
  throw new Error('DB worker result contains a circular reference and cannot cross the thread boundary');
100
101
  }
101
- seen.add(obj);
102
+ if (ctx.memo.has(obj)) return ctx.memo.get(obj);
103
+ ctx.path.add(obj);
102
104
  let result;
103
105
  if (Array.isArray(obj)) {
104
- result = obj.map((v) => sanitizeForTransfer(v, seen));
106
+ result = [];
107
+ ctx.memo.set(obj, result);
108
+ for (const v of obj) result.push(sanitizeForTransfer(v, ctx));
105
109
  } else {
106
110
  result = {};
111
+ ctx.memo.set(obj, result);
107
112
  for (const [key, val] of Object.entries(obj)) {
108
- result[key] = sanitizeForTransfer(val, seen);
113
+ result[key] = sanitizeForTransfer(val, ctx);
109
114
  }
110
115
  }
111
- seen.delete(obj);
116
+ ctx.path.delete(obj);
112
117
  return result;
113
118
  }
114
119