@aria-framework/db-worker 0.3.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 +24 -6
- package/client.js +38 -14
- package/package.json +1 -1
- package/worker.js +31 -9
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,17 @@ 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.
|
|
108
126
|
- **0.3.0** — three review-driven fixes. (1) **`onWorkerDeath` policy hook**:
|
|
109
127
|
called after a non-deliberate worker death; without a policy the process
|
|
110
128
|
keeps running with every invoke() rejecting — a silent outage supervisors
|
package/client.js
CHANGED
|
@@ -27,20 +27,27 @@ 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;
|
|
44
51
|
this._worker = null;
|
|
45
52
|
this._pending = new Map();
|
|
46
53
|
this._nextId = 0;
|
|
@@ -79,12 +86,18 @@ class DbClient {
|
|
|
79
86
|
if (!pending) return;
|
|
80
87
|
this._pending.delete(msg.id);
|
|
81
88
|
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.
|
|
89
|
+
if (typeof msg.execMs === 'number') {
|
|
86
90
|
const total = Date.now() - pending.started;
|
|
87
|
-
this.
|
|
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`);
|
|
100
|
+
}
|
|
88
101
|
}
|
|
89
102
|
if (msg.error) {
|
|
90
103
|
const err = new Error(msg.error.message);
|
|
@@ -98,8 +111,13 @@ class DbClient {
|
|
|
98
111
|
});
|
|
99
112
|
|
|
100
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;
|
|
101
118
|
this._logger.error('Database worker error: ' + err.message);
|
|
102
119
|
this._worker = null;
|
|
120
|
+
const wasBooting = !!this._initReject;
|
|
103
121
|
if (this._initReject) {
|
|
104
122
|
const r = this._initReject; this._initReject = null; r(err);
|
|
105
123
|
}
|
|
@@ -108,7 +126,9 @@ class DbClient {
|
|
|
108
126
|
p.reject(new Error('Database worker crashed: ' + err.message));
|
|
109
127
|
}
|
|
110
128
|
this._pending.clear();
|
|
111
|
-
|
|
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 });
|
|
112
132
|
});
|
|
113
133
|
|
|
114
134
|
this._worker.on('exit', (code) => {
|
|
@@ -118,6 +138,7 @@ class DbClient {
|
|
|
118
138
|
if (code !== 0) {
|
|
119
139
|
this._logger.error(`Database worker exited with code ${code}`);
|
|
120
140
|
this._worker = null;
|
|
141
|
+
const wasBooting = !!this._initReject;
|
|
121
142
|
if (this._initReject) {
|
|
122
143
|
const r = this._initReject; this._initReject = null;
|
|
123
144
|
r(new Error(`Database worker exited with code ${code}`));
|
|
@@ -127,15 +148,18 @@ class DbClient {
|
|
|
127
148
|
p.reject(new Error(`Database worker exited with code ${code}`));
|
|
128
149
|
}
|
|
129
150
|
this._pending.clear();
|
|
130
|
-
this._notifyDeath({ reason: 'exit', code });
|
|
151
|
+
if (!wasBooting) this._notifyDeath({ reason: 'exit', code });
|
|
131
152
|
}
|
|
132
153
|
});
|
|
133
154
|
});
|
|
134
155
|
}
|
|
135
156
|
|
|
136
|
-
/** @private Invoke the app's worker-death policy
|
|
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.) */
|
|
137
160
|
_notifyDeath(info) {
|
|
138
|
-
if (!this._onWorkerDeath) return;
|
|
161
|
+
if (!this._onWorkerDeath || this._deathNotified) return;
|
|
162
|
+
this._deathNotified = true;
|
|
139
163
|
try { this._onWorkerDeath(info); } catch (e) {
|
|
140
164
|
this._logger.error('onWorkerDeath handler threw: ' + e.message);
|
|
141
165
|
}
|
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
|
|
@@ -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) {
|
|
@@ -77,16 +89,26 @@ function sanitizeForTransfer(obj, seen) {
|
|
|
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;
|
|
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.
|
|
80
97
|
seen = seen || new WeakSet();
|
|
81
98
|
if (seen.has(obj)) {
|
|
82
99
|
throw new Error('DB worker result contains a circular reference and cannot cross the thread boundary');
|
|
83
100
|
}
|
|
84
101
|
seen.add(obj);
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
102
|
+
let result;
|
|
103
|
+
if (Array.isArray(obj)) {
|
|
104
|
+
result = obj.map((v) => sanitizeForTransfer(v, seen));
|
|
105
|
+
} else {
|
|
106
|
+
result = {};
|
|
107
|
+
for (const [key, val] of Object.entries(obj)) {
|
|
108
|
+
result[key] = sanitizeForTransfer(val, seen);
|
|
109
|
+
}
|
|
89
110
|
}
|
|
111
|
+
seen.delete(obj);
|
|
90
112
|
return result;
|
|
91
113
|
}
|
|
92
114
|
|