@aria-framework/db-worker 0.3.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.
- package/README.md +36 -6
- package/client.js +67 -14
- package/package.json +1 -1
- package/worker.js +40 -13
package/README.md
CHANGED
|
@@ -74,12 +74,19 @@ 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, slowMs? = 500 })`
|
|
78
|
-
- `slowMs`: any invoke whose
|
|
79
|
-
warn-logged — `Slow DB call (612ms): Ticket.queue` —
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
77
|
+
- `new DbClient({ workerPath, logger?, callTimeoutMs? = 30000, slowMs? = 500, queueWarnMs? = 1000, onWorkerDeath? })`
|
|
78
|
+
- `slowMs`: any invoke whose worker-side EXECUTION takes at least this long
|
|
79
|
+
is warn-logged — `Slow DB call (612ms exec, 1840ms total): Ticket.queue` —
|
|
80
|
+
attributing slowness to the query that was slow, not to calls queued
|
|
81
|
+
behind it. Pass `0` to disable.
|
|
82
|
+
- `queueWarnMs`: the saturation signal — a call that executed fast but
|
|
83
|
+
waited in the queue at least this long logs
|
|
84
|
+
`Slow DB queue (988ms wait, 5ms exec): Model.method`. Catches a worker
|
|
85
|
+
drowning in individually-fast queries. Pass `0` to disable.
|
|
86
|
+
- `onWorkerDeath(info)`: fired AT MOST ONCE on a non-deliberate post-boot
|
|
87
|
+
worker death (never on `close()`, never for boot failures — those reject
|
|
88
|
+
`init()`). Recommended policy: `process.exitCode = 1` + trigger your
|
|
89
|
+
graceful shutdown so a supervisor restarts the service.
|
|
83
90
|
- `init(workerData)` → Promise; rejects on worker boot failure (`init-error`)
|
|
84
91
|
- `invoke(model, method, ...args)` → Promise. Args/results must be
|
|
85
92
|
structured-clone serializable. Per-call timeout; on worker crash/exit ALL
|
|
@@ -105,6 +112,29 @@ Model methods may be sync or async (thenables are awaited). BigInts in results
|
|
|
105
112
|
|
|
106
113
|
## Changelog
|
|
107
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.
|
|
127
|
+
- **0.4.0** — second-review fixes. (1) sanitizeForTransfer tracks the ancestor
|
|
128
|
+
PATH (unwind delete), so shared/diamond references in results are legal
|
|
129
|
+
again — only true cycles throw; the error path is also guarded so an
|
|
130
|
+
unserializable custom error prop degrades to message+stack instead of
|
|
131
|
+
hanging the call. (2) Death notification hardened: at-most-once latch
|
|
132
|
+
('error' + 'exit' both fire for one crash), `_closing` guard on the error
|
|
133
|
+
handler (a teardown-race error no longer turns a clean shutdown into a
|
|
134
|
+
crash exit), and boot failures reject init() instead of firing the policy.
|
|
135
|
+
(3) `queueWarnMs` saturation warning — fast-exec calls with long queue waits
|
|
136
|
+
now log, closing the observability hole the exec-only gate opened.
|
|
137
|
+
(4) execMs uses a monotonic clock (perf_hooks), immune to NTP steps.
|
|
108
138
|
- **0.3.0** — three review-driven fixes. (1) **`onWorkerDeath` policy hook**:
|
|
109
139
|
called after a non-deliberate worker death; without a policy the process
|
|
110
140
|
keeps running with every invoke() rejecting — a silent outage supervisors
|
package/client.js
CHANGED
|
@@ -27,20 +27,33 @@ class DbClient {
|
|
|
27
27
|
* fast calls queued behind a slow one are not misattributed; the total
|
|
28
28
|
* round trip is shown alongside so pile-ups are still visible. Pass 0 to
|
|
29
29
|
* disable.
|
|
30
|
+
* @param {number} [opts.queueWarnMs=1000] - Warn when a call's QUEUE WAIT
|
|
31
|
+
* (total round trip minus execution) reaches this — the saturation signal:
|
|
32
|
+
* a worker drowning in individually-fast queries logs nothing under the
|
|
33
|
+
* exec-time gate alone. Pass 0 to disable.
|
|
30
34
|
* @param {(info: {reason: 'error'|'exit', error?: Error, code?: number}) => void}
|
|
31
|
-
* [opts.onWorkerDeath] - Called after a
|
|
32
|
-
*
|
|
33
|
-
*
|
|
35
|
+
* [opts.onWorkerDeath] - Called AT MOST ONCE after a non-deliberate worker
|
|
36
|
+
* death post-boot (never on close(); never for boot failures, which reject
|
|
37
|
+
* init() so the app's startup error handling owns them). Without a policy
|
|
38
|
+
* the process keeps running with every invoke() rejecting — a silent outage
|
|
34
39
|
* supervisors keyed on process exit cannot see. Recommended app policy:
|
|
35
|
-
*
|
|
40
|
+
* set process.exitCode = 1 and trigger the app's graceful shutdown.
|
|
36
41
|
*/
|
|
37
|
-
constructor({ workerPath, logger, callTimeoutMs, slowMs, onWorkerDeath } = {}) {
|
|
42
|
+
constructor({ workerPath, logger, callTimeoutMs, slowMs, queueWarnMs, onWorkerDeath } = {}) {
|
|
38
43
|
if (!workerPath) throw new Error('DbClient: workerPath is required');
|
|
39
44
|
this._workerPath = workerPath;
|
|
40
45
|
this._logger = logger || console;
|
|
41
46
|
this._callTimeoutMs = callTimeoutMs || 30 * 1000;
|
|
42
47
|
this._slowMs = slowMs === undefined ? 500 : slowMs;
|
|
48
|
+
this._queueWarnMs = queueWarnMs === undefined ? 1000 : queueWarnMs;
|
|
43
49
|
this._onWorkerDeath = typeof onWorkerDeath === 'function' ? onWorkerDeath : null;
|
|
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;
|
|
44
57
|
this._worker = null;
|
|
45
58
|
this._pending = new Map();
|
|
46
59
|
this._nextId = 0;
|
|
@@ -56,6 +69,12 @@ class DbClient {
|
|
|
56
69
|
*/
|
|
57
70
|
init(workerData) {
|
|
58
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;
|
|
59
78
|
this._worker = new Worker(this._workerPath, { workerData });
|
|
60
79
|
this._initReject = reject;
|
|
61
80
|
|
|
@@ -79,12 +98,30 @@ class DbClient {
|
|
|
79
98
|
if (!pending) return;
|
|
80
99
|
this._pending.delete(msg.id);
|
|
81
100
|
if (pending.timer) clearTimeout(pending.timer);
|
|
82
|
-
if (
|
|
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.
|
|
101
|
+
if (typeof msg.execMs === 'number') {
|
|
86
102
|
const total = Date.now() - pending.started;
|
|
87
|
-
this.
|
|
103
|
+
if (this._slowMs && msg.execMs >= this._slowMs) {
|
|
104
|
+
// Threshold on worker-side execution time so calls queued behind a
|
|
105
|
+
// slow one don't log under their own (innocent) names; total shows
|
|
106
|
+
// the queue-wait pile-up.
|
|
107
|
+
this._logger.warn(`Slow DB call (${msg.execMs}ms exec, ${total}ms total): ${pending.label}`);
|
|
108
|
+
} else if (this._queueWarnMs && (total - msg.execMs) >= this._queueWarnMs) {
|
|
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
|
+
}
|
|
124
|
+
}
|
|
88
125
|
}
|
|
89
126
|
if (msg.error) {
|
|
90
127
|
const err = new Error(msg.error.message);
|
|
@@ -98,8 +135,13 @@ class DbClient {
|
|
|
98
135
|
});
|
|
99
136
|
|
|
100
137
|
this._worker.on('error', (err) => {
|
|
138
|
+
// Deliberate close() in progress: pending calls were already rejected
|
|
139
|
+
// and the app initiated the teardown — a race-y error here must not
|
|
140
|
+
// fire the death policy (it would turn a clean shutdown into a crash).
|
|
141
|
+
if (this._closing) return;
|
|
101
142
|
this._logger.error('Database worker error: ' + err.message);
|
|
102
143
|
this._worker = null;
|
|
144
|
+
const wasBooting = !!this._initReject;
|
|
103
145
|
if (this._initReject) {
|
|
104
146
|
const r = this._initReject; this._initReject = null; r(err);
|
|
105
147
|
}
|
|
@@ -108,7 +150,13 @@ class DbClient {
|
|
|
108
150
|
p.reject(new Error('Database worker crashed: ' + err.message));
|
|
109
151
|
}
|
|
110
152
|
this._pending.clear();
|
|
111
|
-
|
|
153
|
+
// Boot failures reject init() — the app's startup error handling owns
|
|
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 });
|
|
112
160
|
});
|
|
113
161
|
|
|
114
162
|
this._worker.on('exit', (code) => {
|
|
@@ -118,6 +166,7 @@ class DbClient {
|
|
|
118
166
|
if (code !== 0) {
|
|
119
167
|
this._logger.error(`Database worker exited with code ${code}`);
|
|
120
168
|
this._worker = null;
|
|
169
|
+
const wasBooting = !!this._initReject;
|
|
121
170
|
if (this._initReject) {
|
|
122
171
|
const r = this._initReject; this._initReject = null;
|
|
123
172
|
r(new Error(`Database worker exited with code ${code}`));
|
|
@@ -127,15 +176,19 @@ class DbClient {
|
|
|
127
176
|
p.reject(new Error(`Database worker exited with code ${code}`));
|
|
128
177
|
}
|
|
129
178
|
this._pending.clear();
|
|
130
|
-
this.
|
|
179
|
+
if (wasBooting) this._deathNotified = true;
|
|
180
|
+
else this._notifyDeath({ reason: 'exit', code });
|
|
131
181
|
}
|
|
132
182
|
});
|
|
133
183
|
});
|
|
134
184
|
}
|
|
135
185
|
|
|
136
|
-
/** @private Invoke the app's worker-death policy
|
|
186
|
+
/** @private Invoke the app's worker-death policy — at most once, never throws.
|
|
187
|
+
* (A worker crash emits 'error' AND then 'exit'; without the latch a policy
|
|
188
|
+
* that doesn't hard-exit — respawn, metrics — would run twice per death.) */
|
|
137
189
|
_notifyDeath(info) {
|
|
138
|
-
if (!this._onWorkerDeath) return;
|
|
190
|
+
if (!this._onWorkerDeath || this._deathNotified) return;
|
|
191
|
+
this._deathNotified = true;
|
|
139
192
|
try { this._onWorkerDeath(info); } catch (e) {
|
|
140
193
|
this._logger.error('onWorkerDeath handler threw: ' + e.message);
|
|
141
194
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aria-framework/db-worker",
|
|
3
|
-
"version": "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
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
20
|
const { parentPort, workerData } = require('worker_threads');
|
|
21
|
+
const { performance } = require('perf_hooks');
|
|
21
22
|
|
|
22
23
|
/**
|
|
23
24
|
* @param {Object} opts
|
|
@@ -37,8 +38,9 @@ function runWorker({ init }) {
|
|
|
37
38
|
const { id, model, method, args } = msg;
|
|
38
39
|
// Worker-side execution time, shipped back so the client's slow-call log
|
|
39
40
|
// attributes slowness to the query that WAS slow, not to calls that were
|
|
40
|
-
// merely queued behind it.
|
|
41
|
-
|
|
41
|
+
// merely queued behind it. Monotonic clock: a wall-clock (Date.now) delta
|
|
42
|
+
// would be corrupted by an NTP step mid-query.
|
|
43
|
+
const t0 = performance.now();
|
|
42
44
|
try {
|
|
43
45
|
const target = models[model];
|
|
44
46
|
if (!target) throw new Error(`Unknown model: ${model}`);
|
|
@@ -52,11 +54,21 @@ function runWorker({ init }) {
|
|
|
52
54
|
}
|
|
53
55
|
|
|
54
56
|
result = sanitizeForTransfer(result);
|
|
55
|
-
parentPort.postMessage({ id, result, execMs:
|
|
57
|
+
parentPort.postMessage({ id, result, execMs: Math.round(performance.now() - t0) });
|
|
56
58
|
} catch (err) {
|
|
57
59
|
// Preserve custom error props (e.g. code, status, entity ids) across the
|
|
58
|
-
// boundary — message/stack aren't enumerable, so the spread adds only
|
|
59
|
-
|
|
60
|
+
// boundary — message/stack aren't enumerable, so the spread adds only
|
|
61
|
+
// extras. Guarded: if the custom props themselves can't be serialized
|
|
62
|
+
// (a true cycle), fall back to message+stack rather than throwing
|
|
63
|
+
// inside the catch — an unposted message would hang the client until
|
|
64
|
+
// its call timeout.
|
|
65
|
+
let payload;
|
|
66
|
+
try {
|
|
67
|
+
payload = sanitizeForTransfer({ message: err.message, stack: err.stack, ...err });
|
|
68
|
+
} catch (_) {
|
|
69
|
+
payload = { message: err.message, stack: err.stack };
|
|
70
|
+
}
|
|
71
|
+
parentPort.postMessage({ id, error: payload, execMs: Math.round(performance.now() - t0) });
|
|
60
72
|
}
|
|
61
73
|
});
|
|
62
74
|
} catch (err) {
|
|
@@ -72,21 +84,36 @@ function runWorker({ init }) {
|
|
|
72
84
|
* props → {}; a Buffer would become a numeric-keyed plain object). Circular
|
|
73
85
|
* result graphs throw a clear error instead of a RangeError stack overflow.
|
|
74
86
|
*/
|
|
75
|
-
function sanitizeForTransfer(obj,
|
|
87
|
+
function sanitizeForTransfer(obj, ctx) {
|
|
76
88
|
if (obj === null || obj === undefined) return obj;
|
|
77
89
|
if (typeof obj === 'bigint') return Number(obj);
|
|
78
90
|
if (typeof obj !== 'object') return obj;
|
|
79
91
|
if (obj instanceof Date || Buffer.isBuffer(obj) || ArrayBuffer.isView(obj)) return obj;
|
|
80
|
-
|
|
81
|
-
|
|
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)) {
|
|
82
100
|
throw new Error('DB worker result contains a circular reference and cannot cross the thread boundary');
|
|
83
101
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
result
|
|
102
|
+
if (ctx.memo.has(obj)) return ctx.memo.get(obj);
|
|
103
|
+
ctx.path.add(obj);
|
|
104
|
+
let result;
|
|
105
|
+
if (Array.isArray(obj)) {
|
|
106
|
+
result = [];
|
|
107
|
+
ctx.memo.set(obj, result);
|
|
108
|
+
for (const v of obj) result.push(sanitizeForTransfer(v, ctx));
|
|
109
|
+
} else {
|
|
110
|
+
result = {};
|
|
111
|
+
ctx.memo.set(obj, result);
|
|
112
|
+
for (const [key, val] of Object.entries(obj)) {
|
|
113
|
+
result[key] = sanitizeForTransfer(val, ctx);
|
|
114
|
+
}
|
|
89
115
|
}
|
|
116
|
+
ctx.path.delete(obj);
|
|
90
117
|
return result;
|
|
91
118
|
}
|
|
92
119
|
|