@12-apps/tenant 1.0.0 → 1.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/ADOPTING.md +137 -1
- package/README.md +10 -4
- package/package.json +1 -1
- package/src/index.ts +44 -2
- package/src/port.ts +84 -3
- package/src/server/index.ts +67 -8
- package/src/slugs/index.ts +125 -0
- package/src/slugs/memory-options.ts +39 -0
- package/src/slugs/memory.ts +373 -0
- package/src/slugs/port.ts +36 -0
- package/src/tree/index.ts +147 -0
- package/src/tree/path.ts +103 -0
- package/src/validate.ts +44 -1
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Values read once per server process and kept until the database says they
|
|
3
|
+
* changed: the memory behind slug resolution, and any other host reading that
|
|
4
|
+
* is invalidated the same way.
|
|
5
|
+
*
|
|
6
|
+
* - **Invalidation comes from the database.** The host's triggers call
|
|
7
|
+
* `pg_notify(<channel>, <scope>)` after the write commits. The payload names
|
|
8
|
+
* the scope to drop (a tenant's id, say), or `*` for every scope. The
|
|
9
|
+
* package owns no trigger: it only listens, through the host's `listen`, on
|
|
10
|
+
* the channel it is given.
|
|
11
|
+
* - **Nothing is kept while the listener is down**: a disconnect drops
|
|
12
|
+
* everything and keeps nothing until the reconnect, which drops everything
|
|
13
|
+
* again, because a notification sent while it was down is lost.
|
|
14
|
+
* - **A load a notification overtakes is not kept**: the scope's epoch, and
|
|
15
|
+
* the epoch of every scope, are read before the load and compared after it.
|
|
16
|
+
* A drop of ANOTHER scope does not cost this one its load, so a busy tenant
|
|
17
|
+
* cannot keep a quiet one from being kept.
|
|
18
|
+
* - **A backstop lifetime** bounds a delivery that never arrives.
|
|
19
|
+
* - **A listener that cannot start** is tried again after a pause, not on every
|
|
20
|
+
* read: until then every read goes to the database.
|
|
21
|
+
* - **One load for a burst** of reads of the same value.
|
|
22
|
+
* - **A write this process made** can quiet the memory (`quiet`): on
|
|
23
|
+
* PostgreSQL the notification reaches the listener a moment after the
|
|
24
|
+
* writer's `COMMIT` returns, and the writer's own read-back must not be
|
|
25
|
+
* answered from the copy it is about to lose.
|
|
26
|
+
*
|
|
27
|
+
* A value is kept under a SCOPE (what one notification drops) and a SLOT (one
|
|
28
|
+
* reader's answer within it), so a tenant's whole configuration goes in one
|
|
29
|
+
* drop. What a reader keeps it gets back as it was kept: the caller copies, or
|
|
30
|
+
* keeps a value it will not edit.
|
|
31
|
+
*
|
|
32
|
+
* Every number is the host's: nothing here has a default.
|
|
33
|
+
*/
|
|
34
|
+
import { validateKeptMemoryOptions } from './memory-options';
|
|
35
|
+
|
|
36
|
+
export { validateKeptMemoryOptions } from './memory-options';
|
|
37
|
+
|
|
38
|
+
/** Every scope, as a notification payload. */
|
|
39
|
+
export const EVERY_SCOPE = '*';
|
|
40
|
+
|
|
41
|
+
/** What the host's listener reports back: the shape `LISTEN` helpers already have. */
|
|
42
|
+
export interface TenantChangeHandlers {
|
|
43
|
+
onNotify(payload: string): void;
|
|
44
|
+
/** The connection (re)connected: anything sent while it was down is lost. */
|
|
45
|
+
onConnected(): void;
|
|
46
|
+
/** The connection dropped: nothing can reach the memory until `onConnected`. */
|
|
47
|
+
onDisconnected?(): void;
|
|
48
|
+
onError?(error: unknown): void;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The host's `LISTEN`: start listening on `channel` and call `handlers` as the
|
|
53
|
+
* database speaks. Resolves once the first connection is up (resolving counts
|
|
54
|
+
* as connected); rejects when it cannot start.
|
|
55
|
+
*/
|
|
56
|
+
export type TenantChangeListener = (channel: string, handlers: TenantChangeHandlers) => Promise<unknown>;
|
|
57
|
+
|
|
58
|
+
/** What the memory reports when its listener fails: the host logs it in its own words. */
|
|
59
|
+
export interface KeptMemoryErrorEvent {
|
|
60
|
+
/** `start`: the listener could not start, nothing is kept until a retry. `dropped`: it dropped and is reconnecting. */
|
|
61
|
+
phase: 'start' | 'dropped';
|
|
62
|
+
channel: string;
|
|
63
|
+
error: unknown;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface KeptMemoryOptions {
|
|
67
|
+
/** The `NOTIFY` channel the host's triggers send on (`/^[a-z_][a-z0-9_]*$/`). */
|
|
68
|
+
channel: string;
|
|
69
|
+
/** The host's `LISTEN`. */
|
|
70
|
+
listen: TenantChangeListener;
|
|
71
|
+
/** Told when the listener cannot start or drops. */
|
|
72
|
+
onError(event: KeptMemoryErrorEvent): void;
|
|
73
|
+
/** How long a kept value is trusted with no notification at all. */
|
|
74
|
+
backstopMs: number;
|
|
75
|
+
/** How long after a listener failed to start before it is tried again. */
|
|
76
|
+
retryMs: number;
|
|
77
|
+
/** A bound on the scopes kept, oldest dropped first. A dropped scope just loads again. */
|
|
78
|
+
maxScopes: number;
|
|
79
|
+
/** A bound on one scope's slots, oldest dropped first. */
|
|
80
|
+
maxSlots: number;
|
|
81
|
+
/**
|
|
82
|
+
* The database the listener hears. Asked before every read, and a different
|
|
83
|
+
* one than last time drops everything and listens afresh (a test that swaps
|
|
84
|
+
* its in-process database must not be answered from the previous one). One
|
|
85
|
+
* that throws means there is none to bind to: nothing is kept. Absent,
|
|
86
|
+
* nothing is compared.
|
|
87
|
+
*/
|
|
88
|
+
database?: () => object | null;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface KeptReadOptions<T> {
|
|
92
|
+
/** Whether this answer may be kept. Every answer is, unless this says no. */
|
|
93
|
+
keep?(value: T): boolean;
|
|
94
|
+
/**
|
|
95
|
+
* The client or transaction `load` reads through. A read joins a load
|
|
96
|
+
* already running for the same slot only through the same one: a reader
|
|
97
|
+
* inside a transaction must not wait on a load that, on a single
|
|
98
|
+
* connection, waits for that transaction to end. A read through one never
|
|
99
|
+
* starts the listener.
|
|
100
|
+
*/
|
|
101
|
+
via?: object;
|
|
102
|
+
/**
|
|
103
|
+
* An epoch ({@link KeptMemory.epoch}) the answer must still be at to be
|
|
104
|
+
* kept, older than the load's own: a snapshot transaction's, taken before
|
|
105
|
+
* its snapshot was, so a change committed after the snapshot and heard
|
|
106
|
+
* already is not kept as current.
|
|
107
|
+
*/
|
|
108
|
+
since?: number;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface KeptMemory {
|
|
112
|
+
/** The value `slot` of `scope` holds, from memory when kept, else from `load`. */
|
|
113
|
+
read<T>(scope: string, slot: string, load: () => Promise<T>, options?: KeptReadOptions<T>): Promise<T>;
|
|
114
|
+
/**
|
|
115
|
+
* The value `slot` of `scope` holds when this process already kept it, else
|
|
116
|
+
* `undefined`: never a load, never the listener's start. For a path that must
|
|
117
|
+
* not pay a statement for what it can do without.
|
|
118
|
+
*/
|
|
119
|
+
peek<T>(scope: string, slot: string): T | undefined;
|
|
120
|
+
/**
|
|
121
|
+
* Drop `scope` (every scope when absent) and keep nothing of it for `ms`:
|
|
122
|
+
* this process just wrote what the memory holds, and the notification is
|
|
123
|
+
* still on its way.
|
|
124
|
+
*/
|
|
125
|
+
quiet(ms: number, scope?: string): void;
|
|
126
|
+
/** Drop `scope` now, as a notification naming it would. */
|
|
127
|
+
drop(scope: string): void;
|
|
128
|
+
/** The count of drops so far: an answer is kept only if none happened since its read began. */
|
|
129
|
+
epoch(): number;
|
|
130
|
+
/** Tests only: start from an empty memory and a fresh listener. */
|
|
131
|
+
resetForTests(): void;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* A memory kept by notification. Validates its options at once (a missing
|
|
136
|
+
* one fails at startup, named); listens lazily, on the first read.
|
|
137
|
+
*/
|
|
138
|
+
export function createKeptMemory(options: KeptMemoryOptions): KeptMemory {
|
|
139
|
+
validateKeptMemoryOptions(options);
|
|
140
|
+
return new NotifiedMemory({ ...options });
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
interface Kept {
|
|
144
|
+
value: unknown;
|
|
145
|
+
until: number;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
class NotifiedMemory implements KeptMemory {
|
|
149
|
+
private readonly kept = new Map<string, Map<string, Kept>>();
|
|
150
|
+
private readonly inFlight = new Map<string, { loading: Promise<unknown>; via: object | undefined }>();
|
|
151
|
+
private drops = 0;
|
|
152
|
+
/** Drops of every scope at once (`*`, a reconnect, a reset). */
|
|
153
|
+
private everyDrops = 0;
|
|
154
|
+
/** Drops of one scope, since the last drop of every scope. */
|
|
155
|
+
private readonly scopeDrops = new Map<string, number>();
|
|
156
|
+
private listening: Promise<boolean> | null = null;
|
|
157
|
+
private retryAfter = 0;
|
|
158
|
+
private quietUntil = 0;
|
|
159
|
+
private readonly quietScopes = new Map<string, number>();
|
|
160
|
+
/** Whether the listener's connection is up: a notification can reach the memory. */
|
|
161
|
+
private connected = false;
|
|
162
|
+
private database: object | null = null;
|
|
163
|
+
|
|
164
|
+
constructor(private readonly options: KeptMemoryOptions) {}
|
|
165
|
+
|
|
166
|
+
async read<T>(scope: string, slot: string, load: () => Promise<T>, readOptions?: KeptReadOptions<T>): Promise<T> {
|
|
167
|
+
if (!(await this.mayKeep(scope, readOptions?.via))) return load();
|
|
168
|
+
const hit = this.kept.get(scope)?.get(slot);
|
|
169
|
+
if (hit && hit.until > Date.now()) return hit.value as T;
|
|
170
|
+
return this.loadOnce(scope, slot, load, readOptions);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
peek<T>(scope: string, slot: string): T | undefined {
|
|
174
|
+
if (!this.boundToDatabase() || !this.connected || this.isQuiet(scope)) return undefined;
|
|
175
|
+
const hit = this.kept.get(scope)?.get(slot);
|
|
176
|
+
return hit !== undefined && hit.until > Date.now() ? (hit.value as T) : undefined;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Whether a read of `scope` may be answered from, and kept in, memory right now. */
|
|
180
|
+
private async mayKeep(scope: string, via: object | undefined): Promise<boolean> {
|
|
181
|
+
if (!this.boundToDatabase()) return false;
|
|
182
|
+
// Starting the listener issues a `LISTEN`, which on a single connection
|
|
183
|
+
// would wait for the caller's own transaction: a read through one does not
|
|
184
|
+
// start it, it only reads.
|
|
185
|
+
if (!this.listening && via !== undefined) return false;
|
|
186
|
+
return (await this.ensureListening()) && this.connected && !this.isQuiet(scope);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** One load for a burst of reads of the same slot through the same client or transaction. */
|
|
190
|
+
private loadOnce<T>(scope: string, slot: string, load: () => Promise<T>, readOptions?: KeptReadOptions<T>): Promise<T> {
|
|
191
|
+
const key = `${scope}\u0000${slot}`;
|
|
192
|
+
const via = readOptions?.via;
|
|
193
|
+
const pending = this.inFlight.get(key);
|
|
194
|
+
if (pending && pending.via === via) return pending.loading as Promise<T>;
|
|
195
|
+
const loading = this.loadAndKeep(scope, slot, load, readOptions).finally(() => {
|
|
196
|
+
if (this.inFlight.get(key)?.loading === loading) this.inFlight.delete(key);
|
|
197
|
+
});
|
|
198
|
+
// A load through another client or transaction is already out: this one runs beside it.
|
|
199
|
+
if (!pending) this.inFlight.set(key, { loading, via });
|
|
200
|
+
return loading;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
epoch(): number {
|
|
204
|
+
return this.drops;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
drop(scope: string): void {
|
|
208
|
+
this.forget(scope);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
quiet(ms: number, scope?: string): void {
|
|
212
|
+
const until = Date.now() + ms;
|
|
213
|
+
if (scope === undefined) {
|
|
214
|
+
this.forget(EVERY_SCOPE);
|
|
215
|
+
this.quietUntil = Math.max(this.quietUntil, until);
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
this.forget(scope);
|
|
219
|
+
this.quietScopes.set(scope, Math.max(this.quietScopes.get(scope) ?? 0, until));
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private isQuiet(scope: string): boolean {
|
|
223
|
+
const now = Date.now();
|
|
224
|
+
if (now < this.quietUntil) return true;
|
|
225
|
+
const until = this.quietScopes.get(scope);
|
|
226
|
+
if (until === undefined) return false;
|
|
227
|
+
if (now < until) return true;
|
|
228
|
+
this.quietScopes.delete(scope);
|
|
229
|
+
return false;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
resetForTests(): void {
|
|
233
|
+
this.reset();
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
private reset(): void {
|
|
237
|
+
this.kept.clear();
|
|
238
|
+
this.inFlight.clear();
|
|
239
|
+
this.drops += 1;
|
|
240
|
+
this.everyDrops += 1;
|
|
241
|
+
this.scopeDrops.clear();
|
|
242
|
+
this.listening = null;
|
|
243
|
+
this.retryAfter = 0;
|
|
244
|
+
this.quietUntil = 0;
|
|
245
|
+
this.quietScopes.clear();
|
|
246
|
+
this.connected = false;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Follow the database the listener hears; `false` when there is none to bind to. */
|
|
250
|
+
private boundToDatabase(): boolean {
|
|
251
|
+
let database: object | null;
|
|
252
|
+
try {
|
|
253
|
+
database = this.options.database ? this.options.database() : null;
|
|
254
|
+
} catch {
|
|
255
|
+
return false;
|
|
256
|
+
}
|
|
257
|
+
if (database !== this.database) {
|
|
258
|
+
this.reset();
|
|
259
|
+
this.database = database;
|
|
260
|
+
}
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
private forget(payload: string): void {
|
|
265
|
+
this.drops += 1;
|
|
266
|
+
if (payload === EVERY_SCOPE || payload === '') {
|
|
267
|
+
this.everyDrops += 1;
|
|
268
|
+
this.scopeDrops.clear();
|
|
269
|
+
this.kept.clear();
|
|
270
|
+
this.inFlight.clear();
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
this.scopeDrops.set(payload, (this.scopeDrops.get(payload) ?? 0) + 1);
|
|
274
|
+
this.kept.delete(payload);
|
|
275
|
+
const prefix = `${payload}\u0000`;
|
|
276
|
+
for (const key of [...this.inFlight.keys()]) if (key.startsWith(prefix)) this.inFlight.delete(key);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Start the listener once. `false` while it is not up: then nothing is kept. */
|
|
280
|
+
private ensureListening(): Promise<boolean> {
|
|
281
|
+
if (this.listening) return this.listening;
|
|
282
|
+
// A database that refused once is not asked again on every read.
|
|
283
|
+
if (Date.now() < this.retryAfter) return Promise.resolve(false);
|
|
284
|
+
const { channel } = this.options;
|
|
285
|
+
let started: Promise<unknown>;
|
|
286
|
+
try {
|
|
287
|
+
// A drop reported before `listen` resolves must not be undone by its resolving.
|
|
288
|
+
const dropped = { since: false };
|
|
289
|
+
started = this.options
|
|
290
|
+
.listen(channel, {
|
|
291
|
+
onNotify: (payload) => this.forget(payload),
|
|
292
|
+
onConnected: () => {
|
|
293
|
+
this.forget(EVERY_SCOPE);
|
|
294
|
+
dropped.since = false;
|
|
295
|
+
this.connected = true;
|
|
296
|
+
},
|
|
297
|
+
onDisconnected: () => {
|
|
298
|
+
dropped.since = true;
|
|
299
|
+
this.connected = false;
|
|
300
|
+
this.forget(EVERY_SCOPE);
|
|
301
|
+
},
|
|
302
|
+
onError: (error) => this.report({ phase: 'dropped', channel, error }),
|
|
303
|
+
})
|
|
304
|
+
.then(() => {
|
|
305
|
+
// Up: the first connection is made before `listen` resolves.
|
|
306
|
+
if (!dropped.since) this.connected = true;
|
|
307
|
+
});
|
|
308
|
+
} catch (error) {
|
|
309
|
+
started = Promise.reject(error);
|
|
310
|
+
}
|
|
311
|
+
const up: Promise<boolean> = started.then(
|
|
312
|
+
() => true,
|
|
313
|
+
(error: unknown) => {
|
|
314
|
+
// Not up: answer from the database, and try again on a later read. The
|
|
315
|
+
// state is reset BEFORE the host is told, so a host reporter that throws
|
|
316
|
+
// cannot leave a rejected start stored for every later read.
|
|
317
|
+
if (this.listening === up) this.listening = null;
|
|
318
|
+
this.retryAfter = Date.now() + this.options.retryMs;
|
|
319
|
+
this.report({ phase: 'start', channel, error });
|
|
320
|
+
return false;
|
|
321
|
+
},
|
|
322
|
+
);
|
|
323
|
+
this.listening = up;
|
|
324
|
+
return up;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Tell the host; a reporter that throws must not break the memory. */
|
|
328
|
+
private report(event: KeptMemoryErrorEvent): void {
|
|
329
|
+
try {
|
|
330
|
+
this.options.onError(event);
|
|
331
|
+
} catch {
|
|
332
|
+
// The host's reporter failed: the memory carries on as if it had logged.
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
private keep(scope: string, slot: string, value: unknown, now: number): void {
|
|
337
|
+
const slots = this.kept.get(scope) ?? new Map<string, Kept>();
|
|
338
|
+
// Most recently used last, so the oldest scope is the first key.
|
|
339
|
+
this.kept.delete(scope);
|
|
340
|
+
this.kept.set(scope, slots);
|
|
341
|
+
slots.delete(slot);
|
|
342
|
+
slots.set(slot, { value, until: now + this.options.backstopMs });
|
|
343
|
+
if (slots.size > this.options.maxSlots) {
|
|
344
|
+
const oldestSlot = slots.keys().next().value;
|
|
345
|
+
if (oldestSlot !== undefined) slots.delete(oldestSlot);
|
|
346
|
+
}
|
|
347
|
+
if (this.kept.size > this.options.maxScopes) {
|
|
348
|
+
const oldest = this.kept.keys().next().value;
|
|
349
|
+
if (oldest !== undefined) this.kept.delete(oldest);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
private async loadAndKeep<T>(scope: string, slot: string, load: () => Promise<T>, readOptions?: KeptReadOptions<T>): Promise<T> {
|
|
354
|
+
const stillCurrent = this.overtakenBy(scope, readOptions?.since);
|
|
355
|
+
const now = Date.now();
|
|
356
|
+
const value = await load();
|
|
357
|
+
if (stillCurrent() && (readOptions?.keep?.(value) ?? true)) this.keep(scope, slot, value, now);
|
|
358
|
+
return value;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Whether nothing that could have changed `scope` was dropped since now: no
|
|
363
|
+
* drop of the scope, none of every scope. A snapshot's epoch (`since`) is the
|
|
364
|
+
* memory's whole count, taken before the snapshot: any drop since then may
|
|
365
|
+
* be a change the snapshot cannot see.
|
|
366
|
+
*/
|
|
367
|
+
private overtakenBy(scope: string, since: number | undefined): () => boolean {
|
|
368
|
+
if (since !== undefined) return () => since === this.drops;
|
|
369
|
+
const atEvery = this.everyDrops;
|
|
370
|
+
const atScope = this.scopeDrops.get(scope) ?? 0;
|
|
371
|
+
return () => atEvery === this.everyDrops && atScope === (this.scopeDrops.get(scope) ?? 0);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The slug port: how the package reads the host's tenant row by its address.
|
|
3
|
+
* The host owns the slug columns and the table of slugs a tenant held before
|
|
4
|
+
* (a kept slug); the package owns none of them and reads both only here.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** What a slug resolves to: at least the tenant's id and its CURRENT slug; the host adds its own columns. */
|
|
8
|
+
export interface TenantSlugRecord {
|
|
9
|
+
id: string;
|
|
10
|
+
slug: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** The tenant a unit's slug is unique within: its id and its tree path (`/<root>/…/<id>/`). */
|
|
14
|
+
export interface TenantSlugParent {
|
|
15
|
+
id: string;
|
|
16
|
+
path: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Every member is ONE read. `parent` is null for a root lookup, whose slug is
|
|
21
|
+
* globally unique; a tenant's slug under a parent is unique within that
|
|
22
|
+
* parent only, and the host reads it there.
|
|
23
|
+
*/
|
|
24
|
+
export interface TenantSlugPort<R extends TenantSlugRecord = TenantSlugRecord> {
|
|
25
|
+
/** The tenant whose CURRENT slug is `slug` (under `parent`), or null. */
|
|
26
|
+
current(slug: string, parent: TenantSlugParent | null): Promise<R | null>;
|
|
27
|
+
/**
|
|
28
|
+
* The tenant that once held `slug` (under `parent`) and has since moved to
|
|
29
|
+
* another, carrying its CURRENT slug; null when none did. A tenant keeps
|
|
30
|
+
* every slug it ever held, so an old address is never handed to another.
|
|
31
|
+
*/
|
|
32
|
+
former(slug: string, parent: TenantSlugParent | null): Promise<R | null>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The slug port's members, in a fixed order: what startup validation checks. */
|
|
36
|
+
export const TENANT_SLUG_PORT_METHODS = ['current', 'former'] as const;
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tenant tree: ownership of any depth (a company above its units, a unit
|
|
3
|
+
* above its venues), read and moved through the tenant port only. The package
|
|
4
|
+
* owns no tenant row: it computes and validates every path, refuses a cycle
|
|
5
|
+
* and plans a move; the host stores the paths and applies the plan.
|
|
6
|
+
*
|
|
7
|
+
* Every read is ONE port call at any depth (`parentOf`, `rootOf` read the
|
|
8
|
+
* tenant's own node; `ancestorsOf` and `descendantsOf` one indexed read each).
|
|
9
|
+
* A move is two node reads and ONE write that rewrites the whole subtree.
|
|
10
|
+
*
|
|
11
|
+
* Participation (a tenant selling inside another tenant's space) is not a
|
|
12
|
+
* parent: the tree is ownership only.
|
|
13
|
+
*/
|
|
14
|
+
import type { TenantTreeMove, TenantTreeNode, TenantTreePort } from '../port';
|
|
15
|
+
|
|
16
|
+
export type { TenantTreePort } from '../port';
|
|
17
|
+
import {
|
|
18
|
+
TenantTreeError,
|
|
19
|
+
assertSegment,
|
|
20
|
+
depthOf,
|
|
21
|
+
isWithin,
|
|
22
|
+
movedPath,
|
|
23
|
+
validateNode,
|
|
24
|
+
} from './path';
|
|
25
|
+
|
|
26
|
+
export {
|
|
27
|
+
TenantTreeError,
|
|
28
|
+
childPath,
|
|
29
|
+
depthOf,
|
|
30
|
+
isWithin,
|
|
31
|
+
parsePath,
|
|
32
|
+
rootPath,
|
|
33
|
+
validateNode,
|
|
34
|
+
type TenantTreeErrorCode,
|
|
35
|
+
} from './path';
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Every read takes the host's transaction optionally (to read what a write in
|
|
40
|
+
* it will see); the move takes it REQUIRED: the package never opens one, and
|
|
41
|
+
* never writes outside the caller's.
|
|
42
|
+
*/
|
|
43
|
+
export interface TenantTree<Tx = unknown> {
|
|
44
|
+
/** The tenant directly above `id`, or null for a root. One port call. */
|
|
45
|
+
parentOf(id: string, tx?: Tx): Promise<string | null>;
|
|
46
|
+
/** The root of `id`'s tree (`id` itself for a root). One port call. */
|
|
47
|
+
rootOf(id: string, tx?: Tx): Promise<string>;
|
|
48
|
+
/** Every tenant above `id`, nearest first; empty for a root. One port call. */
|
|
49
|
+
ancestorsOf(id: string, tx?: Tx): Promise<TenantTreeNode[]>;
|
|
50
|
+
/** Every tenant below `id` at any depth, shallowest first; `id` excluded. One port call. */
|
|
51
|
+
descendantsOf(id: string, tx?: Tx): Promise<TenantTreeNode[]>;
|
|
52
|
+
/**
|
|
53
|
+
* Move `id`, with everything below it, under `parentId` (null: make it a
|
|
54
|
+
* root), inside the caller's transaction: the plan's two reads and the
|
|
55
|
+
* write all run in `tx`. Refuses a cycle before anything is written; answers
|
|
56
|
+
* the rows the host rewrote. Throws `moved` when the tree changed under the
|
|
57
|
+
* plan.
|
|
58
|
+
*/
|
|
59
|
+
move(id: string, parentId: string | null, tx: Tx): Promise<number>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function nodeOf<Tx>(
|
|
63
|
+
port: TenantTreePort<Tx>,
|
|
64
|
+
id: string,
|
|
65
|
+
tx: Tx | undefined,
|
|
66
|
+
): Promise<{ node: TenantTreeNode; ids: string[] }> {
|
|
67
|
+
assertSegment(id);
|
|
68
|
+
const node = await port.treeNode(id, tx);
|
|
69
|
+
if (node === null) throw new TenantTreeError('unknown-tenant', `no tenant "${id}"`);
|
|
70
|
+
return { node, ids: validateNode(node) };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Shallowest first, then by id, so equal depths answer in a stable order. */
|
|
74
|
+
function byDepth(a: TenantTreeNode, b: TenantTreeNode): number {
|
|
75
|
+
return depthOf(a.path) - depthOf(b.path) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The read's nodes, each validated; refuses a read that lost its own tenant. */
|
|
79
|
+
function checked(id: string, nodes: readonly TenantTreeNode[]): TenantTreeNode[] {
|
|
80
|
+
nodes.forEach(validateNode);
|
|
81
|
+
if (!nodes.some((node) => node.id === id)) {
|
|
82
|
+
throw new TenantTreeError('unknown-tenant', `no tenant "${id}"`);
|
|
83
|
+
}
|
|
84
|
+
return [...nodes].sort(byDepth);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function createTenantTree<Tx = unknown>(port: TenantTreePort<Tx>): TenantTree<Tx> {
|
|
88
|
+
return {
|
|
89
|
+
async parentOf(id, tx) {
|
|
90
|
+
return (await nodeOf(port, id, tx)).node.parentId;
|
|
91
|
+
},
|
|
92
|
+
|
|
93
|
+
async rootOf(id, tx) {
|
|
94
|
+
const { ids } = await nodeOf(port, id, tx);
|
|
95
|
+
return ids[0] as string;
|
|
96
|
+
},
|
|
97
|
+
|
|
98
|
+
async ancestorsOf(id, tx) {
|
|
99
|
+
assertSegment(id);
|
|
100
|
+
const nodes = checked(id, await port.treeAncestors(id, tx));
|
|
101
|
+
const self = nodes[nodes.length - 1] as TenantTreeNode;
|
|
102
|
+
// Exactly the ids the tenant's own path names above it, no more, no fewer.
|
|
103
|
+
const above = validateNode(self).slice(0, -1);
|
|
104
|
+
const ancestors = nodes.filter((node) => node.id !== id);
|
|
105
|
+
if (ancestors.length !== above.length || ancestors.some((node, index) => node.id !== above[index])) {
|
|
106
|
+
throw new TenantTreeError('corrupt-path', `the ancestors read for "${id}" disagree with "${self.path}"`);
|
|
107
|
+
}
|
|
108
|
+
return ancestors.reverse();
|
|
109
|
+
},
|
|
110
|
+
|
|
111
|
+
async descendantsOf(id, tx) {
|
|
112
|
+
assertSegment(id);
|
|
113
|
+
const nodes = checked(id, await port.treeDescendants(id, tx));
|
|
114
|
+
const self = nodes[0] as TenantTreeNode;
|
|
115
|
+
if (self.id !== id || nodes.some((node) => !isWithin(node.path, self.path))) {
|
|
116
|
+
throw new TenantTreeError('corrupt-path', `the descendants read for "${id}" left "${self.path}"`);
|
|
117
|
+
}
|
|
118
|
+
return nodes.slice(1);
|
|
119
|
+
},
|
|
120
|
+
|
|
121
|
+
async move(id, parentId, tx) {
|
|
122
|
+
const { node } = await nodeOf(port, id, tx);
|
|
123
|
+
let parentPath: string | null = null;
|
|
124
|
+
if (parentId !== null) {
|
|
125
|
+
if (parentId === id) throw new TenantTreeError('cycle', `"${id}" cannot be its own parent`);
|
|
126
|
+
const parent = (await nodeOf(port, parentId, tx)).node;
|
|
127
|
+
if (isWithin(parent.path, node.path)) {
|
|
128
|
+
throw new TenantTreeError('cycle', `"${id}" cannot move under "${parentId}", which sits below it`);
|
|
129
|
+
}
|
|
130
|
+
parentPath = parent.path;
|
|
131
|
+
}
|
|
132
|
+
const plan: TenantTreeMove = {
|
|
133
|
+
id,
|
|
134
|
+
parentId,
|
|
135
|
+
parentPath,
|
|
136
|
+
fromPath: node.path,
|
|
137
|
+
toPath: movedPath(id, parentPath),
|
|
138
|
+
};
|
|
139
|
+
if (plan.toPath === plan.fromPath) return 0; // already there
|
|
140
|
+
const written = await port.moveSubtree(plan, tx);
|
|
141
|
+
if (written === 0) {
|
|
142
|
+
throw new TenantTreeError('moved', `the tree changed while "${id}" was moving; nothing was written`);
|
|
143
|
+
}
|
|
144
|
+
return written;
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
package/src/tree/path.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The materialized path of the tenant tree: pure, no I/O.
|
|
3
|
+
*
|
|
4
|
+
* A path is `/` + each id from the root down to the tenant itself, each
|
|
5
|
+
* followed by `/`: a root's is `/<id>/`, a unit's `/<root>/<id>/`. Because it
|
|
6
|
+
* ends in `/`, "this tenant and everything below it" is exactly the paths that
|
|
7
|
+
* START with its path, which a host serves with one indexed prefix (or range)
|
|
8
|
+
* read; and every ancestor's id is one of its segments, which a host serves
|
|
9
|
+
* with one primary-key read. Nothing ever recurses.
|
|
10
|
+
*/
|
|
11
|
+
import type { TenantTreeNode } from '../port';
|
|
12
|
+
|
|
13
|
+
/** Why a tree operation was refused. */
|
|
14
|
+
export type TenantTreeErrorCode =
|
|
15
|
+
/** An id is not a valid path segment (empty, or containing `/`). */
|
|
16
|
+
| 'invalid-id'
|
|
17
|
+
/** No tenant has the id. */
|
|
18
|
+
| 'unknown-tenant'
|
|
19
|
+
/** The host returned a node whose path does not agree with its own row. */
|
|
20
|
+
| 'corrupt-path'
|
|
21
|
+
/** The move would make a tenant its own ancestor. */
|
|
22
|
+
| 'cycle'
|
|
23
|
+
/** The tree changed between the plan and the write: nothing was written. */
|
|
24
|
+
| 'moved';
|
|
25
|
+
|
|
26
|
+
/** Thrown when a tree read or move is refused; `code` says why. */
|
|
27
|
+
export class TenantTreeError extends Error {
|
|
28
|
+
readonly code: TenantTreeErrorCode;
|
|
29
|
+
|
|
30
|
+
constructor(code: TenantTreeErrorCode, message: string) {
|
|
31
|
+
super(`@12-apps/tenant: ${message}`);
|
|
32
|
+
this.name = 'TenantTreeError';
|
|
33
|
+
this.code = code;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Refuse an id that cannot be a path segment. */
|
|
38
|
+
export function assertSegment(id: string): void {
|
|
39
|
+
if (typeof id !== 'string' || id.length === 0 || id.includes('/')) {
|
|
40
|
+
throw new TenantTreeError('invalid-id', `"${String(id)}" cannot be a tenant id in a tree path`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The path of a root (a standalone tenant): `/<id>/`. */
|
|
45
|
+
export function rootPath(id: string): string {
|
|
46
|
+
assertSegment(id);
|
|
47
|
+
return `/${id}/`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The path of `id` placed directly under a tenant whose path is `parentPath`. */
|
|
51
|
+
export function childPath(parentPath: string, id: string): string {
|
|
52
|
+
parsePath(parentPath);
|
|
53
|
+
assertSegment(id);
|
|
54
|
+
return `${parentPath}${id}/`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A path's ids, root first. Refuses a malformed path, and one naming the same
|
|
59
|
+
* id twice (a cycle cannot be written down as a path).
|
|
60
|
+
*/
|
|
61
|
+
export function parsePath(path: string): string[] {
|
|
62
|
+
if (typeof path !== 'string' || !/^\/(?:[^/]+\/)+$/u.test(path)) {
|
|
63
|
+
throw new TenantTreeError('corrupt-path', `"${String(path)}" is not a tree path`);
|
|
64
|
+
}
|
|
65
|
+
const ids = path.slice(1, -1).split('/');
|
|
66
|
+
if (new Set(ids).size !== ids.length) {
|
|
67
|
+
throw new TenantTreeError('corrupt-path', `"${path}" names a tenant twice`);
|
|
68
|
+
}
|
|
69
|
+
return ids;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** How deep a path sits: 0 for a root. */
|
|
73
|
+
export function depthOf(path: string): number {
|
|
74
|
+
return parsePath(path).length - 1;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Whether `path` is `ancestorPath` itself or anywhere below it. */
|
|
78
|
+
export function isWithin(path: string, ancestorPath: string): boolean {
|
|
79
|
+
return path.startsWith(ancestorPath);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Hold a node the host returned to its own row: the path parses, ends in the
|
|
84
|
+
* node's own id, and its second-to-last segment is the node's parent (none
|
|
85
|
+
* for a root). Answers the path's ids, root first.
|
|
86
|
+
*/
|
|
87
|
+
export function validateNode(node: TenantTreeNode): string[] {
|
|
88
|
+
const ids = parsePath(node.path);
|
|
89
|
+
const own = ids[ids.length - 1];
|
|
90
|
+
const parent = ids.length > 1 ? ids[ids.length - 2] : null;
|
|
91
|
+
if (own !== node.id || parent !== node.parentId) {
|
|
92
|
+
throw new TenantTreeError(
|
|
93
|
+
'corrupt-path',
|
|
94
|
+
`tenant "${node.id}" (parent ${JSON.stringify(node.parentId)}) has the path "${node.path}"`,
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
return ids;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The new path prefix of a subtree that moves under `parentPath` (null: becomes a root). */
|
|
101
|
+
export function movedPath(id: string, parentPath: string | null): string {
|
|
102
|
+
return parentPath === null ? rootPath(id) : childPath(parentPath, id);
|
|
103
|
+
}
|