@aria-framework/db-worker 0.28.0 → 0.29.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
@@ -452,8 +452,265 @@ in-process, a devDependency). Unlike the `.pg` suites, it runs on every `npm tes
452
452
 
453
453
  Against 0.25.0's code, 6 of its 10 checks fail.
454
454
 
455
+ ## The tenancy core (0.29.0)
456
+
457
+ Every multi-tenant app carried its own copy of these. They move here unchanged in behaviour; an app
458
+ adopts each by replacing its copy with a re-export, and an app that only bumps the version uses none of
459
+ them and sees no difference (every existing export, option and default is as it was).
460
+
461
+ ### `sql` — dialect helpers and the tenant filter
462
+
463
+ ```js
464
+ const { sql } = require('@aria-framework/db-worker'); // an app's lib/sql.js: module.exports = require(...).sql
465
+ `SELECT … FROM notes WHERE board_id = ?${sql.andTenant()}`
466
+ ```
467
+
468
+ Resolved from this package's own `database.driver()` **at call time**, never captured at require time,
469
+ so a test bridge that opens a second driver is followed. Throws "no driver yet" before `init()`.
470
+
471
+ | Helper | Postgres | SQLite |
472
+ |---|---|---|
473
+ | `whereTenant(alias)`, `andTenant(alias)`, `tenantPredicate(alias)` | `partner_id = <CASE tenant>` | `''` (one tenant, no policies) |
474
+ | `TENANT_EXPR` | the CASE text, for a builder that takes its own dialect | the same text |
475
+ | `now`, `nowMinusDays`, `nowMinusSeconds`, `nowPlusMinutes`, `startOf`, `dateGroup`, `daysBetween`, `greatest`, `least`, `returningId`, `tables`, `foreignKeys`, `dialect` | the dialect's | the dialect's |
476
+ | `andPrintableAscii(col)` | `col ~ '^[ -~]*$'` | `col NOT GLOB '*[^ -~]*'` |
477
+ | `arrayParam(v)` / `jsonParam(v)` | the JS array / JSON text | JSON text / JSON text |
478
+ | `jsonColumn(v)` / `arrayColumn(v)` | shape-based, callable on the main thread; a malformed value throws | |
479
+ | `isUniqueViolation`, `uniqueViolation`, `isDatabaseError`, `isDeadlock` | by SQLSTATE (`23505`, any five-character code, `40P01`) | by `SQLITE_*` code |
480
+
481
+ The tenant expression is a `CASE`, not a `COALESCE`: the planner may push a `CASE` into an Index Cond on
482
+ an RLS table and must demote a `COALESCE` to a Filter (measured in an app: 4 buffers against 27 at four
483
+ partners). `test/sql.js` shows both plans on PGlite, and holds the text byte-equal to every app copy
484
+ that has the CASE form. One app still has the COALESCE form; it switches at its own adoption, with a
485
+ measured plan, and the test notices when it does.
486
+
487
+ **`uniqueViolation` on a scoped table:** under row-level security Postgres withholds the "Key (…)" detail
488
+ from the application role, so `columns` is null there and only `index` names the rule.
489
+
490
+ ### `defineTenancy(lists)` — the machinery of `config/tenancy.js`
491
+
492
+ ```js
493
+ module.exports = defineTenancy({ PARTNER, PLATFORM, PARTNER_NULLABLE, EXCLUDED, PLATFORM_POSTGRES_ONLY,
494
+ WIDEN_UNIQUE, NOT_WIDENED_ON_PURPOSE, GLOBAL_BY_VALUE });
495
+ ```
496
+
497
+ Returns the lists plus `POLICY_EXPRESSION`, `all()` and `scoped()`. **The policy text is frozen**: it is in
498
+ migrations every app has applied and pinned, so it is exported as `TENANCY_POLICY_EXPRESSION`, pinned by
499
+ sha256 in `test/tenancyManifest.js` and held byte-equal to all six app copies; passing a different one is
500
+ refused. `all()` is the four decided lists and **never** `PLATFORM_POSTGRES_ONLY` (the classification guard
501
+ compares it with the SQLite schema in both directions); a table in both is refused. Any other key passes
502
+ through untouched (a customer map and its own expression, `NO_CASCADE`); an absent decided list is `{}`.
503
+
504
+ ### Scope assertions, `keepTenant`, `tenantCacheKey`
505
+
506
+ - **`assertPlatformScope(d, label)`** / **`assertPartnerScope(d, label)`** — for a model method that must
507
+ run at one scope: asks the TRANSACTION (`current_setting('app.scope')`, what the policy reads), throws
508
+ `<label> must run at platform scope (asPlatform), not "<scope>"` (or `partner scope (asPartner)`) with
509
+ `code: 'tenant_scope_refused'`, and returns `{ scope, partnerId }`. **Postgres only**: on SQLite they
510
+ return null and refuse nothing. `d` is the driver, read at call time.
511
+ - **`keepTenant(mw | [mw, …])`** — a callback-style middleware (multer/busboy) calls `next` from a stream
512
+ event, outside the request's tenant context; on a pooled driver the handler after it then has no tenant.
513
+ The wrapper restores the context in force before it. Each wrapper is named `keepTenantMw` and carries
514
+ `.wrapped`.
515
+ - **`tenantCacheKey([tenant])`** — `'none'`, `'platform:<id>'` (platform scope has its own bucket per id)
516
+ or `'p:<id>'`; with no argument, the context in force.
517
+
518
+ ### `DbClient` option `onRefusal(model, err)`
519
+
520
+ Awaited after an invoke rejects, before the caller sees the rejection, which is always the original
521
+ error. For a refusal that must outlive its own rollback: the model attaches what to record to its error,
522
+ and the hook writes it as its own invoke, in the caller's tenant. A throwing hook is logged. The hook's
523
+ own invokes pass through it too, so it ignores its own model's errors. Default: none.
524
+
525
+ ### `database.runMigrations(dir, { squashedFrom })`
526
+
527
+ Refuses, with instructions and before anything runs, a SQLite database whose ledger names an old
528
+ migration (`squashedFrom: '001_initial_schema.sql'`) but not the baseline that replaced the chain — which
529
+ would otherwise run the baseline over a populated schema and fail on every boot with "table already
530
+ exists". `{ file, baseline, remedy }`: `baseline` defaults to the directory's first migration for the
531
+ engine, `remedy` replaces the default instructions. Never repaired automatically. SQLite only (as in the
532
+ app it came from); on Postgres the option is validated and nothing is checked.
533
+
534
+ ### `createTenantSettings({ driver, platformOnly, afterWrite, table, label })`
535
+
536
+ The tenant layer over `createSettingsStore` for a PARTNER_NULLABLE `settings` table (a row per partner per
537
+ key, plus the installation row at `partner_id IS NULL`). An app's `models/Settings.js` becomes
538
+ `{ ...createTenantSettings({...}), ...its typed getters }`.
539
+
540
+ | Method | Postgres | SQLite |
541
+ |---|---|---|
542
+ | `get`, `getByPrefix`, `all` | own row first, then the installation row (`DISTINCT ON`, `NULLS LAST`) | the plain store |
543
+ | `set`, `setMultiple` | the plain store's upsert on `(partner_id, key)` | on `key` |
544
+ | `getInstallation(key)` | the `partner_id IS NULL` row, from any scope | the key's one row |
545
+ | `setInstallation(key, v)` | at `NULL`, only when the value changed (in a transaction); platform scope (the policy enforces it) | on `key`, partner_id forced to NULL |
546
+ | `getOwn(key, { partnerScopeOnly })` | own row only (the house's at platform scope); the option refuses platform scope | the key's one row |
547
+ | `clearOwn(key)` | deletes own row | `{ changes: 0 }` |
548
+ | `claimInstallationRun(key, value, staleMs)` | advisory lock, then claim unless a fresh `running` record is there | the same, one writer |
549
+
550
+ - `driver` — a **getter** (default: this package's `database.driver()`); a driver object is refused.
551
+ - `platformOnly(key)` — keys `set` / `setMultiple` refuse below platform scope (`settings_key_platform_only`,
552
+ on both engines, from the tenant context) and `clearOwn` always refuses. **Default: no key** (the
553
+ starter's behaviour). The hub passes its catalogue.
554
+ - `afterWrite(tx, { key, partnerId })` — runs on the writing transaction after a write that CHANGED a row
555
+ (`partnerId` null for the installation row); a throw rolls the write back. With it, `set` and
556
+ `setMultiple` write only when the value changed and answer `{ changes }`; without it they are the plain
557
+ store's statements. Default: none.
558
+ - Typed getters, and any extra refusal an app has (the hub refuses `clearOwn` of a brand key), stay in the
559
+ app's model, wrapped around these.
560
+
561
+ `test/tenantSettings.js` runs on PGlite with real RLS and on SQLite. On PGlite the fixture has the house as partner 5, partners
562
+ 2 and 8 on either side of it, a partner 9 with no rows, and the installation row. That way no sort order of
563
+ `partner_id` can make a read that lost its tenant condition look right.
564
+
565
+ ### `aria-tenancy` — the tenancy of a new table, generated (bin)
566
+
567
+ A new scoped table is born with its tenancy in its own migration pair, and that tenancy is generated from the
568
+ app's manifest, never typed: on a composite key a bare `ON DELETE SET NULL` also nulls `partner_id`, and
569
+ `SET DEFAULT` silently re-parents the row into another tenant.
570
+
571
+ ```
572
+ npx aria-tenancy new <table...> [--name <slug>] [--number <NNN> [--fill-gap]] # writes NNN_slug.sql + NNN_slug.postgres.sql
573
+ npx aria-tenancy new --print <table...> # prints the generated statements; writes nothing
574
+ npx aria-tenancy check # exit 1 unless every policed migration is right
575
+ ```
576
+
577
+ The app passes `aria.tenancy.json` beside its `package.json` (run from that folder or below it):
578
+
579
+ ```json
580
+ {
581
+ "manifest": "config/tenancy.js",
582
+ "migrations": "migrations",
583
+ "frozen": ["001_baseline.sql", "001_baseline.postgres.sql", "…every file applied before the app adopted this…"],
584
+ "partnerIdType": "BIGINT",
585
+ "principalTable": "users",
586
+ "requireUpdateCascade": false,
587
+ "floors": { "tables": 11, "keys": 35 },
588
+ "exceptions": [
589
+ { "file": "030_x.postgres.sql", "kind": "moveRows", "table": "settings", "reason": "the house row becomes the installation row, once" }
590
+ ]
591
+ }
592
+ ```
593
+
594
+ Parsed strictly: an unknown key, a path outside the app's folder, a frozen entry that is not a bare `*.sql` name, a
595
+ floor that is not a whole number, or a malformed exception is refused. `manifest`, `migrations`, `frozen` and
596
+ `partnerIdType` are required; `principalTable` defaults to `users`; `requireUpdateCascade` to false; `floors` to 0;
597
+ `noneAfterFrozen: true` is how an app says no migration follows its frozen list yet (without it an empty set fails
598
+ `check`, and with it a policed file fails it). The manifest must be built with `defineTenancy` (or have `scoped()` /
599
+ `all()` and the frozen policy text). The command loads nothing else of the app and opens no database.
600
+
601
+ - **`partnerIdType`** — `"BIGINT"` or `"INTEGER"`, no default: the type of the Postgres `partner_id` that `new` writes
602
+ and that `check` requires, exactly, of every policed file (the SQLite twin is always `INTEGER`). **A new app chooses
603
+ `BIGINT`**, matching `partners.id`. An app whose policed files already carry `INTEGER` says `INTEGER`. The mixed
604
+ case was measured harmless: an `INTEGER` child's composite key into a `BIGINT` parent works, still refuses a
605
+ mismatched row, and plans as an index-only scan.
606
+ - **`requireUpdateCascade`** — for an app that moves a customer between partners by re-parenting it: every composite
607
+ key into a scoped table that is not an attribution key (into the principal table, or a `NO_CASCADE` column) must be
608
+ `ON UPDATE CASCADE`, so the children follow, and `new` says so in the skeleton. Attribution keys never cascade,
609
+ with or without it. Off by default, because an app whose applied ownership keys carry no update action is correct.
610
+ - **`exceptions`** — what `check` refuses but an app may really need, each `{ file, kind, table | statement, reason }`
611
+ for one policed file: `dropTable` (a tenant table is dropped; the manifest must then no longer classify it),
612
+ `moveRows` (a data statement sets `partner_id` on that table), `privilege` (that exact statement, whitespace
613
+ normalised). An exception that matches nothing fails `check`, so it cannot outlive its statement.
614
+
615
+ `new` writes a CREATE TABLE skeleton per table with `partner_id` inline (Postgres: the stated type, the session
616
+ default and `REFERENCES partners(id)`; SQLite: `INTEGER … DEFAULT 1`, one tenant and no policies), `UNIQUE (id,
617
+ partner_id)`, the partner index, and on Postgres `ENABLE`, `FORCE` and the policy (`TENANCY_POLICY_EXPRESSION`; a table
618
+ in the manifest's `CUSTOMER` map gets the manifest's own `CUSTOMER_POLICY_EXPRESSION(column)` and a key to
619
+ `customers`). Add the table's own columns where marked. It refuses an existing number or file, a number not after
620
+ every frozen file, a table already created by any migration, an unclassified table, a `PARTNER_NULLABLE` one, and a
621
+ `PLATFORM` / `PLATFORM_POSTGRES_ONLY` / `EXCLUDED` one (no `partner_id`, no policy: nothing to generate, so it says
622
+ to create the table in an ordinary migration). **A `--number` below the highest existing migration is refused unless
623
+ `--fill-gap` is given**: such a file sorts before files already applied elsewhere, runs in a different order on a
624
+ fresh database than on an old one, and is easy to miss in review. The pair is written whole or not at all: both files
625
+ to temporary names in the same folder, then linked into place (never over an existing file); on any failure both
626
+ are removed.
627
+
628
+ `check` polices every migration NOT in `frozen`, whatever its name. Each scoped table created there carries exactly
629
+ the generated index, `ENABLE`, `FORCE` and policy (byte for byte) and the generated `partner_id` in both files;
630
+ every key into a scoped table carries `partner_id` on both sides; no `SET DEFAULT`, no `SET NULL` without a column
631
+ list or naming a tenant column; no `ON UPDATE CASCADE` on an attribution key; no other policy, RLS statement, or
632
+ ADD / ALTER / DROP / RENAME of a scoped table's `partner_id`; no data statement that sets `partner_id` (undeclared);
633
+ no DROP TABLE of a tenant table (one the manifest scopes, or one any migration gave a `partner_id`) undeclared, and
634
+ no RENAME TO, view or foreign table taking such a name; and no privilege beyond SELECT / INSERT / UPDATE / DELETE on a
635
+ table or USAGE on a sequence or schema — GRANT ALL, TRUNCATE (which ignores row-level security), WITH GRANT OPTION, a
636
+ role granted to a role, CREATE / ALTER ROLE, ALTER DEFAULT PRIVILEGES, ALTER FUNCTION, SECURITY DEFINER, OWNER TO,
637
+ REASSIGN OWNED and SET ROLE are refused unless declared. What a line reader cannot read safely (DO, functions, dollar
638
+ quotes, rules, triggers, views without `security_invoker`, other schemas, the runner markers, …) is refused. Every
639
+ problem names its file and the statement. The tables born after the frozen list are derived twice (the manifest's
640
+ scoped tables no frozen file creates; the scoped tables a policed file creates) and must agree.
641
+
642
+ **Library:** `require('@aria-framework/db-worker/tenancyGenerator')` gives `loadConfig`, `render`, `skeleton`,
643
+ `checkTree`, `planNew`, `writePair` and `compareKeys` (the offline half of an app's live comparison of its keys with
644
+ `pg_constraint`). It is not spread onto the index.
645
+
646
+ #### What `check` cannot see
647
+
648
+ A line reader of files cannot see a database. These pass `check`, each on purpose:
649
+
650
+ | Case | Verdict | Why |
651
+ |---|---|---|
652
+ | A `.sqlite.sql` file that changes a scoped table | accepted | It never runs on Postgres (`selectForDialect`), and SQLite has one tenant and no policies. Its statements still pass through every refusal. |
653
+ | `SET row_security = off` | accepted | For a role without BYPASSRLS it makes a query a policy would filter fail with an error rather than read past the policy, and it lasts for the migration's session only. |
654
+ | A `customer_id` column added to a PARTNER table | accepted | An app without a customer tier uses it as an ordinary column; the policy still binds `partner_id`. A customer-tier app's live policy test catches a table missing from its `CUSTOMER` map. |
655
+ | A policed file that adds platform tables only | accepted | Correct; an app that expects more says so with `floors.tables`. |
656
+ | `REVOKE` | accepted | It only takes privileges away. |
657
+ | A key whose `ON DELETE` is `CASCADE` where the model meant `NO ACTION` | accepted | Both keep the tenant columns intact; the choice is the model's. |
658
+ | Dropping a scoped table, moving rows between partners, a privilege beyond the four | declared | Refused unless an `exceptions` entry names it with a reason. |
659
+ | A database changed by hand, a half-applied migration, a restore with row security off | not visible | No file changes. The app's live checks catch these; `compareKeys` is the offline half of its key comparison. |
660
+ | A table never classified and never created | not visible | The app's classification guard (every live table is in the manifest) catches it. |
661
+
662
+ An app whose existing tenancy migrations came from the older generator (`generateTenancyMigration`, by ALTER over a
663
+ SQLite snapshot) lists every applied file in `frozen` and uses `new` for tables from then on; `check` does not read
664
+ frozen files except to learn which tables they create or give a `partner_id` and which CHECK constraints they declare.
665
+
666
+ `test/tenancyGenerator.js` regenerates the tenancy of one app's hand-typed 022–024 byte for byte from its manifest
667
+ (verbatim fixtures, each hashed against its git blob), passes `check` over that app's whole tree, fails each rule
668
+ on a broken copy, runs the review's 48 bad migrations and 4 population probes (`test/fixtures/tenancy-attacks.js`,
669
+ each with its verdict), runs the skeleton on SQLite and on PGlite with real RLS, runs the command as a child process
670
+ with the database drivers made unloadable, holds the hub's own composite keys to `requireUpdateCascade`, and
671
+ compares four other apps' latest tenancy pairs.
672
+
673
+ #### Adopting `aria-tenancy`
674
+
675
+ | App | `aria.tenancy.json` |
676
+ |---|---|
677
+ | A new app (the starter) | `partnerIdType: "BIGINT"`, `frozen` its applied files, `noneAfterFrozen: true` until its first new table. |
678
+ | The wall app | `partnerIdType: "INTEGER"` (its policed files carry it), `frozen` its 24 files through 021, `floors` 11 / 35, and one `moveRows` exception for its 030 (the site URL row moved to the installation row). |
679
+ | The hub | `requireUpdateCascade: true` (it moves customers between partners), `partnerIdType: "BIGINT"`, every existing file frozen. |
680
+ | The soc, noc and desk apps | Every existing file frozen, `noneAfterFrozen: true`, `partnerIdType: "BIGINT"`. |
681
+
682
+ The four apps that freeze every existing file need no compatibility rule: `check` reads nothing of their older,
683
+ retrofitted migrations, and they use the command for new tables only. Their own generator wrappers stay as history
684
+ (applied headers name them).
685
+
686
+ ### What changes for an adopting app
687
+
688
+ Nothing changes for an app that only bumps the version. These are the differences an app meets when it
689
+ replaces its own copy with the package's. Each was checked against the app copies on 28 Nov 2026.
690
+
691
+ | Area | What changes | What the app does |
692
+ |---|---|---|
693
+ | A test that stubs the app's `lib/database.driver` to make `sql` render the Postgres form | Once `lib/sql.js` is a re-export, `sql` reads the PACKAGE's `database.driver()`. A stub on the app's `lib/database` export object no longer reaches it. Found in the hub's `scripts/test-package-store-tenancy.js`, the soc app's `scripts/test-sender-hold.js` and the desk app's `scripts/test-sql-dialect.js`. | Stub `require('@aria-framework/db-worker').database.driver`, which is the function `sql` calls. Also stub the app's `lib/database.driver` where the app's own models read it. |
694
+ | Scope assertions on SQLite | `assertPlatformScope` / `assertPartnerScope` do nothing on SQLite (they return null), as their source did. Some app copies of the same idea refuse on SQLite as well. They check `currentTenant()` there (the soc app's `AgentRelease` and `lib/triage/registryInput.js`), or throw "runs on Postgres only" (`ActorAddress`). | Keep the app's own wrapper where it needs the SQLite refusal. |
695
+ | Scope-refusal wording | The package says `<label> must run at platform scope (asPlatform), not "<scope>"` (or `partner scope (asPartner)`). App copies vary ("must run at PLATFORM scope", "must run at its scope", "is the house's, at platform scope only"). | Update the tests that match the old wording, or keep the app's own code. |
696
+ | `clearOwn` | There is no hook for an app-specific refusal. The hub refuses brand keys with `settings_key_in_document`. | Keep that refusal in the app's model, around the package's `clearOwn`. |
697
+ | `isUniqueViolation` | It treats SQLite's `SQLITE_CONSTRAINT_PRIMARYKEY` as a duplicate. The desk app's copy did not. | Nothing, unless a caller relied on a primary-key clash NOT reading as a duplicate. |
698
+ | `isDatabaseError(null)` | Returns false. The desk app's copy threw a TypeError. | Nothing. |
699
+ | `createTenantSettings` with `afterWrite` | `set` / `setMultiple` write only when the value changed, for EVERY key, and answer `{ changes }`. The hub's source did this for brand keys only and used the plain upsert for the rest. | A hook meant for some keys filters them itself (`if (!BRAND_KEYS.has(key)) return;`). |
700
+ | `aria-tenancy` | New; nothing runs until the app adds `aria.tenancy.json` and the command to its suite. The wall app passes `partnerIdType: "INTEGER"` and its `moveRows` exception; the hub passes `requireUpdateCascade: true`; the four apps that freeze every existing file need no compatibility rule. | See "Adopting `aria-tenancy`" above. |
701
+ | The tenant filter (`TENANT_EXPR`, and `createTenantSettings`' reads) | The CASE form. The hub's `lib/sql.js` and `models/Settings.js` still use the older COALESCE form. | The hub switches when it adopts, with a measured query plan (`EXPLAIN (ANALYZE, BUFFERS)` before and after) in its pull request. |
702
+
455
703
  ## Changelog
456
704
 
705
+ - **0.29.0** — The tenancy core (above), additive: `sql`, `defineTenancy` + `TENANCY_POLICY_EXPRESSION`,
706
+ `assertPlatformScope`, `assertPartnerScope`, `keepTenant`, `tenantCacheKey`, `createTenantSettings`, the
707
+ `DbClient` option `onRefusal` and `runMigrations`' `squashedFrom`. And the **`aria-tenancy` command** (`bin`,
708
+ `bin/tenancy.js`; library `tenancyGenerator.js`): `new` writes a new table's migration pair from the manifest
709
+ named in the app's `aria.tenancy.json`, `check` holds every migration after the app's frozen list to the
710
+ generated statements, the composite-key rules, the tenant-table name rules (no undeclared DROP, no rename or view into a tenant name, no ADD COLUMN partner_id) and the privilege rules (no TRUNCATE, ALL, role grants, roles, default privileges, SECURITY DEFINER, OWNER TO), with declared `exceptions`; `partnerIdType` is stated by the app, and `requireUpdateCascade` is the hub's option. The older SQLite-reading `generateTenancyMigration` is
711
+ unchanged and stays exported. No existing export, option or default changes. Tests (PGlite with real RLS and
712
+ SQLite, in `npm test`): `sql.js`, `tenancyManifest.js`, `tenantScope.js`, `tenantSettings.js`,
713
+ `dbClientRefusal.js`, `migrationsSquash.js`, `tenancyGenerator.js`.
457
714
  - **0.28.0** — `driver.inTransaction()` on both drivers, and a model method's `outsideTransaction = true` skips the
458
715
  worker's per-invoke transaction on a pooled driver (above). Additive: no method is marked unless the app marks it.
459
716
  For `@aria-framework/auth` 0.18.0's SQL attempt store, which refuses a claim inside a transaction.
package/bin/tenancy.js ADDED
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * aria-tenancy — the tenancy of a new table, generated from the app's manifest (tenancyGenerator.js has the rules).
4
+ *
5
+ * aria-tenancy new <table...> [--name <slug>] [--number <NNN> [--fill-gap]] write a NEW .sql / .postgres.sql pair
6
+ * aria-tenancy new --print <table...> print the generated statements; write nothing
7
+ * aria-tenancy check exit 1 unless every policed migration carries
8
+ * exactly the generated statements
9
+ *
10
+ * Run from the app's folder (or below it): the nearest folder with a package.json is the app, and its
11
+ * aria.tenancy.json says where the manifest and the migrations are. Nothing else of the app is loaded, and no
12
+ * database is opened.
13
+ */
14
+ 'use strict';
15
+
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+ const gen = require('../tenancyGenerator');
19
+
20
+ const USAGE = 'usage: aria-tenancy new <table...> [--name <slug>] [--number <NNN> [--fill-gap]] [--print]\n aria-tenancy check';
21
+ const fail = (msg) => { console.error(`aria-tenancy: ${msg}`); process.exit(1); };
22
+
23
+ function appDir() {
24
+ let dir = process.cwd();
25
+ for (;;) {
26
+ if (fs.existsSync(path.join(dir, 'package.json'))) return dir;
27
+ const up = path.dirname(dir);
28
+ if (up === dir) fail(`no package.json in ${process.cwd()} or any folder above it — run this in the app's folder`);
29
+ dir = up;
30
+ }
31
+ }
32
+
33
+ const argv = process.argv.slice(2);
34
+ const command = argv.shift();
35
+ if (command !== 'new' && command !== 'check') fail(`${command ? `unknown command "${command}"` : 'no command'}\n${USAGE}`);
36
+
37
+ let config;
38
+ let manifest;
39
+ try {
40
+ config = gen.loadConfig(appDir());
41
+ manifest = gen.loadManifest(config);
42
+ } catch (e) { fail(e.message); }
43
+
44
+ if (command === 'check') {
45
+ if (argv.length) fail(`check takes no arguments, got ${argv.join(' ')}`);
46
+ let result;
47
+ try { result = gen.checkTree(gen.checkOptions(config, manifest)); } catch (e) { fail(e.message); }
48
+ const { problems, stats } = result;
49
+ console.log(`tenancy of the tables born after the frozen migrations (aria-tenancy check, ${config.migrationsName}/):`);
50
+ console.log(` ${stats.tables.length} scoped table(s) in ${config.manifestName} born after the frozen migrations; ${stats.created.length} created by a policed migration`);
51
+ console.log(` ${stats.statementsCompared} generated statement(s) compared, ${stats.keysChecked} key(s) into scoped tables checked (${stats.pgKeys} Postgres), across ${stats.files} policed migration file(s)`);
52
+ if (problems.length) {
53
+ for (const p of problems) console.log(` ✗ ${p}`);
54
+ console.log(`\n${problems.length} problem(s) — regenerate with aria-tenancy new; never hand-write tenancy.`);
55
+ process.exit(1);
56
+ }
57
+ console.log(' ✓ every one carries exactly the generator\'s statements');
58
+ process.exit(0);
59
+ }
60
+
61
+ // new
62
+ const opt = (name) => {
63
+ const i = argv.indexOf('--' + name);
64
+ if (i === -1) return null;
65
+ const v = argv[i + 1];
66
+ if (v === undefined || v.startsWith('--')) fail(`--${name} needs a value`);
67
+ argv.splice(i, 2);
68
+ return v;
69
+ };
70
+ const flag = (n) => { const i = argv.indexOf('--' + n); if (i === -1) return false; argv.splice(i, 1); return true; };
71
+ const print = flag('print');
72
+ const fillGap = flag('fill-gap');
73
+ const name = opt('name');
74
+ const number = opt('number');
75
+ if (argv.some((a) => a.startsWith('--'))) fail(`unknown option ${argv.find((a) => a.startsWith('--'))}\n${USAGE}`);
76
+ const tables = argv;
77
+ if (!tables.length) fail(`name at least one table (classified in ${config.manifestName} first)`);
78
+
79
+ try {
80
+ if (print) {
81
+ if (new Set(tables).size !== tables.length) fail('a table is named twice');
82
+ const preExisting = gen.createdByFrozen(gen.readTree(config.migrationsDir), config.frozen, new Set(manifest.scoped().map((s) => s.table)));
83
+ for (const t of tables) {
84
+ const g = gen.render(manifest, t, gen.renderOptions(config, preExisting));
85
+ console.log(`-- ${t}: inside its CREATE TABLE (Postgres): partner_id ${g.pgPartnerId},`);
86
+ console.log(`-- ${t}: inside its CREATE TABLE (SQLite): partner_id ${g.sqlitePartnerId},`);
87
+ console.log([g.index, ...g.rls].join('\n') + '\n');
88
+ }
89
+ process.exit(0);
90
+ }
91
+ const { files } = gen.planNew(config, manifest, tables, { name, number, fillGap });
92
+ // Both or neither: temporaries first, then linked into place (never over an existing file); a failure removes both.
93
+ gen.writePair(config.migrationsDir, files);
94
+ console.log(` wrote ${Object.keys(files).map((f) => `${config.migrationsName}/${f}`).join(' and ')} — add the tables' own columns, then run aria-tenancy check`);
95
+ } catch (e) {
96
+ fail(e.message);
97
+ }
package/client.js CHANGED
@@ -39,8 +39,19 @@ class DbClient {
39
39
  * the process keeps running with every invoke() rejecting — a silent outage
40
40
  * supervisors keyed on process exit cannot see. Recommended app policy:
41
41
  * set process.exitCode = 1 and trigger the app's graceful shutdown.
42
+ * @param {(model: string, err: Error) => (void|Promise<void>)} [opts.onRefusal] - 0.29.0.
43
+ * Called (and awaited) after an invoke REJECTS, before the caller sees the
44
+ * rejection, which is always the original error whatever the hook does. For
45
+ * "a refusal that must outlive its own rollback": every pooled invoke is one
46
+ * transaction, so a model that audits a refusal and then throws loses the
47
+ * audit row too. The model attaches what must be recorded to its error and
48
+ * the hook writes it as its OWN invoke, after the rollback, in the caller's
49
+ * tenant (the hook runs in the caller's async context). A throwing hook is
50
+ * logged, never thrown. The hook's own invokes pass through it as well, so a
51
+ * hook writing through this client ignores its own model's errors (an audit
52
+ * hook skips model 'Audit'). Default: none, and invoke() is what it was.
42
53
  */
43
- constructor({ workerPath, logger, callTimeoutMs, slowMs, queueWarnMs, onWorkerDeath } = {}) {
54
+ constructor({ workerPath, logger, callTimeoutMs, slowMs, queueWarnMs, onWorkerDeath, onRefusal } = {}) {
44
55
  if (!workerPath) throw new Error('DbClient: workerPath is required');
45
56
  this._workerPath = workerPath;
46
57
  this._logger = logger || console;
@@ -48,6 +59,8 @@ class DbClient {
48
59
  this._slowMs = slowMs === undefined ? 500 : slowMs;
49
60
  this._queueWarnMs = queueWarnMs === undefined ? 1000 : queueWarnMs;
50
61
  this._onWorkerDeath = typeof onWorkerDeath === 'function' ? onWorkerDeath : null;
62
+ if (onRefusal != null && typeof onRefusal !== 'function') throw new Error('DbClient: onRefusal must be a function');
63
+ this._onRefusal = onRefusal || null;
51
64
  this._deathNotified = false;
52
65
  // Queue-warn coalescing: under real saturation EVERY completed call crosses
53
66
  // the threshold — one line each would flood the log (disk I/O during the
@@ -203,6 +216,18 @@ class DbClient {
203
216
  * @returns {Promise<any>}
204
217
  */
205
218
  invoke(model, method, ...args) {
219
+ const p = this._invoke(model, method, args);
220
+ if (!this._onRefusal) return p;
221
+ return p.catch(async (err) => {
222
+ try { await this._onRefusal(model, err); } catch (e) {
223
+ this._logger.error(`onRefusal hook failed for ${model}.${method}: ${e.message}`);
224
+ }
225
+ throw err;
226
+ });
227
+ }
228
+
229
+ /** @private The round trip itself: invoke() before 0.29.0, unchanged. */
230
+ _invoke(model, method, args) {
206
231
  if (!this._worker) {
207
232
  return Promise.reject(new Error('Database worker not initialized'));
208
233
  }
package/database.js CHANGED
@@ -354,10 +354,14 @@ function runMigrations(migrationsDir, opts = {}) {
354
354
  _logger.info(`Migration skipped (not for ${d.kind}): ${skipped}`);
355
355
  }
356
356
 
357
+ // 0.29.0 — validated on every engine, so a malformed option fails where it is written.
358
+ const squash = squashedFromOption(opts.squashedFrom, files);
359
+
357
360
  // ── the synchronous path, unchanged in behaviour since 0.1.0 ──────────────────────────────
358
361
  if (d.kind === 'sqlite') {
359
362
  const db = d.raw;
360
363
  const applied = new Set(db.prepare('SELECT filename FROM migrations').all().map((r) => r.filename));
364
+ if (squash) assertNotPreSquash(applied, squash);
361
365
  let count = 0;
362
366
  for (const file of files) {
363
367
  if (applied.has(file)) continue;
@@ -541,6 +545,56 @@ function runMigrations(migrationsDir, opts = {}) {
541
545
  }
542
546
  }
543
547
 
548
+ /**
549
+ * 0.29.0 — `runMigrations(dir, { squashedFrom })`: refuse a database that predates a squash.
550
+ *
551
+ * The runner keys on FILENAME: it applies any file absent from the ledger. A database created
552
+ * before an app squashed its chain into one baseline records the OLD files and has never seen the
553
+ * baseline — so the runner executes the baseline against a fully-populated database, its first
554
+ * `CREATE TABLE` fails with "table already exists", the transaction rolls back and the worker dies
555
+ * on every boot, with a message that names a SQL error and no cause. One query turns that outage
556
+ * into an instruction (moved from the desk app, which met it on a restored old data directory).
557
+ *
558
+ * DELIBERATELY NOT AUTO-REPAIRED: recording the baseline on the operator's behalf would assert
559
+ * "this database already matches the baseline", which nobody has verified.
560
+ *
561
+ * SQLITE ONLY, as in the app it came from: the history it detects ended before that app could open
562
+ * Postgres. On Postgres the option is validated and nothing is checked.
563
+ *
564
+ * `squashedFrom` is a filename from the old chain (`'001_initial_schema.sql'`) or
565
+ * `{ file, baseline, remedy }`: `baseline` defaults to the first migration in the directory for
566
+ * this engine, `remedy` replaces the default instructions after the first paragraph.
567
+ */
568
+ function squashedFromOption(opt, files) {
569
+ if (opt == null) return null;
570
+ const o = typeof opt === 'string' ? { file: opt } : opt;
571
+ if (!o || typeof o !== 'object' || typeof o.file !== 'string' || !o.file.endsWith('.sql')) {
572
+ throw new Error("runMigrations: squashedFrom must be an old migration's filename, or { file, baseline, remedy }");
573
+ }
574
+ const baseline = o.baseline == null ? files[0] : o.baseline;
575
+ if (typeof baseline !== 'string' || !baseline.endsWith('.sql')) {
576
+ throw new Error('runMigrations: squashedFrom has no baseline (pass { baseline }, or keep the baseline in the directory)');
577
+ }
578
+ if (o.remedy != null && typeof o.remedy !== 'string') throw new Error('runMigrations: squashedFrom.remedy must be text');
579
+ return { file: o.file, baseline, remedy: o.remedy == null ? null : o.remedy };
580
+ }
581
+
582
+ function assertNotPreSquash(applied, { file, baseline, remedy }) {
583
+ if (applied.has(baseline)) return; // post-squash, fine
584
+ if (!applied.has(file)) return; // not a pre-squash database (a fresh one has an empty ledger)
585
+ throw new Error(
586
+ `This database was created before the migration squash: it records ${applied.size} old migrations ` +
587
+ `(${file} among them) and has never applied ${baseline}. Running migrations would try to ` +
588
+ 'CREATE TABLE over the existing schema and fail.\n\n' +
589
+ (remedy || (
590
+ ' Either (recommended): stop the app, move the database file aside and start it again —\n' +
591
+ ' the baseline builds a fresh database.\n\n' +
592
+ ' Or, to keep the existing data (only if you are certain its schema already matches the\n' +
593
+ ' baseline):\n' +
594
+ ` INSERT INTO migrations (filename) VALUES ('${baseline}');`))
595
+ );
596
+ }
597
+
544
598
  /** Adopt the handle init() just opened — the driver must not open a second connection. */
545
599
  function _adoptSqliteDriver(db) {
546
600
  const { createSqliteDriver } = require('./driver/sqlite');
package/index.js CHANGED
@@ -11,7 +11,7 @@
11
11
 
12
12
  // 0.6.0 — MULTI-ENGINE. The driver contract (get/all/run/exec/transaction + dialect +
13
13
  // concurrency) lets a store be written once and run on either engine, selected per APP. SQLite
14
- // stays the default and Support101 never moves; app 3 boots with kind:'postgres'. `pg` and
14
+ // stays the default for the app that started on it; a later app boots with kind:'postgres'. `pg` and
15
15
  // better-sqlite3 are both OPTIONAL peers — neither consumer installs the other's driver.
16
16
  const { createSqliteDriver } = require('./driver/sqlite');
17
17
  const { createPostgresDriver } = require('./driver/postgres');
@@ -46,5 +46,13 @@ module.exports = {
46
46
  // 0.19.0 — the tenancy migration generator. The manifest of which tables belong to a tenant is
47
47
  // the app's; turning it into partner_id columns, composite foreign keys and RLS policies is
48
48
  // mechanical, identical everywhere, and far too intricate to retype per app.
49
- ...require('./tenancyMigration')
49
+ ...require('./tenancyMigration'),
50
+ // 0.29.0 — the tenancy core every multi-tenant app carried as its own copy. `sql` (the dialect
51
+ // helpers and the CASE tenant filter, resolved from this package's database.driver() at call
52
+ // time); `defineTenancy` (the frozen policy text, all(), scoped()); the scope assertions,
53
+ // keepTenant and tenantCacheKey; the tenant settings layer.
54
+ sql: require('./sql'),
55
+ ...require('./tenancyManifest'),
56
+ ...require('./tenantScope'),
57
+ ...require('./tenantSettings')
50
58
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.28.0",
3
+ "version": "0.29.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,
@@ -8,17 +8,26 @@
8
8
  "access": "public"
9
9
  },
10
10
  "main": "index.js",
11
+ "bin": {
12
+ "aria-tenancy": "bin/tenancy.js"
13
+ },
11
14
  "files": [
12
15
  "client.js",
16
+ "bin/",
13
17
  "database.js",
14
18
  "dialect.js",
15
19
  "driver/",
16
20
  "index.js",
17
21
  "schemaSnapshot.js",
18
22
  "settingsStore.js",
23
+ "sql.js",
19
24
  "tableOrder.js",
25
+ "tenancyManifest.js",
26
+ "tenancyGenerator.js",
20
27
  "tenancyMigration.js",
21
28
  "tenantContext.js",
29
+ "tenantScope.js",
30
+ "tenantSettings.js",
22
31
  "worker.js",
23
32
  "workerRegistry.js"
24
33
  ],
@@ -40,7 +49,7 @@
40
49
  "pg": "^8.23.0"
41
50
  },
42
51
  "scripts": {
43
- "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationFailureSurfaces.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/tenancyAttribution.pglite.js && node test/tenancyNullable.pg.js && node test/tenancyPartnerFk.pg.js && node test/tenancyOnUpdate.pg.js && node test/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/clientError.pg.js && node test/migrationRole.pg.js && node test/smoke.js && node test/tier2.js && node test/timezone.pg.js && node test/pinPoolUtc.js && node test/pinAwaited.pg.js && node test/inTransaction.js",
52
+ "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationFailureSurfaces.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/tenancyAttribution.pglite.js && node test/tenancyNullable.pg.js && node test/tenancyPartnerFk.pg.js && node test/tenancyOnUpdate.pg.js && node test/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/clientError.pg.js && node test/migrationRole.pg.js && node test/smoke.js && node test/tier2.js && node test/timezone.pg.js && node test/pinPoolUtc.js && node test/pinAwaited.pg.js && node test/inTransaction.js && node test/sql.js && node test/tenancyManifest.js && node test/tenantScope.js && node test/tenantSettings.js && node test/dbClientRefusal.js && node test/migrationsSquash.js && node test/tenancyGenerator.js",
44
53
  "prepublishOnly": "node ../../test/packaging.js db-worker"
45
54
  }
46
55
  }