@amritk/nish-x86_64-linux 0.38.0 → 0.40.1

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 (86) hide show
  1. package/INSTALL.md +74 -129
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +455 -65
  4. package/package.json +1 -1
  5. package/runtime/core/host.d.ts +11 -0
  6. package/runtime/core/host.mjs +35 -0
  7. package/runtime/nish.d.ts +320 -33
  8. package/runtime/nish.h +84 -10
  9. package/runtime/nish.mjs +69 -6
  10. package/runtime/node.mjs +117 -0
  11. package/runtime/page-frame.d.ts +123 -0
  12. package/runtime/page-frame.mjs +736 -0
  13. package/runtime/page-game.d.ts +132 -0
  14. package/runtime/page-game.mjs +738 -0
  15. package/runtime/runtime-aes.c +97 -12
  16. package/runtime/runtime-async.c +43 -10
  17. package/runtime/runtime-bytes.c +88 -4
  18. package/runtime/runtime-checksum.c +207 -15
  19. package/runtime/runtime-net.c +64 -3
  20. package/runtime/runtime-os.c +174 -27
  21. package/runtime/runtime-region.c +94 -10
  22. package/runtime/runtime-sandbox.c +404 -17
  23. package/runtime/runtime-sha256.c +11 -4
  24. package/runtime/runtime-wasm.c +437 -0
  25. package/runtime/runtime.c +5 -0
  26. package/runtime/vite.mjs +1 -1
  27. package/scripts/build.sh +42 -8
  28. package/std/README.md +78 -91
  29. package/std/array.ts +36 -3
  30. package/std/collections.ts +51 -0
  31. package/std/compress/checksum.ts +13 -0
  32. package/std/compress/deflate.ts +0 -2
  33. package/std/crypto/hmac.ts +37 -10
  34. package/std/crypto/p256.ts +1629 -2732
  35. package/std/crypto/p384.ts +3 -1
  36. package/std/crypto/pki.ts +151 -13
  37. package/std/crypto/sha256.ts +34 -6
  38. package/std/crypto/x25519.ts +153 -64
  39. package/std/crypto/x509.ts +120 -10
  40. package/std/host/game.ts +273 -0
  41. package/std/input.ts +56 -0
  42. package/std/json-tokenizer.ts +344 -111
  43. package/std/json-typed.ts +256 -12
  44. package/std/json-value.ts +144 -3
  45. package/std/json.ts +63 -8
  46. package/std/net/fetch.ts +22 -4
  47. package/std/net/handler.ts +130 -16
  48. package/std/net/http-server.ts +3382 -0
  49. package/std/net/http1-client-codec.ts +6 -2
  50. package/std/net/http1-codec.ts +636 -162
  51. package/std/net/http1-server.ts +569 -42
  52. package/std/net/http2-cleartext.ts +526 -0
  53. package/std/net/http2-tls.ts +48 -0
  54. package/std/net/http2.ts +131 -14
  55. package/std/net/http3-server.ts +29 -3
  56. package/std/net/http3.ts +180 -7
  57. package/std/net/postgres-async.ts +1304 -86
  58. package/std/net/postgres-carrier.ts +343 -10
  59. package/std/net/postgres.ts +122 -7
  60. package/std/net/prefork.ts +195 -11
  61. package/std/net/quic-datagram.ts +30 -0
  62. package/std/net/quic-listener.ts +38 -12
  63. package/std/net/quic-packet.ts +19 -6
  64. package/std/net/quic-recovery.ts +373 -27
  65. package/std/net/quic-stream.ts +195 -37
  66. package/std/net/quic.ts +516 -22
  67. package/std/net/router.ts +407 -38
  68. package/std/net/serve.ts +1022 -110
  69. package/std/net/tls/codec.ts +110 -32
  70. package/std/net/tls/record-server.ts +37 -7
  71. package/std/net/tls/verify.ts +19 -1
  72. package/std/net/tls-tcp.ts +56 -1
  73. package/std/net/tls.ts +196 -50
  74. package/std/net/url.ts +83 -35
  75. package/std/net/websocket.ts +129 -19
  76. package/std/net/webtransport.ts +185 -1
  77. package/std/raster.ts +837 -0
  78. package/std/regex.ts +69 -47
  79. package/std/region.ts +62 -11
  80. package/std/release.ts +593 -0
  81. package/std/secret.ts +26 -59
  82. package/std/synth.ts +143 -0
  83. package/std/text.ts +233 -0
  84. package/std/threads.ts +298 -0
  85. package/std/yaml-json.ts +368 -28
  86. package/std/yaml.ts +122 -27
@@ -35,10 +35,15 @@
35
35
  * response it owes.
36
36
  *
37
37
  * **One exchange at a time.** A request is answered before the next one on
38
- * the connection is read: `respond`, any number of `write`s, `end`. The
39
- * program may answer at once (before the body has arrived) or after
40
- * `H1_END`; either way the request's body is read to its end before the next
41
- * request starts, which is what keeps pipelined requests in order (§9.3.2).
38
+ * the connection is read: `respond`, any number of `write`s, `end`. A
39
+ * response with a length is over once its last byte is written, and one with
40
+ * no body (`Content-Length: 0`, HEAD, 204, 304) once its head is, so `end` is
41
+ * optional for both; a chunked body, and an unframed one to HTTP/1.0, has no
42
+ * length to count and is over only at `end`, without which the connection
43
+ * waits and the next request is never answered. The program may answer at
44
+ * once (before the body has arrived) or after `H1_END`; either way the
45
+ * request's body is read to its end before the next request starts, which is
46
+ * what keeps pipelined requests in order (§9.3.2).
42
47
  * Pipelined bytes wait in the parser's buffer, and once it holds
43
48
  * `inputLimit()` bytes the connection stops asking for input, so the client's
44
49
  * TCP window closes: back-pressure on the way in.
@@ -132,7 +137,7 @@ import {
132
137
  HttpCompressor,
133
138
  httpAcceptEncoding,
134
139
  } from "nish/net/http-compress"
135
- import { netClose, netMss, netRead, netWrite, netWrite2, tcpAccept } from "nish:net"
140
+ import { netClose, netMss, netRead, netShutdown, netWrite, netWrite2, tcpAccept } from "nish:net"
136
141
  import {
137
142
  HTTP1_BODY,
138
143
  HTTP1_CHUNKED,
@@ -171,6 +176,7 @@ import { TlsServerConfig } from "nish/net/tls"
171
176
  import { HTTP_DATE_LAST_SECOND, HTTP_DATE_SIZE, httpDateWrite } from "nish/net/http-fields"
172
177
  import { TLS_RECORD_DONE, TLS_RECORD_STATE_OPEN, TLS_RECORD_WANT_WRITE } from "nish/net/tls/record-server"
173
178
  import { TlsTcpServer } from "nish/net/tls-tcp"
179
+ import { any, loadU8x16, ne } from "nish:simd"
174
180
 
175
181
  /** `next`: nothing to hand over until more input arrives, the output drains, or the program answers. */
176
182
  export const H1_NEED_MORE: i32 = 0
@@ -240,11 +246,160 @@ const H1_S_CLOSING: i32 = 2
240
246
  /** `H1_ERROR` was answered; sending what is left, then done. */
241
247
  const H1_S_FAILED: i32 = 3
242
248
 
249
+ /** `netShutdown`'s write side, for the lingering close. */
250
+ const H1_SHUT_WRITE: i32 = 1
251
+
243
252
  // Where the current exchange's response stands.
244
253
  const H1_R_NONE: i32 = 0
245
254
  const H1_R_BODY: i32 = 1
246
255
  const H1_R_DONE: i32 = 2
247
256
 
257
+ /**
258
+ * The longest final head `respond` keeps to write again (`Http1Connection`'s
259
+ * `headBytes`, one buffer per connection made at its first kept head). A
260
+ * longer head is written fresh every time.
261
+ */
262
+ const H1_HEAD_KEEP: i32 = 1024
263
+
264
+ /**
265
+ * What a kept head's buffer is rounded up to: a cache line, so that a head a
266
+ * few bytes longer than the last (a `Content-Length` with one more digit)
267
+ * fits the buffer it has rather than making another.
268
+ */
269
+ const H1_HEAD_ROUND: i32 = 64
270
+
271
+ /** The most program fields a kept head carries: a head with more is written fresh every time. */
272
+ const H1_HEAD_FIELDS: i32 = 16
273
+
274
+ /**
275
+ * How many responses in a row may miss the kept head before `respond` stops
276
+ * comparing and keeping until the `Date` turns: past it, a head is written as
277
+ * if nothing were kept, so heads that never repeat cost no more than that.
278
+ */
279
+ const H1_HEAD_MISSES: i32 = 4
280
+
281
+ // `respond`'s `Connection` field, as the kept head records it.
282
+ const H1_CONN_NONE: i32 = 0
283
+ const H1_CONN_CLOSE: i32 = 1
284
+ const H1_CONN_KEEP_ALIVE: i32 = 2
285
+
286
+ /** Whether `kept[at ..)` begins with all of `bytes`, a byte at a time: the path for a range a word load cannot prove inside its array. */
287
+ const http1ServerSameByByte = (kept: readonly u8[], at: i32, bytes: readonly u8[]): boolean => {
288
+ for (let k: i32 = 0; k < toI32(bytes.length); k += 1) {
289
+ if (kept[at + k] !== bytes[k]) {
290
+ return false
291
+ }
292
+ }
293
+ return true
294
+ }
295
+
296
+ /**
297
+ * Whether `kept[at ..)` begins with all of `bytes`, eight to fifteen of them:
298
+ * two eight-byte loads a side, the second overlapping the first. One range
299
+ * check comes first and each load's ors are grouped in pairs, as `getU64BE`'s
300
+ * are, so LLVM folds every eight loads into one.
301
+ */
302
+ const http1ServerSame8 = (kept: readonly u8[], at: i32, bytes: readonly u8[]): boolean => {
303
+ const n: i32 = toI32(bytes.length)
304
+ const e: i32 = at + n - 8
305
+ const f: i32 = n - 8
306
+ if (
307
+ !(at >= 0 && at < 2147483640 && at + 8 <= toI32(kept.length)) ||
308
+ !(e >= 0 && e < 2147483640 && e + 8 <= toI32(kept.length)) ||
309
+ !(toI32(bytes.length) >= 8 && f >= 0 && f < 2147483640 && f + 8 <= toI32(bytes.length))
310
+ ) {
311
+ return http1ServerSameByByte(kept, at, bytes)
312
+ }
313
+ return (
314
+ ((toU64(kept[at]) << toU64(56)) |
315
+ (toU64(kept[at + 1]) << toU64(48)) |
316
+ ((toU64(kept[at + 2]) << toU64(40)) | (toU64(kept[at + 3]) << toU64(32))) |
317
+ ((toU64(kept[at + 4]) << toU64(24)) |
318
+ (toU64(kept[at + 5]) << toU64(16)) |
319
+ ((toU64(kept[at + 6]) << toU64(8)) | toU64(kept[at + 7])))) ===
320
+ ((toU64(bytes[0]) << toU64(56)) |
321
+ (toU64(bytes[1]) << toU64(48)) |
322
+ ((toU64(bytes[2]) << toU64(40)) | (toU64(bytes[3]) << toU64(32))) |
323
+ ((toU64(bytes[4]) << toU64(24)) |
324
+ (toU64(bytes[5]) << toU64(16)) |
325
+ ((toU64(bytes[6]) << toU64(8)) | toU64(bytes[7])))) &&
326
+ ((toU64(kept[e]) << toU64(56)) |
327
+ (toU64(kept[e + 1]) << toU64(48)) |
328
+ ((toU64(kept[e + 2]) << toU64(40)) | (toU64(kept[e + 3]) << toU64(32))) |
329
+ ((toU64(kept[e + 4]) << toU64(24)) |
330
+ (toU64(kept[e + 5]) << toU64(16)) |
331
+ ((toU64(kept[e + 6]) << toU64(8)) | toU64(kept[e + 7])))) ===
332
+ ((toU64(bytes[f]) << toU64(56)) |
333
+ (toU64(bytes[f + 1]) << toU64(48)) |
334
+ ((toU64(bytes[f + 2]) << toU64(40)) | (toU64(bytes[f + 3]) << toU64(32))) |
335
+ ((toU64(bytes[f + 4]) << toU64(24)) |
336
+ (toU64(bytes[f + 5]) << toU64(16)) |
337
+ ((toU64(bytes[f + 6]) << toU64(8)) | toU64(bytes[f + 7]))))
338
+ )
339
+ }
340
+
341
+ /** `http1ServerSame8` for four to seven bytes, with four-byte loads. */
342
+ const http1ServerSame4 = (kept: readonly u8[], at: i32, bytes: readonly u8[]): boolean => {
343
+ const n: i32 = toI32(bytes.length)
344
+ const e: i32 = at + n - 4
345
+ const f: i32 = n - 4
346
+ if (
347
+ !(at >= 0 && at < 2147483640 && at + 4 <= toI32(kept.length)) ||
348
+ !(e >= 0 && e < 2147483640 && e + 4 <= toI32(kept.length)) ||
349
+ !(toI32(bytes.length) >= 4 && f >= 0 && f < 2147483640 && f + 4 <= toI32(bytes.length))
350
+ ) {
351
+ return http1ServerSameByByte(kept, at, bytes)
352
+ }
353
+ return (
354
+ ((toU32(kept[at]) << 24) |
355
+ (toU32(kept[at + 1]) << 16) |
356
+ ((toU32(kept[at + 2]) << 8) | toU32(kept[at + 3]))) ===
357
+ ((toU32(bytes[0]) << 24) | (toU32(bytes[1]) << 16) | ((toU32(bytes[2]) << 8) | toU32(bytes[3]))) &&
358
+ ((toU32(kept[e]) << 24) |
359
+ (toU32(kept[e + 1]) << 16) |
360
+ ((toU32(kept[e + 2]) << 8) | toU32(kept[e + 3]))) ===
361
+ ((toU32(bytes[f]) << 24) |
362
+ (toU32(bytes[f + 1]) << 16) |
363
+ ((toU32(bytes[f + 2]) << 8) | toU32(bytes[f + 3])))
364
+ )
365
+ }
366
+
367
+ /**
368
+ * Where `kept[at ..)` holds `bytes` and then the byte `after`: the offset one
369
+ * past the byte that follows `after` (the space of `: `, the LF of CR LF), or
370
+ * -1 when it does not, or when `after` would be at or past `limit`. Sixteen
371
+ * bytes at a time with a last load that overlaps the one before; a name or
372
+ * value under sixteen bytes is two overlapping eight- or four-byte loads, and
373
+ * one under four a byte at a time. A kept value holds no CR (it is field
374
+ * text), so a value that matches is the whole kept value; a name is held to
375
+ * the kept name's length by `sameHead`, since a kept value may hold a colon.
376
+ */
377
+ const http1ServerKept = (kept: u8[], at: i32, limit: i32, bytes: u8[], after: i32): i32 => {
378
+ const n: i32 = toI32(bytes.length)
379
+ if (at < 0 || limit > toI32(kept.length) || n > limit - at - 2 || toI32(kept[at + n]) !== after) {
380
+ return -1
381
+ }
382
+ if (n >= 16) {
383
+ let k: i32 = 0
384
+ while (k < n - 16) {
385
+ if (any(ne(loadU8x16(kept, at + k), loadU8x16(bytes, k)))) {
386
+ return -1
387
+ }
388
+ k += 16
389
+ }
390
+ return any(ne(loadU8x16(kept, at + n - 16), loadU8x16(bytes, n - 16))) ? -1 : at + n + 2
391
+ }
392
+ let same: boolean = false
393
+ if (n >= 8) {
394
+ same = http1ServerSame8(kept, at, bytes)
395
+ } else if (n >= 4) {
396
+ same = http1ServerSame4(kept, at, bytes)
397
+ } else {
398
+ same = http1ServerSameByByte(kept, at, bytes)
399
+ }
400
+ return same ? at + n + 2 : -1
401
+ }
402
+
248
403
  /** Panics unless `value` is in `low .. high`: a cap no connection could work with is the program's mistake. */
249
404
  const http1ServerCheckCap = (name: string, value: i32, low: i32, high: i32): void => {
250
405
  if (value < low || value > high) {
@@ -429,15 +584,30 @@ export class Http1Config {
429
584
  * of its head each `idleTimeout` would hold its slot for good (slowloris).
430
585
  */
431
586
  headTimeout: i32 = 30000
587
+ /**
588
+ * Milliseconds `Http1Server` keeps reading, and throwing away, what a
589
+ * refused client still sends after its error response, before `expire`
590
+ * closes the slot (RFC 9112 §9.6). The server shuts its write side and
591
+ * drains rather than closing at once: a close with unread bytes resets the
592
+ * connection, and the reset can destroy the response before the client
593
+ * reads it.
594
+ */
595
+ lingerTimeout: i32 = 2000
596
+ /**
597
+ * The most bytes a refused slot drains before it is closed whatever is
598
+ * left (RFC 9112 §9.6); 0 closes at once, without a lingering close.
599
+ */
600
+ lingerBytes: i32 = 65536
432
601
  /**
433
602
  * Lend a slot's input and head buffers back to the server between
434
603
  * exchanges: once a response is sent and no byte of the next request has
435
604
  * come, the slot gives both to pools the server's slots share, and takes
436
605
  * them again with the next byte. The memory they hold then follows the
437
606
  * connections mid-request rather than every keep-alive connection open,
438
- * for two pool operations a request. Off by default.
607
+ * for two pool operations a request. On by default; false keeps each
608
+ * slot's buffers across the rest, about 1.9 KB more an idle connection.
439
609
  */
440
- idleInput: boolean = false
610
+ idleInput: boolean = true
441
611
  }
442
612
 
443
613
  /** The reason phrase a status is sent with; RFC 9112 §4 lets a client ignore it. */
@@ -516,6 +686,8 @@ export class Http1OutputPool {
516
686
  private size: i32 = 0
517
687
  /** How many buffers the pool has made. */
518
688
  made: i32 = 0
689
+ /** How many buffers `free` has room for without growing. */
690
+ private room: i32 = 0
519
691
 
520
692
  /**
521
693
  * An empty pool: no buffer is made until the first `take`.
@@ -539,11 +711,25 @@ export class Http1OutputPool {
539
711
  return buf
540
712
  }
541
713
  this.made = this.made + 1
542
- return new Array<u8>(this.size)
714
+ const buf: u8[] = new Array<u8>(this.size)
715
+ // `free` gets room for every buffer made here, while this allocates
716
+ // anyway, so `give` never grows it: a slot's first park can come long
717
+ // after its take, when the arena is meant to be flat.
718
+ if (this.made > this.room) {
719
+ const want: i32 = this.made * 2
720
+ for (let i: i32 = 0; i < want; i++) {
721
+ this.free.push(buf)
722
+ }
723
+ while (this.free.length > 0) {
724
+ this.free.pop()
725
+ }
726
+ this.room = want
727
+ }
728
+ return buf
543
729
  }
544
730
 
545
731
  /**
546
- * Takes back a buffer `take` gave.
732
+ * Takes back a buffer `take` gave, into the room `take` made: it allocates nothing.
547
733
  *
548
734
  * @internal Called by `Http1Connection` in this module, from `release` and `park`, once a borrowed buffer holds nothing it still needs.
549
735
  */
@@ -586,16 +772,19 @@ export class Http1Connection {
586
772
  /** Where the parser's head buffer goes while the slot rests, beside `inputs`; null otherwise. */
587
773
  heads: Http1OutputPool | null
588
774
  /**
589
- * The `Date` every final response carries. The connection makes its own;
590
- * `Http1Server` and `Http1TlsServer` put theirs here, so that every slot of a
591
- * pool shares one and the pool formats at most once a second. A program may
592
- * put another, to share it or to pin its clock.
775
+ * The `Date` every final response carries: the constructor's, or one the
776
+ * connection makes when given none. `Http1Server` and `Http1TlsServer` give
777
+ * theirs, so that every slot of a pool shares one, formats at most once a
778
+ * second and makes no `Date` of its own. A program may put another, to
779
+ * share it or to pin its clock.
593
780
  */
594
781
  date: HttpDate
595
782
  /** When the carrier last moved a byte for the connection, in `monotonicNanos`. */
596
783
  lastActive: i64 = 0
597
784
  /** When the head being read began to arrive, in `monotonicNanos`; meaningful while `headTimed`. */
598
785
  headSince: i64 = 0
786
+ /** When the lingering close began, in `monotonicNanos`; meaningful while `lingering`. */
787
+ lingerSince: i64 = 0
599
788
  private state: i32 = 0
600
789
  private response: i32 = 0
601
790
  /**
@@ -659,6 +848,8 @@ export class Http1Connection {
659
848
  mss: i32 = 0
660
849
  /** The MSS `Http1Server.accept` read from this connection's socket (`netMss`), or 0 when it reports none. */
661
850
  socketMss: i32 = 0
851
+ /** How many bytes the lingering close has drained, or -1 while the connection does not linger. */
852
+ private lingered: i32 = -1
662
853
  /**
663
854
  * The plain TCP socket the carrier sends `output` on, which `sendBody`
664
855
  * writes to directly: `Http1Server.accept` sets it, and `restart` and
@@ -680,13 +871,61 @@ export class Http1Connection {
680
871
  pong: u8[]
681
872
  /** No fields, for the responses the connection writes itself: made once. */
682
873
  private noFields: u8[][]
874
+ /**
875
+ * The last final head `respond` wrote, `headBytes[0 .. headLength)`, kept
876
+ * so that a response asking for the same head is a copy of it: the same
877
+ * status, the same field names and values byte for byte, the same framing
878
+ * and `Connection`, and the same `date` not reformatted since (`formats`).
879
+ * Empty until the first head that is kept (one of at most `H1_HEAD_KEEP`
880
+ * bytes, after a head of the same shape); then made at that head's length
881
+ * rounded up to `H1_HEAD_ROUND`, remade only for a longer one, and kept for
882
+ * the slot's later peers, since what it holds is a function of those inputs
883
+ * alone. An idle slot holds what its heads need, not `H1_HEAD_KEEP`.
884
+ */
885
+ private headBytes: u8[]
886
+ /** How many bytes of `headBytes` the kept head is; 0 while none is kept. */
887
+ private headLength: i32 = 0
888
+ /** Where the kept head's first field line starts, past the status line. */
889
+ private headFieldsAt: i32 = 0
890
+ /** The kept head's status. */
891
+ private headStatus: i32 = 0
892
+ /** The kept head's framing: a length, `HTTP1_CHUNKED` or `HTTP1_NO_BODY`. */
893
+ private headFraming: i32 = 0
894
+ /** The kept head's `Connection` field: `H1_CONN_NONE`, `H1_CONN_CLOSE` or `H1_CONN_KEEP_ALIVE`. */
895
+ private headConnection: i32 = 0
896
+ /** How many of the program's fields the kept head carries. */
897
+ private headFields: i32 = 0
898
+ /**
899
+ * The length of each of the kept head's field names and values, in order,
900
+ * name then value: two per field, made at the first head kept with that
901
+ * many fields and remade only for one with more.
902
+ */
903
+ private headLengths: i32[]
904
+ /** The `HttpDate` the kept head's `Date` came from. */
905
+ private headDate: HttpDate
906
+ /** `headDate.formats()` when the kept head was written: a later format is a new second. */
907
+ private headFormats: i64 = 0
908
+ /** How many responses in a row have missed the kept head, up to `H1_HEAD_MISSES`. */
909
+ private headMisses: i32 = 0
910
+ /**
911
+ * `date.formats()` when the misses reached `H1_HEAD_MISSES`: while the date
912
+ * still has that count, `respond` neither compares nor keeps. -1 while on.
913
+ */
914
+ private headOff: i64 = -1
915
+ /**
916
+ * How many heads `respond` has copied from the kept one rather than written.
917
+ *
918
+ * @internal Read by `tests/link/net_http1_server_head_reuse` to tell a copied head from a written one.
919
+ */
920
+ headCopies: i64 = 0
683
921
 
684
922
  /**
685
923
  * A connection under `config`. A cap outside what the connection can work with panics.
686
924
  *
687
925
  * @param config the caps the connection is held to, read now and kept
926
+ * @param date the `Date` its responses carry, shared with other connections; null makes it one of its own
688
927
  */
689
- constructor(config: Http1Config) {
928
+ constructor(config: Http1Config, date: HttpDate | null = null) {
690
929
  const big: i32 = 1073741824
691
930
  const one: i32 = 1
692
931
  const smallest: i32 = 64
@@ -700,6 +939,8 @@ export class Http1Connection {
700
939
  http1ServerCheckCap("maxMessage", config.maxMessage, H1_ZERO, big - H1_FRAME_HEADER)
701
940
  http1ServerCheckCap("idleTimeout", config.idleTimeout, one, big)
702
941
  http1ServerCheckCap("headTimeout", config.headTimeout, one, big)
942
+ http1ServerCheckCap("lingerTimeout", config.lingerTimeout, one, big)
943
+ http1ServerCheckCap("lingerBytes", config.lingerBytes, H1_ZERO, big)
703
944
  // The buffers the peer's bytes fill grow by doubling and stop at 2^30
704
945
  // (`Http1Parser`'s input and head, `WsDecoder`'s input), so a cap whose
705
946
  // buffer could need more is refused here rather than reached by a peer:
@@ -715,7 +956,7 @@ export class Http1Connection {
715
956
  // The parser is made first: the arena places each block after the last,
716
957
  // so its front fields sit on the lines just behind the connection's own.
717
958
  this.parser = new Http1Parser(config.maxTarget, config.maxHeaderBytes, config.maxHeaders, config.maxBody)
718
- this.date = new HttpDate()
959
+ this.date = date === null ? new HttpDate() : date
719
960
  this.parser.keepText = false
720
961
  this.parser.maxChunk = config.chunkSize
721
962
  this.ws = null
@@ -727,6 +968,9 @@ export class Http1Connection {
727
968
  this.data = this.noOutput
728
969
  this.pong = this.noOutput
729
970
  this.noFields = []
971
+ this.headBytes = this.noOutput
972
+ this.headDate = this.date
973
+ this.headLengths = []
730
974
  // A line must fit whole before the parser can read it, so the buffer
731
975
  // holds the longest request line or field line however small a chunk is.
732
976
  let limit: i32 = config.chunkSize
@@ -769,6 +1013,14 @@ export class Http1Connection {
769
1013
  this.inputEnded = false
770
1014
  this.headTimed = false
771
1015
  this.headSince = 0
1016
+ // A slot's next connection starts with no kept head, and its first
1017
+ // head is not taken for a repeat of the last connection's.
1018
+ this.headLength = 0
1019
+ this.headStatus = 0
1020
+ this.headMisses = 0
1021
+ this.headOff = -1
1022
+ this.lingerSince = 0
1023
+ this.lingered = -1
772
1024
  this.mss = 0
773
1025
  this.socketMss = 0
774
1026
  this.fd = -1
@@ -900,6 +1152,7 @@ export class Http1Connection {
900
1152
  /** The socket failed: nothing more is sent or read, and the connection is done. */
901
1153
  abort(): void {
902
1154
  this.state = H1_S_FAILED
1155
+ this.lingered = -1
903
1156
  this.outputStart = 0
904
1157
  this.outputEnd = 0
905
1158
  this.pongPending = false
@@ -979,7 +1232,10 @@ export class Http1Connection {
979
1232
 
980
1233
  /** The room at the end of the output, once what was sent is moved out of the way. */
981
1234
  private room(): i32 {
982
- this.acquire()
1235
+ // Tested here, so that the usual case, an output already held, is no call.
1236
+ if (this.outputCap === 0) {
1237
+ this.acquire()
1238
+ }
983
1239
  const output: u8[] = this.output
984
1240
  const live: i32 = this.outputEnd - this.outputStart
985
1241
  if (this.outputStart > 0) {
@@ -1031,6 +1287,13 @@ export class Http1Connection {
1031
1287
  private nextRequest(): i32 {
1032
1288
  while (true) {
1033
1289
  if (this.requestEnded) {
1290
+ // A body with nothing left to send is over, `end()` or not: no body
1291
+ // at all, or a length met in full. Chunked and unframed bodies have
1292
+ // no length to count, so only `end()` finishes them.
1293
+ const counted: boolean = this.responseFraming >= 0 && this.responseLeft === 0
1294
+ if (this.response === H1_R_BODY && (this.responseEmpty || counted)) {
1295
+ this.response = H1_R_DONE
1296
+ }
1034
1297
  if (this.response !== H1_R_DONE) {
1035
1298
  return H1_NEED_MORE
1036
1299
  }
@@ -1245,6 +1508,11 @@ export class Http1Connection {
1245
1508
  * output; `H1_AGAIN` when the output has no room for it yet (`H1_WRITE`
1246
1509
  * says when to try again); `H1_CLOSED` with no request to answer.
1247
1510
  *
1511
+ * A response with no body (a `bodyLength` of 0, a HEAD, a 204 or a 304) is
1512
+ * finished once this returns 0, and one with a length once `write` or
1513
+ * `sendBody` has taken all of it: `end` is optional for both. A chunked
1514
+ * body is finished only by `end`.
1515
+ *
1248
1516
  * @param status the HTTP status code to send, 100 to 599 but not 101
1249
1517
  * @param names the program's field names, one per field; nothing checks their
1250
1518
  * case, and the reserved names are refused in any ASCII case
@@ -1259,11 +1527,6 @@ export class Http1Connection {
1259
1527
  if (status < 100 || status > 599 || status === 101) {
1260
1528
  return H1_INVALID
1261
1529
  }
1262
- for (const name of names) {
1263
- if (http1ServerReserved(name)) {
1264
- return H1_INVALID
1265
- }
1266
- }
1267
1530
  const interim: boolean = status < 200
1268
1531
  const empty: boolean = interim || status === 204 || status === 304 || this.parser.methodIs("HEAD")
1269
1532
  if (!empty && bodyLength === HTTP1_NO_BODY) {
@@ -1277,32 +1540,59 @@ export class Http1Connection {
1277
1540
  close = true
1278
1541
  }
1279
1542
  let connection: string = ""
1543
+ let code: i32 = H1_CONN_NONE
1280
1544
  if (!interim && close) {
1281
1545
  connection = "close"
1546
+ code = H1_CONN_CLOSE
1282
1547
  } else if (!interim && this.parser.minor === 0) {
1283
1548
  connection = "keep-alive"
1549
+ code = H1_CONN_KEEP_ALIVE
1550
+ }
1551
+ // Asked first, so that a second that has turned is a new head.
1552
+ const date: u8[] = this.date.current()
1553
+ // Off for the rest of the second once heads stop repeating, so that a
1554
+ // program whose heads differ pays this test and no more.
1555
+ if (!interim && this.date.formats() !== this.headOff) {
1556
+ if (this.sameHead(status, names, values, framing, code)) {
1557
+ if (this.headLength <= this.bodyRoom()) {
1558
+ // `bodyRoom` stops short of the output's end, so the copy fits.
1559
+ copyBytes(this.output, this.outputEnd, this.headBytes, H1_ZERO, this.headLength)
1560
+ this.outputEnd += this.headLength
1561
+ this.headMisses = 0
1562
+ this.headCopies += 1
1563
+ return this.begin(close, framing, empty)
1564
+ }
1565
+ }
1566
+ }
1567
+ const count: i32 = toI32(names.length)
1568
+ for (let k: i32 = 0; k < count; k++) {
1569
+ if (http1ServerReserved(names[k])) {
1570
+ return H1_INVALID
1571
+ }
1284
1572
  }
1285
1573
  const room: i32 = this.bodyRoom()
1574
+ const start: i32 = this.outputEnd
1575
+ const reason: string = http1ServerReason(status)
1286
1576
  const end: i32 = http1WriteResponseHead(
1287
1577
  this.output,
1288
- this.outputEnd,
1578
+ start,
1289
1579
  status,
1290
- http1ServerReason(status),
1580
+ reason,
1291
1581
  names,
1292
1582
  values,
1293
1583
  framing,
1294
1584
  connection,
1295
- this.date.current()
1585
+ date
1296
1586
  )
1297
1587
  if (end === HTTP1_REFUSED) {
1298
1588
  return H1_INVALID
1299
1589
  }
1300
- if (end < 0 || end - this.outputEnd > room) {
1590
+ if (end < 0 || end - start > room) {
1301
1591
  // The head was not written, or ate into the reserve: take it back.
1302
- if (end - this.outputEnd > this.config.outputSize - H1_CONTROL_RESERVE) {
1592
+ if (end - start > this.config.outputSize - H1_CONTROL_RESERVE) {
1303
1593
  return H1_INVALID
1304
1594
  }
1305
- if (this.outputEnd === 0) {
1595
+ if (start === 0) {
1306
1596
  return H1_INVALID
1307
1597
  }
1308
1598
  this.writeHeld = true
@@ -1312,6 +1602,21 @@ export class Http1Connection {
1312
1602
  if (interim) {
1313
1603
  return 0
1314
1604
  }
1605
+ if (this.date.formats() !== this.headOff) {
1606
+ // A head written here is a miss: the kept one did not match.
1607
+ this.headMisses += 1
1608
+ if (this.headMisses < H1_HEAD_MISSES) {
1609
+ this.keepHead(start, end, status, reason, names, values, framing, code)
1610
+ } else {
1611
+ this.headMisses = 0
1612
+ this.headOff = this.date.formats()
1613
+ }
1614
+ }
1615
+ return this.begin(close, framing, empty)
1616
+ }
1617
+
1618
+ /** The final response's head is queued: the exchange now owes its body. Answers 0. */
1619
+ private begin(close: boolean, framing: i32, empty: boolean): i32 {
1315
1620
  this.closeAfter = close
1316
1621
  this.response = H1_R_BODY
1317
1622
  this.responseFraming = framing
@@ -1320,6 +1625,104 @@ export class Http1Connection {
1320
1625
  return 0
1321
1626
  }
1322
1627
 
1628
+ /**
1629
+ * Whether the kept head is the one `respond` would write now: the same
1630
+ * status, framing and `Connection`, the same `date` not reformatted since,
1631
+ * and the program's fields the same in number and, one by one, byte for
1632
+ * byte. Its cost is a compare of the fields' bytes, which stops at the
1633
+ * first that differs.
1634
+ */
1635
+ private sameHead(status: i32, names: u8[][], values: u8[][], framing: i32, connection: i32): boolean {
1636
+ const count: i32 = toI32(names.length)
1637
+ if (
1638
+ this.headLength === 0 ||
1639
+ status !== this.headStatus ||
1640
+ framing !== this.headFraming ||
1641
+ connection !== this.headConnection ||
1642
+ count !== this.headFields ||
1643
+ toI32(values.length) !== count ||
1644
+ this.date !== this.headDate ||
1645
+ this.date.formats() !== this.headFormats
1646
+ ) {
1647
+ return false
1648
+ }
1649
+ const kept: u8[] = this.headBytes
1650
+ const limit: i32 = this.headLength
1651
+ let at: i32 = this.headFieldsAt
1652
+ const lengths: i32[] = this.headLengths
1653
+ // `count` is both arrays' length; testing each proves every access.
1654
+ for (let i: i32 = 0; i < toI32(names.length) && i < toI32(values.length) && at >= 0; i += 1) {
1655
+ // Both lengths, so that a value cannot match the kept bytes past its
1656
+ // own field and pass for the kept head without its text checks.
1657
+ const name: u8[] = names[i]
1658
+ const value: u8[] = values[i]
1659
+ if (toI32(name.length) !== lengths[2 * i] || toI32(value.length) !== lengths[2 * i + 1]) {
1660
+ return false
1661
+ }
1662
+ at = http1ServerKept(kept, at, limit, name, 58)
1663
+ at = http1ServerKept(kept, at, limit, value, 13)
1664
+ }
1665
+ return at >= 0
1666
+ }
1667
+
1668
+ /**
1669
+ * Records the final head just written at `output[start .. end)`, with what
1670
+ * it was written from, for `sameHead`. Its bytes are kept only when the
1671
+ * head before it had the same status, `Connection` and number of fields,
1672
+ * so that a program whose every head differs in those pays a few stores
1673
+ * per response and no copy; a head longer than `H1_HEAD_KEEP`, or with
1674
+ * more than `H1_HEAD_FIELDS` fields, is never kept. The framing is left
1675
+ * out of that test (`sameHead` still compares it): a body length that
1676
+ * varies would otherwise make the buffer's allocation wait for two equal
1677
+ * lengths in a row among the few heads kept each second, a moment set by
1678
+ * the clock rather than the program. The buffer is made at the first head
1679
+ * that is kept, so a connection whose heads never repeat their shape holds
1680
+ * none. `respond` stops calling it, and `sameHead`, for the
1681
+ * rest of the second once `H1_HEAD_MISSES` heads in a row are written.
1682
+ */
1683
+ private keepHead(
1684
+ start: i32,
1685
+ end: i32,
1686
+ status: i32,
1687
+ reason: string,
1688
+ names: u8[][],
1689
+ values: u8[][],
1690
+ framing: i32,
1691
+ connection: i32
1692
+ ): void {
1693
+ const n: i32 = end - start
1694
+ const fields: i32 = toI32(names.length)
1695
+ const again: boolean =
1696
+ status === this.headStatus && connection === this.headConnection && fields === this.headFields
1697
+ this.headStatus = status
1698
+ this.headFraming = framing
1699
+ this.headConnection = connection
1700
+ this.headFields = fields
1701
+ this.headLength = 0
1702
+ if (n > H1_HEAD_KEEP || fields > H1_HEAD_FIELDS) {
1703
+ return
1704
+ }
1705
+ if (!again) {
1706
+ return
1707
+ }
1708
+ if (toI32(this.headBytes.length) < n) {
1709
+ this.headBytes = new Array<u8>(((n + H1_HEAD_ROUND - 1) / H1_HEAD_ROUND) * H1_HEAD_ROUND)
1710
+ }
1711
+ if (toI32(this.headLengths.length) < 2 * fields) {
1712
+ this.headLengths = new Array<i32>(2 * fields)
1713
+ }
1714
+ for (let i: i32 = 0; i < fields && i < toI32(values.length); i += 1) {
1715
+ this.headLengths[2 * i] = toI32(names[i].length)
1716
+ this.headLengths[2 * i + 1] = toI32(values[i].length)
1717
+ }
1718
+ copyBytes(this.headBytes, H1_ZERO, this.output, start, n)
1719
+ // The field lines start past "HTTP/1.1 NNN " reason CRLF.
1720
+ this.headFieldsAt = 15 + toI32(reason.length)
1721
+ this.headLength = n
1722
+ this.headDate = this.date
1723
+ this.headFormats = this.date.formats()
1724
+ }
1725
+
1323
1726
  /**
1324
1727
  * Writes `buf[off .. off + len)` of the response body, as much as the output
1325
1728
  * has room for, and answers how much: a chunk of a chunked body, or bytes
@@ -1327,7 +1730,8 @@ export class Http1Connection {
1327
1730
  * everything was taken, `H1_WRITE` says when to try the rest; `H1_AGAIN`
1328
1731
  * when nothing was. A response with no body takes everything and sends
1329
1732
  * nothing. `H1_CLOSED` with no response under way. A window outside `buf`
1330
- * panics.
1733
+ * panics. Once the bytes taken reach the `Content-Length`, the response is
1734
+ * finished whether or not `end` follows; a chunked body still needs `end`.
1331
1735
  *
1332
1736
  * @param buf the body bytes to send, which stay the caller's
1333
1737
  * @param off where in `buf` the window starts
@@ -1389,7 +1793,8 @@ export class Http1Connection {
1389
1793
  * carrier) copy all of it: it is `write`, with the same bytes on the wire.
1390
1794
  * Answers what `write` answers, `H1_INVALID` for more than the response still
1391
1795
  * owes; `H1_CLOSED` also when the socket failed during the send, which aborts
1392
- * the connection. A window outside `buf` panics.
1796
+ * the connection. A window outside `buf` panics. As with `write`, a
1797
+ * `Content-Length` body sent in full needs no `end`.
1393
1798
  *
1394
1799
  * @param buf the body bytes to send, free for the caller to reuse once this returns
1395
1800
  * @param off where in `buf` the window starts
@@ -1442,6 +1847,13 @@ export class Http1Connection {
1442
1847
  * `H1_AGAIN` when the last chunk does not fit yet; `H1_CLOSED` with no
1443
1848
  * response under way.
1444
1849
  *
1850
+ * Required for a chunked body, and for an unframed one (a chunked response
1851
+ * to HTTP/1.0), which only `end` can say is over: without it the connection
1852
+ * waits and the next request is never read. Optional for a response with
1853
+ * no body or a `Content-Length` written in full, which the connection
1854
+ * finishes itself when it moves to the next request; called before then it
1855
+ * answers 0, and after then `H1_CLOSED`.
1856
+ *
1445
1857
  * @returns 0 once the response is complete, else `H1_INVALID`, `H1_AGAIN` or `H1_CLOSED` as above
1446
1858
  */
1447
1859
  end(): i32 {
@@ -1804,12 +2216,66 @@ export class Http1Connection {
1804
2216
  }
1805
2217
 
1806
2218
  /**
1807
- * Whether `expire` closes the slot at `now`: idle, or a head past its deadline.
2219
+ * Starts the lingering close at `now` (`monotonicNanos`) when the
2220
+ * connection refused its peer (`H1_ERROR`) on a socket that still reads,
2221
+ * the refusal is sent, and the peer has not ended its stream: the carrier
2222
+ * then shuts its write side and drains rather than closing.
2223
+ *
2224
+ * @param now the current time in `monotonicNanos`, which `lingerTimeout` counts from
2225
+ * @returns true when the lingering close began here; false when the connection should simply be closed
2226
+ * @internal Called by `Http1Server.flush` in this module once a refused slot is done.
2227
+ */
2228
+ lingerStart(now: i64): boolean {
2229
+ if (
2230
+ this.lingered >= 0 ||
2231
+ this.state !== H1_S_FAILED ||
2232
+ this.fd < 0 ||
2233
+ this.inputEnded ||
2234
+ this.config.lingerBytes <= 0 ||
2235
+ !this.isDone()
2236
+ ) {
2237
+ return false
2238
+ }
2239
+ this.lingered = 0
2240
+ this.lingerSince = now
2241
+ return true
2242
+ }
2243
+
2244
+ /**
2245
+ * Whether the connection is in its lingering close: its refusal is sent and
2246
+ * its carrier drains what the peer still sends.
2247
+ *
2248
+ * @returns true from `lingerStart` until the connection is restarted or aborted
2249
+ */
2250
+ lingering(): boolean {
2251
+ return this.lingered >= 0
2252
+ }
2253
+
2254
+ /**
2255
+ * Counts `n` more bytes drained in the lingering close.
2256
+ *
2257
+ * @param n how many bytes the carrier just read and threw away
2258
+ * @returns true while the drain stays under `lingerBytes`; false once the slot should be closed
2259
+ * @internal Called by `Http1Server` in this module as it drains a refused slot.
2260
+ */
2261
+ drained(n: i32): boolean {
2262
+ this.lingered = this.lingered + n
2263
+ return this.lingered < this.config.lingerBytes
2264
+ }
2265
+
2266
+ /** Whether the lingering close has lasted longer than `lingerTimeout` at `now` (`monotonicNanos`). */
2267
+ private lingerLate(now: i64): boolean {
2268
+ return this.lingered >= 0 && now - this.lingerSince > toI64(this.config.lingerTimeout) * toI64(1000000)
2269
+ }
2270
+
2271
+ /**
2272
+ * Whether `expire` closes the slot at `now`: idle, a head past its
2273
+ * deadline, or a lingering close past `lingerTimeout`.
1808
2274
  *
1809
2275
  * @internal Called by `Http1Server.expire` and `Http1TlsServer.expire` in this module to pick the slots to close.
1810
2276
  */
1811
2277
  expired(now: i64): boolean {
1812
- return this.idle(now) || this.headLate(now)
2278
+ return this.idle(now) || this.headLate(now) || this.lingerLate(now)
1813
2279
  }
1814
2280
 
1815
2281
  /**
@@ -1834,7 +2300,12 @@ export class Http1Connection {
1834
2300
  start = this.lastActive
1835
2301
  }
1836
2302
  const head: i64 = start + toI64(this.config.headTimeout) * toI64(1000000)
1837
- return head < idle ? head : idle
2303
+ const sooner: i64 = head < idle ? head : idle
2304
+ if (this.lingered >= 0) {
2305
+ const linger: i64 = this.lingerSince + toI64(this.config.lingerTimeout) * toI64(1000000)
2306
+ return linger < sooner ? linger : sooner
2307
+ }
2308
+ return sooner
1838
2309
  }
1839
2310
  }
1840
2311
 
@@ -1934,9 +2405,8 @@ export class Http1Server {
1934
2405
 
1935
2406
  /** A new connection on this pool's outputs and `Date`, for the next slot built. */
1936
2407
  private build(): Http1Connection {
1937
- const conn: Http1Connection = new Http1Connection(this.config)
2408
+ const conn: Http1Connection = new Http1Connection(this.config, this.date)
1938
2409
  conn.pool = this.outputs
1939
- conn.date = this.date
1940
2410
  if (this.config.idleInput) {
1941
2411
  conn.inputs = this.inputs
1942
2412
  conn.heads = this.heads
@@ -2127,6 +2597,10 @@ export class Http1Server {
2127
2597
  return H1_ERROR
2128
2598
  }
2129
2599
  const conn: Http1Connection = this.connections[slot]
2600
+ if (conn.lingering()) {
2601
+ // Its `H1_ERROR` was answered before the lingering close began.
2602
+ return H1_NEED_MORE
2603
+ }
2130
2604
  if (conn.writeHeld) {
2131
2605
  this.send(slot)
2132
2606
  }
@@ -2136,15 +2610,58 @@ export class Http1Server {
2136
2610
  /**
2137
2611
  * Sends what `slot`'s connection holds until the socket would block, and
2138
2612
  * answers the interest: `H1_DONE` once the connection is over and sent,
2139
- * otherwise read while it has room and write while it holds bytes. It ends
2613
+ * otherwise read while it has room and write while it holds bytes or a
2614
+ * write is held back (its `H1_WRITE` comes from `next` once the socket is
2615
+ * writable, even when this send emptied the output). It ends
2140
2616
  * the serve call, so a response written after it reads the clock anew.
2617
+ * Once a refusal (`H1_ERROR`) is sent the slot lingers: its write side is
2618
+ * shut and what the client still sends is drained, answering
2619
+ * `H1_WANT_READ` until the client's end of stream, `lingerBytes`, or
2620
+ * `expire` past `lingerTimeout`; `next` answers `H1_NEED_MORE` meanwhile.
2141
2621
  *
2142
2622
  * @param slot the slot `accept` answered
2143
2623
  * @returns the `H1_WANT_` bits to arm the slot with, or `H1_DONE` when the program should `close` it
2144
2624
  */
2145
2625
  flush(slot: i32): i32 {
2146
2626
  this.date.unhold()
2147
- return this.settle(slot)
2627
+ const wants: i32 = this.settle(slot)
2628
+ if (wants !== H1_DONE || !this.holds(slot)) {
2629
+ return wants
2630
+ }
2631
+ // A refusal is sent: shut the write side and drain what the client still
2632
+ // sends (RFC 9112 §9.6), for `lingerTimeout` and `lingerBytes` at most.
2633
+ // Closed with those bytes unread, the socket would answer them with a
2634
+ // reset that can destroy the response before the client reads it (H1-2).
2635
+ const now: i64 = monotonicNanos()
2636
+ const conn: Http1Connection = this.connections[slot]
2637
+ if (!conn.lingerStart(now) || netShutdown(this.fds[slot], H1_SHUT_WRITE) < 0) {
2638
+ return H1_DONE
2639
+ }
2640
+ const deadline: i64 = conn.expiresNoSooner(now)
2641
+ if (deadline < this.expireAfter) {
2642
+ this.expireAfter = deadline
2643
+ }
2644
+ return this.drain(slot)
2645
+ }
2646
+
2647
+ /**
2648
+ * Reads and throws away what `slot`'s lingering peer sends until the
2649
+ * socket would block, answering `H1_WANT_READ`; `H1_DONE` at its end of
2650
+ * stream, an error, or past `lingerBytes`. What it drains is not activity:
2651
+ * `lastActive` stays, and `expire` closes the slot past `lingerTimeout`.
2652
+ */
2653
+ private drain(slot: i32): i32 {
2654
+ const conn: Http1Connection = this.connections[slot]
2655
+ const fd: i32 = this.fds[slot]
2656
+ while (true) {
2657
+ const n: i32 = netRead(fd, this.scratch, H1_ZERO, toI32(this.scratch.length))
2658
+ if (n === H1_AGAIN) {
2659
+ return H1_WANT_READ
2660
+ }
2661
+ if (n <= 0 || !conn.drained(n)) {
2662
+ return H1_DONE
2663
+ }
2664
+ }
2148
2665
  }
2149
2666
 
2150
2667
  /** `flush` within a serve call: sends, answers the interest, and keeps the clock reading. */
@@ -2153,6 +2670,9 @@ export class Http1Server {
2153
2670
  return H1_DONE
2154
2671
  }
2155
2672
  const conn: Http1Connection = this.connections[slot]
2673
+ if (conn.lingering()) {
2674
+ return this.drain(slot)
2675
+ }
2156
2676
  this.send(slot)
2157
2677
  if (conn.isDone()) {
2158
2678
  return H1_DONE
@@ -2162,7 +2682,12 @@ export class Http1Server {
2162
2682
  if (conn.inputRoom() > 0) {
2163
2683
  wants = wants | H1_WANT_READ
2164
2684
  }
2165
- if (conn.wantsWrite()) {
2685
+ if (conn.wantsWrite() || conn.writeHeld) {
2686
+ // A held write's `H1_WRITE` comes only from `next`. A send here that
2687
+ // emptied the output, because the peer read between `next` and
2688
+ // `flush`, leaves no byte to wait on, and a held write reads nothing,
2689
+ // so without the write bit the slot would be armed for nothing and the
2690
+ // response would never finish. The empty socket is writable at once.
2166
2691
  wants = wants | H1_WANT_WRITE
2167
2692
  }
2168
2693
  return wants
@@ -2230,7 +2755,7 @@ export class Http1Server {
2230
2755
 
2231
2756
  /**
2232
2757
  * Closes every slot that has been idle past `idleTimeout`, or reading one
2233
- * head for longer than `headTimeout`, at `now` (`monotonicNanos`); answers how many.
2758
+ * head for longer than `headTimeout`, or lingering past `lingerTimeout`, at `now` (`monotonicNanos`); answers how many.
2234
2759
  *
2235
2760
  * @param now the current time in `monotonicNanos`, which every timeout is measured against
2236
2761
  * @returns how many slots this call closed
@@ -2334,9 +2859,8 @@ export class Http1TlsServer {
2334
2859
 
2335
2860
  /** A connection on this pool's outputs and `Date` that no slot holds yet. */
2336
2861
  private make(): Http1Connection {
2337
- const conn: Http1Connection = new Http1Connection(this.config)
2862
+ const conn: Http1Connection = new Http1Connection(this.config, this.date)
2338
2863
  conn.pool = this.outputs
2339
- conn.date = this.date
2340
2864
  if (this.config.idleInput) {
2341
2865
  conn.inputs = this.inputs
2342
2866
  conn.heads = this.heads
@@ -2546,7 +3070,7 @@ export class Http1TlsServer {
2546
3070
  * Writes what `slot`'s connection holds into TLS, as far as TLS takes it,
2547
3071
  * and sends it; shuts TLS down once the connection is over or ALPN chose
2548
3072
  * another protocol. Answers TLS's interest, with the write bit while the
2549
- * connection still holds bytes.
3073
+ * connection still holds bytes or a write is held back.
2550
3074
  *
2551
3075
  * @param slot the slot `accept` answered
2552
3076
  * @returns the TLS interest bits the slot now waits for (`H1_WANT_` values), with `TLS_RECORD_DONE` once it should be closed
@@ -2565,7 +3089,10 @@ export class Http1TlsServer {
2565
3089
  }
2566
3090
  conn.park()
2567
3091
  const wants: i32 = this.tls.interest(slot)
2568
- return conn.wantsWrite() && (wants & TLS_RECORD_DONE) === 0 ? wants | TLS_RECORD_WANT_WRITE : wants
3092
+ // A held write waits on the write bit even with nothing queued, as `Http1Server.flush` explains.
3093
+ return (conn.wantsWrite() || conn.writeHeld) && (wants & TLS_RECORD_DONE) === 0
3094
+ ? wants | TLS_RECORD_WANT_WRITE
3095
+ : wants
2569
3096
  }
2570
3097
 
2571
3098
  /**