@amritk/nish-aarch64-linux 0.39.0 → 0.41.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 (57) hide show
  1. package/INSTALL.md +79 -133
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +112 -33
  4. package/package.json +1 -1
  5. package/runtime/nish.d.ts +21 -17
  6. package/runtime/nish.h +10 -0
  7. package/runtime/page-frame.d.ts +123 -0
  8. package/runtime/page-frame.mjs +736 -0
  9. package/runtime/page-game.d.ts +132 -0
  10. package/runtime/page-game.mjs +738 -0
  11. package/runtime/runtime-aes.c +85 -8
  12. package/runtime/runtime-bytes.c +88 -4
  13. package/runtime/runtime-net.c +32 -0
  14. package/runtime/runtime-sandbox.c +55 -28
  15. package/runtime/runtime-uring.c +1194 -0
  16. package/runtime/runtime-wasm.c +422 -0
  17. package/runtime/vite.mjs +1 -1
  18. package/scripts/build.sh +22 -6
  19. package/std/README.md +74 -87
  20. package/std/array.ts +36 -3
  21. package/std/collections.ts +51 -0
  22. package/std/crypto/hmac.ts +37 -10
  23. package/std/crypto/p256.ts +1388 -2664
  24. package/std/crypto/pki.ts +116 -4
  25. package/std/crypto/sha256.ts +34 -6
  26. package/std/crypto/x509.ts +7 -0
  27. package/std/host/game.ts +273 -0
  28. package/std/input.ts +56 -0
  29. package/std/json-tokenizer.ts +325 -112
  30. package/std/json-typed.ts +43 -8
  31. package/std/json-value.ts +144 -3
  32. package/std/json.ts +63 -8
  33. package/std/net/fetch.ts +22 -4
  34. package/std/net/http-server.ts +3382 -0
  35. package/std/net/http1-client-codec.ts +6 -2
  36. package/std/net/http1-codec.ts +137 -12
  37. package/std/net/http1-server.ts +83 -29
  38. package/std/net/http2.ts +47 -14
  39. package/std/net/http3-server.ts +29 -3
  40. package/std/net/http3.ts +180 -7
  41. package/std/net/prefork.ts +49 -13
  42. package/std/net/quic-recovery.ts +240 -9
  43. package/std/net/quic-stream.ts +21 -1
  44. package/std/net/quic.ts +98 -4
  45. package/std/net/router.ts +378 -31
  46. package/std/net/serve.ts +873 -65
  47. package/std/net/tls/verify.ts +19 -1
  48. package/std/net/url.ts +83 -35
  49. package/std/net/websocket.ts +74 -1
  50. package/std/net/webtransport.ts +7 -1
  51. package/std/raster.ts +837 -0
  52. package/std/release.ts +593 -0
  53. package/std/synth.ts +143 -0
  54. package/std/temporal.ts +3091 -0
  55. package/std/threads.ts +298 -0
  56. package/std/yaml-json.ts +368 -28
  57. package/std/yaml.ts +122 -27
package/std/net/serve.ts CHANGED
@@ -27,15 +27,19 @@
27
27
  * return await serve(8080, router, new ServeLimits(), handle)
28
28
  * }
29
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.
30
+ * `serve` drives `nish/net/http1-server`'s connections from a readiness loop
31
+ * of its own, as an `async` function: it awaits the loop's descriptor, so
32
+ * the program's other tasks run while no socket is ready. It routes each
33
+ * request at its head, gathers its body, and hands the whole request to
34
+ * `handle` in a task of its own, spawned with the request's slot; the
35
+ * task's allocations — the request it reads, the response it builds,
36
+ * whatever `handle` makes on the way — live in the task's region and go
37
+ * when it ends.
36
38
  *
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
+ * **The task reads its own copy.** Until it is answered, a request's head is
40
+ * the connection parser's own buffer, read in place. The task copies the
41
+ * head and body into its own memory before `handle` runs, as `spawn` runs it
42
+ * that far at once,
39
43
  * and when `handle` answers it writes the status, the content type and the
40
44
  * body back into the slot's fixed buffers, in bulk, and wakes the
41
45
  * loop. The loop then sends the answer and frees the slot. Nothing the task
@@ -44,16 +48,16 @@
44
48
  * `Arena.used()` flat over thousands of pipelined requests. What the runtime
45
49
  * allocates outside the arena for a task and its region is not measured.
46
50
  *
47
- * **Answers keep request order.** The handler reads a connection's next
51
+ * **Answers keep request order.** The server reads a connection's next
48
52
  * request only once the one before it is answered, so at most one request
49
53
  * per connection is in flight, and pipelined requests are answered in the
50
54
  * order they came: a later request's task starts only after the earlier one
51
55
  * is answered, so it can never finish first.
52
56
  *
53
57
  * **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
58
+ * tasks wrote and takes what the connections queued until neither moves, so
59
+ * a `handle` that answers without waiting serves a whole burst in one turn.
60
+ * The loop holds each answer's send while the next request on its
57
61
  * connection is queued and the output has room, and the loop flushes once
58
62
  * before it parks: one write per connection per turn, and no wake byte for a
59
63
  * task that answers while the loop runs.
@@ -70,10 +74,40 @@
70
74
  * (`docs/wp26-stdlib.md` §3e), which is why each one carries the module's name.
71
75
  */
72
76
  import { copyBytes } from "nish/bytes"
73
- import { HandlerLimits, HttpHandler, HttpRequest } from "nish/net/handler"
74
- import { ROUTER_BAD_ESCAPE, Router } from "nish/net/router"
77
+ import { JsonWriter } from "nish/json"
78
+ import { HttpRequest } from "nish/net/handler"
79
+ import { HTTP1_NO_BODY } from "nish/net/http1-codec"
80
+ import {
81
+ H1_AGAIN,
82
+ H1_BODY,
83
+ H1_DONE,
84
+ H1_END,
85
+ H1_ERROR,
86
+ H1_NEED_MORE,
87
+ H1_POOL_FULL,
88
+ H1_REQUEST,
89
+ H1_WANT_READ,
90
+ H1_WANT_WRITE,
91
+ H1_WRITE,
92
+ Http1Config,
93
+ Http1Connection,
94
+ Http1Server,
95
+ } from "nish/net/http1-server"
96
+ import { ROUTER_BAD_ESCAPE, ROUTER_METHOD_NOT_ALLOWED, Router } from "nish/net/router"
75
97
  import { cancel, cancelAfter, readable, sleep, spawn, taskId } from "nish:async"
76
- import { NET_UNIX_STREAM, netClose, netRead, netWrite, tcpListen, unixSocketPair } from "nish:net"
98
+ import {
99
+ NET_UNIX_STREAM,
100
+ netClose,
101
+ netRead,
102
+ netWrite,
103
+ pollAdd,
104
+ pollCreate,
105
+ pollModify,
106
+ pollRemove,
107
+ pollWait,
108
+ tcpListen,
109
+ unixSocketPair,
110
+ } from "nish:net"
77
111
 
78
112
  /** The listen backlog `serve` asks for. */
79
113
  const SERVE_BACKLOG: i32 = 1024
@@ -81,12 +115,44 @@ const SERVE_BACKLOG: i32 = 1024
81
115
  const SERVE_TYPE_BYTES: i32 = 128
82
116
  /** Distinct content types the server keeps the bytes of; past it a new type is answered 500. */
83
117
  const SERVE_MAX_TYPES: i32 = 64
84
- /** Milliseconds between the ticker's wakes, which run the handler's timeouts. */
118
+ /** Milliseconds between the ticker's wakes, which run the connections' timeouts. */
85
119
  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`. */
120
+ /** `refused` marks a response the loop answers with 404 or 405. */
89
121
  const SERVE_REFUSE: i32 = -1
122
+ /** The poll token of the listening socket. */
123
+ const SERVE_LISTENER: i32 = -1
124
+ /** The poll token of the wake socket. */
125
+ const SERVE_WAKE: i32 = -2
126
+ /** The ready bits that mean a socket can be read or has hung up: EPOLLIN | EPOLLHUP's poll mapping. */
127
+ const SERVE_READ_BITS: i32 = 5
128
+ /** Sockets one poll reports at most. */
129
+ const SERVE_EVENTS: i32 = 256
130
+ /** `accept`'s answer when the backlog is empty. */
131
+ const SERVE_ACCEPT_NONE: i32 = -11
132
+ /** `accept`'s answer when a connection was reset in the backlog: the next one is tried. */
133
+ const SERVE_ACCEPT_ABORTED: i32 = -103
134
+ /** Nanoseconds the listener rests after `accept` runs out of descriptors or memory. */
135
+ const SERVE_ACCEPT_REST: i64 = 100000000
136
+ /** Nanoseconds between the checks for a request body that is too slow. */
137
+ const SERVE_BODY_SWEEP: i64 = 1000000000
138
+ /** Nanoseconds a request's body may take to arrive, from its head. */
139
+ const SERVE_BODY_TIMEOUT: i64 = 30000000000
140
+ // A connection slot's exchange state, `ServeExchange.state`: these SERVE_*
141
+ // numbers are not `HttpHandler`'s HANDLER_* ones (its FLUSHING is 6, and
142
+ // `serve` has no STREAMING), and `serve` does not keep them in
143
+ // `HttpRequest.state`, since a slot holds no record between exchanges.
144
+ /** A slot's exchange: no request. */
145
+ const SERVE_IDLE: i32 = 0
146
+ /** A slot's exchange: its head is read and its body is arriving. */
147
+ const SERVE_READING: i32 = 1
148
+ /** A slot's exchange: whole, waiting for room in the output before it is queued. */
149
+ const SERVE_PARKED: i32 = 2
150
+ /** A slot's exchange: whole and queued for a task. */
151
+ const SERVE_QUEUED: i32 = 3
152
+ /** A slot's exchange: a task holds it. */
153
+ const SERVE_HELD: i32 = 4
154
+ /** A slot's exchange: answered, its last bytes waiting for room. */
155
+ const SERVE_FLUSHING: i32 = 5
90
156
  /** The status a program's malformed answer is sent as. */
91
157
  const SERVE_FAILED: i32 = 500
92
158
 
@@ -166,7 +232,7 @@ export class ServeStats {
166
232
  export class Request {
167
233
  /** The index `Router.add` answered for the route, or a negative `ROUTER_*` code. */
168
234
  route: i32 = 0
169
- /** The request as the handler parsed it, copied into the task: its spans, its head and its body. */
235
+ /** The request as the server parsed it, copied into the task: its spans, its head and its body. */
170
236
  raw: HttpRequest
171
237
 
172
238
  /**
@@ -330,7 +396,7 @@ export class Response {
330
396
  * The answer for a request the router refused: 405 with an `Allow` field
331
397
  * naming the methods the path has, and 404 for anything else.
332
398
  * @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
399
+ * @returns a response the server answers with 404, or 405 and an `Allow` field naming the methods its path has
334
400
  */
335
401
  export const refuse = (_req: Request): Response => new Response(SERVE_REFUSE)
336
402
 
@@ -340,8 +406,11 @@ export const refuse = (_req: Request): Response => new Response(SERVE_REFUSE)
340
406
  * used, and kept.
341
407
  */
342
408
  class ServeState {
343
- /** The request each slot holds, the handler's until it is answered. */
409
+ /** The request each slot holds: its connection's, read by the task before it first waits. */
344
410
  reqs: HttpRequest[]
411
+ /** The connection slot each request was read on, and that slot's generation then: where its answer goes. */
412
+ slots: i32[]
413
+ gens: i32[]
345
414
  /** Whether a slot holds a request. */
346
415
  busy: boolean[]
347
416
  /** Whether a slot's task has written its answer. */
@@ -405,6 +474,8 @@ class ServeState {
405
474
 
406
475
  constructor() {
407
476
  this.reqs = []
477
+ this.slots = []
478
+ this.gens = []
408
479
  this.busy = []
409
480
  this.done = []
410
481
  this.tasks = []
@@ -449,8 +520,12 @@ const serveFields = (st: ServeState, server: string): void => {
449
520
  st.typedValues.push(type)
450
521
  }
451
522
 
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 => {
523
+ /**
524
+ * The last freed slot, making one when every slot is busy and `inFlight`
525
+ * allows; -1 when none. A slot made here starts on `rec`, the record its
526
+ * first request is copied from, which the caller sets again for each one.
527
+ */
528
+ const serveFreeSlot = (st: ServeState, limits: ServeLimits, rec: HttpRequest): i32 => {
454
529
  if (st.freeCount > 0) {
455
530
  st.freeCount -= 1
456
531
  return st.free[st.freeCount]
@@ -459,7 +534,9 @@ const serveFreeSlot = (st: ServeState, limits: ServeLimits): i32 => {
459
534
  if (n >= limits.inFlight) {
460
535
  return -1
461
536
  }
462
- st.reqs.push(new HttpRequest(-1))
537
+ st.reqs.push(rec)
538
+ st.slots.push(toI32(0))
539
+ st.gens.push(toI32(0))
463
540
  st.busy.push(false)
464
541
  st.done.push(false)
465
542
  st.tasks.push(toI64(0))
@@ -499,36 +576,33 @@ const serveAnyBusy = (st: ServeState): boolean => {
499
576
  }
500
577
 
501
578
  /** 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]
579
+ const serveAnswer = (c: ServeConns, st: ServeState, k: i32, stats: ServeStats): void => {
580
+ const s: i32 = st.slots[k]
581
+ const gen: i32 = st.gens[k]
504
582
  const status: i32 = st.status[k]
505
583
  if (status === SERVE_REFUSE) {
506
- h.refuse(r)
584
+ c.refuse(s, gen)
507
585
  return
508
586
  }
509
587
  const length: i32 = st.lengths[k]
510
588
  if (status < 200 || status > 599 || length < 0 || st.typeLengths[k] < 0) {
511
589
  stats.failed += 1
512
- h.problem(r, SERVE_FAILED, "Internal Server Error", "")
590
+ c.problem(s, gen, SERVE_FAILED, c.failed)
513
591
  return
514
592
  }
515
593
  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
- }
594
+ c.send(s, gen, status, st.plainNames, st.plainValues, st.bodies[k], length)
521
595
  return
522
596
  }
523
597
  const type: i32 = st.typeIndex[k] >= 0 ? st.typeIndex[k] : serveType(st, st.types[k], st.typeLengths[k])
524
598
  if (type < 0) {
525
599
  stats.failed += 1
526
- h.problem(r, SERVE_FAILED, "Internal Server Error", "")
600
+ c.problem(s, gen, SERVE_FAILED, c.failed)
527
601
  return
528
602
  }
529
603
  const last: i32 = toI32(st.typedValues.length) - 1
530
604
  st.typedValues[last] = st.typeBytes[type]
531
- h.sendFields(r, status, st.typedNames, st.typedValues, st.bodies[k], toI32(0), length)
605
+ c.send(s, gen, status, st.typedNames, st.typedValues, st.bodies[k], length)
532
606
  }
533
607
 
534
608
  /** 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. */
@@ -553,7 +627,7 @@ const serveType = (st: ServeState, type: u8[], len: i32): i32 => {
553
627
  return -1
554
628
  }
555
629
  // 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.
630
+ // which `ServeConns.send` treats as a program's mistake and panics on.
557
631
  for (let j: i32 = 0; j < len && j < toI32(type.length); j++) {
558
632
  if ((type[j] < 32 && type[j] !== 9) || type[j] === 127) {
559
633
  return -1
@@ -678,7 +752,7 @@ const serveTask = async (
678
752
  }
679
753
  }
680
754
 
681
- /** Wakes the loop every `SERVE_TICK_MS`, so the handler's timeouts run while no socket is ready; ends once the loop stops. */
755
+ /** Wakes the loop every `SERVE_TICK_MS`, so the connections' timeouts run while no socket is ready; ends once the loop stops. */
682
756
  const serveTick = async (st: ServeState): Promise<void> => {
683
757
  while (!st.stopped) {
684
758
  await sleep(SERVE_TICK_MS)
@@ -689,6 +763,737 @@ const serveTick = async (st: ServeState): Promise<void> => {
689
763
  }
690
764
  }
691
765
 
766
+ /** The RFC 9457 problem object `{"type":"about:blank","title":…,"status":…}` as bytes. */
767
+ const serveProblem = (status: i32, title: string): u8[] => {
768
+ const buf: u8[] = new Array<u8>(256)
769
+ const w: JsonWriter = new JsonWriter(buf, 0)
770
+ w.beginObject()
771
+ w.key("type")
772
+ w.string("about:blank")
773
+ w.key("title")
774
+ w.string(title)
775
+ w.key("status")
776
+ w.i32(status)
777
+ w.endObject()
778
+ const out: u8[] = new Array<u8>(w.end)
779
+ copyBytes(out, 0, buf, 0, w.end)
780
+ return out
781
+ }
782
+
783
+ /** Whether `bytes[start .. end)` is the ASCII text `text`. */
784
+ const serveSpanIs = (bytes: u8[], start: i32, end: i32, text: string): boolean => {
785
+ const n: i32 = toI32(text.length)
786
+ if (end - start !== n || start < 0 || end > toI32(bytes.length)) {
787
+ return false
788
+ }
789
+ for (let k: i32 = 0; k < n; k++) {
790
+ if (toI32(bytes[start + k]) !== toI32(text.charCodeAt(k))) {
791
+ return false
792
+ }
793
+ }
794
+ return true
795
+ }
796
+
797
+ /** Appends `bytes[start .. end)` to an `allow` value, after ", " unless it is the first. */
798
+ const serveAllowAppend = (value: u8[], bytes: u8[], start: i32, end: i32): void => {
799
+ if (value.length > 0) {
800
+ value.push(toU8(44))
801
+ value.push(toU8(32))
802
+ }
803
+ for (let k: i32 = start; k < end; k++) {
804
+ if (k >= 0 && k < toI32(bytes.length)) {
805
+ value.push(bytes[k])
806
+ }
807
+ }
808
+ }
809
+
810
+ /** A buffer size at least `need`, doubling from `have` (64 at least). */
811
+ const serveGrown = (have: i32, need: i32): i32 => {
812
+ let size: i32 = have < 64 ? 64 : have
813
+ while (size < need && size < 1073741824) {
814
+ size = size * 2
815
+ }
816
+ return size < need ? need : size
817
+ }
818
+
819
+ /** One slot's exchange: what it needs after its task's copy, and its record until then. */
820
+ class ServeExchange {
821
+ /** The slot's connection: the carrier keeps one object per slot, set again on each accept. */
822
+ conn: Http1Connection
823
+ /** The record, from the head's parse to the task's copy; `ServeConns.none` otherwise. */
824
+ rec: HttpRequest
825
+ /** What the output had no room for yet, `pending[pendingStart .. pendingEnd)`; `noBytes` until the slot needs its own. */
826
+ pending: u8[]
827
+ /** One of the SERVE_* states; 0 is `SERVE_IDLE`. */
828
+ state: i32 = 0
829
+ /** The route `begin` matched: what `refuse` answers from once the record is given back. */
830
+ route: i32 = 0
831
+ pendingStart: i32 = 0
832
+ pendingEnd: i32 = 0
833
+ /** Whether `rec` is this exchange's, not `none`. */
834
+ holds: boolean = false
835
+
836
+ constructor(conn: Http1Connection, none: HttpRequest, noBytes: u8[]) {
837
+ this.conn = conn
838
+ this.rec = none
839
+ this.pending = noBytes
840
+ }
841
+ }
842
+
843
+ /**
844
+ * The connections: an `Http1Server` driven straight from the loop. A slot
845
+ * holds an `HttpRequest` record only from the head's parse to the task's
846
+ * copy: `begin` takes a spare one (building one only when every built
847
+ * record is held) and the loop gives it back once the task has copied it, or
848
+ * once it answered 503, or the connection closed first. The record's head
849
+ * and spans are the parser's own: the parser keeps them until the exchange's
850
+ * answer is sent, and the request's task copies them before it first waits,
851
+ * as `spawn` runs it that far at once. What an exchange needs after the copy
852
+ * — its state, its route for a 404 or 405, the answer's pending bytes — is
853
+ * the slot's own, in a `ServeExchange`: a few dozen bytes, and the pending
854
+ * array, which doubles from 64 bytes until it holds the most of an answer
855
+ * the output could not take (under 2 × `responseBytes`, at most the power of
856
+ * two at or above it) and is kept for the slot's next answer. An exchange
857
+ * moves idle → reading → (parked →) queued → held → (flushing →) idle; a
858
+ * slot whose connection closes goes idle and its generation moves on, so an
859
+ * answer for it is dropped.
860
+ */
861
+ class ServeConns {
862
+ server: Http1Server
863
+ router: Router
864
+ /** The spare request records, `spare[0 .. spareCount)`, the last given back on top; every record built has a place here. */
865
+ spare: HttpRequest[]
866
+ /** Each slot's exchange, made (`growSlots`) as `acceptAll` first fills the slot. */
867
+ ex: ServeExchange[]
868
+ /** The record an exchange points at while it holds none; never read. */
869
+ none: HttpRequest
870
+ noBytes: u8[]
871
+ /** Each slot's generation: moves on when its connection closes. */
872
+ slotGen: i32[]
873
+ /** Whether a slot holds a connection the loop accepted and has not forgotten. */
874
+ open: boolean[]
875
+ /** Whether a slot's send is owed, so it is listed in `owed` once. */
876
+ owing: boolean[]
877
+ /** The slots whose send waits for the end of the turn, `owed[0 .. owedCount)`. */
878
+ owed: i32[]
879
+ /**
880
+ * The queued exchanges' slots, a ring from `queueStart`, and each one's
881
+ * generation when queued. Its length stays a power of two, so a position
882
+ * wraps with a mask.
883
+ */
884
+ queue: i32[]
885
+ queueGen: i32[]
886
+ /** `pollWait`'s answers: token and bits per ready socket. */
887
+ readyFds: i32[]
888
+ /** The parameter spans `allowFor`'s matches write. */
889
+ probe: i32[]
890
+ /** The fields of a problem answer, and of a 405, whose `allow` value is set per answer. */
891
+ problemNames: u8[][]
892
+ problemValues: u8[][]
893
+ allowNames: u8[][]
894
+ allowValues: u8[][]
895
+ /** Each method set an `allow` value was made for, and that value. */
896
+ allowMasks: i64[]
897
+ allowBytes: u8[][]
898
+ /** The problem bodies of 404, 405, 500 and 503. */
899
+ notFound: u8[]
900
+ notAllowed: u8[]
901
+ failed: u8[]
902
+ unavailable: u8[]
903
+ /** When the listener comes back after a rest, or 0. */
904
+ acceptRestUntil: i64 = 0
905
+ /** The clock at the start of this turn, which stamps a head. */
906
+ turnAt: i64 = 0
907
+ /** When slow bodies are next looked for. */
908
+ bodyCheckAt: i64 = 0
909
+ /** Sends made: each settle of a connection with bytes to write. */
910
+ sent: i64 = 0
911
+ listener: i32 = 0
912
+ loop: i32 = 0
913
+ queueStart: i32 = 0
914
+ queueCount: i32 = 0
915
+ owedCount: i32 = 0
916
+ spareCount: i32 = 0
917
+ outputSize: i32 = 0
918
+ /** The most slots the carrier hands out, `limits.connections`. */
919
+ slotLimit: i32 = 0
920
+ /** Set once the server stops taking connections and requests. */
921
+ draining: boolean = false
922
+
923
+ constructor(limits: ServeLimits, listener: i32, router: Router) {
924
+ const config: Http1Config = new Http1Config()
925
+ config.maxHeaderBytes = limits.headerBytes
926
+ config.maxBody = limits.bodyBytes
927
+ config.headTimeout = limits.headTimeout
928
+ config.idleTimeout = limits.idleTimeout
929
+ this.server = new Http1Server(config, listener, limits.connections)
930
+ this.router = router
931
+ this.listener = listener
932
+ this.outputSize = config.outputSize
933
+ this.slotLimit = limits.connections
934
+ this.spare = []
935
+ this.ex = []
936
+ this.none = new HttpRequest(-1)
937
+ this.noBytes = []
938
+ this.slotGen = new Array<i32>(limits.connections)
939
+ this.open = new Array<boolean>(limits.connections)
940
+ this.owing = new Array<boolean>(limits.connections)
941
+ this.owed = new Array<i32>(limits.connections)
942
+ this.queue = new Array<i32>(16)
943
+ this.queueGen = new Array<i32>(16)
944
+ this.readyFds = new Array<i32>(2 * SERVE_EVENTS)
945
+ this.probe = new Array<i32>(2 * router.maxParams + 2)
946
+ const contentType: u8[] = serveBytes("content-type")
947
+ const problemType: u8[] = serveBytes("application/problem+json")
948
+ this.problemNames = [contentType]
949
+ this.problemValues = [problemType]
950
+ this.allowNames = [contentType, serveBytes("allow")]
951
+ this.allowValues = [problemType, problemType]
952
+ this.allowMasks = []
953
+ this.allowBytes = []
954
+ this.notFound = serveProblem(404, "Not Found")
955
+ this.notAllowed = serveProblem(405, "Method Not Allowed")
956
+ this.failed = serveProblem(SERVE_FAILED, "Internal Server Error")
957
+ this.unavailable = serveProblem(503, "Service Unavailable")
958
+ this.loop = pollCreate()
959
+ if (this.loop < 0) {
960
+ panic(`serve: pollCreate failed: ${this.loop}`)
961
+ }
962
+ pollAdd(this.loop, listener, H1_WANT_READ, SERVE_LISTENER)
963
+ }
964
+
965
+ /**
966
+ * One turn: sends what the last turn owed, takes what the sockets have
967
+ * ready without blocking, and runs the timeouts. Answers whether the wake
968
+ * socket was ready.
969
+ */
970
+ turn(): boolean {
971
+ this.flush()
972
+ if (this.acceptRestUntil > 0 && monotonicNanos() >= this.acceptRestUntil) {
973
+ this.acceptRestUntil = 0
974
+ if (!this.draining) {
975
+ pollAdd(this.loop, this.listener, H1_WANT_READ, SERVE_LISTENER)
976
+ }
977
+ }
978
+ const n: i32 = pollWait(this.loop, this.readyFds, 0)
979
+ const now: i64 = monotonicNanos()
980
+ this.turnAt = now
981
+ let woken: boolean = false
982
+ for (let k: i32 = 0; k < n; k++) {
983
+ const token: i32 = this.readyFds[2 * k]
984
+ if (token === SERVE_LISTENER) {
985
+ this.acceptAll()
986
+ } else if (token === SERVE_WAKE) {
987
+ woken = true
988
+ } else if (token >= 0 && this.server.holds(token)) {
989
+ if ((this.readyFds[2 * k + 1] & SERVE_READ_BITS) !== 0) {
990
+ this.server.readable(token)
991
+ } else {
992
+ this.server.writable(token)
993
+ }
994
+ this.drive(token)
995
+ }
996
+ }
997
+ if (this.server.expire(now) > 0) {
998
+ // The carrier closed idle or late connections: forget them.
999
+ for (let s: i32 = 0; s < toI32(this.open.length); s++) {
1000
+ if (this.open[s] && !this.server.holds(s)) {
1001
+ this.forget(s)
1002
+ }
1003
+ }
1004
+ }
1005
+ if (now >= this.bodyCheckAt) {
1006
+ this.bodyCheckAt = now + SERVE_BODY_SWEEP
1007
+ for (let s: i32 = 0; s < toI32(this.open.length); s++) {
1008
+ if (this.open[s] && this.ex[s].state === SERVE_READING && this.ex[s].holds) {
1009
+ if (now - this.ex[s].rec.since > SERVE_BODY_TIMEOUT) {
1010
+ this.closeSlot(s)
1011
+ }
1012
+ }
1013
+ }
1014
+ }
1015
+ return woken
1016
+ }
1017
+
1018
+ /** Stops taking connections; a connection between exchanges closes, the others close after their exchange. */
1019
+ drain(): void {
1020
+ if (this.draining) {
1021
+ return
1022
+ }
1023
+ this.draining = true
1024
+ if (this.acceptRestUntil === 0) {
1025
+ pollRemove(this.loop, this.listener)
1026
+ }
1027
+ for (let s: i32 = 0; s < toI32(this.open.length); s++) {
1028
+ if (this.open[s] && this.server.holds(s)) {
1029
+ if (this.ex[s].state === SERVE_IDLE && !this.ex[s].conn.wantsWrite()) {
1030
+ this.closeSlot(s)
1031
+ } else {
1032
+ this.ex[s].conn.closeAfter = true
1033
+ }
1034
+ }
1035
+ }
1036
+ }
1037
+
1038
+ /** Accepts every waiting connection; out of descriptors or memory, rests the listener rather than spin. */
1039
+ acceptAll(): void {
1040
+ if (this.draining) {
1041
+ return
1042
+ }
1043
+ let slot: i32 = this.server.accept()
1044
+ while (slot >= 0 || slot === H1_POOL_FULL || slot === SERVE_ACCEPT_ABORTED) {
1045
+ if (slot >= 0) {
1046
+ // The carrier takes a freed slot first, then the next never used,
1047
+ // so a slot's entries are made on its first connection: a server
1048
+ // sized for many connections pays for the ones it has had.
1049
+ if (slot >= toI32(this.ex.length)) {
1050
+ this.growSlots(slot)
1051
+ }
1052
+ this.open[slot] = true
1053
+ const e: ServeExchange = this.ex[slot]
1054
+ e.state = SERVE_IDLE
1055
+ e.conn = this.server.connection(slot)
1056
+ pollAdd(this.loop, this.server.fd(slot), H1_WANT_READ, slot)
1057
+ }
1058
+ slot = this.server.accept()
1059
+ }
1060
+ if (slot !== SERVE_ACCEPT_NONE) {
1061
+ pollRemove(this.loop, this.listener)
1062
+ this.acceptRestUntil = monotonicNanos() + SERVE_ACCEPT_REST
1063
+ }
1064
+ }
1065
+
1066
+ /** Sends what each slot owes, once per turn. */
1067
+ flush(): void {
1068
+ const n: i32 = this.owedCount
1069
+ this.owedCount = 0
1070
+ for (let k: i32 = 0; k < n; k++) {
1071
+ const slot: i32 = this.owed[k]
1072
+ this.owing[slot] = false
1073
+ if (this.open[slot] && this.server.holds(slot)) {
1074
+ this.settle(slot, this.ex[slot].conn)
1075
+ }
1076
+ }
1077
+ }
1078
+
1079
+ /** Runs slot `s`'s events until it needs bytes, then owes or makes its send. */
1080
+ drive(s: i32): void {
1081
+ this.driveOn(s, this.ex[s])
1082
+ }
1083
+
1084
+ /** `drive` for a caller that holds slot `s`'s exchange `e`. */
1085
+ driveOn(s: i32, e: ServeExchange): void {
1086
+ const conn: Http1Connection = e.conn
1087
+ let event: i32 = this.server.next(s)
1088
+ while (event !== H1_NEED_MORE && event !== H1_ERROR) {
1089
+ if (event === H1_REQUEST) {
1090
+ this.begin(s, conn)
1091
+ } else if (event === H1_BODY && e.state === SERVE_READING && e.holds) {
1092
+ const r: HttpRequest = e.rec
1093
+ const n: i32 = conn.dataLength
1094
+ const need: i32 = r.bodyLength + n
1095
+ if (toI32(r.body.length) < need) {
1096
+ const grown: u8[] = new Array<u8>(serveGrown(toI32(r.body.length), need))
1097
+ copyBytes(grown, 0, r.body, 0, r.bodyLength)
1098
+ r.body = grown
1099
+ }
1100
+ copyBytes(r.body, r.bodyLength, conn.data, conn.dataStart, n)
1101
+ r.bodyLength = need
1102
+ } else if (event === H1_END && e.state === SERVE_READING) {
1103
+ if (this.roomy(conn)) {
1104
+ this.enqueue(s)
1105
+ } else {
1106
+ e.state = SERVE_PARKED
1107
+ }
1108
+ } else if (event === H1_WRITE && e.state === SERVE_FLUSHING) {
1109
+ this.finish(e)
1110
+ }
1111
+ event = this.server.next(s)
1112
+ }
1113
+ if (event === H1_ERROR) {
1114
+ // The carrier has written its refusal and ends the connection.
1115
+ if (e.state === SERVE_READING) {
1116
+ e.state = SERVE_IDLE
1117
+ this.release(s)
1118
+ }
1119
+ } else if (
1120
+ !this.draining &&
1121
+ conn.wantsWrite() &&
1122
+ !conn.writeHeld &&
1123
+ this.roomy(conn) &&
1124
+ e.state !== SERVE_PARKED
1125
+ ) {
1126
+ // The send waits for the turn's end, to go out with the answers after it.
1127
+ if (!this.owing[s]) {
1128
+ this.owing[s] = true
1129
+ this.owed[this.owedCount] = s
1130
+ this.owedCount += 1
1131
+ }
1132
+ return
1133
+ }
1134
+ this.settle(s, conn)
1135
+ }
1136
+
1137
+ /** Sends slot `s`'s output and rearms it; a parked exchange is queued once there is room. */
1138
+ settle(s: i32, conn: Http1Connection): void {
1139
+ if (conn.wantsWrite()) {
1140
+ this.sent += 1
1141
+ }
1142
+ const wants: i32 = this.server.flush(s)
1143
+ const e: ServeExchange = this.ex[s]
1144
+ if ((wants & H1_DONE) !== 0) {
1145
+ this.closeSlot(s)
1146
+ return
1147
+ }
1148
+ if (this.draining && e.state === SERVE_IDLE && !conn.wantsWrite()) {
1149
+ this.closeSlot(s)
1150
+ return
1151
+ }
1152
+ if (this.server.rearm(s, wants)) {
1153
+ pollModify(this.loop, this.server.fd(s), wants & (H1_WANT_READ | H1_WANT_WRITE), s)
1154
+ }
1155
+ if (e.state === SERVE_PARKED && this.roomy(conn)) {
1156
+ this.enqueue(s)
1157
+ }
1158
+ }
1159
+
1160
+ /** Whether the output is at most half full: room for an answer's head behind what is there. */
1161
+ roomy(conn: Http1Connection): boolean {
1162
+ return (conn.outputEnd - conn.outputStart) * 2 <= this.outputSize
1163
+ }
1164
+
1165
+ /**
1166
+ * Grows the per-slot arrays to cover `slot`: doubling from 64 slots while
1167
+ * few are used, then straight to `slotLimit`. The arena keeps every
1168
+ * outgrown array, so doubling all the way would leave as much again behind.
1169
+ * A server sized for many connections pays for the ones it has had.
1170
+ */
1171
+ growSlots(slot: i32): void {
1172
+ // An exchange's connection is set on its slot's accept; until then it
1173
+ // names the one just accepted, which exists.
1174
+ const conn: Http1Connection = this.server.connection(slot)
1175
+ let n: i32 = toI32(this.ex.length) * 2
1176
+ if (n < 64) {
1177
+ n = 64
1178
+ }
1179
+ if (n > 1024 || n > this.slotLimit) {
1180
+ n = this.slotLimit
1181
+ }
1182
+ if (n <= slot) {
1183
+ n = slot + 1
1184
+ }
1185
+ while (toI32(this.ex.length) < n) {
1186
+ this.ex.push(new ServeExchange(conn, this.none, this.noBytes))
1187
+ }
1188
+ }
1189
+
1190
+ /** Takes a spare record, building one only when every built record is held. */
1191
+ acquire(): HttpRequest {
1192
+ if (this.spareCount > 0) {
1193
+ this.spareCount -= 1
1194
+ return this.spare[this.spareCount]
1195
+ }
1196
+ const r: HttpRequest = new HttpRequest(-1)
1197
+ r.params = new Array<i32>(2 * this.router.maxParams + 2)
1198
+ this.spare.push(r)
1199
+ return r
1200
+ }
1201
+
1202
+ /** Gives slot `s`'s record back, if it holds one: its task has copied it, or nobody will. */
1203
+ release(s: i32): void {
1204
+ const e: ServeExchange = this.ex[s]
1205
+ if (e.holds) {
1206
+ e.holds = false
1207
+ this.spare[this.spareCount] = e.rec
1208
+ this.spareCount += 1
1209
+ e.rec = this.none
1210
+ }
1211
+ }
1212
+
1213
+ /** Slot `s`'s record; only while it holds one, from `begin` to `release`. */
1214
+ req(s: i32): HttpRequest {
1215
+ return this.ex[s].rec
1216
+ }
1217
+
1218
+ /** Points a record for slot `s` at the head the parser read, and routes it. */
1219
+ begin(s: i32, conn: Http1Connection): void {
1220
+ if (this.draining) {
1221
+ // A head read during the drain is the connection's last.
1222
+ conn.closeAfter = true
1223
+ }
1224
+ const e: ServeExchange = this.ex[s]
1225
+ if (!e.holds) {
1226
+ e.rec = this.acquire()
1227
+ e.holds = true
1228
+ }
1229
+ const r: HttpRequest = e.rec
1230
+ const p = conn.parser
1231
+ r.head = p.head
1232
+ r.spans = p.spans
1233
+ r.headLength = p.headLength
1234
+ r.headerCount = p.headerCount
1235
+ r.methodStart = p.methodStart
1236
+ r.methodEnd = p.methodEnd
1237
+ r.targetStart = p.targetStart
1238
+ r.targetEnd = p.targetEnd
1239
+ r.bodyLength = 0
1240
+ r.slot = s
1241
+ r.gen = this.slotGen[s]
1242
+ r.since = this.turnAt
1243
+ e.state = SERVE_READING
1244
+ e.pendingStart = 0
1245
+ e.pendingEnd = 0
1246
+ const router: Router = this.router
1247
+ let route: i32 = router.match(
1248
+ r.head,
1249
+ r.methodStart,
1250
+ r.methodEnd,
1251
+ r.head,
1252
+ r.targetStart,
1253
+ r.targetEnd,
1254
+ r.params
1255
+ )
1256
+ if (route === ROUTER_METHOD_NOT_ALLOWED && r.methodIs("HEAD")) {
1257
+ const get: i32 = router.methodIndex("GET")
1258
+ if (get >= 0) {
1259
+ const viaGet: i32 = router.match(
1260
+ router.methodBytes,
1261
+ router.methodStart[get],
1262
+ router.methodEnd[get],
1263
+ r.head,
1264
+ r.targetStart,
1265
+ r.targetEnd,
1266
+ r.params
1267
+ )
1268
+ if (viaGet >= 0) {
1269
+ route = viaGet
1270
+ }
1271
+ }
1272
+ }
1273
+ r.route = route
1274
+ e.route = route
1275
+ r.paramCount = route >= 0 ? router.paramCount(route) : 0
1276
+ // The router found where the path ends, before any query, as it matched.
1277
+ r.pathEnd = router.pathEnd
1278
+ }
1279
+
1280
+ /** Queues slot `s`'s whole exchange for a task. */
1281
+ enqueue(s: i32): void {
1282
+ this.ex[s].state = SERVE_QUEUED
1283
+ const size: i32 = toI32(this.queue.length)
1284
+ if (this.queueCount === size) {
1285
+ const grown: i32[] = new Array<i32>(2 * size)
1286
+ const grownGen: i32[] = new Array<i32>(2 * size)
1287
+ for (let k: i32 = 0; k < size && k < toI32(grown.length) && k < toI32(grownGen.length); k++) {
1288
+ const from: i32 = (this.queueStart + k) & (size - 1)
1289
+ grown[k] = this.queue[from]
1290
+ grownGen[k] = this.queueGen[from]
1291
+ }
1292
+ this.queue = grown
1293
+ this.queueGen = grownGen
1294
+ this.queueStart = 0
1295
+ }
1296
+ const at: i32 = (this.queueStart + this.queueCount) & (toI32(this.queue.length) - 1)
1297
+ this.queue[at] = s
1298
+ this.queueGen[at] = this.slotGen[s]
1299
+ this.queueCount += 1
1300
+ }
1301
+
1302
+ /** Whether a queued exchange is ready, dropping those whose connection closed. */
1303
+ ready(): boolean {
1304
+ while (this.queueCount > 0) {
1305
+ if (this.live(this.queue[this.queueStart], this.queueGen[this.queueStart])) {
1306
+ return true
1307
+ }
1308
+ this.queueStart = (this.queueStart + 1) & (toI32(this.queue.length) - 1)
1309
+ this.queueCount -= 1
1310
+ }
1311
+ return false
1312
+ }
1313
+
1314
+ /** The next queued exchange's slot, now held; call after `ready`. */
1315
+ take(): i32 {
1316
+ const s: i32 = this.queue[this.queueStart]
1317
+ this.queueStart = (this.queueStart + 1) & (toI32(this.queue.length) - 1)
1318
+ this.queueCount -= 1
1319
+ this.ex[s].state = SERVE_HELD
1320
+ return s
1321
+ }
1322
+
1323
+ /** Whether slot `s` still holds the connection it had at generation `gen`. */
1324
+ live(s: i32, gen: i32): boolean {
1325
+ return this.server.holds(s) && this.slotGen[s] === gen
1326
+ }
1327
+
1328
+ /** Whether nobody waits for the answer of slot `s`'s exchange at generation `gen`. */
1329
+ hungUp(s: i32, gen: i32): boolean {
1330
+ return !this.live(s, gen) || this.ex[s].conn.ended()
1331
+ }
1332
+
1333
+ closeSlot(s: i32): void {
1334
+ this.server.close(s)
1335
+ this.forget(s)
1336
+ }
1337
+
1338
+ /** Marks slot `s` closed: its exchange is nobody's and its generation moves on. */
1339
+ forget(s: i32): void {
1340
+ this.open[s] = false
1341
+ this.slotGen[s] = this.slotGen[s] + 1
1342
+ this.ex[s].state = SERVE_IDLE
1343
+ this.release(s)
1344
+ }
1345
+
1346
+ /**
1347
+ * Answers slot `s`'s held exchange at generation `gen`, unless its
1348
+ * connection closed: the head, `len` bytes of `body` unless the status has
1349
+ * none, the end. What the output cannot take waits in the slot's
1350
+ * `pending` for `H1_WRITE`.
1351
+ */
1352
+ send(s: i32, gen: i32, status: i32, names: u8[][], values: u8[][], body: u8[], len: i32): void {
1353
+ if (!this.live(s, gen)) {
1354
+ return
1355
+ }
1356
+ const e: ServeExchange = this.ex[s]
1357
+ const conn: Http1Connection = e.conn
1358
+ const bodiless: boolean = status === 204 || status === 304
1359
+ const sent: i32 = conn.respond(status, names, values, bodiless ? HTTP1_NO_BODY : len)
1360
+ if (sent === H1_AGAIN) {
1361
+ // The output still holds more of the answer before this one than a
1362
+ // head can fit behind: ending the connection is the one answer left.
1363
+ this.closeSlot(s)
1364
+ return
1365
+ }
1366
+ if (sent !== 0) {
1367
+ panic(
1368
+ `serve: the carrier refused the head (${sent}): a name or value that is not a token or field text`
1369
+ )
1370
+ }
1371
+ if (len > 0 && !bodiless) {
1372
+ const start: i32 = 0
1373
+ let taken: i32 = conn.write(body, start, len)
1374
+ if (taken === H1_AGAIN) {
1375
+ taken = 0
1376
+ } else if (taken < 0) {
1377
+ panic(`serve: the carrier refused the body (${taken})`)
1378
+ }
1379
+ if (taken < len) {
1380
+ const rest: i32 = len - taken
1381
+ if (toI32(e.pending.length) < rest) {
1382
+ e.pending = new Array<u8>(serveGrown(toI32(e.pending.length), rest))
1383
+ }
1384
+ copyBytes(e.pending, 0, body, taken, rest)
1385
+ e.pendingEnd = rest
1386
+ }
1387
+ }
1388
+ this.finish(e)
1389
+ this.driveOn(s, e)
1390
+ }
1391
+
1392
+ /** Writes what the answer still has pending and ends it; the exchange is over once both are done. */
1393
+ finish(e: ServeExchange): void {
1394
+ const conn: Http1Connection = e.conn
1395
+ e.state = SERVE_FLUSHING
1396
+ const left: i32 = e.pendingEnd - e.pendingStart
1397
+ if (left > 0) {
1398
+ const taken: i32 = conn.write(e.pending, e.pendingStart, left)
1399
+ if (taken > 0) {
1400
+ e.pendingStart += taken
1401
+ }
1402
+ if (e.pendingStart < e.pendingEnd) {
1403
+ return
1404
+ }
1405
+ e.pendingStart = 0
1406
+ e.pendingEnd = 0
1407
+ }
1408
+ // `H1_AGAIN`: no room for the end yet; `H1_WRITE` comes back here.
1409
+ if (conn.end() !== H1_AGAIN) {
1410
+ e.state = SERVE_IDLE
1411
+ }
1412
+ }
1413
+
1414
+ /** Answers slot `s`'s exchange at `gen` with 404, or 405 and the methods its path has. */
1415
+ refuse(s: i32, gen: i32): void {
1416
+ if (!this.live(s, gen)) {
1417
+ return
1418
+ }
1419
+ if (this.ex[s].route === ROUTER_METHOD_NOT_ALLOWED) {
1420
+ // The parser still keeps this exchange's head: it reads the next only
1421
+ // once this one is answered.
1422
+ const p = this.ex[s].conn.parser
1423
+ this.allowValues[1] = this.allowFor(p.head, p.targetStart, p.targetEnd)
1424
+ this.send(
1425
+ s,
1426
+ gen,
1427
+ toI32(405),
1428
+ this.allowNames,
1429
+ this.allowValues,
1430
+ this.notAllowed,
1431
+ toI32(this.notAllowed.length)
1432
+ )
1433
+ return
1434
+ }
1435
+ this.send(
1436
+ s,
1437
+ gen,
1438
+ toI32(404),
1439
+ this.problemNames,
1440
+ this.problemValues,
1441
+ this.notFound,
1442
+ toI32(this.notFound.length)
1443
+ )
1444
+ }
1445
+
1446
+ /** Answers slot `s`'s exchange at `gen` with the problem body `body` as `status`. */
1447
+ problem(s: i32, gen: i32, status: i32, body: u8[]): void {
1448
+ this.send(s, gen, status, this.problemNames, this.problemValues, body, toI32(body.length))
1449
+ }
1450
+
1451
+ /** The `allow` value for the path `bytes[targetStart .. targetEnd)`: the methods with a route for it, and HEAD where GET has one. */
1452
+ allowFor(bytes: u8[], targetStart: i32, targetEnd: i32): u8[] {
1453
+ const router: Router = this.router
1454
+ const methods: i32 = toI32(router.methodStart.length)
1455
+ let mask: i64 = 0
1456
+ for (let m: i32 = 0; m < methods; m++) {
1457
+ const route: i32 = router.match(
1458
+ router.methodBytes,
1459
+ router.methodStart[m],
1460
+ router.methodEnd[m],
1461
+ bytes,
1462
+ targetStart,
1463
+ targetEnd,
1464
+ this.probe
1465
+ )
1466
+ if (route >= 0) {
1467
+ mask = mask | (toI64(1) << toI64(m))
1468
+ }
1469
+ }
1470
+ for (let k: i32 = 0; k < toI32(this.allowMasks.length); k++) {
1471
+ if (this.allowMasks[k] === mask) {
1472
+ return this.allowBytes[k]
1473
+ }
1474
+ }
1475
+ let get: boolean = false
1476
+ let head: boolean = false
1477
+ const value: u8[] = []
1478
+ for (let m: i32 = 0; m < methods; m++) {
1479
+ if ((mask & (toI64(1) << toI64(m))) !== toI64(0)) {
1480
+ const start: i32 = router.methodStart[m]
1481
+ const end: i32 = router.methodEnd[m]
1482
+ get = get || serveSpanIs(router.methodBytes, start, end, "GET")
1483
+ head = head || serveSpanIs(router.methodBytes, start, end, "HEAD")
1484
+ serveAllowAppend(value, router.methodBytes, start, end)
1485
+ }
1486
+ }
1487
+ if (get && !head) {
1488
+ const name: u8[] = serveBytes("HEAD")
1489
+ serveAllowAppend(value, name, 0, toI32(name.length))
1490
+ }
1491
+ this.allowMasks.push(mask)
1492
+ this.allowBytes.push(value)
1493
+ return value
1494
+ }
1495
+ }
1496
+
692
1497
  /**
693
1498
  * `serve` on a listening socket the program made — `tcpListen` on port 0 in
694
1499
  * a test, or `tcpListenFlags` with SO_REUSEPORT for a worker — filling
@@ -712,14 +1517,7 @@ export const serveOn = async (
712
1517
  `serve: connections ${limits.connections} and inFlight ${limits.inFlight} need at least 1, responseBytes ${limits.responseBytes} at least 0`
713
1518
  )
714
1519
  }
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()
1520
+ const c: ServeConns = new ServeConns(limits, listener, router)
723
1521
  const st: ServeState = new ServeState()
724
1522
  st.deadline = limits.deadline
725
1523
  serveFields(st, limits.server)
@@ -729,23 +1527,25 @@ export const serveOn = async (
729
1527
  panic(`serve: the wake socket could not be made: ${made}`)
730
1528
  }
731
1529
  st.wakeFd = fds[1]
732
- h.watch(fds[0], SERVE_WAKE)
1530
+ pollAdd(c.loop, fds[0], H1_WANT_READ, SERVE_WAKE)
733
1531
  const drained: u8[] = new Array<u8>(64)
734
1532
  spawn(serveTick(st))
735
1533
  let draining: boolean = false
736
1534
  while (true) {
737
1535
  st.awake = true
738
- h.wait(0)
739
- if (h.fired(SERVE_WAKE)) {
1536
+ if (c.turn()) {
740
1537
  st.signalled = false
741
1538
  while (netRead(fds[0], drained, 0, 64) > 0) {
742
1539
  // Each read takes up to 64 wake bytes; the loop empties the socket.
743
1540
  }
744
1541
  }
745
- // Each pass answers what the tasks wrote and takes what the handler
1542
+ // Each pass answers what the tasks wrote and takes what the connections
746
1543
  // queued: a pipelined request is queued once the one before it is
747
1544
  // 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.
1545
+ // order within this turn, and the answers are sent together. They carry
1546
+ // one clock reading as their `Date`, as a carrier's serve call does,
1547
+ // rather than one read per answer; it is let go once they are sent.
1548
+ c.server.date.hold()
749
1549
  let moved: boolean = true
750
1550
  while (moved || st.fresh) {
751
1551
  moved = false
@@ -754,7 +1554,7 @@ export const serveOn = async (
754
1554
  // does, so the list is read whole and emptied.
755
1555
  for (let i: i32 = 0; i < st.finishedCount && i < toI32(st.finished.length); i++) {
756
1556
  const k: i32 = st.finished[i]
757
- serveAnswer(h, st, k, stats)
1557
+ serveAnswer(c, st, k, stats)
758
1558
  st.busy[k] = false
759
1559
  st.done[k] = false
760
1560
  st.cancelled[k] = false
@@ -765,17 +1565,20 @@ export const serveOn = async (
765
1565
  moved = true
766
1566
  }
767
1567
  st.finishedCount = 0
768
- while (h.ready()) {
769
- const r: HttpRequest = h.take()
770
- const k: i32 = serveFreeSlot(st, limits)
1568
+ while (c.ready()) {
1569
+ const s: i32 = c.take()
1570
+ const k: i32 = serveFreeSlot(st, limits, c.req(s))
771
1571
  moved = true
772
1572
  if (k < 0) {
773
- h.problem(r, 503, "Service Unavailable", "")
1573
+ c.release(s)
1574
+ c.problem(s, c.slotGen[s], 503, c.unavailable)
774
1575
  stats.busy += 1
775
1576
  stats.answered += 1
776
1577
  continue
777
1578
  }
778
- st.reqs[k] = r
1579
+ st.reqs[k] = c.req(s)
1580
+ st.slots[k] = s
1581
+ st.gens[k] = c.slotGen[s]
779
1582
  st.busy[k] = true
780
1583
  st.done[k] = false
781
1584
  st.cancelled[k] = false
@@ -785,7 +1588,11 @@ export const serveOn = async (
785
1588
  st.running[st.runningCount] = k
786
1589
  st.runningCount += 1
787
1590
  }
1591
+ // `spawn` runs the task to its first await, past its copy of the
1592
+ // request, so the record goes back to the pool here: an idle
1593
+ // keep-alive connection holds none.
788
1594
  spawn(serveTask(handle, st, k))
1595
+ c.release(s)
789
1596
  }
790
1597
  }
791
1598
  // A task still running whose client hung up, or any once the server is
@@ -795,7 +1602,7 @@ export const serveOn = async (
795
1602
  for (let i: i32 = 0; i < st.runningCount && i < toI32(st.running.length); i++) {
796
1603
  const k: i32 = st.running[i]
797
1604
  if (st.busy[k] && !st.done[k]) {
798
- if (st.stopping || h.hungUp(st.reqs[k])) {
1605
+ if (st.stopping || c.hungUp(st.slots[k], st.gens[k])) {
799
1606
  serveCancel(st, k)
800
1607
  }
801
1608
  st.running[kept] = k
@@ -807,8 +1614,9 @@ export const serveOn = async (
807
1614
  st.runningCount = kept
808
1615
  // The turn's answers go out together, before the arena is read, so a
809
1616
  // close the send causes is counted in the turn that caused it.
810
- h.flush()
811
- stats.sends = h.sends()
1617
+ c.flush()
1618
+ c.server.date.unhold()
1619
+ stats.sends = c.sent
812
1620
  stats.slots = toI32(st.busy.length)
813
1621
  if (stats.warmAfter > 0 && stats.usedWarm === 0 && stats.answered >= stats.warmAfter) {
814
1622
  stats.usedWarm = Arena.used()
@@ -816,7 +1624,7 @@ export const serveOn = async (
816
1624
  if (!draining && limits.maxRequests > 0 && stats.answered >= limits.maxRequests) {
817
1625
  draining = true
818
1626
  stats.usedEnd = Arena.used()
819
- h.drain()
1627
+ c.drain()
820
1628
  st.stopping = true
821
1629
  for (let k: i32 = 0; k < toI32(st.busy.length); k++) {
822
1630
  if (st.busy[k] && !st.done[k]) {
@@ -824,20 +1632,20 @@ export const serveOn = async (
824
1632
  }
825
1633
  }
826
1634
  }
827
- if (draining && h.connections() === 0 && !serveAnyBusy(st)) {
1635
+ if (draining && c.server.busy() === 0 && !serveAnyBusy(st)) {
828
1636
  break
829
1637
  }
830
- if (h.ready()) {
1638
+ if (c.ready()) {
831
1639
  // A send let a parked request in: take it before parking.
832
1640
  continue
833
1641
  }
834
1642
  st.awake = false
835
- await readable(h.loop)
1643
+ await readable(c.loop)
836
1644
  }
837
1645
  st.stopped = true
838
1646
  netClose(fds[0])
839
1647
  netClose(fds[1])
840
- netClose(h.loop)
1648
+ netClose(c.loop)
841
1649
  return 0
842
1650
  }
843
1651