http.bend

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