@amritk/nish-aarch64-linux 0.37.0 → 0.39.0

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 (73) hide show
  1. package/INSTALL.md +28 -16
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +380 -47
  4. package/package.json +1 -1
  5. package/runtime/core/arrays.d.ts +4 -0
  6. package/runtime/core/arrays.mjs +33 -0
  7. package/runtime/core/host.d.ts +11 -0
  8. package/runtime/core/host.mjs +35 -0
  9. package/runtime/nish.d.ts +645 -66
  10. package/runtime/nish.h +101 -15
  11. package/runtime/nish.mjs +69 -6
  12. package/runtime/node.mjs +117 -0
  13. package/runtime/runtime-aes.c +12 -4
  14. package/runtime/runtime-async.c +267 -51
  15. package/runtime/runtime-checksum.c +207 -15
  16. package/runtime/runtime-cross.c +2 -1
  17. package/runtime/runtime-net.c +32 -3
  18. package/runtime/runtime-os.c +174 -27
  19. package/runtime/runtime-region.c +170 -8
  20. package/runtime/runtime-sandbox.c +377 -17
  21. package/runtime/runtime-sha256.c +11 -4
  22. package/runtime/runtime-text.c +1068 -0
  23. package/runtime/runtime-wasm.c +18 -3
  24. package/runtime/runtime.c +55 -961
  25. package/runtime/vite.mjs +48 -11
  26. package/scripts/build.sh +113 -36
  27. package/std/LICENSE-fdlibm +8 -0
  28. package/std/README.md +7 -4
  29. package/std/array.ts +266 -0
  30. package/std/compress/checksum.ts +13 -0
  31. package/std/compress/deflate.ts +0 -2
  32. package/std/crypto/p256.ts +247 -74
  33. package/std/crypto/p384.ts +3 -1
  34. package/std/crypto/pki.ts +35 -9
  35. package/std/crypto/x25519.ts +153 -64
  36. package/std/crypto/x509.ts +113 -10
  37. package/std/host/text.ts +86 -0
  38. package/std/json-tokenizer.ts +20 -0
  39. package/std/json-typed.ts +217 -8
  40. package/std/math.ts +743 -41
  41. package/std/net/dns-resolver.ts +46 -6
  42. package/std/net/dns.ts +50 -13
  43. package/std/net/fetch.ts +691 -129
  44. package/std/net/handler.ts +142 -16
  45. package/std/net/http-compress.ts +17 -9
  46. package/std/net/http-fields.ts +19 -4
  47. package/std/net/http1-codec.ts +517 -154
  48. package/std/net/http1-server.ts +508 -25
  49. package/std/net/http2-cleartext.ts +526 -0
  50. package/std/net/http2-tls.ts +48 -0
  51. package/std/net/http2.ts +84 -0
  52. package/std/net/postgres-async.ts +2223 -0
  53. package/std/net/postgres-carrier.ts +343 -10
  54. package/std/net/postgres.ts +129 -11
  55. package/std/net/prefork.ts +195 -11
  56. package/std/net/quic-datagram.ts +30 -0
  57. package/std/net/quic-listener.ts +38 -12
  58. package/std/net/quic-packet.ts +19 -6
  59. package/std/net/quic-recovery.ts +134 -19
  60. package/std/net/quic-stream.ts +174 -36
  61. package/std/net/quic.ts +418 -18
  62. package/std/net/router.ts +39 -17
  63. package/std/net/serve.ts +867 -0
  64. package/std/net/tls/codec.ts +110 -32
  65. package/std/net/tls/record-server.ts +37 -7
  66. package/std/net/tls-tcp.ts +56 -1
  67. package/std/net/tls.ts +196 -50
  68. package/std/net/websocket.ts +55 -18
  69. package/std/net/webtransport.ts +179 -1
  70. package/std/regex.ts +69 -47
  71. package/std/region.ts +62 -11
  72. package/std/secret.ts +26 -59
  73. package/std/text.ts +464 -5
@@ -0,0 +1,867 @@
1
+ /**
2
+ * `nish/net/serve` — an HTTP/1.1 server for an `async` program: one task and
3
+ * one region per request, answers in request order.
4
+ *
5
+ * import { Request, Response, ServeLimits, refuse, serve } from "nish/net/serve"
6
+ * import { Router, RouterLimits } from "nish/net/router"
7
+ * import { sleep } from "nish:async"
8
+ *
9
+ * const HOME: i32 = 0 // module constants, in the order the routes are added
10
+ * const USER: i32 = 1
11
+ *
12
+ * async function handle(req: Request): Promise<Response> {
13
+ * switch (req.route) {
14
+ * case HOME: return new Response(200).text("hello\n")
15
+ * case USER: {
16
+ * await sleep(5) // a database, another service: the loop runs on
17
+ * return new Response(200).json(`{"id":"${req.param(0)}"}`)
18
+ * }
19
+ * default: return refuse(req) // 404, or 405 with its Allow
20
+ * }
21
+ * }
22
+ *
23
+ * export async function main(): Promise<i32> {
24
+ * const router = new Router(new RouterLimits())
25
+ * router.add("GET", "/")
26
+ * router.add("GET", "/users/:id")
27
+ * return await serve(8080, router, new ServeLimits(), handle)
28
+ * }
29
+ *
30
+ * `serve` runs `nish/net/handler`'s readiness loop as an `async` function:
31
+ * it awaits the loop's descriptor, so the program's other tasks run while no
32
+ * socket is ready. Each whole request it takes is handed to `handle` in a
33
+ * task of its own, spawned with the request's slot, and the task's
34
+ * allocations — the request it reads, the response it builds, whatever the
35
+ * handler makes on the way — live in the task's region and go when it ends.
36
+ *
37
+ * **The task reads its own copy.** The task copies the request's head and
38
+ * body out of the server's slot into its own memory before `handle` runs,
39
+ * and when `handle` answers it writes the status, the content type and the
40
+ * body back into the slot's fixed buffers, in bulk, and wakes the
41
+ * loop. The loop then sends the answer and frees the slot. Nothing the task
42
+ * allocated outlives it, and the loop's arena does not grow per request once
43
+ * its slots are warm: `tests/link/net_serve_pipelined_flat` pins
44
+ * `Arena.used()` flat over thousands of pipelined requests. What the runtime
45
+ * allocates outside the arena for a task and its region is not measured.
46
+ *
47
+ * **Answers keep request order.** The handler reads a connection's next
48
+ * request only once the one before it is answered, so at most one request
49
+ * per connection is in flight, and pipelined requests are answered in the
50
+ * order they came: a later request's task starts only after the earlier one
51
+ * is answered, so it can never finish first.
52
+ *
53
+ * **A pipelined burst goes out in one write.** The loop answers what the
54
+ * tasks wrote and takes what the handler queued until neither moves, so a
55
+ * handler that answers without waiting serves a whole burst in one turn.
56
+ * The handler holds each answer's send while the next request on its
57
+ * connection is queued and the output has room, and the loop flushes once
58
+ * before it parks: one write per connection per turn, and no wake byte for a
59
+ * task that answers while the loop runs.
60
+ *
61
+ * **Every cap answers.** `ServeLimits` bounds the connections, the requests
62
+ * in flight (503 past it), a request's header section (431) and body (413),
63
+ * and the response a task may write (500 past it). `docs/security/serve.md`
64
+ * is the record.
65
+ *
66
+ * `readable` is refused under `--emit-ts` (NL4017), so a program that serves
67
+ * is native only.
68
+ *
69
+ * Private helpers share the importing program's flat symbol namespace
70
+ * (`docs/wp26-stdlib.md` §3e), which is why each one carries the module's name.
71
+ */
72
+ import { copyBytes } from "nish/bytes"
73
+ import { HandlerLimits, HttpHandler, HttpRequest } from "nish/net/handler"
74
+ import { ROUTER_BAD_ESCAPE, Router } from "nish/net/router"
75
+ import { cancel, cancelAfter, readable, sleep, spawn, taskId } from "nish:async"
76
+ import { NET_UNIX_STREAM, netClose, netRead, netWrite, tcpListen, unixSocketPair } from "nish:net"
77
+
78
+ /** The listen backlog `serve` asks for. */
79
+ const SERVE_BACKLOG: i32 = 1024
80
+ /** Bytes a content type may have; a longer one is answered 500. */
81
+ const SERVE_TYPE_BYTES: i32 = 128
82
+ /** Distinct content types the server keeps the bytes of; past it a new type is answered 500. */
83
+ const SERVE_MAX_TYPES: i32 = 64
84
+ /** Milliseconds between the ticker's wakes, which run the handler's timeouts. */
85
+ const SERVE_TICK_MS: i32 = 1000
86
+ /** The handler's watch id for the wake socket. */
87
+ const SERVE_WAKE: i32 = 0
88
+ /** `refused` marks a response the loop answers with `HttpHandler.refuse`. */
89
+ const SERVE_REFUSE: i32 = -1
90
+ /** The status a program's malformed answer is sent as. */
91
+ const SERVE_FAILED: i32 = 500
92
+
93
+ /** The caps a server holds every request and connection to; each field is read once, by `serve`. */
94
+ export class ServeLimits {
95
+ /** The most connections open at once; a connection past it is accepted and closed at once, and its client sees the connection reset. */
96
+ connections: i32 = 256
97
+ /** The most requests in flight — handed to a task and not yet answered — at once; past it a request is answered 503. */
98
+ inFlight: i32 = 256
99
+ /** The most bytes a request's header section may have; past it the request is answered 431 and its connection ends. */
100
+ headerBytes: i32 = 16384
101
+ /** The most bytes a request body may have; past it the request is answered 413 and its connection ends. */
102
+ bodyBytes: i32 = 1048576
103
+ /** The most bytes a response body may have; a task that answers more is answered 500 instead. */
104
+ responseBytes: i32 = 65536
105
+ /**
106
+ * Milliseconds a request's task may run, from its start to its answer;
107
+ * past it the task is cancelled: each await it is parked on, and each it
108
+ * makes later, answers false at once, so it runs to its end and its slot
109
+ * is freed. 0 or less sets no limit.
110
+ */
111
+ deadline: i32 = 30000
112
+ /**
113
+ * Milliseconds a connection may take to send a whole request head, from
114
+ * its first byte; past it the connection is closed. The bound on a client
115
+ * that trickles its head (slowloris): it holds a connection this long, no
116
+ * longer.
117
+ */
118
+ headTimeout: i32 = 30000
119
+ /**
120
+ * Milliseconds a connection may go without a byte read or written, as a
121
+ * keep-alive connection does between requests; past it the connection is
122
+ * closed, freeing its slot.
123
+ */
124
+ idleTimeout: i32 = 60000
125
+ /**
126
+ * How many requests to answer before stopping: the server then stops
127
+ * accepting, finishes what it holds and returns. 0, the default, serves
128
+ * for good.
129
+ */
130
+ maxRequests: i32 = 0
131
+ /**
132
+ * The `Server` field written into the head of every answer a task writes,
133
+ * as `server: <value>`; "", the default, writes none. The answers the
134
+ * server writes itself carry none: a `refuse` (404, or 405 with its
135
+ * `Allow`) and 400, 413, 431, 500 and 503. Made into bytes once, when the
136
+ * server starts, so it costs no work per request. A control byte in it
137
+ * panics as the server starts.
138
+ */
139
+ server: string = ""
140
+ }
141
+
142
+ /** What a server did, for a log line or a test; `serveOn` fills it as it runs. */
143
+ export class ServeStats {
144
+ /** Requests answered, by a task or by the server itself. */
145
+ answered: i32 = 0
146
+ /** Requests answered 503 because `inFlight` tasks were already running. */
147
+ busy: i32 = 0
148
+ /** Answers a task wrote that broke a cap or a rule, answered 500 instead. */
149
+ failed: i32 = 0
150
+ /** How many slots the server made: the most requests ever in flight at once. */
151
+ slots: i32 = 0
152
+ /** After how many answers to read `usedWarm`; 0 reads it never. */
153
+ warmAfter: i32 = 0
154
+ /** `Arena.used()` in the server's loop once `warmAfter` requests were answered. */
155
+ usedWarm: i64 = 0
156
+ /** `Arena.used()` in the server's loop once `maxRequests` were answered, before draining. */
157
+ usedEnd: i64 = 0
158
+ /** The writes the server began to send answers, counted at the end of each loop turn: a pipelined burst that fits the output is one. */
159
+ sends: i64 = 0
160
+ }
161
+
162
+ /**
163
+ * A request, as `handle` reads it: the task's own copy of the head and body,
164
+ * valid for as long as the task runs.
165
+ */
166
+ export class Request {
167
+ /** The index `Router.add` answered for the route, or a negative `ROUTER_*` code. */
168
+ route: i32 = 0
169
+ /** The request as the handler parsed it, copied into the task: its spans, its head and its body. */
170
+ raw: HttpRequest
171
+
172
+ /**
173
+ * A request over `raw`, which it keeps.
174
+ * @param raw the parsed request, the task's own
175
+ */
176
+ constructor(raw: HttpRequest) {
177
+ this.raw = raw
178
+ this.route = raw.route
179
+ }
180
+
181
+ /**
182
+ * The method.
183
+ * @returns the method as it came on the wire, such as `"GET"`
184
+ */
185
+ method(): string {
186
+ return String.fromBytes(this.raw.head, this.raw.methodStart, this.raw.methodEnd)
187
+ }
188
+
189
+ /**
190
+ * The path: the target up to its `?`, still percent-encoded.
191
+ * @returns the raw path, such as `"/users/7"`
192
+ */
193
+ path(): string {
194
+ return String.fromBytes(this.raw.head, this.raw.targetStart, this.raw.pathEnd)
195
+ }
196
+
197
+ /**
198
+ * Route parameter `k`, percent-decoded. Panics when the request's route has no parameter `k`.
199
+ * @param k the parameter's position in the route pattern, from 0
200
+ * @returns the decoded value, or an empty string when it holds a malformed escape
201
+ */
202
+ param(k: i32): string {
203
+ const out: u8[] = new Array<u8>(this.raw.paramEnd(k) - this.raw.paramStart(k))
204
+ const n: i32 = this.raw.param(k, out)
205
+ return n < 0 ? "" : String.fromBytes(out, 0, n)
206
+ }
207
+
208
+ /**
209
+ * Route parameter `k` read as a decimal number that is not negative and fits an `i32`. Panics when the request's route has no parameter `k`.
210
+ * @param k the parameter's position in the route pattern, from 0
211
+ * @returns the number, or -1 when it is empty, holds a non-digit or overflows
212
+ */
213
+ paramNumber(k: i32): i32 {
214
+ return this.raw.paramDecimal(k)
215
+ }
216
+
217
+ /**
218
+ * Whether route parameter `k` holds a malformed percent escape, which a program answers 400. Panics when the request's route has no parameter `k`.
219
+ * @param k the parameter's position in the route pattern, from 0
220
+ * @returns true when decoding the parameter fails
221
+ */
222
+ paramMalformed(k: i32): boolean {
223
+ const out: u8[] = new Array<u8>(this.raw.paramEnd(k) - this.raw.paramStart(k))
224
+ return this.raw.param(k, out) === ROUTER_BAD_ESCAPE
225
+ }
226
+
227
+ /**
228
+ * The first query parameter named `name`, form-decoded (`+` as a space, `%XX` as its byte).
229
+ * @param name the parameter name, compared decoded
230
+ * @returns the decoded value, or an empty string when there is none or it is malformed
231
+ */
232
+ query(name: string): string {
233
+ if (this.raw.queryIndex(name) < 0) {
234
+ return ""
235
+ }
236
+ const out: u8[] = new Array<u8>(this.raw.queryValueEnd - this.raw.queryValueStart)
237
+ const n: i32 = this.raw.query(name, out)
238
+ return n < 0 ? "" : String.fromBytes(out, 0, n)
239
+ }
240
+
241
+ /**
242
+ * The value of the first header field named `name`.
243
+ * @param name the field name in lowercase, as the parser keeps every name
244
+ * @returns the value, or an empty string when no field has the name
245
+ */
246
+ header(name: string): string {
247
+ const i: i32 = this.raw.header(name)
248
+ return i < 0 ? "" : String.fromBytes(this.raw.head, this.raw.valueStart(i), this.raw.valueEnd(i))
249
+ }
250
+
251
+ /**
252
+ * The body as text.
253
+ * @returns the body's bytes as a string, empty for none
254
+ */
255
+ text(): string {
256
+ return String.fromBytes(this.raw.body, 0, this.raw.bodyLength)
257
+ }
258
+ }
259
+
260
+ /**
261
+ * The answer `handle` gives: a status, a content type and a body. Build it
262
+ * with `new Response(status)` and one of `text`, `json` or `bytes`, or with
263
+ * `refuse`.
264
+ */
265
+ export class Response {
266
+ /** The `Content-Type` value; empty sends none, and the body goes without one. */
267
+ type: string = ""
268
+ /** The body, `body[0 .. length)`. */
269
+ body: u8[]
270
+ /** The status, from 200 to 599; any other is answered 500. */
271
+ status: i32 = 200
272
+ /** How many bytes of `body` are the body. */
273
+ length: i32 = 0
274
+
275
+ /**
276
+ * An answer with `status` and no body yet.
277
+ * @param status the status, from 200 to 599
278
+ */
279
+ constructor(status: i32) {
280
+ this.status = status
281
+ this.body = []
282
+ }
283
+
284
+ /**
285
+ * Sets a plain-text body.
286
+ * @param s the body
287
+ * @returns this response, for a chain
288
+ */
289
+ text(s: string): Response {
290
+ return this.bytes("text/plain; charset=utf-8", serveBytes(s), toI32(0), toI32(s.length))
291
+ }
292
+
293
+ /**
294
+ * Sets a JSON body the program wrote.
295
+ * @param s the JSON text
296
+ * @returns this response, for a chain
297
+ */
298
+ json(s: string): Response {
299
+ return this.bytes("application/json", serveBytes(s), toI32(0), toI32(s.length))
300
+ }
301
+
302
+ /**
303
+ * Sets a body of bytes with a content type.
304
+ * @param type the `Content-Type` value
305
+ * @param buf the buffer holding the body, kept by the response
306
+ * @param off where the body starts in `buf`
307
+ * @param len how many body bytes there are
308
+ * @returns this response, for a chain
309
+ */
310
+ bytes(type: string, buf: u8[], off: i32, len: i32): Response {
311
+ if (off < 0 || len < 0 || off + len > toI32(buf.length)) {
312
+ panic(`Response.bytes: [${off}, ${off + len}) is outside a buffer of ${buf.length}`)
313
+ }
314
+ this.type = type
315
+ if (off === 0) {
316
+ this.body = buf
317
+ } else {
318
+ const copy: u8[] = new Array<u8>(len)
319
+ for (let i: i32 = 0; i < toI32(copy.length); i++) {
320
+ copy[i] = buf[off + i]
321
+ }
322
+ this.body = copy
323
+ }
324
+ this.length = len
325
+ return this
326
+ }
327
+ }
328
+
329
+ /**
330
+ * The answer for a request the router refused: 405 with an `Allow` field
331
+ * naming the methods the path has, and 404 for anything else.
332
+ * @param _req the request to refuse; the loop answers it from the request it holds
333
+ * @returns a response the server answers as `HttpHandler.refuse` does
334
+ */
335
+ export const refuse = (_req: Request): Response => new Response(SERVE_REFUSE)
336
+
337
+ /**
338
+ * The shared state between the loop and its tasks: one slot per request in
339
+ * flight. Each slot's buffers are made once, the first time the slot is
340
+ * used, and kept.
341
+ */
342
+ class ServeState {
343
+ /** The request each slot holds, the handler's until it is answered. */
344
+ reqs: HttpRequest[]
345
+ /** Whether a slot holds a request. */
346
+ busy: boolean[]
347
+ /** Whether a slot's task has written its answer. */
348
+ done: boolean[]
349
+ /** Each slot's task, as `taskId()` answered it; 0 until the task starts. */
350
+ tasks: i64[]
351
+ /** Whether a slot's task was cancelled, so it is cancelled once. */
352
+ cancelled: boolean[]
353
+ /** The free slots, `free[0 .. freeCount)`, the last freed on top. */
354
+ free: i32[]
355
+ /** The slots whose task has answered since the loop last looked, `finished[0 .. finishedCount)`, in the order they answered. */
356
+ finished: i32[]
357
+ /** The slots whose task the loop has started and not yet seen answer, `running[0 .. runningCount)`: the ones a hang-up can cancel. */
358
+ running: i32[]
359
+ /** Whether a slot is in `running`, so a slot answered and reused within a turn is listed once. */
360
+ listed: boolean[]
361
+ /** The status each task answered, or `SERVE_REFUSE`. */
362
+ status: i32[]
363
+ /** The bytes each task wrote into `bodies`, or -1 when its body broke `responseBytes`. */
364
+ lengths: i32[]
365
+ /** The response body each task writes. */
366
+ bodies: u8[][]
367
+ /** The content type each task writes. */
368
+ types: u8[][]
369
+ /** The bytes each task wrote into `types`, or -1 when the type was too long. */
370
+ typeLengths: i32[]
371
+ /** Per slot: the index in `typeBytes` of the type its task answered, or -1 when the task copied it into `types`. */
372
+ typeIndex: i32[]
373
+ /** Each content type the server has sent, as the bytes the loop writes into a head. */
374
+ typeBytes: u8[][]
375
+ /** The same content types as text, in `typeBytes`'s order: what a task compares its answer's type with. */
376
+ typeTexts: string[]
377
+ /** One byte, written to the wake socket. */
378
+ one: u8[]
379
+ /** The fields of an answer with no content type: `ServeLimits.server`'s, or none. */
380
+ plainNames: u8[][]
381
+ plainValues: u8[][]
382
+ /** The fields of an answer with a content type: `ServeLimits.server`'s, then `content-type`, whose value is set per answer. */
383
+ typedNames: u8[][]
384
+ typedValues: u8[][]
385
+ /** How many of `free`'s entries are free slots. */
386
+ freeCount: i32 = 0
387
+ /** How many of `finished`'s entries are answered slots the loop has not yet looked at. */
388
+ finishedCount: i32 = 0
389
+ /** How many of `running`'s entries are slots whose task is running. */
390
+ runningCount: i32 = 0
391
+ /** `ServeLimits.deadline`, which each task arms on itself as it starts. */
392
+ deadline: i32 = 0
393
+ /** The wake socket's end the tasks write to. */
394
+ wakeFd: i32 = 0
395
+ /** Set when the server begins to stop: each task still running, and each that starts later, is cancelled. */
396
+ stopping: boolean = false
397
+ /** Whether a byte is waiting in the wake socket. */
398
+ signalled: boolean = false
399
+ /** Whether the loop is running rather than parked: a task that answers now needs no wake byte, as the loop looks again before it parks. */
400
+ awake: boolean = false
401
+ /** Set by each task that answers, and cleared by the loop as it looks for answers. */
402
+ fresh: boolean = false
403
+ /** Set when the loop has stopped: the ticker ends. */
404
+ stopped: boolean = false
405
+
406
+ constructor() {
407
+ this.reqs = []
408
+ this.busy = []
409
+ this.done = []
410
+ this.tasks = []
411
+ this.cancelled = []
412
+ this.free = []
413
+ this.finished = []
414
+ this.running = []
415
+ this.listed = []
416
+ this.status = []
417
+ this.lengths = []
418
+ this.bodies = []
419
+ this.types = []
420
+ this.typeLengths = []
421
+ this.typeIndex = []
422
+ this.typeBytes = []
423
+ this.typeTexts = []
424
+ this.one = [toU8(1)]
425
+ this.plainNames = []
426
+ this.plainValues = []
427
+ this.typedNames = []
428
+ this.typedValues = []
429
+ }
430
+ }
431
+
432
+ /** Makes `st`'s answer fields, with a `server` field of `server` unless it is "". */
433
+ const serveFields = (st: ServeState, server: string): void => {
434
+ const type: u8[] = serveBytes("content-type")
435
+ if (server !== "") {
436
+ const value: u8[] = serveBytes(server)
437
+ for (let i: i32 = 0; i < toI32(value.length); i++) {
438
+ if (value[i] < 32 || value[i] === 127) {
439
+ panic(`serve: ServeLimits.server holds the control byte ${value[i]} at ${i}`)
440
+ }
441
+ }
442
+ const name: u8[] = serveBytes("server")
443
+ st.plainNames.push(name)
444
+ st.plainValues.push(value)
445
+ st.typedNames.push(name)
446
+ st.typedValues.push(value)
447
+ }
448
+ st.typedNames.push(type)
449
+ st.typedValues.push(type)
450
+ }
451
+
452
+ /** The last freed slot, making one when every slot is busy and `inFlight` allows; -1 when none. */
453
+ const serveFreeSlot = (st: ServeState, limits: ServeLimits): i32 => {
454
+ if (st.freeCount > 0) {
455
+ st.freeCount -= 1
456
+ return st.free[st.freeCount]
457
+ }
458
+ const n: i32 = toI32(st.busy.length)
459
+ if (n >= limits.inFlight) {
460
+ return -1
461
+ }
462
+ st.reqs.push(new HttpRequest(-1))
463
+ st.busy.push(false)
464
+ st.done.push(false)
465
+ st.tasks.push(toI64(0))
466
+ st.cancelled.push(false)
467
+ st.status.push(toI32(0))
468
+ st.lengths.push(toI32(0))
469
+ st.bodies.push(new Array<u8>(limits.responseBytes))
470
+ st.types.push(new Array<u8>(SERVE_TYPE_BYTES))
471
+ st.typeLengths.push(toI32(0))
472
+ st.typeIndex.push(toI32(-1))
473
+ st.free.push(toI32(0))
474
+ st.finished.push(toI32(0))
475
+ st.running.push(toI32(0))
476
+ st.listed.push(false)
477
+ return n
478
+ }
479
+
480
+ /**
481
+ * Cancels slot `k`'s task, once: its awaits answer false from now on, so it
482
+ * runs to its end and writes an answer nobody may read.
483
+ */
484
+ const serveCancel = (st: ServeState, k: i32): void => {
485
+ if (!st.cancelled[k] && st.tasks[k] !== 0) {
486
+ st.cancelled[k] = true
487
+ cancel(st.tasks[k])
488
+ }
489
+ }
490
+
491
+ /** Whether any slot still holds a request. */
492
+ const serveAnyBusy = (st: ServeState): boolean => {
493
+ for (let k: i32 = 0; k < toI32(st.busy.length); k++) {
494
+ if (st.busy[k]) {
495
+ return true
496
+ }
497
+ }
498
+ return false
499
+ }
500
+
501
+ /** Sends slot `k`'s answer, as its task wrote it. */
502
+ const serveAnswer = (h: HttpHandler, st: ServeState, k: i32, stats: ServeStats): void => {
503
+ const r: HttpRequest = st.reqs[k]
504
+ const status: i32 = st.status[k]
505
+ if (status === SERVE_REFUSE) {
506
+ h.refuse(r)
507
+ return
508
+ }
509
+ const length: i32 = st.lengths[k]
510
+ if (status < 200 || status > 599 || length < 0 || st.typeLengths[k] < 0) {
511
+ stats.failed += 1
512
+ h.problem(r, SERVE_FAILED, "Internal Server Error", "")
513
+ return
514
+ }
515
+ if (st.typeLengths[k] === 0) {
516
+ if (length === 0 && st.plainNames.length === 0) {
517
+ h.empty(r, status)
518
+ } else {
519
+ h.sendFields(r, status, st.plainNames, st.plainValues, st.bodies[k], toI32(0), length)
520
+ }
521
+ return
522
+ }
523
+ const type: i32 = st.typeIndex[k] >= 0 ? st.typeIndex[k] : serveType(st, st.types[k], st.typeLengths[k])
524
+ if (type < 0) {
525
+ stats.failed += 1
526
+ h.problem(r, SERVE_FAILED, "Internal Server Error", "")
527
+ return
528
+ }
529
+ const last: i32 = toI32(st.typedValues.length) - 1
530
+ st.typedValues[last] = st.typeBytes[type]
531
+ h.sendFields(r, status, st.typedNames, st.typedValues, st.bodies[k], toI32(0), length)
532
+ }
533
+
534
+ /** The index in `st.typeBytes` of the bytes `type[0 .. len)`, adding them while there is room; -1 when full or when they hold a control byte. */
535
+ const serveType = (st: ServeState, type: u8[], len: i32): i32 => {
536
+ const cache: u8[][] = st.typeBytes
537
+ if (len < 0 || len > toI32(type.length)) {
538
+ return -1
539
+ }
540
+ for (let i: i32 = 0; i < toI32(cache.length); i++) {
541
+ const c: u8[] = cache[i]
542
+ if (toI32(c.length) === len) {
543
+ let same: boolean = true
544
+ for (let j: i32 = 0; j < toI32(c.length) && j < toI32(type.length) && same; j++) {
545
+ same = c[j] === type[j]
546
+ }
547
+ if (same) {
548
+ return i
549
+ }
550
+ }
551
+ }
552
+ if (toI32(cache.length) >= SERVE_MAX_TYPES) {
553
+ return -1
554
+ }
555
+ // A control byte other than a tab would make the carrier refuse the head,
556
+ // which the handler treats as a program's mistake and panics on.
557
+ for (let j: i32 = 0; j < len && j < toI32(type.length); j++) {
558
+ if ((type[j] < 32 && type[j] !== 9) || type[j] === 127) {
559
+ return -1
560
+ }
561
+ }
562
+ const copy: u8[] = new Array<u8>(len)
563
+ for (let j: i32 = 0; j < toI32(copy.length) && j < toI32(type.length); j++) {
564
+ copy[j] = type[j]
565
+ }
566
+ cache.push(copy)
567
+ st.typeTexts.push(String.fromBytes(copy, 0, len))
568
+ return toI32(cache.length) - 1
569
+ }
570
+
571
+ /** A string's bytes: native strings are UTF-8, so its code units are its bytes. */
572
+ const serveBytes = (s: string): u8[] => {
573
+ const n: i32 = toI32(s.length)
574
+ const out: u8[] = new Array<u8>(n)
575
+ for (let i: i32 = 0; i < toI32(out.length) && i < toI32(s.length); i++) {
576
+ out[i] = toU8(s.charCodeAt(i))
577
+ }
578
+ return out
579
+ }
580
+
581
+ /** One request's task: copies it in, runs `handle`, writes the answer into slot `k` and wakes the loop. */
582
+ const serveTask = async (
583
+ handle: (req: Request) => Promise<Response>,
584
+ st: ServeState,
585
+ k: i32
586
+ ): Promise<void> => {
587
+ const self: i64 = taskId()
588
+ st.tasks[k] = self
589
+ if (st.stopping) {
590
+ cancel(self)
591
+ } else if (st.deadline > 0) {
592
+ cancelAfter(self, st.deadline)
593
+ }
594
+ // The copy is written out here, not in a helper: a helper handed both the
595
+ // shared request and the task's own would be refused, as it could store
596
+ // one into the other.
597
+ const src: HttpRequest = st.reqs[k]
598
+ const r: HttpRequest = new HttpRequest(-1)
599
+ const head: u8[] = new Array<u8>(src.headLength)
600
+ copyBytes(head, 0, src.head, 0, src.headLength)
601
+ const spans: i32[] = new Array<i32>(4 * src.headerCount)
602
+ for (let i: i32 = 0; i < toI32(spans.length) && i < toI32(src.spans.length); i++) {
603
+ spans[i] = src.spans[i]
604
+ }
605
+ // No parameters and no body keep the empty arrays the constructor made.
606
+ if (src.paramCount > 0) {
607
+ const params: i32[] = new Array<i32>(2 * src.paramCount)
608
+ for (let i: i32 = 0; i < toI32(params.length) && i < toI32(src.params.length); i++) {
609
+ params[i] = src.params[i]
610
+ }
611
+ r.params = params
612
+ }
613
+ if (src.bodyLength > 0) {
614
+ const body: u8[] = new Array<u8>(src.bodyLength)
615
+ copyBytes(body, 0, src.body, 0, src.bodyLength)
616
+ r.body = body
617
+ }
618
+ r.head = head
619
+ r.spans = spans
620
+ r.route = src.route
621
+ r.paramCount = src.paramCount
622
+ r.methodStart = src.methodStart
623
+ r.methodEnd = src.methodEnd
624
+ r.targetStart = src.targetStart
625
+ r.targetEnd = src.targetEnd
626
+ r.pathEnd = src.pathEnd
627
+ r.headLength = src.headLength
628
+ r.headerCount = src.headerCount
629
+ r.bodyLength = src.bodyLength
630
+ const res: Response = await handle(new Request(r))
631
+ st.status[k] = res.status
632
+ const out: u8[] = st.bodies[k]
633
+ // A length the body cannot hold, negative or past either array, is the
634
+ // handler's mistake: the loop answers 500 for it, as for an over-long body.
635
+ if (res.length < 0 || res.length > toI32(out.length) || res.length > toI32(res.body.length)) {
636
+ st.lengths[k] = -1
637
+ } else {
638
+ // The whole body is copied when the slot holds it, as one `set`: what lies
639
+ // past `length` is never sent. Only a body larger than the slot is copied
640
+ // byte by byte, up to `length`.
641
+ if (res.body.length <= out.length) {
642
+ out.set(res.body)
643
+ } else {
644
+ for (let i: i32 = 0; i < res.length && i < toI32(out.length) && i < toI32(res.body.length); i++) {
645
+ out[i] = res.body[i]
646
+ }
647
+ }
648
+ st.lengths[k] = res.length
649
+ }
650
+ // A type the server has sent before is found by its text, with no copy;
651
+ // the loop copies a new one's bytes into `typeBytes` as it sends it.
652
+ const n: i32 = toI32(res.type.length)
653
+ let known: i32 = -1
654
+ for (let i: i32 = 0; n > 0 && known < 0 && i < toI32(st.typeTexts.length); i++) {
655
+ if (st.typeTexts[i] === res.type) {
656
+ known = i
657
+ }
658
+ }
659
+ st.typeIndex[k] = known
660
+ const type: u8[] = st.types[k]
661
+ if (known >= 0) {
662
+ st.typeLengths[k] = n
663
+ } else if (n > toI32(type.length)) {
664
+ st.typeLengths[k] = -1
665
+ } else {
666
+ for (let i: i32 = 0; i < n && i < toI32(type.length); i++) {
667
+ type[i] = toU8(res.type.charCodeAt(i))
668
+ }
669
+ st.typeLengths[k] = n
670
+ }
671
+ st.done[k] = true
672
+ st.finished[st.finishedCount] = k
673
+ st.finishedCount += 1
674
+ st.fresh = true
675
+ if (!st.awake && !st.signalled) {
676
+ st.signalled = true
677
+ netWrite(st.wakeFd, st.one, 0, 1)
678
+ }
679
+ }
680
+
681
+ /** Wakes the loop every `SERVE_TICK_MS`, so the handler's timeouts run while no socket is ready; ends once the loop stops. */
682
+ const serveTick = async (st: ServeState): Promise<void> => {
683
+ while (!st.stopped) {
684
+ await sleep(SERVE_TICK_MS)
685
+ if (!st.stopped && !st.signalled) {
686
+ st.signalled = true
687
+ netWrite(st.wakeFd, st.one, 0, 1)
688
+ }
689
+ }
690
+ }
691
+
692
+ /**
693
+ * `serve` on a listening socket the program made — `tcpListen` on port 0 in
694
+ * a test, or `tcpListenFlags` with SO_REUSEPORT for a worker — filling
695
+ * `stats` as it runs.
696
+ * @param listener the listening socket, still the program's to close
697
+ * @param router the routes, added before the call
698
+ * @param limits the caps; see `ServeLimits`
699
+ * @param handle the program's answer to a request, run as its own task
700
+ * @param stats where the server counts what it did, the caller's
701
+ * @returns 0 once stopped
702
+ */
703
+ export const serveOn = async (
704
+ listener: i32,
705
+ router: Router,
706
+ limits: ServeLimits,
707
+ handle: (req: Request) => Promise<Response>,
708
+ stats: ServeStats
709
+ ): Promise<i32> => {
710
+ if (limits.connections < 1 || limits.inFlight < 1 || limits.responseBytes < 0) {
711
+ panic(
712
+ `serve: connections ${limits.connections} and inFlight ${limits.inFlight} need at least 1, responseBytes ${limits.responseBytes} at least 0`
713
+ )
714
+ }
715
+ const hl: HandlerLimits = new HandlerLimits()
716
+ hl.slots = limits.connections
717
+ hl.http.maxHeaderBytes = limits.headerBytes
718
+ hl.http.maxBody = limits.bodyBytes
719
+ hl.http.headTimeout = limits.headTimeout
720
+ hl.http.idleTimeout = limits.idleTimeout
721
+ const h: HttpHandler = new HttpHandler(hl, listener, router)
722
+ h.deferSends()
723
+ const st: ServeState = new ServeState()
724
+ st.deadline = limits.deadline
725
+ serveFields(st, limits.server)
726
+ const fds: i32[] = [0, 0]
727
+ const made: i32 = unixSocketPair(NET_UNIX_STREAM, fds)
728
+ if (made < 0) {
729
+ panic(`serve: the wake socket could not be made: ${made}`)
730
+ }
731
+ st.wakeFd = fds[1]
732
+ h.watch(fds[0], SERVE_WAKE)
733
+ const drained: u8[] = new Array<u8>(64)
734
+ spawn(serveTick(st))
735
+ let draining: boolean = false
736
+ while (true) {
737
+ st.awake = true
738
+ h.wait(0)
739
+ if (h.fired(SERVE_WAKE)) {
740
+ st.signalled = false
741
+ while (netRead(fds[0], drained, 0, 64) > 0) {
742
+ // Each read takes up to 64 wake bytes; the loop empties the socket.
743
+ }
744
+ }
745
+ // Each pass answers what the tasks wrote and takes what the handler
746
+ // queued: a pipelined request is queued once the one before it is
747
+ // answered, so a burst on a connection is taken and answered in request
748
+ // order within this turn, and the handler sends the answers together.
749
+ let moved: boolean = true
750
+ while (moved || st.fresh) {
751
+ moved = false
752
+ st.fresh = false
753
+ // A task appends its slot as it answers; none runs while the loop
754
+ // does, so the list is read whole and emptied.
755
+ for (let i: i32 = 0; i < st.finishedCount && i < toI32(st.finished.length); i++) {
756
+ const k: i32 = st.finished[i]
757
+ serveAnswer(h, st, k, stats)
758
+ st.busy[k] = false
759
+ st.done[k] = false
760
+ st.cancelled[k] = false
761
+ st.tasks[k] = 0
762
+ st.free[st.freeCount] = k
763
+ st.freeCount += 1
764
+ stats.answered += 1
765
+ moved = true
766
+ }
767
+ st.finishedCount = 0
768
+ while (h.ready()) {
769
+ const r: HttpRequest = h.take()
770
+ const k: i32 = serveFreeSlot(st, limits)
771
+ moved = true
772
+ if (k < 0) {
773
+ h.problem(r, 503, "Service Unavailable", "")
774
+ stats.busy += 1
775
+ stats.answered += 1
776
+ continue
777
+ }
778
+ st.reqs[k] = r
779
+ st.busy[k] = true
780
+ st.done[k] = false
781
+ st.cancelled[k] = false
782
+ st.tasks[k] = 0
783
+ if (!st.listed[k]) {
784
+ st.listed[k] = true
785
+ st.running[st.runningCount] = k
786
+ st.runningCount += 1
787
+ }
788
+ spawn(serveTask(handle, st, k))
789
+ }
790
+ }
791
+ // A task still running whose client hung up, or any once the server is
792
+ // stopping: nobody waits for its answer, so it is told to stop waiting
793
+ // too. The answered ones leave the list here.
794
+ let kept: i32 = 0
795
+ for (let i: i32 = 0; i < st.runningCount && i < toI32(st.running.length); i++) {
796
+ const k: i32 = st.running[i]
797
+ if (st.busy[k] && !st.done[k]) {
798
+ if (st.stopping || h.hungUp(st.reqs[k])) {
799
+ serveCancel(st, k)
800
+ }
801
+ st.running[kept] = k
802
+ kept += 1
803
+ } else {
804
+ st.listed[k] = false
805
+ }
806
+ }
807
+ st.runningCount = kept
808
+ // The turn's answers go out together, before the arena is read, so a
809
+ // close the send causes is counted in the turn that caused it.
810
+ h.flush()
811
+ stats.sends = h.sends()
812
+ stats.slots = toI32(st.busy.length)
813
+ if (stats.warmAfter > 0 && stats.usedWarm === 0 && stats.answered >= stats.warmAfter) {
814
+ stats.usedWarm = Arena.used()
815
+ }
816
+ if (!draining && limits.maxRequests > 0 && stats.answered >= limits.maxRequests) {
817
+ draining = true
818
+ stats.usedEnd = Arena.used()
819
+ h.drain()
820
+ st.stopping = true
821
+ for (let k: i32 = 0; k < toI32(st.busy.length); k++) {
822
+ if (st.busy[k] && !st.done[k]) {
823
+ serveCancel(st, k)
824
+ }
825
+ }
826
+ }
827
+ if (draining && h.connections() === 0 && !serveAnyBusy(st)) {
828
+ break
829
+ }
830
+ if (h.ready()) {
831
+ // A send let a parked request in: take it before parking.
832
+ continue
833
+ }
834
+ st.awake = false
835
+ await readable(h.loop)
836
+ }
837
+ st.stopped = true
838
+ netClose(fds[0])
839
+ netClose(fds[1])
840
+ netClose(h.loop)
841
+ return 0
842
+ }
843
+
844
+ /**
845
+ * Serves HTTP/1.1 on `port` on every address, handing each request to
846
+ * `handle` in a task of its own, until `limits.maxRequests` are answered (for
847
+ * good when it is 0).
848
+ * @param port the TCP port to listen on
849
+ * @param router the routes, added before the call; a request's `route` is the index `Router.add` answered
850
+ * @param limits the caps; see `ServeLimits`
851
+ * @param handle the program's answer to a request, run as its own task
852
+ * @returns 0 once stopped, or the negative error `tcpListen` answered
853
+ */
854
+ export const serve = async (
855
+ port: i32,
856
+ router: Router,
857
+ limits: ServeLimits,
858
+ handle: (req: Request) => Promise<Response>
859
+ ): Promise<i32> => {
860
+ const listener: i32 = tcpListen("0.0.0.0", port, SERVE_BACKLOG)
861
+ if (listener < 0) {
862
+ return listener
863
+ }
864
+ const done: i32 = await serveOn(listener, router, limits, handle, new ServeStats())
865
+ netClose(listener)
866
+ return done
867
+ }