@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/customerPin.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE CUSTOMER PIN (0.30.0) — a third level under the tenant context's two: work done for ONE customer of ONE partner
|
|
3
|
+
* (a customer's own people, a device of one customer, staff visiting one customer).
|
|
4
|
+
*
|
|
5
|
+
* Moved here, nearly as it was, from the first app that built it for itself: a security boundary with two copies has
|
|
6
|
+
* one that drifts (tenantContext.js). The pin holds at TWO locks, and both are this package's now:
|
|
7
|
+
*
|
|
8
|
+
* 1. the model layer: under a pin only a method on the app's customer-safe list runs (createCustomerScope,
|
|
9
|
+
* customerScope.js). The LIST is the app's; the mechanism is here.
|
|
10
|
+
* 2. row-level security: inside the invoke's own transaction, AFTER the tenant context's settings, the worker sets
|
|
11
|
+
* `app.scope = 'customer'` and `app.customer_id` (PIN_SQL below), which the `customer` arm of every customer
|
|
12
|
+
* table's policy reads (CUSTOMER_POLICY_EXPRESSION, tenancyManifest.js). A partner-only table's policy sends
|
|
13
|
+
* 'customer' to its ELSE arm, so the partner boundary still holds there.
|
|
14
|
+
*
|
|
15
|
+
* HOW IT TRAVELS. Like the tenant context, in three hops, because AsyncLocalStorage does not cross a worker thread:
|
|
16
|
+
* main thread runPinned({ partnerId, customerId, contactId }, fn) — inside a partner-scope runWithTenant
|
|
17
|
+
* DbClient a client built with `{ customerPin: true }` puts activePin() in the message as `pin` (only when one is
|
|
18
|
+
* in force: an unpinned message is exactly what it was). A client WITHOUT the option refuses an invoke
|
|
19
|
+
* made while a pin is in force, rather than running it unpinned.
|
|
20
|
+
* worker refuses unless the worker was given a customer scope (runWorker({ customerScope })), the tenant is
|
|
21
|
+
* 'partner' scope at the pin's own partner, the method is on the safe list and is not
|
|
22
|
+
* `outsideTransaction`; then applies APPLY_SQL, then PIN_SQL, and runs the model inside this same
|
|
23
|
+
* store (one instance per thread), so `pinnedCustomer()` / `pinClause()` narrow the model's own SQL too.
|
|
24
|
+
*
|
|
25
|
+
* THE CONTACT is carried with the pin to the worker, so a model can name the CALLER from the pin rather than from an
|
|
26
|
+
* argument (currentPin().contactId). It is NEVER a database setting: no policy reads it.
|
|
27
|
+
*
|
|
28
|
+
* THE PIN APPLIES ONLY WHILE THE TENANT IN FORCE IS ITS PARTNER'S (activePin). It is DROPPED under a platform-scope
|
|
29
|
+
* context (an app's asHouse / asPlatform) and under another partner's scope. That is deliberate: code that widens on
|
|
30
|
+
* purpose (an audit write at the house, a credential lookup) does so in the open, with runWithTenant, as every widening
|
|
31
|
+
* in this family is — and a pin is never applied at a scope its policy arm was not written for.
|
|
32
|
+
*
|
|
33
|
+
* ON SQLITE there is no row-level security: the pin rests on the safe list and the model's own predicate alone.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
'use strict';
|
|
37
|
+
|
|
38
|
+
const { AsyncLocalStorage } = require('node:async_hooks');
|
|
39
|
+
const { currentTenant } = require('./tenantContext');
|
|
40
|
+
|
|
41
|
+
const store = new AsyncLocalStorage();
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The generic shape of a customer or contact id: a letter or digit, then letters, digits, "_" and "-", at most 64 in
|
|
45
|
+
* all. The value is bound as a parameter and compared as TEXT with the customer column; the shape only keeps out what
|
|
46
|
+
* no id is (empty, whitespace, punctuation, a number, an object). An app with a stricter id passes its own check to
|
|
47
|
+
* createCustomerScope (customerScope.js), which the worker applies as well.
|
|
48
|
+
*/
|
|
49
|
+
const ID_SHAPE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
50
|
+
const isPinId = (v) => typeof v === 'string' && ID_SHAPE.test(v);
|
|
51
|
+
|
|
52
|
+
/** A partner id: a positive safe integer, or a string of digits for one. Nothing else (true, '7.0', ' 7', '0x7'). */
|
|
53
|
+
function partnerIdOf(v) {
|
|
54
|
+
const n = typeof v === 'number' ? v : (typeof v === 'string' && /^\d+$/.test(v) ? Number(v) : NaN);
|
|
55
|
+
return Number.isSafeInteger(n) && n > 0 ? n : null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Validate and freeze a pin. Throws with the reason, because every caller is a security path. */
|
|
59
|
+
function normalisePin(pin) {
|
|
60
|
+
if (!pin || typeof pin !== 'object') throw new Error('customerPin: a pin is required, e.g. { partnerId: 7, customerId: \'cus_…\' }');
|
|
61
|
+
const { partnerId, customerId, contactId = null } = pin;
|
|
62
|
+
const p = partnerIdOf(partnerId);
|
|
63
|
+
if (p === null) throw new Error(`customerPin: partner ${JSON.stringify(partnerId)} is not a partner id (a positive whole number)`);
|
|
64
|
+
if (!isPinId(customerId)) throw new Error(`customerPin: ${JSON.stringify(customerId)} is not a customer id`);
|
|
65
|
+
if (contactId != null && !isPinId(contactId)) throw new Error(`customerPin: ${JSON.stringify(contactId)} is not a contact id`);
|
|
66
|
+
return Object.freeze({ partnerId: p, customerId, contactId: contactId == null ? null : contactId });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Run `fn` pinned to one customer of one partner — and, for a person's session, to the CONTACT it belongs to
|
|
71
|
+
* (`contactId`; null for a device's pin). Throws on a malformed pin. It does NOT set the tenant context: the caller
|
|
72
|
+
* runs it inside a partner-scope runWithTenant (@aria-framework/tenancy's asCustomer does both), and until then
|
|
73
|
+
* activePin() is null and nothing is pinned.
|
|
74
|
+
*/
|
|
75
|
+
function runPinned(pin, fn) {
|
|
76
|
+
return store.run(normalisePin(pin), fn);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The pin in force, `{ partnerId, customerId, contactId }`, or null. */
|
|
80
|
+
function currentPin() {
|
|
81
|
+
return store.getStore() || null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The pin to APPLY to an invoke made now: the pin in force, but only while the tenant in force is 'partner' scope at
|
|
86
|
+
* the pin's own partner (header: code that widens on purpose is not followed). DbClient routes by this.
|
|
87
|
+
*/
|
|
88
|
+
function activePin() {
|
|
89
|
+
const p = store.getStore();
|
|
90
|
+
if (!p) return null;
|
|
91
|
+
const t = currentTenant();
|
|
92
|
+
return t && t.scope === 'partner' && Number(t.partnerId) === p.partnerId ? p : null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The pinned customer's id, or null — what a customer model adds to its own WHERE (the model-layer half). */
|
|
96
|
+
function pinnedCustomer() {
|
|
97
|
+
const p = store.getStore();
|
|
98
|
+
return p ? p.customerId : null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* ` AND <col> = ?` naming the pinned customer, and its params — or nothing outside a pin. Reads pinnedCustomer THROUGH
|
|
103
|
+
* module.exports, at call time, so a test that switches the model half off switches it off here too. `col` is
|
|
104
|
+
* interpolated, so it must be a plain (optionally table-qualified) column name.
|
|
105
|
+
*/
|
|
106
|
+
function pinClause(col) {
|
|
107
|
+
if (typeof col !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/.test(col)) {
|
|
108
|
+
throw new Error(`customerPin: pinClause needs a column name, not ${JSON.stringify(col)}`);
|
|
109
|
+
}
|
|
110
|
+
const pin = module.exports.pinnedCustomer();
|
|
111
|
+
return pin ? { clause: ` AND ${col} = ?`, params: [pin], pin } : { clause: '', params: [], pin: null };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Run `fn` with NO pin, for the app's own follow-up about ONE (partner, customer) pair (telling that customer's devices
|
|
116
|
+
* what changed after a person's request). The tenant context is untouched; only the pinned routing is left behind.
|
|
117
|
+
* WHEN A PIN IS IN FORCE IT MUST BE THAT PAIR: a pinned session can never use this to reach another customer, of its
|
|
118
|
+
* partner or any other — it throws.
|
|
119
|
+
*/
|
|
120
|
+
function runUnpinnedFor({ partnerId, customerId } = {}, fn) {
|
|
121
|
+
const pin = store.getStore();
|
|
122
|
+
if (pin && (pin.customerId !== customerId || pin.partnerId !== partnerIdOf(partnerId))) {
|
|
123
|
+
throw new Error(`customerPin: a session pinned to ${pin.customerId} cannot run unpinned for ${customerId} (partner ${partnerId})`);
|
|
124
|
+
}
|
|
125
|
+
return store.exit(fn);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The one statement that narrows an invoke's transaction to the pin, run by the worker right AFTER APPLY_SQL (which
|
|
130
|
+
* has set 'partner' scope and the partner). The same text, setting names and value as the first app applied, so the
|
|
131
|
+
* policies already in its migrations keep working. Transaction-LOCAL (is_local true), like APPLY_SQL: nothing of it
|
|
132
|
+
* survives into the next invoke on the same pooled connection.
|
|
133
|
+
*/
|
|
134
|
+
const PIN_SQL =
|
|
135
|
+
"SELECT set_config('app.scope', 'customer', true) AS s, set_config('app.customer_id', ?, true) AS c";
|
|
136
|
+
|
|
137
|
+
function pinParams(pin) {
|
|
138
|
+
return [normalisePin(pin).customerId];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
module.exports = {
|
|
142
|
+
runPinned, runUnpinnedFor, currentPin, activePin, pinnedCustomer, pinClause,
|
|
143
|
+
normalisePin, isPinId, PIN_SQL, pinParams
|
|
144
|
+
};
|
package/customerScope.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createCustomerScope (0.30.0) — the WORKER half of a customer-pinned invoke: the model-layer lock of the customer pin
|
|
3
|
+
* (customerPin.js has the whole design).
|
|
4
|
+
*
|
|
5
|
+
* runWorker({
|
|
6
|
+
* init: (wd) => models,
|
|
7
|
+
* customerScope: (models) => createCustomerScope({ safe: CUSTOMER_SAFE, models })
|
|
8
|
+
* });
|
|
9
|
+
*
|
|
10
|
+
* `safe` is the APP's list, model → the methods a customer-pinned session may call; it stays the app's. Under a pin a
|
|
11
|
+
* method that is not on it is REFUSED, so a partner-wide read (a user list, the whole audit trail) has no way in. Fail
|
|
12
|
+
* closed: a new model method is unreachable from a pinned session until somebody lists it. An empty list refuses
|
|
13
|
+
* every pinned call. Without a pin this is never consulted: the invoke runs exactly as it did before.
|
|
14
|
+
*
|
|
15
|
+
* Every refusal carries `code: 'CUSTOMER_SCOPE_REFUSED'`.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
'use strict';
|
|
19
|
+
|
|
20
|
+
const { normalisePin } = require('./customerPin');
|
|
21
|
+
|
|
22
|
+
const SCOPES = new WeakSet();
|
|
23
|
+
const isFn = (f) => typeof f === 'function';
|
|
24
|
+
const isMap = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
25
|
+
const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* THE RULE FOR "A MODEL METHOD" UNDER A PIN, used in both places that decide it: createCustomerScope's construction
|
|
29
|
+
* check of the safe list, and the worker's pinned dispatch (worker.js), which runs the method from ITS OWN registry.
|
|
30
|
+
* The model must be the registry's OWN property, and the method the model's OWN function property — so nothing
|
|
31
|
+
* inherited (`constructor`, `toString`, `hasOwnProperty`, `valueOf`, `__proto__`) can be listed or reached. Returns the
|
|
32
|
+
* function, or null.
|
|
33
|
+
*/
|
|
34
|
+
function ownMethod(registry, model, method) {
|
|
35
|
+
if (!registry || typeof registry !== 'object' || typeof model !== 'string' || typeof method !== 'string') return null;
|
|
36
|
+
if (!own(registry, model)) return null;
|
|
37
|
+
const target = registry[model];
|
|
38
|
+
if (!target || (typeof target !== 'object' && typeof target !== 'function') || !own(target, method)) return null;
|
|
39
|
+
return isFn(target[method]) ? target[method] : null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function refused(message) {
|
|
43
|
+
const e = new Error(message);
|
|
44
|
+
e.code = 'CUSTOMER_SCOPE_REFUSED';
|
|
45
|
+
return e;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* @param {object} o
|
|
50
|
+
* @param {{[model: string]: string[]}} o.safe REQUIRED: the methods a pinned session may call ({} refuses every one)
|
|
51
|
+
* @param {object} o.models REQUIRED: the worker's model registry (what init returned); every listed method must be the
|
|
52
|
+
* model's own function there (ownMethod). Used to check the list only: the worker runs the method from its own
|
|
53
|
+
* registry, so a scope built over another object cannot change what runs
|
|
54
|
+
* @param {(id: string) => boolean} [o.customerId] the app's own, stricter check of a customer id (only `true` passes),
|
|
55
|
+
* applied on top of the package's generic shape
|
|
56
|
+
* @param {(id: string) => boolean} [o.contactId] the same for a contact id (asked only when the pin carries one)
|
|
57
|
+
*/
|
|
58
|
+
function createCustomerScope(o = {}) {
|
|
59
|
+
const { safe, models, customerId: checkCustomer, contactId: checkContact } = o;
|
|
60
|
+
if (!isMap(safe)) throw new Error('createCustomerScope: `safe` is required — { Model: [\'method\', ...] }, the app\'s customer-safe list ({} for none)');
|
|
61
|
+
if (!isMap(models)) throw new Error('createCustomerScope: `models` is required — the worker\'s model registry');
|
|
62
|
+
if (checkCustomer !== undefined && !isFn(checkCustomer)) throw new Error('createCustomerScope: `customerId` must be a function when given');
|
|
63
|
+
if (checkContact !== undefined && !isFn(checkContact)) throw new Error('createCustomerScope: `contactId` must be a function when given');
|
|
64
|
+
const list = {};
|
|
65
|
+
for (const model of Object.keys(safe)) {
|
|
66
|
+
const methods = safe[model];
|
|
67
|
+
if (!Array.isArray(methods) || !methods.every((m) => typeof m === 'string' && m)) {
|
|
68
|
+
throw new Error(`createCustomerScope: safe.${model} must be a list of method names`);
|
|
69
|
+
}
|
|
70
|
+
for (const m of methods) {
|
|
71
|
+
if (!ownMethod(models, model, m)) {
|
|
72
|
+
throw new Error(`createCustomerScope: safe lists ${model}.${m}, which is not the model's own method in the registry`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
list[model] = Object.freeze([...methods]);
|
|
76
|
+
}
|
|
77
|
+
const frozen = Object.freeze(list);
|
|
78
|
+
|
|
79
|
+
/** Is `model.method` on the safe list? */
|
|
80
|
+
function allows(model, method) {
|
|
81
|
+
return typeof model === 'string' && own(frozen, model) && frozen[model].includes(method);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* DECIDE one pinned invoke BEFORE anything runs; the worker then dispatches it from its own registry, by the same path
|
|
86
|
+
* as an unpinned call. Refuses: a malformed pin, or one the app's own checks reject; a tenant that is not 'partner'
|
|
87
|
+
* scope at the pin's own partner (so never at platform scope); a method not on the list. (The worker itself refuses a
|
|
88
|
+
* method that is not the model's own in its registry, and one that declares `outsideTransaction`.)
|
|
89
|
+
*
|
|
90
|
+
* @returns {{ pin: object }} the normalised pin to apply
|
|
91
|
+
*/
|
|
92
|
+
function prepare(pin, tenant, model, method) {
|
|
93
|
+
let p;
|
|
94
|
+
try { p = normalisePin(pin); } catch (e) { throw refused(`CustomerScope: ${e.message}`); }
|
|
95
|
+
if (checkCustomer && checkCustomer(p.customerId) !== true) throw refused(`CustomerScope: "${p.customerId}" is not a customer id this app accepts`);
|
|
96
|
+
if (p.contactId != null && checkContact && checkContact(p.contactId) !== true) throw refused(`CustomerScope: "${p.contactId}" is not a contact id this app accepts`);
|
|
97
|
+
if (!tenant || tenant.scope !== 'partner' || tenant.partnerId == null) {
|
|
98
|
+
throw refused(`CustomerScope: a customer pin needs a partner scope, not ${tenant ? tenant.scope : 'none'}`);
|
|
99
|
+
}
|
|
100
|
+
if (Number(tenant.partnerId) !== p.partnerId) {
|
|
101
|
+
throw refused(`CustomerScope: a pin for partner ${p.partnerId} arrived in partner ${tenant.partnerId}'s scope`);
|
|
102
|
+
}
|
|
103
|
+
if (!allows(model, method)) throw refused(`CustomerScope: ${model}.${method} is not reachable from a customer-pinned session`);
|
|
104
|
+
return { pin: p };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const scope = Object.freeze({ safe: frozen, allows, prepare });
|
|
108
|
+
SCOPES.add(scope);
|
|
109
|
+
return scope;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Was this made by createCustomerScope? (runWorker accepts nothing else.) */
|
|
113
|
+
const isCustomerScope = (s) => SCOPES.has(s);
|
|
114
|
+
|
|
115
|
+
module.exports = { createCustomerScope, isCustomerScope, ownMethod, refused, CUSTOMER_SCOPE_REFUSED: 'CUSTOMER_SCOPE_REFUSED' };
|
package/database.js
CHANGED
|
@@ -354,10 +354,14 @@ function runMigrations(migrationsDir, opts = {}) {
|
|
|
354
354
|
_logger.info(`Migration skipped (not for ${d.kind}): ${skipped}`);
|
|
355
355
|
}
|
|
356
356
|
|
|
357
|
+
// 0.29.0 — validated on every engine, so a malformed option fails where it is written.
|
|
358
|
+
const squash = squashedFromOption(opts.squashedFrom, files);
|
|
359
|
+
|
|
357
360
|
// ── the synchronous path, unchanged in behaviour since 0.1.0 ──────────────────────────────
|
|
358
361
|
if (d.kind === 'sqlite') {
|
|
359
362
|
const db = d.raw;
|
|
360
363
|
const applied = new Set(db.prepare('SELECT filename FROM migrations').all().map((r) => r.filename));
|
|
364
|
+
if (squash) assertNotPreSquash(applied, squash);
|
|
361
365
|
let count = 0;
|
|
362
366
|
for (const file of files) {
|
|
363
367
|
if (applied.has(file)) continue;
|
|
@@ -541,6 +545,56 @@ function runMigrations(migrationsDir, opts = {}) {
|
|
|
541
545
|
}
|
|
542
546
|
}
|
|
543
547
|
|
|
548
|
+
/**
|
|
549
|
+
* 0.29.0 — `runMigrations(dir, { squashedFrom })`: refuse a database that predates a squash.
|
|
550
|
+
*
|
|
551
|
+
* The runner keys on FILENAME: it applies any file absent from the ledger. A database created
|
|
552
|
+
* before an app squashed its chain into one baseline records the OLD files and has never seen the
|
|
553
|
+
* baseline — so the runner executes the baseline against a fully-populated database, its first
|
|
554
|
+
* `CREATE TABLE` fails with "table already exists", the transaction rolls back and the worker dies
|
|
555
|
+
* on every boot, with a message that names a SQL error and no cause. One query turns that outage
|
|
556
|
+
* into an instruction (moved from the desk app, which met it on a restored old data directory).
|
|
557
|
+
*
|
|
558
|
+
* DELIBERATELY NOT AUTO-REPAIRED: recording the baseline on the operator's behalf would assert
|
|
559
|
+
* "this database already matches the baseline", which nobody has verified.
|
|
560
|
+
*
|
|
561
|
+
* SQLITE ONLY, as in the app it came from: the history it detects ended before that app could open
|
|
562
|
+
* Postgres. On Postgres the option is validated and nothing is checked.
|
|
563
|
+
*
|
|
564
|
+
* `squashedFrom` is a filename from the old chain (`'001_initial_schema.sql'`) or
|
|
565
|
+
* `{ file, baseline, remedy }`: `baseline` defaults to the first migration in the directory for
|
|
566
|
+
* this engine, `remedy` replaces the default instructions after the first paragraph.
|
|
567
|
+
*/
|
|
568
|
+
function squashedFromOption(opt, files) {
|
|
569
|
+
if (opt == null) return null;
|
|
570
|
+
const o = typeof opt === 'string' ? { file: opt } : opt;
|
|
571
|
+
if (!o || typeof o !== 'object' || typeof o.file !== 'string' || !o.file.endsWith('.sql')) {
|
|
572
|
+
throw new Error("runMigrations: squashedFrom must be an old migration's filename, or { file, baseline, remedy }");
|
|
573
|
+
}
|
|
574
|
+
const baseline = o.baseline == null ? files[0] : o.baseline;
|
|
575
|
+
if (typeof baseline !== 'string' || !baseline.endsWith('.sql')) {
|
|
576
|
+
throw new Error('runMigrations: squashedFrom has no baseline (pass { baseline }, or keep the baseline in the directory)');
|
|
577
|
+
}
|
|
578
|
+
if (o.remedy != null && typeof o.remedy !== 'string') throw new Error('runMigrations: squashedFrom.remedy must be text');
|
|
579
|
+
return { file: o.file, baseline, remedy: o.remedy == null ? null : o.remedy };
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
function assertNotPreSquash(applied, { file, baseline, remedy }) {
|
|
583
|
+
if (applied.has(baseline)) return; // post-squash, fine
|
|
584
|
+
if (!applied.has(file)) return; // not a pre-squash database (a fresh one has an empty ledger)
|
|
585
|
+
throw new Error(
|
|
586
|
+
`This database was created before the migration squash: it records ${applied.size} old migrations ` +
|
|
587
|
+
`(${file} among them) and has never applied ${baseline}. Running migrations would try to ` +
|
|
588
|
+
'CREATE TABLE over the existing schema and fail.\n\n' +
|
|
589
|
+
(remedy || (
|
|
590
|
+
' Either (recommended): stop the app, move the database file aside and start it again —\n' +
|
|
591
|
+
' the baseline builds a fresh database.\n\n' +
|
|
592
|
+
' Or, to keep the existing data (only if you are certain its schema already matches the\n' +
|
|
593
|
+
' baseline):\n' +
|
|
594
|
+
` INSERT INTO migrations (filename) VALUES ('${baseline}');`))
|
|
595
|
+
);
|
|
596
|
+
}
|
|
597
|
+
|
|
544
598
|
/** Adopt the handle init() just opened — the driver must not open a second connection. */
|
|
545
599
|
function _adoptSqliteDriver(db) {
|
|
546
600
|
const { createSqliteDriver } = require('./driver/sqlite');
|
package/index.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
// 0.6.0 — MULTI-ENGINE. The driver contract (get/all/run/exec/transaction + dialect +
|
|
13
13
|
// concurrency) lets a store be written once and run on either engine, selected per APP. SQLite
|
|
14
|
-
// stays the default
|
|
14
|
+
// stays the default for the app that started on it; a later app boots with kind:'postgres'. `pg` and
|
|
15
15
|
// better-sqlite3 are both OPTIONAL peers — neither consumer installs the other's driver.
|
|
16
16
|
const { createSqliteDriver } = require('./driver/sqlite');
|
|
17
17
|
const { createPostgresDriver } = require('./driver/postgres');
|
|
@@ -46,5 +46,17 @@ module.exports = {
|
|
|
46
46
|
// 0.19.0 — the tenancy migration generator. The manifest of which tables belong to a tenant is
|
|
47
47
|
// the app's; turning it into partner_id columns, composite foreign keys and RLS policies is
|
|
48
48
|
// mechanical, identical everywhere, and far too intricate to retype per app.
|
|
49
|
-
...require('./tenancyMigration')
|
|
49
|
+
...require('./tenancyMigration'),
|
|
50
|
+
// 0.29.0 — the tenancy core every multi-tenant app carried as its own copy. `sql` (the dialect
|
|
51
|
+
// helpers and the CASE tenant filter, resolved from this package's database.driver() at call
|
|
52
|
+
// time); `defineTenancy` (the frozen policy text, all(), scoped()); the scope assertions,
|
|
53
|
+
// keepTenant and tenantCacheKey; the tenant settings layer.
|
|
54
|
+
sql: require('./sql'),
|
|
55
|
+
...require('./tenancyManifest'),
|
|
56
|
+
...require('./tenantScope'),
|
|
57
|
+
...require('./tenantSettings'),
|
|
58
|
+
// 0.30.0 — the customer pin: the third level under the tenant context's two (customerPin.js), the worker's
|
|
59
|
+
// customer-safe lock (createCustomerScope), and — on tenancyManifest above — the frozen CUSTOMER_POLICY_EXPRESSION.
|
|
60
|
+
...require('./customerPin'),
|
|
61
|
+
createCustomerScope: require('./customerScope').createCustomerScope
|
|
50
62
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aria-framework/db-worker",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.30.0",
|
|
4
4
|
"description": "Aria App Framework — db-worker module. Async RPC bridge over synchronous better-sqlite3: a worker-thread dispatcher (runWorker), a main-thread client with per-call timeouts and crash handling (DbClient), and a SQLite layer with WAL pragmas + a numbered-migration runner (database).",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"private": false,
|
|
@@ -8,17 +8,28 @@
|
|
|
8
8
|
"access": "public"
|
|
9
9
|
},
|
|
10
10
|
"main": "index.js",
|
|
11
|
+
"bin": {
|
|
12
|
+
"aria-tenancy": "bin/tenancy.js"
|
|
13
|
+
},
|
|
11
14
|
"files": [
|
|
12
15
|
"client.js",
|
|
16
|
+
"customerPin.js",
|
|
17
|
+
"customerScope.js",
|
|
18
|
+
"bin/",
|
|
13
19
|
"database.js",
|
|
14
20
|
"dialect.js",
|
|
15
21
|
"driver/",
|
|
16
22
|
"index.js",
|
|
17
23
|
"schemaSnapshot.js",
|
|
18
24
|
"settingsStore.js",
|
|
25
|
+
"sql.js",
|
|
19
26
|
"tableOrder.js",
|
|
27
|
+
"tenancyManifest.js",
|
|
28
|
+
"tenancyGenerator.js",
|
|
20
29
|
"tenancyMigration.js",
|
|
21
30
|
"tenantContext.js",
|
|
31
|
+
"tenantScope.js",
|
|
32
|
+
"tenantSettings.js",
|
|
22
33
|
"worker.js",
|
|
23
34
|
"workerRegistry.js"
|
|
24
35
|
],
|
|
@@ -40,7 +51,7 @@
|
|
|
40
51
|
"pg": "^8.23.0"
|
|
41
52
|
},
|
|
42
53
|
"scripts": {
|
|
43
|
-
"test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationFailureSurfaces.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/tenancyAttribution.pglite.js && node test/tenancyNullable.pg.js && node test/tenancyPartnerFk.pg.js && node test/tenancyOnUpdate.pg.js && node test/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/clientError.pg.js && node test/migrationRole.pg.js && node test/smoke.js && node test/tier2.js && node test/timezone.pg.js && node test/pinPoolUtc.js && node test/pinAwaited.pg.js && node test/inTransaction.js",
|
|
54
|
+
"test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationFailureSurfaces.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/tenancyAttribution.pglite.js && node test/tenancyNullable.pg.js && node test/tenancyPartnerFk.pg.js && node test/tenancyOnUpdate.pg.js && node test/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/clientError.pg.js && node test/migrationRole.pg.js && node test/smoke.js && node test/tier2.js && node test/timezone.pg.js && node test/pinPoolUtc.js && node test/pinAwaited.pg.js && node test/inTransaction.js && node test/sql.js && node test/tenancyManifest.js && node test/tenantScope.js && node test/tenantSettings.js && node test/dbClientRefusal.js && node test/migrationsSquash.js && node test/tenancyGenerator.js && node test/customerPin.js && node test/customerPin.pglite.js",
|
|
44
55
|
"prepublishOnly": "node ../../test/packaging.js db-worker"
|
|
45
56
|
}
|
|
46
57
|
}
|