@aria-framework/db-worker 0.1.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 +107 -0
- package/client.js +158 -0
- package/database.js +117 -0
- package/index.js +16 -0
- package/package.json +23 -0
- package/worker.js +81 -0
package/README.md
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# @aria-framework/db-worker
|
|
2
|
+
|
|
3
|
+
Aria App Framework — db-worker module. The async RPC bridge over synchronous
|
|
4
|
+
better-sqlite3: all SQLite work runs in a worker thread so a query can never
|
|
5
|
+
block the main (Express) event loop, and routes get a plain
|
|
6
|
+
`await db.invoke('Model', 'method', ...args)`.
|
|
7
|
+
|
|
8
|
+
```
|
|
9
|
+
Main thread Worker thread
|
|
10
|
+
DbClient.invoke('Ticket','create',…) ─► runWorker dispatch → models.Ticket.create(…)
|
|
11
|
+
result ◄───────────────── database.getDb() runs the SQL
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Plain CommonJS, no build step. `better-sqlite3` is a **peer dependency**.
|
|
15
|
+
|
|
16
|
+
## What the app keeps (three thin files)
|
|
17
|
+
|
|
18
|
+
Node spawns a worker from a **file path**, and the model registry + caches are
|
|
19
|
+
app-specific — so the app keeps thin wrappers and the package owns the ~350
|
|
20
|
+
lines of lifecycle/RPC/migration machinery.
|
|
21
|
+
|
|
22
|
+
**1. Worker entry (`lib/db-worker.js`)** — boot + registry:
|
|
23
|
+
|
|
24
|
+
```js
|
|
25
|
+
const path = require('path');
|
|
26
|
+
const { runWorker, database } = require('@aria-framework/db-worker');
|
|
27
|
+
|
|
28
|
+
runWorker({
|
|
29
|
+
init(workerData) {
|
|
30
|
+
database.init(workerData.dbPath, { logger });
|
|
31
|
+
database.runMigrations(path.join(__dirname, '..', 'migrations'));
|
|
32
|
+
// app-specific extras (e.g. wire field encryption from workerData.fieldsKey)
|
|
33
|
+
return {
|
|
34
|
+
Ticket: require('../models/Ticket'),
|
|
35
|
+
User: require('../models/User')
|
|
36
|
+
// ... every model reachable via invoke()
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
**2. Client singleton (`lib/db-client.js`)** — subclass for app caches:
|
|
43
|
+
|
|
44
|
+
```js
|
|
45
|
+
const path = require('path');
|
|
46
|
+
const { DbClient } = require('@aria-framework/db-worker');
|
|
47
|
+
|
|
48
|
+
class AppDbClient extends DbClient {
|
|
49
|
+
// add synchronous caches here (values hot paths read per-request)
|
|
50
|
+
}
|
|
51
|
+
module.exports = new AppDbClient({
|
|
52
|
+
workerPath: path.join(__dirname, 'db-worker.js'),
|
|
53
|
+
logger
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**3. Database wrapper (`lib/database.js`)** — so models keep requiring
|
|
58
|
+
`../lib/database` and the migrations dir is configured once:
|
|
59
|
+
|
|
60
|
+
```js
|
|
61
|
+
const path = require('path');
|
|
62
|
+
const { database } = require('@aria-framework/db-worker');
|
|
63
|
+
module.exports = {
|
|
64
|
+
init: (dbPath) => database.init(dbPath, { logger }),
|
|
65
|
+
runMigrations: () => database.runMigrations(path.join(__dirname, '..', 'migrations')),
|
|
66
|
+
getDb: database.getDb,
|
|
67
|
+
close: database.close
|
|
68
|
+
};
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Boot: `await dbClient.init({ dbPath, ...anythingTheWorkerNeeds })` — resolves
|
|
72
|
+
once the worker has opened the DB and run migrations.
|
|
73
|
+
|
|
74
|
+
## API
|
|
75
|
+
|
|
76
|
+
### `DbClient` (main thread)
|
|
77
|
+
- `new DbClient({ workerPath, logger?, callTimeoutMs? = 30000 })`
|
|
78
|
+
- `init(workerData)` → Promise; rejects on worker boot failure (`init-error`)
|
|
79
|
+
- `invoke(model, method, ...args)` → Promise. Args/results must be
|
|
80
|
+
structured-clone serializable. Per-call timeout; on worker crash/exit ALL
|
|
81
|
+
in-flight calls reject (nothing hangs). Custom error props set by models
|
|
82
|
+
(`code`, `status`, entity ids…) survive the thread boundary.
|
|
83
|
+
- `close()` — rejects in-flight calls, terminates the worker quietly.
|
|
84
|
+
|
|
85
|
+
### `runWorker({ init })` (worker entry)
|
|
86
|
+
`init(workerData)` does all boot and returns the model registry. Any model the
|
|
87
|
+
app calls via invoke MUST be in the registry ("Unknown model" otherwise).
|
|
88
|
+
Model methods may be sync or async (thenables are awaited). BigInts in results
|
|
89
|
+
(better-sqlite3 `lastInsertRowid`) are converted to Number.
|
|
90
|
+
|
|
91
|
+
### `database` (worker side, singleton per thread)
|
|
92
|
+
- `init(dbPath, { logger?, onOpen? })` — creates the directory, opens the DB,
|
|
93
|
+
then applies pragmas `WAL / synchronous=NORMAL / foreign_keys=ON /
|
|
94
|
+
busy_timeout=5000` and creates the `migrations` tracking table.
|
|
95
|
+
**`onOpen(db)` runs FIRST, before any pragma or table access** — this is the
|
|
96
|
+
SQLCipher hook: an encrypted DB needs `pragma key` before anything touches it.
|
|
97
|
+
- `runMigrations(migrationsDir)` — applies `*.sql` sorted by filename, each in
|
|
98
|
+
a transaction with its tracking-row insert; already-applied files skipped.
|
|
99
|
+
- `getDb()` / `close()`
|
|
100
|
+
|
|
101
|
+
## Changelog
|
|
102
|
+
|
|
103
|
+
- **0.1.0** — first release. Extracted from Support101/Acc101
|
|
104
|
+
`lib/{database,db-client,db-worker}.js`. Changes vs the app originals: model
|
|
105
|
+
registry + boot moved to the app's `init()` callback; migrations dir is an
|
|
106
|
+
argument; `DbClient` is a class (apps subclass + instantiate); new `onOpen`
|
|
107
|
+
hook absorbs Acc101's SQLCipher-key variant.
|
package/client.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Database Client — main thread.
|
|
3
|
+
*
|
|
4
|
+
* Spawns the DB worker thread and routes model calls to it:
|
|
5
|
+
* `await client.invoke('Model', 'method', ...args)`
|
|
6
|
+
*
|
|
7
|
+
* Owns the ugly lifecycle: per-call timeout (a stuck worker would otherwise
|
|
8
|
+
* leak {resolve,reject} and the response objects they close over), rejection
|
|
9
|
+
* of all in-flight calls on worker crash/exit, and quiet deliberate close().
|
|
10
|
+
*
|
|
11
|
+
* Apps subclass to add their own synchronous caches (values read on hot paths
|
|
12
|
+
* that shouldn't pay a thread round-trip per request) and export a singleton.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const { Worker } = require('worker_threads');
|
|
16
|
+
|
|
17
|
+
class DbClient {
|
|
18
|
+
/**
|
|
19
|
+
* @param {Object} opts
|
|
20
|
+
* @param {string} opts.workerPath - Absolute path to the app's worker entry file
|
|
21
|
+
* @param {Object} [opts.logger=console] - Logger with .info/.warn/.error
|
|
22
|
+
* @param {number} [opts.callTimeoutMs=30000] - Per-invoke timeout
|
|
23
|
+
*/
|
|
24
|
+
constructor({ workerPath, logger, callTimeoutMs } = {}) {
|
|
25
|
+
if (!workerPath) throw new Error('DbClient: workerPath is required');
|
|
26
|
+
this._workerPath = workerPath;
|
|
27
|
+
this._logger = logger || console;
|
|
28
|
+
this._callTimeoutMs = callTimeoutMs || 30 * 1000;
|
|
29
|
+
this._worker = null;
|
|
30
|
+
this._pending = new Map();
|
|
31
|
+
this._nextId = 0;
|
|
32
|
+
this._initReject = null;
|
|
33
|
+
this._closing = false; // set during deliberate close() so the forced
|
|
34
|
+
// terminate() exit isn't logged as a crash
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Initialize the worker thread.
|
|
39
|
+
* @param {Object} workerData - Passed verbatim to the worker (e.g. { dbPath, fieldsKey })
|
|
40
|
+
* @returns {Promise<void>} Resolves once the worker posts 'ready' (DB open + migrated)
|
|
41
|
+
*/
|
|
42
|
+
init(workerData) {
|
|
43
|
+
return new Promise((resolve, reject) => {
|
|
44
|
+
this._worker = new Worker(this._workerPath, { workerData });
|
|
45
|
+
this._initReject = reject;
|
|
46
|
+
|
|
47
|
+
const onReady = (msg) => {
|
|
48
|
+
if (msg.type === 'ready') {
|
|
49
|
+
this._worker.removeListener('message', onReady);
|
|
50
|
+
this._initReject = null;
|
|
51
|
+
this._logger.info('Database worker thread ready');
|
|
52
|
+
resolve();
|
|
53
|
+
} else if (msg.type === 'init-error') {
|
|
54
|
+
this._worker.removeListener('message', onReady);
|
|
55
|
+
this._initReject = null;
|
|
56
|
+
reject(new Error(msg.error));
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
this._worker.on('message', onReady);
|
|
60
|
+
|
|
61
|
+
this._worker.on('message', (msg) => {
|
|
62
|
+
if (msg.type === 'ready' || msg.type === 'init-error') return;
|
|
63
|
+
const pending = this._pending.get(msg.id);
|
|
64
|
+
if (!pending) return;
|
|
65
|
+
this._pending.delete(msg.id);
|
|
66
|
+
if (pending.timer) clearTimeout(pending.timer);
|
|
67
|
+
if (msg.error) {
|
|
68
|
+
const err = new Error(msg.error.message);
|
|
69
|
+
err.stack = msg.error.stack;
|
|
70
|
+
// Reattach custom props the model set (code, status, entity ids, …).
|
|
71
|
+
for (const k of Object.keys(msg.error)) { if (k !== 'message' && k !== 'stack') err[k] = msg.error[k]; }
|
|
72
|
+
pending.reject(err);
|
|
73
|
+
} else {
|
|
74
|
+
pending.resolve(msg.result);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
this._worker.on('error', (err) => {
|
|
79
|
+
this._logger.error('Database worker error: ' + err.message);
|
|
80
|
+
this._worker = null;
|
|
81
|
+
if (this._initReject) {
|
|
82
|
+
const r = this._initReject; this._initReject = null; r(err);
|
|
83
|
+
}
|
|
84
|
+
for (const [, p] of this._pending) {
|
|
85
|
+
if (p.timer) clearTimeout(p.timer);
|
|
86
|
+
p.reject(new Error('Database worker crashed: ' + err.message));
|
|
87
|
+
}
|
|
88
|
+
this._pending.clear();
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
this._worker.on('exit', (code) => {
|
|
92
|
+
// A deliberate close() terminates the worker with a non-zero code —
|
|
93
|
+
// that's expected, not a crash, so stay quiet.
|
|
94
|
+
if (this._closing) return;
|
|
95
|
+
if (code !== 0) {
|
|
96
|
+
this._logger.error(`Database worker exited with code ${code}`);
|
|
97
|
+
this._worker = null;
|
|
98
|
+
if (this._initReject) {
|
|
99
|
+
const r = this._initReject; this._initReject = null;
|
|
100
|
+
r(new Error(`Database worker exited with code ${code}`));
|
|
101
|
+
}
|
|
102
|
+
for (const [, p] of this._pending) {
|
|
103
|
+
if (p.timer) clearTimeout(p.timer);
|
|
104
|
+
p.reject(new Error(`Database worker exited with code ${code}`));
|
|
105
|
+
}
|
|
106
|
+
this._pending.clear();
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Invoke a model method on the worker thread.
|
|
114
|
+
* @param {string} model
|
|
115
|
+
* @param {string} method
|
|
116
|
+
* @param {...any} args - must be structured-clone serializable
|
|
117
|
+
* @returns {Promise<any>}
|
|
118
|
+
*/
|
|
119
|
+
invoke(model, method, ...args) {
|
|
120
|
+
if (!this._worker) {
|
|
121
|
+
return Promise.reject(new Error('Database worker not initialized'));
|
|
122
|
+
}
|
|
123
|
+
return new Promise((resolve, reject) => {
|
|
124
|
+
this._nextId = (this._nextId + 1) % Number.MAX_SAFE_INTEGER;
|
|
125
|
+
const id = this._nextId;
|
|
126
|
+
// A stuck worker would otherwise leak {resolve,reject} forever, holding
|
|
127
|
+
// the request and any closed-over response objects. Default 30s >> any
|
|
128
|
+
// healthy query.
|
|
129
|
+
const timer = setTimeout(() => {
|
|
130
|
+
if (this._pending.has(id)) {
|
|
131
|
+
this._pending.delete(id);
|
|
132
|
+
reject(new Error(`DB call timed out after ${this._callTimeoutMs}ms: ${model}.${method}`));
|
|
133
|
+
}
|
|
134
|
+
}, this._callTimeoutMs);
|
|
135
|
+
this._pending.set(id, { resolve, reject, timer });
|
|
136
|
+
this._worker.postMessage({ id, model, method, args });
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Terminate the worker thread. */
|
|
141
|
+
async close() {
|
|
142
|
+
if (this._worker) {
|
|
143
|
+
this._closing = true;
|
|
144
|
+
// Reject any in-flight calls so their callers (and the response objects
|
|
145
|
+
// they close over) are released rather than hanging until process exit.
|
|
146
|
+
for (const [, p] of this._pending) {
|
|
147
|
+
if (p.timer) clearTimeout(p.timer);
|
|
148
|
+
p.reject(new Error('Database worker is shutting down'));
|
|
149
|
+
}
|
|
150
|
+
this._pending.clear();
|
|
151
|
+
await this._worker.terminate();
|
|
152
|
+
this._worker = null;
|
|
153
|
+
this._logger.info('Database worker terminated');
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
module.exports = { DbClient };
|
package/database.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQLite layer — runs INSIDE the DB worker thread.
|
|
3
|
+
*
|
|
4
|
+
* Plain SQLite via better-sqlite3 (peer dependency), with a numbered-migration
|
|
5
|
+
* runner. Models require the consuming app's thin wrapper around this module
|
|
6
|
+
* and call getDb() synchronously.
|
|
7
|
+
*
|
|
8
|
+
* Canonical home: @aria-framework/db-worker (previously copy-pasted between
|
|
9
|
+
* apps as lib/database.js, with per-app drift around SQLCipher key handling —
|
|
10
|
+
* that variant is now the `onOpen` hook).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const Database = require('better-sqlite3');
|
|
14
|
+
const fs = require('fs');
|
|
15
|
+
const path = require('path');
|
|
16
|
+
|
|
17
|
+
let _db = null;
|
|
18
|
+
let _logger = console;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Open the database connection.
|
|
22
|
+
* @param {string} dbPath - Path to the SQLite database file
|
|
23
|
+
* @param {Object} [opts]
|
|
24
|
+
* @param {Object} [opts.logger=console] - Logger with .info/.warn/.error
|
|
25
|
+
* @param {(db: Database) => void} [opts.onOpen] - Runs immediately after open,
|
|
26
|
+
* BEFORE the standard pragmas and the migrations table. This is the hook for
|
|
27
|
+
* `pragma key` (SQLCipher) or any other must-run-first setup — an encrypted
|
|
28
|
+
* database cannot be touched at all until its key pragma is applied.
|
|
29
|
+
* @returns {Database} The better-sqlite3 database instance
|
|
30
|
+
*/
|
|
31
|
+
function init(dbPath, opts = {}) {
|
|
32
|
+
_logger = opts.logger || console;
|
|
33
|
+
|
|
34
|
+
const dir = path.dirname(dbPath);
|
|
35
|
+
if (!fs.existsSync(dir)) {
|
|
36
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
_db = new Database(dbPath);
|
|
40
|
+
|
|
41
|
+
if (typeof opts.onOpen === 'function') opts.onOpen(_db);
|
|
42
|
+
|
|
43
|
+
// Performance + safety pragmas. WAL gives concurrent readers + one writer;
|
|
44
|
+
// synchronous=NORMAL is the recommended pairing (FULL fsyncs every write).
|
|
45
|
+
_db.pragma('journal_mode = WAL');
|
|
46
|
+
_db.pragma('synchronous = NORMAL');
|
|
47
|
+
_db.pragma('foreign_keys = ON');
|
|
48
|
+
_db.pragma('busy_timeout = 5000');
|
|
49
|
+
|
|
50
|
+
// Migration tracking table.
|
|
51
|
+
_db.exec(`
|
|
52
|
+
CREATE TABLE IF NOT EXISTS migrations (
|
|
53
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
54
|
+
filename TEXT NOT NULL UNIQUE,
|
|
55
|
+
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
56
|
+
)
|
|
57
|
+
`);
|
|
58
|
+
|
|
59
|
+
_logger.info(`Database opened: ${dbPath}`);
|
|
60
|
+
return _db;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Run pending migrations from the given directory, sorted by filename.
|
|
65
|
+
* Each migration runs inside a transaction with its tracking-row insert.
|
|
66
|
+
* @param {string} migrationsDir - Directory of .sql files (numbered names)
|
|
67
|
+
*/
|
|
68
|
+
function runMigrations(migrationsDir) {
|
|
69
|
+
const db = getDb();
|
|
70
|
+
|
|
71
|
+
if (!migrationsDir || !fs.existsSync(migrationsDir)) {
|
|
72
|
+
_logger.warn('No migrations directory found');
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const files = fs.readdirSync(migrationsDir)
|
|
77
|
+
.filter(f => f.endsWith('.sql'))
|
|
78
|
+
.sort();
|
|
79
|
+
|
|
80
|
+
const applied = new Set(
|
|
81
|
+
db.prepare('SELECT filename FROM migrations').all().map(r => r.filename)
|
|
82
|
+
);
|
|
83
|
+
|
|
84
|
+
let count = 0;
|
|
85
|
+
for (const file of files) {
|
|
86
|
+
if (applied.has(file)) continue;
|
|
87
|
+
|
|
88
|
+
const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
|
|
89
|
+
const runMigration = db.transaction(() => {
|
|
90
|
+
db.exec(sql);
|
|
91
|
+
db.prepare('INSERT INTO migrations (filename) VALUES (?)').run(file);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
runMigration();
|
|
95
|
+
count++;
|
|
96
|
+
_logger.info(`Migration applied: ${file}`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
_logger.info(count === 0 ? 'No pending migrations' : `Applied ${count} migration(s)`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Get the database instance. Throws if not initialized. */
|
|
103
|
+
function getDb() {
|
|
104
|
+
if (!_db) throw new Error('Database not initialized. Call init() first.');
|
|
105
|
+
return _db;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Close the database connection. */
|
|
109
|
+
function close() {
|
|
110
|
+
if (_db) {
|
|
111
|
+
_db.close();
|
|
112
|
+
_db = null;
|
|
113
|
+
_logger.info('Database closed');
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
module.exports = { init, runMigrations, getDb, close };
|
package/index.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @aria-framework/db-worker — public API.
|
|
3
|
+
*
|
|
4
|
+
* DbClient — main-thread client: spawns the worker, invoke() with timeout
|
|
5
|
+
* + crash handling. Subclass to add app caches.
|
|
6
|
+
* runWorker — worker-side dispatcher: call from the app's worker entry file
|
|
7
|
+
* with { init } returning the model registry.
|
|
8
|
+
* database — worker-side SQLite layer: init(dbPath, {logger, onOpen}) +
|
|
9
|
+
* runMigrations(dir) + getDb() + close(). Singleton per thread.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
module.exports = {
|
|
13
|
+
DbClient: require('./client').DbClient,
|
|
14
|
+
runWorker: require('./worker').runWorker,
|
|
15
|
+
database: require('./database')
|
|
16
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@aria-framework/db-worker",
|
|
3
|
+
"version": "0.1.0",
|
|
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
|
+
"license": "UNLICENSED",
|
|
6
|
+
"private": false,
|
|
7
|
+
"publishConfig": {
|
|
8
|
+
"access": "public"
|
|
9
|
+
},
|
|
10
|
+
"main": "index.js",
|
|
11
|
+
"files": [
|
|
12
|
+
"index.js",
|
|
13
|
+
"database.js",
|
|
14
|
+
"worker.js",
|
|
15
|
+
"client.js"
|
|
16
|
+
],
|
|
17
|
+
"peerDependencies": {
|
|
18
|
+
"better-sqlite3": ">=9"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"better-sqlite3": "^12.10.0"
|
|
22
|
+
}
|
|
23
|
+
}
|
package/worker.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Worker-thread dispatcher — call runWorker() from the app's worker ENTRY file
|
|
3
|
+
* (the file path the app passes to DbClient as workerPath; Node requires a real
|
|
4
|
+
* file to spawn, which is why the entry stays in the app).
|
|
5
|
+
*
|
|
6
|
+
* The app's `init(workerData)` callback does all boot work (open the DB, run
|
|
7
|
+
* migrations, wire field encryption, ...) and RETURNS the model registry:
|
|
8
|
+
* a map of { ModelName: moduleWithMethods }. After that this module owns the
|
|
9
|
+
* message loop:
|
|
10
|
+
*
|
|
11
|
+
* receives { id, model, method, args }
|
|
12
|
+
* → models[model][method](...args) (thenables awaited)
|
|
13
|
+
* → posts { id, result } (BigInt-sanitized)
|
|
14
|
+
* or { id, error } (custom error props preserved)
|
|
15
|
+
*
|
|
16
|
+
* IMPORTANT (unchanged contract): every model the routes call via invoke MUST
|
|
17
|
+
* appear in the registry returned by init(), or the call throws "Unknown model".
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const { parentPort, workerData } = require('worker_threads');
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param {Object} opts
|
|
24
|
+
* @param {(workerData: any) => Object} opts.init - App boot; returns the model registry
|
|
25
|
+
*/
|
|
26
|
+
function runWorker({ init }) {
|
|
27
|
+
if (typeof init !== 'function') {
|
|
28
|
+
throw new Error('runWorker({ init }): init must be a function (workerData) => modelRegistry');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
try {
|
|
32
|
+
const models = init(workerData) || {};
|
|
33
|
+
|
|
34
|
+
parentPort.postMessage({ type: 'ready' });
|
|
35
|
+
|
|
36
|
+
parentPort.on('message', async (msg) => {
|
|
37
|
+
const { id, model, method, args } = msg;
|
|
38
|
+
try {
|
|
39
|
+
const target = models[model];
|
|
40
|
+
if (!target) throw new Error(`Unknown model: ${model}`);
|
|
41
|
+
if (typeof target[method] !== 'function') {
|
|
42
|
+
throw new Error(`Unknown method: ${model}.${method}`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
let result = target[method](...(args || []));
|
|
46
|
+
if (result && typeof result.then === 'function') {
|
|
47
|
+
result = await result; // async methods (e.g. bcrypt-backed user ops)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
result = sanitizeForTransfer(result);
|
|
51
|
+
parentPort.postMessage({ id, result });
|
|
52
|
+
} catch (err) {
|
|
53
|
+
// Preserve custom error props (e.g. code, status, entity ids) across the
|
|
54
|
+
// 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 }) });
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
} catch (err) {
|
|
59
|
+
parentPort.postMessage({ type: 'init-error', error: err.message });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Convert BigInt values (better-sqlite3 returns lastInsertRowid as BigInt) to
|
|
65
|
+
* Number so the result serialises across the thread boundary.
|
|
66
|
+
*/
|
|
67
|
+
function sanitizeForTransfer(obj) {
|
|
68
|
+
if (obj === null || obj === undefined) return obj;
|
|
69
|
+
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;
|
|
77
|
+
}
|
|
78
|
+
return obj;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
module.exports = { runWorker };
|