@12-apps/tenant 1.1.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 CHANGED
@@ -110,7 +110,7 @@ const port: TenantPort<Status, Tx> = {
110
110
  - **`byId` reads on `tx` when one is given**, so a refusal inside the
111
111
  transaction sees the status the transaction sees.
112
112
  - **`bySlug` resolves the tenant's current slug only.** A former slug you keep
113
- for redirects is not answered here.
113
+ is not answered here: kept slugs go through the slug port (below).
114
114
 
115
115
  ### The tenant tree (opt-in)
116
116
 
@@ -179,6 +179,75 @@ names "the tenants below X" must never be the same string as X's own. And
179
179
  wherever you gather the holders of grants by scope, gather the WHOLE chain
180
180
  above a tenant, not only its parent.
181
181
 
182
+ ### Slug resolution (opt-in)
183
+
184
+ A tenant keeps every slug it ever held, so an old link still names it, and a
185
+ lookup is answered from process memory once resolved, until the database says
186
+ the tenant changed. **Optional**, like the tree: a host that passes no `slugs`
187
+ boots unchanged and gets no `tenant.slugs`. Nothing is added to the tenant
188
+ port. The package owns no slug table and no trigger.
189
+
190
+ ```ts
191
+ import { createKeptMemory, createApiTenant } from '@12-apps/tenant/server';
192
+
193
+ // ONE memory per channel per process, made at module load.
194
+ const memory = createKeptMemory({
195
+ channel: 'tenant_slug_changed', // the channel your triggers NOTIFY on
196
+ listen: (channel, handlers) => …, // your LISTEN; resolves once connected
197
+ onError: ({ phase, channel, error }) => …, // log it in your words: 'start' | 'dropped'
198
+ backstopMs: 10 * 60 * 1000, // trust a kept value this long with no notification
199
+ retryMs: 30 * 1000, // pause before retrying a listener that failed to start
200
+ maxScopes: 5_000, // addresses kept, oldest dropped first
201
+ maxSlots: 256, // slots per address (slug resolution uses one)
202
+ database: () => …, // optional: the database the listener hears
203
+ });
204
+ const slugs: TenantSlugPort<YourRecord> = {
205
+ current: (slug, parent) => …, // ONE read: the tenant whose current slug is `slug`
206
+ former: (slug, parent) => …, // ONE read: the tenant that held `slug` before, with its CURRENT slug
207
+ };
208
+ const tenant = createApiTenant({ ...config, port, slugs: { port: slugs, memory } });
209
+ await tenant.slugs?.resolve('north-wing'); // a root
210
+ await tenant.slugs?.resolve('radiology', { parentPath: '/t1/' }); // a unit under t1
211
+ ```
212
+
213
+ Every number is required (`TenantConfigError`, key `memory.<key>`); the port's
214
+ two members and the memory are checked at startup (`slugs.port.current`,
215
+ `slugs.port.former`, `slugs.memory.read`). A host that is not on
216
+ `createApiTenant` yet uses the same pieces standalone: `createSlugResolver(port)`
217
+ (the two reads), `createKeptSlugs(memory)` (the keeping) and
218
+ `createTenantSlugs({ port, memory })` (both).
219
+
220
+ - **The statement budget.** A kept address costs no statement; a miss on a
221
+ current slug costs one (`current`); a former or unknown slug costs two
222
+ (`current`, then `former`). An unknown slug is never kept, so a stream of
223
+ made-up slugs cannot grow the memory.
224
+ - **Keys.** A root lookup keys on the slug alone, as every address did before
225
+ the tree. A unit's slug is unique within its parent: the lookup names the
226
+ parent's path, the port receives `{ id, path }` of the parent, and the key is
227
+ the path plus the slug. A bad path throws `TenantTreeError`; a slug holding
228
+ `/` is loaded every time and never kept.
229
+ - **Your triggers.** On every write that changes what a lookup answers (the
230
+ slug, and every column your record carries), and on every write to your
231
+ former-slug table, `pg_notify(<channel>, '*')` AFTER the write commits. Every
232
+ process drops every kept address: these writes are rare. A payload naming
233
+ one address drops only that one (the root's slug, or the unit's path plus
234
+ slug).
235
+ - **Before any lookup under a parent**, the triggers must also fire on a change
236
+ of the tenant's parent or path: a moved unit answers at its new parent only.
237
+ - **The memory's rules.** Nothing is kept while the listener is down (a
238
+ disconnect and a reconnect each drop everything, since a notification sent
239
+ meanwhile is lost); a load a notification overtakes is not kept; one load
240
+ answers a burst of the same lookup; a read through a transaction (`via`)
241
+ never starts the `LISTEN`, which on a single connection would wait for it.
242
+ Make the database client before the first lookup when `listen` depends on it.
243
+ - **`resolve` or `remember`, never both for one slug.** They share one key and
244
+ one slot: `resolve` keeps the port's record, `remember` keeps your own
245
+ reading of the same address, so mixing them on a slug answers each with
246
+ what the other kept. Pick one per slug (a host whose reading carries more
247
+ than the port's record uses `remember` throughout).
248
+ - **One memory per channel per process**, shared by everything that reads
249
+ under that channel. Two memories on one channel each open a listener.
250
+
182
251
  ### The schema and the migration
183
252
 
184
253
  - Copy the partial into your schema folder with
package/README.md CHANGED
@@ -33,8 +33,8 @@ in later releases on top of the same config. How to adopt it: [ADOPTING.md](./AD
33
33
 
34
34
  | Import | What | Needs |
35
35
  |---|---|---|
36
- | `@12-apps/tenant` | config types, `TenantPort`, `TenantConfigError`, the validators, the tree (`createTenantTree`, the path helpers, `TenantTreeError`) | nothing |
37
- | `@12-apps/tenant/server` | `createApiTenant` (with `tenant.tree` when a `tree` port is given) | nothing |
36
+ | `@12-apps/tenant` | config types, `TenantPort`, `TenantConfigError`, the validators, the tree (`createTenantTree`, the path helpers, `TenantTreeError`), slug resolution (`createKeptMemory`, `createSlugResolver`, `createKeptSlugs`, `createTenantSlugs`, `TenantSlugPort`) | nothing |
37
+ | `@12-apps/tenant/server` | `createApiTenant` (with `tenant.tree` when a `tree` port is given, `tenant.slugs` when `slugs` is), and the slug resolution exports | nothing |
38
38
  | `@12-apps/tenant/hono` | `mountTenant(app, tenant)` | `hono` |
39
39
  | `@12-apps/tenant/react` | `createWebTenant` | nothing yet |
40
40
  | `@12-apps/tenant/manifest` | the wiring manifest (`db`) | `@12-apps/wiring` (types) |
@@ -54,8 +54,8 @@ in later releases on top of the same config. How to adopt it: [ADOPTING.md](./AD
54
54
  `TenantConfigError` naming the key, at startup.
55
55
  - **The tenant row stays the host's.** The package never maps it; its own tables
56
56
  are keyed by an opaque `tenant_id` with no foreign key. `bySlug` resolves the
57
- tenant's CURRENT slug only; former slugs a host keeps are the address
58
- behaviour's, through a port of its own.
57
+ tenant's CURRENT slug only; former (kept) slugs go through the slug port,
58
+ `TenantSlugPort`, which the host implements over its own tables.
59
59
 
60
60
  ## Tables
61
61
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/tenant",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "sideEffects": false,
package/src/index.ts CHANGED
@@ -41,5 +41,27 @@ export {
41
41
  type TenantTreeErrorCode,
42
42
  type TenantTreePort,
43
43
  } from './tree';
44
- export { TenantConfigError, validateCoreConfig, validatePort, validateTreePort } from './validate';
44
+ export {
45
+ EVERY_SCOPE,
46
+ TENANT_SLUG_PORT_METHODS,
47
+ createKeptMemory,
48
+ createKeptSlugs,
49
+ createSlugResolver,
50
+ createTenantSlugs,
51
+ validateKeptMemoryOptions,
52
+ type KeptMemory,
53
+ type KeptMemoryErrorEvent,
54
+ type KeptMemoryOptions,
55
+ type KeptReadOptions,
56
+ type KeptSlugs,
57
+ type TenantChangeHandlers,
58
+ type TenantChangeListener,
59
+ type TenantSlugLookup,
60
+ type TenantSlugParent,
61
+ type TenantSlugPort,
62
+ type TenantSlugRecord,
63
+ type TenantSlugResolver,
64
+ type TenantSlugs,
65
+ } from './slugs';
66
+ export { TenantConfigError, validateCoreConfig, validatePort, validateSlugs, validateTreePort } from './validate';
45
67
  export type { DeepReadonly, TenantReadings, TenantRefusalKind } from './core';
package/src/port.ts CHANGED
@@ -72,8 +72,9 @@ export interface TenantTreeMove {
72
72
  export interface TenantPort<S extends string = string, Tx = unknown> {
73
73
  /**
74
74
  * The tenant whose CURRENT slug is `slug`, or null when none is. A former
75
- * slug the host still keeps for redirects does not resolve here: kept slugs
76
- * are the address slice's, through a port of their own.
75
+ * slug the host still keeps does not resolve here: kept slugs, tree-aware
76
+ * lookups and the resolution cache go through `TenantSlugPort`
77
+ * (`createApiTenant({ slugs })`, or `createTenantSlugs`).
77
78
  */
78
79
  bySlug(slug: string): Promise<TenantRecord<S> | null>;
79
80
  /**
@@ -15,10 +15,39 @@
15
15
  import type { TenantCoreConfig } from '../config';
16
16
  import { createReadings, frozenCopy, type DeepReadonly, type TenantReadings } from '../core';
17
17
  import type { TenantPort, TenantRecord, TenantTreePort } from '../port';
18
+ import { createTenantSlugs, type KeptMemory, type TenantSlugPort, type TenantSlugRecord, type TenantSlugs } from '../slugs';
18
19
  import { createTenantTree, type TenantTree } from '../tree';
19
- import { validateCoreConfig, validatePort, validateTreePort } from '../validate';
20
+ import { validateCoreConfig, validatePort, validateSlugs, validateTreePort } from '../validate';
20
21
 
21
22
  export { TenantConfigError } from '../validate';
23
+ export {
24
+ EVERY_SCOPE,
25
+ TENANT_SLUG_PORT_METHODS,
26
+ createKeptMemory,
27
+ createKeptSlugs,
28
+ createSlugResolver,
29
+ createTenantSlugs,
30
+ type KeptMemory,
31
+ type KeptMemoryErrorEvent,
32
+ type KeptMemoryOptions,
33
+ type KeptReadOptions,
34
+ type KeptSlugs,
35
+ type TenantChangeHandlers,
36
+ type TenantChangeListener,
37
+ type TenantSlugLookup,
38
+ type TenantSlugParent,
39
+ type TenantSlugPort,
40
+ type TenantSlugRecord,
41
+ type TenantSlugResolver,
42
+ type TenantSlugs,
43
+ } from '../slugs';
44
+
45
+ /** Slug resolution's config: the host's slug port and its kept memory. */
46
+ export interface TenantSlugsConfig<R extends TenantSlugRecord = TenantSlugRecord> {
47
+ port: TenantSlugPort<R>;
48
+ /** One memory per channel per process (`createKeptMemory`). */
49
+ memory: KeptMemory;
50
+ }
22
51
 
23
52
  /** A framework-neutral route: the Hono adapter mounts each one as given. */
24
53
  export interface TenantRoute {
@@ -29,10 +58,15 @@ export interface TenantRoute {
29
58
  }
30
59
 
31
60
  /**
32
- * Everything `createApiTenant` needs. Nothing is optional but the tenant tree,
33
- * an opt-in feature: give `tree` and every one of its members is required.
61
+ * Everything `createApiTenant` needs. Nothing is optional but the tenant tree and
62
+ * slug resolution, opt-in features: give `tree` or `slugs` and every one of
63
+ * its members is required.
34
64
  */
35
- export interface TenantServerConfig<S extends string = string, Tx = unknown>
65
+ export interface TenantServerConfig<
66
+ S extends string = string,
67
+ Tx = unknown,
68
+ R extends TenantSlugRecord = TenantSlugRecord,
69
+ >
36
70
  extends TenantCoreConfig<S> {
37
71
  /** The host's tenant row, reached only through this port. */
38
72
  port: TenantPort<S, Tx>;
@@ -41,15 +75,23 @@ export interface TenantServerConfig<S extends string = string, Tx = unknown>
41
75
  * host has no tree and `tenant.tree` is absent.
42
76
  */
43
77
  tree?: TenantTreePort<Tx>;
78
+ /**
79
+ * Slug resolution (kept slugs, the resolution cache). Left out, the host
80
+ * resolves slugs itself and `tenant.slugs` is absent.
81
+ */
82
+ slugs?: TenantSlugsConfig<R>;
44
83
  }
45
84
 
46
- export interface ApiTenant<S extends string = string, Tx = unknown> extends TenantReadings<S> {
85
+ export interface ApiTenant<S extends string = string, Tx = unknown, R extends TenantSlugRecord = TenantSlugRecord>
86
+ extends TenantReadings<S> {
47
87
  /** The validated config's data parts (statuses, ids, copy), deep-frozen copies. */
48
88
  config: DeepReadonly<TenantCoreConfig<S>>;
49
89
  /** The host's tenant port, as given. */
50
90
  port: TenantPort<S, Tx>;
51
91
  /** The tenant tree, read and moved through `config.tree`; absent when none was given. */
52
92
  tree?: TenantTree<Tx>;
93
+ /** Slug resolution through `config.slugs`; absent when none was given. */
94
+ slugs?: TenantSlugs<R>;
53
95
  /** The package's routes, in mount order. None yet: the lifecycle slice adds them. */
54
96
  routes: readonly TenantRoute[];
55
97
  /** The tenant, read through the port, on `tx` when given. */
@@ -63,13 +105,15 @@ export interface ApiTenant<S extends string = string, Tx = unknown> extends Tena
63
105
  setStatusIf(id: string, from: S, to: S, tx: Tx): Promise<boolean>;
64
106
  }
65
107
 
66
- export function createApiTenant<S extends string, Tx = unknown>(
67
- config: TenantServerConfig<S, Tx>,
68
- ): ApiTenant<S, Tx> {
108
+ export function createApiTenant<S extends string, Tx = unknown, R extends TenantSlugRecord = TenantSlugRecord>(
109
+ config: TenantServerConfig<S, Tx, R>,
110
+ ): ApiTenant<S, Tx, R> {
69
111
  validateCoreConfig(config);
70
112
  validatePort((config as { port?: unknown }).port);
71
113
  const treePort = (config as { tree?: unknown }).tree;
72
114
  if (treePort !== undefined) validateTreePort(treePort);
115
+ const slugs = (config as { slugs?: unknown }).slugs;
116
+ if (slugs !== undefined) validateSlugs(slugs);
73
117
  const data = frozenCopy({ statuses: config.statuses, ids: config.ids, copy: config.copy });
74
118
  const known = new Set<string>(data.statuses.all);
75
119
  const { port } = config;
@@ -78,6 +122,7 @@ export function createApiTenant<S extends string, Tx = unknown>(
78
122
  config: data,
79
123
  port,
80
124
  ...(config.tree === undefined ? {} : { tree: createTenantTree(config.tree) }),
125
+ ...(config.slugs === undefined ? {} : { slugs: createTenantSlugs(config.slugs) }),
81
126
  routes: Object.freeze([]),
82
127
  byId: (id, tx) => port.byId(id, tx),
83
128
  setStatusIf: (id, from, to, tx) => {
@@ -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/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
+ }