@aria-framework/db-worker 0.27.2 → 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 +277 -0
- package/bin/tenancy.js +97 -0
- package/client.js +26 -1
- package/database.js +54 -0
- package/driver/postgres.js +13 -0
- package/driver/sqlite.js +10 -0
- package/index.js +10 -2
- package/package.json +11 -2
- package/sql.js +395 -0
- package/tenancyGenerator.js +964 -0
- package/tenancyManifest.js +115 -0
- package/tenantScope.js +120 -0
- package/tenantSettings.js +301 -0
- package/worker.js +9 -2
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `defineTenancy(lists)` (0.29.0) — the fixed machinery of an app's `config/tenancy.js`.
|
|
3
|
+
*
|
|
4
|
+
* An app's `config/tenancy.js` answers "which tables belong to a partner, and which to the
|
|
5
|
+
* platform", and that answer is the app's: its lists stay in its file. What every app carried
|
|
6
|
+
* beside them, identical in all six, is machinery: the frozen row-level-security expression,
|
|
7
|
+
* `all()` and `scoped()`. That moves here, so an app's file ends
|
|
8
|
+
*
|
|
9
|
+
* module.exports = defineTenancy({ PARTNER, PLATFORM, PARTNER_NULLABLE, EXCLUDED,
|
|
10
|
+
* PLATFORM_POSTGRES_ONLY, WIDEN_UNIQUE, ... });
|
|
11
|
+
*
|
|
12
|
+
* ANY OTHER KEY PASSES THROUGH UNTOUCHED — an app with a customer tier keeps its own map and its
|
|
13
|
+
* own expression for it, and an app without a `GLOBAL_BY_VALUE` bucket simply passes none.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
'use strict';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The RLS predicate, used VERBATIM for both USING and WITH CHECK on every scoped table.
|
|
20
|
+
*
|
|
21
|
+
* FROZEN. This text is inside migrations every app has already applied and pinned by sha256; a
|
|
22
|
+
* changed character here would make a generated migration disagree with every database that ran the
|
|
23
|
+
* old one. test/tenancyManifest.js pins its sha256 and holds it byte-equal to every app's copy.
|
|
24
|
+
*
|
|
25
|
+
* Every piece of it is load-bearing, and the asymmetry between the two lookups is the part that
|
|
26
|
+
* looks like a mistake and is not:
|
|
27
|
+
*
|
|
28
|
+
* current_setting('app.scope', true) MISSING_OK. An unset scope must return NULL so the
|
|
29
|
+
* CASE can reach the tenant arm rather than throwing
|
|
30
|
+
* before it can branch.
|
|
31
|
+
* current_setting('app.partner_id')::int STRICT. The missing_ok form returns NULL, so
|
|
32
|
+
* `partner_id = NULL` is NULL and the query returns
|
|
33
|
+
* ZERO ROWS WITH NO ERROR — a background job that lost
|
|
34
|
+
* its context would process nothing, for ever,
|
|
35
|
+
* silently. The strict form throws: fail closed, loud.
|
|
36
|
+
*
|
|
37
|
+
* CASE, not OR SQL OR has no guaranteed short-circuit, so a platform
|
|
38
|
+
* caller with no partner set could reach the strict
|
|
39
|
+
* lookup and throw.
|
|
40
|
+
*/
|
|
41
|
+
const POLICY_EXPRESSION = `
|
|
42
|
+
CASE current_setting('app.scope', true)
|
|
43
|
+
WHEN 'platform' THEN true
|
|
44
|
+
ELSE partner_id = current_setting('app.partner_id')::int
|
|
45
|
+
END`;
|
|
46
|
+
|
|
47
|
+
/** The four lists that together are "every table with a decision" — what `all()` returns. */
|
|
48
|
+
const DECIDED = ['PARTNER', 'PLATFORM', 'PARTNER_NULLABLE', 'EXCLUDED'];
|
|
49
|
+
|
|
50
|
+
/** Computed here; an app passing its own would be a second definition of the same answer. */
|
|
51
|
+
const COMPUTED = ['all', 'scoped'];
|
|
52
|
+
|
|
53
|
+
const isMap = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @param {object} lists the app's classification: PARTNER, PLATFORM, PARTNER_NULLABLE, EXCLUDED
|
|
57
|
+
* ({ table: reason } maps; an absent one is empty), PLATFORM_POSTGRES_ONLY, WIDEN_UNIQUE,
|
|
58
|
+
* NOT_WIDENED_ON_PURPOSE, GLOBAL_BY_VALUE, NO_CASCADE, and anything else, all passed through.
|
|
59
|
+
* @returns {object} the lists, plus POLICY_EXPRESSION, all() and scoped()
|
|
60
|
+
*/
|
|
61
|
+
function defineTenancy(lists) {
|
|
62
|
+
if (!isMap(lists)) throw new Error('defineTenancy: pass the app\'s lists, e.g. { PARTNER: {...}, PLATFORM: {...} }');
|
|
63
|
+
if (Object.prototype.hasOwnProperty.call(lists, 'POLICY_EXPRESSION') && lists.POLICY_EXPRESSION !== POLICY_EXPRESSION) {
|
|
64
|
+
throw new Error('defineTenancy: POLICY_EXPRESSION is frozen — it is inside migrations every app has applied. '
|
|
65
|
+
+ 'Remove it from the lists; the package supplies it.');
|
|
66
|
+
}
|
|
67
|
+
for (const k of COMPUTED) {
|
|
68
|
+
if (Object.prototype.hasOwnProperty.call(lists, k)) throw new Error(`defineTenancy: ${k}() is computed from the lists; do not pass one`);
|
|
69
|
+
}
|
|
70
|
+
for (const k of DECIDED) {
|
|
71
|
+
if (lists[k] !== undefined && !isMap(lists[k])) throw new Error(`defineTenancy: ${k} must be a { table: reason } map`);
|
|
72
|
+
}
|
|
73
|
+
if (lists.PLATFORM_POSTGRES_ONLY !== undefined && !isMap(lists.PLATFORM_POSTGRES_ONLY)) {
|
|
74
|
+
throw new Error('defineTenancy: PLATFORM_POSTGRES_ONLY must be a { table: reason } map');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const out = { ...lists };
|
|
78
|
+
for (const k of DECIDED) if (out[k] === undefined) out[k] = {};
|
|
79
|
+
const { PARTNER, PLATFORM, PARTNER_NULLABLE, EXCLUDED } = out;
|
|
80
|
+
|
|
81
|
+
// ── PLATFORM_POSTGRES_ONLY IS NEVER IN all() ───────────────────────────────────────────────
|
|
82
|
+
//
|
|
83
|
+
// all() is what the classification guard compares against the live SQLITE schema, in BOTH
|
|
84
|
+
// directions — a live table missing from the list, and a listed table that no longer exists ("a
|
|
85
|
+
// rule that inspects nothing"). A Postgres-only table (the session store's) has no SQLite
|
|
86
|
+
// counterpart, so naming it there fails immediately, correctly. The desk app wrote that down as a
|
|
87
|
+
// comment after including it once; here it is a rule: such a table may not also sit in one of
|
|
88
|
+
// the four lists, or all() would hold it after all.
|
|
89
|
+
const pgOnly = Object.keys(out.PLATFORM_POSTGRES_ONLY || {});
|
|
90
|
+
for (const t of pgOnly) {
|
|
91
|
+
for (const k of DECIDED) {
|
|
92
|
+
if (Object.prototype.hasOwnProperty.call(out[k], t)) {
|
|
93
|
+
throw new Error(`defineTenancy: "${t}" is in PLATFORM_POSTGRES_ONLY and in ${k}; a Postgres-only table must `
|
|
94
|
+
+ 'not be in all(), which the classification guard compares with the SQLite schema');
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
out.POLICY_EXPRESSION = POLICY_EXPRESSION;
|
|
100
|
+
/** Every table with a decision, in any list — what the classification guard checks against. */
|
|
101
|
+
out.all = () => [
|
|
102
|
+
...Object.keys(PARTNER),
|
|
103
|
+
...Object.keys(PLATFORM),
|
|
104
|
+
...Object.keys(PARTNER_NULLABLE),
|
|
105
|
+
...Object.keys(EXCLUDED)
|
|
106
|
+
];
|
|
107
|
+
/** The tables that get a partner_id and a policy, with whether the column may be NULL. */
|
|
108
|
+
out.scoped = () => [
|
|
109
|
+
...Object.keys(PARTNER).map((table) => ({ table, nullable: false })),
|
|
110
|
+
...Object.keys(PARTNER_NULLABLE).map((table) => ({ table, nullable: true }))
|
|
111
|
+
];
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
module.exports = { defineTenancy, TENANCY_POLICY_EXPRESSION: POLICY_EXPRESSION };
|
package/tenantScope.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small tenant helpers (0.29.0), each moved from the one app that had it.
|
|
3
|
+
*
|
|
4
|
+
* assertPlatformScope(d, label) refuse unless the TRANSACTION's scope is platform (Postgres only)
|
|
5
|
+
* assertPartnerScope(d, label) refuse unless it is one partner's (Postgres only)
|
|
6
|
+
* keepTenant(middleware | list) a callback-style middleware's `next` runs back inside the tenant
|
|
7
|
+
* tenantCacheKey([tenant]) one keying rule for per-tenant caches
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
'use strict';
|
|
11
|
+
|
|
12
|
+
const { runWithTenant, currentTenant } = require('./tenantContext');
|
|
13
|
+
|
|
14
|
+
const SCOPE_SQL = "SELECT current_setting('app.scope', true) AS scope, "
|
|
15
|
+
+ "NULLIF(current_setting('app.partner_id', true), '') AS partner";
|
|
16
|
+
|
|
17
|
+
function requireDriver(d, fn) {
|
|
18
|
+
if (!d || typeof d.get !== 'function' || !d.dialect) {
|
|
19
|
+
throw new Error(`${fn}(d, label): d must be a db-worker driver (pass database.driver() at call time)`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function refused(message) {
|
|
24
|
+
const e = new Error(message);
|
|
25
|
+
e.code = 'tenant_scope_refused';
|
|
26
|
+
return e;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Refuse unless this transaction runs at PLATFORM scope.
|
|
31
|
+
*
|
|
32
|
+
* For a model method that reads or counts across partners: asked from a partner context the
|
|
33
|
+
* policy would return that partner's rows alone, and each count would silently be its own. So the
|
|
34
|
+
* method refuses before it reads, rather than relying on the permission in front of it alone.
|
|
35
|
+
*
|
|
36
|
+
* THE SESSION IS ASKED, not the caller's word: `current_setting('app.scope')` is what the policy
|
|
37
|
+
* itself reads in the same transaction, so the check cannot disagree with it.
|
|
38
|
+
*
|
|
39
|
+
* POSTGRES ONLY, as in the app it came from: SQLite holds one tenant and has no session settings,
|
|
40
|
+
* so there it returns null and refuses nothing.
|
|
41
|
+
*
|
|
42
|
+
* @param {object} d the driver (database.driver(), read at call time)
|
|
43
|
+
* @param {string} label names the caller in the refusal, e.g. 'Partner.listWithCounts'
|
|
44
|
+
* @returns {Promise<{scope: string, partnerId: number|null}|null>} the scope, or null on SQLite
|
|
45
|
+
*/
|
|
46
|
+
async function assertPlatformScope(d, label) {
|
|
47
|
+
requireDriver(d, 'assertPlatformScope');
|
|
48
|
+
if (d.dialect.kind !== 'postgres') return null;
|
|
49
|
+
const s = await d.get(SCOPE_SQL);
|
|
50
|
+
if (!s || s.scope !== 'platform') {
|
|
51
|
+
throw refused(`${label} must run at platform scope (asPlatform), not "${s && s.scope}"`);
|
|
52
|
+
}
|
|
53
|
+
return { scope: s.scope, partnerId: s.partner == null ? null : Number(s.partner) };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Refuse unless this transaction runs at ONE PARTNER'S scope (a partner id set, scope 'partner').
|
|
58
|
+
*
|
|
59
|
+
* For a read of "this partner's own row" that must never take the house as "this partner": at
|
|
60
|
+
* platform scope the tenant expression names the house. Postgres only, as above.
|
|
61
|
+
*/
|
|
62
|
+
async function assertPartnerScope(d, label) {
|
|
63
|
+
requireDriver(d, 'assertPartnerScope');
|
|
64
|
+
if (d.dialect.kind !== 'postgres') return null;
|
|
65
|
+
const s = await d.get(SCOPE_SQL);
|
|
66
|
+
if (!s || s.scope !== 'partner' || !s.partner) {
|
|
67
|
+
throw refused(`${label} must run at partner scope (asPartner), not "${s && s.scope}"`);
|
|
68
|
+
}
|
|
69
|
+
return { scope: s.scope, partnerId: Number(s.partner) };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* KEEP THE TENANT ACROSS A CALLBACK-STYLE MIDDLEWARE.
|
|
74
|
+
*
|
|
75
|
+
* multer/busboy call a middleware's `next` from a stream event, outside the AsyncLocalStorage
|
|
76
|
+
* context the app opened for the request — so on Postgres (the pooled driver) the handler after an
|
|
77
|
+
* upload ran with NO tenant and every db call threw "invoked with no tenant context" (found on an
|
|
78
|
+
* app's stage server; SQLite does not enforce it, so the suites passed). This wraps the middleware
|
|
79
|
+
* so the context in force BEFORE it is restored for whatever runs after it. With no context in
|
|
80
|
+
* force, `next` is called as it was.
|
|
81
|
+
*
|
|
82
|
+
* Takes one middleware and returns one, or a list (an upload pair) and returns a list.
|
|
83
|
+
* Each wrapper is named `keepTenantMw` and carries the middleware it wraps as `.wrapped`, for an
|
|
84
|
+
* app's identity checks ("is every mounted pair wrapped?").
|
|
85
|
+
*/
|
|
86
|
+
function keepTenant(mw) {
|
|
87
|
+
if (Array.isArray(mw)) return mw.map((one) => keepTenant(one));
|
|
88
|
+
if (typeof mw !== 'function') throw new Error('keepTenant: pass a middleware (req, res, next) or a list of them');
|
|
89
|
+
const keepTenantMw = function keepTenantMw(req, res, next) {
|
|
90
|
+
const ctx = currentTenant();
|
|
91
|
+
return mw(req, res, (err) => (ctx ? runWithTenant(ctx, () => next(err)) : next(err)));
|
|
92
|
+
};
|
|
93
|
+
keepTenantMw.wrapped = mw;
|
|
94
|
+
return keepTenantMw;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* How a per-tenant cache is keyed. ONE decision, one implementation (it was four copies in one
|
|
99
|
+
* app, and a change made four times is made three).
|
|
100
|
+
*
|
|
101
|
+
* PLATFORM SCOPE GETS ITS OWN BUCKET. The policy answers `true` at platform scope, so a read there
|
|
102
|
+
* legitimately returns EVERY tenant's rows. That is a different answer from any partner's and must
|
|
103
|
+
* not be stored under a partner's key — nor a partner's under it. `partnerId` is part of the
|
|
104
|
+
* platform key because asHouse() and asPlatform() are both platform scope with different ids.
|
|
105
|
+
*
|
|
106
|
+
* With no argument it keys the context in force (currentTenant()); pass a tenant to key that one —
|
|
107
|
+
* a main-thread cache whose tenancy module tracks its own context passes it.
|
|
108
|
+
*
|
|
109
|
+
* @param {{scope?: string, partnerId?: number|null}|null} [tenant]
|
|
110
|
+
* @returns {string} 'none', 'platform:<id or empty>' or 'p:<id>'
|
|
111
|
+
*/
|
|
112
|
+
function tenantCacheKey(tenant) {
|
|
113
|
+
const t = arguments.length === 0 ? currentTenant() : tenant;
|
|
114
|
+
if (!t) return 'none';
|
|
115
|
+
return t.scope === 'platform'
|
|
116
|
+
? `platform:${t.partnerId == null ? '' : t.partnerId}`
|
|
117
|
+
: `p:${t.partnerId}`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
module.exports = { assertPlatformScope, assertPartnerScope, keepTenant, tenantCacheKey };
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createTenantSettings (0.29.0) — the tenant layer over createSettingsStore that every multi-tenant
|
|
3
|
+
* app carried in its own `models/Settings.js`.
|
|
4
|
+
*
|
|
5
|
+
* Under the tenancy migration `settings` is PARTNER_NULLABLE: a row per partner per key, plus a
|
|
6
|
+
* row at `partner_id IS NULL` that is the installation-wide default. On Postgres a key therefore no
|
|
7
|
+
* longer identifies one row, and the plain store's `WHERE key = ?` returns one row PER TENANT at
|
|
8
|
+
* platform scope (the policy answers `true` there) — the house's settings page once rendered a
|
|
9
|
+
* reseller's brand name and timezone, `get` and `getByPrefix` disagreed about one key in one
|
|
10
|
+
* transaction, and `all()` returned 19 rows for 16 keys. Two halves, two bugs:
|
|
11
|
+
*
|
|
12
|
+
* the WHERE stops the read crossing tenants
|
|
13
|
+
* the ORDER implements the precedence PARTNER_NULLABLE claims: own row first, NULL row after
|
|
14
|
+
*
|
|
15
|
+
* Composed from the apps, block by block: the starter's own-then-installation readers and
|
|
16
|
+
* `getInstallation` / `setInstallation`; the hub's write-only-when-changed `setInstallation`,
|
|
17
|
+
* `getOwn`, `clearOwn` and its model-level refusal of a platform-only key below platform scope;
|
|
18
|
+
* the soc app's strict own read (`getOwn(key, { partnerScopeOnly: true })`) and
|
|
19
|
+
* `claimInstallationRun`. Typed getters (session timeout, timezone, brand) stay in the app's model,
|
|
20
|
+
* which spreads this beside them.
|
|
21
|
+
*
|
|
22
|
+
* ON SQLITE nothing here is tenant-aware, exactly as the apps' copies: `key` is still the primary
|
|
23
|
+
* key there and there is one tenant, so a key identifies one row by construction and
|
|
24
|
+
* `current_setting` does not exist.
|
|
25
|
+
*
|
|
26
|
+
* THE DRIVER IS A GETTER, read on every call. The apps built their store from `database.driver()`
|
|
27
|
+
* at require time, which binds to the first driver in the process; a test bridge that opens a
|
|
28
|
+
* second one then writes through the old handle.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
'use strict';
|
|
32
|
+
|
|
33
|
+
const { createSettingsStore } = require('./settingsStore');
|
|
34
|
+
const { currentTenant } = require('./tenantContext');
|
|
35
|
+
const { assertPartnerScope } = require('./tenantScope');
|
|
36
|
+
const { TENANT_EXPR } = require('./sql');
|
|
37
|
+
|
|
38
|
+
const PLATFORM_ONLY = 'settings_key_platform_only';
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @param {object} [opts]
|
|
42
|
+
* @param {() => object} [opts.driver] a GETTER for the driver; default: this package's database.driver()
|
|
43
|
+
* @param {(key: string) => boolean} [opts.platformOnly] keys that may be written from platform
|
|
44
|
+
* scope only. Default: no key — what the starter does today. The hub passes its catalogue.
|
|
45
|
+
* @param {(tx: object, info: {key: string, partnerId: number|null}) => Promise<void>} [opts.afterWrite]
|
|
46
|
+
* runs on the writing transaction after a write that CHANGED a row (the hub bumps the partner's
|
|
47
|
+
* sync version). `partnerId` is the row's: null for the installation row. Default: none, and then
|
|
48
|
+
* `set` / `setMultiple` are the plain store's statements, unchanged.
|
|
49
|
+
* @param {string} [opts.table='settings']
|
|
50
|
+
* @param {string} [opts.label='Settings'] names the model in refusals
|
|
51
|
+
*/
|
|
52
|
+
function createTenantSettings(opts = {}) {
|
|
53
|
+
const getDriver = opts.driver || (() => require('./database').driver());
|
|
54
|
+
if (typeof getDriver !== 'function') {
|
|
55
|
+
throw new Error('createTenantSettings: `driver` must be a GETTER — () => database.driver() — not a driver '
|
|
56
|
+
+ 'captured at require time');
|
|
57
|
+
}
|
|
58
|
+
const platformOnly = opts.platformOnly || (() => false);
|
|
59
|
+
if (typeof platformOnly !== 'function') throw new Error('createTenantSettings: platformOnly must be (key) => boolean');
|
|
60
|
+
const afterWrite = opts.afterWrite || null;
|
|
61
|
+
if (afterWrite !== null && typeof afterWrite !== 'function') throw new Error('createTenantSettings: afterWrite must be a function');
|
|
62
|
+
const table = opts.table || 'settings';
|
|
63
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) throw new Error(`createTenantSettings: suspicious table name "${table}"`);
|
|
64
|
+
const label = opts.label || 'Settings';
|
|
65
|
+
|
|
66
|
+
const SCOPED = `(partner_id = ${TENANT_EXPR} OR partner_id IS NULL)`;
|
|
67
|
+
const PREFER_OWN = 'partner_id NULLS LAST';
|
|
68
|
+
|
|
69
|
+
function driver() {
|
|
70
|
+
const d = getDriver();
|
|
71
|
+
if (!d) throw new Error(`${label}: no driver yet — call database.init()/initDriver() first`);
|
|
72
|
+
return d;
|
|
73
|
+
}
|
|
74
|
+
const isPg = (d) => d.dialect.kind === 'postgres';
|
|
75
|
+
|
|
76
|
+
// One plain store per driver, built on first use. The conflict target is the app's constraint,
|
|
77
|
+
// not the store's default: on Postgres the tenancy migration replaces `key TEXT PRIMARY KEY`
|
|
78
|
+
// with `UNIQUE NULLS NOT DISTINCT (partner_id, key)`, and `ON CONFLICT(key)` against that is a
|
|
79
|
+
// REFUSED STATEMENT — reads work and every write fails.
|
|
80
|
+
const stores = new WeakMap();
|
|
81
|
+
function storeFor(d) {
|
|
82
|
+
let s = stores.get(d);
|
|
83
|
+
if (!s) {
|
|
84
|
+
s = createSettingsStore({ driver: d, table, conflictTarget: isPg(d) ? 'partner_id, key' : 'key' });
|
|
85
|
+
stores.set(d, s);
|
|
86
|
+
}
|
|
87
|
+
return s;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** currentTenant() is null for a caller with no scope at all — treated as not platform. */
|
|
91
|
+
const atPlatform = () => (currentTenant() || {}).scope === 'platform';
|
|
92
|
+
const str = (value) => (value == null ? null : String(value));
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The store's upsert, run on `tx`, writing only when the value CHANGED and naming the row's
|
|
96
|
+
* partner — the shape the hook needs. Used only when afterWrite is given.
|
|
97
|
+
*/
|
|
98
|
+
async function writeOne(d, tx, key, value) {
|
|
99
|
+
const conflict = isPg(d) ? 'partner_id, key' : 'key';
|
|
100
|
+
const row = await tx.get(
|
|
101
|
+
`INSERT INTO ${table} (key, value) VALUES (?, ?)
|
|
102
|
+
ON CONFLICT (${conflict}) DO UPDATE SET value = excluded.value
|
|
103
|
+
WHERE ${table}.value IS DISTINCT FROM excluded.value
|
|
104
|
+
RETURNING partner_id`,
|
|
105
|
+
[key, str(value)]
|
|
106
|
+
);
|
|
107
|
+
if (row) await afterWrite(tx, { key, partnerId: row.partner_id == null ? null : Number(row.partner_id) });
|
|
108
|
+
return row ? 1 : 0;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function setInstallation(key, value) {
|
|
112
|
+
const d = driver();
|
|
113
|
+
// NULL IS A VALUE, and `String(null)` is the four-character string "null": a three-state
|
|
114
|
+
// field (NULL when blank, '' for "none", the text otherwise) collapsed into the literal once.
|
|
115
|
+
const v = str(value);
|
|
116
|
+
// ONE ATOMIC STATEMENT PER ENGINE, IN A TRANSACTION, RETURNING A ROW ONLY WHEN SOMETHING MOVED.
|
|
117
|
+
// SQLite conflicts on `key` (its primary key, partner_id defaulting to 1) and forces partner_id
|
|
118
|
+
// back to NULL, so this and set() agree about one row; a stray partner row there is repaired
|
|
119
|
+
// even when the value is unchanged.
|
|
120
|
+
return d.transaction(async (tx) => {
|
|
121
|
+
const moved = isPg(d)
|
|
122
|
+
? await tx.get(
|
|
123
|
+
`INSERT INTO ${table} (key, value, partner_id) VALUES (?, ?, NULL)
|
|
124
|
+
ON CONFLICT (partner_id, key) DO UPDATE SET value = excluded.value
|
|
125
|
+
WHERE ${table}.value IS DISTINCT FROM excluded.value
|
|
126
|
+
RETURNING key`,
|
|
127
|
+
[key, v]
|
|
128
|
+
)
|
|
129
|
+
: await tx.get(
|
|
130
|
+
`INSERT INTO ${table} (key, value, partner_id) VALUES (?, ?, NULL)
|
|
131
|
+
ON CONFLICT (key) DO UPDATE SET value = excluded.value, partner_id = NULL
|
|
132
|
+
WHERE ${table}.value IS DISTINCT FROM excluded.value OR ${table}.partner_id IS NOT NULL
|
|
133
|
+
RETURNING key`,
|
|
134
|
+
[key, v]
|
|
135
|
+
);
|
|
136
|
+
if (moved && afterWrite) await afterWrite(tx, { key, partnerId: null });
|
|
137
|
+
return { ok: true };
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const api = {
|
|
142
|
+
/** Raw value: this tenant's own row, else the installation's, else null. */
|
|
143
|
+
async get(key) {
|
|
144
|
+
const d = driver();
|
|
145
|
+
if (!isPg(d)) return storeFor(d).get(key);
|
|
146
|
+
const row = await d.get(
|
|
147
|
+
`SELECT value FROM ${table} WHERE key = ? AND ${SCOPED} ORDER BY ${PREFER_OWN} LIMIT 1`, [key]);
|
|
148
|
+
return row ? row.value : null;
|
|
149
|
+
},
|
|
150
|
+
|
|
151
|
+
/** { key: value } for keys starting with `prefix` (LIKE-escaped: `_` is a wildcard), own row first. */
|
|
152
|
+
async getByPrefix(prefix) {
|
|
153
|
+
const d = driver();
|
|
154
|
+
if (!isPg(d)) return storeFor(d).getByPrefix(prefix);
|
|
155
|
+
const esc = String(prefix).replace(/[\\%_]/g, (c) => '\\' + c);
|
|
156
|
+
const rows = await d.all(
|
|
157
|
+
`SELECT DISTINCT ON (key) key, value FROM ${table}
|
|
158
|
+
WHERE ${SCOPED} AND key LIKE ? ESCAPE '\\'
|
|
159
|
+
ORDER BY key, ${PREFER_OWN}`,
|
|
160
|
+
[esc + '%']
|
|
161
|
+
);
|
|
162
|
+
const out = {};
|
|
163
|
+
for (const r of rows) out[r.key] = r.value;
|
|
164
|
+
return out;
|
|
165
|
+
},
|
|
166
|
+
|
|
167
|
+
/** Every key once, as [{ key, value }] ordered by key. DISTINCT ON keeps the first row per key
|
|
168
|
+
* given the ORDER BY, so the ordering is the mechanism rather than a tidy-up. */
|
|
169
|
+
async all() {
|
|
170
|
+
const d = driver();
|
|
171
|
+
if (!isPg(d)) return storeFor(d).all();
|
|
172
|
+
return d.all(
|
|
173
|
+
`SELECT DISTINCT ON (key) key, value FROM ${table}
|
|
174
|
+
WHERE ${SCOPED}
|
|
175
|
+
ORDER BY key, ${PREFER_OWN}`
|
|
176
|
+
);
|
|
177
|
+
},
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Upsert one setting in the caller's tenant (partner_id from its session default).
|
|
181
|
+
*
|
|
182
|
+
* A key `platformOnly` names may be written from platform scope only, ENFORCED HERE rather
|
|
183
|
+
* than only at a route: a gate a caller can bypass by writing straight to the model is not a
|
|
184
|
+
* gate. A platform-only key set from partner scope is exactly how an installation key ends up
|
|
185
|
+
* on one tenant's row instead of the partnerless one setInstallation() writes. Both engines.
|
|
186
|
+
*/
|
|
187
|
+
async set(key, value) {
|
|
188
|
+
if (platformOnly(key) && !atPlatform()) throw new Error(PLATFORM_ONLY);
|
|
189
|
+
const d = driver();
|
|
190
|
+
if (!afterWrite) return storeFor(d).set(key, value);
|
|
191
|
+
return d.transaction(async (tx) => ({ changes: await writeOne(d, tx, key, value) }));
|
|
192
|
+
},
|
|
193
|
+
|
|
194
|
+
/** Several in ONE transaction; `undefined` values are skipped. The same platform-only rule. */
|
|
195
|
+
async setMultiple(keyValues) {
|
|
196
|
+
if (!atPlatform()) {
|
|
197
|
+
const bad = Object.keys(keyValues || {}).filter((k) => platformOnly(k));
|
|
198
|
+
if (bad.length) throw new Error(PLATFORM_ONLY);
|
|
199
|
+
}
|
|
200
|
+
const d = driver();
|
|
201
|
+
if (!afterWrite) return storeFor(d).setMultiple(keyValues);
|
|
202
|
+
const entries = Object.entries(keyValues || {}).filter(([, v]) => v !== undefined);
|
|
203
|
+
await d.transaction(async (tx) => {
|
|
204
|
+
for (const [k, v] of entries) await writeOne(d, tx, k, v);
|
|
205
|
+
});
|
|
206
|
+
},
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* An INSTALLATION value — the row at `partner_id IS NULL`, never shadowed by a partner's.
|
|
210
|
+
*
|
|
211
|
+
* get()'s precedence is right for a brand name and wrong for a kill switch. Works from any
|
|
212
|
+
* scope, including none: the policy's USING admits the NULL row explicitly. On SQLite the
|
|
213
|
+
* key's one row (single tenant: the installation's value and the tenant's are the same value).
|
|
214
|
+
*/
|
|
215
|
+
async getInstallation(key) {
|
|
216
|
+
const d = driver();
|
|
217
|
+
if (!isPg(d)) {
|
|
218
|
+
const row = await d.get(`SELECT value FROM ${table} WHERE key = ?`, [key]);
|
|
219
|
+
return row ? row.value : null;
|
|
220
|
+
}
|
|
221
|
+
// ORDER BY, not just LIMIT 1: a read that is deterministic on its own does not depend on a
|
|
222
|
+
// constraint added later.
|
|
223
|
+
const row = await d.get(
|
|
224
|
+
`SELECT value FROM ${table} WHERE key = ? AND partner_id IS NULL ORDER BY value LIMIT 1`, [key]);
|
|
225
|
+
return row ? row.value : null;
|
|
226
|
+
},
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Write an INSTALLATION value, explicitly at `partner_id IS NULL`, only when it changed.
|
|
230
|
+
* MUST BE CALLED AT PLATFORM SCOPE, and the database enforces it: the nullable table's WITH
|
|
231
|
+
* CHECK admits a NULL partner_id through the platform arm only.
|
|
232
|
+
*/
|
|
233
|
+
setInstallation,
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* A key's value from THIS TENANT'S OWN ROW ONLY — never the installation's, even when this
|
|
237
|
+
* tenant has none. For a caller that needs to KNOW whether a value is set (a partner reading its
|
|
238
|
+
* own brand keys must see blank, so its resolver applies its own default).
|
|
239
|
+
*
|
|
240
|
+
* At platform scope the tenant expression names the house, so this answers the house's own
|
|
241
|
+
* row. `{ partnerScopeOnly: true }` refuses there instead — for a per-partner job that must
|
|
242
|
+
* never read the house as "this partner". Postgres only; on SQLite the key's one row.
|
|
243
|
+
*/
|
|
244
|
+
async getOwn(key, { partnerScopeOnly = false } = {}) {
|
|
245
|
+
const d = driver();
|
|
246
|
+
if (!isPg(d)) {
|
|
247
|
+
const row = await d.get(`SELECT value FROM ${table} WHERE key = ?`, [key]);
|
|
248
|
+
return row ? row.value : null;
|
|
249
|
+
}
|
|
250
|
+
if (partnerScopeOnly) await assertPartnerScope(d, `${label}.getOwn reads one partner's own row and`);
|
|
251
|
+
const row = await d.get(`SELECT value FROM ${table} WHERE key = ? AND partner_id = ${TENANT_EXPR} LIMIT 1`, [key]);
|
|
252
|
+
return row ? row.value : null;
|
|
253
|
+
},
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* DROP THIS TENANT'S OWN ROW, so it inherits the installation's value again. A platform-only
|
|
257
|
+
* key has no partner rows to drop and is refused. On SQLite (one row per key, one tenant)
|
|
258
|
+
* nothing is deleted.
|
|
259
|
+
*/
|
|
260
|
+
async clearOwn(key) {
|
|
261
|
+
if (platformOnly(key)) throw new Error(PLATFORM_ONLY);
|
|
262
|
+
const d = driver();
|
|
263
|
+
if (!isPg(d)) return { changes: 0 };
|
|
264
|
+
const r = await d.run(`DELETE FROM ${table} WHERE key = ? AND partner_id = ${TENANT_EXPR}`, [key]);
|
|
265
|
+
return { changes: Number(r.changes) };
|
|
266
|
+
},
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* CLAIM AN INSTALLATION "RUNNING" MARK, ATOMICALLY: under an advisory lock on the key
|
|
270
|
+
* (Postgres; it lasts as long as the caller's transaction, which on a pooled worker is the
|
|
271
|
+
* invoke), read the installation value; if it is a JSON record `{ running: {...} }` or
|
|
272
|
+
* `{ running: true, started_at }` younger than `staleMs`, refuse (false); otherwise write
|
|
273
|
+
* `value` and answer true. Two presses at once: exactly one claims. SQLite has one writer.
|
|
274
|
+
* A record is aged by its `updated_at` when it has one (a run that writes its progress is alive
|
|
275
|
+
* while it writes), else by `started_at`. An unreadable value counts as no claim.
|
|
276
|
+
*/
|
|
277
|
+
async claimInstallationRun(key, value, staleMs) {
|
|
278
|
+
const d = driver();
|
|
279
|
+
const pg = isPg(d);
|
|
280
|
+
if (pg) await d.get('SELECT pg_advisory_xact_lock(hashtext(?)) AS l', [`settings:${key}`]);
|
|
281
|
+
const row = await d.get(pg
|
|
282
|
+
? `SELECT value FROM ${table} WHERE key = ? AND partner_id IS NULL`
|
|
283
|
+
: `SELECT value FROM ${table} WHERE key = ?`, [key]);
|
|
284
|
+
let cur = null;
|
|
285
|
+
try { cur = row && row.value ? JSON.parse(row.value) : null; } catch (e) { cur = null; }
|
|
286
|
+
const run = cur && cur.running && typeof cur.running === 'object' ? cur.running : cur;
|
|
287
|
+
if (run && run.running) {
|
|
288
|
+
const age = Date.now() - Date.parse(`${String(run.updated_at || run.started_at).replace(' ', 'T')}Z`);
|
|
289
|
+
if (age < Number(staleMs)) return false;
|
|
290
|
+
}
|
|
291
|
+
// `this` when the app spread this object into its model (so an override of setInstallation is
|
|
292
|
+
// honoured, as the source did); the package's own otherwise.
|
|
293
|
+
const self = this && typeof this.setInstallation === 'function' ? this : api;
|
|
294
|
+
await self.setInstallation(key, value);
|
|
295
|
+
return true;
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
return api;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
module.exports = { createTenantSettings };
|
package/worker.js
CHANGED
|
@@ -43,7 +43,7 @@ function currentDriver() {
|
|
|
43
43
|
* On a serial driver (SQLite) there is no RLS and nothing to set. The context is still
|
|
44
44
|
* established so a model can read it, and no transaction is forced around a read.
|
|
45
45
|
*/
|
|
46
|
-
async function withTenant(tenant, label, dispatch) {
|
|
46
|
+
async function withTenant(tenant, label, dispatch, { outsideTransaction = false } = {}) {
|
|
47
47
|
const driver = currentDriver();
|
|
48
48
|
if (!driver || driver.concurrency !== 'pool') {
|
|
49
49
|
return tenant ? runWithTenant(tenant, dispatch) : dispatch();
|
|
@@ -56,6 +56,13 @@ async function withTenant(tenant, label, dispatch) {
|
|
|
56
56
|
'Wrap the caller in runWithTenant({ scope, partnerId }, ...).'
|
|
57
57
|
);
|
|
58
58
|
}
|
|
59
|
+
// 0.28.0 — a method that DECLARES `outsideTransaction = true` runs with the context set but no
|
|
60
|
+
// transaction around it: each statement autocommits on its own pooled connection and carries NO
|
|
61
|
+
// transaction-local scope. Only for statements on tables with no row-level policy (a PLATFORM
|
|
62
|
+
// table); on a scoped table the strict policy refuses them, which fails closed. It exists for
|
|
63
|
+
// writes that must commit even when the caller then fails — an attempt claim
|
|
64
|
+
// (@aria-framework/auth 0.18.0), which a rollback would otherwise erase.
|
|
65
|
+
if (outsideTransaction) return runWithTenant(tenant, dispatch);
|
|
59
66
|
return runWithTenant(tenant, () => driver.transaction(async (tx) => {
|
|
60
67
|
await tx.run(APPLY_SQL, applyParams(tenant));
|
|
61
68
|
return dispatch();
|
|
@@ -132,7 +139,7 @@ async function runWorker({ init }) {
|
|
|
132
139
|
r = await r; // async methods (e.g. bcrypt-backed user ops)
|
|
133
140
|
}
|
|
134
141
|
return r;
|
|
135
|
-
});
|
|
142
|
+
}, { outsideTransaction: target[method].outsideTransaction === true });
|
|
136
143
|
|
|
137
144
|
result = sanitizeForTransfer(result);
|
|
138
145
|
parentPort.postMessage({ id, result, execMs: Math.round(performance.now() - t0) });
|