@aria-framework/tenancy 0.0.0-stage → 0.2.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/CHANGELOG.md +104 -0
- package/README.md +1188 -2
- package/index.js +19 -0
- package/lib/hosts/hostTenant.js +379 -0
- package/lib/hosts/hostname.js +321 -0
- package/lib/hosts/index.js +8 -0
- package/lib/hosts/tenantChrome.js +184 -0
- package/lib/partners/acting.js +216 -0
- package/lib/partners/actingIdle.js +177 -0
- package/lib/partners/index.js +10 -0
- package/lib/partners/provisioner.js +247 -0
- package/lib/partners/store.js +460 -0
- package/lib/scope/fleetView.js +437 -0
- package/lib/scope/idle.js +244 -0
- package/lib/scope/index.js +10 -0
- package/lib/scope/tenancy.js +786 -0
- package/lib/scope/writeGate.js +442 -0
- package/package.json +36 -4
- package/views/acting-banner.ejs +33 -0
- package/views/fleet-view-banner.ejs +29 -0
- package/views/fleet-view-button.ejs +23 -0
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createProvisioner — creating a partner, and giving it the things it cannot work without.
|
|
3
|
+
*
|
|
4
|
+
* const { createPartner, provision } = createProvisioner({ tenancy, db, rbac, logger, seeds, deactivateWith,
|
|
5
|
+
* onPartnersChanged, writesRequirePlatform });
|
|
6
|
+
*
|
|
7
|
+
* ── WHY THIS IS NOT IN THE PARTNER STORE ────────────────────────────────────────────────────────────────────────────
|
|
8
|
+
*
|
|
9
|
+
* A partner row on its own is a tenant that cannot be used: its roles, templates and the rest are partner-scoped, and a
|
|
10
|
+
* partner with no RBAC cache grants nothing. Every one of them has to be written INSIDE the new partner's scope, and
|
|
11
|
+
* that is the seam: models run in the DB worker and receive their tenant IN THE MESSAGE, so a model cannot switch
|
|
12
|
+
* tenants mid-call. `asPartner()` lives on the main thread, so the orchestration lives here, next to it.
|
|
13
|
+
*
|
|
14
|
+
* ── IT IS NOT ATOMIC, AND IT SAYS SO ────────────────────────────────────────────────────────────────────────────────
|
|
15
|
+
*
|
|
16
|
+
* The row and its seeds are separate worker round-trips. If seeding fails, the partner is left DEACTIVATED and the
|
|
17
|
+
* error reported: a half-built tenant nobody can sign into is recoverable; one that ACCEPTS logins is a support call
|
|
18
|
+
* about pages that refuse for no visible reason. Each seed is idempotent, so `provision()` can be re-run (a
|
|
19
|
+
* Re-provision action), rather than inviting somebody to create a second partner and hope. A seed that checks "is my
|
|
20
|
+
* table empty for this partner" does nothing for a fully seeded partner that predates a seed added later: that is a
|
|
21
|
+
* separate backfill, not this.
|
|
22
|
+
*
|
|
23
|
+
* ── WHAT CHANGED IN THE MOVE ────────────────────────────────────────────────────────────────────────────────────────
|
|
24
|
+
*
|
|
25
|
+
* - The seeds are the app's list (`seeds: [{ name, run }]`), each run inside the partner's scope, each result
|
|
26
|
+
* checked: a seed that returns nothing is an error, never "none", and `ctx.rows()` refuses a read that is not an
|
|
27
|
+
* array (an empty array has to mean empty: a mistyped method read as "none" re-seeds on every run).
|
|
28
|
+
* - RBAC is refreshed after EVERY provision, the re-provision route's included: a role seeded into a partner the cache
|
|
29
|
+
* does not know about grants nothing until the next restart.
|
|
30
|
+
* - The thrown error carries `partnerId`.
|
|
31
|
+
* - A failed deactivation of a half-built partner is LOGGED AT ERROR, and the messages stop claiming the partner was
|
|
32
|
+
* deactivated. Every copy swallowed it (`.catch(() => {})`), so a partner could stay ACTIVE while the log said
|
|
33
|
+
* "left DEACTIVATED".
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
'use strict';
|
|
37
|
+
|
|
38
|
+
function fail(message) { throw new Error(`createProvisioner: ${message}`); }
|
|
39
|
+
|
|
40
|
+
function createProvisioner(options) {
|
|
41
|
+
const o = options || {};
|
|
42
|
+
if (!o.tenancy || typeof o.tenancy.asPartner !== 'function') fail('tenancy is required (the app\'s createTenancy result: asPartner is used)');
|
|
43
|
+
if (!o.db || typeof o.db.invoke !== 'function') fail('db is required (the app\'s db client: invoke is used)');
|
|
44
|
+
if (!o.rbac || typeof o.rbac.refresh !== 'function') fail('rbac is required (refresh(partnerId) is called after every provision)');
|
|
45
|
+
if (!o.logger || typeof o.logger.error !== 'function' || typeof o.logger.info !== 'function') fail('logger is required (info and error)');
|
|
46
|
+
// NO DEFAULT SEEDS: what a new tenant needs is the app's, and another app's list would seed the wrong things quietly.
|
|
47
|
+
if (!Array.isArray(o.seeds) || o.seeds.length === 0) fail('seeds is required: [{ name, run(ctx) }, …], run inside the partner\'s scope');
|
|
48
|
+
const names = new Set();
|
|
49
|
+
for (const s of o.seeds) {
|
|
50
|
+
if (!s || typeof s.name !== 'string' || !s.name || typeof s.run !== 'function') fail('each seed is { name, run(ctx) }');
|
|
51
|
+
if (names.has(s.name)) fail(`two seeds are named "${s.name}"`);
|
|
52
|
+
names.add(s.name);
|
|
53
|
+
}
|
|
54
|
+
// NO DEFAULT DEACTIVATION: an app whose hub-received partners refuse the local switch deactivates another way.
|
|
55
|
+
if (typeof o.deactivateWith !== 'function') fail("deactivateWith is required: (partnerId, opts) => the app's deactivation (setActive, or its hub path)");
|
|
56
|
+
// ONE CALLBACK AFTER EVERY WRITE TO THE PARTNER LIST HAS COMMITTED, on the main thread (an invoke that returned
|
|
57
|
+
// has committed; the store runs in the worker and cannot reach a main-thread cache). The app wires it to
|
|
58
|
+
// createTenancy's refreshActivePartners() and createHostTenant's forget(). No default: an app that forgot it would keep
|
|
59
|
+
// serving a deactivated partner's host, or honour acting into it, until its next restart.
|
|
60
|
+
//
|
|
61
|
+
// A FUNCTION OR A LIST OF FUNCTIONS, all STARTED AT ONCE (in array order) and each ISOLATED: with one function doing
|
|
62
|
+
// both, a host forget() that threw (an app's onForget) stopped the active-partner refresh after it, and acting into a
|
|
63
|
+
// deactivated partner went on for ever; awaited one after the other, the first one's slow work delayed the second's
|
|
64
|
+
// effect. An entry that throws or rejects is logged, naming its position, and stops none of the others.
|
|
65
|
+
const subscribers = Array.isArray(o.onPartnersChanged) ? o.onPartnersChanged.slice() : [o.onPartnersChanged];
|
|
66
|
+
if (subscribers.length === 0 || !subscribers.every((f) => typeof f === 'function')) {
|
|
67
|
+
fail("onPartnersChanged is required: (event) => …, or a list of them, the app's refresh of every partner-list cache (active partners, hosts)");
|
|
68
|
+
}
|
|
69
|
+
// REQUIRED, NO DEFAULT, the same value the app gives the partner store: `true` refuses createPartner, provision,
|
|
70
|
+
// updatePartner, setPartnerActive and write below platform scope, judged here on the main thread from the current
|
|
71
|
+
// tenant context, BEFORE anything is written or any seed runs. provision() writes into the partner it names through
|
|
72
|
+
// asPartner(id), so without this a caller at partner A's scope could seed partner B. Engine-independent: it reads
|
|
73
|
+
// the context, not the database, so it refuses on SQLite too (where the store's own check does nothing).
|
|
74
|
+
if (typeof o.writesRequirePlatform !== 'boolean') fail('writesRequirePlatform is required (true or false), the same value the partner store is given: must provisioning and partner writes run at platform scope?');
|
|
75
|
+
if (o.writesRequirePlatform && typeof o.tenancy.currentTenant !== 'function') fail('tenancy.currentTenant is required with writesRequirePlatform');
|
|
76
|
+
const partnerModel = o.partnerModel || 'Partner';
|
|
77
|
+
const { tenancy, db, rbac, logger, seeds, deactivateWith, writesRequirePlatform } = o;
|
|
78
|
+
|
|
79
|
+
/** Refuse below platform scope (writesRequirePlatform), before anything is written; the store's code and sentence shape. */
|
|
80
|
+
function platformOnly(label) {
|
|
81
|
+
if (!writesRequirePlatform) return;
|
|
82
|
+
const ctx = tenancy.currentTenant();
|
|
83
|
+
if (ctx && ctx.scope === 'platform') return;
|
|
84
|
+
throw Object.assign(new Error(`Partner provisioning: ${label} writes the partner list and must run at platform scope (asPlatform), not "${ctx ? ctx.scope : 'none'}"`),
|
|
85
|
+
{ code: 'tenant_scope_refused' });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** A seed's read of "what is there already": anything but an array is an error, never "none found". */
|
|
89
|
+
async function rows(model, method, ...args) {
|
|
90
|
+
const r = await db.invoke(model, method, ...args);
|
|
91
|
+
if (!Array.isArray(r)) throw new Error(`partner provisioning: ${model}.${method} returned ${r === null ? 'null' : typeof r}, expected an array`);
|
|
92
|
+
return r;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Give a partner the rows it cannot work without, then refresh its RBAC cache. Safe to re-run.
|
|
97
|
+
*
|
|
98
|
+
* EVERY SEED INSIDE THE PARTNER'S OWN SCOPE: each scoped table defaults `partner_id` from the session, so the rows
|
|
99
|
+
* land in the right tenant without any model naming it, and outside a scope the NOT NULL refuses them rather than
|
|
100
|
+
* defaulting to somebody.
|
|
101
|
+
*
|
|
102
|
+
* @returns {Promise<object>} { <seed name>: what that seed returned }, in the order of `seeds`
|
|
103
|
+
*/
|
|
104
|
+
async function provision(partnerId, opts) {
|
|
105
|
+
platformOnly('provision');
|
|
106
|
+
const id = Number(partnerId);
|
|
107
|
+
const seeded = await tenancy.asPartner(id, async () => {
|
|
108
|
+
const out = {};
|
|
109
|
+
for (const s of seeds) {
|
|
110
|
+
const r = await s.run({ db, partnerId: id, rows, tenancy, opts });
|
|
111
|
+
if (r === undefined) throw new Error(`partner provisioning: the seed "${s.name}" returned nothing — a seed says what it did`);
|
|
112
|
+
out[s.name] = r;
|
|
113
|
+
}
|
|
114
|
+
return out;
|
|
115
|
+
});
|
|
116
|
+
// THE CACHE, AND THIS IS THE LINE PEOPLE FORGET: RBAC loads every partner's roles at boot, so a partner seeded
|
|
117
|
+
// afterwards has no cache until refresh(id) or a restart, and grants nothing, which reads as a permissions bug.
|
|
118
|
+
await rbac.refresh(id);
|
|
119
|
+
return seeded;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// THE FAILURE PATH CANNOT ITSELF FAIL: a logger that throws there would hand the caller the logger's error, with no
|
|
123
|
+
// partnerId, and a half-built partner whose deactivation failed would stay active and unreported.
|
|
124
|
+
function safeLog(level, line) {
|
|
125
|
+
try { logger[level](typeof line === 'function' ? line() : line); } catch (_) { /* the error the caller gets says the same */ }
|
|
126
|
+
}
|
|
127
|
+
const messageOf = (e) => (e && e.message) || String(e);
|
|
128
|
+
|
|
129
|
+
const describe = (seeded) => Object.entries(seeded)
|
|
130
|
+
.map(([k, v]) => `${k}=${v !== null && typeof v === 'object' ? JSON.stringify(v) : v}`).join(', ');
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Create a partner and make it usable; on a failure, leave it DEACTIVATED and throw with `partnerId`.
|
|
134
|
+
*
|
|
135
|
+
* `domain` and `portal_host` are DERIVED BY THE CALLER: deriving needs the installation's base domain, and the route
|
|
136
|
+
* is where a bad one has a form to be reported on. Every field is passed to the store's create as given (an app's
|
|
137
|
+
* own create fields included), and `opts` to both the create and the deactivation.
|
|
138
|
+
*/
|
|
139
|
+
async function createPartner(fields, opts) {
|
|
140
|
+
platformOnly('createPartner');
|
|
141
|
+
const partner = opts === undefined
|
|
142
|
+
? await db.invoke(partnerModel, 'create', fields)
|
|
143
|
+
: await db.invoke(partnerModel, 'create', fields, opts);
|
|
144
|
+
const id = Number(partner.id);
|
|
145
|
+
let seeded;
|
|
146
|
+
try {
|
|
147
|
+
seeded = await provision(id, opts);
|
|
148
|
+
} catch (e) {
|
|
149
|
+
// LEFT UNUSABLE ON PURPOSE, rather than deleted: deleting would discard whatever did get written and hide the
|
|
150
|
+
// evidence; deactivating makes it unreachable to its people while leaving an operator something to fix.
|
|
151
|
+
let deactivated = true;
|
|
152
|
+
try {
|
|
153
|
+
await deactivateWith(id, opts);
|
|
154
|
+
await changed({ op: 'deactivate', id, reason: 'provisioning failed' });
|
|
155
|
+
} catch (de) {
|
|
156
|
+
deactivated = false;
|
|
157
|
+
safeLog('error', `Partner ${id} "${partner.name}" could not be DEACTIVATED after its provisioning failed `
|
|
158
|
+
+ `(${messageOf(de)}) — it is still ACTIVE and half-built. Deactivate it by hand, then fix the cause and re-provision.`);
|
|
159
|
+
}
|
|
160
|
+
safeLog('error', `Partner ${id} "${partner.name}" was created but could not be provisioned (${messageOf(e)}) — `
|
|
161
|
+
+ (deactivated ? 'left DEACTIVATED. Fix the cause and re-provision; do not create a second.'
|
|
162
|
+
: 'and it could NOT be deactivated (logged above).'));
|
|
163
|
+
const err = new Error(deactivated
|
|
164
|
+
? `The partner was created but could not be set up (${messageOf(e)}). It has been deactivated so `
|
|
165
|
+
+ 'nobody can sign in to a half-built tenant. Re-provision it once the cause is fixed.'
|
|
166
|
+
: `The partner was created but could not be set up (${messageOf(e)}), and it could not be deactivated either: `
|
|
167
|
+
+ 'it is still active. Deactivate it, then re-provision it once the cause is fixed.');
|
|
168
|
+
err.partnerId = id;
|
|
169
|
+
err.deactivated = deactivated;
|
|
170
|
+
err.cause = e;
|
|
171
|
+
// The row exists whether or not it could be deactivated: the caches hear of it either way.
|
|
172
|
+
if (!deactivated) await changed({ op: 'create', id, reason: 'provisioning failed, still active' });
|
|
173
|
+
throw err;
|
|
174
|
+
}
|
|
175
|
+
// Logged OUTSIDE the try: a logger that throws must not turn a provisioned partner into a "failed" one and
|
|
176
|
+
// deactivate it.
|
|
177
|
+
await changed({ op: 'create', id });
|
|
178
|
+
safeLog('info', () => `Partner ${id} "${partner.name}" created and provisioned: ${describe(seeded)}`);
|
|
179
|
+
return { ...partner, seeded };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* The callback, guarded: every subscriber is STARTED AT ONCE, in array order (each called synchronously, one after
|
|
184
|
+
* the other, before any is awaited), each isolated, and all are awaited to settle before the write answers. So no
|
|
185
|
+
* entry's slow work delays another's immediate effect (the active set's stale mark, the host map's drop), and order
|
|
186
|
+
* opens no window. One that throws or rejects is logged at error (with its position when there is more than one);
|
|
187
|
+
* nothing changes what the write answered. Every entry must settle: nothing here bounds one that never does.
|
|
188
|
+
*/
|
|
189
|
+
async function changed(event) {
|
|
190
|
+
const failed = (i, e) => {
|
|
191
|
+
const which = subscribers.length > 1 ? ` (onPartnersChanged entry ${i + 1} of ${subscribers.length})` : '';
|
|
192
|
+
safeLog('error', `Partner ${event.id}: the partner-list refresh${which} after "${event.op}" failed (${messageOf(e)}) — `
|
|
193
|
+
+ 'host and active-partner caches may be stale until the next change or restart.');
|
|
194
|
+
};
|
|
195
|
+
const runs = subscribers.map((f, i) => {
|
|
196
|
+
try { return Promise.resolve(f(event)).catch((e) => failed(i, e)); } catch (e) { failed(i, e); return null; }
|
|
197
|
+
});
|
|
198
|
+
await Promise.all(runs);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The other two writes to the partner list, through the same callback: the app's routes call these instead of
|
|
203
|
+
* invoking the store directly, so every write that commits refreshes the caches. The store's own answer is
|
|
204
|
+
* returned unchanged (`changes` 0 for a repeat). A write that throws refreshes nothing.
|
|
205
|
+
*/
|
|
206
|
+
async function updatePartner(id, fields, opts) {
|
|
207
|
+
platformOnly('updatePartner');
|
|
208
|
+
const r = opts === undefined ? await db.invoke(partnerModel, 'update', id, fields) : await db.invoke(partnerModel, 'update', id, fields, opts);
|
|
209
|
+
await changed({ op: 'update', id: Number(id), changes: Number(r && r.changes) || 0 });
|
|
210
|
+
return r;
|
|
211
|
+
}
|
|
212
|
+
async function setPartnerActive(id, active, opts) {
|
|
213
|
+
platformOnly('setPartnerActive');
|
|
214
|
+
const r = opts === undefined ? await db.invoke(partnerModel, 'setActive', id, active) : await db.invoke(partnerModel, 'setActive', id, active, opts);
|
|
215
|
+
await changed({ op: active ? 'activate' : 'deactivate', id: Number(id), changes: Number(r && r.changes) || 0 });
|
|
216
|
+
return r;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* The guarded notifier, for a main-thread write that does not go through this provisioner: call it right after the
|
|
221
|
+
* write has returned. Never throws; a failing callback is logged at error.
|
|
222
|
+
*/
|
|
223
|
+
async function partnersChanged(event) {
|
|
224
|
+
await changed({ op: 'change', id: null, ...(event || {}) });
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* A DIRECT STORE WRITE ON THE MAIN THREAD, followed by the callback: `write('setActiveFromHub', id, 0)`,
|
|
229
|
+
* `write('bindHouseRef', ref)`, `write('update', id, fields)`. Invokes `<partnerModel>.<method>(...args)`, fires
|
|
230
|
+
* the notifier ONCE after it returned (committed), not when it throws, and returns its answer unchanged. The
|
|
231
|
+
* attached apps' hub-receive paths write through this, so a partner deactivated at the hub ends acting into it and
|
|
232
|
+
* clears its host as a local deactivation does.
|
|
233
|
+
*/
|
|
234
|
+
async function write(method, ...args) {
|
|
235
|
+
if (typeof method !== 'string' || !method) throw new Error('write(method, ...args): name the store method');
|
|
236
|
+
platformOnly(`write('${method}')`);
|
|
237
|
+
const r = await db.invoke(partnerModel, method, ...args);
|
|
238
|
+
const first = args[0];
|
|
239
|
+
const id = (typeof first === 'number' || (typeof first === 'string' && /^[0-9]+$/.test(first))) ? Number(first) : null;
|
|
240
|
+
await changed({ op: method, id, changes: Number(r && r.changes) || 0 });
|
|
241
|
+
return r;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
return { createPartner, provision, updatePartner, setPartnerActive, partnersChanged, write };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
module.exports = { createProvisioner };
|