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