@amritk/nish-aarch64-linux 0.38.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/bin/nish +0 -0
  2. package/docs/AI.md +348 -37
  3. package/package.json +1 -1
  4. package/runtime/core/host.d.ts +11 -0
  5. package/runtime/core/host.mjs +35 -0
  6. package/runtime/nish.d.ts +301 -18
  7. package/runtime/nish.h +74 -10
  8. package/runtime/nish.mjs +69 -6
  9. package/runtime/node.mjs +117 -0
  10. package/runtime/runtime-aes.c +12 -4
  11. package/runtime/runtime-async.c +43 -10
  12. package/runtime/runtime-checksum.c +207 -15
  13. package/runtime/runtime-net.c +32 -3
  14. package/runtime/runtime-os.c +174 -27
  15. package/runtime/runtime-region.c +94 -10
  16. package/runtime/runtime-sandbox.c +377 -17
  17. package/runtime/runtime-sha256.c +11 -4
  18. package/runtime/runtime-wasm.c +15 -0
  19. package/runtime/runtime.c +5 -0
  20. package/scripts/build.sh +27 -8
  21. package/std/README.md +5 -4
  22. package/std/compress/checksum.ts +13 -0
  23. package/std/compress/deflate.ts +0 -2
  24. package/std/crypto/p256.ts +247 -74
  25. package/std/crypto/p384.ts +3 -1
  26. package/std/crypto/pki.ts +35 -9
  27. package/std/crypto/x25519.ts +153 -64
  28. package/std/crypto/x509.ts +113 -10
  29. package/std/json-tokenizer.ts +20 -0
  30. package/std/json-typed.ts +217 -8
  31. package/std/net/handler.ts +130 -16
  32. package/std/net/http1-codec.ts +499 -150
  33. package/std/net/http1-server.ts +495 -22
  34. package/std/net/http2-cleartext.ts +526 -0
  35. package/std/net/http2-tls.ts +48 -0
  36. package/std/net/http2.ts +84 -0
  37. package/std/net/postgres-async.ts +1304 -86
  38. package/std/net/postgres-carrier.ts +343 -10
  39. package/std/net/postgres.ts +122 -7
  40. package/std/net/prefork.ts +195 -11
  41. package/std/net/quic-datagram.ts +30 -0
  42. package/std/net/quic-listener.ts +38 -12
  43. package/std/net/quic-packet.ts +19 -6
  44. package/std/net/quic-recovery.ts +134 -19
  45. package/std/net/quic-stream.ts +174 -36
  46. package/std/net/quic.ts +418 -18
  47. package/std/net/router.ts +39 -17
  48. package/std/net/serve.ts +162 -58
  49. package/std/net/tls/codec.ts +110 -32
  50. package/std/net/tls/record-server.ts +37 -7
  51. package/std/net/tls-tcp.ts +56 -1
  52. package/std/net/tls.ts +196 -50
  53. package/std/net/websocket.ts +55 -18
  54. package/std/net/webtransport.ts +179 -1
  55. package/std/regex.ts +69 -47
  56. package/std/region.ts +62 -11
  57. package/std/secret.ts +26 -59
  58. package/std/text.ts +233 -0
@@ -52,8 +52,10 @@
52
52
  * frame with a one-byte payload, or a status code that may not be sent
53
53
  * (§5.5.1, §7.4).
54
54
  * - 1007: a text message, or a close reason, that is not UTF-8 (§8.1). A text
55
- * message is checked as each fragment arrives, so a bad byte is refused
56
- * without waiting for the rest.
55
+ * message is checked as its bytes arrive, inside a frame as well as across
56
+ * fragments, so a bad byte is refused without waiting for the rest of the
57
+ * frame. The message buffer grows with the bytes received, not the length
58
+ * a frame header declares.
57
59
  * - 1009: a message longer than `maxMessage` (§7.4.1), refused from the frame
58
60
  * header that would pass it, before its payload arrives.
59
61
  *
@@ -279,6 +281,8 @@ export class WsDecoder {
279
281
  messageOpcode: i32 = 0
280
282
  /** @internal Decoder state the module's `websocket` helpers read and write. */
281
283
  messageLen: i32 = 0
284
+ /** How many payload bytes of the text frame still arriving are unmasked and UTF-8 checked. @internal */
285
+ frameChecked: i32 = 0
282
286
 
283
287
  /** Whether every frame must be masked, as a server requires of a client. */
284
288
  expectMasked: boolean = false
@@ -359,6 +363,7 @@ export class WsDecoder {
359
363
  this.closeReason = ""
360
364
  this.messageOpcode = 0
361
365
  this.messageLen = 0
366
+ this.frameChecked = 0
362
367
  this.data = this.control
363
368
  websocketUtf8Reset(this.utf8)
364
369
  }
@@ -401,7 +406,8 @@ const websocketFail = (d: WsDecoder, code: i32, reason: string): i32 => {
401
406
  /**
402
407
  * Copies the frame payload at `buf[from .. from + len)` into `to[at ..)`,
403
408
  * unmasking it with the key at `buf[maskAt .. maskAt + 4)` when `masked`
404
- * (§5.3: byte i is XORed with key byte i mod 4).
409
+ * (§5.3: byte i is XORed with key byte i mod 4). `phase` is how far into the
410
+ * payload `from` is, so a payload can be unmasked a piece at a time.
405
411
  */
406
412
  const websocketUnmaskInto = (
407
413
  buf: u8[],
@@ -409,6 +415,7 @@ const websocketUnmaskInto = (
409
415
  len: i32,
410
416
  masked: boolean,
411
417
  maskAt: i32,
418
+ phase: i32,
412
419
  to: u8[],
413
420
  at: i32
414
421
  ): void => {
@@ -422,13 +429,19 @@ const websocketUnmaskInto = (
422
429
  (toU32(buf[maskAt + 2]) << 8) |
423
430
  toU32(buf[maskAt + 3])
424
431
  }
432
+ for (let r: i32 = 0; r < (phase & 3); r += 1) {
433
+ key = (key << 8) | (key >>> 24)
434
+ }
425
435
  for (let k: i32 = 0; k < len; k += 1) {
426
436
  to[at + k] = buf[from + k] ^ toU8(key >>> 24)
427
437
  key = (key << 8) | (key >>> 24)
428
438
  }
429
439
  }
430
440
 
431
- /** Grows `d.message` so that `need` bytes fit, keeping its live bytes. */
441
+ /**
442
+ * Grows `d.message` so that `need` bytes fit, keeping its live bytes: the
443
+ * message so far and the part of a text frame already checked.
444
+ */
432
445
  const websocketMessageRoom = (d: WsDecoder, need: i32): void => {
433
446
  const old: u8[] = d.message
434
447
  let size: i32 = toI32(old.length)
@@ -439,7 +452,8 @@ const websocketMessageRoom = (d: WsDecoder, need: i32): void => {
439
452
  size = size > 1073741823 ? 2147483647 : size * 2
440
453
  }
441
454
  const grown: u8[] = new Array<u8>(size)
442
- for (let k: i32 = 0; k < d.messageLen && k < toI32(grown.length) && k < toI32(old.length); k += 1) {
455
+ const live: i32 = d.messageLen + d.frameChecked
456
+ for (let k: i32 = 0; k < live && k < toI32(grown.length) && k < toI32(old.length); k += 1) {
443
457
  grown[k] = old[k]
444
458
  }
445
459
  d.message = grown
@@ -567,15 +581,41 @@ const websocketFrameEvent = (d: WsDecoder): i32 => {
567
581
  return websocketFail(d, WS_CLOSE_TOO_BIG, "a message longer than the limit")
568
582
  }
569
583
  }
584
+ const payloadAt: i32 = at + headerLength
585
+ const maskAt: i32 = payloadAt - 4
586
+ const text: boolean =
587
+ opcode === WS_OP_TEXT || (opcode === WS_OP_CONTINUATION && d.messageOpcode === WS_OP_TEXT)
588
+ if (text) {
589
+ // A text frame is unmasked and checked as its bytes arrive, so a byte
590
+ // that cannot continue UTF-8 fails the connection at once (§8.1), not
591
+ // when the frame or the message ends.
592
+ const arrived: i32 = ready - headerLength < length ? ready - headerLength : length
593
+ const from: i32 = d.messageLen
594
+ const done: i32 = d.frameChecked
595
+ if (done === 0 && opcode === WS_OP_TEXT) {
596
+ // A new message starts its UTF-8 check afresh, in place: nothing is
597
+ // allocated per message.
598
+ websocketUtf8Reset(d.utf8)
599
+ }
600
+ if (arrived > done) {
601
+ // Room for the bytes that have arrived, not the length the header
602
+ // declares: a peer that declares much and sends little costs little.
603
+ websocketMessageRoom(d, from + arrived)
604
+ websocketUnmaskInto(buf, payloadAt + done, arrived - done, masked, maskAt, done, d.message, from + done)
605
+ d.frameChecked = arrived
606
+ if (!websocketUtf8Run(d.utf8, d.message, from + done, arrived - done)) {
607
+ return websocketFail(d, WS_CLOSE_INVALID_DATA, "a text message that is not UTF-8")
608
+ }
609
+ }
610
+ }
570
611
  if (ready - headerLength < length) {
571
612
  return WS_NEED_MORE
572
613
  }
573
614
  // The whole frame is here: take it out of the input.
574
- const payloadAt: i32 = at + headerLength
575
- const maskAt: i32 = payloadAt - 4
576
615
  d.start = payloadAt + length
616
+ d.frameChecked = 0
577
617
  if (control) {
578
- websocketUnmaskInto(buf, payloadAt, length, masked, maskAt, d.control, 0)
618
+ websocketUnmaskInto(buf, payloadAt, length, masked, maskAt, 0, d.control, 0)
579
619
  d.opcode = opcode
580
620
  d.data = d.control
581
621
  d.dataLen = length
@@ -586,21 +626,18 @@ const websocketFrameEvent = (d: WsDecoder): i32 => {
586
626
  }
587
627
  if (opcode !== WS_OP_CONTINUATION) {
588
628
  d.messageOpcode = opcode
589
- // A new message starts its UTF-8 check afresh, in place: nothing is
590
- // allocated per message.
591
- websocketUtf8Reset(d.utf8)
592
629
  }
593
630
  const from: i32 = d.messageLen
594
- websocketMessageRoom(d, from + length)
595
- websocketUnmaskInto(buf, payloadAt, length, masked, maskAt, d.message, from)
596
- d.messageLen = from + length
597
- if (d.messageOpcode === WS_OP_TEXT && !websocketUtf8Run(d.utf8, d.message, from, length)) {
598
- return websocketFail(d, WS_CLOSE_INVALID_DATA, "a text message that is not UTF-8")
631
+ if (!text) {
632
+ // A text frame's payload is already in `message`, unmasked and checked.
633
+ websocketMessageRoom(d, from + length)
634
+ websocketUnmaskInto(buf, payloadAt, length, masked, maskAt, 0, d.message, from)
599
635
  }
636
+ d.messageLen = from + length
600
637
  if (!fin) {
601
638
  return WS_CONTINUE
602
639
  }
603
- if (d.messageOpcode === WS_OP_TEXT && d.utf8.need !== 0) {
640
+ if (text && d.utf8.need !== 0) {
604
641
  return websocketFail(d, WS_CLOSE_INVALID_DATA, "a text message that ends inside a character")
605
642
  }
606
643
  // The message is handed out whole, and the next data frame starts a new one
@@ -747,7 +784,7 @@ export const websocketWriteFrame = (
747
784
  }
748
785
  // Masking and unmasking are the same XOR, so the copied payload goes
749
786
  // through the decoder's own loop, reading the key just written.
750
- websocketUnmaskInto(out, payloadAt, len, true, keyAt, out, payloadAt)
787
+ websocketUnmaskInto(out, payloadAt, len, true, keyAt, 0, out, payloadAt)
751
788
  }
752
789
  return payloadAt + len
753
790
  }
@@ -105,6 +105,22 @@
105
105
  * state through the QUIC connection's stream index, never by a scan, and
106
106
  * nothing a warm session does allocates. Counters a peer drives saturate.
107
107
  *
108
+ * **The clock.** Each session keeps the time of its last activity
109
+ * (`monotonicNanos`, read once a call of `next`): its request, its accept,
110
+ * a datagram or a stream event either way, a capsule. `expire(now)`, called
111
+ * from the program's loop as `Http1Server.expire` is, ends every session
112
+ * quiet for longer than `WebTransportConfig.idleTimeout`: one never answered
113
+ * is refused with 503, an accepted one is closed (CLOSE with code 0 and the
114
+ * FIN, or a reset both ways when the capsule does not fit), and one already
115
+ * closed whose client never finished its half is let go. Each session it
116
+ * ends that the program still held is reported by the next calls of `next`
117
+ * as WT_CLOSED, `closedByPeer` false, code 0. A session takes at most
118
+ * `maxDatagramsPerSecond` datagrams in each fixed one-second window, the
119
+ * first starting when the session is asked for and the next at the first
120
+ * datagram a second or more after it; the rest are dropped and counted in
121
+ * `datagramsDropped`. The window does not slide, so across a boundary up to
122
+ * twice the cap can arrive within a second.
123
+ *
108
124
  * **Error codes.** A stream's reset and STOP_SENDING carry an HTTP/3 code;
109
125
  * a WebTransport application's 32-bit code maps into the range from
110
126
  * 0x52e4a40fa8db (`wtCodeToHttp3`, `wtCodeFromHttp3`), as Chrome maps it.
@@ -155,6 +171,7 @@ import {
155
171
  import { QUIC_DATAGRAM_ERR_FULL, QUIC_DATAGRAM_NONE, QUIC_DATAGRAM_OK, QuicConnection } from "nish/net/quic"
156
172
  import { quicPacketCopy, quicVarintSize } from "nish/net/quic-packet"
157
173
  import { quicStreamIsUni } from "nish/net/quic-stream"
174
+ import { monotonicNanos } from "nish:process"
158
175
 
159
176
  /** A session asked for: `sessionId`, `fields`. */
160
177
  export const WT_SESSION: i32 = 16
@@ -198,6 +215,15 @@ export const WT_FIRST_APP_CODE: i64 = 0x52e4a40fa8db
198
215
  /** The most a configuration may set `maxStreams` and `maxPending` to. */
199
216
  const WT_MAX_CAP: i32 = 4096
200
217
 
218
+ /** The longest `idleTimeout`, a day in milliseconds, and the highest `maxDatagramsPerSecond`. */
219
+ const WT_MAX_IDLE: i32 = 86400000
220
+ const WT_MAX_RATE: i32 = 1048576
221
+ /** Nanoseconds in a millisecond, and in a second. */
222
+ const WT_MILLI: i64 = 1000000
223
+ const WT_SECOND: i64 = 1000000000
224
+ /** The status a session asked for and never answered gets when `expire` ends it. */
225
+ const WT_STATUS_UNANSWERED: i32 = 503
226
+
201
227
  /** Session states. */
202
228
  const WT_FREE: i32 = 0
203
229
  const WT_ASKED: i32 = 1
@@ -234,6 +260,14 @@ export class WebTransportConfig {
234
260
  maxStreams: i32 = 64
235
261
  /** Streams that may wait at once for a session not yet answered or not yet arrived (draft-02 §4.5). */
236
262
  maxPending: i32 = 16
263
+ /**
264
+ * Milliseconds a session may go without activity before `expire` ends it, 1 to 86,400,000: a
265
+ * session asked for counts from its request, an accepted one from its last datagram or stream
266
+ * event either way, and one this side closed from its close.
267
+ */
268
+ idleTimeout: i32 = 60000
269
+ /** Datagrams one session may deliver in a second, 1 to 1,048,576; the rest are dropped and counted. */
270
+ maxDatagramsPerSecond: i32 = 1024
237
271
  }
238
272
 
239
273
  /**
@@ -463,8 +497,18 @@ export class WebTransport {
463
497
  datagramsIn: i32[]
464
498
  /** How many datagrams each session sent, saturating at 2^31 - 1; zeroed when a session is asked for. */
465
499
  datagramsOut: i32[]
500
+ /** When each session was last active, and when its datagram second began and how many it took (`monotonicNanos`). */
501
+ private lastActive: i64[]
502
+ private rateSince: i64[]
503
+ private rateCount: i32[]
466
504
  /** The free sessions, a stack. */
467
505
  private free: i32[]
506
+ /** Sessions `expire` ended that `next` has not yet reported, `expiredCount` of them, with their IDs. */
507
+ private expiredSessions: i32[]
508
+ private expiredIds: i64[]
509
+ /** The time `next` last read, which stamps activity; and no session can expire before `expireAfter`. */
510
+ private now: i64 = 0
511
+ private expireAfter: i64 = 0
468
512
  // Per QUIC stream slot.
469
513
  /** The session whose CONNECT stream the slot holds, or -1. */
470
514
  sessionAt: i32[]
@@ -495,6 +539,8 @@ export class WebTransport {
495
539
  * WT_CLOSED, `errorCode` itself.
496
540
  */
497
541
  appCode: i64 = -1
542
+ /** How many of `expiredSessions` `next` has still to report. */
543
+ private expiredCount: i32 = 0
498
544
  /** Where the capsules of a DATA window are being read: `h3.data[capAt .. capEnd)`, for session `capSession`. */
499
545
  private capAt: i32 = 0
500
546
  private capEnd: i32 = 0
@@ -527,7 +573,8 @@ export class WebTransport {
527
573
  /**
528
574
  * The WebTransport layer of `h3`, whose `Http3Config` must have
529
575
  * `webtransportSessions` above 0. A cap out of range panics.
530
- * @param config The caps: `maxStreams` 1 to 4096 and `maxPending` 0 to 4096; kept, not copied.
576
+ * @param config The caps: `maxStreams` 1 to 4096, `maxPending` 0 to 4096, `idleTimeout` 1 to
577
+ * 86,400,000 and `maxDatagramsPerSecond` 1 to 1,048,576; kept, not copied.
531
578
  * @param h3 The connection this layer reads and writes, kept for the layer's life; its restarts
532
579
  * restart this layer too.
533
580
  */
@@ -539,6 +586,8 @@ export class WebTransport {
539
586
  }
540
587
  webtransportCheckCap("maxStreams", config.maxStreams, 1, WT_MAX_CAP)
541
588
  webtransportCheckCap("maxPending", config.maxPending, 0, WT_MAX_CAP)
589
+ webtransportCheckCap("idleTimeout", config.idleTimeout, 1, WT_MAX_IDLE)
590
+ webtransportCheckCap("maxDatagramsPerSecond", config.maxDatagramsPerSecond, 1, WT_MAX_RATE)
542
591
  this.config = config
543
592
  this.h3 = h3
544
593
  this.quic = h3.quic
@@ -566,7 +615,13 @@ export class WebTransport {
566
615
  this.capFill = new Array<i32>(sessions)
567
616
  this.datagramsIn = new Array<i32>(sessions)
568
617
  this.datagramsOut = new Array<i32>(sessions)
618
+ this.lastActive = new Array<i64>(sessions)
619
+ this.rateSince = new Array<i64>(sessions)
620
+ this.rateCount = new Array<i32>(sessions)
569
621
  this.free = new Array<i32>(sessions)
622
+ this.expiredSessions = new Array<i32>(sessions)
623
+ this.expiredIds = new Array<i64>(sessions)
624
+ this.now = monotonicNanos()
570
625
  const n: i32 = toI32(h3.quic.streams.slots.length)
571
626
  const slots: i32 = n > 0 ? n : WT_ONE
572
627
  this.sessionAt = new Array<i32>(slots)
@@ -595,6 +650,8 @@ export class WebTransport {
595
650
  }
596
651
  this.waiting.reset()
597
652
  this.adoptCount = 0
653
+ this.expiredCount = 0
654
+ this.expireAfter = 0
598
655
  this.capAt = 0
599
656
  this.capEnd = 0
600
657
  this.capSession = -1
@@ -659,6 +716,16 @@ export class WebTransport {
659
716
  */
660
717
  next(): i32 {
661
718
  this.current()
719
+ const clock: i64 = monotonicNanos()
720
+ // The clock never runs back, so a session's deadline only moves later.
721
+ this.now = clock > this.now ? clock : this.now
722
+ if (this.expiredCount > 0) {
723
+ this.expiredCount = this.expiredCount - 1
724
+ const id: i64 = this.expiredIds[this.expiredCount]
725
+ this.sessionId = id
726
+ this.stream = id
727
+ return this.closedEvent(this.expiredSessions[this.expiredCount], WT_ZERO64, WT_ZERO, false)
728
+ }
662
729
  for (let guard: i32 = 0; guard < 1000000; guard++) {
663
730
  if (this.adoptCount > 0) {
664
731
  const event: i32 = this.adoptWaiting()
@@ -717,6 +784,17 @@ export class WebTransport {
717
784
  this.datagramsDropped = h3Count(this.datagramsDropped)
718
785
  return WT_ONE
719
786
  }
787
+ if (this.now - this.rateSince[s] >= WT_SECOND) {
788
+ this.rateSince[s] = this.now
789
+ this.rateCount[s] = 0
790
+ }
791
+ if (this.rateCount[s] >= this.config.maxDatagramsPerSecond) {
792
+ // Past the session's datagrams a second: dropped, as one QUIC could not queue would be.
793
+ this.datagramsDropped = h3Count(this.datagramsDropped)
794
+ return WT_ONE
795
+ }
796
+ this.rateCount[s] = this.rateCount[s] + 1
797
+ this.lastActive[s] = this.now
720
798
  const at: i32 = h3VarintLength(this.datagram, WT_ZERO)
721
799
  this.datagramsIn[s] = h3Count(this.datagramsIn[s])
722
800
  this.session = s
@@ -761,6 +839,7 @@ export class WebTransport {
761
839
  return event === H3_STOPPED ? H3_NEED_MORE : event
762
840
  }
763
841
  const t: i32 = this.streamSession[k]
842
+ this.touch(k)
764
843
  this.stream = id
765
844
  this.session = t
766
845
  this.sessionId = t >= 0 && t < toI32(this.sessionIds.length) ? this.sessionIds[t] : WT_NONE64
@@ -796,6 +875,7 @@ export class WebTransport {
796
875
  /** An event of session `s`'s CONNECT stream. */
797
876
  private connectEvent(s: i32, event: i32): i32 {
798
877
  const h3: Http3Connection = this.h3
878
+ this.lastActive[s] = this.now
799
879
  this.session = s
800
880
  this.sessionId = this.sessionIds[s]
801
881
  this.stream = this.sessionIds[s]
@@ -914,6 +994,9 @@ export class WebTransport {
914
994
  this.capFill[s] = 0
915
995
  this.datagramsIn[s] = 0
916
996
  this.datagramsOut[s] = 0
997
+ this.lastActive[s] = this.now
998
+ this.rateSince[s] = this.now
999
+ this.rateCount[s] = 0
917
1000
  this.sessionAt[k] = s
918
1001
  this.session = s
919
1002
  this.sessionId = id
@@ -952,6 +1035,7 @@ export class WebTransport {
952
1035
  return result
953
1036
  }
954
1037
  this.states[s] = WT_OPEN
1038
+ this.lastActive[s] = this.now
955
1039
  // The streams that waited for it are taken by the next calls of `next`, each with its WT_STREAM.
956
1040
  if (this.waiting.first(id) >= 0 && this.adoptCount < toI32(this.adoptions.length)) {
957
1041
  this.adoptions[this.adoptCount] = s
@@ -1021,6 +1105,8 @@ export class WebTransport {
1021
1105
  this.streamCount[s] = 0
1022
1106
  this.dropPending(this.sessionIds[s])
1023
1107
  this.states[s] = WT_GONE
1108
+ // A closed session's clock restarts: the client has `idleTimeout` to finish its half.
1109
+ this.lastActive[s] = this.now
1024
1110
  }
1025
1111
 
1026
1112
  /** Refuses with WT_SESSION_GONE every stream waiting for session `id`. */
@@ -1099,6 +1185,94 @@ export class WebTransport {
1099
1185
  return this.h3.writeDataWhole(id, out, WT_ZERO, p, false)
1100
1186
  }
1101
1187
 
1188
+ /** Stamps the session of the stream in QUIC slot `k` as active now. */
1189
+ private touch(k: i32): void {
1190
+ const t: i32 = this.streamSession[k]
1191
+ if (t >= 0 && t < toI32(this.lastActive.length)) {
1192
+ this.lastActive[t] = this.now
1193
+ }
1194
+ }
1195
+
1196
+ // ---- The clock -------------------------------------------------------------------
1197
+
1198
+ /**
1199
+ * Ends every session quiet for longer than `idleTimeout` at `now` (see
1200
+ * the module comment): one never answered is refused with 503, an
1201
+ * accepted one closed with code 0, and one already closed whose client
1202
+ * never finished its half let go. Call it from the program's loop; it
1203
+ * returns at once before the soonest deadline it last saw. The next calls
1204
+ * of `next` report each session the program held as WT_CLOSED.
1205
+ * @param now The current time, from `monotonicNanos`.
1206
+ * @returns How many sessions it ended.
1207
+ */
1208
+ expire(now: i64): i32 {
1209
+ this.current()
1210
+ if (now < this.expireAfter) {
1211
+ return 0
1212
+ }
1213
+ this.now = now > this.now ? now : this.now
1214
+ const idle: i64 = toI64(this.config.idleTimeout) * WT_MILLI
1215
+ let soonest: i64 = now + idle
1216
+ let n: i32 = 0
1217
+ for (let s: i32 = 0; s < toI32(this.states.length); s++) {
1218
+ const state: i32 = this.states[s]
1219
+ if (state !== WT_FREE) {
1220
+ const deadline: i64 = this.lastActive[s] + idle
1221
+ if (now > deadline) {
1222
+ this.timeOut(s, state)
1223
+ n = n + 1
1224
+ } else if (deadline < soonest) {
1225
+ soonest = deadline
1226
+ }
1227
+ }
1228
+ }
1229
+ this.expireAfter = soonest
1230
+ return n
1231
+ }
1232
+
1233
+ /**
1234
+ * The soonest `expire` could end a session, at or after `now`: activity
1235
+ * only moves a session's deadline later.
1236
+ * @param now The current time, from `monotonicNanos`.
1237
+ * @returns The earliest `monotonicNanos` instant at which `expire` could end a session; `now` plus
1238
+ * `idleTimeout` when no session is held.
1239
+ */
1240
+ expiresNoSooner(now: i64): i64 {
1241
+ const idle: i64 = toI64(this.config.idleTimeout) * WT_MILLI
1242
+ let soonest: i64 = now + idle
1243
+ for (let s: i32 = 0; s < toI32(this.states.length); s++) {
1244
+ if (this.states[s] !== WT_FREE && this.lastActive[s] + idle < soonest) {
1245
+ soonest = this.lastActive[s] + idle
1246
+ }
1247
+ }
1248
+ return soonest > now ? soonest : now
1249
+ }
1250
+
1251
+ /** Ends session `s`, in `state`, for its idleness, and queues its WT_CLOSED unless the program let go of it already. */
1252
+ private timeOut(s: i32, state: i32): void {
1253
+ const id: i64 = this.sessionIds[s]
1254
+ if (state === WT_ASKED) {
1255
+ this.answer(id, WT_STATUS_UNANSWERED)
1256
+ this.release(s)
1257
+ } else if (state === WT_OPEN) {
1258
+ if (this.close(id, WT_ZERO64, this.reason, WT_ZERO, WT_ZERO) !== 0) {
1259
+ // No room for the capsule: reset the CONNECT stream both ways, after which no event ends the session.
1260
+ this.h3.reset(id, H3_NO_ERROR)
1261
+ this.release(s)
1262
+ }
1263
+ } else {
1264
+ // Closed here, or by the client's CLOSE, and the client never finished its half: stop reading it.
1265
+ this.h3.discardRequest(id, H3_NO_ERROR)
1266
+ this.release(s)
1267
+ return
1268
+ }
1269
+ if (this.expiredCount < toI32(this.expiredSessions.length)) {
1270
+ this.expiredSessions[this.expiredCount] = s
1271
+ this.expiredIds[this.expiredCount] = id
1272
+ this.expiredCount = this.expiredCount + 1
1273
+ }
1274
+ }
1275
+
1102
1276
  // ---- Capsules --------------------------------------------------------------------
1103
1277
 
1104
1278
  /**
@@ -1368,6 +1542,9 @@ export class WebTransport {
1368
1542
  return H3_CLOSED
1369
1543
  }
1370
1544
  const n: i32 = this.h3.writeStream(id, buf, off, len, fin)
1545
+ if (n >= 0) {
1546
+ this.touch(k)
1547
+ }
1371
1548
  if (fin && n === len) {
1372
1549
  this.settle(k, WT_SENT)
1373
1550
  }
@@ -1463,6 +1640,7 @@ export class WebTransport {
1463
1640
  quicPacketCopy(out, p, buf, off, len)
1464
1641
  const result: i32 = this.quic.sendDatagram(out, WT_ZERO, p + len)
1465
1642
  if (result === QUIC_DATAGRAM_OK) {
1643
+ this.lastActive[s] = this.now
1466
1644
  this.datagramsOut[s] = h3Count(this.datagramsOut[s])
1467
1645
  return 0
1468
1646
  }