@aria-framework/db-worker 0.10.0 → 0.12.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,89 @@ 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
+
208
+ ## Migrations per engine (0.12.0)
209
+
210
+ A migration file may name the engine it is for. The runner picks; it never translates.
211
+
212
+ ```
213
+ 001_baseline.sql runs on sqlite
214
+ 001_baseline.postgres.sql runs on postgres, and supersedes 001_baseline.sql there
215
+ 002_records.sql runs on both — no sibling, so it is dialect-neutral
216
+ ```
217
+
218
+ The suffix is the **driver kind**, spelled exactly (`sqlite`, `postgres`). There is no `pg`
219
+ alias on purpose: two names for one thing is how a migration ends up silently never running.
220
+ A suffix outside that set (`002_records.v2.sql`) is just part of the name and runs everywhere.
221
+
222
+ **Why the plain file keeps its name.** The obvious symmetrical scheme — rename the baseline to
223
+ `001_baseline.sqlite.sql` — cannot be done. The ledger is keyed by FILENAME, and every database
224
+ this framework has created has `001_baseline.sql` in its `migrations` table. Renaming it makes
225
+ the runner see an unapplied migration and re-run a baseline over live tables. The rule is
226
+ additive for that reason and no other, and `test/migrationDialect.js` proves that adding a
227
+ Postgres sibling does nothing to an already-migrated SQLite database.
228
+
229
+ This is selection, not a portable DDL layer. An app still writes its own schema per engine —
230
+ the framework guarantees only which files ran and the transaction around each.
231
+
163
232
  ## Changelog
164
233
 
234
+ - **0.12.0** — dialect-selected migration files (above).
235
+
236
+ - **0.11.0** — the tenant-context contract above: `runWithTenant()` / `currentTenant()`,
237
+ serialised across the worker boundary, applied as one `set_config` statement inside a
238
+ per-invoke transaction on pooled drivers. Fail-closed when a pooled driver gets no context.
239
+ - **0.10.0** — a transaction that merely OVERLAPS another is not nested inside it. Nesting is
240
+ tracked with `AsyncLocalStorage` (the call stack) instead of a counter on the connection, and a
241
+ top-level transaction queues behind any already open. Before this, the second of two
242
+ overlapping transactions was rejected **while its writes stayed committed**, and a failed
243
+ `BEGIN` leaked the depth counter for the life of the connection. Siblings queue too: two nested
244
+ transactions started together opened two savepoints, and releasing the outer released the inner.
245
+
165
246
  - **0.8.0** — `-- aria:no-transaction` (above). Also: the SQLite path now rolls
166
247
  back a transaction an unwrapped file left open, and restores the connection
167
248
  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/database.js CHANGED
@@ -222,6 +222,45 @@ function execUnwrappedSqlite(db, sql) {
222
222
  }
223
223
  }
224
224
 
225
+ /** Engines a migration file may name. A suffix outside this set is just part of the name. */
226
+ const MIGRATION_DIALECTS = new Set(['sqlite', 'postgres']);
227
+
228
+ /**
229
+ * Choose the migration files that belong to THIS engine.
230
+ *
231
+ * 001_baseline.sql runs on sqlite
232
+ * 001_baseline.postgres.sql runs on postgres, and supersedes 001_baseline.sql there
233
+ * 002_records.sql runs on both — no sibling, so it is dialect-neutral
234
+ *
235
+ * The suffix is the DRIVER KIND, spelled exactly. One spelling, no alias table: two ways to
236
+ * name the same thing is precisely the sort of detail that rots into a file silently never
237
+ * running.
238
+ *
239
+ * WHY NOT SIMPLY RENAME the baseline to 001_baseline.sqlite.sql and be symmetrical: the ledger
240
+ * is keyed by FILENAME. Every database this framework has ever created has 001_baseline.sql in
241
+ * its migrations table. Renaming it makes the runner see an unapplied migration and re-run a
242
+ * baseline over live data. The rule is additive for that reason and no other.
243
+ *
244
+ * This is SELECTION, not translation. An app still writes its own DDL per engine — the header
245
+ * below is explicit that a portable DDL layer would be a leaky translation of the one thing
246
+ * engines differ on most. All this decides is which of the app's files to hand to which engine.
247
+ */
248
+ function selectForDialect(files, kind) {
249
+ const specific = new Map(); // plain name -> the file that supersedes it here
250
+ const foreign = new Set(); // files that name a DIFFERENT engine
251
+
252
+ for (const f of files) {
253
+ const m = /^(.*)\.([A-Za-z0-9]+)\.sql$/.exec(f);
254
+ if (!m) continue;
255
+ const suffix = m[2].toLowerCase();
256
+ if (!MIGRATION_DIALECTS.has(suffix)) continue; // e.g. 002_records.v2.sql — just a name
257
+ if (suffix === kind) specific.set(m[1] + '.sql', f);
258
+ else foreign.add(f);
259
+ }
260
+
261
+ return files.filter((f) => !foreign.has(f) && !specific.has(f));
262
+ }
263
+
225
264
  /**
226
265
  * Apply pending numbered migrations, in filename order, each in its own transaction — unless
227
266
  * the file opts out with `-- aria:no-transaction` (see the marker notes above).
@@ -251,7 +290,12 @@ function runMigrations(migrationsDir) {
251
290
  _logger.warn('No migrations directory found');
252
291
  return Promise.resolve({ applied: 0 });
253
292
  }
254
- const files = fs.readdirSync(migrationsDir).filter((f) => f.endsWith('.sql')).sort();
293
+ const all = fs.readdirSync(migrationsDir).filter((f) => f.endsWith('.sql')).sort();
294
+ const files = selectForDialect(all, d.kind);
295
+ for (const skipped of all.filter((f) => !files.includes(f))) {
296
+ // Announced, because a migration that silently never runs is the worst kind of absent.
297
+ _logger.info(`Migration skipped (not for ${d.kind}): ${skipped}`);
298
+ }
255
299
 
256
300
  // ── the synchronous path, unchanged in behaviour since 0.1.0 ──────────────────────────────
257
301
  if (d.kind === 'sqlite') {
@@ -415,4 +459,4 @@ async function initDriver(opts = {}) {
415
459
  return _driver;
416
460
  }
417
461
 
418
- module.exports = { init, initDriver, runMigrations, getDb, driver, close };
462
+ module.exports = { init, initDriver, runMigrations, getDb, driver, close, selectForDialect };
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.10.0",
3
+ "version": "0.12.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/transactions.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/migrationDialect.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) });