@fabrika/app 0.9.0-cloudflare.2 → 0.9.0-cloudflare.3

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.
Files changed (53) hide show
  1. package/package.json +9 -9
  2. package/skill/SKILL.md +20 -18
  3. package/skill/references/app-setup.md +29 -16
  4. package/skill/references/endpoint.md +24 -22
  5. package/skill/references/errors.md +3 -2
  6. package/skill/references/jobs.md +13 -3
  7. package/skill/references/tests.md +7 -0
  8. package/src/bun.ts +159 -6
  9. package/src/cloudflare/application.ts +543 -73
  10. package/src/cloudflare/export.ts +621 -0
  11. package/src/cloudflare/import.ts +1097 -0
  12. package/src/cloudflare/maintenance.ts +518 -0
  13. package/src/cloudflare/ops.ts +147 -18
  14. package/src/cloudflare/restore.ts +167 -0
  15. package/src/cloudflare/tracker.ts +192 -0
  16. package/src/cloudflare.ts +3 -2
  17. package/src/contract/artifact-schema.ts +7 -1
  18. package/src/contract/build.ts +6 -2
  19. package/src/contract/context.ts +26 -9
  20. package/src/contract/defaults.ts +22 -2
  21. package/src/contract/define.ts +1 -1
  22. package/src/contract/group.ts +1 -1
  23. package/src/files/kinds.ts +54 -24
  24. package/src/implement/anonymous.ts +1 -10
  25. package/src/implement/boot.ts +21 -9
  26. package/src/implement/dispatch.ts +171 -33
  27. package/src/implement/egress.ts +34 -8
  28. package/src/implement/invocation.ts +50 -10
  29. package/src/implement/workload.ts +18 -3
  30. package/src/jobs/runner.ts +639 -96
  31. package/src/testing/kit.ts +60 -0
  32. package/types/src/bun.d.ts +34 -1
  33. package/types/src/cloudflare/application.d.ts +36 -5
  34. package/types/src/cloudflare/export.d.ts +16 -0
  35. package/types/src/cloudflare/import.d.ts +58 -0
  36. package/types/src/cloudflare/maintenance.d.ts +117 -0
  37. package/types/src/cloudflare/ops.d.ts +39 -4
  38. package/types/src/cloudflare/restore.d.ts +9 -0
  39. package/types/src/cloudflare/tracker.d.ts +29 -0
  40. package/types/src/cloudflare.d.ts +2 -1
  41. package/types/src/contract/artifact-schema.d.ts +2 -0
  42. package/types/src/contract/context.d.ts +24 -9
  43. package/types/src/contract/defaults.d.ts +19 -1
  44. package/types/src/contract/define.d.ts +1 -1
  45. package/types/src/contract/group.d.ts +1 -1
  46. package/types/src/files/kinds.d.ts +17 -6
  47. package/types/src/implement/anonymous.d.ts +0 -4
  48. package/types/src/implement/boot.d.ts +11 -0
  49. package/types/src/implement/dispatch.d.ts +31 -0
  50. package/types/src/implement/invocation.d.ts +17 -7
  51. package/types/src/implement/workload.d.ts +5 -0
  52. package/types/src/jobs/runner.d.ts +60 -2
  53. package/types/src/testing/kit.d.ts +16 -0
@@ -31,6 +31,7 @@ import {
31
31
  workloadKeyVariable,
32
32
  } from '@fabrika/auth-core'
33
33
  import type { Database } from '@fabrika/db'
34
+ import { frameworkTablesOf, type LeaseFence } from '@fabrika/db/framework'
34
35
  import { refuseInProduction } from '@fabrika/db/production'
35
36
  import { MemoryEmailSender } from '@fabrika/email/memory'
36
37
  import type { FileObjectStore } from '@fabrika/platform'
@@ -197,6 +198,15 @@ export interface TestKit<C extends AnyContract> {
197
198
  runJob(name: JobName<C> | typeof FILE_SCAN_JOB | typeof FILE_SWEEP_JOB, options?: JobRunOptions): Promise<JobRunResult>
198
199
  /** Waits for the work requests left running: the runs a site's `ctx.kick` sent, a failure's report. */
199
200
  drain(): Promise<void>
201
+ /**
202
+ * Runs every job with a wake due now or within `within` ms (0 by default) once, as the Cloudflare object's alarm
203
+ * runs it: the startup repair first (each job's cron wake at its next fire), then each wake ahead moved to now, then
204
+ * each due job under its lease, a failed run's retry moved to its backoff. It first waits for the runs a site's
205
+ * `ctx.kick` sent. Nothing else fires on its own. Handlers keep real time: only the wakes move, never the clock, so
206
+ * a run again schedules its cron fire from now, and a later call skips a cron fire this kit already ran early. Needs
207
+ * the application's data layer.
208
+ */
209
+ runDueJobs(options?: { readonly within?: number }): Promise<readonly DueJobRun[]>
200
210
  /**
201
211
  * The stand-in for every job's transport: what reached it (`accepted`, `handoffs`) and its faults (`refuse`,
202
212
  * `unavailable`, `unreachable`, `loseAnswers`, `during`, `heal`). Each message carries the transport key,
@@ -218,6 +228,12 @@ export interface TestKit<C extends AnyContract> {
218
228
  solveChallenge(procedure: object): Promise<string>
219
229
  }
220
230
 
231
+ /** A job `runDueJobs` ran, and its run's result. */
232
+ export interface DueJobRun {
233
+ readonly job: string
234
+ readonly result: JobRunResult
235
+ }
236
+
221
237
  /** The names of the contract's cron jobs. */
222
238
  export type JobName<C> = C extends { readonly surface: { readonly jobs: infer J } } ? keyof J & string : never
223
239
 
@@ -693,6 +709,49 @@ export function bootTestKit<C extends AnyContract>(
693
709
  return application.jobs.run(name, runOptions)
694
710
  }
695
711
 
712
+ // The cron fires `runDueJobs` ran early, as `<key>@<due>`: a run schedules the same fire again from the real now.
713
+ const ranEarly = new Set<string>()
714
+ const runDueJobs = async (dueOptions: { readonly within?: number } = {}): Promise<readonly DueJobRun[]> => {
715
+ const within = dueOptions.within ?? 0
716
+ if (!Number.isFinite(within) || within < 0) {
717
+ throw new TypeError('runDueJobs({ within }) takes milliseconds, 0 or more')
718
+ }
719
+ const scheduler = application.jobs.scheduler
720
+ if (scheduler === null || app.database === null) {
721
+ throw new Error(
722
+ "runDueJobs runs the jobs over the application's data layer: serve(contract, { database: scoped(tables) }) and testKit(app, { database })",
723
+ )
724
+ }
725
+ await drain()
726
+ await scheduler.repair()
727
+ const { jobs: leases, wakes } = frameworkTablesOf(app.database)
728
+ const now = (await leases.now()).getTime()
729
+ const ahead: string[] = []
730
+ const fires: string[] = []
731
+ for (const job of scheduler.jobs) {
732
+ for (const wake of await wakes.pending(job)) {
733
+ const due = wake.dueAt.getTime()
734
+ const fire = wake.reason === 'cron' ? `${wake.dedupe}@${due}` : null
735
+ if (due > now && due <= now + within && (fire === null || !ranEarly.has(fire))) {
736
+ ahead.push(wake.id)
737
+ if (fire !== null) fires.push(fire)
738
+ }
739
+ }
740
+ }
741
+ if (ahead.length > 0) {
742
+ await wakes.hasten(ahead)
743
+ }
744
+ // Only once the wakes moved: a hasten that failed left them ahead, and the next call moves them again.
745
+ for (const fire of fires) ranEarly.add(fire)
746
+ const taken: { readonly job: string; readonly fence: LeaseFence }[] = []
747
+ for (const job of scheduler.jobs) {
748
+ const { fence, reaped } = await scheduler.take(job)
749
+ if (reaped) await scheduler.crashed(job)
750
+ if (fence !== null) taken.push({ job, fence })
751
+ }
752
+ return await Promise.all(taken.map(async ({ job, fence }) => ({ job, result: await scheduler.run(job, fence) })))
753
+ }
754
+
696
755
  const acceptInvitation = (invitationId: string, person?: LabelledTestCaller): LabelledTestCaller => {
697
756
  if (standIn === null) {
698
757
  throw new Error('this kit was given its own membership transport, so its IAM holds no invitation to accept')
@@ -725,6 +784,7 @@ export function bootTestKit<C extends AnyContract>(
725
784
  iam,
726
785
  runJob,
727
786
  drain,
787
+ runDueJobs,
728
788
  acceptInvitation,
729
789
  mail,
730
790
  mailKeyScope,
@@ -1,9 +1,10 @@
1
+ import { type Session } from '@fabrika/db/framework';
1
2
  import type { FileObjectStore } from '@fabrika/platform';
2
3
  import type { FetchService, RequestExecutionContext } from './fetch.js';
3
4
  import { type IamKeySource } from './implement/boot.js';
4
5
  import { type CrashEvents } from './implement/crashes.js';
5
6
  import { type ContractImplementation } from './implement/implement.js';
6
- import { type JobRunOptions, type JobRunResult } from './jobs/runner.js';
7
+ import { type ContractJobs, type JobRunOptions, type JobRunResult } from './jobs/runner.js';
7
8
  export { diskAssets } from './disk-assets.js';
8
9
  export { clamscanArguments, type ClamscanOptions, clamscanScanner } from './files/clamscan.js';
9
10
  export { markProductionProcess } from '@fabrika/db/production';
@@ -32,6 +33,38 @@ export interface ContractServer {
32
33
  /** Stops accepting requests and waits for the ones in flight. */
33
34
  stop(): Promise<void>;
34
35
  }
36
+ /**
37
+ * How long the wake timer waits for a wake that is already due: such a wake's own kick is under way (the post-commit start,
38
+ * or the timer's last one), and looking at once would kick its job a second time before that kick took the lease.
39
+ */
40
+ export declare const WAKE_RETRY_MS = 1000;
41
+ /**
42
+ * How long after a write projected the timer a refresh that cannot see the projected wake looks again: the write may still
43
+ * be committing, and no transaction that writes a wake outlasts a request's budget.
44
+ */
45
+ export declare const WAKE_SETTLE_MS: number;
46
+ /**
47
+ * The serving process's one timer to the jobs' next wake, Bun's side of the scheduler (ADR-0065 §5): it kicks each job
48
+ * whose wake came due through the kick path, so the lease admits one container. A write of this process lowers it in
49
+ * that write's transaction (`project`, `BootOptions.projectWakes`), by the delay on the database's clock; a wake another
50
+ * container wrote is found when the serving process refreshes it with its job check. Crontab still runs the schedule.
51
+ */
52
+ export declare class WakeTimer {
53
+ #private;
54
+ /** `track` holds each kick the timer starts until it ended, for the shutdown drain. */
55
+ constructor(track: (kick: Promise<void>) => void);
56
+ /** The booted application's jobs; until then nothing fires. */
57
+ attach(jobs: ContractJobs): void;
58
+ /**
59
+ * `BootOptions.projectWakes`: never later than the next wake the write leaves, which a rollback only makes early. The
60
+ * timer may fire before the write commits, so the wake stays unseen until a refresh finds it.
61
+ */
62
+ readonly project: (transaction: Session) => Promise<void>;
63
+ /** Kicks every job whose wake is due and arms the timer at the next one; it never rejects. */
64
+ refresh(): Promise<void>;
65
+ /** Fires no more and refreshes no more; resolves once a refresh under way ended, so it starts no kick after it. */
66
+ stop(): Promise<void>;
67
+ }
35
68
  /**
36
69
  * The stored files' object storage (Zerops object storage, path-style), when the platform wrote its variables;
37
70
  * a partial set stops the boot. The credentials are never quoted in a message.
@@ -1,7 +1,8 @@
1
1
  import { type SqliteStorage } from '@fabrika/db/sqlite';
2
2
  import { type CrashEvents } from '../implement/crashes.js';
3
3
  import type { ContractImplementation } from '../implement/implement.js';
4
- import { type OpsStorage } from './ops.js';
4
+ import { type JobClock } from '../jobs/runner.js';
5
+ import { type OpsRecovery, type OpsStorage } from './ops.js';
5
6
  /** The application module, imported only after the environment was captured: the generated entrypoint's `import()`. */
6
7
  export type ImplementationLoader = () => Promise<{
7
8
  readonly default: ContractImplementation;
@@ -18,20 +19,43 @@ export interface ContractWorkerOptions {
18
19
  readonly rejections?: CrashEvents;
19
20
  /** What posts a report to Operations' ingest; `fetch` by default. */
20
21
  readonly operationsFetch?: (request: Request) => Promise<Response>;
22
+ /** The jobs' and the alarm's waits and an attempt's deadline; the system clock by default. */
23
+ readonly clock?: JobClock;
21
24
  }
22
25
  /**
23
- * Marks the Worker's minute tick, with its `scheduledTime`. The Worker's `fetch` removes it from every request it
26
+ * Marks the Worker's repair tick, with its `scheduledTime`. The Worker's `fetch` removes it from every request it
24
27
  * forwards, so only its own `scheduled` handler reaches the tick.
25
28
  */
26
29
  export declare const TICK_HEADER = "X-Fabrika-Tick";
27
- /** What the object needs of its `ctx.storage`; a Durable Object's `DurableObjectStorage` fits it. */
28
- export type ApplicationStorage = SqliteStorage & OpsStorage;
30
+ /** A wake runs at most this early: `Date.now()` is pinned between I/O, so an alarm may start a moment before it (I6). */
31
+ export declare const ALARM_SLACK_MS = 50;
32
+ /** After an internal error the alarm is armed again this far ahead; the repair tick covers a re-arm that failed. */
33
+ export declare const ALARM_RETRY_MS = 30000;
34
+ /**
35
+ * The object's KV key that holds the name of the object it is, recorded at its first verified event: an alarm names no
36
+ * object, and the one ordinary traffic reaches may since have changed. Outside the SQLite, so no dump carries it.
37
+ */
38
+ export declare const OBJECT_NAME_KEY = "fabrika:object";
39
+ /** The object's alarm. On a SQLite-backed object `setAlarm` and `deleteAlarm` commit with the open transaction. */
40
+ export interface AlarmStorage {
41
+ setAlarm(scheduledTime: number): Promise<void>;
42
+ deleteAlarm(): Promise<void>;
43
+ }
44
+ /**
45
+ * What the object needs of its `ctx.storage`; a Durable Object's `DurableObjectStorage` fits it. A test double without
46
+ * an alarm arms none.
47
+ */
48
+ export type ApplicationStorage = SqliteStorage & OpsStorage & Partial<AlarmStorage>;
29
49
  /** What the object needs of its `DurableObjectState`. */
30
50
  export interface ApplicationState {
31
- readonly storage: ApplicationStorage;
51
+ readonly storage: ApplicationStorage & Partial<Omit<OpsRecovery, 'abort'>>;
32
52
  blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>;
33
53
  waitUntil(promise: Promise<unknown>): void;
54
+ /** workerd resets the object; the test double has none. */
55
+ abort?(reason?: string): void;
34
56
  }
57
+ /** `state` with every `waitUntil` promise recorded by the isolate's pending-work tracker (the ops operation `timers`). */
58
+ export declare function trackedState(state: ApplicationState): ApplicationState;
35
59
  /** What the object classes of this isolate boot: the generated entrypoint's `createContractWorker` registers it. */
36
60
  export declare function registerApplication(load: ImplementationLoader, options: ContractWorkerOptions): void;
37
61
  /** The application environment's one object. The Worker's generated entrypoint exports it as `FabrikaApplication`. */
@@ -39,4 +63,11 @@ export declare class FabrikaApplication {
39
63
  #private;
40
64
  constructor(state: ApplicationState, env: Readonly<Record<string, unknown>>);
41
65
  fetch(request: Request): Promise<Response>;
66
+ /**
67
+ * workerd calls it when the alarm is due (ADR-0065 §5). Only the object ordinary traffic reaches runs jobs, and only
68
+ * in `open`; otherwise it runs nothing and arms nothing: the maintenance operation owns the object, reopening arms the
69
+ * alarm again, and the repair tick arms the serving object's. It never throws, because after six failures the platform
70
+ * stops retrying: an internal error in `open` arms it again in `ALARM_RETRY_MS` and is reported.
71
+ */
72
+ alarm(): Promise<void>;
42
73
  }
@@ -0,0 +1,16 @@
1
+ import { type OpsExportRequest } from '@fabrika/auth-core';
2
+ import type { MaintenanceBarrier } from './maintenance.js';
3
+ import type { OpsTarget } from './ops.js';
4
+ /** One step of a dump of the object's database (ADR-0070). */
5
+ export declare function serveExport(target: OpsTarget, barrier: MaintenanceBarrier, step: OpsExportRequest): Promise<Response>;
6
+ /** What an export step reads: the object's storage, bucket and bookmarks, and the digest of the contract it was deployed with. */
7
+ export interface ExportSource extends Pick<OpsTarget, 'storage' | 'bucket' | 'recovery'> {
8
+ /** `FABRIKA_CONTRACT_DIGEST`, which the manifest records. */
9
+ readonly contractDigest: string | null;
10
+ }
11
+ /**
12
+ * One step of a dump. A diagnostic step runs in any mode. A consistent one runs in the barrier's turn, only at the
13
+ * published generation, never while the object is `open` or holds an import marker, so no transition and no migration
14
+ * falls inside it; past `begin` it refuses a database whose state or stretch is not the one its `begin` saw.
15
+ */
16
+ export declare function exportStep(source: ExportSource, barrier: MaintenanceBarrier, step: OpsExportRequest): Promise<Response>;
@@ -0,0 +1,58 @@
1
+ import { type OpsDumpSchema, type OpsImportRequest } from '@fabrika/auth-core';
2
+ import type { SqliteStorage } from '@fabrika/db/sqlite';
3
+ import { type SqliteMigrationBundle } from '@fabrika/db/sqlite-migrate';
4
+ import type { MaintenanceBarrier } from './maintenance.js';
5
+ import type { OpsTarget } from './ops.js';
6
+ /**
7
+ * One step of loading a dump into a fresh object (ADR-0070); `serving` is the object of ordinary traffic. A runtime
8
+ * whose storage has no synchronous KV or `deleteAll` does not serve the operation.
9
+ */
10
+ export declare function serveImport(target: OpsTarget, barrier: MaintenanceBarrier, step: OpsImportRequest, serving: string): Promise<Response>;
11
+ /** workerd's synchronous KV storage of a SQLite-backed object: it lives in the same database, so it commits with a transaction. */
12
+ export interface ImportKv {
13
+ get(key: string): unknown;
14
+ put(key: string, value: unknown): void;
15
+ delete(key: string): boolean;
16
+ }
17
+ /** What the importer needs of the object's storage; a SQLite-backed `DurableObjectStorage` fits it. */
18
+ export interface ImportStorage extends SqliteStorage {
19
+ readonly kv: ImportKv;
20
+ /** Wipes the object's database, its KV storage and its alarm. */
21
+ deleteAll(): Promise<void>;
22
+ }
23
+ /** The object an import step loads into. */
24
+ export interface ImportTarget {
25
+ readonly storage: ImportStorage;
26
+ /** The environment's bucket (the `FABRIKA_FILES` R2 binding), where the backup lies. */
27
+ readonly bucket: unknown;
28
+ /** The release's migration bundles in the order the object applies them: the framework's, then the application's. */
29
+ readonly migrations: readonly SqliteMigrationBundle[];
30
+ /** The object of ordinary traffic (`FABRIKA_APPLICATION_OBJECT`), which `discard` never wipes. */
31
+ readonly serving: string;
32
+ }
33
+ /** The KV key of the import marker. Invariant: an object that holds it never boots and never leaves `inspect`. */
34
+ export declare const IMPORT_MARKER_KEY = "fabrika:import";
35
+ /** Whether the object holds an import marker, so it must neither boot nor leave `inspect`. */
36
+ export declare function importInProgress(storage: {
37
+ readonly kv: ImportKv;
38
+ }): boolean;
39
+ /**
40
+ * One step of loading the consistent backup `step.source` into the fresh object `target` (ADR-0070 §6), in the
41
+ * barrier's turn: ADR-0069's stale refusal unless `step.generation` is the published one, then `serving_object` on the
42
+ * object of ordinary traffic, then `wrong_mode` unless `inspect`. The turn is held across the step's R2 reads, so the
43
+ * generation and mode it was admitted under still hold when it commits.
44
+ */
45
+ export declare function importStep(target: ImportTarget, barrier: MaintenanceBarrier, step: OpsImportRequest): Promise<Response>;
46
+ /**
47
+ * The schema `planOpsDump` reads, from the PRAGMAs workerd admits, of every table a dump holds. An `INITIALLY DEFERRED`
48
+ * clause is read from the table's SQL outside its quotes and comments, and marks every foreign key of its table; the
49
+ * names a `CHECK` reads come from the same SQL (`checkNamesOf`).
50
+ */
51
+ export declare function describeDumpSchema(storage: SqliteStorage): OpsDumpSchema;
52
+ /**
53
+ * The names the `CHECK` clauses of a table's `sql` read: every word and quoted identifier between a `CHECK` keyword's
54
+ * parentheses, ASCII-lowercase, keywords and numbers included, so it lists at least every column a `CHECK` reads. A
55
+ * string literal and a comment name nothing; a double-quoted string, which SQLite may read as either, counts as a name.
56
+ * `null` when the text does not scan (an unclosed quote, comment or parenthesis), which counts as naming every column.
57
+ */
58
+ export declare function checkNamesOf(sql: string): string[] | null;
@@ -0,0 +1,117 @@
1
+ import { type OpsMaintenance, type OpsMode, type OpsPublishedState, type OpsStateAck } from '@fabrika/auth-core';
2
+ import type { InvocationAdmission, InvocationGate, InvocationKind } from '../implement/dispatch.js';
3
+ export declare const DRAIN_BOUND_MS: number;
4
+ /** The state R2 holds, and its version: the etag a conditional put names. */
5
+ export interface StoredMaintenance {
6
+ readonly state: OpsPublishedState;
7
+ readonly version: string;
8
+ }
9
+ /**
10
+ * Since which generation the object has written nothing, as of the published generation `generation`: kept only while
11
+ * it is `read-only`, `closed` or `inspect`.
12
+ */
13
+ export interface FrozenRecord {
14
+ readonly generation: number;
15
+ readonly since: number;
16
+ }
17
+ /** The object's durable copy of its maintenance state. */
18
+ export interface MaintenanceStore {
19
+ /** `null` only for a definite not-found; every other failure throws, and is never read as absence. */
20
+ read(): Promise<StoredMaintenance | null>;
21
+ /** Puts `state` if R2 still holds `version` (`null`: holds nothing); the new version, or `null` when the condition failed. */
22
+ put(state: OpsPublishedState, version: string | null): Promise<string | null>;
23
+ /** The frozen record, `null` when none is stored. A store without these keeps the record in memory only. */
24
+ readFrozen?(): Promise<FrozenRecord | null>;
25
+ putFrozen?(record: FrozenRecord): Promise<void>;
26
+ }
27
+ /** `__fabrika/ops/<object>.json` in the environment's bucket (`bucket`, an R2 binding). */
28
+ export declare function r2MaintenanceStore(bucket: unknown, object: string): MaintenanceStore;
29
+ export type TransitionResult = {
30
+ readonly kind: 'acknowledged';
31
+ readonly ack: OpsStateAck;
32
+ }
33
+ /** The 409: what R2 holds as far as the object knows, `null` before the first publication. */
34
+ | {
35
+ readonly kind: 'stale';
36
+ readonly published: OpsPublishedState | null;
37
+ }
38
+ /** R2 could not be read or written: the call fails and Control retries. */
39
+ | {
40
+ readonly kind: 'failed';
41
+ }
42
+ /** The caller's `frozen` held the object in `inspect`: nothing changed. */
43
+ | {
44
+ readonly kind: 'frozen';
45
+ };
46
+ export type MigrateResult<T> = {
47
+ readonly kind: 'migrated';
48
+ readonly value: T;
49
+ } | {
50
+ readonly kind: 'stale';
51
+ readonly published: OpsPublishedState | null;
52
+ };
53
+ /** What a step run in the barrier's turn answers, and what keeps the turn past the answer (`null`: nothing). */
54
+ export interface TurnStep<T> {
55
+ readonly value: T;
56
+ readonly holdUntil: Promise<void> | null;
57
+ }
58
+ export type StepResult<T> = {
59
+ readonly kind: 'ran';
60
+ readonly value: T;
61
+ } | {
62
+ readonly kind: 'stale';
63
+ readonly published: OpsPublishedState | null;
64
+ };
65
+ export interface BarrierOptions {
66
+ /** The drain's bound; `DRAIN_BOUND_MS` by default. */
67
+ readonly drainBoundMs?: number;
68
+ }
69
+ export declare class MaintenanceBarrier {
70
+ #private;
71
+ private constructor();
72
+ /** The cold start: an absent state is `open`; a failed read rejects, and the caller retries on its next request. */
73
+ static load(store: MaintenanceStore, options?: BarrierOptions): Promise<MaintenanceBarrier>;
74
+ get mode(): OpsMode;
75
+ view(): OpsMaintenance;
76
+ /** What R2 holds as far as this instance knows, `null` before the first publication: what a stale refusal names. */
77
+ get published(): OpsPublishedState | null;
78
+ /**
79
+ * The generation at which the object entered its current stretch of `read-only`, `closed` and `inspect`, or at which a
80
+ * data step last wrote within it; `null` outside such a stretch. A consistent dump is one state while it holds.
81
+ */
82
+ get frozenSince(): number | null;
83
+ /**
84
+ * Called in a data step's turn before the step writes while the object writes nothing else (an import step, a
85
+ * restore's `arm`): the stretch starts again at the current generation, durably before the write. A failed put rejects.
86
+ */
87
+ restrictedWrite(): Promise<void>;
88
+ /** The scope of one invocation, admitted now: the generation and mode it captures, which its writes are fenced on. */
89
+ event(): BarrierEvent;
90
+ /** Whether a write of an invocation admitted at `generation` in `mode` may commit now. */
91
+ writable(generation: number | null, mode: OpsMode): boolean;
92
+ /** Admits an invocation of `kind` captured at `generation`, or `null` when the mode refuses it or a transition followed. */
93
+ admit(kind: InvocationKind, generation: number | null): InvocationAdmission | null;
94
+ /**
95
+ * `POST /__fabrika/ops/state`: the transition of ADR-0069 §3, acknowledged once published and drained. `frozen` is
96
+ * asked in the turn, after every data step before it: while it holds, no transition leaves `inspect`.
97
+ */
98
+ transition(requested: OpsPublishedState, frozen?: () => boolean): Promise<TransitionResult>;
99
+ /**
100
+ * `POST /__fabrika/ops/migrate`: `work` runs only under the published generation, in a mode that may migrate, and no
101
+ * transition runs meanwhile.
102
+ */
103
+ migrate<T>(generation: number, work: () => Promise<T>): Promise<MigrateResult<T>>;
104
+ /**
105
+ * A data step of Control's (ADR-0070): `work` runs in the barrier's turn, only under the published `generation`, with
106
+ * the mode it is in. No transition runs until `work` settles, nor, when it answers one, until `holdUntil` settles.
107
+ */
108
+ step<T>(generation: number, work: (mode: OpsMode) => Promise<TurnStep<T>>): Promise<StepResult<T>>;
109
+ }
110
+ /** One invocation's view of the barrier: the gate that admits and counts its work, and its write fence. */
111
+ export declare class BarrierEvent implements InvocationGate {
112
+ #private;
113
+ constructor(barrier: MaintenanceBarrier, generation: number | null, mode: OpsMode);
114
+ admit(kind: InvocationKind): InvocationAdmission | null;
115
+ /** Whether this invocation may commit a write now: still `open`, at the generation it was admitted under. */
116
+ writable(): boolean;
117
+ }
@@ -1,6 +1,8 @@
1
1
  import { type ApplicationObjects, type OpsBootFailureContent, type OpsOperation } from '@fabrika/auth-core';
2
- import type { SqliteCursor, SqliteValue } from '@fabrika/db/sqlite';
3
- /** What the view reads of the object's storage; workerd's `DurableObjectStorage` has both optional members. */
2
+ import type { SqliteCursor, SqliteStorage, SqliteValue } from '@fabrika/db/sqlite';
3
+ import type { SqliteMigrationBundle } from '@fabrika/db/sqlite-migrate';
4
+ import type { MaintenanceBarrier } from './maintenance.js';
5
+ /** What the view reads of the object's storage; workerd's `DurableObjectStorage` has every optional member. */
4
6
  export interface OpsStorage {
5
7
  readonly sql: {
6
8
  exec(query: string, ...bindings: SqliteValue[]): SqliteCursor;
@@ -9,6 +11,27 @@ export interface OpsStorage {
9
11
  };
10
12
  /** The bun:sqlite test double has no alarm. */
11
13
  getAlarm?(): Promise<number | null>;
14
+ /** The object's KV storage, which point-in-time recovery rewinds with its SQLite; the bun:sqlite double has none. */
15
+ get?(key: string): Promise<unknown>;
16
+ put?(key: string, value: unknown): Promise<void>;
17
+ /** The synchronous KV of a SQLite-backed object, in the same database; the bun:sqlite test double has none. */
18
+ readonly kv?: {
19
+ get(key: string): unknown;
20
+ put(key: string, value: unknown): void;
21
+ delete(key: string): boolean;
22
+ };
23
+ /** Wipes the object's database, its KV and its alarm; the bun:sqlite test double has none. */
24
+ deleteAll?(): Promise<void>;
25
+ }
26
+ /**
27
+ * The object's point-in-time recovery: workerd's storage bookmarks and the abort that resets the object. `null` where the
28
+ * storage has none (the bun:sqlite double, a runtime without PITR).
29
+ */
30
+ export interface OpsRecovery {
31
+ getCurrentBookmark(): Promise<string>;
32
+ getBookmarkForTime(time: number): Promise<string>;
33
+ onNextSessionRestoreBookmark(bookmark: string): Promise<string>;
34
+ abort(reason: string): void;
12
35
  }
13
36
  /** `X-Fabrika-Endpoint` of the composed ops row, the only value an ops request may carry (ADR-0022 rule 3). */
14
37
  export declare const OPS_ENDPOINT: string;
@@ -21,16 +44,28 @@ export interface OpsAccess {
21
44
  export declare function opsAccess(env: Readonly<Record<string, unknown>>): OpsAccess | null;
22
45
  /** What an ops request reads of the object it reached. */
23
46
  export interface OpsTarget {
24
- readonly storage: OpsStorage;
47
+ readonly storage: OpsStorage & SqliteStorage;
48
+ /** The environment's bucket (the `FABRIKA_FILES` R2 binding), where dumps and the maintenance state live. */
49
+ readonly bucket: unknown;
50
+ readonly recovery: OpsRecovery | null;
51
+ /** The digest of the contract this release was deployed with (`FABRIKA_CONTRACT_DIGEST`); a dump's manifest records it. */
52
+ readonly contractDigest: string | null;
53
+ /** The release's migration bundles in the order the object applies them: the framework's, then the application's. */
54
+ readonly migrations: readonly SqliteMigrationBundle[];
25
55
  /**
26
56
  * The instance's last failed boot, the application's error text included. Asked only after authentication: it
27
57
  * waits for a boot under way and never starts one.
28
58
  */
29
59
  bootFailure(): Promise<OpsBootFailureContent | null>;
60
+ /** The barrier of the object named `object`, read from R2 on a cold start; rejects while R2 cannot be read. */
61
+ maintenance(object: string): Promise<MaintenanceBarrier>;
62
+ /** Runs the pending migrations and boots the application; `false` when the boot failed. */
63
+ migrate(): Promise<boolean>;
30
64
  }
31
65
  /**
32
66
  * Answers an ops request the Worker forwarded with the proxy secret, which the object checked before. Authentication
33
- * runs first; an unknown operation, a malformed body and an object name the list lacks are refused after it.
67
+ * runs first; an unknown operation, a malformed body and an object name the list lacks are refused after it. Every
68
+ * operation needs the barrier, so while R2 cannot be read each answers 503.
34
69
  */
35
70
  export declare function serveOps(request: Request, access: OpsAccess | null, target: OpsTarget): Promise<Response>;
36
71
  /** The object an ops request names, read with its operation's strict parser; `null` for a body that does not parse. */
@@ -0,0 +1,9 @@
1
+ import { type OpsRestoreRequest } from '@fabrika/auth-core';
2
+ import type { MaintenanceBarrier } from './maintenance.js';
3
+ import type { OpsTarget } from './ops.js';
4
+ /**
5
+ * One step of the original object's point-in-time restore (ADR-0070 §9 step 6). `prepare` and `arm` run in the
6
+ * barrier's turn, only under the published generation, on an object that is not the one ordinary traffic reaches
7
+ * (`serving`), while it is `inspect`; `verify` writes nothing and runs in any mode.
8
+ */
9
+ export declare function serveRestore(target: OpsTarget, barrier: MaintenanceBarrier, step: OpsRestoreRequest, serving: boolean): Promise<Response>;
@@ -0,0 +1,29 @@
1
+ import { type OpsTimersRequest, type OpsTimersView } from '@fabrika/auth-core';
2
+ import { type Scrubber } from '../jobs/scrub.js';
3
+ /** The global timers the tracker wraps while it is on; `globalThis` fits it. */
4
+ export interface TimerScope {
5
+ setTimeout(handler: unknown, delay?: unknown, ...args: unknown[]): unknown;
6
+ setInterval(handler: unknown, delay?: unknown, ...args: unknown[]): unknown;
7
+ clearTimeout(id?: unknown): void;
8
+ clearInterval(id?: unknown): void;
9
+ }
10
+ export interface TimerTracker {
11
+ /** Switches tracking on (wrapping the scope's timers) or off (restoring them and forgetting every record). */
12
+ track(on: boolean): void;
13
+ /**
14
+ * While tracking is on, records `promise` until it settles and answers a chain that settles as it does, rejection
15
+ * included, so the caller hands the chain to `waitUntil` and an unhandled rejection stays unhandled. Off, `promise`.
16
+ */
17
+ pending<T>(promise: Promise<T>): Promise<T>;
18
+ /** The live records, oldest first, at most `OPS_TIMERS_CAP` of them. */
19
+ view(): OpsTimersView;
20
+ }
21
+ /** A tracker over `scope`'s timers, off until `track(true)`; each stack is scrubbed by `scrubber`. */
22
+ export declare function timerTracker(scope: TimerScope, now: () => number, scrubber: Scrubber): TimerTracker;
23
+ /**
24
+ * Records a promise an object hands to `waitUntil` while the tracker is on. Hand the answer, not `promise`, to
25
+ * `waitUntil`: it rejects as `promise` does, so an unhandled rejection still reaches the crash reporting.
26
+ */
27
+ export declare function trackPending<T>(promise: Promise<T>): Promise<T>;
28
+ /** The isolate's live timers and `waitUntil` promises; `track` switches the isolate's tracker on or off first. */
29
+ export declare function serveTimers(request: OpsTimersRequest): Response;
@@ -35,7 +35,8 @@ export interface ContractWorker {
35
35
  /**
36
36
  * The Worker module of a contract application, called only by the generated entrypoint, which also exports
37
37
  * `FabrikaApplication`. The application runs in the environment's Durable Object (ADR-0065): `fetch` forwards every
38
- * request to it with the proxy secret, the proxy's own headers unchanged, and `scheduled` forwards the minute tick.
38
+ * request to it with the proxy secret, the proxy's own headers unchanged, and `scheduled` forwards the repair tick: the
39
+ * object's alarm runs the jobs, and the tick repairs its wakes and arms an alarm nothing armed yet.
39
40
  * An ops request goes to the object its body names instead (ADR-0069). The object captures the environment, imports
40
41
  * the application and boots it.
41
42
  */
@@ -1,5 +1,7 @@
1
1
  import { type ContractArtifact, type OutputShape, type SchemaShape } from '@fabrika/auth-core';
2
2
  import { z } from 'zod/v4';
3
+ /** A file's object key starts with its kind: the framework keeps its own objects in the files bucket under this prefix. */
4
+ export declare const RESERVED_FILE_KIND_PREFIX = "__fabrika";
3
5
  /** A `SchemaShape` read back as JSON. */
4
6
  export declare const schemaShapeSchema: z.ZodType<SchemaShape>;
5
7
  export declare const outputShapeSchema: z.ZodType<OutputShape>;
@@ -91,14 +91,24 @@ export type SqlValue = string | number | boolean | bigint | Date | null | readon
91
91
  export interface SqlTag<Ix extends AnyDbIndex = AnyDbIndex, M extends SqlMode = SqlMode> {
92
92
  <Row extends Schema>(row: Row): (text: TemplateStringsArray, ...values: readonly (SqlValue | SqlScope)[]) => Promise<z.output<Row>[]>;
93
93
  /**
94
- * The capability's whole predicate on `table` (`alias` its name in the statement, the table's by default): the
95
- * object's key and every link of its chain for a `Ref`, what `ctx.db.within` matches for a `Within`, every row for
96
- * `ctx.app`. Interpolated as `where ${ctx.sql.scope(ctx.target, 'tasks', 't')}`, its values are bound parameters.
97
- * A table the capability reaches for no use of this site is a type error here; at run time the fragment on the
98
- * statement's UPDATE or DELETE target needs that operation's action, and anywhere else an action the table reads
99
- * with.
94
+ * The capability's whole predicate on `table`: the object's key and every link of its chain for a `Ref`, what
95
+ * `ctx.db.within` matches for a `Within`, every row for `ctx.app`. Interpolated as
96
+ * `where ${ctx.sql.scope(ctx.target, 'tasks', { alias: 't' })}`, its values are bound parameters. `alias` is the
97
+ * table's name in the statement (the table's own by default). `use` states what the statement does with the table:
98
+ * `'read'` (the default) needs an action the table reads with, `'update'` or `'delete'` (a `'write'` site only) that
99
+ * operation's action, checked when the fragment is built. The statement is not read for where the fragment stands:
100
+ * using it as stated is the author's and the approver's to check. A table the capability reaches for no use of this
101
+ * site is a type error here.
100
102
  */
101
- scope<C extends Ref<string, string> | Within<string, string> | AppCapability<string>, T extends FragmentTable<Ix, C, M>>(capability: C, table: T, alias?: string): SqlScope;
103
+ scope<C extends Ref<string, string> | Within<string, string> | AppCapability<string>, T extends FragmentTable<Ix, C, M>>(capability: C, table: T, options?: SqlScopeOptions): SqlScope;
104
+ }
105
+ /**
106
+ * The third argument of `ctx.sql.scope`: the table's alias in the statement, and what the statement does with it. A
107
+ * `'read'` site's `ctx.sql` is refused `'update'` and `'delete'` at run time; a `'write'` site's stays assignable to it.
108
+ */
109
+ export interface SqlScopeOptions {
110
+ readonly alias?: string;
111
+ readonly use?: 'read' | 'update' | 'delete';
102
112
  }
103
113
  declare const sqlScope: unique symbol;
104
114
  /** What `ctx.sql.scope(…)` builds: only the framework makes one, and only its own tag takes it. */
@@ -369,13 +379,18 @@ export type PublicContext<K extends KitTypes, Kind extends DataKind, Acts extend
369
379
  } & NoMail;
370
380
  /**
371
381
  * `ctx.kick('<job>')` of a site that declares `kicks`: the job runs in the background after the site's transaction
372
- * committed, once however often it is kicked, and not at all on a rollback.
382
+ * committed, once however often it is kicked, and not at all on a rollback. `ctx.kick('<job>', { at })` runs it at `at`
383
+ * instead. Either way the kick is a durable wake written in the site's transaction, and it carries nothing.
373
384
  */
374
385
  export type KickContext<Ks> = [Ks] extends [never] ? {
375
386
  readonly kick: Unavailable<"declare kicks: ['<cron job>'] on this site to kick a job after its commit">;
376
387
  } : Ks extends readonly (infer N extends string)[] ? {
377
- kick(job: N): void;
388
+ kick(job: N, options?: KickOptions): void;
378
389
  } : never;
390
+ /** When a kicked job runs: at `at`, a `Date`; without options, as soon as the site committed. */
391
+ export interface KickOptions {
392
+ readonly at: Date;
393
+ }
379
394
  /** `ctx.tokens.sign('<purpose>', claims, { days })` of a site that declares `signs`: a token of one of those purposes. */
380
395
  export type TokensContext<K extends KitTypes, Sg> = [Sg] extends [never] ? {
381
396
  readonly tokens: Unavailable<"declare signs: ['<token purpose>'] on this site to sign its tokens">;
@@ -22,6 +22,16 @@ export declare const PROCEDURE_LIMITS: {
22
22
  /** The headers of one part of a multipart body, at most. */
23
23
  readonly maxPartHeaderBytes: number;
24
24
  };
25
+ /**
26
+ * The slowest body a procedure or a webhook waits for: its deadline is `maxBytes` at `bytesPerSecond`, `minMs` at least.
27
+ * The handler's own `timeoutMs` starts after the last byte, so the approval diff names both.
28
+ */
29
+ export declare const BODY_DEADLINE: {
30
+ readonly bytesPerSecond: number;
31
+ readonly minMs: 30000;
32
+ };
33
+ /** How long a body of at most `maxBytes` may take to arrive. */
34
+ export declare function bodyDeadlineMs(maxBytes: number): number;
25
35
  /**
26
36
  * A procedure with file fields is `multipart/form-data`: its JSON input travels in the first part, named `input`, and
27
37
  * each file in a part named after its field. A field of several files sends one part per file, under its name.
@@ -37,7 +47,15 @@ export declare const WEBHOOK_LIMITS: {
37
47
  readonly maxMaxBytes: number;
38
48
  readonly timeoutMs: 10000;
39
49
  };
40
- /** A job attempt's time limit (`limits.timeoutMs`) and its ceiling, which keeps a lease and a timer within a day. */
50
+ /**
51
+ * The longest job segment on Cloudflare: setup, one attempt and its finish. A framework policy inside the 15 minutes
52
+ * `waitUntil` keeps an object alive, not a platform guarantee; longer work chunks through claims.
53
+ */
54
+ export declare const CLOUDFLARE_MAX_JOB_SEGMENT_MS: number;
55
+ /**
56
+ * A job attempt's time limit (`limits.timeoutMs`) and its ceiling, which keeps a lease and a timer within a day. The
57
+ * default is one Cloudflare segment, so a job that declares no limit deploys on either provider.
58
+ */
41
59
  export declare const JOB_LIMITS: {
42
60
  readonly timeoutMs: number;
43
61
  readonly maxTimeoutMs: number;
@@ -5,7 +5,7 @@ import type { TokenPurposes } from './token';
5
5
  export type Path = `/${string}`;
6
6
  /** Whether `value` is written as a `Path`; what `buildArtifact` refuses of one is a separate check. */
7
7
  export declare function isPath(value: string): value is Path;
8
- /** A job attempt's time limit: 15 minutes by default, at most a day. A job reads no body, so it has no `maxBytes`. */
8
+ /** A job attempt's time limit: 14 minutes by default, at most a day. A job reads no body, so it has no `maxBytes`. */
9
9
  export interface JobLimitsOption {
10
10
  readonly timeoutMs?: number;
11
11
  }