@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
package/std/json-typed.ts CHANGED
@@ -25,10 +25,11 @@
25
25
  * functions here for each field, and into `JsonWriter`'s, so all of the parsing
26
26
  * is the tokenizer's and all of the writing is the writer's. A field may be an
27
27
  * `i32`, `u32`, `i64`, `u64`, `f64` (or `number`), `boolean` or `string`, a
28
- * numeric enum (its number), a class decoded the same way, a `JsonNumber`, an
29
- * array of any of those, a `Map<string, V>` (a JSON object) whose `V` is any of
30
- * these, or a string, class, array or map `| null`; anything else is refused at
31
- * the call, naming the field (docs/LANGUAGE.md, "Typed JSON").
28
+ * numeric enum (its number), a class decoded the same way, a tagged union of
29
+ * classes, a `JsonNumber`, an array of any of those, a `Map<string, V>` (a
30
+ * JSON object) whose `V` is any of these, or a string, class, union, array or
31
+ * map `| null`; anything else is refused at the call, naming the field
32
+ * (docs/LANGUAGE.md, "Typed JSON").
32
33
  *
33
34
  * **Call shapes.** `jsonDecode(d, out)` reads the one JSON object `d` holds
34
35
  * into `out`, a declared class, and answers `d.failed`: `JSON_DECODE_OK` (0)
@@ -70,6 +71,11 @@
70
71
  * map's, each value a V each value set map's order
71
72
  * JsonNumber any number, kept as the text d.number(n) jsonEncodeNumber
72
73
  * it is written in
74
+ * tagged union U, U | null an object whose tag names a the variant's the variant's
75
+ * variant, and null for the decoding, into encoding, its
76
+ * second the object held tag first
77
+ * when its tag
78
+ * matches
73
79
  *
74
80
  * A `Map`'s `V` is any type in this list, `| null` or not, a `Map` included;
75
81
  * `JsonNumber` may stand alone, be `| null`, be an array's element or be a
@@ -182,6 +188,9 @@
182
188
  * its field's type. Without it every field is required and a missing key is
183
189
  * `JSON_DECODE_MISSING`.
184
190
  * - `presence`, described below. Without it nothing is recorded.
191
+ * - `tag`, a string literal: what a variant of a tagged union writes as its
192
+ * tag, described below. Without it, or with `tag: ""`, the tag is the enum
193
+ * member's name.
185
194
  *
186
195
  * Each misuse has its own diagnostic:
187
196
  *
@@ -191,7 +200,7 @@
191
200
  * the literal it must be (a module constant, an array for the
192
201
  * object, a string for `optional`'s array); `presence` or one of
193
202
  * its entries not an object literal of string literals
194
- * NL2494 an option other than `rename`, `optional` and `presence`
203
+ * NL2494 an option other than `rename`, `optional`, `presence` and `tag`
195
204
  * NL2495 a name that is not one of the class's fields; `presence` naming
196
205
  * a field or a presence field the class does not declare
197
206
  * NL2496 a rename to a value that is not a string
@@ -204,9 +213,11 @@
204
213
  * field it records, records two fields, is recorded by a presence
205
214
  * field of its own or is renamed or made optional; a field
206
215
  * recorded twice
216
+ * NL2722 a `tag` that is not a string literal
217
+ * NL2724 a `tag` on a class with no field whose type is one enum member
207
218
  *
208
- * A spread or a computed key in the literal is refused as it is anywhere
209
- * (NL1061, NL1041), a subclass by `extends`, and a second `static readonly
219
+ * A spread in the literal is refused (NL2711), a computed key as it is
220
+ * anywhere (NL1041), a subclass by `extends`, and a second `static readonly
210
221
  * json` is a duplicate member. The options are not a value: `User.json` names a
211
222
  * class where a value is due, and is refused as any class name there is.
212
223
  *
@@ -253,6 +264,53 @@
253
264
  * refused before any of it is applied. `examples/merge-patch.ts` is the
254
265
  * recipe in full.
255
266
  *
267
+ * **A tagged union.** A union of classes, each with a field whose type is
268
+ * one member of one enum (`readonly kind: Kind.Num = Kind.Num`), is written
269
+ * as one object whose tag picks the variant:
270
+ *
271
+ * enum Kind { Num, Neg }
272
+ * class Num { readonly kind: Kind.Num = Kind.Num; value: f64 = 0 }
273
+ * class Neg {
274
+ * static readonly json = { tag: "negate" };
275
+ * readonly kind: Kind.Neg = Kind.Neg;
276
+ * arg: Expr;
277
+ * constructor() { this.arg = zero() }
278
+ * }
279
+ * type Expr = Num | Neg; // {"kind":"negate","arg":{"kind":"Num","value":2}}
280
+ *
281
+ * let e: Expr = zero();
282
+ * e = jsonDecodeUnion(d, e); // d.failed says whether it worked
283
+ * jsonEncode(w, e);
284
+ *
285
+ * The tag's key is the tag field's name, or its `rename`, and every variant
286
+ * gives the same one (NL2721). Its value is the enum member's name, or the
287
+ * variant's `tag` option, and no two variants write the same one (NL2720). The
288
+ * tag may be any key of the object: when it is the first, the variant is picked
289
+ * at once; when it is not, the keys before it are stepped over, checked but not
290
+ * kept, and the object is read again from its first key once the variant is
291
+ * known. A nested union does the same inside the bytes its parent read ahead
292
+ * over only when it is decoded, so each byte of the input is read again at
293
+ * most once per level of nesting above it: at most `maxDepth` times
294
+ * (docs/security/json.md, JSON-17), counted in `JsonDecoder.unionReread`.
295
+ *
296
+ * `jsonDecode` decodes into the object it is given and cannot change which
297
+ * class that is, so a union is decoded with `jsonDecodeUnion(d, prev)`, which
298
+ * answers the object it decoded into: `prev` when the tag names `prev`'s
299
+ * variant, a new one made by `new V()` when it does not or `prev` is `null`,
300
+ * and `prev` when the decode fails (NL2719 refuses `jsonDecode` of a union;
301
+ * NL2723 refuses `jsonDecodeUnion` of anything else). A union field, a union
302
+ * array's element and a `| null` union field follow the same rule. Encoding
303
+ * writes the tag first, then the variant's fields. A variant decoded alone,
304
+ * by `jsonDecode`, reads its tag like any field and fails with
305
+ * `JSON_DECODE_TAG` when it is not its own. The code is written once per
306
+ * union, so a recursive union is one function that calls itself, and a
307
+ * `Map<string, Expr>` decodes and encodes each value through it.
308
+ *
309
+ * A failed decode answers `prev` at the top only. A union field, element or
310
+ * map value below it whose tag named another variant already holds the new
311
+ * variant when the failure comes, decoded up to it, as any failed `jsonDecode`
312
+ * leaves what it read: check `d.failed` before using the object.
313
+ *
256
314
  * **Errors are sticky codes**, as the tokenizer's and the writer's are. The
257
315
  * first error sets `failed` to a negative code — a `JSON_DECODE_*` code here,
258
316
  * or the tokenizer's own `JSON_TOK_ERR_*` code when the text is not JSON or
@@ -271,6 +329,8 @@
271
329
  * JSON_DECODE_DUPLICATE -23 a key given twice the second
272
330
  * JSON_DECODE_MISSING -24 a field the object lacks the object's `}`
273
331
  * JSON_DECODE_MAP_LIMIT -25 more than maxMapKeys map keys the first key past it
332
+ * JSON_DECODE_TAG -26 a union's tag missing, not a the tag's value, or
333
+ * string, or no variant's the object's `{`
274
334
  * JSON_TOK_ERR_* -1 to -13 text that is not JSON, or past the tokenizer's
275
335
  * a JsonLimits limit
276
336
  *
@@ -373,10 +433,17 @@ export const JSON_DECODE_MISSING: i32 = -24
373
433
  * together (docs/security/json.md, JSON-13).
374
434
  */
375
435
  export const JSON_DECODE_MAP_LIMIT: i32 = -25
436
+ /**
437
+ * A tagged union's object whose tag is missing, not a string, or none of the
438
+ * union's variants' wire tags, or a variant's object whose tag is not that
439
+ * variant's own; `errorAt` is the tag's value, or the object's `{` when the
440
+ * tag is missing.
441
+ */
442
+ export const JSON_DECODE_TAG: i32 = -26
376
443
 
377
444
  /** What a program running under Node is told, where the compiler would have written the code. */
378
445
  const JSON_TYPED_ERASED: string =
379
- "nish/json-typed: jsonDecode and jsonEncode are written by the compiler from the class's fields, and under Node the types are erased"
446
+ "nish/json-typed: jsonDecode, jsonDecodeUnion and jsonEncode are written by the compiler from the class's fields, and under Node the types are erased"
380
447
 
381
448
  /**
382
449
  * A JSON number kept as the text it was written in, so that no digit is lost:
@@ -537,6 +604,20 @@ export class JsonDecoder {
537
604
  * ended, or a value `takeNull` found was not `null`.
538
605
  */
539
606
  private held: boolean = false
607
+ /** The `{` of the union object `unionTag` read ahead in, or `-1` when its tag was the first key. */
608
+ private unionStart: i32 = -1
609
+ /**
610
+ * The bytes this decoding has read twice: for each tagged union whose tag
611
+ * was not its first key, those from its `{` to the end of its tag, which
612
+ * the decoder read ahead over and then reads again as the variant's
613
+ * fields. A byte is read again once for each union object it is inside,
614
+ * so this is at most `maxDepth` times the input's length
615
+ * (docs/security/json.md, JSON-17), and it stops at `i32`'s largest
616
+ * value, 2147483647, which only raised limits reach; `reset` clears it.
617
+ * It counts the spans `enterUnion` reads again, not the keys `unionTag`
618
+ * steps over to find a tag.
619
+ */
620
+ unionReread: i32 = 0
540
621
 
541
622
  /**
542
623
  * A decoder over `src[off, off + len)`, with no error and no map key taken.
@@ -565,6 +646,8 @@ export class JsonDecoder {
565
646
  this.errorAt = -1
566
647
  this.held = false
567
648
  this.mapKeys = 0
649
+ this.unionStart = -1
650
+ this.unionReread = 0
568
651
  }
569
652
 
570
653
  /**
@@ -772,6 +855,111 @@ export class JsonDecoder {
772
855
  }
773
856
  }
774
857
 
858
+ /**
859
+ * Opens a tagged union's object and reads ahead to its tag, the key `key`,
860
+ * stepping over the values of the keys before it, and leaves the tag's
861
+ * string as the current token for `keyLength`, `keyByte` and `keyIs`.
862
+ * When the tag was not the first key, `enterUnion` goes back to the
863
+ * object's first key. A missing tag, or one that is not a string, is
864
+ * `JSON_DECODE_TAG`; any other value than an object is `JSON_DECODE_TYPE`.
865
+ *
866
+ * @param key The tag's key on the wire.
867
+ * @returns `true` at the tag's string; `false` after any error.
868
+ *
869
+ * @internal Called by name by the decoder the compiler writes for a union,
870
+ * src/emit-json.ts.
871
+ */
872
+ unionTag(key: string): boolean {
873
+ if (!this.beginObject()) {
874
+ return false
875
+ }
876
+ const tok: JsonTokenizer = this.tok
877
+ const start: i32 = tok.tokStart
878
+ let first: boolean = true
879
+ while (this.nextField()) {
880
+ if (tok.keyEquals(key)) {
881
+ const k: i32 = tok.next()
882
+ if (k < 0) {
883
+ this.fail(k, tok.errorAt)
884
+ return false
885
+ }
886
+ if (k !== JSON_TOK_STRING) {
887
+ this.fail(JSON_DECODE_TAG, tok.tokStart)
888
+ return false
889
+ }
890
+ this.unionStart = first ? -1 : start
891
+ return true
892
+ }
893
+ first = false
894
+ const k: i32 = tok.skipValue()
895
+ if (k < 0) {
896
+ this.fail(k, tok.errorAt)
897
+ return false
898
+ }
899
+ }
900
+ this.fail(JSON_DECODE_TAG, start)
901
+ return false
902
+ }
903
+
904
+ /**
905
+ * Records `JSON_DECODE_TAG` at the current string, a tag no variant of the
906
+ * union gives.
907
+ *
908
+ * @internal Called by name by the decoder the compiler writes for a union,
909
+ * src/emit-json.ts.
910
+ */
911
+ unknownTag(): void {
912
+ this.unionStart = -1
913
+ this.fail(JSON_DECODE_TAG, this.tok.tokStart)
914
+ }
915
+
916
+ /**
917
+ * Readies the object `unionTag` read the tag of for its variant's fields:
918
+ * when the tag was the first key, the next key is the one after it; when it
919
+ * was not, the object starts over from its first key, and the tag is read
920
+ * again as a field.
921
+ *
922
+ * @returns `true` when the tag is already read; `false` when it is still to come.
923
+ *
924
+ * @internal Called by name by the decoder the compiler writes for a union,
925
+ * src/emit-json.ts.
926
+ */
927
+ enterUnion(): boolean {
928
+ const start: i32 = this.unionStart
929
+ if (start < 0) {
930
+ return true
931
+ }
932
+ this.unionStart = -1
933
+ // Held at `i32`'s largest value, where raised limits could carry a sum
934
+ // past it: nothing an input holds may panic.
935
+ const span: i32 = this.tok.tokEnd - start
936
+ this.unionReread = span > 2147483647 - this.unionReread ? 2147483647 : this.unionReread + span
937
+ this.tok.rewindObject(start)
938
+ return false
939
+ }
940
+
941
+ /**
942
+ * Reads a variant's tag field: its value must be the string `name`, and
943
+ * anything else is `JSON_DECODE_TAG` at the value.
944
+ *
945
+ * @param name The variant's tag on the wire.
946
+ *
947
+ * @internal Called by name by the decoder the compiler writes for
948
+ * `jsonDecode`, src/emit-json.ts.
949
+ */
950
+ tagValue(name: string): void {
951
+ const k: i32 = this.take()
952
+ if (k === JSON_TOK_STRING) {
953
+ if (!this.tok.keyEquals(name)) {
954
+ this.fail(JSON_DECODE_TAG, this.tok.tokStart)
955
+ }
956
+ return
957
+ }
958
+ if (k >= 0) {
959
+ this.fail(JSON_DECODE_TAG, this.tok.tokStart)
960
+ }
961
+ }
962
+
775
963
  /**
776
964
  * Records `JSON_DECODE_DUPLICATE` at the current key, which the object
777
965
  * already gave.
@@ -1439,6 +1627,27 @@ export const jsonDecode = <T>(_d: JsonDecoder, _out: T): i32 => {
1439
1627
  panic(JSON_TYPED_ERASED)
1440
1628
  }
1441
1629
 
1630
+ /**
1631
+ * Decodes the JSON text `d` reads into a tagged union, `T`: the object's tag
1632
+ * picks the variant. When it is `prev`'s, `prev` is decoded into and
1633
+ * returned, its fields, nested objects and arrays reused; otherwise a new
1634
+ * object of that variant is made with its constructor of no parameters and
1635
+ * returned. The tag may be any key of the object; it is cheapest first. The
1636
+ * compiler writes the code from the union's variants at every call, and `T`
1637
+ * is never written at the call; under Node this body ends the program with a
1638
+ * panic, because the types are erased.
1639
+ *
1640
+ * @param _d The decoder over the input; its `failed` and `errorAt` say what
1641
+ * went wrong, and `reset` starts it over.
1642
+ * @param _prev The value the union holds now, reused when the tag names its variant.
1643
+ * @returns The decoded value; on any failure `prev`, perhaps partly
1644
+ * overwritten, with `d.failed` set to the first error's code, such as
1645
+ * `JSON_DECODE_TAG`.
1646
+ */
1647
+ export const jsonDecodeUnion = <T>(_d: JsonDecoder, _prev: T): T => {
1648
+ panic(JSON_TYPED_ERASED)
1649
+ }
1650
+
1442
1651
  /**
1443
1652
  * Writes `value` to `w` as one JSON object, its fields in declaration order,
1444
1653
  * the text `JSON.stringify` writes for it, in the writer's modes. The compiler
@@ -237,9 +237,15 @@ export class HttpRequest {
237
237
  targetEnd: i32 = 0
238
238
  /**
239
239
  * Where the path ends: the target's first `?`, or its end.
240
- * @internal Set by `HttpHandler` in this module when it copies the head, and read by `pathIs` and `queryIndex`.
240
+ * @internal Set by `HttpHandler` in this module from the router's `pathEnd` once it has routed the request,
241
+ * so the path is scanned once; copied by std/net/serve.ts with the head, and read by `pathIs` and `queryIndex`.
241
242
  */
242
243
  pathEnd: i32 = 0
244
+ /**
245
+ * How many bytes of `head` are this request's head: every span lies inside `head[0 .. headLength)`.
246
+ * @internal Set by `HttpHandler` in this module when it copies the head, and read by std/net/serve.ts to copy a request.
247
+ */
248
+ headLength: i32 = 0
243
249
  /**
244
250
  * How many fields `spans` describes.
245
251
  * @internal Set by `HttpHandler` in this module when it copies the head, and read by `header`.
@@ -488,6 +494,10 @@ export class HttpHandler {
488
494
  private slotGen: i32[]
489
495
  private current: i32[]
490
496
  private open: boolean[]
497
+ /** Whether a slot is in `owed`: an answer's send was put off for the request queued behind it. */
498
+ private owing: boolean[]
499
+ /** The slots whose send `flush` still owes, `owedCount` of them. */
500
+ private owed: i32[]
491
501
  /** `pollWait`'s output. */
492
502
  private readyFds: i32[]
493
503
  /** Per watched id: whether its descriptor was ready in the last `wait`. */
@@ -535,9 +545,13 @@ export class HttpHandler {
535
545
  loop: i32 = 0
536
546
  private queueStart: i32 = 0
537
547
  private queueCount: i32 = 0
548
+ private owedCount: i32 = 0
549
+ private sent: i64 = 0
538
550
  private outputSize: i32 = 0
539
551
  /** Set by `drain`: accept nothing more and close each connection once it is idle. */
540
552
  private draining: boolean = false
553
+ /** Set by `deferSends`: a send may wait for `flush`. Off, every answer is sent as it ends. */
554
+ private deferring: boolean = false
541
555
  /** Whether `json` gave out the writer for a value `sendJson` has not yet sent. */
542
556
  private jsonBegun: boolean = false
543
557
 
@@ -570,6 +584,8 @@ export class HttpHandler {
570
584
  this.slotGen = new Array<i32>(limits.slots)
571
585
  this.current = new Array<i32>(limits.slots)
572
586
  this.open = new Array<boolean>(limits.slots)
587
+ this.owing = new Array<boolean>(limits.slots)
588
+ this.owed = new Array<i32>(limits.slots)
573
589
  for (let s: i32 = 0; s < limits.slots; s++) {
574
590
  this.current[s] = -1
575
591
  }
@@ -631,6 +647,7 @@ export class HttpHandler {
631
647
  * @returns how many whole requests are queued for `take` after this turn
632
648
  */
633
649
  wait(timeoutMs: i32): i32 {
650
+ this.flush()
634
651
  for (let id: i32 = 0; id < HANDLER_MAX_WATCHED; id++) {
635
652
  this.watchedFired[id] = false
636
653
  }
@@ -648,6 +665,12 @@ export class HttpHandler {
648
665
  timeout = rest
649
666
  }
650
667
  }
668
+ if (this.deferring && this.queueCount > 0) {
669
+ // A send `flush` made let a parked request in: it is ready now. Only
670
+ // owed sends can do that; without `deferSends` a request left queued
671
+ // is the program's to take, and the turn blocks as it always has.
672
+ timeout = 0
673
+ }
651
674
  const n: i32 = pollWait(this.loop, this.readyFds, timeout)
652
675
  const now: i64 = monotonicNanos()
653
676
  this.turnAt = now
@@ -679,6 +702,17 @@ export class HttpHandler {
679
702
  return this.queueCount
680
703
  }
681
704
 
705
+ /**
706
+ * Lets the handler put a connection's send off until `flush`, so the
707
+ * answers to a pipelined burst go out in one write. Off by default, so an
708
+ * answer is sent as it ends. A program that turns it on calls `flush` (or
709
+ * `wait`, which flushes) after each turn of answers, before it blocks;
710
+ * `nish/net/serve` does.
711
+ */
712
+ deferSends(): void {
713
+ this.deferring = true
714
+ }
715
+
682
716
  /**
683
717
  * Begins a graceful stop: the handler accepts no more connections, closes
684
718
  * each idle one now, and closes each other one once the request on it is
@@ -732,9 +766,36 @@ export class HttpHandler {
732
766
  }
733
767
  }
734
768
 
769
+ /**
770
+ * Sends every answer whose send was put off, so the connection's answers to
771
+ * a pipelined burst go out in one write. `wait` calls it before it blocks; a
772
+ * program that blocks elsewhere, as `nish/net/serve` does, calls it first.
773
+ */
774
+ flush(): void {
775
+ const n: i32 = this.owedCount
776
+ this.owedCount = 0
777
+ for (let k: i32 = 0; k < n; k++) {
778
+ const slot: i32 = this.owed[k]
779
+ this.owing[slot] = false
780
+ if (this.open[slot] && this.server.holds(slot)) {
781
+ this.settle(slot, this.server.connection(slot))
782
+ }
783
+ }
784
+ }
785
+
786
+ /**
787
+ * How many times the handler handed a connection's waiting output to its
788
+ * socket: one per connection per pass, however many answers it holds.
789
+ * @returns the count of sends since the handler was made, each one write or a few for a partial one
790
+ */
791
+ sends(): i64 {
792
+ return this.sent
793
+ }
794
+
735
795
  /**
736
796
  * Takes `slot`'s events until it needs the socket again, then sends what it
737
- * holds and re-arms it, or closes it once it is over.
797
+ * holds and re-arms it, or closes it once it is over. While `owable` allows,
798
+ * the send waits for `flush`, so the answers behind this one go out with it.
738
799
  */
739
800
  private drive(slot: i32): void {
740
801
  const conn: Http1Connection = this.server.connection(slot)
@@ -755,7 +816,46 @@ export class HttpHandler {
755
816
  // The carrier has written its refusal and ends the connection; a
756
817
  // request it was reading is nobody's.
757
818
  this.releaseReading(slot)
819
+ } else if (this.owable(slot, conn)) {
820
+ if (!this.owing[slot]) {
821
+ this.owing[slot] = true
822
+ this.owed[this.owedCount] = slot
823
+ this.owedCount += 1
824
+ }
825
+ return
826
+ }
827
+ this.settle(slot, conn)
828
+ }
829
+
830
+ /**
831
+ * Whether `slot`'s send can wait for `flush`: `deferSends` turned that on, it has output to send, the
832
+ * output is still roomy, so more answers fit behind it, and no request on
833
+ * it is parked waiting for the room a send makes. A connection with nothing
834
+ * to send is settled at once, so a hang-up closes in the pass that reads it.
835
+ * Nor does a held write wait: its `H1_WRITE` comes only from `next`, so a
836
+ * send put off until the peer has read would empty the output, arm the slot
837
+ * for reading alone, and leave the rest of the response unsent.
838
+ * `flush` runs before every poll, so a send put off here goes out before
839
+ * the handler waits.
840
+ */
841
+ private owable(slot: i32, conn: Http1Connection): boolean {
842
+ const at: i32 = this.current[slot]
843
+ return (
844
+ this.deferring &&
845
+ !this.draining &&
846
+ conn.wantsWrite() &&
847
+ !conn.writeHeld &&
848
+ this.roomy(conn) &&
849
+ (at < 0 || this.requests[at].state !== HANDLER_PARKED)
850
+ )
851
+ }
852
+
853
+ /** Sends what `slot` holds and re-arms it, or closes it once it is over; enqueues a parked request once there is room. */
854
+ private settle(slot: i32, conn: Http1Connection): void {
855
+ if (conn.wantsWrite()) {
856
+ this.sent += 1
758
857
  }
858
+ // `flush` arms a held write for writing even once its send emptied the output.
759
859
  const wants: i32 = this.server.flush(slot)
760
860
  if ((wants & H1_DONE) !== 0) {
761
861
  this.closeSlot(slot)
@@ -792,23 +892,18 @@ export class HttpHandler {
792
892
  r.head = new Array<u8>(handlerGrown(toI32(r.head.length), length))
793
893
  }
794
894
  copyBytes(r.head, HANDLER_ZERO, p.head, HANDLER_ZERO, length)
795
- const spanCount: i32 = 4 * p.headerCount
796
- if (toI32(r.spans.length) < spanCount) {
797
- r.spans = new Array<i32>(handlerGrown(toI32(r.spans.length), spanCount))
798
- }
799
- for (let k: i32 = 0; k < spanCount; k++) {
800
- r.spans[k] = p.spans[k]
895
+ // The parser's spans are copied whole, as one `set`: only the first
896
+ // `4 * headerCount` are this head's, and only those are ever read.
897
+ if (toI32(r.spans.length) < toI32(p.spans.length)) {
898
+ r.spans = new Array<i32>(handlerGrown(toI32(r.spans.length), toI32(p.spans.length)))
801
899
  }
900
+ r.spans.set(p.spans)
901
+ r.headLength = length
802
902
  r.headerCount = p.headerCount
803
903
  r.methodStart = p.methodStart
804
904
  r.methodEnd = p.methodEnd
805
905
  r.targetStart = p.targetStart
806
906
  r.targetEnd = p.targetEnd
807
- let pathEnd: i32 = r.targetStart
808
- while (pathEnd < r.targetEnd && toI32(r.head[pathEnd]) !== 63) {
809
- pathEnd += 1
810
- }
811
- r.pathEnd = pathEnd
812
907
  r.bodyLength = 0
813
908
  r.slot = slot
814
909
  r.gen = this.slotGen[slot]
@@ -817,6 +912,8 @@ export class HttpHandler {
817
912
  r.pendingStart = 0
818
913
  r.pendingEnd = 0
819
914
  this.route(r)
915
+ // The router found where the path ends, before any query, as it matched.
916
+ r.pathEnd = this.router.pathEnd
820
917
  this.current[slot] = r.index
821
918
  }
822
919
 
@@ -1155,6 +1252,21 @@ export class HttpHandler {
1155
1252
  * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the connection closed first
1156
1253
  */
1157
1254
  write(r: HttpRequest, buf: u8[], off: i32, len: i32): i32 {
1255
+ const put: i32 = this.put(r, buf, off, len)
1256
+ if (put === HANDLER_SENT) {
1257
+ this.drive(r.slot)
1258
+ }
1259
+ return put
1260
+ }
1261
+
1262
+ /**
1263
+ * `write` without its pass over the connection: the bytes are in the
1264
+ * carrier's output or pending on the request, and nothing is sent or
1265
+ * re-armed. The caller owes the slot a `drive` — `write` gives it at once,
1266
+ * `sendFields` leaves it to the `end` that follows, so a whole answer takes
1267
+ * one pass instead of two.
1268
+ */
1269
+ private put(r: HttpRequest, buf: u8[], off: i32, len: i32): i32 {
1158
1270
  if (r.state !== HANDLER_STREAMING) {
1159
1271
  panic(`HttpHandler.write: the response is not started (state ${r.state})`)
1160
1272
  }
@@ -1187,7 +1299,6 @@ export class HttpHandler {
1187
1299
  if (taken < len) {
1188
1300
  this.keep(r, buf, off + taken, len - taken)
1189
1301
  }
1190
- this.drive(r.slot)
1191
1302
  return HANDLER_SENT
1192
1303
  }
1193
1304
 
@@ -1213,7 +1324,9 @@ export class HttpHandler {
1213
1324
  /**
1214
1325
  * Ends `r`'s response. `r` is the handler's again: it goes back once the
1215
1326
  * carrier has taken every byte, and the connection's next request is read.
1216
- * Answers `HANDLER_SENT` or `HANDLER_DROPPED`.
1327
+ * Answers `HANDLER_SENT` or `HANDLER_DROPPED`. After `deferSends` the send
1328
+ * may be put off so a pipelined burst goes out in one write: call `wait` or
1329
+ * `flush` after answering, or it waits for the next of them.
1217
1330
  * @param r a request whose response `start` began; the handler's again after this call
1218
1331
  * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the connection closed first
1219
1332
  */
@@ -1281,7 +1394,8 @@ export class HttpHandler {
1281
1394
  return HANDLER_DROPPED
1282
1395
  }
1283
1396
  if (len > 0 && status !== 204 && status !== 304) {
1284
- this.write(r, body, off, len)
1397
+ // No pass between the body and the end: `end` drives the slot once.
1398
+ this.put(r, body, off, len)
1285
1399
  }
1286
1400
  return this.end(r)
1287
1401
  }