@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.
@@ -0,0 +1,160 @@
1
+ /**
2
+ * The two gates a closing or closed tenant puts in front of an API.
3
+ *
4
+ * - **Admin** (`<admin.prefix>/<slug>/…`): an open tenant passes; a CLOSED one
5
+ * is refused (`closed`); a CLOSING one admits only whoever holds the close
6
+ * permission (`holdsClose`), who reads everything and writes only through
7
+ * `admin.closingWrites`, the rest `readOnly`; everyone else `closing`.
8
+ * A request with nobody signed in passes: the route's own guard answers it.
9
+ * - **Public** (`<public.prefix>/<family>/<slug>/…`): a write (and, for a
10
+ * `readsToo` family, a read) naming a closing or closed tenant is refused
11
+ * `gone`. A family's `fixedWords` are routes of its own, never asked as a
12
+ * slug; after a word in `slugAfter` the NEXT segment is the slug.
13
+ *
14
+ * The status rides the host's `lookup` (its kept slug lookup): an open tenant
15
+ * pays whatever that lookup costs and nothing more, and a fixed word pays
16
+ * nothing. A lookup that throws passes the request on: the route's own lookup
17
+ * fails the same way. The path is read as a router reads it (`decodeURI`), so
18
+ * an escaped segment is no way around; the slug is decoded.
19
+ */
20
+ import type { TenantCopyPack, TenantCoreConfig } from '../config';
21
+ import type { DeepReadonly } from '../core';
22
+ import { isTenantGone } from './pure';
23
+ import { TENANT_REFUSAL_STATUS, refusalSentence, type GateRefusal, type TenantLifecycleRefusalKind } from './refusal';
24
+ import { validateGates } from './validate';
25
+
26
+ export interface TenantPublicFamily {
27
+ /** Refuse reads too (a menu that must not be served), not only writes. */
28
+ readsToo: boolean;
29
+ /** Second segments that are routes of the family, never a slug. */
30
+ fixedWords: readonly string[];
31
+ /** Second segments after which the THIRD segment is the slug. */
32
+ slugAfter: readonly string[];
33
+ }
34
+
35
+ export interface TenantGatesConfig {
36
+ admin: { prefix: string; closingWrites: readonly string[] };
37
+ public: { prefix: string; families: Readonly<Record<string, TenantPublicFamily>> };
38
+ /** The host's kept slug lookup: the tenant's id and status, or null. */
39
+ lookup(slug: string): Promise<{ id: string; status: string } | null>;
40
+ /** Whether the signed-in actor holds the close permission; null when nobody is signed in. Fail closed. */
41
+ holdsClose(request: Request, tenantId: string): Promise<boolean | null>;
42
+ /** The current request's locale (null: the default pack). */
43
+ locale(): string | null;
44
+ }
45
+
46
+ export interface TenantGates {
47
+ /** The refusal an admin request meets, or null when it passes. */
48
+ adminRefusal(request: Request): Promise<GateRefusal | null>;
49
+ /** The refusal a public request meets, or null when it passes. */
50
+ publicRefusal(request: Request): Promise<GateRefusal | null>;
51
+ /** The slug a public path names, or null for a path that names none (or a read the family lets through). */
52
+ publicSlugOf(path: string, method: string): string | null;
53
+ /** The admin decision for a tenant of `status`; `holds` is asked only while it is closing. */
54
+ adminDecision(
55
+ status: string,
56
+ request: { method: string; rest: string },
57
+ holds: () => Promise<boolean | null>,
58
+ ): Promise<GateRefusal | null>;
59
+ /** The admin and public prefixes and families, as validated: what a mount reads. */
60
+ config: DeepReadonly<Pick<TenantGatesConfig, 'admin' | 'public'>>;
61
+ }
62
+
63
+ /** Methods that read: everything else writes. */
64
+ const READS = new Set(['GET', 'HEAD', 'OPTIONS']);
65
+
66
+ function escaped(text: string): string {
67
+ return text.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
68
+ }
69
+
70
+ /** The path as the router reads it (an escaped segment decoded). */
71
+ function routedPath(pathname: string): string {
72
+ try {
73
+ return decodeURI(pathname);
74
+ } catch {
75
+ return pathname;
76
+ }
77
+ }
78
+
79
+ /** The decoded slug, or null for a malformed escape: the route answers that request itself. */
80
+ function decodedSlug(slug: string): string | null {
81
+ try {
82
+ return decodeURIComponent(slug);
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
88
+ export function createTenantGates(
89
+ tenant: { config: DeepReadonly<TenantCoreConfig>; copyFor(locale: string | null | undefined): TenantCopyPack },
90
+ config: TenantGatesConfig,
91
+ ): TenantGates {
92
+ validateGates(config);
93
+ const { statuses, ids } = tenant.config;
94
+ const adminRoute = new RegExp(`^${escaped(config.admin.prefix)}/([^/]+)(/.*)?$`, 'u');
95
+ const closingWrites = new Set(config.admin.closingWrites);
96
+ const families = new Map(
97
+ Object.entries(config.public.families).map(([name, family]) => [
98
+ name,
99
+ { readsToo: family.readsToo, fixed: new Set(family.fixedWords), after: new Set(family.slugAfter) },
100
+ ]),
101
+ );
102
+ const publicDepth = config.public.prefix.split('/').length - 1;
103
+
104
+ const refusal = (kind: TenantLifecycleRefusalKind): GateRefusal => ({
105
+ kind,
106
+ status: TENANT_REFUSAL_STATUS[kind],
107
+ code: ids.refusals[kind],
108
+ message: refusalSentence(tenant.copyFor(config.locale()), kind),
109
+ });
110
+
111
+ const adminDecision: TenantGates['adminDecision'] = async (status, request, holds) => {
112
+ if (!isTenantGone(statuses, status)) return null;
113
+ if (status === statuses.closed) return refusal('closed');
114
+ const holder = await holds();
115
+ if (holder === null) return null;
116
+ if (!holder) return refusal('closing');
117
+ if (READS.has(request.method.toUpperCase()) || closingWrites.has(request.rest)) return null;
118
+ return refusal('readOnly');
119
+ };
120
+
121
+ /** The family's rule for a path under the public prefix, and the segments after the family. */
122
+ const ruleOf = (path: string, method: string) => {
123
+ if (!path.startsWith(`${config.public.prefix}/`)) return null;
124
+ const [family = '', second = '', third = ''] = path.split('/').slice(publicDepth + 1);
125
+ const rule = families.get(family);
126
+ if (rule === undefined || (READS.has(method.toUpperCase()) && !rule.readsToo)) return null;
127
+ return { rule, second, third };
128
+ };
129
+
130
+ const publicSlugOf: TenantGates['publicSlugOf'] = (path, method) => {
131
+ const found = ruleOf(path, method);
132
+ if (found === null) return null;
133
+ const { rule, second, third } = found;
134
+ if (rule.after.has(second)) return third || null;
135
+ return rule.fixed.has(second) ? null : second || null;
136
+ };
137
+
138
+ const lookup = (slug: string) => config.lookup(slug).catch(() => null);
139
+
140
+ return {
141
+ config: { admin: config.admin, public: config.public } as TenantGates['config'],
142
+ adminDecision,
143
+ publicSlugOf,
144
+ adminRefusal: async (request) => {
145
+ const match = adminRoute.exec(routedPath(new URL(request.url).pathname));
146
+ const slug = match?.[1] === undefined ? null : decodedSlug(match[1]);
147
+ const found = slug === null ? null : await lookup(slug);
148
+ if (found === null || !isTenantGone(statuses, found.status)) return null;
149
+ return adminDecision(found.status, { method: request.method, rest: match?.[2] ?? '' }, () =>
150
+ config.holdsClose(request, found.id),
151
+ );
152
+ },
153
+ publicRefusal: async (request) => {
154
+ const raw = publicSlugOf(routedPath(new URL(request.url).pathname), request.method);
155
+ const slug = raw === null ? null : decodedSlug(raw);
156
+ const found = slug === null ? null : await lookup(slug);
157
+ return found !== null && isTenantGone(statuses, found.status) ? refusal('gone') : null;
158
+ },
159
+ };
160
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * The tenant lifecycle (opt-in): close, reopen, the closing state, the
3
+ * blockers, the sweep and the notices' words. Built by
4
+ * `createApiTenant({ lifecycle })`, or by `createTenantLifecycle` over an
5
+ * existing tenant.
6
+ */
7
+ import type { TenantCopyPack } from '../config';
8
+ import { closeTenant, reopenTenant } from './close';
9
+ import { createContext, type LifecycleTenant } from './context';
10
+ import { sweepTenants } from './sweep';
11
+ import type { TenantLifecycle, TenantLifecycleConfig, TenantLifecycleCopyPack, TenantNoticePayload } from './types';
12
+ import { validateLifecycle, validateLifecycleCopy } from './validate';
13
+
14
+ export { isTenantGone, purgeAtFor, reminderDue, sameTenantName, type TenantReminder } from './pure';
15
+ export {
16
+ TENANT_REFUSAL_STATUS,
17
+ TenantLifecycleRefusal,
18
+ type GateRefusal,
19
+ type TenantLifecycleRefusalKind,
20
+ } from './refusal';
21
+ export { createTenantGates, type TenantGates, type TenantGatesConfig, type TenantPublicFamily } from './gates';
22
+ export { validateGates, validateLifecycle } from './validate';
23
+ export type { LifecycleTenant } from './context';
24
+ export {
25
+ TENANT_LIFECYCLE_COPY_KEYS,
26
+ type TenantAuditEvent,
27
+ type TenantBlocker,
28
+ type TenantBlockerCount,
29
+ type TenantBlockerKind,
30
+ type TenantCloseEntry,
31
+ type TenantClosingCreate,
32
+ type TenantClosingEvent,
33
+ type TenantClosingMirror,
34
+ type TenantClosingRow,
35
+ type TenantClosingStamp,
36
+ type TenantClosingState,
37
+ type TenantClosingTable,
38
+ type TenantLifecycle,
39
+ type TenantLifecycleConfig,
40
+ type TenantLifecycleCopyPack,
41
+ type TenantNoticePayload,
42
+ type TenantSweepResult,
43
+ } from './types';
44
+
45
+ /** `2026-12-19T…` as the locale writes a day, in `timeZone`. */
46
+ function dayOf(iso: string, locale: string, timeZone: string): string {
47
+ return new Intl.DateTimeFormat(locale, { timeZone }).format(new Date(iso));
48
+ }
49
+
50
+ type Words = { title: string; body: string };
51
+
52
+ type Writer = (copy: TenantCopyPack, extra: TenantLifecycleCopyPack, name: string, day: string, payload: TenantNoticePayload) => Words;
53
+
54
+ function scheduledWords(copy: TenantCopyPack, extra: TenantLifecycleCopyPack, name: string, day: string, payload: TenantNoticePayload): Words {
55
+ if (payload.by !== 'platform') return { title: copy.noticeScheduledTitle(name), body: copy.noticeScheduledBody(name, day) };
56
+ const reason = payload.reason?.trim() ?? '';
57
+ return {
58
+ title: extra.noticePlatformScheduledTitle(name),
59
+ body: reason === '' ? extra.noticePlatformScheduledBodyNoReason(name, day) : extra.noticePlatformScheduledBody(name, day, reason),
60
+ };
61
+ }
62
+
63
+ /**
64
+ * The lifecycle's notice words alone, for a host whose notification
65
+ * registry renders them apart from the lifecycle wiring (no hooks needed):
66
+ * the tenant's copy packs plus the lifecycle's copy extension, validated
67
+ * here as `createTenantLifecycle` validates it (every key, every locale of
68
+ * the base copy), so every locale the reader may resolve to has its own
69
+ * extension, and a platform close never falls back to the member's sentence.
70
+ */
71
+ export function createNoticeWords(
72
+ tenant: Pick<LifecycleTenant<string, unknown>, 'config' | 'copyFor'>,
73
+ config: Pick<TenantLifecycleConfig, 'copy'>,
74
+ ): TenantLifecycle['noticeWords'] {
75
+ const { notifications } = tenant.config.ids;
76
+ const { statuses } = tenant.config;
77
+ const { locales, defaultLocale } = tenant.config.copy;
78
+ validateLifecycleCopy((config as { copy?: unknown }).copy, Object.keys(locales));
79
+ // Validated above for every base locale, and `tag` is always one of them.
80
+ const extraFor = (tag: string): TenantLifecycleCopyPack => config.copy.locales[tag] as TenantLifecycleCopyPack;
81
+ const writers = new Map<string, Writer>([
82
+ [notifications.closingScheduled, scheduledWords],
83
+ [notifications.closingWeek, (copy, _extra, name, day) => ({ title: copy.noticeWeekTitle(name), body: copy.noticeWeekBody(name, day) })],
84
+ [notifications.closingDay, (copy, _extra, name) => ({ title: copy.noticeDayTitle(name), body: copy.noticeDayBody(name) })],
85
+ [
86
+ notifications.reopened,
87
+ (copy, extra, name, _day, payload) =>
88
+ payload.restored !== undefined && payload.restored !== null && payload.restored !== statuses.active
89
+ ? { title: extra.noticeReopenedRestoredTitle(name), body: extra.noticeReopenedRestoredBody(name) }
90
+ : { title: copy.noticeReopenedTitle(name), body: copy.noticeReopenedBody(name) },
91
+ ],
92
+ ]);
93
+ return (typeId, payload, at) => {
94
+ const write = writers.get(typeId);
95
+ if (write === undefined) throw new RangeError(`@12-apps/tenant: "${typeId}" is not one of the lifecycle's notice types.`);
96
+ const tag = at.locale !== null && Object.hasOwn(locales, at.locale) ? at.locale : defaultLocale;
97
+ return write(tenant.copyFor(tag), extraFor(tag), payload.name, dayOf(payload.purgeAt, tag, at.timeZone), payload);
98
+ };
99
+ }
100
+
101
+ /**
102
+ * The lifecycle over `tenant`, validated before it returns. The host wiring
103
+ * it MUST return `name` from its port's `bySlug` and `byId`.
104
+ */
105
+ export function createTenantLifecycle<S extends string, Tx>(
106
+ tenant: LifecycleTenant<S, Tx>,
107
+ config: TenantLifecycleConfig<S, Tx>,
108
+ ): TenantLifecycle<S> {
109
+ validateLifecycle(config, Object.keys(tenant.config.copy.locales), tenant.tree !== undefined);
110
+ const context = createContext(tenant, config);
111
+ return {
112
+ close: (input) => closeTenant(context, input),
113
+ reopen: (input) => reopenTenant(context, input),
114
+ state: async (record) => {
115
+ if (!context.isGone(record.status)) return { status: record.status, requestedAt: null, purgeAt: null };
116
+ const row = await (await context.table()).findUnique({ where: { tenantId: record.id } });
117
+ return {
118
+ status: record.status,
119
+ requestedAt: row?.requestedAt.toISOString() ?? null,
120
+ purgeAt: row?.purgeAt.toISOString() ?? null,
121
+ };
122
+ },
123
+ blockers: (tenantId, now = new Date()) => context.blockersOf(tenantId, now),
124
+ sweep: (now) => sweepTenants(context, now),
125
+ noticeWords: createNoticeWords(tenant, config),
126
+ };
127
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The lifecycle's pure readings: whether a status is gone, the typed-name
3
+ * check, the purge date and the reminder due. No I/O, so a guard, a screen and
4
+ * a test read the same answer.
5
+ */
6
+ import type { TenantStatusSet } from '../config';
7
+
8
+ const DAY_MS = 24 * 60 * 60 * 1000;
9
+
10
+ /** Whether `status` is the closing or the closed status of the host's set. */
11
+ export function isTenantGone(statuses: Pick<TenantStatusSet, 'closing' | 'closed'>, status: string): boolean {
12
+ return status === statuses.closing || status === statuses.closed;
13
+ }
14
+
15
+ /**
16
+ * Two spellings of a tenant's name agree: Unicode composition, outer and
17
+ * repeated spaces and case aside, case folded in `locale`. An empty typing
18
+ * never agrees.
19
+ */
20
+ export function sameTenantName(typed: string, name: string, locale: string): boolean {
21
+ const norm = (value: string) =>
22
+ value.normalize('NFC').trim().replace(/\s+/gu, ' ').toLocaleLowerCase(locale);
23
+ const left = norm(typed);
24
+ return left !== '' && left === norm(name);
25
+ }
26
+
27
+ /**
28
+ * When a tenant closed at `requestedAt` is purged: `graceDays` whole days of
29
+ * 86 400 000 ms later. Milliseconds, never calendar days, so a daylight-saving
30
+ * change moves nothing.
31
+ */
32
+ export function purgeAtFor(requestedAt: Date, graceDays: number): Date {
33
+ return new Date(requestedAt.getTime() + graceDays * DAY_MS);
34
+ }
35
+
36
+ /** Which reminder a sweep may send. */
37
+ export type TenantReminder = 'week' | 'day';
38
+
39
+ /**
40
+ * The reminder due at `now` for a tenant purged at `purgeAt`, given the ones
41
+ * already sent; null for none. `days.week` and `days.day` are how many days
42
+ * before the purge each goes out. A sweep that missed the week (its queue was
43
+ * down) sends the day's alone, and nothing is sent once the purge is due.
44
+ */
45
+ export function reminderDue(
46
+ purgeAt: Date,
47
+ sent: { week: boolean; day: boolean },
48
+ now: Date,
49
+ days: { week: number; day: number },
50
+ ): TenantReminder | null {
51
+ const left = purgeAt.getTime() - now.getTime();
52
+ if (left <= 0) return null;
53
+ if (!sent.day && left <= days.day * DAY_MS) return 'day';
54
+ if (!sent.week && !sent.day && left <= days.week * DAY_MS) return 'week';
55
+ return null;
56
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The refusals the lifecycle and its gates answer: each a refusal kind of the
3
+ * host's own code set, with a FIXED HTTP status and the sentence of the
4
+ * caller's copy pack.
5
+ */
6
+ import type { TenantCopyPack } from '../config';
7
+ import type { TenantRefusalKind } from '../core';
8
+
9
+ /** The lifecycle's refusal kinds (the export's are the export slice's). */
10
+ export type TenantLifecycleRefusalKind = Exclude<TenantRefusalKind, 'exportNeedsPerson' | 'exportNotFound' | 'exportExpired'>;
11
+
12
+ /** Each kind's HTTP status: never the host's choice, so every host's clients read the same. */
13
+ export const TENANT_REFUSAL_STATUS: Readonly<Record<TenantLifecycleRefusalKind, 403 | 409 | 422>> = {
14
+ closing: 403,
15
+ readOnly: 403,
16
+ closed: 403,
17
+ gone: 409,
18
+ alreadyClosing: 409,
19
+ notActive: 409,
20
+ closingBlocked: 409,
21
+ purged: 409,
22
+ notClosing: 409,
23
+ reasonTooShort: 422,
24
+ nameMismatch: 422,
25
+ };
26
+
27
+ const SENTENCES: Readonly<Record<TenantLifecycleRefusalKind, (copy: TenantCopyPack, count: number) => string>> = {
28
+ closing: (copy) => copy.refusalClosing,
29
+ readOnly: (copy) => copy.refusalReadOnly,
30
+ closed: (copy) => copy.refusalClosed,
31
+ gone: (copy) => copy.refusalGone,
32
+ alreadyClosing: (copy) => copy.refusalAlreadyClosing,
33
+ notActive: (copy) => copy.refusalNotActive,
34
+ closingBlocked: (copy, count) => copy.refusalBlocked(count),
35
+ purged: (copy) => copy.refusalPurged,
36
+ notClosing: (copy) => copy.refusalNotClosing,
37
+ reasonTooShort: (copy) => copy.refusalReasonTooShort,
38
+ nameMismatch: (copy) => copy.refusalNameMismatch,
39
+ };
40
+
41
+ /** The sentence a kind reads in `copy`; `count` is the blockers' for `closingBlocked`. */
42
+ export function refusalSentence(copy: TenantCopyPack, kind: TenantLifecycleRefusalKind, count = 0): string {
43
+ return SENTENCES[kind](copy, count);
44
+ }
45
+
46
+ /** A refusal as a gate answers it: status, the host's code, the sentence. */
47
+ export interface GateRefusal {
48
+ kind: TenantLifecycleRefusalKind;
49
+ status: 403 | 409 | 422;
50
+ code: string;
51
+ message: string;
52
+ }
53
+
54
+ /** Thrown by `close` and `reopen`: the host maps it onto its own error envelope. */
55
+ export class TenantLifecycleRefusal extends Error {
56
+ readonly kind: TenantLifecycleRefusalKind;
57
+ readonly code: string;
58
+ readonly status: 403 | 409 | 422;
59
+ readonly details: Readonly<Record<string, number>>;
60
+
61
+ constructor(refusal: GateRefusal, details: Readonly<Record<string, number>> = {}) {
62
+ super(refusal.message);
63
+ this.name = 'TenantLifecycleRefusal';
64
+ this.kind = refusal.kind;
65
+ this.code = refusal.code;
66
+ this.status = refusal.status;
67
+ this.details = details;
68
+ }
69
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The sweep: every pass reads the closing rows not yet purged, oldest purge
3
+ * first, at most `sweepBatch`, and for each one:
4
+ *
5
+ * - deletes it when the tenant is neither closing nor closed (a stale row of
6
+ * a tenant reopened behind the package's back: by a host release that
7
+ * wrote only its older table, say), conditionally on its `requestedAt`,
8
+ * with the mirror, in one transaction; a stale row never takes a slot of
9
+ * the batch, so the next page is read and no due tenant waits behind it;
10
+ * - retries the after-close hook while it has not gone through;
11
+ * - once due, runs the host's purge, and stamps `purgedAt` on `purged` and on
12
+ * `already` (which heals a crash between the host's purge and the stamp);
13
+ * - before that, while closing, sends the reminder due: re-read right before
14
+ * the send, stamped only once the notice was RECORDED, conditionally, so a
15
+ * failed send is retried and two passes cannot both send.
16
+ *
17
+ * One tenant's failure goes to `onError` and never stops the others.
18
+ */
19
+ import type { TenantRecord } from '../port';
20
+ import { runAfterClose, payloadOf } from './close';
21
+ import type { LifecycleContext } from './context';
22
+ import { reminderDue, type TenantReminder } from './pure';
23
+ import type { TenantClosingRow, TenantSweepResult } from './types';
24
+
25
+ const sentOf = (row: TenantClosingRow) => ({ week: row.remindedWeekAt !== null, day: row.remindedDayAt !== null });
26
+
27
+ async function remind<S extends string, Tx>(
28
+ context: LifecycleContext<S, Tx>,
29
+ row: TenantClosingRow,
30
+ now: Date,
31
+ result: TenantSweepResult,
32
+ ): Promise<void> {
33
+ const { config } = context;
34
+ const { statuses, ids } = context.tenant.config;
35
+ if (reminderDue(row.purgeAt, sentOf(row), now, config.reminderDays) === null) return;
36
+ // Re-read right before the send: a reopen, or another pass's stamp, may have landed.
37
+ const fresh = await (await context.table()).findUnique({ where: { tenantId: row.tenantId } });
38
+ const tenant = await context.tenant.byId(row.tenantId);
39
+ if (fresh === null || fresh.purgedAt !== null || tenant === null || tenant.status !== statuses.closing) return;
40
+ const due: TenantReminder | null = reminderDue(fresh.purgeAt, sentOf(fresh), now, config.reminderDays);
41
+ if (due === null) return;
42
+ const type = due === 'week' ? ids.notifications.closingWeek : ids.notifications.closingDay;
43
+ const told = await config.notify(type, payloadOf(tenant, context.nameOf(tenant, 'port.byId'), fresh.purgeAt, null, null));
44
+ if (!told) return;
45
+ const field = due === 'week' ? 'remindedWeekAt' : 'remindedDayAt';
46
+ result.reminded[due] += await context.stamp(row.tenantId, field, now, { kind: 'reminded', which: due, at: now });
47
+ }
48
+
49
+ async function sweepOne<S extends string, Tx>(
50
+ context: LifecycleContext<S, Tx>,
51
+ row: TenantClosingRow,
52
+ tenant: TenantRecord<S>,
53
+ now: Date,
54
+ result: TenantSweepResult,
55
+ ): Promise<void> {
56
+ if (row.afterCloseDoneAt === null && (await runAfterClose(context, tenant, now))) result.afterCloseRetried += 1;
57
+ if (row.purgeAt.getTime() <= now.getTime()) {
58
+ const outcome = await context.config.onPurgeDue(row.tenantId, { now });
59
+ if (outcome === 'skipped') return;
60
+ if (outcome === 'purged') result.purged += 1;
61
+ await context.stamp(row.tenantId, 'purgedAt', now, { kind: 'purged', at: now });
62
+ return;
63
+ }
64
+ if (tenant.status === context.tenant.config.statuses.closing) await remind(context, row, now, result);
65
+ }
66
+
67
+ /** Delete a stale row (its tenant is live again) while it is still the row read, with the mirror, in one transaction. */
68
+ async function dropStale<S extends string, Tx>(context: LifecycleContext<S, Tx>, row: TenantClosingRow): Promise<void> {
69
+ await context.config.db.transaction(async (tx) => {
70
+ const { count } = await (await context.table(tx)).deleteMany({
71
+ where: { tenantId: row.tenantId, requestedAt: row.requestedAt, purgedAt: null },
72
+ });
73
+ if (count > 0 && context.config.mirror !== undefined) await context.config.mirror.deleted(tx, row.tenantId, row.requestedAt);
74
+ });
75
+ }
76
+
77
+ /** One row: dropped when stale (answers false), else swept (answers true: it took a slot of the batch). */
78
+ async function visit<S extends string, Tx>(
79
+ context: LifecycleContext<S, Tx>,
80
+ row: TenantClosingRow,
81
+ now: Date,
82
+ result: TenantSweepResult,
83
+ ): Promise<boolean> {
84
+ try {
85
+ const tenant = await context.tenant.byId(row.tenantId);
86
+ if (tenant === null || !context.isGone(tenant.status)) {
87
+ await dropStale(context, row);
88
+ return false;
89
+ }
90
+ // Each tenant is its own purge and its own recorded notice: one at a time, by design.
91
+ await sweepOne(context, row, tenant, now, result);
92
+ } catch (error) {
93
+ context.config.onError(error, { act: 'sweep', tenantId: row.tenantId });
94
+ }
95
+ return true;
96
+ }
97
+
98
+ /** One page, in order, until `room` live tenants were swept. Answers how many were. */
99
+ async function sweepPage<S extends string, Tx>(
100
+ context: LifecycleContext<S, Tx>,
101
+ page: readonly TenantClosingRow[],
102
+ room: number,
103
+ now: Date,
104
+ result: TenantSweepResult,
105
+ ): Promise<number> {
106
+ let swept = 0;
107
+ for (const row of page) {
108
+ if (swept >= room) break;
109
+ if (await visit(context, row, now, result)) swept += 1;
110
+ }
111
+ return swept;
112
+ }
113
+
114
+ /**
115
+ * Pages of `sweepBatch` rows, oldest purge first, by keyset; at most
116
+ * `sweepBatch` live tenants are swept per pass, and a stale row (dropped)
117
+ * does not count, so the pass reads on until the batch is full or no row is left.
118
+ */
119
+ export async function sweepTenants<S extends string, Tx>(context: LifecycleContext<S, Tx>, now: Date): Promise<TenantSweepResult> {
120
+ const { config } = context;
121
+ const table = await context.table();
122
+ const result: TenantSweepResult = { reminded: { week: 0, day: 0 }, purged: 0, afterCloseRetried: 0 };
123
+ let swept = 0;
124
+ let after: TenantClosingRow | null = null;
125
+ while (swept < config.sweepBatch) {
126
+ const page: TenantClosingRow[] = await table.findMany({
127
+ where:
128
+ after === null
129
+ ? { purgedAt: null }
130
+ : { purgedAt: null, OR: [{ purgeAt: { gt: after.purgeAt } }, { purgeAt: after.purgeAt, tenantId: { gt: after.tenantId } }] },
131
+ orderBy: [{ purgeAt: 'asc' }, { tenantId: 'asc' }],
132
+ take: config.sweepBatch,
133
+ });
134
+ swept += await sweepPage(context, page, config.sweepBatch - swept, now, result);
135
+ if (page.length < config.sweepBatch) break;
136
+ after = page[page.length - 1] ?? null;
137
+ }
138
+ return result;
139
+ }