@12-apps/tenant 1.2.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.
- package/ADOPTING.md +112 -4
- package/README.md +7 -5
- package/package.json +1 -1
- package/src/config.ts +6 -2
- package/src/hono/index.ts +51 -0
- package/src/index.ts +20 -0
- package/src/lifecycle/close.ts +191 -0
- package/src/lifecycle/context.ts +126 -0
- package/src/lifecycle/gates.ts +160 -0
- package/src/lifecycle/index.ts +127 -0
- package/src/lifecycle/pure.ts +56 -0
- package/src/lifecycle/refusal.ts +69 -0
- package/src/lifecycle/sweep.ts +139 -0
- package/src/lifecycle/types.ts +255 -0
- package/src/lifecycle/validate.ts +174 -0
- package/src/port.ts +14 -0
- package/src/server/index.ts +15 -1
- package/src/tree/index.ts +15 -0
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The lifecycle's config and its answers: closing a tenant, reopening it, the
|
|
3
|
+
* sweep that reminds and purges, and the hooks through which the host does
|
|
4
|
+
* whatever its own domain needs on each step.
|
|
5
|
+
*
|
|
6
|
+
* OPT-IN, like the tree and slug resolution: `createApiTenant({ lifecycle })`
|
|
7
|
+
* (or `createTenantLifecycle`). A host that wires it MUST return `name` from
|
|
8
|
+
* its tenant port's `bySlug` and `byId` (ADOPTING.md, "Lifecycle").
|
|
9
|
+
*/
|
|
10
|
+
import type { TenantRecord, TenantTreeNode } from '../port';
|
|
11
|
+
|
|
12
|
+
/** Who closes: a member of the tenant (from `active` only, name typed), or the platform (any `closableFrom`, no name). */
|
|
13
|
+
export type TenantCloseEntry = 'member' | 'platform';
|
|
14
|
+
|
|
15
|
+
/** One kind of blocker the host names, and the path (under the tenant) that resolves it. */
|
|
16
|
+
export interface TenantBlockerKind {
|
|
17
|
+
kind: string;
|
|
18
|
+
path: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** What the host's blocker read answers: how many of a kind still block the close. */
|
|
22
|
+
export interface TenantBlockerCount {
|
|
23
|
+
kind: string;
|
|
24
|
+
count: number;
|
|
25
|
+
/** Whatever the host wants the blocker sentence to read (an amount, a date). Passed through. */
|
|
26
|
+
detail?: Readonly<Record<string, string | number>>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** A blocker as the package answers it: the count with its resolve path. */
|
|
30
|
+
export interface TenantBlocker extends TenantBlockerCount {
|
|
31
|
+
path: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** One `tenant_closings` row, as the package reads it. */
|
|
35
|
+
export interface TenantClosingRow {
|
|
36
|
+
tenantId: string;
|
|
37
|
+
requestedAt: Date;
|
|
38
|
+
requestedById: string | null;
|
|
39
|
+
reason: string;
|
|
40
|
+
priorStatus: string | null;
|
|
41
|
+
purgeAt: Date;
|
|
42
|
+
remindedWeekAt: Date | null;
|
|
43
|
+
remindedDayAt: Date | null;
|
|
44
|
+
purgedAt: Date | null;
|
|
45
|
+
afterCloseDoneAt: Date | null;
|
|
46
|
+
afterCloseFailedAt: Date | null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** What a close writes into a fresh row. */
|
|
50
|
+
export type TenantClosingCreate = Pick<
|
|
51
|
+
TenantClosingRow,
|
|
52
|
+
'tenantId' | 'requestedAt' | 'requestedById' | 'reason' | 'priorStatus' | 'purgeAt'
|
|
53
|
+
>;
|
|
54
|
+
|
|
55
|
+
/** The stamps the package writes, each only while still null. */
|
|
56
|
+
export type TenantClosingStamp = 'remindedWeekAt' | 'remindedDayAt' | 'purgedAt' | 'afterCloseDoneAt' | 'afterCloseFailedAt';
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The slice of the synced Prisma model (`tenantClosing`) the package uses, on
|
|
60
|
+
* the host's client or transaction. A host passes its delegate, or an adapter
|
|
61
|
+
* with these five members.
|
|
62
|
+
*/
|
|
63
|
+
export interface TenantClosingTable {
|
|
64
|
+
findUnique(args: { where: { tenantId: string } }): Promise<TenantClosingRow | null>;
|
|
65
|
+
/**
|
|
66
|
+
* A page of the rows not purged yet, oldest purge first, after the keyset
|
|
67
|
+
* `after` (the last row of the previous page) when given.
|
|
68
|
+
*/
|
|
69
|
+
findMany(args: {
|
|
70
|
+
where: {
|
|
71
|
+
purgedAt: null;
|
|
72
|
+
OR?: [{ purgeAt: { gt: Date } }, { purgeAt: Date; tenantId: { gt: string } }];
|
|
73
|
+
};
|
|
74
|
+
orderBy: [{ purgeAt: 'asc' }, { tenantId: 'asc' }];
|
|
75
|
+
take: number;
|
|
76
|
+
}): Promise<TenantClosingRow[]>;
|
|
77
|
+
create(args: { data: TenantClosingCreate }): Promise<unknown>;
|
|
78
|
+
/** A reopen deletes by tenant; the sweep deletes a stale row only while it is the one it read (`requestedAt`, not purged). */
|
|
79
|
+
deleteMany(args: { where: { tenantId: string; requestedAt?: Date; purgedAt?: null } }): Promise<{ count: number }>;
|
|
80
|
+
updateMany(args: {
|
|
81
|
+
where: { tenantId: string } & Partial<Record<TenantClosingStamp, null>>;
|
|
82
|
+
data: Partial<Record<TenantClosingStamp, Date>>;
|
|
83
|
+
}): Promise<{ count: number }>;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A stamp the package wrote, handed to the mirror so an old table moves with it. */
|
|
87
|
+
export type TenantClosingEvent =
|
|
88
|
+
| { kind: 'reminded'; which: 'week' | 'day'; at: Date }
|
|
89
|
+
| { kind: 'afterClose'; ok: boolean; at: Date }
|
|
90
|
+
| { kind: 'purged'; at: Date };
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* OPT-IN expand-and-contract: a host moving an older closing table onto
|
|
94
|
+
* `tenant_closings` mirrors every package write into it, IN THE SAME
|
|
95
|
+
* TRANSACTION as the package's own write, until its contract release drops it.
|
|
96
|
+
*/
|
|
97
|
+
export interface TenantClosingMirror<Tx> {
|
|
98
|
+
/** A close replaced the tenant's row (`row` is what was written). */
|
|
99
|
+
replaced(tx: Tx, row: TenantClosingCreate): Promise<void>;
|
|
100
|
+
/** A stamp landed; write it where still null, as the package did. */
|
|
101
|
+
event(tx: Tx, tenantId: string, event: TenantClosingEvent): Promise<void>;
|
|
102
|
+
/**
|
|
103
|
+
* A reopen, or the sweep's stale-row drop, deleted the tenant's row.
|
|
104
|
+
* `requestedAt` is the deleted row's own: delete the older table's row only
|
|
105
|
+
* while it is that same close (a re-close the older release wrote since
|
|
106
|
+
* stays). Absent when the package read no row (a reopen of a close only the
|
|
107
|
+
* older table holds): delete by tenant.
|
|
108
|
+
*/
|
|
109
|
+
deleted(tx: Tx, tenantId: string, requestedAt?: Date): Promise<void>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The facts of an audited act. The host writes its own `after` shape from them. */
|
|
113
|
+
export type TenantAuditEvent =
|
|
114
|
+
| { act: 'closeScheduled'; tenantId: string; by: TenantCloseEntry; reason: string; purgeAt: Date; priorStatus: string }
|
|
115
|
+
| { act: 'closeReopened'; tenantId: string; by: TenantCloseEntry; purgeAt: Date | null; restored: string }
|
|
116
|
+
| { act: 'afterCloseFailed'; tenantId: string; error: string };
|
|
117
|
+
|
|
118
|
+
/** What every notice the lifecycle raises carries. */
|
|
119
|
+
export interface TenantNoticePayload {
|
|
120
|
+
tenantId: string;
|
|
121
|
+
name: string;
|
|
122
|
+
slug: string;
|
|
123
|
+
/** ISO instant the tenant's data is purged. */
|
|
124
|
+
purgeAt: string;
|
|
125
|
+
/** Who scheduled the close, on the scheduled notice; null on the others. */
|
|
126
|
+
by: TenantCloseEntry | null;
|
|
127
|
+
/** The close's reason, on a platform close's scheduled notice only (the owner reads why). */
|
|
128
|
+
reason: string | null;
|
|
129
|
+
/**
|
|
130
|
+
* The status a reopen restored, on the reopened notice; absent or null on
|
|
131
|
+
* the others. When it is not the active status (a tenant the platform
|
|
132
|
+
* closed while suspended), the notice reads the lifecycle extension's
|
|
133
|
+
* restored sentences, never "it is live again".
|
|
134
|
+
*/
|
|
135
|
+
restored?: string | null;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The sentences only a lifecycle host writes, on top of the base pack: the
|
|
140
|
+
* platform close's notice (with its reason, and without one), and the reopen
|
|
141
|
+
* notice of a tenant restored to a status other than active (it is not live
|
|
142
|
+
* again: a suspended tenant stays suspended).
|
|
143
|
+
*/
|
|
144
|
+
export interface TenantLifecycleCopyPack {
|
|
145
|
+
readonly noticePlatformScheduledTitle: (name: string) => string;
|
|
146
|
+
readonly noticePlatformScheduledBody: (name: string, purgeDay: string, reason: string) => string;
|
|
147
|
+
/** The platform close's body when the notice carries no reason. */
|
|
148
|
+
readonly noticePlatformScheduledBodyNoReason: (name: string, purgeDay: string) => string;
|
|
149
|
+
readonly noticeReopenedRestoredTitle: (name: string) => string;
|
|
150
|
+
readonly noticeReopenedRestoredBody: (name: string) => string;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The keys of the lifecycle's copy extension, in a fixed order. */
|
|
154
|
+
export const TENANT_LIFECYCLE_COPY_KEYS = [
|
|
155
|
+
'noticePlatformScheduledTitle',
|
|
156
|
+
'noticePlatformScheduledBody',
|
|
157
|
+
'noticePlatformScheduledBodyNoReason',
|
|
158
|
+
'noticeReopenedRestoredTitle',
|
|
159
|
+
'noticeReopenedRestoredBody',
|
|
160
|
+
] as const satisfies readonly (keyof TenantLifecycleCopyPack)[];
|
|
161
|
+
|
|
162
|
+
export interface TenantLifecycleConfig<S extends string = string, Tx = unknown> {
|
|
163
|
+
/** Days a closing tenant may reopen before its purge. Integer > 0. */
|
|
164
|
+
graceDays: number;
|
|
165
|
+
/** Days before the purge each reminder goes out. Integers, 0 < day < week < graceDays. */
|
|
166
|
+
reminderDays: { week: number; day: number };
|
|
167
|
+
/** The reason's floor, in characters after trimming. Integer > 0. */
|
|
168
|
+
minReasonLength: number;
|
|
169
|
+
/** The locale the typed-name check folds case in (an Intl tag, `pt-BR`). */
|
|
170
|
+
nameLocale: string;
|
|
171
|
+
/** Closing rows a sweep reads per pass. Integer > 0. */
|
|
172
|
+
sweepBatch: number;
|
|
173
|
+
/** The platform close's sentences, per locale: every tag of `copy.locales`. */
|
|
174
|
+
copy: { locales: Readonly<Record<string, TenantLifecycleCopyPack>> };
|
|
175
|
+
/** The host's transactions, and the package's table on a transaction or on the client. */
|
|
176
|
+
db: {
|
|
177
|
+
transaction<T>(run: (tx: Tx) => Promise<T>): Promise<T>;
|
|
178
|
+
table(tx?: Tx): TenantClosingTable | Promise<TenantClosingTable>;
|
|
179
|
+
};
|
|
180
|
+
/** The host's own blockers: their kinds, and one read that counts them (on `tx` inside the close). */
|
|
181
|
+
blockers: {
|
|
182
|
+
kinds: readonly TenantBlockerKind[];
|
|
183
|
+
read(tenantId: string, at: { now: Date; tx?: Tx }): Promise<readonly TenantBlockerCount[]>;
|
|
184
|
+
};
|
|
185
|
+
/**
|
|
186
|
+
* The blocker the package adds itself for open descendants (a tenant with
|
|
187
|
+
* units not closing or closed cannot close). REQUIRED when the tenant was
|
|
188
|
+
* built with a `tree`, refused without one; its kind is not among `blockers.kinds`.
|
|
189
|
+
*/
|
|
190
|
+
openDescendants?: TenantBlockerKind;
|
|
191
|
+
/** The host's dangerous-act check (a PIN, say). Throws to refuse; resolves to admit. */
|
|
192
|
+
confirmDangerousAct(request: Request, at: { tenantId: string; by: TenantCloseEntry }): Promise<void>;
|
|
193
|
+
/** After a close commits (a billing cancel, say). Throws = failed: stamped, audited, retried by the sweep. */
|
|
194
|
+
afterClose(at: { tenant: TenantRecord<S>; node: TenantTreeNode | null; now: Date }): Promise<void>;
|
|
195
|
+
/** Drop whatever the host caches about the tenant. */
|
|
196
|
+
invalidate(tenantId: string): Promise<void>;
|
|
197
|
+
/** Raise a notice; true when RECORDED (a reminder is stamped only then). */
|
|
198
|
+
notify(typeId: string, payload: TenantNoticePayload): Promise<boolean>;
|
|
199
|
+
/** The purge is due: run the host's. `skipped` stamps nothing; `purged` and `already` stamp `purgedAt`. */
|
|
200
|
+
onPurgeDue(tenantId: string, at: { now: Date }): Promise<'purged' | 'already' | 'skipped'>;
|
|
201
|
+
/** Write one audit line ON `tx`. `action` is `ids.audit[event.act]`. */
|
|
202
|
+
audit(tx: Tx, action: string, event: TenantAuditEvent): Promise<void>;
|
|
203
|
+
/** The current request's locale, for refusals (null: the default pack). */
|
|
204
|
+
locale(): string | null;
|
|
205
|
+
/** A hook failed after the act committed; the act stands. */
|
|
206
|
+
onError(error: unknown, at: { act: string; tenantId: string }): void;
|
|
207
|
+
/** The expand-and-contract mirror, when the host is moving an older table. */
|
|
208
|
+
mirror?: TenantClosingMirror<Tx>;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** A tenant's closing state, as an API answers it. */
|
|
212
|
+
export interface TenantClosingState<S extends string = string> {
|
|
213
|
+
status: S;
|
|
214
|
+
/** ISO, while closing or closed. */
|
|
215
|
+
requestedAt: string | null;
|
|
216
|
+
/** ISO, while closing or closed. */
|
|
217
|
+
purgeAt: string | null;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export interface TenantSweepResult {
|
|
221
|
+
reminded: { week: number; day: number };
|
|
222
|
+
/** Tenants the host's purge ran for on this pass. */
|
|
223
|
+
purged: number;
|
|
224
|
+
/** After-close hooks retried and gone through on this pass. */
|
|
225
|
+
afterCloseRetried: number;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export interface TenantLifecycle<S extends string = string> {
|
|
229
|
+
/** Close the tenant: the dangerous act, its checks, one transaction, then the hooks. */
|
|
230
|
+
close(input: {
|
|
231
|
+
tenant: TenantRecord<S>;
|
|
232
|
+
by: TenantCloseEntry;
|
|
233
|
+
reason: string;
|
|
234
|
+
/** The tenant's name as the member typed it; ignored for the platform. */
|
|
235
|
+
typedName?: string;
|
|
236
|
+
/** The member's user id; null for the platform (its audit line says who). */
|
|
237
|
+
actorUserId: string | null;
|
|
238
|
+
request: Request;
|
|
239
|
+
now?: Date;
|
|
240
|
+
}): Promise<TenantClosingState<S>>;
|
|
241
|
+
/** Reopen a closing tenant, restoring the status its close started from. */
|
|
242
|
+
reopen(input: { tenant: TenantRecord<S>; by: TenantCloseEntry }): Promise<TenantClosingState<S>>;
|
|
243
|
+
/** The tenant's closing state: no read unless it is closing or closed. */
|
|
244
|
+
state(tenant: { id: string; status: S }): Promise<TenantClosingState<S>>;
|
|
245
|
+
/** What still blocks the close, each with its resolve path. */
|
|
246
|
+
blockers(tenantId: string, now?: Date): Promise<TenantBlocker[]>;
|
|
247
|
+
/** Remind, retry the after-close hook, and purge what is due, at `now`. */
|
|
248
|
+
sweep(now: Date): Promise<TenantSweepResult>;
|
|
249
|
+
/** The title and body of a lifecycle notice, in `locale`, its day formatted in `timeZone`. */
|
|
250
|
+
noticeWords(
|
|
251
|
+
typeId: string,
|
|
252
|
+
payload: TenantNoticePayload,
|
|
253
|
+
at: { locale: string | null; timeZone: string },
|
|
254
|
+
): { title: string; body: string };
|
|
255
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Startup validation of the lifecycle and the gates, read as `unknown` like
|
|
3
|
+
* the rest of the config: every missing or bad key is named
|
|
4
|
+
* (`TenantConfigError`), and nothing falls back to a value of the host's.
|
|
5
|
+
*/
|
|
6
|
+
import { TenantConfigError } from '../validate';
|
|
7
|
+
import { TENANT_LIFECYCLE_COPY_KEYS } from './types';
|
|
8
|
+
|
|
9
|
+
type Bag = Record<string, unknown>;
|
|
10
|
+
|
|
11
|
+
function isBag(value: unknown): value is Bag {
|
|
12
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function present(value: unknown, key: string): void {
|
|
16
|
+
if (value === undefined || value === null) throw new TenantConfigError(key, 'is required and missing');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function bagAt(value: unknown, key: string): Bag {
|
|
20
|
+
present(value, key);
|
|
21
|
+
if (!isBag(value)) throw new TenantConfigError(key, 'must be an object');
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function textAt(value: unknown, key: string): string {
|
|
26
|
+
present(value, key);
|
|
27
|
+
if (typeof value !== 'string' || value.trim() === '') throw new TenantConfigError(key, 'must be a non-empty string');
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function fnAt(bag: Bag, member: string, key: string): void {
|
|
32
|
+
present(bag[member], key);
|
|
33
|
+
if (typeof bag[member] !== 'function') throw new TenantConfigError(key, 'must be a function');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function positiveInt(value: unknown, key: string): number {
|
|
37
|
+
present(value, key);
|
|
38
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {
|
|
39
|
+
throw new TenantConfigError(key, 'must be a whole number above 0');
|
|
40
|
+
}
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function listAt(value: unknown, key: string): unknown[] {
|
|
45
|
+
present(value, key);
|
|
46
|
+
if (!Array.isArray(value)) throw new TenantConfigError(key, 'must be an array');
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function canonicalLocale(value: unknown, key: string): void {
|
|
51
|
+
const tag = textAt(value, key);
|
|
52
|
+
let canonical: string | undefined;
|
|
53
|
+
try {
|
|
54
|
+
canonical = Intl.getCanonicalLocales(tag)[0];
|
|
55
|
+
} catch {
|
|
56
|
+
canonical = undefined;
|
|
57
|
+
}
|
|
58
|
+
if (canonical !== tag) throw new TenantConfigError(key, `must be a canonical locale tag ("${tag}" is not)`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function blockerKind(value: unknown, key: string): string {
|
|
62
|
+
const bag = bagAt(value, key);
|
|
63
|
+
textAt(bag.path, `${key}.path`);
|
|
64
|
+
return textAt(bag.kind, `${key}.kind`);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function validateNumbers(lifecycle: Bag): void {
|
|
68
|
+
const grace = positiveInt(lifecycle.graceDays, 'lifecycle.graceDays');
|
|
69
|
+
const days = bagAt(lifecycle.reminderDays, 'lifecycle.reminderDays');
|
|
70
|
+
const week = positiveInt(days.week, 'lifecycle.reminderDays.week');
|
|
71
|
+
const day = positiveInt(days.day, 'lifecycle.reminderDays.day');
|
|
72
|
+
if (week >= grace) throw new TenantConfigError('lifecycle.reminderDays.week', 'must be fewer days than graceDays');
|
|
73
|
+
if (day >= week) throw new TenantConfigError('lifecycle.reminderDays.day', 'must be fewer days than reminderDays.week');
|
|
74
|
+
positiveInt(lifecycle.minReasonLength, 'lifecycle.minReasonLength');
|
|
75
|
+
canonicalLocale(lifecycle.nameLocale, 'lifecycle.nameLocale');
|
|
76
|
+
positiveInt(lifecycle.sweepBatch, 'lifecycle.sweepBatch');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The lifecycle's copy extension: every key, for every tag of the base copy. */
|
|
80
|
+
export function validateLifecycleCopy(value: unknown, tags: readonly string[]): void {
|
|
81
|
+
const locales = bagAt(bagAt(value, 'lifecycle.copy').locales, 'lifecycle.copy.locales');
|
|
82
|
+
const packs = new Map(tags.map((tag) => [tag, bagAt(locales[tag], `lifecycle.copy.locales.${tag}`)]));
|
|
83
|
+
const sentences = tags.flatMap((tag) => TENANT_LIFECYCLE_COPY_KEYS.map((copyKey) => [tag, copyKey] as const));
|
|
84
|
+
for (const [tag, copyKey] of sentences) {
|
|
85
|
+
const key = `lifecycle.copy.locales.${tag}.${copyKey}`;
|
|
86
|
+
const sentence = packs.get(tag)?.[copyKey];
|
|
87
|
+
present(sentence, key);
|
|
88
|
+
if (typeof sentence !== 'function') throw new TenantConfigError(key, 'must be a function that writes the whole sentence');
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function validateBlockers(lifecycle: Bag, hasTree: boolean): void {
|
|
93
|
+
const blockers = bagAt(lifecycle.blockers, 'lifecycle.blockers');
|
|
94
|
+
const seen = new Set<string>();
|
|
95
|
+
listAt(blockers.kinds, 'lifecycle.blockers.kinds').forEach((entry, index) => {
|
|
96
|
+
const kind = blockerKind(entry, `lifecycle.blockers.kinds[${index}]`);
|
|
97
|
+
if (seen.has(kind)) throw new TenantConfigError(`lifecycle.blockers.kinds[${index}].kind`, `repeats "${kind}"`);
|
|
98
|
+
seen.add(kind);
|
|
99
|
+
});
|
|
100
|
+
fnAt(blockers, 'read', 'lifecycle.blockers.read');
|
|
101
|
+
if (!hasTree) {
|
|
102
|
+
if (lifecycle.openDescendants !== undefined) {
|
|
103
|
+
throw new TenantConfigError('lifecycle.openDescendants', 'is given with no tree: only a tenant built with `tree` has descendants');
|
|
104
|
+
}
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
const kind = blockerKind(lifecycle.openDescendants, 'lifecycle.openDescendants');
|
|
108
|
+
if (seen.has(kind)) {
|
|
109
|
+
throw new TenantConfigError('lifecycle.openDescendants.kind', `repeats "${kind}", already one of blockers.kinds`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const HOOKS = ['confirmDangerousAct', 'afterClose', 'invalidate', 'notify', 'onPurgeDue', 'audit', 'locale', 'onError'] as const;
|
|
114
|
+
|
|
115
|
+
const MIRROR = ['replaced', 'event', 'deleted'] as const;
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The lifecycle's config. `tags` are the base copy's locales (each needs the
|
|
119
|
+
* lifecycle's sentences too); `hasTree` says whether the tenant has a tree.
|
|
120
|
+
*/
|
|
121
|
+
export function validateLifecycle(value: unknown, tags: readonly string[], hasTree: boolean): void {
|
|
122
|
+
if (value === null || !isBag(value)) {
|
|
123
|
+
throw new TenantConfigError('lifecycle', 'must be the lifecycle config object, or be left out');
|
|
124
|
+
}
|
|
125
|
+
validateNumbers(value);
|
|
126
|
+
validateLifecycleCopy(value.copy, tags);
|
|
127
|
+
const db = bagAt(value.db, 'lifecycle.db');
|
|
128
|
+
fnAt(db, 'transaction', 'lifecycle.db.transaction');
|
|
129
|
+
fnAt(db, 'table', 'lifecycle.db.table');
|
|
130
|
+
validateBlockers(value, hasTree);
|
|
131
|
+
for (const hook of HOOKS) fnAt(value, hook, `lifecycle.${hook}`);
|
|
132
|
+
if (value.mirror === undefined) return;
|
|
133
|
+
const mirror = bagAt(value.mirror, 'lifecycle.mirror');
|
|
134
|
+
for (const member of MIRROR) fnAt(mirror, member, `lifecycle.mirror.${member}`);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function validateAdmin(value: unknown): void {
|
|
138
|
+
const admin = bagAt(value, 'gates.admin');
|
|
139
|
+
const prefix = textAt(admin.prefix, 'gates.admin.prefix');
|
|
140
|
+
if (!prefix.startsWith('/') || prefix.endsWith('/')) {
|
|
141
|
+
throw new TenantConfigError('gates.admin.prefix', 'must start with "/" and not end with one');
|
|
142
|
+
}
|
|
143
|
+
listAt(admin.closingWrites, 'gates.admin.closingWrites').forEach((path, index) => {
|
|
144
|
+
const write = textAt(path, `gates.admin.closingWrites[${index}]`);
|
|
145
|
+
if (!write.startsWith('/')) throw new TenantConfigError(`gates.admin.closingWrites[${index}]`, 'must start with "/"');
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function validateFamily(value: unknown, key: string): void {
|
|
150
|
+
const family = bagAt(value, key);
|
|
151
|
+
present(family.readsToo, `${key}.readsToo`);
|
|
152
|
+
if (typeof family.readsToo !== 'boolean') throw new TenantConfigError(`${key}.readsToo`, 'must be true or false');
|
|
153
|
+
for (const list of ['fixedWords', 'slugAfter'] as const) {
|
|
154
|
+
listAt(family[list], `${key}.${list}`).forEach((word, index) => textAt(word, `${key}.${list}[${index}]`));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function validatePublic(value: unknown): void {
|
|
159
|
+
const pub = bagAt(value, 'gates.public');
|
|
160
|
+
const prefix = textAt(pub.prefix, 'gates.public.prefix');
|
|
161
|
+
if (!prefix.startsWith('/') || prefix.endsWith('/')) {
|
|
162
|
+
throw new TenantConfigError('gates.public.prefix', 'must start with "/" and not end with one');
|
|
163
|
+
}
|
|
164
|
+
const families = bagAt(pub.families, 'gates.public.families');
|
|
165
|
+
for (const [name, family] of Object.entries(families)) validateFamily(family, `gates.public.families.${name}`);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The gates' config. */
|
|
169
|
+
export function validateGates(value: unknown): void {
|
|
170
|
+
const gates = bagAt(value, 'gates');
|
|
171
|
+
validateAdmin(gates.admin);
|
|
172
|
+
validatePublic(gates.public);
|
|
173
|
+
for (const hook of ['lookup', 'holdsClose', 'locale'] as const) fnAt(gates, hook, `gates.${hook}`);
|
|
174
|
+
}
|
package/src/port.ts
CHANGED
|
@@ -24,6 +24,14 @@ export interface TenantRecord<S extends string = string> {
|
|
|
24
24
|
slug: string;
|
|
25
25
|
/** The tenant row's current status: any value of the host's status set. */
|
|
26
26
|
status: S;
|
|
27
|
+
/**
|
|
28
|
+
* The tenant's display name. Optional for the port as a whole, REQUIRED of
|
|
29
|
+
* `bySlug` and `byId` once the host wires the lifecycle
|
|
30
|
+
* (`createApiTenant({ lifecycle })`): its notices and the member close's
|
|
31
|
+
* typed-name check read it, and a record without it there is refused as a
|
|
32
|
+
* programming error (`TenantConfigError` on `port.bySlug`/`port.byId`).
|
|
33
|
+
*/
|
|
34
|
+
name?: string;
|
|
27
35
|
}
|
|
28
36
|
|
|
29
37
|
/**
|
|
@@ -40,6 +48,12 @@ export interface TenantTreeNode {
|
|
|
40
48
|
parentId: string | null;
|
|
41
49
|
/** `/<root id>/…/<own id>/`; a root's is `/<own id>/`. */
|
|
42
50
|
path: string;
|
|
51
|
+
/**
|
|
52
|
+
* The tenant's status, when the host's read carries it. Optional for the
|
|
53
|
+
* tree alone; REQUIRED of `treeDescendants` once the lifecycle is wired, so
|
|
54
|
+
* the open-descendants blocker costs that one read and no read per unit.
|
|
55
|
+
*/
|
|
56
|
+
status?: string;
|
|
43
57
|
}
|
|
44
58
|
|
|
45
59
|
/**
|
package/src/server/index.ts
CHANGED
|
@@ -18,6 +18,9 @@ import type { TenantPort, TenantRecord, TenantTreePort } from '../port';
|
|
|
18
18
|
import { createTenantSlugs, type KeptMemory, type TenantSlugPort, type TenantSlugRecord, type TenantSlugs } from '../slugs';
|
|
19
19
|
import { createTenantTree, type TenantTree } from '../tree';
|
|
20
20
|
import { validateCoreConfig, validatePort, validateSlugs, validateTreePort } from '../validate';
|
|
21
|
+
import { createTenantLifecycle, type TenantLifecycle, type TenantLifecycleConfig } from '../lifecycle';
|
|
22
|
+
|
|
23
|
+
export * from '../lifecycle';
|
|
21
24
|
|
|
22
25
|
export { TenantConfigError } from '../validate';
|
|
23
26
|
export {
|
|
@@ -80,6 +83,12 @@ export interface TenantServerConfig<
|
|
|
80
83
|
* resolves slugs itself and `tenant.slugs` is absent.
|
|
81
84
|
*/
|
|
82
85
|
slugs?: TenantSlugsConfig<R>;
|
|
86
|
+
/**
|
|
87
|
+
* The closing lifecycle (close, reopen, the sweep). Left out, the host runs
|
|
88
|
+
* its own and `tenant.lifecycle` is absent. Given, the port's `bySlug` and
|
|
89
|
+
* `byId` MUST return each tenant's `name`.
|
|
90
|
+
*/
|
|
91
|
+
lifecycle?: TenantLifecycleConfig<S, Tx>;
|
|
83
92
|
}
|
|
84
93
|
|
|
85
94
|
export interface ApiTenant<S extends string = string, Tx = unknown, R extends TenantSlugRecord = TenantSlugRecord>
|
|
@@ -92,6 +101,8 @@ export interface ApiTenant<S extends string = string, Tx = unknown, R extends Te
|
|
|
92
101
|
tree?: TenantTree<Tx>;
|
|
93
102
|
/** Slug resolution through `config.slugs`; absent when none was given. */
|
|
94
103
|
slugs?: TenantSlugs<R>;
|
|
104
|
+
/** The closing lifecycle through `config.lifecycle`; absent when none was given. */
|
|
105
|
+
lifecycle?: TenantLifecycle<S>;
|
|
95
106
|
/** The package's routes, in mount order. None yet: the lifecycle slice adds them. */
|
|
96
107
|
routes: readonly TenantRoute[];
|
|
97
108
|
/** The tenant, read through the port, on `tx` when given. */
|
|
@@ -117,7 +128,7 @@ export function createApiTenant<S extends string, Tx = unknown, R extends Tenant
|
|
|
117
128
|
const data = frozenCopy({ statuses: config.statuses, ids: config.ids, copy: config.copy });
|
|
118
129
|
const known = new Set<string>(data.statuses.all);
|
|
119
130
|
const { port } = config;
|
|
120
|
-
|
|
131
|
+
const tenant: ApiTenant<S, Tx, R> = {
|
|
121
132
|
...createReadings(data),
|
|
122
133
|
config: data,
|
|
123
134
|
port,
|
|
@@ -136,4 +147,7 @@ export function createApiTenant<S extends string, Tx = unknown, R extends Tenant
|
|
|
136
147
|
return port.setStatusIf(id, from, to, tx);
|
|
137
148
|
},
|
|
138
149
|
};
|
|
150
|
+
if (config.lifecycle === undefined) return tenant;
|
|
151
|
+
// Validated by the factory, before anything is returned.
|
|
152
|
+
return { ...tenant, lifecycle: createTenantLifecycle(tenant, config.lifecycle) };
|
|
139
153
|
}
|
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
|
},
|