@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.
@@ -0,0 +1,183 @@
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 CUSTOMER map,
13
+ * and an app without a `GLOBAL_BY_VALUE` bucket simply passes none. Since 0.30.0 the customer tier's
14
+ * policy text is the package's too (CUSTOMER_POLICY_EXPRESSION below): a manifest's own function is
15
+ * accepted only when it produces exactly that text.
16
+ */
17
+
18
+ 'use strict';
19
+
20
+ /**
21
+ * The RLS predicate, used VERBATIM for both USING and WITH CHECK on every scoped table.
22
+ *
23
+ * FROZEN. This text is inside migrations every app has already applied and pinned by sha256; a
24
+ * changed character here would make a generated migration disagree with every database that ran the
25
+ * old one. test/tenancyManifest.js pins its sha256 and holds it byte-equal to every app's copy.
26
+ *
27
+ * Every piece of it is load-bearing, and the asymmetry between the two lookups is the part that
28
+ * looks like a mistake and is not:
29
+ *
30
+ * current_setting('app.scope', true) MISSING_OK. An unset scope must return NULL so the
31
+ * CASE can reach the tenant arm rather than throwing
32
+ * before it can branch.
33
+ * current_setting('app.partner_id')::int STRICT. The missing_ok form returns NULL, so
34
+ * `partner_id = NULL` is NULL and the query returns
35
+ * ZERO ROWS WITH NO ERROR — a background job that lost
36
+ * its context would process nothing, for ever,
37
+ * silently. The strict form throws: fail closed, loud.
38
+ *
39
+ * CASE, not OR SQL OR has no guaranteed short-circuit, so a platform
40
+ * caller with no partner set could reach the strict
41
+ * lookup and throw.
42
+ */
43
+ const POLICY_EXPRESSION = `
44
+ CASE current_setting('app.scope', true)
45
+ WHEN 'platform' THEN true
46
+ ELSE partner_id = current_setting('app.partner_id')::int
47
+ END`;
48
+
49
+ /**
50
+ * 0.30.0 — the predicate for a CUSTOMER table (a table in the manifest's CUSTOMER map, table → the column naming its
51
+ * customer), VERBATIM for both USING and WITH CHECK. POLICY_EXPRESSION's two arms unchanged, plus:
52
+ *
53
+ * WHEN 'customer' a session pinned to one customer (customerPin.js: the worker sets app.scope = 'customer' and
54
+ * app.customer_id inside the invoke's transaction): its partner AND its customer. BOTH lookups
55
+ * STRICT, for the reason POLICY_EXPRESSION gives. A pin that lost its customer ERRORS OR MATCHES
56
+ * NOTHING — it errors on a connection that never set app.customer_id, and matches nothing on a
57
+ * pooled one an earlier transaction set it on (the setting then reads ''). It never widens.
58
+ *
59
+ * Partner-only tables need no change for the pin: their ELSE arm already reads 'customer' as "this partner".
60
+ *
61
+ * FROZEN, like POLICY_EXPRESSION, and for the same reason: this text is inside migrations an app has applied (the
62
+ * first app with a customer tier, from its 022 on). test/tenancyManifest.js pins its sha256 for the column
63
+ * `customer_id`, and test/tenancyGenerator.js rebuilds that app's applied policies from THIS function byte for byte.
64
+ * `column` is interpolated, so it must be a plain column name.
65
+ */
66
+ const CUSTOMER_POLICY_EXPRESSION = (column) => {
67
+ if (typeof column !== 'string' || !/^[a-z_][a-z0-9_]*$/.test(column)) {
68
+ throw new Error(`CUSTOMER_POLICY_EXPRESSION: ${JSON.stringify(column)} is not a plain column name`);
69
+ }
70
+ return `
71
+ CASE current_setting('app.scope', true)
72
+ WHEN 'platform' THEN true
73
+ WHEN 'customer' THEN partner_id = current_setting('app.partner_id')::int
74
+ AND ${column} = current_setting('app.customer_id')
75
+ ELSE partner_id = current_setting('app.partner_id')::int
76
+ END`;
77
+ };
78
+
79
+ /**
80
+ * A manifest's OWN customer policy function, held to the package's: it must produce the package's text for every
81
+ * column its CUSTOMER map names, and for the probe column `customer_id`. Throws, naming the first column that
82
+ * differs. The caller then uses the package's function.
83
+ */
84
+ function assertSameCustomerPolicy(fn, customer, name) {
85
+ if (typeof fn !== 'function') {
86
+ throw new Error(`${name}: CUSTOMER_POLICY_EXPRESSION must be a function (column) => text, or left out (the package supplies it)`);
87
+ }
88
+ const cols = new Set(['customer_id', ...Object.values(customer || {})]);
89
+ for (const c of cols) {
90
+ let theirs;
91
+ try { theirs = fn(c); } catch (e) { theirs = e; }
92
+ if (theirs !== CUSTOMER_POLICY_EXPRESSION(c)) {
93
+ throw new Error(`${name}: its CUSTOMER_POLICY_EXPRESSION(${JSON.stringify(c)}) is not the package's frozen customer policy text `
94
+ + '(the policy applied migrations carry). Remove it from the manifest; the package supplies it.');
95
+ }
96
+ }
97
+ }
98
+
99
+ /** The four lists that together are "every table with a decision" — what `all()` returns. */
100
+ const DECIDED = ['PARTNER', 'PLATFORM', 'PARTNER_NULLABLE', 'EXCLUDED'];
101
+
102
+ /** Computed here; an app passing its own would be a second definition of the same answer. */
103
+ const COMPUTED = ['all', 'scoped'];
104
+
105
+ const isMap = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
106
+
107
+ /**
108
+ * @param {object} lists the app's classification: PARTNER, PLATFORM, PARTNER_NULLABLE, EXCLUDED
109
+ * ({ table: reason } maps; an absent one is empty), PLATFORM_POSTGRES_ONLY, WIDEN_UNIQUE,
110
+ * NOT_WIDENED_ON_PURPOSE, GLOBAL_BY_VALUE, NO_CASCADE, and anything else, all passed through.
111
+ * @returns {object} the lists, plus POLICY_EXPRESSION, all() and scoped()
112
+ */
113
+ function defineTenancy(lists) {
114
+ if (!isMap(lists)) throw new Error('defineTenancy: pass the app\'s lists, e.g. { PARTNER: {...}, PLATFORM: {...} }');
115
+ if (Object.prototype.hasOwnProperty.call(lists, 'POLICY_EXPRESSION') && lists.POLICY_EXPRESSION !== POLICY_EXPRESSION) {
116
+ throw new Error('defineTenancy: POLICY_EXPRESSION is frozen — it is inside migrations every app has applied. '
117
+ + 'Remove it from the lists; the package supplies it.');
118
+ }
119
+ for (const k of COMPUTED) {
120
+ if (Object.prototype.hasOwnProperty.call(lists, k)) throw new Error(`defineTenancy: ${k}() is computed from the lists; do not pass one`);
121
+ }
122
+ for (const k of DECIDED) {
123
+ if (lists[k] !== undefined && !isMap(lists[k])) throw new Error(`defineTenancy: ${k} must be a { table: reason } map`);
124
+ }
125
+ if (lists.PLATFORM_POSTGRES_ONLY !== undefined && !isMap(lists.PLATFORM_POSTGRES_ONLY)) {
126
+ throw new Error('defineTenancy: PLATFORM_POSTGRES_ONLY must be a { table: reason } map');
127
+ }
128
+ // 0.30.0 — the customer tier. CUSTOMER is the app's ({ table: column }); its policy text is the package's.
129
+ if (lists.CUSTOMER !== undefined) {
130
+ if (!isMap(lists.CUSTOMER)) throw new Error('defineTenancy: CUSTOMER must be a { table: customer column } map');
131
+ for (const [t, c] of Object.entries(lists.CUSTOMER)) {
132
+ if (typeof c !== 'string' || !/^[a-z_][a-z0-9_]*$/.test(c)) {
133
+ throw new Error(`defineTenancy: CUSTOMER.${t} must name its customer column, not ${JSON.stringify(c)}`);
134
+ }
135
+ }
136
+ }
137
+ const ownCustomerPolicy = Object.prototype.hasOwnProperty.call(lists, 'CUSTOMER_POLICY_EXPRESSION');
138
+ if (ownCustomerPolicy) assertSameCustomerPolicy(lists.CUSTOMER_POLICY_EXPRESSION, lists.CUSTOMER, 'defineTenancy');
139
+
140
+ const out = { ...lists };
141
+ for (const k of DECIDED) if (out[k] === undefined) out[k] = {};
142
+ const { PARTNER, PLATFORM, PARTNER_NULLABLE, EXCLUDED } = out;
143
+
144
+ // ── PLATFORM_POSTGRES_ONLY IS NEVER IN all() ───────────────────────────────────────────────
145
+ //
146
+ // all() is what the classification guard compares against the live SQLITE schema, in BOTH
147
+ // directions — a live table missing from the list, and a listed table that no longer exists ("a
148
+ // rule that inspects nothing"). A Postgres-only table (the session store's) has no SQLite
149
+ // counterpart, so naming it there fails immediately, correctly. The desk app wrote that down as a
150
+ // comment after including it once; here it is a rule: such a table may not also sit in one of
151
+ // the four lists, or all() would hold it after all.
152
+ const pgOnly = Object.keys(out.PLATFORM_POSTGRES_ONLY || {});
153
+ for (const t of pgOnly) {
154
+ for (const k of DECIDED) {
155
+ if (Object.prototype.hasOwnProperty.call(out[k], t)) {
156
+ throw new Error(`defineTenancy: "${t}" is in PLATFORM_POSTGRES_ONLY and in ${k}; a Postgres-only table must `
157
+ + 'not be in all(), which the classification guard compares with the SQLite schema');
158
+ }
159
+ }
160
+ }
161
+
162
+ out.POLICY_EXPRESSION = POLICY_EXPRESSION;
163
+ // Only for a manifest with a customer tier (or one that brought its own, equal, function): a manifest without one
164
+ // gets exactly the keys it got before.
165
+ if (lists.CUSTOMER !== undefined || ownCustomerPolicy) out.CUSTOMER_POLICY_EXPRESSION = CUSTOMER_POLICY_EXPRESSION;
166
+ /** Every table with a decision, in any list — what the classification guard checks against. */
167
+ out.all = () => [
168
+ ...Object.keys(PARTNER),
169
+ ...Object.keys(PLATFORM),
170
+ ...Object.keys(PARTNER_NULLABLE),
171
+ ...Object.keys(EXCLUDED)
172
+ ];
173
+ /** The tables that get a partner_id and a policy, with whether the column may be NULL. */
174
+ out.scoped = () => [
175
+ ...Object.keys(PARTNER).map((table) => ({ table, nullable: false })),
176
+ ...Object.keys(PARTNER_NULLABLE).map((table) => ({ table, nullable: true }))
177
+ ];
178
+ return out;
179
+ }
180
+
181
+ module.exports = {
182
+ defineTenancy, TENANCY_POLICY_EXPRESSION: POLICY_EXPRESSION, CUSTOMER_POLICY_EXPRESSION, assertSameCustomerPolicy
183
+ };
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 };