@yaks/api 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.
Files changed (152) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +956 -2
  3. package/_dist/actor.d.ts +59 -0
  4. package/_dist/actor.d.ts.map +1 -0
  5. package/_dist/address.d.ts +33 -0
  6. package/_dist/address.d.ts.map +1 -0
  7. package/_dist/asset.d.ts +15 -0
  8. package/_dist/asset.d.ts.map +1 -0
  9. package/_dist/batches.d.ts +4 -0
  10. package/_dist/batches.d.ts.map +1 -0
  11. package/_dist/body.d.ts +7 -0
  12. package/_dist/body.d.ts.map +1 -0
  13. package/_dist/deno.d.ts +38 -0
  14. package/_dist/deno.d.ts.map +1 -0
  15. package/_dist/doors.d.ts +134 -0
  16. package/_dist/doors.d.ts.map +1 -0
  17. package/_dist/graph.d.ts +17 -0
  18. package/_dist/graph.d.ts.map +1 -0
  19. package/_dist/headers.d.ts +5 -0
  20. package/_dist/headers.d.ts.map +1 -0
  21. package/_dist/log.d.ts +253 -0
  22. package/_dist/log.d.ts.map +1 -0
  23. package/_dist/mod.d.ts +71 -0
  24. package/_dist/mod.d.ts.map +1 -0
  25. package/_dist/publish.d.ts +7 -0
  26. package/_dist/publish.d.ts.map +1 -0
  27. package/_dist/reached.d.ts +145 -0
  28. package/_dist/reached.d.ts.map +1 -0
  29. package/_dist/receipts.d.ts +153 -0
  30. package/_dist/receipts.d.ts.map +1 -0
  31. package/_dist/refuse.d.ts +51 -0
  32. package/_dist/refuse.d.ts.map +1 -0
  33. package/_dist/relay.d.ts +3 -0
  34. package/_dist/relay.d.ts.map +1 -0
  35. package/_dist/request.d.ts +79 -0
  36. package/_dist/request.d.ts.map +1 -0
  37. package/_dist/requests.d.ts +7 -0
  38. package/_dist/requests.d.ts.map +1 -0
  39. package/_dist/route.d.ts +71 -0
  40. package/_dist/route.d.ts.map +1 -0
  41. package/_dist/routed.d.ts +33 -0
  42. package/_dist/routed.d.ts.map +1 -0
  43. package/_dist/routes.d.ts +46 -0
  44. package/_dist/routes.d.ts.map +1 -0
  45. package/_dist/save.d.ts +6 -0
  46. package/_dist/save.d.ts.map +1 -0
  47. package/_dist/socket.d.ts +73 -0
  48. package/_dist/socket.d.ts.map +1 -0
  49. package/_dist/subs.d.ts +134 -0
  50. package/_dist/subs.d.ts.map +1 -0
  51. package/_dist/timing.d.ts +8 -0
  52. package/_dist/timing.d.ts.map +1 -0
  53. package/_dist/tools.d.ts +80 -0
  54. package/_dist/tools.d.ts.map +1 -0
  55. package/_dist/vocab.d.ts +6 -0
  56. package/_dist/vocab.d.ts.map +1 -0
  57. package/access.js +32 -0
  58. package/access.js.map +1 -0
  59. package/access.ts +42 -0
  60. package/actor.js +75 -0
  61. package/actor.js.map +1 -0
  62. package/actor.ts +106 -0
  63. package/address.js +42 -0
  64. package/address.js.map +1 -0
  65. package/address.ts +49 -0
  66. package/admission.js +71 -0
  67. package/admission.js.map +1 -0
  68. package/admission.ts +64 -0
  69. package/asset.js +37 -0
  70. package/asset.js.map +1 -0
  71. package/asset.ts +47 -0
  72. package/batches.js +92 -0
  73. package/batches.js.map +1 -0
  74. package/batches.ts +96 -0
  75. package/body.js +51 -0
  76. package/body.js.map +1 -0
  77. package/body.ts +82 -0
  78. package/deno.js +88 -0
  79. package/deno.js.map +1 -0
  80. package/deno.json +1 -0
  81. package/deno.ts +150 -0
  82. package/doors.js +435 -0
  83. package/doors.js.map +1 -0
  84. package/doors.ts +570 -0
  85. package/graph.js +12 -0
  86. package/graph.js.map +1 -0
  87. package/graph.ts +23 -0
  88. package/headers.js +5 -0
  89. package/headers.js.map +1 -0
  90. package/headers.ts +9 -0
  91. package/interest.js +224 -0
  92. package/interest.js.map +1 -0
  93. package/interest.ts +264 -0
  94. package/log.js +1011 -0
  95. package/log.js.map +1 -0
  96. package/log.ts +1035 -0
  97. package/mod.js +69 -0
  98. package/mod.js.map +1 -0
  99. package/mod.ts +142 -0
  100. package/package.json +75 -4
  101. package/peer_query.js +164 -0
  102. package/peer_query.js.map +1 -0
  103. package/peer_query.ts +158 -0
  104. package/publish.js +7 -0
  105. package/publish.js.map +1 -0
  106. package/publish.ts +16 -0
  107. package/reached.js +456 -0
  108. package/reached.js.map +1 -0
  109. package/reached.ts +549 -0
  110. package/receipts.js +543 -0
  111. package/receipts.js.map +1 -0
  112. package/receipts.ts +749 -0
  113. package/refuse.js +120 -0
  114. package/refuse.js.map +1 -0
  115. package/refuse.ts +179 -0
  116. package/relay.js +249 -0
  117. package/relay.js.map +1 -0
  118. package/relay.ts +284 -0
  119. package/request.js +218 -0
  120. package/request.js.map +1 -0
  121. package/request.ts +235 -0
  122. package/requests.js +250 -0
  123. package/requests.js.map +1 -0
  124. package/requests.ts +257 -0
  125. package/route.js +139 -0
  126. package/route.js.map +1 -0
  127. package/route.ts +228 -0
  128. package/routed.js +25 -0
  129. package/routed.js.map +1 -0
  130. package/routed.ts +53 -0
  131. package/routes.js +154 -0
  132. package/routes.js.map +1 -0
  133. package/routes.ts +201 -0
  134. package/save.js +341 -0
  135. package/save.js.map +1 -0
  136. package/save.ts +393 -0
  137. package/socket.js +398 -0
  138. package/socket.js.map +1 -0
  139. package/socket.ts +496 -0
  140. package/subs.js +2295 -0
  141. package/subs.js.map +1 -0
  142. package/subs.ts +2979 -0
  143. package/timing.js +17 -0
  144. package/timing.js.map +1 -0
  145. package/timing.ts +26 -0
  146. package/tools.js +251 -0
  147. package/tools.js.map +1 -0
  148. package/tools.ts +315 -0
  149. package/vocab.js +18 -0
  150. package/vocab.js.map +1 -0
  151. package/vocab.json +93 -0
  152. package/vocab.ts +18 -0
package/receipts.ts ADDED
@@ -0,0 +1,749 @@
1
+ /**
2
+ * A keyed write and its receipt: committed once, and every resend told what
3
+ * the first send was told.
4
+ *
5
+ * Every host keeps its receipts in one place, its write log (`./log.ts`),
6
+ * plain SQLite tables on the graph's own connection, and inserts each in the
7
+ * transaction that commits its write.
8
+ *
9
+ * - Every receipt is named by its writer and key (`./log.ts` `receiptKey`),
10
+ * so two writers' same key never meet, and an outbox key's is bound to its
11
+ * body. @yaks/api's own door keeps one with its graph's hooks
12
+ * ({@link receipts}, {@link received}); the request token is an in-process
13
+ * capability, not client input.
14
+ * - A host's door over the log ({@link door}) also keeps the input it could
15
+ * not commit yet: while its row ceiling stopped it, while it could not
16
+ * start, or while it failed, and replays it in order once the object may
17
+ * write again; {@link landing} completes each write in the transaction
18
+ * that commits it.
19
+ *
20
+ * @module
21
+ */
22
+ import { decode } from '@yaks/vocab/wire'
23
+ import {
24
+ type Actor,
25
+ type Bundle,
26
+ type Graph,
27
+ type Plugin,
28
+ token,
29
+ } from '@yaks/graph'
30
+ import type { Driver } from 'jsr:@yaks/sql@0.2.36'
31
+ import { Refused } from '@yaks/graph/errors'
32
+ import { published } from './publish.js'
33
+ import { json, refuse } from './refuse.js'
34
+ import {
35
+ aside,
36
+ dead,
37
+ done,
38
+ durable,
39
+ fingerprinted,
40
+ first,
41
+ fits,
42
+ held,
43
+ IDEMPOTENCY,
44
+ keep,
45
+ type Kept,
46
+ landed,
47
+ named,
48
+ next,
49
+ opened,
50
+ owned,
51
+ parked,
52
+ raise,
53
+ type Receipt,
54
+ receiptKey,
55
+ received as logged,
56
+ remembered,
57
+ replayed,
58
+ said,
59
+ type Sent,
60
+ started,
61
+ taken,
62
+ unstarted,
63
+ waiting,
64
+ } from './log.js'
65
+
66
+ // A keyed write on its way to the graph: the request its receipt is kept
67
+ // under in the log (log.ts `named`), and whether it carried no bundles.
68
+ type Asked = { receipt: Request; empty: boolean }
69
+ let pending = new Map<string, Asked>()
70
+ let requestKey = '$apiReceipt'
71
+
72
+ class Replay extends Error {
73
+ constructor(public answer: Bundle[]) {
74
+ super('committed write replay')
75
+ this.name = 'Refused'
76
+ }
77
+ }
78
+
79
+ // The log, raised once a connection (log.ts `raise`): a host whose schema
80
+ // names it stands already, and one that does not gains it at its first
81
+ // keyed write.
82
+ let raised = new WeakSet<object>()
83
+ const writeLog = Symbol('API write log')
84
+ type ReceiptPlugin = Plugin & { [writeLog]?: Driver }
85
+ let standing = (db: Driver) => {
86
+ let at = db.connection ?? db
87
+ if (raised.has(at)) return
88
+ raise(db)
89
+ raised.add(at)
90
+ }
91
+
92
+ /** API-owned graph hooks over the host's write log (`db`), also loaded by
93
+ * the box's graph facet: a keyed write's receipt is inserted in the
94
+ * transaction that commits it, and a resend is told what it was told. */
95
+ export let receipts = (db: Driver): Plugin => {
96
+ let writes = new WeakMap<object, Asked>()
97
+ let plugin: ReceiptPlugin = {
98
+ [writeLog]: db,
99
+ name: '@yaks/api/receipts',
100
+ requests: [requestKey],
101
+ authorize: (bundles, _tx, _error, context) => {
102
+ let marked = bundles.find((b) => requestKey in b)
103
+ if (!marked) return bundles
104
+ let key = marked[requestKey]
105
+ let held = typeof key == 'string' ? pending.get(key) : undefined
106
+ if (!held || !context?.transaction) {
107
+ throw new Refused('invalid API receipt capability')
108
+ }
109
+ let name = held.receipt.headers.get(IDEMPOTENCY)!
110
+ // Its body bound: another body under the same key is refused here.
111
+ let was = first(db, name, held.receipt)
112
+ if (was?.state == 'applied') {
113
+ let vocab = (context.graph as Graph).vocab
114
+ throw new Replay(decode(vocab, JSON.parse(was.answer)))
115
+ }
116
+ writes.set(context.transaction, held)
117
+ return bundles.flatMap((b) => {
118
+ if (!(requestKey in b)) return [b]
119
+ let { [requestKey]: _key, ...rest } = b
120
+ return held.empty ? [] : [rest as Bundle]
121
+ })
122
+ },
123
+ hooks: {
124
+ commit: (bundles, _tx, _error, context) => {
125
+ let held = context?.transaction && writes.get(context.transaction)
126
+ if (!held) return bundles
127
+ let vocab = (context!.graph as Graph).vocab
128
+ logged(db, { request: held.receipt }, () => published(vocab, bundles))
129
+ return bundles
130
+ },
131
+ },
132
+ }
133
+ return plugin
134
+ }
135
+
136
+ /** Apply with a receipt named by its writer and key (log.ts `receiptKey`),
137
+ * kept in the graph's registered write log in the write's own transaction.
138
+ * A standalone door may supply the graph's own connection as `db`.
139
+ * It is kept as every receipt under
140
+ * that key is: an outbox key's for good and bound to its exact body, since a
141
+ * durable browser outbox may replay after an arbitrary delay, and any other's
142
+ * for the resend window. A host with no log refuses a keyed write
143
+ * rather than apply it without the receipt that makes a resend safe. */
144
+ export let received = async (
145
+ graph: Graph,
146
+ db: Driver | undefined,
147
+ key: string,
148
+ body: string,
149
+ actor: Actor | null,
150
+ bundles: Bundle[],
151
+ options: Parameters<Graph['apply']>[1],
152
+ ): Promise<Bundle[]> => {
153
+ let registered = (graph.plugins as ReceiptPlugin[]).find((p) => p[writeLog])
154
+ ?.[writeLog]
155
+ let log = registered ?? db
156
+ if (!log) throw new Refused('Idempotency-Key needs a host with a write log')
157
+ standing(log)
158
+ if (!registered) graph.use(receipts(log))
159
+ if (bundles.some((b) => requestKey in b)) {
160
+ throw new Refused('invalid API receipt capability')
161
+ }
162
+ let capability = crypto.randomUUID()
163
+ pending.set(capability, {
164
+ receipt: named(receiptKey(actor, key), token(body)!),
165
+ empty: !bundles.length,
166
+ })
167
+ try {
168
+ let marked = bundles.length
169
+ ? bundles.map((b, i) => i ? b : { ...b, [requestKey]: capability })
170
+ : [{
171
+ entity: { eid: crypto.randomUUID() },
172
+ $quiet: true,
173
+ [requestKey]: capability,
174
+ }]
175
+ return await graph.apply(marked, options)
176
+ } catch (error) {
177
+ if (error instanceof Replay) return error.answer
178
+ throw error
179
+ } finally {
180
+ pending.delete(capability)
181
+ }
182
+ }
183
+
184
+ // ---- landing a write in its batch's transaction -----------------------------
185
+
186
+ /** A host's log and the words its answers are kept in, read as each is
187
+ * needed: an object opens its storage again with each incarnation. */
188
+ export type Beside = {
189
+ readonly db: Driver
190
+ readonly vocab: Graph['vocab']
191
+ now: () => number
192
+ }
193
+
194
+ /** What a commit lands: a kept write by its place in the log, a live keyed
195
+ * request by its receipt, or neither. */
196
+ export type Mark = number | Receipt | null
197
+
198
+ /** A host's hook into its graph's commits, and the one apply it names a
199
+ * write for. */
200
+ export type Landing = {
201
+ plugin: Plugin
202
+ during: <T>(mark: Mark, apply: () => T) => T
203
+ }
204
+
205
+ /** The hook that completes a write in the transaction that commits its
206
+ * batch: a kept write leaves the log, or stays `applied` with its answer
207
+ * (`landed`), and a live keyed request's receipt is inserted (`received`). A
208
+ * resend cannot see one without the other. `during` names the write for the
209
+ * one synchronous `apply()` it wraps; every other batch (an effect's, a
210
+ * tick's, one applied after an await) finds none named.
211
+ *
212
+ * ```ts
213
+ * import { equal } from '@yaks/testing'
214
+ * import { graph } from '@yaks/graph'
215
+ * import { ram } from '@yaks/ram'
216
+ * import { loadVocab } from '@yaks/vocab'
217
+ * import { open } from '@yaks/sqlite/db'
218
+ * import { keep, next, raise } from './log.ts'
219
+ * import { landing } from './receipts.ts'
220
+ * let vocab = loadVocab({ $defs: { doc: { component: true, type: 'object',
221
+ * properties: { title: { type: 'string' } } } } })
222
+ * let db = open(':memory:')
223
+ * raise(db)
224
+ * let hook = landing({ db, vocab, now: Date.now })
225
+ * let g = graph({ vocab, storage: ram(vocab), plugins: [hook.plugin] })
226
+ * let sent = new Request('http://store/apply', { method: 'POST', body: '[]' })
227
+ * let seq = keep(db, sent, '[]')
228
+ * await hook.during(seq, () => g.apply([{ entity: { eid: 'a' }, doc: { title: 'A' } }]))
229
+ * equal(next(db), null)
230
+ * ```
231
+ */
232
+ export let landing = (log: Beside): Landing => {
233
+ let at: Mark = null
234
+ let plugin: Plugin = {
235
+ name: '@yaks/api/log',
236
+ // Logging follows a successful write and adds no admission refusal.
237
+ admission: () => true,
238
+ hooks: {
239
+ commit: (bundles) => {
240
+ if (at != null) {
241
+ let answer = () => published(log.vocab, bundles)
242
+ if (typeof at == 'number') landed(log.db, at, answer, log.now)
243
+ else logged(log.db, at, answer, log.now)
244
+ at = null
245
+ }
246
+ return bundles
247
+ },
248
+ },
249
+ }
250
+ return {
251
+ plugin,
252
+ during: <T>(mark: Mark, apply: () => T): T => {
253
+ at = mark
254
+ try {
255
+ return apply()
256
+ } finally {
257
+ at = null
258
+ }
259
+ },
260
+ }
261
+ }
262
+
263
+ // ---- the door a kept write comes in at, and its replay ----------------------
264
+
265
+ /** A refusal that asks to be sent again `retry.after` ms on. */
266
+ export type Halt = Error & { retry: { after: number } }
267
+
268
+ /** What keeps an object from writing for a while, given as data: its row
269
+ * ceiling (@yaks/durable-object `bounded`), whose statements the log's own
270
+ * still take while it is stopped. */
271
+ export type Window = {
272
+ /** What a write would be refused with now, if anything. */
273
+ refusal: () => Halt | null
274
+ /** Run statements a stopped object must still take. */
275
+ free: <T>(body: () => T) => T
276
+ /** Whether a failure is the window's refusal. */
277
+ stops: (error: unknown) => error is Halt
278
+ }
279
+
280
+ /** What a host lends its write log's replay ({@link replays}). */
281
+ export type Replayer = {
282
+ readonly db: Driver
283
+ now: () => number
284
+ readonly window: Window
285
+ /** One kept write applied, `mark` naming it to {@link landing}. */
286
+ commit: (request: Request, mark: Mark) => Promise<Response>
287
+ /** The object's alarm at `at`; `why` says what for. */
288
+ arm: (at: number, why?: string) => unknown
289
+ /** A failure, where it happened. */
290
+ report: (error: unknown, request: string) => void
291
+ /** A replay, or a read's wait on one, as a phase of the host's trace. */
292
+ stage?: (
293
+ name: 'replay' | 'settle',
294
+ work: () => Promise<void>,
295
+ ) => Promise<void>
296
+ /** How long until the alarm comes back for a write kept on a failure. */
297
+ retry?: number
298
+ }
299
+
300
+ /** What a host lends its write log's door. */
301
+ export type Host = Beside & Replayer & {
302
+ /** The object brought up for a request: its refusal, if it can't be. */
303
+ ready: (request: Request) => Promise<Response | null>
304
+ /** Every other door, for a write the log does not keep. */
305
+ serve: (request: Request) => Promise<Response>
306
+ /** Today's authority to write, asked of a durable outbox write before its
307
+ * receipt is told: a cached acceptance is still a write answer. */
308
+ authorize: (request: Request) => Promise<void>
309
+ /** Whether the log may keep a body, as said before decoding: one carrying
310
+ * a secret's value it may not. */
311
+ keeps: (told: string) => boolean
312
+ /** The caller's own view of an answer. */
313
+ answer: (request: Request, response: Response) => Promise<Response>
314
+ /** Why the object could not start, once it could not. */
315
+ refused: () => string | null
316
+ /** Who sent a request, said by its headers alone: the log names a keyed
317
+ * write by its writer (`./log.ts` `receiptKey`) before the host may have
318
+ * started to ask anything more. */
319
+ writer: (request: Request) => Actor | null
320
+ }
321
+
322
+ /** The replay of a host's write log ({@link replays}). */
323
+ export type Replays = {
324
+ /** The log, from its oldest waiting write, one replay at a time. */
325
+ drain: () => Promise<void>
326
+ /** The log first, for a request that reads: unless the log itself failed,
327
+ * which the alarm owns, or a replay is already running. */
328
+ settle: () => Promise<unknown> | void
329
+ /** A replay asked for anew, by the alarm or a person's retry: the log that
330
+ * failed last time may stand now. */
331
+ mend: () => Promise<void>
332
+ }
333
+
334
+ /** A host's write door over its log ({@link door}). */
335
+ export type Door = Replays & {
336
+ /** The hook that lands each write in its batch's transaction: last among
337
+ * the graph's, so the answer a keyed write keeps is the batch as every
338
+ * other commit hook left it. */
339
+ plugin: Plugin
340
+ /** A write in at `/apply`. */
341
+ write: (request: Request) => Promise<Response>
342
+ /** A durable outbox write as its commit begins: today's authority asked
343
+ * first, then the request bound to its body. Only a matching durable
344
+ * receipt may stand in for a rehearsal (`check`), which is told what the
345
+ * write was told; a fresh rehearsal still runs every guard and never
346
+ * writes a receipt. */
347
+ bound: (
348
+ request: Request,
349
+ text: string,
350
+ check?: boolean,
351
+ ) => Promise<Request | Response>
352
+ /** A batch's commit around the host's one synchronous `apply()`, the
353
+ * write it lands named to `plugin` for exactly that call: a live keyed
354
+ * write is looked for once more right before it, and one already in the
355
+ * log is told what that one was told. */
356
+ applying: <T>(request: Request, mark: Mark, apply: () => T) => T | Response
357
+ }
358
+
359
+ // A JSON answer's headers, for one the write log kept as text.
360
+ let JSONED = { headers: { 'content-type': 'application/json' } }
361
+
362
+ /**
363
+ * The one drain of a host's write log, from its oldest waiting write, and
364
+ * the live callers it answers as each lands. What it leaves `running` (a
365
+ * reset cut it off) or `failed` is the host's to take up, since only the
366
+ * host knows whether a write it started may be tried again: a Store asks for
367
+ * review (log.ts `interrupted`), a Builder hears a line in the transaction
368
+ * that lands it, so it replays one again.
369
+ */
370
+ let replaying = (host: Replayer) => {
371
+ let { now, report } = host
372
+ let retry = host.retry ?? 60_000
373
+ let stage = host.stage ?? ((_name, work) => work())
374
+ // The replay in progress, one at a time; whether the last one stopped
375
+ // because the log itself failed, which the alarm or the next incarnation
376
+ // takes up; and the live callers waiting on a kept write, by its place.
377
+ let draining: Promise<void> | null = null
378
+ let stuck = false
379
+ let callers = new Map<number, (answer: Response) => void>()
380
+
381
+ let wait = () => host.window.refusal()?.retry.after ?? 0
382
+ // The alarm, `ms` from now: when this object's window ends.
383
+ let later = (ms: number) => host.arm(now() + ms, 'stopped')
384
+ let tell = (seq: number, answer: Response) => {
385
+ let caller = callers.get(seq)
386
+ callers.delete(seq)
387
+ caller?.(answer)
388
+ }
389
+
390
+ /** The answer for a write kept while this object is stopped, `ms` more,
391
+ * and the alarm that comes back for it then. */
392
+ let waits = (seq: number, ms: number): Response => {
393
+ void later(ms)
394
+ let s = Math.ceil(ms / 1000)
395
+ let answer = parked(
396
+ seq,
397
+ `this app is past the rows it may write for ${s} s`,
398
+ )
399
+ answer.headers.set('retry-after', String(s))
400
+ return answer
401
+ }
402
+
403
+ /** The caller's answer for a kept write, and the alarm that comes back for
404
+ * it. */
405
+ let park = (seq: number, why: string): Response => {
406
+ void host.arm(now() + retry)
407
+ return parked(seq, why)
408
+ }
409
+
410
+ /** One kept write, applied: out of the log when it commits or is refused
411
+ * as asked, and set aside when it fails (`aside`), its failure reported
412
+ * where the host's commit caught it. `live` is a write whose caller is
413
+ * still here to be told its refusal; a replay's refusal has nobody to
414
+ * tell, so it stays in the log with its reason and is reported. */
415
+ let land = async (k: Kept, live: boolean): Promise<Response> => {
416
+ try {
417
+ let r = await host.commit(replayed(k), k.seq)
418
+ // The window's to wait out (`drain`), never the write's refusal.
419
+ if (r.status == 429 && wait()) return r
420
+ if (r.status < 300) done(host.db, k.seq)
421
+ else if (r.status >= 500) aside(host.db, k.seq, await said(r.clone()))
422
+ else if (live) done(host.db, k.seq)
423
+ else {
424
+ let why = await said(r.clone())
425
+ dead(host.db, k.seq, why)
426
+ report(
427
+ new Error(`a kept write no longer applies: ${why}`),
428
+ 'write replay',
429
+ )
430
+ }
431
+ return r
432
+ } catch (e) {
433
+ if (host.window.stops(e)) throw e
434
+ report(e, 'write replay')
435
+ if (held(host.db, k.seq)) aside(host.db, k.seq, String(e))
436
+ return refuse(e)
437
+ }
438
+ }
439
+
440
+ /** The log from its oldest waiting write to its newest, one at a time. A
441
+ * write that fails is set aside (`land`) and the ones behind it go on;
442
+ * only the log itself failing stops the pass, and then the alarm or the
443
+ * next incarnation starts another. Each write whose caller is still
444
+ * waiting is answered as it lands; the ones left waiting are told they are
445
+ * kept. */
446
+ let drain = (): Promise<void> => {
447
+ if (draining) return draining
448
+ let run = async () => {
449
+ // Yield once, so `draining` is set before the loop can end and clear
450
+ // it: a write that arrives in between must find the loop running.
451
+ await null
452
+ let at: Kept | null = null
453
+ try {
454
+ for (let k = at = next(host.db); k; k = at = next(host.db, k.seq)) {
455
+ let live = callers.has(k.seq)
456
+ started(host.db, k.seq)
457
+ let r = await land(k, live)
458
+ // Stopped before it applied: it waits again as it was, and every
459
+ // write behind it with it, until the window ends.
460
+ let ms = r.status == 429 ? wait() : 0
461
+ if (ms) {
462
+ let seq = k.seq
463
+ host.window.free(() => unstarted(host.db, seq))
464
+ tell(seq, waits(seq, ms))
465
+ break
466
+ }
467
+ let kept = r.status >= 500 && held(host.db, k.seq)
468
+ // A storage failure can escape even the log's error handler. Keep
469
+ // the live caller reachable until every response read is done, so
470
+ // the failure cleanup below can still answer it.
471
+ tell(k.seq, kept ? parked(k.seq, await said(r)) : r)
472
+ }
473
+ } catch (e) {
474
+ if (host.window.stops(e)) {
475
+ let seq = at?.seq
476
+ if (seq != null) host.window.free(() => unstarted(host.db, seq))
477
+ } else {
478
+ stuck = true
479
+ report(e, 'write replay')
480
+ }
481
+ }
482
+ // Synchronously after the last look at the log: nothing can be kept
483
+ // between that look and this line without finding the loop gone.
484
+ draining = null
485
+ let ms = wait()
486
+ for (let [seq, caller] of callers) {
487
+ caller(
488
+ ms
489
+ ? waits(seq, ms)
490
+ : park(seq, 'earlier writes to this app are still waiting'),
491
+ )
492
+ }
493
+ if (ms && !callers.size) void later(ms)
494
+ callers.clear()
495
+ }
496
+ return draining = stage('replay', run)
497
+ }
498
+
499
+ return {
500
+ drain,
501
+ tell,
502
+ waits,
503
+ park,
504
+ /** Whether a replay may start now: none is running, and the log did
505
+ * not fail last time. */
506
+ idle: () => !stuck && !draining,
507
+ stuck: () => stuck,
508
+ /** What a live caller is told once its kept write lands. */
509
+ heard: (seq: number): Promise<Response> =>
510
+ new Promise<Response>((r) => {
511
+ let other = callers.get(seq)
512
+ callers.set(seq, other ? (a) => (other(a.clone()), r(a)) : r)
513
+ }),
514
+ settle(): Promise<unknown> | void {
515
+ let going = draining
516
+ if (going) return stage('settle', () => going)
517
+ // While stopped, what the log holds waits for the alarm.
518
+ if (wait()) return
519
+ if (!stuck && waiting(host.db)) return drain()
520
+ },
521
+ mend(): Promise<void> {
522
+ stuck = false
523
+ return drain()
524
+ },
525
+ }
526
+ }
527
+
528
+ /**
529
+ * The replay of a host's write log, for a host whose input comes in at a
530
+ * door of its own and is kept there (log.ts `keep`): a space's Builder keeps
531
+ * a person's lines so, and replays them one turn at a time.
532
+ *
533
+ * ```ts
534
+ * import { equal } from '@yaks/testing'
535
+ * import { open } from '@yaks/sqlite/db'
536
+ * import { keep, next, raise } from './log.ts'
537
+ * import { replays } from './receipts.ts'
538
+ * let db = open(':memory:')
539
+ * raise(db)
540
+ * let heard: string[] = []
541
+ * let log = replays({
542
+ * db,
543
+ * now: Date.now,
544
+ * arm: () => {},
545
+ * report: () => {},
546
+ * window: {
547
+ * refusal: () => null,
548
+ * free: (body) => body(),
549
+ * stops: (_e): _e is never => false,
550
+ * },
551
+ * commit: async (r) => (heard.push(await r.text()), new Response('[]')),
552
+ * })
553
+ * keep(db, new Request('http://builder/say', { method: 'POST' }), 'hello')
554
+ * await log.drain()
555
+ * equal([heard, next(db)], [['hello'], null])
556
+ * ```
557
+ */
558
+ export let replays = (host: Replayer): Replays => {
559
+ let { drain, settle, mend } = replaying(host)
560
+ return { drain, settle, mend }
561
+ }
562
+
563
+ /**
564
+ * A host's write door over its log. A live keyed write commits its mutation
565
+ * and successful receipt together, with no transient log stages. Input that
566
+ * cannot commit is kept and replayed in order by the one drain that runs at a
567
+ * time ({@link replays}). A write that finds the object stopped is kept and
568
+ * told when to look again, and the alarm armed for the window's end replays
569
+ * it. One that finds the object refusing to start, or the log itself
570
+ * failing, is answered 202 and waits in the log. A resend (its idempotency
571
+ * key already in the log) is the write it repeats: told what that one was
572
+ * told, or waiting beside it.
573
+ */
574
+ export let door = (host: Host): Door => {
575
+ let { now, report } = host
576
+ let { drain, tell, waits, park, idle, stuck, heard, settle, mend } =
577
+ replaying(host)
578
+
579
+ /** A write that arrives while this object may not write: kept in the log,
580
+ * which the window lets through (`free`), as `pending`, and told when to
581
+ * look again. A resend of one kept so is told the same; one of a write the
582
+ * log already settled waits, and hears what it was once the object
583
+ * writes. */
584
+ let hold = (request: Request, body: string, stop: Halt): Response => {
585
+ let key = request.headers.get(IDEMPOTENCY)
586
+ let was = host.window.free(() => key ? first(host.db, key, request) : null)
587
+ if (was && was.state != 'pending' && was.state != 'running') {
588
+ return refuse(stop)
589
+ }
590
+ let seq = was?.seq ??
591
+ host.window.free(() => keep(host.db, request, body, now))
592
+ return waits(seq, stop.retry.after)
593
+ }
594
+
595
+ /** A write in at `/apply`, its key named by its writer from here on. */
596
+ let write = async (came: Request): Promise<Response> => {
597
+ let request = owned(came, host.writer(came))
598
+ // A binary write is kept as it came, since decoding it needs a start
599
+ // that may not run, and is decoded as it lands.
600
+ let { body, told } = await taken(request)
601
+ let sent = () =>
602
+ new Request(request, { body: opened(request.headers, body) })
603
+ let key = request.headers.get(IDEMPOTENCY)
604
+ let seq: number
605
+ let was: Sent | null
606
+ let unkept = async () => {
607
+ let req = sent()
608
+ return await host.ready(req) ?? host.serve(req)
609
+ }
610
+ if (!fits(body) || !host.keeps(told)) {
611
+ // A browser keeps retrying its intent until acceptance. Never apply it
612
+ // without the receipt that makes a later resend safe.
613
+ if (durable(key)) {
614
+ return refuse(
615
+ new Refused(
616
+ 'outbox writes must fit in the write log and cannot carry secret values',
617
+ ),
618
+ )
619
+ }
620
+ return unkept()
621
+ }
622
+ // Authority is the replay's to check (the host's commit), as for every
623
+ // kept write.
624
+ let stop = host.window.refusal()
625
+ if (stop) return hold(fingerprinted(request, body), body, stop)
626
+ if (durable(key)) {
627
+ try {
628
+ await host.authorize(request)
629
+ request = fingerprinted(request, body)
630
+ } catch (e) {
631
+ if (host.window.stops(e)) {
632
+ return hold(fingerprinted(request, body), body, e)
633
+ }
634
+ return refuse(e)
635
+ }
636
+ }
637
+ try {
638
+ was = key ? first(host.db, key, request) : null
639
+ // No pending/running row for a successful live write. Readiness may
640
+ // yield, so check the key again afterwards and inside the commit,
641
+ // immediately before synchronous apply. Concurrent same-key requests
642
+ // cannot mutate twice.
643
+ if (!was && key) {
644
+ let no = await host.ready(request)
645
+ was = key ? first(host.db, key, request) : null
646
+ if (!was && !no && idle() && !waiting(host.db)) {
647
+ let r = await host.commit(sent(), { request })
648
+ // Its transaction unwound when the window refused it mid-way.
649
+ let stop = r.status == 429 ? host.window.refusal() : null
650
+ if (stop) return hold(request, body, stop)
651
+ if (r.status < 500) return host.answer(request, r)
652
+ // An error after the transaction must not enqueue its mutation
653
+ // again.
654
+ let committed = key ? first(host.db, key, request) : null
655
+ if (committed?.state == 'applied') {
656
+ return host.answer(request, new Response(committed.answer, JSONED))
657
+ }
658
+ seq = keep(host.db, request, body, now)
659
+ aside(host.db, seq, await said(r.clone()))
660
+ return park(seq, await said(r))
661
+ }
662
+ }
663
+ seq = was?.seq ?? keep(host.db, request, body, now)
664
+ } catch (e) {
665
+ if (e instanceof Refused) {
666
+ return (e as Refused & { status?: number }).status == 503
667
+ ? json({ error: e.name, message: e.message }, 503)
668
+ : refuse(e)
669
+ }
670
+ if (host.window.stops(e)) return hold(request, body, e)
671
+ report(e, 'write log')
672
+ // Readiness can throw too. Keep that input if storage still works;
673
+ // never bypass a keyed receipt after an error and risk a second
674
+ // mutation.
675
+ if (key) {
676
+ try {
677
+ let was = first(host.db, key, request)
678
+ if (was?.state == 'applied') {
679
+ return host.answer(request, new Response(was.answer, JSONED))
680
+ }
681
+ let seq = was?.seq ?? keep(host.db, request, body, now)
682
+ aside(host.db, seq, String(e))
683
+ return park(seq, String(e))
684
+ } catch {
685
+ return refuse(e)
686
+ }
687
+ }
688
+ return unkept()
689
+ }
690
+ if (was?.state == 'applied') {
691
+ return host.answer(request, new Response(was.answer, JSONED))
692
+ }
693
+ if (was?.state == 'refused') return refuse(new Refused(was.why))
694
+ if (was?.state == 'failed') return parked(seq, was.why, was.audit)
695
+ if (was?.state == 'interrupted' || was?.state == 'unreviewed') {
696
+ return parked(seq, was.why, true)
697
+ }
698
+ // Heard before yielding, so a replay a startup effect drains meanwhile
699
+ // answers it and treats its refusal as a live one.
700
+ let answer = heard(seq)
701
+ let no = await host.ready(request)
702
+ if (no || stuck()) {
703
+ tell(
704
+ seq,
705
+ park(
706
+ seq,
707
+ no
708
+ ? host.refused() ?? 'this app could not start'
709
+ : 'earlier writes to this app are still waiting',
710
+ ),
711
+ )
712
+ } else void drain()
713
+ return answer.then((response) => host.answer(request, response))
714
+ }
715
+
716
+ let { plugin, during } = landing(host)
717
+
718
+ return {
719
+ plugin,
720
+ write,
721
+ drain,
722
+ async bound(
723
+ request: Request,
724
+ text: string,
725
+ check = false,
726
+ ): Promise<Request | Response> {
727
+ let key = request.headers.get(IDEMPOTENCY)
728
+ if (!durable(key)) return request
729
+ await host.authorize(request)
730
+ request = fingerprinted(request, text)
731
+ // A rehearsal never comes in at `write`: its key is named here.
732
+ let answer = check
733
+ ? remembered(host.db, receiptKey(host.writer(request), key!), request)
734
+ : null
735
+ return answer ? host.answer(request, answer) : request
736
+ },
737
+ applying<T>(request: Request, mark: Mark, apply: () => T): T | Response {
738
+ if (mark != null && typeof mark != 'number') {
739
+ let key = mark.request.headers.get(IDEMPOTENCY)
740
+ let was = key ? first(host.db, key, request) : null
741
+ if (was?.state == 'applied') return new Response(was.answer, JSONED)
742
+ if (was) return parked(was.seq, was.why, was.audit)
743
+ }
744
+ return during(mark, apply)
745
+ },
746
+ settle,
747
+ mend,
748
+ }
749
+ }