@amritk/nish-aarch64-linux 0.39.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 (54) hide show
  1. package/INSTALL.md +74 -129
  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-wasm.c +422 -0
  16. package/runtime/vite.mjs +1 -1
  17. package/scripts/build.sh +15 -0
  18. package/std/README.md +73 -87
  19. package/std/array.ts +36 -3
  20. package/std/collections.ts +51 -0
  21. package/std/crypto/hmac.ts +37 -10
  22. package/std/crypto/p256.ts +1388 -2664
  23. package/std/crypto/pki.ts +116 -4
  24. package/std/crypto/sha256.ts +34 -6
  25. package/std/crypto/x509.ts +7 -0
  26. package/std/host/game.ts +273 -0
  27. package/std/input.ts +56 -0
  28. package/std/json-tokenizer.ts +325 -112
  29. package/std/json-typed.ts +43 -8
  30. package/std/json-value.ts +144 -3
  31. package/std/json.ts +63 -8
  32. package/std/net/fetch.ts +22 -4
  33. package/std/net/http-server.ts +3382 -0
  34. package/std/net/http1-client-codec.ts +6 -2
  35. package/std/net/http1-codec.ts +137 -12
  36. package/std/net/http1-server.ts +83 -29
  37. package/std/net/http2.ts +47 -14
  38. package/std/net/http3-server.ts +29 -3
  39. package/std/net/http3.ts +180 -7
  40. package/std/net/quic-recovery.ts +240 -9
  41. package/std/net/quic-stream.ts +21 -1
  42. package/std/net/quic.ts +98 -4
  43. package/std/net/router.ts +378 -31
  44. package/std/net/serve.ts +873 -65
  45. package/std/net/tls/verify.ts +19 -1
  46. package/std/net/url.ts +83 -35
  47. package/std/net/websocket.ts +74 -1
  48. package/std/net/webtransport.ts +7 -1
  49. package/std/raster.ts +837 -0
  50. package/std/release.ts +593 -0
  51. package/std/synth.ts +143 -0
  52. package/std/threads.ts +298 -0
  53. package/std/yaml-json.ts +368 -28
  54. package/std/yaml.ts +122 -27
package/std/net/http3.ts CHANGED
@@ -94,6 +94,9 @@
94
94
  * - a GOAWAY whose push ID rose, a MAX_PUSH_ID that fell, a CANCEL_PUSH past
95
95
  * the push IDs allowed (H3_ID_ERROR, §5.2, §7.2.7, §7.2.3);
96
96
  * - a control frame past `H3_CONTROL_FRAME_MAX` (H3_EXCESSIVE_LOAD);
97
+ * - a request reset past what `resetBudget` allows — by the client, or by
98
+ * this side for a stream error or a 431 the client caused, net of the
99
+ * requests this side answered (H3_EXCESSIVE_LOAD, §10.5);
97
100
  * - and QPACK's three.
98
101
  *
99
102
  * A stream error resets one request, both ways, and the connection lives: a
@@ -312,11 +315,22 @@ const H3_FLAG_WAITING: i32 = 16
312
315
  const H3_FLAG_WT: i32 = 256
313
316
  /** A request stream past this side's GOAWAY, refused unless its first bytes make it a WebTransport stream. */
314
317
  const H3_FLAG_LATE: i32 = 512
318
+ /** A request already charged to the reset budget: a client's RESET_STREAM and STOP_SENDING on one stream cost one. */
319
+ const H3_FLAG_CHARGED: i32 = 1024
315
320
 
316
321
  /** The connection's states. */
317
322
  const H3_STATE_OPEN: i32 = 0
318
323
  const H3_STATE_FAILED: i32 = 1
319
324
 
325
+ /** The clock's modes. OFF: no `next` has found `h3` chosen yet, so nothing is timed. */
326
+ const H3_CLOCK_OFF: i32 = -1
327
+ /** IDLE: no request in hand; timed by `idleTimeout`. */
328
+ const H3_CLOCK_IDLE: i32 = 0
329
+ /** HEAD: a request short of its head; timed by `headTimeout` and `idleTimeout`. */
330
+ const H3_CLOCK_HEAD: i32 = 1
331
+ /** BUSY: every request in hand past its head; not timed. */
332
+ const H3_CLOCK_BUSY: i32 = 2
333
+
320
334
  /** What `requestFrame` answers when it read a frame header and the stream has more to read. */
321
335
  const H3_CONTINUE: i32 = -1
322
336
 
@@ -364,11 +378,35 @@ export class Http3Config {
364
378
  * DATAGRAM frames; at 0 it must not (RFC 9297 §2.1.1).
365
379
  */
366
380
  webtransportSessions: i32 = 0
381
+ /**
382
+ * The milliseconds a connection may go without progress while no request
383
+ * is in hand before `clock` closes it (H3-5), 1 to 2^31 - 1. Progress is
384
+ * the connection starting, a request's head arriving whole, and the last
385
+ * request in hand finishing. With no request open the close is H3_NO_ERROR;
386
+ * with one still short of its head it is H3_EXCESSIVE_LOAD.
387
+ */
388
+ idleTimeout: i32 = 60000
389
+ /**
390
+ * The milliseconds a request's head may take to arrive whole, from its
391
+ * first byte or the last head before it, before `clock` closes the
392
+ * connection with H3_EXCESSIVE_LOAD (H3-5), 1 to 2^31 - 1. A body that
393
+ * trickles after its head is the program's to time, as a long response is.
394
+ */
395
+ headTimeout: i32 = 30000
367
396
  /**
368
397
  * Whether `:protocol` is accepted (RFC 9220's extended CONNECT), and
369
398
  * SETTINGS_ENABLE_CONNECT_PROTOCOL sent. WebTransport turns it on.
370
399
  */
371
400
  extendedConnect: boolean = false
401
+ /**
402
+ * How many requests may be reset before the connection is closed with
403
+ * H3_EXCESSIVE_LOAD, net of those this side answered: each request the
404
+ * client resets or stops, and each this side resets for a stream error or
405
+ * answers with a 431, costs one; each response this side ends with a FIN
406
+ * earns one back, up to this. Rapid reset (CVE-2023-44487) and MadeYouReset
407
+ * (CVE-2025-8671) over HTTP/3.
408
+ */
409
+ resetBudget: i32 = 100
372
410
  }
373
411
 
374
412
  /** Panics unless `value` lies in `[low, high]`: a cap out of range is the program's mistake. */
@@ -539,6 +577,9 @@ export class Http3Connection {
539
577
  lastStreamId: i64 = 0
540
578
  /** H3_STREAM's session ID. */
541
579
  session: i64 = -1
580
+ /** When `clock` last saw progress, and when it first saw a head waiting since; -1 for not yet. */
581
+ private clockSince: i64 = -1
582
+ private headSince: i64 = -1
542
583
  /**
543
584
  * The QUIC stream slot of the last event's stream: still right when the read that made the event freed it.
544
585
  * @internal Read by `webtransport.ts` to find its own per-slot state; not for callers.
@@ -575,9 +616,18 @@ export class Http3Connection {
575
616
  * with `content-length`, a stream that ends before its HEADERS, a trailer section too large.
576
617
  */
577
618
  streamErrors: i32 = 0
619
+ /** What is left of `config.resetBudget`. */
620
+ private resetCredit: i32 = 0
578
621
  private againHead: i32 = 0
579
622
  private againCount: i32 = 0
580
623
  private waitCount: i32 = 0
624
+ /**
625
+ * The heads delivered, wrapping, and the count and `H3_CLOCK_*` mode `clock` last saw. The mode is
626
+ * OFF (-1) from construction and `restart` until `next` finds `h3` chosen and sets it to IDLE.
627
+ */
628
+ private heads: i32 = 0
629
+ private clockHeads: i32 = 0
630
+ private clockMode: i32 = -1
581
631
  /** How many times `restart` ran: a layer above that keeps state per connection compares it to know when to forget its own. */
582
632
  generation: i32 = 0
583
633
  /** Whether the client's SETTINGS have arrived. */
@@ -620,6 +670,9 @@ export class Http3Connection {
620
670
  http3CheckCap("the QUIC unidirectional stream limit", toI32(quic.streams.maxUni), 3, 1024)
621
671
  http3CheckCap("the QUIC local stream limit", toI32(quic.streams.localStreams), 3, 1024)
622
672
  http3CheckCap("webtransportSessions", config.webtransportSessions, 0, H3_MAX_SESSIONS)
673
+ http3CheckCap("resetBudget", config.resetBudget, 0, 2147483647)
674
+ http3CheckCap("idleTimeout", config.idleTimeout, 1, 2147483647)
675
+ http3CheckCap("headTimeout", config.headTimeout, 1, 2147483647)
623
676
  // RFC 9297 §2.1.1: QUIC datagrams carry HTTP datagrams, which only WebTransport uses here.
624
677
  const datagrams: boolean = quic.datagramsIn.capacity() > 0
625
678
  if (config.webtransportSessions > 0 && !datagrams) {
@@ -737,10 +790,15 @@ export class Http3Connection {
737
790
  this.errorCode = 0
738
791
  this.lastStreamId = 0
739
792
  this.session = -1
793
+ this.clockSince = -1
794
+ this.headSince = -1
740
795
  this.slot = -1
741
796
  this.againHead = 0
742
797
  this.againCount = 0
743
798
  this.waitCount = 0
799
+ this.heads = 0
800
+ this.clockHeads = 0
801
+ this.clockMode = H3_CLOCK_OFF
744
802
  this.generation = this.generation < 2147483647 ? this.generation + 1 : H3_ONE
745
803
  this.dataStart = 0
746
804
  this.dataLength = 0
@@ -750,6 +808,7 @@ export class Http3Connection {
750
808
  this.rejected = 0
751
809
  this.tooLarge = 0
752
810
  this.streamErrors = 0
811
+ this.resetCredit = this.config.resetBudget
753
812
  this.settingsSeen = false
754
813
  this.resetByPeer = false
755
814
  }
@@ -782,6 +841,75 @@ export class Http3Connection {
782
841
  return this.goawayId >= 0 && this.live === 0 && streams.peerBidiClosed >= streams.peerBidiOpened
783
842
  }
784
843
 
844
+ /**
845
+ * Runs the connection's clock (H3-5): closes the QUIC connection once it
846
+ * has gone `idleTimeout` without progress while no request is in hand, or a
847
+ * request's head has waited `headTimeout`, and otherwise answers when to
848
+ * look again. `Http3Server` calls it on every flush of the slot; a program
849
+ * driving a connection itself calls it after each `next` and when the
850
+ * time it answered comes. It allocates nothing. The clock starts on the
851
+ * first `next` after the handshake chose `h3`, whether or not the client's
852
+ * MAX_STREAMS has let this side's own streams open yet: a connection the
853
+ * program runs another protocol on, and never asks for an event, is left
854
+ * to QUIC's own idle timeout.
855
+ *
856
+ * @param now The current millisecond on the caller's monotonic clock.
857
+ * @returns The millisecond the clock next needs a look, or -1 when it needs none: no `next` has
858
+ * found `h3` chosen yet, every request in hand is past its head, or the connection is closed (by this call too).
859
+ */
860
+ clock(now: i64): i64 {
861
+ if (this.clockMode === H3_CLOCK_OFF || this.quic.closed()) {
862
+ return -1
863
+ }
864
+ let mode: i32 = H3_CLOCK_BUSY
865
+ if (this.live === 0) {
866
+ mode = H3_CLOCK_IDLE
867
+ } else if (this.awaitsHead()) {
868
+ mode = H3_CLOCK_HEAD
869
+ }
870
+ const finished: boolean = this.clockMode === H3_CLOCK_BUSY && mode !== H3_CLOCK_BUSY
871
+ if (this.clockSince < 0 || this.heads !== this.clockHeads || finished) {
872
+ this.clockSince = now
873
+ this.clockHeads = this.heads
874
+ this.headSince = -1
875
+ }
876
+ if (mode !== H3_CLOCK_HEAD) {
877
+ this.headSince = -1
878
+ } else if (this.headSince < 0) {
879
+ this.headSince = now
880
+ }
881
+ this.clockMode = mode
882
+ if (mode === H3_CLOCK_BUSY) {
883
+ return -1
884
+ }
885
+ let due: i64 = this.clockSince + toI64(this.config.idleTimeout)
886
+ if (mode === H3_CLOCK_HEAD) {
887
+ due = http3Min(due, this.headSince + toI64(this.config.headTimeout))
888
+ }
889
+ if (now < due) {
890
+ return due
891
+ }
892
+ this.quic.close(mode === H3_CLOCK_HEAD ? H3_EXCESSIVE_LOAD : H3_NO_ERROR)
893
+ return -1
894
+ }
895
+
896
+ /** Whether a request stream the client opened, counted in `live`, has not yet given its head. */
897
+ private awaitsHead(): boolean {
898
+ const skip: i32 = H3_FLAG_DELIVERED | H3_FLAG_WT
899
+ for (let k: i32 = 0; k < toI32(this.slotId.length); k++) {
900
+ const flags: i32 = this.flags[k]
901
+ if (
902
+ this.phase[k] === H3_PHASE_HEADERS &&
903
+ (flags & H3_FLAG_COUNTED) !== 0 &&
904
+ (flags & skip) === 0 &&
905
+ http3IsRequest(this.slotId[k])
906
+ ) {
907
+ return true
908
+ }
909
+ }
910
+ return false
911
+ }
912
+
785
913
  /** Writes `buf[0 .. n)` to this side's new stream `id` whole, as its first bytes; answers whether it took them. */
786
914
  private writeNew(id: i64, buf: u8[], n: i32): boolean {
787
915
  return n > 0 && this.quic.streamWrite(id, buf, H3_ZERO, n, false) === n
@@ -955,6 +1083,12 @@ export class Http3Connection {
955
1083
  this.quic.fail(H3_NO_APPLICATION_PROTOCOL, toI64(0))
956
1084
  return this.fail(H3_NO_APPLICATION_PROTOCOL)
957
1085
  }
1086
+ // The clock runs from here, not from start() finishing: a client
1087
+ // whose MAX_STREAMS keeps this side's unidirectional streams unopened
1088
+ // is still served its requests, so it is still timed.
1089
+ if (this.clockMode === H3_CLOCK_OFF) {
1090
+ this.clockMode = H3_CLOCK_IDLE
1091
+ }
958
1092
  this.start()
959
1093
  }
960
1094
  while (this.state !== H3_STATE_FAILED) {
@@ -1643,6 +1777,10 @@ export class Http3Connection {
1643
1777
  // The client stopped the response (QUIC answered with RESET_STREAM, §3.5 of RFC 9000).
1644
1778
  const told: boolean = (this.flags[k] & H3_FLAG_DELIVERED) !== 0
1645
1779
  this.mark(k, H3_FLAG_SEND_DONE)
1780
+ const charged: i32 = this.chargeReset(k)
1781
+ if (charged !== H3_NEED_MORE) {
1782
+ return charged
1783
+ }
1646
1784
  if (told) {
1647
1785
  if (phase !== H3_PHASE_DONE) {
1648
1786
  this.phase[k] = H3_PHASE_DISCARD
@@ -1863,6 +2001,7 @@ export class Http3Connection {
1863
2001
  this.contentLength[k] = this.fields.contentLength
1864
2002
  this.phase[k] = H3_PHASE_BODY
1865
2003
  this.flags[k] = this.flags[k] | H3_FLAG_DELIVERED
2004
+ this.heads = this.heads < 2147483647 ? this.heads + 1 : H3_ZERO
1866
2005
  this.stream = id
1867
2006
  return H3_REQUEST
1868
2007
  }
@@ -1922,6 +2061,10 @@ export class Http3Connection {
1922
2061
  if (n === QUIC_STREAM_ERR_RESET) {
1923
2062
  // §4.1.1: a response to a request that will not finish is abandoned too.
1924
2063
  this.abandon(k, id, resetCode === H3_REQUEST_CANCELLED ? H3_REQUEST_CANCELLED : H3_REQUEST_INCOMPLETE)
2064
+ const charged: i32 = this.chargeReset(k)
2065
+ if (charged !== H3_NEED_MORE) {
2066
+ return charged
2067
+ }
1925
2068
  return delivered ? this.resetEvent(id, resetCode, true) : this.dropped(id)
1926
2069
  }
1927
2070
  if (n !== QUIC_STREAM_END) {
@@ -1931,13 +2074,15 @@ export class Http3Connection {
1931
2074
  // §4.1.1: the stream ended before a whole request.
1932
2075
  this.abandon(k, id, H3_REQUEST_INCOMPLETE)
1933
2076
  this.streamErrors = h3Count(this.streamErrors)
1934
- return this.dropped(id)
2077
+ const charged: i32 = this.chargeReset(k)
2078
+ return charged !== H3_NEED_MORE ? charged : this.dropped(id)
1935
2079
  }
1936
2080
  if (this.contentLength[k] >= 0 && this.dataTotal[k] !== this.contentLength[k]) {
1937
2081
  // §4.1.2: the body is shorter than its content-length.
1938
2082
  this.abandon(k, id, H3_MESSAGE_ERROR)
1939
2083
  this.streamErrors = h3Count(this.streamErrors)
1940
- return this.resetEvent(id, H3_MESSAGE_ERROR, false)
2084
+ const charged: i32 = this.chargeReset(k)
2085
+ return charged !== H3_NEED_MORE ? charged : this.resetEvent(id, H3_MESSAGE_ERROR, false)
1941
2086
  }
1942
2087
  this.stream = id
1943
2088
  return H3_END
@@ -1957,12 +2102,39 @@ export class Http3Connection {
1957
2102
  this.abandon(k, id, code)
1958
2103
  this.quic.streamStopSending(id, code)
1959
2104
  this.phase[k] = H3_PHASE_DISCARD
2105
+ const charged: i32 = this.chargeReset(k)
2106
+ if (charged !== H3_NEED_MORE) {
2107
+ return charged
2108
+ }
1960
2109
  if ((this.flags[k] & H3_FLAG_DELIVERED) !== 0) {
1961
2110
  return this.resetEvent(id, code, false)
1962
2111
  }
1963
2112
  return this.dropped(id)
1964
2113
  }
1965
2114
 
2115
+ /**
2116
+ * Charges request `k` to the reset budget, once whatever reset it: a client
2117
+ * that cannot reset many requests itself provokes this side into it
2118
+ * (MadeYouReset, CVE-2025-8671). Answers H3_NEED_MORE, or once the budget
2119
+ * is spent the connection error H3_EXCESSIVE_LOAD (§10.5).
2120
+ */
2121
+ private chargeReset(k: i32): i32 {
2122
+ if ((this.flags[k] & H3_FLAG_CHARGED) !== 0) {
2123
+ return H3_NEED_MORE
2124
+ }
2125
+ this.flags[k] = this.flags[k] | H3_FLAG_CHARGED
2126
+ this.resetCredit = this.resetCredit - 1
2127
+ return this.resetCredit < 0 ? this.fail(H3_EXCESSIVE_LOAD) : H3_NEED_MORE
2128
+ }
2129
+
2130
+ /** This side ended request `k`'s response with a FIN: its send side is done, and a request the program answered earns the reset budget one back. */
2131
+ private answered(k: i32): void {
2132
+ this.mark(k, H3_FLAG_SEND_DONE)
2133
+ if ((this.flags[k] & H3_FLAG_DELIVERED) !== 0 && this.resetCredit < this.config.resetBudget) {
2134
+ this.resetCredit = this.resetCredit + 1
2135
+ }
2136
+ }
2137
+
1966
2138
  /** H3_DROPPED for request stream `id` with WebTransport on, which waits on such a stream; H3_NEED_MORE without. */
1967
2139
  private dropped(id: i64): i32 {
1968
2140
  if (!this.webtransport) {
@@ -2000,7 +2172,8 @@ export class Http3Connection {
2000
2172
  }
2001
2173
  this.quic.streamStopSending(id, H3_NO_ERROR)
2002
2174
  this.phase[k] = H3_PHASE_DISCARD
2003
- return this.dropped(id)
2175
+ const charged: i32 = this.chargeReset(k)
2176
+ return charged !== H3_NEED_MORE ? charged : this.dropped(id)
2004
2177
  }
2005
2178
 
2006
2179
  /**
@@ -2191,7 +2364,7 @@ export class Http3Connection {
2191
2364
  this.quic.streamWrite(id, out, H3_ZERO, toI32(length), fin)
2192
2365
  this.flags[k] = this.flags[k] | H3_FLAG_HEADERS_SENT
2193
2366
  if (fin) {
2194
- this.mark(k, H3_FLAG_SEND_DONE)
2367
+ this.answered(k)
2195
2368
  }
2196
2369
  return 0
2197
2370
  }
@@ -2299,7 +2472,7 @@ export class Http3Connection {
2299
2472
  if (len === 0) {
2300
2473
  if (endStream && this.dataLeft[k] === 0) {
2301
2474
  this.quic.streamWrite(id, this.zeros, H3_ZERO, H3_ZERO, true)
2302
- this.mark(k, H3_FLAG_SEND_DONE)
2475
+ this.answered(k)
2303
2476
  }
2304
2477
  return 0
2305
2478
  }
@@ -2336,7 +2509,7 @@ export class Http3Connection {
2336
2509
  break
2337
2510
  }
2338
2511
  if (fin) {
2339
- this.mark(k, H3_FLAG_SEND_DONE)
2512
+ this.answered(k)
2340
2513
  }
2341
2514
  }
2342
2515
  return total > 0 ? total : H3_AGAIN
@@ -2388,7 +2561,7 @@ export class Http3Connection {
2388
2561
  this.quic.streamWrite(id, this.scratch, H3_ZERO, hp, false)
2389
2562
  this.quic.streamWrite(id, buf, off, len, fin)
2390
2563
  if (fin) {
2391
- this.mark(k, H3_FLAG_SEND_DONE)
2564
+ this.answered(k)
2392
2565
  }
2393
2566
  return 0
2394
2567
  }
@@ -2,7 +2,7 @@
2
2
  * `nish/net/quic-recovery` — QUIC loss detection and congestion control
3
3
  * (RFC 9002): the packets each packet number space has in flight, the
4
4
  * round-trip estimate, loss by packet and by time threshold, the probe
5
- * timeout with its backoff, NewReno, and a pacer. Sans-IO: it never sees a
5
+ * timeout with its backoff, NewReno or CUBIC, and a pacer. Sans-IO: it never sees a
6
6
  * byte of a packet, only packet numbers, sizes and the caller's clock.
7
7
  *
8
8
  * import { QuicRecovery, QUIC_RECOVERY_TIMEOUT_PTO } from "nish/net/quic-recovery";
@@ -50,6 +50,18 @@
50
50
  * only if, when it arrived, the bytes in flight were at least half the
51
51
  * window.
52
52
  *
53
+ * **Congestion control.** `controller` picks it, once, before the first
54
+ * packet: `QUIC_RECOVERY_NEWRENO` (Appendix B, the default) or
55
+ * `QUIC_RECOVERY_CUBIC` (RFC 9438). Both share slow start, recovery
56
+ * periods, persistent congestion's collapse to the minimum window and the
57
+ * rule above for a window not in use. CUBIC keeps 0.7 of the window at a
58
+ * congestion event rather than half, then grows along W(t) = W_max + C ×
59
+ * (t − K)³ with C 0.4, concave up to the window it lost at and convex past
60
+ * it, never below what Reno would have reached (its Reno-friendly region),
61
+ * and with fast convergence. Its arithmetic is integers in bytes and
62
+ * milliseconds, and K's cube root is found by bisection, so two machines
63
+ * given the same events reach the same window to the byte.
64
+ *
53
65
  * **ECN** (§7.1, B.7; RFC 9000 §13.4.2 and its Appendix A.4). A caller that
54
66
  * marks its packets ECT(0) asks `ecnCodepoint()` what to mark with, says so
55
67
  * with `onEctSent` for every packet it marked, and hands an ACK_ECN frame's
@@ -77,7 +89,7 @@
77
89
  * timeout, at a rate that halves each time, until the idle timeout ends the
78
90
  * connection.
79
91
  *
80
- * Written from RFC 9002 §5 to §7 and its Appendices A and B, in this
92
+ * Written from RFC 9002 §5 to §7 and its Appendices A and B, and RFC 9438, in this
81
93
  * module's own structure; nothing here is ported from another
82
94
  * implementation. Private names carry the `quicRecovery` prefix
83
95
  * (`docs/wp26-stdlib.md` §3e).
@@ -180,9 +192,75 @@ const QUIC_RECOVERY_MICROS: i64 = 1000
180
192
  */
181
193
  const QUIC_RECOVERY_PACER_WINDOW: i64 = 4294967296
182
194
 
195
+ /** The congestion controller of RFC 9002 §7 and Appendix B: NewReno. */
196
+ export const QUIC_RECOVERY_NEWRENO: i32 = 0
197
+ /** The congestion controller of RFC 9438: CUBIC, with its Reno-friendly region and fast convergence. */
198
+ export const QUIC_RECOVERY_CUBIC: i32 = 1
199
+ /**
200
+ * The controller a server runs unless it has a reason to pick: CUBIC. It
201
+ * beat NewReno outside the spread across loss draws on transfers of 32 and
202
+ * 128 bandwidth-delay products and finished level on one
203
+ * (`bench/quic-goodput.ts`; the figures are in docs/security/quic.md).
204
+ * It holds the same value as `QUIC_RECOVERY_CUBIC`, written out rather than
205
+ * aliased so the default reads as a choice of its own.
206
+ */
207
+ export const QUIC_RECOVERY_DEFAULT: i32 = 1
208
+
209
+ /**
210
+ * CUBIC's longest span in milliseconds: K and every `t − K` its curve is
211
+ * read at are clamped to ±40 s. A cube of it times twice the largest UDP
212
+ * payload stays inside an `i64` (2 × 65535 × 40000³ < 2^63), and K reaches
213
+ * it only after a fall of 25600 datagrams, 30 MB at 1200 bytes. What the
214
+ * clamp costs: 40 s past K, W(t) stops at W_max + 25600 datagrams, so a
215
+ * window that far past its last loss grows only as fast as W_est.
216
+ */
217
+ const QUIC_RECOVERY_CUBIC_SPAN: i64 = 40000
218
+ /**
219
+ * C (0.4 segments/s³) on milliseconds: W(t) = W_max + 2 × size × (t − K)³ / 5 × 10⁹
220
+ * bytes, `size` the datagram size and t in milliseconds (RFC 9438 §4.2).
221
+ */
222
+ const QUIC_RECOVERY_CUBIC_SCALE: i64 = 5000000000
223
+
183
224
  /** The larger of two times or durations. */
184
225
  const quicRecoveryMax = (a: i64, b: i64): i64 => (a > b ? a : b)
185
226
 
227
+ /** `x` clamped to −`QUIC_RECOVERY_CUBIC_SPAN` .. `QUIC_RECOVERY_CUBIC_SPAN`. */
228
+ const quicRecoveryCubicClamp = (x: i64): i64 => {
229
+ if (x > QUIC_RECOVERY_CUBIC_SPAN) {
230
+ return QUIC_RECOVERY_CUBIC_SPAN
231
+ }
232
+ return x < -QUIC_RECOVERY_CUBIC_SPAN ? -QUIC_RECOVERY_CUBIC_SPAN : x
233
+ }
234
+
235
+ /**
236
+ * The integer cube root of `x`, the largest r with r³ <= x, for 0 <= x <=
237
+ * `QUIC_RECOVERY_CUBIC_SPAN`³, found by bisection over 0 .. the span: 16
238
+ * steps, the same answer on every machine, no floating point.
239
+ *
240
+ * @param x The cube, 0 to 40000³.
241
+ * @returns Its root, 0 to 40000.
242
+ */
243
+ export const quicRecoveryCbrt = (x: i64): i64 => {
244
+ let lo: i64 = 0
245
+ let hi: i64 = QUIC_RECOVERY_CUBIC_SPAN
246
+ if (x <= lo) {
247
+ return lo
248
+ }
249
+ if (x >= hi * hi * hi) {
250
+ return hi
251
+ }
252
+ // lo³ <= x < hi³ holds at every step.
253
+ while (hi - lo > 1) {
254
+ const mid: i64 = (lo + hi) / 2
255
+ if (mid * mid * mid <= x) {
256
+ lo = mid
257
+ } else {
258
+ hi = mid
259
+ }
260
+ }
261
+ return lo
262
+ }
263
+
186
264
  /**
187
265
  * The ack-eliciting packets one space sent, in a ring of `capacity` slots
188
266
  * in the order they went out: slot `slot(k)` is the `k`-th from the oldest
@@ -546,6 +624,33 @@ export class QuicRecovery {
546
624
  ssthresh: i64 = 0
547
625
  /** congestion_recovery_start_time (B.2), or -1 outside recovery. */
548
626
  recoveryStart: i64 = -1
627
+ /**
628
+ * The congestion controller, `QUIC_RECOVERY_NEWRENO` or `QUIC_RECOVERY_CUBIC`, which the caller
629
+ * sets once, before the first packet; `reset` keeps it.
630
+ */
631
+ controller: i32 = 0
632
+ /** CUBIC's W_max (RFC 9438 §4.2) in bytes: the window its curve plateaus at, 0 before the first congestion event. */
633
+ cubicMax: i64 = 0
634
+ /** CUBIC's K in milliseconds: how long after `cubicEpoch` the curve reaches `cubicMax`. */
635
+ cubicK: i64 = 0
636
+ /** When CUBIC's congestion avoidance stage began (t = 0 of its curve), in milliseconds, or -1 outside one. */
637
+ cubicEpoch: i64 = -1
638
+ /** CUBIC's W_est (§4.3) in bytes: the window Reno's AIMD with β 0.7 would have reached since `cubicEpoch`. */
639
+ cubicEst: i64 = 0
640
+ /** What `cubicEst`'s last step truncated: the numerator of a fraction of 17 × the window then. */
641
+ cubicEstCarry: i64 = 0
642
+ /**
643
+ * What the window's last step toward the curve truncated: the numerator of a fraction of the
644
+ * window then, so steps smaller than a byte add up instead of being lost (RFC 9438's cwnd_cnt).
645
+ */
646
+ cubicCarry: i64 = 0
647
+ /** CUBIC's cwnd_prior (§4.6): the window just before the last reduction, in bytes. */
648
+ cubicPrior: i64 = 0
649
+ /**
650
+ * When the window last stopped being used (§5.8) during a congestion avoidance stage, or -1: the
651
+ * curve's epoch moves on by the time it was idle, so it resumes where it stood.
652
+ */
653
+ cubicIdle: i64 = -1
549
654
  /** The pacer's credit in bytes (§7.7), and the time it was last topped up in microseconds, or -1. */
550
655
  pacerBudget: i64 = 0
551
656
  /**
@@ -648,6 +753,14 @@ export class QuicRecovery {
648
753
  this.congestionWindow = QUIC_RECOVERY_INITIAL_WINDOW
649
754
  this.ssthresh = QUIC_MAX_VARINT
650
755
  this.recoveryStart = -1
756
+ this.cubicMax = 0
757
+ this.cubicK = 0
758
+ this.cubicEpoch = -1
759
+ this.cubicEst = 0
760
+ this.cubicEstCarry = 0
761
+ this.cubicCarry = 0
762
+ this.cubicPrior = 0
763
+ this.cubicIdle = -1
651
764
  this.pacerBudget = QUIC_RECOVERY_INITIAL_WINDOW
652
765
  this.pacerTime = -1
653
766
  this.pacerRtt = QUIC_RECOVERY_INITIAL_RTT * QUIC_RECOVERY_MICROS
@@ -970,8 +1083,11 @@ export class QuicRecovery {
970
1083
  }
971
1084
  this.detectLoss(sp, now)
972
1085
  this.packetsLost(sp, now)
1086
+ if (this.controller === QUIC_RECOVERY_CUBIC) {
1087
+ this.cubicInUse(inUse, now)
1088
+ }
973
1089
  for (let k: i32 = 0; k < sp.ackedCount; k += 1) {
974
- this.packetAcked(sp, sp.ackedSlot(k), inUse)
1090
+ this.packetAcked(sp, sp.ackedSlot(k), inUse, now)
975
1091
  }
976
1092
  this.ptoCount = 0
977
1093
  return sp.ackedCount
@@ -1192,6 +1308,9 @@ export class QuicRecovery {
1192
1308
  if (newest >= 0 && this.persistentCongestion(sp)) {
1193
1309
  this.congestionWindow = this.minimumWindow()
1194
1310
  this.recoveryStart = -1
1311
+ // CUBIC starts over from slow start (RFC 9438 §4.8): its next stage is a new epoch.
1312
+ this.cubicEpoch = -1
1313
+ this.cubicIdle = -1
1195
1314
  this.persistentCongestions = this.persistentCongestions + 1
1196
1315
  }
1197
1316
  for (let k: i32 = 0; k < sp.lostCount; k += 1) {
@@ -1250,35 +1369,147 @@ export class QuicRecovery {
1250
1369
  return this.recoveryStart >= 0 && sentTime <= this.recoveryStart
1251
1370
  }
1252
1371
 
1253
- /** OnCongestionEvent (B.6): halve the window, once per recovery period. */
1372
+ /**
1373
+ * OnCongestionEvent (B.6), once per recovery period: NewReno halves the
1374
+ * window. CUBIC (RFC 9438 §4.6, §4.7) keeps 0.7 of it, and remembers
1375
+ * where it was as W_max, or 0.85 of that when it is below the W_max
1376
+ * before (fast convergence), so a flow losing ground leaves room sooner.
1377
+ */
1254
1378
  private congestionEvent(sentTime: i64, now: i64): void {
1255
1379
  if (this.inRecovery(sentTime)) {
1256
1380
  return
1257
1381
  }
1258
1382
  this.recoveryStart = now
1259
- this.ssthresh = this.congestionWindow / 2
1383
+ const cwnd: i64 = this.congestionWindow
1384
+ if (this.controller === QUIC_RECOVERY_CUBIC) {
1385
+ this.cubicMax = cwnd < this.cubicMax ? (cwnd * 17) / 20 : cwnd
1386
+ this.cubicPrior = cwnd
1387
+ this.cubicEpoch = -1
1388
+ this.cubicIdle = -1
1389
+ this.ssthresh = (cwnd * 7) / 10
1390
+ } else {
1391
+ this.ssthresh = cwnd / 2
1392
+ }
1260
1393
  this.congestionWindow = quicRecoveryMax(this.ssthresh, this.minimumWindow())
1261
1394
  this.congestionEvents = this.congestionEvents + 1
1262
1395
  }
1263
1396
 
1264
1397
  /**
1265
1398
  * OnPacketAcked (B.5) for slot `s`: in slow start the window grows by the
1266
- * packet's size, in congestion avoidance by datagramSize × size / window; not at
1267
- * all for a packet sent during recovery, or when `inUse` says the window
1268
- * was not being used (§7.8).
1399
+ * packet's size; in congestion avoidance NewReno's by datagramSize × size / window,
1400
+ * CUBIC's as `cubicAcked` says. Not at all for a packet sent during
1401
+ * recovery, or when `inUse` says the window was not being used (§7.8).
1269
1402
  */
1270
- private packetAcked(sp: QuicSentPackets, s: i32, inUse: boolean): void {
1403
+ private packetAcked(sp: QuicSentPackets, s: i32, inUse: boolean, now: i64): void {
1271
1404
  if (!inUse || this.inRecovery(sp.timeAt(s))) {
1272
1405
  return
1273
1406
  }
1274
1407
  const size: i64 = toI64(sp.sizeAt(s))
1275
1408
  if (this.congestionWindow < this.ssthresh) {
1276
1409
  this.congestionWindow = this.congestionWindow + size
1410
+ } else if (this.controller === QUIC_RECOVERY_CUBIC) {
1411
+ this.cubicAcked(size, now)
1277
1412
  } else {
1278
1413
  this.congestionWindow = this.congestionWindow + (this.datagramSize * size) / this.congestionWindow
1279
1414
  }
1280
1415
  }
1281
1416
 
1417
+ /**
1418
+ * CUBIC's congestion avoidance (RFC 9438 §4.2 to §4.5) for `size` bytes
1419
+ * newly acknowledged at `now`. The first acknowledgement of a stage starts
1420
+ * its epoch: K = ∛((W_max − cwnd) / C), or 0 with W_max taken as cwnd
1421
+ * when the window is already past it (after slow start). W_est then grows
1422
+ * as Reno's would with β 0.7, by α = 3(1 − β)/(1 + β) = 9/17 datagram a
1423
+ * window of acknowledgements, and by 1 once it has passed cwnd_prior. If
1424
+ * the curve W(t) is below W_est the window is W_est (the Reno-friendly
1425
+ * region); otherwise it moves toward W(t + RTT), held within cwnd ..
1426
+ * 1.5 × cwnd, by (target − cwnd) × size / cwnd: concave below W_max, convex
1427
+ * past it. Integers throughout; W_est and the window each carry what their
1428
+ * division truncated, so a step under a byte is deferred, never dropped.
1429
+ */
1430
+ private cubicAcked(size: i64, now: i64): void {
1431
+ const cwnd: i64 = this.congestionWindow
1432
+ if (this.cubicEpoch < 0) {
1433
+ this.cubicEpoch = now
1434
+ this.cubicIdle = -1
1435
+ this.cubicEst = cwnd
1436
+ this.cubicEstCarry = 0
1437
+ this.cubicCarry = 0
1438
+ if (this.cubicMax > cwnd) {
1439
+ this.cubicK = this.cubicSpan(this.cubicMax - cwnd)
1440
+ } else {
1441
+ this.cubicK = 0
1442
+ this.cubicMax = cwnd
1443
+ }
1444
+ }
1445
+ const alpha: i64 = this.cubicEst >= this.cubicPrior ? 17 : 9
1446
+ const num: i64 = alpha * size * this.datagramSize + this.cubicEstCarry
1447
+ const den: i64 = 17 * cwnd
1448
+ this.cubicEst = this.cubicEst + num / den
1449
+ this.cubicEstCarry = num % den
1450
+ const t: i64 = now - this.cubicEpoch
1451
+ if (this.cubicWindow(t) < this.cubicEst) {
1452
+ this.congestionWindow = quicRecoveryMax(cwnd, this.cubicEst)
1453
+ return
1454
+ }
1455
+ const ceiling: i64 = cwnd + cwnd / 2
1456
+ const curve: i64 = this.cubicWindow(t + this.smoothedRtt)
1457
+ const target: i64 = quicRecoveryMax(cwnd, curve > ceiling ? ceiling : curve)
1458
+ // The window only grows within a stage, so the carry, below the window
1459
+ // it was a fraction of, stays below the one it is added against.
1460
+ const step: i64 = (target - cwnd) * size + this.cubicCarry
1461
+ this.congestionWindow = cwnd + step / cwnd
1462
+ this.cubicCarry = step % cwnd
1463
+ }
1464
+
1465
+ /**
1466
+ * W_cubic(t) (RFC 9438 §4.2) in bytes, `t` milliseconds into the epoch:
1467
+ * W_max + C × (t − K)³ in datagrams, which is W_max + 2 × size × (t − K)³ /
1468
+ * 5 × 10⁹ in bytes and milliseconds, with t − K clamped to ±40 s. The
1469
+ * division truncates toward zero.
1470
+ */
1471
+ private cubicWindow(t: i64): i64 {
1472
+ const d: i64 = quicRecoveryCubicClamp(t - this.cubicK)
1473
+ return this.cubicMax + (2 * this.datagramSize * (d * d * d)) / QUIC_RECOVERY_CUBIC_SCALE
1474
+ }
1475
+
1476
+ /**
1477
+ * K (RFC 9438 §4.2) for a fall of `drop` bytes below W_max: ∛(drop / C) in
1478
+ * datagrams and seconds, which is ∛(drop × 5 × 10⁹ / (2 × size)) in
1479
+ * milliseconds, rounded down; a fall too deep for the cube to fit is 40 s.
1480
+ */
1481
+ private cubicSpan(drop: i64): i64 {
1482
+ const two: i64 = 2 * this.datagramSize
1483
+ const span: i64 = QUIC_RECOVERY_CUBIC_SPAN
1484
+ // drop >= span³ × 2 × size / (5 × 10⁹), which is 25600 × size, has K at the span or past it.
1485
+ if (drop >= 25600 * this.datagramSize) {
1486
+ return span
1487
+ }
1488
+ return quicRecoveryCbrt((drop * QUIC_RECOVERY_CUBIC_SCALE) / two)
1489
+ }
1490
+
1491
+ /**
1492
+ * The application-limited rule (RFC 9438 §5.8) at an acknowledgement:
1493
+ * while the window is not in use it does not grow (`packetAcked`), and the
1494
+ * time it spends so is taken out of the curve, so a stage resumes where it
1495
+ * stood rather than at the point the clock has reached.
1496
+ */
1497
+ private cubicInUse(inUse: boolean, now: i64): void {
1498
+ if (this.cubicEpoch < 0) {
1499
+ return
1500
+ }
1501
+ if (!inUse) {
1502
+ if (this.cubicIdle < 0) {
1503
+ this.cubicIdle = now
1504
+ }
1505
+ return
1506
+ }
1507
+ if (this.cubicIdle >= 0) {
1508
+ this.cubicEpoch = this.cubicEpoch + (now - this.cubicIdle)
1509
+ this.cubicIdle = -1
1510
+ }
1511
+ }
1512
+
1282
1513
  /**
1283
1514
  * The probe timeout's period without backoff (§6.2.1): smoothed_rtt +
1284
1515
  * max(4 × rttvar, kGranularity), plus the peer's max_ack_delay once the