http.bend

bend-kit-http@0.30.0.0 · 6,645 lines · 0 definitions

1# HTTP/1.1 and HTTP/2 client, with an HTTP/1.1 server. Source: https://github.com/paymog/bend-kit/tree/main/http
2import Base
3import bend-kit-http@0.30.0.0/admission.bend as Admission
4import bend-kit-http@0.30.0.0/completion.bend as Completion
5# By hash: bend-kit-url@0.4.1.0, -encoding@0.3.0.0, -json@0.5.0.1, -bytes@0.3.0.0, -zlib@0.2.0.0.
6import bend-kit-wire@0.4.5.0/wire.bend as Wire
7import bend-kit-http2@0.1.2.0/http2.bend as H2
8import bend-kit-http2@0.1.2.0/hpack.bend as Hpack
9import bend-kit-bytes@0.3.1.0/bytes.bend as HBytes
10import bend-kit-time@0.1.0.0/time.bend as Time
11import bend-kit-int@0.2.0.0/int.bend as Int
12import bend-kit-concurrency@0.1.0.0/concurrency.bend as Conc
13import bend-kit-url@0.4.1.0/url.bend as Url
14import bend-kit-encoding@0.3.0.0/encoding.bend as Enc
15import bend-kit-json@0.5.0.1/json.bend as Json
16import bend-kit-bytes@0.3.0.0/bytes.bend as Bytes
17import bend-kit-dns@0.5.0.0/dns.bend as Dns
18import bend-kit-zlib@0.2.0.0/zlib.bend as Zlib
19
20# HTTP/1.1 codec and client (RFC 9112) for http:// and https:// (OpenSSL 3 at run time).
21# parse: start-line → field lines → blank → body length (§6.3); chunked (§7.1).
22# Bodies are Bytes. The String parsers below are the spec: one Char per octet.
23# fetch reads until frame() says the response is whole. It returns Result, not Maybe.
24# Build with -o for big bodies: the `bend file.bend` runner overflows on ~30 KB strings; native binaries do not.
25#   import bend-kit-http@0.22.0.0/http.bend as Http
26
27type Req is Type:
28  Req{method: String, path: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes}
29
30type Res is Type:
31  Res{status: U32, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes}
32
33# A typed Data payload can be captured in receipt; the response remains affine.
34type Reply is Type:
35  Reply{response: Res, receipt: Completion.Receipt}
36
37def reply.complete(~D: Data, ~done: Completion.Completion<D> -> IO(Unit), payload: D, response: Res) -> Reply:
38  Reply{response, Completion.receipt(~D, ~done, payload)}
39
40
41# The body type and its conversions, so a caller needs no bytes import.
42def Body() -> Type:
43  Bytes.Bytes
44
45# A byte string (one Char per octet) to a body, and back.
46def from_string(+s: String) -> Bytes.Bytes:
47  Bytes.from_string(s)
48
49def to_string(b: Bytes.Bytes) -> String:
50  Bytes.to_string(b)
51
52def length(b: Bytes.Bytes) -> Bytes.Bytes & U32:
53  Bytes.length(b)
54
55# Why fetch failed. Wire errors keep the errno and the text the effect already had.
56# ponytail: 60 and 110 are ETIMEDOUT on macOS and Linux. Windows is out of scope.
57type Err is Data:
58  ErrUrl{}
59  ErrDns{}
60  ErrConnect{code: U32, why: String}
61  ErrTls{code: U32, why: String}
62  ErrRead{code: U32, why: String}
63  ErrWrite{code: U32, why: String}
64  ErrTimeout{}
65  ErrRedirect{}
66  ErrBad{}
67
68def err.late(+code: U32) -> Bool:
69  Bool.or(U32.is_eq(code, 60), U32.is_eq(code, 110))
70
71def err.pick(e: Err, late: Bool) -> Err:
72  match late:
73    case True{}:
74      ErrTimeout{}
75    case False{}:
76      e
77
78def err.or_late(code: U32, e: Err) -> Err:
79  err.pick(e, err.late(code))
80
81type Fields is Data:
82  FieldsBad{}
83  FieldsOk{m: Map<&2, List<&2, String>>}
84
85# One list per field name, in arrival order. header() is the first value.
86# Set-Cookie is never joined. Encode writes one line per value.
87def empty() -> Map<&2, List<&2, String>>:
88  Map.new(&2, List<&2, String>)
89
90def fields.of(r: Map<&2, List<&2, String>> & List<&2, String>) -> List<&2, String>:
91  (h, xs) = r
92  xs
93
94def fields(+h: Map<&2, List<&2, String>>, k: String) -> List<&2, String>:
95  fields.of(Map.get(List<&2, String>, Nil{}, h, k))
96
97def header.first(xs: List<&2, String>) -> String:
98  match xs:
99    case Nil{}:
100      ""
101    case Con{v, t}:
102      v
103
104def header(+h: Map<&2, List<&2, String>>, k: String) -> String:
105  header.first(fields(h, k))
106
107def field.last(xs: List<&2, String>) -> String:
108  match xs:
109    case Nil{}:
110      ""
111    case Con{v, Nil{}}:
112      v
113    case Con{v, t}:
114      field.last(t)
115
116# Transfer-Encoding is a list; chunked, when present, is the last coding.
117def header.last(+h: Map<&2, List<&2, String>>, k: String) -> String:
118  field.last(fields(h, k))
119
120def snoc(xs: List<&2, String>, v: String) -> List<&2, String>:
121  match xs:
122    case Nil{}:
123      [v]
124    case Con{h, t}:
125      Con{h, snoc(t, v)}
126
127def set(m: Map<&2, List<&2, String>>, k: String, v: String) -> Map<&2, List<&2, String>>:
128  Map.set(&2, List<&2, String>, m, k, [v])
129
130def add(+m: Map<&2, List<&2, String>>, +k: String, v: String) -> Map<&2, List<&2, String>>:
131  Map.set(&2, List<&2, String>, m, k, snoc(fields(m, k), v))
132
133def sanitize.cons(ch: Char, rest: String, drop: Bool) -> String:
134  match drop:
135    case True{}:
136      rest
137    case False{}:
138      SCon{ch, rest}
139
140def sanitize(s: String) -> String:
141  match s:
142    case SNil{}:
143      SNil{}
144    case SCon{Chr{+c}, t}:
145      sanitize.cons(Chr{c}, sanitize(t), Bool.or(U32.is_eq(c, 13), U32.is_eq(c, 10)))
146
147def drop_cr.last.if(cr: Bool, c: U32) -> String:
148  match cr:
149    case True{}:
150      SNil{}
151    case False{}:
152      SCon{Chr{c}, SNil{}}
153
154def drop_cr.last(+c: U32) -> String:
155  drop_cr.last.if(U32.is_eq(c, 13), c)
156
157# prev is the char before s; it is kept unless it is a final CR.
158def drop_cr.go(s: String, prev: U32) -> String:
159  match s:
160    case SNil{}:
161      drop_cr.last(prev)
162    case SCon{Chr{c}, t}:
163      SCon{Chr{prev}, drop_cr.go(t, c)}
164
165def drop_cr(s: String) -> String:
166  match s:
167    case SNil{}:
168      SNil{}
169    case SCon{Chr{c}, t}:
170      drop_cr.go(t, c)
171
172# w holds the last four octets; a char past 255 clears it.
173def blank_end.go(s: String, w: U32) -> Bool:
174  match s:
175    case SNil{}:
176      U32.is_eq(w, 218762506)
177    case SCon{Chr{+c}, t}:
178      blank_end.go(t, Bool.pick(U32, U32.is_lt(c, 256), (w * 256 + c : U32), 0))
179
180# String.ends_with(s, "\r\n\r\n") in one pass, with no reversed copy.
181def blank_end(s: String) -> Bool:
182  blank_end.go(s, 0)
183
184def trim_end.cons(h: Char, r: String, space: Bool) -> String:
185  match r:
186    case SNil{}:
187      match space:
188        case True{}:
189          SNil{}
190        case False{}:
191          SCon{h, SNil{}}
192    case SCon{a, t}:
193      SCon{h, SCon{a, t}}
194
195# String.trim_end without the two reversed copies.
196def trim_end(s: String) -> String:
197  match s:
198    case SNil{}:
199      SNil{}
200    case SCon{+h, t}:
201      trim_end.cons(h, trim_end(t), Char.is_space(h))
202
203def trim(s: String) -> String:
204  trim_end(String.trim_start(s))
205
206# Bool.pick evaluates both arms; a split that recursed inside it would reverse acc at every byte.
207def take.cut(acc: String, rest: String) -> String & String:
208  (String.reverse(String.drop(acc, 1n)), rest)
209
210# hit: the last char pushed onto acc was the stop char.
211def take_sp.go(s: String, acc: String, hit: Bool) -> String & String:
212  match s:
213    case SNil{}:
214      match hit:
215        case True{}:
216          take.cut(acc, SNil{})
217        case False{}:
218          (String.reverse(acc), SNil{})
219    case SCon{Chr{+c}, t}:
220      match hit:
221        case True{}:
222          take.cut(acc, SCon{Chr{c}, t})
223        case False{}:
224          take_sp.go(t, SCon{Chr{c}, acc}, U32.is_eq(c, 32))
225
226def take_sp(s: String) -> String & String:
227  take_sp.go(s, SNil{}, False{})
228
229def start_line.ver(m: String, pv: String & String) -> String & String & String:
230  (p, v) = pv
231  (m, p, drop_cr(v))
232
233def start_line.rest(mr: String & String) -> String & String & String:
234  (m, r) = mr
235  start_line.ver(m, take_sp(r))
236
237def start_line(s: String) -> String & String & String:
238  start_line.rest(take_sp(s))
239
240def split_at_blank.go(s: String, e: Bool, w: U32, acc: String) -> String & String:
241  match s:
242    case SNil{}:
243      (String.reverse(acc), SNil{})
244    case SCon{Chr{+a}, t}:
245      match e:
246        case True{}:
247          (String.reverse(acc), SCon{Chr{a}, t})
248        case False{}:
249          +w2 = (w * 256 + a : U32)
250          split_at_blank.go(t, U32.is_eq(w2, 218762506), w2, SCon{Chr{a}, acc})
251
252# split_at_blank, plus whether the head ends in the blank line.
253def split_at_blank.flag.go(+raw: String, s: String, off: Nat, w: U32, e: Bool) -> String & String & Bool:
254  match s:
255    case SNil{}:
256      (String.take(raw, off), SNil{}, e)
257    case SCon{Chr{+a}, t}:
258      match e:
259        case True{}:
260          (String.take(raw, off), SCon{Chr{a}, t}, True{})
261        case False{}:
262          +w2 = (w * 256 + a : U32)
263          +off1 = (1n + off : Nat)
264          split_at_blank.flag.go(raw, t, off1, w2, U32.is_eq(w2, 218762506))
265
266def split_at_blank.pair(r: String & String & Bool) -> String & String:
267  (head, rest, whole) = r
268  (head, rest)
269
270def split_at_blank(+s: String) -> String & String:
271  split_at_blank.pair(split_at_blank.flag.go(s, s, 0n, 0, False{}))
272
273def split_colon.go(s: String, acc: String, hit: Bool) -> String & String:
274  match s:
275    case SNil{}:
276      match hit:
277        case True{}:
278          take.cut(acc, SNil{})
279        case False{}:
280          (String.reverse(acc), SNil{})
281    case SCon{Chr{+c}, t}:
282      match hit:
283        case True{}:
284          take.cut(acc, SCon{Chr{c}, t})
285        case False{}:
286          split_colon.go(t, SCon{Char.to_lower(Chr{c}), acc}, U32.is_eq(c, 58))
287
288def split_colon(+s: String) -> String & String:
289  split_colon.go(s, SNil{}, False{})
290
291def has_header.of(r: Map<&2, List<&2, String>> & Bool) -> Bool:
292  (h, b) = r
293  b
294
295def has_header(+h: Map<&2, List<&2, String>>, k: String) -> Bool:
296  has_header.of(Map.has(&2, List<&2, String>, h, k))
297
298def folded(+line: String) -> Bool:
299  Bool.or(String.starts_with(line, " "), String.starts_with(line, "\t"))
300
301def tracked(+k: String) -> Bool:
302  Bool.or(String.eq(k, "host"), String.eq(k, "content-length"))
303
304def fields_put.dup(m: Map<&2, List<&2, String>>, k: String, v: String, bad: Bool) -> Fields:
305  match bad:
306    case True{}:
307      FieldsBad{}
308    case False{}:
309      FieldsOk{add(m, k, v)}
310
311def fields_put.tracked(+m: Map<&2, List<&2, String>>, +k: String, v: String, t: Bool) -> Fields:
312  match t:
313    case True{}:
314      fields_put.dup(m, k, v, has_header(m, k))
315    case False{}:
316      FieldsOk{add(m, k, v)}
317
318def fields_put.key(+m: Map<&2, List<&2, String>>, +k: String, v: String) -> Fields:
319  fields_put.tracked(m, k, v, tracked(k))
320
321def fields_put.kv(m: Map<&2, List<&2, String>>, kv: String & String) -> Fields:
322  (k, v) = kv
323  fields_put.key(m, k, trim(v))
324
325def fields_put.fold(m: Map<&2, List<&2, String>>, line: String, fold: Bool) -> Fields:
326  match fold:
327    case True{}:
328      FieldsBad{}
329    case False{}:
330      fields_put.kv(m, split_colon(line))
331
332def fields_put.empty(m: Map<&2, List<&2, String>>, +line: String, e: Bool) -> Fields:
333  match e:
334    case True{}:
335      FieldsOk{m}
336    case False{}:
337      fields_put.fold(m, line, folded(line))
338
339def fields_put.ok(m: Map<&2, List<&2, String>>, +line: String) -> Fields:
340  fields_put.empty(m, line, String.is_empty(line))
341
342def fields_put(acc: Fields, line: String) -> Fields:
343  match acc:
344    case FieldsBad{}:
345      FieldsBad{}
346    case FieldsOk{m}:
347      fields_put.ok(m, line)
348
349def parse.headers.done(acc: Fields) -> Maybe<&2, Map<&2, List<&2, String>>>:
350  match acc:
351    case FieldsBad{}:
352      None{}
353    case FieldsOk{m}:
354      Some{m}
355
356
357def parse.headers.scan.line(acc: String, fields: Fields) -> Fields:
358  match acc:
359    case SCon{Chr{13}, t}:
360      fields_put(fields, String.reverse(t))
361    case other:
362      fields_put(fields, String.reverse(other))
363
364def parse.headers.scan(s: String, acc: String, fields: Fields) -> Fields:
365  match s:
366    case SNil{}:
367      parse.headers.scan.line(acc, fields)
368    case SCon{Chr{10}, t}:
369      parse.headers.scan(t, SNil{}, parse.headers.scan.line(acc, fields))
370    case SCon{c, t}:
371      parse.headers.scan(t, SCon{c, acc}, fields)
372
373def parse.headers.raw(s: String) -> Maybe<&2, Map<&2, List<&2, String>>>:
374  parse.headers.done(parse.headers.scan(s, SNil{}, FieldsOk{empty()}))
375
376def parse.first(s: String, acc: String) -> String & String:
377  match s:
378    case SNil{}:
379      (String.reverse(acc), SNil{})
380    case SCon{Chr{10}, t}:
381      (String.reverse(acc), t)
382    case SCon{c, t}:
383      parse.first(t, SCon{c, acc})
384
385def parse_u32.digit(+c: U32) -> Bool:
386  Bool.and(U32.is_le(48, c), U32.is_le(c, 57))
387
388def parse_u32.add(acc: U32, c: U32) -> U32:
389  (acc * 10 + (c - 48 : U32) : U32)
390
391def parse_u32.done(acc: U32, bad: Bool) -> Maybe<&2, U32>:
392  match bad:
393    case True{}:
394      None{}
395    case False{}:
396      Some{acc}
397
398def parse_u32.go(s: String, acc: U32, bad: Bool) -> Maybe<&2, U32>:
399  match s:
400    case SNil{}:
401      parse_u32.done(acc, bad)
402    case SCon{Chr{+c}, t}:
403      parse_u32.go(t, parse_u32.add(acc, c), Bool.or(bad, Bool.not(parse_u32.digit(c))))
404
405def parse_u32(s: String) -> Maybe<&2, U32>:
406  match s:
407    case SNil{}:
408      None{}
409    case SCon{Chr{+c}, t}:
410      parse_u32.go(t, parse_u32.add(0, c), Bool.not(parse_u32.digit(c)))
411
412# More: a valid prefix. Bad: cannot become a body. Body: a whole chunked body.
413type Hold is Data:
414  HoldMore{}
415  HoldBad{}
416  HoldBody{b: String}
417  HoldUntil{b: String}
418
419def is_hex(+c: U32) -> Bool:
420  Bool.or(parse_u32.digit(c), Bool.or(Bool.and(U32.is_le(97, c), U32.is_le(c, 102)), Bool.and(U32.is_le(65, c), U32.is_le(c, 70))))
421
422def hexv(+c: U32) -> U32:
423  Bool.pick(U32, parse_u32.digit(c), (c - 48 : U32), Bool.pick(U32, U32.is_le(c, 70), (c - 55 : U32), (c - 87 : U32)))
424
425# A chunked body decoder that reads each byte once, so a body fed in pieces
426# costs O(bytes) in total. Tr{j}: j bytes of the closing CRLF CRLF matched.
427type Dc is Data:
428  DcSize{acc: U32, seen: Bool}
429  DcExt{n: U32}
430  DcSizeLf{n: U32}
431  DcData{k: U32}
432  DcDataCr{}
433  DcDataLf{}
434  DcTr{j: U32}
435  DcDone{}
436  DcBad{}
437
438# st: where the decoder is. racc: the body so far, reversed. rest: bytes after a Done body.
439type Dco is Data:
440  Dco{st: Dc, racc: String, rest: String}
441
442def dc.start() -> Dc:
443  DcSize{0, False{}}
444
445def dc.size.semi(+n: U32, semi: Bool) -> Dc:
446  match semi:
447    case True{}:
448      DcExt{n}
449    case False{}:
450      DcBad{}
451
452def dc.size.cr(+n: U32, +c: U32, cr: Bool) -> Dc:
453  match cr:
454    case True{}:
455      DcSizeLf{n}
456    case False{}:
457      dc.size.semi(n, U32.is_eq(c, 59))
458
459def dc.size.end(+n: U32, +c: U32, seen: Bool) -> Dc:
460  match seen:
461    case False{}:
462      DcBad{}
463    case True{}:
464      dc.size.cr(n, c, U32.is_eq(c, 13))
465
466# A size that would overflow 32 bits ends the digits, and size.end then refuses it.
467def dc.size(+acc: U32, seen: Bool, +c: U32, digit: Bool) -> Dc:
468  match digit:
469    case True{}:
470      DcSize{(acc * 16 + hexv(c) : U32), True{}}
471    case False{}:
472      dc.size.end(acc, c, seen)
473
474# RFC 9112 §7.1.1: recipients ignore unknown chunk extensions; a bare LF is not CRLF.
475def dc.ext.lf(+n: U32, lf: Bool) -> Dc:
476  match lf:
477    case True{}:
478      DcBad{}
479    case False{}:
480      DcExt{n}
481
482def dc.ext(+n: U32, +c: U32, cr: Bool) -> Dc:
483  match cr:
484    case True{}:
485      DcSizeLf{n}
486    case False{}:
487      dc.ext.lf(n, U32.is_eq(c, 10))
488
489def dc.sized(+n: U32, zero: Bool) -> Dc:
490  match zero:
491    case True{}:
492      DcTr{2}
493    case False{}:
494      DcData{n}
495
496def dc.size.lf(+n: U32, lf: Bool) -> Dc:
497  match lf:
498    case True{}:
499      dc.sized(n, U32.is_eq(n, 0))
500    case False{}:
501      DcBad{}
502
503# k data bytes are left and m of them were just read.
504def dc.data(+k: U32, +m: U32) -> Dc:
505  Bool.pick(Dc, U32.is_le(k, m), DcDataCr{}, DcData{(k - m : U32)})
506
507def dc.pick(ok: Bool, next: Dc) -> Dc:
508  match ok:
509    case True{}:
510      next
511    case False{}:
512      DcBad{}
513
514# ponytail: trailer fields are dropped unparsed (§7.1.2 allows discarding)
515def dc.tr.hit(+j: U32) -> Dc:
516  Bool.pick(Dc, U32.is_eq(j, 3), DcDone{}, DcTr{(j + 1 : U32)})
517
518def dc.tr(+j: U32, +c: U32, hit: Bool) -> Dc:
519  match hit:
520    case True{}:
521      dc.tr.hit(j)
522    case False{}:
523      Bool.pick(Dc, U32.is_eq(c, 13), DcTr{1}, DcTr{0})
524
525def dc.tr.want(+j: U32) -> U32:
526  Bool.pick(U32, U32.is_eq(U32.mod(j, 2), 0), 13, 10)
527
528def dc.byte(h: Char) -> U32:
529  Chr{c} = h
530  c
531
532# One byte c. Done and Bad never look at it, and a data byte is not inspected.
533def dc.step(st: Dc, +c: U32) -> Dc:
534  match st:
535    case DcBad{}:
536      DcBad{}
537    case DcSize{+acc, seen}:
538      dc.size(acc, seen, c, Bool.and(is_hex(c), U32.is_le(acc, 268435455)))
539    case DcExt{+n}:
540      dc.ext(n, c, U32.is_eq(c, 13))
541    case DcSizeLf{+n}:
542      dc.size.lf(n, U32.is_eq(c, 10))
543    case DcDataCr{}:
544      dc.pick(U32.is_eq(c, 13), DcDataLf{})
545    case DcDataLf{}:
546      dc.pick(U32.is_eq(c, 10), dc.start())
547    case DcTr{+j}:
548      dc.tr(j, c, U32.is_eq(c, dc.tr.want(j)))
549    case DcData{+k}:
550      dc.data(k, 1)
551    case DcDone{}:
552      DcDone{}
553
554def dc.live(st: Dc) -> Bool:
555  match st:
556    case DcDone{}:
557      False{}
558    case DcBad{}:
559      False{}
560    case DcSize{a, b}:
561      True{}
562    case DcExt{n}:
563      True{}
564    case DcSizeLf{n}:
565      True{}
566    case DcData{k}:
567      True{}
568    case DcDataCr{}:
569      True{}
570    case DcDataLf{}:
571      True{}
572    case DcTr{j}:
573      True{}
574
575def dc.feed(s: String, st: Dc, racc: String) -> Dco:
576  match s:
577    case SNil{}:
578      Dco{st, racc, ""}
579    case SCon{h, t}:
580      match st:
581        case DcBad{}:
582          Dco{DcBad{}, racc, ""}
583        case DcDone{}:
584          Dco{DcDone{}, racc, SCon{h, t}}
585        case DcData{+k}:
586          dc.feed(t, dc.data(k, 1), SCon{h, racc})
587        case DcSize{+acc, seen}:
588          dc.feed(t, dc.step(DcSize{acc, seen}, dc.byte(h)), racc)
589        case DcExt{+n}:
590          dc.feed(t, dc.step(DcExt{n}, dc.byte(h)), racc)
591        case DcSizeLf{+n}:
592          dc.feed(t, dc.step(DcSizeLf{n}, dc.byte(h)), racc)
593        case DcDataCr{}:
594          dc.feed(t, dc.step(DcDataCr{}, dc.byte(h)), racc)
595        case DcDataLf{}:
596          dc.feed(t, dc.step(DcDataLf{}, dc.byte(h)), racc)
597        case DcTr{+j}:
598          dc.feed(t, dc.step(DcTr{j}, dc.byte(h)), racc)
599
600def chunk.hold(o: Dco) -> Hold:
601  Dco{st, racc, rest} = o
602  match st:
603    case DcDone{}:
604      HoldBody{String.reverse(racc)}
605    case DcBad{}:
606      HoldBad{}
607    case DcSize{a, b}:
608      HoldMore{}
609    case DcExt{n}:
610      HoldMore{}
611    case DcSizeLf{n}:
612      HoldMore{}
613    case DcData{k}:
614      HoldMore{}
615    case DcDataCr{}:
616      HoldMore{}
617    case DcDataLf{}:
618      HoldMore{}
619    case DcTr{j}:
620      HoldMore{}
621
622def chunk.live(s: String) -> Hold:
623  chunk.hold(dc.feed(s, dc.start(), ""))
624
625def chunk.rest(o: Dco) -> Maybe<&2, String>:
626  Dco{st, racc, rest} = o
627  match st:
628    case DcDone{}:
629      Some{rest}
630    case DcBad{}:
631      None{}
632    case DcSize{a, b}:
633      None{}
634    case DcExt{n}:
635      None{}
636    case DcSizeLf{n}:
637      None{}
638    case DcData{k}:
639      None{}
640    case DcDataCr{}:
641      None{}
642    case DcDataLf{}:
643      None{}
644    case DcTr{j}:
645      None{}
646
647def chunk.suffix(s: String) -> Maybe<&2, String>:
648  chunk.rest(dc.feed(s, dc.start(), ""))
649
650def chunk.decode.hold(h: Hold) -> Maybe<&2, String>:
651  match h:
652    case HoldMore{}:
653      None{}
654    case HoldBad{}:
655      None{}
656    case HoldUntil{b}:
657      None{}
658    case HoldBody{b}:
659      Some{b}
660
661def chunk.decode(s: String) -> Maybe<&2, String>:
662  chunk.decode.hold(chunk.live(s))
663
664def bytes.snd(r: Bytes.Bytes & Bytes.Bytes) -> Bytes.Bytes:
665  (a, b) = r
666  b
667
668def found.at(+from: U32, m: Maybe<&2, U32>) -> Maybe<&2, U32>:
669  match m:
670    case None{}:
671      None{}
672    case Some{+j}:
673      Some{(from + j : U32)}
674
675# A chunked body decoded from piece[i..]: a data run is sliced whole, and every other byte steps dc.
676type Cs is Type:
677  Cs{piece: Bytes.Bytes, i: U32, st: Dc, parts: List<&1, Bytes.Bytes>}
678
679# st: where the decoder stopped. parts: the data so far, newest first. rest: the bytes after a Done body.
680type Ck is Type:
681  Ck{st: Dc, parts: List<&1, Bytes.Bytes>, rest: Bytes.Bytes}
682
683def ck.next(+len: U32, +i: U32, +st: Dc, piece: Bytes.Bytes, parts: List<&1, Bytes.Bytes>) -> Bool & Cs:
684  (Bool.and(U32.is_lt(i, len), dc.live(st)), Cs{piece, i, st, parts})
685
686def ck.data(+len: U32, +i: U32, +k: U32, +m: U32, parts: List<&1, Bytes.Bytes>, r: Bytes.Bytes & Bytes.Bytes) -> Bool & Cs:
687  (piece, run) = r
688  ck.next(len, (i + m : U32), dc.data(k, m), piece, Con{run, parts})
689
690def ck.byte(+len: U32, +i: U32, st: Dc, parts: List<&1, Bytes.Bytes>, r: Bytes.Bytes & Maybe<&2, U32>) -> Bool & Cs:
691  (piece, m) = r
692  match m:
693    case None{}:
694      ck.next(len, i, DcBad{}, piece, parts)
695    case Some{+c}:
696      ck.next(len, (i + 1 : U32), dc.step(st, c), piece, parts)
697
698def ck.step(+len: U32, cs: Cs) -> Bool & Cs:
699  Cs{piece, +i, st, parts} = cs
700  match st:
701    case DcData{+k}:
702      +m = U32.min(k, (len - i : U32))
703      ck.data(len, i, k, m, parts, Bytes.slice(piece, i, m))
704    case DcDone{}:
705      (False{}, Cs{piece, i, DcDone{}, parts})
706    case DcBad{}:
707      (False{}, Cs{piece, i, DcBad{}, parts})
708    case DcSize{+acc, seen}:
709      ck.byte(len, i, DcSize{acc, seen}, parts, Bytes.get(piece, i))
710    case DcExt{+n}:
711      ck.byte(len, i, DcExt{n}, parts, Bytes.get(piece, i))
712    case DcSizeLf{+n}:
713      ck.byte(len, i, DcSizeLf{n}, parts, Bytes.get(piece, i))
714    case DcDataCr{}:
715      ck.byte(len, i, DcDataCr{}, parts, Bytes.get(piece, i))
716    case DcDataLf{}:
717      ck.byte(len, i, DcDataLf{}, parts, Bytes.get(piece, i))
718    case DcTr{+j}:
719      ck.byte(len, i, DcTr{j}, parts, Bytes.get(piece, i))
720
721def ck.rest(st: Dc, parts: List<&1, Bytes.Bytes>, r: Bytes.Bytes & Bytes.Bytes) -> Ck:
722  (piece, rest) = r
723  Ck{st, parts, rest}
724
725def ck.end(+len: U32, cs: Cs) -> Ck:
726  Cs{piece, +i, st, parts} = cs
727  ck.rest(st, parts, Bytes.slice(piece, i, (len - i : U32)))
728
729# Each step reads at least one byte, so len steps are enough.
730def ck.feed(f: Nat, +len: U32, r: Bool & Cs) -> Ck:
731  match f:
732    case 0n:
733      (go, cs) = r
734      ck.end(len, cs)
735    case 1n+p:
736      (go, cs) = r
737      match go:
738        case False{}:
739          ck.end(len, cs)
740        case True{}:
741          ck.feed(p, len, ck.step(len, cs))
742
743def ck(piece: Bytes.Bytes, +st: Dc, parts: List<&1, Bytes.Bytes>) -> Ck:
744  Bytes.Bytes{+len, buf} = piece
745  ck.feed(U32.to_nat(len), len, ck.next(len, 0, st, Bytes.Bytes{len, buf}, parts))
746
747def parse.res.cl.have(+rest: String, +k: Nat, short: Bool) -> Hold:
748  match short:
749    case True{}:
750      HoldMore{}
751    case False{}:
752      HoldBody{String.take(rest, k)}
753
754def parse.res.cl.k(+rest: String, +k: Nat) -> Hold:
755  parse.res.cl.have(rest, k, Nat.is_lt(String.length(rest), k))
756
757def parse.res.cl.n(rest: String, n: Maybe<&2, U32>) -> Hold:
758  match n:
759    case None{}:
760      HoldBad{}
761    case Some{k}:
762      parse.res.cl.k(rest, U32.to_nat(k))
763
764def parse.body.cl(+h: Map<&2, List<&2, String>>, rest: String, hascl: Bool) -> Hold:
765  match hascl:
766    case False{}:
767      HoldBody{""}
768    case True{}:
769      parse.res.cl.n(rest, parse_u32(header(h, "content-length")))
770
771# RFC 9112 §6.3 (4): a request coding other than chunked cannot be framed.
772def parse.body.chunked.eq(rest: String, ok: Bool) -> Hold:
773  match ok:
774    case False{}:
775      HoldBad{}
776    case True{}:
777      chunk.live(rest)
778
779def parse.body.chunked.val(te: String, rest: String) -> Hold:
780  parse.body.chunked.eq(rest, String.eq(String.to_lower(te), "chunked"))
781
782def parse.body.chunked(+h: Map<&2, List<&2, String>>, rest: String, hascl: Bool) -> Hold:
783  match hascl:
784    case True{}:
785      HoldBad{}
786    case False{}:
787      parse.body.chunked.val(header.last(h, "transfer-encoding"), rest)
788
789def parse.body.te(+h: Map<&2, List<&2, String>>, rest: String, te: Bool) -> Hold:
790  match te:
791    case True{}:
792      parse.body.chunked(h, rest, has_header(h, "content-length"))
793    case False{}:
794      parse.body.cl(h, rest, has_header(h, "content-length"))
795
796def parse.body(+h: Map<&2, List<&2, String>>, rest: String) -> Hold:
797  parse.body.te(h, rest, has_header(h, "transfer-encoding"))
798
799# Bad: never a request. More: the head is not whole; read on. Head: the head is whole
800# and valid, and the body is still coming (req.body is empty). Req: a whole request.
801type Got is Type:
802  GotBad{}
803  GotMore{}
804  GotHead{req: Req}
805  GotReq{req: Req}
806
807def parse.finish(method: String, path: String, h: Map<&2, List<&2, String>>, body: Hold) -> Got:
808  match body:
809    case HoldBad{}:
810      GotBad{}
811    case HoldMore{}:
812      GotHead{Req{method, path, h, Bytes.new(0)}}
813    case HoldUntil{b}:
814      GotBad{}
815    case HoldBody{b}:
816      GotReq{Req{method, path, h, Bytes.from_string(b)}}
817
818def parse.host(method: String, path: String, +h: Map<&2, List<&2, String>>, rest: String, has: Bool) -> Got:
819  match has:
820    case False{}:
821      GotBad{}
822    case True{}:
823      parse.finish(method, path, h, parse.body(h, rest))
824
825# RFC 9112 §3.2: only HTTP/1.1 requires Host.
826def parse.fields(method: String, path: String, rest: String, v11: Bool, fs: Maybe<&2, Map<&2, List<&2, String>>>) -> Got:
827  match fs:
828    case None{}:
829      GotBad{}
830    case Some{+h}:
831      parse.host(method, path, h, rest, Bool.or(Bool.not(v11), has_header(h, "host")))
832
833def target_ok(+p: String) -> Bool:
834  Bool.or(String.starts_with(p, "/"), Bool.or(String.eq(p, "*"), String.starts_with(p, "http://")))
835
836def parse.target(method: String, +path: String, headers: String, rest: String, v11: Bool, ok: Bool) -> Got:
837  match ok:
838    case False{}:
839      GotBad{}
840    case True{}:
841      parse.fields(method, path, rest, v11, parse.headers.raw(headers))
842
843def parse.ver(method: String, +path: String, +v: String, headers: String, rest: String, ok: Bool) -> Got:
844  match ok:
845    case False{}:
846      GotBad{}
847    case True{}:
848      parse.target(method, path, headers, rest, String.eq(v, "HTTP/1.1"), target_ok(path))
849
850def parse.empty_method(method: String, path: String, +v: String, headers: String, rest: String, empty: Bool) -> Got:
851  match empty:
852    case True{}:
853      GotBad{}
854    case False{}:
855      parse.ver(method, path, v, headers, rest, Bool.or(String.eq(v, "HTTP/1.1"), String.eq(v, "HTTP/1.0")))
856
857def parse.start3(mpv: String & String & String, headers: String, rest: String) -> Got:
858  (+method, path, v) = mpv
859  parse.empty_method(method, path, v, headers, rest, String.is_empty(method))
860
861def parse.lines(lr: String & String, rest: String) -> Got:
862  (line, headers) = lr
863  parse.start3(start_line(line), headers, rest)
864
865
866def parse.head(+head: String, rest: String, whole: Bool) -> Got:
867  match whole:
868    case False{}:
869      GotMore{}
870    case True{}:
871      parse.lines(parse.first(head, SNil{}), rest)
872
873def parse.of(hb: String & String & Bool) -> Got:
874  (head, rest, whole) = hb
875  parse.head(head, rest, whole)
876
877# serve reads until this is not GotMore.
878def parse.got(+raw: String) -> Got:
879  parse.of(split_at_blank.flag.go(raw, raw, 0n, 0, False{}))
880
881
882def parse.req(g: Got) -> Maybe<&1, Req>:
883  match g:
884    case GotReq{req}:
885      Some{req}
886    case GotBad{}:
887      None{}
888    case GotMore{}:
889      None{}
890    case GotHead{req}:
891      None{}
892
893def parse(raw: String) -> Maybe<&1, Req>:
894  parse.req(parse.got(raw))
895
896def parse.res.cl(+h: Map<&2, List<&2, String>>, rest: String, hascl: Bool) -> Hold:
897  match hascl:
898    case False{}:
899      HoldBody{rest}
900    case True{}:
901      parse.res.cl.n(rest, parse_u32(header(h, "content-length")))
902
903def parse.res.chunked.eq(rest: String, ok: Bool) -> Hold:
904  match ok:
905    case False{}:
906      HoldUntil{rest}
907    case True{}:
908      chunk.live(rest)
909
910def parse.res.chunked.val(te: String, rest: String) -> Hold:
911  parse.res.chunked.eq(rest, String.eq(String.to_lower(te), "chunked"))
912
913def parse.res.chunked(+h: Map<&2, List<&2, String>>, rest: String, hascl: Bool) -> Hold:
914  match hascl:
915    case True{}:
916      HoldBad{}
917    case False{}:
918      parse.res.chunked.val(header.last(h, "transfer-encoding"), rest)
919
920def parse.res.te(+h: Map<&2, List<&2, String>>, rest: String, te: Bool) -> Hold:
921  match te:
922    case True{}:
923      parse.res.chunked(h, rest, has_header(h, "content-length"))
924    case False{}:
925      parse.res.cl(h, rest, has_header(h, "content-length"))
926
927def parse.res.body(+h: Map<&2, List<&2, String>>, rest: String) -> Hold:
928  parse.res.te(h, rest, has_header(h, "transfer-encoding"))
929
930# Bad: never a message. More: a valid prefix; read on. Done: a whole response.
931type Frame is Type:
932  FrameBad{}
933  FrameMore{}
934  FrameDone{res: Res}
935
936# RFC 9112 §8: a message cut short by close is incomplete, not valid.
937def frame.cut(closed: Bool) -> Frame:
938  match closed:
939    case True{}:
940      FrameBad{}
941    case False{}:
942      FrameMore{}
943
944def frame.wait(res: Res, wait: Bool) -> Frame:
945  match wait:
946    case True{}:
947      FrameMore{}
948    case False{}:
949      FrameDone{res}
950
951def frame.done(status: U32, h: Map<&2, List<&2, String>>, body: Hold, +closed: Bool, open: Bool) -> Frame:
952  match body:
953    case HoldBad{}:
954      FrameBad{}
955    case HoldMore{}:
956      frame.cut(closed)
957    case HoldUntil{b}:
958      frame.wait(Res{status, h, Bytes.from_string(b)}, Bool.not(closed))
959    case HoldBody{b}:
960      frame.wait(Res{status, h, Bytes.from_string(b)}, Bool.and(open, Bool.not(closed)))
961
962# RFC 9112 §6.3 (8): no TE and no CL ⇒ the body runs until the server closes.
963def frame.open(+h: Map<&2, List<&2, String>>) -> Bool:
964  Bool.not(Bool.or(has_header(h, "transfer-encoding"), has_header(h, "content-length")))
965
966# RFC 9112 §6.3 (1): HEAD, 1xx, 204 and 304 responses end at the blank line.
967def frame.nobody(+status: U32, head: Bool) -> Bool:
968  Bool.or(head, Bool.or(U32.is_lt(status, 200), Bool.or(U32.is_eq(status, 204), U32.is_eq(status, 304))))
969
970# 101 is the final response. Other 1xx are interim; a final response follows.
971def frame.interim(+status: U32) -> Bool:
972  Bool.and(U32.is_lt(status, 200), Bool.not(U32.is_eq(status, 101)))
973
974def frame.status(status: U32, +h: Map<&2, List<&2, String>>, rest: String, closed: Bool, nobody: Bool) -> Frame:
975  match nobody:
976    case True{}:
977      FrameDone{Res{status, h, Bytes.new(0)}}
978    case False{}:
979      frame.done(status, h, parse.res.body(h, rest), closed, frame.open(h))
980
981def parse.res.fields(+status: U32, rest: String, fs: Maybe<&2, Map<&2, List<&2, String>>>, closed: Bool, head: Bool) -> Frame:
982  match fs:
983    case None{}:
984      FrameBad{}
985    case Some{h}:
986      frame.status(status, h, rest, closed, frame.nobody(status, head))
987
988def parse.res.num(code: Maybe<&2, U32>, headers: String, rest: String, closed: Bool, head: Bool) -> Frame:
989  match code:
990    case None{}:
991      FrameBad{}
992    case Some{n}:
993      parse.res.fields(n, rest, parse.headers.raw(headers), closed, head)
994
995def parse.res.ver(code: String, headers: String, rest: String, closed: Bool, head: Bool, ok: Bool) -> Frame:
996  match ok:
997    case False{}:
998      FrameBad{}
999    case True{}:
1000      parse.res.num(parse_u32(code), headers, rest, closed, head)
1001
1002def parse.res.start3(mpv: String & String & String, headers: String, rest: String, closed: Bool, head: Bool) -> Frame:
1003  (+ver, code, reason) = mpv
1004  parse.res.ver(code, headers, rest, closed, head, Bool.or(String.eq(ver, "HTTP/1.1"), String.eq(ver, "HTTP/1.0")))
1005
1006def parse.res.lines(lr: String & String, rest: String, closed: Bool, head: Bool) -> Frame:
1007  (line, headers) = lr
1008  parse.res.start3(start_line(line), headers, rest, closed, head)
1009
1010def parse.res.blank(hd: String, rest: String, +closed: Bool, head: Bool, ok: Bool) -> Frame:
1011  match ok:
1012    case False{}:
1013      frame.cut(closed)
1014    case True{}:
1015      parse.res.lines(parse.first(hd, SNil{}), rest, closed, head)
1016
1017def parse.res.of(hb: String & String, closed: Bool, head: Bool) -> Frame:
1018  (+hd, rest) = hb
1019  parse.res.blank(hd, rest, closed, head, blank_end(hd))
1020
1021type Lead is Data:
1022  LeadCut{}
1023  LeadFinal{}
1024  LeadSkip{+rest: String}
1025
1026def frame.lead.if(rest: String, interim: Bool) -> Lead:
1027  match interim:
1028    case True{}:
1029      LeadSkip{rest}
1030    case False{}:
1031      LeadFinal{}
1032
1033def frame.lead.num(n: Maybe<&2, U32>, rest: String) -> Lead:
1034  match n:
1035    case None{}:
1036      LeadFinal{}
1037    case Some{s}:
1038      frame.lead.if(rest, frame.interim(s))
1039
1040def frame.lead.code(mpv: String & String & String, rest: String) -> Lead:
1041  (ver, code, reason) = mpv
1042  frame.lead.num(parse_u32(code), rest)
1043
1044def frame.lead.lines(xs: List<&2, String>, rest: String) -> Lead:
1045  match xs:
1046    case Nil{}:
1047      LeadFinal{}
1048    case Con{line, headers}:
1049      frame.lead.code(start_line(line), rest)
1050
1051def frame.lead.blank(+hd: String, rest: String, ok: Bool) -> Lead:
1052  match ok:
1053    case False{}:
1054      LeadCut{}
1055    case True{}:
1056      frame.lead.lines(String.lines(hd), rest)
1057
1058def frame.lead(hb: String & String) -> Lead:
1059  (+hd, rest) = hb
1060  frame.lead.blank(hd, rest, blank_end(hd))
1061
1062def frame.at.cont(+raw: String, lead: Lead) -> String:
1063  match lead:
1064    case LeadCut{}:
1065      raw
1066    case LeadFinal{}:
1067      raw
1068    case LeadSkip{rest}:
1069      rest
1070
1071def frame.at.zero.go(+raw: String, closed: Bool, head: Bool, lead: Lead) -> Frame:
1072  match lead:
1073    case LeadCut{}:
1074      frame.cut(closed)
1075    case LeadFinal{}:
1076      parse.res.of(split_at_blank(raw), closed, head)
1077    case LeadSkip{rest}:
1078      FrameBad{}
1079
1080def frame.at.zero.of(+raw: String, closed: Bool, head: Bool) -> Frame:
1081  frame.at.zero.go(raw, closed, head, frame.lead(split_at_blank(raw)))
1082
1083def frame.at.pos.do(f: Nat, +raw: String, closed: Bool, head: Bool, hb: String & String, lead: Lead) -> Frame:
1084  match f:
1085    case 0n:
1086      match lead:
1087        case LeadCut{}:
1088          frame.cut(closed)
1089        case LeadFinal{}:
1090          parse.res.of(hb, closed, head)
1091        case LeadSkip{+rest}:
1092          frame.at.zero.of(rest, closed, head)
1093    case 1n+g:
1094      match lead:
1095        case LeadCut{}:
1096          frame.cut(closed)
1097        case LeadFinal{}:
1098          parse.res.of(hb, closed, head)
1099        case LeadSkip{+rest}:
1100          frame.at.pos.do(g, rest, closed, head, split_at_blank(rest), frame.lead(split_at_blank(rest)))
1101
1102def frame.at.zero(+raw: String, closed: Bool, head: Bool) -> Frame:
1103  frame.at.zero.of(raw, closed, head)
1104
1105# ponytail: 8 interim responses; raise the fuel if a server sends more
1106def frame.at(fuel: Nat, +raw: String, closed: Bool, head: Bool) -> Frame:
1107  match fuel:
1108    case 0n:
1109      frame.at.zero(raw, closed, head)
1110    case 1n+f:
1111      frame.at.pos.do(f, raw, closed, head, split_at_blank(raw), frame.lead(split_at_blank(raw)))
1112
1113# frame(bytes so far, server closed?, request was HEAD?)
1114def frame(raw: String, closed: Bool, head: Bool) -> Frame:
1115  frame.at(8n, raw, closed, head)
1116
1117def frame.res(f: Frame) -> Maybe<&1, Res>:
1118  match f:
1119    case FrameDone{res}:
1120      Some{res}
1121    case FrameBad{}:
1122      None{}
1123    case FrameMore{}:
1124      None{}
1125
1126def parse_res(raw: String) -> Maybe<&1, Res>:
1127  frame.res(frame(raw, True{}, False{}))
1128
1129def res_fields.res(res: Res, k: String) -> List<&2, String>:
1130  Res{status, headers, body} = res
1131  fields(headers, k)
1132
1133def res_fields(m: Maybe<&1, Res>, k: String) -> List<&2, String>:
1134  match m:
1135    case None{}:
1136      Nil{}
1137    case Some{res}:
1138      res_fields.res(res, k)
1139
1140# The response body as it arrives. Len: bytes left. Chunk: the decoder. Close: until the
1141# server closes. Done: the body is whole. Bad: it cannot become a body.
1142type Rb is Data:
1143  RbLen{left: U32}
1144  RbChunk{st: Dc}
1145  RbClose{}
1146  RbDone{}
1147  RbBad{}
1148
1149def rb.cl(n: Maybe<&2, U32>) -> Maybe<&2, Rb>:
1150  match n:
1151    case None{}:
1152      None{}
1153    case Some{+k}:
1154      Some{Bool.pick(Rb, U32.is_zero(k), RbDone{}, RbLen{k})}
1155
1156def rb.te(+h: Map<&2, List<&2, String>>, cl: Bool) -> Maybe<&2, Rb>:
1157  match cl:
1158    case True{}:
1159      None{}
1160    case False{}:
1161      Some{Bool.pick(Rb, String.eq(String.to_lower(header.last(h, "transfer-encoding")), "chunked"), RbChunk{dc.start()}, RbClose{})}
1162
1163def rb.len(+h: Map<&2, List<&2, String>>, te: Bool) -> Maybe<&2, Rb>:
1164  match te:
1165    case True{}:
1166      rb.te(h, has_header(h, "content-length"))
1167    case False{}:
1168      Bool.pick(Maybe<&2, Rb>, has_header(h, "content-length"), rb.cl(parse_u32(header(h, "content-length"))), Some{RbClose{}})
1169
1170# RFC 9112 §6.3: how the body of this response ends. None: it cannot be framed.
1171def rb.of(+h: Map<&2, List<&2, String>>, nobody: Bool) -> Maybe<&2, Rb>:
1172  match nobody:
1173    case True{}:
1174      Some{RbDone{}}
1175    case False{}:
1176      rb.len(h, has_header(h, "transfer-encoding"))
1177
1178# rb: how the body goes on. parts: body bytes so far, newest first. rest: bytes past a Done body.
1179type Bf is Type:
1180  Bf{rb: Rb, parts: List<&1, Bytes.Bytes>, rest: Bytes.Bytes}
1181
1182def rb.len.cut(parts: List<&1, Bytes.Bytes>, +len: U32, +left: U32, r: Bytes.Bytes & Bytes.Bytes) -> Bf:
1183  (piece, data) = r
1184  Bf{RbDone{}, Con{data, parts}, bytes.snd(Bytes.slice(piece, left, (len - left : U32)))}
1185
1186def rb.len.have(short: Bool, +left: U32, parts: List<&1, Bytes.Bytes>, +len: U32, piece: Bytes.Bytes) -> Bf:
1187  match short:
1188    case True{}:
1189      Bf{RbLen{(left - len : U32)}, Con{piece, parts}, Bytes.new(0)}
1190    case False{}:
1191      rb.len.cut(parts, len, left, Bytes.slice(piece, 0, left))
1192
1193def rb.chunk(c: Ck) -> Bf:
1194  Ck{st, parts, rest} = c
1195  match st:
1196    case DcDone{}:
1197      Bf{RbDone{}, parts, rest}
1198    case DcBad{}:
1199      Bf{RbBad{}, parts, rest}
1200    case DcSize{a, b}:
1201      Bf{RbChunk{DcSize{a, b}}, parts, rest}
1202    case DcExt{x}:
1203      Bf{RbChunk{DcExt{x}}, parts, rest}
1204    case DcSizeLf{x}:
1205      Bf{RbChunk{DcSizeLf{x}}, parts, rest}
1206    case DcData{k}:
1207      Bf{RbChunk{DcData{k}}, parts, rest}
1208    case DcDataCr{}:
1209      Bf{RbChunk{DcDataCr{}}, parts, rest}
1210    case DcDataLf{}:
1211      Bf{RbChunk{DcDataLf{}}, parts, rest}
1212    case DcTr{j}:
1213      Bf{RbChunk{DcTr{j}}, parts, rest}
1214
1215# The body bytes in piece, added to parts.
1216def rb.feed(rb: Rb, parts: List<&1, Bytes.Bytes>, piece: Bytes.Bytes) -> Bf:
1217  match rb:
1218    case RbLen{+left}:
1219      Bytes.Bytes{+len, buf} = piece
1220      rb.len.have(U32.is_lt(len, left), left, parts, len, Bytes.Bytes{len, buf})
1221    case RbChunk{st}:
1222      rb.chunk(ck(piece, st, parts))
1223    case RbClose{}:
1224      Bf{RbClose{}, Con{piece, parts}, Bytes.new(0)}
1225    case RbDone{}:
1226      Bf{RbDone{}, parts, piece}
1227    case RbBad{}:
1228      Bf{RbBad{}, parts, piece}
1229
1230# RFC 9112 §8: only a close-delimited body may end at close.
1231def rb.eof(rb: Rb) -> Bool:
1232  match rb:
1233    case RbClose{}:
1234      True{}
1235    case RbDone{}:
1236      True{}
1237    case RbLen{n}:
1238      False{}
1239    case RbChunk{st}:
1240      False{}
1241    case RbBad{}:
1242      False{}
1243
1244def rb.body(parts: List<&1, Bytes.Bytes>) -> Bytes.Bytes:
1245  Bytes.concat(List.reverse(&1, Bytes.Bytes, parts))
1246
1247# The head scan. Seek: look for the blank line from byte from; k interim heads are behind.
1248# Wait: no blank line yet. Res: the final head, how its body ends, and the bytes after it.
1249type Hs is Type:
1250  HsSeek{buf: Bytes.Bytes, from: U32, k: U32}
1251  HsWait{buf: Bytes.Bytes, k: U32}
1252  HsBad{}
1253  HsRes{res: Res, rb: Rb, rest: Bytes.Bytes}
1254
1255def hs.final(+status: U32, +h: Map<&2, List<&2, String>>, rest: Bytes.Bytes, m: Maybe<&2, Rb>) -> Hs:
1256  match m:
1257    case None{}:
1258      HsBad{}
1259    case Some{rb}:
1260      HsRes{Res{status, h, Bytes.new(0)}, rb, rest}
1261
1262def hs.skip(more: Bool, +k: U32, rest: Bytes.Bytes) -> Hs:
1263  match more:
1264    case True{}:
1265      HsSeek{rest, 0, (k + 1 : U32)}
1266    case False{}:
1267      HsBad{}
1268
1269def hs.pick(interim: Bool, +head: Bool, +k: U32, +status: U32, +h: Map<&2, List<&2, String>>, rest: Bytes.Bytes) -> Hs:
1270  match interim:
1271    case True{}:
1272      hs.skip(U32.is_lt(k, 8), k, rest)
1273    case False{}:
1274      hs.final(status, h, rest, rb.of(h, frame.nobody(status, head)))
1275
1276def hs.res(+head: Bool, +k: U32, rest: Bytes.Bytes, res: Res) -> Hs:
1277  Res{+status, +h, body} = res
1278  hs.pick(frame.interim(status), head, k, status, h, rest)
1279
1280# The head alone, framed as a HEAD response so it stops at the blank line.
1281def hs.parsed(+head: Bool, +k: U32, rest: Bytes.Bytes, f: Frame) -> Hs:
1282  match f:
1283    case FrameDone{res}:
1284      hs.res(head, k, rest, res)
1285    case FrameBad{}:
1286      HsBad{}
1287    case FrameMore{}:
1288      HsBad{}
1289
1290def hs.split(+head: Bool, +k: U32, +hlen: U32, +len: U32, r: Bytes.Bytes & Bytes.Bytes) -> Hs:
1291  (buf, hb) = r
1292  hs.parsed(head, k, bytes.snd(Bytes.slice(buf, hlen, (len - hlen : U32))), parse.res.of(split_at_blank(Bytes.to_string(hb)), False{}, True{}))
1293
1294def hs.hit(+head: Bool, +k: U32, +len: U32, buf: Bytes.Bytes, at: Maybe<&2, U32>) -> Hs:
1295  match at:
1296    case None{}:
1297      HsWait{buf, k}
1298    case Some{+i}:
1299      +hlen = (i + 4 : U32)
1300      hs.split(head, k, hlen, len, Bytes.slice(buf, 0, hlen))
1301
1302def hs.seek.of(+head: Bool, +k: U32, +len: U32, +from: U32, buf: Bytes.Bytes, r: Bytes.Bytes & Maybe<&2, U32>) -> Hs:
1303  (tail, m) = r
1304  hs.hit(head, k, len, buf, found.at(from, m))
1305
1306def hs.seek(+head: Bool, +k: U32, +len: U32, +from: U32, r: Bytes.Bytes & Bytes.Bytes) -> Hs:
1307  (buf, tail) = r
1308  hs.seek.of(head, k, len, from, buf, Bytes.find(tail, "\r\n\r\n"))
1309
1310def hs.step(+head: Bool, st: Hs) -> Hs:
1311  match st:
1312    case HsSeek{buf, +from, +k}:
1313      Bytes.Bytes{+len, b} = buf
1314      hs.seek(head, k, len, from, Bytes.slice(Bytes.Bytes{len, b}, from, (len - from : U32)))
1315    case HsWait{buf, k}:
1316      HsWait{buf, k}
1317    case HsBad{}:
1318      HsBad{}
1319    case HsRes{res, rb, rest}:
1320      HsRes{res, rb, rest}
1321
1322# Each step ends the scan or passes one interim head, and at most 8 interim heads pass.
1323def hs.scan(fuel: Nat, +head: Bool, st: Hs) -> Hs:
1324  match fuel:
1325    case 0n:
1326      match st:
1327        case HsSeek{buf, from, k}:
1328          HsBad{}
1329        case HsWait{buf, k}:
1330          HsWait{buf, k}
1331        case HsBad{}:
1332          HsBad{}
1333        case HsRes{res, rb, rest}:
1334          HsRes{res, rb, rest}
1335    case 1n+f:
1336      hs.scan(f, head, hs.step(head, st))
1337
1338# piece joins buf; only the new bytes, and the 3 before them, can finish the blank line.
1339def hs.more(+head: Bool, +k: U32, buf: Bytes.Bytes, piece: Bytes.Bytes) -> Hs:
1340  Bytes.Bytes{+ol, ob} = buf
1341  hs.scan(10n, head, HsSeek{Bytes.append(Bytes.Bytes{ol, ob}, piece), Bool.pick(U32, U32.is_lt(ol, 3), 0, (ol - 3 : U32)), k})
1342
1343# Untrusted servers must not grow the buffer without bound.
1344def fetch.max() -> Nat:
1345  U32.to_nat(16777216)
1346
1347# A response read in pieces. Head: the head is not whole yet. Body: it is, and parts is the body so far.
1348# Len: a Content-Length body in one buffer of that size, with left bytes still to come.
1349type Rv is Type:
1350  RvHead{buf: Bytes.Bytes, k: U32}
1351  RvBody{res: Res, rb: Rb, parts: List<&1, Bytes.Bytes>}
1352  RvLen{res: Res, left: U32, body: Bytes.Bytes}
1353
1354# More: read on. Done: the response, and the bytes after it when the body is self-delimited.
1355type Rt is Type:
1356  RtMore{rv: Rv}
1357  RtBad{}
1358  RtDone{res: Res, rest: Maybe<&1, Bytes.Bytes>}
1359
1360def rv.start() -> Rv:
1361  RvHead{Bytes.new(0), 0}
1362
1363def rv.whole(res: Res, b: Bytes.Bytes, rest: Maybe<&1, Bytes.Bytes>) -> Rt:
1364  Res{status, headers, body} = res
1365  RtDone{Res{status, headers, b}, rest}
1366
1367def rv.done(res: Res, parts: List<&1, Bytes.Bytes>, rest: Maybe<&1, Bytes.Bytes>) -> Rt:
1368  rv.whole(res, rb.body(parts), rest)
1369
1370def rl.put.of(+total: U32, +len: U32, r: Array<U32> & Array<U32>) -> Bytes.Bytes & Bytes.Bytes:
1371  (src, dst) = r
1372  (Bytes.Bytes{total, dst}, Bytes.Bytes{len, src})
1373
1374# The first m bytes of piece, written into body after the total - left bytes already there.
1375def rl.put(+m: U32, +left: U32, body: Bytes.Bytes, piece: Bytes.Bytes) -> Bytes.Bytes & Bytes.Bytes:
1376  Bytes.Bytes{+total, dst} = body
1377  Bytes.Bytes{+len, src} = piece
1378  rl.put.of(total, len, Bytes.copy(m, src, dst, 0, (total - left : U32)))
1379
1380def rl.fed(short: Bool, res: Res, +left: U32, +len: U32, r: Bytes.Bytes & Bytes.Bytes) -> Rt:
1381  match short:
1382    case True{}:
1383      (body, piece) = r
1384      RtMore{RvLen{res, (left - len : U32), body}}
1385    case False{}:
1386      (body, piece) = r
1387      rv.whole(res, body, Some{bytes.snd(Bytes.slice(piece, left, (len - left : U32)))})
1388
1389def rl.feed(res: Res, +left: U32, body: Bytes.Bytes, piece: Bytes.Bytes) -> Rt:
1390  Bytes.Bytes{+len, buf} = piece
1391  rl.fed(U32.is_lt(len, left), res, left, len, rl.put(U32.min(len, left), left, body, Bytes.Bytes{len, buf}))
1392
1393def rv.fed(res: Res, bf: Bf) -> Rt:
1394  Bf{rb, parts, rest} = bf
1395  match rb:
1396    case RbDone{}:
1397      rv.done(res, parts, Some{rest})
1398    case RbBad{}:
1399      RtBad{}
1400    case RbLen{n}:
1401      RtMore{RvBody{res, RbLen{n}, parts}}
1402    case RbChunk{st}:
1403      RtMore{RvBody{res, RbChunk{st}, parts}}
1404    case RbClose{}:
1405      RtMore{RvBody{res, RbClose{}, parts}}
1406
1407# Some{left}: a Content-Length body small enough to allocate up front. Larger ones fail at the fetch cap.
1408def rb.buf(rb: Rb) -> Maybe<&2, U32>:
1409  match rb:
1410    case RbLen{+left}:
1411      Bool.pick(Maybe<&2, U32>, Nat.is_lt(fetch.max(), U32.to_nat(left)), None{}, Some{left})
1412    case RbChunk{st}:
1413      None{}
1414    case RbClose{}:
1415      None{}
1416    case RbDone{}:
1417      None{}
1418    case RbBad{}:
1419      None{}
1420
1421def rv.body(m: Maybe<&2, U32>, res: Res, rb: Rb, rest: Bytes.Bytes) -> Rt:
1422  match m:
1423    case None{}:
1424      rv.fed(res, rb.feed(rb, Nil{}, rest))
1425    case Some{+left}:
1426      rl.feed(res, left, Bytes.new(left), rest)
1427
1428def rv.head(hs: Hs) -> Rt:
1429  match hs:
1430    case HsWait{buf, k}:
1431      RtMore{RvHead{buf, k}}
1432    case HsBad{}:
1433      RtBad{}
1434    case HsSeek{buf, from, k}:
1435      RtBad{}
1436    case HsRes{res, +rb, rest}:
1437      rv.body(rb.buf(rb), res, rb, rest)
1438
1439def rv.eof(res: Res, parts: List<&1, Bytes.Bytes>, ok: Bool) -> Rt:
1440  match ok:
1441    case True{}:
1442      rv.done(res, parts, None{})
1443    case False{}:
1444      RtBad{}
1445
1446# One read: piece, or the server closed (RFC 9112 §8: a message cut short is not a message).
1447def rv.step(closed: Bool, +head: Bool, rv: Rv, piece: Bytes.Bytes) -> Rt:
1448  match closed:
1449    case True{}:
1450      match rv:
1451        case RvHead{buf, k}:
1452          RtBad{}
1453        case RvBody{res, rb, parts}:
1454          rv.eof(res, parts, rb.eof(rb))
1455        case RvLen{res, left, body}:
1456          RtBad{}
1457    case False{}:
1458      match rv:
1459        case RvHead{buf, +k}:
1460          rv.head(hs.more(head, k, buf, piece))
1461        case RvBody{res, rb, parts}:
1462          rv.fed(res, rb.feed(rb, parts, piece))
1463        case RvLen{res, +left, body}:
1464          rl.feed(res, left, body, piece)
1465
1466def rv.end(closed: Bool, +head: Bool, t: Rt) -> Rt:
1467  match closed:
1468    case False{}:
1469      t
1470    case True{}:
1471      match t:
1472        case RtMore{rv}:
1473          rv.step(True{}, head, rv, Bytes.new(0))
1474        case RtBad{}:
1475          RtBad{}
1476        case RtDone{res, rest}:
1477          RtDone{res, rest}
1478
1479def rv.go(xs: List<&2, String>, closed: Bool, +head: Bool, t: Rt) -> Rt:
1480  match xs:
1481    case Nil{}:
1482      rv.end(closed, head, t)
1483    case Con{+x, rest}:
1484      match t:
1485        case RtMore{rv}:
1486          rv.go(rest, closed, head, rv.step(False{}, head, rv, Bytes.from_string(x)))
1487        case RtBad{}:
1488          RtBad{}
1489        case RtDone{res, r}:
1490          RtDone{res, r}
1491
1492def rt.frame(t: Rt) -> Frame:
1493  match t:
1494    case RtMore{rv}:
1495      FrameMore{}
1496    case RtBad{}:
1497      FrameBad{}
1498    case RtDone{res, rest}:
1499      FrameDone{res}
1500
1501# What the read loop makes of these pieces, then a close when closed is set.
1502def res.frame(xs: List<&2, String>, closed: Bool, +head: Bool) -> Frame:
1503  rt.frame(rv.go(xs, closed, head, RtMore{rv.start()}))
1504
1505def rt.rest(t: Rt) -> Maybe<&1, Bytes.Bytes>:
1506  match t:
1507    case RtMore{rv}:
1508      None{}
1509    case RtBad{}:
1510      None{}
1511    case RtDone{res, rest}:
1512      rest
1513
1514def after.of(m: Maybe<&1, Bytes.Bytes>) -> Maybe<&2, String>:
1515  match m:
1516    case None{}:
1517      None{}
1518    case Some{b}:
1519      Some{Bytes.to_string(b)}
1520
1521# Bytes after a complete self-delimited message. None if it is not one yet.
1522def after(+raw: String, +head: Bool) -> Maybe<&2, String>:
1523  after.of(rt.rest(rv.go([raw], False{}, head, RtMore{rv.start()})))
1524
1525def req.v11.ver(mpv: String & String & String) -> Bool:
1526  (+method, path, v) = mpv
1527  String.eq(v, "HTTP/1.1")
1528
1529def req.v11.line(+line: String) -> Bool:
1530  req.v11.ver(start_line(line))
1531
1532def req.v11.lines(xs: List<&2, String>) -> Bool:
1533  match xs:
1534    case Nil{}:
1535      False{}
1536    case Con{line, headers}:
1537      req.v11.line(line)
1538
1539def req.v11.pick(+head: String, ok: Bool) -> Bool:
1540  match ok:
1541    case False{}:
1542      False{}
1543    case True{}:
1544      req.v11.lines(String.lines(head))
1545
1546def req.v11.of(hb: String & String) -> Bool:
1547  (+head, rest) = hb
1548  req.v11.pick(head, blank_end(head))
1549
1550def req.v11(+raw: String) -> Bool:
1551  req.v11.of(split_at_blank(raw))
1552
1553def req.conn_close(+headers: Map<&2, List<&2, String>>) -> Bool:
1554  String.eq(String.to_lower(header(headers, "connection")), "close")
1555
1556def res.conn_close(+headers: Map<&2, List<&2, String>>) -> Bool:
1557  String.eq(String.to_lower(header(headers, "connection")), "close")
1558
1559def serve.fail_close(+status: U32) -> Bool:
1560  Bool.or(U32.is_eq(status, 400), Bool.or(U32.is_eq(status, 413), U32.is_eq(status, 431)))
1561
1562def serve.keep.ok(fail: Bool, res_close: Bool) -> Bool:
1563  match fail:
1564    case True{}:
1565      False{}
1566    case False{}:
1567      Bool.not(res_close)
1568
1569def serve.keep.v11(v11: Bool, +req_close: Bool, +status: U32, res_close: Bool) -> Bool:
1570  match v11:
1571    case False{}:
1572      False{}
1573    case True{}:
1574      match req_close:
1575        case True{}:
1576          False{}
1577        case False{}:
1578          serve.keep.ok(serve.fail_close(status), res_close)
1579
1580def serve.keep(+headers: Map<&2, List<&2, String>>, v11: Bool, +status: U32, +res: Map<&2, List<&2, String>>) -> Bool:
1581  serve.keep.v11(v11, req.conn_close(headers), status, res.conn_close(res))
1582
1583
1584def again.keep(close: Bool, x: Bytes.Bytes) -> Maybe<&1, Bytes.Bytes>:
1585  match close:
1586    case True{}:
1587      None{}
1588    case False{}:
1589      Some{x}
1590
1591def again.rest(close: Bool, rest: Maybe<&1, Bytes.Bytes>) -> Maybe<&1, Bytes.Bytes>:
1592  match rest:
1593    case None{}:
1594      None{}
1595    case Some{x}:
1596      again.keep(close, x)
1597
1598# The bytes past the response when the socket can take another request: the request did not
1599# ask to close, the response is self-delimited, and the peer did not say close.
1600def again(close: Bool, +h: Map<&2, List<&2, String>>, rest: Maybe<&1, Bytes.Bytes>) -> Maybe<&1, Bytes.Bytes>:
1601  match close:
1602    case True{}:
1603      None{}
1604    case False{}:
1605      again.rest(String.eq(String.to_lower(header(h, "connection")), "close"), rest)
1606
1607def res_body.res(res: Res) -> Bytes.Bytes:
1608  Res{status, headers, body} = res
1609  body
1610
1611def res_body(m: Maybe<&1, Res>) -> Bytes.Bytes:
1612  match m:
1613    case None{}:
1614      Bytes.new(0)
1615    case Some{res}:
1616      res_body.res(res)
1617
1618def text(res: Res) -> String:
1619  Enc.utf8.decode(res_body.res(res))
1620
1621# UTF-8 is checked, not repaired: bad UTF-8 in a string gives None (RFC 8259 §8.1).
1622def json(res: Res) -> Maybe<&1, Json.Val>:
1623  Json.parse.bytes(res_body.res(res))
1624
1625def got_body.req(req: Req) -> Bytes.Bytes:
1626  Req{method, path, headers, body} = req
1627  body
1628
1629def got_body(m: Maybe<&1, Req>) -> Bytes.Bytes:
1630  match m:
1631    case None{}:
1632      Bytes.new(0)
1633    case Some{req}:
1634      got_body.req(req)
1635
1636def body.of(hb: String & String) -> String:
1637  (h, b) = hb
1638  b
1639
1640def body(s: String) -> String:
1641  body.of(split_at_blank.go(s, False{}, 0, SNil{}))
1642
1643def headers_lines(+k: String, vs: List<&2, String>, acc: String) -> String:
1644  match vs:
1645    case Nil{}:
1646      acc
1647    case Con{v, t}:
1648      headers_lines(k, t, acc ++ ("\r\n" ++ sanitize(k) ++ ": " ++ sanitize(v)))
1649
1650def headers_block.go(xs: List<&2, Sigma<&2, &2, String, _ => List<&2, String>>>, acc: String) -> String:
1651  match xs:
1652    case Nil{}:
1653      acc
1654    case (k, vs) <> t:
1655      headers_block.go(t, headers_lines(k, vs, acc))
1656
1657def headers_block(h: Map<&2, List<&2, String>>) -> String:
1658  headers_block.go(Map.to_list(&2, List<&2, String>, h), "")
1659
1660# RFC 9110 §15. An unknown code gets an empty reason, which RFC 9112 §4 allows.
1661type Reason is Data:
1662  Reason{code: U32, text: String}
1663
1664def reasons() -> List<&2, Reason>:
1665  [Reason{100, "Continue"}, Reason{101, "Switching Protocols"}, Reason{103, "Early Hints"},
1666   Reason{200, "OK"}, Reason{201, "Created"}, Reason{202, "Accepted"}, Reason{203, "Non-Authoritative Information"}, Reason{204, "No Content"}, Reason{205, "Reset Content"}, Reason{206, "Partial Content"},
1667   Reason{300, "Multiple Choices"}, Reason{301, "Moved Permanently"}, Reason{302, "Found"}, Reason{303, "See Other"}, Reason{304, "Not Modified"}, Reason{307, "Temporary Redirect"}, Reason{308, "Permanent Redirect"},
1668   Reason{400, "Bad Request"}, Reason{401, "Unauthorized"}, Reason{402, "Payment Required"}, Reason{403, "Forbidden"}, Reason{404, "Not Found"}, Reason{405, "Method Not Allowed"}, Reason{406, "Not Acceptable"}, Reason{407, "Proxy Authentication Required"}, Reason{408, "Request Timeout"}, Reason{409, "Conflict"}, Reason{410, "Gone"}, Reason{411, "Length Required"}, Reason{412, "Precondition Failed"}, Reason{413, "Content Too Large"}, Reason{414, "URI Too Long"}, Reason{415, "Unsupported Media Type"}, Reason{416, "Range Not Satisfiable"}, Reason{417, "Expectation Failed"}, Reason{421, "Misdirected Request"}, Reason{422, "Unprocessable Content"}, Reason{426, "Upgrade Required"}, Reason{428, "Precondition Required"}, Reason{429, "Too Many Requests"}, Reason{431, "Request Header Fields Too Large"},
1669   Reason{500, "Internal Server Error"}, Reason{501, "Not Implemented"}, Reason{502, "Bad Gateway"}, Reason{503, "Service Unavailable"}, Reason{504, "Gateway Timeout"}, Reason{505, "HTTP Version Not Supported"}]
1670
1671def reason.go(xs: List<&2, Reason>, +status: U32) -> String:
1672  match xs:
1673    case Nil{}:
1674      ""
1675    case Con{Reason{k, v}, t}:
1676      Bool.pick(String, U32.is_eq(k, status), v, reason.go(t, status))
1677
1678def reason(+status: U32) -> String:
1679  reason.go(reasons(), status)
1680
1681def response(+status: U32, headers: Map<&2, List<&2, String>>, body: String) -> String:
1682  ("HTTP/1.1 " ++ U32.show(status) ++ " " ++ reason(status) ++ headers_block(headers)) ++ ("\r\n\r\n" ++ body)
1683
1684def encode.body(head: Bool, top: Bytes.Bytes, body: Bytes.Bytes) -> Bytes.Bytes:
1685  match head:
1686    case True{}:
1687      top
1688    case False{}:
1689      Bytes.append(top, body)
1690
1691def encode.len(+status: U32, headers: Map<&2, List<&2, String>>, head: Bool, body: Bytes.Bytes) -> Bytes.Bytes:
1692  Bytes.Bytes{+len, buf} = body
1693  encode.body(head, Bytes.from_string(response(status, set(headers, "content-length", U32.show(len)), "")), Bytes.Bytes{len, buf})
1694
1695# RFC 9110 §6.4.1, §8.6: 1xx, 204 and 304 have no body; HEAD gets the length but no body.
1696def encode.pick(+status: U32, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, head: Bool, nobody: Bool) -> Bytes.Bytes:
1697  match nobody:
1698    case True{}:
1699      Bytes.from_string(response(status, headers, ""))
1700    case False{}:
1701      encode.len(status, headers, head, body)
1702
1703def encode.on(r: Res, head: Bool) -> Bytes.Bytes:
1704  Res{+status, headers, body} = r
1705  encode.pick(status, headers, body, head, frame.nobody(status, False{}))
1706
1707def encode(r: Res) -> Bytes.Bytes:
1708  encode.on(r, False{})
1709
1710def request(method: String, path: String, headers: Map<&2, List<&2, String>>, body: String) -> String:
1711  (method ++ " " ++ path ++ " HTTP/1.1" ++ headers_block(headers)) ++ ("\r\n\r\n" ++ body)
1712
1713def req.reserved(+k: String) -> Bool:
1714  Bool.or(Bool.or(String.eq(k, "host"), String.eq(k, "connection")), Bool.or(String.eq(k, "content-length"), String.eq(k, "transfer-encoding")))
1715
1716def req.put.one(m: Map<&2, List<&2, String>>, +k: String, vs: List<&2, String>, skip: Bool) -> Map<&2, List<&2, String>>:
1717  match skip:
1718    case True{}:
1719      m
1720    case False{}:
1721      Map.set(&2, List<&2, String>, m, k, vs)
1722
1723def req.put(xs: List<&2, Sigma<&2, &2, String, _ => List<&2, String>>>, m: Map<&2, List<&2, String>>) -> Map<&2, List<&2, String>>:
1724  match xs:
1725    case Nil{}:
1726      m
1727    case (k, vs) <> t:
1728      +lk = String.to_lower(k)
1729      req.put(t, req.put.one(m, lk, vs, req.reserved(lk)))
1730
1731# RFC 9110 §8.6: no Content-Length on a bodiless request whose method gives a body no meaning.
1732def req.cl(+m: Map<&2, List<&2, String>>, +method: String, +len: U32) -> Map<&2, List<&2, String>>:
1733  +bodied = Bool.or(Bool.not(U32.is_zero(len)), Bool.or(String.eq(method, "POST"), Bool.or(String.eq(method, "PUT"), String.eq(method, "PATCH"))))
1734  Bool.pick(Map<&2, List<&2, String>>, bodied, set(m, "content-length", U32.show(len)), m)
1735
1736# Caller headers are lowercased so they cannot duplicate ours; host, connection,
1737# content-length and transfer-encoding are always ours (no smuggling through them).
1738def encode_req.word(close: Bool) -> String:
1739  match close:
1740    case True{}:
1741      "close"
1742    case False{}:
1743      "keep-alive"
1744
1745def encode_req.on(+method: String, target: String, host: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, close: Bool) -> Bytes.Bytes:
1746  Bytes.Bytes{+len, buf} = body
1747  +h = set(set(req.put(Map.to_list(&2, List<&2, String>, headers), empty()), "host", host), "connection", encode_req.word(close))
1748  Bytes.append(Bytes.from_string(request(method, target, req.cl(h, method, len), "")), Bytes.Bytes{len, buf})
1749
1750def encode_req(+method: String, target: String, host: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> Bytes.Bytes:
1751  encode_req.on(method, target, host, headers, body, True{})
1752
1753# Redirects (RFC 9110 §15.4, as WHATWG fetch applies them)
1754# --------------------------------------------------------
1755
1756# One request to make: headers are already lowercased (see req.put).
1757type Hop is Type:
1758  Hop{method: String, url: Url.Abs, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes}
1759
1760def redirect.code(+s: U32) -> Bool:
1761  Bool.or(Bool.or(U32.is_eq(s, 301), U32.is_eq(s, 302)), Bool.or(U32.is_eq(s, 303), Bool.or(U32.is_eq(s, 307), U32.is_eq(s, 308))))
1762
1763def redirect.origin(a: Url.Abs) -> String:
1764  Url.Abs{scheme, host, port, target} = a
1765  scheme ++ "://" ++ host ++ ":" ++ U32.show(port)
1766
1767def redirect.del(ks: List<&2, String>, m: Map<&2, List<&2, String>>) -> Map<&2, List<&2, String>>:
1768  match ks:
1769    case Nil{}:
1770      m
1771    case Con{k, t}:
1772      redirect.del(t, Map.del(&2, List<&2, String>, m, k))
1773
1774def redirect.hdrs(+h: Map<&2, List<&2, String>>, drop: Bool, cross: Bool) -> Map<&2, List<&2, String>>:
1775  +h2 = Bool.pick(Map<&2, List<&2, String>>, drop, redirect.del(["content-type", "content-encoding", "content-language", "content-location"], h), h)
1776  Bool.pick(Map<&2, List<&2, String>>, cross, redirect.del(["authorization", "cookie", "proxy-authorization"], h2), h2)
1777
1778# 303 turns any method but HEAD into GET; 301 and 302 turn POST into GET;
1779# 307 and 308 keep method and body. A GET carries no body or body headers.
1780# Credentials do not follow a hop to another origin.
1781def redirect.body(drop: Bool, body: Bytes.Bytes) -> Bytes.Bytes:
1782  match drop:
1783    case True{}:
1784      Bytes.new(0)
1785    case False{}:
1786      body
1787
1788def redirect.to(+status: U32, +method: String, +from: Url.Abs, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, next: Maybe<&2, Url.Abs>) -> Maybe<&1, Hop>:
1789  match next:
1790    case None{}:
1791      None{}
1792    case Some{+to}:
1793      +drop = Bool.or(Bool.and(U32.is_eq(status, 303), Bool.not(String.eq(method, "HEAD"))), Bool.and(Bool.or(U32.is_eq(status, 301), U32.is_eq(status, 302)), String.eq(method, "POST")))
1794      Some{Hop{Bool.pick(String, drop, "GET", method), to, redirect.hdrs(headers, drop, Bool.not(String.eq(redirect.origin(from), redirect.origin(to)))), redirect.body(drop, body)}}
1795
1796def redirect.hop(status: U32, h: Hop, loc: String) -> Maybe<&1, Hop>:
1797  Hop{method, +url, headers, body} = h
1798  redirect.to(status, method, url, headers, body, Url.resolve(url, loc))
1799
1800def redirect.if(status: U32, h: Hop, loc: String, ok: Bool) -> Maybe<&1, Hop>:
1801  match ok:
1802    case False{}:
1803      None{}
1804    case True{}:
1805      redirect.hop(status, h, loc)
1806
1807# The next request after a response, or None when it is not a redirect we follow.
1808def redirect(+status: U32, +headers: Map<&2, List<&2, String>>, h: Hop) -> Maybe<&1, Hop>:
1809  redirect.if(status, h, header(headers, "location"), Bool.and(redirect.code(status), has_header(headers, "location")))
1810
1811# Cookies (RFC 6265bis §5)
1812# ------------------------
1813
1814# A stored cookie. domain is lowercase, with no leading dot; host_only sends it to that host alone.
1815# expiry None is a session cookie. http_only and same_site ("strict", "lax", "none" or "default")
1816# are kept, not enforced: fetch has no browsing client, so its requests are same-site (§5.2).
1817type Cookie is Data:
1818  Cookie{name: String, value: String, domain: String, host_only: Bool, path: String, secure: Bool, http_only: Bool, same_site: String, expiry: Maybe<&2, Time.Instant>}
1819
1820# The cookies, oldest first, and the caller's clock. No cookie in it has expired by now.
1821type Jar is Data:
1822  Jar{now: Time.Instant, cookies: List<&2, Cookie>}
1823
1824def jar.new(now: Time.Instant) -> Jar:
1825  Jar{now, Nil{}}
1826
1827def jar.cookies(j: Jar) -> List<&2, Cookie>:
1828  Jar{now, cs} = j
1829  cs
1830
1831def cookie.live.at(+now: Time.Instant, e: Maybe<&2, Time.Instant>) -> Bool:
1832  match e:
1833    case None{}:
1834      True{}
1835    case Some{t}:
1836      Cmp.is_lt(Time.Instant.cmp(now, t))
1837
1838# Alive at now: no expiry, or an expiry after now.
1839def cookie.live(+now: Time.Instant, c: Cookie) -> Bool:
1840  Cookie{name, value, domain, host_only, path, secure, http_only, same_site, expiry} = c
1841  cookie.live.at(now, expiry)
1842
1843def jar.live(cs: List<&2, Cookie>, +now: Time.Instant) -> List<&2, Cookie>:
1844  match cs:
1845    case Nil{}:
1846      Nil{}
1847    case Con{+c, t}:
1848      List.filter.put(Cookie, c, jar.live(t, now), cookie.live(now, c))
1849
1850# The jar at a later time: cookies expired by now are evicted (§5.7).
1851def jar.at(j: Jar, +now: Time.Instant) -> Jar:
1852  Jar{old, cs} = j
1853  Jar{now, jar.live(cs, now)}
1854
1855def cookie.cut.found(r: String & String) -> String & String & Bool:
1856  (a, b) = r
1857  (a, b, True{})
1858
1859# hit: the last char pushed onto acc was c.
1860def cookie.cut.go(s: String, +c: U32, acc: String, hit: Bool) -> String & String & Bool:
1861  match s:
1862    case SNil{}:
1863      match hit:
1864        case True{}:
1865          cookie.cut.found(take.cut(acc, SNil{}))
1866        case False{}:
1867          (String.reverse(acc), SNil{}, False{})
1868    case SCon{Chr{+x}, t}:
1869      match hit:
1870        case True{}:
1871          cookie.cut.found(take.cut(acc, SCon{Chr{x}, t}))
1872        case False{}:
1873          cookie.cut.go(t, c, SCon{Chr{x}, acc}, U32.is_eq(x, c))
1874
1875# s split at its first c: before, after, and whether c was there.
1876def cookie.cut(s: String, +c: U32) -> String & String & Bool:
1877  cookie.cut.go(s, c, SNil{}, False{})
1878
1879def cookie.fst(r: String & String & Bool) -> String:
1880  (a, b, found) = r
1881  a
1882
1883# The path of an origin-form target: the part before "?".
1884def cookie.target_path(t: String) -> String:
1885  cookie.fst(cookie.cut(t, 63))
1886
1887# Longer than n octets.
1888def cookie.over(s: String, +n: U32) -> Bool:
1889  match s:
1890    case SNil{}:
1891      False{}
1892    case SCon{c, t}:
1893      Bool.or(U32.is_eq(n, 0), cookie.over(t, (n - 1 : U32)))
1894
1895# %x00-08 / %x0A-1F / %x7F: control characters other than HTAB.
1896def cookie.ctl(s: String) -> Bool:
1897  match s:
1898    case SNil{}:
1899      False{}
1900    case SCon{Chr{+c}, t}:
1901      Bool.or(Bool.or(U32.is_lt(c, 9), Bool.and(U32.is_gt(c, 9), U32.is_lt(c, 32))), Bool.or(U32.is_eq(c, 127), cookie.ctl(t)))
1902
1903def cookie.ascii(s: String) -> Bool:
1904  match s:
1905    case SNil{}:
1906      True{}
1907    case SCon{Chr{+c}, t}:
1908      Bool.and(U32.is_lt(c, 128), cookie.ascii(t))
1909
1910def cookie.ip4(s: String) -> Bool:
1911  match s:
1912    case SNil{}:
1913      True{}
1914    case SCon{Chr{+c}, t}:
1915      Bool.and(Bool.or(parse_u32.digit(c), U32.is_eq(c, 46)), cookie.ip4(t))
1916
1917# An IP literal rather than a host name: IPv6 has a colon, IPv4 is digits and dots.
1918def cookie.ip(+h: String) -> Bool:
1919  Bool.or(String.contains(h, ":"), cookie.ip4(h))
1920
1921# §5.1.3: s is d, or a host name under d on a label boundary.
1922def cookie.domain_match(+s: String, +d: String) -> Bool:
1923  Bool.or(String.eq(s, d), Bool.and(String.ends_with(s, "." ++ d), Bool.not(cookie.ip(s))))
1924
1925# A reversed path with its last segment and slash dropped.
1926def cookie.up(rs: String) -> String:
1927  match rs:
1928    case SNil{}:
1929      SNil{}
1930    case SCon{Chr{47}, t}:
1931      t
1932    case SCon{Chr{c}, t}:
1933      cookie.up(t)
1934
1935# §5.1.4: the request path up to its last "/", or "/".
1936def cookie.default_path(+p: String) -> String:
1937  +up = String.reverse(cookie.up(String.reverse(p)))
1938  Bool.pick(String, Bool.or(Bool.not(String.starts_with(p, "/")), String.is_empty(up)), "/", up)
1939
1940# §5.1.4: request path p path-matches cookie path c.
1941def cookie.path_match(+p: String, +c: String) -> Bool:
1942  Bool.or(String.eq(p, c), Bool.and(String.starts_with(p, c), Bool.or(String.ends_with(c, "/"), String.starts_with(String.drop(p, String.length(c)), "/"))))
1943
1944type Hms is Data:
1945  Hms{h: U32, m: U32, s: U32}
1946
1947# §5.1.1 cookie-date: the first time, day, month and year tokens found.
1948type Cdate is Data:
1949  Cdate{time: Maybe<&2, Hms>, day: Maybe<&2, U32>, month: Maybe<&2, U32>, year: Maybe<&2, U32>}
1950
1951def cookie.date.delim(+c: U32) -> Bool:
1952  Bool.or(U32.is_eq(c, 9), Bool.or(Bool.and(U32.is_ge(c, 32), U32.is_le(c, 47)), Bool.or(Bool.and(U32.is_ge(c, 59), U32.is_le(c, 64)), Bool.or(Bool.and(U32.is_ge(c, 91), U32.is_le(c, 96)), Bool.and(U32.is_ge(c, 123), U32.is_le(c, 126))))))
1953
1954def cookie.date.push(acc: String, ts: List<&2, String>) -> List<&2, String>:
1955  match acc:
1956    case SNil{}:
1957      ts
1958    case SCon{h, t}:
1959      Con{String.reverse(SCon{h, t}), ts}
1960
1961def cookie.date.step(d: Bool, +c: U32, acc: String, ts: List<&2, String>) -> String & List<&2, String>:
1962  match d:
1963    case True{}:
1964      (SNil{}, cookie.date.push(acc, ts))
1965    case False{}:
1966      (SCon{Chr{c}, acc}, ts)
1967
1968# The date-tokens, last first. st: the token so far (reversed) and the tokens before it.
1969def cookie.date.tokens(s: String, st: String & List<&2, String>) -> List<&2, String>:
1970  match s:
1971    case SNil{}:
1972      (acc, ts) = st
1973      cookie.date.push(acc, ts)
1974    case SCon{Chr{+c}, t}:
1975      (acc, ts) = st
1976      cookie.date.tokens(t, cookie.date.step(cookie.date.delim(c), c, acc, ts))
1977
1978def cookie.date.head(+s: String) -> Bool:
1979  match s:
1980    case SNil{}:
1981      False{}
1982    case SCon{Chr{+c}, t}:
1983      parse_u32.digit(c)
1984
1985# The digits at the start of s: (count, value, rest). d: s starts with a digit.
1986def cookie.date.run(s: String, d: Bool, +n: U32, +acc: U32) -> U32 & U32 & String:
1987  match s:
1988    case SNil{}:
1989      (n, acc, SNil{})
1990    case SCon{Chr{+c}, +t}:
1991      match d:
1992        case True{}:
1993          cookie.date.run(t, cookie.date.head(t), (n + 1 : U32), (acc * 10 + (c - 48 : U32) : U32))
1994        case False{}:
1995          (n, acc, SCon{Chr{c}, t})
1996
1997def cookie.date.within(r: U32 & U32 & String, +lo: U32, +hi: U32) -> Maybe<&1, U32 & String>:
1998  (+n, v, rest) = r
1999  Bool.pick(Maybe<&1, U32 & String>, Bool.and(U32.is_ge(n, lo), U32.is_le(n, hi)), Some{(v, rest)}, None{})
2000
2001# lo to hi digits and what follows them, which does not start with a digit.
2002def cookie.date.num(+s: String, +lo: U32, +hi: U32) -> Maybe<&1, U32 & String>:
2003  cookie.date.within(cookie.date.run(s, cookie.date.head(s), 0, 0), lo, hi)
2004
2005def cookie.date.val(m: Maybe<&1, U32 & String>) -> Maybe<&2, U32>:
2006  match m:
2007    case None{}:
2008      None{}
2009    case Some{(v, t)}:
2010      Some{v}
2011
2012def cookie.date.colon(s: String) -> Maybe<&2, String>:
2013  match s:
2014    case SNil{}:
2015      None{}
2016    case SCon{Chr{58}, t}:
2017      Some{t}
2018    case SCon{Chr{c}, t}:
2019      None{}
2020
2021def cookie.date.sec(+h: U32, +m: U32, r: Maybe<&1, U32 & String>) -> Maybe<&2, Hms>:
2022  match r:
2023    case None{}:
2024      None{}
2025    case Some{(s, t)}:
2026      Some{Hms{h, m, s}}
2027
2028def cookie.date.min.c(+h: U32, +m: U32, c: Maybe<&2, String>) -> Maybe<&2, Hms>:
2029  match c:
2030    case None{}:
2031      None{}
2032    case Some{+t}:
2033      cookie.date.sec(h, m, cookie.date.num(t, 1, 2))
2034
2035def cookie.date.min(+h: U32, r: Maybe<&1, U32 & String>) -> Maybe<&2, Hms>:
2036  match r:
2037    case None{}:
2038      None{}
2039    case Some{(m, t)}:
2040      cookie.date.min.c(h, m, cookie.date.colon(t))
2041
2042def cookie.date.hour.c(+h: U32, c: Maybe<&2, String>) -> Maybe<&2, Hms>:
2043  match c:
2044    case None{}:
2045      None{}
2046    case Some{+t}:
2047      cookie.date.min(h, cookie.date.num(t, 1, 2))
2048
2049def cookie.date.hour(r: Maybe<&1, U32 & String>) -> Maybe<&2, Hms>:
2050  match r:
2051    case None{}:
2052      None{}
2053    case Some{(h, t)}:
2054      cookie.date.hour.c(h, cookie.date.colon(t))
2055
2056# hms-time: 1*2DIGIT ":" 1*2DIGIT ":" 1*2DIGIT, then anything but a digit.
2057def cookie.date.time(+tok: String) -> Maybe<&2, Hms>:
2058  cookie.date.hour(cookie.date.num(tok, 1, 2))
2059
2060def cookie.date.month.go(xs: List<&2, String>, +w: String, +i: U32) -> Maybe<&2, U32>:
2061  match xs:
2062    case Nil{}:
2063      None{}
2064    case Con{x, t}:
2065      Bool.pick(Maybe<&2, U32>, String.eq(x, w), Some{i}, cookie.date.month.go(t, w, (i + 1 : U32)))
2066
2067# The month named by the first three letters, from 1.
2068def cookie.date.month(+tok: String) -> Maybe<&2, U32>:
2069  cookie.date.month.go(["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"], String.to_lower(String.take(tok, 3n)), 1)
2070
2071# Each try* below: the flag is set, so go on; or the token matches, so stop; or go on.
2072def cookie.date.year(y: Maybe<&2, U32>, +tok: String, t: Maybe<&2, Hms>, d: Maybe<&2, U32>, m: Maybe<&2, U32>) -> Cdate:
2073  match y:
2074    case None{}:
2075      Cdate{t, d, m, cookie.date.val(cookie.date.num(tok, 2, 4))}
2076    case Some{v}:
2077      Cdate{t, d, m, Some{v}}
2078
2079def cookie.date.month.got(g: Maybe<&2, U32>, +tok: String, t: Maybe<&2, Hms>, d: Maybe<&2, U32>, y: Maybe<&2, U32>) -> Cdate:
2080  match g:
2081    case None{}:
2082      cookie.date.year(y, tok, t, d, None{})
2083    case Some{v}:
2084      Cdate{t, d, Some{v}, y}
2085
2086def cookie.date.month.try(m: Maybe<&2, U32>, +tok: String, t: Maybe<&2, Hms>, d: Maybe<&2, U32>, y: Maybe<&2, U32>) -> Cdate:
2087  match m:
2088    case None{}:
2089      cookie.date.month.got(cookie.date.month(tok), tok, t, d, y)
2090    case Some{v}:
2091      cookie.date.year(y, tok, t, d, Some{v})
2092
2093def cookie.date.day.got(g: Maybe<&2, U32>, +tok: String, t: Maybe<&2, Hms>, m: Maybe<&2, U32>, y: Maybe<&2, U32>) -> Cdate:
2094  match g:
2095    case None{}:
2096      cookie.date.month.try(m, tok, t, None{}, y)
2097    case Some{v}:
2098      Cdate{t, Some{v}, m, y}
2099
2100def cookie.date.day.try(d: Maybe<&2, U32>, +tok: String, t: Maybe<&2, Hms>, m: Maybe<&2, U32>, y: Maybe<&2, U32>) -> Cdate:
2101  match d:
2102    case None{}:
2103      cookie.date.day.got(cookie.date.val(cookie.date.num(tok, 1, 2)), tok, t, m, y)
2104    case Some{v}:
2105      cookie.date.month.try(m, tok, t, Some{v}, y)
2106
2107def cookie.date.time.got(g: Maybe<&2, Hms>, +tok: String, d: Maybe<&2, U32>, m: Maybe<&2, U32>, y: Maybe<&2, U32>) -> Cdate:
2108  match g:
2109    case None{}:
2110      cookie.date.day.try(d, tok, None{}, m, y)
2111    case Some{v}:
2112      Cdate{Some{v}, d, m, y}
2113
2114def cookie.date.time.try(t: Maybe<&2, Hms>, +tok: String, d: Maybe<&2, U32>, m: Maybe<&2, U32>, y: Maybe<&2, U32>) -> Cdate:
2115  match t:
2116    case None{}:
2117      cookie.date.time.got(cookie.date.time(tok), tok, d, m, y)
2118    case Some{v}:
2119      cookie.date.day.try(d, tok, Some{v}, m, y)
2120
2121def cookie.date.fold(ts: List<&2, String>, st: Cdate) -> Cdate:
2122  match ts:
2123    case Nil{}:
2124      st
2125    case Con{+tok, rest}:
2126      Cdate{t, d, m, y} = st
2127      cookie.date.fold(rest, cookie.date.time.try(t, tok, d, m, y))
2128
2129# 70–99 are 19xx, 0–69 are 20xx.
2130def cookie.date.fix(+y: U32) -> U32:
2131  Bool.pick(U32, U32.is_le(y, 69), (y + 2000 : U32), Bool.pick(U32, U32.is_le(y, 99), (y + 1900 : U32), y))
2132
2133def cookie.date.at(+y: U32, +d: U32, mo: U32, h: U32, mi: U32, s: U32) -> Maybe<&2, Time.Instant>:
2134  Bool.pick(Maybe<&2, Time.Instant>, Bool.and(U32.is_ge(y, 1601), Bool.and(U32.is_ge(d, 1), U32.is_le(d, 31))), Time.mk(Time.DateTime{Time.Date{y, mo, d}, h, mi, s, 0}), None{})
2135
2136def cookie.date.fin(st: Cdate) -> Maybe<&2, Time.Instant>:
2137  match st:
2138    case Cdate{Some{Hms{h, mi, s}}, Some{d}, Some{mo}, Some{y}}:
2139      cookie.date.at(cookie.date.fix(y), d, mo, h, mi, s)
2140    case _:
2141      None{}
2142
2143# §5.1.1: a cookie-date such as "Sun, 06 Nov 1994 08:49:37 GMT" or "Thu, 01-Jan-70 00:00:01 GMT".
2144# Time.mk refuses a day past the month's end and a time past 23:59:59.
2145def cookie.date(s: String) -> Maybe<&2, Time.Instant>:
2146  cookie.date.fin(cookie.date.fold(List.reverse(&2, String, cookie.date.tokens(s, (SNil{}, Nil{}))), Cdate{None{}, None{}, None{}, None{}}))
2147
2148# §5.6.1–§5.6.7: the last of each attribute. expires is the date as sent; max_age is capped seconds.
2149# Neither is a time from now yet: a Cav with a Time.Instant and now beside it is too wide (bendlang/bend#1069).
2150type Cav is Data:
2151  Cav{expires: Maybe<&2, Time.Instant>, max_age: Maybe<&2, U32>, domain: String, path: Maybe<&2, String>, secure: Bool, http_only: Bool, same_site: String}
2152
2153def cookie.cav() -> Cav:
2154  Cav{None{}, None{}, "", None{}, False{}, False{}, "default"}
2155
2156# §5.5: 400 days, the longest a cookie lives.
2157def cookie.limit() -> U32:
2158  34560000
2159
2160def cookie.later(+now: Time.Instant, +secs: U32) -> Time.Instant:
2161  Time.Instant.add(now, Time.Duration.of_secs(Int.I64.from_u32(secs)))
2162
2163def cookie.expires.cap(+now: Time.Instant, m: Maybe<&2, Time.Instant>) -> Maybe<&2, Time.Instant>:
2164  match m:
2165    case None{}:
2166      None{}
2167    case Some{+t}:
2168      +lim = cookie.later(now, cookie.limit())
2169      Some{Bool.pick(Time.Instant, Cmp.is_lt(Time.Instant.cmp(lim, t)), lim, t)}
2170
2171def cookie.max_age.zero(m: Maybe<&2, U32>) -> Maybe<&2, U32>:
2172  match m:
2173    case None{}:
2174      None{}
2175    case Some{s}:
2176      Some{0}
2177
2178def cookie.max_age.nz(s: String) -> String:
2179  match s:
2180    case SNil{}:
2181      SNil{}
2182    case SCon{Chr{48}, t}:
2183      cookie.max_age.nz(t)
2184    case SCon{Chr{c}, t}:
2185      SCon{Chr{c}, t}
2186
2187# More than 9 significant digits is past the limit (and would overflow parse_u32).
2188def cookie.max_age.cap(long: Bool, m: Maybe<&2, U32>) -> Maybe<&2, U32>:
2189  match m:
2190    case None{}:
2191      None{}
2192    case Some{s}:
2193      Some{Bool.pick(U32, long, cookie.limit(), s)}
2194
2195def cookie.max_age.secs(+v: String, neg: Bool) -> Maybe<&2, U32>:
2196  match neg:
2197    case True{}:
2198      cookie.max_age.zero(parse_u32(String.drop(v, 1n)))
2199    case False{}:
2200      cookie.max_age.cap(cookie.over(cookie.max_age.nz(v), 9), parse_u32(v))
2201
2202# Zero or less is the earliest time, so the cookie is already expired.
2203def cookie.max_age.at(+now: Time.Instant, m: Maybe<&2, U32>) -> Maybe<&2, Time.Instant>:
2204  match m:
2205    case None{}:
2206      None{}
2207    case Some{+s}:
2208      Some{Bool.pick(Time.Instant, U32.is_eq(s, 0), Time.Instant.epoch(), cookie.later(now, U32.min(s, cookie.limit())))}
2209
2210# §5.6.2: DIGIT*, or "-" and DIGIT*. Anything else is ignored.
2211def cookie.max_age(+v: String) -> Maybe<&2, U32>:
2212  cookie.max_age.secs(v, String.starts_with(v, "-"))
2213
2214def cookie.same_site(+v: String) -> String:
2215  +l = String.to_lower(v)
2216  Bool.pick(String, Bool.or(String.eq(l, "strict"), Bool.or(String.eq(l, "lax"), String.eq(l, "none"))), l, "default")
2217
2218type Av is Data:
2219  AvExpires{}
2220  AvMaxAge{}
2221  AvDomain{}
2222  AvPath{}
2223  AvSecure{}
2224  AvHttpOnly{}
2225  AvSameSite{}
2226  AvOther{}
2227
2228def cookie.av.kind(+k: String) -> Av:
2229  Bool.pick(Av, String.eq(k, "expires"), AvExpires{}, Bool.pick(Av, String.eq(k, "max-age"), AvMaxAge{}, Bool.pick(Av, String.eq(k, "domain"), AvDomain{}, Bool.pick(Av, String.eq(k, "path"), AvPath{}, Bool.pick(Av, String.eq(k, "secure"), AvSecure{}, Bool.pick(Av, String.eq(k, "httponly"), AvHttpOnly{}, Bool.pick(Av, String.eq(k, "samesite"), AvSameSite{}, AvOther{})))))))
2230
2231# An Expires or Max-Age that does not parse leaves the earlier one. A leading dot of Domain is dropped.
2232def cookie.av.put(k: Av, a: Cav, +v: String) -> Cav:
2233  match k a:
2234    case AvExpires{} Cav{e, m, d, p, s, h, ss}:
2235      Cav{Maybe.or(&2, Time.Instant, cookie.date(v), e), m, d, p, s, h, ss}
2236    case AvMaxAge{} Cav{e, m, d, p, s, h, ss}:
2237      Cav{e, Maybe.or(&2, U32, cookie.max_age(v), m), d, p, s, h, ss}
2238    case AvDomain{} Cav{e, m, d, p, s, h, ss}:
2239      Cav{e, m, String.to_lower(Bool.pick(String, String.starts_with(v, "."), String.drop(v, 1n), v)), p, s, h, ss}
2240    case AvPath{} Cav{e, m, d, p, s, h, ss}:
2241      Cav{e, m, d, Some{v}, s, h, ss}
2242    case AvSecure{} Cav{e, m, d, p, s, h, ss}:
2243      Cav{e, m, d, p, True{}, h, ss}
2244    case AvHttpOnly{} Cav{e, m, d, p, s, h, ss}:
2245      Cav{e, m, d, p, s, True{}, ss}
2246    case AvSameSite{} Cav{e, m, d, p, s, h, ss}:
2247      Cav{e, m, d, p, s, h, cookie.same_site(v)}
2248    case AvOther{} Cav{e, m, d, p, s, h, ss}:
2249      Cav{e, m, d, p, s, h, ss}
2250
2251# §5.6: name and value trimmed; a value over 1024 octets drops the attribute.
2252def cookie.av(+a: Cav, kv: String & String & Bool) -> Cav:
2253  (k, v, found) = kv
2254  +tv = trim(v)
2255  Bool.pick(Cav, cookie.over(tv, 1024), a, cookie.av.put(cookie.av.kind(String.to_lower(trim(k))), a, tv))
2256
2257def cookie.avs(xs: List<&2, String>, a: Cav) -> Cav:
2258  match xs:
2259    case Nil{}:
2260      a
2261    case Con{x, t}:
2262      cookie.avs(t, cookie.av(a, cookie.cut(x, 61)))
2263
2264# §5.6: with no "=", the name is empty and the pair is the value.
2265def cookie.nv(r: String & String & Bool) -> String & String:
2266  (a, b, found) = r
2267  match found:
2268    case True{}:
2269      (trim(a), trim(b))
2270    case False{}:
2271      ("", trim(a))
2272
2273def cookie.prefixed(+s: String, +p: String) -> Bool:
2274  String.starts_with(String.to_lower(s), p)
2275
2276# §5.7 steps 8–10: (domain, host-only), or None to ignore the cookie.
2277# ponytail: the public-suffix check knows single-label suffixes only (com, org, localhost). Multi-label
2278# ones (co.uk, github.io) need the publicsuffix.org list; ship it as data when a caller needs it.
2279def cookie.domain.of(+host: String, +d: String) -> Maybe<&1, String & Bool>:
2280  +suffix = Bool.and(Bool.not(String.is_empty(d)), Bool.not(String.contains(d, ".")))
2281  +d2 = Bool.pick(String, Bool.and(suffix, String.eq(d, host)), "", d)
2282  Bool.pick(Maybe<&1, String & Bool>, Bool.or(Bool.and(suffix, Bool.not(String.eq(d, host))), Bool.not(cookie.ascii(d))), None{},
2283    Bool.pick(Maybe<&1, String & Bool>, String.is_empty(d2), Some{(host, True{})},
2284      Bool.pick(Maybe<&1, String & Bool>, cookie.domain_match(host, d2), Some{(d2, False{})}, None{})))
2285
2286def cookie.path.of(p: Maybe<&2, String>, +req: String) -> String:
2287  match p:
2288    case None{}:
2289      cookie.default_path(req)
2290    case Some{+v}:
2291      Bool.pick(String, String.starts_with(v, "/"), v, cookie.default_path(req))
2292
2293# §5.7 steps 12–20: Secure needs https; SameSite=None needs Secure; the __Secure- and __Host- prefixes.
2294def cookie.make.dm(dm: Maybe<&1, String & Bool>, +name: String, +value: String, +path: String, has_path: Bool, +secure: Bool, http_only: Bool, +same_site: String, expiry: Maybe<&2, Time.Instant>, https: Bool) -> Maybe<&2, Cookie>:
2295  match dm:
2296    case None{}:
2297      None{}
2298    case Some{(domain, +host_only)}:
2299      +host = Bool.and(Bool.and(secure, host_only), Bool.and(has_path, String.eq(path, "/")))
2300      +bad = Bool.or(Bool.or(Bool.and(secure, Bool.not(https)), Bool.and(String.eq(same_site, "none"), Bool.not(secure))),
2301        Bool.or(Bool.or(Bool.and(cookie.prefixed(name, "__secure-"), Bool.not(secure)), Bool.and(cookie.prefixed(name, "__host-"), Bool.not(host))),
2302          Bool.and(String.is_empty(name), Bool.or(cookie.prefixed(value, "__secure-"), cookie.prefixed(value, "__host-")))))
2303      Bool.pick(Maybe<&2, Cookie>, bad, None{}, Some{Cookie{name, value, domain, host_only, path, secure, http_only, same_site, expiry}})
2304
2305# Max-Age wins over Expires, whatever their order (§5.7 step 6). Both count from now.
2306def cookie.expiry(+now: Time.Instant, m: Maybe<&2, U32>, e: Maybe<&2, Time.Instant>) -> Maybe<&2, Time.Instant>:
2307  Maybe.or(&2, Time.Instant, cookie.max_age.at(now, m), cookie.expires.cap(now, e))
2308
2309def cookie.make(+now: Time.Instant, a: Url.Abs, +name: String, +value: String, c: Cav) -> Maybe<&2, Cookie>:
2310  Url.Abs{scheme, host, port, target} = a
2311  Cav{e, m, d, +p, secure, http_only, same_site} = c
2312  cookie.make.dm(cookie.domain.of(host, d), name, value, cookie.path.of(p, cookie.target_path(target)), Maybe.is_some(&2, String, p), secure, http_only, same_site, cookie.expiry(now, m, e), String.eq(scheme, "https"))
2313
2314# An empty name and value, or more than 4096 octets of them, is ignored.
2315def cookie.parse.nv(+now: Time.Instant, a: Url.Abs, nv: String & String, avs: List<&2, String>) -> Maybe<&2, Cookie>:
2316  (+name, +value) = nv
2317  Bool.pick(Maybe<&2, Cookie>, Bool.or(Bool.and(String.is_empty(name), String.is_empty(value)), cookie.over(name ++ value, 4096)), None{}, cookie.make(now, a, name, value, cookie.avs(avs, cookie.cav())))
2318
2319def cookie.parse.go(+now: Time.Instant, a: Url.Abs, xs: List<&2, String>) -> Maybe<&2, Cookie>:
2320  match xs:
2321    case Nil{}:
2322      None{}
2323    case Con{first, avs}:
2324      cookie.parse.nv(now, a, cookie.nv(cookie.cut(first, 61)), avs)
2325
2326# §5.6 and §5.7: one Set-Cookie value received from a at now, or None when it is ignored.
2327def cookie.parse(+now: Time.Instant, a: Url.Abs, +line: String) -> Maybe<&2, Cookie>:
2328  Bool.pick(Maybe<&2, Cookie>, cookie.ctl(line), None{}, cookie.parse.go(now, a, String.split(line, ';')))
2329
2330def cookie.https(a: Url.Abs) -> Bool:
2331  Url.Abs{scheme, host, port, target} = a
2332  String.eq(scheme, "https")
2333
2334def cookie.secure(c: Cookie) -> Bool:
2335  Cookie{name, value, domain, host_only, path, secure, http_only, same_site, expiry} = c
2336  secure
2337
2338# Same name, domain, host-only flag and path: the new cookie replaces the old one.
2339def cookie.same(+a: Cookie, +b: Cookie) -> Bool:
2340  Cookie{n1, v1, d1, h1, p1, s1, o1, ss1, e1} = a
2341  Cookie{n2, v2, d2, h2, p2, s2, o2, ss2, e2} = b
2342  Bool.and(Bool.and(String.eq(n1, n2), String.eq(d1, d2)), Bool.and(Bool.not(Bool.xor(h1, h2)), String.eq(p1, p2)))
2343
2344# §5.7 step 16: a secure cookie that a new cookie from plain http must not overlay.
2345def cookie.shadows(+old: Cookie, +c: Cookie) -> Bool:
2346  Cookie{n1, v1, +d1, h1, p1, s1, o1, ss1, e1} = old
2347  Cookie{n2, v2, +d2, h2, p2, s2, o2, ss2, e2} = c
2348  Bool.and(Bool.and(String.eq(n1, n2), s1), Bool.and(Bool.or(cookie.domain_match(d1, d2), cookie.domain_match(d2, d1)), cookie.path_match(p2, p1)))
2349
2350def cookie.shadowed(cs: List<&2, Cookie>, +c: Cookie) -> Bool:
2351  match cs:
2352    case Nil{}:
2353      False{}
2354    case Con{+o, t}:
2355      Bool.or(cookie.shadows(o, c), cookie.shadowed(t, c))
2356
2357# cs with the cookie c replaces swapped for c (keeping its place, so its creation order), or c last.
2358# A c that is not live only removes the old one: that is how a server deletes a cookie.
2359def cookie.put(cs: List<&2, Cookie>, +c: Cookie, +live: Bool) -> List<&2, Cookie>:
2360  match cs:
2361    case Nil{}:
2362      Bool.pick(List<&2, Cookie>, live, [c], Nil{})
2363    case Con{+o, +t}:
2364      Bool.pick(List<&2, Cookie>, cookie.same(o, c), Bool.pick(List<&2, Cookie>, live, Con{c, t}, t), Con{o, cookie.put(t, c, live)})
2365
2366def jar.put.c(m: Maybe<&2, Cookie>, j: Jar, +https: Bool) -> Jar:
2367  match m:
2368    case None{}:
2369      Jar{now, cs} = j
2370      Jar{now, cs}
2371    case Some{+c}:
2372      Jar{+now, +cs} = j
2373      Jar{now, Bool.pick(List<&2, Cookie>, Bool.and(Bool.not(Bool.or(https, cookie.secure(c))), cookie.shadowed(cs, c)), cs, cookie.put(cs, c, cookie.live(now, c)))}
2374
2375def jar.put.one(j: Jar, +a: Url.Abs, x: String) -> Jar:
2376  Jar{+now, cs} = j
2377  jar.put.c(cookie.parse(now, a, x), Jar{now, cs}, cookie.https(a))
2378
2379def jar.put.all(xs: List<&2, String>, j: Jar, +a: Url.Abs) -> Jar:
2380  match xs:
2381    case Nil{}:
2382      j
2383    case Con{x, t}:
2384      jar.put.all(t, jar.put.one(j, a, x), a)
2385
2386# Every set-cookie field of h, in order, as received from a.
2387def jar.store.abs(j: Jar, +a: Url.Abs, +h: Map<&2, List<&2, String>>) -> Jar:
2388  jar.put.all(fields(h, "set-cookie"), j, a)
2389
2390def jar.store.url(j: Jar, u: Maybe<&2, Url.Abs>, +h: Map<&2, List<&2, String>>) -> Jar:
2391  match u:
2392    case None{}:
2393      j
2394    case Some{+a}:
2395      jar.store.abs(j, a, h)
2396
2397# The jar after res came from url, and res as it was. Header names are lowercase, as parse gives them.
2398# An unparsable url stores nothing.
2399def jar.store(j: Jar, url: String, res: Res) -> Jar & Res:
2400  Res{status, +headers, body} = res
2401  (jar.store.url(j, Url.absolute(url), headers), Res{status, headers, body})
2402
2403# §5.8.3: domain (exact when host-only), path, and Secure only over https.
2404def cookie.sends(+host: String, +path: String, +https: Bool, +c: Cookie) -> Bool:
2405  Cookie{n, v, +d, +ho, +p, s, o, ss, e} = c
2406  Bool.and(Bool.pick(Bool, ho, String.eq(host, d), cookie.domain_match(host, d)), Bool.and(cookie.path_match(path, p), Bool.or(Bool.not(s), https)))
2407
2408def cookie.pick(cs: List<&2, Cookie>, +host: String, +path: String, +https: Bool) -> List<&2, Cookie>:
2409  match cs:
2410    case Nil{}:
2411      Nil{}
2412    case Con{+c, t}:
2413      List.filter.put(Cookie, c, cookie.pick(t, host, path, https), cookie.sends(host, path, https, c))
2414
2415# The sort order of §5.8.3: longer paths first; the stable sort keeps creation order among equals.
2416def cookie.longer(a: Cookie, b: Cookie) -> Bool:
2417  Cookie{n1, v1, d1, h1, p1, s1, o1, ss1, e1} = a
2418  Cookie{n2, v2, d2, h2, p2, s2, o2, ss2, e2} = b
2419  Bool.not(Nat.is_lt(String.length(p1), String.length(p2)))
2420
2421def cookie.pair(c: Cookie) -> String:
2422  Cookie{+n, +v, d, h, p, s, o, ss, e} = c
2423  Bool.pick(String, String.is_empty(n), v, n ++ "=" ++ v)
2424
2425def cookie.pairs(cs: List<&2, Cookie>) -> List<&2, String>:
2426  match cs:
2427    case Nil{}:
2428      Nil{}
2429    case Con{c, t}:
2430      Con{cookie.pair(c), cookie.pairs(t)}
2431
2432# §5.8.3: the cookie-string for a request to a, or "" when no cookie matches.
2433def jar.string(j: Jar, a: Url.Abs) -> String:
2434  Jar{now, cs} = j
2435  Url.Abs{scheme, +host, port, target} = a
2436  String.join(cookie.pairs(List.sort(~Cookie, ~cookie.longer, cookie.pick(cs, host, cookie.target_path(target), String.eq(scheme, "https")))), "; ")
2437
2438# One cookie field: the caller's own cookie values first, then the jar's.
2439def jar.header(+h: Map<&2, List<&2, String>>, +s: String) -> Map<&2, List<&2, String>>:
2440  +old = String.join(fields(h, "cookie"), "; ")
2441  Bool.pick(Map<&2, List<&2, String>>, String.is_empty(s), h, set(h, "cookie", Bool.pick(String, String.is_empty(old), s, old ++ "; " ++ s)))
2442
2443def jar.apply.url(j: Jar, u: Maybe<&2, Url.Abs>, +h: Map<&2, List<&2, String>>) -> Map<&2, List<&2, String>>:
2444  match u:
2445    case None{}:
2446      h
2447    case Some{a}:
2448      jar.header(h, jar.string(j, a))
2449
2450# The headers with the jar's cookies for a request to url in their cookie field (lowercase, as fetch
2451# sends names). An unparsable url adds nothing.
2452def jar.apply(j: Jar, url: String, +h: Map<&2, List<&2, String>>) -> Map<&2, List<&2, String>>:
2453  jar.apply.url(j, Url.absolute(url), h)
2454
2455# The jar, if any, that a fetch threads through its hops.
2456def jar.opt.apply(m: Maybe<&2, Jar>, a: Url.Abs, +h: Map<&2, List<&2, String>>) -> Map<&2, List<&2, String>>:
2457  match m:
2458    case None{}:
2459      h
2460    case Some{j}:
2461      jar.header(h, jar.string(j, a))
2462
2463def jar.opt.res(j: Jar, +a: Url.Abs, r: Result<&1, &1, Err, Res>) -> Maybe<&2, Jar> & Result<&1, &1, Err, Res>:
2464  match r:
2465    case Fail{e}:
2466      (Some{j}, Fail{e})
2467    case Done{res}:
2468      Res{status, +headers, body} = res
2469      (Some{jar.store.abs(j, a, headers)}, Done{Res{status, headers, body}})
2470
2471def jar.opt.store(m: Maybe<&2, Jar>, +a: Url.Abs, r: Result<&1, &1, Err, Res>) -> Maybe<&2, Jar> & Result<&1, &1, Err, Res>:
2472  match m:
2473    case None{}:
2474      (None{}, r)
2475    case Some{j}:
2476      jar.opt.res(j, a, r)
2477
2478def io.recv.words(tls: Bool, s: Socket, max: U32, ms: U32) -> IO(Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>):
2479  match tls:
2480    case True{}:
2481      Wire.tls.recv.words(s, max, ms)
2482    case False{}:
2483      Wire.recv.words(s, max, ms)
2484
2485def io.send.words(tls: Bool, s: Socket, +len: U32, buf: Array<U32>) -> IO(Socket & Result<&1, &1, U32 & String, Unit>):
2486  match tls:
2487    case True{}:
2488      Wire.tls.send.words(s, len, buf)
2489    case False{}:
2490      Wire.send.words(s, len, buf)
2491
2492def io.send.bytes(tls: Bool, s: Socket, b: Bytes.Bytes) -> IO(Socket & Result<&1, &1, U32 & String, Unit>):
2493  Bytes.Bytes{+len, buf} = b
2494  io.send.words(tls, s, len, buf)
2495
2496def io.close(tls: Bool, s: Socket) -> IO(Unit):
2497  match tls:
2498    case True{}:
2499      Wire.tls.close(s)
2500    case False{}:
2501      Socket.close(s)
2502
2503def fetch.close(tls: Bool, s: Socket, r: Result<&1, &1, Err, Res>) -> IO(Result<&1, &1, Err, Res>):
2504  do IO<Result<&1, &1, Err, Res>>:
2505    io.close(tls, s)
2506    return r
2507
2508# none: no response byte arrived, so an idempotent request may be retried (RFC 9112 §9.3.1).
2509# sock: the socket, when it can take another request.
2510type Out is Type:
2511  OutDone{res: Res, sock: Maybe<&1, Socket>, rest: Bytes.Bytes}
2512  OutFail{e: Err, none: Bool}
2513
2514def fetch.boxed(r: Result<&1, &1, Err, Res>, none: Bool) -> Out:
2515  match r:
2516    case Done{res}:
2517      OutDone{res, None{}, Bytes.new(0)}
2518    case Fail{e}:
2519      OutFail{e, none}
2520
2521def fetch.bad(tls: Bool, s: Socket, e: Maybe<&2, Err>) -> IO(Result<&1, &1, Err, Res>):
2522  match e:
2523    case None{}:
2524      fetch.close(tls, s, Fail{ErrBad{}})
2525    case Some{err}:
2526      fetch.close(tls, s, Fail{err})
2527
2528def fetch.shut(tls: Bool, s: Socket, r: Result<&1, &1, Err, Res>, none: Bool) -> IO(Out):
2529  do IO<Out>:
2530    x : Result<&1, &1, Err, Res> <- fetch.close(tls, s, r)
2531    return fetch.boxed(x, none)
2532
2533def fetch.hold.go(tls: Bool, s: Socket, res: Res, left: Maybe<&1, Bytes.Bytes>) -> IO(Out):
2534  match left:
2535    case Some{x}:
2536      IO.pure(Out, OutDone{res, Some{s}, x})
2537    case None{}:
2538      fetch.shut(tls, s, Done{res}, False{})
2539
2540def fetch.hold(tls: Bool, close: Bool, s: Socket, res: Res, left: Maybe<&1, Bytes.Bytes>) -> IO(Out):
2541  Res{status, +headers, body} = res
2542  fetch.hold.go(tls, s, Res{status, headers, body}, again(close, headers, left))
2543
2544def fetch.failout(tls: Bool, s: Socket, e: Maybe<&2, Err>, none: Bool) -> IO(Out):
2545  do IO<Out>:
2546    r : Result<&1, &1, Err, Res> <- fetch.bad(tls, s, e)
2547    return fetch.boxed(r, none)
2548
2549# Read state: the response so far and the bytes read, or how it ended.
2550# none: no byte arrived, so an idempotent request may be retried.
2551type Fl is Type:
2552  FlMore{rv: Rv, n: U32}
2553  FlBad{err: Maybe<&2, Err>, none: Bool}
2554  FlDone{res: Res, rest: Maybe<&1, Bytes.Bytes>}
2555
2556def fetch.rt(+n: U32, t: Rt) -> Fl:
2557  match t:
2558    case RtMore{rv}:
2559      FlMore{rv, n}
2560    case RtBad{}:
2561      FlBad{None{}, U32.is_zero(n)}
2562    case RtDone{res, rest}:
2563      FlDone{res, rest}
2564
2565# 64 KiB of head past the body cap, as serve allows.
2566def fetch.over(+n: U32) -> Bool:
2567  Nat.is_lt(Nat.add(fetch.max(), 65536n), U32.to_nat(n))
2568
2569def fetch.piece.cap(over: Bool, +head: Bool, rv: Rv, +n2: U32, +len: U32, buf: Array<U32>) -> Fl:
2570  match over:
2571    case True{}:
2572      FlBad{None{}, False{}}
2573    case False{}:
2574      fetch.rt(n2, rv.step(U32.is_zero(len), head, rv, Bytes.Bytes{len, buf}))
2575
2576def fetch.piece(+head: Bool, rv: Rv, +n: U32, p: U32 & Array<U32>) -> Fl:
2577  (+len, buf) = p
2578  +n2 = (n + len : U32)
2579  fetch.piece.cap(fetch.over(n2), head, rv, n2, len, buf)
2580
2581def fetch.next(+head: Bool, rv: Rv, +n: U32, m: Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>) -> Socket & Fl:
2582  (s, r) = m
2583  match r:
2584    case Fail{(+code, why)}:
2585      (s, FlBad{Some{err.or_late(code, ErrRead{code, why})}, U32.is_zero(n)})
2586    case Done{p}:
2587      (s, fetch.piece(head, rv, n, p))
2588
2589# Reads until the response is whole or cannot be; an empty read means the server closed.
2590@unsafe
2591def fetch.loop(+close: Bool, +head: Bool, +tls: Bool, +ms: U32, st: Socket & Fl) -> IO(Out):
2592  (s, fl) = st
2593  match fl:
2594    case FlMore{rv, +n}:
2595      do IO<Out>:
2596        m : Socket & Result<&1, &1, U32 & String, U32 & Array<U32>> <- io.recv.words(tls, s, 65536, ms)
2597        fetch.loop(close, head, tls, ms, fetch.next(head, rv, n, m))
2598    case FlBad{err, none}:
2599      fetch.failout(tls, s, err, none)
2600    case FlDone{res, rest}:
2601      fetch.hold(tls, close, s, res, rest)
2602
2603def exchange.sent(+tls: Bool, +ms: U32, +close: Bool, +head: Bool, m: Socket & Result<&1, &1, U32 & String, Unit>) -> IO(Out):
2604  (s, r) = m
2605  match r:
2606    case Fail{(+code, why)}:
2607      fetch.shut(tls, s, Fail{err.or_late(code, ErrWrite{code, why})}, True{})
2608    case Done{u}:
2609      fetch.loop(close, head, tls, ms, (s, FlMore{rv.start(), 0}))
2610
2611def exchange.go(+tls: Bool, +ms: U32, +close: Bool, +head: Bool, s: Socket, wire: Bytes.Bytes) -> IO(Out):
2612  do IO<Out>:
2613    sent : Socket & Result<&1, &1, U32 & String, Unit> <- io.send.bytes(tls, s, wire)
2614    exchange.sent(tls, ms, close, head, sent)
2615
2616def exchange.tup(o: Out) -> Maybe<&1, Socket> & Result<&1, &1, Err, Res> & Bytes.Bytes:
2617  match o:
2618    case OutFail{e, none}:
2619      (None{}, Fail{e}, Bytes.new(0))
2620    case OutDone{res, sock, rest}:
2621      (sock, Done{res}, rest)
2622
2623# One request on an open socket. Some{socket}: it can take another request.
2624def exchange(+tls: Bool, +ms: U32, +close: Bool, +head: Bool, s: Socket, wire: Bytes.Bytes) -> IO(Maybe<&1, Socket> & Result<&1, &1, Err, Res> & Bytes.Bytes):
2625  do IO<Maybe<&1, Socket> & Result<&1, &1, Err, Res> & Bytes.Bytes>:
2626    o : Out <- exchange.go(tls, ms, close, head, s, wire)
2627    return exchange.tup(o)
2628
2629# Paths to a PEM client chain and its private key for mutual TLS.
2630type Cert is Data:
2631  Cert{chain: String, key: String}
2632
2633type Proxy is Data:
2634  ProxyDirect{}
2635  ProxyVia{host: String, port: U32, authorization: String}
2636
2637type Route is Data:
2638  RouteDirect{tls: Bool, host: String, port: U32, cert: Maybe<&2, Cert>}
2639  RouteProxy{tls: Bool, host: String, port: U32, sni: String,
2640    authority: String, authorization: String, cert: Maybe<&2, Cert>}
2641
2642# Connection pool: idle sockets by origin and client identity, newest first, at most cap per key.
2643# fetch uses a fresh pool per call.
2644
2645type Conn is Type:
2646  Conn{tls: Bool, s: Socket}
2647  ConnH2{s: Socket, client: H2.Client}
2648
2649type Send is Type:
2650  Send{method: String, target: String, authority: String,
2651    headers: Map<&2, List<&2, String>>, body: Bytes.Bytes}
2652
2653type H2Step is Type:
2654  H2Reply{s: Socket, reply: H2.Reply}
2655  H2Sent{client: H2.Client, events: List<&1, H2.ClientEvent>,
2656    sent: Result<&1, &1, Err, Socket>}
2657  H2Events{s: Socket, client: H2.Client, result: Result<&1, &1, Err, Maybe<&1, Res>>}
2658  H2Received{client: H2.Client,
2659    answer: Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>}
2660
2661type TunnelStep is Type:
2662  TunnelRead{s: Socket, raw: String}
2663  TunnelHead{s: Socket, raw: String, frame: Frame}
2664  TunnelGot{raw: String,
2665    answer: Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>}
2666
2667type Pool is Type:
2668  Pool{cap: U32, idle: Map<&1, List<&1, Conn>>}
2669
2670def pool.new.with(+cap: U32) -> Pool:
2671  Pool{cap, Map.new(&1, List<&1, Conn>)}
2672
2673# Up to 8 idle sockets per origin.
2674def pool.new() -> Pool:
2675  pool.new.with(8)
2676
2677def pool.key(+scheme: String, +host: String, +port: U32) -> String:
2678  scheme ++ "://" ++ host ++ ":" ++ U32.show(port)
2679
2680def pool.key.cert(+base: String, cert: Maybe<&2, Cert>) -> String:
2681  match cert:
2682    case None{}:
2683      base
2684    case Some{Cert{+chain, +key}}:
2685      base ++ "|cert:" ++ Nat.show(String.length(chain)) ++ ":" ++ chain
2686        ++ Nat.show(String.length(key)) ++ ":" ++ key
2687
2688def pool.take.of(+cap: U32, +key: String, r: Map<&1, List<&1, Conn>> & Maybe<&1, List<&1, Conn>>) -> Pool & Maybe<&1, Conn>:
2689  (m, got) = r
2690  match got:
2691    case None{}:
2692      (Pool{cap, m}, None{})
2693    case Some{xs}:
2694      match xs:
2695        case Nil{}:
2696          (Pool{cap, m}, None{})
2697        case Con{c, t}:
2698          (Pool{cap, Map.set(&1, List<&1, Conn>, m, key, t)}, Some{c})
2699
2700# The socket given back last.
2701def pool.take(p: Pool, +key: String) -> Pool & Maybe<&1, Conn>:
2702  Pool{+cap, idle} = p
2703  pool.take.of(cap, key, Map.pop(&1, List<&1, Conn>, idle, key))
2704
2705def conn.close(c: Conn) -> IO(Unit):
2706  match c:
2707    case Conn{tls, s}:
2708      io.close(tls, s)
2709    case ConnH2{s, client}:
2710      Wire.tls.close(s)
2711
2712# The first n sockets; the rest are closed.
2713def conns.cut(xs: List<&1, Conn>, n: Nat) -> IO(List<&1, Conn>):
2714  match xs:
2715    case Nil{}:
2716      IO.pure(List<&1, Conn>, Nil{})
2717    case Con{c, t}:
2718      match n:
2719        case 0n:
2720          do IO<List<&1, Conn>>:
2721            conn.close(c)
2722            conns.cut(t, 0n)
2723        case 1n+k:
2724          do IO<List<&1, Conn>>:
2725            r : List<&1, Conn> <- conns.cut(t, k)
2726            return c <> r
2727
2728def pool.give.of(+cap: U32, +key: String, c: Conn, limit: Nat,
2729    r: Map<&1, List<&1, Conn>> & Maybe<&1, List<&1, Conn>>) -> IO(Pool):
2730  (m, old) = r
2731  do IO<Pool>:
2732    xs : List<&1, Conn> <- conns.cut(c <> Maybe.default(&1, List<&1, Conn>, old, Nil{}), limit)
2733    return Pool{cap, Map.set(&1, List<&1, Conn>, m, key, xs)}
2734
2735# Past the limit (cap for HTTP/1.1, one session for HTTP/2), close the oldest idle connection.
2736def pool.give(p: Pool, +key: String, c: Conn) -> IO(Pool):
2737  Pool{+cap, idle} = p
2738  match c:
2739    case Conn{tls, s}:
2740      pool.give.of(cap, key, Conn{tls, s}, U32.to_nat(cap), Map.pop(&1, List<&1, Conn>, idle, key))
2741    case ConnH2{s, client}:
2742      pool.give.of(cap, key, ConnH2{s, client}, Bool.pick(Nat, U32.is_zero(cap), 0n, 1n),
2743        Map.pop(&1, List<&1, Conn>, idle, key))
2744
2745def pool.close.go(xs: List<&1, List<&1, Conn>>) -> IO(Unit):
2746  match xs:
2747    case Nil{}:
2748      IO.pure(Unit, Unit{})
2749    case Con{cs, t}:
2750      do IO<Unit>:
2751        none : List<&1, Conn> <- conns.cut(cs, 0n)
2752        pool.close.go(t)
2753
2754def pool.close(p: Pool) -> IO(Unit):
2755  Pool{cap, idle} = p
2756  pool.close.go(Map.values(&1, List<&1, Conn>, idle))
2757
2758# RFC 9110 §9.2.2
2759def pool.idempotent(+method: String) -> Bool:
2760  Bool.or(String.eq(method, "GET"), Bool.or(String.eq(method, "HEAD"), Bool.or(String.eq(method, "OPTIONS"), Bool.or(String.eq(method, "TRACE"), Bool.or(String.eq(method, "PUT"), String.eq(method, "DELETE"))))))
2761
2762def conn.tls(m: Socket & Result<&1, &1, U32 & String, Unit>) -> IO(Result<&1, &1, Err, Conn>):
2763  (s, r) = m
2764  match r:
2765    case Fail{(+code, why)}:
2766      do IO<Result<&1, &1, Err, Conn>>:
2767        Wire.tls.close(s)
2768        return Fail{err.or_late(code, ErrTls{code, why})}
2769    case Done{u}:
2770      IO.pure(Result<&1, &1, Err, Conn>, Done{Conn{True{}, s}})
2771
2772def conn.h2.sent(client: H2.Client, r: Socket & Result<&1, &1, U32 & String, Unit>) -> IO(Result<&1, &1, Err, Conn>):
2773  (s, sent) = r
2774  match sent:
2775    case Fail{(+code, why)}:
2776      do IO<Result<&1, &1, Err, Conn>>:
2777        Wire.tls.close(s)
2778        return Fail{err.or_late(code, ErrWrite{code, why})}
2779    case Done{u}:
2780      IO.pure(Result<&1, &1, Err, Conn>, Done{ConnH2{s, client}})
2781
2782def conn.h2.start(s: Socket, r: H2.Client & HBytes.Bytes) -> IO(Result<&1, &1, Err, Conn>):
2783  (client, HBytes.Bytes{len, buf}) = r
2784  do IO<Result<&1, &1, Err, Conn>>:
2785    sent : Socket & Result<&1, &1, U32 & String, Unit> <- Wire.tls.send.words(s, len, buf)
2786    conn.h2.sent(client, sent)
2787
2788def conn.tls.protocol(proto: String, s: Socket) -> IO(Result<&1, &1, Err, Conn>):
2789  match proto:
2790    case "h2":
2791      conn.h2.start(s, H2.client.start())
2792    case "http/1.1":
2793      IO.pure(Result<&1, &1, Err, Conn>, Done{Conn{True{}, s}})
2794    case "":
2795      IO.pure(Result<&1, &1, Err, Conn>, Done{Conn{True{}, s}})
2796    case other:
2797      do IO<Result<&1, &1, Err, Conn>>:
2798        Wire.tls.close(s)
2799        return Fail{ErrTls{71, "unsupported ALPN: " ++ other}}
2800
2801def conn.tls.alpn(m: Socket & Result<&1, &1, U32 & String, String>) -> IO(Result<&1, &1, Err, Conn>):
2802  (s, r) = m
2803  match r:
2804    case Fail{(+code, why)}:
2805      do IO<Result<&1, &1, Err, Conn>>:
2806        Wire.tls.close(s)
2807        return Fail{err.or_late(code, ErrTls{code, why})}
2808    case Done{proto}:
2809      conn.tls.protocol(proto, s)
2810
2811def conn.secure.no.cert(offer: Bool, s: Socket, host: String, +ms: U32) ->
2812    IO(Result<&1, &1, Err, Conn>):
2813  match offer:
2814    case True{}:
2815      do IO<Result<&1, &1, Err, Conn>>:
2816        hs : Socket & Result<&1, &1, U32 & String, String> <-
2817          Wire.tls.connect.alpn(s, host, ms, "h2,http/1.1")
2818        conn.tls.alpn(hs)
2819    case False{}:
2820      do IO<Result<&1, &1, Err, Conn>>:
2821        hs : Socket & Result<&1, &1, U32 & String, Unit> <- Wire.tls.connect(s, host, ms)
2822        conn.tls(hs)
2823
2824def conn.secure.tls(cert: Maybe<&2, Cert>, s: Socket, host: String, +ms: U32,
2825    offer: Bool) -> IO(Result<&1, &1, Err, Conn>):
2826  match cert:
2827    case None{}:
2828      conn.secure.no.cert(offer, s, host, ms)
2829    case Some{Cert{chain, key}}:
2830      do IO<Result<&1, &1, Err, Conn>>:
2831        hs : Socket & Result<&1, &1, U32 & String, Unit> <-
2832          Wire.tls.connect.cert(s, host, ms, chain, key)
2833        conn.tls(hs)
2834
2835# A failed handshake is an error, never plaintext.
2836def conn.secure(+ms: U32, sni: String, s: Socket, tls: Bool,
2837    cert: Maybe<&2, Cert>, offer: Bool) -> IO(Result<&1, &1, Err, Conn>):
2838  match tls:
2839    case False{}:
2840      IO.pure(Result<&1, &1, Err, Conn>, Done{Conn{False{}, s}})
2841    case True{}:
2842      conn.secure.tls(cert, s, sni, ms, offer)
2843
2844def conn.made(+ms: U32, sni: String, tls: Bool, cert: Maybe<&2, Cert>,
2845    offer: Bool, r: Result<&1, &1, U32 & String, Socket>) ->
2846    IO(Result<&1, &1, Err, Conn>):
2847  match r:
2848    case Fail{(+code, why)}:
2849      IO.pure(Result<&1, &1, Err, Conn>, Fail{err.or_late(code, ErrConnect{code, why})})
2850    case Done{s}:
2851      conn.secure(ms, sni, s, tls, cert, offer)
2852
2853def conn.open(+tls: Bool, +ms: U32, sni: String, ip: String, port: U32) ->
2854    IO(Result<&1, &1, Err, Conn>):
2855  do IO<Result<&1, &1, Err, Conn>>:
2856    c : Result<&1, &1, U32 & String, Socket> <- Wire.connect(ip, port, ms)
2857    conn.made(ms, sni, tls, None{}, False{}, c)
2858
2859# ponytail: addresses are tried in order, not raced; a broken first route can consume the step timeout.
2860type Dial is Type:
2861  Dial{port: U32, ms: U32, deadline: Nat, action: IO(Result<&1, &1, U32 & String, Socket>)}
2862
2863def conn.dial.time(+ip: String, +port: U32, +deadline: Nat, now: Nat, expired: Bool) ->
2864  IO(Result<&1, &1, U32 & String, Socket>):
2865  match expired:
2866    case True{}:
2867      IO.pure(Result<&1, &1, U32 & String, Socket>, Fail{(60, "connect timeout")})
2868    case False{}:
2869      Wire.connect(ip, port, U32.from_nat(Nat.sub(deadline, now)))
2870
2871def conn.dial.with(+ip: String, +port: U32, +ms: U32, +deadline: Nat, +now: Nat, unlimited: Bool) ->
2872  IO(Result<&1, &1, U32 & String, Socket>):
2873  match unlimited:
2874    case True{}:
2875      Wire.connect(ip, port, 0)
2876    case False{}:
2877      conn.dial.time(ip, port, deadline, now, Nat.is_le(deadline, now))
2878
2879def conn.dial.try(+ip: String, +port: U32, +ms: U32, +deadline: Nat) ->
2880  IO(Result<&1, &1, U32 & String, Socket>):
2881  do IO<Result<&1, &1, U32 & String, Socket>>:
2882    now : Nat <- IO.now()
2883    conn.dial.with(ip, port, ms, deadline, now, U32.is_zero(ms))
2884
2885def conn.dial.after(r: Result<&1, &1, U32 & String, Socket>, ip: String, +port: U32, +ms: U32, +deadline: Nat) ->
2886  IO(Result<&1, &1, U32 & String, Socket>):
2887  match r:
2888    case Done{s}:
2889      IO.pure(Result<&1, &1, U32 & String, Socket>, Done{s})
2890    case Fail{e}:
2891      conn.dial.try(ip, port, ms, deadline)
2892
2893def conn.dial.more(prev: IO(Result<&1, &1, U32 & String, Socket>), ip: String, +port: U32, +ms: U32, +deadline: Nat) ->
2894  IO(Result<&1, &1, U32 & String, Socket>):
2895  do IO<Result<&1, &1, U32 & String, Socket>>:
2896    r : Result<&1, &1, U32 & String, Socket> <- prev
2897    conn.dial.after(r, ip, port, ms, deadline)
2898
2899def conn.dial.fold(d: Dial, ip: String) -> Dial:
2900  Dial{+port, +ms, +deadline, action} = d
2901  Dial{port, ms, deadline, conn.dial.more(action, ip, port, ms, deadline)}
2902
2903def conn.dial.run(d: Dial) -> IO(Result<&1, &1, U32 & String, Socket>):
2904  Dial{port, ms, deadline, action} = d
2905  action
2906
2907def conn.dial.all(+port: U32, +ms: U32, +start: Nat, first: String, rest: List<&2, String>) ->
2908  IO(Result<&1, &1, U32 & String, Socket>):
2909  match rest:
2910    case Nil{}:
2911      Wire.connect(first, port, ms)
2912    case Con{ip, tail}:
2913      +deadline = Nat.add(start, U32.to_nat(ms))
2914      conn.dial.run(List.foldl(~&2, ~String, ~Dial, ~conn.dial.fold, Con{ip, tail},
2915        Dial{port, ms, deadline, Wire.connect(first, port, ms)}))
2916
2917def conn.open.all(+tls: Bool, +ms: U32, +host: String, +port: U32,
2918    ips: List<&2, String>, cert: Maybe<&2, Cert>, offer: Bool) ->
2919    IO(Result<&1, &1, Err, Conn>):
2920  match ips:
2921    case Nil{}:
2922      IO.pure(Result<&1, &1, Err, Conn>, Fail{ErrDns{}})
2923    case Con{addr, rest}:
2924      do IO<Result<&1, &1, Err, Conn>>:
2925        start : Nat <- IO.now()
2926        r : Result<&1, &1, U32 & String, Socket> <- conn.dial.all(port, ms, start, addr, rest)
2927        conn.made(ms, host, tls, cert, offer, r)
2928
2929def proxy.auth.safe(s: String) -> Bool:
2930  match s:
2931    case SNil{}:
2932      True{}
2933    case SCon{Chr{+c}, rest}:
2934      Bool.and(U32.is_ge(c, 32), Bool.and(U32.is_ne(c, 127), proxy.auth.safe(rest)))
2935
2936def proxy.auth.checked(+decoded: String, valid: Bool) -> Maybe<&2, String>:
2937  match valid:
2938    case False{}:
2939      None{}
2940    case True{}:
2941      Some{"Basic " ++ Bytes.to_base64(Bytes.from_string(decoded))}
2942
2943def proxy.auth.value(m: Maybe<&2, String>) -> Maybe<&2, String>:
2944  match m:
2945    case None{}:
2946      None{}
2947    case Some{+decoded}:
2948      proxy.auth.checked(decoded, Bool.and(Url.has(decoded, 58), proxy.auth.safe(decoded)))
2949
2950def proxy.from.abs(authorization: String, m: Maybe<&2, Url.Abs>) -> Maybe<&2, Proxy>:
2951  match m:
2952    case None{}:
2953      None{}
2954    case Some{Url.Abs{scheme, host, port, target}}:
2955      Some{ProxyVia{host, port, authorization}}
2956
2957def proxy.from.user(user: String, host: String) -> Maybe<&2, Proxy>:
2958  do Maybe<&2, Proxy>:
2959    authorization : String <- proxy.auth.value(Url.pct.decode(user))
2960    proxy.from.abs(authorization, Url.absolute("http://" ++ host))
2961
2962def proxy.from.authority(has_user: Bool, authority: String, split: String & String) ->
2963    Maybe<&2, Proxy>:
2964  match has_user:
2965    case False{}:
2966      proxy.from.abs("", Url.absolute("http://" ++ authority))
2967    case True{}:
2968      (user, host) = split
2969      proxy.from.user(user, host)
2970
2971def proxy.from.parts(parts: String & String) -> Maybe<&2, Proxy>:
2972  (+authority, path) = parts
2973  match path:
2974    case SNil{}:
2975      proxy.from.authority(Url.has(authority, 64), authority, Url.take_to(authority, 64))
2976    case other:
2977      None{}
2978
2979def proxy.from.url.if(valid: Bool, raw: String) -> Maybe<&2, Proxy>:
2980  match valid:
2981    case False{}:
2982      None{}
2983    case True{}:
2984      proxy.from.parts(Url.take_to(String.drop(raw, 7n), 47))
2985
2986def proxy.from.url(+raw: String) -> Maybe<&2, Proxy>:
2987  proxy.from.url.if(String.starts_with(String.to_lower(raw), "http://"), raw)
2988
2989def proxy.no.domain(+host: String, +suffix: String) -> Bool:
2990  Bool.or(String.eq(host, suffix), String.ends_with(host, "." ++ suffix))
2991
2992def proxy.no.suffix(+host: String, +raw: String) -> Bool:
2993  match raw:
2994    case SCon{Chr{46}, +suffix}:
2995      proxy.no.domain(host, suffix)
2996    case other:
2997      proxy.no.domain(host, raw)
2998
2999def proxy.no.port(valid: Bool, +host: String, suffix: String) -> Bool:
3000  match valid:
3001    case False{}:
3002      False{}
3003    case True{}:
3004      proxy.no.suffix(host, suffix)
3005
3006def proxy.no.named(+host: String, +port: U32, parts: String & String) -> Bool:
3007  (suffix, port_text) = parts
3008  match port_text:
3009    case SNil{}:
3010      proxy.no.suffix(host, suffix)
3011    case other:
3012      proxy.no.port(String.eq(port_text, U32.show(port)), host, suffix)
3013
3014def proxy.no.literal(+host: String, +port: U32, +name: String) -> Bool:
3015  Bool.or(String.eq(name, host), Bool.or(String.eq(name, "[" ++ host ++ "]"),
3016    Bool.or(String.eq(name, host ++ ":" ++ U32.show(port)),
3017      String.eq(name, "[" ++ host ++ "]:" ++ U32.show(port)))))
3018
3019def proxy.no.token(+host: String, +port: U32, token: String) -> Bool:
3020  +name = String.to_lower(trim(token))
3021  Bool.or(String.eq(name, "*"),
3022    Bool.or(proxy.no.literal(host, port, name),
3023      Bool.and(Bool.not(Url.has(host, 58)),
3024        proxy.no.named(host, port, Url.take_to(name, 58)))))
3025
3026def proxy.no.list(xs: List<&2, String>, +host: String, +port: U32) -> Bool:
3027  match xs:
3028    case Nil{}:
3029      False{}
3030    case Con{token, rest}:
3031      Bool.or(proxy.no.token(host, port, token), proxy.no.list(rest, host, port))
3032
3033def proxy.no_match(+host: String, +port: U32, no_proxy: String) -> Bool:
3034  proxy.no.list(String.split(no_proxy, ','), String.to_lower(host), port)
3035
3036def proxy.env.value(r: Result<&1, &1, U32 & String, String>) -> String:
3037  match r:
3038    case Fail{e}:
3039      ""
3040    case Done{value}:
3041      value
3042
3043def proxy.env.lower(r: Result<&1, &1, U32 & String, String>, upper: String) ->
3044    IO(String):
3045  match r:
3046    case Done{value}:
3047      IO.pure(String, value)
3048    case Fail{e}:
3049      do IO<String>:
3050        got : Result<&1, &1, U32 & String, String> <- IO.get_env(upper)
3051        return proxy.env.value(got)
3052
3053def proxy.env(lower: String, upper: String) -> IO(String):
3054  do IO<String>:
3055    got : Result<&1, &1, U32 & String, String> <- IO.get_env(lower)
3056    proxy.env.lower(got, upper)
3057
3058def proxy.from.env(value: String) -> Maybe<&2, Proxy>:
3059  match value:
3060    case SNil{}:
3061      Some{ProxyDirect{}}
3062    case other:
3063      proxy.from.url(value)
3064
3065def proxy.choose(bypass: Bool, value: String) -> Maybe<&2, Proxy>:
3066  match bypass:
3067    case True{}:
3068      Some{ProxyDirect{}}
3069    case False{}:
3070      proxy.from.env(value)
3071
3072def proxy.select(+scheme: String, +host: String, +port: U32) ->
3073    IO(Maybe<&2, Proxy>):
3074  +secure = String.eq(scheme, "https")
3075  do IO<Maybe<&2, Proxy>>:
3076    bypass : String <- proxy.env("no_proxy", "NO_PROXY")
3077    value : String <- proxy.env(Bool.pick(String, secure, "https_proxy", "http_proxy"),
3078      Bool.pick(String, secure, "HTTPS_PROXY", "HTTP_PROXY"))
3079    return proxy.choose(proxy.no_match(host, port, bypass), value)
3080
3081def h2.header.skip(+name: String) -> Bool:
3082  match name:
3083    case SCon{Chr{58}, rest}:
3084      True{}
3085    case other:
3086      Bool.or(req.reserved(name),
3087        Bool.or(String.eq(name, "keep-alive"),
3088          Bool.or(String.eq(name, "proxy-connection"),
3089            Bool.or(String.eq(name, "upgrade"), String.eq(name, "te")))))
3090
3091def h2.header.mode(+name: String) -> U32:
3092  Bool.pick(U32,
3093    Bool.or(String.eq(name, "authorization"),
3094      Bool.or(String.eq(name, "cookie"), String.eq(name, "proxy-authorization"))),
3095    2, 0)
3096
3097def h2.header.values(+name: String, +mode: U32, vs: List<&2, String>) -> List<&2, Hpack.Field>:
3098  match vs:
3099    case Nil{}:
3100      Nil{}
3101    case Con{v, tail}:
3102      Hpack.Field{name, sanitize(v), mode} <> h2.header.values(name, mode, tail)
3103
3104def h2.header.tokens(vs: List<&2, String>) -> List<&2, String>:
3105  match vs:
3106    case Nil{}:
3107      Nil{}
3108    case Con{value, rest}:
3109      List.append(&2, String, String.split(value, ','), h2.header.tokens(rest))
3110
3111def h2.header.nominated.one(enabled: Bool, vs: List<&2, String>,
3112    rest: List<&2, String>) -> List<&2, String>:
3113  match enabled:
3114    case True{}:
3115      List.append(&2, String, h2.header.tokens(vs), rest)
3116    case False{}:
3117      rest
3118
3119def h2.header.nominated(xs: List<&2, Sigma<&2, &2, String, _ => List<&2, String>>>) ->
3120    List<&2, String>:
3121  match xs:
3122    case Nil{}:
3123      Nil{}
3124    case (name, values) <> tail:
3125      h2.header.nominated.one(String.eq(String.to_lower(name), "connection"),
3126        values, h2.header.nominated(tail))
3127
3128def h2.header.has(xs: List<&2, String>, +key: String) -> Bool:
3129  match xs:
3130    case Nil{}:
3131      False{}
3132    case Con{value, rest}:
3133      Bool.or(String.eq(String.to_lower(trim(value)), key), h2.header.has(rest, key))
3134
3135def h2.header.item(skip: Bool, +name: String, vs: List<&2, String>,
3136    tail: List<&2, Hpack.Field>) -> List<&2, Hpack.Field>:
3137  match skip:
3138    case True{}:
3139      tail
3140    case False{}:
3141      List.append(&2, Hpack.Field, h2.header.values(name, h2.header.mode(name), vs), tail)
3142
3143def h2.header.items(xs: List<&2, Sigma<&2, &2, String, _ => List<&2, String>>>,
3144    +nominated: List<&2, String>) -> List<&2, Hpack.Field>:
3145  match xs:
3146    case Nil{}:
3147      Nil{}
3148    case (name, values) <> tail:
3149      +key = String.to_lower(name)
3150      h2.header.item(Bool.or(h2.header.skip(key), h2.header.has(nominated, key)),
3151        key, values, h2.header.items(tail, nominated))
3152
3153def h2.request.fields(+method: String, target: String, authority: String,
3154    headers: Map<&2, List<&2, String>>) -> List<&2, Hpack.Field>:
3155  +xs = Map.to_list(&2, List<&2, String>, headers)
3156  List.append(&2, Hpack.Field,
3157    [Hpack.Field{":method", method, 0}, Hpack.Field{":scheme", "https", 0},
3158      Hpack.Field{":authority", authority, 0}, Hpack.Field{":path", target, 0}],
3159    h2.header.items(xs, h2.header.nominated(xs)))
3160
3161def h2.response.status.value(+value: String, valid: Bool) -> Maybe<&2, U32>:
3162  match valid:
3163    case False{}:
3164      None{}
3165    case True{}:
3166      parse_u32(value)
3167
3168def h2.response.status(xs: List<&2, Hpack.Field>) -> Maybe<&2, U32>:
3169  match xs:
3170    case Nil{}:
3171      None{}
3172    case Con{Hpack.Field{name, +value, mode}, tail}:
3173      match name:
3174        case ":status":
3175          h2.response.status.value(value, Nat.is_eq(String.length(value), 3n))
3176        case other:
3177          h2.response.status(tail)
3178
3179def h2.response.headers(xs: List<&2, Hpack.Field>, acc: Map<&2, List<&2, String>>) ->
3180    Map<&2, List<&2, String>>:
3181  match xs:
3182    case Nil{}:
3183      acc
3184    case Con{Hpack.Field{name, value, mode}, tail}:
3185      match name:
3186        case SCon{Chr{58}, rest}:
3187          h2.response.headers(tail, acc)
3188        case other:
3189          h2.response.headers(tail, add(acc, String.to_lower(name), value))
3190
3191def h2.response.final(interim: Bool, +status: U32, headers: List<&2, Hpack.Field>,
3192    body: HBytes.Bytes) -> Result<&1, &1, Err, Maybe<&1, Res>>:
3193  match interim:
3194    case True{}:
3195      Done{None{}}
3196    case False{}:
3197      HBytes.Bytes{len, buf} = body
3198      Done{Some{Res{status, h2.response.headers(headers, empty()), Bytes.Bytes{len, buf}}}}
3199
3200def h2.response.valid(valid: Bool, +status: U32, headers: List<&2, Hpack.Field>,
3201    body: HBytes.Bytes) -> Result<&1, &1, Err, Maybe<&1, Res>>:
3202  match valid:
3203    case False{}:
3204      Fail{ErrBad{}}
3205    case True{}:
3206      h2.response.final(U32.is_lt(status, 200), status, headers, body)
3207
3208def h2.response.parsed(m: Maybe<&2, U32>, headers: List<&2, Hpack.Field>,
3209    body: HBytes.Bytes) -> Result<&1, &1, Err, Maybe<&1, Res>>:
3210  match m:
3211    case None{}:
3212      Fail{ErrBad{}}
3213    case Some{+status}:
3214      h2.response.valid(Bool.and(U32.is_ge(status, 100), U32.is_lt(status, 600)),
3215        status, headers, body)
3216
3217def h2.response(+fields: List<&2, Hpack.Field>, body: HBytes.Bytes) ->
3218    Result<&1, &1, Err, Maybe<&1, Res>>:
3219  h2.response.parsed(h2.response.status(fields), fields, body)
3220
3221def h2.event.fold(acc: Result<&1, &1, Err, Maybe<&1, Res>>,
3222    event: H2.ClientEvent) -> Result<&1, &1, Err, Maybe<&1, Res>>:
3223  match acc:
3224    case Fail{e}:
3225      Fail{e}
3226    case Done{Some{res}}:
3227      Done{Some{res}}
3228    case Done{None{}}:
3229      match event:
3230        case H2.Response{id, headers, body}:
3231          h2.response(headers, body)
3232        case H2.Reset{id, code}:
3233          Fail{ErrBad{}}
3234        case H2.Shutdown{last, code}:
3235          Done{None{}}
3236        case H2.Pong{data}:
3237          Done{None{}}
3238
3239def h2.send.report(r: Socket & Result<&1, &1, U32 & String, Unit>) ->
3240    IO(Result<&1, &1, Err, Socket>):
3241  (s, sent) = r
3242  match sent:
3243    case Fail{(+code, why)}:
3244      do IO<Result<&1, &1, Err, Socket>>:
3245        Wire.tls.close(s)
3246        return Fail{err.or_late(code, ErrWrite{code, why})}
3247    case Done{unit}:
3248      IO.pure(Result<&1, &1, Err, Socket>, Done{s})
3249
3250def h2.send.one(prev: Result<&1, &1, Err, Socket>, b: HBytes.Bytes) ->
3251    IO(Result<&1, &1, Err, Socket>):
3252  match prev:
3253    case Fail{e}:
3254      IO.pure(Result<&1, &1, Err, Socket>, Fail{e})
3255    case Done{s}:
3256      HBytes.Bytes{len, buf} = b
3257      do IO<Result<&1, &1, Err, Socket>>:
3258        sent : Socket & Result<&1, &1, U32 & String, Unit> <- Wire.tls.send.words(s, len, buf)
3259        h2.send.report(sent)
3260
3261def h2.send.fold(prev: IO(Result<&1, &1, Err, Socket>), b: HBytes.Bytes) ->
3262    IO(Result<&1, &1, Err, Socket>):
3263  do IO<Result<&1, &1, Err, Socket>>:
3264    r : Result<&1, &1, Err, Socket> <- prev
3265    h2.send.one(r, b)
3266
3267def h2.send(xs: List<&1, HBytes.Bytes>, s: Socket) -> IO(Result<&1, &1, Err, Socket>):
3268  List.foldl(~&1, ~HBytes.Bytes, ~IO(Result<&1, &1, Err, Socket>), ~h2.send.fold,
3269    xs, IO.pure(Result<&1, &1, Err, Socket>, Done{s}))
3270
3271def h2.received.step(over: Bool, s: Socket, client: H2.Client,
3272    +len: U32, buf: Array<U32>) -> H2Step:
3273  match over:
3274    case True{}:
3275      H2Reply{s, H2.Failed{H2.Error{1, True{}, 0}}}
3276    case False{}:
3277      H2Reply{s, H2.client.receive(client, HBytes.Bytes{len, buf})}
3278
3279def h2.fail(s: Socket, e: Err) -> IO(Result<&1, &1, Err, Conn & Res>):
3280  do IO<Result<&1, &1, Err, Conn & Res>>:
3281    Wire.tls.close(s)
3282    return Fail{e}
3283
3284def h2.loop(n: Nat, step: H2Step, +ms: U32, +used: U32) ->
3285    IO(Result<&1, &1, Err, Conn & Res>):
3286  match n:
3287    case 0n:
3288      match step:
3289        case H2Reply{s, reply}:
3290          h2.fail(s, ErrBad{})
3291        case H2Sent{client, events, sent}:
3292          match sent:
3293            case Fail{e}:
3294              IO.pure(Result<&1, &1, Err, Conn & Res>, Fail{e})
3295            case Done{s}:
3296              h2.fail(s, ErrBad{})
3297        case H2Events{s, client, result}:
3298          h2.fail(s, ErrBad{})
3299        case H2Received{client, answer}:
3300          (s, r) = answer
3301          h2.fail(s, ErrBad{})
3302    case 1n+p:
3303      match step:
3304        case H2Reply{s, reply}:
3305          match reply:
3306            case H2.Failed{error}:
3307              h2.fail(s, ErrBad{})
3308            case H2.Ready{client, writes, events}:
3309              do IO<Result<&1, &1, Err, Conn & Res>>:
3310                sent : Result<&1, &1, Err, Socket> <- h2.send(writes, s)
3311                h2.loop(p, H2Sent{client, events, sent}, ms, used)
3312        case H2Sent{client, events, sent}:
3313          match sent:
3314            case Fail{e}:
3315              IO.pure(Result<&1, &1, Err, Conn & Res>, Fail{e})
3316            case Done{s}:
3317              h2.loop(p, H2Events{s, client,
3318                List.foldl(~&1, ~H2.ClientEvent,
3319                  ~Result<&1, &1, Err, Maybe<&1, Res>>, ~h2.event.fold,
3320                  events, Done{None{}})}, ms, used)
3321        case H2Events{s, client, result}:
3322          match result:
3323            case Fail{e}:
3324              h2.fail(s, e)
3325            case Done{Some{res}}:
3326              IO.pure(Result<&1, &1, Err, Conn & Res>,
3327                Done{(ConnH2{s, client}, res)})
3328            case Done{None{}}:
3329              do IO<Result<&1, &1, Err, Conn & Res>>:
3330                r : Socket & Result<&1, &1, U32 & String, U32 & Array<U32>> <-
3331                  Wire.tls.recv.words(s, 16384, ms)
3332                h2.loop(p, H2Received{client, r}, ms, used)
3333        case H2Received{client, answer}:
3334          match answer:
3335            case (s, Fail{(+code, why)}):
3336              h2.fail(s, err.or_late(code, ErrRead{code, why}))
3337            case (s, Done{(0, buf)}):
3338              h2.fail(s, ErrBad{})
3339            case (s, Done{(+len, buf)}):
3340              +total = (used + len : U32)
3341              h2.loop(p, h2.received.step(fetch.over(total), s, client, len, buf), ms, total)
3342
3343def h2.exchange(s: Socket, client: H2.Client, +ms: U32, request: Send) ->
3344    IO(Result<&1, &1, Err, Conn & Res>):
3345  Send{method, target, authority, headers, Bytes.Bytes{len, buf}} = request
3346  h2.loop(Nat.mul(4n, Nat.add(fetch.max(), 65536n)),
3347    H2Reply{s, H2.client.request(client,
3348      h2.request.fields(method, target, authority, headers), HBytes.Bytes{len, buf})},
3349    ms, 0)
3350
3351def proxy.connect.fail(s: Socket, e: Err) -> IO(Result<&1, &1, Err, Conn>):
3352  do IO<Result<&1, &1, Err, Conn>>:
3353    io.close(False{}, s)
3354    return Fail{e}
3355
3356def proxy.connect.extra(m: Maybe<&2, String>, s: Socket, +ms: U32,
3357    sni: String, cert: Maybe<&2, Cert>) -> IO(Result<&1, &1, Err, Conn>):
3358  match m:
3359    case None{}:
3360      proxy.connect.fail(s, ErrBad{})
3361    case Some{rest}:
3362      match rest:
3363        case SNil{}:
3364          conn.secure(ms, sni, s, True{}, cert, True{})
3365        case other:
3366          proxy.connect.fail(s, ErrBad{})
3367
3368def proxy.connect.status(ok: Bool, +status: U32, raw: String, s: Socket,
3369    +ms: U32, sni: String, cert: Maybe<&2, Cert>) ->
3370    IO(Result<&1, &1, Err, Conn>):
3371  match ok:
3372    case False{}:
3373      proxy.connect.fail(s, ErrConnect{status, "proxy CONNECT refused"})
3374    case True{}:
3375      proxy.connect.extra(after(raw, True{}), s, ms, sni, cert)
3376
3377def proxy.connect.finish(res: Res, raw: String, s: Socket, +ms: U32,
3378    sni: String, cert: Maybe<&2, Cert>) -> IO(Result<&1, &1, Err, Conn>):
3379  Res{+status, headers, body} = res
3380  proxy.connect.status(Bool.and(U32.is_ge(status, 200), U32.is_lt(status, 300)),
3381    status, raw, s, ms, sni, cert)
3382
3383def proxy.connect.frame(raw: String, over: Bool) -> Frame:
3384  match over:
3385    case True{}:
3386      FrameBad{}
3387    case False{}:
3388      frame(raw, False{}, True{})
3389
3390def proxy.connect.chunk(empty: Bool, s: Socket, raw: String,
3391    +len: U32, buf: Array<U32>) -> TunnelStep:
3392  match empty:
3393    case True{}:
3394      TunnelHead{s, raw, FrameBad{}}
3395    case False{}:
3396      TunnelRead{s, raw ++ Bytes.to_string(Bytes.Bytes{len, buf})}
3397
3398def proxy.connect.loop(n: Nat, step: TunnelStep, +ms: U32, +sni: String,
3399    +cert: Maybe<&2, Cert>) -> IO(Result<&1, &1, Err, Conn>):
3400  match n:
3401    case 0n:
3402      match step:
3403        case TunnelRead{s, raw}:
3404          proxy.connect.fail(s, ErrBad{})
3405        case TunnelHead{s, raw, result}:
3406          proxy.connect.fail(s, ErrBad{})
3407        case TunnelGot{raw, answer}:
3408          (s, result) = answer
3409          proxy.connect.fail(s, ErrBad{})
3410    case 1n+p:
3411      match step:
3412        case TunnelRead{s, +raw}:
3413          proxy.connect.loop(p, TunnelHead{s, raw,
3414            proxy.connect.frame(raw, Nat.is_gt(String.length(raw), 65536n))},
3415            ms, sni, cert)
3416        case TunnelHead{s, raw, result}:
3417          match result:
3418            case FrameBad{}:
3419              proxy.connect.fail(s, ErrBad{})
3420            case FrameMore{}:
3421              do IO<Result<&1, &1, Err, Conn>>:
3422                answer : Socket & Result<&1, &1, U32 & String, U32 & Array<U32>> <-
3423                  io.recv.words(False{}, s, 4096, ms)
3424                proxy.connect.loop(p, TunnelGot{raw, answer}, ms, sni, cert)
3425            case FrameDone{res}:
3426              proxy.connect.finish(res, raw, s, ms, sni, cert)
3427        case TunnelGot{raw, answer}:
3428          match answer:
3429            case (s, Fail{(+code, why)}):
3430              proxy.connect.fail(s, err.or_late(code, ErrRead{code, why}))
3431            case (s, Done{(+len, buf)}):
3432              proxy.connect.loop(p,
3433                proxy.connect.chunk(U32.is_zero(len), s, raw, len, buf),
3434                ms, sni, cert)
3435
3436def proxy.connect.header(+authority: String, authorization: String) -> String:
3437  match authorization:
3438    case SNil{}:
3439      "CONNECT " ++ authority ++ " HTTP/1.1\r\nHost: " ++ authority ++ "\r\n\r\n"
3440    case other:
3441      "CONNECT " ++ authority ++ " HTTP/1.1\r\nHost: " ++ authority
3442        ++ "\r\nProxy-Authorization: " ++ authorization ++ "\r\n\r\n"
3443
3444def proxy.connect.sent(r: Socket & Result<&1, &1, U32 & String, Unit>,
3445    +ms: U32, sni: String, cert: Maybe<&2, Cert>) ->
3446    IO(Result<&1, &1, Err, Conn>):
3447  (s, sent) = r
3448  match sent:
3449    case Fail{(+code, why)}:
3450      proxy.connect.fail(s, err.or_late(code, ErrWrite{code, why}))
3451    case Done{unit}:
3452      proxy.connect.loop(Nat.mul(3n, 65536n), TunnelRead{s, ""}, ms, sni, cert)
3453
3454def proxy.connect(s: Socket, +ms: U32, sni: String, authority: String,
3455    authorization: String, cert: Maybe<&2, Cert>) ->
3456    IO(Result<&1, &1, Err, Conn>):
3457  do IO<Result<&1, &1, Err, Conn>>:
3458    sent : Socket & Result<&1, &1, U32 & String, Unit> <-
3459      io.send.bytes(False{}, s, Bytes.from_string(proxy.connect.header(authority, authorization)))
3460    proxy.connect.sent(sent, ms, sni, cert)
3461
3462def proxy.route.tls(tls: Bool, s: Socket, +ms: U32, sni: String,
3463    authority: String, authorization: String, cert: Maybe<&2, Cert>) ->
3464    IO(Result<&1, &1, Err, Conn>):
3465  match tls:
3466    case False{}:
3467      IO.pure(Result<&1, &1, Err, Conn>, Done{Conn{False{}, s}})
3468    case True{}:
3469      proxy.connect(s, ms, sni, authority, authorization, cert)
3470
3471def proxy.route.connected(tls: Bool, +ms: U32, sni: String, authority: String,
3472    authorization: String, cert: Maybe<&2, Cert>,
3473    r: Result<&1, &1, Err, Conn>) -> IO(Result<&1, &1, Err, Conn>):
3474  match r:
3475    case Fail{e}:
3476      IO.pure(Result<&1, &1, Err, Conn>, Fail{e})
3477    case Done{c}:
3478      match c:
3479        case Conn{plain, s}:
3480          proxy.route.tls(tls, s, ms, sni, authority, authorization, cert)
3481        case ConnH2{s, client}:
3482          do IO<Result<&1, &1, Err, Conn>>:
3483            Wire.tls.close(s)
3484            return Fail{ErrBad{}}
3485
3486def proxy.route.open(+ms: U32, +tls: Bool, +host: String, +port: U32,
3487    +sni: String, +authority: String, +authorization: String,
3488    cert: Maybe<&2, Cert>) -> IO(Result<&1, &1, Err, Conn>):
3489  do IO<Result<&1, &1, Err, Conn>>:
3490    ips : List<&2, String> <- Dns.resolve.all(host)
3491    conn : Result<&1, &1, Err, Conn> <-
3492      conn.open.all(False{}, ms, host, port, ips, None{}, False{})
3493    proxy.route.connected(tls, ms, sni, authority, authorization, cert, conn)
3494
3495def route.open(+ms: U32, route: Route) -> IO(Result<&1, &1, Err, Conn>):
3496  match route:
3497    case RouteDirect{tls, +host, port, cert}:
3498      do IO<Result<&1, &1, Err, Conn>>:
3499        ips : List<&2, String> <- Dns.resolve.all(host)
3500        conn.open.all(tls, ms, host, port, ips, cert, True{})
3501    case RouteProxy{tls, host, port, sni, authority, authorization, cert}:
3502      proxy.route.open(ms, tls, host, port, sni, authority, authorization, cert)
3503
3504def conn.ex.h1(+tls: Bool, s: Socket, +ms: U32, request: Send) -> IO(Out):
3505  Send{+method, target, authority, headers, body} = request
3506  exchange.go(tls, ms, False{}, String.eq(method, "HEAD"), s,
3507    encode_req.on(method, target, authority, headers, body, False{}))
3508
3509# A socket with bytes past the response is out of step with the server, so it is closed.
3510def pool.keep.s(p: Pool, +key: String, +tls: Bool, res: Res, s: Socket, clean: Bool) -> IO(Pool & Result<&1, &1, Err, Res>):
3511  match clean:
3512    case True{}:
3513      do IO<Pool & Result<&1, &1, Err, Res>>:
3514        p2 : Pool <- pool.give(p, key, Conn{tls, s})
3515        return (p2, Done{res})
3516    case False{}:
3517      do IO<Pool & Result<&1, &1, Err, Res>>:
3518        io.close(tls, s)
3519        return (p, Done{res})
3520
3521def pool.keep.m(p: Pool, +key: String, +tls: Bool, res: Res, +clean: Bool, sock: Maybe<&1, Socket>) -> IO(Pool & Result<&1, &1, Err, Res>):
3522  match sock:
3523    case None{}:
3524      IO.pure(Pool & Result<&1, &1, Err, Res>, (p, Done{res}))
3525    case Some{s}:
3526      pool.keep.s(p, key, tls, res, s, clean)
3527
3528def pool.keep(p: Pool, +key: String, +tls: Bool, res: Res, sock: Maybe<&1, Socket>, rest: Bytes.Bytes) -> IO(Pool & Result<&1, &1, Err, Res>):
3529  Bytes.Bytes{+len, buf} = rest
3530  pool.keep.m(p, key, tls, res, U32.is_zero(len), sock)
3531
3532def pool.after(p: Pool, +key: String, +tls: Bool, o: Out) -> IO(Pool & Result<&1, &1, Err, Res>):
3533  match o:
3534    case OutFail{e, none}:
3535      IO.pure(Pool & Result<&1, &1, Err, Res>, (p, Fail{e}))
3536    case OutDone{res, sock, rest}:
3537      pool.keep(p, key, tls, res, sock, rest)
3538
3539def pool.h2.reusable(c: Conn) -> Bool & Conn:
3540  match c:
3541    case Conn{tls, s}:
3542      (True{}, Conn{tls, s})
3543    case ConnH2{s, H2.Client{input, streams, encoder, decoder, +control}}:
3544      H2.Control{next, active, frame_max, initial, max_streams, send_window,
3545        recv_window, first, ack, continuation, +goaway} = control
3546      (Maybe.is_none(&2, U32, goaway),
3547        ConnH2{s, H2.Client{input, streams, encoder, decoder, control}})
3548
3549def pool.h2.keep(p: Pool, +key: String, res: Res, state: Bool & Conn) ->
3550    IO(Pool & Result<&1, &1, Err, Res>):
3551  (reusable, c) = state
3552  match reusable:
3553    case True{}:
3554      do IO<Pool & Result<&1, &1, Err, Res>>:
3555        next : Pool <- pool.give(p, key, c)
3556        return (next, Done{res})
3557    case False{}:
3558      do IO<Pool & Result<&1, &1, Err, Res>>:
3559        conn.close(c)
3560        return (p, Done{res})
3561
3562def pool.h2.result(p: Pool, +key: String, r: Result<&1, &1, Err, Conn & Res>) ->
3563    IO(Pool & Result<&1, &1, Err, Res>):
3564  match r:
3565    case Fail{e}:
3566      IO.pure(Pool & Result<&1, &1, Err, Res>, (p, Fail{e}))
3567    case Done{(c, res)}:
3568      pool.h2.keep(p, key, res, pool.h2.reusable(c))
3569
3570def pool.h2.ex(p: Pool, +key: String, +ms: U32, request: Send,
3571    s: Socket, client: H2.Client) -> IO(Pool & Result<&1, &1, Err, Res>):
3572  do IO<Pool & Result<&1, &1, Err, Res>>:
3573    r : Result<&1, &1, Err, Conn & Res> <- h2.exchange(s, client, ms, request)
3574    pool.h2.result(p, key, r)
3575
3576def pool.fresh.conn(p: Pool, +key: String, +ms: U32, request: Send,
3577    r: Result<&1, &1, Err, Conn>) -> IO(Pool & Result<&1, &1, Err, Res>):
3578  match r:
3579    case Fail{e}:
3580      IO.pure(Pool & Result<&1, &1, Err, Res>, (p, Fail{e}))
3581    case Done{c}:
3582      match c:
3583        case Conn{+tls, s}:
3584          do IO<Pool & Result<&1, &1, Err, Res>>:
3585            o : Out <- conn.ex.h1(tls, s, ms, request)
3586            pool.after(p, key, tls, o)
3587        case ConnH2{s, client}:
3588          pool.h2.ex(p, key, ms, request, s, client)
3589
3590def pool.fresh(p: Pool, +key: String, +ms: U32, request: Send, route: Route) ->
3591    IO(Pool & Result<&1, &1, Err, Res>):
3592  do IO<Pool & Result<&1, &1, Err, Res>>:
3593    c : Result<&1, &1, Err, Conn> <- route.open(ms, route)
3594    pool.fresh.conn(p, key, ms, request, c)
3595
3596# A reused socket the server already closed fails before any response byte.
3597def pool.retry(+none: Bool, +idem: Bool) -> Bool:
3598  Bool.and(none, idem)
3599
3600def pool.stale(p: Pool, +key: String, +ms: U32, request: Send,
3601    e: Err, again: Bool, route: Route) ->
3602    IO(Pool & Result<&1, &1, Err, Res>):
3603  match again:
3604    case True{}:
3605      pool.fresh(p, key, ms, request, route)
3606    case False{}:
3607      IO.pure(Pool & Result<&1, &1, Err, Res>, (p, Fail{e}))
3608
3609def pool.reused(p: Pool, +key: String, +tls: Bool, +ms: U32, +idem: Bool,
3610    spare: Send, o: Out, route: Route) ->
3611    IO(Pool & Result<&1, &1, Err, Res>):
3612  match o:
3613    case OutFail{e, +none}:
3614      pool.stale(p, key, ms, spare, e, pool.retry(none, idem), route)
3615    case OutDone{res, sock, rest}:
3616      pool.keep(p, key, tls, res, sock, rest)
3617
3618# Copy only the reused HTTP/1.1 request body, for a stale-socket retry.
3619def pool.idle.h1.bodies(p: Pool, +key: String, +tls: Bool, +ms: U32, +idem: Bool,
3620    s: Socket, +method: String, +target: String, +authority: String,
3621    +headers: Map<&2, List<&2, String>>, r: Bytes.Bytes & Bytes.Bytes,
3622    route: Route) -> IO(Pool & Result<&1, &1, Err, Res>):
3623  (wire, spare) = r
3624  do IO<Pool & Result<&1, &1, Err, Res>>:
3625    o : Out <- conn.ex.h1(tls, s, ms, Send{method, target, authority, headers, wire})
3626    pool.reused(p, key, tls, ms, idem,
3627      Send{method, target, authority, headers, spare}, o, route)
3628
3629def pool.idle.h1(p: Pool, +key: String, +tls: Bool, +ms: U32, +idem: Bool,
3630    s: Socket, request: Send, route: Route) ->
3631    IO(Pool & Result<&1, &1, Err, Res>):
3632  Send{+method, +target, +authority, +headers, body} = request
3633  pool.idle.h1.bodies(p, key, tls, ms, idem, s, method, target,
3634    authority, headers, Bytes.slice(body, 0, 4294967295), route)
3635
3636def pool.idle.reuse(p: Pool, +key: String, +ms: U32, +idem: Bool,
3637    c: Conn, request: Send, route: Route) ->
3638    IO(Pool & Result<&1, &1, Err, Res>):
3639  match c:
3640    case Conn{tls, s}:
3641      pool.idle.h1(p, key, tls, ms, idem, s, request, route)
3642    case ConnH2{s, client}:
3643      pool.h2.ex(p, key, ms, request, s, client)
3644
3645def pool.idle(taken: Pool & Maybe<&1, Conn>, +key: String, +ms: U32,
3646    +idem: Bool, request: Send, route: Route) ->
3647    IO(Pool & Result<&1, &1, Err, Res>):
3648  (p, m) = taken
3649  match m:
3650    case None{}:
3651      pool.fresh(p, key, ms, request, route)
3652    case Some{c}:
3653      pool.idle.reuse(p, key, ms, idem, c, request, route)
3654
3655def proxy.http.headers(headers: Map<&2, List<&2, String>>,
3656    authorization: String) -> Map<&2, List<&2, String>>:
3657  match authorization:
3658    case SNil{}:
3659      headers
3660    case other:
3661      set(headers, "proxy-authorization", authorization)
3662
3663def proxy.absolute(scheme: String, host_field: String, target: String) -> String:
3664  scheme ++ "://" ++ host_field ++ target
3665
3666def proxy.request(secure: Bool, +scheme: String, method: String,
3667    +target: String, +hf: String, headers: Map<&2, List<&2, String>>,
3668    body: Bytes.Bytes, authorization: String) -> Send:
3669  match secure:
3670    case True{}:
3671      Send{method, target, hf, Map.del(&2, List<&2, String>, headers,
3672        "proxy-authorization"), body}
3673    case False{}:
3674      Send{method, proxy.absolute(scheme, hf, target), hf,
3675        proxy.http.headers(headers, authorization), body}
3676
3677def pool.origin.proxy(p: Pool, +method: String, +ms: U32,
3678    headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, +hf: String,
3679    +scheme: String, +host: String, +port: U32, +target: String,
3680    +cert: Maybe<&2, Cert>, proxy: Proxy) ->
3681    IO(Pool & Result<&1, &1, Err, Res>):
3682  match proxy:
3683    case ProxyDirect{}:
3684      +key = pool.key.cert(pool.key(scheme, host, port), cert)
3685      pool.idle(pool.take(p, key), key, ms, pool.idempotent(method),
3686        Send{method, target, hf, headers, body},
3687        RouteDirect{String.eq(scheme, "https"), host, port, cert})
3688    case ProxyVia{+proxy_host, +proxy_port, +authorization}:
3689      +secure = String.eq(scheme, "https")
3690      +key = pool.key.cert(pool.key(scheme, host, port)
3691        ++ "|proxy:" ++ proxy_host ++ ":" ++ U32.show(proxy_port)
3692        ++ "|auth:" ++ authorization, cert)
3693      pool.idle(pool.take(p, key), key, ms, pool.idempotent(method),
3694        proxy.request(secure, scheme, method, target, hf, headers, body, authorization),
3695        RouteProxy{secure, proxy_host, proxy_port, host,
3696          Url.host_field.wrap(host, Url.has(host, 58)) ++ ":" ++ U32.show(port),
3697          authorization, cert})
3698
3699def pool.origin.choice(p: Pool, method: String, ms: U32,
3700    headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, hf: String,
3701    scheme: String, host: String, port: U32, target: String,
3702    cert: Maybe<&2, Cert>, choice: Maybe<&2, Proxy>) ->
3703    IO(Pool & Result<&1, &1, Err, Res>):
3704  match choice:
3705    case None{}:
3706      IO.pure(Pool & Result<&1, &1, Err, Res>, (p, Fail{ErrUrl{}}))
3707    case Some{proxy}:
3708      pool.origin.proxy(p, method, ms, headers, body, hf, scheme, host, port,
3709        target, cert, proxy)
3710
3711def pool.origin(p: Pool, method: String, ms: U32,
3712    headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, hf: String,
3713    a: Url.Abs, known: Bool, cert: Maybe<&2, Cert>,
3714    choice: Maybe<&2, Proxy>) ->
3715    IO(Pool & Result<&1, &1, Err, Res>):
3716  Url.Abs{scheme, host, port, target} = a
3717  match known:
3718    case False{}:
3719      IO.pure(Pool & Result<&1, &1, Err, Res>, (p, Fail{ErrUrl{}}))
3720    case True{}:
3721      pool.origin.choice(p, method, ms, headers, body, hf, scheme, host,
3722        port, target, cert, choice)
3723
3724def pool.scheme.ok(a: Url.Abs) -> Bool:
3725  Url.Abs{+scheme, host, port, target} = a
3726  Bool.or(String.eq(scheme, "http"), String.eq(scheme, "https"))
3727
3728def pool.one.back(h: Hop, pr: Pool & Result<&1, &1, Err, Res>) -> Pool & Result<&1, &1, Err, Res> & Hop:
3729  (p, r) = pr
3730  (p, r, h)
3731
3732# sent is headers plus any jar cookies; the hop keeps headers, so cookies never pile up across hops.
3733def pool.one.of(p: Pool, +method: String, +url: Url.Abs,
3734    headers: Map<&2, List<&2, String>>, sent: Map<&2, List<&2, String>>,
3735    +ms: U32, r: Bytes.Bytes & Bytes.Bytes, cert: Maybe<&2, Cert>) ->
3736    IO(Pool & Result<&1, &1, Err, Res> & Hop):
3737  Url.Abs{+scheme, +host, +port, target} = url
3738  (body, wire) = r
3739  do IO<Pool & Result<&1, &1, Err, Res> & Hop>:
3740    choice : Maybe<&2, Proxy> <- proxy.select(scheme, host, port)
3741    pr : Pool & Result<&1, &1, Err, Res> <-
3742      pool.origin(p, method, ms, sent, wire, Url.host_field(url),
3743        url, pool.scheme.ok(url), cert, choice)
3744    return pool.one.back(Hop{method, url, headers, body}, pr)
3745
3746# One request, on an idle socket to its origin when the pool has one. The hop comes back for the redirect.
3747def pool.one(p: Pool, h: Hop, +ms: U32, cert: Maybe<&2, Cert>, jar: Maybe<&2, Jar>) -> IO(Pool & Result<&1, &1, Err, Res> & Hop):
3748  Hop{+method, +url, +headers, body} = h
3749  pool.one.of(p, method, url, headers, jar.opt.apply(jar, url, headers), ms, Bytes.slice(body, 0, 4294967295), cert)
3750
3751type Next is Type:
3752  NDone{res: Result<&1, &1, Err, Res>}
3753  NStop{}
3754  NGo{left: Nat, hop: Hop}
3755
3756type Mode is Data:
3757  ModeFollow{}
3758  ModeManual{}
3759  ModeError{}
3760
3761# left: redirects still allowed after the request we just finished.
3762def fetch.hop(left: Nat, h: Hop) -> Next:
3763  match left:
3764    case 0n:
3765      NStop{}
3766    case 1n+p:
3767      NGo{p, h}
3768
3769def fetch.decide.r(left: Nat, r: Res, next: Maybe<&1, Hop>) -> Next:
3770  match next:
3771    case None{}:
3772      NDone{Done{r}}
3773    case Some{h}:
3774      fetch.hop(left, h)
3775
3776def fetch.decide.res(left: Nat, h: Hop, r: Res) -> Next:
3777  Res{+status, +headers, body} = r
3778  fetch.decide.r(left, Res{status, headers, body}, redirect(status, headers, h))
3779
3780def fetch.decide(left: Nat, h: Hop, m: Result<&1, &1, Err, Res>) -> Next:
3781  match m:
3782    case Fail{e}:
3783      NDone{Fail{e}}
3784    case Done{r}:
3785      fetch.decide.res(left, h, r)
3786
3787def fetch.error.res(r: Res, bad: Bool) -> Next:
3788  match bad:
3789    case True{}:
3790      NDone{Fail{ErrRedirect{}}}
3791    case False{}:
3792      NDone{Done{r}}
3793
3794def fetch.error(h: Hop, m: Result<&1, &1, Err, Res>) -> Next:
3795  match m:
3796    case Fail{e}:
3797      NDone{Fail{e}}
3798    case Done{r}:
3799      Res{+status, +headers, body} = r
3800      fetch.error.res(Res{status, headers, body}, Bool.and(redirect.code(status), has_header(headers, "location")))
3801
3802def fetch.policy(mode: Mode, left: Nat, h: Hop, m: Result<&1, &1, Err, Res>) -> Next:
3803  match mode:
3804    case ModeFollow{}:
3805      fetch.decide(left, h, m)
3806    case ModeManual{}:
3807      NDone{m}
3808    case ModeError{}:
3809      fetch.error(h, m)
3810
3811# A caller's own Accept-Encoding wins; enc is the codings fetch can undo.
3812def accept.enc(+h: Map<&2, List<&2, String>>, +enc: String) -> Map<&2, List<&2, String>>:
3813  Bool.pick(Map<&2, List<&2, String>>, has_header(h, "accept-encoding"), h, set(h, "accept-encoding", enc))
3814
3815def fetch.start(method: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, u: Maybe<&2, Url.Abs>, +enc: String) -> Next:
3816  match u:
3817    case None{}:
3818      NDone{Fail{ErrUrl{}}}
3819    case Some{a}:
3820      NGo{20n, Hop{method, a, accept.enc(req.put(Map.to_list(&2, List<&2, String>, headers), empty()), enc), body}}
3821
3822# The redirect loop's state: the pool, what to do next, the client identity, and the jar if any.
3823type Hops is Type:
3824  Hops{p: Pool, next: Next, cert: Maybe<&2, Cert>, jar: Maybe<&2, Jar>}
3825
3826def pool.next.move(p: Pool, +old: String, cert: Maybe<&2, Cert>, jar: Maybe<&2, Jar>, n: Next) -> Hops:
3827  match n:
3828    case NGo{left, h}:
3829      Hop{method, +url, headers, body} = h
3830      Hops{p, NGo{left, Hop{method, url, headers, body}},
3831        Bool.pick(Maybe<&2, Cert>, String.eq(old, redirect.origin(url)), cert, None{}), jar}
3832    case NDone{r}:
3833      Hops{p, NDone{r}, None{}, jar}
3834    case NStop{}:
3835      Hops{p, NStop{}, None{}, jar}
3836
3837def pool.next.of(+mode: Mode, left: Nat, cert: Maybe<&2, Cert>, p: Pool, +url: Url.Abs, h: Hop, r: Maybe<&2, Jar> & Result<&1, &1, Err, Res>) -> Hops:
3838  (jar, m) = r
3839  pool.next.move(p, redirect.origin(url), cert, jar, fetch.policy(mode, left, h, m))
3840
3841# The jar takes the response's Set-Cookie fields first, redirect or not.
3842def pool.next(+mode: Mode, left: Nat, cert: Maybe<&2, Cert>, jar: Maybe<&2, Jar>, x: Pool & Result<&1, &1, Err, Res> & Hop) -> Hops:
3843  (p, m, h) = x
3844  Hop{method, +url, headers, body} = h
3845  pool.next.of(mode, left, cert, p, url, Hop{method, url, headers, body}, jar.opt.store(jar, url, m))
3846
3847def pool.hops.one(+mode: Mode, +ms: U32, +cert: Maybe<&2, Cert>, +jar: Maybe<&2, Jar>, p: Pool, h: Hop, left: Nat) -> IO(Hops):
3848  do IO<Hops>:
3849    x : Pool & Result<&1, &1, Err, Res> & Hop <- pool.one(p, h, ms, cert, jar)
3850    return pool.next(mode, left, cert, jar, x)
3851
3852# NGo.left is how many redirects may follow this request. 20 is WHATWG's limit.
3853# The jar, when there is one, gives cookies to every hop and takes them from every response.
3854@unsafe
3855def pool.hops(+mode: Mode, +ms: U32, st: Hops) -> IO(Pool & Result<&1, &1, Err, Res> & Maybe<&2, Jar>):
3856  Hops{p, n, cert, cj} = st
3857  match n:
3858    case NDone{m}:
3859      IO.pure(Pool & Result<&1, &1, Err, Res> & Maybe<&2, Jar>, (p, m, cj))
3860    case NStop{}:
3861      IO.pure(Pool & Result<&1, &1, Err, Res> & Maybe<&2, Jar>, (p, Fail{ErrRedirect{}}, cj))
3862    case NGo{+left, h}:
3863      do IO<Pool & Result<&1, &1, Err, Res> & Maybe<&2, Jar>>:
3864        next : Hops <- pool.hops.one(mode, ms, cert, cj, p, h, left)
3865        pool.hops(mode, ms, next)
3866
3867# Content-Encoding (RFC 9110 §8.4): each value, trimmed and lowercased, in the order applied.
3868def ce.keep(+w: String, +rest: List<&2, String>) -> List<&2, String>:
3869  Bool.pick(List<&2, String>, String.is_empty(w), rest, Con{w, rest})
3870
3871def ce.norm(xs: List<&2, String>) -> List<&2, String>:
3872  match xs:
3873    case Nil{}:
3874      Nil{}
3875    case Con{v, t}:
3876      ce.keep(String.to_lower(trim(v)), ce.norm(t))
3877
3878def ce.split(xs: List<&2, String>) -> List<&2, String>:
3879  match xs:
3880    case Nil{}:
3881      Nil{}
3882    case Con{v, t}:
3883      List.append(&2, String, ce.norm(String.split(v, ',')), ce.split(t))
3884
3885# Ok: decoded so far. Bad: a coding failed. Skip: a coding we cannot decode, so the body stays as sent.
3886type Dec is Data:
3887  DecOk{b: String}
3888  DecBad{}
3889  DecSkip{}
3890
3891def ce.of(m: Maybe<&2, String>) -> Dec:
3892  match m:
3893    case None{}:
3894      DecBad{}
3895    case Some{b}:
3896      DecOk{b}
3897
3898# Servers send deflate both with and without the zlib wrapper.
3899def ce.deflate(+b: String, m: Maybe<&2, String>) -> Dec:
3900  match m:
3901    case Some{out}:
3902      DecOk{out}
3903    case None{}:
3904      ce.of(Zlib.inflate(b))
3905
3906def ce.apply(+c: String, +b: String) -> Dec:
3907  Bool.pick(Dec, Bool.or(String.eq(c, "gzip"), String.eq(c, "x-gzip")), ce.of(Zlib.gunzip(b)),
3908    Bool.pick(Dec, String.eq(c, "deflate"), ce.deflate(b, Zlib.unzlib(b)),
3909      Bool.pick(Dec, String.eq(c, "identity"), DecOk{b}, DecSkip{})))
3910
3911def ce.go(cs: List<&2, String>, d: Dec) -> Dec:
3912  match cs:
3913    case Nil{}:
3914      d
3915    case Con{+c, t}:
3916      match d:
3917        case DecOk{+b}:
3918          ce.go(t, ce.apply(c, b))
3919        case DecBad{}:
3920          DecBad{}
3921        case DecSkip{}:
3922          DecSkip{}
3923
3924def decoded.pick(d: Dec, +status: U32, headers: Map<&2, List<&2, String>>, body: String) -> Result<&1, &1, Err, Res>:
3925  match d:
3926    case DecOk{b}:
3927      Done{Res{status, headers, Bytes.from_string(b)}}
3928    case DecBad{}:
3929      Fail{ErrBad{}}
3930    case DecSkip{}:
3931      Done{Res{status, headers, Bytes.from_string(body)}}
3932
3933# ponytail: the codings run on a String copy of the body; give zlib a Bytes input if gzip bodies get big.
3934def decoded.cs(+status: U32, +headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, cs: List<&2, String>) -> Result<&1, &1, Err, Res>:
3935  match cs:
3936    case Nil{}:
3937      Done{Res{status, headers, body}}
3938    case Con{c, t}:
3939      +s = Bytes.to_string(body)
3940      decoded.pick(ce.go(Con{c, t}, DecOk{s}), status, headers, s)
3941
3942def decoded.go(empty: Bool, +status: U32, +headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> Result<&1, &1, Err, Res>:
3943  match empty:
3944    case True{}:
3945      Done{Res{status, headers, body}}
3946    case False{}:
3947      decoded.cs(status, headers, body, List.reverse(&2, String, ce.split(fields(headers, "content-encoding"))))
3948
3949# The body decoded per Content-Encoding; the headers stay as sent. A corrupt body is ErrBad.
3950def decoded(res: Res) -> Result<&1, &1, Err, Res>:
3951  Res{+status, +headers, body} = res
3952  Bytes.Bytes{+len, buf} = body
3953  decoded.go(U32.is_zero(len), status, headers, Bytes.Bytes{len, buf})
3954
3955def decoded.m(r: Result<&1, &1, Err, Res>) -> Maybe<&1, Res>:
3956  match r:
3957    case Done{x}:
3958      Some{x}
3959    case Fail{e}:
3960      None{}
3961
3962def decoded.some(res: Res) -> Maybe<&1, Res>:
3963  decoded.m(decoded(res))
3964
3965def ce.words(r: Result<&1, &1, U32 & String, U32 & Array<U32>>) -> Maybe<&1, Bytes.Bytes>:
3966  match r:
3967    case Fail{e}:
3968      None{}
3969    case Done{(+len, buf)}:
3970      Some{Bytes.Bytes{len, buf}}
3971
3972# A decoded body stops at 16 MiB, like a received one.
3973def ce.eff(~eff: U32 -> U32 -> Array<U32> -> IO(Result<&1, &1, U32 & String, U32 & Array<U32>>), b: Bytes.Bytes) -> IO(Maybe<&1, Bytes.Bytes>):
3974  Bytes.Bytes{+len, buf} = b
3975  do IO<Maybe<&1, Bytes.Bytes>>:
3976    r : Result<&1, &1, U32 & String, U32 & Array<U32>> <- eff(16777216, len, buf)
3977    return ce.words(r)
3978
3979def ce.dec(d: Dec) -> Maybe<&1, Bytes.Bytes>:
3980  match d:
3981    case DecOk{b}:
3982      Some{Bytes.from_string(b)}
3983    case DecBad{}:
3984      None{}
3985    case DecSkip{}:
3986      None{}
3987
3988# ponytail: deflate runs on the pure decoder, which also takes raw DEFLATE; servers rarely send it.
3989def ce.io.deflate(on: Bool, b: Bytes.Bytes) -> IO(Maybe<&1, Bytes.Bytes>):
3990  match on:
3991    case True{}:
3992      +s = Bytes.to_string(b)
3993      IO.pure(Maybe<&1, Bytes.Bytes>, ce.dec(ce.deflate(s, Zlib.unzlib(s))))
3994    case False{}:
3995      IO.pure(Maybe<&1, Bytes.Bytes>, Some{b})
3996
3997def ce.io.zstd(on: Bool, +c: String, b: Bytes.Bytes) -> IO(Maybe<&1, Bytes.Bytes>):
3998  match on:
3999    case True{}:
4000      ce.eff(~Zlib.zstd.words, b)
4001    case False{}:
4002      ce.io.deflate(String.eq(c, "deflate"), b)
4003
4004def ce.io.br(on: Bool, +c: String, b: Bytes.Bytes) -> IO(Maybe<&1, Bytes.Bytes>):
4005  match on:
4006    case True{}:
4007      ce.eff(~Zlib.brotli.words, b)
4008    case False{}:
4009      ce.io.zstd(String.eq(c, "zstd"), c, b)
4010
4011# One known coding undone: gzip, x-gzip, br, zstd, deflate, or identity.
4012def ce.io.gz(on: Bool, +c: String, b: Bytes.Bytes) -> IO(Maybe<&1, Bytes.Bytes>):
4013  match on:
4014    case True{}:
4015      ce.eff(~Zlib.inflate.words, b)
4016    case False{}:
4017      ce.io.br(String.eq(c, "br"), c, b)
4018
4019def ce.io.go(cs: List<&2, String>, m: Maybe<&1, Bytes.Bytes>) -> IO(Maybe<&1, Bytes.Bytes>):
4020  match cs:
4021    case Nil{}:
4022      match m:
4023        case None{}:
4024          IO.pure(Maybe<&1, Bytes.Bytes>, None{})
4025        case Some{b}:
4026          IO.pure(Maybe<&1, Bytes.Bytes>, Some{b})
4027    case Con{+c, t}:
4028      match m:
4029        case None{}:
4030          IO.pure(Maybe<&1, Bytes.Bytes>, None{})
4031        case Some{b}:
4032          do IO<Maybe<&1, Bytes.Bytes>>:
4033            n : Maybe<&1, Bytes.Bytes> <- ce.io.gz(Bool.or(String.eq(c, "gzip"), String.eq(c, "x-gzip")), c, b)
4034            ce.io.go(t, n)
4035
4036def ce.has(xs: List<&2, String>, +c: String) -> Bool:
4037  match xs:
4038    case Nil{}:
4039      False{}
4040    case Con{x, t}:
4041      Bool.or(String.eq(c, x), ce.has(t, c))
4042
4043def ce.known(cs: List<&2, String>, +ok: List<&2, String>) -> Bool:
4044  match cs:
4045    case Nil{}:
4046      True{}
4047    case Con{c, t}:
4048      Bool.and(ce.has(ok, c), ce.known(t, ok))
4049
4050def decoded.io.pick(m: Maybe<&1, Bytes.Bytes>, +status: U32, headers: Map<&2, List<&2, String>>) -> Result<&1, &1, Err, Res>:
4051  match m:
4052    case Some{b}:
4053      Done{Res{status, headers, b}}
4054    case None{}:
4055      Fail{ErrBad{}}
4056
4057def decoded.io.run(known: Bool, +status: U32, +headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, cs: List<&2, String>) -> IO(Result<&1, &1, Err, Res>):
4058  match known:
4059    case True{}:
4060      do IO<Result<&1, &1, Err, Res>>:
4061        m : Maybe<&1, Bytes.Bytes> <- ce.io.go(cs, Some{body})
4062        return decoded.io.pick(m, status, headers)
4063    case False{}:
4064      IO.pure(Result<&1, &1, Err, Res>, Done{Res{status, headers, body}})
4065
4066def decoded.io.go(empty: Bool, +enc: String, +status: U32, +headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Result<&1, &1, Err, Res>):
4067  match empty:
4068    case True{}:
4069      IO.pure(Result<&1, &1, Err, Res>, Done{Res{status, headers, body}})
4070    case False{}:
4071      +cs = List.reverse(&2, String, ce.split(fields(headers, "content-encoding")))
4072      decoded.io.run(ce.known(cs, Con{"identity", Con{"x-gzip", ce.split(Con{enc, Nil{}})}}), status, headers, body, cs)
4073
4074# decoded through the C libraries, for the codings in enc. A body with any other coding stays as sent.
4075def decoded.io(+enc: String, res: Res) -> IO(Result<&1, &1, Err, Res>):
4076  Res{+status, +headers, body} = res
4077  Bytes.Bytes{+len, buf} = body
4078  decoded.io.go(U32.is_zero(len), enc, status, headers, Bytes.Bytes{len, buf})
4079
4080# An effect on empty input fails with ENOENT only when its library does not load.
4081def codings.ok(r: Result<&1, &1, U32 & String, U32 & Array<U32>>) -> Bool:
4082  match r:
4083    case Fail{(+c, why)}:
4084      Bool.not(U32.is_eq(c, 2))
4085    case Done{p}:
4086      True{}
4087
4088def codings.has(~eff: U32 -> U32 -> Array<U32> -> IO(Result<&1, &1, U32 & String, U32 & Array<U32>>), b: Bytes.Bytes) -> IO(Bool):
4089  Bytes.Bytes{+len, buf} = b
4090  do IO<Bool>:
4091    r : Result<&1, &1, U32 & String, U32 & Array<U32>> <- eff(0, len, buf)
4092    return codings.ok(r)
4093
4094def codings.add(has: Bool, +enc: String, +c: String) -> String:
4095  Bool.pick(String, has, enc ++ ", " ++ c, enc)
4096
4097# gzip and deflate, then br and zstd when their C library loads.
4098def codings() -> IO(String):
4099  do IO<String>:
4100    b : Bool <- codings.has(~Zlib.brotli.words, Bytes.new(0))
4101    z : Bool <- codings.has(~Zlib.zstd.words, Bytes.new(0))
4102    return codings.add(z, codings.add(b, "gzip, deflate", "br"), "zstd")
4103
4104# The final response of a fetch, after redirects.
4105def fetch.final(+enc: String, r: Result<&1, &1, Err, Res>) -> IO(Result<&1, &1, Err, Res>):
4106  match r:
4107    case Done{res}:
4108      decoded.io(enc, res)
4109    case Fail{e}:
4110      IO.pure(Result<&1, &1, Err, Res>, Fail{e})
4111
4112def pool.final(+enc: String, pr: Pool & Result<&1, &1, Err, Res> & Maybe<&2, Jar>) -> IO(Pool & Result<&1, &1, Err, Res>):
4113  (p, r, jar) = pr
4114  do IO<Pool & Result<&1, &1, Err, Res>>:
4115    d : Result<&1, &1, Err, Res> <- fetch.final(enc, r)
4116    return (p, d)
4117
4118def pool.how.enc(+enc: String, p: Pool, method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, ms: U32, mode: Mode, cert: Maybe<&2, Cert>) -> IO(Pool & Result<&1, &1, Err, Res>):
4119  do IO<Pool & Result<&1, &1, Err, Res>>:
4120    pr : Pool & Result<&1, &1, Err, Res> & Maybe<&2, Jar> <- pool.hops(mode, ms, Hops{p, fetch.start(method, headers, body, Url.absolute(url), enc), cert, None{}})
4121    pool.final(enc, pr)
4122
4123def pool.how.cert(p: Pool, method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, ms: U32, mode: Mode, cert: Maybe<&2, Cert>) -> IO(Pool & Result<&1, &1, Err, Res>):
4124  do IO<Pool & Result<&1, &1, Err, Res>>:
4125    enc : String <- codings()
4126    pool.how.enc(enc, p, method, url, headers, body, ms, mode, cert)
4127
4128# pool.how(p, "GET", "https://example.com/x?y=1", headers, body, ms, mode) follows redirects
4129# on p's idle sockets. Fail is a bad URL, a failed lookup, connect, handshake, send, read,
4130# a malformed response, more than 20 redirects, or a step past ms. Bodies are bytes.
4131def pool.how(p: Pool, method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, ms: U32, mode: Mode) -> IO(Pool & Result<&1, &1, Err, Res>):
4132  pool.how.cert(p, method, url, headers, body, ms, mode, None{})
4133
4134def pool.fetch.with(p: Pool, method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, ms: U32) -> IO(Pool & Result<&1, &1, Err, Res>):
4135  pool.how(p, method, url, headers, body, ms, ModeFollow{})
4136
4137def pool.fetch(p: Pool, method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Pool & Result<&1, &1, Err, Res>):
4138  pool.fetch.with(p, method, url, headers, body, 30000)
4139
4140def pool.fetch.cert.with(p: Pool, method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, chain: String, key: String, ms: U32) -> IO(Pool & Result<&1, &1, Err, Res>):
4141  pool.how.cert(p, method, url, headers, body, ms, ModeFollow{}, Some{Cert{chain, key}})
4142
4143def pool.fetch.cert(p: Pool, method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, chain: String, key: String) -> IO(Pool & Result<&1, &1, Err, Res>):
4144  pool.fetch.cert.with(p, method, url, headers, body, chain, key, 30000)
4145
4146# One request for fetch.all: the arguments of fetch, as a record.
4147type Fetch is Type:
4148  Fetch{method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes}
4149
4150def fetch.all.job(p: Pool, f: Fetch) -> IO(Pool & Result<&1, &1, Err, Res>):
4151  Fetch{method, url, headers, body} = f
4152  pool.fetch(p, method, url, headers, body)
4153
4154def fetch.all.pools(n: Nat) -> List<Pool>:
4155  match n:
4156    case 0n:
4157      Nil{}
4158    case 1n+p:
4159      pool.new() <> fetch.all.pools(p)
4160
4161def fetch.all.close(ps: List<Pool>) -> IO(Unit):
4162  match ps:
4163    case Nil{}:
4164      IO.pure(Unit, Unit{})
4165    case p <> rest:
4166      do IO<Unit>:
4167        pool.close(p)
4168        fetch.all.close(rest)
4169
4170def fetch.all.done(r: List<Pool> & List<Result<&1, &1, Err, Res>>) -> IO(List<Result<&1, &1, Err, Res>>):
4171  (ps, rs) = r
4172  do IO<List<Result<&1, &1, Err, Res>>>:
4173    fetch.all.close(ps)
4174    return rs
4175
4176# No requests start no workers, since Conc.pool needs at least one.
4177def fetch.all.go(xs: List<Fetch>, +workers: Nat) -> IO(List<Result<&1, &1, Err, Res>>):
4178  match xs:
4179    case Nil{}:
4180      IO.pure(List<Result<&1, &1, Err, Res>>, Nil{})
4181    case x <> rest:
4182      do IO<List<Result<&1, &1, Err, Res>>>:
4183        r : List<Pool> & List<Result<&1, &1, Err, Res>> <-
4184          Conc.pool(~Pool, ~Fetch, ~Result<&1, &1, Err, Res>, ~fetch.all.job, fetch.all.pools(workers), x <> rest)
4185        fetch.all.done(r)
4186
4187def fetch.all.of(+n: U32, nx: Nat & List<Fetch>) -> IO(List<Result<&1, &1, Err, Res>>):
4188  (+len, xs) = nx
4189  fetch.all.go(xs, Nat.min(len, Nat.max(1n, U32.to_nat(n))))
4190
4191# Each request as fetch would make it, on at most n workers (0 counts as 1, and
4192# never more workers than requests). Each worker owns its own Pool, so an idle
4193# socket is reused only by the worker that opened it; every pool is closed at the
4194# end. Results come back in the order of reqs.
4195def fetch.all(reqs: List<Fetch>, +n: U32) -> IO(List<Result<&1, &1, Err, Res>>):
4196  fetch.all.of(n, Conc.count(Fetch, reqs))
4197
4198# The hops always hand the jar back; j is only the type's fallback.
4199def pool.jar.final(+enc: String, j: Jar, pr: Pool & Result<&1, &1, Err, Res> & Maybe<&2, Jar>) -> IO(Pool & Jar & Result<&1, &1, Err, Res>):
4200  (p, r, jar) = pr
4201  do IO<Pool & Jar & Result<&1, &1, Err, Res>>:
4202    d : Result<&1, &1, Err, Res> <- fetch.final(enc, r)
4203    return (p, Maybe.default(&2, Jar, jar, j), d)
4204
4205def pool.jar.enc(+enc: String, p: Pool, +j: Jar, method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Pool & Jar & Result<&1, &1, Err, Res>):
4206  do IO<Pool & Jar & Result<&1, &1, Err, Res>>:
4207    pr : Pool & Result<&1, &1, Err, Res> & Maybe<&2, Jar> <- pool.hops(ModeFollow{}, 30000, Hops{p, fetch.start(method, headers, body, Url.absolute(url), enc), None{}, Some{j}})
4208    pool.jar.final(enc, j, pr)
4209
4210# pool.fetch with a cookie jar (RFC 6265bis). Before every hop, redirects included, the jar's
4211# cookies for that URL join the request's cookie field; after every response, redirects included,
4212# its Set-Cookie fields go into the jar. The jar's clock is the caller's: advance it with jar.at.
4213def pool.fetch.jar(p: Pool, j: Jar, method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Pool & Jar & Result<&1, &1, Err, Res>):
4214  do IO<Pool & Jar & Result<&1, &1, Err, Res>>:
4215    enc : String <- codings()
4216    pool.jar.enc(enc, p, j, method, url, headers, body)
4217def fetch.end(pr: Pool & Result<&1, &1, Err, Res>) -> IO(Result<&1, &1, Err, Res>):
4218  (p, r) = pr
4219  do IO<Result<&1, &1, Err, Res>>:
4220    pool.close(p)
4221    return r
4222
4223# fetch is pool.how on a fresh pool that closes afterwards.
4224def fetch.how(method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, ms: U32, mode: Mode) -> IO(Result<&1, &1, Err, Res>):
4225  do IO<Result<&1, &1, Err, Res>>:
4226    pr : Pool & Result<&1, &1, Err, Res> <- pool.how(pool.new(), method, url, headers, body, ms, mode)
4227    fetch.end(pr)
4228
4229def fetch.with(method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, ms: U32) -> IO(Result<&1, &1, Err, Res>):
4230  fetch.how(method, url, headers, body, ms, ModeFollow{})
4231
4232def fetch.cert.with(method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, chain: String, key: String, ms: U32) -> IO(Result<&1, &1, Err, Res>):
4233  do IO<Result<&1, &1, Err, Res>>:
4234    pr : Pool & Result<&1, &1, Err, Res> <- pool.fetch.cert.with(pool.new(), method, url, headers, body, chain, key, ms)
4235    fetch.end(pr)
4236
4237def fetch.cert(method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, chain: String, key: String) -> IO(Result<&1, &1, Err, Res>):
4238  fetch.cert.with(method, url, headers, body, chain, key, 30000)
4239
4240# fetch.with and a 30 s step timeout.
4241def fetch(method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Result<&1, &1, Err, Res>):
4242  fetch.with(method, url, headers, body, 30000)
4243
4244def get(url: String) -> IO(Result<&1, &1, Err, Res>):
4245  fetch("GET", url, empty(), Bytes.new(0))
4246
4247# POST v as compact JSON, with content-type: application/json.
4248def post.json(url: String, v: Json.Val) -> IO(Result<&1, &1, Err, Res>):
4249  fetch("POST", url, set(empty(), "content-type", "application/json"), Json.encode.bytes(v))
4250
4251# Base URLs: resolve(base, ref) is ref against the absolute http(s) URL base (RFC 3986 §5.2),
4252# written back as a URL for fetch. None when base is not absolute or ref has another scheme.
4253def resolve.show(a: Url.Abs) -> String:
4254  Url.Abs{+scheme, host, port, +target} = a
4255  scheme ++ "://" ++ Url.host_field(Url.Abs{scheme, host, port, target}) ++ target
4256
4257def resolve.to(m: Maybe<&2, Url.Abs>) -> Maybe<&2, String>:
4258  match m:
4259    case None{}:
4260      None{}
4261    case Some{a}:
4262      Some{resolve.show(a)}
4263
4264def resolve.base(m: Maybe<&2, Url.Abs>, +ref: String) -> Maybe<&2, String>:
4265  match m:
4266    case None{}:
4267      None{}
4268    case Some{b}:
4269      resolve.to(Url.resolve(b, ref))
4270
4271def resolve(base: String, +ref: String) -> Maybe<&2, String>:
4272  resolve.base(Url.absolute(base), ref)
4273
4274# Retry. The wait before retry n (0 first) is 500 ms doubled n times, at most 30 s;
4275# its upper half is jitter r: backoff(n, r) = half + r mod (half + 1).
4276def retry.cap() -> U32:
4277  30000
4278
4279def retry.base(n: Nat) -> U32:
4280  match n:
4281    case 0n:
4282      500
4283    case 1n+p:
4284      U32.min((retry.base(p) * 2 : U32), retry.cap())
4285
4286def retry.backoff.half(+half: U32, +r: U32) -> U32:
4287  (half + (r % (half + 1)) : U32)
4288
4289def retry.backoff(n: Nat, +r: U32) -> U32:
4290  retry.backoff.half((retry.base(n) / 2 : U32), r)
4291
4292# ms clamped to 0 .. retry.cap().
4293def retry.after.ms(+ms: Int.I64) -> U32:
4294  Bool.pick(U32, Int.I64.is_neg(ms), 0,
4295    Bool.pick(U32, Int.I64.is_lt(ms, Int.I64.from_u32(retry.cap())), Int.I64.to_u32(ms), retry.cap()))
4296
4297def retry.after.date(m: Maybe<&2, Time.Instant>, now: Time.Instant) -> Maybe<&2, U32>:
4298  match m:
4299    case None{}:
4300      None{}
4301    case Some{date}:
4302      Some{retry.after.ms(Time.Duration.to_ms(Time.Instant.since(date, now)))}
4303
4304# More than 5 digits is past the cap, and would overflow parse_u32.
4305def retry.after.secs(+v: String, now: Time.Instant, n: Maybe<&2, U32>) -> Maybe<&2, U32>:
4306  match n:
4307    case None{}:
4308      retry.after.date(Time.http_date.parse(v), now)
4309    case Some{s}:
4310      Some{Bool.pick(U32, Nat.is_lt(5n, String.length(v)), retry.cap(), U32.min((s * 1000 : U32), retry.cap()))}
4311
4312# Retry-After (RFC 9110 §10.2.3) as ms from now, at most retry.cap(): delay-seconds, or an
4313# HTTP-date (a past date is 0). None when v is empty or neither form.
4314def retry.after(+v: String, now: Time.Instant) -> Maybe<&2, U32>:
4315  retry.after.secs(v, now, parse_u32(v))
4316
4317def retry.wait(m: Maybe<&2, U32>, n: Nat, +r: U32) -> U32:
4318  match m:
4319    case None{}:
4320      retry.backoff(n, r)
4321    case Some{ms}:
4322      ms
4323
4324# The wait before retry n: Retry-After v when it reads as a delay, else backoff with jitter r.
4325def retry.delay(+v: String, now: Time.Instant, n: Nat, +r: U32) -> U32:
4326  retry.wait(retry.after(v, now), n, r)
4327
4328# Statuses a later try may clear.
4329def retry.status(+s: U32) -> Bool:
4330  Bool.or(Bool.or(U32.is_eq(s, 408), U32.is_eq(s, 429)),
4331    Bool.or(Bool.or(U32.is_eq(s, 500), U32.is_eq(s, 502)), Bool.or(U32.is_eq(s, 503), U32.is_eq(s, 504))))
4332
4333# A refused connect or a timeout may clear; any other error would repeat.
4334def retry.fail(e: Err) -> Result<&1, &1, Err, Res> & Maybe<&2, String>:
4335  match e:
4336    case ErrConnect{code, why}:
4337      (Fail{ErrConnect{code, why}}, Some{""})
4338    case ErrTimeout{}:
4339      (Fail{ErrTimeout{}}, Some{""})
4340    case other:
4341      (Fail{other}, None{})
4342
4343def retry.res(res: Res) -> Result<&1, &1, Err, Res> & Maybe<&2, String>:
4344  Res{+status, +headers, body} = res
4345  (Done{Res{status, headers, body}}, Bool.pick(Maybe<&2, String>, retry.status(status), Some{header(headers, "retry-after")}, None{}))
4346
4347def retry.judge.try(r: Result<&1, &1, Err, Res>) -> Result<&1, &1, Err, Res> & Maybe<&2, String>:
4348  match r:
4349    case Fail{e}:
4350      retry.fail(e)
4351    case Done{res}:
4352      retry.res(res)
4353
4354# One try, judged: the result as it came, and Some{Retry-After value} ("" when absent)
4355# when an idempotent request may try again.
4356def retry.judge(idem: Bool, r: Result<&1, &1, Err, Res>) -> Result<&1, &1, Err, Res> & Maybe<&2, String>:
4357  match idem:
4358    case False{}:
4359      (r, None{})
4360    case True{}:
4361      retry.judge.try(r)
4362
4363# ponytail: a failed random source gives jitter 0, so the wait is the lower half.
4364def retry.jitter(r: Result<&1, &1, U32 & String, U32>) -> U32:
4365  match r:
4366    case Fail{e}:
4367      0
4368    case Done{x}:
4369      x
4370
4371def retry.sleep(+v: String, n: Nat) -> IO(Unit):
4372  do IO<Unit>:
4373    now : Time.Instant <- Time.now()
4374    rnd : Result<&1, &1, U32 & String, U32> <- IO.random_u32()
4375    IO.sleep(retry.delay(v, now, n, retry.jitter(rnd)))
4376
4377def retry.kept(body: Bytes.Bytes, j: Result<&1, &1, Err, Res> & Maybe<&2, String>) -> Bytes.Bytes & Result<&1, &1, Err, Res> & Maybe<&2, String>:
4378  (r, m) = j
4379  (body, r, m)
4380
4381# One fetch of the copy; the body comes back for the next try.
4382def retry.one(+idem: Bool, +method: String, +url: String, +headers: Map<&2, List<&2, String>>,
4383    r: Bytes.Bytes & Bytes.Bytes) -> IO(Bytes.Bytes & Result<&1, &1, Err, Res> & Maybe<&2, String>):
4384  (body, spare) = r
4385  do IO<Bytes.Bytes & Result<&1, &1, Err, Res> & Maybe<&2, String>>:
4386    got : Result<&1, &1, Err, Res> <- fetch(method, url, headers, spare)
4387    return retry.kept(body, retry.judge(idem, got))
4388
4389# left: retries still allowed. n: the retry to wait for next, 0 first.
4390def retry.go(left: Nat, +n: Nat, +idem: Bool, +method: String, +url: String,
4391    +headers: Map<&2, List<&2, String>>,
4392    t: Bytes.Bytes & Result<&1, &1, Err, Res> & Maybe<&2, String>) -> IO(Result<&1, &1, Err, Res>):
4393  match left:
4394    case 0n:
4395      (body, r, m) = t
4396      IO.pure(Result<&1, &1, Err, Res>, r)
4397    case 1n+p:
4398      (body, r, m) = t
4399      match m:
4400        case None{}:
4401          IO.pure(Result<&1, &1, Err, Res>, r)
4402        case Some{v}:
4403          do IO<Result<&1, &1, Err, Res>>:
4404            retry.sleep(v, n)
4405            tried : Bytes.Bytes & Result<&1, &1, Err, Res> & Maybe<&2, String> <-
4406              retry.one(idem, method, url, headers, Bytes.slice(body, 0, 4294967295))
4407            retry.go(p, 1n+n, idem, method, url, headers, tried)
4408
4409# fetch.retry(n, method, url, headers, body) is fetch, tried again up to n times while an
4410# idempotent method (GET, HEAD, OPTIONS, TRACE, PUT, DELETE) gets a connect error, a timeout,
4411# or 408, 429, 500, 502, 503, or 504. POST, PATCH and other methods get one try. It waits
4412# Retry-After (seconds or HTTP-date, at most 30 s) when given, else the backoff. When retries
4413# run out, the last response or error comes back as it was.
4414def retry.start(enabled: Bool, n: U32, +method: String, +url: String,
4415    +headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) ->
4416    IO(Result<&1, &1, Err, Res>):
4417  match enabled:
4418    case False{}:
4419      fetch(method, url, headers, body)
4420    case True{}:
4421      do IO<Result<&1, &1, Err, Res>>:
4422        first : Bytes.Bytes & Result<&1, &1, Err, Res> & Maybe<&2, String> <-
4423          retry.one(True{}, method, url, headers, Bytes.slice(body, 0, 4294967295))
4424        retry.go(U32.to_nat(n), 0n, True{}, method, url, headers, first)
4425
4426def fetch.retry(+n: U32, +method: String, +url: String,
4427    +headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) ->
4428    IO(Result<&1, &1, Err, Res>):
4429  retry.start(Bool.and(U32.is_ne(n, 0), pool.idempotent(method)),
4430    n, method, url, headers, body)
4431
4432# Streaming (a body read or sent in pieces). A decoded stream owns its decoders.
4433# What the next read returns: read more, a raw piece, a decoded piece, the end, or an error.
4434type Po is Type:
4435  PoNone{}
4436  PoPiece{b: Bytes.Bytes}
4437  PoReady{b: Bytes.Bytes}
4438  PoEnd{}
4439  PoBad{e: Err}
4440
4441type Stream is Type:
4442  Stream{tls: Bool, s: Socket, ms: U32, res: Res, rb: Rb, out: Po, decs: List<&1, Zlib.Decoder>}
4443
4444type Pc is Type:
4445  Pc{rb: Rb, out: Po}
4446
4447# A body piece, or none when empty: more reads the next piece, and not more is the end.
4448def pc.po(more: Bool, empty: Bool, b: Bytes.Bytes) -> Po:
4449  match empty:
4450    case True{}:
4451      Bool.pick(Po, more, PoNone{}, PoEnd{})
4452    case False{}:
4453      PoPiece{b}
4454
4455def pc.piece(more: Bool, +rb: Rb, b: Bytes.Bytes) -> Pc:
4456  Bytes.Bytes{+len, buf} = b
4457  Pc{rb, pc.po(more, U32.is_zero(len), Bytes.Bytes{len, buf})}
4458
4459def pc.fed.of(b: Bytes.Bytes, st: Rb) -> Pc:
4460  match st:
4461    case RbDone{}:
4462      pc.piece(False{}, RbDone{}, b)
4463    case RbBad{}:
4464      Pc{RbDone{}, PoBad{ErrBad{}}}
4465    case RbLen{n}:
4466      pc.piece(True{}, RbLen{n}, b)
4467    case RbChunk{st}:
4468      pc.piece(True{}, RbChunk{st}, b)
4469    case RbClose{}:
4470      pc.piece(True{}, RbClose{}, b)
4471
4472def pc.fed(bf: Bf) -> Pc:
4473  Bf{st, parts, rest} = bf
4474  pc.fed.of(rb.body(parts), st)
4475
4476# The body bytes that just arrived: what they add to the body, and how it ends.
4477def pc.of(rb: Rb, piece: Bytes.Bytes) -> Pc:
4478  pc.fed(rb.feed(rb, Nil{}, piece))
4479
4480# The server closed. Only a close-delimited body may end this way (RFC 9112 §8).
4481def pc.end(ok: Bool) -> Pc:
4482  match ok:
4483    case True{}:
4484      Pc{RbDone{}, PoEnd{}}
4485    case False{}:
4486      Pc{RbDone{}, PoBad{ErrBad{}}}
4487
4488def pc.eof(st: Rb) -> Pc:
4489  pc.end(rb.eof(st))
4490
4491def stream.mk(+tls: Bool, s: Socket, +ms: U32, res: Res, decs: List<&1, Zlib.Decoder>, pc: Pc) -> Stream:
4492  Pc{rb, out} = pc
4493  Stream{tls, s, ms, res, rb, out, decs}
4494
4495def stream.got.piece(+tls: Bool, s: Socket, +ms: U32, res: Res, decs: List<&1, Zlib.Decoder>, +rb: Rb, p: U32 & Array<U32>) -> Stream:
4496  (+len, buf) = p
4497  stream.mk(tls, s, ms, res, decs, Bool.pick(Pc, U32.is_zero(len), pc.eof(rb), pc.of(rb, Bytes.Bytes{len, buf})))
4498
4499def stream.got(+tls: Bool, +ms: U32, res: Res, decs: List<&1, Zlib.Decoder>, +rb: Rb, m: Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>) -> Stream:
4500  (s, r) = m
4501  match r:
4502    case Fail{(+code, why)}:
4503      Stream{tls, s, ms, res, RbDone{}, PoBad{err.or_late(code, ErrRead{code, why})}, decs}
4504    case Done{p}:
4505      stream.got.piece(tls, s, ms, res, decs, rb, p)
4506
4507def stream.after(+rb: Rb) -> Po:
4508  match rb:
4509    case RbDone{}:
4510      PoEnd{}
4511    case RbBad{}:
4512      PoEnd{}
4513    case RbLen{n}:
4514      PoNone{}
4515    case RbChunk{st}:
4516      PoNone{}
4517    case RbClose{}:
4518      PoNone{}
4519
4520type Fed is Type:
4521  Fed{decs: List<&1, Zlib.Decoder>, body: Result<&1, &1, Err, Bytes.Bytes>}
4522
4523def stream.feed.received(done: List<&1, Zlib.Decoder>, m: Zlib.Decoder & Result<&1, &1, U32 & String, U32 & Array<U32>>) -> Fed:
4524  (d, r) = m
4525  match r:
4526    case Fail{e}:
4527      Fed{d <> done, Fail{ErrBad{}}}
4528    case Done{(+len, buf)}:
4529      Fed{d <> done, Done{Bytes.Bytes{len, buf}}}
4530
4531def stream.feed.step(st: Fed, d: Zlib.Decoder) -> IO(Fed):
4532  Fed{done, body} = st
4533  match body:
4534    case Fail{e}:
4535      IO.pure(Fed, Fed{d <> done, Fail{e}})
4536    case Done{b}:
4537      Bytes.Bytes{+len, buf} = b
4538      do IO<Fed>:
4539        m : Zlib.Decoder & Result<&1, &1, U32 & String, U32 & Array<U32>> <-
4540          Zlib.dec.feed.words(d, 16777216, len, buf)
4541        return stream.feed.received(done, m)
4542
4543def stream.feed.one(prev: IO(Fed), d: Zlib.Decoder) -> IO(Fed):
4544  do IO<Fed>:
4545    st : Fed <- prev
4546    stream.feed.step(st, d)
4547
4548def stream.feed.reverse(st: Fed) -> Fed:
4549  Fed{done, body} = st
4550  Fed{List.reverse(&1, Zlib.Decoder, done), body}
4551
4552def stream.feed.all(decs: List<&1, Zlib.Decoder>, b: Bytes.Bytes) -> IO(Fed):
4553  do IO<Fed>:
4554    st : Fed <- List.foldl(~&1, ~Zlib.Decoder, ~IO(Fed), ~stream.feed.one, decs,
4555      IO.pure(Fed, Fed{Nil{}, Done{b}}))
4556    return stream.feed.reverse(st)
4557
4558def stream.ready(empty: Bool, +rb: Rb, b: Bytes.Bytes) -> Po:
4559  match empty:
4560    case True{}:
4561      stream.after(rb)
4562    case False{}:
4563      PoReady{b}
4564
4565def stream.feed.got(+tls: Bool, s: Socket, +ms: U32, res: Res, +rb: Rb, st: Fed) -> Stream:
4566  Fed{decs, body} = st
4567  match body:
4568    case Fail{e}:
4569      Stream{tls, s, ms, res, rb, PoBad{e}, decs}
4570    case Done{b}:
4571      Bytes.Bytes{+len, buf} = b
4572      Stream{tls, s, ms, res, rb, stream.ready(U32.is_zero(len), rb, Bytes.Bytes{len, buf}), decs}
4573
4574def stream.feed.st(st: Stream, b: Bytes.Bytes) -> IO(Stream):
4575  Stream{+tls, s, +ms, res, +rb, out, decs} = st
4576  match decs:
4577    case Nil{}:
4578      IO.pure(Stream, Stream{tls, s, ms, res, rb, PoReady{b}, Nil{}})
4579    case Con{d, rest}:
4580      do IO<Stream>:
4581        fed : Fed <- stream.feed.all(Con{d, rest}, b)
4582        return stream.feed.got(tls, s, ms, res, rb, fed)
4583
4584def stream.finish.ok(r: Result<&1, &1, U32 & String, Unit>) -> Bool:
4585  match r:
4586    case Fail{e}:
4587      False{}
4588    case Done{u}:
4589      True{}
4590
4591def stream.finish(decs: List<&1, Zlib.Decoder>) -> IO(Bool):
4592  match decs:
4593    case Nil{}:
4594      IO.pure(Bool, True{})
4595    case Con{d, rest}:
4596      do IO<Bool>:
4597        r : Result<&1, &1, U32 & String, Unit> <- Zlib.dec.finish(d)
4598        tail : Bool <- stream.finish(rest)
4599        return Bool.and(stream.finish.ok(r), tail)
4600
4601def stream.ended(good: Bool, +tls: Bool, s: Socket, +ms: U32, res: Res, +rb: Rb) ->
4602  Stream & Result<&1, &1, Err, Maybe<&1, Bytes.Bytes>>:
4603  match good:
4604    case True{}:
4605      (Stream{tls, s, ms, res, rb, PoEnd{}, Nil{}}, Done{None{}})
4606    case False{}:
4607      (Stream{tls, s, ms, res, rb, PoBad{ErrBad{}}, Nil{}}, Fail{ErrBad{}})
4608
4609# The next piece of the body; None at the end. A piece is never empty.
4610@unsafe
4611def stream.read(st: Stream) -> IO(Stream & Result<&1, &1, Err, Maybe<&1, Bytes.Bytes>>):
4612  Stream{+tls, s, +ms, res, +rb, out, decs} = st
4613  match out:
4614    case PoPiece{b}:
4615      do IO<Stream & Result<&1, &1, Err, Maybe<&1, Bytes.Bytes>>>:
4616        next : Stream <- stream.feed.st(Stream{tls, s, ms, res, rb, PoNone{}, decs}, b)
4617        stream.read(next)
4618    case PoReady{b}:
4619      IO.pure(Stream & Result<&1, &1, Err, Maybe<&1, Bytes.Bytes>>,
4620        (Stream{tls, s, ms, res, rb, stream.after(rb), decs}, Done{Some{b}}))
4621    case PoEnd{}:
4622      do IO<Stream & Result<&1, &1, Err, Maybe<&1, Bytes.Bytes>>>:
4623        good : Bool <- stream.finish(decs)
4624        return stream.ended(good, tls, s, ms, res, rb)
4625    case PoBad{+e}:
4626      IO.pure(Stream & Result<&1, &1, Err, Maybe<&1, Bytes.Bytes>>,
4627        (Stream{tls, s, ms, res, rb, PoBad{e}, decs}, Fail{e}))
4628    case PoNone{}:
4629      do IO<Stream & Result<&1, &1, Err, Maybe<&1, Bytes.Bytes>>>:
4630        m : Socket & Result<&1, &1, U32 & String, U32 & Array<U32>> <- io.recv.words(tls, s, 65536, ms)
4631        stream.read(stream.got(tls, ms, res, decs, rb, m))
4632
4633# Status and headers. Its body is empty: read the body with stream.read.
4634def stream.res(st: Stream) -> Stream & Res:
4635  Stream{tls, s, ms, res, rb, out, decs} = st
4636  Res{+status, +headers, body} = res
4637  (Stream{tls, s, ms, Res{status, headers, body}, rb, out, decs}, Res{status, headers, Bytes.new(0)})
4638
4639def stream.close(st: Stream) -> IO(Unit):
4640  Stream{tls, s, ms, res, rb, out, decs} = st
4641  do IO<Unit>:
4642    good : Bool <- stream.finish(decs)
4643    io.close(tls, s)
4644
4645# Head read state: still scanning, cut short or bad, or the head with the bytes after it.
4646type Sh is Type:
4647  ShMore{buf: Bytes.Bytes, k: U32}
4648  ShBad{err: Maybe<&2, Err>}
4649  ShRes{res: Res, rb: Rb, rest: Bytes.Bytes}
4650
4651def sh.of(hs: Hs) -> Sh:
4652  match hs:
4653    case HsWait{buf, k}:
4654      ShMore{buf, k}
4655    case HsBad{}:
4656      ShBad{None{}}
4657    case HsSeek{buf, from, k}:
4658      ShBad{None{}}
4659    case HsRes{res, rb, rest}:
4660      ShRes{res, rb, rest}
4661
4662def sh.piece(+head: Bool, buf: Bytes.Bytes, +k: U32, p: U32 & Array<U32>) -> Sh:
4663  (+len, b) = p
4664  Bool.pick(Sh, U32.is_zero(len), ShBad{None{}}, sh.of(hs.more(head, k, buf, Bytes.Bytes{len, b})))
4665
4666def sh.next(+head: Bool, buf: Bytes.Bytes, +k: U32, m: Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>) -> Socket & Sh:
4667  (s, r) = m
4668  match r:
4669    case Fail{(+code, why)}:
4670      (s, ShBad{Some{err.or_late(code, ErrRead{code, why})}})
4671    case Done{p}:
4672      (s, sh.piece(head, buf, k, p))
4673
4674def fetch.fail.of(r: Result<&1, &1, Err, Res>) -> Result<&1, &1, Err, Stream>:
4675  match r:
4676    case Fail{e}:
4677      Fail{e}
4678    case Done{res}:
4679      Fail{ErrBad{}}
4680
4681# Reads until the final head is in; the body bytes that came with it are the first piece.
4682@unsafe
4683def stream.head(+tls: Bool, +ms: U32, +head: Bool, st: Socket & Sh) -> IO(Result<&1, &1, Err, Stream>):
4684  (s, sh) = st
4685  match sh:
4686    case ShMore{buf, +k}:
4687      do IO<Result<&1, &1, Err, Stream>>:
4688        m : Socket & Result<&1, &1, U32 & String, U32 & Array<U32>> <- io.recv.words(tls, s, 65536, ms)
4689        stream.head(tls, ms, head, sh.next(head, buf, k, m))
4690    case ShBad{err}:
4691      do IO<Result<&1, &1, Err, Stream>>:
4692        r : Result<&1, &1, Err, Res> <- fetch.bad(tls, s, err)
4693        return fetch.fail.of(r)
4694    case ShRes{res, rb, rest}:
4695      IO.pure(Result<&1, &1, Err, Stream>, Done{stream.mk(tls, s, ms, res, Nil{}, pc.of(rb, rest))})
4696
4697def stream.sent(+tls: Bool, +ms: U32, +head: Bool, m: Socket & Result<&1, &1, U32 & String, Unit>) -> IO(Result<&1, &1, Err, Stream>):
4698  (s, r) = m
4699  match r:
4700    case Fail{(+code, why)}:
4701      do IO<Result<&1, &1, Err, Stream>>:
4702        io.close(tls, s)
4703        return Fail{err.or_late(code, ErrWrite{code, why})}
4704    case Done{u}:
4705      stream.head(tls, ms, head, (s, ShMore{Bytes.new(0), 0}))
4706
4707def stream.conn(r: Result<&1, &1, Err, Conn>, +ms: U32, +head: Bool, wire: Bytes.Bytes) -> IO(Result<&1, &1, Err, Stream>):
4708  match r:
4709    case Fail{e}:
4710      IO.pure(Result<&1, &1, Err, Stream>, Fail{e})
4711    case Done{c}:
4712      match c:
4713        case Conn{+tls, s}:
4714          do IO<Result<&1, &1, Err, Stream>>:
4715            sent : Socket & Result<&1, &1, U32 & String, Unit> <- io.send.bytes(tls, s, wire)
4716            stream.sent(tls, ms, head, sent)
4717        case ConnH2{s, client}:
4718          do IO<Result<&1, &1, Err, Stream>>:
4719            Wire.tls.close(s)
4720            return Fail{ErrBad{}}
4721
4722# One connection per stream; the request says close.
4723def stream.origin(+ms: U32, +head: Bool, wire: Bytes.Bytes, a: Url.Abs, known: Bool) -> IO(Result<&1, &1, Err, Stream>):
4724  Url.Abs{+scheme, +host, +port, target} = a
4725  match known:
4726    case False{}:
4727      IO.pure(Result<&1, &1, Err, Stream>, Fail{ErrUrl{}})
4728    case True{}:
4729      do IO<Result<&1, &1, Err, Stream>>:
4730        ips : List<&2, String> <- Dns.resolve.all(host)
4731        c : Result<&1, &1, Err, Conn> <- conn.open.all(String.eq(scheme, "https"), ms, host, port, ips, None{}, False{})
4732        stream.conn(c, ms, head, wire)
4733
4734def stream.one.of(+method: String, +url: Url.Abs, +headers: Map<&2, List<&2, String>>, +ms: U32, r: Bytes.Bytes & Bytes.Bytes) -> IO(Hop & Result<&1, &1, Err, Stream>):
4735  Url.Abs{scheme, host, port, +target} = url
4736  (body, wire) = r
4737  do IO<Hop & Result<&1, &1, Err, Stream>>:
4738    got : Result<&1, &1, Err, Stream> <- stream.origin(ms, String.eq(method, "HEAD"), encode_req.on(method, target, Url.host_field(url), headers, wire, True{}), url, pool.scheme.ok(url))
4739    return (Hop{method, url, headers, body}, got)
4740
4741# One request on its own connection. The hop comes back for the redirect.
4742def stream.one(h: Hop, +ms: U32) -> IO(Hop & Result<&1, &1, Err, Stream>):
4743  Hop{+method, +url, +headers, body} = h
4744  stream.one.of(method, url, headers, ms, Bytes.slice(body, 0, 4294967295))
4745
4746# Go: the next request. Drop: close this stream, then go on. Done: the answer.
4747type Sn is Type:
4748  SnGo{left: Nat, hop: Hop}
4749  SnDrop{st: Stream, next: Next}
4750  SnDone{r: Result<&1, &1, Err, Stream>}
4751
4752def sn.of(n: Next) -> Sn:
4753  match n:
4754    case NGo{l, h}:
4755      SnGo{l, h}
4756    case NStop{}:
4757      SnDone{Fail{ErrRedirect{}}}
4758    case NDone{m}:
4759      match m:
4760        case Fail{e}:
4761          SnDone{Fail{e}}
4762        case Done{r}:
4763          SnDone{Fail{ErrBad{}}}
4764
4765def stream.decide.n(st: Stream, n: Next) -> Sn:
4766  match n:
4767    case NDone{m}:
4768      SnDone{Done{st}}
4769    case NGo{l, h}:
4770      SnDrop{st, NGo{l, h}}
4771    case NStop{}:
4772      SnDrop{st, NStop{}}
4773
4774def stream.decide.of(+left: Nat, hop: Hop, sr: Stream & Res) -> Sn:
4775  (st, res) = sr
4776  stream.decide.n(st, fetch.decide(left, hop, Done{res}))
4777
4778def stream.decide(+left: Nat, x: Hop & Result<&1, &1, Err, Stream>) -> Sn:
4779  (hop, r) = x
4780  match r:
4781    case Fail{e}:
4782      SnDone{Fail{e}}
4783    case Done{st}:
4784      stream.decide.of(left, hop, stream.res(st))
4785
4786@unsafe
4787def stream.hops(+ms: U32, sn: Sn) -> IO(Result<&1, &1, Err, Stream>):
4788  match sn:
4789    case SnDone{r}:
4790      IO.pure(Result<&1, &1, Err, Stream>, r)
4791    case SnGo{+left, hop}:
4792      do IO<Result<&1, &1, Err, Stream>>:
4793        x : Hop & Result<&1, &1, Err, Stream> <- stream.one(hop, ms)
4794        stream.hops(ms, stream.decide(left, x))
4795    case SnDrop{st, next}:
4796      do IO<Result<&1, &1, Err, Stream>>:
4797        stream.close(st)
4798        stream.hops(ms, sn.of(next))
4799
4800type Opened is Type:
4801  Opened{decs: List<&1, Zlib.Decoder>, bad: Bool}
4802
4803def stream.open.got(st: Opened, r: Result<&1, &1, U32 & String, Zlib.Decoder>) -> Opened:
4804  Opened{decs, bad} = st
4805  match r:
4806    case Fail{e}:
4807      Opened{decs, True{}}
4808    case Done{d}:
4809      Opened{d <> decs, bad}
4810
4811def stream.open.add(st: Opened, m: IO(Result<&1, &1, U32 & String, Zlib.Decoder>)) -> IO(Opened):
4812  do IO<Opened>:
4813    r : Result<&1, &1, U32 & String, Zlib.Decoder> <- m
4814    return stream.open.got(st, r)
4815
4816def stream.open.zstd(zstd: Bool, st: Opened) -> IO(Opened):
4817  match zstd:
4818    case True{}:
4819      stream.open.add(st, Zlib.zstd.new())
4820    case False{}:
4821      IO.pure(Opened, st)
4822
4823def stream.open.br(br: Bool, +c: String, st: Opened) -> IO(Opened):
4824  match br:
4825    case True{}:
4826      stream.open.add(st, Zlib.brotli.new())
4827    case False{}:
4828      stream.open.zstd(String.eq(c, "zstd"), st)
4829
4830def stream.open.gz(gz: Bool, +c: String, st: Opened) -> IO(Opened):
4831  match gz:
4832    case True{}:
4833      stream.open.add(st, Zlib.inflate.new())
4834    case False{}:
4835      stream.open.br(String.eq(c, "br"), c, st)
4836
4837def stream.open.step(+c: String, st: Opened) -> IO(Opened):
4838  Opened{decs, bad} = st
4839  match bad:
4840    case True{}:
4841      IO.pure(Opened, Opened{decs, True{}})
4842    case False{}:
4843      stream.open.gz(Bool.or(String.eq(c, "gzip"), Bool.or(String.eq(c, "x-gzip"), String.eq(c, "deflate"))),
4844        c, Opened{decs, False{}})
4845
4846def stream.open.one(prev: IO(Opened), c: String) -> IO(Opened):
4847  do IO<Opened>:
4848    st : Opened <- prev
4849    stream.open.step(c, st)
4850
4851def stream.open.all(cs: List<&2, String>) -> IO(Opened):
4852  List.foldl(~&2, ~String, ~IO(Opened), ~stream.open.one, cs, IO.pure(Opened, Opened{Nil{}, False{}}))
4853
4854def stream.put.decs(st: Stream, decs: List<&1, Zlib.Decoder>) -> Stream:
4855  Stream{tls, s, ms, res, rb, out, old} = st
4856  Stream{tls, s, ms, res, rb, out, decs}
4857
4858def stream.init.opened(st: Stream, opened: Opened) -> IO(Result<&1, &1, Err, Stream>):
4859  Opened{decs, bad} = opened
4860  match bad:
4861    case True{}:
4862      do IO<Result<&1, &1, Err, Stream>>:
4863        stream.close(stream.put.decs(st, decs))
4864        return Fail{ErrBad{}}
4865    case False{}:
4866      IO.pure(Result<&1, &1, Err, Stream>, Done{stream.put.decs(st, List.reverse(&1, Zlib.Decoder, decs))})
4867
4868def stream.init.known(known: Bool, st: Stream, cs: List<&2, String>) -> IO(Result<&1, &1, Err, Stream>):
4869  match known:
4870    case False{}:
4871      IO.pure(Result<&1, &1, Err, Stream>, Done{st})
4872    case True{}:
4873      do IO<Result<&1, &1, Err, Stream>>:
4874        opened : Opened <- stream.open.all(cs)
4875        stream.init.opened(st, opened)
4876
4877def stream.init.st(+enc: String, st: Stream) -> IO(Result<&1, &1, Err, Stream>):
4878  Stream{tls, s, ms, res, rb, out, decs} = st
4879  Res{+status, +headers, body} = res
4880  +cs = List.reverse(&2, String, ce.split(fields(headers, "content-encoding")))
4881  stream.init.known(ce.known(cs, Con{"identity", Con{"x-gzip", ce.split(Con{enc, Nil{}})}}),
4882    Stream{tls, s, ms, Res{status, headers, body}, rb, out, decs}, cs)
4883
4884def stream.init(+enc: String, r: Result<&1, &1, Err, Stream>) -> IO(Result<&1, &1, Err, Stream>):
4885  match r:
4886    case Fail{e}:
4887      IO.pure(Result<&1, &1, Err, Stream>, Fail{e})
4888    case Done{st}:
4889      stream.init.st(enc, st)
4890
4891def stream.start(method: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, u: Maybe<&2, Url.Abs>) -> Sn:
4892  match u:
4893    case None{}:
4894      SnDone{Fail{ErrUrl{}}}
4895    case Some{a}:
4896      SnGo{20n, Hop{method, a, req.put(Map.to_list(&2, List<&2, String>, headers), empty()), body}}
4897
4898# Open a raw stream. Its body bytes and headers remain as sent.
4899def open.raw.with(method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, +ms: U32) -> IO(Result<&1, &1, Err, Stream>):
4900  stream.hops(ms, stream.start(method, headers, body, Url.absolute(url)))
4901
4902def open.raw(method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Result<&1, &1, Err, Stream>):
4903  open.raw.with(method, url, headers, body, 30000)
4904
4905def open.with.enc(+enc: String, method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, +ms: U32) -> IO(Result<&1, &1, Err, Stream>):
4906  do IO<Result<&1, &1, Err, Stream>>:
4907    r : Result<&1, &1, Err, Stream> <-
4908      stream.hops(ms, stream.start(method, accept.enc(headers, enc), body, Url.absolute(url)))
4909    stream.init(enc, r)
4910
4911# Follow redirects, then decode each body piece by Content-Encoding. Unknown codings stay raw.
4912def open.with(method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, +ms: U32) -> IO(Result<&1, &1, Err, Stream>):
4913  do IO<Result<&1, &1, Err, Stream>>:
4914    enc : String <- codings()
4915    open.with.enc(enc, method, url, headers, body, ms)
4916
4917def open(method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Result<&1, &1, Err, Stream>):
4918  open.with(method, url, headers, body, 30000)
4919
4920# Upload: the request body sent in chunks (RFC 9112 §7.1). err: the first failed write.
4921type Up is Type:
4922  Up{tls: Bool, s: Socket, ms: U32, head: Bool, err: Maybe<&2, Err>}
4923
4924def hex.digit(+n: U32) -> Char:
4925  Chr{Bool.pick(U32, U32.is_lt(n, 10), (48 + n : U32), (87 + n : U32))}
4926
4927def hex.go(k: Nat, +n: U32, acc: String) -> String:
4928  match k:
4929    case 0n:
4930      acc
4931    case 1n+p:
4932      hex.go(p, U32.shrn(n, 4n), SCon{hex.digit(U32.and(n, 15)), acc})
4933
4934def hex.trim(+s: String) -> String:
4935  match s:
4936    case SNil{}:
4937      SNil{}
4938    case SCon{Chr{+c}, +t}:
4939      Bool.pick(String, Bool.and(U32.is_eq(c, 48), Bool.not(String.is_empty(t))), hex.trim(t), SCon{Chr{c}, t})
4940
4941def hex(+n: U32) -> String:
4942  hex.trim(hex.go(8n, n, ""))
4943
4944def up.sent(+tls: Bool, +ms: U32, +head: Bool, m: Socket & Result<&1, &1, U32 & String, Unit>) -> Up:
4945  (s, r) = m
4946  match r:
4947    case Fail{(+code, why)}:
4948      Up{tls, s, ms, head, Some{err.or_late(code, ErrWrite{code, why})}}
4949    case Done{u}:
4950      Up{tls, s, ms, head, None{}}
4951
4952def up.conn(r: Result<&1, &1, Err, Conn>, +ms: U32, +head: Bool, wire: String) -> IO(Result<&1, &1, Err, Up>):
4953  match r:
4954    case Fail{e}:
4955      IO.pure(Result<&1, &1, Err, Up>, Fail{e})
4956    case Done{c}:
4957      match c:
4958        case Conn{+tls, s}:
4959          do IO<Result<&1, &1, Err, Up>>:
4960            sent : Socket & Result<&1, &1, U32 & String, Unit> <- io.send.bytes(tls, s, Bytes.from_string(wire))
4961            return Done{up.sent(tls, ms, head, sent)}
4962        case ConnH2{s, client}:
4963          do IO<Result<&1, &1, Err, Up>>:
4964            Wire.tls.close(s)
4965            return Fail{ErrBad{}}
4966
4967def up.head(+method: String, +target: String, +hf: String, +headers: Map<&2, List<&2, String>>) -> String:
4968  request(method, target, set(set(set(req.put(Map.to_list(&2, List<&2, String>, headers), empty()), "host", hf), "connection", "close"), "transfer-encoding", "chunked"), "")
4969
4970def up.origin(+method: String, +ms: U32, headers: Map<&2, List<&2, String>>, a: Url.Abs, known: Bool) -> IO(Result<&1, &1, Err, Up>):
4971  Url.Abs{+scheme, +host, +port, +target} = a
4972  match known:
4973    case False{}:
4974      IO.pure(Result<&1, &1, Err, Up>, Fail{ErrUrl{}})
4975    case True{}:
4976      do IO<Result<&1, &1, Err, Up>>:
4977        ips : List<&2, String> <- Dns.resolve.all(host)
4978        c : Result<&1, &1, Err, Conn> <- conn.open.all(String.eq(scheme, "https"), ms, host, port, ips, None{}, False{})
4979        up.conn(c, ms, String.eq(method, "HEAD"), up.head(method, target, Url.host_field(a), headers))
4980
4981def up.url(+method: String, +ms: U32, headers: Map<&2, List<&2, String>>, u: Maybe<&2, Url.Abs>) -> IO(Result<&1, &1, Err, Up>):
4982  match u:
4983    case None{}:
4984      IO.pure(Result<&1, &1, Err, Up>, Fail{ErrUrl{}})
4985    case Some{+a}:
4986      up.origin(method, ms, headers, a, pool.scheme.ok(a))
4987
4988# Http.upload(method, url, headers) sends the head. A streamed body cannot be replayed, so redirects are not followed.
4989def upload.with(+method: String, url: String, headers: Map<&2, List<&2, String>>, +ms: U32) -> IO(Result<&1, &1, Err, Up>):
4990  up.url(method, ms, headers, Url.absolute(url))
4991
4992def upload(+method: String, url: String, headers: Map<&2, List<&2, String>>) -> IO(Result<&1, &1, Err, Up>):
4993  upload.with(method, url, headers, 30000)
4994
4995def up.wrote(+tls: Bool, +ms: U32, +head: Bool, m: Socket & Result<&1, &1, U32 & String, Unit>) -> Up & Result<&2, &2, Err, Unit>:
4996  (s, r) = m
4997  match r:
4998    case Fail{(+code, why)}:
4999      +e = err.or_late(code, ErrWrite{code, why})
5000      (Up{tls, s, ms, head, Some{e}}, Fail{e})
5001    case Done{u}:
5002      (Up{tls, s, ms, head, None{}}, Done{Unit{}})
5003
5004# One write per chunk, so the size line and the data do not wait on each other (Nagle).
5005def up.put(+tls: Bool, s: Socket, +ms: U32, +head: Bool, +len: U32, piece: Bytes.Bytes, skip: Bool) -> IO(Up & Result<&2, &2, Err, Unit>):
5006  match skip:
5007    case True{}:
5008      IO.pure(Up & Result<&2, &2, Err, Unit>, (Up{tls, s, ms, head, None{}}, Done{Unit{}}))
5009    case False{}:
5010      do IO<Up & Result<&2, &2, Err, Unit>>:
5011        sent : Socket & Result<&1, &1, U32 & String, Unit> <- io.send.bytes(tls, s, Bytes.concat(Con{Bytes.from_string(hex(len) ++ "\r\n"), Con{piece, Con{Bytes.from_string("\r\n"), Nil{}}}}))
5012        return up.wrote(tls, ms, head, sent)
5013
5014def up.chunk(+tls: Bool, s: Socket, +ms: U32, +head: Bool, piece: Bytes.Bytes) -> IO(Up & Result<&2, &2, Err, Unit>):
5015  Bytes.Bytes{+len, buf} = piece
5016  up.put(tls, s, ms, head, len, Bytes.Bytes{len, buf}, U32.is_zero(len))
5017
5018# One chunk. An empty piece sends nothing, since an empty chunk would end the body.
5019def upload.write(up: Up, piece: Bytes.Bytes) -> IO(Up & Result<&2, &2, Err, Unit>):
5020  Up{+tls, s, +ms, +head, err} = up
5021  match err:
5022    case Some{+e}:
5023      IO.pure(Up & Result<&2, &2, Err, Unit>, (Up{tls, s, ms, head, Some{e}}, Fail{e}))
5024    case None{}:
5025      up.chunk(tls, s, ms, head, piece)
5026
5027# Ends the body and returns the response as a stream.
5028def upload.finish(up: Up) -> IO(Result<&1, &1, Err, Stream>):
5029  Up{+tls, s, +ms, +head, err} = up
5030  match err:
5031    case Some{e}:
5032      do IO<Result<&1, &1, Err, Stream>>:
5033        io.close(tls, s)
5034        return Fail{e}
5035    case None{}:
5036      do IO<Result<&1, &1, Err, Stream>>:
5037        sent : Socket & Result<&1, &1, U32 & String, Unit> <- io.send.bytes(tls, s, Bytes.from_string("0\r\n\r\n"))
5038        stream.sent(tls, ms, head, sent)
5039
5040type ServerConfig is Data:
5041  ServerConfig{host: String, port: U32, body_bytes: U32, header_bytes: U32,
5042    connections: U32, requests: U32, buffered: U32, header_ms: U32, body_ms: U32,
5043    idle_ms: U32, write_ms: U32}
5044
5045# Shared framing settings; all live readers reserve admission before allocation.
5046type Limits is Data:
5047  Limits{body: Nat, headers: U32, header_ms: U32, body_ms: U32, idle_ms: U32, write_ms: U32}
5048
5049# Bytes.words rounds with len+3 in U32. A retained cap plus the fixed 65536
5050# receive overshoot must still fit before that addition, including temporary copies.
5051def limits.representable() -> U32:
5052  4294901756
5053
5054def limits.validate.ok(valid: Bool) -> IO(Unit):
5055  match valid:
5056    case True{}:
5057      IO.pure(Unit, Unit{})
5058    case False{}:
5059      IO.die(Unit, 22, "request cap plus 65536-byte recv overshoot and 3-byte packed rounding must fit U32")
5060
5061def limits.validate(+max: Nat) -> IO(Unit):
5062  limits.validate.ok(Nat.is_gt(max, 0n) && Nat.is_le(max, U32.to_nat(limits.representable())))
5063
5064def limits(max: Nat) -> Limits:
5065  Limits{max, 65536, 5000, 30000, 30000, 30000}
5066
5067def limits.config(config: ServerConfig) -> Limits:
5068  ServerConfig{host, port, body, headers, connections, requests, buffered, header_ms, body_ms, idle_ms, write_ms} = config
5069  Limits{U32.to_nat(body), headers, header_ms, body_ms, idle_ms, write_ms}
5070
5071# One absolute deadline, never replenished by progress.
5072type Phase is Data:
5073  Phase{kind: U32, until: Time.Duration}
5074
5075def phase.new(+kind: U32, ms: U32, now: Time.Duration) -> Phase:
5076  Phase{kind, Time.Duration.add(now, Time.Duration.of_ms(ms))}
5077
5078def phase.remaining(+until: Time.Duration, +now: Time.Duration) -> U32:
5079  Bool.pick(U32, Cmp.is_lt(Time.Duration.cmp(now, until)),
5080    U32.max(1, Int.I64.to_u32(Time.Duration.to_ms(Time.Duration.sub(until, now)))), 0)
5081
5082def bounded.sent(m: Socket & (U32 & Result<&1, &1, U32 & String, Unit>)) -> Socket & Result<&1, &1, U32 & String, Unit>:
5083  (s, (accepted, result)) = m
5084  (s, result)
5085
5086def bounded.send.ready(expired: Bool, s: Socket, b: Bytes.Bytes, ms: U32) -> IO(Socket & Result<&1, &1, U32 & String, Unit>):
5087  match expired:
5088    case True{}:
5089      IO.pure(Socket & Result<&1, &1, U32 & String, Unit>, (s, Fail{(60, "write deadline expired")}))
5090    case False{}:
5091      Bytes.Bytes{len, words} = b
5092      do IO<Socket & Result<&1, &1, U32 & String, Unit>>:
5093        sent : Socket & (U32 & Result<&1, &1, U32 & String, Unit>) <- Wire.send.words.deadline(s, len, words, ms)
5094        return bounded.sent(sent)
5095
5096def bounded.send(s: Socket, b: Bytes.Bytes, until: Time.Duration) -> IO(Socket & Result<&1, &1, U32 & String, Unit>):
5097  do IO<Socket & Result<&1, &1, U32 & String, Unit>>:
5098    now : Time.Duration <- Time.mono()
5099    +ms : U32 = phase.remaining(until, now)
5100    bounded.send.ready(U32.is_zero(ms), s, b, ms)
5101
5102def reply.bytes(res: Res, head: Bool, close: Bool) -> Bytes.Bytes:
5103  Res{+status, +headers, body} = res
5104  encode.on(Res{status, Bool.pick(Map<&2, List<&2, String>>, close, set(headers, "connection", "close"), headers), body}, head)
5105
5106def reply.fail.bytes(+status: U32) -> Res:
5107  Res{status, set(empty(), "connection", "close"), Bytes.from_string(reason(status))}
5108
5109def reply.drain.of(m: Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>) -> Socket & Bool:
5110  (s, r) = m
5111  match r:
5112    case Fail{e}:
5113      (s, False{})
5114    case Done{data}:
5115      (len, words) = data
5116      (s, Bool.not(U32.is_zero(len)))
5117
5118# ponytail: cap drain at 32 MiB and 2.55 s; use socket half-close if larger peers need guaranteed delivery.
5119def reply.drain(n: Nat, alive: Bool, +until: Time.Duration, st: Socket & Bool) -> IO(Unit):
5120  match n:
5121    case 0n:
5122      (s, more) = st
5123      Socket.close(s)
5124    case 1n+p:
5125      match alive:
5126        case False{}:
5127          (s, more) = st
5128          Socket.close(s)
5129        case True{}:
5130          (s, more) = st
5131          match more:
5132            case False{}:
5133              Socket.close(s)
5134            case True{}:
5135              do IO<Unit>:
5136                got : Socket & Result<&1, &1, U32 & String, U32 & Array<U32>> <- Wire.recv.words(s, 65536, 50)
5137                now : Time.Duration <- Time.mono()
5138                reply.drain(p, Cmp.is_lt(Time.Duration.cmp(now, until)), until, reply.drain.of(got))
5139
5140def reply.sent.close(m: Socket & Result<&1, &1, U32 & String, Unit>) -> IO(Unit):
5141  (s, r) = m
5142  match r:
5143    case Fail{e}:
5144      Socket.close(s)
5145    case Done{u}:
5146      do IO<Unit>:
5147        now : Time.Duration <- Time.mono()
5148        reply.drain(U32.to_nat(512), True{}, Time.Duration.add(now, Time.Duration.of_ms(2500)), (s, True{}))
5149
5150def reply.sent.observe(observer: Completion.Receipt, status: U32,
5151  sent: Socket & Result<&1, &1, U32 & String, Unit>) -> IO(Unit):
5152  (socket, result) = sent
5153  match result:
5154    case Fail{(code, message)}:
5155      do IO<Unit>:
5156        Socket.close(socket)
5157        Completion.report(observer, status, Completion.WriteFailed{code, message})
5158    case Done{unit}:
5159      do IO<Unit>:
5160        reply.sent.close((socket, Done{unit}))
5161        Completion.report(observer, status, Completion.HostAccepted{})
5162
5163
5164def reply_fail(observer: Completion.Receipt, s: Socket, +status: U32, ms: U32) -> IO(Unit):
5165  do IO<Unit>:
5166    now : Time.Duration <- Time.mono()
5167    sent : Socket & Result<&1, &1, U32 & String, Unit> <-
5168      bounded.send(s, encode(reply.fail.bytes(status)), Time.Duration.add(now, Time.Duration.of_ms(ms)))
5169    reply.sent.observe(observer, status, sent)
5170
5171
5172# The head is parsed once, when it is whole. Body pieces are kept as they come and joined once.
5173type Sv is Type:
5174  SvHead{buf: Bytes.Bytes}
5175  SvLen{req: Req, v11: Bool, left: U32, parts: List<&1, Bytes.Bytes>}
5176  SvChunk{req: Req, v11: Bool, n: U32, st: Dc, parts: List<&1, Bytes.Bytes>}
5177
5178type InputOperation is Data:
5179  ReadInput{}
5180  SendContinue{}
5181
5182# More: read on, first answering 100 Continue when cont is set.
5183type Turn is Type:
5184  TurnClose{}
5185  TurnInputFailed{operation: InputOperation, code: U32, message: String}
5186  TurnFail{status: U32}
5187  TurnReq{req: Req, rest: Bytes.Bytes, v11: Bool}
5188  TurnMore{sv: Sv, cont: Bool}
5189
5190def serve.max() -> Nat:
5191  fetch.max()
5192
5193def sv.none() -> Sv:
5194  SvHead{Bytes.new(0)}
5195
5196def sv.body(req: Req, +v11: Bool, parts: List<&1, Bytes.Bytes>, rest: Bytes.Bytes) -> Turn:
5197  Req{method, path, headers, body} = req
5198  TurnReq{Req{method, path, headers, rb.body(parts)}, rest, v11}
5199
5200def sv.len.cut(req: Req, +v11: Bool, parts: List<&1, Bytes.Bytes>, +len: U32, +left: U32, r: Bytes.Bytes & Bytes.Bytes) -> Turn:
5201  (piece, last) = r
5202  sv.body(req, v11, Con{last, parts}, bytes.snd(Bytes.slice(piece, left, (len - left : U32))))
5203
5204def sv.len.have(short: Bool, req: Req, +v11: Bool, +left: U32, parts: List<&1, Bytes.Bytes>, +len: U32, piece: Bytes.Bytes) -> Turn:
5205  match short:
5206    case True{}:
5207      TurnMore{SvLen{req, v11, (left - len : U32), Con{piece, parts}}, False{}}
5208    case False{}:
5209      sv.len.cut(req, v11, parts, len, left, Bytes.slice(piece, 0, left))
5210
5211def sv.len(req: Req, +v11: Bool, +left: U32, parts: List<&1, Bytes.Bytes>, piece: Bytes.Bytes) -> Turn:
5212  Bytes.Bytes{+len, buf} = piece
5213  sv.len.have(U32.is_lt(len, left), req, v11, left, parts, len, Bytes.Bytes{len, buf})
5214
5215def sv.chunk.of(req: Req, +v11: Bool, +n: U32, c: Ck) -> Turn:
5216  Ck{st, parts, rest} = c
5217  match st:
5218    case DcDone{}:
5219      sv.body(req, v11, parts, rest)
5220    case DcBad{}:
5221      TurnFail{400}
5222    case DcSize{a, b}:
5223      TurnMore{SvChunk{req, v11, n, DcSize{a, b}, parts}, False{}}
5224    case DcExt{x}:
5225      TurnMore{SvChunk{req, v11, n, DcExt{x}, parts}, False{}}
5226    case DcSizeLf{x}:
5227      TurnMore{SvChunk{req, v11, n, DcSizeLf{x}, parts}, False{}}
5228    case DcData{k}:
5229      TurnMore{SvChunk{req, v11, n, DcData{k}, parts}, False{}}
5230    case DcDataCr{}:
5231      TurnMore{SvChunk{req, v11, n, DcDataCr{}, parts}, False{}}
5232    case DcDataLf{}:
5233      TurnMore{SvChunk{req, v11, n, DcDataLf{}, parts}, False{}}
5234    case DcTr{j}:
5235      TurnMore{SvChunk{req, v11, n, DcTr{j}, parts}, False{}}
5236
5237def sv.chunk.parts.cons(+len: U32, buf: Array<U32>, counted: List<&1, Bytes.Bytes> & Nat) -> List<&1, Bytes.Bytes> & Nat:
5238  (rest, n) = counted
5239  (Con{Bytes.Bytes{len, buf}, rest}, Nat.add(U32.to_nat(len), n))
5240
5241def sv.chunk.parts(xs: List<&1, Bytes.Bytes>, old: List<&1, Bytes.Bytes>) -> List<&1, Bytes.Bytes> & Nat:
5242  match xs:
5243    case Nil{}:
5244      (old, 0n)
5245    case Con{b, tail}:
5246      Bytes.Bytes{+len, buf} = b
5247      sv.chunk.parts.cons(len, buf, sv.chunk.parts(tail, old))
5248
5249def sv.chunk.cap(big: Bool, req: Req, +v11: Bool, n: U32, st: Dc, parts: List<&1, Bytes.Bytes>, rest: Bytes.Bytes) -> Turn:
5250  match big:
5251    case True{}:
5252      TurnFail{413}
5253    case False{}:
5254      sv.chunk.of(req, v11, n, Ck{st, parts, rest})
5255
5256def sv.chunk.counted(+max: Nat, req: Req, v11: Bool, n: U32, st: Dc, rest: Bytes.Bytes, counted: List<&1, Bytes.Bytes> & Nat) -> Turn:
5257  (parts, size) = counted
5258  +total = Nat.add(U32.to_nat(n), size)
5259  sv.chunk.cap(Nat.is_lt(max, total) || Nat.is_lt(U32.to_nat(4294967295), total), req, v11,
5260    U32.from_nat(total), st, parts, rest)
5261
5262def sv.chunk.decoded(max: Nat, req: Req, v11: Bool, n: U32, old: List<&1, Bytes.Bytes>, c: Ck) -> Turn:
5263  Ck{st, parts, rest} = c
5264  sv.chunk.counted(max, req, v11, n, st, rest, sv.chunk.parts(parts, old))
5265
5266def sv.chunk(+max: Nat, req: Req, +v11: Bool, +n: U32, st: Dc, parts: List<&1, Bytes.Bytes>, piece: Bytes.Bytes) -> Turn:
5267  sv.chunk.decoded(max, req, v11, n, parts, ck(piece, st, Nil{}))
5268
5269# RFC 9110 §10.1.1: answer 100 Continue only when the body is still to come.
5270def sv.cont(want: Bool, t: Turn) -> Turn:
5271  match t:
5272    case TurnMore{sv, c}:
5273      TurnMore{sv, want}
5274    case TurnClose{}:
5275      TurnClose{}
5276    case TurnInputFailed{operation, code, message}:
5277      TurnInputFailed{operation, code, message}
5278    case TurnFail{s}:
5279      TurnFail{s}
5280    case TurnReq{req, rest, v11}:
5281      TurnReq{req, rest, v11}
5282
5283def sv.cl.k(big: Bool, req: Req, +v11: Bool, +k: U32, rest: Bytes.Bytes) -> Turn:
5284  match big:
5285    case True{}:
5286      TurnFail{413}
5287    case False{}:
5288      sv.len(req, v11, k, Nil{}, rest)
5289
5290def sv.cl(+max: Nat, req: Req, +v11: Bool, rest: Bytes.Bytes, n: Maybe<&2, U32>) -> Turn:
5291  match n:
5292    case None{}:
5293      TurnFail{400}
5294    case Some{+k}:
5295      sv.cl.k(Nat.is_lt(max, U32.to_nat(k)), req, v11, k, rest)
5296
5297def sv.frame(+max: Nat, req: Req, +v11: Bool, rest: Bytes.Bytes, te: Bool) -> Turn:
5298  Req{method, path, +headers, body} = req
5299  match te:
5300    case True{}:
5301      sv.chunk(max, Req{method, path, headers, body}, v11, 0, dc.start(), Nil{}, rest)
5302    case False{}:
5303      sv.cl(max, Req{method, path, headers, body}, v11, rest, parse_u32(header(headers, "content-length")))
5304
5305def sv.expects(+v11: Bool, +headers: Map<&2, List<&2, String>>) -> Bool:
5306  Bool.and(v11, String.eq(String.to_lower(header(headers, "expect")), "100-continue"))
5307
5308def sv.got.head(+max: Nat, +v11: Bool, rest: Bytes.Bytes, req: Req) -> Turn:
5309  Req{method, path, +headers, body} = req
5310  sv.cont(sv.expects(v11, headers), sv.frame(max, Req{method, path, headers, body}, v11, rest, has_header(headers, "transfer-encoding")))
5311
5312def sv.parsed(+max: Nat, +v11: Bool, rest: Bytes.Bytes, g: Got) -> Turn:
5313  match g:
5314    case GotBad{}:
5315      TurnFail{400}
5316    case GotMore{}:
5317      TurnFail{400}
5318    case GotReq{req}:
5319      TurnReq{req, rest, v11}
5320    case GotHead{req}:
5321      sv.got.head(max, v11, rest, req)
5322
5323def sv.split(+max: Nat, +hlen: U32, +len: U32, r: Bytes.Bytes & Bytes.Bytes) -> Turn:
5324  (buf, hb) = r
5325  +head = Bytes.to_string(hb)
5326  sv.parsed(max, req.v11(head), bytes.snd(Bytes.slice(buf, hlen, (len - hlen : U32))), parse.got(head))
5327
5328def sv.hit.none(big: Bool, buf: Bytes.Bytes) -> Turn:
5329  match big:
5330    case True{}:
5331      TurnFail{431}
5332    case False{}:
5333      TurnMore{SvHead{buf}, False{}}
5334
5335def sv.hit.some(big: Bool, +max: Nat, +hlen: U32, +len: U32, buf: Bytes.Bytes) -> Turn:
5336  match big:
5337    case True{}:
5338      TurnFail{431}
5339    case False{}:
5340      sv.split(max, hlen, len, Bytes.slice(buf, 0, hlen))
5341
5342# RFC 6585 §5: refuse a head over the configured byte limit.
5343def sv.hit(+max: Nat, +headers: U32, +len: U32, buf: Bytes.Bytes, at: Maybe<&2, U32>) -> Turn:
5344  match at:
5345    case None{}:
5346      sv.hit.none(U32.is_lt(headers, len), buf)
5347    case Some{+i}:
5348      +hlen = (i + 4 : U32)
5349      sv.hit.some(U32.is_lt(headers, hlen), max, hlen, len, buf)
5350
5351def sv.seek.of(+max: Nat, +headers: U32, +len: U32, +from: U32, buf: Bytes.Bytes, r: Bytes.Bytes & Maybe<&2, U32>) -> Turn:
5352  (tail, m) = r
5353  sv.hit(max, headers, len, buf, found.at(from, m))
5354
5355def sv.seek(+max: Nat, +headers: U32, +len: U32, +from: U32, r: Bytes.Bytes & Bytes.Bytes) -> Turn:
5356  (buf, tail) = r
5357  sv.seek.of(max, headers, len, from, buf, Bytes.find(tail, "\r\n\r\n"))
5358
5359# Only the new bytes, and the 3 before them, can finish the blank line.
5360def sv.head.at(+max: Nat, +headers: U32, +from: U32, buf: Bytes.Bytes) -> Turn:
5361  Bytes.Bytes{+len, b} = buf
5362  sv.seek(max, headers, len, from, Bytes.slice(Bytes.Bytes{len, b}, from, (len - from : U32)))
5363
5364def sv.head(+max: Nat, +headers: U32, buf: Bytes.Bytes, piece: Bytes.Bytes) -> Turn:
5365  Bytes.Bytes{+ol, ob} = buf
5366  sv.head.at(max, headers, Bool.pick(U32, U32.is_lt(ol, 3), 0, (ol - 3 : U32)), Bytes.append(Bytes.Bytes{ol, ob}, piece))
5367
5368def sv.closed.pick(empty: Bool) -> Turn:
5369  match empty:
5370    case True{}:
5371      TurnClose{}
5372    case False{}:
5373      TurnFail{400}
5374
5375def sv.closed.head(buf: Bytes.Bytes) -> Turn:
5376  Bytes.Bytes{+len, b} = buf
5377  sv.closed.pick(U32.is_eq(len, 0))
5378
5379# A close mid-request is a request cut short (RFC 9112 §8).
5380def sv.step(closed: Bool, +max: Nat, +headers: U32, sv: Sv, piece: Bytes.Bytes) -> Turn:
5381  match closed:
5382    case True{}:
5383      match sv:
5384        case SvHead{buf}:
5385          sv.closed.head(buf)
5386        case SvLen{req, v11, left, parts}:
5387          TurnFail{400}
5388        case SvChunk{req, v11, n, st, parts}:
5389          TurnFail{400}
5390    case False{}:
5391      match sv:
5392        case SvHead{buf}:
5393          sv.head(max, headers, buf, piece)
5394        case SvLen{req, +v11, +left, parts}:
5395          sv.len(req, v11, left, parts, piece)
5396        case SvChunk{req, +v11, +n, st, parts}:
5397          sv.chunk(max, req, v11, n, st, parts, piece)
5398
5399def sv.frame.req(t: Turn) -> Maybe<&1, String & String>:
5400  match t:
5401    case TurnReq{req, rest, v11}:
5402      Req{method, path, headers, body} = req
5403      Some{(Bytes.to_string(body), Bytes.to_string(rest))}
5404    case TurnMore{sv, c}:
5405      None{}
5406    case TurnFail{s}:
5407      None{}
5408    case TurnClose{}:
5409      None{}
5410    case TurnInputFailed{operation, code, message}:
5411      None{}
5412
5413def sv.frame.go(xs: List<&2, String>, t: Turn) -> Maybe<&1, String & String>:
5414  match xs:
5415    case Nil{}:
5416      sv.frame.req(t)
5417    case Con{+x, rest}:
5418      match t:
5419        case TurnMore{sv, c}:
5420          sv.frame.go(rest, sv.step(False{}, serve.max(), 65536, sv, Bytes.from_string(x)))
5421        case TurnReq{req, r, v11}:
5422          sv.frame.req(TurnReq{req, r, v11})
5423        case TurnFail{s}:
5424          None{}
5425        case TurnClose{}:
5426          None{}
5427        case TurnInputFailed{operation, code, message}:
5428          None{}
5429
5430# The body and the bytes after it, once the pieces make a whole request; None otherwise.
5431def serve.frame(xs: List<&2, String>) -> Maybe<&1, String & String>:
5432  sv.frame.go(xs, TurnMore{sv.none(), False{}})
5433
5434def talk.piece(settings: Limits, sv: Sv, p: U32 & Array<U32>) -> Turn:
5435  Limits{max, headers, hm, bm, im, wm} = settings
5436  (+len, buf) = p
5437  sv.step(U32.is_eq(len, 0), max, headers, sv, Bytes.Bytes{len, buf})
5438
5439def talk.next(settings: Limits, sv: Sv, m: Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>) -> Socket & Turn:
5440  (s, r) = m
5441  match r:
5442    case Fail{(+code, message)}:
5443      (s, Bool.pick(Turn, err.late(code), TurnFail{408}, TurnInputFailed{ReadInput{}, code, message}))
5444    case Done{p}:
5445      (s, talk.piece(settings, sv, p))
5446
5447def talk.after.pick(empty: Bool, settings: Limits, rest: Bytes.Bytes) -> Turn:
5448  match empty:
5449    case True{}:
5450      TurnMore{sv.none(), False{}}
5451    case False{}:
5452      Limits{max, headers, hm, bm, im, wm} = settings
5453      sv.step(False{}, max, headers, sv.none(), rest)
5454
5455def talk.after.rest(settings: Limits, rest: Bytes.Bytes, s: Socket) -> Socket & Turn:
5456  Bytes.Bytes{+len, buf} = rest
5457  (s, talk.after.pick(U32.is_eq(len, 0), settings, Bytes.Bytes{len, buf}))
5458
5459def talk.after.keep(keep: Bool, settings: Limits, rest: Bytes.Bytes, s: Socket) -> Socket & Turn:
5460  match keep:
5461    case False{}:
5462      (s, TurnClose{})
5463    case True{}:
5464      talk.after.rest(settings, rest, s)
5465
5466def talk.after(settings: Limits, keep: Bool, rest: Bytes.Bytes, m: Socket & Result<&1, &1, U32 & String, Unit>) -> (Socket & Turn) & Completion.Outcome:
5467  (s, r) = m
5468  match r:
5469    case Fail{(code, message)}:
5470      ((s, TurnClose{}), Completion.WriteFailed{code, message})
5471    case Done{u}:
5472      (talk.after.keep(keep, settings, rest, s), Completion.HostAccepted{})
5473
5474def talk.send(+settings: Limits, s: Socket, rest: Bytes.Bytes, +headers: Map<&2, List<&2, String>>, v11: Bool, +head: Bool, res: Res) -> IO((Socket & Turn) & Completion.Outcome):
5475  Limits{max, cap, hm, bm, im, wm} = settings
5476  Res{+status, +rh, body} = res
5477  +keep = serve.keep(headers, v11, status, rh)
5478  do IO<(Socket & Turn) & Completion.Outcome>:
5479    now : Time.Duration <- Time.mono()
5480    sent : Socket & Result<&1, &1, U32 & String, Unit> <-
5481      bounded.send(s, reply.bytes(Res{status, rh, body}, head, Bool.not(keep)), Time.Duration.add(now, Time.Duration.of_ms(wm)))
5482    return talk.after(settings, keep, rest, sent)
5483
5484def talk.completed.connection(outcome: Completion.Outcome, next: Socket & Turn) -> IO(Maybe<&1, Socket & Turn>):
5485  match outcome:
5486    case Completion.HostAccepted{}:
5487      (socket, turn) = next
5488      IO.pure(Maybe<&1, Socket & Turn>, Some{(socket, turn)})
5489    case Completion.WriteFailed{code, message}:
5490      (socket, turn) = next
5491      do IO<Maybe<&1, Socket & Turn>>:
5492        Socket.close(socket)
5493        return None{}
5494    case Completion.IncompleteResponse{}:
5495      (socket, turn) = next
5496      do IO<Maybe<&1, Socket & Turn>>:
5497        Socket.close(socket)
5498        return None{}
5499
5500def talk.completed(observer: Completion.Receipt, receipt: Completion.Receipt, +status: U32,
5501  sent: (Socket & Turn) & Completion.Outcome) -> IO(Maybe<&1, Socket & Turn>):
5502  (next, outcome) = sent
5503  +observed = {outcome : Completion.Outcome}
5504  do IO<Maybe<&1, Socket & Turn>>:
5505    remaining : Maybe<&1, Socket & Turn> <- talk.completed.connection(observed, next)
5506    Completion.report(observer, status, observed)
5507    Completion.report(receipt, status, observed)
5508    return remaining
5509
5510def talk.respond(observer: Completion.Receipt, +settings: Limits, s: Socket, rest: Bytes.Bytes,
5511  headers: Map<&2, List<&2, String>>, v11: Bool, head: Bool, reply: Reply) -> IO(Maybe<&1, Socket & Turn>):
5512  Reply{Res{+status, rh, body}, receipt} = reply
5513  do IO<Maybe<&1, Socket & Turn>>:
5514    sent : (Socket & Turn) & Completion.Outcome <- talk.send(settings, s, rest, headers, v11, head, Res{status, rh, body})
5515    talk.completed(observer, receipt, status, sent)
5516
5517def talk.cont(cont: Bool, s: Socket, ms: U32) -> IO(Socket & Result<&1, &1, U32 & String, Unit>):
5518  match cont:
5519    case False{}:
5520      IO.pure(Socket & Result<&1, &1, U32 & String, Unit>, (s, Done{Unit{}}))
5521    case True{}:
5522      do IO<Socket & Result<&1, &1, U32 & String, Unit>>:
5523        now : Time.Duration <- Time.mono()
5524        bounded.send(s, Bytes.from_string("HTTP/1.1 100 Continue\r\n\r\n"), Time.Duration.add(now, Time.Duration.of_ms(ms)))
5525
5526def phase.head(empty: Bool, settings: Limits, now: Time.Duration) -> Phase:
5527  match empty:
5528    case True{}:
5529      Limits{max, cap, hm, bm, im, wm} = settings
5530      phase.new(0, im, now)
5531    case False{}:
5532      Limits{max, cap, hm, bm, im, wm} = settings
5533      phase.new(1, hm, now)
5534
5535def phase.start(settings: Limits, sv: Sv, now: Time.Duration) -> Phase & Sv:
5536  Limits{max, cap, hm, bm, im, wm} = settings
5537  match sv:
5538    case SvHead{buf}:
5539      Bytes.Bytes{+len, words} = buf
5540      (phase.head(U32.is_zero(len), Limits{max, cap, hm, bm, im, wm}, now), SvHead{Bytes.Bytes{len, words}})
5541    case SvLen{req, v11, left, parts}:
5542      (phase.new(2, bm, now), SvLen{req, v11, left, parts})
5543    case SvChunk{req, v11, n, st, parts}:
5544      (phase.new(2, bm, now), SvChunk{req, v11, n, st, parts})
5545
5546def phase.select(settings: Limits, sv: Sv, now: Time.Duration, previous: Maybe<&2, Phase>) -> Phase & Sv:
5547  match previous:
5548    case None{}:
5549      phase.start(settings, sv, now)
5550    case Some{phase}:
5551      (phase, sv)
5552
5553# Buffered pipelined headers have already ended before upload callbacks run.
5554def phase.body(previous: Maybe<&2, Phase>, settings: Limits, now: Time.Duration) -> Phase:
5555  match previous:
5556    case Some{phase}:
5557      phase
5558    case None{}:
5559      Limits{max, cap, hm, bm, im, wm} = settings
5560      phase.new(2, bm, now)
5561
5562def phase.after(+settings: Limits, +now: Time.Duration, +phase: Phase, t: Turn) -> Turn & Phase:
5563  Limits{max, cap, hm, bm, im, wm} = settings
5564  Phase{+kind, until} = phase
5565  match t:
5566    case TurnMore{sv, cont}:
5567      match sv:
5568        case SvHead{buf}:
5569          (TurnMore{SvHead{buf}, cont}, Bool.pick(Phase, U32.is_zero(kind), phase.new(1, hm, now), phase))
5570        case SvLen{req, v11, left, parts}:
5571          (TurnMore{SvLen{req, v11, left, parts}, cont}, Bool.pick(Phase, U32.is_eq(kind, 2), phase, phase.new(2, bm, now)))
5572        case SvChunk{req, v11, n, st, parts}:
5573          (TurnMore{SvChunk{req, v11, n, st, parts}, cont}, Bool.pick(Phase, U32.is_eq(kind, 2), phase, phase.new(2, bm, now)))
5574    case TurnReq{req, rest, v11}:
5575      (TurnReq{req, rest, v11}, phase)
5576    case TurnFail{+status}:
5577      (Bool.pick(Turn, U32.is_zero(kind) && U32.is_eq(status, 408), TurnClose{}, TurnFail{status}), phase)
5578    case TurnClose{}:
5579      (TurnClose{}, phase)
5580    case TurnInputFailed{operation, code, message}:
5581      (TurnInputFailed{operation, code, message}, phase)
5582
5583def phase.expired(phase: Phase) -> Turn:
5584  Phase{kind, until} = phase
5585  Bool.pick(Turn, U32.is_zero(kind), TurnClose{}, TurnFail{408})
5586
5587def talk.received.state(s: Socket, next: Turn & Phase) -> (Socket & Turn) & Phase:
5588  (t, p) = next
5589  ((s, t), p)
5590
5591def talk.received.phase(settings: Limits, phase: Phase, now: Time.Duration, next: Socket & Turn) -> (Socket & Turn) & Phase:
5592  (s, t) = next
5593  talk.received.state(s, phase.after(settings, now, phase, t))
5594
5595def talk.received.late(expired: Bool, +settings: Limits, +phase: Phase, now: Time.Duration, sv: Sv, m: Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>) -> (Socket & Turn) & Phase:
5596  match expired:
5597    case True{}:
5598      (s, r) = m
5599      ((s, phase.expired(phase)), phase)
5600    case False{}:
5601      talk.received.phase(settings, phase, now, talk.next(settings, sv, m))
5602
5603# A real host read slice returns its socket; no raced operation is abandoned.
5604# The original absolute phase survives slice timeouts and stop observations.
5605# Admitted streamed uploads retain their state and finish; unadmitted input closes.
5606def talk.read.running(held: Bool, inbox: Chan(Admission.Command)) -> IO(Bool):
5607  match held:
5608    case True{}: IO.pure(Bool, True{})
5609    case False{}: Admission.running(inbox)
5610
5611type ReadStep is Type:
5612  ReadChecking{socket: Socket, state: Sv, phase: Phase}
5613  ReadAllowed{running: Bool, socket: Socket, state: Sv, phase: Phase}
5614  ReadBudget{ms: U32, socket: Socket, state: Sv, phase: Phase}
5615  ReadReceived{state: Sv, phase: Phase, now: Time.Duration,
5616    result: Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>}
5617  ReadFailed{retry: Bool, socket: Socket, state: Sv, phase: Phase,
5618    now: Time.Duration, error: U32 & String}
5619
5620# One state machine owns the socket through each actual host return.
5621@unsafe
5622def talk.read.loop(+inbox: Chan(Admission.Command), +held: Bool, +settings: Limits,
5623  step: ReadStep) -> IO((Socket & Turn) & Phase):
5624  match step:
5625    case ReadChecking{s, sv, phase}:
5626      do IO<(Socket & Turn) & Phase>:
5627        running : Bool <- talk.read.running(held, inbox)
5628        talk.read.loop(inbox, held, settings, ReadAllowed{running, s, sv, phase})
5629    case ReadAllowed{running, s, sv, +phase}:
5630      match running:
5631        case False{}:
5632          IO.pure((Socket & Turn) & Phase, ((s, TurnClose{}), phase))
5633        case True{}:
5634          Phase{kind, until} = phase
5635          do IO<(Socket & Turn) & Phase>:
5636            now : Time.Duration <- Time.mono()
5637            +ms : U32 = phase.remaining(until, now)
5638            talk.read.loop(inbox, held, settings,
5639              ReadBudget{Bool.pick(U32, held, ms, U32.min(ms, 50)), s, sv, phase})
5640    case ReadBudget{ms, s, sv, +phase}:
5641      match ms:
5642        case 0:
5643          IO.pure((Socket & Turn) & Phase, ((s, phase.expired(phase)), phase))
5644        case _:
5645          do IO<(Socket & Turn) & Phase>:
5646            got : Socket & Result<&1, &1, U32 & String, U32 & Array<U32>> <- Wire.recv.words(s, 65536, ms)
5647            now : Time.Duration <- Time.mono()
5648            talk.read.loop(inbox, held, settings, ReadReceived{sv, phase, now, got})
5649    case ReadReceived{sv, +phase, +now, got}:
5650      Phase{kind, until} = phase
5651      (s, result) = got
5652      match result:
5653        case Fail{(+code, message)}:
5654          talk.read.loop(inbox, held, settings,
5655            ReadFailed{err.late(code) && Cmp.is_lt(Time.Duration.cmp(now, until)), s, sv, phase, now, (code, message)})
5656        case Done{packed}:
5657          IO.pure((Socket & Turn) & Phase,
5658            talk.received.late(Bool.not(Cmp.is_lt(Time.Duration.cmp(now, until))), settings, phase, now, sv, (s, Done{packed})))
5659    case ReadFailed{retry, s, sv, +phase, +now, error}:
5660      match retry:
5661        case True{}:
5662          talk.read.loop(inbox, held, settings, ReadChecking{s, sv, phase})
5663        case False{}:
5664          Phase{kind, until} = phase
5665          IO.pure((Socket & Turn) & Phase,
5666            talk.received.late(Bool.not(Cmp.is_lt(Time.Duration.cmp(now, until))), settings, phase, now, sv, (s, Fail{error})))
5667
5668def talk.read(+inbox: Chan(Admission.Command), held: Bool, +settings: Limits, sv: Sv, phase: Phase, m: Socket & Result<&1, &1, U32 & String, Unit>) -> IO((Socket & Turn) & Phase):
5669  (s, r) = m
5670  match r:
5671    case Fail{(code, message)}:
5672      IO.pure((Socket & Turn) & Phase, ((s, TurnInputFailed{SendContinue{}, code, message}), phase))
5673    case Done{u}:
5674      talk.read.loop(inbox, held, settings, ReadChecking{s, sv, phase})
5675
5676def talk.recv.selected(+inbox: Chan(Admission.Command), held: Bool, +settings: Limits, s: Socket, cont: Bool, selected: Phase & Sv) -> IO((Socket & Turn) & Phase):
5677  Limits{max, cap, hm, bm, im, wm} = settings
5678  (phase, state) = selected
5679  do IO<(Socket & Turn) & Phase>:
5680    sent : Socket & Result<&1, &1, U32 & String, Unit> <- talk.cont(cont, s, wm)
5681    talk.read(inbox, held, settings, state, phase, sent)
5682
5683def talk.recv(+inbox: Chan(Admission.Command), held: Bool, +settings: Limits, s: Socket, sv: Sv, cont: Bool, previous: Maybe<&2, Phase>) -> IO((Socket & Turn) & Phase):
5684  do IO<(Socket & Turn) & Phase>:
5685    now : Time.Duration <- Time.mono()
5686    talk.recv.selected(inbox, held, settings, s, cont, phase.select(settings, sv, now, previous))
5687
5688type Serving is Type:
5689  Serving{connection: Socket & Turn, phase: Maybe<&2, Phase>}
5690
5691def talk.state(received: (Socket & Turn) & Phase) -> Serving:
5692  (connection, phase) = received
5693  Serving{connection, Some{phase}}
5694
5695def serve.write.state(after: Maybe<&1, Socket & Turn>) -> Maybe<&1, Serving>:
5696  match after:
5697    case None{}:
5698      None{}
5699    case Some{connection}:
5700      Some{Serving{connection, None{}}}
5701
5702# A buffered-work unit owns one connection's incomplete request, decoded body,
5703# and pipelined remainder from before its first recv until the task really returns.
5704# ponytail: idle sockets also reserve buffer units; split idle/read leases if idle utilization matters.
5705def admission.done(+inbox: Chan(Admission.Command), operation: IO(Unit)) -> IO(Unit):
5706  do IO<Unit>:
5707    operation
5708    Admission.give(inbox, 0)
5709
5710def admission.head(req: Req) -> Bool:
5711  Req{method, path, headers, body} = req
5712  String.eq(method, "HEAD")
5713
5714def admission.turn.head(turn: Turn) -> Bool:
5715  match turn:
5716    case TurnReq{req, rest, v11}:
5717      admission.head(req)
5718    case TurnMore{sv, cont}:
5719      match sv:
5720        case SvHead{buf}:
5721          False{}
5722        case SvLen{req, v11, left, parts}:
5723          admission.head(req)
5724        case SvChunk{req, v11, n, state, parts}:
5725          admission.head(req)
5726    case TurnFail{status}:
5727      False{}
5728    case TurnClose{}:
5729      False{}
5730    case TurnInputFailed{operation, code, message}:
5731      False{}
5732
5733# This rejection has parsed metadata, so normal HEAD body suppression still applies.
5734def admission.reject(observer: Completion.Receipt, s: Socket, head: Bool, ms: U32) -> IO(Unit):
5735  do IO<Unit>:
5736    now : Time.Duration <- Time.mono()
5737    sent : Socket & Result<&1, &1, U32 & String, Unit> <-
5738      bounded.send(s, reply.bytes(reply.fail.bytes(503), head, True{}), Time.Duration.add(now, Time.Duration.of_ms(ms)))
5739    reply.sent.observe(observer, 503, sent)
5740
5741def admission.request(
5742  ~C: Data, ~h: C -> Req -> IO(Reply), ~observe: C -> U32 -> Completion.Outcome -> IO(Unit),
5743  admitted: Bool, +inbox: Chan(Admission.Command), +context: C, +settings: Limits, s: Socket, req: Req, rest: Bytes.Bytes, v11: Bool
5744) -> IO(Maybe<&1, Socket & Turn>):
5745  match admitted:
5746    case False{}:
5747      Limits{max, cap, hm, bm, im, wm} = settings
5748      do IO<Maybe<&1, Socket & Turn>>:
5749        admission.reject(Completion.Observed{status => outcome => observe(context, status, outcome)}, s, admission.head(req), wm)
5750        return None{}
5751    case True{}:
5752      Req{+method, path, +headers, body} = req
5753      do IO<Maybe<&1, Socket & Turn>>:
5754        res : Reply <- h(context, Req{method, path, headers, body})
5755        next : Maybe<&1, Socket & Turn> <- talk.respond(Completion.Observed{status => outcome => observe(context, status, outcome)}, settings, s, rest, headers, v11, String.eq(method, "HEAD"), res)
5756        Admission.give(inbox, 1)
5757        return next
5758
5759
5760@unsafe
5761def talk(~C: Data, ~h: C -> Req -> IO(Reply), ~observe: C -> U32 -> Completion.Outcome -> IO(Unit), +context: C, +settings: Limits, +inbox: Chan(Admission.Command), st: Maybe<&1, Serving>) -> IO(Unit):
5762  Limits{max, cap, hm, bm, im, wm} = settings
5763  match st:
5764    case None{}:
5765      IO.pure(Unit, Unit{})
5766    case Some{Serving{(s, t), phase}}:
5767      match t:
5768        case TurnMore{sv, cont}:
5769          do IO<Unit>:
5770            received : (Socket & Turn) & Phase <- talk.recv(inbox, False{}, settings, s, sv, cont, phase)
5771            talk(~C, ~h, ~observe, context, settings, inbox, Some{talk.state(received)})
5772        case TurnReq{req, rest, v11}:
5773          do IO<Unit>:
5774            admitted : Bool <- Admission.take(inbox, 1)
5775            next : Maybe<&1, Socket & Turn> <- admission.request(~C, ~h, ~observe, admitted, inbox, context, settings, s, req, rest, v11)
5776            talk(~C, ~h, ~observe, context, settings, inbox, serve.write.state(next))
5777        case TurnFail{status}:
5778          reply_fail(Completion.Observed{status => outcome => observe(context, status, outcome)}, s, status, wm)
5779        case TurnClose{}:
5780          Socket.close(s)
5781        case TurnInputFailed{operation, code, message}:
5782          Socket.close(s)
5783
5784def conn.admitted(~h: Req -> IO(Reply), ~observe: U32 -> Completion.Outcome -> IO(Unit), admitted: Bool, +settings: Limits, +inbox: Chan(Admission.Command), l: Listener, s: Socket) -> IO(Listener):
5785  match admitted:
5786    case False{}:
5787      do IO<Listener>:
5788        Socket.close(s)
5789        return l
5790    case True{}:
5791      do IO<Listener>:
5792        IO.spawn(Unit, admission.done(inbox, talk(~Unit, ~(context => req => h(req)), ~(context => status => outcome => observe(status, outcome)), Unit{}, settings, inbox,
5793          Some{Serving{(s, TurnMore{sv.none(), False{}}), None{}}})))
5794        return l
5795
5796def conn(~h: Req -> IO(Reply), ~observe: U32 -> Completion.Outcome -> IO(Unit), +settings: Limits, +inbox: Chan(Admission.Command), m: Listener & Result<&1, &1, U32 & String, Socket>) -> IO(Listener):
5797  (l, r) = m
5798  do IO<Listener>:
5799    s : Socket <- IO.pass(Socket, r)
5800    admitted : Bool <- Admission.take(inbox, 0)
5801    conn.admitted(~h, ~observe, admitted, settings, inbox, l, s)
5802
5803# Finite positive settings, not zero/unlimited sentinels.
5804type StartupError is Data:
5805  InvalidConfig{}
5806  BindError{code: U32, message: String}
5807
5808# Application-owned affine dependencies never enter this transport owner.
5809type Server<-C: Data> is Type:
5810  Server{listener: Listener, context: C, config: ServerConfig, admission: Chan(Admission.Command), drained: Chan(Admission.Counts)}
5811
5812def server.config(host: String, port: U32) -> ServerConfig:
5813  ServerConfig{host, port, 16777216, 65536, 128, 128, 128, 5000, 30000, 30000, 30000}
5814
5815def server.config.with(host: String, port: U32, max: Nat) -> ServerConfig:
5816  ServerConfig{host, port, U32.from_nat(max), 65536, 128, 128, 128, 5000, 30000, 30000, 30000}
5817
5818# Host deadline effects use signed 32-bit milliseconds.
5819def server.deadline.valid(+ms: U32) -> Bool:
5820  U32.is_gt(ms, 0) && U32.is_le(ms, 2147483647)
5821
5822def server.config.valid(config: ServerConfig) -> Bool:
5823  ServerConfig{host, port, +body, +headers, connections, requests, buffered, header_ms, body_ms, idle_ms, write_ms} = config
5824  U32.is_le(port, 65535) && U32.is_gt(body, 0) && U32.is_le(body, limits.representable()) &&
5825    U32.is_gt(headers, 0) && U32.is_le(headers, limits.representable()) &&
5826    U32.is_gt(connections, 0) && U32.is_gt(requests, 0) && U32.is_gt(buffered, 0) &&
5827    server.deadline.valid(header_ms) && server.deadline.valid(body_ms) &&
5828    server.deadline.valid(idle_ms) && server.deadline.valid(write_ms)
5829
5830def server.opened(~C: Data, ~O: Type, owner: O, listener: Listener, context: C,
5831  config: ServerConfig, opened: Chan(Admission.Command) & Chan(Admission.Counts)) -> IO(O & Result<&2, &1, StartupError, Server<C>>):
5832  (inbox, drained) = opened
5833  IO.pure(O & Result<&2, &1, StartupError, Server<C>>, (owner, Done{Server{listener, context, config, inbox, drained}}))
5834
5835def server.started(~C: Data, ~O: Type, context: C, owner: O, +config: ServerConfig, result: Result<&1, &1, U32 & String, Listener>) -> IO(O & Result<&2, &1, StartupError, Server<C>>):
5836  ServerConfig{host, port, body, headers, connections, requests, buffered, hm, bm, im, wm} = config
5837  match result:
5838    case Fail{error}:
5839      (code, message) = error
5840      IO.pure(O & Result<&2, &1, StartupError, Server<C>>, (owner, Fail{BindError{code, message}}))
5841    case Done{listener}:
5842      do IO<O & Result<&2, &1, StartupError, Server<C>>>:
5843        opened : Chan(Admission.Command) & Chan(Admission.Counts) <- Admission.open.owner(Admission.Caps{connections, requests, buffered})
5844        server.opened(~C, ~O, owner, listener, context, config, opened)
5845
5846def server.start.valid(~C: Data, ~O: Type, valid: Bool, context: C, owner: O, +config: ServerConfig) -> IO(O & Result<&2, &1, StartupError, Server<C>>):
5847  match valid:
5848    case False{}:
5849      IO.pure(O & Result<&2, &1, StartupError, Server<C>>, (owner, Fail{InvalidConfig{}}))
5850    case True{}:
5851      ServerConfig{host, port, body, headers, connections, requests, buffered, header_ms, body_ms, idle_ms, write_ms} = config
5852      do IO<O & Result<&2, &1, StartupError, Server<C>>>:
5853        result : Result<&1, &1, U32 & String, Listener> <- TCP.listen(host, port)
5854        server.started(~C, ~O, context, owner, config, result)
5855
5856# Done is the readiness signal: TCP.listen has installed an accepting socket.
5857# Both branches return the preopened application owner unchanged.
5858def server.start(~C: Data, ~O: Type, context: C, owner: O, +config: ServerConfig) -> IO(O & Result<&2, &1, StartupError, Server<C>>):
5859  server.start.valid(~C, ~O, server.config.valid(config), context, owner, config)
5860
5861
5862# Copyable read-only observations remain usable while server.run owns the listener.
5863type ServerStats is Data:
5864  ServerStats{inbox: Chan(Admission.Command)}
5865
5866type ServerCounts is Data:
5867  ServerCounts{connections: U32, active: U32, buffered: U32,
5868    connection_high: U32, active_high: U32, buffered_high: U32,
5869    connection_rejected: Nat, active_rejected: Nat, buffered_rejected: Nat}
5870
5871def server.observer(~C: Data, server: Server<C>) -> Server<C> & ServerStats:
5872  Server{listener, context, config, +inbox, drained} = server
5873  (Server{listener, context, config, inbox, drained}, ServerStats{inbox})
5874
5875def server.counts(counts: Maybe<&2, Admission.Counts>) -> Maybe<&2, ServerCounts>:
5876  match counts:
5877    case None{}:
5878      None{}
5879    case Some{Admission.Counts{c, a, b, ch, ah, bh, cr, ar, br}}:
5880      Some{ServerCounts{c, a, b, ch, ah, bh, cr, ar, br}}
5881
5882# None means accounting has closed after the listener and its retained operations.
5883# This is not a drain result or a per-response write outcome.
5884def server.stats(observer: ServerStats) -> IO(Maybe<&2, ServerCounts>):
5885  ServerStats{inbox} = observer
5886  do IO<Maybe<&2, ServerCounts>>:
5887    counts : Maybe<&2, Admission.Counts> <- Admission.snapshot(inbox)
5888    return server.counts(counts)
5889
5890type ServerControl is Data:
5891  ServerControl{inbox: Chan(Admission.Command)}
5892
5893# Stop linearizes in Admission. It requests quiescence, never attests drain.
5894def server.control(~C: Data, server: Server<C>) -> Server<C> & ServerControl:
5895  Server{listener, context, config, +inbox, drained} = server
5896  (Server{listener, context, config, inbox, drained}, ServerControl{inbox})
5897
5898def server.stop(control: ServerControl) -> IO(Bool):
5899  ServerControl{inbox} = control
5900  Admission.quiesce(inbox)
5901
5902def server.final.counts(counts: Admission.Counts) -> ServerCounts:
5903  Admission.Counts{c, a, b, ch, ah, bh, cr, ar, br} = counts
5904  ServerCounts{c, a, b, ch, ah, bh, cr, ar, br}
5905
5906# Only the listener owner closes it, after the current accept really returns.
5907# Joining the controller waits for every real operation, including callbacks.
5908def server.close(~C: Data, server: Server<C>) -> IO(ServerCounts):
5909  Server{listener, context, config, +inbox, drained} = server
5910  do IO<ServerCounts>:
5911    requested : Bool <- Admission.quiesce(inbox)
5912    Listener.close(listener)
5913    Admission.close(inbox)
5914    counts : Admission.Counts <- IO.join(Admission.Counts, drained)
5915    return server.final.counts(counts)
5916
5917type ServerExit is Data:
5918  ServerStopped{counts: ServerCounts}
5919  ServerAcceptFailed{code: U32, message: String, counts: ServerCounts}
5920
5921def server.finished(stopped: Bool, error: U32 & String, counts: ServerCounts) -> ServerExit:
5922  match stopped:
5923    case True{}:
5924      ServerStopped{counts}
5925    case False{}:
5926      (code, message) = error
5927      ServerAcceptFailed{code, message, counts}
5928
5929def server.finish(~C: Data, stopped: Bool, error: U32 & String, server: Server<C>) -> IO(ServerExit):
5930  do IO<ServerExit>:
5931    counts : ServerCounts <- server.close(~C, server)
5932    return server.finished(stopped, error, counts)
5933
5934def server.admitted(~C: Data, ~operation: C -> Limits -> Chan(Admission.Command) -> Socket -> IO(Unit), admitted: Bool, +context: C, +config: ServerConfig, +inbox: Chan(Admission.Command), drained: Chan(Admission.Counts), listener: Listener, socket: Socket) -> IO(Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>):
5935  match admitted:
5936    case False{}:
5937      do IO<Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>>:
5938        Socket.close(socket)
5939        return (Server{listener, context, config, inbox, drained}, Fail{(11, "transport capacity exhausted")})
5940    case True{}:
5941      do IO<Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>>:
5942        finished : Chan(Unit) <- IO.fork(Unit, admission.done(inbox, operation(context, limits.config(config), inbox, socket)))
5943        return (Server{listener, context, config, inbox, drained}, Done{finished})
5944
5945def server.accepted(~C: Data, ~operation: C -> Limits -> Chan(Admission.Command) -> Socket -> IO(Unit), +context: C, +config: ServerConfig, +inbox: Chan(Admission.Command), drained: Chan(Admission.Counts), result: Listener & Result<&1, &1, U32 & String, Socket>) -> IO(Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>):
5946  (listener, got) = result
5947  match got:
5948    case Fail{error}:
5949      IO.pure(Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>, (Server{listener, context, config, inbox, drained}, Fail{error}))
5950    case Done{socket}:
5951      do IO<Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>>:
5952        admitted : Bool <- Admission.take(inbox, 0)
5953        server.admitted(~C, ~operation, admitted, context, config, inbox, drained, listener, socket)
5954
5955# One accepting step, so the caller retains explicit listener ownership.
5956type AcceptStep<-C: Data> is Type:
5957  AcceptChecking{server: Server<C>}
5958  AcceptAllowed{running: Bool, server: Server<C>}
5959  AcceptReceived{result: Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>}
5960  AcceptFailed{retry: Bool, server: Server<C>, error: U32 & String}
5961
5962@unsafe
5963def server.accept.loop(~C: Data, ~operation: C -> Limits -> Chan(Admission.Command) -> Socket -> IO(Unit),
5964  step: AcceptStep<C>) -> IO(Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>):
5965  match step:
5966    case AcceptChecking{server}:
5967      Server{listener, context, config, +inbox, drained} = server
5968      do IO<Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>>:
5969        running : Bool <- Admission.running(inbox)
5970        server.accept.loop(~C, ~operation, AcceptAllowed{running, Server{listener, context, config, inbox, drained}})
5971    case AcceptAllowed{running, server}:
5972      match running:
5973        case False{}:
5974          IO.pure(Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>, (server, Fail{(0, "server stopped")}))
5975        case True{}:
5976          Server{listener, context, config, inbox, drained} = server
5977          do IO<Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>>:
5978            result : Listener & Result<&1, &1, U32 & String, Socket> <- Wire.accept.deadline(listener, 50)
5979            accepted : Server<C> & Result<&1, &1, U32 & String, Chan(Unit)> <-
5980              server.accepted(~C, ~operation, context, config, inbox, drained, result)
5981            server.accept.loop(~C, ~operation, AcceptReceived{accepted})
5982    case AcceptReceived{accepted}:
5983      (server, result) = accepted
5984      match result:
5985        case Fail{(+code, message)}:
5986          server.accept.loop(~C, ~operation, AcceptFailed{err.late(code), server, (code, message)})
5987        case Done{finished}:
5988          IO.pure(Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>, (server, Done{finished}))
5989    case AcceptFailed{retry, server, error}:
5990      match retry:
5991        case True{}: server.accept.loop(~C, ~operation, AcceptChecking{server})
5992        case False{}: IO.pure(Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>, (server, Fail{error}))
5993
5994def server.accept.operation(~C: Data, ~operation: C -> Limits -> Chan(Admission.Command) -> Socket -> IO(Unit),
5995  server: Server<C>) -> IO(Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>):
5996  server.accept.loop(~C, ~operation, AcceptChecking{server})
5997
5998def server.accept(~C: Data, ~h: C -> Req -> IO(Reply), ~observe: C -> U32 -> Completion.Outcome -> IO(Unit), server: Server<C>) -> IO(Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>):
5999  server.accept.operation(~C,
6000    ~(context => settings => inbox => socket => talk(~C, ~h, ~observe, context, settings, inbox,
6001      Some{Serving{(socket, TurnMore{sv.none(), False{}}), None{}}})), server)
6002
6003def error.stopped(error: U32 & String) -> Bool:
6004  (code, message) = error
6005  U32.is_zero(code) && String.eq(message, "server stopped")
6006
6007type ServerLoop<-C: Data> is Type:
6008  ServerListening{server: Server<C>}
6009  ServerAccepted{result: Server<C> & Result<&1, &1, U32 & String, Chan(Unit)>}
6010  ServerFailed{retry: Bool, server: Server<C>, error: U32 & String}
6011
6012def error.capacity(error: U32 & String) -> Bool:
6013  (code, message) = error
6014  U32.is_eq(code, 11) && String.eq(message, "transport capacity exhausted")
6015
6016
6017# A single recursive state machine avoids recursion hidden inside a template.
6018@unsafe
6019def server.run.loop(~C: Data, ~operation: C -> Limits -> Chan(Admission.Command) -> Socket -> IO(Unit), step: ServerLoop<C>) -> IO(ServerExit):
6020  match step:
6021    case ServerListening{server}:
6022      do IO<ServerExit>:
6023        result : Server<C> & Result<&1, &1, U32 & String, Chan(Unit)> <- server.accept.operation(~C, ~operation, server)
6024        server.run.loop(~C, ~operation, ServerAccepted{result})
6025    case ServerAccepted{accepted}:
6026      (server, result) = accepted
6027      match result:
6028        case Fail{+error}:
6029          server.run.loop(~C, ~operation, ServerFailed{error.capacity(error), server, error})
6030        case Done{finished}:
6031          do IO<ServerExit>:
6032            Chan.close(Unit, finished)
6033            server.run.loop(~C, ~operation, ServerListening{server})
6034    case ServerFailed{retry, server, +error}:
6035      match retry:
6036        case True{}:
6037          server.run.loop(~C, ~operation, ServerListening{server})
6038        case False{}:
6039          server.finish(~C, error.stopped(error), error, server)
6040
6041def server.run(~C: Data, ~h: C -> Req -> IO(Reply), ~observe: C -> U32 -> Completion.Outcome -> IO(Unit), server: Server<C>) -> IO(ServerExit):
6042  server.run.loop(~C,
6043    ~(context => settings => inbox => socket => talk(~C, ~h, ~observe, context, settings, inbox,
6044      Some{Serving{(socket, TurnMore{sv.none(), False{}}), None{}}})), ServerListening{server})
6045
6046# Convenience wrappers use the same owner and observe its actual exit/drain.
6047def server.exited(result: ServerExit) -> IO(Unit):
6048  match result:
6049    case ServerStopped{counts}: IO.pure(Unit, Unit{})
6050    case ServerAcceptFailed{code, message, counts}: IO.die(Unit, code, message)
6051
6052def server.start.failed(error: StartupError) -> IO(Unit):
6053  match error:
6054    case InvalidConfig{}: IO.die(Unit, 22, "invalid server configuration")
6055    case BindError{code, message}: IO.die(Unit, code, message)
6056
6057def serve.config.result(result: Result<&2, &2, StartupError, Unit>) -> IO(Unit):
6058  match result:
6059    case Fail{error}: server.start.failed(error)
6060    case Done{unit}: IO.pure(Unit, unit)
6061
6062def serve.stream.nonempty(~S: Type, ~piece: S -> Bytes.Bytes -> IO(S & Bool), empty: Bool, state: S, b: Bytes.Bytes) -> IO(S & Bool):
6063  match empty:
6064    case True{}:
6065      IO.pure(S & Bool, (state, False{}))
6066    case False{}:
6067      piece(state, b)
6068
6069# The piece callback returns True to discard the rest of this request body.
6070def serve.stream.one(~S: Type, ~piece: S -> Bytes.Bytes -> IO(S & Bool), drop: Bool, state: S, b: Bytes.Bytes) -> IO(S & Bool):
6071  match drop:
6072    case True{}:
6073      IO.pure(S & Bool, (state, True{}))
6074    case False{}:
6075      Bytes.Bytes{+len, buf} = b
6076      serve.stream.nonempty(~S, ~piece, U32.is_eq(len, 0), state, Bytes.Bytes{len, buf})
6077
6078def serve.stream.parts(~S: Type, ~piece: S -> Bytes.Bytes -> IO(S & Bool), xs: List<&1, Bytes.Bytes>, st: S & Bool) -> IO(S & Bool):
6079  match xs:
6080    case Nil{}:
6081      IO.pure(S & Bool, st)
6082    case Con{b, rest}:
6083      (state, drop) = st
6084      do IO<S & Bool>:
6085        next : S & Bool <- serve.stream.one(~S, ~piece, drop, state, b)
6086        serve.stream.parts(~S, ~piece, rest, next)
6087
6088def serve.stream.feed(~S: Type, ~start: Req -> IO(S), ~piece: S -> Bytes.Bytes -> IO(S & Bool), req: Req, m: Maybe<&1, S & Bool>, parts: List<&1, Bytes.Bytes>) -> IO(S & Bool):
6089  match m:
6090    case None{}:
6091      do IO<S & Bool>:
6092        state : S <- start(req)
6093        serve.stream.parts(~S, ~piece, parts, (state, False{}))
6094    case Some{st}:
6095      serve.stream.parts(~S, ~piece, parts, st)
6096
6097def serve.stream.respond(~S: Type, ~finish: S -> IO(Reply), ~observe: U32 -> Completion.Outcome -> IO(Unit), +settings: Limits, s: Socket, rest: Bytes.Bytes, +headers: Map<&2, List<&2, String>>, v11: Bool, +method: String, st: S & Bool) -> IO(Maybe<&1, Socket & Turn>):
6098  (state, dropped) = st
6099  do IO<Maybe<&1, Socket & Turn>>:
6100    res : Reply <- finish(state)
6101    talk.respond(Completion.Observed{status => outcome => observe(status, outcome)}, settings, s, rest, headers, v11, String.eq(method, "HEAD"), res)
6102
6103def admission.ready(t: Turn) -> Bool & Turn:
6104  match t:
6105    case TurnReq{req, rest, v11}:
6106      (True{}, TurnReq{req, rest, v11})
6107    case TurnMore{sv, cont}:
6108      match sv:
6109        case SvHead{buf}:
6110          (False{}, TurnMore{SvHead{buf}, cont})
6111        case SvLen{req, v11, left, parts}:
6112          (True{}, TurnMore{SvLen{req, v11, left, parts}, cont})
6113        case SvChunk{req, v11, n, state, parts}:
6114          (True{}, TurnMore{SvChunk{req, v11, n, state, parts}, cont})
6115    case TurnFail{status}:
6116      (False{}, TurnFail{status})
6117    case TurnClose{}:
6118      (False{}, TurnClose{})
6119    case TurnInputFailed{operation, code, message}:
6120      (False{}, TurnInputFailed{operation, code, message})
6121
6122def admission.give.held(held: Bool, inbox: Chan(Admission.Command)) -> IO(Unit):
6123  match held:
6124    case False{}:
6125      IO.pure(Unit, Unit{})
6126    case True{}:
6127      Admission.give(inbox, 1)
6128
6129type StreamServing<-S: Type> is Type:
6130  StreamCheck{held: Bool, connection: Serving, state: Maybe<&1, S & Bool>}
6131  StreamReady{held: Bool, ready: Bool, connection: Serving, state: Maybe<&1, S & Bool>}
6132  StreamChecked{held: Bool, admitted: Bool, connection: Serving, state: Maybe<&1, S & Bool>}
6133  StreamDone{}
6134
6135def serve.stream.after(~S: Type, next: Maybe<&1, Socket & Turn>) -> StreamServing<S>:
6136  match next:
6137    case None{}:
6138      StreamDone{}
6139    case Some{connection}:
6140      StreamCheck{False{}, Serving{connection, None{}}, None{}}
6141
6142def serve.stream.ready(~S: Type, held: Bool, socket: Socket, phase: Maybe<&2, Phase>,
6143  state: Maybe<&1, S & Bool>, result: Bool & Turn) -> StreamServing<S>:
6144  (ready, turn) = result
6145  StreamReady{held, ready, Serving{(socket, turn), phase}, state}
6146
6147def admission.stream.take(needed: Bool, inbox: Chan(Admission.Command)) -> IO(Bool):
6148  match needed:
6149    case False{}:
6150      IO.pure(Bool, True{})
6151    case True{}:
6152      Admission.take(inbox, 1)
6153
6154type StreamAbort is Data:
6155  StreamClosed{}
6156  StreamFailed{status: U32}
6157  StreamInputFailed{operation: InputOperation, code: U32, message: String}
6158
6159# The application consumes its real affine state on unsuccessful upload paths.
6160# An abort that does not return remains admitted work, not a fabricated drain.
6161def serve.stream.abort(~S: Type, ~abort: S -> StreamAbort -> IO(Unit),
6162  reason: StreamAbort, state: Maybe<&1, S & Bool>) -> IO(Unit):
6163  match state:
6164    case None{}: IO.pure(Unit, Unit{})
6165    case Some{pair}:
6166      (value, dropped) = pair
6167      abort(value, reason)
6168
6169# One recursive state machine keeps template callbacks out of mutual recursion.
6170@unsafe
6171def serve.stream.talk(
6172  ~S: Type, ~start: Req -> IO(S), ~piece: S -> Bytes.Bytes -> IO(S & Bool),
6173  ~finish: S -> IO(Reply), ~abort: S -> StreamAbort -> IO(Unit), ~observe: U32 -> Completion.Outcome -> IO(Unit), +settings: Limits, +inbox: Chan(Admission.Command), step: StreamServing<S>
6174) -> IO(Unit):
6175  Limits{max, cap, hm, bm, im, wm} = settings
6176  match step:
6177    case StreamDone{}:
6178      IO.pure(Unit, Unit{})
6179    case StreamCheck{held, connection, state}:
6180      Serving{(socket, turn), phase} = connection
6181      serve.stream.talk(~S, ~start, ~piece, ~finish, ~abort, ~observe, settings, inbox,
6182        serve.stream.ready(~S, held, socket, phase, state, admission.ready(turn)))
6183    case StreamReady{+held, +ready, connection, state}:
6184      do IO<Unit>:
6185        admitted : Bool <- admission.stream.take(Bool.not(held) && ready, inbox)
6186        serve.stream.talk(~S, ~start, ~piece, ~finish, ~abort, ~observe, settings, inbox,
6187          StreamChecked{held || ready, admitted, connection, state})
6188    case StreamChecked{+held, admitted, connection, m}:
6189      match admitted:
6190        case False{}:
6191          Serving{(socket, turn), phase} = connection
6192          do IO<Unit>:
6193            serve.stream.abort(~S, ~abort, StreamFailed{503}, m)
6194            admission.reject(Completion.Observed{status => outcome => observe(status, outcome)}, socket, admission.turn.head(turn), wm)
6195        case True{}:
6196          Serving{(s, t), phase} = connection
6197          match t:
6198            case TurnClose{}:
6199              do IO<Unit>:
6200                Socket.close(s)
6201                serve.stream.abort(~S, ~abort, StreamClosed{}, m)
6202                admission.give.held(held, inbox)
6203            case TurnInputFailed{operation, code, message}:
6204              do IO<Unit>:
6205                Socket.close(s)
6206                serve.stream.abort(~S, ~abort, StreamInputFailed{operation, code, message}, m)
6207                admission.give.held(held, inbox)
6208            case TurnFail{+status}:
6209              do IO<Unit>:
6210                serve.stream.abort(~S, ~abort, StreamFailed{status}, m)
6211                reply_fail(Completion.Observed{status => outcome => observe(status, outcome)}, s, status, wm)
6212                admission.give.held(held, inbox)
6213            case TurnReq{req, rest, v11}:
6214              Req{+method, path, +headers, body} = req
6215              do IO<Unit>:
6216                next : S & Bool <- serve.stream.feed(~S, ~start, ~piece,
6217                  Req{method, path, headers, Bytes.new(0)}, m, [body])
6218                after : Maybe<&1, Socket & Turn> <- serve.stream.respond(~S, ~finish, ~observe, settings, s, rest, headers, v11, method, next)
6219                Admission.give(inbox, 1)
6220                serve.stream.talk(~S, ~start, ~piece, ~finish, ~abort, ~observe, settings, inbox,
6221                  serve.stream.after(~S, after))
6222            case TurnMore{sv, cont}:
6223              match sv:
6224                case SvHead{buf}:
6225                  do IO<Unit>:
6226                    received : (Socket & Turn) & Phase <- talk.recv(inbox, held, settings, s, SvHead{buf}, cont, phase)
6227                    serve.stream.talk(~S, ~start, ~piece, ~finish, ~abort, ~observe, settings, inbox,
6228                      StreamCheck{held, talk.state(received), m})
6229                case SvLen{req, +v11, +left, parts}:
6230                  Req{+method, +path, +headers, body} = req
6231                  do IO<Unit>:
6232                    now : Time.Duration <- Time.mono()
6233                    reading : Phase = phase.body(phase, settings, now)
6234                    next : S & Bool <- serve.stream.feed(~S, ~start, ~piece,
6235                      Req{method, path, headers, body}, m, List.reverse(&1, Bytes.Bytes, parts))
6236                    received : (Socket & Turn) & Phase <- talk.recv(inbox, held, settings, s,
6237                      SvLen{Req{method, path, headers, Bytes.new(0)}, v11, left, Nil{}}, cont, Some{reading})
6238                    serve.stream.talk(~S, ~start, ~piece, ~finish, ~abort, ~observe, settings, inbox,
6239                      StreamCheck{held, talk.state(received), Some{next}})
6240                case SvChunk{req, +v11, +n, st, parts}:
6241                  Req{+method, +path, +headers, body} = req
6242                  do IO<Unit>:
6243                    now : Time.Duration <- Time.mono()
6244                    reading : Phase = phase.body(phase, settings, now)
6245                    next : S & Bool <- serve.stream.feed(~S, ~start, ~piece,
6246                      Req{method, path, headers, body}, m, List.reverse(&1, Bytes.Bytes, parts))
6247                    received : (Socket & Turn) & Phase <- talk.recv(inbox, held, settings, s,
6248                      SvChunk{Req{method, path, headers, Bytes.new(0)}, v11, n, st, Nil{}}, cont, Some{reading})
6249                    serve.stream.talk(~S, ~start, ~piece, ~finish, ~abort, ~observe, settings, inbox,
6250                      StreamCheck{held, talk.state(received), Some{next}})
6251
6252
6253def server.stream.run(
6254  ~S: Type, ~start: Req -> IO(S), ~piece: S -> Bytes.Bytes -> IO(S & Bool),
6255  ~finish: S -> IO(Reply), ~abort: S -> StreamAbort -> IO(Unit), ~observe: U32 -> Completion.Outcome -> IO(Unit), server: Server<Unit>
6256) -> IO(ServerExit):
6257  server.run.loop(~Unit,
6258    ~(context => settings => inbox => socket =>
6259      serve.stream.talk(~S, ~start, ~piece, ~finish, ~abort, ~observe, settings, inbox,
6260        StreamCheck{False{}, Serving{(socket, TurnMore{sv.none(), False{}}), None{}}, None{}})),
6261    ServerListening{server})
6262
6263def serve.stream.started(
6264  ~S: Type, ~start: Req -> IO(S), ~piece: S -> Bytes.Bytes -> IO(S & Bool), ~finish: S -> IO(Reply), ~abort: S -> StreamAbort -> IO(Unit), ~observe: U32 -> Completion.Outcome -> IO(Unit),
6265  result: Unit & Result<&2, &1, StartupError, Server<Unit>>
6266) -> IO(Result<&2, &2, StartupError, Unit>):
6267  (owner, got) = result
6268  match got:
6269    case Fail{error}:
6270      IO.pure(Result<&2, &2, StartupError, Unit>, Fail{error})
6271    case Done{server}:
6272      do IO<Result<&2, &2, StartupError, Unit>>:
6273        exited : ServerExit <- server.stream.run(~S, ~start, ~piece, ~finish, ~abort, ~observe, server)
6274        server.exited(exited)
6275        return Done{Unit{}}
6276
6277def serve.stream.config(
6278  ~S: Type, ~start: Req -> IO(S), ~piece: S -> Bytes.Bytes -> IO(S & Bool), ~finish: S -> IO(Reply), ~abort: S -> StreamAbort -> IO(Unit), ~observe: U32 -> Completion.Outcome -> IO(Unit),
6279  config: ServerConfig
6280) -> IO(Result<&2, &2, StartupError, Unit>):
6281  do IO<Result<&2, &2, StartupError, Unit>>:
6282    started : Unit & Result<&2, &1, StartupError, Server<Unit>> <- server.start(~Unit, ~Unit, Unit{}, Unit{}, config)
6283    serve.stream.started(~S, ~start, ~piece, ~finish, ~abort, ~observe, started)
6284
6285type WriterMode is Data:
6286  WriteKnown{left: U32}
6287  WriteChunk{}
6288  WriteNone{}
6289
6290type Writer is Type:
6291  Writer{s: Maybe<&1, Socket>, mode: WriterMode, until: Time.Duration, outcome: Completion.Outcome}
6292
6293type WriteHead<-S: Type> is Type:
6294  WriteHead{status: U32, headers: Map<&2, List<&2, String>>, length: Maybe<&2, U32>, state: S, receipt: Completion.Receipt}
6295
6296def writer.sent(+mode: WriterMode, +until: Time.Duration, m: Socket & Result<&1, &1, U32 & String, Unit>) -> IO(Writer):
6297  (s, r) = m
6298  match r:
6299    case Fail{(code, message)}:
6300      do IO<Writer>:
6301        Socket.close(s)
6302        return Writer{None{}, mode, until, Completion.WriteFailed{code, message}}
6303    case Done{u}:
6304      IO.pure(Writer, Writer{Some{s}, mode, until, Completion.HostAccepted{}})
6305
6306def writer.raw(w: Writer, b: Bytes.Bytes) -> IO(Writer):
6307  Writer{socket, +mode, +until, outcome} = w
6308  match socket:
6309    case None{}:
6310      IO.pure(Writer, Writer{None{}, mode, until, outcome})
6311    case Some{s}:
6312      do IO<Writer>:
6313        sent : Socket & Result<&1, &1, U32 & String, Unit> <- bounded.send(s, b, until)
6314        writer.sent(mode, until, sent)
6315
6316def writer.chunk(s: Socket, b: Bytes.Bytes, +len: U32, until: Time.Duration) -> IO(Writer):
6317  do IO<Writer>:
6318    head : Writer <- writer.raw(Writer{Some{s}, WriteChunk{}, until, Completion.HostAccepted{}}, Bytes.from_string(hex(len) ++ "\r\n"))
6319    data : Writer <- writer.raw(head, b)
6320    writer.raw(data, Bytes.from_string("\r\n"))
6321
6322def writer.known(ok: Bool, s: Socket, +left: U32, len: U32, b: Bytes.Bytes, +until: Time.Duration) -> IO(Writer):
6323  match ok:
6324    case False{}:
6325      do IO<Writer>:
6326        Socket.close(s)
6327        return Writer{None{}, WriteKnown{left}, until, Completion.IncompleteResponse{}}
6328    case True{}:
6329      writer.raw(Writer{Some{s}, WriteKnown{(left - len : U32)}, until, Completion.HostAccepted{}}, b)
6330
6331def writer.chunk.go(empty: Bool, s: Socket, b: Bytes.Bytes, len: U32, until: Time.Duration) -> IO(Writer):
6332  match empty:
6333    case True{}:
6334      IO.pure(Writer, Writer{Some{s}, WriteChunk{}, until, Completion.HostAccepted{}})
6335    case False{}:
6336      writer.chunk(s, b, len, until)
6337
6338def writer.write.mode(s: Socket, mode: WriterMode, b: Bytes.Bytes, until: Time.Duration) -> IO(Writer):
6339  match mode:
6340    case WriteNone{}:
6341      IO.pure(Writer, Writer{Some{s}, WriteNone{}, until, Completion.HostAccepted{}})
6342    case WriteKnown{+left}:
6343      Bytes.Bytes{+len, buf} = b
6344      writer.known(U32.is_le(len, left), s, left, len, Bytes.Bytes{len, buf}, until)
6345    case WriteChunk{}:
6346      Bytes.Bytes{+len, buf} = b
6347      writer.chunk.go(U32.is_zero(len), s, Bytes.Bytes{len, buf}, len, until)
6348
6349def writer.write(w: Writer, b: Bytes.Bytes) -> IO(Writer):
6350  Writer{socket, mode, until, outcome} = w
6351  match socket:
6352    case None{}:
6353      IO.pure(Writer, Writer{None{}, mode, until, outcome})
6354    case Some{s}:
6355      writer.write.mode(s, mode, b, until)
6356
6357def writer.result(w: Writer) -> Maybe<&1, Socket> & Completion.Outcome:
6358  Writer{socket, mode, until, outcome} = w
6359  (socket, outcome)
6360
6361def writer.finish.known(complete: Bool, s: Socket) -> IO(Maybe<&1, Socket> & Completion.Outcome):
6362  match complete:
6363    case True{}:
6364      IO.pure(Maybe<&1, Socket> & Completion.Outcome, (Some{s}, Completion.HostAccepted{}))
6365    case False{}:
6366      do IO<Maybe<&1, Socket> & Completion.Outcome>:
6367        Socket.close(s)
6368        return (None{}, Completion.IncompleteResponse{})
6369
6370def writer.finish.mode(s: Socket, mode: WriterMode, until: Time.Duration) -> IO(Maybe<&1, Socket> & Completion.Outcome):
6371  match mode:
6372    case WriteNone{}:
6373      IO.pure(Maybe<&1, Socket> & Completion.Outcome, (Some{s}, Completion.HostAccepted{}))
6374    case WriteKnown{left}:
6375      writer.finish.known(U32.is_zero(left), s)
6376    case WriteChunk{}:
6377      do IO<Maybe<&1, Socket> & Completion.Outcome>:
6378        end : Writer <- writer.raw(Writer{Some{s}, WriteChunk{}, until, Completion.HostAccepted{}}, Bytes.from_string("0\r\n\r\n"))
6379        return writer.result(end)
6380
6381def writer.finish(w: Writer) -> IO(Maybe<&1, Socket> & Completion.Outcome):
6382  Writer{socket, mode, until, outcome} = w
6383  match socket:
6384    case None{}:
6385      IO.pure(Maybe<&1, Socket> & Completion.Outcome, (None{}, outcome))
6386    case Some{s}:
6387      writer.finish.mode(s, mode, until)
6388
6389def writer.header.one(m: Map<&2, List<&2, String>>, +key: String, vs: List<&2, String>, framing: Bool) -> Map<&2, List<&2, String>>:
6390  match framing:
6391    case True{}:
6392      m
6393    case False{}:
6394      Map.set(&2, List<&2, String>, m, key, vs)
6395
6396def writer.headers(xs: List<&2, Sigma<&2, &2, String, _ => List<&2, String>>>, m: Map<&2, List<&2, String>>) -> Map<&2, List<&2, String>>:
6397  match xs:
6398    case Nil{}:
6399      m
6400    case (k, vs) <> rest:
6401      +key = String.to_lower(k)
6402      +framing = Bool.or(String.eq(key, "content-length"), String.eq(key, "transfer-encoding"))
6403      writer.headers(rest, writer.header.one(m, key, vs, framing))
6404
6405def writer.plan.body(headers: Map<&2, List<&2, String>>, length: Maybe<&2, U32>) -> WriterMode & Map<&2, List<&2, String>>:
6406  match length:
6407    case Some{+n}:
6408      (WriteKnown{n}, set(headers, "content-length", U32.show(n)))
6409    case None{}:
6410      (WriteChunk{}, set(headers, "transfer-encoding", "chunked"))
6411
6412def writer.plan(nobody: Bool, headers: Map<&2, List<&2, String>>, length: Maybe<&2, U32>) -> WriterMode & Map<&2, List<&2, String>>:
6413  match nobody:
6414    case True{}:
6415      (WriteNone{}, headers)
6416    case False{}:
6417      writer.plan.body(headers, length)
6418
6419def serve.write.after(settings: Limits, keep: Bool, rest: Bytes.Bytes, socket: Maybe<&1, Socket>) -> Maybe<&1, Socket & Turn>:
6420  match socket:
6421    case None{}:
6422      None{}
6423    case Some{s}:
6424      Some{talk.after.keep(keep, settings, rest, s)}
6425
6426def serve.write.completed(observer: Completion.Receipt, receipt: Completion.Receipt, +status: U32,
6427  settings: Limits, keep: Bool, rest: Bytes.Bytes, result: Maybe<&1, Socket> & Completion.Outcome) -> IO(Maybe<&1, Socket & Turn>):
6428  (socket, outcome) = result
6429  +observed = {outcome : Completion.Outcome}
6430  do IO<Maybe<&1, Socket & Turn>>:
6431    Completion.report(observer, status, observed)
6432    Completion.report(receipt, status, observed)
6433    return serve.write.after(settings, keep, rest, socket)
6434
6435def serve.write.returned(observer: Completion.Receipt, status: U32, settings: Limits, keep: Bool,
6436  rest: Bytes.Bytes, result: Writer & Completion.Receipt) -> IO(Maybe<&1, Socket & Turn>):
6437  (writer, receipt) = result
6438  do IO<Maybe<&1, Socket & Turn>>:
6439    done : Maybe<&1, Socket> & Completion.Outcome <- writer.finish(writer)
6440    serve.write.completed(observer, receipt, status, settings, keep, rest, done)
6441
6442def serve.write.finish(observer: Completion.Receipt, receipt: Completion.Receipt, status: U32,
6443  settings: Limits, keep: Bool, rest: Bytes.Bytes, w: Writer) -> IO(Maybe<&1, Socket & Turn>):
6444  serve.write.returned(observer, status, settings, keep, rest, (w, receipt))
6445
6446def serve.write.body(~S: Type, ~write: S -> Writer -> Completion.Receipt -> IO(Writer & Completion.Receipt), ~dispose: S -> IO(Unit),
6447  observer: Completion.Receipt, receipt: Completion.Receipt, status: U32, settings: Limits,
6448  keep: Bool, rest: Bytes.Bytes, state: S, s: Socket, mode: WriterMode, suppress: Bool, until: Time.Duration) -> IO(Maybe<&1, Socket & Turn>):
6449  match suppress:
6450    case True{}:
6451      do IO<Maybe<&1, Socket & Turn>>:
6452        dispose(state)
6453        serve.write.finish(observer, receipt, status, settings, keep, rest, Writer{Some{s}, WriteNone{}, until, Completion.HostAccepted{}})
6454    case False{}:
6455      do IO<Maybe<&1, Socket & Turn>>:
6456        result : Writer & Completion.Receipt <- write(state, Writer{Some{s}, mode, until, Completion.HostAccepted{}}, receipt)
6457        serve.write.returned(observer, status, settings, keep, rest, result)
6458
6459def serve.write.open(~S: Type, ~write: S -> Writer -> Completion.Receipt -> IO(Writer & Completion.Receipt), ~dispose: S -> IO(Unit),
6460  observer: Completion.Receipt, receipt: Completion.Receipt, +status: U32, settings: Limits,
6461  keep: Bool, rest: Bytes.Bytes, state: S, mode: WriterMode, suppress: Bool, until: Time.Duration,
6462  m: Socket & Result<&1, &1, U32 & String, Unit>) -> IO(Maybe<&1, Socket & Turn>):
6463  (s, r) = m
6464  match r:
6465    case Fail{(code, message)}:
6466      +failure = {Completion.WriteFailed{code, message} : Completion.Outcome}
6467      do IO<Maybe<&1, Socket & Turn>>:
6468        Socket.close(s)
6469        dispose(state)
6470        Completion.report(observer, status, failure)
6471        Completion.report(receipt, status, failure)
6472        return None{}
6473    case Done{u}:
6474      serve.write.body(~S, ~write, ~dispose, observer, receipt, status, settings, keep, rest, state, s, mode, suppress, until)
6475
6476def writer.connection(keep: Bool, headers: Map<&2, List<&2, String>>) -> Map<&2, List<&2, String>>:
6477  match keep:
6478    case True{}:
6479      headers
6480    case False{}:
6481      set(headers, "connection", "close")
6482
6483def serve.write.send.plan(
6484  ~S: Type, ~write: S -> Writer -> Completion.Receipt -> IO(Writer & Completion.Receipt), ~dispose: S -> IO(Unit),
6485  observer: Completion.Receipt, receipt: Completion.Receipt, +settings: Limits, s: Socket, rest: Bytes.Bytes,
6486  +keep: Bool, +head: Bool, +status: U32, state: S, plan: WriterMode & Map<&2, List<&2, String>>
6487) -> IO(Maybe<&1, Socket & Turn>):
6488  Limits{max, cap, hm, bm, im, wm} = settings
6489  (mode, headers) = plan
6490  sent_headers = writer.connection(keep, headers)
6491  do IO<Maybe<&1, Socket & Turn>>:
6492    now : Time.Duration <- Time.mono()
6493    +until : Time.Duration = Time.Duration.add(now, Time.Duration.of_ms(wm))
6494    sent : Socket & Result<&1, &1, U32 & String, Unit> <-
6495      bounded.send(s, Bytes.from_string(response(status, sent_headers, "")), until)
6496    serve.write.open(~S, ~write, ~dispose, observer, receipt, status, settings, keep, rest, state, mode,
6497      frame.nobody(status, head), until, sent)
6498
6499def serve.write.send(
6500  ~S: Type, ~write: S -> Writer -> Completion.Receipt -> IO(Writer & Completion.Receipt), ~dispose: S -> IO(Unit), observer: Completion.Receipt, settings: Limits, s: Socket, rest: Bytes.Bytes,
6501  +headers: Map<&2, List<&2, String>>, v11: Bool, +head: Bool, out: WriteHead<S>
6502) -> IO(Maybe<&1, Socket & Turn>):
6503  WriteHead{+status, rh, length, state, receipt} = out
6504  +normalized = writer.headers(Map.to_list(&2, List<&2, String>, rh), empty())
6505  +keep = serve.keep(headers, v11, status, normalized)
6506  serve.write.send.plan(~S, ~write, ~dispose, observer, receipt, settings, s, rest, keep, head, status, state,
6507    writer.plan(frame.nobody(status, False{}), normalized, length))
6508
6509def admission.write(
6510  ~S: Type, ~start: Req -> IO(WriteHead<S>), ~write: S -> Writer -> Completion.Receipt -> IO(Writer & Completion.Receipt), ~dispose: S -> IO(Unit), ~observe: U32 -> Completion.Outcome -> IO(Unit),
6511  admitted: Bool, +inbox: Chan(Admission.Command), +settings: Limits,
6512  s: Socket, req: Req, rest: Bytes.Bytes, v11: Bool
6513) -> IO(Maybe<&1, Socket & Turn>):
6514  match admitted:
6515    case False{}:
6516      Limits{max, cap, hm, bm, im, wm} = settings
6517      do IO<Maybe<&1, Socket & Turn>>:
6518        admission.reject(Completion.Observed{status => outcome => observe(status, outcome)}, s, admission.head(req), wm)
6519        return None{}
6520    case True{}:
6521      Req{+method, path, +headers, body} = req
6522      do IO<Maybe<&1, Socket & Turn>>:
6523        out : WriteHead<S> <- start(Req{method, path, headers, body})
6524        after : Maybe<&1, Socket & Turn> <- serve.write.send(~S, ~write, ~dispose, Completion.Observed{status => outcome => observe(status, outcome)}, settings, s, rest, headers, v11, String.eq(method, "HEAD"), out)
6525        Admission.give(inbox, 1)
6526        return after
6527
6528@unsafe
6529def serve.write.talk(
6530  ~S: Type, ~start: Req -> IO(WriteHead<S>), ~write: S -> Writer -> Completion.Receipt -> IO(Writer & Completion.Receipt), ~dispose: S -> IO(Unit), ~observe: U32 -> Completion.Outcome -> IO(Unit),
6531  +settings: Limits, +inbox: Chan(Admission.Command), st: Maybe<&1, Serving>
6532) -> IO(Unit):
6533  Limits{max, cap, hm, bm, im, wm} = settings
6534  match st:
6535    case None{}:
6536      IO.pure(Unit, Unit{})
6537    case Some{Serving{(s, t), phase}}:
6538      match t:
6539        case TurnMore{sv, cont}:
6540          do IO<Unit>:
6541            received : (Socket & Turn) & Phase <- talk.recv(inbox, False{}, settings, s, sv, cont, phase)
6542            serve.write.talk(~S, ~start, ~write, ~dispose, ~observe, settings, inbox, Some{talk.state(received)})
6543        case TurnReq{req, rest, v11}:
6544          do IO<Unit>:
6545            admitted : Bool <- Admission.take(inbox, 1)
6546            after : Maybe<&1, Socket & Turn> <- admission.write(~S, ~start, ~write, ~dispose, ~observe, admitted, inbox, settings, s, req, rest, v11)
6547            serve.write.talk(~S, ~start, ~write, ~dispose, ~observe, settings, inbox, serve.write.state(after))
6548        case TurnFail{status}:
6549          reply_fail(Completion.Observed{status => outcome => observe(status, outcome)}, s, status, wm)
6550        case TurnClose{}:
6551          Socket.close(s)
6552        case TurnInputFailed{operation, code, message}:
6553          Socket.close(s)
6554
6555def server.write.run(
6556  ~S: Type, ~start: Req -> IO(WriteHead<S>),
6557  ~write: S -> Writer -> Completion.Receipt -> IO(Writer & Completion.Receipt),
6558  ~dispose: S -> IO(Unit),
6559  ~observe: U32 -> Completion.Outcome -> IO(Unit), server: Server<Unit>
6560) -> IO(ServerExit):
6561  server.run.loop(~Unit,
6562    ~(context => settings => inbox => socket =>
6563      serve.write.talk(~S, ~start, ~write, ~dispose, ~observe, settings, inbox,
6564        Some{Serving{(socket, TurnMore{sv.none(), False{}}), None{}}})),
6565    ServerListening{server})
6566
6567def serve.write.started(
6568  ~S: Type, ~start: Req -> IO(WriteHead<S>), ~write: S -> Writer -> Completion.Receipt -> IO(Writer & Completion.Receipt), ~dispose: S -> IO(Unit), ~observe: U32 -> Completion.Outcome -> IO(Unit),
6569  result: Unit & Result<&2, &1, StartupError, Server<Unit>>
6570) -> IO(Result<&2, &2, StartupError, Unit>):
6571  (owner, got) = result
6572  match got:
6573    case Fail{error}:
6574      IO.pure(Result<&2, &2, StartupError, Unit>, Fail{error})
6575    case Done{server}:
6576      do IO<Result<&2, &2, StartupError, Unit>>:
6577        exited : ServerExit <- server.write.run(~S, ~start, ~write, ~dispose, ~observe, server)
6578        server.exited(exited)
6579        return Done{Unit{}}
6580
6581def serve.write.config(
6582  ~S: Type, ~start: Req -> IO(WriteHead<S>), ~write: S -> Writer -> Completion.Receipt -> IO(Writer & Completion.Receipt), ~dispose: S -> IO(Unit), ~observe: U32 -> Completion.Outcome -> IO(Unit), config: ServerConfig
6583) -> IO(Result<&2, &2, StartupError, Unit>):
6584  do IO<Result<&2, &2, StartupError, Unit>>:
6585    started : Unit & Result<&2, &1, StartupError, Server<Unit>> <- server.start(~Unit, ~Unit, Unit{}, Unit{}, config)
6586    serve.write.started(~S, ~start, ~write, ~dispose, ~observe, started)
6587
6588def serve.started(~h: Req -> IO(Reply), ~observe: U32 -> Completion.Outcome -> IO(Unit),
6589  started: Unit & Result<&2, &1, StartupError, Server<Unit>>) -> IO(Unit):
6590  (owner, result) = started
6591  match result:
6592    case Fail{error}: server.start.failed(error)
6593    case Done{server}:
6594      do IO<Unit>:
6595        exited : ServerExit <- server.run(~Unit, ~(context => req => h(req)),
6596          ~(context => status => outcome => observe(status, outcome)), server)
6597        server.exited(exited)
6598
6599def serve.on.with(~h: Req -> IO(Reply), ~observe: U32 -> Completion.Outcome -> IO(Unit), host: String, +port: U32, +max: Nat) -> IO(Unit):
6600  do IO<Unit>:
6601    limits.validate(max)
6602    started : Unit & Result<&2, &1, StartupError, Server<Unit>> <-
6603      server.start(~Unit, ~Unit, Unit{}, Unit{}, server.config.with(host, port, max))
6604    serve.started(~h, ~observe, started)
6605
6606def serve.on(~h: Req -> IO(Reply), ~observe: U32 -> Completion.Outcome -> IO(Unit), host: String, +port: U32) -> IO(Unit):
6607  serve.on.with(~h, ~observe, host, port, serve.max())
6608
6609def serve.with(~h: Req -> IO(Reply), ~observe: U32 -> Completion.Outcome -> IO(Unit), +port: U32, +max: Nat) -> IO(Unit):
6610  serve.on.with(~h, ~observe, "0.0.0.0", port, max)
6611
6612def serve(~h: Req -> IO(Reply), ~observe: U32 -> Completion.Outcome -> IO(Unit), +port: U32) -> IO(Unit):
6613  serve.with(~h, ~observe, port, serve.max())
6614
6615def serve.stream.on.with(
6616  ~S: Type, ~start: Req -> IO(S), ~piece: S -> Bytes.Bytes -> IO(S & Bool),
6617  ~finish: S -> IO(Reply), ~abort: S -> StreamAbort -> IO(Unit), ~observe: U32 -> Completion.Outcome -> IO(Unit), host: String, +port: U32, +max: Nat
6618) -> IO(Unit):
6619  do IO<Unit>:
6620    limits.validate(max)
6621    result : Result<&2, &2, StartupError, Unit> <-
6622      serve.stream.config(~S, ~start, ~piece, ~finish, ~abort, ~observe, server.config.with(host, port, max))
6623    serve.config.result(result)
6624
6625def serve.stream.with(
6626  ~S: Type, ~start: Req -> IO(S), ~piece: S -> Bytes.Bytes -> IO(S & Bool),
6627  ~finish: S -> IO(Reply), ~abort: S -> StreamAbort -> IO(Unit), ~observe: U32 -> Completion.Outcome -> IO(Unit), +port: U32, +max: Nat
6628) -> IO(Unit):
6629  serve.stream.on.with(~S, ~start, ~piece, ~finish, ~abort, ~observe, "0.0.0.0", port, max)
6630
6631def serve.write.on.with(
6632  ~S: Type, ~start: Req -> IO(WriteHead<S>), ~write: S -> Writer -> Completion.Receipt -> IO(Writer & Completion.Receipt), ~dispose: S -> IO(Unit), ~observe: U32 -> Completion.Outcome -> IO(Unit),
6633  host: String, +port: U32, +max: Nat
6634) -> IO(Unit):
6635  do IO<Unit>:
6636    limits.validate(max)
6637    result : Result<&2, &2, StartupError, Unit> <-
6638      serve.write.config(~S, ~start, ~write, ~dispose, ~observe, server.config.with(host, port, max))
6639    serve.config.result(result)
6640
6641def serve.write.with(
6642  ~S: Type, ~start: Req -> IO(WriteHead<S>), ~write: S -> Writer -> Completion.Receipt -> IO(Writer & Completion.Receipt), ~dispose: S -> IO(Unit), ~observe: U32 -> Completion.Outcome -> IO(Unit),
6643  +port: U32, +max: Nat
6644) -> IO(Unit):
6645  serve.write.on.with(~S, ~start, ~write, ~dispose, ~observe, "0.0.0.0", port, max)