@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.
- package/LICENSE +202 -0
- package/README.md +956 -2
- package/_dist/actor.d.ts +59 -0
- package/_dist/actor.d.ts.map +1 -0
- package/_dist/address.d.ts +33 -0
- package/_dist/address.d.ts.map +1 -0
- package/_dist/asset.d.ts +15 -0
- package/_dist/asset.d.ts.map +1 -0
- package/_dist/batches.d.ts +4 -0
- package/_dist/batches.d.ts.map +1 -0
- package/_dist/body.d.ts +7 -0
- package/_dist/body.d.ts.map +1 -0
- package/_dist/deno.d.ts +38 -0
- package/_dist/deno.d.ts.map +1 -0
- package/_dist/doors.d.ts +134 -0
- package/_dist/doors.d.ts.map +1 -0
- package/_dist/graph.d.ts +17 -0
- package/_dist/graph.d.ts.map +1 -0
- package/_dist/headers.d.ts +5 -0
- package/_dist/headers.d.ts.map +1 -0
- package/_dist/log.d.ts +253 -0
- package/_dist/log.d.ts.map +1 -0
- package/_dist/mod.d.ts +71 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/publish.d.ts +7 -0
- package/_dist/publish.d.ts.map +1 -0
- package/_dist/reached.d.ts +145 -0
- package/_dist/reached.d.ts.map +1 -0
- package/_dist/receipts.d.ts +153 -0
- package/_dist/receipts.d.ts.map +1 -0
- package/_dist/refuse.d.ts +51 -0
- package/_dist/refuse.d.ts.map +1 -0
- package/_dist/relay.d.ts +3 -0
- package/_dist/relay.d.ts.map +1 -0
- package/_dist/request.d.ts +79 -0
- package/_dist/request.d.ts.map +1 -0
- package/_dist/requests.d.ts +7 -0
- package/_dist/requests.d.ts.map +1 -0
- package/_dist/route.d.ts +71 -0
- package/_dist/route.d.ts.map +1 -0
- package/_dist/routed.d.ts +33 -0
- package/_dist/routed.d.ts.map +1 -0
- package/_dist/routes.d.ts +46 -0
- package/_dist/routes.d.ts.map +1 -0
- package/_dist/save.d.ts +6 -0
- package/_dist/save.d.ts.map +1 -0
- package/_dist/socket.d.ts +73 -0
- package/_dist/socket.d.ts.map +1 -0
- package/_dist/subs.d.ts +134 -0
- package/_dist/subs.d.ts.map +1 -0
- package/_dist/timing.d.ts +8 -0
- package/_dist/timing.d.ts.map +1 -0
- package/_dist/tools.d.ts +80 -0
- package/_dist/tools.d.ts.map +1 -0
- package/_dist/vocab.d.ts +6 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/access.js +32 -0
- package/access.js.map +1 -0
- package/access.ts +42 -0
- package/actor.js +75 -0
- package/actor.js.map +1 -0
- package/actor.ts +106 -0
- package/address.js +42 -0
- package/address.js.map +1 -0
- package/address.ts +49 -0
- package/admission.js +71 -0
- package/admission.js.map +1 -0
- package/admission.ts +64 -0
- package/asset.js +37 -0
- package/asset.js.map +1 -0
- package/asset.ts +47 -0
- package/batches.js +92 -0
- package/batches.js.map +1 -0
- package/batches.ts +96 -0
- package/body.js +51 -0
- package/body.js.map +1 -0
- package/body.ts +82 -0
- package/deno.js +88 -0
- package/deno.js.map +1 -0
- package/deno.json +1 -0
- package/deno.ts +150 -0
- package/doors.js +435 -0
- package/doors.js.map +1 -0
- package/doors.ts +570 -0
- package/graph.js +12 -0
- package/graph.js.map +1 -0
- package/graph.ts +23 -0
- package/headers.js +5 -0
- package/headers.js.map +1 -0
- package/headers.ts +9 -0
- package/interest.js +224 -0
- package/interest.js.map +1 -0
- package/interest.ts +264 -0
- package/log.js +1011 -0
- package/log.js.map +1 -0
- package/log.ts +1035 -0
- package/mod.js +69 -0
- package/mod.js.map +1 -0
- package/mod.ts +142 -0
- package/package.json +75 -4
- package/peer_query.js +164 -0
- package/peer_query.js.map +1 -0
- package/peer_query.ts +158 -0
- package/publish.js +7 -0
- package/publish.js.map +1 -0
- package/publish.ts +16 -0
- package/reached.js +456 -0
- package/reached.js.map +1 -0
- package/reached.ts +549 -0
- package/receipts.js +543 -0
- package/receipts.js.map +1 -0
- package/receipts.ts +749 -0
- package/refuse.js +120 -0
- package/refuse.js.map +1 -0
- package/refuse.ts +179 -0
- package/relay.js +249 -0
- package/relay.js.map +1 -0
- package/relay.ts +284 -0
- package/request.js +218 -0
- package/request.js.map +1 -0
- package/request.ts +235 -0
- package/requests.js +250 -0
- package/requests.js.map +1 -0
- package/requests.ts +257 -0
- package/route.js +139 -0
- package/route.js.map +1 -0
- package/route.ts +228 -0
- package/routed.js +25 -0
- package/routed.js.map +1 -0
- package/routed.ts +53 -0
- package/routes.js +154 -0
- package/routes.js.map +1 -0
- package/routes.ts +201 -0
- package/save.js +341 -0
- package/save.js.map +1 -0
- package/save.ts +393 -0
- package/socket.js +398 -0
- package/socket.js.map +1 -0
- package/socket.ts +496 -0
- package/subs.js +2295 -0
- package/subs.js.map +1 -0
- package/subs.ts +2979 -0
- package/timing.js +17 -0
- package/timing.js.map +1 -0
- package/timing.ts +26 -0
- package/tools.js +251 -0
- package/tools.js.map +1 -0
- package/tools.ts +315 -0
- package/vocab.js +18 -0
- package/vocab.js.map +1 -0
- package/vocab.json +93 -0
- package/vocab.ts +18 -0
package/README.md
CHANGED
|
@@ -1,3 +1,957 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @yaks/api
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Serves graph writes, queries, and live query subscriptions through an HTTP and
|
|
4
|
+
WebSocket request handler. Your application supplies the
|
|
5
|
+
[graph](../graph/README.md#data-model), authentication policy, and server
|
|
6
|
+
runtime.
|
|
7
|
+
|
|
8
|
+
A **handler** takes a `Request` and returns a `Response`, synchronously or
|
|
9
|
+
asynchronously (`Handler`). A **route** gives a handler an HTTP method and path
|
|
10
|
+
(`Route`): `{ method: 'GET', path: '/health', handle }`. A **filter** checks
|
|
11
|
+
each request before a route answers it, refusing the request by throwing
|
|
12
|
+
(`Filter`).
|
|
13
|
+
|
|
14
|
+
A **subscription** holds a [query](../query/README.md#query-model) and pushes
|
|
15
|
+
its answer to one client when a committed [batch](../graph/README.md#data-model)
|
|
16
|
+
affects it. A **frame** is one subscription message (`Frame`), such as
|
|
17
|
+
`{ id: 'books', bundles: [...] }`. A **sink** receives frames (`Sink`). The
|
|
18
|
+
**subscription registry** keeps subscriptions for sinks (`Subs`). It lives in
|
|
19
|
+
memory; keep it, or its handler, between requests.
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
deno add jsr:@yaks/api
|
|
25
|
+
# or: npx jsr add @yaks/api
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Use
|
|
29
|
+
|
|
30
|
+
The handler can be called directly, without binding a port:
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { api } from '@yaks/api'
|
|
34
|
+
import { graph } from '@yaks/graph'
|
|
35
|
+
import { ram } from '@yaks/ram'
|
|
36
|
+
import { loadVocab } from '@yaks/vocab'
|
|
37
|
+
import { equal } from '@yaks/testing'
|
|
38
|
+
|
|
39
|
+
const vocab = loadVocab({
|
|
40
|
+
$defs: {
|
|
41
|
+
book: {
|
|
42
|
+
component: true,
|
|
43
|
+
type: 'object',
|
|
44
|
+
properties: {
|
|
45
|
+
title: { type: 'string' },
|
|
46
|
+
price: { type: 'number' },
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
})
|
|
51
|
+
const g = graph({ vocab, storage: ram(vocab) })
|
|
52
|
+
const handle = api({ graph: g })
|
|
53
|
+
const bundles = [{ entity: { eid: 'b1' }, book: { title: 'Dune', price: 12 } }]
|
|
54
|
+
const written = await handle(
|
|
55
|
+
new Request('https://shop.test/apply', {
|
|
56
|
+
method: 'POST',
|
|
57
|
+
body: JSON.stringify(bundles),
|
|
58
|
+
}),
|
|
59
|
+
)
|
|
60
|
+
equal(written.status, 200)
|
|
61
|
+
equal(await written.json(), bundles)
|
|
62
|
+
const answer = await handle(new Request('https://shop.test/query?q=.book'))
|
|
63
|
+
equal(await answer.json(), bundles)
|
|
64
|
+
const declarations = await handle(new Request('https://shop.test/vocab'))
|
|
65
|
+
equal((await declarations.json()).docs, vocab.docs)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
| Endpoint | Request | Response |
|
|
69
|
+
| ---------------- | ----------------------------------------------------------------- | ------------------------------------ |
|
|
70
|
+
| `POST /apply` | JSON array of [bundles](../graph/README.md#data-model), or NDJSON | Applied bundles |
|
|
71
|
+
| `GET /query?q=…` | URL-encoded query | Bundles or an aggregate value |
|
|
72
|
+
| `POST /query` | JSON string or `{"q":"…"}` | Same as GET |
|
|
73
|
+
| `/ws` | WebSocket upgrade | Subscription frames |
|
|
74
|
+
| `GET /vocab` | GET | `{ docs, keywords }` for `loadVocab` |
|
|
75
|
+
| `GET /who` | GET | The actor, and what `standing` says |
|
|
76
|
+
|
|
77
|
+
`/apply` returns [patches](../graph/README.md#data-model) and graph-generated
|
|
78
|
+
changes, rather than every stored component. `?check=1` runs the write pipeline
|
|
79
|
+
and rolls the transaction back; effects do not run. It reserves nothing and
|
|
80
|
+
provides no transaction across graphs. A subsequent write can still fail.
|
|
81
|
+
|
|
82
|
+
`GET /query?live=1&q=…` uses the subscription registry's `snapshot`: stored
|
|
83
|
+
bundles with current relayed values. Ordinary `/query` reads stored data,
|
|
84
|
+
including saved relayed values. A saved value does not count as a connected
|
|
85
|
+
writer's presence after that writer disconnects.
|
|
86
|
+
|
|
87
|
+
### Keyed JSON writes
|
|
88
|
+
|
|
89
|
+
A **receipt** is the canonical applied answer kept atomically with a successful
|
|
90
|
+
JSON `POST /apply` carrying `Idempotency-Key`. Resend the same key and exact
|
|
91
|
+
body after a lost answer: aliases and `$was` are accepted once, and a replay
|
|
92
|
+
returns the original answer without another mutation. A key is its writer's:
|
|
93
|
+
every door keeps a receipt under the writer (`by` and `via`) and key as one name
|
|
94
|
+
(`@yaks/api/log` `receiptKey`), so two writers' same key are two writes. Reusing
|
|
95
|
+
an `outbox:` key with a different body is refused.
|
|
96
|
+
|
|
97
|
+
```sh
|
|
98
|
+
curl -X POST http://localhost:3000/apply \
|
|
99
|
+
-H 'Idempotency-Key: outbox:my-unique-write' \
|
|
100
|
+
-H 'Content-Type: application/json' \
|
|
101
|
+
-d '[{"entity":{"eid":"$note"},"doc":{"title":"Remember"}}]'
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
A receipt under an `outbox:` key, as `@yaks/sync` and `@yaks/client` send, has
|
|
105
|
+
no expiry: durable outboxes may replay after any offline interval. One under any
|
|
106
|
+
other key is kept for ten minutes, the resend window of a server retrying a call
|
|
107
|
+
(`@yaks/durable-object`). Only a SHA-256 digest binds the request body; the body
|
|
108
|
+
itself is not retained. The canonical answer is retained before caller answer
|
|
109
|
+
projection and projected again when replayed.
|
|
110
|
+
|
|
111
|
+
Receipts are kept in the host's write log (`@yaks/api/log`): plain SQLite tables
|
|
112
|
+
beside the graph, never graph rows, inserted in the transaction that commits the
|
|
113
|
+
write. So the log must be the graph's own connection, handed to the door as
|
|
114
|
+
`db`:
|
|
115
|
+
|
|
116
|
+
```ts ignore
|
|
117
|
+
let db = open('graph.db')
|
|
118
|
+
let graph = graph({ vocab, storage: storage(db, vocab) })
|
|
119
|
+
Deno.serve(api({ graph, db }))
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
A composed host hands its store's connection to `@yaks/api/graph` and
|
|
123
|
+
`@yaks/api/routes` itself. This includes custom servers used with `@yaks/sync`
|
|
124
|
+
or `@yaks/client`, whose ordinary writes carry idempotency keys. A keyed write
|
|
125
|
+
to a door with no `db` is refused, not retried as an unkeyed write. Dry runs
|
|
126
|
+
(`?check`) do not consume keys. Keyed NDJSON imports are refused because they
|
|
127
|
+
span transactions; unkeyed requests keep their ordinary behavior.
|
|
128
|
+
|
|
129
|
+
A host decides what surrounds a commit and gives it to the apply door as data
|
|
130
|
+
(`Applying`, which `api` takes too, or `applier` alone): `trust`, the requests
|
|
131
|
+
it trusts and the graph they write through, which admits server-owned properties
|
|
132
|
+
and may keep the last write's provenance with `?stamp=0`; `authorize`, today's
|
|
133
|
+
authority to write, asked before a durable outbox write is told a kept answer;
|
|
134
|
+
and `log`, a write log (`@yaks/api/receipts` `door`) that keeps receipts in
|
|
135
|
+
SQLite beside the graph instead of in it. Binary envelopes are decoded in the
|
|
136
|
+
graph's words, sent or kept. A constraint the batch broke is its refusal, not a
|
|
137
|
+
server failure.
|
|
138
|
+
|
|
139
|
+
## Exports
|
|
140
|
+
|
|
141
|
+
| Import | Exports |
|
|
142
|
+
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
143
|
+
| `@yaks/api` | `api`, `Options`, `Handler`, `Route`, `routed`, `Filter`; `Authenticate`, `asking`, `signed`, `PeerWriter`; `ask`, `applier`, `Applier`, `Applying`, `Trusted`, `pour`, `poured`, `CHUNK`, `WriteContext`; `published`; `subscriptions`, `Subs`, `Listening`, `Ask`, `Frame`, `Sink`, `Opening`, `Timer`; `attach`, `clockReply`, `decode`, `Incoming`, `queue`, `receive`, `sink`, `Socket`, `Upgrade`; `denoUpgrade`, `denoListen`, `Listen`, `Listener`, `Addr`; `json`, `refusal`, `refuse`, `fault`, `faults`, `Reporter`, `Tags`, `FILED`, `Refusal`, `Unauthorized`; `served`, `requested`, `agent`, `Report`, `Watch`, `Answered`; `timed` |
|
|
144
|
+
| `@yaks/api/vocab` | `apiDoc`, `docs`, `description` |
|
|
145
|
+
| `@yaks/api/routes` | `handler`, `Hosting` |
|
|
146
|
+
| `@yaks/api/tools` | `runs`, `Serving`, `PORT`, `HOSTNAME` |
|
|
147
|
+
| `@yaks/api/reached` | `reached`, `Reached`, `beside`, `watched`: subscriptions over graphs a host asks but cannot watch, or watches another keeps |
|
|
148
|
+
| `@yaks/api/refuse` | `json`, `refusal`, `refuse`, `fault`, `faults`, `Reporter`, `Tags`, `FILED`, `Refusal`, `Unauthorized` |
|
|
149
|
+
| `@yaks/api/asset` | `text`, `bytes`: a file a package ships, read through the module loader |
|
|
150
|
+
|
|
151
|
+
## Query answers
|
|
152
|
+
|
|
153
|
+
A query with `.fields` returns narrowed bundles and separate bundles for
|
|
154
|
+
entities reached through references. Aggregate queries return a value instead of
|
|
155
|
+
bundles. Both GET and POST use the same query syntax and storage support.
|
|
156
|
+
|
|
157
|
+
```ts
|
|
158
|
+
import { api, type Frame, subscriptions } from '@yaks/api'
|
|
159
|
+
import { graph } from '@yaks/graph'
|
|
160
|
+
import { ram } from '@yaks/ram'
|
|
161
|
+
import { loadVocab } from '@yaks/vocab'
|
|
162
|
+
import { equal } from '@yaks/testing'
|
|
163
|
+
|
|
164
|
+
const vocab = loadVocab({
|
|
165
|
+
$defs: {
|
|
166
|
+
book: {
|
|
167
|
+
component: true,
|
|
168
|
+
type: 'object',
|
|
169
|
+
properties: {
|
|
170
|
+
title: { type: 'string' },
|
|
171
|
+
price: { type: 'number' },
|
|
172
|
+
},
|
|
173
|
+
},
|
|
174
|
+
},
|
|
175
|
+
})
|
|
176
|
+
const g = graph({ vocab, storage: ram(vocab) })
|
|
177
|
+
await g.apply([{ entity: { eid: 'b1' }, book: { title: 'Dune', price: 12 } }])
|
|
178
|
+
const handle = api({ graph: g })
|
|
179
|
+
const ask = async (q: string) =>
|
|
180
|
+
(await handle(
|
|
181
|
+
new Request('https://shop.test/query', {
|
|
182
|
+
method: 'POST',
|
|
183
|
+
body: JSON.stringify({ q }),
|
|
184
|
+
}),
|
|
185
|
+
)).json()
|
|
186
|
+
equal(await ask('.book&.count'), { count: 1 })
|
|
187
|
+
equal(await ask('.book&.distinct=book.price'), { distinct: ['12'] })
|
|
188
|
+
equal(await ask('.book&.tally=book.price'), { tally: { '12': 1 } })
|
|
189
|
+
equal(await ask('.book&.fields=book.title'), [{
|
|
190
|
+
entity: { eid: 'b1' },
|
|
191
|
+
book: { title: 'Dune' },
|
|
192
|
+
}])
|
|
193
|
+
const subs = subscriptions(g)
|
|
194
|
+
const frames: Frame[] = []
|
|
195
|
+
const to = (frame: Frame) => {
|
|
196
|
+
frames.push(frame)
|
|
197
|
+
}
|
|
198
|
+
await subs.open(to, 'titles', '.book&.fields=book.title')
|
|
199
|
+
equal(frames[0].coverage, { b1: { book: ['title'] } })
|
|
200
|
+
await subs.open(to, 'count', '.book&.count')
|
|
201
|
+
equal(frames[1].count, 1)
|
|
202
|
+
await subs.drop(to)
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
## Authentication and caller context
|
|
206
|
+
|
|
207
|
+
`authenticate(request)` runs on every request, including reads and WebSocket
|
|
208
|
+
upgrades. Its [actor](../graph/README.md#data-model) replaces client-supplied
|
|
209
|
+
`$actor` on every incoming bundle. Omitting it, or returning `null`, permits
|
|
210
|
+
unattributed requests. Throw `Unauthorized` to answer with HTTP 401.
|
|
211
|
+
Authentication does not decide which entities or properties a caller may access;
|
|
212
|
+
the graph and application supply that policy.
|
|
213
|
+
|
|
214
|
+
A graph that keeps no sessions of its own names its callers by asking the door
|
|
215
|
+
of one that does: `asking(url)` sends a request's `x-via` to that door's
|
|
216
|
+
`GET /who` and answers its actor. A host composes it as `@yaks/api` with
|
|
217
|
+
`{ "who": "<base URL>" }`, as the box's tracker asks the box.
|
|
218
|
+
|
|
219
|
+
`standing(request, actor)` is what `GET /who` says of a caller beside the actor
|
|
220
|
+
`authenticate` named: whether they may read and write, say, or where they sign
|
|
221
|
+
in. It is the host's to word, and its keys never replace `by` or `via`, so a
|
|
222
|
+
graph asking the door is told only who is calling. Without it, `/who` answers
|
|
223
|
+
the actor alone, `null` for nobody. `whoDoor({authenticate, standing})` is that
|
|
224
|
+
door by itself, for a host whose other doors are its own.
|
|
225
|
+
|
|
226
|
+
`write(request, bundles)` adds caller context before signing a JSON batch or
|
|
227
|
+
each NDJSON chunk, including checked writes. `read(request)` supplies graph
|
|
228
|
+
`ReadOpts` for queries, socket frames and applied write replies. Applied replies
|
|
229
|
+
use the graph's answer hooks with `patch: true`, so callers receive their own
|
|
230
|
+
vocabulary while storage keeps the graph's vocabulary.
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
import { api, signed, Unauthorized } from '@yaks/api'
|
|
234
|
+
import { graph } from '@yaks/graph'
|
|
235
|
+
import { ram } from '@yaks/ram'
|
|
236
|
+
import { loadVocab } from '@yaks/vocab'
|
|
237
|
+
import { equal } from '@yaks/testing'
|
|
238
|
+
|
|
239
|
+
const vocab = loadVocab({ $defs: {} })
|
|
240
|
+
const g = graph({ vocab, storage: ram(vocab) })
|
|
241
|
+
const handle = api({
|
|
242
|
+
graph: g,
|
|
243
|
+
authenticate: () => {
|
|
244
|
+
throw new Unauthorized('sign in')
|
|
245
|
+
},
|
|
246
|
+
})
|
|
247
|
+
const response = await handle(new Request('https://shop.test/vocab'))
|
|
248
|
+
equal(response.status, 401)
|
|
249
|
+
equal(await response.json(), { error: 'Unauthorized', message: 'sign in' })
|
|
250
|
+
equal(
|
|
251
|
+
signed([{ entity: { eid: 'b1' }, $actor: { by: 'untrusted' } }], {
|
|
252
|
+
by: 'member',
|
|
253
|
+
}),
|
|
254
|
+
[{ entity: { eid: 'b1' }, $actor: { by: 'member' } }],
|
|
255
|
+
)
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
## Streaming imports
|
|
259
|
+
|
|
260
|
+
A **chunk** is the group of up to `CHUNK` (50) input bundles that `pour` applies
|
|
261
|
+
in one transaction. Send `application/x-ndjson` to `/apply`: one bundle per
|
|
262
|
+
line, with blank lines skipped. `poured` accepts any content type containing
|
|
263
|
+
`ndjson`. Request and response bodies are streamed; each completed chunk emits
|
|
264
|
+
its applied input bundles, omitting additional entities generated by the graph.
|
|
265
|
+
|
|
266
|
+
```ts
|
|
267
|
+
import { api, poured } from '@yaks/api'
|
|
268
|
+
import { graph } from '@yaks/graph'
|
|
269
|
+
import { ram } from '@yaks/ram'
|
|
270
|
+
import { loadVocab } from '@yaks/vocab'
|
|
271
|
+
import { equal } from '@yaks/testing'
|
|
272
|
+
|
|
273
|
+
const vocab = loadVocab({
|
|
274
|
+
$defs: {
|
|
275
|
+
book: {
|
|
276
|
+
component: true,
|
|
277
|
+
type: 'object',
|
|
278
|
+
properties: {
|
|
279
|
+
title: { type: 'string' },
|
|
280
|
+
},
|
|
281
|
+
},
|
|
282
|
+
},
|
|
283
|
+
})
|
|
284
|
+
const g = graph({ vocab, storage: ram(vocab) })
|
|
285
|
+
const handle = api({ graph: g })
|
|
286
|
+
const bundle = { entity: { eid: 'b1' }, book: { title: 'Dune' } }
|
|
287
|
+
const input = () =>
|
|
288
|
+
new Request('https://shop.test/apply?check=1', {
|
|
289
|
+
method: 'POST',
|
|
290
|
+
headers: { 'content-type': 'application/x-ndjson' },
|
|
291
|
+
body: '\n' + JSON.stringify(bundle) + '\n',
|
|
292
|
+
})
|
|
293
|
+
equal(poured(input()), true)
|
|
294
|
+
const checked = await handle(input())
|
|
295
|
+
equal((await checked.text()).trim(), JSON.stringify(bundle))
|
|
296
|
+
equal(await g.read('.book'), [])
|
|
297
|
+
const committed = await handle(
|
|
298
|
+
new Request('https://shop.test/apply', {
|
|
299
|
+
method: 'POST',
|
|
300
|
+
headers: { 'content-type': 'application/x-ndjson' },
|
|
301
|
+
body: JSON.stringify(bundle),
|
|
302
|
+
}),
|
|
303
|
+
)
|
|
304
|
+
equal((await committed.text()).trim(), JSON.stringify(bundle))
|
|
305
|
+
equal(await g.read('.book'), [bundle])
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
The status stays 200 once streaming starts. A failure is the final response
|
|
309
|
+
line: `{ error, message, line, committed }`. `line` is a 1-based input line
|
|
310
|
+
number; `committed` counts input bundles in successful preceding chunks. The
|
|
311
|
+
failed chunk rolls back; earlier chunks remain committed. For an apply failure,
|
|
312
|
+
the handler checks the chunk with one bundle omitted at a time to locate the
|
|
313
|
+
failure. If no single omission succeeds, it reports the chunk's first line.
|
|
314
|
+
Processing stops after the failure; the reported line need not be the only bad
|
|
315
|
+
line or the last line read.
|
|
316
|
+
|
|
317
|
+
Under `?check=1`, `committed` counts bundles that passed checks, and later
|
|
318
|
+
chunks cannot depend on entities earlier chunks would have created. A `$name`
|
|
319
|
+
[alias](../graph/README.md#ids-and-names) resolves only within its chunk; use
|
|
320
|
+
known eids for references across chunks.
|
|
321
|
+
|
|
322
|
+
## Outgoing bundles
|
|
323
|
+
|
|
324
|
+
`published` omits components declaring `sync: none` from HTTP responses, socket
|
|
325
|
+
frames and projection coverage. It preserves identities, aliases, stamps and
|
|
326
|
+
deletion markers without changing stored bundles.
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
import { published } from '@yaks/api'
|
|
330
|
+
import { loadVocab } from '@yaks/vocab'
|
|
331
|
+
import { equal } from '@yaks/testing'
|
|
332
|
+
|
|
333
|
+
const vocab = loadVocab({
|
|
334
|
+
$defs: {
|
|
335
|
+
local: {
|
|
336
|
+
component: true,
|
|
337
|
+
type: 'object',
|
|
338
|
+
sync: 'none',
|
|
339
|
+
properties: {
|
|
340
|
+
note: { type: 'string' },
|
|
341
|
+
},
|
|
342
|
+
},
|
|
343
|
+
},
|
|
344
|
+
})
|
|
345
|
+
const bundle = { entity: { eid: 'b1' }, local: { note: 'this node' } }
|
|
346
|
+
equal(published(vocab, [bundle]), [{ entity: { eid: 'b1' } }])
|
|
347
|
+
equal(bundle.local.note, 'this node')
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
## Subscriptions
|
|
351
|
+
|
|
352
|
+
`subscriptions(graph)` observes the graph's `effect` phase, including direct
|
|
353
|
+
application writes. `open` sends the current answer and subsequent changes;
|
|
354
|
+
`close` closes one subscription; `drop` closes every subscription for a sink.
|
|
355
|
+
`subscribe: true` selects the **raw feed**, which sends each committed batch
|
|
356
|
+
without an initial answer. `commit` admits bundles from another process, and
|
|
357
|
+
`restore` opens saved subscriptions together, sharing initial reads.
|
|
358
|
+
|
|
359
|
+
```ts
|
|
360
|
+
import { type Frame, subscriptions } from '@yaks/api'
|
|
361
|
+
import { graph } from '@yaks/graph'
|
|
362
|
+
import { ram } from '@yaks/ram'
|
|
363
|
+
import { loadVocab } from '@yaks/vocab'
|
|
364
|
+
import { equal, until } from '@yaks/testing'
|
|
365
|
+
|
|
366
|
+
const vocab = loadVocab({
|
|
367
|
+
$defs: {
|
|
368
|
+
book: {
|
|
369
|
+
component: true,
|
|
370
|
+
type: 'object',
|
|
371
|
+
properties: {
|
|
372
|
+
price: { type: 'number' },
|
|
373
|
+
},
|
|
374
|
+
},
|
|
375
|
+
},
|
|
376
|
+
})
|
|
377
|
+
const g = graph({ vocab, storage: ram(vocab) })
|
|
378
|
+
const subs = subscriptions(g)
|
|
379
|
+
const frames: Frame[] = []
|
|
380
|
+
const to = (frame: Frame) => {
|
|
381
|
+
frames.push(frame)
|
|
382
|
+
}
|
|
383
|
+
await subs.restore([{ sink: to, id: 'cheap', query: '.book.price<20' }])
|
|
384
|
+
equal(frames[0].bundles, [])
|
|
385
|
+
await g.apply([{ entity: { eid: 'b1' }, book: { price: 12 } }])
|
|
386
|
+
await until(() => frames.length == 2)
|
|
387
|
+
equal(frames[1].bundles, [{ entity: { eid: 'b1' }, book: { price: 12 } }])
|
|
388
|
+
await g.apply([{ entity: { eid: 'b1' }, book: { price: 25 } }])
|
|
389
|
+
await until(() => frames.length == 3)
|
|
390
|
+
equal(frames[2].gone, ['b1'])
|
|
391
|
+
await subs.close(to, 'cheap')
|
|
392
|
+
await subs.open(to, 'all', true)
|
|
393
|
+
await g.apply([{ entity: { eid: 'b2' }, book: { price: 10 } }])
|
|
394
|
+
await until(() => frames.length == 4)
|
|
395
|
+
equal(frames[3].id, 'all')
|
|
396
|
+
await subs.drop(to)
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
Query frames contain current matching bundles and `gone` eids for deleted
|
|
400
|
+
entities or entities that stopped matching. A refresh may send the whole answer.
|
|
401
|
+
|
|
402
|
+
Every frame carrying rows, `gone` eids or a reduction says the store's
|
|
403
|
+
`revision` when it was sent, which its rows are no newer than, and `since`, the
|
|
404
|
+
revision of its subscription's frame before it (absent on the first). The
|
|
405
|
+
registry's revision moves on with every commit it hears and every change its
|
|
406
|
+
`revision` token reveals; it starts at the time (`now`), so a registry made
|
|
407
|
+
again after a restart starts past every frame the last one sent. A frame
|
|
408
|
+
carrying only relayed or transient values says no revision. A subscriber can
|
|
409
|
+
tell a frame older than a row it holds, or one whose `since` it never heard
|
|
410
|
+
(@yaks/sync). Queries that can test one entity at a time use
|
|
411
|
+
[@yaks/match](../match/README.md); queries with references, ordering, limits or
|
|
412
|
+
walks use dependency reads or refreshes. A refresh runs only after a commit
|
|
413
|
+
writes a component its query reads, on an entity it selects or on one a
|
|
414
|
+
reference or a walk passes through, or deletes an entity the query could have
|
|
415
|
+
read: a member of its answer, or any entity when the query reads past each
|
|
416
|
+
entity alone. A query with a text term or `.near` is read again after every
|
|
417
|
+
commit. Writes return at commit without waiting for subscriber reads; commits
|
|
418
|
+
arriving during a read share the next pass. A subscription's first answer is
|
|
419
|
+
sent when its read finishes, even when commits landed during it: those are
|
|
420
|
+
caught up after, by reading it again and sending what moved, so an answer the
|
|
421
|
+
store's writes move faster than it can be read is still heard.
|
|
422
|
+
|
|
423
|
+
A small answer of a query tested one entity at a time is held in memory and kept
|
|
424
|
+
current from what each commit moves. Subscriptions asking the same query with
|
|
425
|
+
the same options share it, and it outlives the last of them for a while: a
|
|
426
|
+
client that closes a subscription and opens it again is answered without a read.
|
|
427
|
+
|
|
428
|
+
For stores other graph instances can write, pass `revision` to
|
|
429
|
+
`subscriptions(graph, { revision })`: a function returning the store's change
|
|
430
|
+
token. `check()` compares it with the last observed token; a change discards
|
|
431
|
+
retained answers and sends active query subscriptions complete answers with
|
|
432
|
+
`reset: true`, so removed members leave the client too. Opening and restoring
|
|
433
|
+
subscriptions also check before reusing retained answers. A host can call
|
|
434
|
+
`check()` periodically; the routes handler does so automatically.
|
|
435
|
+
|
|
436
|
+
A `.fields` [projection](../graph/README.md#projections) carries `coverage` for
|
|
437
|
+
selected bundles. A covered property omitted from its bundle is absent; an
|
|
438
|
+
uncovered property was not read. Entities reached through references travel in
|
|
439
|
+
`peers`, with `peerCoverage` and `peerGone`, outside the selected set. Aggregate
|
|
440
|
+
queries send `{ id, count }`, `{ id, distinct }` or `{ id, tally }` on opening
|
|
441
|
+
and when their value changes. Initial query frames carry `transientReset` eids
|
|
442
|
+
and may carry [transient frames](../graph/README.md#transient-text).
|
|
443
|
+
|
|
444
|
+
`subscriptions(graph, { invalidate })` accepts an application dependency rule:
|
|
445
|
+
returning `true` from `invalidate(query, applied)` refreshes that subscription.
|
|
446
|
+
It does not discover dependencies outside the query automatically.
|
|
447
|
+
`refused(error, query)` is told of each subscription the registry refuses and
|
|
448
|
+
closes, the caller's own refusals included, for a host that knows whose query it
|
|
449
|
+
was to report.
|
|
450
|
+
|
|
451
|
+
`@yaks/api/reached` is a registry over graphs a host can ask but not watch, such
|
|
452
|
+
as the members of a [@yaks/reach](../reach/README.md) composition. It answers a
|
|
453
|
+
line with `read(line, opts, writer)`, as the watch's opener (the read it asks as
|
|
454
|
+
and the writer its socket holds, which `Subs.open` and `Opening` carry), whole
|
|
455
|
+
and with `reset`, and asks every line again when a member's graph moved
|
|
456
|
+
(`hear`), sending an answer only when it moved. A refusal is sent under its id
|
|
457
|
+
and the subscription stays open for the next change. `restore` with `quiet`
|
|
458
|
+
holds watches unasked until `resume` or the next `hear`.
|
|
459
|
+
`beside(subs, reached, borrows)` is one `Subs` of the two: the lines `borrows`
|
|
460
|
+
names go to the reach, and everything else (the graph's own lines, the raw feed,
|
|
461
|
+
relayed values) to `subs`, so a Durable Object's hibernatable sockets serve
|
|
462
|
+
both.
|
|
463
|
+
|
|
464
|
+
`watched({watch})` is a registry whose every line is a live watch another keeps,
|
|
465
|
+
such as a reach's (@yaks/reach `watch`): each frame goes out under the
|
|
466
|
+
subscription's id, a refusal said as one, and closing the subscription stops the
|
|
467
|
+
watch. It answers lines only: the raw feed is refused, and relayed values go
|
|
468
|
+
nowhere.
|
|
469
|
+
|
|
470
|
+
### Relayed values
|
|
471
|
+
|
|
472
|
+
A **relay** forwards `sync: peers` components to other sinks watching their
|
|
473
|
+
entities. It holds one value per entity and component under its last writer's
|
|
474
|
+
connection, merging partial patches. It never echoes a connection's own values.
|
|
475
|
+
A clear (`{ component: null }`), disconnect or declared duration expiry clears
|
|
476
|
+
that value. Raw feeds receive every relay; query subscriptions receive existing
|
|
477
|
+
values when they open or an entity joins their answer.
|
|
478
|
+
|
|
479
|
+
```ts
|
|
480
|
+
import { type Frame, subscriptions } from '@yaks/api'
|
|
481
|
+
import { graph } from '@yaks/graph'
|
|
482
|
+
import { ram } from '@yaks/ram'
|
|
483
|
+
import { loadVocab } from '@yaks/vocab'
|
|
484
|
+
import { equal } from '@yaks/testing'
|
|
485
|
+
|
|
486
|
+
const vocab = loadVocab({
|
|
487
|
+
$defs: {
|
|
488
|
+
cursor: {
|
|
489
|
+
component: true,
|
|
490
|
+
type: 'object',
|
|
491
|
+
sync: 'peers',
|
|
492
|
+
durable: 'connection',
|
|
493
|
+
properties: { x: { type: 'number' } },
|
|
494
|
+
},
|
|
495
|
+
position: {
|
|
496
|
+
component: true,
|
|
497
|
+
type: 'object',
|
|
498
|
+
sync: 'peers',
|
|
499
|
+
durable: 'forever',
|
|
500
|
+
save: '.entity',
|
|
501
|
+
properties: { x: { type: 'number' } },
|
|
502
|
+
},
|
|
503
|
+
},
|
|
504
|
+
})
|
|
505
|
+
const g = graph({ vocab, storage: ram(vocab) })
|
|
506
|
+
const subs = subscriptions(g)
|
|
507
|
+
const writer = (_frame: Frame) => {}
|
|
508
|
+
const seen: Frame[] = []
|
|
509
|
+
const reader = (frame: Frame) => {
|
|
510
|
+
seen.push(frame)
|
|
511
|
+
}
|
|
512
|
+
await subs.open(reader, 'all', true)
|
|
513
|
+
const cursor = { entity: { eid: 'b1' }, cursor: { x: 4 } }
|
|
514
|
+
await subs.relay(writer, [cursor])
|
|
515
|
+
equal(seen[0].relay, [cursor])
|
|
516
|
+
equal(await g.read('.cursor'), [])
|
|
517
|
+
equal(await subs.snapshot('.cursor.x=4'), [cursor])
|
|
518
|
+
await g.apply([{ entity: { eid: 'b1' } }])
|
|
519
|
+
await subs.relay(writer, [{ entity: { eid: 'b1' }, position: { x: 7 } }])
|
|
520
|
+
equal(await g.read('.position'), [{
|
|
521
|
+
entity: { eid: 'b1' },
|
|
522
|
+
position: { x: 7 },
|
|
523
|
+
}])
|
|
524
|
+
await subs.drop(writer)
|
|
525
|
+
equal(await subs.snapshot('.cursor'), [])
|
|
526
|
+
await subs.drop(reader)
|
|
527
|
+
```
|
|
528
|
+
|
|
529
|
+
Without `save`, relayed values stay outside storage. A `durable: 'connection'`
|
|
530
|
+
value clears when its writer disconnects. A duration such as `durable: '5s'`
|
|
531
|
+
remains available until that time after the latest write, even if its writer
|
|
532
|
+
disconnects. Another connection can take over by writing the same component;
|
|
533
|
+
that write restarts the duration. This lets an elected simulation owner hand off
|
|
534
|
+
its latest value without storing it.
|
|
535
|
+
|
|
536
|
+
A component's **save query** selects the stored entities whose latest relayed
|
|
537
|
+
value should be stored. For example,
|
|
538
|
+
`save: '.player (!position | .updated.at<="30s ago")'` saves only stored players
|
|
539
|
+
with no position yet or an update at least thirty seconds old. It does not
|
|
540
|
+
inspect the incoming value. A stored entity that never matches is never saved,
|
|
541
|
+
including an explicit clear.
|
|
542
|
+
|
|
543
|
+
The server checks on arrival and after relevant stored facts change. A relative
|
|
544
|
+
time condition is checked every second only while the stored entity satisfies
|
|
545
|
+
its other eligibility predicates. An entity lacking a required component owns no
|
|
546
|
+
clock retry. When a writer disconnects, its latest value remains pending until
|
|
547
|
+
the query matches; disconnect never bypasses the query. Every relay, with or
|
|
548
|
+
without `save`, passes `graph.admit` before it is held or forwarded. Admission
|
|
549
|
+
runs ordinary write checks as the connection's authenticated writer, including
|
|
550
|
+
ownership, request guards and schema constraints. Partial patches are checked
|
|
551
|
+
with the latest admitted peer value, and the relay forwards the checked result
|
|
552
|
+
after write hooks and rules. Certified plugins check temporary rows without
|
|
553
|
+
stored writes; other plugins use an ordinary dry run. Each save applies as the
|
|
554
|
+
connection's authenticated actor and vocabulary versions (`PeerWriter`). A
|
|
555
|
+
refused input leaves the previous accepted value intact; a refused save is sent
|
|
556
|
+
to its writer.
|
|
557
|
+
|
|
558
|
+
A query can select by relayed values; moving, clearing or expiring them changes
|
|
559
|
+
membership. Subscription `bundles` carry stored components, while `relay`
|
|
560
|
+
carries current relayed values. A projection through a reference cannot be read
|
|
561
|
+
over relayed values.
|
|
562
|
+
|
|
563
|
+
## WebSocket protocol
|
|
564
|
+
|
|
565
|
+
`attach` connects a socket to a subscription registry and drops its
|
|
566
|
+
subscriptions on close. `receive` dispatches one message; `decode` admits UTF-8
|
|
567
|
+
text of up to 64 KiB before JSON parsing. Oversized or malformed messages
|
|
568
|
+
produce a `refused` frame with a recoverable top-level id, or an empty id. They
|
|
569
|
+
do not close the socket or disturb other subscriptions.
|
|
570
|
+
|
|
571
|
+
```text
|
|
572
|
+
→ { subscribe: "<query>" | true, id: "<id>", acks?: true, frames?: true, page?: "<path>" }
|
|
573
|
+
→ { ack: "<token>" }
|
|
574
|
+
→ { unsubscribe: "<id>" }
|
|
575
|
+
→ { relay: Bundle[] }
|
|
576
|
+
→ { clock: <finite number> }
|
|
577
|
+
← { clock: <echoed number>, received: <epoch ms>, sent: <epoch ms> }
|
|
578
|
+
← { id, bundles, gone?, coverage?, peers?, peerCoverage?, peerGone? }
|
|
579
|
+
← { id, count } | { id, distinct } | { id, tally }
|
|
580
|
+
← { id, relay: Bundle[] } | { id, transient: TransientFrame[] }
|
|
581
|
+
← { id, refused: { error, message, … } }
|
|
582
|
+
← { frames: [{ id, … }, …], ack: "<token>" }
|
|
583
|
+
```
|
|
584
|
+
|
|
585
|
+
A **clock exchange** samples the server clock on the existing socket. The client
|
|
586
|
+
sends a finite numeric `clock` token (its request timestamp); the server echoes
|
|
587
|
+
it with `received` and `sent`, epoch milliseconds from `Date.now()` at receipt
|
|
588
|
+
and send. Clock replies go directly to that socket, without a subscription, ack
|
|
589
|
+
or durable read/write. Invalid clock tokens are not clock exchanges and follow
|
|
590
|
+
ordinary message validation.
|
|
591
|
+
|
|
592
|
+
`clockReply(socket, value, received, now?)` handles a decoded clock request and
|
|
593
|
+
returns whether it replied. Hosts with their own socket message boundary capture
|
|
594
|
+
`received` before dispatch and call it before subscription recovery or ack
|
|
595
|
+
queues. An injected `now` must return epoch milliseconds.
|
|
596
|
+
|
|
597
|
+
```ts
|
|
598
|
+
import { clockReply } from '@yaks/api'
|
|
599
|
+
import { equal } from '@yaks/testing'
|
|
600
|
+
|
|
601
|
+
const replies: unknown[] = []
|
|
602
|
+
const socket = { send: (text: string) => replies.push(JSON.parse(text)) }
|
|
603
|
+
equal(
|
|
604
|
+
clockReply(
|
|
605
|
+
socket,
|
|
606
|
+
{ clock: 12.5 },
|
|
607
|
+
1_800_000_000_000,
|
|
608
|
+
() => 1_800_000_000_002,
|
|
609
|
+
),
|
|
610
|
+
true,
|
|
611
|
+
)
|
|
612
|
+
equal(replies, [{
|
|
613
|
+
clock: 12.5,
|
|
614
|
+
received: 1_800_000_000_000,
|
|
615
|
+
sent: 1_800_000_000_002,
|
|
616
|
+
}])
|
|
617
|
+
equal(clockReply(socket, { clock: '12.5' }, 1_800_000_000_000), false)
|
|
618
|
+
```
|
|
619
|
+
|
|
620
|
+
A subscription's `page` is the path of the page that asked for it, which a
|
|
621
|
+
failure its reads meet names (@yaks/graph/asker); nothing answers by it.
|
|
622
|
+
|
|
623
|
+
An **ack** is the token a client echoes after applying a frame. With
|
|
624
|
+
`acks:
|
|
625
|
+
true`, subscription frames wait for their ack before more subscription
|
|
626
|
+
frames are sent. `frames: true` groups adjacent non-relay frames under one ack;
|
|
627
|
+
acknowledge only after applying the whole group. Relay-only frames carry no ack
|
|
628
|
+
or replay state. On reconnect, clients reopen subscriptions and resend relayed
|
|
629
|
+
values.
|
|
630
|
+
|
|
631
|
+
`queue` handles socket buffering and acks; `sink` queues frames until the socket
|
|
632
|
+
opens. Relay frames wait up to 16 ms and merge recent patches, retaining a clear
|
|
633
|
+
before a later partial patch. A membership or stored-data frame flushes
|
|
634
|
+
preceding relays first. Admission uses the component's declared pace, caps
|
|
635
|
+
unpaced traffic, and closes persistent floods. Rejected inputs leave accepted
|
|
636
|
+
values intact. Relay pace reads the registry's time, the `now` given to
|
|
637
|
+
`subscriptions`, unless `attach` was given one; @yaks/durable-object's sockets
|
|
638
|
+
also set their frame queues' timers with the registry's `timer`.
|
|
639
|
+
|
|
640
|
+
```ts
|
|
641
|
+
import { decode, type Frame, queue } from '@yaks/api'
|
|
642
|
+
import { equal } from '@yaks/testing'
|
|
643
|
+
|
|
644
|
+
const sent: (Frame & { ack: string })[] = []
|
|
645
|
+
const q = queue({
|
|
646
|
+
send: (text) => {
|
|
647
|
+
sent.push(JSON.parse(text))
|
|
648
|
+
},
|
|
649
|
+
})
|
|
650
|
+
q.enable()
|
|
651
|
+
q.send({ id: 'books', bundles: [] })
|
|
652
|
+
q.send({ id: 'books', gone: ['b1'] })
|
|
653
|
+
equal(sent.length, 1)
|
|
654
|
+
q.ack(sent[0].ack)
|
|
655
|
+
equal(sent.length, 2)
|
|
656
|
+
equal(sent[1].gone, ['b1'])
|
|
657
|
+
equal(decode('{"unsubscribe":"books"}'), { value: { unsubscribe: 'books' } })
|
|
658
|
+
q.close()
|
|
659
|
+
```
|
|
660
|
+
|
|
661
|
+
A socket can be wired without an HTTP upgrade when the host already owns it:
|
|
662
|
+
|
|
663
|
+
```ts
|
|
664
|
+
import { attach, type Frame, type Socket, subscriptions } from '@yaks/api'
|
|
665
|
+
import { graph } from '@yaks/graph'
|
|
666
|
+
import { ram } from '@yaks/ram'
|
|
667
|
+
import { loadVocab } from '@yaks/vocab'
|
|
668
|
+
import { equal, until } from '@yaks/testing'
|
|
669
|
+
|
|
670
|
+
const vocab = loadVocab({ $defs: {} })
|
|
671
|
+
const g = graph({ vocab, storage: ram(vocab) })
|
|
672
|
+
const subs = subscriptions(g)
|
|
673
|
+
const events = new EventTarget()
|
|
674
|
+
const frames: Frame[] = []
|
|
675
|
+
const socket: Socket = {
|
|
676
|
+
readyState: 1,
|
|
677
|
+
send: (text) => {
|
|
678
|
+
frames.push(JSON.parse(text))
|
|
679
|
+
},
|
|
680
|
+
addEventListener: events.addEventListener.bind(events),
|
|
681
|
+
}
|
|
682
|
+
attach(subs, socket)
|
|
683
|
+
events.dispatchEvent(
|
|
684
|
+
new MessageEvent('message', {
|
|
685
|
+
data: JSON.stringify({ subscribe: '.entity', id: 'all' }),
|
|
686
|
+
}),
|
|
687
|
+
)
|
|
688
|
+
await until(() => frames.length == 1)
|
|
689
|
+
equal(frames[0].bundles, [])
|
|
690
|
+
events.dispatchEvent(
|
|
691
|
+
new MessageEvent('message', {
|
|
692
|
+
data: JSON.stringify({ unsubscribe: 'all' }),
|
|
693
|
+
}),
|
|
694
|
+
)
|
|
695
|
+
events.dispatchEvent(new Event('close'))
|
|
696
|
+
```
|
|
697
|
+
|
|
698
|
+
Durable writes use `/apply`; socket relays only carry `sync: peers` components.
|
|
699
|
+
`denoUpgrade` is the default WebSocket upgrade. Other runtimes supply an
|
|
700
|
+
`Upgrade` returning `{ socket, response }`; Cloudflare Workers can use
|
|
701
|
+
`workerUpgrade` from [@yaks/workerd](../workerd/README.md).
|
|
702
|
+
|
|
703
|
+
## Refusals and request reports
|
|
704
|
+
|
|
705
|
+
A **refusal** is the JSON error body sent to a caller (`Refusal`): its error
|
|
706
|
+
name, message, and enumerable details except `stack`. `refusal` constructs that
|
|
707
|
+
body; `refuse` adds the HTTP status from
|
|
708
|
+
[@yaks/graph](../graph/README.md#admission-and-schema-checks). `json` constructs
|
|
709
|
+
a JSON response. `fault` reports an error whose status is at least 500, with
|
|
710
|
+
where it was caught, leaving expected client refusals unreported. It goes to the
|
|
711
|
+
reporter a host installed with `faults`, which returns its removal, or to the
|
|
712
|
+
console while none is. Every failure this package catches goes there: a socket
|
|
713
|
+
message, a subscription refresh, a streamed import's failed line, and a server
|
|
714
|
+
failure `refuse` answers. Under `served`, that last one is reported with its
|
|
715
|
+
request instead, once. While a host's reporter hears them, an answer at 500 or
|
|
716
|
+
over that was reported carries the `FILED` header (`x-yak-filed`), so a caller
|
|
717
|
+
relaying it, another server or a page, files it no second time. A host gives
|
|
718
|
+
`api()` or `applier()` the `tags` it adds to what that door reports, such as
|
|
719
|
+
which of its stores it is; the reporter hears them beside `where`.
|
|
720
|
+
|
|
721
|
+
These are also `@yaks/api/refuse`, which loads none of the server: a process
|
|
722
|
+
that serves nothing, such as a `yak` command, installs its reporter with
|
|
723
|
+
`faults` from there.
|
|
724
|
+
|
|
725
|
+
```ts
|
|
726
|
+
import {
|
|
727
|
+
faults,
|
|
728
|
+
FILED,
|
|
729
|
+
json,
|
|
730
|
+
refusal,
|
|
731
|
+
refuse,
|
|
732
|
+
Unauthorized,
|
|
733
|
+
} from '@yaks/api/refuse'
|
|
734
|
+
import { Misfit } from '@yaks/graph/errors'
|
|
735
|
+
import { equal } from '@yaks/testing'
|
|
736
|
+
|
|
737
|
+
const caught: string[] = []
|
|
738
|
+
const remove = faults((_error, where) => {
|
|
739
|
+
caught.push(where)
|
|
740
|
+
})
|
|
741
|
+
const error = new Unauthorized('sign in')
|
|
742
|
+
equal(refusal(error), { error: 'Unauthorized', message: 'sign in' })
|
|
743
|
+
equal(refuse(error).status, 401)
|
|
744
|
+
const gone = new Request('https://shop.test/books?token=x', { method: 'PUT' })
|
|
745
|
+
const broke = refuse(new Error('disk gone'), gone)
|
|
746
|
+
equal(broke.status, 500)
|
|
747
|
+
remove()
|
|
748
|
+
// The failure reached the reporter, named by where; the refusal did not. Its
|
|
749
|
+
// answer says so, and a caller relaying it files it no second time.
|
|
750
|
+
equal(caught, ['PUT /books'])
|
|
751
|
+
equal(broke.headers.get(FILED), '1')
|
|
752
|
+
equal(refuse(new Error('disk gone')).headers.has(FILED), false)
|
|
753
|
+
equal(await json({ ready: true }).json(), { ready: true })
|
|
754
|
+
// A write that did not fit the vocabulary is a `Refused` that says so.
|
|
755
|
+
const misfit = new Misfit('book.pages is a number')
|
|
756
|
+
equal(refusal(misfit), {
|
|
757
|
+
error: 'Refused',
|
|
758
|
+
message: 'book.pages is a number',
|
|
759
|
+
misfit: true,
|
|
760
|
+
})
|
|
761
|
+
equal(refuse(misfit).status, 400)
|
|
762
|
+
```
|
|
763
|
+
|
|
764
|
+
| Status | Error names |
|
|
765
|
+
| ------ | --------------------------------------------------------- |
|
|
766
|
+
| 400 | `Refused`, `Unsupported`, `SyntaxError`, `Unknown` |
|
|
767
|
+
| 401 | `Unauthorized` |
|
|
768
|
+
| 403 | `Denied` |
|
|
769
|
+
| 404 | `NotFound` (also unknown routes) |
|
|
770
|
+
| 405 | Wrong endpoint method, or `/ws` without an upgrade header |
|
|
771
|
+
| 409 | `Stale` |
|
|
772
|
+
| 500 | Unmapped error names |
|
|
773
|
+
|
|
774
|
+
Socket refusals are frames, and streaming import refusals are final NDJSON
|
|
775
|
+
lines. An HTTP answer at 500 or over carries `x-request-id` and is handed to
|
|
776
|
+
`report` as a bundle with the **request component**, which records method, URL
|
|
777
|
+
without query string, matched route, status, duration and reduced user agent.
|
|
778
|
+
`served` watches any handler this way. An answer already carrying `x-request-id`
|
|
779
|
+
is not reported again. `report` chooses where to keep the bundle; the default
|
|
780
|
+
reports it through `fault`. `requested` constructs it and `agent` reduces a
|
|
781
|
+
`User-Agent`.
|
|
782
|
+
|
|
783
|
+
```ts
|
|
784
|
+
import { agent, requested, served, timed } from '@yaks/api'
|
|
785
|
+
import { type Bundle } from '@yaks/graph'
|
|
786
|
+
import { equal } from '@yaks/testing'
|
|
787
|
+
|
|
788
|
+
const request = new Request('https://shop.test/books?private=value')
|
|
789
|
+
const reports: Bundle[] = []
|
|
790
|
+
const handle = served(() => new Response('unavailable', { status: 503 }), {
|
|
791
|
+
report: (bundle) => {
|
|
792
|
+
reports.push(bundle)
|
|
793
|
+
},
|
|
794
|
+
route: () => '/books',
|
|
795
|
+
})
|
|
796
|
+
const response = await handle(request)
|
|
797
|
+
equal(reports[0].entity.eid, response.headers.get('x-request-id'))
|
|
798
|
+
equal(requested('r1', request, { status: 503, ms: 2 }).request, {
|
|
799
|
+
method: 'GET',
|
|
800
|
+
url: 'https://shop.test/books',
|
|
801
|
+
status: 503,
|
|
802
|
+
ms: 2,
|
|
803
|
+
})
|
|
804
|
+
equal(agent('curl/8.5.0'), 'curl 8.5.0')
|
|
805
|
+
const lines: string[] = []
|
|
806
|
+
const fetch = timed((line) => {
|
|
807
|
+
lines.push(line)
|
|
808
|
+
}, () =>
|
|
809
|
+
new Response('', {
|
|
810
|
+
headers: { 'server-timing': 'read;dur=2' },
|
|
811
|
+
}))
|
|
812
|
+
await fetch(request)
|
|
813
|
+
equal(lines, ['GET /books?private=value 200 read;dur=2'])
|
|
814
|
+
```
|
|
815
|
+
|
|
816
|
+
`timed` is a client fetch wrapper that prints the response's `Server-Timing`
|
|
817
|
+
header through a supplied callback, returning the response unchanged.
|
|
818
|
+
|
|
819
|
+
## Plugin routes and serving
|
|
820
|
+
|
|
821
|
+
`@yaks/api/routes` exports `handler(host)`, which composes plugin routes and
|
|
822
|
+
filters with the four endpoints. Exact paths beat prefixes; longer prefixes beat
|
|
823
|
+
shorter ones; plugin order breaks ties. A plugin's exact route can override an
|
|
824
|
+
endpoint. A catch-all route only answers paths no endpoint claims. Host commits
|
|
825
|
+
from `host.feed` reach the subscription registry as well as local graph commits.
|
|
826
|
+
When the host has no commit feed and `host.storage.revision` is available, the
|
|
827
|
+
handler checks it every second and resets query answers after a store change,
|
|
828
|
+
including writes from another process. Opening a query checks the revision
|
|
829
|
+
before reusing a retained answer. A host with a commit feed is never polled: the
|
|
830
|
+
feed carries every commit as patches, all those heard since its last call in one
|
|
831
|
+
pass (`subs.hear`), and when it missed some, query answers are reset as after a
|
|
832
|
+
store change. The checks and commit feed stop with `host.stopping`.
|
|
833
|
+
|
|
834
|
+
`handler(host, { under: '/api' })` answers the endpoints under that path as well
|
|
835
|
+
as at the root: `/api/query` is `/query`, and `/api/ws` upgrades as `/ws` does,
|
|
836
|
+
since the request is read, never rewritten. That is where a page's
|
|
837
|
+
`./api/client.js` finds its store's doors (@yaks/platform's `yak/client`).
|
|
838
|
+
`pathOf(request, under)` (`@yaks/api/routed`) is the path the endpoints read.
|
|
839
|
+
|
|
840
|
+
```ts
|
|
841
|
+
import { routed } from '@yaks/api'
|
|
842
|
+
import { handler } from '@yaks/api/routes'
|
|
843
|
+
import { graph } from '@yaks/graph'
|
|
844
|
+
import { ram } from '@yaks/ram'
|
|
845
|
+
import { loadVocab } from '@yaks/vocab'
|
|
846
|
+
import { equal } from '@yaks/testing'
|
|
847
|
+
|
|
848
|
+
const vocab = loadVocab({ $defs: {} })
|
|
849
|
+
const g = graph({ vocab, storage: ram(vocab) })
|
|
850
|
+
const route = {
|
|
851
|
+
method: 'GET',
|
|
852
|
+
path: '/health',
|
|
853
|
+
handle: () => new Response('ready'),
|
|
854
|
+
}
|
|
855
|
+
equal(routed(route, 'GET', '/health'), true)
|
|
856
|
+
const checked: string[] = []
|
|
857
|
+
const handle = handler({
|
|
858
|
+
graph: g,
|
|
859
|
+
who: () => null,
|
|
860
|
+
routes: [route],
|
|
861
|
+
filters: [(request) => {
|
|
862
|
+
checked.push(new URL(request.url).pathname)
|
|
863
|
+
}],
|
|
864
|
+
})
|
|
865
|
+
equal(
|
|
866
|
+
await (await handle(new Request('https://shop.test/health'))).text(),
|
|
867
|
+
'ready',
|
|
868
|
+
)
|
|
869
|
+
equal(checked, ['/health'])
|
|
870
|
+
```
|
|
871
|
+
|
|
872
|
+
`@yaks/api/vocab` declares the request component and the `serve` tool.
|
|
873
|
+
`@yaks/api/tools` implements `serve`: it binds a TCP port, starts the host's
|
|
874
|
+
[duties](../cli/README.md#duties-the-work-nobody-is-asking-for), and returns
|
|
875
|
+
when the server stops. Port and hostname come from tool arguments, then
|
|
876
|
+
configuration, then `PORT` (8787) and `HOSTNAME` (`127.0.0.1`). It reports the
|
|
877
|
+
bound address on stderr while the call remains running. Keep the listener on
|
|
878
|
+
loopback when a local proxy such as cloudflared serves it. A non-loopback TCP
|
|
879
|
+
peer must present `Authorization: Bearer <token>` on every request, including
|
|
880
|
+
MCP, graph reads and writes, plugin routes and WebSocket upgrades. Configure the
|
|
881
|
+
credential in this plugin's options as
|
|
882
|
+
`{"use":"@yaks/api","with":{"token":{"secret":"YAK_API_TOKEN"}}}`; the host
|
|
883
|
+
reads the secret from its vault for each request, so rotations take effect
|
|
884
|
+
immediately. Without a configured credential, remote requests receive 401. Host,
|
|
885
|
+
forwarded and session headers cannot identify a loopback peer.
|
|
886
|
+
|
|
887
|
+
Stopping, it takes no new connection, closes its sockets and lets the requests
|
|
888
|
+
in flight finish for `grace` seconds (`GRACE`, 10). After that it cancels `GET`,
|
|
889
|
+
`HEAD` and `OPTIONS` reads, cuts every answer still streaming that no admitted
|
|
890
|
+
write is producing (an MCP call's event stream), and waits for admitted writes
|
|
891
|
+
before returning. A read or an answer that never ends cannot hold the process.
|
|
892
|
+
`share` lets a second server started the same way listen on the port at once
|
|
893
|
+
(SO_REUSEPORT; Deno needs `--unstable-net`, which this repository's deno.json
|
|
894
|
+
turns on), and `ready` names a file it writes its pid to once listening: a
|
|
895
|
+
replacement answers before the server it replaces stops, the way `yak restart`
|
|
896
|
+
hands the box's web over ([@yaks/cli](../cli/README.md)). Without `share` a
|
|
897
|
+
taken port is refused. See [@yaks/tools](../tools/README.md) for tool execution
|
|
898
|
+
and [@yaks/cli](../cli/README.md) for host configuration.
|
|
899
|
+
|
|
900
|
+
A host configured with this package exposes the tool through `yak`:
|
|
901
|
+
|
|
902
|
+
```json
|
|
903
|
+
{
|
|
904
|
+
"db": "graph.db",
|
|
905
|
+
"plugins": ["@yaks/api"],
|
|
906
|
+
"port": 8787
|
|
907
|
+
}
|
|
908
|
+
```
|
|
909
|
+
|
|
910
|
+
```sh
|
|
911
|
+
yak serve --config yak.json
|
|
912
|
+
# In another terminal, check the served vocabulary:
|
|
913
|
+
curl --fail http://127.0.0.1:8787/vocab
|
|
914
|
+
```
|
|
915
|
+
|
|
916
|
+
The following binds a local port, so it is excluded from documentation tests:
|
|
917
|
+
|
|
918
|
+
```ts ignore
|
|
919
|
+
import { api, denoListen } from '@yaks/api'
|
|
920
|
+
import { graph } from '@yaks/graph'
|
|
921
|
+
import { ram } from '@yaks/ram'
|
|
922
|
+
import { loadVocab } from '@yaks/vocab'
|
|
923
|
+
import { equal } from '@yaks/testing'
|
|
924
|
+
|
|
925
|
+
const vocab = loadVocab({ $defs: {} })
|
|
926
|
+
const g = graph({ vocab, storage: ram(vocab) })
|
|
927
|
+
let port = 0
|
|
928
|
+
const server = denoListen({
|
|
929
|
+
port: 0,
|
|
930
|
+
hostname: '127.0.0.1',
|
|
931
|
+
onListen: (addr) => {
|
|
932
|
+
port = addr.port
|
|
933
|
+
},
|
|
934
|
+
}, api({ graph: g }))
|
|
935
|
+
try {
|
|
936
|
+
equal((await fetch(`http://127.0.0.1:${port}/vocab`)).status, 200)
|
|
937
|
+
} finally {
|
|
938
|
+
await server.shutdown()
|
|
939
|
+
await server.finished
|
|
940
|
+
}
|
|
941
|
+
```
|
|
942
|
+
|
|
943
|
+
## Limits
|
|
944
|
+
|
|
945
|
+
This package creates no database. [Storage](../graph/README.md#data-model)
|
|
946
|
+
adapters persist graph data; [@yaks/query](../query/README.md) defines query
|
|
947
|
+
syntax and the adapter decides which queries it supports. Authorization belongs
|
|
948
|
+
to the application and graph plugins. Feature packages own their routes, such as
|
|
949
|
+
[@yaks/mcp](../mcp/README.md)'s `/mcp`.
|
|
950
|
+
|
|
951
|
+
The handler uses standard web interfaces. `denoListen` and `denoUpgrade` look up
|
|
952
|
+
Deno at call time and throw outside Deno. Other runtimes provide their own
|
|
953
|
+
WebSocket upgrade, and runtimes that bind their own ports do not use `serve`.
|
|
954
|
+
|
|
955
|
+
## License
|
|
956
|
+
|
|
957
|
+
Apache-2.0
|