@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
package/ADOPTING.md
CHANGED
|
@@ -110,7 +110,143 @@ 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
|
-
|
|
113
|
+
is not answered here: kept slugs go through the slug port (below).
|
|
114
|
+
|
|
115
|
+
### The tenant tree (opt-in)
|
|
116
|
+
|
|
117
|
+
A tenant may sit under another (ownership only, any depth: a company above its
|
|
118
|
+
units, a unit above its venues). **The tree is optional.** A host with no tree
|
|
119
|
+
passes no `tree` and gets no `tenant.tree` (`createApiTenant` leaves the key
|
|
120
|
+
out); a host written for a release before the tree boots unchanged, since none
|
|
121
|
+
of the tree's methods is on the tenant port. A host that wants it passes its
|
|
122
|
+
own port as `tree`, and then all four members are required and checked at
|
|
123
|
+
startup (`TenantConfigError`, key `tree.<method>`):
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
const tree: TenantTreePort<Tx> = {
|
|
127
|
+
treeNode: (id, tx) => …, // on tx when given: { id, parentId, path } | null — one read
|
|
128
|
+
treeAncestors: (id, tx) => …, // on tx when given: the node and every node above it — one read
|
|
129
|
+
treeDescendants: (id, tx) => …, // on tx when given: the node and every node below it — one read
|
|
130
|
+
moveSubtree: (move, tx) => …, // a planned move ON tx — lock, then ONE rewrite; rows written
|
|
131
|
+
};
|
|
132
|
+
const tenant = createApiTenant({ ...config, port, tree });
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Store three columns on your tenant row: the parent's id (NULL for a standalone
|
|
136
|
+
tenant), the **materialized path** and, if you want one, your own unit code.
|
|
137
|
+
The package computes and validates every path; you store it and apply what it
|
|
138
|
+
plans.
|
|
139
|
+
|
|
140
|
+
- **The path** is `/<root id>/…/<own id>/`; a standalone tenant's is
|
|
141
|
+
`/<own id>/`, so backfilling an existing table makes every row a root.
|
|
142
|
+
Ids must not contain `/`.
|
|
143
|
+
- **`treeAncestors(id)`**: ONE read of the rows whose ids are the segments of
|
|
144
|
+
the tenant's own path (a primary-key read; nothing recurses).
|
|
145
|
+
- **`treeDescendants(id)`**: ONE read of the rows whose path starts with the
|
|
146
|
+
tenant's own, served by an index on the path. With a byte-ordered collation
|
|
147
|
+
(Postgres `COLLATE "C"`) the prefix is exactly the range
|
|
148
|
+
`path >= p AND path < p-minus-its-last-"/" || '0'`.
|
|
149
|
+
- **`moveSubtree(move, tx)`**, on the caller's transaction:
|
|
150
|
+
1. **Lock** every row of the subtree AND the new parent `FOR UPDATE`, in ONE
|
|
151
|
+
global order that never changes (by id). Two crossing moves (A under B
|
|
152
|
+
while B goes under A) then wait on each other instead of deadlocking.
|
|
153
|
+
2. **Rewrite** in ONE statement: replace the prefix `move.fromPath` with
|
|
154
|
+
`move.toPath` on every row under it and re-point the row `move.id` at
|
|
155
|
+
`move.parentId`, ONLY while that row's path is still `fromPath` and the
|
|
156
|
+
parent's is still `parentPath`. Answer the rows written; 0 tells the
|
|
157
|
+
package the tree moved under its plan, and it refuses the move by name
|
|
158
|
+
(`moved`).
|
|
159
|
+
- **A new unit reads its parent's path `FOR SHARE`** (an insert trigger, or
|
|
160
|
+
your writer). With the move's lock above, an insert under a moving tenant
|
|
161
|
+
either waits for the move and takes the moved path, or commits first and the
|
|
162
|
+
move's rewrite (a later statement) moves it too. Without both locks a unit
|
|
163
|
+
can keep a stale prefix, and a stale prefix names the wrong ancestors.
|
|
164
|
+
- **Hold the row to its path** in the database too: a path that names the row
|
|
165
|
+
once and last, and is `/<own id>/` exactly when there is no parent, so no
|
|
166
|
+
writer can store a cycle. Such a check does not hold the path's PREFIX to
|
|
167
|
+
the parent's path; only the port's writes keep that true, so write the tree
|
|
168
|
+
through them.
|
|
169
|
+
|
|
170
|
+
`tenant.tree` answers `parentOf`, `rootOf`, `ancestorsOf`, `descendantsOf` (one
|
|
171
|
+
port call each, at any depth; each takes your transaction optionally) and
|
|
172
|
+
`move(id, parentId, tx)`, which runs its reads and its write in your
|
|
173
|
+
transaction (required) and refuses a cycle (`TenantTreeError`, code `cycle`)
|
|
174
|
+
before anything is written.
|
|
175
|
+
|
|
176
|
+
A grant across a tree is your authorization's business, not the package's.
|
|
177
|
+
Keep it distinguishable from a grant on the parent tenant itself: a scope that
|
|
178
|
+
names "the tenants below X" must never be the same string as X's own. And
|
|
179
|
+
wherever you gather the holders of grants by scope, gather the WHOLE chain
|
|
180
|
+
above a tenant, not only its parent.
|
|
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.
|
|
114
250
|
|
|
115
251
|
### The schema and the migration
|
|
116
252
|
|
package/README.md
CHANGED
|
@@ -15,6 +15,12 @@ This first release ships the **contract** every later behaviour extends:
|
|
|
15
15
|
`bySlug`, `byId(id, tx?)`, `setStatusIf(id, from, to, tx)`,
|
|
16
16
|
`clearProfile(tx, id)`, `timeZone(id)`. Its writes run on the caller's
|
|
17
17
|
transaction;
|
|
18
|
+
- the **tenant tree**, OPT-IN: a tenant under a parent, any depth, on a
|
|
19
|
+
materialized path the package computes and validates, through a `tree` port
|
|
20
|
+
of its own (`treeNode`, `treeAncestors`, `treeDescendants`,
|
|
21
|
+
`moveSubtree(move, tx)`); `parentOf`, `rootOf`, `ancestorsOf`, `descendantsOf`
|
|
22
|
+
(one port call each) and a subtree `move` that refuses a cycle. A host that
|
|
23
|
+
passes no `tree` gets no `tenant.tree`;
|
|
18
24
|
- `createApiTenant` and `createWebTenant`, which validate all of it at startup
|
|
19
25
|
and keep a deep-frozen copy of the data;
|
|
20
26
|
- the package's own tables, `tenant_closings` and `tenant_data_exports`, as a
|
|
@@ -27,8 +33,8 @@ in later releases on top of the same config. How to adopt it: [ADOPTING.md](./AD
|
|
|
27
33
|
|
|
28
34
|
| Import | What | Needs |
|
|
29
35
|
|---|---|---|
|
|
30
|
-
| `@12-apps/tenant` | config types, `TenantPort`, `TenantConfigError`, the validators | nothing |
|
|
31
|
-
| `@12-apps/tenant/server` | `createApiTenant` | 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 |
|
|
32
38
|
| `@12-apps/tenant/hono` | `mountTenant(app, tenant)` | `hono` |
|
|
33
39
|
| `@12-apps/tenant/react` | `createWebTenant` | nothing yet |
|
|
34
40
|
| `@12-apps/tenant/manifest` | the wiring manifest (`db`) | `@12-apps/wiring` (types) |
|
|
@@ -48,8 +54,8 @@ in later releases on top of the same config. How to adopt it: [ADOPTING.md](./AD
|
|
|
48
54
|
`TenantConfigError` naming the key, at startup.
|
|
49
55
|
- **The tenant row stays the host's.** The package never maps it; its own tables
|
|
50
56
|
are keyed by an opaque `tenant_id` with no foreign key. `bySlug` resolves the
|
|
51
|
-
tenant's CURRENT slug only; former slugs
|
|
52
|
-
|
|
57
|
+
tenant's CURRENT slug only; former (kept) slugs go through the slug port,
|
|
58
|
+
`TenantSlugPort`, which the host implements over its own tables.
|
|
53
59
|
|
|
54
60
|
## Tables
|
|
55
61
|
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -20,6 +20,48 @@ export {
|
|
|
20
20
|
type TenantRefusalCodes,
|
|
21
21
|
type TenantStatusSet,
|
|
22
22
|
} from './config';
|
|
23
|
-
export {
|
|
24
|
-
|
|
23
|
+
export {
|
|
24
|
+
TENANT_PORT_METHODS,
|
|
25
|
+
TENANT_TREE_PORT_METHODS,
|
|
26
|
+
type TenantPort,
|
|
27
|
+
type TenantRecord,
|
|
28
|
+
type TenantTreeMove,
|
|
29
|
+
type TenantTreeNode,
|
|
30
|
+
} from './port';
|
|
31
|
+
export {
|
|
32
|
+
TenantTreeError,
|
|
33
|
+
childPath,
|
|
34
|
+
createTenantTree,
|
|
35
|
+
depthOf,
|
|
36
|
+
isWithin,
|
|
37
|
+
parsePath,
|
|
38
|
+
rootPath,
|
|
39
|
+
validateNode,
|
|
40
|
+
type TenantTree,
|
|
41
|
+
type TenantTreeErrorCode,
|
|
42
|
+
type TenantTreePort,
|
|
43
|
+
} from './tree';
|
|
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';
|
|
25
67
|
export type { DeepReadonly, TenantReadings, TenantRefusalKind } from './core';
|
package/src/port.ts
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
* The tenant row, its slugs and its domains stay the host's. The package never
|
|
5
5
|
* maps them (Prisma refuses two models on one table, and a shared partial has
|
|
6
6
|
* no foreign key into a host table), so it asks the host through these five
|
|
7
|
-
* functions instead. Every one is required.
|
|
7
|
+
* functions instead. Every one is required. (The tenant tree has a port of its
|
|
8
|
+
* own, `TenantTreePort`, optional as a whole.)
|
|
8
9
|
*
|
|
9
10
|
* TRANSACTIONS. Every lifecycle step changes the tenant row and the package's
|
|
10
11
|
* own rows together: a close flips the status, recounts the blockers (one
|
|
@@ -25,6 +26,44 @@ export interface TenantRecord<S extends string = string> {
|
|
|
25
26
|
status: S;
|
|
26
27
|
}
|
|
27
28
|
|
|
29
|
+
/**
|
|
30
|
+
* One tenant's place in the tenant tree, as the host stores it.
|
|
31
|
+
*
|
|
32
|
+
* The tree is ownership only (a company above its units, a unit above its
|
|
33
|
+
* venues), of any depth. `path` is the materialized path the package computes
|
|
34
|
+
* (`/<root id>/…/<own id>/`), so no tree read recurses.
|
|
35
|
+
*/
|
|
36
|
+
export interface TenantTreeNode {
|
|
37
|
+
/** The host's tenant id. */
|
|
38
|
+
id: string;
|
|
39
|
+
/** The tenant directly above, or null for a standalone tenant (a root). */
|
|
40
|
+
parentId: string | null;
|
|
41
|
+
/** `/<root id>/…/<own id>/`; a root's is `/<own id>/`. */
|
|
42
|
+
path: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* A subtree move, planned and validated by the package. The host first locks
|
|
47
|
+
* the subtree and the new parent (ADOPTING.md, "The tenant tree (opt-in)"), then
|
|
48
|
+
* rewrites in ONE statement: every path starting with `fromPath` has that
|
|
49
|
+
* prefix replaced by `toPath`, and the row `id` is re-pointed at `parentId`.
|
|
50
|
+
*/
|
|
51
|
+
export interface TenantTreeMove {
|
|
52
|
+
/** The tenant that moves, everything below it moving with it. */
|
|
53
|
+
id: string;
|
|
54
|
+
/** Its new parent, or null to make it a root. */
|
|
55
|
+
parentId: string | null;
|
|
56
|
+
/**
|
|
57
|
+
* The new parent's path as the package read it (null with no parent). The
|
|
58
|
+
* host applies the move only while the parent's path still is this.
|
|
59
|
+
*/
|
|
60
|
+
parentPath: string | null;
|
|
61
|
+
/** The moving tenant's path before the move: the prefix replaced. */
|
|
62
|
+
fromPath: string;
|
|
63
|
+
/** Its path after the move: the replacement prefix. */
|
|
64
|
+
toPath: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
28
67
|
/**
|
|
29
68
|
* `Tx` is the host's transaction client. The package never opens one itself:
|
|
30
69
|
* it hands back whatever the host gave it, so the host's own writes and the
|
|
@@ -33,8 +72,9 @@ export interface TenantRecord<S extends string = string> {
|
|
|
33
72
|
export interface TenantPort<S extends string = string, Tx = unknown> {
|
|
34
73
|
/**
|
|
35
74
|
* The tenant whose CURRENT slug is `slug`, or null when none is. A former
|
|
36
|
-
* slug the host still keeps
|
|
37
|
-
*
|
|
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`).
|
|
38
78
|
*/
|
|
39
79
|
bySlug(slug: string): Promise<TenantRecord<S> | null>;
|
|
40
80
|
/**
|
|
@@ -69,3 +109,44 @@ export const TENANT_PORT_METHODS = [
|
|
|
69
109
|
'clearProfile',
|
|
70
110
|
'timeZone',
|
|
71
111
|
] as const satisfies readonly (keyof TenantPort)[];
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The tenant TREE's port: OPTIONAL as a whole, and every member required when
|
|
115
|
+
* it is given (`createApiTenant`'s `tree`). A host with no tree passes none and
|
|
116
|
+
* gets no `tenant.tree`; a host written against a release before the tree
|
|
117
|
+
* boots unchanged. Same transaction rule as the tenant port: the one write
|
|
118
|
+
* takes the caller's `tx`, required; the reads take it optionally.
|
|
119
|
+
*/
|
|
120
|
+
export interface TenantTreePort<Tx = unknown> {
|
|
121
|
+
/**
|
|
122
|
+
* One tenant's node, ONE read. Null when none exists. Read inside
|
|
123
|
+
* `tx` when one is given, so a move's plan sees what its write will.
|
|
124
|
+
*/
|
|
125
|
+
treeNode(id: string, tx?: Tx): Promise<TenantTreeNode | null>;
|
|
126
|
+
/**
|
|
127
|
+
* The tenant and every tenant above it, in ONE read (the ids are
|
|
128
|
+
* the segments of its own path). Any order; empty when the tenant is unknown.
|
|
129
|
+
*/
|
|
130
|
+
treeAncestors(id: string, tx?: Tx): Promise<TenantTreeNode[]>;
|
|
131
|
+
/**
|
|
132
|
+
* The tenant and every tenant below it at any depth, in ONE
|
|
133
|
+
* indexed prefix read on the path. Any order; empty when the tenant is unknown.
|
|
134
|
+
*/
|
|
135
|
+
treeDescendants(id: string, tx?: Tx): Promise<TenantTreeNode[]>;
|
|
136
|
+
/**
|
|
137
|
+
* Apply a planned move inside the caller's transaction (required: a write
|
|
138
|
+
* never runs outside it): lock the subtree and the new parent, then ONE
|
|
139
|
+
* rewrite statement (ADOPTING.md, "The tenant tree (opt-in)"). Answers the rows
|
|
140
|
+
* written. 0 means the tree changed since the plan (the subtree is no longer
|
|
141
|
+
* at `fromPath`, or the parent no longer at `parentPath`): nothing written.
|
|
142
|
+
*/
|
|
143
|
+
moveSubtree(move: TenantTreeMove, tx: Tx): Promise<number>;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The tree port's members, in a fixed order: what startup validation checks when a tree is given. */
|
|
147
|
+
export const TENANT_TREE_PORT_METHODS = [
|
|
148
|
+
'treeNode',
|
|
149
|
+
'treeAncestors',
|
|
150
|
+
'treeDescendants',
|
|
151
|
+
'moveSubtree',
|
|
152
|
+
] as const satisfies readonly (keyof TenantTreePort)[];
|
package/src/server/index.ts
CHANGED
|
@@ -14,10 +14,40 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import type { TenantCoreConfig } from '../config';
|
|
16
16
|
import { createReadings, frozenCopy, type DeepReadonly, type TenantReadings } from '../core';
|
|
17
|
-
import type { TenantPort, TenantRecord } from '../port';
|
|
18
|
-
import {
|
|
17
|
+
import type { TenantPort, TenantRecord, TenantTreePort } from '../port';
|
|
18
|
+
import { createTenantSlugs, type KeptMemory, type TenantSlugPort, type TenantSlugRecord, type TenantSlugs } from '../slugs';
|
|
19
|
+
import { createTenantTree, type TenantTree } from '../tree';
|
|
20
|
+
import { validateCoreConfig, validatePort, validateSlugs, validateTreePort } from '../validate';
|
|
19
21
|
|
|
20
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
|
+
}
|
|
21
51
|
|
|
22
52
|
/** A framework-neutral route: the Hono adapter mounts each one as given. */
|
|
23
53
|
export interface TenantRoute {
|
|
@@ -27,18 +57,41 @@ export interface TenantRoute {
|
|
|
27
57
|
handler(request: Request): Promise<Response>;
|
|
28
58
|
}
|
|
29
59
|
|
|
30
|
-
/**
|
|
31
|
-
|
|
60
|
+
/**
|
|
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.
|
|
64
|
+
*/
|
|
65
|
+
export interface TenantServerConfig<
|
|
66
|
+
S extends string = string,
|
|
67
|
+
Tx = unknown,
|
|
68
|
+
R extends TenantSlugRecord = TenantSlugRecord,
|
|
69
|
+
>
|
|
32
70
|
extends TenantCoreConfig<S> {
|
|
33
71
|
/** The host's tenant row, reached only through this port. */
|
|
34
72
|
port: TenantPort<S, Tx>;
|
|
73
|
+
/**
|
|
74
|
+
* The tenant tree's port (a tenant under a parent, any depth). Left out, the
|
|
75
|
+
* host has no tree and `tenant.tree` is absent.
|
|
76
|
+
*/
|
|
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>;
|
|
35
83
|
}
|
|
36
84
|
|
|
37
|
-
export interface ApiTenant<S extends string = string, Tx = unknown
|
|
85
|
+
export interface ApiTenant<S extends string = string, Tx = unknown, R extends TenantSlugRecord = TenantSlugRecord>
|
|
86
|
+
extends TenantReadings<S> {
|
|
38
87
|
/** The validated config's data parts (statuses, ids, copy), deep-frozen copies. */
|
|
39
88
|
config: DeepReadonly<TenantCoreConfig<S>>;
|
|
40
89
|
/** The host's tenant port, as given. */
|
|
41
90
|
port: TenantPort<S, Tx>;
|
|
91
|
+
/** The tenant tree, read and moved through `config.tree`; absent when none was given. */
|
|
92
|
+
tree?: TenantTree<Tx>;
|
|
93
|
+
/** Slug resolution through `config.slugs`; absent when none was given. */
|
|
94
|
+
slugs?: TenantSlugs<R>;
|
|
42
95
|
/** The package's routes, in mount order. None yet: the lifecycle slice adds them. */
|
|
43
96
|
routes: readonly TenantRoute[];
|
|
44
97
|
/** The tenant, read through the port, on `tx` when given. */
|
|
@@ -52,11 +105,15 @@ export interface ApiTenant<S extends string = string, Tx = unknown> extends Tena
|
|
|
52
105
|
setStatusIf(id: string, from: S, to: S, tx: Tx): Promise<boolean>;
|
|
53
106
|
}
|
|
54
107
|
|
|
55
|
-
export function createApiTenant<S extends string, Tx = unknown>(
|
|
56
|
-
config: TenantServerConfig<S, Tx>,
|
|
57
|
-
): 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> {
|
|
58
111
|
validateCoreConfig(config);
|
|
59
112
|
validatePort((config as { port?: unknown }).port);
|
|
113
|
+
const treePort = (config as { tree?: unknown }).tree;
|
|
114
|
+
if (treePort !== undefined) validateTreePort(treePort);
|
|
115
|
+
const slugs = (config as { slugs?: unknown }).slugs;
|
|
116
|
+
if (slugs !== undefined) validateSlugs(slugs);
|
|
60
117
|
const data = frozenCopy({ statuses: config.statuses, ids: config.ids, copy: config.copy });
|
|
61
118
|
const known = new Set<string>(data.statuses.all);
|
|
62
119
|
const { port } = config;
|
|
@@ -64,6 +121,8 @@ export function createApiTenant<S extends string, Tx = unknown>(
|
|
|
64
121
|
...createReadings(data),
|
|
65
122
|
config: data,
|
|
66
123
|
port,
|
|
124
|
+
...(config.tree === undefined ? {} : { tree: createTenantTree(config.tree) }),
|
|
125
|
+
...(config.slugs === undefined ? {} : { slugs: createTenantSlugs(config.slugs) }),
|
|
67
126
|
routes: Object.freeze([]),
|
|
68
127
|
byId: (id, tx) => port.byId(id, tx),
|
|
69
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
|
+
}
|