@aria-framework/db-worker 0.28.0 → 0.30.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 +330 -0
- package/bin/tenancy.js +97 -0
- package/client.js +47 -2
- package/customerPin.js +144 -0
- package/customerScope.js +115 -0
- package/database.js +54 -0
- package/index.js +14 -2
- package/package.json +13 -2
- package/sql.js +395 -0
- package/tenancyGenerator.js +970 -0
- package/tenancyManifest.js +183 -0
- package/tenantScope.js +120 -0
- package/tenantSettings.js +301 -0
- package/worker.js +40 -5
package/README.md
CHANGED
|
@@ -452,8 +452,338 @@ 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
|
+
|
|
703
|
+
## The customer pin (0.30.0)
|
|
704
|
+
|
|
705
|
+
A third level under the tenant context's two: work done for ONE customer of ONE partner (a customer's own people, a
|
|
706
|
+
device of one customer). It holds at two locks, both in this package; the lists stay the app's.
|
|
707
|
+
|
|
708
|
+
```js
|
|
709
|
+
// main thread
|
|
710
|
+
const db = new DbClient({ workerPath, logger, customerPin: true });
|
|
711
|
+
runWithTenant({ scope: 'partner', partnerId: 7 },
|
|
712
|
+
() => runPinned({ partnerId: 7, customerId: 'c_123', contactId: 'p_9' }, () => db.invoke('Media', 'list')));
|
|
713
|
+
// (@aria-framework/tenancy's asCustomer(partnerId, customerId, fn, { contactId }) does both)
|
|
714
|
+
|
|
715
|
+
// worker entry
|
|
716
|
+
runWorker({ init, customerScope: (models) => createCustomerScope({ safe: CUSTOMER_SAFE, models }) });
|
|
717
|
+
```
|
|
718
|
+
|
|
719
|
+
| Export | What it does | What it refuses |
|
|
720
|
+
|---|---|---|
|
|
721
|
+
| `runPinned({ partnerId, customerId, contactId }, fn)` | runs `fn` pinned (AsyncLocalStorage; restored after `fn` returns or throws) | a partner that is not a positive whole number (a number or a digit string; not `true`, `'7.0'`, `' 7'`); a customer or contact id that is not a letter or digit then letters, digits, `_`, `-` (at most 64) |
|
|
722
|
+
| `currentPin()` | the pin in force, frozen, or null | |
|
|
723
|
+
| `activePin()` | the pin to apply to an invoke made NOW: the pin, only while the tenant in force is `'partner'` scope at the pin's own partner | |
|
|
724
|
+
| `pinnedCustomer()`, `pinClause(col)` | the model-layer half: the pinned customer, or ` AND <col> = ?` and its params (nothing outside a pin) | `pinClause`: a `col` that is not a column name |
|
|
725
|
+
| `runUnpinnedFor({ partnerId, customerId }, fn)` | leaves the pin for the app's own follow-up about that same pair | a pin in force for any other pair |
|
|
726
|
+
| `createCustomerScope({ safe, models, customerId?, contactId? })` | the worker's lock: under a pin only a listed method runs. It only DECIDES; the worker runs the method from its own registry, by the same dispatch as an unpinned call, so a scope built over another object cannot change what runs | a list naming anything but a registered model's OWN function property (so never `constructor`, `toString`, `hasOwnProperty`, `valueOf`, `__proto__`); with a pin: a method that is not the model's own in the worker's registry, an unlisted method, every method when the list is `{}`, an `outsideTransaction` method, a tenant that is not partner scope at the pin's partner, an id the app's own check rejects. Code `CUSTOMER_SCOPE_REFUSED` |
|
|
727
|
+
| `DbClient` option `customerPin` | `true`: an invoke under an active pin carries it as the message's `pin` | `false` (default): such an invoke is refused, never run unpinned |
|
|
728
|
+
| `runWorker` option `customerScope` | `(models) => createCustomerScope(...)`, called once after `init` | without it every pinned invoke is refused |
|
|
729
|
+
| `PIN_SQL`, `pinParams(pin)` | the statement the worker runs, inside the invoke's transaction, right AFTER `APPLY_SQL` | |
|
|
730
|
+
| `CUSTOMER_POLICY_EXPRESSION(column)` | the customer table's policy text, frozen (below) | a column that is not a plain lower-case name |
|
|
731
|
+
|
|
732
|
+
**A rule for the adopting app: a customer-safe model is a plain object whose methods are its own properties.** A model
|
|
733
|
+
that is an instance of a class holds its methods on the class's prototype, so none of them can be listed:
|
|
734
|
+
`createCustomerScope` throws when the worker starts, and the app does not boot. Write such a model as an object literal
|
|
735
|
+
(or assign the methods onto the instance) before listing it. Without a pin nothing changes: an inherited method still
|
|
736
|
+
runs as it always did.
|
|
737
|
+
|
|
738
|
+
**What reaches the database.** On a pooled driver a pinned invoke is: `BEGIN`; `APPLY_SQL` (`'partner'`, the partner);
|
|
739
|
+
`SELECT set_config('app.scope', 'customer', true) AS s, set_config('app.customer_id', ?, true) AS c`; the model,
|
|
740
|
+
inside the worker's own pin; `COMMIT`. Both settings are transaction-local, so nothing of a pin survives into the next
|
|
741
|
+
invoke on the same connection. The contact is carried to the worker (`currentPin().contactId`) and is NEVER a
|
|
742
|
+
database setting: no policy reads it. On SQLite nothing is set; the safe list and the model's own predicate hold.
|
|
743
|
+
|
|
744
|
+
**Why the pin is dropped outside its partner's scope.** `activePin()` answers null under a platform-scope context
|
|
745
|
+
(an app's `asHouse` / `asPlatform`) and under another partner's scope, so an invoke made there goes UNPINNED. This is
|
|
746
|
+
on purpose: an app that widens (an audit row written at the house, a credential lookup) does it in the open, with
|
|
747
|
+
`runWithTenant`, as every widening in this family is — and a pin is never applied at a scope its policy arm was not
|
|
748
|
+
written for (the worker refuses a pin whose partner is not the tenant's, and any pin at platform scope).
|
|
749
|
+
|
|
750
|
+
**No change for an app that never pins.** No pin in force: the message is `{ id, model, method, args, tenant }` as
|
|
751
|
+
before, the worker sends the same statements, and `defineTenancy` adds no key to a manifest without `CUSTOMER`.
|
|
752
|
+
|
|
753
|
+
### `CUSTOMER_POLICY_EXPRESSION(column)` — frozen
|
|
754
|
+
|
|
755
|
+
The policy of a table in the manifest's `CUSTOMER` map (`{ table: customer column }`): `TENANCY_POLICY_EXPRESSION`'s
|
|
756
|
+
two arms plus `WHEN 'customer' THEN partner_id = current_setting('app.partner_id')::int AND <column> =
|
|
757
|
+
current_setting('app.customer_id')`. Both lookups strict: a pin that lost its customer errors or matches nothing,
|
|
758
|
+
never widens. The text is the one the first app with a customer tier applied in its migrations (022 to 055 at its
|
|
759
|
+
commit `553e262`); `test/tenancyManifest.js` pins its sha256 and `test/tenancyGenerator.js` rebuilds every one of that
|
|
760
|
+
app's applied customer policies (one per table in its `CUSTOMER` map) from this function, byte for byte. The generator (`aria-tenancy`) uses it for a
|
|
761
|
+
CUSTOMER table. A manifest that still carries its own `CUSTOMER_POLICY_EXPRESSION` is accepted only when it produces
|
|
762
|
+
the same text (for every column its `CUSTOMER` names, and `customer_id`), and refused otherwise.
|
|
763
|
+
|
|
455
764
|
## Changelog
|
|
456
765
|
|
|
766
|
+
- **0.30.0** — The customer pin (above), moved in from the first app that built it: `runPinned`, `runUnpinnedFor`,
|
|
767
|
+
`currentPin`, `activePin`, `pinnedCustomer`, `pinClause`, `normalisePin`, `isPinId`, `PIN_SQL`, `pinParams`;
|
|
768
|
+
`createCustomerScope`; the `DbClient` option `customerPin` and the `runWorker` option `customerScope`;
|
|
769
|
+
`CUSTOMER_POLICY_EXPRESSION` (frozen) and `assertSameCustomerPolicy`. Additive for an app without a customer tier:
|
|
770
|
+
an unpinned invoke's message and statements are byte for byte what they were. **One behaviour change**, for a
|
|
771
|
+
manifest with a customer tier: its own `CUSTOMER_POLICY_EXPRESSION` must produce the package's text (it passed
|
|
772
|
+
through `defineTenancy` untouched before, and the generator rendered it), and `defineTenancy` refuses a `CUSTOMER`
|
|
773
|
+
value that is not a column name; a manifest with a `CUSTOMER` map and no function now gets the package's text
|
|
774
|
+
(the generator threw before). Only one app has a customer tier, and its function produces the package's text.
|
|
775
|
+
Tests (in `npm test`): `customerPin.js` (a real worker, the recording driver), `customerPin.pglite.js` (a real
|
|
776
|
+
worker over PGlite, real row-level security as a non-owner, non-superuser role), and new checks in
|
|
777
|
+
`tenancyManifest.js` and `tenancyGenerator.js`.
|
|
778
|
+
- **0.29.0** — The tenancy core (above), additive: `sql`, `defineTenancy` + `TENANCY_POLICY_EXPRESSION`,
|
|
779
|
+
`assertPlatformScope`, `assertPartnerScope`, `keepTenant`, `tenantCacheKey`, `createTenantSettings`, the
|
|
780
|
+
`DbClient` option `onRefusal` and `runMigrations`' `squashedFrom`. And the **`aria-tenancy` command** (`bin`,
|
|
781
|
+
`bin/tenancy.js`; library `tenancyGenerator.js`): `new` writes a new table's migration pair from the manifest
|
|
782
|
+
named in the app's `aria.tenancy.json`, `check` holds every migration after the app's frozen list to the
|
|
783
|
+
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
|
|
784
|
+
unchanged and stays exported. No existing export, option or default changes. Tests (PGlite with real RLS and
|
|
785
|
+
SQLite, in `npm test`): `sql.js`, `tenancyManifest.js`, `tenantScope.js`, `tenantSettings.js`,
|
|
786
|
+
`dbClientRefusal.js`, `migrationsSquash.js`, `tenancyGenerator.js`.
|
|
457
787
|
- **0.28.0** — `driver.inTransaction()` on both drivers, and a model method's `outsideTransaction = true` skips the
|
|
458
788
|
worker's per-invoke transaction on a pooled driver (above). Additive: no method is marked unless the app marks it.
|
|
459
789
|
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
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
const { Worker } = require('worker_threads');
|
|
16
16
|
const { currentTenant } = require('./tenantContext');
|
|
17
|
+
const { activePin } = require('./customerPin');
|
|
17
18
|
|
|
18
19
|
class DbClient {
|
|
19
20
|
/**
|
|
@@ -39,8 +40,24 @@ class DbClient {
|
|
|
39
40
|
* the process keeps running with every invoke() rejecting — a silent outage
|
|
40
41
|
* supervisors keyed on process exit cannot see. Recommended app policy:
|
|
41
42
|
* set process.exitCode = 1 and trigger the app's graceful shutdown.
|
|
43
|
+
* @param {(model: string, err: Error) => (void|Promise<void>)} [opts.onRefusal] - 0.29.0.
|
|
44
|
+
* Called (and awaited) after an invoke REJECTS, before the caller sees the
|
|
45
|
+
* rejection, which is always the original error whatever the hook does. For
|
|
46
|
+
* "a refusal that must outlive its own rollback": every pooled invoke is one
|
|
47
|
+
* transaction, so a model that audits a refusal and then throws loses the
|
|
48
|
+
* audit row too. The model attaches what must be recorded to its error and
|
|
49
|
+
* the hook writes it as its OWN invoke, after the rollback, in the caller's
|
|
50
|
+
* tenant (the hook runs in the caller's async context). A throwing hook is
|
|
51
|
+
* logged, never thrown. The hook's own invokes pass through it as well, so a
|
|
52
|
+
* hook writing through this client ignores its own model's errors (an audit
|
|
53
|
+
* hook skips model 'Audit'). Default: none, and invoke() is what it was.
|
|
54
|
+
* @param {boolean} [opts.customerPin=false] - 0.30.0. true: an invoke made while a
|
|
55
|
+
* customer pin is in force (customerPin.js activePin) carries it to the worker,
|
|
56
|
+
* which applies it (runWorker({ customerScope })). false (the default): such an
|
|
57
|
+
* invoke is REFUSED, never run unpinned. Without a pin in force, both are exactly
|
|
58
|
+
* the client they were.
|
|
42
59
|
*/
|
|
43
|
-
constructor({ workerPath, logger, callTimeoutMs, slowMs, queueWarnMs, onWorkerDeath } = {}) {
|
|
60
|
+
constructor({ workerPath, logger, callTimeoutMs, slowMs, queueWarnMs, onWorkerDeath, onRefusal, customerPin } = {}) {
|
|
44
61
|
if (!workerPath) throw new Error('DbClient: workerPath is required');
|
|
45
62
|
this._workerPath = workerPath;
|
|
46
63
|
this._logger = logger || console;
|
|
@@ -48,6 +65,10 @@ class DbClient {
|
|
|
48
65
|
this._slowMs = slowMs === undefined ? 500 : slowMs;
|
|
49
66
|
this._queueWarnMs = queueWarnMs === undefined ? 1000 : queueWarnMs;
|
|
50
67
|
this._onWorkerDeath = typeof onWorkerDeath === 'function' ? onWorkerDeath : null;
|
|
68
|
+
if (onRefusal != null && typeof onRefusal !== 'function') throw new Error('DbClient: onRefusal must be a function');
|
|
69
|
+
this._onRefusal = onRefusal || null;
|
|
70
|
+
if (customerPin !== undefined && typeof customerPin !== 'boolean') throw new Error('DbClient: customerPin must be true or false');
|
|
71
|
+
this._customerPin = customerPin === true;
|
|
51
72
|
this._deathNotified = false;
|
|
52
73
|
// Queue-warn coalescing: under real saturation EVERY completed call crosses
|
|
53
74
|
// the threshold — one line each would flood the log (disk I/O during the
|
|
@@ -203,9 +224,29 @@ class DbClient {
|
|
|
203
224
|
* @returns {Promise<any>}
|
|
204
225
|
*/
|
|
205
226
|
invoke(model, method, ...args) {
|
|
227
|
+
const p = this._invoke(model, method, args);
|
|
228
|
+
if (!this._onRefusal) return p;
|
|
229
|
+
return p.catch(async (err) => {
|
|
230
|
+
try { await this._onRefusal(model, err); } catch (e) {
|
|
231
|
+
this._logger.error(`onRefusal hook failed for ${model}.${method}: ${e.message}`);
|
|
232
|
+
}
|
|
233
|
+
throw err;
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** @private The round trip itself: invoke() before 0.29.0, unchanged. */
|
|
238
|
+
_invoke(model, method, args) {
|
|
206
239
|
if (!this._worker) {
|
|
207
240
|
return Promise.reject(new Error('Database worker not initialized'));
|
|
208
241
|
}
|
|
242
|
+
// 0.30.0 — the customer pin in force for this call, if any (customerPin.js). Read BEFORE anything is queued, so a
|
|
243
|
+
// refused call leaves nothing pending.
|
|
244
|
+
const pin = activePin();
|
|
245
|
+
if (pin && !this._customerPin) {
|
|
246
|
+
const e = new Error(`DbClient: ${model}.${method} was invoked under a customer pin, and this client was not built with { customerPin: true } — refused rather than run unpinned`);
|
|
247
|
+
e.code = 'CUSTOMER_SCOPE_REFUSED';
|
|
248
|
+
return Promise.reject(e);
|
|
249
|
+
}
|
|
209
250
|
return new Promise((resolve, reject) => {
|
|
210
251
|
this._nextId = (this._nextId + 1) % Number.MAX_SAFE_INTEGER;
|
|
211
252
|
const id = this._nextId;
|
|
@@ -222,7 +263,11 @@ class DbClient {
|
|
|
222
263
|
// The tenant context travels IN THE MESSAGE because AsyncLocalStorage does not cross a
|
|
223
264
|
// worker thread. null when the app has established none — which a pooled driver refuses
|
|
224
265
|
// on the far side rather than guessing which tenant was meant.
|
|
225
|
-
|
|
266
|
+
// The pin travels the same way, as its own field, and ONLY when one is in force: an unpinned message is
|
|
267
|
+
// byte for byte the message it always was.
|
|
268
|
+
const msg = { id, model, method, args, tenant: currentTenant() };
|
|
269
|
+
if (pin) msg.pin = pin;
|
|
270
|
+
this._worker.postMessage(msg);
|
|
226
271
|
});
|
|
227
272
|
}
|
|
228
273
|
|