@fabrika/app 0.9.0-cloudflare.1 → 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 (72) hide show
  1. package/package.json +9 -9
  2. package/skill/SKILL.md +21 -17
  3. package/skill/references/app-setup.md +42 -11
  4. package/skill/references/endpoint.md +29 -22
  5. package/skill/references/errors.md +32 -31
  6. package/skill/references/jobs.md +22 -3
  7. package/skill/references/tests.md +29 -1
  8. package/src/build.ts +6 -1
  9. package/src/bun.ts +168 -5
  10. package/src/cloudflare/application.ts +546 -76
  11. package/src/cloudflare/bindings.ts +26 -5
  12. package/src/cloudflare/export.ts +621 -0
  13. package/src/cloudflare/import.ts +1097 -0
  14. package/src/cloudflare/maintenance.ts +518 -0
  15. package/src/cloudflare/names.ts +6 -0
  16. package/src/cloudflare/ops.ts +147 -18
  17. package/src/cloudflare/restore.ts +167 -0
  18. package/src/cloudflare/tracker.ts +192 -0
  19. package/src/cloudflare.ts +3 -2
  20. package/src/contract/artifact-schema.ts +13 -2
  21. package/src/contract/build.ts +38 -11
  22. package/src/contract/context.ts +26 -9
  23. package/src/contract/defaults.ts +22 -2
  24. package/src/contract/define.ts +1 -1
  25. package/src/contract/group.ts +10 -1
  26. package/src/contract/kit.ts +2 -1
  27. package/src/disk-assets.ts +8 -3
  28. package/src/files/kinds.ts +54 -24
  29. package/src/implement/anonymous.ts +1 -10
  30. package/src/implement/boot.ts +30 -12
  31. package/src/implement/capability.ts +3 -0
  32. package/src/implement/dispatch.ts +175 -37
  33. package/src/implement/egress.ts +367 -8
  34. package/src/implement/invocation.ts +60 -19
  35. package/src/implement/workload.ts +18 -3
  36. package/src/jobs/runner.ts +646 -98
  37. package/src/spa-fallback.ts +12 -0
  38. package/src/testing/endpoint-access.ts +135 -23
  39. package/src/testing/isolation.ts +8 -1
  40. package/src/testing/kit.ts +60 -0
  41. package/types/src/build.d.ts +1 -1
  42. package/types/src/bun.d.ts +34 -1
  43. package/types/src/cloudflare/application.d.ts +36 -5
  44. package/types/src/cloudflare/bindings.d.ts +6 -0
  45. package/types/src/cloudflare/export.d.ts +16 -0
  46. package/types/src/cloudflare/import.d.ts +58 -0
  47. package/types/src/cloudflare/maintenance.d.ts +117 -0
  48. package/types/src/cloudflare/names.d.ts +5 -0
  49. package/types/src/cloudflare/ops.d.ts +39 -4
  50. package/types/src/cloudflare/restore.d.ts +9 -0
  51. package/types/src/cloudflare/tracker.d.ts +29 -0
  52. package/types/src/cloudflare.d.ts +2 -1
  53. package/types/src/contract/artifact-schema.d.ts +2 -0
  54. package/types/src/contract/context.d.ts +24 -9
  55. package/types/src/contract/defaults.d.ts +19 -1
  56. package/types/src/contract/define.d.ts +1 -1
  57. package/types/src/contract/group.d.ts +9 -1
  58. package/types/src/contract/kit.d.ts +2 -2
  59. package/types/src/disk-assets.d.ts +4 -1
  60. package/types/src/files/kinds.d.ts +17 -6
  61. package/types/src/implement/anonymous.d.ts +0 -4
  62. package/types/src/implement/boot.d.ts +17 -0
  63. package/types/src/implement/capability.d.ts +2 -0
  64. package/types/src/implement/dispatch.d.ts +33 -1
  65. package/types/src/implement/egress.d.ts +36 -1
  66. package/types/src/implement/invocation.d.ts +20 -10
  67. package/types/src/implement/workload.d.ts +5 -0
  68. package/types/src/jobs/runner.d.ts +63 -2
  69. package/types/src/spa-fallback.d.ts +2 -0
  70. package/types/src/testing/endpoint-access.d.ts +25 -1
  71. package/types/src/testing/isolation.d.ts +1 -1
  72. package/types/src/testing/kit.d.ts +16 -0
@@ -0,0 +1,12 @@
1
+ // Which request an SPA mount answers with its `index.html` when it names no file: a route of the page, not a missing
2
+ // asset. Both asset servers apply it (`diskAssets`, `bindingAssets`), so a missing script stays a 404 and never arrives
3
+ // as an HTML page with a 200.
4
+
5
+ import { rawRequestTarget } from '@fabrika/auth-core'
6
+
7
+ /** A GET or HEAD whose last path segment has no extension, or one that asks for HTML (a navigation to `/notes/v1.2`). */
8
+ export function isPageRoute(request: Request): boolean {
9
+ if (request.method !== 'GET' && request.method !== 'HEAD') return false
10
+ const last = rawRequestTarget(request.url).pathname.split('/').pop() ?? ''
11
+ return !last.includes('.') || (request.headers.get('Accept') ?? '').includes('text/html')
12
+ }
@@ -20,6 +20,9 @@ import type { Tables } from '@fabrika/db'
20
20
  import { tablePolicies } from '@fabrika/db/tables'
21
21
  import { type IsolationWorlds, type SampleValue, SEEDED_OBJECT_VERSION, type TestDatabase, type WorldRow } from '@fabrika/db/testing'
22
22
  import { MemoryFileObjects } from '@fabrika/platform/testing'
23
+ import { readFile } from 'node:fs/promises'
24
+ import { basename } from 'node:path'
25
+ import { fileURLToPath } from 'node:url'
23
26
  import { z } from 'zod/v4'
24
27
  import type { RpcFetch } from '../client/transport'
25
28
  import { compileContract } from '../contract/compile'
@@ -33,6 +36,7 @@ import {
33
36
  } from '../contract/defaults'
34
37
  import type { AnyContract } from '../contract/define'
35
38
  import type { FileScanner, ScanVerdict } from '../files/scan'
39
+ import { bytesAreOfType, SNIFF_BYTES } from '../files/sniff'
36
40
  import type { ApplicationEnvironment, ContractImplementation } from '../implement/implement'
37
41
  import type { TestCaller, TestGrant } from './caller'
38
42
  import { standInIamKit } from './kit'
@@ -110,6 +114,54 @@ export interface EndpointAccessKit {
110
114
  anyone(endpoint: string, input: Readonly<Record<string, unknown>>): Promise<ReachOutcome>
111
115
  }
112
116
 
117
+ export interface EndpointAccessOptions {
118
+ /**
119
+ * The file every case of an endpoint sends in a file field instead of the kit's sample, by endpoint id and input
120
+ * field: a file of the application's repository that a handler inspecting the content accepts (a valid package). Its
121
+ * type is the first of the field's kind that its bytes are; a file of none of them throws. `files` of the fixtures.
122
+ */
123
+ readonly files?: Readonly<Record<string, Readonly<Record<string, URL>>>>
124
+ /**
125
+ * The error types of the refusals (400) an endpoint's handler answers its own object with when the case's input meets
126
+ * no domain rule the kit can satisfy, by endpoint id: such a 400 is the handler's own answer, so the request passed
127
+ * the access form, and the endpoint's own case gets it as `{ status: 400 }` instead of failing; so does the other
128
+ * scope's request a leak case makes first. The own scope's answer of a leak case, and a global or capability case,
129
+ * still throw on it (an answer that holds nothing proves no isolation), so does any other 400, and an input the schema
130
+ * refuses (`validation`) always does. `refusals` of the fixtures.
131
+ */
132
+ readonly refusals?: Readonly<Record<string, readonly string[]>>
133
+ /**
134
+ * Known values for text columns of the row the endpoint addresses (the row of the table that owns its dimension), by
135
+ * endpoint id: the value in the own scope's row, and `<value>-other` in the other scope's, which counts among the
136
+ * other scope's values a leak shows. For a handler whose rule ties a column to the input or a file fixture (a package
137
+ * that names the skill's slug). `pins` of the fixtures.
138
+ */
139
+ readonly pins?: Readonly<Record<string, Readonly<Record<string, string>>>>
140
+ }
141
+
142
+ /**
143
+ * Whether a request takes a refusal the fixtures declare for its endpoint as the handler's answer: an own case's, and the
144
+ * other scope's request a leak case makes first, whose answer is not the one checked.
145
+ */
146
+ type Refusals = 'declared' | 'none'
147
+
148
+ /**
149
+ * The pins of a case's endpoint (column → the own scope's value of a text column), and the removals of the case: rows
150
+ * seeded with pins are removed once the case is over, so the next case can pin the same values under a unique index.
151
+ */
152
+ interface Pinning {
153
+ readonly pins: Readonly<Record<string, string>>
154
+ readonly removals: (() => Promise<void>)[]
155
+ }
156
+
157
+ const NO_PINNING: Pinning = { pins: {}, removals: [] }
158
+
159
+ /** Seeded worlds, their removal taken by the case when they hold pinned values. */
160
+ const pinned = <W extends { readonly remove: () => Promise<void> }>(worlds: W, pinning: Pinning): W => {
161
+ if (Object.keys(pinning.pins).length > 0) pinning.removals.push(worlds.remove)
162
+ return worlds
163
+ }
164
+
113
165
  interface ActionEndpoint {
114
166
  readonly id: string
115
167
  /** The link mount of a link procedure; `null` for every other endpoint. */
@@ -285,7 +337,12 @@ export const managerGrants = (
285
337
  * The endpoint access kit of `app`, whose data layer is `scoped(tables)`, over `postgres`. It boots `app` once, so the
286
338
  * application's layer is bound here and nowhere else in the process.
287
339
  */
288
- export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract>, tables: Tables<DB, P>, postgres: TestDatabase): EndpointAccessKit {
340
+ export function endpointAccessKit<DB, P>(
341
+ app: ContractImplementation<AnyContract>,
342
+ tables: Tables<DB, P>,
343
+ postgres: TestDatabase,
344
+ options: EndpointAccessOptions = {},
345
+ ): EndpointAccessKit {
289
346
  // The objects of the files the cases seed live in memory; their rows are the application's own tables.
290
347
  const objects = new MemoryFileObjects()
291
348
  const { kit, standIn } = standInIamKit(app, {
@@ -404,16 +461,20 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
404
461
  throw new Error(`${row.id} admits neither a human nor a machine caller`)
405
462
  }
406
463
 
407
- /** A case's request by a new caller holding `grants`, its generated fields filled for `chain` and that caller. */
464
+ /**
465
+ * A case's request by a new caller holding `grants`, its generated fields filled for `chain` and that caller. Only an
466
+ * own case passes `refusals: 'declared'`.
467
+ */
408
468
  const ask = async (
409
469
  row: ActionEndpoint,
410
470
  grants: readonly Grant[],
411
471
  input: Readonly<Record<string, unknown>>,
412
472
  chain: Chain,
473
+ refusals: Refusals = 'none',
413
474
  ): Promise<{ readonly status: number; readonly text: string; readonly marks: readonly string[] }> => {
414
475
  const asker = callerFor(row, grants)
415
476
  const asked = withGenerated(row, input, chain, asker.caller)
416
- return { ...(await askAs(row, asker.fetch, asked.input)), marks: asked.marks }
477
+ return { ...(await askAs(row, asker.fetch, asked.input, refusals)), marks: asked.marks }
417
478
  }
418
479
 
419
480
  // A seeded file column references an empty object, which a handler that serves or opens the file reads here.
@@ -427,7 +488,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
427
488
  }
428
489
 
429
490
  /** The request of a case: a GET's input in its URL, a file field's marker as a file of its kind in a multipart body. */
430
- const requestOf = (row: ActionEndpoint, body: Readonly<Record<string, unknown>>): readonly [string, RequestInit] => {
491
+ const requestOf = async (row: ActionEndpoint, body: Readonly<Record<string, unknown>>): Promise<readonly [string, RequestInit]> => {
431
492
  if (row.method === 'GET') {
432
493
  const params = new URLSearchParams(Object.entries(body).map(([name, value]) => [name, value === null ? 'null' : String(value)]))
433
494
  return [params.size === 0 ? row.path : `${row.path}?${params}`, { method: 'GET' }]
@@ -446,7 +507,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
446
507
  for (const item of Array.isArray(value) ? value : [value]) {
447
508
  const kind = fileKindOf(item)
448
509
  if (kind === undefined) throw new Error(`${row.id}: the file field ${name} holds ${JSON.stringify(item)}, not a generated file`)
449
- files.push([name, generatedFile(kind)])
510
+ files.push([name, await generatedFile(row.id, name, kind)])
450
511
  }
451
512
  }
452
513
  const form = new FormData()
@@ -455,30 +516,69 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
455
516
  return [row.path, { method: 'POST', body: form }]
456
517
  }
457
518
 
458
- const generatedFile = (kind: string): File => {
459
- const sample = sampleFile(kind, kit.artifact.fileKinds?.[kind]?.types ?? [])
460
- return new File([sample.bytes], `generated-${kind}`, { type: sample.type })
519
+ /** The file a case sends in `field`: the author's file fixture of the endpoint's field, else a sample of `kind`. */
520
+ const generatedFile = async (endpoint: string, field: string, kind: string): Promise<File> => {
521
+ const types = kit.artifact.fileKinds?.[kind]?.types ?? []
522
+ const fixture = options.files?.[endpoint]?.[field]
523
+ if (fixture === undefined) {
524
+ const sample = sampleFile(kind, types)
525
+ return new File([sample.bytes], `generated-${kind}`, { type: sample.type })
526
+ }
527
+ const path = fileURLToPath(fixture)
528
+ const bytes = await fixtureBytes(endpoint, field, path)
529
+ const type = types.find((candidate) => bytesAreOfType(candidate, bytes.subarray(0, SNIFF_BYTES)))
530
+ if (type === undefined) {
531
+ throw new Error(`${endpoint}: the file of ${field}, ${path}, is none of the types of files.${kind} (${types.join(', ')})`)
532
+ }
533
+ return new File([bytes], basename(path), { type })
534
+ }
535
+
536
+ // A file fixture is read once; every case sends the same bytes.
537
+ const fixtureFiles = new Map<string, Uint8Array<ArrayBuffer>>()
538
+ const fixtureBytes = async (endpoint: string, field: string, path: string): Promise<Uint8Array<ArrayBuffer>> => {
539
+ const known = fixtureFiles.get(path)
540
+ if (known !== undefined) return known
541
+ let bytes: Uint8Array<ArrayBuffer>
542
+ try {
543
+ bytes = new Uint8Array(await readFile(path))
544
+ } catch {
545
+ throw new Error(`${endpoint}: the file of ${field} in the fixtures, ${path}, cannot be read; add it to the repository or correct its path`)
546
+ }
547
+ fixtureFiles.set(path, bytes)
548
+ return bytes
461
549
  }
462
550
 
463
551
  const askAs = async (
464
552
  row: ActionEndpoint,
465
553
  fetch: RpcFetch,
466
554
  body: Readonly<Record<string, unknown>>,
555
+ refusals: Refusals = 'none',
467
556
  ): Promise<{ readonly status: number; readonly text: string }> => {
468
557
  stockSeededObjects()
469
- const [url, init] = requestOf(row, body)
558
+ const [url, init] = await requestOf(row, body)
470
559
  const response = await fetch(url, init)
471
560
  const text = await response.text()
472
561
  // A 400 hides what the case is about: input is parsed before the access form runs, and a handler's refusal of
473
562
  // the input it was given is no answer to another scope. Either is what the generator could not build.
474
563
  if (response.status === 400) {
475
564
  const type = errorType(text)
565
+ const declared = type !== undefined && type !== 'validation' && options.refusals?.[row.id]?.includes(type) === true
566
+ // The own case may take it: it shows the access form let the caller through. The answer a leak case checks, or a
567
+ // global case's, would pass holding nothing, which proves nothing.
568
+ if (declared && refusals === 'declared') {
569
+ return { status: response.status, text }
570
+ }
571
+ if (declared) {
572
+ throw new Error(
573
+ `${row.id}: the handler answered its declared refusal (400 ${type}), which only the own case takes; this case proves nothing on it until the fixtures give what the handler needs (pins, files, fixtures) (${text})`,
574
+ )
575
+ }
476
576
  throw new Error(
477
577
  type === 'validation'
478
578
  ? `${row.id}: the case's input does not match the endpoint's input schema; correct its fixture (${text})`
479
579
  : `${row.id}: the handler refused the case's input (400 ${
480
580
  type ?? 'without a type'
481
- }); the case cannot reach what it tests until its fixtures give what the handler needs: a picked person in members, a row of its object in rows, the state in seeds or the whole input in fixtures (${text})`,
581
+ }); the case cannot reach what it tests until its fixtures give what the handler needs: a picked person in members, a row of its object in rows, the state in seeds, a file it accepts in files, the whole input in fixtures, or the refusal it answers in refusals (${text})`,
482
582
  )
483
583
  }
484
584
  return { status: response.status, text }
@@ -494,6 +594,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
494
594
  field: SchemaShape | undefined,
495
595
  seed: Seed,
496
596
  input: Readonly<Record<string, unknown>>,
597
+ pinning: Pinning = NO_PINNING,
497
598
  ): Promise<Scopes> => {
498
599
  const named = rowFields(input)
499
600
  const owner = ownerOf(dimension)
@@ -514,7 +615,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
514
615
  },
515
616
  }
516
617
  }
517
- const worlds = await postgres.seedWorlds(tables, owner, seed)
618
+ const worlds = pinned(await postgres.seedWorlds(tables, owner, seed, pinning.pins), pinning)
518
619
  const own = await rowsIn(worlds.own, named)
519
620
  const other = await rowsIn(worlds.other, named)
520
621
  return {
@@ -569,14 +670,17 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
569
670
  * For a report `in` `dimension`: one row in each scope of every table that lies in it, the table that owns it with
570
671
  * `seed`. Each side's targets are its rows' values of `dimension`, and each caller holds all of them.
571
672
  */
572
- const inScopesOf = async (action: string, dimension: string, field: SchemaShape | undefined, seed: Seed) => {
673
+ const inScopesOf = async (action: string, dimension: string, field: SchemaShape | undefined, seed: Seed, pinning: Pinning = NO_PINNING) => {
573
674
  const own: InTarget[] = []
574
675
  const other: InTarget[] = []
575
676
  const values: string[] = []
576
677
  for (const name of tableNames) {
577
678
  const mode = policies[name]?.scope.mode
578
679
  if (mode !== 'dimension' && mode !== 'child') continue
579
- const worlds = await postgres.seedWorlds(tables, name, name === ownerOf(dimension) ? seed : {})
680
+ const owned = name === ownerOf(dimension)
681
+ const worlds = owned
682
+ ? pinned(await postgres.seedWorlds(tables, name, seed, pinning.pins), pinning)
683
+ : await postgres.seedWorlds(tables, name)
580
684
  const ownAt = worlds.own.chain.findIndex((link) => link.type === dimension)
581
685
  const otherAt = worlds.other.chain.findIndex((link) => link.type === dimension)
582
686
  const ownValue = worlds.own.chain[ownAt]?.value
@@ -588,7 +692,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
588
692
  }
589
693
  }
590
694
  if (own.length === 0) {
591
- const scopes = await scopesOf(action, dimension, field, seed, {})
695
+ const scopes = await scopesOf(action, dimension, field, seed, {}, pinning)
592
696
  return { own: [scopes.own], other: [scopes.other], values: scopes.other.values }
593
697
  }
594
698
  return { own, other, values }
@@ -711,6 +815,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
711
815
  mount: string,
712
816
  seed: Seed,
713
817
  input: Readonly<Record<string, unknown>>,
818
+ pinning: Pinning,
714
819
  ): Promise<{ readonly fetch: RpcFetch; readonly rows: Readonly<Record<string, string>> }> => {
715
820
  const access = row.access
716
821
  if (access.form !== 'on') {
@@ -720,7 +825,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
720
825
  if (owner === undefined) {
721
826
  throw new Error(`${row.id}: no table owns ${access.dimension}, so no link can be bound to one`)
722
827
  }
723
- const { own } = await postgres.seedWorlds(tables, owner, seed)
828
+ const { own } = pinned(await postgres.seedWorlds(tables, owner, seed, pinning.pins), pinning)
724
829
  const holder = kit.testCaller([{ action: row.action, scope: { type: access.dimension, value: own.key } }], {
725
830
  kind: 'link',
726
831
  link: { mount, chain: own.chain },
@@ -737,6 +842,9 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
737
842
  // the call and the runs it kicked are over. A list per call, so a concurrent case never removes the rows another
738
843
  // was given; the generated cases run one after another, since a row a required foreign key needed is shared.
739
844
  const accessKitOf = (removals: (() => Promise<void>)[]): EndpointAccessKit => {
845
+ /** The pins of `endpoint`, whose seeded rows this call removes once it is over. */
846
+ const pinningOf = (endpoint: string): Pinning => ({ pins: options.pins?.[endpoint] ?? {}, removals })
847
+
740
848
  /** One row of each application table `appRows` names, for this call only. */
741
849
  const seedAppRows = async (appRows: AppRows): Promise<void> => {
742
850
  if (Object.keys(appRows).length === 0) return
@@ -750,7 +858,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
750
858
  if (access.form !== 'on' && access.form !== 'in') {
751
859
  throw new Error(`${endpoint} has the access form ${access.form}; only on and in name an object or a scope value`)
752
860
  }
753
- const scopes = await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, input)
861
+ const scopes = await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, input, pinningOf(endpoint))
754
862
  const asked = addressing(input, access.from, scopes.other)
755
863
  const { status } = await ask(row, holding(row, input, scopes.own.grants, scopes.own.chain), asked, scopes.own.chain)
756
864
  return { status }
@@ -760,12 +868,12 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
760
868
  const { action, access } = row
761
869
  if (access.form === 'in') {
762
870
  await seedAppRows(appRows)
763
- const scopes = await inScopesOf(action, access.dimension, fieldOf(row.input, access.from), seed)
871
+ const scopes = await inScopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, pinningOf(endpoint))
764
872
  const grants = (targets: readonly InTarget[]): Grant[] =>
765
873
  targets.flatMap(({ target, chain }) => holding(row, input, [{ action, scope: { type: access.dimension, value: target } }], chain))
766
874
  const marks: string[] = []
767
875
  for (const side of scopes.other) {
768
- const answer = await ask(row, grants(scopes.other), addressing(input, access.from, side), side.chain)
876
+ const answer = await ask(row, grants(scopes.other), addressing(input, access.from, side), side.chain, 'declared')
769
877
  marks.push(...answer.marks)
770
878
  }
771
879
  const answers = []
@@ -779,14 +887,17 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
779
887
  }
780
888
  await seedAppRows(appRows)
781
889
  const scopes = access.form === 'on'
782
- ? await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, input)
890
+ ? await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, input, pinningOf(endpoint))
783
891
  : await listScopesOf(action, access.dimension)
784
892
  const from = access.form === 'on' ? access.from : null
893
+ // The other scope asks first, to fill whatever a handler keeps between requests; its pins differ from the own
894
+ // scope's, so a refusal the fixtures declare is its answer too. The own scope's answer is the one checked.
785
895
  const other = await ask(
786
896
  row,
787
897
  holding(row, input, scopes.other.grants, scopes.other.chain),
788
898
  addressing(input, from, scopes.other),
789
899
  scopes.other.chain,
900
+ 'declared',
790
901
  )
791
902
  const answer = await ask(
792
903
  row,
@@ -804,16 +915,17 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
804
915
  }
805
916
  await seedAppRows(appRows)
806
917
  if (row.link !== null) {
807
- const holder = await linkHolder(row, row.link, seed, input)
808
- const { status } = await askAs(row, holder.fetch, { ...input, ...holder.rows })
918
+ const holder = await linkHolder(row, row.link, seed, input, pinningOf(endpoint))
919
+ const { status } = await askAs(row, holder.fetch, { ...input, ...holder.rows }, 'declared')
809
920
  return { status }
810
921
  }
811
- const scopes = await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, input)
922
+ const scopes = await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, input, pinningOf(endpoint))
812
923
  const { status } = await ask(
813
924
  row,
814
925
  holding(row, input, scopes.own.grants, scopes.own.chain),
815
926
  addressing(input, access.from, scopes.own),
816
927
  scopes.own.chain,
928
+ 'declared',
817
929
  )
818
930
  return { status }
819
931
  },
@@ -864,7 +976,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
864
976
  }
865
977
  const { access } = named
866
978
  if (access.form === 'on' || access.form === 'in') {
867
- const scopes = await scopesOf(named.action, access.dimension, fieldOf(named.input, access.from), seed, input)
979
+ const scopes = await scopesOf(named.action, access.dimension, fieldOf(named.input, access.from), seed, input, pinningOf(endpoint))
868
980
  asked = addressing(asked, access.from, scopes.other)
869
981
  grants.push(...scopes.own.grants)
870
982
  }
@@ -6,7 +6,14 @@ import { refuseInProduction } from '@fabrika/db/production'
6
6
 
7
7
  refuseInProduction('@fabrika/app/testing/isolation')
8
8
 
9
- export { type DeniedOutcome, type EndpointAccessKit, endpointAccessKit, type LeakOutcome, type ReachOutcome } from './endpoint-access'
9
+ export {
10
+ type DeniedOutcome,
11
+ type EndpointAccessKit,
12
+ endpointAccessKit,
13
+ type EndpointAccessOptions,
14
+ type LeakOutcome,
15
+ type ReachOutcome,
16
+ } from './endpoint-access'
10
17
  export {
11
18
  type AppCaller,
12
19
  type AppCountOutcome,
@@ -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,
@@ -10,7 +10,7 @@ export declare const GENERATED_MIGRATIONS_FILE = "fabrika/migrations.generated.t
10
10
  export declare const MIGRATIONS_DIRECTORY = "db/migrations";
11
11
  export type EntryRuntime = 'bun' | 'cloudflare';
12
12
  export * from './build-recipe.js';
13
- export { CLOUDFLARE_APPLICATION_BINDING, CLOUDFLARE_APPLICATION_CLASS, CLOUDFLARE_FILES_BINDING } from './cloudflare/names.js';
13
+ export { CLOUDFLARE_APPLICATION_BINDING, CLOUDFLARE_APPLICATION_CLASS, CLOUDFLARE_ASSETS_BINDING, CLOUDFLARE_FILES_BINDING, } from './cloudflare/names.js';
14
14
  /** The entrypoint source for one runtime. */
15
15
  export declare function generatedEntry(runtime: EntryRuntime): string;
16
16
  /** Writes the entrypoint under `root` and returns its path; the Cloudflare one also writes the migrations module it imports. */
@@ -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
  }
@@ -18,6 +18,12 @@ export declare function bindingTerminals(binding: unknown): IamTerminalRpc | und
18
18
  * An answer that is not IAM's decided outcome throws: "IAM could not be asked".
19
19
  */
20
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
+ */
21
27
  export declare function bindingAssets(binding: unknown): SpaAssets | undefined;
22
28
  /**
23
29
  * The service bindings to owners' proxy Workers (`FABRIKA_CONNECT_<IMPORT>`), which `captureEnvironment` keeps from
@@ -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>;