@12-apps/tenant 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Slug resolution: a tenant by its address, kept slugs included, from process
3
+ * memory once resolved.
4
+ *
5
+ * - **Kept slugs**: a tenant keeps every slug it ever held. A lookup reads the
6
+ * CURRENT slug first and a former one only on a miss, so a known address
7
+ * costs one read and an old one two, as it always has.
8
+ * - **Tree-aware**: a root's slug is globally unique and keys on the slug
9
+ * alone, so every address that resolves today keeps resolving. A unit's slug
10
+ * is unique within its parent: the lookup names the parent's path, and the
11
+ * key is that path plus the slug.
12
+ * - **Kept until the database says it changed**: the memory is the host's
13
+ * (`createKeptMemory`), listening on the host's channel; only a found tenant
14
+ * is kept, so a stream of made-up slugs cannot grow it.
15
+ */
16
+ import { parsePath } from '../tree/path';
17
+ import type { KeptMemory } from './memory';
18
+ import type { TenantSlugParent, TenantSlugPort, TenantSlugRecord } from './port';
19
+
20
+ export {
21
+ EVERY_SCOPE,
22
+ createKeptMemory,
23
+ validateKeptMemoryOptions,
24
+ type KeptMemory,
25
+ type KeptMemoryErrorEvent,
26
+ type KeptMemoryOptions,
27
+ type KeptReadOptions,
28
+ type TenantChangeHandlers,
29
+ type TenantChangeListener,
30
+ } from './memory';
31
+ export {
32
+ TENANT_SLUG_PORT_METHODS,
33
+ type TenantSlugParent,
34
+ type TenantSlugPort,
35
+ type TenantSlugRecord,
36
+ } from './port';
37
+
38
+ /** Where a slug is looked up: under a parent (its tree path), or, left out, among the roots. */
39
+ export interface TenantSlugLookup {
40
+ parentPath?: string;
41
+ }
42
+
43
+ /** The parent a lookup names, or null for a root lookup. Throws `TenantTreeError` on a bad path. */
44
+ function parentOf(lookup: TenantSlugLookup | undefined): TenantSlugParent | null {
45
+ const path = lookup?.parentPath;
46
+ if (path === undefined) return null;
47
+ const ids = parsePath(path);
48
+ return { id: ids[ids.length - 1] as string, path };
49
+ }
50
+
51
+ /**
52
+ * The memory's key for a lookup, or null when it must not be kept: a root
53
+ * keys on the slug (as every address before the tree did), a unit on its
54
+ * parent's path plus the slug. A slug holding `/` is never a key (it could
55
+ * pass for a path): it is loaded every time, never thrown on.
56
+ */
57
+ function keyOf(slug: string, lookup: TenantSlugLookup | undefined): string | null {
58
+ if (slug.includes('/')) return null;
59
+ const parent = parentOf(lookup);
60
+ return parent === null ? slug : `${parent.path}${slug}`;
61
+ }
62
+
63
+ export interface TenantSlugResolver<R extends TenantSlugRecord = TenantSlugRecord> {
64
+ /** The tenant `slug` names, current first and a former slug only on a miss; null when none. Never kept. */
65
+ load(slug: string, lookup?: TenantSlugLookup): Promise<R | null>;
66
+ }
67
+
68
+ export function createSlugResolver<R extends TenantSlugRecord>(port: TenantSlugPort<R>): TenantSlugResolver<R> {
69
+ return {
70
+ async load(slug, lookup) {
71
+ const parent = parentOf(lookup);
72
+ return (await port.current(slug, parent)) ?? (await port.former(slug, parent));
73
+ },
74
+ };
75
+ }
76
+
77
+ export interface KeptSlugs {
78
+ /**
79
+ * What `slug` resolves to, from memory once this process resolved it since
80
+ * the last change, else from `load`. Only a non-null answer is kept; one
81
+ * load for a burst of lookups of the same slug.
82
+ */
83
+ read<T>(slug: string, load: () => Promise<T | null>, lookup?: TenantSlugLookup): Promise<T | null>;
84
+ }
85
+
86
+ /** The slug half of a memory: one scope per address, one slot. */
87
+ export function createKeptSlugs(memory: KeptMemory): KeptSlugs {
88
+ return {
89
+ read(slug, load, lookup) {
90
+ const key = keyOf(slug, lookup);
91
+ if (key === null) return load();
92
+ return memory.read(key, '', load, { keep: (value) => value !== null });
93
+ },
94
+ };
95
+ }
96
+
97
+ export interface TenantSlugs<R extends TenantSlugRecord = TenantSlugRecord> extends TenantSlugResolver<R> {
98
+ /**
99
+ * The tenant `slug` names, kept: from memory when resolved since the last
100
+ * change, else through the port. Shares its key and slot with `remember`:
101
+ * for a given slug a host uses one or the other, never both, or each would
102
+ * be answered with what the other kept.
103
+ */
104
+ resolve(slug: string, lookup?: TenantSlugLookup): Promise<R | null>;
105
+ /**
106
+ * Keep a host's own reading of a slug in the same memory (a host that reads
107
+ * more than the port does). Same key and slot as `resolve`: use one or the
108
+ * other for a given slug.
109
+ */
110
+ remember: KeptSlugs['read'];
111
+ }
112
+
113
+ /** The port, resolved through the memory. */
114
+ export function createTenantSlugs<R extends TenantSlugRecord>(config: {
115
+ port: TenantSlugPort<R>;
116
+ memory: KeptMemory;
117
+ }): TenantSlugs<R> {
118
+ const resolver = createSlugResolver(config.port);
119
+ const kept = createKeptSlugs(config.memory);
120
+ return {
121
+ load: resolver.load,
122
+ resolve: (slug, lookup) => kept.read(slug, () => resolver.load(slug, lookup), lookup),
123
+ remember: kept.read,
124
+ };
125
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The kept memory's startup validation: every option is required (but the
3
+ * database), and a missing or bad one throws naming `memory.<key>`.
4
+ */
5
+ import { TenantConfigError } from '../validate';
6
+ import type { KeptMemoryOptions } from './memory';
7
+
8
+ const CHANNEL = /^[a-z_][a-z0-9_]*$/u;
9
+
10
+ function requireFunction(value: unknown, key: string): void {
11
+ if (value === undefined || value === null) throw new TenantConfigError(key, 'is required and missing');
12
+ if (typeof value !== 'function') throw new TenantConfigError(key, 'must be a function');
13
+ }
14
+
15
+ function requireCount(value: unknown, key: string): void {
16
+ if (value === undefined || value === null) throw new TenantConfigError(key, 'is required and missing');
17
+ if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {
18
+ throw new TenantConfigError(key, 'must be a positive integer');
19
+ }
20
+ }
21
+
22
+ function requireChannel(channel: unknown): void {
23
+ if (channel === undefined || channel === null) throw new TenantConfigError('memory.channel', 'is required and missing');
24
+ if (typeof channel !== 'string' || !CHANNEL.test(channel)) {
25
+ throw new TenantConfigError('memory.channel', 'must be a lower-case identifier (/^[a-z_][a-z0-9_]*$/)');
26
+ }
27
+ }
28
+
29
+ /** Validate the memory's options. Throws {@link TenantConfigError} naming `memory.<key>`. */
30
+ export function validateKeptMemoryOptions(options: unknown): asserts options is KeptMemoryOptions {
31
+ if (options === undefined || options === null) throw new TenantConfigError('memory', 'is required and missing');
32
+ if (typeof options !== 'object' || Array.isArray(options)) throw new TenantConfigError('memory', 'must be an object');
33
+ const bag = options as Record<string, unknown>;
34
+ requireChannel(bag.channel);
35
+ requireFunction(bag.listen, 'memory.listen');
36
+ requireFunction(bag.onError, 'memory.onError');
37
+ for (const key of ['backstopMs', 'retryMs', 'maxScopes', 'maxSlots'] as const) requireCount(bag[key], `memory.${key}`);
38
+ if (bag.database !== undefined) requireFunction(bag.database, 'memory.database');
39
+ }
@@ -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;
package/src/tree/index.ts CHANGED
@@ -41,6 +41,13 @@ export {
41
41
  * never writes outside the caller's.
42
42
  */
43
43
  export interface TenantTree<Tx = unknown> {
44
+ /**
45
+ * The tenant's own node, validated, or null when the tree knows no such
46
+ * tenant. One port call. Optional on the type (added in a minor: a host
47
+ * typing a `TenantTree` of its own keeps compiling); `createTenantTree`
48
+ * always provides it.
49
+ */
50
+ nodeOf?(id: string, tx?: Tx): Promise<TenantTreeNode | null>;
44
51
  /** The tenant directly above `id`, or null for a root. One port call. */
45
52
  parentOf(id: string, tx?: Tx): Promise<string | null>;
46
53
  /** The root of `id`'s tree (`id` itself for a root). One port call. */
@@ -86,6 +93,14 @@ function checked(id: string, nodes: readonly TenantTreeNode[]): TenantTreeNode[]
86
93
 
87
94
  export function createTenantTree<Tx = unknown>(port: TenantTreePort<Tx>): TenantTree<Tx> {
88
95
  return {
96
+ async nodeOf(id, tx) {
97
+ assertSegment(id);
98
+ const node = await port.treeNode(id, tx);
99
+ if (node === null) return null;
100
+ validateNode(node);
101
+ return node;
102
+ },
103
+
89
104
  async parentOf(id, tx) {
90
105
  return (await nodeOf(port, id, tx)).node.parentId;
91
106
  },
package/src/validate.ts CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  type TenantIds,
13
13
  } from './config';
14
14
  import { TENANT_PORT_METHODS, TENANT_TREE_PORT_METHODS, type TenantPort, type TenantTreePort } from './port';
15
+ import { TENANT_SLUG_PORT_METHODS } from './slugs/port';
15
16
 
16
17
  /** Thrown at startup when the config is missing a piece or carries a bad one. */
17
18
  export class TenantConfigError extends Error {
@@ -221,3 +222,26 @@ export function validateTreePort(value: unknown): asserts value is TenantTreePor
221
222
  }
222
223
  }
223
224
  }
225
+
226
+ /** A member that must be present and a function, named by its dotted key. */
227
+ function requireMethod(bag: Bag, method: string, key: string): void {
228
+ if (bag[method] === undefined || bag[method] === null) {
229
+ throw new TenantConfigError(key, 'is required and missing');
230
+ }
231
+ if (typeof bag[method] !== 'function') throw new TenantConfigError(key, 'must be a function');
232
+ }
233
+
234
+ /**
235
+ * Slug resolution, when the host opts in: the slug port (both members) and a
236
+ * kept memory (`createKeptMemory`, validated when it was made). Left out
237
+ * (`undefined`), there is nothing to check.
238
+ */
239
+ export function validateSlugs(value: unknown): void {
240
+ if (value === null || !isBag(value)) {
241
+ throw new TenantConfigError('slugs', 'must be the slug config object ({ port, memory }), or be left out');
242
+ }
243
+ const port = requireBag(value.port, 'slugs.port');
244
+ for (const method of TENANT_SLUG_PORT_METHODS) requireMethod(port, method, `slugs.port.${method}`);
245
+ const memory = requireBag(value.memory, 'slugs.memory');
246
+ requireMethod(memory, 'read', 'slugs.memory.read');
247
+ }