@aria-framework/db-worker 0.2.0 → 0.3.0

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 +10 -0
  2. package/client.js +31 -11
  3. package/package.json +1 -1
  4. package/worker.js +25 -13
package/README.md CHANGED
@@ -105,6 +105,16 @@ Model methods may be sync or async (thenables are awaited). BigInts in results
105
105
 
106
106
  ## Changelog
107
107
 
108
+ - **0.3.0** — three review-driven fixes. (1) **`onWorkerDeath` policy hook**:
109
+ called after a non-deliberate worker death; without a policy the process
110
+ keeps running with every invoke() rejecting — a silent outage supervisors
111
+ can't see. Recommended app policy: log + `process.exit(1)`. (2) **Slow-call
112
+ timing moved into the worker**: the threshold now applies to execution time
113
+ (`execMs` shipped in each response), so calls queued behind a slow query no
114
+ longer log under their own names; the message shows `exec` and `total`.
115
+ (3) **Sanitizer hardened**: Date/Buffer/typed arrays pass through untouched
116
+ (structured clone handles them; recursing mangled them), and circular result
117
+ graphs throw a clear error instead of overflowing the stack.
108
118
  - **0.2.0** — slow-call detection: `DbClient` warn-logs any invoke at or over
109
119
  `slowMs` (default 500ms, 0 disables) with duration + `Model.method`. Turns
110
120
  performance work measurement-driven — add the index when a real query names
package/client.js CHANGED
@@ -20,18 +20,27 @@ class DbClient {
20
20
  * @param {string} opts.workerPath - Absolute path to the app's worker entry file
21
21
  * @param {Object} [opts.logger=console] - Logger with .info/.warn/.error
22
22
  * @param {number} [opts.callTimeoutMs=30000] - Per-invoke timeout
23
- * @param {number} [opts.slowMs=500] - Warn-log any invoke whose round trip
24
- * takes at least this long ("Slow DB call (612ms): Ticket.queue"), so slow
25
- * queries name themselves before users complain. Includes worker queue
26
- * wait — if one slow query backs up others, the pile-up is visible too.
27
- * Pass 0 to disable.
23
+ * @param {number} [opts.slowMs=500] - Warn-log any invoke whose worker-side
24
+ * EXECUTION takes at least this long ("Slow DB call (612ms exec, 1840ms
25
+ * total): Ticket.queue"), so slow queries name themselves before users
26
+ * complain. The threshold applies to execution time (not queue wait), so
27
+ * fast calls queued behind a slow one are not misattributed; the total
28
+ * round trip is shown alongside so pile-ups are still visible. Pass 0 to
29
+ * disable.
30
+ * @param {(info: {reason: 'error'|'exit', error?: Error, code?: number}) => void}
31
+ * [opts.onWorkerDeath] - Called after a NON-deliberate worker death (crash
32
+ * or unexpected exit; never on close()). Without a policy here the process
33
+ * keeps running with every invoke() rejecting — a silent outage that
34
+ * supervisors keyed on process exit cannot see. Recommended app policy:
35
+ * log loudly and process.exit(1) so systemd/pm2 restarts the service.
28
36
  */
29
- constructor({ workerPath, logger, callTimeoutMs, slowMs } = {}) {
37
+ constructor({ workerPath, logger, callTimeoutMs, slowMs, onWorkerDeath } = {}) {
30
38
  if (!workerPath) throw new Error('DbClient: workerPath is required');
31
39
  this._workerPath = workerPath;
32
40
  this._logger = logger || console;
33
41
  this._callTimeoutMs = callTimeoutMs || 30 * 1000;
34
42
  this._slowMs = slowMs === undefined ? 500 : slowMs;
43
+ this._onWorkerDeath = typeof onWorkerDeath === 'function' ? onWorkerDeath : null;
35
44
  this._worker = null;
36
45
  this._pending = new Map();
37
46
  this._nextId = 0;
@@ -70,11 +79,12 @@ class DbClient {
70
79
  if (!pending) return;
71
80
  this._pending.delete(msg.id);
72
81
  if (pending.timer) clearTimeout(pending.timer);
73
- if (this._slowMs) {
74
- const elapsed = Date.now() - pending.started;
75
- if (elapsed >= this._slowMs) {
76
- this._logger.warn(`Slow DB call (${elapsed}ms): ${pending.label}`);
77
- }
82
+ if (this._slowMs && typeof msg.execMs === 'number' && msg.execMs >= this._slowMs) {
83
+ // Threshold on worker-side execution time so calls queued behind a
84
+ // slow one don't log under their own (innocent) names; total shows
85
+ // the queue-wait pile-up.
86
+ const total = Date.now() - pending.started;
87
+ this._logger.warn(`Slow DB call (${msg.execMs}ms exec, ${total}ms total): ${pending.label}`);
78
88
  }
79
89
  if (msg.error) {
80
90
  const err = new Error(msg.error.message);
@@ -98,6 +108,7 @@ class DbClient {
98
108
  p.reject(new Error('Database worker crashed: ' + err.message));
99
109
  }
100
110
  this._pending.clear();
111
+ this._notifyDeath({ reason: 'error', error: err });
101
112
  });
102
113
 
103
114
  this._worker.on('exit', (code) => {
@@ -116,11 +127,20 @@ class DbClient {
116
127
  p.reject(new Error(`Database worker exited with code ${code}`));
117
128
  }
118
129
  this._pending.clear();
130
+ this._notifyDeath({ reason: 'exit', code });
119
131
  }
120
132
  });
121
133
  });
122
134
  }
123
135
 
136
+ /** @private Invoke the app's worker-death policy (never throws). */
137
+ _notifyDeath(info) {
138
+ if (!this._onWorkerDeath) return;
139
+ try { this._onWorkerDeath(info); } catch (e) {
140
+ this._logger.error('onWorkerDeath handler threw: ' + e.message);
141
+ }
142
+ }
143
+
124
144
  /**
125
145
  * Invoke a model method on the worker thread.
126
146
  * @param {string} model
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
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
@@ -35,6 +35,10 @@ function runWorker({ init }) {
35
35
 
36
36
  parentPort.on('message', async (msg) => {
37
37
  const { id, model, method, args } = msg;
38
+ // Worker-side execution time, shipped back so the client's slow-call log
39
+ // attributes slowness to the query that WAS slow, not to calls that were
40
+ // merely queued behind it.
41
+ const t0 = Date.now();
38
42
  try {
39
43
  const target = models[model];
40
44
  if (!target) throw new Error(`Unknown model: ${model}`);
@@ -48,11 +52,11 @@ function runWorker({ init }) {
48
52
  }
49
53
 
50
54
  result = sanitizeForTransfer(result);
51
- parentPort.postMessage({ id, result });
55
+ parentPort.postMessage({ id, result, execMs: Date.now() - t0 });
52
56
  } catch (err) {
53
57
  // Preserve custom error props (e.g. code, status, entity ids) across the
54
58
  // boundary — message/stack aren't enumerable, so the spread adds only extras.
55
- parentPort.postMessage({ id, error: sanitizeForTransfer({ message: err.message, stack: err.stack, ...err }) });
59
+ parentPort.postMessage({ id, error: sanitizeForTransfer({ message: err.message, stack: err.stack, ...err }), execMs: Date.now() - t0 });
56
60
  }
57
61
  });
58
62
  } catch (err) {
@@ -61,21 +65,29 @@ function runWorker({ init }) {
61
65
  }
62
66
 
63
67
  /**
64
- * Convert BigInt values (better-sqlite3 returns lastInsertRowid as BigInt) to
65
- * Number so the result serialises across the thread boundary.
68
+ * Convert BigInt values (better-sqlite3 can return lastInsertRowid as BigInt)
69
+ * to Number so consumers get plain numbers. Dates, Buffers and typed arrays
70
+ * pass through untouched — structured clone handles them natively, and
71
+ * recursing with Object.entries would mangle them (a Date has no enumerable
72
+ * props → {}; a Buffer would become a numeric-keyed plain object). Circular
73
+ * result graphs throw a clear error instead of a RangeError stack overflow.
66
74
  */
67
- function sanitizeForTransfer(obj) {
75
+ function sanitizeForTransfer(obj, seen) {
68
76
  if (obj === null || obj === undefined) return obj;
69
77
  if (typeof obj === 'bigint') return Number(obj);
70
- if (Array.isArray(obj)) return obj.map(sanitizeForTransfer);
71
- if (typeof obj === 'object') {
72
- const result = {};
73
- for (const [key, val] of Object.entries(obj)) {
74
- result[key] = sanitizeForTransfer(val);
75
- }
76
- return result;
78
+ if (typeof obj !== 'object') return obj;
79
+ if (obj instanceof Date || Buffer.isBuffer(obj) || ArrayBuffer.isView(obj)) return obj;
80
+ seen = seen || new WeakSet();
81
+ if (seen.has(obj)) {
82
+ throw new Error('DB worker result contains a circular reference and cannot cross the thread boundary');
77
83
  }
78
- return obj;
84
+ seen.add(obj);
85
+ if (Array.isArray(obj)) return obj.map((v) => sanitizeForTransfer(v, seen));
86
+ const result = {};
87
+ for (const [key, val] of Object.entries(obj)) {
88
+ result[key] = sanitizeForTransfer(val, seen);
89
+ }
90
+ return result;
79
91
  }
80
92
 
81
93
  module.exports = { runWorker };