@fabrika/app 0.9.0-dev.4 → 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.
- package/package.json +9 -9
- package/skill/SKILL.md +41 -14
- package/skill/references/app-setup.md +43 -12
- package/skill/references/dev.md +2 -1
- package/skill/references/endpoint.md +30 -24
- package/skill/references/errors.md +40 -35
- package/skill/references/files.md +4 -2
- package/skill/references/jobs.md +21 -4
- package/skill/references/table-and-migration.md +19 -2
- package/skill/references/tests.md +40 -1
- package/skill/references/webhooks-links-connectors.md +1 -1
- package/src/build-recipe.ts +198 -0
- package/src/build.ts +60 -4
- package/src/bun.ts +181 -13
- package/src/cloudflare/application.ts +822 -0
- package/src/cloudflare/bindings.ts +159 -0
- package/src/cloudflare/export.ts +641 -0
- package/src/cloudflare/import.ts +1021 -0
- package/src/cloudflare/maintenance.ts +518 -0
- package/src/cloudflare/names.ts +16 -0
- package/src/cloudflare/ops.ts +375 -0
- package/src/cloudflare/r2-files.ts +172 -0
- package/src/cloudflare/restore.ts +167 -0
- package/src/cloudflare/tracker.ts +192 -0
- package/src/cloudflare.ts +100 -146
- package/src/contract/app-id.ts +5 -0
- package/src/contract/artifact-schema.ts +9 -1
- package/src/contract/build.ts +40 -2
- package/src/contract/compile.ts +1 -0
- package/src/contract/context.ts +35 -9
- package/src/contract/declaration.ts +2 -0
- package/src/contract/defaults.ts +22 -2
- package/src/contract/define.ts +29 -3
- package/src/contract/kit.ts +4 -1
- package/src/contract/platform.ts +3 -2
- package/src/contract/vocabulary.ts +26 -8
- package/src/dev/launcher.ts +50 -4
- package/src/disk-assets.ts +8 -3
- package/src/files/archive.ts +2 -2
- package/src/files/job-names.ts +12 -0
- package/src/files/kinds.ts +73 -31
- package/src/files/scan.ts +3 -4
- package/src/files/streams.ts +3 -1
- package/src/implement/anonymous.ts +12 -11
- package/src/implement/boot.ts +75 -6
- package/src/implement/bounded.ts +21 -2
- package/src/implement/capability.ts +15 -3
- package/src/implement/dispatch.ts +419 -177
- package/src/implement/failures.ts +17 -1
- package/src/implement/faults.ts +1 -0
- package/src/implement/index.ts +1 -0
- package/src/implement/invocation.ts +58 -10
- package/src/implement/principal.ts +25 -2
- package/src/implement/terminals.ts +93 -0
- package/src/implement/workload.ts +42 -16
- package/src/jobs/mail.ts +8 -0
- package/src/jobs/report.ts +5 -1
- package/src/jobs/runner.ts +672 -113
- package/src/jobs/schedule.ts +7 -1
- package/src/jobs/scrub.ts +14 -1
- package/src/jobs/types.ts +6 -0
- package/src/spa-fallback.ts +12 -0
- package/src/testing/endpoint-access.ts +307 -152
- package/src/testing/isolation.ts +8 -1
- package/src/testing/kit.ts +80 -2
- package/src/testing/proxy.ts +15 -10
- package/types/src/build-recipe.d.ts +70 -0
- package/types/src/build.d.ts +19 -1
- package/types/src/bun.d.ts +34 -1
- package/types/src/cloudflare/application.d.ts +73 -0
- package/types/src/cloudflare/bindings.d.ts +33 -0
- package/types/src/cloudflare/export.d.ts +16 -0
- package/types/src/cloudflare/import.d.ts +51 -0
- package/types/src/cloudflare/maintenance.d.ts +117 -0
- package/types/src/cloudflare/names.d.ts +11 -0
- package/types/src/cloudflare/ops.d.ts +81 -0
- package/types/src/cloudflare/r2-files.d.ts +9 -0
- package/types/src/cloudflare/restore.d.ts +9 -0
- package/types/src/cloudflare/tracker.d.ts +29 -0
- package/types/src/cloudflare.d.ts +12 -18
- package/types/src/contract/app-id.d.ts +2 -0
- package/types/src/contract/artifact-schema.d.ts +2 -0
- package/types/src/contract/context.d.ts +35 -11
- package/types/src/contract/declaration.d.ts +4 -0
- package/types/src/contract/defaults.d.ts +19 -1
- package/types/src/contract/define.d.ts +20 -3
- package/types/src/contract/kit.d.ts +2 -1
- package/types/src/contract/platform.d.ts +2 -2
- package/types/src/contract/vocabulary.d.ts +9 -7
- package/types/src/disk-assets.d.ts +4 -1
- package/types/src/files/job-names.d.ts +9 -0
- package/types/src/files/kinds.d.ts +21 -14
- package/types/src/files/scan.d.ts +1 -3
- package/types/src/implement/anonymous.d.ts +2 -4
- package/types/src/implement/boot.d.ts +17 -1
- package/types/src/implement/bounded.d.ts +11 -1
- package/types/src/implement/capability.d.ts +4 -2
- package/types/src/implement/dispatch.d.ts +34 -1
- package/types/src/implement/failures.d.ts +5 -0
- package/types/src/implement/faults.d.ts +1 -0
- package/types/src/implement/index.d.ts +1 -0
- package/types/src/implement/invocation.d.ts +22 -7
- package/types/src/implement/principal.d.ts +6 -1
- package/types/src/implement/terminals.d.ts +33 -0
- package/types/src/implement/workload.d.ts +5 -0
- package/types/src/jobs/runner.d.ts +66 -2
- package/types/src/jobs/schedule.d.ts +2 -0
- package/types/src/jobs/types.d.ts +6 -0
- package/types/src/spa-fallback.d.ts +2 -0
- package/types/src/testing/endpoint-access.d.ts +37 -5
- package/types/src/testing/isolation.d.ts +1 -1
- package/types/src/testing/kit.d.ts +22 -1
- package/types/src/testing/proxy.d.ts +4 -4
|
@@ -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 {
|
|
4
|
-
|
|
5
|
-
|
|
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
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
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
|
-
*
|
|
90
|
-
*
|
|
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
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
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
|
|
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
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
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
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
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
|
-
*
|
|
124
|
-
* the
|
|
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
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
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
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
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
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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
|
-
*
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
*
|
|
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
|
-
|
|
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
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
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-]*$/
|