@aria-framework/db-worker 0.9.0 → 0.11.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 CHANGED
@@ -160,8 +160,63 @@ Connection pragmas (`journal_mode`, `synchronous`, `foreign_keys`,
160
160
  `busy_timeout`) are re-asserted after any unwrapped file, so a migration that
161
161
  turns foreign keys off cannot leave them off for the process.
162
162
 
163
+ ## Tenant context (0.11.0)
164
+
165
+ Postgres row-level security reads its scope from session settings that live only as long as a
166
+ transaction. Something has to put them there on **every** database call, and that something must
167
+ not be an app: two copies of a security boundary means one of them drifts and nobody notices
168
+ which. So the mechanism is here, and every consumer gets the same one.
169
+
170
+ ```js
171
+ const { runWithTenant, currentTenant } = require('@aria-framework/db-worker');
172
+
173
+ // middleware, main thread
174
+ app.use((req, res, next) => {
175
+ runWithTenant({ scope: req.user.scopeKind, partnerId: req.user.partnerId }, next);
176
+ });
177
+ ```
178
+
179
+ Three hops, because `AsyncLocalStorage` does not cross a worker thread:
180
+
181
+ 1. the app runs a request inside `runWithTenant({ scope, partnerId }, fn)`
182
+ 2. `DbClient.invoke` reads the context and puts it **in the message**
183
+ 3. `runWorker` re-establishes it, and on a pooled driver opens a transaction whose first
184
+ statement is
185
+ ```sql
186
+ SELECT set_config('app.scope', $1, true), set_config('app.partner_id', $2, true)
187
+ ```
188
+
189
+ `scope` is `platform` (sees every tenant) or `partner` (sees exactly one). A `partner` scope
190
+ without a `partnerId` is refused — there is no safe default for "which tenant is this?", and a
191
+ guess reads as working software until it returns somebody else's rows. A `platform` scope may
192
+ carry no partner; it then cannot INSERT into a table whose `partner_id` defaults from the
193
+ setting, which is correct — a platform user acting *for* a partner has to say which one.
194
+
195
+ ### On a pooled driver, EVERY invoke opens a transaction — reads included
196
+
197
+ This is not an oversight waiting to be optimised away. `set_config(..., true)` is
198
+ transaction-**local**, and a pooled driver hands each transaction its own client: a statement run
199
+ outside one lands on whichever client the pool happened to serve and is gone by the next. A read
200
+ done that way carries no scope at all — which the strict policy turns into an error, but an
201
+ unpredictable one, decided by which client came out of the pool. Making every invoke a
202
+ transaction removes the question rather than answering it per call site. `test/tenantContext.js`
203
+ holds it down.
204
+
205
+ On a serial driver (SQLite) there is no row-level security and nothing is set. The context is
206
+ still established so a model can read it via `currentTenant()`, and no transaction is forced.
207
+
163
208
  ## Changelog
164
209
 
210
+ - **0.11.0** — the tenant-context contract above: `runWithTenant()` / `currentTenant()`,
211
+ serialised across the worker boundary, applied as one `set_config` statement inside a
212
+ per-invoke transaction on pooled drivers. Fail-closed when a pooled driver gets no context.
213
+ - **0.10.0** — a transaction that merely OVERLAPS another is not nested inside it. Nesting is
214
+ tracked with `AsyncLocalStorage` (the call stack) instead of a counter on the connection, and a
215
+ top-level transaction queues behind any already open. Before this, the second of two
216
+ overlapping transactions was rejected **while its writes stayed committed**, and a failed
217
+ `BEGIN` leaked the depth counter for the life of the connection. Siblings queue too: two nested
218
+ transactions started together opened two savepoints, and releasing the outer released the inner.
219
+
165
220
  - **0.8.0** — `-- aria:no-transaction` (above). Also: the SQLite path now rolls
166
221
  back a transaction an unwrapped file left open, and restores the connection
167
222
  pragmas afterwards — without that, one failing marked migration left
package/client.js CHANGED
@@ -13,6 +13,7 @@
13
13
  */
14
14
 
15
15
  const { Worker } = require('worker_threads');
16
+ const { currentTenant } = require('./tenantContext');
16
17
 
17
18
  class DbClient {
18
19
  /**
@@ -218,7 +219,10 @@ class DbClient {
218
219
  }
219
220
  }, this._callTimeoutMs);
220
221
  this._pending.set(id, { resolve, reject, timer, started: Date.now(), label: `${model}.${method}` });
221
- this._worker.postMessage({ id, model, method, args });
222
+ // The tenant context travels IN THE MESSAGE because AsyncLocalStorage does not cross a
223
+ // worker thread. null when the app has established none — which a pooled driver refuses
224
+ // on the far side rather than guessing which tenant was meant.
225
+ this._worker.postMessage({ id, model, method, args, tenant: currentTenant() });
222
226
  });
223
227
  }
224
228
 
package/driver/sqlite.js CHANGED
@@ -67,17 +67,89 @@ function createSqliteDriver(opts = {}) {
67
67
  }
68
68
 
69
69
  /** The contract over an open better-sqlite3 handle. */
70
- // The nesting depth belongs to the CONNECTION, not to the wrapper around it. Each store that
71
- // resolves a legacy { getDb } mints its OWN driver over the shared handle (auth/resolveDriver.js),
72
- // so a per-closure counter gave every store a private depth of 0 — and the exact composition
73
- // savepoint nesting was released for (an app wrapper's transaction around a store's own) issued
74
- // a second BEGIN and threw "cannot start a transaction within a transaction", leaving the outer
75
- // transaction open. Hanging it off the handle makes every wrapper over one connection agree.
76
- const DEPTH = Symbol.for('aria.db-worker.depth');
70
+ // NESTING IS A PROPERTY OF THE CALL STACK, NOT OF THE CONNECTION.
71
+ //
72
+ // This was a depth counter hung off the handle, and a counter cannot tell two different things
73
+ // apart, because both look like "a transaction began while a transaction was open":
74
+ //
75
+ // NESTED transaction() called INSIDE another's callback -> a savepoint
76
+ // OVERLAP transaction() called WHILE another is open -> must wait its turn
77
+ //
78
+ // Treating overlap as nesting corrupted both sides: the second got a savepoint, the first's
79
+ // COMMIT destroyed every savepoint on the connection, and the second was then REJECTED while
80
+ // its writes stayed committed — a rollback that did not roll back. AsyncLocalStorage answers
81
+ // the question a counter cannot, because it follows the async call chain, which is what
82
+ // "inside" actually means.
83
+ //
84
+ // The context names the connection it belongs to. That is what the old per-connection counter
85
+ // was really protecting: a legacy { getDb } shim mints its OWN driver over a shared handle
86
+ // (auth/resolveDriver.js), and both must agree about nesting — while two different databases
87
+ // stay independent of each other.
88
+ const { AsyncLocalStorage } = require('node:async_hooks');
89
+ const txContext = new AsyncLocalStorage();
90
+
91
+ /** Per-connection serialisation of TOP-LEVEL transactions. Hung off the handle for the same
92
+ * reason the depth was: every wrapper over one connection has to share one queue. */
93
+ const QUEUE_OWNER = Symbol.for('aria.db-worker.txqueue');
77
94
 
78
95
  function wrap(db) {
79
96
  const stmt = (sql) => db.prepare(sql);
80
- if (typeof db[DEPTH] !== 'number') db[DEPTH] = 0;
97
+ // The connection is the owner of the top-level queue, and it has to BE an owner object rather
98
+ // than a bare promise so enqueue() can treat it exactly like any other level.
99
+ if (!db[QUEUE_OWNER]) db[QUEUE_OWNER] = { queue: Promise.resolve() };
100
+
101
+ /**
102
+ * One transaction context per LEVEL, each owning the queue for its own children.
103
+ *
104
+ * A single queue on the connection is not enough: two nested transactions started together
105
+ * inside one parent (a Promise.all over two stores, say) open two savepoints at once, and
106
+ * releasing the outer of the two releases the inner with it — the original bug, one level
107
+ * down. Siblings therefore take turns, exactly as top-level transactions do.
108
+ *
109
+ * Depth is fixed when the context is made rather than incremented and decremented in place,
110
+ * so a sibling cannot observe a depth that belongs to another one.
111
+ */
112
+ const context = (depth) => ({ db, depth, queue: Promise.resolve() });
113
+
114
+ /** Serialise a child behind its siblings. Chained on BOTH settle paths, so one failure does
115
+ * not wedge every transaction queued after it. */
116
+ function enqueue(owner, run) {
117
+ const mine = owner.queue.then(run, run);
118
+ owner.queue = mine.then(() => {}, () => {});
119
+ return mine;
120
+ }
121
+
122
+ /** A real transaction. Entered only with the connection to itself. */
123
+ async function top(fn) {
124
+ const ctx = context(0);
125
+ db.exec('BEGIN');
126
+ try {
127
+ const out = await txContext.run(ctx, () => fn(api));
128
+ db.exec('COMMIT');
129
+ return out;
130
+ } catch (e) {
131
+ // The original error is what matters; a failed rollback must not mask it.
132
+ try { db.exec('ROLLBACK'); } catch (_) { /* noop */ }
133
+ throw e;
134
+ }
135
+ }
136
+
137
+ /** A savepoint inside the transaction we are demonstrably running within. */
138
+ async function nested(parent, fn) {
139
+ const ctx = context(parent.depth + 1);
140
+ const sp = `aria_sp_${ctx.depth}`;
141
+ db.exec(`SAVEPOINT ${sp}`);
142
+ try {
143
+ const out = await txContext.run(ctx, () => fn(api));
144
+ db.exec(`RELEASE ${sp}`);
145
+ return out;
146
+ } catch (e) {
147
+ // ROLLBACK TO rewinds to the savepoint but LEAVES it on the stack. Releasing it as well
148
+ // is what keeps the stack balanced for whatever the outer transaction does next.
149
+ try { db.exec(`ROLLBACK TO ${sp}`); db.exec(`RELEASE ${sp}`); } catch (_) { /* noop */ }
150
+ throw e;
151
+ }
152
+ }
81
153
 
82
154
  const api = {
83
155
  kind: 'sqlite',
@@ -107,29 +179,28 @@ function wrap(db) {
107
179
  /**
108
180
  * Transactions are run with explicit BEGIN/COMMIT rather than better-sqlite3's
109
181
  * `db.transaction(fn)`, because that helper REFUSES an async callback — and every callback
110
- * here is async by contract. Safe only because this driver declares 'serial': nothing else
111
- * can issue a statement between the BEGIN and the COMMIT.
182
+ * here is async by contract.
183
+ *
184
+ * Two paths, and telling them apart is the entire point:
185
+ *
186
+ * inside another transaction on THIS connection -> SAVEPOINT, so the inner half can fail
187
+ * without discarding the outer work
188
+ * anywhere else -> a real BEGIN, QUEUED behind whatever
189
+ * is already open on this connection
190
+ *
191
+ * The queue is what makes overlap safe rather than merely detected. SQLite allows one write
192
+ * transaction per connection, so waiting costs nothing that was ever available anyway.
193
+ *
194
+ * A nested call whose async context was somehow lost would be mistaken for a top-level one
195
+ * and queue behind the transaction it is running inside — a hang. AsyncLocalStorage
196
+ * propagates through promises, timers and microtasks, which is all any callback here uses,
197
+ * and test/transactions.js holds that down across await, setImmediate and Promise.all.
112
198
  */
113
199
  async transaction(fn) {
114
- // NESTING VIA SAVEPOINTS. Stores compose — an app wrapper can put its own transaction
115
- // around a store call that already opens one (a role rename that must retarget users in
116
- // the same atomic step is the case that surfaced this). A second BEGIN is an error in
117
- // SQLite, so depth is tracked: the outermost is a real transaction, inner ones are
118
- // savepoints that can roll back independently without discarding the outer work.
119
- const depth = db[DEPTH]++;
120
- const sp = `aria_sp_${depth}`;
121
- db.exec(depth === 0 ? 'BEGIN' : `SAVEPOINT ${sp}`);
122
- try {
123
- const out = await fn(api);
124
- db.exec(depth === 0 ? 'COMMIT' : `RELEASE ${sp}`);
125
- return out;
126
- } catch (e) {
127
- // The original error is what matters; a failed rollback must not mask it.
128
- try { db.exec(depth === 0 ? 'ROLLBACK' : `ROLLBACK TO ${sp}`); } catch (_) { /* noop */ }
129
- throw e;
130
- } finally {
131
- db[DEPTH] = depth;
132
- }
200
+ const parent = txContext.getStore();
201
+ if (parent && parent.db === db) return enqueue(parent, () => nested(parent, fn));
202
+ // No parent on this connection: a top-level transaction, queued on the connection itself.
203
+ return enqueue(db[QUEUE_OWNER], () => top(fn));
133
204
  },
134
205
 
135
206
  async close() {
package/index.js CHANGED
@@ -29,5 +29,9 @@ module.exports = {
29
29
  ...require('./tableOrder'),
30
30
  ...require('./schemaSnapshot'),
31
31
  ...require('./workerRegistry'),
32
- ...require('./settingsStore')
32
+ ...require('./settingsStore'),
33
+ // 0.11.0 — the tenant-context contract. One mechanism for both apps: RLS reads its scope
34
+ // from transaction-local session settings, and a security boundary with two copies has one
35
+ // that drifts.
36
+ ...require('./tenantContext')
33
37
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.9.0",
3
+ "version": "0.11.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,
@@ -18,7 +18,8 @@
18
18
  "workerRegistry.js",
19
19
  "settingsStore.js",
20
20
  "dialect.js",
21
- "driver/"
21
+ "driver/",
22
+ "tenantContext.js"
22
23
  ],
23
24
  "peerDependencies": {
24
25
  "better-sqlite3": ">=9",
@@ -37,6 +38,6 @@
37
38
  "pg": "^8.23.0"
38
39
  },
39
40
  "scripts": {
40
- "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/regressions.js && node test/smoke.js && node test/tier2.js"
41
+ "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/smoke.js && node test/tier2.js"
41
42
  }
42
43
  }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The tenant context: WHO a database call is being made on behalf of.
3
+ *
4
+ * Postgres row-level security reads its scope from session settings that live only as long as a
5
+ * transaction. Something has to put them there on every single call, and that something must not
6
+ * be an app — two copies of a security boundary means one of them drifts and nobody notices which.
7
+ * So the mechanism lives here and every consumer gets the same one.
8
+ *
9
+ * THREE HOPS, because AsyncLocalStorage does not cross a worker thread:
10
+ *
11
+ * 1. the app runs a request inside runWithTenant({ scope, partnerId }, ...) (main thread)
12
+ * 2. DbClient.invoke reads currentTenant() and puts it IN THE MESSAGE
13
+ * 3. runWorker re-establishes it, and on a pooled driver opens a transaction whose first
14
+ * statement is set_config for both keys
15
+ *
16
+ * The package carries a context. It does not decide what a request's scope IS — that is the app's,
17
+ * and it differs between a signed-in staff user, a portal contact and a cron job.
18
+ *
19
+ * WHY IT REFUSES RATHER THAN DEFAULTS. There is no safe default for "which tenant is this?". A
20
+ * missing partnerId that silently became 0, or NULL, or the house partner, is precisely the bug
21
+ * RLS exists to prevent — and it would read as working software.
22
+ */
23
+
24
+ 'use strict';
25
+
26
+ const { AsyncLocalStorage } = require('node:async_hooks');
27
+
28
+ const store = new AsyncLocalStorage();
29
+
30
+ /**
31
+ * 'platform' sees every tenant; 'partner' sees exactly one.
32
+ *
33
+ * These are the two values the RLS policy branches on, so the set is closed on purpose: a typo'd
34
+ * scope must be an error here rather than an ELSE branch in SQL that quietly matches nothing.
35
+ */
36
+ const SCOPES = new Set(['platform', 'partner']);
37
+
38
+ /** Validate and freeze. Throws with the reason, because every caller of this is a security path. */
39
+ function normalise(ctx) {
40
+ if (!ctx || typeof ctx !== 'object') {
41
+ throw new Error('tenantContext: a context is required, e.g. { scope: \'partner\', partnerId: 7 }');
42
+ }
43
+ const scope = String(ctx.scope == null ? '' : ctx.scope);
44
+ if (!SCOPES.has(scope)) {
45
+ throw new Error(
46
+ `tenantContext: scope must be 'platform' or 'partner', got ${JSON.stringify(ctx.scope)}`
47
+ );
48
+ }
49
+
50
+ let partnerId = ctx.partnerId === undefined ? null : ctx.partnerId;
51
+ if (partnerId !== null) {
52
+ const n = Number(partnerId);
53
+ if (!Number.isInteger(n)) {
54
+ throw new Error(`tenantContext: partnerId must be an integer or null, got ${JSON.stringify(ctx.partnerId)}`);
55
+ }
56
+ partnerId = n;
57
+ }
58
+
59
+ // A partner scope with no partner is the one combination that must never reach the database.
60
+ if (scope === 'partner' && partnerId === null) {
61
+ throw new Error("tenantContext: scope 'partner' requires a partnerId");
62
+ }
63
+
64
+ // Frozen so a downstream caller cannot widen its own scope by mutating the object it was given.
65
+ // Plain data, so it survives structuredClone across the worker boundary.
66
+ return Object.freeze({ scope, partnerId });
67
+ }
68
+
69
+ /**
70
+ * Run `fn` with this tenant context in scope. Everything `fn` awaits inherits it, including any
71
+ * DbClient.invoke it makes.
72
+ */
73
+ function runWithTenant(ctx, fn) {
74
+ return store.run(normalise(ctx), fn);
75
+ }
76
+
77
+ /** The context in scope, or null. */
78
+ function currentTenant() {
79
+ return store.getStore() || null;
80
+ }
81
+
82
+ /**
83
+ * The one statement that applies a context, and the values it binds.
84
+ *
85
+ * ONE statement rather than two SET LOCALs, so the per-invoke cost is a single round trip. The
86
+ * third argument to set_config is `is_local`: true ties the setting to the current transaction,
87
+ * which is exactly the lifetime a request wants and the reason every invoke must open one.
88
+ *
89
+ * A platform context may legitimately carry no partnerId — it is reading across tenants. It then
90
+ * cannot INSERT into a table whose partner_id defaults from this setting, which is correct: a
91
+ * platform user acting FOR a partner has to say which one.
92
+ */
93
+ const APPLY_SQL =
94
+ "SELECT set_config('app.scope', ?, true), set_config('app.partner_id', ?, true)";
95
+
96
+ function applyParams(ctx) {
97
+ const c = normalise(ctx);
98
+ return [c.scope, c.partnerId === null ? '' : String(c.partnerId)];
99
+ }
100
+
101
+ module.exports = { runWithTenant, currentTenant, normalise, APPLY_SQL, applyParams, SCOPES };
package/worker.js CHANGED
@@ -19,6 +19,48 @@
19
19
 
20
20
  const { parentPort, workerData } = require('worker_threads');
21
21
  const { performance } = require('perf_hooks');
22
+ const { runWithTenant, APPLY_SQL, applyParams } = require('./tenantContext');
23
+
24
+ /**
25
+ * The driver, or null before the app's init() has opened one. Read per call rather than cached:
26
+ * tests swap drivers at runtime, and a cached answer would be wrong for the rest of the process.
27
+ */
28
+ function currentDriver() {
29
+ try { return require('./database').driver() || null; } catch (_) { return null; }
30
+ }
31
+
32
+ /**
33
+ * Re-establish the tenant context, and on a pooled driver make it real.
34
+ *
35
+ * ON A POOLED DRIVER EVERY INVOKE OPENS A TRANSACTION — READS INCLUDED. That is not an
36
+ * oversight waiting to be optimised away. set_config(..., true) is transaction-LOCAL, and a
37
+ * pooled driver hands each transaction its own client: a statement run outside one lands on
38
+ * whichever client the pool happened to serve and is gone by the next. A read done that way
39
+ * carries no scope at all — which the strict policy turns into an error, but an unpredictable
40
+ * one, decided by which client came out of the pool. Making every invoke a transaction removes
41
+ * the question rather than answering it per call site.
42
+ *
43
+ * On a serial driver (SQLite) there is no RLS and nothing to set. The context is still
44
+ * established so a model can read it, and no transaction is forced around a read.
45
+ */
46
+ async function withTenant(tenant, label, dispatch) {
47
+ const driver = currentDriver();
48
+ if (!driver || driver.concurrency !== 'pool') {
49
+ return tenant ? runWithTenant(tenant, dispatch) : dispatch();
50
+ }
51
+ if (!tenant) {
52
+ // Fail closed. There is no safe default for "which tenant is this?", and a guess here
53
+ // would read as working software right up until it returned somebody else's rows.
54
+ throw new Error(
55
+ `db-worker: ${label} was invoked with no tenant context, and this driver is pooled. ` +
56
+ 'Wrap the caller in runWithTenant({ scope, partnerId }, ...).'
57
+ );
58
+ }
59
+ return runWithTenant(tenant, () => driver.transaction(async (tx) => {
60
+ await tx.run(APPLY_SQL, applyParams(tenant));
61
+ return dispatch();
62
+ }));
63
+ }
22
64
 
23
65
  /**
24
66
  * @param {Object} opts
@@ -71,7 +113,7 @@ async function runWorker({ init }) {
71
113
  });
72
114
 
73
115
  async function handle(msg) {
74
- const { id, model, method, args } = msg;
116
+ const { id, model, method, args, tenant } = msg;
75
117
  // Worker-side execution time, shipped back so the client's slow-call log
76
118
  // attributes slowness to the query that WAS slow, not to calls that were
77
119
  // merely queued behind it. Monotonic clock: a wall-clock (Date.now) delta
@@ -84,10 +126,13 @@ async function runWorker({ init }) {
84
126
  throw new Error(`Unknown method: ${model}.${method}`);
85
127
  }
86
128
 
87
- let result = target[method](...(args || []));
88
- if (result && typeof result.then === 'function') {
89
- result = await result; // async methods (e.g. bcrypt-backed user ops)
90
- }
129
+ let result = await withTenant(tenant, `${model}.${method}`, async () => {
130
+ let r = target[method](...(args || []));
131
+ if (r && typeof r.then === 'function') {
132
+ r = await r; // async methods (e.g. bcrypt-backed user ops)
133
+ }
134
+ return r;
135
+ });
91
136
 
92
137
  result = sanitizeForTransfer(result);
93
138
  parentPort.postMessage({ id, result, execMs: Math.round(performance.now() - t0) });