@fabrika/app 0.9.0-dev.1 → 0.9.0-dev.10

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 (222) hide show
  1. package/package.json +32 -26
  2. package/skill/SKILL.md +46 -15
  3. package/skill/references/app-setup.md +43 -12
  4. package/skill/references/dev.md +5 -2
  5. package/skill/references/endpoint.md +39 -28
  6. package/skill/references/errors.md +50 -37
  7. package/skill/references/files.md +8 -4
  8. package/skill/references/jobs.md +39 -7
  9. package/skill/references/table-and-migration.md +47 -3
  10. package/skill/references/tests.md +61 -10
  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 +888 -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/capability-cases.ts +30 -0
  30. package/src/contract/compile.ts +1 -0
  31. package/src/contract/containers.ts +19 -0
  32. package/src/contract/context.ts +35 -9
  33. package/src/contract/declaration.ts +2 -0
  34. package/src/contract/defaults.ts +22 -2
  35. package/src/contract/define.ts +29 -3
  36. package/src/contract/index.ts +1 -0
  37. package/src/contract/kit.ts +4 -1
  38. package/src/contract/platform.ts +3 -2
  39. package/src/contract/vocabulary.ts +26 -8
  40. package/src/dev/changes.ts +5 -43
  41. package/src/dev/contract-digest.ts +17 -0
  42. package/src/dev/index.ts +1 -1
  43. package/src/dev/launcher.ts +197 -41
  44. package/src/dev/output.ts +13 -3
  45. package/src/dev/wire.ts +11 -1
  46. package/src/disk-assets.ts +8 -3
  47. package/src/files/archive.ts +2 -2
  48. package/src/files/handle.ts +2 -1
  49. package/src/files/job-names.ts +12 -0
  50. package/src/files/kinds.ts +74 -32
  51. package/src/files/scan.ts +3 -4
  52. package/src/files/streams.ts +3 -1
  53. package/src/implement/anonymous.ts +12 -11
  54. package/src/implement/boot.ts +84 -27
  55. package/src/implement/bounded.ts +21 -2
  56. package/src/implement/capability.ts +16 -4
  57. package/src/implement/dispatch.ts +423 -178
  58. package/src/implement/failures.ts +59 -4
  59. package/src/implement/faults.ts +5 -1
  60. package/src/implement/index.ts +1 -0
  61. package/src/implement/invocation.ts +62 -11
  62. package/src/implement/principal.ts +25 -2
  63. package/src/implement/terminals.ts +93 -0
  64. package/src/implement/tokens.ts +4 -2
  65. package/src/implement/types.ts +22 -4
  66. package/src/implement/workload.ts +42 -16
  67. package/src/jobs/mail.ts +8 -0
  68. package/src/jobs/report.ts +5 -1
  69. package/src/jobs/runner.ts +702 -126
  70. package/src/jobs/schedule.ts +7 -1
  71. package/src/jobs/scrub.ts +14 -1
  72. package/src/jobs/types.ts +6 -0
  73. package/src/spa-fallback.ts +12 -0
  74. package/src/testing/endpoint-access.ts +331 -169
  75. package/src/testing/index.ts +1 -1
  76. package/src/testing/isolation.ts +8 -1
  77. package/src/testing/kit.ts +86 -4
  78. package/src/testing/policy-isolation.ts +2 -2
  79. package/src/testing/proxy.ts +15 -10
  80. package/types/src/agent-skill.d.ts +29 -0
  81. package/types/src/build-recipe.d.ts +70 -0
  82. package/types/src/build.d.ts +29 -0
  83. package/types/src/bun.d.ts +99 -0
  84. package/types/src/client/caller.d.ts +19 -0
  85. package/types/src/client/contract.d.ts +131 -0
  86. package/types/src/client/error-reporting.d.ts +66 -0
  87. package/types/src/client/index.d.ts +4 -0
  88. package/types/src/client/rpc.d.ts +14 -0
  89. package/types/src/client/share.d.ts +2 -0
  90. package/types/src/client/transport.d.ts +42 -0
  91. package/types/src/cloudflare/application.d.ts +73 -0
  92. package/types/src/cloudflare/bindings.d.ts +33 -0
  93. package/types/src/cloudflare/export.d.ts +16 -0
  94. package/types/src/cloudflare/import.d.ts +47 -0
  95. package/types/src/cloudflare/maintenance.d.ts +117 -0
  96. package/types/src/cloudflare/names.d.ts +11 -0
  97. package/types/src/cloudflare/ops.d.ts +81 -0
  98. package/types/src/cloudflare/r2-files.d.ts +9 -0
  99. package/types/src/cloudflare/restore.d.ts +9 -0
  100. package/types/src/cloudflare/tracker.d.ts +29 -0
  101. package/types/src/cloudflare.d.ts +43 -0
  102. package/types/src/contract/app-id.d.ts +2 -0
  103. package/types/src/contract/artifact-schema.d.ts +10 -0
  104. package/types/src/contract/attachment.d.ts +41 -0
  105. package/types/src/contract/build.d.ts +12 -0
  106. package/types/src/contract/capability-cases.d.ts +9 -0
  107. package/types/src/contract/compile.d.ts +11 -0
  108. package/types/src/contract/connect.d.ts +51 -0
  109. package/types/src/contract/containers.d.ts +3 -0
  110. package/types/src/contract/context.d.ts +525 -0
  111. package/types/src/contract/declaration.d.ts +307 -0
  112. package/types/src/contract/defaults.d.ts +226 -0
  113. package/types/src/contract/define.d.ts +376 -0
  114. package/types/src/contract/file.d.ts +44 -0
  115. package/types/src/contract/group.d.ts +274 -0
  116. package/types/src/contract/handled.d.ts +18 -0
  117. package/types/src/contract/index.d.ts +20 -0
  118. package/types/src/contract/kit.d.ts +211 -0
  119. package/types/src/contract/platform.d.ts +9 -0
  120. package/types/src/contract/problems.d.ts +14 -0
  121. package/types/src/contract/redirect.d.ts +25 -0
  122. package/types/src/contract/schema-from-shape.d.ts +10 -0
  123. package/types/src/contract/schema-shape.d.ts +5 -0
  124. package/types/src/contract/snapshot-source.d.ts +15 -0
  125. package/types/src/contract/token.d.ts +58 -0
  126. package/types/src/contract/vocabulary.d.ts +32 -0
  127. package/types/src/contract/webhook-binding.d.ts +24 -0
  128. package/types/src/contract/webhook-scheme.d.ts +23 -0
  129. package/types/src/dev/changes.d.ts +7 -0
  130. package/types/src/dev/contract-digest.d.ts +1 -0
  131. package/types/src/dev/index.d.ts +2 -0
  132. package/types/src/dev/launcher.d.ts +32 -0
  133. package/types/src/dev/output.d.ts +28 -0
  134. package/types/src/dev/wire.d.ts +126 -0
  135. package/types/src/disk-assets.d.ts +6 -0
  136. package/types/src/errors.d.ts +46 -0
  137. package/types/src/fetch.d.ts +7 -0
  138. package/types/src/files/archive.d.ts +26 -0
  139. package/types/src/files/clamscan.d.ts +32 -0
  140. package/types/src/files/handle.d.ts +107 -0
  141. package/types/src/files/job-names.d.ts +9 -0
  142. package/types/src/files/kinds.d.ts +112 -0
  143. package/types/src/files/scan.d.ts +78 -0
  144. package/types/src/files/sniff.d.ts +7 -0
  145. package/types/src/files/streams.d.ts +17 -0
  146. package/types/src/files/treatment.d.ts +18 -0
  147. package/types/src/from-row.d.ts +20 -0
  148. package/types/src/honeypot.d.ts +2 -0
  149. package/types/src/implement/anonymous.d.ts +24 -0
  150. package/types/src/implement/attachment.d.ts +14 -0
  151. package/types/src/implement/boot.d.ts +128 -0
  152. package/types/src/implement/bounded.d.ts +32 -0
  153. package/types/src/implement/browser-config.d.ts +19 -0
  154. package/types/src/implement/capability.d.ts +142 -0
  155. package/types/src/implement/challenge.d.ts +75 -0
  156. package/types/src/implement/client-address.d.ts +11 -0
  157. package/types/src/implement/connect.d.ts +67 -0
  158. package/types/src/implement/crashes.d.ts +31 -0
  159. package/types/src/implement/dispatch.d.ts +251 -0
  160. package/types/src/implement/egress.d.ts +14 -0
  161. package/types/src/implement/environment.d.ts +14 -0
  162. package/types/src/implement/failures.d.ts +58 -0
  163. package/types/src/implement/faults.d.ts +48 -0
  164. package/types/src/implement/headers.d.ts +7 -0
  165. package/types/src/implement/implement.d.ts +58 -0
  166. package/types/src/implement/index.d.ts +25 -0
  167. package/types/src/implement/invocation.d.ts +136 -0
  168. package/types/src/implement/membership.d.ts +201 -0
  169. package/types/src/implement/multipart.d.ts +36 -0
  170. package/types/src/implement/params.d.ts +7 -0
  171. package/types/src/implement/principal.d.ts +57 -0
  172. package/types/src/implement/project.d.ts +11 -0
  173. package/types/src/implement/public.d.ts +61 -0
  174. package/types/src/implement/serve.d.ts +25 -0
  175. package/types/src/implement/terminals.d.ts +33 -0
  176. package/types/src/implement/tokens.d.ts +49 -0
  177. package/types/src/implement/types.d.ts +263 -0
  178. package/types/src/implement/urls.d.ts +15 -0
  179. package/types/src/implement/verifiers.d.ts +19 -0
  180. package/types/src/implement/webhook.d.ts +55 -0
  181. package/types/src/implement/workload.d.ts +61 -0
  182. package/types/src/implement/xlsx.d.ts +6 -0
  183. package/types/src/index.d.ts +12 -0
  184. package/types/src/jobs/exception.d.ts +40 -0
  185. package/types/src/jobs/mail.d.ts +67 -0
  186. package/types/src/jobs/report.d.ts +56 -0
  187. package/types/src/jobs/runner.d.ts +218 -0
  188. package/types/src/jobs/schedule.d.ts +17 -0
  189. package/types/src/jobs/scrub.d.ts +12 -0
  190. package/types/src/jobs/types.d.ts +98 -0
  191. package/types/src/react/caller.d.ts +30 -0
  192. package/types/src/react/errors.d.ts +40 -0
  193. package/types/src/react/hooks.d.ts +110 -0
  194. package/types/src/react/index.d.ts +5 -0
  195. package/types/src/react/provider.d.ts +58 -0
  196. package/types/src/react/store.d.ts +68 -0
  197. package/types/src/react/testing.d.ts +28 -0
  198. package/types/src/react/types.d.ts +33 -0
  199. package/types/src/rpc/builder.d.ts +52 -0
  200. package/types/src/rpc/contract.d.ts +23 -0
  201. package/types/src/rpc/dispatcher.d.ts +11 -0
  202. package/types/src/rpc/types.d.ts +62 -0
  203. package/types/src/service/define.d.ts +42 -0
  204. package/types/src/service/index.d.ts +3 -0
  205. package/types/src/service/serve.d.ts +28 -0
  206. package/types/src/spa-fallback.d.ts +2 -0
  207. package/types/src/standard-schema.d.ts +55 -0
  208. package/types/src/testing/caller.d.ts +95 -0
  209. package/types/src/testing/challenge.d.ts +11 -0
  210. package/types/src/testing/dev.d.ts +97 -0
  211. package/types/src/testing/endpoint-access.d.ts +132 -0
  212. package/types/src/testing/index.d.ts +12 -0
  213. package/types/src/testing/isolation.d.ts +3 -0
  214. package/types/src/testing/kit.d.ts +207 -0
  215. package/types/src/testing/membership.d.ts +132 -0
  216. package/types/src/testing/policy-isolation.d.ts +113 -0
  217. package/types/src/testing/preload.d.ts +1 -0
  218. package/types/src/testing/proxy.d.ts +40 -0
  219. package/types/src/testing/runner.d.ts +8 -0
  220. package/types/src/testing/sample-file.d.ts +5 -0
  221. package/types/src/testing/status.d.ts +4 -0
  222. package/types/src/undumpable.d.ts +5 -0
@@ -0,0 +1,167 @@
1
+ // One step of the original object's point-in-time restore (ADR-0070): the ops operation `restore`, served before the application boots.
2
+
3
+ import {
4
+ OPS_DATA_REFUSED_STATUS,
5
+ OPS_STALE_STATUS,
6
+ type OpsDataRefusal,
7
+ type OpsDataRefusalReason,
8
+ type OpsMode,
9
+ type OpsRestoreArm,
10
+ type OpsRestorePrepare,
11
+ type OpsRestoreRequest,
12
+ type OpsRestoreVerify,
13
+ type OpsStaleRefusal,
14
+ parseOpsRestoreArmAck,
15
+ parseOpsRestorePrepareAck,
16
+ parseOpsRestoreVerifyAck,
17
+ } from '@fabrika/auth-core'
18
+ import { jsonResponse } from '../errors.js'
19
+ import type { MaintenanceBarrier, TurnStep } from './maintenance.js'
20
+ import type { OpsRecovery, OpsStorage, OpsTarget } from './ops.js'
21
+
22
+ /**
23
+ * The KV key prefix of an operation's sentinel, followed by its id. KV, unlike R2, is rewound with the object's SQLite,
24
+ * so the absence of an operation's key proves its restore; no operation writes another's.
25
+ */
26
+ const SENTINEL_PREFIX = '__fabrika/restore-sentinel/'
27
+
28
+ const ABORT_REASON = 'fabrika: point-in-time restore armed'
29
+
30
+ /**
31
+ * One step of the original object's point-in-time restore (ADR-0070 §9 step 6). `prepare` and `arm` run in the
32
+ * barrier's turn, only under the published generation, on an object that is not the one ordinary traffic reaches
33
+ * (`serving`), while it is `inspect`; `verify` writes nothing and runs in any mode.
34
+ */
35
+ export async function serveRestore(target: OpsTarget, barrier: MaintenanceBarrier, step: OpsRestoreRequest, serving: boolean): Promise<Response> {
36
+ const { recovery } = target
37
+ if (recovery === null) {
38
+ return jsonResponse({ refused: 'not_implemented' }, 501)
39
+ }
40
+ const sentinels = kvSentinels(target.storage)
41
+ switch (step.step) {
42
+ case 'prepare':
43
+ return await inTurn(barrier, step.generation, serving, () => prepare(recovery, sentinels, step))
44
+ case 'arm':
45
+ return await inTurn(barrier, step.generation, serving, async () => {
46
+ await barrier.restrictedWrite()
47
+ return await arm(recovery, step)
48
+ })
49
+ case 'verify':
50
+ return await verify(recovery, sentinels, step)
51
+ }
52
+ }
53
+
54
+ /**
55
+ * The first prepare of an operation reads the current bookmark, then the target's, and keeps both under its sentinel
56
+ * key; a retried one answers what it kept. A target not lexically before the current bookmark would keep the sentinel.
57
+ */
58
+ async function prepare(recovery: OpsRecovery, sentinels: SentinelStore, step: OpsRestorePrepare): Promise<TurnStep<Response>> {
59
+ const kept = await sentinels.read(step.sentinel)
60
+ if (kept !== undefined) {
61
+ return answered(answer(parseOpsRestorePrepareAck(kept)))
62
+ }
63
+ const current = await recovery.getCurrentBookmark()
64
+ let target: string
65
+ try {
66
+ target = await recovery.getBookmarkForTime(Date.parse(step.at))
67
+ } catch {
68
+ return answered(dataRefusal('bookmark_unavailable'))
69
+ }
70
+ if (!(target < current)) {
71
+ return answered(dataRefusal('bookmark_unavailable'))
72
+ }
73
+ const ack = parseOpsRestorePrepareAck({ step: 'prepare', current, target })
74
+ if (ack !== null) {
75
+ await sentinels.write(step.sentinel, ack)
76
+ }
77
+ return answered(answer(ack))
78
+ }
79
+
80
+ /** Arms the restore and resets the object once the answer is out, holding the barrier's turn until then. */
81
+ async function arm(recovery: OpsRecovery, step: OpsRestoreArm): Promise<TurnStep<Response>> {
82
+ let undo: string
83
+ try {
84
+ undo = await recovery.onNextSessionRestoreBookmark(step.target)
85
+ } catch {
86
+ return answered(dataRefusal('bookmark_unavailable'))
87
+ }
88
+ const response = answer(parseOpsRestoreArmAck({ step: 'arm', undo }))
89
+ // workerd's abort throws, so on a real object the turn is never released and no transition is acknowledged after it.
90
+ const reset = new Promise<void>((resolve) =>
91
+ setTimeout(() => {
92
+ recovery.abort(ABORT_REASON)
93
+ resolve()
94
+ }, 0)
95
+ )
96
+ return { value: response, holdUntil: reset }
97
+ }
98
+
99
+ /** Present while the KV holds this operation's key: a restore to a target before its `prepare` removed it. */
100
+ async function verify(recovery: OpsRecovery, sentinels: SentinelStore, step: OpsRestoreVerify): Promise<Response> {
101
+ const present = (await sentinels.read(step.sentinel)) !== undefined
102
+ return answer(parseOpsRestoreVerifyAck({ step: 'verify', sentinel: present ? 'present' : 'absent', bookmark: await recovery.getCurrentBookmark() }))
103
+ }
104
+
105
+ /**
106
+ * ADR-0070 §1 and §9: inside the barrier's turn, ADR-0069's stale refusal unless `generation` is the published one,
107
+ * then `serving_object` on the object of ordinary traffic, then `wrong_mode` unless `inspect`.
108
+ */
109
+ async function inTurn(
110
+ barrier: MaintenanceBarrier,
111
+ generation: number,
112
+ serving: boolean,
113
+ work: () => Promise<TurnStep<Response>>,
114
+ ): Promise<Response> {
115
+ const result = await barrier.step(generation, (mode: OpsMode) => {
116
+ if (serving) {
117
+ return Promise.resolve(answered(dataRefusal('serving_object')))
118
+ }
119
+ return mode === 'inspect' ? work() : Promise.resolve(answered(dataRefusal('wrong_mode')))
120
+ })
121
+ if (result.kind === 'ran') {
122
+ return result.value
123
+ }
124
+ const refusal: OpsStaleRefusal = { refused: 'stale_generation', published: result.published }
125
+ return jsonResponse(refusal, OPS_STALE_STATUS)
126
+ }
127
+
128
+ function answered(response: Response): TurnStep<Response> {
129
+ return { value: response, holdUntil: null }
130
+ }
131
+
132
+ function dataRefusal(reason: OpsDataRefusalReason): Response {
133
+ const refusal: OpsDataRefusal = { refused: reason, table: null }
134
+ return jsonResponse(refusal, OPS_DATA_REFUSED_STATUS)
135
+ }
136
+
137
+ /** An answer the wire's own parser accepted; a bookmark the storage handed out that it refuses fails the step. */
138
+ function answer(parsed: object | null): Response {
139
+ if (parsed === null) {
140
+ throw new Error("the object's restore answer does not parse as the wire's acknowledgement")
141
+ }
142
+ return jsonResponse(parsed, 200)
143
+ }
144
+
145
+ /** The operations' sentinels in the object's KV storage, each under its own key. */
146
+ interface SentinelStore {
147
+ /** What the operation's key holds, `undefined` when it holds nothing. */
148
+ read(sentinel: string): Promise<unknown>
149
+ write(sentinel: string, value: unknown): Promise<void>
150
+ }
151
+
152
+ function kvSentinels(storage: OpsStorage): SentinelStore {
153
+ return {
154
+ async read(sentinel) {
155
+ if (storage.get === undefined) {
156
+ throw new Error("the object's storage has no get; a Durable Object's storage has it")
157
+ }
158
+ return await storage.get(`${SENTINEL_PREFIX}${sentinel}`)
159
+ },
160
+ async write(sentinel, value) {
161
+ if (storage.put === undefined) {
162
+ throw new Error("the object's storage has no put; a Durable Object's storage has it")
163
+ }
164
+ await storage.put(`${SENTINEL_PREFIX}${sentinel}`, value)
165
+ },
166
+ }
167
+ }
@@ -0,0 +1,192 @@
1
+ // The pending-work tracker (ADR-0069 §2, ADR-0070 §10): the ops operation `timers`, diagnostics only. While it is on, it
2
+ // wraps the isolate's global timers and records each live timer and each `waitUntil` promise with the stack that
3
+ // registered it, scrubbed and bounded. Its scope is the isolate, not one object: every object the isolate hosts shares
4
+ // the switch and the records, and only the isolate's eviction resets them, so the next isolate's tracker starts off.
5
+
6
+ import {
7
+ OPS_TIMER_STACK_MAX_BYTES,
8
+ OPS_TIMER_STACK_MAX_FRAMES,
9
+ OPS_TIMERS_CAP,
10
+ type OpsTimer,
11
+ type OpsTimersRequest,
12
+ type OpsTimersView,
13
+ } from '@fabrika/auth-core'
14
+ import { jsonResponse } from '../errors.js'
15
+ import { type Scrubber, secretScrubber } from '../jobs/scrub.js'
16
+
17
+ /** The global timers the tracker wraps while it is on; `globalThis` fits it. */
18
+ export interface TimerScope {
19
+ setTimeout(handler: unknown, delay?: unknown, ...args: unknown[]): unknown
20
+ setInterval(handler: unknown, delay?: unknown, ...args: unknown[]): unknown
21
+ clearTimeout(id?: unknown): void
22
+ clearInterval(id?: unknown): void
23
+ }
24
+
25
+ export interface TimerTracker {
26
+ /** Switches tracking on (wrapping the scope's timers) or off (restoring them and forgetting every record). */
27
+ track(on: boolean): void
28
+ /**
29
+ * While tracking is on, records `promise` until it settles and answers a chain that settles as it does, rejection
30
+ * included, so the caller hands the chain to `waitUntil` and an unhandled rejection stays unhandled. Off, `promise`.
31
+ */
32
+ pending<T>(promise: Promise<T>): Promise<T>
33
+ /** The live records, oldest first, at most `OPS_TIMERS_CAP` of them. */
34
+ view(): OpsTimersView
35
+ }
36
+
37
+ type Caller = (...args: never[]) => unknown
38
+
39
+ /** A tracker over `scope`'s timers, off until `track(true)`; each stack is scrubbed by `scrubber`. */
40
+ export function timerTracker(scope: TimerScope, now: () => number, scrubber: Scrubber): TimerTracker {
41
+ // Keyed by the timer's handle (`handleKey`), or by a fresh object for a promise; a Map keeps creation order.
42
+ const live = new Map<unknown, OpsTimer>()
43
+ /** The scope's own timers and the tracker's wrappers over them, while tracking is on. */
44
+ let installed: { readonly own: TimerScope; readonly wrapped: TimerScope } | null = null
45
+
46
+ const record = (kind: OpsTimer['kind'], delay: unknown, caller: Caller): OpsTimer => ({
47
+ kind,
48
+ since: new Date(now()).toISOString(),
49
+ delayMs: kind === 'waitUntil' ? null : delayOf(delay),
50
+ stack: stackBelow(caller, scrubber),
51
+ })
52
+
53
+ // A wrapper that other code kept after `track(false)` still works; it records only while tracking is on.
54
+ const wrap = (own: TimerScope): TimerScope => {
55
+ /** The record of a timer about to start, taken in the wrapper's own frame; `null` when nothing is recorded. */
56
+ const recorded = (kind: 'timeout' | 'interval', handler: unknown, delay: unknown, caller: Caller): OpsTimer | null =>
57
+ installed === null || typeof handler !== 'function' ? null : record(kind, delay, caller)
58
+ const schedule = (kind: 'timeout' | 'interval', entry: OpsTimer | null, handler: unknown, delay: unknown, args: readonly unknown[]): unknown => {
59
+ const start = kind === 'timeout' ? own.setTimeout : own.setInterval
60
+ if (entry === null || typeof handler !== 'function') {
61
+ return Reflect.apply(start, scope, [handler, delay, ...args])
62
+ }
63
+ let id: unknown
64
+ // An ordinary function, so the runtime's receiver (Bun passes the handle) reaches the handler.
65
+ const run = function(this: unknown, ...callArgs: unknown[]): unknown {
66
+ if (kind === 'timeout') {
67
+ live.delete(handleKey(id))
68
+ }
69
+ return Reflect.apply(handler, this, callArgs)
70
+ }
71
+ id = Reflect.apply(start, scope, [run, delay, ...args])
72
+ live.set(handleKey(id), entry)
73
+ return id
74
+ }
75
+ const clear = (stop: (id?: unknown) => void, id: unknown): void => {
76
+ // A timeout's and an interval's handles share one pool, so either clear ends either kind.
77
+ live.delete(handleKey(id))
78
+ Reflect.apply(stop, scope, [id])
79
+ }
80
+ // The stack is taken before `schedule`: a proper tail call (JavaScriptCore) would drop the frame `stackBelow` cuts at.
81
+ return {
82
+ setTimeout: function setTimeout(handler, delay, ...args) {
83
+ return schedule('timeout', recorded('timeout', handler, delay, setTimeout), handler, delay, args)
84
+ },
85
+ setInterval: function setInterval(handler, delay, ...args) {
86
+ return schedule('interval', recorded('interval', handler, delay, setInterval), handler, delay, args)
87
+ },
88
+ clearTimeout: (id) => clear(own.clearTimeout, id),
89
+ clearInterval: (id) => clear(own.clearInterval, id),
90
+ }
91
+ }
92
+
93
+ const pending = <T>(promise: Promise<T>): Promise<T> => {
94
+ if (installed === null) {
95
+ return promise
96
+ }
97
+ const key = {}
98
+ live.set(key, record('waitUntil', null, pending))
99
+ return promise.then(
100
+ (value) => {
101
+ live.delete(key)
102
+ return value
103
+ },
104
+ (error: unknown) => {
105
+ live.delete(key)
106
+ throw error
107
+ },
108
+ )
109
+ }
110
+
111
+ return {
112
+ track(on) {
113
+ if (on && installed === null) {
114
+ const own = { setTimeout: scope.setTimeout, setInterval: scope.setInterval, clearTimeout: scope.clearTimeout, clearInterval: scope.clearInterval }
115
+ const wrapped = wrap(own)
116
+ installed = { own, wrapped }
117
+ scope.setTimeout = wrapped.setTimeout
118
+ scope.setInterval = wrapped.setInterval
119
+ scope.clearTimeout = wrapped.clearTimeout
120
+ scope.clearInterval = wrapped.clearInterval
121
+ } else if (!on && installed !== null) {
122
+ const { own, wrapped } = installed
123
+ // Restores only what is still the tracker's own, so a later wrapper by other code stays in place.
124
+ if (scope.setTimeout === wrapped.setTimeout) scope.setTimeout = own.setTimeout
125
+ if (scope.setInterval === wrapped.setInterval) scope.setInterval = own.setInterval
126
+ if (scope.clearTimeout === wrapped.clearTimeout) scope.clearTimeout = own.clearTimeout
127
+ if (scope.clearInterval === wrapped.clearInterval) scope.clearInterval = own.clearInterval
128
+ installed = null
129
+ live.clear()
130
+ }
131
+ },
132
+ pending,
133
+ view() {
134
+ const timers = [...live.values()]
135
+ return { tracking: installed !== null, timers: timers.slice(0, OPS_TIMERS_CAP), omitted: Math.max(0, timers.length - OPS_TIMERS_CAP) }
136
+ },
137
+ }
138
+ }
139
+
140
+ /**
141
+ * One key for every form of a handle a clear accepts: Bun's handle object also clears by its number, workerd's handle is
142
+ * that number already.
143
+ */
144
+ function handleKey(id: unknown): unknown {
145
+ if (typeof id !== 'object' || id === null) {
146
+ return id
147
+ }
148
+ const numeric = Number(id)
149
+ return Number.isSafeInteger(numeric) ? numeric : id
150
+ }
151
+
152
+ /** The delay a timer was asked for, in whole milliseconds: what the runtime coerces to a number, else 0. */
153
+ function delayOf(delay: unknown): number {
154
+ const ms = typeof delay === 'number' || typeof delay === 'string' ? Number(delay) : 0
155
+ return Number.isFinite(ms) && ms > 0 ? Math.min(Math.trunc(ms), Number.MAX_SAFE_INTEGER) : 0
156
+ }
157
+
158
+ /** The frames below `caller`, without the tracker's own: at most `OPS_TIMER_STACK_MAX_FRAMES`, scrubbed, then cut to bytes. */
159
+ function stackBelow(caller: Caller, scrubber: Scrubber): string {
160
+ const holder: { stack?: string } = {}
161
+ Error.captureStackTrace(holder, caller)
162
+ const frames = (holder.stack ?? '').replace(/^Error\n/, '').split('\n').slice(0, OPS_TIMER_STACK_MAX_FRAMES)
163
+ return cutToBytes(scrubber.scrub(frames.join('\n')), OPS_TIMER_STACK_MAX_BYTES)
164
+ }
165
+
166
+ /** `text` cut at a character boundary so its UTF-8 encoding fits `bytes`. */
167
+ function cutToBytes(text: string, bytes: number): string {
168
+ const { read } = new TextEncoder().encodeInto(text, new Uint8Array(bytes))
169
+ return text.slice(0, read)
170
+ }
171
+
172
+ /**
173
+ * The isolate's tracker, shared by every object the isolate hosts. Its scrubber knows the credential shapes only: the
174
+ * tracker is reached before any object captures the environment's secret values.
175
+ */
176
+ const isolateTracker = timerTracker(globalThis, () => Date.now(), secretScrubber([]))
177
+
178
+ /**
179
+ * Records a promise an object hands to `waitUntil` while the tracker is on. Hand the answer, not `promise`, to
180
+ * `waitUntil`: it rejects as `promise` does, so an unhandled rejection still reaches the crash reporting.
181
+ */
182
+ export function trackPending<T>(promise: Promise<T>): Promise<T> {
183
+ return isolateTracker.pending(promise)
184
+ }
185
+
186
+ /** The isolate's live timers and `waitUntil` promises; `track` switches the isolate's tracker on or off first. */
187
+ export function serveTimers(request: OpsTimersRequest): Response {
188
+ if (request.track !== null) {
189
+ isolateTracker.track(request.track)
190
+ }
191
+ return jsonResponse(isolateTracker.view(), 200)
192
+ }
package/src/cloudflare.ts CHANGED
@@ -1,17 +1,31 @@
1
1
  // ─── Cloudflare Workers adapter ──────────────────────────────────────
2
2
 
3
- import { DecodedIamMembership } from '@fabrika/auth'
4
- import type { IamMembershipRpc } from '@fabrika/auth-core'
5
- import { parseJwks } from '@fabrika/jwks'
3
+ import {
4
+ type ApplicationObjects,
5
+ FABRIKA_APPLICATION_OBJECT,
6
+ FABRIKA_APPLICATION_OBJECTS,
7
+ FABRIKA_PROXY_SECRET,
8
+ OPS_PREFIX,
9
+ opsRefusal,
10
+ parseApplicationObjects,
11
+ parseOpsOperation,
12
+ PROXY_SECRET_HEADER,
13
+ } from '@fabrika/auth-core'
14
+ import { type ContractWorkerOptions, type ImplementationLoader, registerApplication, TICK_HEADER } from './cloudflare/application.js'
15
+ import { method } from './cloudflare/bindings.js'
16
+ import { CLOUDFLARE_APPLICATION_BINDING } from './cloudflare/names.js'
17
+ import { jsonBody, objectNamed, opsAccess, opsAuthenticated } from './cloudflare/ops.js'
6
18
  import type { FetchService, RequestExecutionContext } from './fetch.js'
7
- import { boot, type ContractApp, type IamKeySource } from './implement/boot.js'
8
- import { CONNECT_BINDING_PREFIX, type ConnectFetch } from './implement/connect.js'
9
- import { type CrashEvents, environmentCrashReporter, reportSurvivedCrashes } from './implement/crashes.js'
10
- import type { SpaAssets } from './implement/dispatch.js'
11
- import { captureEnvironment } from './implement/environment.js'
12
- import type { ContractImplementation } from './implement/implement.js'
13
19
 
14
20
  export { markProductionProcess } from '@fabrika/db/production'
21
+ export {
22
+ type ApplicationMigration,
23
+ type ApplicationState,
24
+ type ApplicationStorage,
25
+ type ContractWorkerOptions,
26
+ FabrikaApplication,
27
+ type ImplementationLoader,
28
+ } from './cloudflare/application.js'
15
29
 
16
30
  /** Minimal structural view of a Workers `ExecutionContext`. */
17
31
  export interface CloudflareExecutionContext extends RequestExecutionContext {
@@ -58,166 +72,106 @@ export function createCloudflareWorker<Env>(
58
72
 
59
73
  // ─── Contract applications ───────────────────────────────────────────
60
74
 
61
- /** The framework's bindings: IAM's application entrypoint and the Workers Assets of the SPA. No handler sees them. */
62
- const FRAMEWORK_BINDINGS: ReadonlySet<string> = new Set(['IAM', 'ASSETS'])
63
-
64
- function method(target: unknown, name: string): ((...args: unknown[]) => unknown) | null {
65
- if (typeof target !== 'object' || target === null || !(name in target)) {
66
- return null
67
- }
68
- const found: unknown = Reflect.get(target, name)
69
- return typeof found === 'function' ? (...args) => Reflect.apply(found, target, args) : null
70
- }
71
-
72
- function bindingKeySource(binding: unknown): IamKeySource {
73
- const getJwks = method(binding, 'getJwks')
74
- if (getJwks === null) {
75
- throw new Error('the IAM binding is missing (env.IAM); the platform binds it to every application Worker')
76
- }
77
- return {
78
- async getJwks() {
79
- const jwks = parseJwks(await getJwks())
80
- if (jwks === null) {
81
- throw new Error('IAM returned no usable key set')
82
- }
83
- return jwks
84
- },
75
+ /** The environment's proxy secret, which every request the Worker forwards to its object carries. */
76
+ function proxySecretOf(env: Readonly<Record<string, unknown>>): string {
77
+ const secret = env[FABRIKA_PROXY_SECRET]
78
+ if (typeof secret !== 'string' || secret === '') {
79
+ throw new Error(`${FABRIKA_PROXY_SECRET} is not set; the application's Worker forwards nothing to its object without it`)
85
80
  }
81
+ return secret
86
82
  }
87
83
 
88
84
  /**
89
- * IAM's membership operations on the `IAM` binding (`PropustkaApplication`), every answer decoded like the HTTP
90
- * transport's. A binding without them is no membership transport, and `boot` refuses a contract that needs one.
85
+ * The object of ordinary traffic and the objects an ops request may name, all in the environment's own namespace.
86
+ * Without either variable (an older deploy) the one object is `application`.
91
87
  */
92
- function bindingMembership(binding: unknown): IamMembershipRpc | undefined {
93
- const methods = ['requestDelegation', 'createScope', 'assignMember', 'revokeMember', 'listMembers', 'issueLink', 'revokeLink'] as const
94
- if (!methods.every((name) => method(binding, name) !== null)) {
95
- return undefined
88
+ function applicationObjects(env: Readonly<Record<string, unknown>>): ApplicationObjects {
89
+ const object = env[FABRIKA_APPLICATION_OBJECT]
90
+ const objects = env[FABRIKA_APPLICATION_OBJECTS]
91
+ const parsed = parseApplicationObjects(typeof object === 'string' ? object : undefined, typeof objects === 'string' ? objects : undefined)
92
+ if (parsed === null) {
93
+ throw new Error(`${FABRIKA_APPLICATION_OBJECT} and ${FABRIKA_APPLICATION_OBJECTS} name no valid set of objects; a deploy writes both`)
96
94
  }
97
- return new DecodedIamMembership(async (name, input) => {
98
- const call = method(binding, name)
99
- if (call === null) {
100
- throw new Error(`the IAM binding has no ${name}`)
101
- }
102
- return await call(input)
103
- })
95
+ return parsed
104
96
  }
105
97
 
106
- function bindingAssets(binding: unknown): SpaAssets | undefined {
107
- const fetchAsset = method(binding, 'fetch')
108
- if (fetchAsset === null) {
109
- return undefined
98
+ /** The object `name` of the environment's namespace (`FABRIKA_APPLICATION`), as a fetch. */
99
+ function applicationObject(env: Readonly<Record<string, unknown>>, name: string): (request: Request) => Promise<Response> {
100
+ const namespace = env[CLOUDFLARE_APPLICATION_BINDING]
101
+ const idFromName = method(namespace, 'idFromName')
102
+ const get = method(namespace, 'get')
103
+ if (idFromName === null || get === null) {
104
+ throw new Error(`the ${CLOUDFLARE_APPLICATION_BINDING} binding is missing; the provider binds the application's Durable Object to its Worker`)
110
105
  }
111
- return {
112
- async serve(_mount, request) {
113
- const response: unknown = await fetchAsset(request)
114
- if (!(response instanceof Response)) {
115
- throw new Error('the ASSETS binding answered something that is not a Response')
116
- }
117
- return response
118
- },
106
+ const stub: unknown = get(idFromName(name))
107
+ // Read, not tested with `in`: a stub answers `fetch` without owning the property.
108
+ const fetchObject: unknown = typeof stub === 'object' && stub !== null ? Reflect.get(stub, 'fetch') : undefined
109
+ if (typeof fetchObject !== 'function') {
110
+ throw new Error(`the ${CLOUDFLARE_APPLICATION_BINDING} binding answered no object`)
111
+ }
112
+ return async (request) => {
113
+ const response: unknown = await Reflect.apply(fetchObject, stub, [request])
114
+ if (!(response instanceof Response)) {
115
+ throw new Error("the application's object answered something that is not a Response")
116
+ }
117
+ return response
119
118
  }
120
119
  }
121
120
 
122
121
  /**
123
- * The service bindings to owners' proxy Workers (`FABRIKA_CONNECT_<IMPORT>`), which `captureEnvironment` keeps from
124
- * the application because no `FABRIKA_*` value reaches it. A binding routes by itself: the URL it is called with
125
- * carries the owner's host, which the proxy Worker selects the application by.
122
+ * An ops request reaches the object its body names, when the environment lists it (ADR-0069 §1). Every refusal here
123
+ * is the same answer the object gives, and the object checks everything again.
126
124
  */
127
- function connectBindings(env: Readonly<Record<string, unknown>>): Record<string, ConnectFetch> {
128
- const bindings: Record<string, ConnectFetch> = {}
129
- for (const [name, binding] of Object.entries(env)) {
130
- // Read, not tested with `in`: a binding stub may answer `fetch` without owning the property (Lopata's does not).
131
- const fetchOwner: unknown = name.startsWith(CONNECT_BINDING_PREFIX) && typeof binding === 'object' && binding !== null
132
- ? Reflect.get(binding, 'fetch')
133
- : undefined
134
- if (typeof fetchOwner === 'function') {
135
- bindings[name] = async (request) => {
136
- const response: unknown = await Reflect.apply(fetchOwner, binding, [request])
137
- if (!(response instanceof Response)) {
138
- throw new Error(`the ${name} binding answered something that is not a Response`)
139
- }
140
- return response
141
- }
142
- }
125
+ async function forwardOps(request: Request, env: Readonly<Record<string, unknown>>): Promise<Response> {
126
+ const access = opsAccess(env)
127
+ // Receiver authentication of Control's key, as the object runs it; no enforcement decision. It runs before the body is
128
+ // read or any object looked up, so an unauthenticated caller wakes no object and learns nothing of the names.
129
+ if (access === null || !opsAuthenticated(request, access)) {
130
+ return opsRefusal()
143
131
  }
144
- return bindings
145
- }
146
-
147
- /** The application module, imported only after the environment was captured: the generated entrypoint's `import()`. */
148
- export type ImplementationLoader = () => Promise<{ readonly default: ContractImplementation }>
149
-
150
- export interface ContractWorkerOptions {
151
- /** Where the isolate hears of an unhandled rejection; the global `unhandledrejection` event by default. */
152
- readonly rejections?: CrashEvents
153
- /** What posts a report to Operations' ingest; `fetch` by default. */
154
- readonly operationsFetch?: (request: Request) => Promise<Response>
132
+ const operation = parseOpsOperation(new URL(request.url).pathname)
133
+ const object = operation === null ? null : objectNamed(operation, await jsonBody(request.clone()))
134
+ if (object === null || !access.objects.objects.includes(object)) {
135
+ return opsRefusal()
136
+ }
137
+ return await applicationObject(env, object)(request)
155
138
  }
156
139
 
157
- /** The isolate's `unhandledrejection` event. Listening leaves the runtime's own handling, its log line, in place. */
158
- function globalRejectionEvents(): CrashEvents {
159
- return {
160
- listen(listener) {
161
- const rejection = (event: Event) => listener('unhandled_rejection', Reflect.get(event, 'reason'))
162
- globalThis.addEventListener('unhandledrejection', rejection)
163
- return () => globalThis.removeEventListener('unhandledrejection', rejection)
164
- },
165
- }
140
+ export interface ContractWorker {
141
+ fetch(request: Request, env: Readonly<Record<string, unknown>>, exec: CloudflareExecutionContext): Promise<Response>
142
+ scheduled(controller: CloudflareScheduledController, env: Readonly<Record<string, unknown>>, exec: CloudflareExecutionContext): Promise<void>
166
143
  }
167
144
 
168
145
  /**
169
- * A Worker module for a contract application, called only by the generated entrypoint. A Worker receives its
170
- * environment with the first request, so the framework captures it, scrubs the process environment and only then
171
- * imports the application and boots it, once per environment object. With an Operations DSN, the first failed boot
172
- * of an isolate is reported, and once one booted, every unhandled rejection of the isolate is, within a budget.
146
+ * The Worker module of a contract application, called only by the generated entrypoint, which also exports
147
+ * `FabrikaApplication`. The application runs in the environment's Durable Object (ADR-0065): `fetch` forwards every
148
+ * request to it with the proxy secret, the proxy's own headers unchanged, and `scheduled` forwards the repair tick: the
149
+ * object's alarm runs the jobs, and the tick repairs its wakes and arms an alarm nothing armed yet.
150
+ * An ops request goes to the object its body names instead (ADR-0069). The object captures the environment, imports
151
+ * the application and boots it.
173
152
  */
174
- export function createContractWorker(load: ImplementationLoader, options: ContractWorkerOptions = {}): {
175
- fetch(request: Request, env: Readonly<Record<string, unknown>>, exec: CloudflareExecutionContext): Promise<Response>
176
- } {
177
- const booted = new WeakMap<object, Promise<ContractApp>>()
178
- let bootFailureReported = false
179
- let watchingRejections = false
180
- const bootFor = async (env: Readonly<Record<string, unknown>>, exec: CloudflareExecutionContext): Promise<ContractApp> => {
181
- const variables = Object.fromEntries(Object.entries(env).filter(([name]) => !FRAMEWORK_BINDINGS.has(name)))
182
- const environment = captureEnvironment(variables)
183
- const crashes = environmentCrashReporter(environment, options.operationsFetch)
184
- let contractApp: ContractApp
185
- try {
186
- const { default: app } = await load()
187
- contractApp = boot(app, {
188
- environment,
189
- iam: bindingKeySource(env['IAM']),
190
- assets: bindingAssets(env['ASSETS']),
191
- membership: bindingMembership(env['IAM']),
192
- connectBindings: connectBindings(env),
193
- // The proxy Worker sets `X-Fabrika-Client-Ip` from `CF-Connecting-IP`, the visitor Cloudflare saw.
194
- clientAddress: 'vouched',
195
- ...(options.operationsFetch === undefined ? {} : { operationsFetch: options.operationsFetch }),
196
- })
197
- } catch (error) {
198
- // Every request of a failed isolate boots again; one report says it.
199
- if (crashes !== null && !bootFailureReported) {
200
- bootFailureReported = true
201
- exec.waitUntil(crashes.report('boot_failed', error))
202
- }
203
- throw error
204
- }
205
- if (crashes !== null && !watchingRejections) {
206
- watchingRejections = true
207
- reportSurvivedCrashes(options.rejections ?? globalRejectionEvents(), crashes)
208
- }
209
- return contractApp
210
- }
153
+ export function createContractWorker(load: ImplementationLoader, options: ContractWorkerOptions = {}): ContractWorker {
154
+ registerApplication(load, options)
211
155
  return {
212
- async fetch(request, env, exec) {
213
- let contractApp = booted.get(env)
214
- if (contractApp === undefined) {
215
- contractApp = bootFor(env, exec)
216
- booted.set(env, contractApp)
217
- // A failed boot is not cached: the next request boots again and fails with the same problems.
218
- contractApp.catch(() => booted.delete(env))
156
+ async fetch(request, env) {
157
+ const headers = new Headers(request.headers)
158
+ headers.delete(TICK_HEADER)
159
+ headers.set(PROXY_SECRET_HEADER, proxySecretOf(env))
160
+ const forwarded = new Request(request, { headers })
161
+ if (new URL(request.url).pathname.startsWith(OPS_PREFIX)) {
162
+ return await forwardOps(forwarded, env)
163
+ }
164
+ return await applicationObject(env, applicationObjects(env).object)(forwarded)
165
+ },
166
+ async scheduled(controller, env) {
167
+ const tick = new Request('https://application.invalid/', {
168
+ method: 'POST',
169
+ headers: { [PROXY_SECRET_HEADER]: proxySecretOf(env), [TICK_HEADER]: String(controller.scheduledTime) },
170
+ })
171
+ const response = await applicationObject(env, applicationObjects(env).object)(tick)
172
+ if (!response.ok) {
173
+ throw new Error(`the application's object answered the repair tick with ${response.status}`)
219
174
  }
220
- return (await contractApp).fetch(request, exec)
221
175
  },
222
176
  }
223
177
  }
@@ -0,0 +1,5 @@
1
+ // A leaf module: the contract (client side included) and the build recipe both read the id rule, and the contract must
2
+ // not reach the recipe's server-side modules through it.
3
+
4
+ /** The contract's application id rule; an id that holds to it reaches a generated script unquoted. */
5
+ export const CONTRACT_APP_ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/