@aria-framework/db-worker 0.1.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 +20 -1
  2. package/client.js +34 -2
  3. package/package.json +1 -1
  4. package/worker.js +25 -13
package/README.md CHANGED
@@ -74,7 +74,12 @@ once the worker has opened the DB and run migrations.
74
74
  ## API
75
75
 
76
76
  ### `DbClient` (main thread)
77
- - `new DbClient({ workerPath, logger?, callTimeoutMs? = 30000 })`
77
+ - `new DbClient({ workerPath, logger?, callTimeoutMs? = 30000, slowMs? = 500 })`
78
+ - `slowMs`: any invoke whose round trip takes at least this long is
79
+ warn-logged — `Slow DB call (612ms): Ticket.queue` — so slow queries name
80
+ themselves in every app before users complain. The measurement includes
81
+ worker queue wait, so one slow query backing up others is visible as a
82
+ pile-up. Pass `0` to disable.
78
83
  - `init(workerData)` → Promise; rejects on worker boot failure (`init-error`)
79
84
  - `invoke(model, method, ...args)` → Promise. Args/results must be
80
85
  structured-clone serializable. Per-call timeout; on worker crash/exit ALL
@@ -100,6 +105,20 @@ Model methods may be sync or async (thenables are awaited). BigInts in results
100
105
 
101
106
  ## Changelog
102
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.
118
+ - **0.2.0** — slow-call detection: `DbClient` warn-logs any invoke at or over
119
+ `slowMs` (default 500ms, 0 disables) with duration + `Model.method`. Turns
120
+ performance work measurement-driven — add the index when a real query names
121
+ itself, not speculatively.
103
122
  - **0.1.0** — first release. Extracted from Support101/Acc101
104
123
  `lib/{database,db-client,db-worker}.js`. Changes vs the app originals: model
105
124
  registry + boot moved to the app's `init()` callback; migrations dir is an
package/client.js CHANGED
@@ -20,12 +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 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.
23
36
  */
24
- constructor({ workerPath, logger, callTimeoutMs } = {}) {
37
+ constructor({ workerPath, logger, callTimeoutMs, slowMs, onWorkerDeath } = {}) {
25
38
  if (!workerPath) throw new Error('DbClient: workerPath is required');
26
39
  this._workerPath = workerPath;
27
40
  this._logger = logger || console;
28
41
  this._callTimeoutMs = callTimeoutMs || 30 * 1000;
42
+ this._slowMs = slowMs === undefined ? 500 : slowMs;
43
+ this._onWorkerDeath = typeof onWorkerDeath === 'function' ? onWorkerDeath : null;
29
44
  this._worker = null;
30
45
  this._pending = new Map();
31
46
  this._nextId = 0;
@@ -64,6 +79,13 @@ class DbClient {
64
79
  if (!pending) return;
65
80
  this._pending.delete(msg.id);
66
81
  if (pending.timer) clearTimeout(pending.timer);
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}`);
88
+ }
67
89
  if (msg.error) {
68
90
  const err = new Error(msg.error.message);
69
91
  err.stack = msg.error.stack;
@@ -86,6 +108,7 @@ class DbClient {
86
108
  p.reject(new Error('Database worker crashed: ' + err.message));
87
109
  }
88
110
  this._pending.clear();
111
+ this._notifyDeath({ reason: 'error', error: err });
89
112
  });
90
113
 
91
114
  this._worker.on('exit', (code) => {
@@ -104,11 +127,20 @@ class DbClient {
104
127
  p.reject(new Error(`Database worker exited with code ${code}`));
105
128
  }
106
129
  this._pending.clear();
130
+ this._notifyDeath({ reason: 'exit', code });
107
131
  }
108
132
  });
109
133
  });
110
134
  }
111
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
+
112
144
  /**
113
145
  * Invoke a model method on the worker thread.
114
146
  * @param {string} model
@@ -132,7 +164,7 @@ class DbClient {
132
164
  reject(new Error(`DB call timed out after ${this._callTimeoutMs}ms: ${model}.${method}`));
133
165
  }
134
166
  }, this._callTimeoutMs);
135
- this._pending.set(id, { resolve, reject, timer });
167
+ this._pending.set(id, { resolve, reject, timer, started: Date.now(), label: `${model}.${method}` });
136
168
  this._worker.postMessage({ id, model, method, args });
137
169
  });
138
170
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.1.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 };