@fabrika/app 0.9.0-dev.3 → 0.9.0-dev.5

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 (115) hide show
  1. package/package.json +14 -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 +641 -0
  18. package/src/cloudflare/import.ts +1021 -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 +84 -13
  38. package/src/dev/output.ts +13 -3
  39. package/src/disk-assets.ts +8 -3
  40. package/src/files/archive.ts +2 -2
  41. package/src/files/job-names.ts +12 -0
  42. package/src/files/kinds.ts +73 -31
  43. package/src/files/scan.ts +3 -4
  44. package/src/files/streams.ts +3 -1
  45. package/src/implement/anonymous.ts +12 -11
  46. package/src/implement/boot.ts +75 -6
  47. package/src/implement/bounded.ts +21 -2
  48. package/src/implement/capability.ts +15 -3
  49. package/src/implement/dispatch.ts +419 -177
  50. package/src/implement/failures.ts +17 -1
  51. package/src/implement/faults.ts +1 -0
  52. package/src/implement/index.ts +1 -0
  53. package/src/implement/invocation.ts +58 -10
  54. package/src/implement/principal.ts +25 -2
  55. package/src/implement/terminals.ts +93 -0
  56. package/src/implement/workload.ts +42 -16
  57. package/src/jobs/mail.ts +8 -0
  58. package/src/jobs/report.ts +5 -1
  59. package/src/jobs/runner.ts +672 -113
  60. package/src/jobs/schedule.ts +7 -1
  61. package/src/jobs/scrub.ts +14 -1
  62. package/src/jobs/types.ts +6 -0
  63. package/src/spa-fallback.ts +12 -0
  64. package/src/testing/endpoint-access.ts +307 -152
  65. package/src/testing/isolation.ts +8 -1
  66. package/src/testing/kit.ts +80 -2
  67. package/src/testing/proxy.ts +15 -10
  68. package/types/src/build-recipe.d.ts +70 -0
  69. package/types/src/build.d.ts +19 -1
  70. package/types/src/bun.d.ts +34 -1
  71. package/types/src/cloudflare/application.d.ts +73 -0
  72. package/types/src/cloudflare/bindings.d.ts +33 -0
  73. package/types/src/cloudflare/export.d.ts +16 -0
  74. package/types/src/cloudflare/import.d.ts +51 -0
  75. package/types/src/cloudflare/maintenance.d.ts +117 -0
  76. package/types/src/cloudflare/names.d.ts +11 -0
  77. package/types/src/cloudflare/ops.d.ts +81 -0
  78. package/types/src/cloudflare/r2-files.d.ts +9 -0
  79. package/types/src/cloudflare/restore.d.ts +9 -0
  80. package/types/src/cloudflare/tracker.d.ts +29 -0
  81. package/types/src/cloudflare.d.ts +12 -18
  82. package/types/src/contract/app-id.d.ts +2 -0
  83. package/types/src/contract/artifact-schema.d.ts +2 -0
  84. package/types/src/contract/context.d.ts +35 -11
  85. package/types/src/contract/declaration.d.ts +4 -0
  86. package/types/src/contract/defaults.d.ts +19 -1
  87. package/types/src/contract/define.d.ts +20 -3
  88. package/types/src/contract/kit.d.ts +2 -1
  89. package/types/src/contract/platform.d.ts +2 -2
  90. package/types/src/contract/vocabulary.d.ts +9 -7
  91. package/types/src/dev/output.d.ts +8 -2
  92. package/types/src/disk-assets.d.ts +4 -1
  93. package/types/src/files/job-names.d.ts +9 -0
  94. package/types/src/files/kinds.d.ts +21 -14
  95. package/types/src/files/scan.d.ts +1 -3
  96. package/types/src/implement/anonymous.d.ts +2 -4
  97. package/types/src/implement/boot.d.ts +17 -1
  98. package/types/src/implement/bounded.d.ts +11 -1
  99. package/types/src/implement/capability.d.ts +4 -2
  100. package/types/src/implement/dispatch.d.ts +34 -1
  101. package/types/src/implement/failures.d.ts +5 -0
  102. package/types/src/implement/faults.d.ts +1 -0
  103. package/types/src/implement/index.d.ts +1 -0
  104. package/types/src/implement/invocation.d.ts +22 -7
  105. package/types/src/implement/principal.d.ts +6 -1
  106. package/types/src/implement/terminals.d.ts +33 -0
  107. package/types/src/implement/workload.d.ts +5 -0
  108. package/types/src/jobs/runner.d.ts +66 -2
  109. package/types/src/jobs/schedule.d.ts +2 -0
  110. package/types/src/jobs/types.d.ts +6 -0
  111. package/types/src/spa-fallback.d.ts +2 -0
  112. package/types/src/testing/endpoint-access.d.ts +37 -5
  113. package/types/src/testing/isolation.d.ts +1 -1
  114. package/types/src/testing/kit.d.ts +22 -1
  115. package/types/src/testing/proxy.d.ts +4 -4
@@ -17,13 +17,22 @@ import {
17
17
  FABRIKA_IAM_APP_ID,
18
18
  FABRIKA_PROXY_SECRET,
19
19
  type IamMembershipRpc,
20
+ type IamTerminalRpc,
20
21
  isLoopbackHost,
21
22
  type Jwks,
22
23
  parseAppEnvironmentId,
23
24
  } from '@fabrika/auth-core'
24
25
  import type { Database } from '@fabrika/db'
25
26
  import type { CapabilityAuthority } from '@fabrika/db/capability'
26
- import { bindScopedDatabase, type DataAccess, dataAccessOf, type FrameworkTables, frameworkTablesOf, isScopedDatabase } from '@fabrika/db/framework'
27
+ import {
28
+ bindScopedDatabaseProvisionally,
29
+ type DataAccess,
30
+ dataAccessOf,
31
+ type FrameworkTables,
32
+ frameworkTablesOf,
33
+ isScopedDatabase,
34
+ type Session,
35
+ } from '@fabrika/db/framework'
27
36
  import type { DataKind } from '@fabrika/db/tables'
28
37
  import type { EmailProviderRegistry } from '@fabrika/email'
29
38
  import { builtinEmailProviders } from '@fabrika/email/providers'
@@ -91,6 +100,11 @@ export interface BootOptions {
91
100
  readonly requireProxySecret?: boolean
92
101
  /** The object storage of the stored files, which the Bun adapter opens. Without it, a contract with file kinds does not boot. */
93
102
  readonly files?: FileObjectStore
103
+ /**
104
+ * How long a removed file's object outlives its row, so a restored backup's rows find their files:
105
+ * `FILE_TOMBSTONE_RETENTION_MS` on Cloudflare. Zero when omitted, as on Bun.
106
+ */
107
+ readonly fileRetentionMs?: number
94
108
  /**
95
109
  * The malware scanner of the scan job of `scan: true` file kinds, which the Bun adapter supplies to a job run
96
110
  * (`clamscanScanner`). Without it the scan job leaves every quarantined file quarantined and reports.
@@ -101,6 +115,11 @@ export interface BootOptions {
101
115
  * creates scopes, manages members or issues share links does not boot.
102
116
  */
103
117
  readonly membership?: IamMembershipRpc
118
+ /**
119
+ * IAM's identification operations at a terminal (ADR-0067): the IAM binding on Cloudflare, `HttpIamTerminals`
120
+ * elsewhere. Without it, a contract that declares a terminal does not boot.
121
+ */
122
+ readonly terminals?: IamTerminalRpc
104
123
  /**
105
124
  * Cloudflare service bindings to the owners' proxy Workers, by binding name (`FABRIKA_CONNECT_<IMPORT>`). An import
106
125
  * without one calls its owner with `fetch`.
@@ -150,6 +169,11 @@ export interface BootOptions {
150
169
  * then `null`.
151
170
  */
152
171
  readonly clientAddress?: 'vouched'
172
+ /**
173
+ * Runs in the transaction of every change of a job's wakes or lease (`DataLayerRuntime.projectWakes`): the Cloudflare
174
+ * object arms its alarm there. Bun supplies none.
175
+ */
176
+ readonly projectWakes?: (transaction: Session) => Promise<void>
153
177
  }
154
178
 
155
179
  /** The pool size a runtime adapter that names none is assumed to have: the Bun adapter's default. */
@@ -262,6 +286,18 @@ function readProxySecret(framework: Readonly<Record<string, string>>, required:
262
286
  return proxySecretDigest(secret)
263
287
  }
264
288
 
289
+ /** What an application's SQLite database (a Durable Object's, ADR-0065) cannot serve: a scanning file kind. */
290
+ function sqliteProblems(artifact: ContractArtifact, database: Database | undefined, problems: string[]): void {
291
+ if (database?.dialect !== 'sqlite') {
292
+ return
293
+ }
294
+ for (const [name, kind] of Object.entries(artifact.fileKinds ?? {})) {
295
+ if (kind.scan === true) {
296
+ problems.push(`files '${name}' declares scan: true; no malware scanner runs on Cloudflare, so a scanning file kind is not served there`)
297
+ }
298
+ }
299
+ }
300
+
265
301
  /** What this version cannot serve yet; a contract that declares it does not boot rather than answer nothing. */
266
302
  function unservable(
267
303
  artifact: ContractArtifact,
@@ -350,6 +386,8 @@ interface BoundDatabase {
350
386
  readonly framework: FrameworkTables | null
351
387
  /** The mini-ORM behind a staged-kit site's `ctx.db`; only a `scoped(tables)` layer has it. */
352
388
  readonly data: DataAccess | null
389
+ /** Disconnects a `scoped(tables)` layer this boot bound; `null` for any other database. */
390
+ readonly release: (() => void) | null
353
391
  }
354
392
 
355
393
  /**
@@ -360,6 +398,7 @@ function contractDatabase(
360
398
  database: ImplementationDatabase | null,
361
399
  connection: Database | undefined,
362
400
  capabilities: CapabilityAuthority,
401
+ projectWakes: ((transaction: Session) => Promise<void>) | undefined,
363
402
  problems: string[],
364
403
  ): BoundDatabase | null {
365
404
  if (database === null) {
@@ -367,7 +406,7 @@ function contractDatabase(
367
406
  }
368
407
  if (!isScopedDatabase(database)) {
369
408
  if ('locate' in database) {
370
- return { database, framework: null, data: null }
409
+ return { database, framework: null, data: null, release: null }
371
410
  }
372
411
  problems.push('serve(contract, { database }) takes the scoped(tables) result of @fabrika/db itself, not a copy or a wrapper of it')
373
412
  return null
@@ -377,8 +416,13 @@ function contractDatabase(
377
416
  return null
378
417
  }
379
418
  try {
380
- const locate = bindScopedDatabase(database, { database: connection, capabilities, readOnly: requestIsReadOnly })
381
- return { database: { tables: database.tables, locate }, framework: frameworkTablesOf(database), data: dataAccessOf(database) }
419
+ const { locate, release } = bindScopedDatabaseProvisionally(database, {
420
+ database: connection,
421
+ capabilities,
422
+ readOnly: requestIsReadOnly,
423
+ ...(projectWakes === undefined ? {} : { projectWakes }),
424
+ })
425
+ return { database: { tables: database.tables, locate }, framework: frameworkTablesOf(database), data: dataAccessOf(database), release }
382
426
  } catch {
383
427
  problems.push('the data layer was bound before boot; only the framework binds it, so remove @fabrika/db/framework from the application')
384
428
  return null
@@ -651,11 +695,28 @@ function runtimePurposes(contract: AnyContract, artifact: ContractArtifact): Rea
651
695
  }
652
696
 
653
697
  export function boot(app: ContractImplementation, options: BootOptions): ContractApp {
698
+ const binding: Binding = { release: null }
699
+ try {
700
+ return bootOnce(app, options, binding)
701
+ } catch (error) {
702
+ // A failed boot releases the data layer it bound, so a later boot of the same application binds it again.
703
+ binding.release?.()
704
+ throw error
705
+ }
706
+ }
707
+
708
+ /** What `bootOnce` bound: released when the boot fails, kept when it succeeds. */
709
+ interface Binding {
710
+ release: (() => void) | null
711
+ }
712
+
713
+ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Binding): ContractApp {
654
714
  const problems: string[] = []
655
715
  installEgressGuard()
656
716
  // What a handler reaches through these is the platform's own request, which no site's egress covers.
657
717
  const objects = options.files === undefined ? undefined : platformFacility(options.files)
658
718
  const membershipRpc = options.membership === undefined ? undefined : platformFacility(options.membership)
719
+ const terminalRpc = options.terminals === undefined ? undefined : platformFacility(options.terminals)
659
720
  const workloadTokens = options.workloadTokens === undefined ? undefined : platformFacility(options.workloadTokens)
660
721
  const variables = readFramework(options.environment.framework, app.contract.vocabulary.app, problems)
661
722
  const artifact = compileContract(app.contract, app.database?.tables ?? {})
@@ -673,10 +734,12 @@ export function boot(app: ContractImplementation, options: BootOptions): Contrac
673
734
  const owned = new Set(Object.values(artifact.tables).flatMap((table) => table.scope.mode === 'dimension' ? [table.scope.dimension] : []))
674
735
  const containers = containersOf(artifact)
675
736
  unservable(artifact, options.assets, owned, containers, problems)
737
+ sqliteProblems(artifact, options.database, problems)
676
738
  // This runtime's own: what another `boot` call mints, application code's included, its stores refuse.
677
739
  const issuer = createCapabilityIssuer()
678
- const fileKinds = storedFileKinds(artifact, app.database, objects, problems)
679
- const bound = contractDatabase(app.database, options.database, issuer.authority, problems)
740
+ const fileKinds = storedFileKinds(artifact, app.database, objects, problems, options.fileRetentionMs ?? 0)
741
+ const bound = contractDatabase(app.database, options.database, issuer.authority, options.projectWakes, problems)
742
+ binding.release = bound?.release ?? null
680
743
  const framework = bound?.framework ?? null
681
744
  frameworkProblems(artifact, framework, problems)
682
745
  const database = bound?.database ?? null
@@ -896,6 +959,11 @@ export function boot(app: ContractImplementation, options: BootOptions): Contrac
896
959
  if (site !== undefined && data === null) {
897
960
  problems.push(`'${site.row.id}' reaches data through ctx.db, which runs on @fabrika/db: pass serve(contract, { database: scoped(tables) })`)
898
961
  }
962
+ if (artifact.terminal !== undefined && options.terminals === undefined) {
963
+ problems.push(
964
+ 'the contract declares a terminal, and the runtime adapter supplies no IAM transport for its identifications (the IAM binding on Cloudflare; FABRIKA_IAM_RPC_URL and FABRIKA_IAM_RPC_KEY on Bun)',
965
+ )
966
+ }
899
967
  const asking = [...endpoints.values()].find(asksIam)
900
968
  if (asking !== undefined && options.membership === undefined) {
901
969
  problems.push(
@@ -919,6 +987,7 @@ export function boot(app: ContractImplementation, options: BootOptions): Contrac
919
987
  containers,
920
988
  assets: options.assets ?? null,
921
989
  membership,
990
+ terminals: artifact.terminal === undefined ? null : (terminalRpc ?? null),
922
991
  framework,
923
992
  mint: issuer.mint,
924
993
  capabilities: issuer.authority,
@@ -8,9 +8,28 @@
8
8
  */
9
9
  export const REQUEST_BUDGET_MS = 10_000
10
10
 
11
+ /** A signal that aborts once its time passed, and a `clear` its work calls when it settles. */
12
+ export interface Deadline {
13
+ readonly signal: AbortSignal
14
+ clear(): void
15
+ }
16
+
17
+ /**
18
+ * Aborts like `AbortSignal.timeout(ms)`, or when `parent` aborts. Its timer is cleared by `clear`, which every caller
19
+ * runs in `finally`: workerd counts a pending timer as work, so an uncleared one keeps a Durable Object awake.
20
+ */
21
+ export function deadline(ms: number, parent?: AbortSignal): Deadline {
22
+ const controller = new AbortController()
23
+ const timer = setTimeout(() => controller.abort(new DOMException('The operation timed out.', 'TimeoutError')), ms)
24
+ return {
25
+ signal: parent === undefined ? controller.signal : AbortSignal.any([parent, controller.signal]),
26
+ clear: () => clearTimeout(timer),
27
+ }
28
+ }
29
+
11
30
  /** A handler's `ctx.signal`: aborted when the client leaves (`request.signal`) or once `budgetMs` passed. */
12
- export function handlerSignal(request: Request, budgetMs: number = REQUEST_BUDGET_MS): AbortSignal {
13
- return AbortSignal.any([request.signal, AbortSignal.timeout(budgetMs)])
31
+ export function handlerSignal(request: Request, budgetMs: number = REQUEST_BUDGET_MS): Deadline {
32
+ return deadline(budgetMs, request.signal)
14
33
  }
15
34
 
16
35
  export interface BoundedRead {
@@ -269,14 +269,18 @@ export class Within<D extends string, A extends string> implements WithinCapabil
269
269
  principal: string,
270
270
  values: readonly string[] | 'all',
271
271
  containers: readonly ContainerGrant[],
272
+ contained: readonly ContainerGrant[],
272
273
  ) {
273
274
  if (token !== MINT) {
274
275
  throw new CapabilityRefusedError('not_minted', 'a Within is minted by the framework only; declare the access form in fabrika.contract.ts')
275
276
  }
276
277
  const held = values === 'all' ? freeze([]) : containerGrantsOf(containers)
278
+ const inside = values === 'all' ? freeze([]) : containerGrantsOf(contained)
277
279
  let count = values === 'all' ? 0 : values.length
278
- for (let index = 0; index < held.length; index++) {
279
- count += held[index]?.values.length ?? 0
280
+ for (const group of [held, inside]) {
281
+ for (let index = 0; index < group.length; index++) {
282
+ count += group[index]?.values.length ?? 0
283
+ }
280
284
  }
281
285
  if (count > MAX_WITHIN_VALUES) {
282
286
  throw new CapabilityLimitError(
@@ -292,6 +296,7 @@ export class Within<D extends string, A extends string> implements WithinCapabil
292
296
  principal,
293
297
  values: values === 'all' ? 'all' : copyOf(values),
294
298
  containers: held,
299
+ contained: inside,
295
300
  })
296
301
  this.#frame = frame
297
302
  this.#issuer = issuer
@@ -315,6 +320,11 @@ export class Within<D extends string, A extends string> implements WithinCapabil
315
320
  return this.#grant.containers
316
321
  }
317
322
 
323
+ /** The dimensions inside this one in which the caller holds the action: `note → [n1]` for a workspace list. */
324
+ get contained(): readonly ContainerGrant[] {
325
+ return this.#grant.contained
326
+ }
327
+
318
328
  static {
319
329
  readWithin = (value) =>
320
330
  typeof value === 'object' && value !== null && #grant in value ? { grant: value.#grant, frame: value.#frame, issuer: value.#issuer } : undefined
@@ -434,6 +444,7 @@ export interface CapabilityMint {
434
444
  principal: string,
435
445
  values: readonly string[] | 'all',
436
446
  containers?: readonly ContainerGrant[],
447
+ contained?: readonly ContainerGrant[],
437
448
  ): Within<D, A>
438
449
  app<A extends string>(frame: RequestFrame, action: A, principal: string): AppCapability<A>
439
450
  }
@@ -469,8 +480,9 @@ export function createCapabilityIssuer(): CapabilityIssuer {
469
480
  principal: string,
470
481
  values: readonly string[] | 'all',
471
482
  containers: readonly ContainerGrant[] = [],
483
+ contained: readonly ContainerGrant[] = [],
472
484
  ): Within<D, A> {
473
- return new Within(MINT, issuer, frame, dimension, action, principal, values, containers)
485
+ return new Within(MINT, issuer, frame, dimension, action, principal, values, containers, contained)
474
486
  },
475
487
  app<A extends string>(frame: RequestFrame, action: A, principal: string): AppCapability<A> {
476
488
  return new AppCapability(MINT, issuer, frame, action, principal)