@12-apps/tenant 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ADOPTING.md CHANGED
@@ -7,8 +7,8 @@ Two halves, one factory each, one config object each. Nothing is optional.
7
7
  import { createApiTenant } from '@12-apps/tenant/server';
8
8
  import { mountTenant } from '@12-apps/tenant/hono';
9
9
 
10
- const tenant = createApiTenant({ statuses, ids, copy, port });
11
- mountTenant(app, tenant); // mounts nothing yet: the routes arrive with the lifecycle
10
+ const tenant = createApiTenant({ statuses, ids, copy, port }); // + tree, slugs, lifecycle: each opt-in
11
+ mountTenant(app, tenant); // mounts nothing: hosts keep their own route modules
12
12
 
13
13
  // frontend
14
14
  import { createWebTenant } from '@12-apps/tenant/react';
@@ -92,8 +92,8 @@ const copy = { locales: { 'pt-BR': ptBR, 'en-US': enUS }, defaultLocale: 'pt-BR'
92
92
 
93
93
  ```ts
94
94
  const port: TenantPort<Status, Tx> = {
95
- bySlug: (slug) => …, // the CURRENT slug only: { id, slug, status } | null
96
- byId: (id, tx) => …, // on tx when given: { id, slug, status } | null
95
+ bySlug: (slug) => …, // the CURRENT slug only: { id, slug, status, name? } | null
96
+ byId: (id, tx) => …, // on tx when given: { id, slug, status, name? } | null
97
97
  setStatusIf: (id, from, to, tx) => …, // compare-and-set ON tx: true only when the row moved
98
98
  clearProfile: (tx, id) => …, // erase the row's profile, on tx
99
99
  timeZone: (id) => …, // IANA zone
@@ -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,183 @@ 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
+
251
+ ### Lifecycle (opt-in): close, reopen, the sweep, the gates
252
+
253
+ Additive: a host that passes no `lifecycle` boots unchanged and gets no
254
+ `tenant.lifecycle`.
255
+
256
+ ```ts
257
+ const tenant = createApiTenant({
258
+ statuses, ids, copy, port, tree, // tree optional
259
+ lifecycle: {
260
+ graceDays: 30, reminderDays: { week: 7, day: 1 }, // integers, 0 < day < week < graceDays
261
+ minReasonLength: 3, nameLocale: 'pt-BR', sweepBatch: 200,
262
+ copy: { locales: { 'pt-BR': { noticePlatformScheduledTitle, noticePlatformScheduledBody,
263
+ noticePlatformScheduledBodyNoReason, noticeReopenedRestoredTitle, noticeReopenedRestoredBody }, … } },
264
+ db: { transaction: (run) => prisma.$transaction(run), table: (tx) => (tx ?? prisma).tenantClosing },
265
+ blockers: { kinds: [{ kind: 'patients', path: 'ward' }, …], read: (tenantId, { now, tx }) => … },
266
+ openDescendants: { kind: 'units', path: 'units' }, // REQUIRED with `tree`, refused without
267
+ confirmDangerousAct: (request, { tenantId, by }) => …, // throws to refuse (a PIN check)
268
+ afterClose: ({ tenant, node, now }) => …, // throws = failed: stamped, audited, retried by the sweep
269
+ invalidate: (tenantId) => …,
270
+ notify: (typeId, payload) => …, // resolves true only once RECORDED
271
+ onPurgeDue: (tenantId, { now }) => …, // 'purged' | 'already' | 'skipped'
272
+ audit: (tx, action, event) => …, // on tx; action = ids.audit[event.act]
273
+ locale: () => …, onError: (error, { act, tenantId }) => …,
274
+ mirror, // optional: an older table you are moving (below)
275
+ },
276
+ });
277
+ ```
278
+
279
+ - **Your port MUST return `name` from `bySlug` and `byId`** once the lifecycle
280
+ is wired. `TenantRecord.name` stays optional for hosts without it; with it, a
281
+ record that lacks a name is a programming error, thrown as a
282
+ `TenantConfigError` on `port.byId` the first time the lifecycle needs it
283
+ (never a notice with an empty name).
284
+ - **The lifecycle's own sentences are a copy extension**,
285
+ `lifecycle.copy.locales.<tag>`, required for every tag of `copy.locales`
286
+ and validated per key (`lifecycle.copy.locales.pt-BR.noticePlatformScheduledBody`):
287
+ the platform close's title and body (with its reason, and
288
+ `noticePlatformScheduledBodyNoReason` when the notice carries none), and
289
+ `noticeReopenedRestored*`, which a reopen notice reads when it restored a
290
+ status other than active (`payload.restored`): a tenant reopened to
291
+ suspended is not live again, and its notice must not say so.
292
+ The base pack (`TENANT_COPY_SHAPE`) is unchanged. `blocker(kind, count,
293
+ detail?)` takes the blocker's optional `detail` (an amount and a date).
294
+ - **Two entries into one flow.** `close({ by: 'member', typedName, … })`
295
+ starts from `statuses.active` only and checks the typed name in
296
+ `nameLocale`; `close({ by: 'platform', … })` starts from any of
297
+ `statuses.closableFrom`, asks no name, writes `requested_by_id` null (your
298
+ audit line says who) and hands the reason to the scheduled notice
299
+ (`payload.reason`, words from `noticePlatformScheduled*`). Both record
300
+ `prior_status`; `reopen` restores it (or `active` when it is null or not a
301
+ live status).
302
+ - **The order of a close**: `confirmDangerousAct`, the reason, the name, then
303
+ ONE transaction (`setStatusIf`, your blockers read again ON `tx` plus the
304
+ open-descendants count, the row replaced, `mirror.replaced`, `audit`). A
305
+ blocker found there rolls the move back (409 `closingBlocked`, `details:
306
+ { pending }`). After the commit, never inside it: `afterClose` (with the
307
+ tenant's tree node, so a unit can skip its root's billing), `invalidate`,
308
+ `notify`. A hook that throws goes to `onError` and never undoes the close.
309
+ - **Refusals** are `TenantLifecycleRefusal { kind, code, status, details }`,
310
+ `code` from your `ids.refusals`, the message from `copyFor(locale())`. The
311
+ statuses are fixed: 403 closing/readOnly/closed, 409 gone, alreadyClosing,
312
+ notActive, closingBlocked, purged, notClosing, 422 reasonTooShort,
313
+ nameMismatch.
314
+ - **Schedule `tenant.lifecycle.sweep(now)`** on your own job runner (hourly is
315
+ plenty). Per row: skip a tenant no longer closing or closed; retry
316
+ `afterClose` while it has not gone through; once due, `onPurgeDue` and stamp
317
+ `purged_at` on `purged` or `already`; before that, send the reminder due,
318
+ stamped only once `notify` answered true.
319
+ - **Statement budget.** `state()` reads nothing for a live tenant and one row
320
+ for a gone one. `blockers()` and the close add ONE `treeDescendants` read
321
+ when a tree is wired: with the lifecycle, that read MUST return each node's
322
+ `status` (`TenantTreeNode.status`), or the blocker throws a
323
+ `TenantConfigError` on `tree.treeDescendants`. The sweep reads one `byId`
324
+ per row and stamps in a transaction of its own.
325
+ - **Stale rows heal.** A closing row whose tenant is neither closing nor
326
+ closed (reopened by a release that wrote only your older table, say) is
327
+ deleted by the sweep, conditionally on its `requestedAt`, with
328
+ `mirror.deleted`, in one transaction. It takes no slot of `sweepBatch`:
329
+ the sweep pages on (keyset on `purgeAt`, `tenantId`) until `sweepBatch`
330
+ live tenants were swept or no row is left.
331
+ - **Gates**: `createTenantGates(tenant, { admin: { prefix, closingWrites },
332
+ public: { prefix, families }, lookup, holdsClose, locale })` and
333
+ `mountTenantGates(app, gates)` from `@12-apps/tenant/hono`. `lookup` is your
334
+ kept slug lookup (the status rides it: an open tenant pays nothing more); a
335
+ family's `fixedWords` are never looked up; `slugAfter` names words after
336
+ which the next segment is the slug. The middlewares are typed structurally
337
+ (`TenantGateMiddleware`), so they fit whatever Hono version you resolve.
338
+ - **Notice words without the hooks**: `createNoticeWords(tenant, { copy })`
339
+ answers `noticeWords` alone, for a notification registry that renders the
340
+ lifecycle's notices apart from the module that wires its hooks. It
341
+ validates the extension as the lifecycle does, and a locale without one
342
+ reads the default locale's.
343
+ - **`TenantTree.nodeOf` is optional on the type** (added in this minor, so a
344
+ host typing a tree of its own keeps compiling); `createTenantTree` always
345
+ provides it, and the lifecycle reads no node when it is absent.
346
+
347
+ #### Moving an older closing table (expand and contract)
348
+
349
+ Pass `mirror: { replaced, event, deleted }`: each runs on the package's own
350
+ transaction, so the two tables never disagree. `deleted(tx, tenantId, requestedAt?)`
351
+ hands you the deleted row's `requestedAt`: delete your old row only while it
352
+ is that same close, so a re-close your previous release wrote meanwhile
353
+ survives (absent when the package read no row: delete by tenant). Write each stamp where it is
354
+ still null, as the package does. Rows your PREVIOUS release wrote only into
355
+ the old table (during a rolling deploy) are not in `tenant_closings`: before
356
+ each sweep, catch them up with one upsert (`INSERT … SELECT … ON CONFLICT
357
+ (tenant_id) DO UPDATE`), and backfill once with a data-only migration.
358
+
182
359
  ### The schema and the migration
183
360
 
184
361
  - Copy the partial into your schema folder with
package/README.md CHANGED
@@ -26,16 +26,18 @@ This first release ships the **contract** every later behaviour extends:
26
26
  - the package's own tables, `tenant_closings` and `tenant_data_exports`, as a
27
27
  Prisma partial with its own migration.
28
28
 
29
- The lifecycle (close, reopen, the sweep), the purge and the data export arrive
30
- in later releases on top of the same config. How to adopt it: [ADOPTING.md](./ADOPTING.md).
29
+ The closing lifecycle (close and reopen as a dangerous act, the blockers, the
30
+ sweep that reminds and purges, and the admin and public gates) is opt-in:
31
+ `createApiTenant({ lifecycle })` and `createTenantGates`. The purge and the
32
+ data export arrive in later releases on top of the same config. How to adopt it: [ADOPTING.md](./ADOPTING.md).
31
33
 
32
34
  ## Entry points
33
35
 
34
36
  | Import | What | Needs |
35
37
  |---|---|---|
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 |
38
- | `@12-apps/tenant/hono` | `mountTenant(app, tenant)` | `hono` |
38
+ | `@12-apps/tenant` | config types, the lifecycle's pure readings (`isTenantGone`, `sameTenantName`, `purgeAtFor`, `reminderDue`), `TenantPort`, `TenantConfigError`, the validators, the tree (`createTenantTree`, the path helpers, `TenantTreeError`), slug resolution (`createKeptMemory`, `createSlugResolver`, `createKeptSlugs`, `createTenantSlugs`, `TenantSlugPort`) | nothing |
39
+ | `@12-apps/tenant/server` | `createApiTenant` (with `tenant.tree` when a `tree` port is given, `tenant.slugs` when `slugs` is, `tenant.lifecycle` when `lifecycle` is), `createTenantLifecycle`, `createTenantGates`, `TenantLifecycleRefusal`, and the slug resolution exports | nothing |
40
+ | `@12-apps/tenant/hono` | `mountTenant(app, tenant)`, `mountTenantGates(app, gates)`, `tenantAdminGate`, `tenantPublicGate` | `hono` |
39
41
  | `@12-apps/tenant/react` | `createWebTenant` | nothing yet |
40
42
  | `@12-apps/tenant/manifest` | the wiring manifest (`db`) | `@12-apps/wiring` (types) |
41
43
 
@@ -54,8 +56,8 @@ in later releases on top of the same config. How to adopt it: [ADOPTING.md](./AD
54
56
  `TenantConfigError` naming the key, at startup.
55
57
  - **The tenant row stays the host's.** The package never maps it; its own tables
56
58
  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.
59
+ tenant's CURRENT slug only; former (kept) slugs go through the slug port,
60
+ `TenantSlugPort`, which the host implements over its own tables.
59
61
 
60
62
  ## Tables
61
63
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/tenant",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "sideEffects": false,
package/src/config.ts CHANGED
@@ -245,8 +245,12 @@ export interface TenantCopyPack {
245
245
  readonly refusalExportExpired: string;
246
246
  readonly pendingTitle: string;
247
247
  readonly pendingNone: string;
248
- /** One line per kind of blocker; `kind` is one of the host's own blocker kinds. */
249
- readonly blocker: (kind: string, count: number) => string;
248
+ /**
249
+ * One line per kind of blocker; `kind` is one of the host's own blocker
250
+ * kinds. `detail` is whatever the host's blocker read attached to it (an
251
+ * amount and a date, say), passed through as given.
252
+ */
253
+ readonly blocker: (kind: string, count: number, detail?: Readonly<Record<string, string | number>>) => string;
250
254
  /** The shortcut that resolves a blocker of that kind. */
251
255
  readonly shortcut: (kind: string) => string;
252
256
  readonly dataTitle: string;
package/src/hono/index.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import type { Hono } from 'hono';
8
8
 
9
+ import type { GateRefusal, TenantGates } from '../lifecycle';
9
10
  import type { ApiTenant } from '../server';
10
11
 
11
12
  /** Mount every route of `tenant` on `app`, in order. Returns `app`. */
@@ -15,3 +16,53 @@ export function mountTenant<A extends Pick<Hono, 'on'>>(app: A, tenant: Pick<Api
15
16
  }
16
17
  return app;
17
18
  }
19
+
20
+ /**
21
+ * A gate middleware, typed structurally (the request it reads and the `next`
22
+ * it calls), so it fits any Hono version the host resolves the optional peer to.
23
+ */
24
+ export type TenantGateMiddleware = (
25
+ context: { req: { raw: Request } },
26
+ next: () => Promise<void>,
27
+ ) => Promise<Response | undefined>;
28
+
29
+ /** The one member of a Hono app the gate mount calls. */
30
+ export interface TenantGateApp {
31
+ use(path: string, handler: TenantGateMiddleware): unknown;
32
+ }
33
+
34
+ /** A refusal as the response every gate renders: `{ error, code, details: {} }` with its status. */
35
+ function refused(refusal: GateRefusal): Response {
36
+ return Response.json({ error: refusal.message, code: refusal.code, details: {} }, { status: refusal.status });
37
+ }
38
+
39
+ /** The admin gate as a middleware: mount it on `<admin.prefix>/*`. */
40
+ export function tenantAdminGate(gates: Pick<TenantGates, 'adminRefusal'>): TenantGateMiddleware {
41
+ return async (context, next) => {
42
+ const refusal = await gates.adminRefusal(context.req.raw);
43
+ if (refusal !== null) return refused(refusal);
44
+ await next();
45
+ return undefined;
46
+ };
47
+ }
48
+
49
+ /** The public gate as a middleware: mount it on each `<public.prefix>/<family>/*`. */
50
+ export function tenantPublicGate(gates: Pick<TenantGates, 'publicRefusal'>): TenantGateMiddleware {
51
+ return async (context, next) => {
52
+ const refusal = await gates.publicRefusal(context.req.raw);
53
+ if (refusal !== null) return refused(refusal);
54
+ await next();
55
+ return undefined;
56
+ };
57
+ }
58
+
59
+ /** Mount both gates: `<admin.prefix>/*`, then `<public.prefix>/<family>/*` for each family. Returns `app`. */
60
+ export function mountTenantGates<A extends TenantGateApp>(
61
+ app: A,
62
+ gates: Pick<TenantGates, 'adminRefusal' | 'publicRefusal' | 'config'>,
63
+ ): A {
64
+ app.use(`${gates.config.admin.prefix}/*`, tenantAdminGate(gates));
65
+ const pub = tenantPublicGate(gates);
66
+ for (const family of Object.keys(gates.config.public.families)) app.use(`${gates.config.public.prefix}/${family}/*`, pub);
67
+ return app;
68
+ }
package/src/index.ts CHANGED
@@ -41,5 +41,47 @@ 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';
68
+ export {
69
+ TENANT_LIFECYCLE_COPY_KEYS,
70
+ TENANT_REFUSAL_STATUS,
71
+ isTenantGone,
72
+ purgeAtFor,
73
+ reminderDue,
74
+ sameTenantName,
75
+ type GateRefusal,
76
+ type TenantAuditEvent,
77
+ type TenantBlocker,
78
+ type TenantBlockerCount,
79
+ type TenantBlockerKind,
80
+ type TenantCloseEntry,
81
+ type TenantClosingEvent,
82
+ type TenantClosingState,
83
+ type TenantLifecycleCopyPack,
84
+ type TenantLifecycleRefusalKind,
85
+ type TenantNoticePayload,
86
+ type TenantReminder,
87
+ } from './lifecycle';
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Closing a tenant and reopening it.
3
+ *
4
+ * **Close**, a dangerous act: the host's confirmation first, then the reason
5
+ * and (a member's close) the typed name, then ONE transaction: the
6
+ * conditional status move, the blockers counted AGAIN after it (anything
7
+ * found rolls the move back), the closing row replaced, the mirror, the audit
8
+ * line. After the commit, and never able to undo it: the after-close hook
9
+ * (stamped either way; a failure is audited and the sweep retries it), the
10
+ * cache invalidation and the notice.
11
+ *
12
+ * **Reopen**: the row read once, then ONE transaction: closing → the status
13
+ * the close started from (a valid one, else active), the row deleted, the
14
+ * mirror, the audit line. Then the invalidation and the notice.
15
+ */
16
+ import type { TenantStatusSet } from '../config';
17
+ import type { TenantRecord } from '../port';
18
+ import type { LifecycleContext } from './context';
19
+ import { purgeAtFor, sameTenantName } from './pure';
20
+ import type {
21
+ TenantCloseEntry,
22
+ TenantClosingCreate,
23
+ TenantClosingState,
24
+ TenantLifecycle,
25
+ TenantNoticePayload,
26
+ } from './types';
27
+
28
+ type CloseInput<S extends string> = Parameters<TenantLifecycle<S>['close']>[0];
29
+
30
+ export function payloadOf(
31
+ tenant: TenantRecord,
32
+ name: string,
33
+ purgeAt: Date,
34
+ by: TenantCloseEntry | null,
35
+ reason: string | null,
36
+ restored: string | null = null,
37
+ ): TenantNoticePayload {
38
+ return { tenantId: tenant.id, name, slug: tenant.slug, purgeAt: purgeAt.toISOString(), by, reason, restored };
39
+ }
40
+
41
+ /** Where `close` and `reopen` get their record: the caller, who read it through the port or its own lookup. */
42
+ const CALLER_RECORD = 'close/reopen tenant (the caller\'s record, port.bySlug/byId)';
43
+
44
+ /** The refusal for a tenant the close may not move, by the status the transaction reads. */
45
+ async function notClosable<S extends string, Tx>(context: LifecycleContext<S, Tx>, id: string, tx: Tx): Promise<Error> {
46
+ const current = await context.tenant.byId(id, tx);
47
+ return context.refuse(current !== null && context.isGone(current.status) ? 'alreadyClosing' : 'notActive');
48
+ }
49
+
50
+ /** The transaction: the move, the recount, the row, the mirror and the audit line. */
51
+ async function closeInTransaction<S extends string, Tx>(
52
+ context: LifecycleContext<S, Tx>,
53
+ input: CloseInput<S>,
54
+ row: TenantClosingCreate,
55
+ ): Promise<void> {
56
+ const { tenant, config } = context;
57
+ const { ids } = tenant.config;
58
+ const statuses = tenant.config.statuses as unknown as TenantStatusSet<S>;
59
+ const from: readonly string[] = input.by === 'member' ? [statuses.active] : statuses.closableFrom;
60
+ const id = input.tenant.id;
61
+ await config.db.transaction(async (tx) => {
62
+ if (!from.includes(input.tenant.status)) throw await notClosable(context, id, tx);
63
+ if (!(await tenant.setStatusIf(id, input.tenant.status, statuses.closing, tx))) throw await notClosable(context, id, tx);
64
+ // After the move, in the same transaction: what landed since the page's read is seen here, and rolls the move back.
65
+ const blockers = await context.blockersOf(id, row.requestedAt, tx);
66
+ if (blockers.length > 0) throw context.refuse('closingBlocked', { pending: blockers.length }, blockers.length);
67
+ const table = await context.table(tx);
68
+ // A row an earlier close left (reopened by the platform before a stamp cleared it) is replaced: fresh stamps.
69
+ await table.deleteMany({ where: { tenantId: id } });
70
+ await table.create({ data: row });
71
+ if (config.mirror !== undefined) await config.mirror.replaced(tx, row);
72
+ await config.audit(tx, ids.audit.closeScheduled, {
73
+ act: 'closeScheduled',
74
+ tenantId: id,
75
+ by: input.by,
76
+ reason: row.reason,
77
+ purgeAt: row.purgeAt,
78
+ priorStatus: input.tenant.status,
79
+ });
80
+ });
81
+ }
82
+
83
+ /** The after-close hook, stamped either way; a failure is audited with its stamp, in one transaction. */
84
+ export async function runAfterClose<S extends string, Tx>(
85
+ context: LifecycleContext<S, Tx>,
86
+ tenant: TenantRecord<S>,
87
+ now: Date,
88
+ ): Promise<boolean> {
89
+ const { config } = context;
90
+ try {
91
+ const node = (await context.tenant.tree?.nodeOf?.(tenant.id)) ?? null;
92
+ await config.afterClose({ tenant, node, now });
93
+ } catch (error) {
94
+ config.onError(error, { act: 'afterClose', tenantId: tenant.id });
95
+ const message = (error instanceof Error ? error.message : String(error)).slice(0, 200);
96
+ await context.quietly('afterCloseFailed', tenant.id, () =>
97
+ config.db.transaction(async (tx) => {
98
+ await (await context.table(tx)).updateMany({
99
+ where: { tenantId: tenant.id, afterCloseDoneAt: null },
100
+ data: { afterCloseFailedAt: now },
101
+ });
102
+ if (config.mirror !== undefined) await config.mirror.event(tx, tenant.id, { kind: 'afterClose', ok: false, at: now });
103
+ await config.audit(tx, context.tenant.config.ids.audit.afterCloseFailed, {
104
+ act: 'afterCloseFailed',
105
+ tenantId: tenant.id,
106
+ error: message,
107
+ });
108
+ }),
109
+ );
110
+ return false;
111
+ }
112
+ // The hook went through; a missed stamp only means the sweep runs it again, which the host's hook must tolerate.
113
+ await context.quietly('afterCloseStamp', tenant.id, () =>
114
+ context.stamp(tenant.id, 'afterCloseDoneAt', now, { kind: 'afterClose', ok: true, at: now }),
115
+ );
116
+ return true;
117
+ }
118
+
119
+ export async function closeTenant<S extends string, Tx>(
120
+ context: LifecycleContext<S, Tx>,
121
+ given: CloseInput<S>,
122
+ ): Promise<TenantClosingState<S>> {
123
+ // A snapshot: the status the close starts from is the one the caller read, whatever happens to its object.
124
+ const input = { ...given, tenant: { ...given.tenant } };
125
+ const { config } = context;
126
+ const { ids } = context.tenant.config;
127
+ const statuses = context.tenant.config.statuses as unknown as TenantStatusSet<S>;
128
+ const id = input.tenant.id;
129
+ await config.confirmDangerousAct(input.request, { tenantId: id, by: input.by });
130
+ const reason = input.reason.trim();
131
+ if (reason.length < config.minReasonLength) throw context.refuse('reasonTooShort');
132
+ const name = context.nameOf(input.tenant, CALLER_RECORD);
133
+ if (input.by === 'member' && !sameTenantName(input.typedName ?? '', name, config.nameLocale)) {
134
+ throw context.refuse('nameMismatch');
135
+ }
136
+ const now = input.now ?? new Date();
137
+ const purgeAt = purgeAtFor(now, config.graceDays);
138
+ const row: TenantClosingCreate = {
139
+ tenantId: id,
140
+ requestedAt: now,
141
+ requestedById: input.by === 'member' ? input.actorUserId : null,
142
+ reason,
143
+ priorStatus: input.tenant.status,
144
+ purgeAt,
145
+ };
146
+ await closeInTransaction(context, input, row);
147
+ await runAfterClose(context, input.tenant, now);
148
+ await context.quietly('invalidate', id, () => config.invalidate(id));
149
+ await context.quietly('notify', id, () =>
150
+ config.notify(
151
+ ids.notifications.closingScheduled,
152
+ payloadOf(input.tenant, name, purgeAt, input.by, input.by === 'platform' ? reason : null),
153
+ ),
154
+ );
155
+ return { status: statuses.closing, requestedAt: now.toISOString(), purgeAt: purgeAt.toISOString() };
156
+ }
157
+
158
+ export async function reopenTenant<S extends string, Tx>(
159
+ context: LifecycleContext<S, Tx>,
160
+ input: { tenant: TenantRecord<S>; by: TenantCloseEntry },
161
+ ): Promise<TenantClosingState<S>> {
162
+ const { config } = context;
163
+ const { ids } = context.tenant.config;
164
+ const statuses = context.tenant.config.statuses as unknown as TenantStatusSet<S>;
165
+ const id = input.tenant.id;
166
+ const name = context.nameOf(input.tenant, CALLER_RECORD);
167
+ const row = await (await context.table()).findUnique({ where: { tenantId: id } });
168
+ const prior = row?.priorStatus ?? null;
169
+ const target = (
170
+ prior !== null && (statuses.all as readonly string[]).includes(prior) && !context.isGone(prior) ? prior : statuses.active
171
+ ) as S;
172
+ await config.db.transaction(async (tx) => {
173
+ if (!(await context.tenant.setStatusIf(id, statuses.closing, target, tx))) {
174
+ throw context.refuse(row?.purgedAt ? 'purged' : 'notClosing');
175
+ }
176
+ await (await context.table(tx)).deleteMany({ where: { tenantId: id } });
177
+ if (config.mirror !== undefined) await config.mirror.deleted(tx, id, row?.requestedAt);
178
+ await config.audit(tx, ids.audit.closeReopened, {
179
+ act: 'closeReopened',
180
+ tenantId: id,
181
+ by: input.by,
182
+ purgeAt: row?.purgeAt ?? null,
183
+ restored: target,
184
+ });
185
+ });
186
+ await context.quietly('invalidate', id, () => config.invalidate(id));
187
+ await context.quietly('notify', id, () =>
188
+ config.notify(ids.notifications.reopened, payloadOf(input.tenant, name, row?.purgeAt ?? new Date(), null, null, target)),
189
+ );
190
+ return { status: target, requestedAt: null, purgeAt: null };
191
+ }