@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/timing.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// The client's side of `Server-Timing`: a `fetch` that says one line per
|
|
2
|
+
// response, with the numbers the server sent, for `yak --timing` and for any
|
|
3
|
+
// other program that wants to see where a request's time went.
|
|
4
|
+
/** A `fetch` that prints one line per response:
|
|
5
|
+
*
|
|
6
|
+
* POST /mcp 200 door;dur=12, hops;dur=3, total;dur=41
|
|
7
|
+
*
|
|
8
|
+
* The numbers are the server's own `Server-Timing` header (yaks.app writes it
|
|
9
|
+
* in workers/yak/timing.ts), printed exactly as they arrived, so this line and
|
|
10
|
+
* a `curl -i` agree. A server that sends no such header still gets a line. */ export let timed = (say, go = (r)=>fetch(r))=>async (request)=>{
|
|
11
|
+
let res = await go(request);
|
|
12
|
+
let at = new URL(request.url);
|
|
13
|
+
let entries = res.headers.get('server-timing');
|
|
14
|
+
say(`${request.method} ${at.pathname}${at.search} ${res.status}${entries ? ` ${entries}` : ''}`);
|
|
15
|
+
return res;
|
|
16
|
+
};
|
|
17
|
+
//# sourceMappingURL=timing.js.map
|
package/timing.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"timing.js","sources":["./timing.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,6EAA6E;AAC7E,+DAA+D;AAE/D;;;;;;4EAM4E,GAC5E,OAAO,IAAI,QAAQ,CACjB,KACA,KAAyD,CAAC,IAAM,MAAM,EAAE,GAE1E,OAAO;IACL,IAAI,MAAM,MAAM,GAAG;IACnB,IAAI,KAAK,IAAI,IAAI,QAAQ,GAAG;IAC5B,IAAI,UAAU,IAAI,OAAO,CAAC,GAAG,CAAC;IAC9B,IACE,GAAG,QAAQ,MAAM,CAAC,CAAC,EAAE,GAAG,QAAQ,GAAG,GAAG,MAAM,CAAC,CAAC,EAAE,IAAI,MAAM,GACxD,UAAU,CAAC,EAAE,EAAE,SAAS,GAAG,IAC3B;IAEJ,OAAO;EACT,EAAC"}
|
package/timing.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// The client's side of `Server-Timing`: a `fetch` that says one line per
|
|
2
|
+
// response, with the numbers the server sent, for `yak --timing` and for any
|
|
3
|
+
// other program that wants to see where a request's time went.
|
|
4
|
+
|
|
5
|
+
/** A `fetch` that prints one line per response:
|
|
6
|
+
*
|
|
7
|
+
* POST /mcp 200 door;dur=12, hops;dur=3, total;dur=41
|
|
8
|
+
*
|
|
9
|
+
* The numbers are the server's own `Server-Timing` header (yaks.app writes it
|
|
10
|
+
* in workers/yak/timing.ts), printed exactly as they arrived, so this line and
|
|
11
|
+
* a `curl -i` agree. A server that sends no such header still gets a line. */
|
|
12
|
+
export let timed = (
|
|
13
|
+
say: (line: string) => void,
|
|
14
|
+
go: (request: Request) => Response | Promise<Response> = (r) => fetch(r),
|
|
15
|
+
) =>
|
|
16
|
+
async (request: Request): Promise<Response> => {
|
|
17
|
+
let res = await go(request)
|
|
18
|
+
let at = new URL(request.url)
|
|
19
|
+
let entries = res.headers.get('server-timing')
|
|
20
|
+
say(
|
|
21
|
+
`${request.method} ${at.pathname}${at.search} ${res.status}${
|
|
22
|
+
entries ? ` ${entries}` : ''
|
|
23
|
+
}`,
|
|
24
|
+
)
|
|
25
|
+
return res
|
|
26
|
+
}
|
package/tools.js
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
// The implementation behind the `tool: true` declaration in ./vocab.json,
|
|
2
|
+
// exported as `@yaks/api/tools`.
|
|
3
|
+
//
|
|
4
|
+
// `serve` is the only one, and it is what makes one process the one answering
|
|
5
|
+
// HTTP for a graph. It is a tool rather than a command of the `yak` program,
|
|
6
|
+
// because listening on a port is something a package contributes, the same way
|
|
7
|
+
// a package contributes components, rules and routes: `yak` reads the config
|
|
8
|
+
// and loads the plugins, and this package brings the verb. A config whose
|
|
9
|
+
// plugins do not include @yaks/api has no `serve` to run, and a config that
|
|
10
|
+
// names it can be served by anything that lists its tools.
|
|
11
|
+
//
|
|
12
|
+
// It acts on the machine rather than on the graph — it binds a port there —
|
|
13
|
+
// the way `land` acts on a checkout, so it belongs to the process that opened
|
|
14
|
+
// the graph in the first place. What it listens with is already assembled:
|
|
15
|
+
// `host.handler` is this package's own doors with the listed plugins' routes
|
|
16
|
+
// in front of them, built by ./routes.ts when the host was composed.
|
|
17
|
+
//
|
|
18
|
+
// A call that does not return. The runner writes the call row and claims it
|
|
19
|
+
// `running` before the tool starts, and writes the result and `done` when it
|
|
20
|
+
// returns (@yaks/tools). This one returns when the server stops, so the record
|
|
21
|
+
// of a server that is up is a call still marked `running`, and the record of
|
|
22
|
+
// one that has stopped is its result, carrying the address it answered on and
|
|
23
|
+
// how long it answered for. Two consequences worth knowing: nothing is printed
|
|
24
|
+
// until it stops, which is why the address is reported on stderr as soon as
|
|
25
|
+
// the port is bound; and a server is never run again by a sweep. Stopped by a
|
|
26
|
+
// signal, it stops taking requests and closes its sockets, lets the requests
|
|
27
|
+
// in flight finish for a grace of seconds, then cancels reads, cuts every
|
|
28
|
+
// answer still streaming that no admitted write is producing (an MCP call's
|
|
29
|
+
// event stream), lets go of a tool still running, and waits for admitted
|
|
30
|
+
// writes before returning. The reader then closes after the request owners
|
|
31
|
+
// finish, preserving edits. A killed process leaves its call claimed;
|
|
32
|
+
// the next server closes that process and interrupts the call (host.ts `bury`).
|
|
33
|
+
//
|
|
34
|
+
// A restart is invisible when the replacement answers before this one stops
|
|
35
|
+
// taking requests. `share` lets two servers listen on one port at once, and
|
|
36
|
+
// `ready` names a file written once this one is listening, which is what a
|
|
37
|
+
// supervisor waits on before stopping the old one (@yaks/cli `restart`).
|
|
38
|
+
// Sharing is asked for, never assumed: a second server started by mistake on a
|
|
39
|
+
// taken port is refused rather than quietly handed half its requests.
|
|
40
|
+
import { requests } from "./requests.js";
|
|
41
|
+
import { argsOf } from "@yaks/graph/call";
|
|
42
|
+
import { CallError } from "@yaks/tools/errors";
|
|
43
|
+
import { denoListen, denoReady, rebuild } from "./deno.js";
|
|
44
|
+
import { secured } from "./access.js";
|
|
45
|
+
import { DB, HOSTNAME, PORT, served } from "./address.js";
|
|
46
|
+
export { HOSTNAME, PORT, served } from "./address.js";
|
|
47
|
+
/** Seconds a stopping server lets requests finish before cancelling reads
|
|
48
|
+
* and cutting streamed answers. Admitted writes drain even after this grace
|
|
49
|
+
* expires. */ export let GRACE = 10;
|
|
50
|
+
let seconds = (ms)=>`${Math.round(ms / 1000)}s`;
|
|
51
|
+
/** `handler`, serving the graph file `db`, for a request whose {@link DB}
|
|
52
|
+
* header names the file it means: the file this server serves is answered
|
|
53
|
+
* with the header said back, which is how a client knows the answer came from
|
|
54
|
+
* its graph, and any other is answered 421 Misdirected Request, with nothing
|
|
55
|
+
* run. A request naming none is answered as it always was.
|
|
56
|
+
*
|
|
57
|
+
* ```ts
|
|
58
|
+
* import { assertEquals } from '@std/assert'
|
|
59
|
+
* import { DB } from '@yaks/api/address'
|
|
60
|
+
* import { addressed } from '@yaks/api/tools'
|
|
61
|
+
*
|
|
62
|
+
* let handle = addressed(() => new Response('ok'), '/g.db')
|
|
63
|
+
* let asked = (db?: string) =>
|
|
64
|
+
* handle(new Request('http://x/', { headers: db ? { [DB]: db } : {} }))
|
|
65
|
+
* let mine = await asked('/g.db')
|
|
66
|
+
* assertEquals([mine.status, mine.headers.get(DB)], [200, '/g.db'])
|
|
67
|
+
* assertEquals((await asked()).headers.get(DB), null)
|
|
68
|
+
* assertEquals((await asked('/copy.db')).status, 421)
|
|
69
|
+
* ```
|
|
70
|
+
*/ export let addressed = (handler, db)=>async (request)=>{
|
|
71
|
+
let meant = request.headers.get(DB);
|
|
72
|
+
if (meant == null) return handler(request);
|
|
73
|
+
if (meant != db) {
|
|
74
|
+
return new Response('this server serves another graph', {
|
|
75
|
+
status: 421
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
let answer = await handler(request);
|
|
79
|
+
if (answer.status < 200) return answer;
|
|
80
|
+
let headers = new Headers(answer.headers);
|
|
81
|
+
headers.set(DB, meant);
|
|
82
|
+
return new Response(answer.body, {
|
|
83
|
+
status: answer.status,
|
|
84
|
+
statusText: answer.statusText,
|
|
85
|
+
headers
|
|
86
|
+
});
|
|
87
|
+
};
|
|
88
|
+
/** What a server says once it listens at `at`: the address and the graph,
|
|
89
|
+
* then each door a route says something about, at `origin`, where a client on
|
|
90
|
+
* this machine reaches it.
|
|
91
|
+
*
|
|
92
|
+
* ```ts
|
|
93
|
+
* import { assertEquals } from '@std/assert'
|
|
94
|
+
* import { listening } from '@yaks/api/tools'
|
|
95
|
+
*
|
|
96
|
+
* assertEquals(
|
|
97
|
+
* listening('http://0.0.0.0:80', 'http://127.0.0.1:80', {
|
|
98
|
+
* config: { db: 'g.db' },
|
|
99
|
+
* routes: [{ path: '/', says: 'the canvas' }, { path: '/ws' }],
|
|
100
|
+
* }),
|
|
101
|
+
* 'serve — http://0.0.0.0:80 · g.db\n' +
|
|
102
|
+
* ' http://127.0.0.1:80/ the canvas\n' +
|
|
103
|
+
* 'Ctrl-C stops it',
|
|
104
|
+
* )
|
|
105
|
+
* ```
|
|
106
|
+
*/ export let listening = (at, origin, host)=>{
|
|
107
|
+
let told = (host.routes ?? []).filter((r)=>r.says).sort((a, b)=>a.path.localeCompare(b.path));
|
|
108
|
+
let wide = Math.max(0, ...told.map((r)=>r.path.length));
|
|
109
|
+
return [
|
|
110
|
+
`serve — ${at} · ${host.config.db ?? 'no db'}`,
|
|
111
|
+
...told.map((r)=>` ${origin}${r.path.padEnd(wide)} ${r.says}`),
|
|
112
|
+
'Ctrl-C stops it'
|
|
113
|
+
].join('\n');
|
|
114
|
+
};
|
|
115
|
+
/** A handler whose ingress sets these headers, replacing caller input. */ export let entering = (handler, headers = {})=>(request)=>{
|
|
116
|
+
let marks = Object.entries(headers);
|
|
117
|
+
if (!marks.length) return handler(request);
|
|
118
|
+
let set = new Headers(request.headers);
|
|
119
|
+
for (let [name, value] of marks)set.set(name, value);
|
|
120
|
+
return handler(rebuild(request, {
|
|
121
|
+
headers: set
|
|
122
|
+
}));
|
|
123
|
+
};
|
|
124
|
+
/** The implementation of the tool ./vocab.json declares. */ export let runs = (host, options = {}, listen = denoListen)=>({
|
|
125
|
+
serve: async (call)=>{
|
|
126
|
+
let handler = host.handler;
|
|
127
|
+
// A host that composed this package has a handler; one that does not has
|
|
128
|
+
// nothing to listen with, and binding a port to refuse every request is
|
|
129
|
+
// not a server.
|
|
130
|
+
if (!handler) throw new Error('serve has no handler — compose @yaks/api');
|
|
131
|
+
let args = argsOf(call);
|
|
132
|
+
let port = Number(args.port ?? host.config.port ?? PORT);
|
|
133
|
+
let hostname = String(args.hostname ?? host.config.hostname ?? HOSTNAME);
|
|
134
|
+
let grace = Number(args.grace ?? GRACE) * 1000;
|
|
135
|
+
// Closing for dead processes comes before warming, which starts workers
|
|
136
|
+
// for the duty roles no live process covers, and a dead one would seem
|
|
137
|
+
// to cover its own. Running their unanswered calls belongs to recovery.
|
|
138
|
+
// A server sharing a port takes requests from the one it replaces as soon
|
|
139
|
+
// as it listens, so it listens warm. One starting alone listens at once,
|
|
140
|
+
// since nothing answers there until it does, and warms once it listens.
|
|
141
|
+
let warmed = async ()=>{
|
|
142
|
+
await host.bury?.();
|
|
143
|
+
await host.warm?.();
|
|
144
|
+
};
|
|
145
|
+
if (args.share === true) await warmed();
|
|
146
|
+
let at = '';
|
|
147
|
+
let began = Date.now();
|
|
148
|
+
let active = requests(addressed(handler, host.config.db));
|
|
149
|
+
let servers = [];
|
|
150
|
+
let server = {
|
|
151
|
+
shutdown: ()=>Promise.all(servers.map((s)=>s.shutdown())),
|
|
152
|
+
get finished () {
|
|
153
|
+
return Promise.all(servers.map((s)=>s.finished));
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
try {
|
|
157
|
+
for (let [i, endpoint] of [
|
|
158
|
+
{
|
|
159
|
+
port,
|
|
160
|
+
hostname
|
|
161
|
+
},
|
|
162
|
+
...options.listeners ?? []
|
|
163
|
+
].entries()){
|
|
164
|
+
servers.push(listen({
|
|
165
|
+
port: endpoint.port,
|
|
166
|
+
hostname: endpoint.hostname ?? HOSTNAME,
|
|
167
|
+
reusePort: args.share === true,
|
|
168
|
+
onListen: (addr)=>{
|
|
169
|
+
if (i == 0) at = `http://${addr.hostname}:${addr.port}`;
|
|
170
|
+
console.error(listening(`http://${addr.hostname}:${addr.port}`, served(addr), host));
|
|
171
|
+
}
|
|
172
|
+
}, secured(entering(active.handle, endpoint.headers), ()=>options.token)));
|
|
173
|
+
}
|
|
174
|
+
} catch (error) {
|
|
175
|
+
await server.shutdown();
|
|
176
|
+
if (error instanceof Error && error.name == 'AddrInUse') {
|
|
177
|
+
throw new CallError('address', `${hostname}:${port} is already in use`);
|
|
178
|
+
}
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
// Stopping: no new connection, every socket closed, and the requests in
|
|
182
|
+
// flight let finish until the grace is up. Reads and streamed answers are
|
|
183
|
+
// then cut, and so is a write's wait on its tool (@yaks/api `cutOf`): a
|
|
184
|
+
// kept write is answered without its reply, and a call whose tool is
|
|
185
|
+
// still running with where its answer will be kept (@yaks/tools
|
|
186
|
+
// `Invocation.call`). Either held the drain past systemd's stop timeout.
|
|
187
|
+
// Admitted writes finish before the listener and graph close.
|
|
188
|
+
let cut = false;
|
|
189
|
+
let timer;
|
|
190
|
+
let graced = new Promise((done)=>{
|
|
191
|
+
let stop = ()=>{
|
|
192
|
+
void server.shutdown();
|
|
193
|
+
timer = setTimeout(()=>{
|
|
194
|
+
cut = true;
|
|
195
|
+
console.error('serve drain —', JSON.stringify(active.open()));
|
|
196
|
+
active.cancel();
|
|
197
|
+
done();
|
|
198
|
+
}, grace);
|
|
199
|
+
};
|
|
200
|
+
if (host.stopping.aborted) stop();
|
|
201
|
+
else host.stopping.addEventListener('abort', stop, {
|
|
202
|
+
once: true
|
|
203
|
+
});
|
|
204
|
+
});
|
|
205
|
+
let unready;
|
|
206
|
+
try {
|
|
207
|
+
if (args.share !== true) await warmed();
|
|
208
|
+
if (typeof args.ready == 'string') unready = await denoReady(args.ready);
|
|
209
|
+
// And the duties in their long-lived form: the effect pool, where this
|
|
210
|
+
// process serves `effects`, and the plugins' services, each under its
|
|
211
|
+
// own lease, for as long as this process is up. Commands passing
|
|
212
|
+
// through leave these roles to a host that stays up.
|
|
213
|
+
// Not awaited: it returns when the host closes.
|
|
214
|
+
if (!host.stopping.aborted) void host.duties();
|
|
215
|
+
await Promise.race([
|
|
216
|
+
...servers.map((s)=>s.finished),
|
|
217
|
+
graced
|
|
218
|
+
]);
|
|
219
|
+
} finally{
|
|
220
|
+
// Already stopping unless saying it was ready failed; never awaited,
|
|
221
|
+
// since a shutdown settles only once every request has.
|
|
222
|
+
void server.shutdown();
|
|
223
|
+
clearTimeout(timer);
|
|
224
|
+
active.cancel();
|
|
225
|
+
let phase = 'request cleanup';
|
|
226
|
+
let waiting = setTimeout(()=>console.error(`serve drain — waiting for ${phase}`, JSON.stringify(active.open())), 5000);
|
|
227
|
+
try {
|
|
228
|
+
await active.drain();
|
|
229
|
+
phase = 'listener';
|
|
230
|
+
await server.finished;
|
|
231
|
+
} finally{
|
|
232
|
+
clearTimeout(waiting);
|
|
233
|
+
}
|
|
234
|
+
await unready?.();
|
|
235
|
+
}
|
|
236
|
+
return [
|
|
237
|
+
{
|
|
238
|
+
entity: {
|
|
239
|
+
eid: '$served'
|
|
240
|
+
},
|
|
241
|
+
content: {
|
|
242
|
+
body: `served ${at} for ${seconds(Date.now() - began)}` + (cut ? `, cutting what was open after ${seconds(grace)}` : '')
|
|
243
|
+
},
|
|
244
|
+
output: {
|
|
245
|
+
source: call.entity.eid
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
];
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
//# sourceMappingURL=tools.js.map
|
package/tools.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tools.js","sources":["./tools.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,iCAAiC;AACjC,EAAE;AACF,8EAA8E;AAC9E,6EAA6E;AAC7E,+EAA+E;AAC/E,6EAA6E;AAC7E,0EAA0E;AAC1E,4EAA4E;AAC5E,2DAA2D;AAC3D,EAAE;AACF,4EAA4E;AAC5E,8EAA8E;AAC9E,2EAA2E;AAC3E,6EAA6E;AAC7E,qEAAqE;AACrE,EAAE;AACF,4EAA4E;AAC5E,6EAA6E;AAC7E,+EAA+E;AAC/E,6EAA6E;AAC7E,8EAA8E;AAC9E,+EAA+E;AAC/E,4EAA4E;AAC5E,8EAA8E;AAC9E,6EAA6E;AAC7E,0EAA0E;AAC1E,4EAA4E;AAC5E,yEAAyE;AACzE,2EAA2E;AAC3E,sEAAsE;AACtE,gFAAgF;AAChF,EAAE;AACF,4EAA4E;AAC5E,4EAA4E;AAC5E,2EAA2E;AAC3E,yEAAyE;AACzE,+EAA+E;AAC/E,sEAAsE;AAEtE,SAAS,QAAQ,wBAAuB;AAExC,SAAS,MAAM,gCA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G,EAAE;UACjE;UACA,QAAQ;YAAE,QAAQ,KAAK,MAAM,CAAC,GAAG;UAAC;QACpC;OAAE;IACJ;EACF,CAAC,EAAC"}
|
package/tools.ts
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
// The implementation behind the `tool: true` declaration in ./vocab.json,
|
|
2
|
+
// exported as `@yaks/api/tools`.
|
|
3
|
+
//
|
|
4
|
+
// `serve` is the only one, and it is what makes one process the one answering
|
|
5
|
+
// HTTP for a graph. It is a tool rather than a command of the `yak` program,
|
|
6
|
+
// because listening on a port is something a package contributes, the same way
|
|
7
|
+
// a package contributes components, rules and routes: `yak` reads the config
|
|
8
|
+
// and loads the plugins, and this package brings the verb. A config whose
|
|
9
|
+
// plugins do not include @yaks/api has no `serve` to run, and a config that
|
|
10
|
+
// names it can be served by anything that lists its tools.
|
|
11
|
+
//
|
|
12
|
+
// It acts on the machine rather than on the graph — it binds a port there —
|
|
13
|
+
// the way `land` acts on a checkout, so it belongs to the process that opened
|
|
14
|
+
// the graph in the first place. What it listens with is already assembled:
|
|
15
|
+
// `host.handler` is this package's own doors with the listed plugins' routes
|
|
16
|
+
// in front of them, built by ./routes.ts when the host was composed.
|
|
17
|
+
//
|
|
18
|
+
// A call that does not return. The runner writes the call row and claims it
|
|
19
|
+
// `running` before the tool starts, and writes the result and `done` when it
|
|
20
|
+
// returns (@yaks/tools). This one returns when the server stops, so the record
|
|
21
|
+
// of a server that is up is a call still marked `running`, and the record of
|
|
22
|
+
// one that has stopped is its result, carrying the address it answered on and
|
|
23
|
+
// how long it answered for. Two consequences worth knowing: nothing is printed
|
|
24
|
+
// until it stops, which is why the address is reported on stderr as soon as
|
|
25
|
+
// the port is bound; and a server is never run again by a sweep. Stopped by a
|
|
26
|
+
// signal, it stops taking requests and closes its sockets, lets the requests
|
|
27
|
+
// in flight finish for a grace of seconds, then cancels reads, cuts every
|
|
28
|
+
// answer still streaming that no admitted write is producing (an MCP call's
|
|
29
|
+
// event stream), lets go of a tool still running, and waits for admitted
|
|
30
|
+
// writes before returning. The reader then closes after the request owners
|
|
31
|
+
// finish, preserving edits. A killed process leaves its call claimed;
|
|
32
|
+
// the next server closes that process and interrupts the call (host.ts `bury`).
|
|
33
|
+
//
|
|
34
|
+
// A restart is invisible when the replacement answers before this one stops
|
|
35
|
+
// taking requests. `share` lets two servers listen on one port at once, and
|
|
36
|
+
// `ready` names a file written once this one is listening, which is what a
|
|
37
|
+
// supervisor waits on before stopping the old one (@yaks/cli `restart`).
|
|
38
|
+
// Sharing is asked for, never assumed: a second server started by mistake on a
|
|
39
|
+
// taken port is refused rather than quietly handed half its requests.
|
|
40
|
+
|
|
41
|
+
import { requests } from './requests.js'
|
|
42
|
+
import type { Bundle } from 'jsr:@yaks/graph@0.2.36'
|
|
43
|
+
import { argsOf } from '@yaks/graph/call'
|
|
44
|
+
import type { Runs } from 'jsr:@yaks/graph@0.2.36/tools'
|
|
45
|
+
import type { Runner } from 'jsr:@yaks/tools@0.2.36'
|
|
46
|
+
import { CallError } from '@yaks/tools/errors'
|
|
47
|
+
import {
|
|
48
|
+
denoListen,
|
|
49
|
+
denoReady,
|
|
50
|
+
type Listen,
|
|
51
|
+
type Listener,
|
|
52
|
+
rebuild,
|
|
53
|
+
} from './deno.js'
|
|
54
|
+
import { secured } from './access.js'
|
|
55
|
+
import { DB, HOSTNAME, PORT, served } from './address.js'
|
|
56
|
+
import type { Handler, Route } from './route.ts'
|
|
57
|
+
|
|
58
|
+
export { HOSTNAME, PORT, served } from './address.js'
|
|
59
|
+
|
|
60
|
+
/** Seconds a stopping server lets requests finish before cancelling reads
|
|
61
|
+
* and cutting streamed answers. Admitted writes drain even after this grace
|
|
62
|
+
* expires. */
|
|
63
|
+
export let GRACE = 10
|
|
64
|
+
|
|
65
|
+
/** What this tool needs from the host that composed it: the request handler to
|
|
66
|
+
* answer with, the duties it takes over while it is up, and the config
|
|
67
|
+
* that said where to listen. */
|
|
68
|
+
export type Serving = {
|
|
69
|
+
config: { db?: string; port?: number; hostname?: string }
|
|
70
|
+
/** what this host answers with. Optional because a host has one only where
|
|
71
|
+
* a plugin built one, and ./routes.ts is that plugin — so a `Serving` put
|
|
72
|
+
* together by hand may carry none. */
|
|
73
|
+
handler?: Handler
|
|
74
|
+
/** the plugins' routes: each that `says` what it is is told on listening */
|
|
75
|
+
routes?: Pick<Route, 'path' | 'says'>[]
|
|
76
|
+
runner: Runner
|
|
77
|
+
duties: (signal?: AbortSignal) => Promise<void>
|
|
78
|
+
/** close for the processes on this machine that ended without closing
|
|
79
|
+
* (@yaks/cli host.ts `bury`); a host that tracks no processes has none */
|
|
80
|
+
bury?: () => Promise<unknown>
|
|
81
|
+
stopping: AbortSignal
|
|
82
|
+
/** warm the host (@yaks/host `Host.warm`): a server taking over a port
|
|
83
|
+
* (`share`) warms before it listens, any other once it listens, and every
|
|
84
|
+
* server before it says it is ready; one that fails ends the server */
|
|
85
|
+
warm?: () => Promise<void>
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
let seconds = (ms: number): string => `${Math.round(ms / 1000)}s`
|
|
89
|
+
|
|
90
|
+
/** `handler`, serving the graph file `db`, for a request whose {@link DB}
|
|
91
|
+
* header names the file it means: the file this server serves is answered
|
|
92
|
+
* with the header said back, which is how a client knows the answer came from
|
|
93
|
+
* its graph, and any other is answered 421 Misdirected Request, with nothing
|
|
94
|
+
* run. A request naming none is answered as it always was.
|
|
95
|
+
*
|
|
96
|
+
* ```ts
|
|
97
|
+
* import { assertEquals } from '@std/assert'
|
|
98
|
+
* import { DB } from '@yaks/api/address'
|
|
99
|
+
* import { addressed } from '@yaks/api/tools'
|
|
100
|
+
*
|
|
101
|
+
* let handle = addressed(() => new Response('ok'), '/g.db')
|
|
102
|
+
* let asked = (db?: string) =>
|
|
103
|
+
* handle(new Request('http://x/', { headers: db ? { [DB]: db } : {} }))
|
|
104
|
+
* let mine = await asked('/g.db')
|
|
105
|
+
* assertEquals([mine.status, mine.headers.get(DB)], [200, '/g.db'])
|
|
106
|
+
* assertEquals((await asked()).headers.get(DB), null)
|
|
107
|
+
* assertEquals((await asked('/copy.db')).status, 421)
|
|
108
|
+
* ```
|
|
109
|
+
*/
|
|
110
|
+
export let addressed =
|
|
111
|
+
(handler: Handler, db?: string): Handler => async (request) => {
|
|
112
|
+
let meant = request.headers.get(DB)
|
|
113
|
+
if (meant == null) return handler(request)
|
|
114
|
+
if (meant != db) {
|
|
115
|
+
return new Response('this server serves another graph', { status: 421 })
|
|
116
|
+
}
|
|
117
|
+
let answer = await handler(request)
|
|
118
|
+
if (answer.status < 200) return answer
|
|
119
|
+
let headers = new Headers(answer.headers)
|
|
120
|
+
headers.set(DB, meant)
|
|
121
|
+
return new Response(answer.body, {
|
|
122
|
+
status: answer.status,
|
|
123
|
+
statusText: answer.statusText,
|
|
124
|
+
headers,
|
|
125
|
+
})
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** What a server says once it listens at `at`: the address and the graph,
|
|
129
|
+
* then each door a route says something about, at `origin`, where a client on
|
|
130
|
+
* this machine reaches it.
|
|
131
|
+
*
|
|
132
|
+
* ```ts
|
|
133
|
+
* import { assertEquals } from '@std/assert'
|
|
134
|
+
* import { listening } from '@yaks/api/tools'
|
|
135
|
+
*
|
|
136
|
+
* assertEquals(
|
|
137
|
+
* listening('http://0.0.0.0:80', 'http://127.0.0.1:80', {
|
|
138
|
+
* config: { db: 'g.db' },
|
|
139
|
+
* routes: [{ path: '/', says: 'the canvas' }, { path: '/ws' }],
|
|
140
|
+
* }),
|
|
141
|
+
* 'serve — http://0.0.0.0:80 · g.db\n' +
|
|
142
|
+
* ' http://127.0.0.1:80/ the canvas\n' +
|
|
143
|
+
* 'Ctrl-C stops it',
|
|
144
|
+
* )
|
|
145
|
+
* ```
|
|
146
|
+
*/
|
|
147
|
+
export let listening = (
|
|
148
|
+
at: string,
|
|
149
|
+
origin: string,
|
|
150
|
+
host: Pick<Serving, 'config' | 'routes'>,
|
|
151
|
+
): string => {
|
|
152
|
+
let told = (host.routes ?? []).filter((r) => r.says)
|
|
153
|
+
.sort((a, b) => a.path.localeCompare(b.path))
|
|
154
|
+
let wide = Math.max(0, ...told.map((r) => r.path.length))
|
|
155
|
+
return [
|
|
156
|
+
`serve — ${at} · ${host.config.db ?? 'no db'}`,
|
|
157
|
+
...told.map((r) => ` ${origin}${r.path.padEnd(wide)} ${r.says}`),
|
|
158
|
+
'Ctrl-C stops it',
|
|
159
|
+
].join('\n')
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** An additional transport into the same handler, with trusted headers set
|
|
163
|
+
* by its listener rather than accepted from HTTP input. */
|
|
164
|
+
export type Endpoint = {
|
|
165
|
+
port: number
|
|
166
|
+
hostname?: string
|
|
167
|
+
headers?: Record<string, string>
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** A handler whose ingress sets these headers, replacing caller input. */
|
|
171
|
+
export let entering =
|
|
172
|
+
(handler: Handler, headers: Record<string, string> = {}): Handler =>
|
|
173
|
+
(request) => {
|
|
174
|
+
let marks = Object.entries(headers)
|
|
175
|
+
if (!marks.length) return handler(request)
|
|
176
|
+
let set = new Headers(request.headers)
|
|
177
|
+
for (let [name, value] of marks) set.set(name, value)
|
|
178
|
+
return handler(rebuild(request, { headers: set }))
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** The implementation of the tool ./vocab.json declares. */
|
|
182
|
+
export let runs = (
|
|
183
|
+
host: Serving,
|
|
184
|
+
options: { token?: string; listeners?: Endpoint[] } = {},
|
|
185
|
+
listen: Listen = denoListen,
|
|
186
|
+
): Runs => ({
|
|
187
|
+
serve: async (call): Promise<Bundle[]> => {
|
|
188
|
+
let handler = host.handler
|
|
189
|
+
// A host that composed this package has a handler; one that does not has
|
|
190
|
+
// nothing to listen with, and binding a port to refuse every request is
|
|
191
|
+
// not a server.
|
|
192
|
+
if (!handler) throw new Error('serve has no handler — compose @yaks/api')
|
|
193
|
+
let args = argsOf(call)
|
|
194
|
+
let port = Number(args.port ?? host.config.port ?? PORT)
|
|
195
|
+
let hostname = String(args.hostname ?? host.config.hostname ?? HOSTNAME)
|
|
196
|
+
let grace = Number(args.grace ?? GRACE) * 1000
|
|
197
|
+
// Closing for dead processes comes before warming, which starts workers
|
|
198
|
+
// for the duty roles no live process covers, and a dead one would seem
|
|
199
|
+
// to cover its own. Running their unanswered calls belongs to recovery.
|
|
200
|
+
// A server sharing a port takes requests from the one it replaces as soon
|
|
201
|
+
// as it listens, so it listens warm. One starting alone listens at once,
|
|
202
|
+
// since nothing answers there until it does, and warms once it listens.
|
|
203
|
+
let warmed = async () => {
|
|
204
|
+
await host.bury?.()
|
|
205
|
+
await host.warm?.()
|
|
206
|
+
}
|
|
207
|
+
if (args.share === true) await warmed()
|
|
208
|
+
let at = ''
|
|
209
|
+
let began = Date.now()
|
|
210
|
+
let active = requests(addressed(handler, host.config.db))
|
|
211
|
+
let servers: Listener[] = []
|
|
212
|
+
let server = {
|
|
213
|
+
shutdown: () => Promise.all(servers.map((s) => s.shutdown())),
|
|
214
|
+
get finished() {
|
|
215
|
+
return Promise.all(servers.map((s) => s.finished))
|
|
216
|
+
},
|
|
217
|
+
}
|
|
218
|
+
try {
|
|
219
|
+
for (
|
|
220
|
+
let [i, endpoint] of [{ port, hostname }, ...options.listeners ?? []]
|
|
221
|
+
.entries()
|
|
222
|
+
) {
|
|
223
|
+
servers.push(listen(
|
|
224
|
+
{
|
|
225
|
+
port: endpoint.port,
|
|
226
|
+
hostname: endpoint.hostname ?? HOSTNAME,
|
|
227
|
+
reusePort: args.share === true,
|
|
228
|
+
onListen: (addr) => {
|
|
229
|
+
if (i == 0) at = `http://${addr.hostname}:${addr.port}`
|
|
230
|
+
console.error(
|
|
231
|
+
listening(
|
|
232
|
+
`http://${addr.hostname}:${addr.port}`,
|
|
233
|
+
served(addr),
|
|
234
|
+
host,
|
|
235
|
+
),
|
|
236
|
+
)
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
secured(
|
|
240
|
+
entering(active.handle, endpoint.headers),
|
|
241
|
+
() => options.token,
|
|
242
|
+
),
|
|
243
|
+
))
|
|
244
|
+
}
|
|
245
|
+
} catch (error) {
|
|
246
|
+
await server.shutdown()
|
|
247
|
+
if (error instanceof Error && error.name == 'AddrInUse') {
|
|
248
|
+
throw new CallError('address', `${hostname}:${port} is already in use`)
|
|
249
|
+
}
|
|
250
|
+
throw error
|
|
251
|
+
}
|
|
252
|
+
// Stopping: no new connection, every socket closed, and the requests in
|
|
253
|
+
// flight let finish until the grace is up. Reads and streamed answers are
|
|
254
|
+
// then cut, and so is a write's wait on its tool (@yaks/api `cutOf`): a
|
|
255
|
+
// kept write is answered without its reply, and a call whose tool is
|
|
256
|
+
// still running with where its answer will be kept (@yaks/tools
|
|
257
|
+
// `Invocation.call`). Either held the drain past systemd's stop timeout.
|
|
258
|
+
// Admitted writes finish before the listener and graph close.
|
|
259
|
+
let cut = false
|
|
260
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
261
|
+
let graced = new Promise<void>((done) => {
|
|
262
|
+
let stop = () => {
|
|
263
|
+
void server.shutdown()
|
|
264
|
+
timer = setTimeout(() => {
|
|
265
|
+
cut = true
|
|
266
|
+
console.error('serve drain —', JSON.stringify(active.open()))
|
|
267
|
+
active.cancel()
|
|
268
|
+
done()
|
|
269
|
+
}, grace)
|
|
270
|
+
}
|
|
271
|
+
if (host.stopping.aborted) stop()
|
|
272
|
+
else host.stopping.addEventListener('abort', stop, { once: true })
|
|
273
|
+
})
|
|
274
|
+
let unready: (() => Promise<void>) | undefined
|
|
275
|
+
try {
|
|
276
|
+
if (args.share !== true) await warmed()
|
|
277
|
+
if (typeof args.ready == 'string') unready = await denoReady(args.ready)
|
|
278
|
+
// And the duties in their long-lived form: the effect pool, where this
|
|
279
|
+
// process serves `effects`, and the plugins' services, each under its
|
|
280
|
+
// own lease, for as long as this process is up. Commands passing
|
|
281
|
+
// through leave these roles to a host that stays up.
|
|
282
|
+
// Not awaited: it returns when the host closes.
|
|
283
|
+
if (!host.stopping.aborted) void host.duties()
|
|
284
|
+
await Promise.race([...servers.map((s) => s.finished), graced])
|
|
285
|
+
} finally {
|
|
286
|
+
// Already stopping unless saying it was ready failed; never awaited,
|
|
287
|
+
// since a shutdown settles only once every request has.
|
|
288
|
+
void server.shutdown()
|
|
289
|
+
clearTimeout(timer)
|
|
290
|
+
active.cancel()
|
|
291
|
+
let phase = 'request cleanup'
|
|
292
|
+
let waiting = setTimeout(() =>
|
|
293
|
+
console.error(
|
|
294
|
+
`serve drain — waiting for ${phase}`,
|
|
295
|
+
JSON.stringify(active.open()),
|
|
296
|
+
), 5000)
|
|
297
|
+
try {
|
|
298
|
+
await active.drain()
|
|
299
|
+
phase = 'listener'
|
|
300
|
+
await server.finished
|
|
301
|
+
} finally {
|
|
302
|
+
clearTimeout(waiting)
|
|
303
|
+
}
|
|
304
|
+
await unready?.()
|
|
305
|
+
}
|
|
306
|
+
return [{
|
|
307
|
+
entity: { eid: '$served' },
|
|
308
|
+
content: {
|
|
309
|
+
body: `served ${at} for ${seconds(Date.now() - began)}` +
|
|
310
|
+
(cut ? `, cutting what was open after ${seconds(grace)}` : ''),
|
|
311
|
+
},
|
|
312
|
+
output: { source: call.entity.eid },
|
|
313
|
+
}]
|
|
314
|
+
},
|
|
315
|
+
})
|
package/vocab.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// The vocabulary, and only that: the module exported as `@yaks/api/vocab`.
|
|
2
|
+
// `request` records failed HTTP answers, and belongs to the answering server;
|
|
3
|
+
// a keyed write's receipt is no graph row but the write log's (./log.ts). The
|
|
4
|
+
// tool `serve` in ./tools.ts, because listening on a port is something
|
|
5
|
+
// somebody asks a graph to do, and a thing you can ask a graph to do is a tool.
|
|
6
|
+
import doc from './vocab.json' with {
|
|
7
|
+
type: 'json'
|
|
8
|
+
};
|
|
9
|
+
import manifest from './package.json' with {
|
|
10
|
+
type: 'json'
|
|
11
|
+
};
|
|
12
|
+
/** The components and the tool this plugin declares. */ export let apiDoc = doc;
|
|
13
|
+
/** What this package is: its manifest's description, the one place it is
|
|
14
|
+
* written, which a host stamps on each document here. */ export let description = manifest.description;
|
|
15
|
+
/** Every document this plugin declares. */ export let docs = [
|
|
16
|
+
apiDoc
|
|
17
|
+
];
|
|
18
|
+
//# sourceMappingURL=vocab.js.map
|
package/vocab.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vocab.js","sources":["./vocab.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,8EAA8E;AAC9E,8EAA8E;AAC9E,uEAAuE;AACvE,gFAAgF;AAEhF,OAAO,SAAS,oBAAoB;EAAE,MAAM;AAAO,EAAC;AACpD,OAAO,cAAc,sBAAsB;EAAE,MAAM;AAAO,EAAC;AAE3D,sDAAsD,GACtD,OAAO,IAAI,SAAmB,IAAG;AAEjC;uDACuD,GACvD,OAAO,IAAI,cAAsB,SAAS,WAAW,CAAA;AAErD,yCAAyC,GACzC,OAAO,IAAI,OAAmB;EAAC;CAAO,CAAA"}
|