@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/doors.ts ADDED
@@ -0,0 +1,570 @@
1
+ // The two HTTP endpoints, `/apply` and `/query`. Both are thin on purpose:
2
+ // read the request, hand the graph a query or an array of bundles, respond
3
+ // with JSON. Everything that decides anything — what a caller may write,
4
+ // whether a precondition still holds, who gets notified — lives in
5
+ // @yaks/graph or in the subscription registry, not here.
6
+ //
7
+ // `/apply` also accepts an import too big to hold in memory: NDJSON, one
8
+ // bundle per line, applied in chunks and responded to as it goes (`pour`). It
9
+ // is the same endpoint, the same `apply()` and the same refusals — what
10
+ // changes is that neither the request body nor the response body is ever
11
+ // whole in memory.
12
+
13
+ import type { Actor, ApplyOpts, Bundle, Graph, ReadOpts } from 'jsr:@yaks/graph@0.2.36'
14
+ import { aggregate, reduced } from '@yaks/graph/read'
15
+ import type { Driver } from 'jsr:@yaks/sql@0.2.36'
16
+ import { knownOptions, Refused } from '@yaks/graph/errors'
17
+ import { parse } from '@yaks/query'
18
+ import { during, parent, peek, scope } from '@yaks/trace'
19
+ import { type Authenticate, signed } from './actor.js'
20
+ import { bodyChunks, poured, readBody, WRITE_BYTES, writeSize } from './body.js'
21
+ import { fault, json, refusal, refuse, type Tags } from './refuse.js'
22
+ import { published } from './publish.js'
23
+ import {
24
+ binaryHeaders,
25
+ constrained,
26
+ decoded,
27
+ durable,
28
+ IDEMPOTENCY,
29
+ taken,
30
+ } from './log.js'
31
+ import { type Door, type Mark, received } from './receipts.js'
32
+ import { admit } from './requests.js'
33
+ import { decode, stringify } from '@yaks/vocab/wire'
34
+
35
+ /** The HTTP write options, checked before a body or stream can commit. */
36
+ export let writeOptions = (
37
+ request: Request,
38
+ extra: string[] = [],
39
+ ): { check: boolean } => {
40
+ let params = new URL(request.url).searchParams
41
+ knownOptions(Object.fromEntries(params), ['check', ...extra])
42
+ return { check: params.has('check') }
43
+ }
44
+
45
+ /** Context the application gives each incoming write before authentication
46
+ * signs it. Streaming imports call it once per chunk, including checks. */
47
+ export type WriteContext = (
48
+ request: Request,
49
+ bundles: Bundle[],
50
+ ) => Bundle[] | Promise<Bundle[]>
51
+
52
+ /**
53
+ * How many bundles go into one transaction when an import arrives one bundle
54
+ * per line. It is the width the D1 adapter's round-trip limit counts — 50
55
+ * bundles cost the same two round trips as one (packages/d1 `hops_test.ts`) —
56
+ * so a chunk is as wide as the network carries for free.
57
+ */
58
+ export let CHUNK = 50
59
+
60
+ export { poured }
61
+
62
+ let CHUNK_BYTES = 1024 * 1024
63
+
64
+ // The body's lines as they arrive, each with the 1-based number it was on.
65
+ // Nothing is held but the line being read and the tail of the last read, so a
66
+ // 10 MB import is never a 10 MB string and never one `JSON.parse`.
67
+ let lines = async function* (
68
+ request: Request,
69
+ ): AsyncGenerator<[number, string]> {
70
+ let decoder = new TextDecoder()
71
+ let held: string[] = []
72
+ let length = 0
73
+ let at = 0
74
+ let parts = function* (text: string): Generator<[number, string]> {
75
+ let from = 0
76
+ while (from < text.length) {
77
+ let end = text.indexOf('\n', from)
78
+ let part = text.slice(from, end < 0 ? undefined : end)
79
+ length += part.length
80
+ if (2 * length > WRITE_BYTES) {
81
+ throw Object.assign(writeSize(), { line: at + 1 })
82
+ }
83
+ if (part) held.push(part)
84
+ if (end < 0) break
85
+ let line: [number, string] = [++at, held.join('')]
86
+ held = []
87
+ length = 0
88
+ yield line
89
+ from = end + 1
90
+ }
91
+ }
92
+ for await (let bytes of bodyChunks(request)) {
93
+ for (let i = 0; i < bytes.length; i += 64 * 1024) {
94
+ yield* parts(decoder.decode(bytes.subarray(i, i + 64 * 1024), {
95
+ stream: true,
96
+ }))
97
+ }
98
+ }
99
+ yield* parts(decoder.decode())
100
+ if (length) yield [++at, held.join('')]
101
+ }
102
+
103
+ // Which bundle of a refused chunk caused the refusal. A chunk is one
104
+ // transaction, so the error names the whole chunk and not a line — and
105
+ // somebody staring at a 10 MB file needs the line number. So the refused
106
+ // chunk is re-applied with one bundle left out at a time (with `check`, which
107
+ // rolls back before it commits): the bundle whose absence lets the rest
108
+ // through is the offender. Nothing is re-applied until something has already
109
+ // gone wrong, and when no single bundle is responsible — two bad lines, or a
110
+ // chunk refused as a whole — the chunk's first line is reported.
111
+ let culprit = async (
112
+ graph: Graph,
113
+ chunk: Bundle[],
114
+ cause?: string,
115
+ ): Promise<number> => {
116
+ for (let i = 0; i < chunk.length; i++) {
117
+ let rest = chunk.filter((_, j) => j != i)
118
+ if (!rest.length) return i
119
+ try {
120
+ await graph.apply(rest, { check: true, ...(cause && { parent: cause }) })
121
+ return i
122
+ } catch {
123
+ // Still refused: that bundle was not what broke it.
124
+ }
125
+ }
126
+ return 0
127
+ }
128
+
129
+ // The lines of a chunk as the graph returned them, in the graph's order. A
130
+ // bundle whose entity was minted through an alias comes back under `$alias`;
131
+ // every other one comes back under its eid.
132
+ let asked = (held: Bundle[], applied: Bundle[]): Bundle[] => {
133
+ let keys = new Set(held.map((b) => b.entity.eid))
134
+ return applied.filter((b) => keys.has(b.$alias ?? b.entity.eid))
135
+ }
136
+
137
+ /**
138
+ * `POST /apply` with `content-type: application/x-ndjson` — one bundle per
139
+ * line, applied in chunks of up to {@link CHUNK} bundles and answered as
140
+ * each chunk commits. Large lines fill a chunk sooner. Blank lines are
141
+ * skipped, and a single line that exceeds the batch size is refused.
142
+ *
143
+ * The response is line for line: a bundle a plugin adds alongside the ones
144
+ * sent (an archetype descriptor, an entity deleted by a cascade) is the
145
+ * graph's own bookkeeping, not a line the importer wrote, and is left out.
146
+ *
147
+ * The status is 200 whatever happens, because the first bundles have already
148
+ * been written to the response before a later line can be refused. So a
149
+ * refusal is the last line of the body instead — what `apply()` threw, plus
150
+ * two numbers:
151
+ *
152
+ * ```json
153
+ * {"error":"Refused","message":"unknown property:
154
+ * book.colour","line":137,"committed":100}
155
+ * ```
156
+ *
157
+ * `line` is the 1-based line the offending bundle was on, and `committed` how
158
+ * many bundles were written before it. Nothing after that line is read.
159
+ * (Under `?check=1` every chunk is rolled back, so `committed` counts what
160
+ * would have been written.)
161
+ *
162
+ * **An alias resolves within its own chunk and nowhere else.** A bundle
163
+ * naming `$x` and the bundle minting it have to fall in the same run of
164
+ * {@link CHUNK} lines and the same byte window.
165
+ */
166
+ export let pour = (
167
+ graph: Graph,
168
+ request: Request,
169
+ who: Actor | null,
170
+ activity: object = graph,
171
+ context?: WriteContext,
172
+ opts?: ReadOpts,
173
+ params: string[] = [],
174
+ tags?: Tags,
175
+ ): Response => {
176
+ let body = request.body
177
+ if (!body) throw new Refused('/apply takes one bundle per line')
178
+ let { check } = writeOptions(request, params)
179
+ let cause: string | undefined
180
+ let out = new TransformStream<Uint8Array, Uint8Array>()
181
+ let writer = out.writable.getWriter()
182
+ let bytes = new TextEncoder()
183
+ // Awaited, so a slow reader slows the import down rather than piling the
184
+ // whole response up behind itself.
185
+ let disconnected = false
186
+ let say = async (v: unknown) => {
187
+ if (disconnected) return
188
+ let line = bytes.encode(`${stringify(v)}\n`)
189
+ try {
190
+ await writer.write(line)
191
+ } catch {
192
+ // This identity stream has no transform that can fail: only its reader
193
+ // can cancel it. Losing the reply must not abandon received writes.
194
+ disconnected = true
195
+ }
196
+ }
197
+
198
+ let run = async () => {
199
+ let held: Bundle[] = []
200
+ let at: number[] = []
201
+ let committed = 0
202
+ let size = 0
203
+ // The line number a refusal belongs to: the line being read, until a
204
+ // chunk is refused and one of its own lines is identified.
205
+ let blame = 0
206
+ let flush = async () => {
207
+ let batch = signed(context ? await context(request, held) : held, who)
208
+ let applied: Bundle[]
209
+ try {
210
+ applied = await graph.apply(batch, {
211
+ check,
212
+ ...(cause && { parent: cause }),
213
+ })
214
+ } catch (err) {
215
+ blame = at[await culprit(graph, batch, cause)]
216
+ throw err
217
+ }
218
+ let reply = opts
219
+ ? await graph.answer(published(graph.vocab, applied), {
220
+ ...opts,
221
+ patch: true,
222
+ })
223
+ : applied
224
+ for (let b of published(graph.vocab, asked(held, reply))) await say(b)
225
+ committed += held.length
226
+ held = []
227
+ at = []
228
+ size = 0
229
+ }
230
+ try {
231
+ for await (let [n, line] of lines(request)) {
232
+ if (!line.trim()) continue
233
+ if (held.length && size + 2 * line.length > CHUNK_BYTES) await flush()
234
+ blame = n
235
+ held.push(decode(graph.vocab, JSON.parse(line)) as Bundle)
236
+ at.push(n)
237
+ size += 2 * line.length
238
+ if (held.length == CHUNK || size >= CHUNK_BYTES) await flush()
239
+ }
240
+ if (held.length) await flush()
241
+ } catch (err) {
242
+ fault(err, `${request.method} ${new URL(request.url).pathname}`, tags)
243
+ let line = (err as { line?: number } | null)?.line ?? blame
244
+ await say({ ...refusal(err), line, committed })
245
+ }
246
+ }
247
+ let c = peek(activity)
248
+ let flowing = c
249
+ ? scope(undefined, () => {
250
+ let span = c.begin({
251
+ kind: 'request',
252
+ name: 'http stream apply',
253
+ package: '@yaks/api',
254
+ })
255
+ cause = span?.id
256
+ return during(span, run)
257
+ })
258
+ : run()
259
+ let finished = admit(
260
+ request,
261
+ flowing.catch(async (error) => {
262
+ await writer.abort(error).catch(() => {})
263
+ throw error
264
+ }).finally(async () => {
265
+ if (!disconnected) await writer.close().catch(() => {})
266
+ }),
267
+ )
268
+ // Standalone calls have no listener to observe completion.
269
+ void finished.catch(() => {})
270
+ return new Response(out.readable, {
271
+ headers: { 'content-type': 'application/x-ndjson' },
272
+ })
273
+ }
274
+
275
+ /** A request its host trusts, such as the platform's own bookkeeping: who it
276
+ * writes as, and the graph it writes through, which admits the server-owned
277
+ * properties and stands the caller's guards down. Only a trusted write may
278
+ * keep the last write's provenance (`?stamp=0`). */
279
+ export type Trusted = { graph: Graph; actor: Actor | null }
280
+
281
+ /** What an apply door is built of: the graph a caller writes and how they
282
+ * read it, and what its host decides around a commit, given as data. Each is
283
+ * read as a request needs it, so a host whose graph is built again with each
284
+ * incarnation lends one door for all of them. */
285
+ export type Applying = {
286
+ /** the graph a caller writes */
287
+ graph: Graph
288
+ /** Runtime activity stays keyed by the composed graph, not a read overlay. */
289
+ activity?: object
290
+ /** who is writing (default: nobody) */
291
+ authenticate?: Authenticate
292
+ /** The caller's view of the graph, which a write's answer is read in. A
293
+ * `person` here outranks the one `authenticate` names. */
294
+ read?: (
295
+ request: Request,
296
+ ) => ReadOpts | undefined | Promise<ReadOpts | undefined>
297
+ /** Caller write context, applied to JSON batches and every import chunk. */
298
+ write?: WriteContext
299
+ /** Additional apply query parameters interpreted by this host. */
300
+ writeParams?: string[]
301
+ /** Which requests the host trusts, and how ({@link Trusted}); `undefined`
302
+ * for every other, which `authenticate` signs. */
303
+ trust?: (request: Request) => Trusted | undefined
304
+ /** Today's authority to write, which throws for a caller who may not: asked
305
+ * of a durable outbox write before a kept answer is told without the graph
306
+ * deciding again (default: `authenticate`). A trusted request holds it. */
307
+ authorize?: (request: Request) => unknown
308
+ /** The host's door over its write log (./receipts.ts `door`), which keeps
309
+ * its receipts with the input it could not commit yet. */
310
+ log?: Pick<Door, 'bound' | 'applying'>
311
+ /** The host's write log, for a door with no door over it: SQL on the
312
+ * graph's own connection, where a keyed write's receipt is inserted in the
313
+ * transaction that commits it (./receipts.ts `received`). Composed graphs
314
+ * register their log through the API graph facet, so their doors omit this. */
315
+ db?: Driver
316
+ /** The identity that owns a keyed write in this door's log. Defaults to
317
+ * the authenticated writer. A door can keep receipts across changes in
318
+ * the instrument that signs those writes. */
319
+ receiptActor?: Actor
320
+ /** What the host adds to each failure this door reports (./refuse.ts
321
+ * `Tags`, `faults`), such as which of its stores it is: read as one is. */
322
+ tags?: () => Tags
323
+ }
324
+
325
+ /** A host's apply door ({@link applier}). */
326
+ export type Applier = {
327
+ /** `POST /apply`: a batch in, as applied out, in the caller's view, or as
328
+ * the log keeps it when `mark` names the write to the log. It never throws:
329
+ * a refusal is answered at its status, and a constraint the batch broke is
330
+ * its refusal. */
331
+ apply: (request: Request, mark?: Mark) => Promise<Response>
332
+ /** Today's authority to write ({@link Applying} `authorize`). */
333
+ authorize: (request: Request) => Promise<void>
334
+ /** A canonical answer as its caller sees it: a kept write's, told again. */
335
+ answer: (request: Request, response: Response) => Promise<Response>
336
+ }
337
+
338
+ /**
339
+ * `POST /apply` — a JSON array of bundles in, that array as applied out. The
340
+ * response body is the array `apply()` returned, including server-written
341
+ * stamps and any entity a cascading delete took with it.
342
+ *
343
+ * `?check=1` asks only whether the array would be accepted: every phase runs
344
+ * and the transaction is rolled back, so nothing is written and no effect
345
+ * observes it, while a refusal is still a refusal. That is what lets one batch be spread over several graphs — ask them all, then commit.
346
+ *
347
+ * A binary envelope is decoded in the graph's words, whether it came as sent
348
+ * or as a write log keeps it (./log.ts `taken`). `content-type:
349
+ * application/x-ndjson` is the same endpoint for an import too big to hold in
350
+ * memory — see {@link pour}.
351
+ *
352
+ * ```ts
353
+ * import { equal } from '@yaks/testing'
354
+ * import { graph } from '@yaks/graph'
355
+ * import { ram } from '@yaks/ram'
356
+ * import { loadVocab } from '@yaks/vocab'
357
+ * import { applier } from './doors.ts'
358
+ * let vocab = loadVocab({ $defs: { doc: { component: true, type: 'object',
359
+ * properties: { title: { type: 'string' } } } } })
360
+ * let g = graph({ vocab, storage: ram(vocab) })
361
+ * let door = applier({ graph: g })
362
+ * let sent = (body: unknown) => new Request('http://g/apply', {
363
+ * method: 'POST', body: JSON.stringify(body),
364
+ * })
365
+ * let r = await door.apply(sent([{ entity: { eid: 'a' }, doc: { title: 'A' } }]))
366
+ * equal(r.status, 200)
367
+ * equal((await door.apply(sent({}))).status, 400)
368
+ * ```
369
+ */
370
+ export let applier = (o: Applying): Applier => {
371
+ let authenticate: Authenticate = (request) =>
372
+ o.authenticate ? o.authenticate(request) : null
373
+ let view = async (request: Request, who?: Actor | null) => ({
374
+ person: who?.by ?? null,
375
+ ...await o.read?.(request),
376
+ })
377
+ let seen = async (request: Request, rows: Bundle[], who?: Actor | null) => {
378
+ let { graph } = o
379
+ return published(
380
+ graph.vocab,
381
+ await graph.answer(published(graph.vocab, rows), {
382
+ ...await view(request, who),
383
+ patch: true,
384
+ }),
385
+ )
386
+ }
387
+
388
+ let apply = async (sent: Request, mark: Mark = null): Promise<Response> => {
389
+ let request = sent
390
+ try {
391
+ let { graph } = o
392
+ let activity = o.activity ?? graph
393
+ let params = [...(o.writeParams ?? []), ...(o.trust ? ['stamp'] : [])]
394
+ let { check } = writeOptions(request, params)
395
+ let trusted = o.trust?.(request)
396
+ let writer = trusted?.graph ?? graph
397
+ let key = request.headers.get(IDEMPOTENCY)
398
+ let cause = peek(activity) ? parent(activity, request) : undefined
399
+ if (poured(request)) {
400
+ if (durable(key)) {
401
+ throw new Refused('Durable outbox keys require a JSON apply')
402
+ }
403
+ let who = trusted ? trusted.actor : await authenticate(request)
404
+ return pour(
405
+ writer,
406
+ request,
407
+ who,
408
+ activity,
409
+ o.write,
410
+ await view(request, who),
411
+ params,
412
+ o.tags?.(),
413
+ )
414
+ }
415
+ let { body: text } = await taken(request)
416
+ let body = decoded(graph.vocab, request.headers, text)
417
+ if (!Array.isArray(body)) {
418
+ throw new Refused('/apply takes a JSON array of bundles')
419
+ }
420
+ let who = trusted ? trusted.actor : await authenticate(request)
421
+ if (o.log) {
422
+ let bound = await o.log.bound(request, text, check)
423
+ if (bound instanceof Response) return bound
424
+ request = bound
425
+ }
426
+ let batch = signed(o.write ? await o.write(request, body) : body, who)
427
+ let options: ApplyOpts = {
428
+ check,
429
+ ...(trusted && new URL(request.url).searchParams.get('stamp') == '0'
430
+ ? { stamp: false }
431
+ : {}),
432
+ ...(cause && { parent: cause }),
433
+ }
434
+ let applied: Bundle[]
435
+ if (o.log) {
436
+ let out = o.log.applying(
437
+ request,
438
+ mark,
439
+ () => writer.apply(batch, options),
440
+ )
441
+ if (out instanceof Response) return out
442
+ applied = await out
443
+ } else if (key && !check) {
444
+ // A receipt is of the batch as decoded: a binary one's envelope is
445
+ // not what it says.
446
+ let said = binaryHeaders(request.headers) ? stringify(body) : text
447
+ applied = await received(
448
+ writer,
449
+ o.db,
450
+ key,
451
+ said,
452
+ o.receiptActor ?? who,
453
+ batch,
454
+ options,
455
+ )
456
+ } else applied = await writer.apply(batch, options)
457
+ // The log keeps canonical patches; each caller, a resend included, is
458
+ // told its own view.
459
+ return json(
460
+ mark == null
461
+ ? await seen(request, applied, who)
462
+ : published(graph.vocab, applied),
463
+ )
464
+ } catch (e) {
465
+ return refuse(constrained(e), sent, o.tags?.())
466
+ }
467
+ }
468
+
469
+ return {
470
+ apply,
471
+ async authorize(request) {
472
+ if (o.trust?.(request)) return
473
+ await (o.authorize ?? authenticate)(request)
474
+ },
475
+ async answer(request, response) {
476
+ if (
477
+ response.status != 200 ||
478
+ response.headers.get('content-type')?.includes('ndjson')
479
+ ) return response
480
+ let rows = decode(o.graph.vocab, await response.json()) as Bundle[]
481
+ return new Response(stringify(await seen(request, rows)), response)
482
+ },
483
+ }
484
+ }
485
+
486
+ // The query string a request carries: `?q=` on a GET, and on a POST either a
487
+ // bare JSON string or `{ q }`.
488
+ let lineOf = (body: unknown): string | null => {
489
+ if (typeof body == 'string') return body
490
+ if (body && typeof body == 'object' && 'q' in body) {
491
+ return typeof body.q == 'string' ? body.q : null
492
+ }
493
+ return null
494
+ }
495
+
496
+ /** Shape a query's published bundles before writing them to the wire. */
497
+ export type ListQuery = (
498
+ rows: Bundle[],
499
+ request: Request,
500
+ ) => Bundle[] | Promise<Bundle[]>
501
+
502
+ /**
503
+ * `GET /query?q=…` or `POST /query` — a query string in, the bundles it
504
+ * selects out.
505
+ *
506
+ * Unless the query asks for a reduction. `.count`, `.distinct=prop` and
507
+ * `.tally=prop` are questions about the selection rather than about its
508
+ * members, and the store answers each with one SQL statement (`rows()` rather
509
+ * than `read()`); the response body is then `{"count":n}`, `{"distinct":[…]}`
510
+ * or `{"tally":{…}}`.
511
+ */
512
+ export let ask = async (
513
+ graph: Graph,
514
+ request: Request,
515
+ activity: object = graph,
516
+ opts?: ReadOpts,
517
+ list?: ListQuery,
518
+ ): Promise<Response> => {
519
+ let q = request.method == 'GET'
520
+ ? new URL(request.url).searchParams.get('q')
521
+ : lineOf(JSON.parse(await readBody(request)))
522
+ if (q == null) throw new Refused('/query needs a query: ?q=… or a body {q}')
523
+ // Parsed once, here: both `rows()` and `read()` accept the parsed query, so
524
+ // the string is parsed to decide which of them answers, and not parsed
525
+ // again to answer.
526
+ let ast = parse(q)
527
+ let cause = peek(activity) ? parent(activity, request) : undefined
528
+ let options = {
529
+ ...opts,
530
+ signal: request.signal,
531
+ ...(cause && { parent: cause }),
532
+ }
533
+ let op = aggregate(ast)
534
+ try {
535
+ if (op) return json(reduced(op, await graph.rows(ast, options)))
536
+ let rows = published(graph.vocab, await graph.read(ast, options))
537
+ return listed(list ? await list(rows, request) : rows)
538
+ } catch (error) {
539
+ if (request.signal.aborted && error === request.signal.reason) {
540
+ throw new Refused('query was interrupted')
541
+ }
542
+ throw error
543
+ }
544
+ }
545
+
546
+ // How much of a listed answer is said per piece of the stream.
547
+ let PIECE = 64 * 1024
548
+
549
+ // A list as its JSON response, said one entity at a time: the bytes
550
+ // `JSON.stringify` would write, never built as one string, so a selection of
551
+ // any size is sent rather than failing to fit in one. The stream pulls, so a
552
+ // slow reader slows the saying.
553
+ let listed = (items: unknown[]): Response => {
554
+ let bytes = new TextEncoder()
555
+ let next = 0
556
+ return new Response(
557
+ new ReadableStream<Uint8Array>({
558
+ start: (c) => c.enqueue(bytes.encode('[')),
559
+ pull: (c) => {
560
+ let piece = ''
561
+ while (next < items.length && piece.length < PIECE) {
562
+ piece += (next ? ',' : '') + stringify(items[next++])
563
+ }
564
+ c.enqueue(bytes.encode(next < items.length ? piece : piece + ']'))
565
+ if (next == items.length) c.close()
566
+ },
567
+ }),
568
+ { headers: { 'content-type': 'application/json' } },
569
+ )
570
+ }
package/graph.js ADDED
@@ -0,0 +1,12 @@
1
+ // The box loads these hooks before opening its doors: its keyed writes'
2
+ // receipts, kept in its write log on the store's own connection.
3
+ import { asking } from "./actor.js";
4
+ import { receipts } from "./receipts.js";
5
+ /** A keyed write's receipt, inserted in the transaction that commits it, on
6
+ * a host with SQL; a host with none refuses a keyed write at the door. */ export let plugins = (host)=>host.storage.statements ? [
7
+ receipts(host.storage.statements)
8
+ ] : [];
9
+ /** A host whose options name `who`, another graph's base URL, asks that
10
+ * graph's door who a request is from (./actor.ts `asking`); one naming none
11
+ * leaves the question to another plugin. */ export let authenticate = (_host, options)=>options.who ? asking(options.who) : undefined;
12
+ //# sourceMappingURL=graph.js.map
package/graph.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.js","sources":["./graph.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,iEAAiE;AAGjE,SAAS,MAAM,qBAAuC;AACtD,SAAS,QAAQ,wBAAuB;AAMxC;wEACwE,GACxE,OAAO,IAAI,UAAU,CAAC,OACpB,KAAK,OAAO,CAAC,UAAU,GAAG;IAAC,SAAS,KAAK,OAAO,CAAC,UAAU;GAAE,GAAG,EAAE,CAAA;AAEpE;;0CAE0C,GAC1C,OAAO,IAAI,eAAe,CACxB,OACA,UAC6B,QAAQ,GAAG,GAAG,OAAO,QAAQ,GAAG,IAAI,UAAS"}
package/graph.ts ADDED
@@ -0,0 +1,23 @@
1
+ // The box loads these hooks before opening its doors: its keyed writes'
2
+ // receipts, kept in its write log on the store's own connection.
3
+ import type { Plugin } from 'jsr:@yaks/graph@0.2.36'
4
+ import type { Driver } from 'jsr:@yaks/sql@0.2.36'
5
+ import { asking, type Authenticate } from './actor.js'
6
+ import { receipts } from './receipts.js'
7
+
8
+ /** What this facet reads off its host: the statements of the store's own
9
+ * connection, where it has SQL, which its write log is kept over. */
10
+ export type Hosting = { storage: { statements?: Driver } }
11
+
12
+ /** A keyed write's receipt, inserted in the transaction that commits it, on
13
+ * a host with SQL; a host with none refuses a keyed write at the door. */
14
+ export let plugins = (host: Hosting): Plugin[] =>
15
+ host.storage.statements ? [receipts(host.storage.statements)] : []
16
+
17
+ /** A host whose options name `who`, another graph's base URL, asks that
18
+ * graph's door who a request is from (./actor.ts `asking`); one naming none
19
+ * leaves the question to another plugin. */
20
+ export let authenticate = (
21
+ _host: unknown,
22
+ options: { who?: string },
23
+ ): Authenticate | undefined => options.who ? asking(options.who) : undefined
package/headers.js ADDED
@@ -0,0 +1,5 @@
1
+ /** The header a caller names one write by, across its sends. */ export let IDEMPOTENCY = 'idempotency-key';
2
+ /** Prefix for a durable write owned by the page's person across web processes.
3
+ * Older keys keep their original receipt namespace. */ export let PERSON_OUTBOX = 'outbox:person:';
4
+ /** The header a door adds to a failure already reported at its source. */ export let FILED = 'x-yak-filed';
5
+ //# sourceMappingURL=headers.js.map
package/headers.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"headers.js","sources":["./headers.ts"],"names":[],"mappings":"AAAA,8DAA8D,GAC9D,OAAO,IAAI,cAAsB,kBAAiB;AAElD;qDACqD,GACrD,OAAO,IAAI,gBAAgB,iBAAgB;AAE3C,wEAAwE,GACxE,OAAO,IAAI,QAAgB,cAAa"}
package/headers.ts ADDED
@@ -0,0 +1,9 @@
1
+ /** The header a caller names one write by, across its sends. */
2
+ export let IDEMPOTENCY: string = 'idempotency-key'
3
+
4
+ /** Prefix for a durable write owned by the page's person across web processes.
5
+ * Older keys keep their original receipt namespace. */
6
+ export let PERSON_OUTBOX = 'outbox:person:'
7
+
8
+ /** The header a door adds to a failure already reported at its source. */
9
+ export let FILED: string = 'x-yak-filed'