@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/actor.ts ADDED
@@ -0,0 +1,106 @@
1
+ // Who is writing. A client can put anything in the JSON it posts — including
2
+ // whose name is on it — so the request handler is the only place that can
3
+ // know. Every array of bundles that arrives here has its `$actor` component
4
+ // discarded and replaced by the identity the application's `authenticate`
5
+ // returned for this request. A client that sends `$actor: { by: 'someone
6
+ // else' }` is not refused; it is simply overwritten, because there is nothing
7
+ // to argue about: the graph stamps what reached it, and what reaches it is
8
+ // what this handler decided.
9
+ //
10
+ // An unauthenticated request writes with no actor at all — the bundles are
11
+ // stored unattributed rather than attributed to a guess. An application that
12
+ // would rather refuse throws `Unauthorized` from its `authenticate`.
13
+
14
+ import type { Actor } from 'jsr:@yaks/graph@0.2.36'
15
+
16
+ /**
17
+ * How the application names the writer of a request: the actor making it, or
18
+ * `null` for nobody. Throwing
19
+ * {@link https://jsr.io/@yaks/api/doc/~/Unauthorized | Unauthorized} answers
20
+ * the request with a 401.
21
+ *
22
+ * An actor is the pair a write is stamped with — `by` the identity it acts
23
+ * for, and `via` whatever it came through: a session, a connector, or the
24
+ * server itself. An application that knows only the identity returns only
25
+ * `by`.
26
+ *
27
+ * It runs on every request the handler answers — a read, a write and a
28
+ * WebSocket upgrade alike — so an application that restricts reads restricts
29
+ * them here. A door that has already read the request's body hands what it
30
+ * said as `message` (the MCP door's JSON-RPC message), so the caller a body
31
+ * names is answered without reading it twice.
32
+ *
33
+ * ```ts
34
+ * declare let memberOf: (key: string) => string
35
+ *
36
+ * let authenticate = (request: Request) => {
37
+ * let key = request.headers.get('authorization')
38
+ * return key ? { by: memberOf(key) } : null
39
+ * }
40
+ * ```
41
+ */
42
+ export type Authenticate = (
43
+ request: Request,
44
+ message?: unknown,
45
+ ) => Actor | null | Promise<Actor | null>
46
+
47
+ // The bundles signed by this handler: every bundle's `$actor` replaced by
48
+ // this writer, or removed when there is none. What a client sent is never
49
+ // kept. It is defined in @yaks/graph beside `land` — signing a write is a
50
+ // fact about a graph, not about HTTP — and re-exported here, where `/apply`
51
+ // reaches for it.
52
+ export { signed } from '@yaks/graph/provenance'
53
+
54
+ /** The header a request names the run behind it in: the fleet's own name
55
+ * for the instrument behind a write, never a credential. */
56
+ export let VIA = 'x-via'
57
+
58
+ /**
59
+ * Callers named by another graph's door: a request naming a run in `x-via` is
60
+ * whoever the door at `url` says it is (its `GET /who`, read for its `by` and
61
+ * `via` alone), so a graph that keeps no sessions of its own, such as the
62
+ * box's tracker, signs a session's writes as the graph that keeps them does.
63
+ * A request naming none is nobody here.
64
+ *
65
+ * ```ts
66
+ * import { api, asking } from '@yaks/api'
67
+ * import { graph } from '@yaks/graph'
68
+ * import { ram } from '@yaks/ram'
69
+ * import { loadVocab } from '@yaks/vocab'
70
+ * import { assertEquals } from '@std/assert'
71
+ *
72
+ * const vocab = loadVocab({ $defs: {} })
73
+ * const box = api({
74
+ * graph: graph({ vocab, storage: ram(vocab) }),
75
+ * authenticate: (r) => ({ by: 'agent', via: r.headers.get('x-via')! }),
76
+ * })
77
+ * const who = asking('http://box.test', async (url, init) =>
78
+ * box(new Request(url, init)))
79
+ * const request = new Request('http://tracker.test/apply', {
80
+ * headers: { 'x-via': 'run' },
81
+ * })
82
+ * assertEquals(await who(request), { by: 'agent', via: 'run' })
83
+ * assertEquals(await who(new Request('http://tracker.test/apply')), null)
84
+ * ```
85
+ */
86
+ export let asking = (url: string, go: typeof fetch = fetch): Authenticate => {
87
+ let at = `${url.replace(/\/$/, '')}/who`
88
+ return async (request) => {
89
+ let via = request.headers.get(VIA)
90
+ if (!via) return null
91
+ let response = await go(at, { headers: { [VIA]: via } })
92
+ if (!response.ok) {
93
+ await response.body?.cancel()
94
+ throw new Error(`${at} answered ${response.status}`)
95
+ }
96
+ // The door may say more of its caller than who they are (route.ts
97
+ // `Standing`); only who they are signs a write here.
98
+ let said = await response.json() as Actor | null
99
+ return said?.by || said?.via
100
+ ? {
101
+ ...said.by ? { by: said.by } : {},
102
+ ...said.via ? { via: said.via } : {},
103
+ }
104
+ : null
105
+ }
106
+ }
package/address.js ADDED
@@ -0,0 +1,42 @@
1
+ // Where a client on this machine finds the server a config serves, exported
2
+ // as `@yaks/api/address`. It imports nothing, so a client that only needs the
3
+ // address (a `yak` command asking the running server, @yaks/cli ./warm.ts)
4
+ // loads none of the server.
5
+ /** The port `serve` listens on when neither the call nor the config names
6
+ * one. */ export let PORT = 8787;
7
+ /** The interface `serve` binds when neither the call nor the config names
8
+ * one: this machine alone. A server that answers every request as the machine
9
+ * itself (@yaks/cli's `doorman`) is offered to a network only when a config
10
+ * says so. */ export let HOSTNAME = '127.0.0.1';
11
+ /** The header a request names the graph file it means in: a server serving
12
+ * another answers it 421 and runs nothing (./tools.ts), so a command whose
13
+ * config shares a port with another graph's never reaches that graph. */ export let DB = 'x-yak-db';
14
+ /** The header a request asks for a tool's answer drawn as text in, as the
15
+ * server's own views draw it (@yaks/mcp `Options.text`): what a command not
16
+ * writing to a terminal prints, sent so the command loads no views. A server
17
+ * that drew it says the header back; one that did not answers as it does
18
+ * every client. */ export let TEXT = 'x-yak-text';
19
+ /** Where a client on this machine reaches the server a config serves: its
20
+ * port, else {@link PORT}, at its hostname, or this machine's own address
21
+ * where it names none or every interface.
22
+ *
23
+ * ```ts
24
+ * import { assertEquals } from '@std/assert'
25
+ * import { served } from '@yaks/api/address'
26
+ *
27
+ * assertEquals(served({}), 'http://127.0.0.1:8787')
28
+ * assertEquals(
29
+ * served({ port: 5173, hostname: '0.0.0.0' }),
30
+ * 'http://127.0.0.1:5173',
31
+ * )
32
+ * ```
33
+ */ export let served = (config)=>{
34
+ let { hostname = HOSTNAME, port = PORT } = config;
35
+ let any = [
36
+ '0.0.0.0',
37
+ '::',
38
+ '[::]'
39
+ ].includes(hostname);
40
+ return `http://${any ? HOSTNAME : hostname}:${port}`;
41
+ };
42
+ //# sourceMappingURL=address.js.map
package/address.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"address.js","sources":["./address.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,8EAA8E;AAC9E,2EAA2E;AAC3E,4BAA4B;AAE5B;QACQ,GACR,OAAO,IAAI,OAAO,KAAI;AAEtB;;;YAGY,GACZ,OAAO,IAAI,WAAW,YAAW;AAEjC;;uEAEuE,GACvE,OAAO,IAAI,KAAK,WAAU;AAE1B;;;;iBAIiB,GACjB,OAAO,IAAI,OAAO,aAAY;AAE9B;;;;;;;;;;;;;;CAcC,GACD,OAAO,IAAI,SAAS,CAClB;EAEA,IAAI,EAAE,WAAW,QAAQ,EAAE,OAAO,IAAI,EAAE,GAAG;EAC3C,IAAI,MAAM;IAAC;IAAW;IAAM;GAAO,CAAC,QAAQ,CAAC;EAC7C,OAAO,CAAC,OAAO,EAAE,MAAM,WAAW,SAAS,CAAC,EAAE,MAAM;AACtD,EAAC"}
package/address.ts ADDED
@@ -0,0 +1,49 @@
1
+ // Where a client on this machine finds the server a config serves, exported
2
+ // as `@yaks/api/address`. It imports nothing, so a client that only needs the
3
+ // address (a `yak` command asking the running server, @yaks/cli ./warm.ts)
4
+ // loads none of the server.
5
+
6
+ /** The port `serve` listens on when neither the call nor the config names
7
+ * one. */
8
+ export let PORT = 8787
9
+
10
+ /** The interface `serve` binds when neither the call nor the config names
11
+ * one: this machine alone. A server that answers every request as the machine
12
+ * itself (@yaks/cli's `doorman`) is offered to a network only when a config
13
+ * says so. */
14
+ export let HOSTNAME = '127.0.0.1'
15
+
16
+ /** The header a request names the graph file it means in: a server serving
17
+ * another answers it 421 and runs nothing (./tools.ts), so a command whose
18
+ * config shares a port with another graph's never reaches that graph. */
19
+ export let DB = 'x-yak-db'
20
+
21
+ /** The header a request asks for a tool's answer drawn as text in, as the
22
+ * server's own views draw it (@yaks/mcp `Options.text`): what a command not
23
+ * writing to a terminal prints, sent so the command loads no views. A server
24
+ * that drew it says the header back; one that did not answers as it does
25
+ * every client. */
26
+ export let TEXT = 'x-yak-text'
27
+
28
+ /** Where a client on this machine reaches the server a config serves: its
29
+ * port, else {@link PORT}, at its hostname, or this machine's own address
30
+ * where it names none or every interface.
31
+ *
32
+ * ```ts
33
+ * import { assertEquals } from '@std/assert'
34
+ * import { served } from '@yaks/api/address'
35
+ *
36
+ * assertEquals(served({}), 'http://127.0.0.1:8787')
37
+ * assertEquals(
38
+ * served({ port: 5173, hostname: '0.0.0.0' }),
39
+ * 'http://127.0.0.1:5173',
40
+ * )
41
+ * ```
42
+ */
43
+ export let served = (
44
+ config: { port?: number; hostname?: string },
45
+ ): string => {
46
+ let { hostname = HOSTNAME, port = PORT } = config
47
+ let any = ['0.0.0.0', '::', '[::]'].includes(hostname)
48
+ return `http://${any ? HOSTNAME : hostname}:${port}`
49
+ }
package/admission.js ADDED
@@ -0,0 +1,71 @@
1
+ // One socket's peer relay allowance. The vocabulary sets a component's pace;
2
+ // each entity gets that pace independently, and a transport ceiling bounds
3
+ // the whole connection even when it moves many entities.
4
+ let BURST = 2;
5
+ let CEILING = 16 // at most about sixty unpaced messages a second
6
+ ;
7
+ let MAX_PATCHES = 64;
8
+ let STRIKES = 8;
9
+ let KEYS = 4096;
10
+ /** Admit a whole relay message or none of it. A rejected patch never replaces
11
+ * the last value the relay accepted. A sustained sender loses its socket. */ export let admission = (pace, now = ()=>Date.now())=>{
12
+ let buckets = new Map();
13
+ let bad = 0;
14
+ let since = 0;
15
+ let refuse = (at)=>{
16
+ if (at - since >= 1000) bad = 0, since = at;
17
+ return ++bad >= STRIKES ? 'close' : 'skip';
18
+ };
19
+ return (bundles)=>{
20
+ let at = now();
21
+ if (bundles.length > MAX_PATCHES) return 'close';
22
+ let counts = new Map([
23
+ [
24
+ '',
25
+ {
26
+ cost: 1,
27
+ span: CEILING
28
+ }
29
+ ]
30
+ ]);
31
+ let patches = 0;
32
+ for (let b of bundles){
33
+ // Let the relay's normal admission report malformed bundles.
34
+ if (!b || typeof b != 'object') continue;
35
+ for (let [comp, patch] of Object.entries(b)){
36
+ if (comp == 'entity' || comp.startsWith('$')) continue;
37
+ if (++patches > MAX_PATCHES) return 'close';
38
+ let span = pace(comp);
39
+ if (patch == null || span == null) continue;
40
+ let key = JSON.stringify([
41
+ b.entity?.eid,
42
+ comp
43
+ ]);
44
+ counts.set(key, {
45
+ cost: (counts.get(key)?.cost ?? 0) + 1,
46
+ span
47
+ });
48
+ }
49
+ }
50
+ let next = new Map();
51
+ for (let [key, { cost, span }] of counts){
52
+ let was = buckets.get(key) ?? {
53
+ at,
54
+ left: BURST
55
+ };
56
+ let left = Math.min(BURST, was.left + Math.max(0, at - was.at) / span);
57
+ if (left < cost) return refuse(at);
58
+ next.set(key, {
59
+ at,
60
+ left: left - cost
61
+ });
62
+ }
63
+ for (let [key, bucket] of next){
64
+ buckets.delete(key);
65
+ buckets.set(key, bucket);
66
+ }
67
+ while(buckets.size > KEYS)buckets.delete(buckets.keys().next().value);
68
+ return 'accept';
69
+ };
70
+ };
71
+ //# sourceMappingURL=admission.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"admission.js","sources":["./admission.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,2EAA2E;AAC3E,yDAAyD;AAOzD,IAAI,QAAQ;AACZ,IAAI,UAAU,GAAG,gDAAgD;;AACjE,IAAI,cAAc;AAClB,IAAI,UAAU;AACd,IAAI,OAAO;AAEX;2EAC2E,GAC3E,OAAO,IAAI,YAAY,CACrB,MACA,MAAoB,IAAM,KAAK,GAAG,EAAE;EAEpC,IAAI,UAAU,IAAI;EAClB,IAAI,MAAM;EACV,IAAI,QAAQ;EAEZ,IAAI,SAAS,CAAC;IACZ,IAAI,KAAK,SAAS,MAAM,MAAM,GAAG,QAAQ;IACzC,OAAO,EAAE,OAAO,UAAU,UAAU;EACtC;EAEA,OAAO,CAAC;IACN,IAAI,KAAK;IACT,IAAI,QAAQ,MAAM,GAAG,aAAa,OAAO;IACzC,IAAI,SAAS,IAAI,IAA4C;MAC3D;QAAC;QAAI;UAAE,MAAM;UAAG,MAAM;QAAQ;OAAE;KACjC;IACD,IAAI,UAAU;IACd,KAAK,IAAI,KAAK,QAAS;MACrB,6DAA6D;MAC7D,IAAI,CAAC,KAAK,OAAO,KAAK,UAAU;MAChC,KAAK,IAAI,CAAC,MAAM,MAAM,IAAI,OAAO,OAAO,CAAC,GAAI;QAC3C,IAAI,QAAQ,YAAY,KAAK,UAAU,CAAC,MAAM;QAC9C,IAAI,EAAE,UAAU,aAAa,OAAO;QACpC,IAAI,OAAO,KAAK;QAChB,IAAI,SAAS,QAAQ,QAAQ,MAAM;QACnC,IAAI,MAAM,KAAK,SAAS,CAAC;UAAC,EAAE,MAAM,EAAE;UAAK;SAAK;QAC9C,OAAO,GAAG,CAAC,KAAK;UAAE,MAAM,CAAC,OAAO,GAAG,CAAC,MAAM,QAAQ,CAAC,IAAI;UAAG;QAAK;MACjE;IACF;IACA,IAAI,OAAO,IAAI;IACf,KAAK,IAAI,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,IAAI,OAAQ;MACxC,IAAI,MAAM,QAAQ,GAAG,CAAC,QAAQ;QAAE;QAAI,MAAM;MAAM;MAChD,IAAI,OAAO,KAAK,GAAG,CAAC,OAAO,IAAI,IAAI,GAAG,KAAK,GAAG,CAAC,GAAG,KAAK,IAAI,EAAE,IAAI;MACjE,IAAI,OAAO,MAAM,OAAO,OAAO;MAC/B,KAAK,GAAG,CAAC,KAAK;QAAE;QAAI,MAAM,OAAO;MAAK;IACxC;IACA,KAAK,IAAI,CAAC,KAAK,OAAO,IAAI,KAAM;MAC9B,QAAQ,MAAM,CAAC;MACf,QAAQ,GAAG,CAAC,KAAK;IACnB;IACA,MAAO,QAAQ,IAAI,GAAG,KAAM,QAAQ,MAAM,CAAC,QAAQ,IAAI,GAAG,IAAI,GAAG,KAAK;IACtE,OAAO;EACT;AACF,EAAC"}
package/admission.ts ADDED
@@ -0,0 +1,64 @@
1
+ // One socket's peer relay allowance. The vocabulary sets a component's pace;
2
+ // each entity gets that pace independently, and a transport ceiling bounds
3
+ // the whole connection even when it moves many entities.
4
+
5
+ import type { Bundle } from 'jsr:@yaks/graph@0.2.36'
6
+
7
+ type Bucket = { at: number; left: number }
8
+ export type Verdict = 'accept' | 'skip' | 'close'
9
+
10
+ let BURST = 2
11
+ let CEILING = 16 // at most about sixty unpaced messages a second
12
+ let MAX_PATCHES = 64
13
+ let STRIKES = 8
14
+ let KEYS = 4096
15
+
16
+ /** Admit a whole relay message or none of it. A rejected patch never replaces
17
+ * the last value the relay accepted. A sustained sender loses its socket. */
18
+ export let admission = (
19
+ pace: (comp: string) => number | null,
20
+ now: () => number = () => Date.now(),
21
+ ): (bundles: Bundle[]) => Verdict => {
22
+ let buckets = new Map<string, Bucket>()
23
+ let bad = 0
24
+ let since = 0
25
+
26
+ let refuse = (at: number): Verdict => {
27
+ if (at - since >= 1000) bad = 0, since = at
28
+ return ++bad >= STRIKES ? 'close' : 'skip'
29
+ }
30
+
31
+ return (bundles) => {
32
+ let at = now()
33
+ if (bundles.length > MAX_PATCHES) return 'close'
34
+ let counts = new Map<string, { cost: number; span: number }>([
35
+ ['', { cost: 1, span: CEILING }],
36
+ ])
37
+ let patches = 0
38
+ for (let b of bundles) {
39
+ // Let the relay's normal admission report malformed bundles.
40
+ if (!b || typeof b != 'object') continue
41
+ for (let [comp, patch] of Object.entries(b)) {
42
+ if (comp == 'entity' || comp.startsWith('$')) continue
43
+ if (++patches > MAX_PATCHES) return 'close'
44
+ let span = pace(comp)
45
+ if (patch == null || span == null) continue
46
+ let key = JSON.stringify([b.entity?.eid, comp])
47
+ counts.set(key, { cost: (counts.get(key)?.cost ?? 0) + 1, span })
48
+ }
49
+ }
50
+ let next = new Map<string, Bucket>()
51
+ for (let [key, { cost, span }] of counts) {
52
+ let was = buckets.get(key) ?? { at, left: BURST }
53
+ let left = Math.min(BURST, was.left + Math.max(0, at - was.at) / span)
54
+ if (left < cost) return refuse(at)
55
+ next.set(key, { at, left: left - cost })
56
+ }
57
+ for (let [key, bucket] of next) {
58
+ buckets.delete(key)
59
+ buckets.set(key, bucket)
60
+ }
61
+ while (buckets.size > KEYS) buckets.delete(buckets.keys().next().value!)
62
+ return 'accept'
63
+ }
64
+ }
package/asset.js ADDED
@@ -0,0 +1,37 @@
1
+ // A file a package ships beside its modules, exported as `@yaks/api/asset`:
2
+ // a page, a stylesheet, an icon, what a route answers with. Read through the
3
+ // module loader, as an import of the file's text or bytes, wherever the
4
+ // package is served from: a checkout reads its own file, and a package from
5
+ // JSR reads Deno's module cache, which fetches it from jsr.io once and keeps
6
+ // it. A `fetch` of the same address goes to jsr.io in every process, and fails
7
+ // offline. The workspace runs with Deno's `raw-imports`, which these need.
8
+ // A browser has no text or bytes imports, so a page reads a web address with
9
+ // `fetch`, which its own cache serves: the kit's stylesheets on an app page.
10
+ import { importing } from "@yaks/fp/imports";
11
+ let fetched = (url)=>!('Deno' in globalThis) && /^https?:$/.test(url.protocol);
12
+ let raw = async (url, type)=>(await importing(url.href, undefined, {
13
+ with: {
14
+ type
15
+ }
16
+ })).default;
17
+ /** The text of the file at `url`.
18
+ *
19
+ * ```ts
20
+ * import { assert } from '@std/assert'
21
+ * assert((await text(new URL('./asset.ts', import.meta.url))).includes('raw-imports'))
22
+ * ```
23
+ */ export let text = async (url)=>fetched(url) ? await (await answered(url)).text() : await raw(url, 'text');
24
+ /** The bytes of the file at `url`.
25
+ *
26
+ * ```ts
27
+ * import { assertEquals } from '@std/assert'
28
+ * assertEquals((await bytes(new URL('data:,yak'))).length, 3)
29
+ * ```
30
+ */ export let bytes = async (url)=>new Uint8Array(fetched(url) ? await (await answered(url)).arrayBuffer() : await raw(url, 'bytes'));
31
+ // A page's fetch of a file it ships, refused rather than read as its error page.
32
+ let answered = async (url)=>{
33
+ let res = await fetch(url);
34
+ if (!res.ok) throw new Error(`${url.href} answered ${res.status}`);
35
+ return res;
36
+ };
37
+ //# sourceMappingURL=asset.js.map
package/asset.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"asset.js","sources":["./asset.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,6EAA6E;AAC7E,wEAAwE;AACxE,4EAA4E;AAC5E,6EAA6E;AAC7E,+EAA+E;AAC/E,2EAA2E;AAC3E,6EAA6E;AAC7E,6EAA6E;AAC7E,SAAS,SAAS,gCAAqC;AAEvD,IAAI,UAAU,CAAC,MACb,CAAC,CAAC,UAAU,UAAU,KAAK,YAAY,IAAI,CAAC,IAAI,QAAQ;AAE1D,IAAI,MAAM,OAAO,KAAU,OACzB,CAAC,MAAM,UAAU,IAAI,IAAI,EAAE,WAAW;IAAE,MAAM;MAAE;IAAK;EAAE,EAAE,EAAE,OAAO;AAEpE;;;;;;CAMC,GACD,OAAO,IAAI,OAAO,OAAO,MACvB,QAAQ,OAAO,MAAM,CAAC,MAAM,SAAS,IAAI,EAAE,IAAI,KAAK,MAAM,IAAI,KAAK,QAAO;AAE5E;;;;;;CAMC,GACD,OAAO,IAAI,QAAQ,OAAO,MACxB,IAAI,WACF,QAAQ,OACJ,MAAM,CAAC,MAAM,SAAS,IAAI,EAAE,WAAW,KACvC,MAAM,IAAI,KAAK,UACpB;AAEH,iFAAiF;AACjF,IAAI,WAAW,OAAO;EACpB,IAAI,MAAM,MAAM,MAAM;EACtB,IAAI,CAAC,IAAI,EAAE,EAAE,MAAM,IAAI,MAAM,GAAG,IAAI,IAAI,CAAC,UAAU,EAAE,IAAI,MAAM,EAAE;EACjE,OAAO;AACT"}
package/asset.ts ADDED
@@ -0,0 +1,47 @@
1
+ // A file a package ships beside its modules, exported as `@yaks/api/asset`:
2
+ // a page, a stylesheet, an icon, what a route answers with. Read through the
3
+ // module loader, as an import of the file's text or bytes, wherever the
4
+ // package is served from: a checkout reads its own file, and a package from
5
+ // JSR reads Deno's module cache, which fetches it from jsr.io once and keeps
6
+ // it. A `fetch` of the same address goes to jsr.io in every process, and fails
7
+ // offline. The workspace runs with Deno's `raw-imports`, which these need.
8
+ // A browser has no text or bytes imports, so a page reads a web address with
9
+ // `fetch`, which its own cache serves: the kit's stylesheets on an app page.
10
+ import { importing } from '@yaks/fp/imports'
11
+
12
+ let fetched = (url: URL) =>
13
+ !('Deno' in globalThis) && /^https?:$/.test(url.protocol)
14
+
15
+ let raw = async (url: URL, type: 'text' | 'bytes') =>
16
+ (await importing(url.href, undefined, { with: { type } })).default
17
+
18
+ /** The text of the file at `url`.
19
+ *
20
+ * ```ts
21
+ * import { assert } from '@std/assert'
22
+ * assert((await text(new URL('./asset.ts', import.meta.url))).includes('raw-imports'))
23
+ * ```
24
+ */
25
+ export let text = async (url: URL): Promise<string> =>
26
+ fetched(url) ? await (await answered(url)).text() : await raw(url, 'text')
27
+
28
+ /** The bytes of the file at `url`.
29
+ *
30
+ * ```ts
31
+ * import { assertEquals } from '@std/assert'
32
+ * assertEquals((await bytes(new URL('data:,yak'))).length, 3)
33
+ * ```
34
+ */
35
+ export let bytes = async (url: URL): Promise<Uint8Array<ArrayBuffer>> =>
36
+ new Uint8Array(
37
+ fetched(url)
38
+ ? await (await answered(url)).arrayBuffer()
39
+ : await raw(url, 'bytes'),
40
+ )
41
+
42
+ // A page's fetch of a file it ships, refused rather than read as its error page.
43
+ let answered = async (url: URL) => {
44
+ let res = await fetch(url)
45
+ if (!res.ok) throw new Error(`${url.href} answered ${res.status}`)
46
+ return res
47
+ }
package/batches.js ADDED
@@ -0,0 +1,92 @@
1
+ import { sha256 } from "@yaks/graph";
2
+ import { stringify } from "@yaks/vocab/wire";
3
+ import { WRITE_BYTES, writeSize } from "./body.js";
4
+ import { IDEMPOTENCY } from "./headers.js";
5
+ import { INTENT, Pending, ROOM } from "./log.js";
6
+ let encoder = new TextEncoder();
7
+ // A reference to another row in the request can depend on that row being
8
+ // visible in the same transaction. Keep the entire interval together.
9
+ let spans = (bundles)=>{
10
+ let ids = new Map(bundles.map(({ entity }, i)=>[
11
+ entity?.eid,
12
+ [
13
+ i,
14
+ i
15
+ ]
16
+ ]));
17
+ let visit = (value, i)=>{
18
+ if (typeof value == 'string') {
19
+ let span = ids.get(value);
20
+ if (span) {
21
+ span[0] = Math.min(span[0], i);
22
+ span[1] = Math.max(span[1], i);
23
+ }
24
+ } else if (value && typeof value == 'object' && !ArrayBuffer.isView(value)) {
25
+ for (let part of Object.values(value))visit(part, i);
26
+ }
27
+ };
28
+ for (let [i, bundle] of bundles.entries())visit(bundle, i);
29
+ let ends = bundles.map((_, i)=>i);
30
+ for (let [from, to] of ids.values())ends[from] = Math.max(ends[from], to);
31
+ return ends;
32
+ };
33
+ /** Encode ordered write batches that fit the Store's receipt log. Keep
34
+ * dependent rows and their aliases in the same transaction. */ export let writeBatches = (bundles, room = ROOM)=>{
35
+ let rows = bundles.map((bundle)=>stringify(bundle));
36
+ let sizes = rows.map((row)=>encoder.encode(row).byteLength + 1);
37
+ if (bundles.length <= 2_000 && sizes.reduce((sum, size)=>sum + size, 1) <= room) {
38
+ return [
39
+ `[${rows.join(',')}]`
40
+ ];
41
+ }
42
+ let ends = spans(bundles);
43
+ let batches = [];
44
+ let begin = 0, bytes = 1;
45
+ for(let i = 0; i < rows.length;){
46
+ let from = i, end = ends[i], size = 0;
47
+ while(i <= end){
48
+ end = Math.max(end, ends[i]);
49
+ size += sizes[i++];
50
+ }
51
+ if (size + 1 > WRITE_BYTES) throw writeSize();
52
+ if (from > begin && (bytes + size > room || i - begin > 2_000)) {
53
+ batches.push(`[${rows.slice(begin, from).join(',')}]`);
54
+ begin = from;
55
+ bytes = 1;
56
+ }
57
+ bytes += size;
58
+ }
59
+ batches.push(`[${rows.slice(begin).join(',')}]`);
60
+ return batches;
61
+ };
62
+ /** Send a large write a batch at a time, retaining a separate receipt for
63
+ * each batch when the caller supplied a key. */ export let applyBatches = async (bundles, headers, send)=>{
64
+ let batches = writeBatches(bundles);
65
+ if (batches.length == 1) return await send(batches[0], headers);
66
+ let tagged = new Headers(headers);
67
+ let key = tagged.get(IDEMPOTENCY);
68
+ if (key && !tagged.has(INTENT)) {
69
+ tagged.set(INTENT, sha256(batches.map(sha256).join('')));
70
+ }
71
+ let applied = [];
72
+ let pending;
73
+ for (let [i, body] of batches.entries()){
74
+ if (key && i) tagged.set(IDEMPOTENCY, `${key}:part:${i}`);
75
+ try {
76
+ for (let row of (await send(body, Object.fromEntries(tagged)))){
77
+ applied.push(row);
78
+ }
79
+ } catch (error) {
80
+ if (!(error instanceof Pending)) {
81
+ if (i && error instanceof Error) Object.assign(error, {
82
+ partial: true
83
+ });
84
+ throw error;
85
+ }
86
+ pending ??= error;
87
+ }
88
+ }
89
+ if (pending) throw pending;
90
+ return applied;
91
+ };
92
+ //# sourceMappingURL=batches.js.map
package/batches.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batches.js","sources":["./batches.ts"],"names":[],"mappings":"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"}
package/batches.ts ADDED
@@ -0,0 +1,96 @@
1
+ import { type Bundle, sha256 } from '@yaks/graph'
2
+ import { stringify } from '@yaks/vocab/wire'
3
+ import { WRITE_BYTES, writeSize } from './body.js'
4
+ import { IDEMPOTENCY } from './headers.js'
5
+ import { INTENT, Pending, ROOM } from './log.js'
6
+
7
+ let encoder = new TextEncoder()
8
+
9
+ // A reference to another row in the request can depend on that row being
10
+ // visible in the same transaction. Keep the entire interval together.
11
+ let spans = (bundles: Bundle[]) => {
12
+ let ids = new Map(bundles.map(({ entity }, i) => [entity?.eid, [i, i]]))
13
+ let visit = (value: unknown, i: number): void => {
14
+ if (typeof value == 'string') {
15
+ let span = ids.get(value)
16
+ if (span) {
17
+ span[0] = Math.min(span[0], i)
18
+ span[1] = Math.max(span[1], i)
19
+ }
20
+ } else if (
21
+ value && typeof value == 'object' && !ArrayBuffer.isView(value)
22
+ ) {
23
+ for (let part of Object.values(value)) visit(part, i)
24
+ }
25
+ }
26
+ for (let [i, bundle] of bundles.entries()) visit(bundle, i)
27
+ let ends = bundles.map((_, i) => i)
28
+ for (let [from, to] of ids.values()) ends[from] = Math.max(ends[from], to)
29
+ return ends
30
+ }
31
+
32
+ /** Encode ordered write batches that fit the Store's receipt log. Keep
33
+ * dependent rows and their aliases in the same transaction. */
34
+ export let writeBatches = (bundles: Bundle[], room = ROOM): string[] => {
35
+ let rows = bundles.map((bundle) => stringify(bundle))
36
+ let sizes = rows.map((row) => encoder.encode(row).byteLength + 1)
37
+ if (
38
+ bundles.length <= 2_000 &&
39
+ sizes.reduce((sum, size) => sum + size, 1) <= room
40
+ ) {
41
+ return [`[${rows.join(',')}]`]
42
+ }
43
+ let ends = spans(bundles)
44
+ let batches: string[] = []
45
+ let begin = 0, bytes = 1
46
+ for (let i = 0; i < rows.length;) {
47
+ let from = i, end = ends[i], size = 0
48
+ while (i <= end) {
49
+ end = Math.max(end, ends[i])
50
+ size += sizes[i++]
51
+ }
52
+ if (size + 1 > WRITE_BYTES) throw writeSize()
53
+ if (from > begin && (bytes + size > room || i - begin > 2_000)) {
54
+ batches.push(`[${rows.slice(begin, from).join(',')}]`)
55
+ begin = from
56
+ bytes = 1
57
+ }
58
+ bytes += size
59
+ }
60
+ batches.push(`[${rows.slice(begin).join(',')}]`)
61
+ return batches
62
+ }
63
+
64
+ /** Send a large write a batch at a time, retaining a separate receipt for
65
+ * each batch when the caller supplied a key. */
66
+ export let applyBatches = async (
67
+ bundles: Bundle[],
68
+ headers: Record<string, string>,
69
+ send: (body: string, headers: Record<string, string>) => Promise<Bundle[]>,
70
+ ): Promise<Bundle[]> => {
71
+ let batches = writeBatches(bundles)
72
+ if (batches.length == 1) return await send(batches[0], headers)
73
+ let tagged = new Headers(headers)
74
+ let key = tagged.get(IDEMPOTENCY)
75
+ if (key && !tagged.has(INTENT)) {
76
+ tagged.set(INTENT, sha256(batches.map(sha256).join('')))
77
+ }
78
+ let applied: Bundle[] = []
79
+ let pending: Pending | undefined
80
+ for (let [i, body] of batches.entries()) {
81
+ if (key && i) tagged.set(IDEMPOTENCY, `${key}:part:${i}`)
82
+ try {
83
+ for (let row of await send(body, Object.fromEntries(tagged))) {
84
+ applied.push(row)
85
+ }
86
+ } catch (error) {
87
+ if (!(error instanceof Pending)) {
88
+ if (i && error instanceof Error) Object.assign(error, { partial: true })
89
+ throw error
90
+ }
91
+ pending ??= error
92
+ }
93
+ }
94
+ if (pending) throw pending
95
+ return applied
96
+ }