@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/log.js ADDED
@@ -0,0 +1,1011 @@
1
+ /**
2
+ * The write log: a host's keyed writes and their receipts, and the input it
3
+ * could not commit yet, kept in plain SQLite tables beside its graph.
4
+ *
5
+ * - A live keyed request commits its mutation and receipt in one graph
6
+ * transaction ({@link landing}). Successful input needs no earlier pending
7
+ * or running row: the caller holds it until acknowledged, and a resend after
8
+ * a reset either finds the exact committed answer or applies an uncommitted
9
+ * mutation.
10
+ * - Input that cannot commit is kept with its headers and body, so a host that
11
+ * is stopped (its row ceiling's window), cannot start, or cannot apply it
12
+ * recovers without asking the caller to send it again. Pending writes replay
13
+ * oldest first, one replay at a time (`./receipts.ts` `door`), each live
14
+ * caller answered as its write lands. Failed writes wait for another incarnation;
15
+ * interrupted and legacy unreviewed attempts need explicit review. Reviewed
16
+ * retries keep their input and complete outcome forever.
17
+ * - Every keyed write is kept under its writer's name for its key
18
+ * ({@link receiptKey}), whichever door it came in at. Ordinary receipts
19
+ * expire after the resend window; browser outbox receipts and held input
20
+ * never expire.
21
+ *
22
+ * The tables belong to no vocabulary or app migration. Their place beside
23
+ * the graph makes the receipt and the mutation atomic even when the graph
24
+ * above storage cannot stand. A Store keeps its batches here, a space's
25
+ * Builder the lines a person said while it could not answer them, and every
26
+ * door of @yaks/api its keyed writes' receipts (`./receipts.ts` `received`).
27
+ *
28
+ * ```ts
29
+ * import { equal } from '@yaks/testing'
30
+ * import { open } from '@yaks/sqlite/db'
31
+ * import { done, keep, next, raise, replayed } from './log.ts'
32
+ * let db = open(':memory:')
33
+ * raise(db)
34
+ * let sent = new Request('http://store/apply', { method: 'POST', body: '[]' })
35
+ * let seq = keep(db, sent, '[]')
36
+ * equal([next(db)?.seq, await replayed(next(db)!).text()], [seq, '[]'])
37
+ * done(db, seq)
38
+ * equal(next(db), null)
39
+ * ```
40
+ *
41
+ * @module
42
+ */ import { sha256, token } from "@yaks/graph";
43
+ import { composed } from "@yaks/graph/bundle";
44
+ import { derivedEid } from "@yaks/graph/identity";
45
+ import { Refused } from "@yaks/graph/errors";
46
+ import { fromBase64, toBase64 } from "@yaks/fp";
47
+ import { among, and, as, col, desc, eq, ge, gt, isNull, lit, lt, not, op, or, select, table, val } from "@yaks/sql";
48
+ import { BINARY, decode, stringify, unpack } from "@yaks/vocab/wire";
49
+ import { poured, writeBytes } from "./body.js";
50
+ import { IDEMPOTENCY } from "./headers.js";
51
+ export { IDEMPOTENCY };
52
+ // ---- a body as the log keeps it ---------------------------------------------
53
+ // A binary apply is kept undecoded: decoding needs the words a store's start
54
+ // reads, and a write is kept before its store has started, while it may not
55
+ // and when it can't. The log holds the envelope as it came, in base64 beside
56
+ // the headers that say it is binary, and its store decodes it as it lands.
57
+ /** Whether headers say their body is a binary envelope. */ export let binaryHeaders = (headers)=>headers.get('content-type')?.split(';')[0].trim() == BINARY;
58
+ /** A write's body as the log keeps it, and its bundles as it says them before
59
+ * any decoding, which is what a secret is looked for in. A JSON body is its
60
+ * text, both times; a binary one is its envelope in base64, and the
61
+ * envelope's header with its references. An envelope that can't be read is
62
+ * refused here, while its caller still holds it.
63
+ *
64
+ * ```ts
65
+ * import { equal } from '@yaks/testing'
66
+ * import { binary, BINARY } from '@yaks/vocab/wire'
67
+ * import { opened, taken } from './log.ts'
68
+ * let raw = binary([{ entity: { eid: 'a' }, photo: { bytes: Uint8Array.of(7) } }])
69
+ * let sent = (body: BodyInit, type = BINARY) =>
70
+ * new Request('http://store/apply', { method: 'POST', headers: { 'content-type': type }, body })
71
+ * let { body, told } = await taken(sent(raw))
72
+ * equal(told, '[{"entity":{"eid":"a"},"photo":{"bytes":{"$bytes":0,"length":1}}}]')
73
+ * equal(opened(new Headers({ 'content-type': BINARY }), body), raw)
74
+ * equal(await taken(sent('[]', 'application/json')), { body: '[]', told: '[]' })
75
+ * equal(opened(new Headers(), '[]'), '[]')
76
+ * ```
77
+ */ export let taken = async (request)=>{
78
+ let raw = await writeBytes(request);
79
+ if (!binaryHeaders(request.headers)) {
80
+ let body = new TextDecoder().decode(raw);
81
+ return {
82
+ body,
83
+ told: body
84
+ };
85
+ }
86
+ return {
87
+ body: toBase64(raw),
88
+ told: JSON.stringify(unpack(raw).value)
89
+ };
90
+ };
91
+ /** A kept body as it was sent: the envelope of a binary one (`taken`), the
92
+ * text of any other. */ export let opened = (headers, body)=>binaryHeaders(headers) ? fromBase64(body) : body;
93
+ /** What a kept body says once its words are known: a binary one's envelope
94
+ * decoded in them, as a JSON one's base64 values are. Only declared binary
95
+ * properties interpret payload references.
96
+ *
97
+ * ```ts
98
+ * import { equal } from '@yaks/testing'
99
+ * import { loadVocab } from '@yaks/vocab'
100
+ * import { binary, BINARY } from '@yaks/vocab/wire'
101
+ * import { decoded, taken } from './log.ts'
102
+ * let vocab = loadVocab({ $defs: { photo: { component: true, type: 'object',
103
+ * properties: { bytes: { type: 'string', contentEncoding: 'base64' } } } } })
104
+ * let bundle = { entity: { eid: 'a' }, photo: { bytes: Uint8Array.of(7) } }
105
+ * let { body } = await taken(new Request('http://store/apply', {
106
+ * method: 'POST', headers: { 'content-type': BINARY }, body: binary([bundle]),
107
+ * }))
108
+ * equal(decoded(vocab, new Headers({ 'content-type': BINARY }), body), [bundle])
109
+ * equal(decoded(vocab, new Headers(), '[{"photo":{"bytes":{"$bytes":"Bw==","encoding":"base64"}}}]'),
110
+ * [{ photo: { bytes: Uint8Array.of(7) } }])
111
+ * ```
112
+ */ export let decoded = (vocab, headers, body)=>{
113
+ if (!binaryHeaders(headers)) return decode(vocab, JSON.parse(body));
114
+ let packed = unpack(fromBase64(body));
115
+ return decode(vocab, packed.value, packed.payload);
116
+ };
117
+ // ---- the log ----------------------------------------------------------------
118
+ let LOG = 'yak_writes';
119
+ let KEY = 'idempotency_key';
120
+ let ANSWERS = 'yak_write_answers';
121
+ export let WRITES = {
122
+ t: 'create table',
123
+ name: LOG,
124
+ ifNot: true,
125
+ cols: [
126
+ {
127
+ name: 'seq',
128
+ type: 'integer',
129
+ pk: true,
130
+ autoincrement: true
131
+ },
132
+ {
133
+ name: 'at',
134
+ type: 'text',
135
+ notNull: true
136
+ },
137
+ {
138
+ name: 'headers',
139
+ type: 'text',
140
+ notNull: true
141
+ },
142
+ {
143
+ name: 'body',
144
+ type: 'text',
145
+ notNull: true
146
+ },
147
+ {
148
+ name: 'state',
149
+ type: 'text',
150
+ notNull: true,
151
+ default: lit('pending')
152
+ },
153
+ {
154
+ name: 'tries',
155
+ type: 'integer',
156
+ notNull: true,
157
+ default: lit(0)
158
+ },
159
+ {
160
+ name: 'why',
161
+ type: 'text'
162
+ },
163
+ {
164
+ name: KEY,
165
+ type: 'text'
166
+ },
167
+ {
168
+ name: 'answer',
169
+ type: 'text'
170
+ },
171
+ {
172
+ name: 'generation',
173
+ type: 'integer'
174
+ },
175
+ {
176
+ name: 'audit',
177
+ type: 'integer',
178
+ notNull: true,
179
+ default: lit(0)
180
+ },
181
+ {
182
+ name: 'status',
183
+ type: 'integer'
184
+ }
185
+ ]
186
+ };
187
+ let PARTS = {
188
+ t: 'create table',
189
+ name: ANSWERS,
190
+ ifNot: true,
191
+ cols: [
192
+ {
193
+ name: 'seq',
194
+ type: 'integer',
195
+ notNull: true
196
+ },
197
+ {
198
+ name: 'part',
199
+ type: 'integer',
200
+ notNull: true
201
+ },
202
+ {
203
+ name: 'body',
204
+ type: 'text',
205
+ notNull: true
206
+ }
207
+ ]
208
+ };
209
+ /** The empty write log and its indexes, shared with prepared test stores. */ export let schema = ()=>[
210
+ WRITES,
211
+ PARTS,
212
+ {
213
+ t: 'create index',
214
+ name: `${LOG}_${KEY}`,
215
+ on: LOG,
216
+ cols: [
217
+ col(KEY)
218
+ ],
219
+ unique: true,
220
+ ifNot: true
221
+ },
222
+ // Ordinary keyed receipts last ten minutes; outbox receipts last forever.
223
+ // Neither pending work nor expiry may scan that retained history.
224
+ {
225
+ t: 'create index',
226
+ name: `${LOG}_pending`,
227
+ on: LOG,
228
+ cols: [
229
+ col('seq')
230
+ ],
231
+ where: eq(col('state'), lit('pending')),
232
+ ifNot: true
233
+ },
234
+ {
235
+ t: 'create index',
236
+ name: `${LOG}_expiring`,
237
+ on: LOG,
238
+ cols: [
239
+ col('at')
240
+ ],
241
+ where: EXPIRABLE,
242
+ ifNot: true
243
+ },
244
+ {
245
+ t: 'create index',
246
+ name: `${ANSWERS}_seq_part`,
247
+ on: ANSWERS,
248
+ cols: [
249
+ col('seq'),
250
+ col('part')
251
+ ],
252
+ unique: true,
253
+ ifNot: true
254
+ },
255
+ // Waking repairs only interrupted attempts, never successful history.
256
+ ...[
257
+ 'running',
258
+ 'failed'
259
+ ].map((state)=>({
260
+ t: 'create index',
261
+ name: `${LOG}_${state}`,
262
+ on: LOG,
263
+ cols: [
264
+ col('seq')
265
+ ],
266
+ where: eq(col('state'), lit(state)),
267
+ ifNot: true
268
+ }))
269
+ ];
270
+ /** The log, raised, with every column it predates added: an object keeps its
271
+ * log across code versions, and whichever code wakes it next reads it. */ export let raise = (db)=>{
272
+ db.query(WRITES);
273
+ db.query(PARTS);
274
+ let has = db.query({
275
+ t: 'pragma',
276
+ name: 'table_info',
277
+ arg: LOG
278
+ }).map((r)=>String(r.name));
279
+ for (let add of WRITES.cols){
280
+ if (!has.includes(add.name)) {
281
+ db.query({
282
+ t: 'alter table',
283
+ table: LOG,
284
+ add
285
+ });
286
+ }
287
+ }
288
+ for (let stmt of schema().slice(2))db.query(stmt);
289
+ // The old index included durable receipts: retire it after its replacement.
290
+ db.query({
291
+ t: 'drop',
292
+ kind: 'index',
293
+ name: `${LOG}_expiry`,
294
+ ifExists: true
295
+ });
296
+ };
297
+ // How long an applied write keeps its answer for a resend. The kernel resends
298
+ // within half a minute (@yaks/durable-object `backoff`), so this is room to
299
+ // spare.
300
+ let WINDOW = 10 * 60_000;
301
+ let BATCH = 16;
302
+ // What a connection knows of its log without reading it: when it last expired
303
+ // receipts, and that it holds no waiting write, from the last look until
304
+ // something keeps one (`keep`, `retry`, `revived`). Every row in the log is
305
+ // written here, so a look is good until one of those runs.
306
+ let swept = new WeakMap();
307
+ let idle = new WeakSet();
308
+ let of = (db)=>db.connection ?? db;
309
+ let PENDING = eq(col('state'), lit('pending'));
310
+ let FAILED = eq(col('state'), lit('failed'));
311
+ let APPLIED = eq(col('state'), lit('applied'));
312
+ let RUNNING = eq(col('state'), lit('running'));
313
+ let INTERRUPTED = eq(col('state'), lit('interrupted'));
314
+ let UNREVIEWED = eq(col('state'), lit('unreviewed'));
315
+ let AUDIT = eq(col('audit'), lit(1));
316
+ let REVIVABLE = and(FAILED, not(AUDIT));
317
+ // Case-sensitive, just like the browser's stable key prefix. Keep this in the
318
+ // partial index too, so expiry never walks indefinitely retained receipts.
319
+ let EXPIRABLE = and(APPLIED, not(AUDIT), or(isNull(col(KEY)), not(op('glob', col(KEY), lit('outbox:*')))));
320
+ /** Browser outbox intents need the same answer even after hours offline. */ export let durable = (key)=>key?.startsWith('outbox:') ?? false;
321
+ let at = (seq)=>eq(col('seq'), val(seq));
322
+ let outcome = (db, seq)=>{
323
+ let rows = db.query(select({
324
+ cols: [
325
+ col('body')
326
+ ],
327
+ from: table(ANSWERS),
328
+ where: at(seq),
329
+ order: [
330
+ col('part')
331
+ ]
332
+ }));
333
+ if (!rows.length) throw new Error(`audited write ${seq} has no outcome`);
334
+ return rows.map((r)=>String(r.body)).join('');
335
+ };
336
+ // A reset rolls the graph transaction back, but not this earlier marker. A
337
+ // committed write changes or removes its log row in the graph transaction.
338
+ export let started = (db, seq)=>void db.query({
339
+ t: 'update',
340
+ table: LOG,
341
+ set: {
342
+ state: lit('running'),
343
+ tries: op('+', col('tries'), lit(1))
344
+ },
345
+ where: and(at(seq), PENDING)
346
+ });
347
+ /** A started write its store stopped before it could apply it
348
+ * (`./receipts.ts` `replays`): waiting again, its try not counted, so the
349
+ * replay after the wait takes it as it was. Its transaction unwound, so
350
+ * nothing of it landed. Without `seq`, every write a reset cut off, for a
351
+ * host that hears a write only in the transaction that lands it, so a reset
352
+ * left nothing of one it started (a Builder's line). */ export let unstarted = (db, seq)=>{
353
+ idle.delete(of(db));
354
+ db.query({
355
+ t: 'update',
356
+ table: LOG,
357
+ set: {
358
+ state: lit('pending'),
359
+ tries: op('-', col('tries'), lit(1))
360
+ },
361
+ where: seq == null ? RUNNING : and(at(seq), RUNNING)
362
+ });
363
+ };
364
+ // A running marker survives a reset. Older code could leave a pending write
365
+ // after starting it, so every row it left is unreviewed until someone reads
366
+ // the body and deliberately retries. New writes carry a generation and retain
367
+ // ordinary automatic replay while they have not started.
368
+ export let interrupted = (db)=>{
369
+ let running = db.query({
370
+ t: 'update',
371
+ table: LOG,
372
+ set: {
373
+ state: lit('interrupted'),
374
+ why: lit('the Store reset while applying this write; inspect before retrying')
375
+ },
376
+ where: RUNNING,
377
+ returning: [
378
+ col('seq')
379
+ ]
380
+ });
381
+ let old = db.query({
382
+ t: 'update',
383
+ table: LOG,
384
+ set: {
385
+ state: lit('unreviewed'),
386
+ why: lit('this write predates attempt tracking; inspect before retrying')
387
+ },
388
+ where: and(PENDING, isNull(col('generation'))),
389
+ returning: [
390
+ col('seq')
391
+ ]
392
+ });
393
+ return {
394
+ running: running.length,
395
+ unreviewed: old.length
396
+ };
397
+ };
398
+ /** Kept writes, with the body only when one is named for inspection. */ export let writes = (db, seq, recent = false)=>db.query(select({
399
+ cols: [
400
+ col('seq'),
401
+ col('at'),
402
+ col('state'),
403
+ col('tries'),
404
+ col('why'),
405
+ col('status'),
406
+ col('audit'),
407
+ col('headers'),
408
+ ...seq == null ? [] : [
409
+ col('body'),
410
+ col(KEY),
411
+ col('answer')
412
+ ]
413
+ ],
414
+ from: table(LOG),
415
+ where: seq == null ? recent ? undefined : not(APPLIED) : at(seq),
416
+ order: [
417
+ recent ? desc(col('seq')) : col('seq')
418
+ ],
419
+ limit: lit(seq == null ? 100 : 1)
420
+ })).map(({ headers, ...r })=>({
421
+ ...r,
422
+ kernel: new Headers(JSON.parse(String(headers))).get('x-yak-kernel') == '1',
423
+ ...seq != null && r.answer == null && r.state == 'applied' ? {
424
+ answer: outcome(db, seq)
425
+ } : {}
426
+ }));
427
+ /** Explicitly retry an interrupted or unreviewed write, keeping its body and
428
+ * key, and keeping its final answer beside them when it commits. */ export let retry = (db, seq)=>{
429
+ idle.delete(of(db));
430
+ return db.query({
431
+ t: 'update',
432
+ table: LOG,
433
+ set: {
434
+ state: lit('pending'),
435
+ generation: lit(1),
436
+ audit: lit(1),
437
+ why: lit(null),
438
+ answer: lit(null),
439
+ status: lit(null)
440
+ },
441
+ where: and(at(seq), or(INTERRUPTED, UNREVIEWED, and(FAILED, AUDIT))),
442
+ returning: [
443
+ col('seq')
444
+ ]
445
+ }).length > 0;
446
+ };
447
+ /** A write still held for review, without changing its state. */ export let kept = (db, seq)=>{
448
+ let [row] = db.query(select({
449
+ cols: [
450
+ col('seq'),
451
+ col('headers'),
452
+ col('body')
453
+ ],
454
+ from: table(LOG),
455
+ where: and(at(seq), or(INTERRUPTED, UNREVIEWED, and(FAILED, AUDIT))),
456
+ limit: lit(1)
457
+ }));
458
+ return row ? {
459
+ seq: Number(row.seq),
460
+ headers: String(row.headers),
461
+ body: String(row.body)
462
+ } : undefined;
463
+ };
464
+ /** Whether a request is a write the log keeps: a batch to apply. A dry run
465
+ * (`?check=1`) writes nothing. */ export let logged = (req)=>{
466
+ let url = new URL(req.url);
467
+ return req.method == 'POST' && url.pathname == '/apply' && !url.searchParams.has('check') && !poured(req);
468
+ };
469
+ // A Durable Object's SQLite holds at most 2 MB in one row. A bigger body —
470
+ // an NDJSON import, which the caller holds as a file and is answered line by
471
+ // line — is applied as it comes, without a place in the log.
472
+ export let ROOM = 1_900_000;
473
+ /** Whether a body fits in the log. */ export let fits = (body)=>body.length * 3 <= ROOM || new TextEncoder().encode(body).length <= ROOM;
474
+ // A write is stamped, and its receipts expire, on the clock of the host that
475
+ // keeps the log; unset, the runtime's.
476
+ let stamp = (now)=>new Date(now()).toISOString();
477
+ /** Expire a bounded batch of ordinary receipts, never held user input.
478
+ * A backlog is paid down by subsequent writes; an empty tail is checked at
479
+ * most once a tenth of the resend window. An app write never owes the whole
480
+ * directory's idle history. */ let expire = (db, now)=>{
481
+ let t = now();
482
+ if (t - (swept.get(of(db)) ?? -Infinity) < WINDOW / 10) return;
483
+ let gone = new Date(t - WINDOW).toISOString();
484
+ let rows = db.query({
485
+ t: 'delete',
486
+ from: LOG,
487
+ where: among(col('seq'), select({
488
+ cols: [
489
+ col('seq')
490
+ ],
491
+ from: table(LOG),
492
+ where: and(EXPIRABLE, lt(col('at'), val(gone))),
493
+ order: [
494
+ col('at')
495
+ ],
496
+ limit: lit(BATCH)
497
+ })),
498
+ // SQLite materializes RETURNING before yielding its first row. The
499
+ // inline receipt can occupy nearly a whole SQLite row.
500
+ returning: [
501
+ col('seq'),
502
+ as(isNull(col('answer')), 'chunked')
503
+ ]
504
+ });
505
+ for (let row of rows){
506
+ if (row.chunked) {
507
+ db.query({
508
+ t: 'delete',
509
+ from: ANSWERS,
510
+ where: at(Number(row.seq))
511
+ });
512
+ }
513
+ }
514
+ if (rows.length < BATCH) swept.set(of(db), t);
515
+ };
516
+ /** Keep one write that cannot commit now; its place in the replay log. */ export let keep = (db, req, body, now = Date.now)=>{
517
+ expire(db, now);
518
+ idle.delete(of(db));
519
+ let [row] = db.query({
520
+ t: 'insert',
521
+ into: LOG,
522
+ cols: [
523
+ 'at',
524
+ 'headers',
525
+ 'body',
526
+ KEY,
527
+ 'generation'
528
+ ],
529
+ rows: [
530
+ [
531
+ val(stamp(now)),
532
+ val(JSON.stringify([
533
+ ...req.headers
534
+ ])),
535
+ val(body),
536
+ val(req.headers.get(IDEMPOTENCY)),
537
+ lit(1)
538
+ ]
539
+ ],
540
+ returning: [
541
+ col('seq')
542
+ ]
543
+ });
544
+ return Number(row.seq);
545
+ };
546
+ // Internal evidence binds both the routed bytes and the original spanning intent.
547
+ // Recompute at the host's door: a caller-supplied digest is never evidence.
548
+ export let INTENT = 'x-yak-outbox-intent';
549
+ let FINGERPRINT = 'x-yak-outbox-fingerprint';
550
+ export let fingerprinted = (request, body)=>{
551
+ if (!durable(request.headers.get(IDEMPOTENCY))) return request;
552
+ let headers = new Headers(request.headers);
553
+ headers.set(FINGERPRINT, sha256(JSON.stringify([
554
+ body,
555
+ headers.get(INTENT),
556
+ headers.get('x-yak-person')
557
+ ])));
558
+ return new Request(request, {
559
+ headers,
560
+ body: opened(headers, body)
561
+ });
562
+ };
563
+ /**
564
+ * The key the log keeps a write under: its writer's and its sender's key as
565
+ * one name, so one writer's key never reads another's receipt. An outbox
566
+ * key's name is an outbox key too, kept for good ({@link durable}); any
567
+ * other expires after the resend window.
568
+ *
569
+ * ```ts
570
+ * import { equal } from '@yaks/testing'
571
+ * import { durable, receiptKey } from './log.ts'
572
+ * let ada = { by: 'ada' }
573
+ * equal(receiptKey(ada, 'k') == receiptKey({ by: 'bob' }, 'k'), false)
574
+ * equal(receiptKey(ada, 'k') == receiptKey(ada, 'k'), true)
575
+ * equal([durable(receiptKey(ada, 'outbox:k')), durable(receiptKey(ada, 'k'))],
576
+ * [true, false])
577
+ * ```
578
+ */ export let receiptKey = (writer, key)=>{
579
+ let id = derivedEid(`api receipt|${token([
580
+ writer?.by ?? null,
581
+ writer?.via ?? null,
582
+ key
583
+ ])}`);
584
+ return `${durable(key) ? 'outbox:' : ''}receipt:${id}`;
585
+ };
586
+ // The keys a log names (`receiptKey`) sort in two runs, `outbox:receipt:…`
587
+ // and `receipt:…`; a key kept as its sender said it sorts outside both, so
588
+ // the key's index finds those alone. A row with no key compares as neither.
589
+ let UNNAMED = or(lt(col(KEY), lit('outbox:receipt:')), and(ge(col(KEY), lit('outbox:receipt;')), lt(col(KEY), lit('receipt:'))), ge(col(KEY), lit('receipt;')));
590
+ /** A request with its key named by its writer ({@link receiptKey}), as the
591
+ * log keeps it; one with no key as it is. Its body is taken along unread. */ export let owned = (request, writer)=>{
592
+ let key = request.headers.get(IDEMPOTENCY);
593
+ if (!key) return request;
594
+ let headers = new Headers(request.headers);
595
+ headers.set(IDEMPOTENCY, receiptKey(writer, key));
596
+ return new Request(request, {
597
+ headers
598
+ });
599
+ };
600
+ /**
601
+ * Every key the log holds as its sender said it, named by its writer
602
+ * ({@link receiptKey}), in its column and in the headers its write is
603
+ * replayed with: a log kept by code that took a key as it came. `writer` says
604
+ * who sent each, from its request's headers. How many it named; a log named
605
+ * already costs one look at the key's index.
606
+ *
607
+ * ```ts
608
+ * import { equal } from '@yaks/testing'
609
+ * import { open } from '@yaks/sqlite/db'
610
+ * import { first, keep, raise, receiptKey, rekey } from './log.ts'
611
+ * let db = open(':memory:')
612
+ * raise(db)
613
+ * let sent = new Request('http://store/apply', {
614
+ * method: 'POST', headers: { 'idempotency-key': 'k', 'x-by': 'ada' },
615
+ * })
616
+ * keep(db, sent, '[]')
617
+ * let writer = (r: Request) => ({ by: r.headers.get('x-by')! })
618
+ * equal([rekey(db, writer), rekey(db, writer)], [1, 0])
619
+ * equal(first(db, receiptKey({ by: 'ada' }, 'k'))?.seq, 1)
620
+ * ```
621
+ */ export let rekey = (db, writer)=>{
622
+ let rows = db.query(select({
623
+ cols: [
624
+ col('seq'),
625
+ col(KEY),
626
+ col('headers')
627
+ ],
628
+ from: table(LOG),
629
+ where: UNNAMED
630
+ }));
631
+ for (let row of rows){
632
+ let headers = new Headers(JSON.parse(String(row.headers)));
633
+ let key = receiptKey(writer(new Request('http://log/', {
634
+ headers
635
+ })), String(row[KEY]));
636
+ headers.set(IDEMPOTENCY, key);
637
+ db.query({
638
+ t: 'update',
639
+ table: LOG,
640
+ set: {
641
+ [KEY]: val(key),
642
+ headers: val(JSON.stringify([
643
+ ...headers
644
+ ]))
645
+ },
646
+ where: at(Number(row.seq))
647
+ });
648
+ }
649
+ return rows.length;
650
+ };
651
+ /** The request a door that names its writes itself keeps a receipt under
652
+ * (`./receipts.ts` `received`): its `key` for the write ({@link
653
+ * receiptKey}), bound to the body `digest` names. */ export let named = (key, digest)=>new Request('http://receipt/apply', {
654
+ method: 'POST',
655
+ headers: {
656
+ [IDEMPOTENCY]: key,
657
+ [FINGERPRINT]: digest
658
+ }
659
+ });
660
+ /** The write a key was first sent with, if the log holds it. */ export let first = (db, key, request)=>{
661
+ let [row] = db.query(select({
662
+ cols: [
663
+ col('seq'),
664
+ col('state'),
665
+ col('why'),
666
+ col('answer'),
667
+ col('audit'),
668
+ ...durable(key) && request ? [
669
+ col('headers')
670
+ ] : []
671
+ ],
672
+ from: table(LOG),
673
+ where: eq(col(KEY), val(key))
674
+ }));
675
+ if (row && durable(key) && request) {
676
+ let before = new Headers(JSON.parse(String(row.headers)));
677
+ let digest = request.headers.get(FINGERPRINT);
678
+ if (!digest || before.get(FINGERPRINT) != digest) {
679
+ throw new Refused('outbox key was already used for a different intent');
680
+ }
681
+ }
682
+ return row ? {
683
+ seq: Number(row.seq),
684
+ state: String(row.state),
685
+ why: String(row.why ?? ''),
686
+ answer: row.state == 'applied' && row.answer == null ? outcome(db, Number(row.seq)) : String(row.answer ?? '[]'),
687
+ audit: row.audit == 1
688
+ } : null;
689
+ };
690
+ /** Cached acceptance after the caller has checked current write authority.
691
+ * Durable requests must have been fingerprinted from their body at the door. */ export let remembered = (db, key, request)=>{
692
+ let was = first(db, key, request);
693
+ return was?.state == 'applied' ? new Response(was.answer, {
694
+ headers: {
695
+ 'content-type': 'application/json'
696
+ }
697
+ }) : null;
698
+ };
699
+ // Split on Unicode boundaries so every SQLite text value fits the host's
700
+ // row limit and joining the values reproduces the answer byte for byte.
701
+ let pieces = function*(text) {
702
+ for(let i = 0; i < text.length;){
703
+ let end = Math.min(i + 300_000, text.length);
704
+ let last = text.charCodeAt(end - 1);
705
+ if (end < text.length && last >= 0xD800 && last <= 0xDBFF) end--;
706
+ yield text.slice(i, end);
707
+ i = end;
708
+ }
709
+ };
710
+ export let received = (db, receipt, answer, now = Date.now)=>{
711
+ let key = receipt.request.headers.get(IDEMPOTENCY);
712
+ if (!key) return;
713
+ expire(db, now);
714
+ let text = stringify(composed(answer()));
715
+ let whole = fits(text);
716
+ // Its sequence number is asked back only for an answer kept in parts: a
717
+ // returned row is a row read.
718
+ let [row] = db.query({
719
+ t: 'insert',
720
+ into: LOG,
721
+ cols: [
722
+ 'at',
723
+ 'headers',
724
+ 'body',
725
+ KEY,
726
+ 'generation',
727
+ 'state',
728
+ 'answer',
729
+ 'status'
730
+ ],
731
+ rows: [
732
+ [
733
+ val(stamp(now)),
734
+ val(JSON.stringify([
735
+ ...receipt.request.headers
736
+ ])),
737
+ lit(''),
738
+ val(key),
739
+ lit(1),
740
+ lit('applied'),
741
+ val(whole ? text : null),
742
+ lit(200)
743
+ ]
744
+ ],
745
+ returning: whole ? undefined : [
746
+ col('seq')
747
+ ]
748
+ });
749
+ if (!whole) chunks(db, Number(row.seq), text);
750
+ };
751
+ let chunks = (db, seq, text)=>{
752
+ for (let [part, body] of [
753
+ ...pieces(text)
754
+ ].entries()){
755
+ db.query({
756
+ t: 'insert',
757
+ into: ANSWERS,
758
+ cols: [
759
+ 'seq',
760
+ 'part',
761
+ 'body'
762
+ ],
763
+ rows: [
764
+ [
765
+ val(seq),
766
+ val(part),
767
+ val(body)
768
+ ]
769
+ ]
770
+ });
771
+ }
772
+ };
773
+ /** Walk the persisted input and outcome of writes without replaying them. */ export let retainedWrites = (db, after, limit)=>db.query(select({
774
+ cols: [
775
+ col('seq'),
776
+ col('state'),
777
+ col('headers'),
778
+ col('body'),
779
+ col('answer')
780
+ ],
781
+ from: table(LOG),
782
+ where: gt(col('seq'), val(after)),
783
+ order: [
784
+ col('seq')
785
+ ],
786
+ limit: val(limit)
787
+ })).map((r)=>{
788
+ let seq = Number(r.seq);
789
+ let chunked = r.answer == null && r.state == 'applied';
790
+ return {
791
+ seq,
792
+ state: String(r.state),
793
+ body: String(r.body),
794
+ binary: binaryHeaders(new Headers(JSON.parse(String(r.headers)))),
795
+ answer: chunked ? outcome(db, seq) : r.answer == null ? null : String(r.answer),
796
+ chunked
797
+ };
798
+ });
799
+ /** Rewrite an unchanged receipt inside the caller's transaction. */ export let rewriteWrite = (db, was, body, answer)=>{
800
+ let written = db.query({
801
+ t: 'update',
802
+ table: LOG,
803
+ set: {
804
+ body: val(body),
805
+ answer: val(was.chunked ? null : answer)
806
+ },
807
+ where: and(at(was.seq), eq(col('state'), val(was.state)), eq(col('body'), val(was.body))),
808
+ returning: [
809
+ col('seq')
810
+ ]
811
+ }).length > 0;
812
+ if (written && was.chunked && answer != null && answer != was.answer) {
813
+ db.query({
814
+ t: 'delete',
815
+ from: ANSWERS,
816
+ where: at(was.seq)
817
+ });
818
+ chunks(db, was.seq, answer);
819
+ }
820
+ return written;
821
+ };
822
+ /** A committed write, in its batch's own transaction: out of the log, or,
823
+ * sent with a key, kept as `applied` with its answer for a resend to be told.
824
+ * The hook receives phase patches; compose them here to keep exactly what
825
+ * `apply()` returns after the transaction. An audited retry keeps its original
826
+ * body and full answer in chunks. Ordinary large answers use chunks too,
827
+ * so every resend receives the complete canonical answer. */ export let landed = (db, seq, answer, now = Date.now)=>{
828
+ let [row] = db.query(select({
829
+ cols: [
830
+ col(KEY),
831
+ col('audit')
832
+ ],
833
+ from: table(LOG),
834
+ where: at(seq)
835
+ }));
836
+ if (row?.[KEY] == null && row?.audit != 1) return done(db, seq);
837
+ let all = composed(answer());
838
+ let text = stringify(all);
839
+ if (row.audit == 1 || !fits(text)) chunks(db, seq, text);
840
+ db.query({
841
+ t: 'update',
842
+ table: LOG,
843
+ set: {
844
+ state: lit('applied'),
845
+ ...row.audit == 1 ? {} : {
846
+ at: val(stamp(now)),
847
+ body: lit('')
848
+ },
849
+ answer: val(row.audit == 1 || !fits(text) ? null : text),
850
+ status: lit(200)
851
+ },
852
+ where: at(seq)
853
+ });
854
+ };
855
+ /** The oldest write still waiting after `seq`. A replay walks the log forward
856
+ * from one to the next, so it tries no write twice. */ export let next = (db, seq = 0)=>{
857
+ if (idle.has(of(db))) return null;
858
+ let [row] = db.query(select({
859
+ cols: [
860
+ col('seq'),
861
+ col('headers'),
862
+ col('body')
863
+ ],
864
+ from: table(LOG),
865
+ where: and(PENDING, gt(col('seq'), val(seq))),
866
+ order: [
867
+ col('seq')
868
+ ],
869
+ limit: lit(1)
870
+ }));
871
+ if (!row && !seq) idle.add(of(db));
872
+ return row ? {
873
+ seq: Number(row.seq),
874
+ headers: String(row.headers),
875
+ body: String(row.body)
876
+ } : null;
877
+ };
878
+ /** Whether any write is waiting. */ export let waiting = (db)=>next(db) != null;
879
+ /** Whether a new incarnation must settle writes before serving a read. */ export let recovering = (db)=>db.query(select({
880
+ cols: [
881
+ lit(1)
882
+ ],
883
+ from: table(LOG),
884
+ where: or(PENDING, REVIVABLE),
885
+ limit: lit(1)
886
+ })).length > 0;
887
+ /** The write is answered: it leaves the log, unless it is kept as `applied`
888
+ * for a resend (`landed`). */ export let done = (db, seq)=>void db.query({
889
+ t: 'delete',
890
+ from: LOG,
891
+ where: and(at(seq), not(APPLIED))
892
+ });
893
+ /** A write that failed on a store that started: set aside with why, so the
894
+ * writes behind it go on. */ export let aside = (db, seq, why)=>void db.query({
895
+ t: 'update',
896
+ table: LOG,
897
+ set: {
898
+ state: lit('failed'),
899
+ why: val(why)
900
+ },
901
+ where: and(at(seq), or(PENDING, RUNNING))
902
+ });
903
+ /** Every write set aside, waiting again: a new incarnation may be new code. */ export let revived = (db)=>{
904
+ idle.delete(of(db));
905
+ db.query({
906
+ t: 'update',
907
+ table: LOG,
908
+ set: {
909
+ state: lit('pending')
910
+ },
911
+ where: REVIVABLE
912
+ });
913
+ };
914
+ /** A replay the store refused: kept, with why, and never replayed again. */ export let dead = (db, seq, why)=>void db.query({
915
+ t: 'update',
916
+ table: LOG,
917
+ set: {
918
+ state: lit('refused'),
919
+ why: val(why)
920
+ },
921
+ where: at(seq)
922
+ });
923
+ /** The request a kept write was, to send `at` its door again (a Store's
924
+ * `/apply` unless said): a binary one's envelope as it came, which its
925
+ * apply door decodes ({@link decoded}). */ export let replayed = (k, at = 'http://store/apply')=>{
926
+ let headers = new Headers(JSON.parse(k.headers));
927
+ return new Request(at, {
928
+ method: 'POST',
929
+ headers,
930
+ body: opened(headers, k.body)
931
+ });
932
+ };
933
+ /** A constraint the batch broke — a unique name already taken, a required
934
+ * column left empty — is the batch's own refusal, not the store failing, and
935
+ * SQLite says which in its message. Left a 500, such a write would wait in
936
+ * the log for code that can never apply it, and hold up every write behind
937
+ * it. */ export let constrained = (e)=>e instanceof Error && /constraint failed/i.test(e.message) ? new Refused(e.message) : e;
938
+ /** What an answer said, in its own words. */ export let said = async (r)=>{
939
+ let text = await r.text();
940
+ try {
941
+ return String(JSON.parse(text).message ?? text);
942
+ } catch {
943
+ return text;
944
+ }
945
+ };
946
+ /** Whether a write is still in the log, waiting or set aside. */ export let held = (db, seq)=>db.query(select({
947
+ cols: [
948
+ lit(1)
949
+ ],
950
+ from: table(LOG),
951
+ where: and(at(seq), or(PENDING, FAILED, RUNNING))
952
+ })).length > 0;
953
+ /** Every write still in the log, oldest first: waiting, under way or set
954
+ * aside, and how many times each was tried. What a host that keeps a
955
+ * person's own words shows them of those words (a Builder's kept lines).
956
+ * One read a state, each on its own index: a log also keeps receipts, and
957
+ * an outbox's for good.
958
+ *
959
+ * ```ts
960
+ * import { equal } from '@yaks/testing'
961
+ * import { open } from '@yaks/sqlite/db'
962
+ * import { aside, keep, raise, started, unanswered } from './log.ts'
963
+ * let db = open(':memory:')
964
+ * raise(db)
965
+ * let sent = new Request('http://builder/say', { method: 'POST' })
966
+ * let one = keep(db, sent, 'one'), two = keep(db, sent, 'two')
967
+ * started(db, one)
968
+ * aside(db, one, 'unreachable')
969
+ * equal(unanswered(db).map((k) => [k.seq, k.body, k.tries]), [[one, 'one', 1], [two, 'two', 0]])
970
+ * ```
971
+ */ export let unanswered = (db)=>[
972
+ PENDING,
973
+ RUNNING,
974
+ FAILED
975
+ ].flatMap((where)=>db.query(select({
976
+ cols: [
977
+ col('seq'),
978
+ col('headers'),
979
+ col('body'),
980
+ col('tries')
981
+ ],
982
+ from: table(LOG),
983
+ where
984
+ }))).map((r)=>({
985
+ seq: Number(r.seq),
986
+ headers: String(r.headers),
987
+ body: String(r.body),
988
+ tries: Number(r.tries)
989
+ })).sort((a, b)=>a.seq - b.seq);
990
+ /** A kept write, as the door that sent it hears it (meta.ts): not applied
991
+ * yet, and not lost. The failure that held it back was reported where it
992
+ * happened, so this is not a defect of its own (defects.ts `refused`). A
993
+ * store that kept it while stopped says how long until it lands
994
+ * (`retry.after`, in ms), which a door passes on as `retry-after`. */ export class Pending extends Error {
995
+ retry;
996
+ constructor(message, after = 0){
997
+ super(message);
998
+ this.name = 'Pending';
999
+ if (after > 0) this.retry = {
1000
+ after
1001
+ };
1002
+ }
1003
+ }
1004
+ /** What a caller is told when its write is kept but not yet applied. */ export let parked = (seq, why, review = false)=>Response.json({
1005
+ error: 'Pending',
1006
+ message: `${why} — the write is kept and ${review ? 'needs owner review before it can be retried' : 'will be applied when this app recovers'}; do not send it again`,
1007
+ pending: seq
1008
+ }, {
1009
+ status: 202
1010
+ });
1011
+ //# sourceMappingURL=log.js.map