@aria-framework/db-worker 0.29.0 → 0.31.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.
@@ -9,8 +9,10 @@
9
9
  * module.exports = defineTenancy({ PARTNER, PLATFORM, PARTNER_NULLABLE, EXCLUDED,
10
10
  * PLATFORM_POSTGRES_ONLY, WIDEN_UNIQUE, ... });
11
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.
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.
14
16
  */
15
17
 
16
18
  'use strict';
@@ -44,6 +46,56 @@ const POLICY_EXPRESSION = `
44
46
  ELSE partner_id = current_setting('app.partner_id')::int
45
47
  END`;
46
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
+
47
99
  /** The four lists that together are "every table with a decision" — what `all()` returns. */
48
100
  const DECIDED = ['PARTNER', 'PLATFORM', 'PARTNER_NULLABLE', 'EXCLUDED'];
49
101
 
@@ -73,9 +125,24 @@ function defineTenancy(lists) {
73
125
  if (lists.PLATFORM_POSTGRES_ONLY !== undefined && !isMap(lists.PLATFORM_POSTGRES_ONLY)) {
74
126
  throw new Error('defineTenancy: PLATFORM_POSTGRES_ONLY must be a { table: reason } map');
75
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');
76
139
 
77
140
  const out = { ...lists };
78
141
  for (const k of DECIDED) if (out[k] === undefined) out[k] = {};
142
+ // 0.31.0 — tables a package defines (tableDefinitions.js), spread in as tenancyFragment(...sets): classified HERE,
143
+ // from the definitions, and a manifest that classifies one of them differently is refused. Without the key nothing
144
+ // below runs and the manifest gets exactly the keys and values it got before.
145
+ if (lists.TABLE_DEFINITIONS !== undefined) mergeDefinitions(lists, out);
79
146
  const { PARTNER, PLATFORM, PARTNER_NULLABLE, EXCLUDED } = out;
80
147
 
81
148
  // ── PLATFORM_POSTGRES_ONLY IS NEVER IN all() ───────────────────────────────────────────────
@@ -97,6 +164,9 @@ function defineTenancy(lists) {
97
164
  }
98
165
 
99
166
  out.POLICY_EXPRESSION = POLICY_EXPRESSION;
167
+ // Only for a manifest with a customer tier (or one that brought its own, equal, function): a manifest without one
168
+ // gets exactly the keys it got before. (out.CUSTOMER: a definition set's customer tables give a manifest one.)
169
+ if (out.CUSTOMER !== undefined || ownCustomerPolicy) out.CUSTOMER_POLICY_EXPRESSION = CUSTOMER_POLICY_EXPRESSION;
100
170
  /** Every table with a decision, in any list — what the classification guard checks against. */
101
171
  out.all = () => [
102
172
  ...Object.keys(PARTNER),
@@ -112,4 +182,44 @@ function defineTenancy(lists) {
112
182
  return out;
113
183
  }
114
184
 
115
- module.exports = { defineTenancy, TENANCY_POLICY_EXPRESSION: POLICY_EXPRESSION };
185
+ /**
186
+ * 0.31.0 — the classification of the tables in lists.TABLE_DEFINITIONS (an array of sets built with defineTables, as
187
+ * tenancyFragment gives it), merged into `out`: each table into PARTNER (its description as the reason) and a
188
+ * customer table into CUSTOMER. Refused: a value that is not such an array, a table in two sets, and an app list that
189
+ * classifies a defined table differently — in PLATFORM, PARTNER_NULLABLE, EXCLUDED or PLATFORM_POSTGRES_ONLY, with
190
+ * another customer column, or with one where the definition has none. The app listing a table exactly as its
191
+ * definition does (PARTNER, and the same column) is the same classification and accepted.
192
+ */
193
+ function mergeDefinitions(lists, out) {
194
+ const { isTableDefinitions, classificationOf } = require('./tableDefinitions');
195
+ const sets = lists.TABLE_DEFINITIONS;
196
+ if (!Array.isArray(sets) || !sets.length || !sets.every(isTableDefinitions)) {
197
+ throw new Error('defineTenancy: TABLE_DEFINITIONS is what tenancyFragment(...sets) gives — sets built with defineTables');
198
+ }
199
+ const from = {};
200
+ const PARTNER = { ...out.PARTNER };
201
+ const CUSTOMER = { ...(lists.CUSTOMER || {}) };
202
+ let customerTables = false;
203
+ for (const set of sets) {
204
+ const c = classificationOf(set);
205
+ for (const t of Object.keys(c.PARTNER)) {
206
+ if (from[t]) throw new Error(`defineTenancy: ${t} is defined by both ${from[t]} and ${set.name}`);
207
+ from[t] = set.name;
208
+ const elsewhere = ['PLATFORM', 'PARTNER_NULLABLE', 'EXCLUDED', 'PLATFORM_POSTGRES_ONLY'].find((k) => Object.prototype.hasOwnProperty.call(lists[k] || {}, t));
209
+ if (elsewhere) throw new Error(`defineTenancy: ${t} is in ${elsewhere}, but ${set.name} ${set.version} defines it as a PARTNER${c.CUSTOMER[t] ? ' and CUSTOMER' : ''} table`);
210
+ const theirs = Object.prototype.hasOwnProperty.call(CUSTOMER, t) ? CUSTOMER[t] : null;
211
+ const ours = c.CUSTOMER[t] || null;
212
+ if (Object.prototype.hasOwnProperty.call(lists.CUSTOMER || {}, t) && theirs !== ours) {
213
+ throw new Error(`defineTenancy: CUSTOMER.${t} is ${JSON.stringify(theirs)}, but ${set.name} ${set.version} defines it as ${ours ? `a CUSTOMER table with the column ${ours}` : 'a PARTNER-only table'}`);
214
+ }
215
+ if (!Object.prototype.hasOwnProperty.call(PARTNER, t)) PARTNER[t] = c.PARTNER[t];
216
+ if (ours) { CUSTOMER[t] = ours; customerTables = true; }
217
+ }
218
+ }
219
+ out.PARTNER = PARTNER;
220
+ if (lists.CUSTOMER !== undefined || customerTables) out.CUSTOMER = CUSTOMER;
221
+ }
222
+
223
+ module.exports = {
224
+ defineTenancy, TENANCY_POLICY_EXPRESSION: POLICY_EXPRESSION, CUSTOMER_POLICY_EXPRESSION, assertSameCustomerPolicy
225
+ };
package/worker.js CHANGED
@@ -20,6 +20,8 @@
20
20
  const { parentPort, workerData } = require('worker_threads');
21
21
  const { performance } = require('perf_hooks');
22
22
  const { runWithTenant, APPLY_SQL, applyParams } = require('./tenantContext');
23
+ const { PIN_SQL, pinParams, runPinned } = require('./customerPin');
24
+ const { isCustomerScope, ownMethod, refused } = require('./customerScope');
23
25
 
24
26
  /**
25
27
  * The driver, or null before the app's init() has opened one. Read per call rather than cached:
@@ -43,7 +45,7 @@ function currentDriver() {
43
45
  * On a serial driver (SQLite) there is no RLS and nothing to set. The context is still
44
46
  * established so a model can read it, and no transaction is forced around a read.
45
47
  */
46
- async function withTenant(tenant, label, dispatch, { outsideTransaction = false } = {}) {
48
+ async function withTenant(tenant, label, dispatch, { outsideTransaction = false, pin = null } = {}) {
47
49
  const driver = currentDriver();
48
50
  if (!driver || driver.concurrency !== 'pool') {
49
51
  return tenant ? runWithTenant(tenant, dispatch) : dispatch();
@@ -65,6 +67,9 @@ async function withTenant(tenant, label, dispatch, { outsideTransaction = false
65
67
  if (outsideTransaction) return runWithTenant(tenant, dispatch);
66
68
  return runWithTenant(tenant, () => driver.transaction(async (tx) => {
67
69
  await tx.run(APPLY_SQL, applyParams(tenant));
70
+ // 0.30.0 — a customer-pinned invoke (customerPin.js): narrowed to the customer AFTER the tenant's own settings, in
71
+ // the same transaction. Only when a pin came in the message; an unpinned invoke sends exactly what it always did.
72
+ if (pin) await tx.run(PIN_SQL, pinParams(pin));
68
73
  return dispatch();
69
74
  }));
70
75
  }
@@ -72,11 +77,16 @@ async function withTenant(tenant, label, dispatch, { outsideTransaction = false
72
77
  /**
73
78
  * @param {Object} opts
74
79
  * @param {(workerData: any) => Object} opts.init - App boot; returns the model registry
80
+ * @param {(models: Object) => Object} [opts.customerScope] - 0.30.0: given the registry once after init, returns
81
+ * createCustomerScope({ safe, models }). Without it every customer-pinned invoke is refused.
75
82
  */
76
- async function runWorker({ init }) {
83
+ async function runWorker({ init, customerScope } = {}) {
77
84
  if (typeof init !== 'function') {
78
85
  throw new Error('runWorker({ init }): init must be a function (workerData) => modelRegistry');
79
86
  }
87
+ if (customerScope !== undefined && typeof customerScope !== 'function') {
88
+ throw new Error('runWorker({ customerScope }): customerScope must be a function (models) => createCustomerScope({ safe, models })');
89
+ }
80
90
 
81
91
  try {
82
92
  // AWAITED since 0.6.0. An app's init opens the database and runs migrations, and on
@@ -84,6 +94,11 @@ async function runWorker({ init }) {
84
94
  // model registry and serve queries against an unmigrated database. `await` on a synchronous
85
95
  // init returns the same object it always did, so the SQLite path is unchanged.
86
96
  const models = (await init(workerData)) || {};
97
+ let customer = null;
98
+ if (customerScope) {
99
+ customer = await customerScope(models);
100
+ if (!isCustomerScope(customer)) throw new Error('runWorker({ customerScope }): it must return createCustomerScope({ safe, models })');
101
+ }
87
102
 
88
103
  parentPort.postMessage({ type: 'ready' });
89
104
 
@@ -120,7 +135,7 @@ async function runWorker({ init }) {
120
135
  });
121
136
 
122
137
  async function handle(msg) {
123
- const { id, model, method, args, tenant } = msg;
138
+ const { id, model, method, args, tenant, pin } = msg;
124
139
  // Worker-side execution time, shipped back so the client's slow-call log
125
140
  // attributes slowness to the query that WAS slow, not to calls that were
126
141
  // merely queued behind it. Monotonic clock: a wall-clock (Date.now) delta
@@ -133,13 +148,33 @@ async function runWorker({ init }) {
133
148
  throw new Error(`Unknown method: ${model}.${method}`);
134
149
  }
135
150
 
136
- let result = await withTenant(tenant, `${model}.${method}`, async () => {
151
+ // ONE dispatch, from THIS worker's registry, for an unpinned and a pinned call alike.
152
+ const dispatch = async () => {
137
153
  let r = target[method](...(args || []));
138
154
  if (r && typeof r.then === 'function') {
139
155
  r = await r; // async methods (e.g. bcrypt-backed user ops)
140
156
  }
141
157
  return r;
142
- }, { outsideTransaction: target[method].outsideTransaction === true });
158
+ };
159
+ let result;
160
+ if (pin !== undefined) {
161
+ // 0.30.0 — CUSTOMER-PINNED (customerPin.js). Every refusal happens here, before a transaction is opened. The
162
+ // scope only DECIDES (pin, tenant, safe list); what runs is target[method] above, from this registry.
163
+ if (!customer) {
164
+ throw refused(`db-worker: ${model}.${method} arrived pinned to a customer, and this worker has no customerScope (runWorker({ customerScope }))`);
165
+ }
166
+ const call = customer.prepare(pin, tenant, model, method);
167
+ if (ownMethod(models, model, method) !== target[method]) {
168
+ throw refused(`CustomerScope: ${model}.${method} is not the model's own method in this worker's registry`);
169
+ }
170
+ if (target[method].outsideTransaction === true) {
171
+ throw refused(`CustomerScope: ${model}.${method} runs outside a transaction, where a customer pin cannot apply`);
172
+ }
173
+ result = await withTenant(tenant, `${model}.${method}`, () => runPinned(call.pin, dispatch), { pin: call.pin });
174
+ } else {
175
+ result = await withTenant(tenant, `${model}.${method}`, dispatch,
176
+ { outsideTransaction: target[method].outsideTransaction === true });
177
+ }
143
178
 
144
179
  result = sanitizeForTransfer(result);
145
180
  parentPort.postMessage({ id, result, execMs: Math.round(performance.now() - t0) });