@yaks/durable-object 0.0.0-stage → 0.2.36
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/LICENSE +202 -0
- package/README.md +554 -2
- package/_dist/alarm.d.ts +35 -0
- package/_dist/alarm.d.ts.map +1 -0
- package/_dist/ceiling.d.ts +167 -0
- package/_dist/ceiling.d.ts.map +1 -0
- package/_dist/compose.d.ts +79 -0
- package/_dist/compose.d.ts.map +1 -0
- package/_dist/copy.d.ts +67 -0
- package/_dist/copy.d.ts.map +1 -0
- package/_dist/door.d.ts +172 -0
- package/_dist/door.d.ts.map +1 -0
- package/_dist/job.d.ts +26 -0
- package/_dist/job.d.ts.map +1 -0
- package/_dist/keys.d.ts +14 -0
- package/_dist/keys.d.ts.map +1 -0
- package/_dist/mod.d.ts +65 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/object.d.ts +75 -0
- package/_dist/object.d.ts.map +1 -0
- package/_dist/profile.d.ts +32 -0
- package/_dist/profile.d.ts.map +1 -0
- package/_dist/query-memory.d.ts +27 -0
- package/_dist/query-memory.d.ts.map +1 -0
- package/_dist/resets.d.ts +208 -0
- package/_dist/resets.d.ts.map +1 -0
- package/_dist/rewind.d.ts +21 -0
- package/_dist/rewind.d.ts.map +1 -0
- package/_dist/sockets.d.ts +90 -0
- package/_dist/sockets.d.ts.map +1 -0
- package/_dist/sql.d.ts +72 -0
- package/_dist/sql.d.ts.map +1 -0
- package/_dist/store.d.ts +8 -0
- package/_dist/store.d.ts.map +1 -0
- package/alarm.js +126 -0
- package/alarm.js.map +1 -0
- package/alarm.ts +188 -0
- package/ceiling.js +536 -0
- package/ceiling.js.map +1 -0
- package/ceiling.ts +681 -0
- package/compose.js +201 -0
- package/compose.js.map +1 -0
- package/compose.ts +249 -0
- package/copy.js +394 -0
- package/copy.js.map +1 -0
- package/copy.ts +413 -0
- package/deno.json +1 -0
- package/door.js +364 -0
- package/door.js.map +1 -0
- package/door.ts +542 -0
- package/example.ts +108 -0
- package/holds.js +85 -0
- package/holds.js.map +1 -0
- package/holds.ts +72 -0
- package/job.js +151 -0
- package/job.js.map +1 -0
- package/job.ts +166 -0
- package/keys.js +59 -0
- package/keys.js.map +1 -0
- package/keys.ts +85 -0
- package/mod.js +65 -0
- package/mod.js.map +1 -0
- package/mod.ts +167 -0
- package/object.js +247 -0
- package/object.js.map +1 -0
- package/object.ts +385 -0
- package/package.json +68 -4
- package/profile.js +131 -0
- package/profile.js.map +1 -0
- package/profile.ts +150 -0
- package/query-memory.js +157 -0
- package/query-memory.js.map +1 -0
- package/query-memory.ts +240 -0
- package/resets.js +302 -0
- package/resets.js.map +1 -0
- package/resets.ts +353 -0
- package/rewind.js +68 -0
- package/rewind.js.map +1 -0
- package/rewind.ts +91 -0
- package/sockets.js +749 -0
- package/sockets.js.map +1 -0
- package/sockets.ts +991 -0
- package/sql.js +221 -0
- package/sql.js.map +1 -0
- package/sql.ts +330 -0
- package/store.js +58 -0
- package/store.js.map +1 -0
- package/store.ts +80 -0
- package/watches.js +8 -0
- package/watches.js.map +1 -0
- package/watches.ts +23 -0
package/door.ts
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
1
|
+
// The door to an object: its stub by name, a request built from scratch for
|
|
2
|
+
// every call through it, and the call sent again when the runtime reset the
|
|
3
|
+
// object or lost the call (./resets.ts).
|
|
4
|
+
//
|
|
5
|
+
// A caller reaches an object only by fetch, so everything a call needs to say
|
|
6
|
+
// rides on the request, and the request is built here, from a path, an init
|
|
7
|
+
// and the headers the call sets. What those headers mean is the caller's: a
|
|
8
|
+
// door scrubs the ones the caller names, so a header only the caller may set
|
|
9
|
+
// never rides in on an init that is someone else's Request, and `send` dresses
|
|
10
|
+
// the request in whatever else the caller always says. Nothing here knows what
|
|
11
|
+
// the object is for.
|
|
12
|
+
|
|
13
|
+
import { IDEMPOTENCY } from '@yaks/api/headers'
|
|
14
|
+
import {
|
|
15
|
+
type Clock,
|
|
16
|
+
heard,
|
|
17
|
+
type Hold,
|
|
18
|
+
resolvers,
|
|
19
|
+
system,
|
|
20
|
+
waitFor,
|
|
21
|
+
within,
|
|
22
|
+
} from '@yaks/fp'
|
|
23
|
+
import {
|
|
24
|
+
evicted,
|
|
25
|
+
killed,
|
|
26
|
+
opaque,
|
|
27
|
+
retried,
|
|
28
|
+
starved,
|
|
29
|
+
unserved,
|
|
30
|
+
} from './resets.js'
|
|
31
|
+
|
|
32
|
+
/** A Durable Object stub: one object, reachable by fetch. */
|
|
33
|
+
export type Stub = {
|
|
34
|
+
fetch(req: Request, init?: Pick<RequestInit, 'signal'>): Promise<Response>
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A Durable Object namespace binding, the part of it a door uses. */
|
|
38
|
+
export type Namespace = {
|
|
39
|
+
idFromName(name: string): unknown
|
|
40
|
+
get(id: unknown, options?: { locationHint?: string }): Stub
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The stub for the object a name stands in, created where `hint` says (a
|
|
45
|
+
* Cloudflare location hint, such as `'enam'`). The runtime reads a hint only
|
|
46
|
+
* at an object's first get and never moves an object, so where the first get
|
|
47
|
+
* placed it is where it answers from, for good.
|
|
48
|
+
*
|
|
49
|
+
* A stub is an I/O object the runtime binds to the request that took it, so
|
|
50
|
+
* take one per call: getting one costs nothing.
|
|
51
|
+
*
|
|
52
|
+
* ```ts
|
|
53
|
+
* import { assertEquals } from '@std/assert'
|
|
54
|
+
* let got: unknown[] = []
|
|
55
|
+
* let ns = {
|
|
56
|
+
* idFromName: (name: string) => `id:${name}`,
|
|
57
|
+
* get: (...args: unknown[]) => (got.push(args), { fetch: () => Promise.resolve(new Response()) }),
|
|
58
|
+
* }
|
|
59
|
+
* stubOf(ns, 'ada', 'enam')
|
|
60
|
+
* stubOf(ns, 'bo')
|
|
61
|
+
* assertEquals(got, [['id:ada', { locationHint: 'enam' }], ['id:bo']])
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
export let stubOf = (ns: Namespace, name: string, hint?: string): Stub => {
|
|
65
|
+
let id = ns.idFromName(name)
|
|
66
|
+
return hint ? ns.get(id, { locationHint: hint }) : ns.get(id)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A call's options: `replayable: false` says it must not be sent twice. */
|
|
70
|
+
export type Call = { replayable?: boolean }
|
|
71
|
+
|
|
72
|
+
/** A door onto one object: a path, its init and the headers this call sets,
|
|
73
|
+
* answered by the object. An init that is a Request carries its method, body
|
|
74
|
+
* and headers across, which is how a socket upgrade reaches the object with
|
|
75
|
+
* its `Upgrade` header on it. `consume` reads the answer with `read`. */
|
|
76
|
+
export type Door = {
|
|
77
|
+
(
|
|
78
|
+
path: string,
|
|
79
|
+
init?: RequestInit | Request,
|
|
80
|
+
headers?: Record<string, string>,
|
|
81
|
+
options?: Call,
|
|
82
|
+
): Promise<Response>
|
|
83
|
+
consume<T>(
|
|
84
|
+
path: string,
|
|
85
|
+
read: (response: Response) => T | Promise<T>,
|
|
86
|
+
init?: RequestInit | Request,
|
|
87
|
+
headers?: Record<string, string>,
|
|
88
|
+
options?: Call,
|
|
89
|
+
): Promise<T>
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Whatever answers a request: a stub, or the object itself in-process. */
|
|
93
|
+
export type Send = (req: Request) => Promise<Response>
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* An object's door onto itself: each call waits a `turn` of its event loop
|
|
97
|
+
* before `send` answers it. In-process a call is a method call that settles on
|
|
98
|
+
* microtasks alone, so a job asking read after read held the object for the
|
|
99
|
+
* whole job, and every request waiting on the object waited that long: the
|
|
100
|
+
* directory's trash sweep held every door on the platform for 18 s (T-4061).
|
|
101
|
+
* Its calls still run in order; the requests waiting run between them. The
|
|
102
|
+
* runtime gives the turn (the next task: Node's `setImmediate` where it has
|
|
103
|
+
* one), since not every Worker that loads this module has it.
|
|
104
|
+
*
|
|
105
|
+
* ```ts
|
|
106
|
+
* import { assertEquals } from '@std/assert'
|
|
107
|
+
* import { setImmediate } from 'node:timers'
|
|
108
|
+
* let next = () => new Promise<void>((go) => void setImmediate(go))
|
|
109
|
+
* let seen: string[] = []
|
|
110
|
+
* let itself = yielding(() => {
|
|
111
|
+
* seen.push('job')
|
|
112
|
+
* return Promise.resolve(new Response())
|
|
113
|
+
* }, next)
|
|
114
|
+
* setImmediate(() => seen.push('waiting'))
|
|
115
|
+
* await itself(new Request('http://store/query'))
|
|
116
|
+
* assertEquals(seen, ['waiting', 'job'])
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
export let yielding =
|
|
120
|
+
(send: Send, turn: () => Promise<void>): Send => async (req) => {
|
|
121
|
+
await turn()
|
|
122
|
+
return await send(req)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* A door that builds each request from scratch and hands it to `send`: the
|
|
127
|
+
* init's headers named in `scrub` are dropped, then the call's own headers
|
|
128
|
+
* set. `send` sees the request last, so what it sets is the final word.
|
|
129
|
+
*
|
|
130
|
+
* ```ts
|
|
131
|
+
* import { assertEquals } from '@std/assert'
|
|
132
|
+
* let door = doorOf((req) => Promise.resolve(new Response(
|
|
133
|
+
* `${new URL(req.url).pathname} ${req.headers.get('x-who')}`,
|
|
134
|
+
* )), ['x-who'])
|
|
135
|
+
* let visitor = new Request('http://visitor', { headers: { 'x-who': 'me' } })
|
|
136
|
+
* assertEquals(await door.consume('/query', (r) => r.text(), visitor), '/query null')
|
|
137
|
+
* assertEquals(await (await door('/query', visitor, { 'x-who': 'kernel' })).text(), '/query kernel')
|
|
138
|
+
* ```
|
|
139
|
+
*/
|
|
140
|
+
export let doorOf = (send: Send, scrub: string[] = []): Door => {
|
|
141
|
+
let ask = (
|
|
142
|
+
path: string,
|
|
143
|
+
init: RequestInit | Request = {},
|
|
144
|
+
headers: Record<string, string> = {},
|
|
145
|
+
) => {
|
|
146
|
+
let req = new Request(`http://store${path}`, init)
|
|
147
|
+
for (let h of scrub) req.headers.delete(h)
|
|
148
|
+
for (let [k, v] of Object.entries(headers)) req.headers.set(k, v)
|
|
149
|
+
return send(req)
|
|
150
|
+
}
|
|
151
|
+
return Object.assign(ask, {
|
|
152
|
+
consume: <T>(
|
|
153
|
+
path: string,
|
|
154
|
+
read: (response: Response) => T | Promise<T>,
|
|
155
|
+
init: RequestInit | Request = {},
|
|
156
|
+
headers: Record<string, string> = {},
|
|
157
|
+
) => ask(path, init, headers).then(read),
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
let copied = async (response: Response): Promise<() => Response> => {
|
|
162
|
+
let body = response.body ? await response.arrayBuffer() : null
|
|
163
|
+
let init = {
|
|
164
|
+
status: response.status,
|
|
165
|
+
statusText: response.statusText,
|
|
166
|
+
headers: [...response.headers],
|
|
167
|
+
}
|
|
168
|
+
return () => new Response(body?.slice(0), init)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// How long a caller waits on a batch another request sends before presuming
|
|
172
|
+
// that request ended (`coalesced`): far past a read's round trip, and well
|
|
173
|
+
// inside the minute after which a request that has not answered is a defect.
|
|
174
|
+
let PATIENCE = 15_000
|
|
175
|
+
|
|
176
|
+
// How often a caller looks for its batch's answer.
|
|
177
|
+
let BEAT = 5
|
|
178
|
+
|
|
179
|
+
type Trip = (signal: AbortSignal) => Promise<() => Response>
|
|
180
|
+
|
|
181
|
+
// One read's callers share a batch: the opener sends its trip, and the answer
|
|
182
|
+
// lands on it as a value, the response's bytes or the failure, or `lost` once
|
|
183
|
+
// nobody will answer it.
|
|
184
|
+
type Batch = {
|
|
185
|
+
answer?: () => Response
|
|
186
|
+
failed?: { error: unknown }
|
|
187
|
+
lost?: boolean
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
let landed = (batch: Batch) =>
|
|
191
|
+
batch.answer || batch.failed || batch.lost ? batch : null
|
|
192
|
+
|
|
193
|
+
/** Share finite reads accepted by `reads` and queued before `turn` sends them,
|
|
194
|
+
* each caller receiving its own bytes. A read already sent answers no later
|
|
195
|
+
* caller: its snapshot may predate that caller. So one read of a request
|
|
196
|
+
* travels at a time: whoever asks it meanwhile shares the next, sent once it
|
|
197
|
+
* lands, as passengers board the next lift rather than the one already
|
|
198
|
+
* moving. However many callers ask one read together, the object answers it
|
|
199
|
+
* once a round trip. A write or an excluded read separates batches. `hold`
|
|
200
|
+
* keeps the opener's trip alive past its own request. With a shorter
|
|
201
|
+
* `headStart`, a batch can send after that much time behind a slow trip.
|
|
202
|
+
* A caller sharing its first batch can also join a fresh batch after that
|
|
203
|
+
* wait. The original sender can still finish.
|
|
204
|
+
*
|
|
205
|
+
* Callers are often different requests, and a Worker settles a promise only
|
|
206
|
+
* in the request that made it: one request's wake to another is dropped once
|
|
207
|
+
* the sleeper's request ends (@yaks/fp `Scope`). So no caller awaits or
|
|
208
|
+
* settles another's promise. The caller that opens a batch sends it from its
|
|
209
|
+
* own request, and its answer lands on the batch as a value: the bytes, which
|
|
210
|
+
* each caller makes its own response from, or the failure. The opener hears
|
|
211
|
+
* its own send land; every other caller looks for it every `beat` ms on its
|
|
212
|
+
* own clock (@yaks/fp `waitFor`).
|
|
213
|
+
*
|
|
214
|
+
* What runs in another request is dropped, without a word, once that request
|
|
215
|
+
* ends: a batch whose opener ended before sending it, or whose trip never
|
|
216
|
+
* lands, would answer nobody. So a caller unanswered for `patience` ms
|
|
217
|
+
* (`heard` on `clock`) presumes its batch lost and boards again from its own
|
|
218
|
+
* request once, and an opener aborts a trip of its own still out then. `wait`
|
|
219
|
+
* wraps the caller's full wait, so a host can name it. */
|
|
220
|
+
export let coalesced = (
|
|
221
|
+
door: Door,
|
|
222
|
+
reads: (request: Request) => boolean,
|
|
223
|
+
{
|
|
224
|
+
hold,
|
|
225
|
+
turn = queueMicrotask,
|
|
226
|
+
patience = PATIENCE,
|
|
227
|
+
headStart = patience,
|
|
228
|
+
clock = system,
|
|
229
|
+
beat = BEAT,
|
|
230
|
+
wait = (seated) => seated(),
|
|
231
|
+
}: {
|
|
232
|
+
hold?: Hold
|
|
233
|
+
turn?: (send: () => void) => void
|
|
234
|
+
patience?: number
|
|
235
|
+
headStart?: number
|
|
236
|
+
clock?: Clock
|
|
237
|
+
beat?: number
|
|
238
|
+
wait?: <T>(seated: () => Promise<T>) => Promise<T>
|
|
239
|
+
} = {},
|
|
240
|
+
): Door => {
|
|
241
|
+
// The batch still boarding for each read, and the one travelling.
|
|
242
|
+
let boarding = new Map<string, Batch>()
|
|
243
|
+
let moving = new Map<string, Batch>()
|
|
244
|
+
let looking = { clock, beat }
|
|
245
|
+
// What boards from here on shares nothing sent before.
|
|
246
|
+
let part = () => {
|
|
247
|
+
boarding.clear()
|
|
248
|
+
moving.clear()
|
|
249
|
+
}
|
|
250
|
+
let apart = async (send: () => Promise<Response>) => {
|
|
251
|
+
part()
|
|
252
|
+
try {
|
|
253
|
+
return await send()
|
|
254
|
+
} finally {
|
|
255
|
+
part()
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
// A batch nobody answered in time: nobody boards behind it again.
|
|
259
|
+
let lost = (key: string, batch: Batch) => {
|
|
260
|
+
batch.lost ||= !batch.answer && !batch.failed
|
|
261
|
+
if (boarding.get(key) == batch) boarding.delete(key)
|
|
262
|
+
if (moving.get(key) == batch) moving.delete(key)
|
|
263
|
+
}
|
|
264
|
+
// The opener's send, all in its own request: once the read ahead lands (or
|
|
265
|
+
// is presumed lost) and this turn's callers have boarded.
|
|
266
|
+
let send = (key: string, batch: Batch, trip: Trip): Promise<void> => {
|
|
267
|
+
let { promise: sent, resolve: done } = resolvers<void>()
|
|
268
|
+
let go = () => {
|
|
269
|
+
if (batch.lost) return done()
|
|
270
|
+
if (boarding.get(key) == batch) boarding.delete(key)
|
|
271
|
+
moving.set(key, batch)
|
|
272
|
+
let stop = new AbortController()
|
|
273
|
+
let { promise: cut, reject } = resolvers<never>()
|
|
274
|
+
let cancel = heard(patience, () => {
|
|
275
|
+
stop.abort()
|
|
276
|
+
reject(new Error('The store did not answer the read in time'))
|
|
277
|
+
}, clock)
|
|
278
|
+
Promise.race([trip(stop.signal), cut]).then(
|
|
279
|
+
(answer) => void (batch.answer = answer),
|
|
280
|
+
(error) => {
|
|
281
|
+
if (stop.signal.aborted) lost(key, batch)
|
|
282
|
+
else batch.failed = { error }
|
|
283
|
+
},
|
|
284
|
+
).finally(() => {
|
|
285
|
+
cancel()
|
|
286
|
+
if (moving.get(key) == batch) moving.delete(key)
|
|
287
|
+
done()
|
|
288
|
+
})
|
|
289
|
+
}
|
|
290
|
+
let ahead = moving.get(key)
|
|
291
|
+
if (!ahead) turn(go)
|
|
292
|
+
else {
|
|
293
|
+
let gone = () => moving.get(key) != ahead || landed(ahead)
|
|
294
|
+
void waitFor(() => gone() || null, headStart, looking).then((went) => {
|
|
295
|
+
if (!went && headStart >= patience) lost(key, ahead)
|
|
296
|
+
turn(go)
|
|
297
|
+
})
|
|
298
|
+
}
|
|
299
|
+
return sent
|
|
300
|
+
}
|
|
301
|
+
let ride = async (key: string, trip: Trip): Promise<Response> => {
|
|
302
|
+
for (let sent = 0; sent < 2; sent++) {
|
|
303
|
+
let batch = boarding.get(key)
|
|
304
|
+
let sending: Promise<void> | undefined
|
|
305
|
+
if (!batch) {
|
|
306
|
+
boarding.set(key, batch = {})
|
|
307
|
+
sending = send(key, batch, trip)
|
|
308
|
+
hold?.(sending)
|
|
309
|
+
}
|
|
310
|
+
// The opener sent the trip from its own request, so it hears its own
|
|
311
|
+
// send land; only a caller who boarded another's batch looks for it.
|
|
312
|
+
let share = sent == 0 ? Math.min(headStart, patience) : patience
|
|
313
|
+
let got = sending
|
|
314
|
+
? await within(sending.then(() => landed(batch)), patience, clock)
|
|
315
|
+
: await waitFor(() => landed(batch), share, looking)
|
|
316
|
+
if (got?.answer) return got.answer()
|
|
317
|
+
if (got?.failed) throw got.failed.error
|
|
318
|
+
if (sending || share >= patience) {
|
|
319
|
+
lost(key, batch)
|
|
320
|
+
} else if (boarding.get(key) == batch) {
|
|
321
|
+
// Leave the original sender free to finish while these callers retry.
|
|
322
|
+
boarding.delete(key)
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
throw Object.assign(
|
|
326
|
+
new Error('The store did not answer the read after a retry'),
|
|
327
|
+
{ status: 504 },
|
|
328
|
+
)
|
|
329
|
+
}
|
|
330
|
+
let ask = async (
|
|
331
|
+
path: string,
|
|
332
|
+
init: RequestInit | Request = {},
|
|
333
|
+
headers: Record<string, string> = {},
|
|
334
|
+
options: Call = {},
|
|
335
|
+
) => {
|
|
336
|
+
let method = init instanceof Request ? init.method : init.method ?? 'GET'
|
|
337
|
+
if (method != 'GET' || options.replayable === false) {
|
|
338
|
+
return await apart(() => door(path, init, headers, options))
|
|
339
|
+
}
|
|
340
|
+
return await doorOf(async (request) => {
|
|
341
|
+
// An upgrade starts an independent stream. It cannot answer a batch,
|
|
342
|
+
// and it need not release every batched read during a reconnect.
|
|
343
|
+
if (request.headers.has('upgrade')) {
|
|
344
|
+
return await door(path, init, headers, options)
|
|
345
|
+
}
|
|
346
|
+
if (!reads(request)) {
|
|
347
|
+
return await apart(() => door(path, init, headers, options))
|
|
348
|
+
}
|
|
349
|
+
let key = JSON.stringify([
|
|
350
|
+
request.url,
|
|
351
|
+
[...request.headers].filter(([name]) => name != IDEMPOTENCY),
|
|
352
|
+
])
|
|
353
|
+
// The call's own headers are set again past the inner door's scrub, as
|
|
354
|
+
// an uncoalesced call sets them.
|
|
355
|
+
return await wait(() =>
|
|
356
|
+
ride(
|
|
357
|
+
key,
|
|
358
|
+
(signal) =>
|
|
359
|
+
door.consume(
|
|
360
|
+
path,
|
|
361
|
+
copied,
|
|
362
|
+
new Request(request, { signal }),
|
|
363
|
+
headers,
|
|
364
|
+
options,
|
|
365
|
+
),
|
|
366
|
+
)
|
|
367
|
+
)
|
|
368
|
+
})(path, init, headers)
|
|
369
|
+
}
|
|
370
|
+
return Object.assign(ask, {
|
|
371
|
+
consume: <T>(
|
|
372
|
+
path: string,
|
|
373
|
+
read: (response: Response) => T | Promise<T>,
|
|
374
|
+
init?: RequestInit | Request,
|
|
375
|
+
headers?: Record<string, string>,
|
|
376
|
+
options?: Call,
|
|
377
|
+
) => ask(path, init, headers, options).then(read),
|
|
378
|
+
})
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// The header that makes a resend safe: an object that applied a key answers
|
|
382
|
+
// the next send of it as it answered the first (@yaks/api/receipts).
|
|
383
|
+
export { IDEMPOTENCY }
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* The reset an answer carries, as the runtime throws it, or null. An object
|
|
387
|
+
* the runtime resets mid-request can still answer, and it answers the reset as
|
|
388
|
+
* it answers any error, in a 500's refusal body (@yaks/api `refuse`), so the
|
|
389
|
+
* words the runtime meant as "fetch again" would reach the caller as a
|
|
390
|
+
* failure. An object that ran out of memory answers the same way.
|
|
391
|
+
*
|
|
392
|
+
* ```ts
|
|
393
|
+
* import { assertEquals } from '@std/assert'
|
|
394
|
+
* let said = (message: string) => Response.json({ message }, { status: 500 })
|
|
395
|
+
* assertEquals((await reset(said('Network connection lost.')))?.message, 'Network connection lost.')
|
|
396
|
+
* assertEquals(await reset(said('boot failed')), null)
|
|
397
|
+
* assertEquals(await reset(new Response('Network connection lost.')), null)
|
|
398
|
+
* ```
|
|
399
|
+
*/
|
|
400
|
+
export let reset = async (r: Response): Promise<Error | null> => {
|
|
401
|
+
if (r.status < 500) return null
|
|
402
|
+
let said: { message?: unknown; retryable?: unknown } | null = await r
|
|
403
|
+
.clone().text().then((t) => JSON.parse(t)).catch(() => null)
|
|
404
|
+
// The whole body rides along as `said`, for a caller that reads more of it.
|
|
405
|
+
let e = typeof said?.message == 'string'
|
|
406
|
+
? Object.assign(new Error(said.message), {
|
|
407
|
+
retryable: said.retryable,
|
|
408
|
+
said,
|
|
409
|
+
})
|
|
410
|
+
: null
|
|
411
|
+
return evicted(e) || starved(e) ? e : null
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** An answer, with a reset in it thrown as the runtime throws one. */
|
|
415
|
+
export let thrown = async (r: Response): Promise<Response> => {
|
|
416
|
+
let e = await reset(r)
|
|
417
|
+
if (e) throw e
|
|
418
|
+
return r
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** The most bytes of an answer {@link received} reads whole. */
|
|
422
|
+
export let WHOLE = 1024 * 1024
|
|
423
|
+
|
|
424
|
+
/** Whether an answer is read whole where it arrives: a finite one, no larger
|
|
425
|
+
* than {@link WHOLE} by the length it declares. A live stream (ndjson, SSE or
|
|
426
|
+
* a socket) is handed on as it comes, since its reader owns its lifetime, and
|
|
427
|
+
* so is a file, which declares more: it is never held whole. */
|
|
428
|
+
export let finite = (r: Response): boolean =>
|
|
429
|
+
!!r.body && r.status != 101 &&
|
|
430
|
+
!/ndjson|event-stream/.test(r.headers.get('content-type') ?? '') &&
|
|
431
|
+
Number(r.headers.get('content-length') ?? 0) <= WHOLE
|
|
432
|
+
|
|
433
|
+
let local = new WeakSet<Response>()
|
|
434
|
+
|
|
435
|
+
/** Mark an answer made in this process. It has no remote hop whose reset
|
|
436
|
+
* could cut off its body after the headers arrived. */
|
|
437
|
+
export let inProcess = (r: Response): Response => {
|
|
438
|
+
local.add(r)
|
|
439
|
+
return r
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** Read a {@link finite} answer whole inside the retry that sent it, so a
|
|
443
|
+
* restart cutting off its body is sent again. */
|
|
444
|
+
export let received = async (r: Response): Promise<Response> =>
|
|
445
|
+
!local.has(r) && finite(r) ? new Response(await r.arrayBuffer(), r) : r
|
|
446
|
+
|
|
447
|
+
// A request can be built twice from its init only while the body is a value:
|
|
448
|
+
// a stream, or a Request whose body the first build took, is spent.
|
|
449
|
+
let rebuildable = (init: RequestInit | Request) =>
|
|
450
|
+
init instanceof Request ? !init.body : !(init.body instanceof ReadableStream)
|
|
451
|
+
|
|
452
|
+
/** What `resending` is told: `report` hears a kill for the object's limits or
|
|
453
|
+
* a refusal for memory, the failures no retry should hide, with the path
|
|
454
|
+
* that met it; `settled` may answer a call whose resends ran
|
|
455
|
+
* out, in place of its last failure; `wait` waits out each pause
|
|
456
|
+
* (`retried`). */
|
|
457
|
+
export type Resend = {
|
|
458
|
+
report?: (error: unknown, path: string) => void
|
|
459
|
+
settled?: (failure: unknown, path: string) => Response | null
|
|
460
|
+
wait?: (ms: number) => Promise<void>
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* A door that sends a call again when the object never ran it (`unserved`):
|
|
465
|
+
* the runtime reset the object or lost the call, thrown or answered
|
|
466
|
+
* (`reset`), or dropped it from an overloaded object's queue, as `retried`
|
|
467
|
+
* paces it. A call is
|
|
468
|
+
* sent again only when that is safe: its request can be built again (no
|
|
469
|
+
* streamed body, and not `replayable: false`), and each carries one
|
|
470
|
+
* `IDEMPOTENCY` key across its sends, so an object that applied it before its
|
|
471
|
+
* answer was lost answers the next as it answered the first. A caller that
|
|
472
|
+
* will send the call again itself names the key, and the door keeps it.
|
|
473
|
+
*
|
|
474
|
+
* An answer is read whole inside the retry, so a restart that cuts off its
|
|
475
|
+
* body is sent again too; a stream is handed on as it comes. A caller that
|
|
476
|
+
* reads the answer (`consume`) reads it inside the same retry, so a read
|
|
477
|
+
* failing in the runtime's opaque words is sent again, and a write is not.
|
|
478
|
+
*
|
|
479
|
+
* ```ts
|
|
480
|
+
* import { assertEquals } from '@std/assert'
|
|
481
|
+
* let sends = 0
|
|
482
|
+
* let door = resending(doorOf(() =>
|
|
483
|
+
* Promise.resolve(++sends < 2
|
|
484
|
+
* ? Response.json({ message: 'Network connection lost.' }, { status: 500 })
|
|
485
|
+
* : new Response('ok'))
|
|
486
|
+
* ), { wait: () => Promise.resolve() })
|
|
487
|
+
* assertEquals([await (await door('/query')).text(), sends], ['ok', 2])
|
|
488
|
+
* ```
|
|
489
|
+
*/
|
|
490
|
+
export let resending = (door: Door, o: Resend = {}): Door => {
|
|
491
|
+
let ask = <T>(
|
|
492
|
+
path: string,
|
|
493
|
+
read: ((response: Response) => T | Promise<T>) | null,
|
|
494
|
+
init: RequestInit | Request = {},
|
|
495
|
+
headers: Record<string, string> = {},
|
|
496
|
+
options: Call = {},
|
|
497
|
+
) => {
|
|
498
|
+
let once = { [IDEMPOTENCY]: crypto.randomUUID(), ...headers }
|
|
499
|
+
let method = init instanceof Request ? init.method : init.method ?? 'GET'
|
|
500
|
+
let safe = method == 'GET' || method == 'HEAD'
|
|
501
|
+
let replayable = rebuildable(init) && options.replayable !== false
|
|
502
|
+
let take = read ??
|
|
503
|
+
((r: Response) => (replayable ? received(r) : r) as T | Promise<T>)
|
|
504
|
+
let resent = (e: unknown) => unserved(e) || (!!read && safe && opaque(e))
|
|
505
|
+
let sent = retried(
|
|
506
|
+
async () => {
|
|
507
|
+
init.signal?.throwIfAborted()
|
|
508
|
+
try {
|
|
509
|
+
return await take(await thrown(await door(path, init, once)))
|
|
510
|
+
} catch (e) {
|
|
511
|
+
if (killed(e) || starved(e)) o.report?.(e, path)
|
|
512
|
+
throw e
|
|
513
|
+
}
|
|
514
|
+
},
|
|
515
|
+
replayable,
|
|
516
|
+
resent,
|
|
517
|
+
o.wait,
|
|
518
|
+
)
|
|
519
|
+
return sent.catch((e) => {
|
|
520
|
+
let answer = o.settled?.(e, path)
|
|
521
|
+
if (!answer) throw e
|
|
522
|
+
return take(answer)
|
|
523
|
+
})
|
|
524
|
+
}
|
|
525
|
+
return Object.assign(
|
|
526
|
+
(
|
|
527
|
+
path: string,
|
|
528
|
+
init?: RequestInit | Request,
|
|
529
|
+
headers?: Record<string, string>,
|
|
530
|
+
options?: Call,
|
|
531
|
+
) => ask<Response>(path, null, init, headers, options),
|
|
532
|
+
{
|
|
533
|
+
consume: <T>(
|
|
534
|
+
path: string,
|
|
535
|
+
read: (response: Response) => T | Promise<T>,
|
|
536
|
+
init?: RequestInit | Request,
|
|
537
|
+
headers?: Record<string, string>,
|
|
538
|
+
options?: Call,
|
|
539
|
+
) => ask(path, read, init, headers, options),
|
|
540
|
+
},
|
|
541
|
+
)
|
|
542
|
+
}
|
package/example.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// The whole thing, as one Durable Object: a bookshop whose graph lives in the
|
|
2
|
+
// object's SQLite and whose subscribers hear about every batch. It is a class
|
|
3
|
+
// because the platform requires one — a Durable Object is a class the runtime
|
|
4
|
+
// constructs — and it is the only class in the package.
|
|
5
|
+
//
|
|
6
|
+
// Three handlers, and each is one line of plumbing:
|
|
7
|
+
// fetch @yaks/api's routes, with /ws taken first
|
|
8
|
+
// webSocketMessage a frame from a hibernatable socket
|
|
9
|
+
// webSocketClose that socket went away
|
|
10
|
+
//
|
|
11
|
+
// Copy it, swap the vocabulary for yours, and point a `wrangler.toml` binding
|
|
12
|
+
// at the class. The README carries the same code with the deploy steps.
|
|
13
|
+
|
|
14
|
+
import { api, type Handler, subscriptions } from 'jsr:@yaks/api@0.2.36'
|
|
15
|
+
import { graph } from 'jsr:@yaks/graph@0.2.36'
|
|
16
|
+
import { loadVocab, type VocabDoc } from 'jsr:@yaks/vocab@0.2.36'
|
|
17
|
+
import {
|
|
18
|
+
type DurableStorage,
|
|
19
|
+
type Hibernation,
|
|
20
|
+
type Sockets,
|
|
21
|
+
sockets,
|
|
22
|
+
storage,
|
|
23
|
+
type Wire,
|
|
24
|
+
} from './mod.ts'
|
|
25
|
+
|
|
26
|
+
// In your Worker this is `DurableObjectState`, and you would write that. Here
|
|
27
|
+
// it is the slice of one this package needs, so the file compiles without
|
|
28
|
+
// pulling Cloudflare's globals into a type-check shared with every other
|
|
29
|
+
// package; workers_check.ts is where the runtime's own type is held to it.
|
|
30
|
+
type State = Hibernation & { storage: DurableStorage }
|
|
31
|
+
|
|
32
|
+
// The shop's vocabulary: JSON Schema plus the yaks keywords. A book is a `doc`
|
|
33
|
+
// (title and body) plus a `book` (price, status, who wrote it); deleting an
|
|
34
|
+
// author detaches their books rather than deleting them.
|
|
35
|
+
let doc: VocabDoc = {
|
|
36
|
+
$defs: {
|
|
37
|
+
entity: {
|
|
38
|
+
component: true,
|
|
39
|
+
type: 'object',
|
|
40
|
+
wire: false,
|
|
41
|
+
properties: { num: { type: 'number', stamped: true } },
|
|
42
|
+
},
|
|
43
|
+
doc: {
|
|
44
|
+
component: true,
|
|
45
|
+
type: 'object',
|
|
46
|
+
kind: true,
|
|
47
|
+
properties: {
|
|
48
|
+
title: { type: 'string' },
|
|
49
|
+
body: { type: 'string', store: 'blob' },
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
book: {
|
|
53
|
+
component: true,
|
|
54
|
+
type: 'object',
|
|
55
|
+
kind: true,
|
|
56
|
+
before: ['doc'],
|
|
57
|
+
properties: {
|
|
58
|
+
price: { type: 'number' },
|
|
59
|
+
status: { type: 'string', enum: ['shelved', 'sold'] },
|
|
60
|
+
author: { type: 'string', ref: 'entity', death: 'detach' },
|
|
61
|
+
},
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
let vocab = loadVocab(doc)
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* One bookshop, in one Durable Object: `POST /apply` writes, `GET /query`
|
|
70
|
+
* reads, and `/ws` is a live subscription that survives the object being
|
|
71
|
+
* evicted between two batches.
|
|
72
|
+
*/
|
|
73
|
+
export class Bookshop {
|
|
74
|
+
#live: Sockets
|
|
75
|
+
#route: Handler
|
|
76
|
+
|
|
77
|
+
/** @param ctx the object's own state — its storage and its sockets */
|
|
78
|
+
constructor(ctx: State) {
|
|
79
|
+
let store = storage(ctx.storage, vocab)
|
|
80
|
+
// Create-if-not-exists, so every wake-up is safe.
|
|
81
|
+
store.install()
|
|
82
|
+
let shop = graph({ storage: store, vocab })
|
|
83
|
+
// One registry, shared: the sockets push what the routes commit.
|
|
84
|
+
let subs = subscriptions(shop)
|
|
85
|
+
this.#live = sockets(subs, ctx)
|
|
86
|
+
this.#route = api({ graph: shop, subs })
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The object's request entry point. `wake()` first: a batch applied by the
|
|
90
|
+
* request that woke this object must still reach the sockets it
|
|
91
|
+
* inherited. */
|
|
92
|
+
fetch(request: Request): Response | Promise<Response> {
|
|
93
|
+
this.#live.wake()
|
|
94
|
+
return new URL(request.url).pathname == '/ws'
|
|
95
|
+
? this.#live.accept(request)
|
|
96
|
+
: this.#route(request)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A frame from a client: a subscription opened or closed. */
|
|
100
|
+
webSocketMessage(ws: Wire, data: string | ArrayBuffer): void {
|
|
101
|
+
this.#live.message(ws, data)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** That client went away. */
|
|
105
|
+
webSocketClose(ws: Wire): void {
|
|
106
|
+
this.#live.close(ws)
|
|
107
|
+
}
|
|
108
|
+
}
|