@aria-framework/db-worker 0.2.0 → 0.4.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.
- package/README.md +34 -6
- package/client.js +54 -10
- package/package.json +1 -1
- package/worker.js +46 -12
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,27 @@ Model methods may be sync or async (thenables are awaited). BigInts in results
|
|
|
105
112
|
|
|
106
113
|
## Changelog
|
|
107
114
|
|
|
115
|
+
- **0.4.0** — second-review fixes. (1) sanitizeForTransfer tracks the ancestor
|
|
116
|
+
PATH (unwind delete), so shared/diamond references in results are legal
|
|
117
|
+
again — only true cycles throw; the error path is also guarded so an
|
|
118
|
+
unserializable custom error prop degrades to message+stack instead of
|
|
119
|
+
hanging the call. (2) Death notification hardened: at-most-once latch
|
|
120
|
+
('error' + 'exit' both fire for one crash), `_closing` guard on the error
|
|
121
|
+
handler (a teardown-race error no longer turns a clean shutdown into a
|
|
122
|
+
crash exit), and boot failures reject init() instead of firing the policy.
|
|
123
|
+
(3) `queueWarnMs` saturation warning — fast-exec calls with long queue waits
|
|
124
|
+
now log, closing the observability hole the exec-only gate opened.
|
|
125
|
+
(4) execMs uses a monotonic clock (perf_hooks), immune to NTP steps.
|
|
126
|
+
- **0.3.0** — three review-driven fixes. (1) **`onWorkerDeath` policy hook**:
|
|
127
|
+
called after a non-deliberate worker death; without a policy the process
|
|
128
|
+
keeps running with every invoke() rejecting — a silent outage supervisors
|
|
129
|
+
can't see. Recommended app policy: log + `process.exit(1)`. (2) **Slow-call
|
|
130
|
+
timing moved into the worker**: the threshold now applies to execution time
|
|
131
|
+
(`execMs` shipped in each response), so calls queued behind a slow query no
|
|
132
|
+
longer log under their own names; the message shows `exec` and `total`.
|
|
133
|
+
(3) **Sanitizer hardened**: Date/Buffer/typed arrays pass through untouched
|
|
134
|
+
(structured clone handles them; recursing mangled them), and circular result
|
|
135
|
+
graphs throw a clear error instead of overflowing the stack.
|
|
108
136
|
- **0.2.0** — slow-call detection: `DbClient` warn-logs any invoke at or over
|
|
109
137
|
`slowMs` (default 500ms, 0 disables) with duration + `Model.method`. Turns
|
|
110
138
|
performance work measurement-driven — add the index when a real query names
|
package/client.js
CHANGED
|
@@ -20,18 +20,34 @@ 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
|
|
24
|
-
* takes at least this long ("Slow DB call (612ms
|
|
25
|
-
* queries name themselves before users
|
|
26
|
-
*
|
|
27
|
-
*
|
|
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 {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.
|
|
34
|
+
* @param {(info: {reason: 'error'|'exit', error?: Error, code?: number}) => void}
|
|
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
|
|
39
|
+
* supervisors keyed on process exit cannot see. Recommended app policy:
|
|
40
|
+
* set process.exitCode = 1 and trigger the app's graceful shutdown.
|
|
28
41
|
*/
|
|
29
|
-
constructor({ workerPath, logger, callTimeoutMs, slowMs } = {}) {
|
|
42
|
+
constructor({ workerPath, logger, callTimeoutMs, slowMs, queueWarnMs, onWorkerDeath } = {}) {
|
|
30
43
|
if (!workerPath) throw new Error('DbClient: workerPath is required');
|
|
31
44
|
this._workerPath = workerPath;
|
|
32
45
|
this._logger = logger || console;
|
|
33
46
|
this._callTimeoutMs = callTimeoutMs || 30 * 1000;
|
|
34
47
|
this._slowMs = slowMs === undefined ? 500 : slowMs;
|
|
48
|
+
this._queueWarnMs = queueWarnMs === undefined ? 1000 : queueWarnMs;
|
|
49
|
+
this._onWorkerDeath = typeof onWorkerDeath === 'function' ? onWorkerDeath : null;
|
|
50
|
+
this._deathNotified = false;
|
|
35
51
|
this._worker = null;
|
|
36
52
|
this._pending = new Map();
|
|
37
53
|
this._nextId = 0;
|
|
@@ -70,10 +86,17 @@ class DbClient {
|
|
|
70
86
|
if (!pending) return;
|
|
71
87
|
this._pending.delete(msg.id);
|
|
72
88
|
if (pending.timer) clearTimeout(pending.timer);
|
|
73
|
-
if (
|
|
74
|
-
const
|
|
75
|
-
if (
|
|
76
|
-
|
|
89
|
+
if (typeof msg.execMs === 'number') {
|
|
90
|
+
const total = Date.now() - pending.started;
|
|
91
|
+
if (this._slowMs && msg.execMs >= this._slowMs) {
|
|
92
|
+
// Threshold on worker-side execution time so calls queued behind a
|
|
93
|
+
// slow one don't log under their own (innocent) names; total shows
|
|
94
|
+
// the queue-wait pile-up.
|
|
95
|
+
this._logger.warn(`Slow DB call (${msg.execMs}ms exec, ${total}ms total): ${pending.label}`);
|
|
96
|
+
} 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`);
|
|
77
100
|
}
|
|
78
101
|
}
|
|
79
102
|
if (msg.error) {
|
|
@@ -88,8 +111,13 @@ class DbClient {
|
|
|
88
111
|
});
|
|
89
112
|
|
|
90
113
|
this._worker.on('error', (err) => {
|
|
114
|
+
// Deliberate close() in progress: pending calls were already rejected
|
|
115
|
+
// and the app initiated the teardown — a race-y error here must not
|
|
116
|
+
// fire the death policy (it would turn a clean shutdown into a crash).
|
|
117
|
+
if (this._closing) return;
|
|
91
118
|
this._logger.error('Database worker error: ' + err.message);
|
|
92
119
|
this._worker = null;
|
|
120
|
+
const wasBooting = !!this._initReject;
|
|
93
121
|
if (this._initReject) {
|
|
94
122
|
const r = this._initReject; this._initReject = null; r(err);
|
|
95
123
|
}
|
|
@@ -98,6 +126,9 @@ class DbClient {
|
|
|
98
126
|
p.reject(new Error('Database worker crashed: ' + err.message));
|
|
99
127
|
}
|
|
100
128
|
this._pending.clear();
|
|
129
|
+
// 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 });
|
|
101
132
|
});
|
|
102
133
|
|
|
103
134
|
this._worker.on('exit', (code) => {
|
|
@@ -107,6 +138,7 @@ class DbClient {
|
|
|
107
138
|
if (code !== 0) {
|
|
108
139
|
this._logger.error(`Database worker exited with code ${code}`);
|
|
109
140
|
this._worker = null;
|
|
141
|
+
const wasBooting = !!this._initReject;
|
|
110
142
|
if (this._initReject) {
|
|
111
143
|
const r = this._initReject; this._initReject = null;
|
|
112
144
|
r(new Error(`Database worker exited with code ${code}`));
|
|
@@ -116,11 +148,23 @@ class DbClient {
|
|
|
116
148
|
p.reject(new Error(`Database worker exited with code ${code}`));
|
|
117
149
|
}
|
|
118
150
|
this._pending.clear();
|
|
151
|
+
if (!wasBooting) this._notifyDeath({ reason: 'exit', code });
|
|
119
152
|
}
|
|
120
153
|
});
|
|
121
154
|
});
|
|
122
155
|
}
|
|
123
156
|
|
|
157
|
+
/** @private Invoke the app's worker-death policy — at most once, never throws.
|
|
158
|
+
* (A worker crash emits 'error' AND then 'exit'; without the latch a policy
|
|
159
|
+
* that doesn't hard-exit — respawn, metrics — would run twice per death.) */
|
|
160
|
+
_notifyDeath(info) {
|
|
161
|
+
if (!this._onWorkerDeath || this._deathNotified) return;
|
|
162
|
+
this._deathNotified = true;
|
|
163
|
+
try { this._onWorkerDeath(info); } catch (e) {
|
|
164
|
+
this._logger.error('onWorkerDeath handler threw: ' + e.message);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
124
168
|
/**
|
|
125
169
|
* Invoke a model method on the worker thread.
|
|
126
170
|
* @param {string} model
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aria-framework/db-worker",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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
|
@@ -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
|
|
@@ -35,6 +36,11 @@ function runWorker({ init }) {
|
|
|
35
36
|
|
|
36
37
|
parentPort.on('message', async (msg) => {
|
|
37
38
|
const { id, model, method, args } = msg;
|
|
39
|
+
// Worker-side execution time, shipped back so the client's slow-call log
|
|
40
|
+
// attributes slowness to the query that WAS slow, not to calls that were
|
|
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();
|
|
38
44
|
try {
|
|
39
45
|
const target = models[model];
|
|
40
46
|
if (!target) throw new Error(`Unknown model: ${model}`);
|
|
@@ -48,11 +54,21 @@ function runWorker({ init }) {
|
|
|
48
54
|
}
|
|
49
55
|
|
|
50
56
|
result = sanitizeForTransfer(result);
|
|
51
|
-
parentPort.postMessage({ id, result });
|
|
57
|
+
parentPort.postMessage({ id, result, execMs: Math.round(performance.now() - t0) });
|
|
52
58
|
} catch (err) {
|
|
53
59
|
// Preserve custom error props (e.g. code, status, entity ids) across the
|
|
54
|
-
// boundary — message/stack aren't enumerable, so the spread adds only
|
|
55
|
-
|
|
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) });
|
|
56
72
|
}
|
|
57
73
|
});
|
|
58
74
|
} catch (err) {
|
|
@@ -61,21 +77,39 @@ function runWorker({ init }) {
|
|
|
61
77
|
}
|
|
62
78
|
|
|
63
79
|
/**
|
|
64
|
-
* Convert BigInt values (better-sqlite3
|
|
65
|
-
* Number so
|
|
80
|
+
* Convert BigInt values (better-sqlite3 can return lastInsertRowid as BigInt)
|
|
81
|
+
* to Number so consumers get plain numbers. Dates, Buffers and typed arrays
|
|
82
|
+
* pass through untouched — structured clone handles them natively, and
|
|
83
|
+
* recursing with Object.entries would mangle them (a Date has no enumerable
|
|
84
|
+
* props → {}; a Buffer would become a numeric-keyed plain object). Circular
|
|
85
|
+
* result graphs throw a clear error instead of a RangeError stack overflow.
|
|
66
86
|
*/
|
|
67
|
-
function sanitizeForTransfer(obj) {
|
|
87
|
+
function sanitizeForTransfer(obj, seen) {
|
|
68
88
|
if (obj === null || obj === undefined) return obj;
|
|
69
89
|
if (typeof obj === 'bigint') return Number(obj);
|
|
70
|
-
if (
|
|
71
|
-
if (
|
|
72
|
-
|
|
90
|
+
if (typeof obj !== 'object') return obj;
|
|
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)) {
|
|
99
|
+
throw new Error('DB worker result contains a circular reference and cannot cross the thread boundary');
|
|
100
|
+
}
|
|
101
|
+
seen.add(obj);
|
|
102
|
+
let result;
|
|
103
|
+
if (Array.isArray(obj)) {
|
|
104
|
+
result = obj.map((v) => sanitizeForTransfer(v, seen));
|
|
105
|
+
} else {
|
|
106
|
+
result = {};
|
|
73
107
|
for (const [key, val] of Object.entries(obj)) {
|
|
74
|
-
result[key] = sanitizeForTransfer(val);
|
|
108
|
+
result[key] = sanitizeForTransfer(val, seen);
|
|
75
109
|
}
|
|
76
|
-
return result;
|
|
77
110
|
}
|
|
78
|
-
|
|
111
|
+
seen.delete(obj);
|
|
112
|
+
return result;
|
|
79
113
|
}
|
|
80
114
|
|
|
81
115
|
module.exports = { runWorker };
|