@fabrika/app 0.9.0-dev.4 → 0.9.0-dev.6

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 (113) hide show
  1. package/package.json +9 -9
  2. package/skill/SKILL.md +41 -14
  3. package/skill/references/app-setup.md +43 -12
  4. package/skill/references/dev.md +2 -1
  5. package/skill/references/endpoint.md +30 -24
  6. package/skill/references/errors.md +40 -35
  7. package/skill/references/files.md +4 -2
  8. package/skill/references/jobs.md +21 -4
  9. package/skill/references/table-and-migration.md +19 -2
  10. package/skill/references/tests.md +40 -1
  11. package/skill/references/webhooks-links-connectors.md +1 -1
  12. package/src/build-recipe.ts +198 -0
  13. package/src/build.ts +60 -4
  14. package/src/bun.ts +181 -13
  15. package/src/cloudflare/application.ts +822 -0
  16. package/src/cloudflare/bindings.ts +159 -0
  17. package/src/cloudflare/export.ts +621 -0
  18. package/src/cloudflare/import.ts +1013 -0
  19. package/src/cloudflare/maintenance.ts +518 -0
  20. package/src/cloudflare/names.ts +16 -0
  21. package/src/cloudflare/ops.ts +375 -0
  22. package/src/cloudflare/r2-files.ts +172 -0
  23. package/src/cloudflare/restore.ts +167 -0
  24. package/src/cloudflare/tracker.ts +192 -0
  25. package/src/cloudflare.ts +100 -146
  26. package/src/contract/app-id.ts +5 -0
  27. package/src/contract/artifact-schema.ts +9 -1
  28. package/src/contract/build.ts +40 -2
  29. package/src/contract/compile.ts +1 -0
  30. package/src/contract/context.ts +35 -9
  31. package/src/contract/declaration.ts +2 -0
  32. package/src/contract/defaults.ts +22 -2
  33. package/src/contract/define.ts +29 -3
  34. package/src/contract/kit.ts +4 -1
  35. package/src/contract/platform.ts +3 -2
  36. package/src/contract/vocabulary.ts +26 -8
  37. package/src/dev/launcher.ts +50 -4
  38. package/src/disk-assets.ts +8 -3
  39. package/src/files/archive.ts +2 -2
  40. package/src/files/job-names.ts +12 -0
  41. package/src/files/kinds.ts +73 -31
  42. package/src/files/scan.ts +3 -4
  43. package/src/files/streams.ts +3 -1
  44. package/src/implement/anonymous.ts +12 -11
  45. package/src/implement/boot.ts +75 -6
  46. package/src/implement/bounded.ts +21 -2
  47. package/src/implement/capability.ts +15 -3
  48. package/src/implement/dispatch.ts +419 -177
  49. package/src/implement/failures.ts +17 -1
  50. package/src/implement/faults.ts +1 -0
  51. package/src/implement/index.ts +1 -0
  52. package/src/implement/invocation.ts +58 -10
  53. package/src/implement/principal.ts +25 -2
  54. package/src/implement/terminals.ts +93 -0
  55. package/src/implement/workload.ts +42 -16
  56. package/src/jobs/mail.ts +8 -0
  57. package/src/jobs/report.ts +5 -1
  58. package/src/jobs/runner.ts +672 -113
  59. package/src/jobs/schedule.ts +7 -1
  60. package/src/jobs/scrub.ts +14 -1
  61. package/src/jobs/types.ts +6 -0
  62. package/src/spa-fallback.ts +12 -0
  63. package/src/testing/endpoint-access.ts +307 -152
  64. package/src/testing/isolation.ts +8 -1
  65. package/src/testing/kit.ts +80 -2
  66. package/src/testing/proxy.ts +15 -10
  67. package/types/src/build-recipe.d.ts +70 -0
  68. package/types/src/build.d.ts +19 -1
  69. package/types/src/bun.d.ts +34 -1
  70. package/types/src/cloudflare/application.d.ts +73 -0
  71. package/types/src/cloudflare/bindings.d.ts +33 -0
  72. package/types/src/cloudflare/export.d.ts +16 -0
  73. package/types/src/cloudflare/import.d.ts +51 -0
  74. package/types/src/cloudflare/maintenance.d.ts +117 -0
  75. package/types/src/cloudflare/names.d.ts +11 -0
  76. package/types/src/cloudflare/ops.d.ts +81 -0
  77. package/types/src/cloudflare/r2-files.d.ts +9 -0
  78. package/types/src/cloudflare/restore.d.ts +9 -0
  79. package/types/src/cloudflare/tracker.d.ts +29 -0
  80. package/types/src/cloudflare.d.ts +12 -18
  81. package/types/src/contract/app-id.d.ts +2 -0
  82. package/types/src/contract/artifact-schema.d.ts +2 -0
  83. package/types/src/contract/context.d.ts +35 -11
  84. package/types/src/contract/declaration.d.ts +4 -0
  85. package/types/src/contract/defaults.d.ts +19 -1
  86. package/types/src/contract/define.d.ts +20 -3
  87. package/types/src/contract/kit.d.ts +2 -1
  88. package/types/src/contract/platform.d.ts +2 -2
  89. package/types/src/contract/vocabulary.d.ts +9 -7
  90. package/types/src/disk-assets.d.ts +4 -1
  91. package/types/src/files/job-names.d.ts +9 -0
  92. package/types/src/files/kinds.d.ts +21 -14
  93. package/types/src/files/scan.d.ts +1 -3
  94. package/types/src/implement/anonymous.d.ts +2 -4
  95. package/types/src/implement/boot.d.ts +17 -1
  96. package/types/src/implement/bounded.d.ts +11 -1
  97. package/types/src/implement/capability.d.ts +4 -2
  98. package/types/src/implement/dispatch.d.ts +34 -1
  99. package/types/src/implement/failures.d.ts +5 -0
  100. package/types/src/implement/faults.d.ts +1 -0
  101. package/types/src/implement/index.d.ts +1 -0
  102. package/types/src/implement/invocation.d.ts +22 -7
  103. package/types/src/implement/principal.d.ts +6 -1
  104. package/types/src/implement/terminals.d.ts +33 -0
  105. package/types/src/implement/workload.d.ts +5 -0
  106. package/types/src/jobs/runner.d.ts +66 -2
  107. package/types/src/jobs/schedule.d.ts +2 -0
  108. package/types/src/jobs/types.d.ts +6 -0
  109. package/types/src/spa-fallback.d.ts +2 -0
  110. package/types/src/testing/endpoint-access.d.ts +37 -5
  111. package/types/src/testing/isolation.d.ts +1 -1
  112. package/types/src/testing/kit.d.ts +22 -1
  113. package/types/src/testing/proxy.d.ts +4 -4
@@ -16,18 +16,22 @@ import {
16
16
  FABRIKA_IAM_ISSUER,
17
17
  FABRIKA_TOKEN_KEYS,
18
18
  type IamMembershipRpc,
19
+ type IamTerminalRpc,
19
20
  isNormalizedMailbox,
20
21
  type Jwks,
21
22
  MAX_ACCESS_TOKEN_BYTES,
23
+ MAX_APPLICATION_TOKEN_BYTES,
22
24
  normalizeEmailIdentity,
23
25
  type PermissionEntry,
24
26
  PROXY_TOKEN_HEADER,
25
27
  SESSION_COOKIE,
28
+ type TerminalFailure,
26
29
  TOKEN_ALG,
27
30
  UNTRUSTED_FORWARD_HEADERS,
28
31
  workloadKeyVariable,
29
32
  } from '@fabrika/auth-core'
30
33
  import type { Database } from '@fabrika/db'
34
+ import { frameworkTablesOf, type LeaseFence } from '@fabrika/db/framework'
31
35
  import { refuseInProduction } from '@fabrika/db/production'
32
36
  import { MemoryEmailSender } from '@fabrika/email/memory'
33
37
  import type { FileObjectStore } from '@fabrika/platform'
@@ -78,6 +82,14 @@ import {
78
82
  import { endpointProxy } from './proxy'
79
83
 
80
84
  export const TEST_ISSUER = 'https://iam.test'
85
+
86
+ /** The kit's IAM without a terminal: no identification is open, so every one is `not_found`. */
87
+ const noIdentification = (): Promise<TerminalFailure> => Promise.resolve({ ok: false, reason: 'not_found' })
88
+ const NO_IDENTIFICATIONS: IamTerminalRpc = Object.freeze({
89
+ inspectIdentification: noIdentification,
90
+ assertIdentity: noIdentification,
91
+ cancelIdentification: noIdentification,
92
+ })
81
93
  export const TEST_ENVIRONMENT = 'test'
82
94
  const KEY_ID = 'test-key'
83
95
  const TOKEN_TTL_SECONDS = 300
@@ -112,6 +124,11 @@ export interface TestKitOptions {
112
124
  * kit's proxy obtains each delegation grant from it. Without it the kit's IAM answers them under IAM's rules.
113
125
  */
114
126
  readonly membership?: IamMembershipRpc
127
+ /**
128
+ * IAM's identifications at a terminal (ADR-0067), for a contract that declares one. Without it the kit's IAM knows no
129
+ * open identification: `inspect` answers null and `assert` `not_found`.
130
+ */
131
+ readonly terminals?: IamTerminalRpc
115
132
  /**
116
133
  * Each import's owner, by the import's name: its origin and edge key, which the platform writes as the import's
117
134
  * framework variables, and how a request reaches it — usually the owner kit's `fetch`.
@@ -181,6 +198,15 @@ export interface TestKit<C extends AnyContract> {
181
198
  runJob(name: JobName<C> | typeof FILE_SCAN_JOB | typeof FILE_SWEEP_JOB, options?: JobRunOptions): Promise<JobRunResult>
182
199
  /** Waits for the work requests left running: the runs a site's `ctx.kick` sent, a failure's report. */
183
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[]>
184
210
  /**
185
211
  * The stand-in for every job's transport: what reached it (`accepted`, `handoffs`) and its faults (`refuse`,
186
212
  * `unavailable`, `unreachable`, `loseAnswers`, `during`, `heal`). Each message carries the transport key,
@@ -202,6 +228,12 @@ export interface TestKit<C extends AnyContract> {
202
228
  solveChallenge(procedure: object): Promise<string>
203
229
  }
204
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
+
205
237
  /** The names of the contract's cron jobs. */
206
238
  export type JobName<C> = C extends { readonly surface: { readonly jobs: infer J } } ? keyof J & string : never
207
239
 
@@ -428,6 +460,7 @@ export function bootTestKit<C extends AnyContract>(
428
460
  ...dev,
429
461
  ...(options.revealHandlerErrors === undefined ? {} : { revealHandlerErrors: options.revealHandlerErrors }),
430
462
  membership,
463
+ terminals: options.terminals ?? (artifact.terminal === undefined ? undefined : NO_IDENTIFICATIONS),
431
464
  connectBindings,
432
465
  workloadTokens,
433
466
  mailStandIn: options.mail === 'none' ? 'none' : mail,
@@ -523,7 +556,7 @@ export function bootTestKit<C extends AnyContract>(
523
556
 
524
557
  const scope = <D extends DimensionOf<C>>(dimension: D, value: string): TestScope<D> => Object.freeze({ type: dimension, value })
525
558
 
526
- /** The caller's token, or why IAM signs none: a disabled principal, or a token above `MAX_ACCESS_TOKEN_BYTES`. */
559
+ /** The caller's token, or why IAM signs none: a disabled principal, or a token above IAM's bound for it. */
527
560
  async function mint(caller: TestCaller): Promise<{ readonly ok: true; readonly token: string; readonly expiresAt: number } | MintRefusal> {
528
561
  if (caller.disabled) return { ok: false, reason: 'disabled' }
529
562
  const now = Math.floor(Date.now() / 1000)
@@ -542,7 +575,8 @@ export function bootTestKit<C extends AnyContract>(
542
575
  })
543
576
  const { privateKey } = await signing
544
577
  const token = await new SignJWT({ ...claims }).setProtectedHeader({ alg: TOKEN_ALG, kid: KEY_ID }).sign(privateKey)
545
- if (token.length > MAX_ACCESS_TOKEN_BYTES) return { ok: false, reason: 'token_too_large' }
578
+ // IAM bounds a workload's own token as any installation token, and a token the proxy injects at the application's.
579
+ if (token.length > (caller.app === null ? MAX_APPLICATION_TOKEN_BYTES : MAX_ACCESS_TOKEN_BYTES)) return { ok: false, reason: 'token_too_large' }
546
580
  byToken.set(token, { caller, expiresAt: claims.exp })
547
581
  return { ok: true, token, expiresAt: claims.exp }
548
582
  }
@@ -675,6 +709,49 @@ export function bootTestKit<C extends AnyContract>(
675
709
  return application.jobs.run(name, runOptions)
676
710
  }
677
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
+
678
755
  const acceptInvitation = (invitationId: string, person?: LabelledTestCaller): LabelledTestCaller => {
679
756
  if (standIn === null) {
680
757
  throw new Error('this kit was given its own membership transport, so its IAM holds no invitation to accept')
@@ -707,6 +784,7 @@ export function bootTestKit<C extends AnyContract>(
707
784
  iam,
708
785
  runJob,
709
786
  drain,
787
+ runDueJobs,
710
788
  acceptInvitation,
711
789
  mail,
712
790
  mailKeyScope,
@@ -19,18 +19,18 @@ import {
19
19
  type TokenCache,
20
20
  } from '@fabrika/proxy-core'
21
21
  import { applyCrossOriginHeaders, crossOriginHeaders } from '@fabrika/proxy-core/headers'
22
- import { contractProxyTable } from '@fabrika/proxy-core/manifest'
22
+ import { contractProxyEntry, contractProxyTable } from '@fabrika/proxy-core/manifest'
23
23
 
24
24
  /** What the proxy did with a request: answered it itself, or forwarded it with what only the proxy may set. */
25
25
  export type ProxyOutcome =
26
26
  | {
27
27
  readonly outcome: 'forward'
28
- /** Every header only the proxy may assert, with the value the decision gave it. */
29
- readonly asserted: ReadonlyMap<string, string>
30
28
  /**
31
- * Whether the request's own `Authorization` reaches the application: not on an anonymous endpoint, except a webhook
32
- * row the decision marked to pass it on.
29
+ * Every header only the proxy may assert, with the value the decision gave it. A credentialed request that carried
30
+ * `Authorization` has it replaced by the minted token, so the caller's `px_` key never reaches the application.
33
31
  */
32
+ readonly asserted: ReadonlyMap<string, string>
33
+ /** Whether the request's own `Authorization` reaches the application: only on a webhook row the decision marked to pass it on. */
34
34
  readonly keepsAuthorization: boolean
35
35
  /** What the application's answer is given for an admitted cross-origin request, over its own headers. */
36
36
  readonly decorate: (headers: Headers) => void
@@ -66,14 +66,14 @@ const ASSERTED_HEADERS = [PROXY_TOKEN_HEADER, REQUEST_ID_HEADER, ENDPOINT_HEADER
66
66
  export function endpointProxy(options: EndpointProxyOptions): TestProxy {
67
67
  const verify = createVerifyService({
68
68
  manifest: {
69
- apps: [{
69
+ apps: [contractProxyEntry({
70
70
  id: options.appId,
71
71
  hosts: [options.host],
72
72
  upstream: 'app',
73
73
  scheme: 'https',
74
- ...contractProxyTable(options.artifact),
75
- ...(options.crossOrigins === undefined || options.crossOrigins.length === 0 ? {} : { crossOrigins: [...options.crossOrigins] }),
76
- }],
74
+ table: contractProxyTable(options.artifact),
75
+ ...(options.crossOrigins === undefined ? {} : { crossOrigins: options.crossOrigins }),
76
+ })],
77
77
  },
78
78
  iam: options.iam,
79
79
  issuer: options.issuer,
@@ -105,10 +105,15 @@ export function endpointProxy(options: EndpointProxyOptions): TestProxy {
105
105
  asserted.set(header, value)
106
106
  }
107
107
  }
108
+ const keepsAuthorization = verification.headers.get(FORWARD_AUTHORIZATION_HEADER) === '1'
109
+ const minted = asserted.get(PROXY_TOKEN_HEADER)
110
+ if (!keepsAuthorization && minted !== undefined && request.headers.has('Authorization')) {
111
+ asserted.set('Authorization', `Bearer ${minted}`)
112
+ }
108
113
  return {
109
114
  outcome: 'forward',
110
115
  asserted,
111
- keepsAuthorization: asserted.has(PROXY_TOKEN_HEADER) || verification.headers.get(FORWARD_AUTHORIZATION_HEADER) === '1',
116
+ keepsAuthorization,
112
117
  decorate: (answer) => {
113
118
  if (allowOrigin !== null) applyCrossOriginHeaders(answer, crossOriginHeaders(allowOrigin))
114
119
  },
@@ -0,0 +1,70 @@
1
+ export { CONTRACT_APP_ID_PATTERN } from './contract/app-id.js';
2
+ export { FILE_SCAN_JOB, FILE_SWEEP_JOB } from './files/job-names.js';
3
+ /** The TypeScript release of the platform's type check; the application's own `typescript` is not run. */
4
+ export declare const PLATFORM_TYPESCRIPT_VERSION = "5.9.3";
5
+ /** A `c.cron` job name, which a crontab line carries unquoted. */
6
+ export declare const CONTRACT_JOB_NAME_PATTERN: RegExp;
7
+ /** Five cron fields of digits and `*`, `/`, `,`, `-` only. */
8
+ export declare const CRON_SCHEDULE_PATTERN: RegExp;
9
+ /** What one contract application's recipe depends on. `contractRecipe` refuses a value that a shell would read as more. */
10
+ export interface ContractRecipeInput {
11
+ readonly appId: string;
12
+ /** The `@fabrika/check` release whose reader read the application (ADR-0062). */
13
+ readonly checkRelease: string;
14
+ /** The absolute directory the build runs in: the checker reads the source there. */
15
+ readonly sourceRoot: string;
16
+ /** The absolute directory the built application runs from: each generated script starts there. */
17
+ readonly runtimeRoot: string;
18
+ /** With a database, every container migrates and checks its schema before the server starts. */
19
+ readonly database: boolean;
20
+ /** Whether the build uploads its source maps, last and never failing the build. */
21
+ readonly sourceMaps: boolean;
22
+ readonly jobs: readonly {
23
+ readonly name: string;
24
+ readonly schedule: string;
25
+ }[];
26
+ /** The contract declares a file collection: the sweep of removed files is scheduled. */
27
+ readonly files: boolean;
28
+ /** A file collection scans its uploads: the scan pass is scheduled. */
29
+ readonly scan: boolean;
30
+ }
31
+ /** One build step: a command run in the source root, or a generated file written there, line by line. */
32
+ export type ContractBuildStep = {
33
+ readonly run: string;
34
+ } | {
35
+ readonly write: string;
36
+ readonly lines: readonly string[];
37
+ };
38
+ /** One check of the build: a command run in the source root that fails the build. */
39
+ export interface ContractCheck {
40
+ readonly name: 'tests' | 'tsc' | 'fabrika-check';
41
+ readonly command: string;
42
+ }
43
+ export interface ContractRecipe {
44
+ /** The steps after the authored SPA commands, in order. */
45
+ readonly build: readonly ContractBuildStep[];
46
+ /** The checks among `build`, in its order. */
47
+ readonly checks: readonly ContractCheck[];
48
+ /** The generated scripts every container runs before `start`, in order; any failure stops the activation. */
49
+ readonly init: readonly string[];
50
+ /** The generated script that starts the server, which only `exec`s it. */
51
+ readonly start: string;
52
+ /** The command the start script `exec`s, run from the runtime root. */
53
+ readonly serve: readonly string[];
54
+ /** The command that migrates the application's database, run from the runtime root. */
55
+ readonly migrate: readonly string[];
56
+ /** The jobs to schedule, each on one container; a command runs from the runtime root. */
57
+ readonly jobs: readonly {
58
+ readonly schedule: string;
59
+ readonly command: string;
60
+ }[];
61
+ }
62
+ /**
63
+ * The recipe of one contract application. The application's tests run first: they are authored code, so everything
64
+ * after them is reinstalled, regenerated or checked again. They run `--isolate`, as the application skill runs them: a
65
+ * test file's DOM globals otherwise leak into the next file. `tsc` runs before the checker, as in the skill's loop: the
66
+ * usual quick fix of a type error is a cast or an `any`, which only the checker refuses, so the checker is the last word
67
+ * on the code. The build has no database, so the schema checks run as init scripts, after the migrations and before the
68
+ * readiness window opens.
69
+ */
70
+ export declare function contractRecipe(input: ContractRecipeInput): ContractRecipe;
@@ -4,8 +4,26 @@ export declare const CONTRACT_FILE = "fabrika.contract.ts";
4
4
  export declare const GENERATED_ENTRY_FILE = "fabrika/entry.generated.ts";
5
5
  /** The module whose default export is `serve(contract, …)`, relative to the application root. */
6
6
  export declare const IMPLEMENTATION_FILE = "src/app.ts";
7
+ /** The application's migrations as a module, relative to the application root: a Worker reads no file system. */
8
+ export declare const GENERATED_MIGRATIONS_FILE = "fabrika/migrations.generated.ts";
9
+ /** Where an application keeps its migrations, relative to its root; `fabrika db new` writes there. */
10
+ export declare const MIGRATIONS_DIRECTORY = "db/migrations";
7
11
  export type EntryRuntime = 'bun' | 'cloudflare';
12
+ export * from './build-recipe.js';
13
+ export { CLOUDFLARE_APPLICATION_BINDING, CLOUDFLARE_APPLICATION_CLASS, CLOUDFLARE_ASSETS_BINDING, CLOUDFLARE_FILES_BINDING, } from './cloudflare/names.js';
8
14
  /** The entrypoint source for one runtime. */
9
15
  export declare function generatedEntry(runtime: EntryRuntime): string;
10
- /** Writes the entrypoint under `root` and returns its path. */
16
+ /** Writes the entrypoint under `root` and returns its path; the Cloudflare one also writes the migrations module it imports. */
11
17
  export declare function writeGeneratedEntry(root: string, runtime: EntryRuntime): Promise<string>;
18
+ /** The application's migrations under `root`, every `.sql` file of `db/migrations` by name; none without the directory. */
19
+ export declare function applicationMigrations(root: string): Promise<readonly {
20
+ readonly name: string;
21
+ readonly sql: string;
22
+ }[]>;
23
+ /** The migrations module source: the files' names and texts, verbatim, so their checksums stay the files'. */
24
+ export declare function generatedMigrations(migrations: readonly {
25
+ readonly name: string;
26
+ readonly sql: string;
27
+ }[]): string;
28
+ /** Writes the migrations module under `root` and returns its path. */
29
+ export declare function writeGeneratedMigrations(root: string): Promise<string>;
@@ -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.
@@ -0,0 +1,73 @@
1
+ import { type SqliteStorage } from '@fabrika/db/sqlite';
2
+ import { type CrashEvents } from '../implement/crashes.js';
3
+ import type { ContractImplementation } from '../implement/implement.js';
4
+ import { type JobClock } from '../jobs/runner.js';
5
+ import { type OpsRecovery, type OpsStorage } from './ops.js';
6
+ /** The application module, imported only after the environment was captured: the generated entrypoint's `import()`. */
7
+ export type ImplementationLoader = () => Promise<{
8
+ readonly default: ContractImplementation;
9
+ }>;
10
+ /** One of the application's SQLite migrations, as `fabrika app build` bundles them from `db/migrations`. */
11
+ export interface ApplicationMigration {
12
+ readonly name: string;
13
+ readonly sql: string;
14
+ }
15
+ export interface ContractWorkerOptions {
16
+ /** The application's own SQLite migrations, applied as the bundle `app` after the framework's `fabrika`. */
17
+ readonly migrations?: readonly ApplicationMigration[];
18
+ /** Where the isolate hears of an unhandled rejection; the global `unhandledrejection` event by default. */
19
+ readonly rejections?: CrashEvents;
20
+ /** What posts a report to Operations' ingest; `fetch` by default. */
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;
24
+ }
25
+ /**
26
+ * Marks the Worker's repair tick, with its `scheduledTime`. The Worker's `fetch` removes it from every request it
27
+ * forwards, so only its own `scheduled` handler reaches the tick.
28
+ */
29
+ export declare const TICK_HEADER = "X-Fabrika-Tick";
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>;
49
+ /** What the object needs of its `DurableObjectState`. */
50
+ export interface ApplicationState {
51
+ readonly storage: ApplicationStorage & Partial<Omit<OpsRecovery, 'abort'>>;
52
+ blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>;
53
+ waitUntil(promise: Promise<unknown>): void;
54
+ /** workerd resets the object; the test double has none. */
55
+ abort?(reason?: string): void;
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;
59
+ /** What the object classes of this isolate boot: the generated entrypoint's `createContractWorker` registers it. */
60
+ export declare function registerApplication(load: ImplementationLoader, options: ContractWorkerOptions): void;
61
+ /** The application environment's one object. The Worker's generated entrypoint exports it as `FabrikaApplication`. */
62
+ export declare class FabrikaApplication {
63
+ #private;
64
+ constructor(state: ApplicationState, env: Readonly<Record<string, unknown>>);
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>;
73
+ }
@@ -0,0 +1,33 @@
1
+ import type { IamMembershipRpc, IamTerminalRpc } from '@fabrika/auth-core';
2
+ import type { IamKeySource } from '../implement/boot.js';
3
+ import { type ConnectFetch } from '../implement/connect.js';
4
+ import type { SpaAssets } from '../implement/dispatch.js';
5
+ import type { WorkloadTokenSource } from '../implement/workload.js';
6
+ /** The method `name` of a binding, bound to it, or `null` when it has none. */
7
+ export declare function method(target: unknown, name: string): ((...args: unknown[]) => unknown) | null;
8
+ export declare function bindingKeySource(binding: unknown): IamKeySource;
9
+ /**
10
+ * IAM's membership operations on the `IAM` binding (`PropustkaApplication`), every answer decoded like the HTTP
11
+ * transport's. A binding without them is no membership transport, and `boot` refuses a contract that needs one.
12
+ */
13
+ export declare function bindingMembership(binding: unknown): IamMembershipRpc | undefined;
14
+ /** The identifications at a terminal over the IAM binding, when its entrypoint serves them (ADR-0067). */
15
+ export declare function bindingTerminals(binding: unknown): IamTerminalRpc | undefined;
16
+ /**
17
+ * IAM's token exchange on the `IAM` binding (`mintFromKey`), for the keys of the jobs, webhooks and public procedures.
18
+ * An answer that is not IAM's decided outcome throws: "IAM could not be asked".
19
+ */
20
+ export declare function bindingWorkloadTokens(binding: unknown): WorkloadTokenSource | undefined;
21
+ /**
22
+ * The SPA and link mounts' files from the Workers Assets binding, whose directory mirrors the request paths: the mount
23
+ * `/admin` reads `admin/…` of it, the root mount the rest (the Cloudflare deploy stages each mount's `dir` there). A page
24
+ * route that names no file (`isPageRoute`) gets the mount's `index.html`, as `diskAssets` serves it: Workers Assets
25
+ * answers `<prefix>/` with it. A missing asset stays 404.
26
+ */
27
+ export declare function bindingAssets(binding: unknown): SpaAssets | undefined;
28
+ /**
29
+ * The service bindings to owners' proxy Workers (`FABRIKA_CONNECT_<IMPORT>`), which `captureEnvironment` keeps from
30
+ * the application because no `FABRIKA_*` value reaches it. A binding routes by itself: the URL it is called with
31
+ * carries the owner's host, which the proxy Worker selects the application by.
32
+ */
33
+ export declare function connectBindings(env: Readonly<Record<string, unknown>>): Record<string, ConnectFetch>;
@@ -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,51 @@
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. A `CHECK` or an
48
+ * `INITIALLY DEFERRED` clause is read from the table's SQL outside its quotes and comments; one such clause marks every
49
+ * foreign key of its table.
50
+ */
51
+ export declare function describeDumpSchema(storage: SqliteStorage): OpsDumpSchema;