http.bend

bend-kit-http@0.22.0.0 · 5,364 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.1/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. max_age and expires are already times.
2123type Cav is Data:
2124  Cav{expires: Maybe<&2, Time.Instant>, max_age: Maybe<&2, Time.Instant>, domain: String, path: Maybe<&2, String>, secure: Bool, http_only: Bool, same_site: String}
2125
2126def cookie.cav() -> Cav:
2127  Cav{None{}, None{}, "", None{}, False{}, False{}, "default"}
2128
2129# §5.5: 400 days, the longest a cookie lives.
2130def cookie.limit() -> U32:
2131  34560000
2132
2133def cookie.later(+now: Time.Instant, +secs: U32) -> Time.Instant:
2134  Time.Instant.add(now, Time.Duration.of_secs(Int.I64.from_u32(secs)))
2135
2136def cookie.expires.cap(+now: Time.Instant, m: Maybe<&2, Time.Instant>) -> Maybe<&2, Time.Instant>:
2137  match m:
2138    case None{}:
2139      None{}
2140    case Some{+t}:
2141      +lim = cookie.later(now, cookie.limit())
2142      Some{Bool.pick(Time.Instant, Cmp.is_lt(Time.Instant.cmp(lim, t)), lim, t)}
2143
2144def cookie.max_age.zero(m: Maybe<&2, U32>) -> Maybe<&2, U32>:
2145  match m:
2146    case None{}:
2147      None{}
2148    case Some{s}:
2149      Some{0}
2150
2151def cookie.max_age.nz(s: String) -> String:
2152  match s:
2153    case SNil{}:
2154      SNil{}
2155    case SCon{Chr{48}, t}:
2156      cookie.max_age.nz(t)
2157    case SCon{Chr{c}, t}:
2158      SCon{Chr{c}, t}
2159
2160# More than 9 significant digits is past the limit (and would overflow parse_u32).
2161def cookie.max_age.cap(long: Bool, m: Maybe<&2, U32>) -> Maybe<&2, U32>:
2162  match m:
2163    case None{}:
2164      None{}
2165    case Some{s}:
2166      Some{Bool.pick(U32, long, cookie.limit(), s)}
2167
2168def cookie.max_age.secs(+v: String, neg: Bool) -> Maybe<&2, U32>:
2169  match neg:
2170    case True{}:
2171      cookie.max_age.zero(parse_u32(String.drop(v, 1n)))
2172    case False{}:
2173      cookie.max_age.cap(cookie.over(cookie.max_age.nz(v), 9), parse_u32(v))
2174
2175# Zero or less is the earliest time, so the cookie is already expired.
2176def cookie.max_age.at(+now: Time.Instant, m: Maybe<&2, U32>) -> Maybe<&2, Time.Instant>:
2177  match m:
2178    case None{}:
2179      None{}
2180    case Some{+s}:
2181      Some{Bool.pick(Time.Instant, U32.is_eq(s, 0), Time.Instant.epoch(), cookie.later(now, U32.min(s, cookie.limit())))}
2182
2183# §5.6.2: DIGIT*, or "-" and DIGIT*. Anything else is ignored.
2184def cookie.max_age(+now: Time.Instant, +v: String) -> Maybe<&2, Time.Instant>:
2185  cookie.max_age.at(now, cookie.max_age.secs(v, String.starts_with(v, "-")))
2186
2187def cookie.same_site(+v: String) -> String:
2188  +l = String.to_lower(v)
2189  Bool.pick(String, Bool.or(String.eq(l, "strict"), Bool.or(String.eq(l, "lax"), String.eq(l, "none"))), l, "default")
2190
2191type Av is Data:
2192  AvExpires{}
2193  AvMaxAge{}
2194  AvDomain{}
2195  AvPath{}
2196  AvSecure{}
2197  AvHttpOnly{}
2198  AvSameSite{}
2199  AvOther{}
2200
2201def cookie.av.kind(+k: String) -> Av:
2202  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{})))))))
2203
2204# An Expires or Max-Age that does not parse leaves the earlier one. A leading dot of Domain is dropped.
2205def cookie.av.put(k: Av, a: Cav, +now: Time.Instant, +v: String) -> Cav:
2206  match k a:
2207    case AvExpires{} Cav{e, m, d, p, s, h, ss}:
2208      Cav{Maybe.or(&2, Time.Instant, cookie.expires.cap(now, cookie.date(v)), e), m, d, p, s, h, ss}
2209    case AvMaxAge{} Cav{e, m, d, p, s, h, ss}:
2210      Cav{e, Maybe.or(&2, Time.Instant, cookie.max_age(now, v), m), d, p, s, h, ss}
2211    case AvDomain{} Cav{e, m, d, p, s, h, ss}:
2212      Cav{e, m, String.to_lower(Bool.pick(String, String.starts_with(v, "."), String.drop(v, 1n), v)), p, s, h, ss}
2213    case AvPath{} Cav{e, m, d, p, s, h, ss}:
2214      Cav{e, m, d, Some{v}, s, h, ss}
2215    case AvSecure{} Cav{e, m, d, p, s, h, ss}:
2216      Cav{e, m, d, p, True{}, h, ss}
2217    case AvHttpOnly{} Cav{e, m, d, p, s, h, ss}:
2218      Cav{e, m, d, p, s, True{}, ss}
2219    case AvSameSite{} Cav{e, m, d, p, s, h, ss}:
2220      Cav{e, m, d, p, s, h, cookie.same_site(v)}
2221    case AvOther{} Cav{e, m, d, p, s, h, ss}:
2222      Cav{e, m, d, p, s, h, ss}
2223
2224# §5.6: name and value trimmed; a value over 1024 octets drops the attribute.
2225def cookie.av(+now: Time.Instant, +a: Cav, kv: String & String & Bool) -> Cav:
2226  (k, v, found) = kv
2227  +tv = trim(v)
2228  Bool.pick(Cav, cookie.over(tv, 1024), a, cookie.av.put(cookie.av.kind(String.to_lower(trim(k))), a, now, tv))
2229
2230def cookie.avs(xs: List<&2, String>, +now: Time.Instant, a: Cav) -> Cav:
2231  match xs:
2232    case Nil{}:
2233      a
2234    case Con{x, t}:
2235      cookie.avs(t, now, cookie.av(now, a, cookie.cut(x, 61)))
2236
2237# §5.6: with no "=", the name is empty and the pair is the value.
2238def cookie.nv(r: String & String & Bool) -> String & String:
2239  (a, b, found) = r
2240  match found:
2241    case True{}:
2242      (trim(a), trim(b))
2243    case False{}:
2244      ("", trim(a))
2245
2246def cookie.prefixed(+s: String, +p: String) -> Bool:
2247  String.starts_with(String.to_lower(s), p)
2248
2249# §5.7 steps 8–10: (domain, host-only), or None to ignore the cookie.
2250# ponytail: the public-suffix check knows single-label suffixes only (com, org, localhost). Multi-label
2251# ones (co.uk, github.io) need the publicsuffix.org list; ship it as data when a caller needs it.
2252def cookie.domain.of(+host: String, +d: String) -> Maybe<&1, String & Bool>:
2253  +suffix = Bool.and(Bool.not(String.is_empty(d)), Bool.not(String.contains(d, ".")))
2254  +d2 = Bool.pick(String, Bool.and(suffix, String.eq(d, host)), "", d)
2255  Bool.pick(Maybe<&1, String & Bool>, Bool.or(Bool.and(suffix, Bool.not(String.eq(d, host))), Bool.not(cookie.ascii(d))), None{},
2256    Bool.pick(Maybe<&1, String & Bool>, String.is_empty(d2), Some{(host, True{})},
2257      Bool.pick(Maybe<&1, String & Bool>, cookie.domain_match(host, d2), Some{(d2, False{})}, None{})))
2258
2259def cookie.path.of(p: Maybe<&2, String>, +req: String) -> String:
2260  match p:
2261    case None{}:
2262      cookie.default_path(req)
2263    case Some{+v}:
2264      Bool.pick(String, String.starts_with(v, "/"), v, cookie.default_path(req))
2265
2266# §5.7 steps 12–20: Secure needs https; SameSite=None needs Secure; the __Secure- and __Host- prefixes.
2267def 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>:
2268  match dm:
2269    case None{}:
2270      None{}
2271    case Some{(domain, +host_only)}:
2272      +host = Bool.and(Bool.and(secure, host_only), Bool.and(has_path, String.eq(path, "/")))
2273      +bad = Bool.or(Bool.or(Bool.and(secure, Bool.not(https)), Bool.and(String.eq(same_site, "none"), Bool.not(secure))),
2274        Bool.or(Bool.or(Bool.and(cookie.prefixed(name, "__secure-"), Bool.not(secure)), Bool.and(cookie.prefixed(name, "__host-"), Bool.not(host))),
2275          Bool.and(String.is_empty(name), Bool.or(cookie.prefixed(value, "__secure-"), cookie.prefixed(value, "__host-")))))
2276      Bool.pick(Maybe<&2, Cookie>, bad, None{}, Some{Cookie{name, value, domain, host_only, path, secure, http_only, same_site, expiry}})
2277
2278# Max-Age wins over Expires, whatever their order (§5.7 step 6).
2279def cookie.make(a: Url.Abs, +name: String, +value: String, c: Cav) -> Maybe<&2, Cookie>:
2280  Url.Abs{scheme, host, port, target} = a
2281  Cav{e, m, d, +p, secure, http_only, same_site} = c
2282  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, Maybe.or(&2, Time.Instant, m, e), String.eq(scheme, "https"))
2283
2284# An empty name and value, or more than 4096 octets of them, is ignored.
2285def cookie.parse.nv(+now: Time.Instant, a: Url.Abs, nv: String & String, avs: List<&2, String>) -> Maybe<&2, Cookie>:
2286  (+name, +value) = nv
2287  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(a, name, value, cookie.avs(avs, now, cookie.cav())))
2288
2289def cookie.parse.go(+now: Time.Instant, a: Url.Abs, xs: List<&2, String>) -> Maybe<&2, Cookie>:
2290  match xs:
2291    case Nil{}:
2292      None{}
2293    case Con{first, avs}:
2294      cookie.parse.nv(now, a, cookie.nv(cookie.cut(first, 61)), avs)
2295
2296# §5.6 and §5.7: one Set-Cookie value received from a at now, or None when it is ignored.
2297def cookie.parse(+now: Time.Instant, a: Url.Abs, +line: String) -> Maybe<&2, Cookie>:
2298  Bool.pick(Maybe<&2, Cookie>, cookie.ctl(line), None{}, cookie.parse.go(now, a, String.split(line, ';')))
2299
2300def cookie.https(a: Url.Abs) -> Bool:
2301  Url.Abs{scheme, host, port, target} = a
2302  String.eq(scheme, "https")
2303
2304def cookie.secure(c: Cookie) -> Bool:
2305  Cookie{name, value, domain, host_only, path, secure, http_only, same_site, expiry} = c
2306  secure
2307
2308# Same name, domain, host-only flag and path: the new cookie replaces the old one.
2309def cookie.same(+a: Cookie, +b: Cookie) -> Bool:
2310  Cookie{n1, v1, d1, h1, p1, s1, o1, ss1, e1} = a
2311  Cookie{n2, v2, d2, h2, p2, s2, o2, ss2, e2} = b
2312  Bool.and(Bool.and(String.eq(n1, n2), String.eq(d1, d2)), Bool.and(Bool.not(Bool.xor(h1, h2)), String.eq(p1, p2)))
2313
2314# §5.7 step 16: a secure cookie that a new cookie from plain http must not overlay.
2315def cookie.shadows(+old: Cookie, +c: Cookie) -> Bool:
2316  Cookie{n1, v1, +d1, h1, p1, s1, o1, ss1, e1} = old
2317  Cookie{n2, v2, +d2, h2, p2, s2, o2, ss2, e2} = c
2318  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)))
2319
2320def cookie.shadowed(cs: List<&2, Cookie>, +c: Cookie) -> Bool:
2321  match cs:
2322    case Nil{}:
2323      False{}
2324    case Con{+o, t}:
2325      Bool.or(cookie.shadows(o, c), cookie.shadowed(t, c))
2326
2327# cs with the cookie c replaces swapped for c (keeping its place, so its creation order), or c last.
2328# A c that is not live only removes the old one: that is how a server deletes a cookie.
2329def cookie.put(cs: List<&2, Cookie>, +c: Cookie, +live: Bool) -> List<&2, Cookie>:
2330  match cs:
2331    case Nil{}:
2332      Bool.pick(List<&2, Cookie>, live, [c], Nil{})
2333    case Con{+o, +t}:
2334      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)})
2335
2336def jar.put.c(m: Maybe<&2, Cookie>, j: Jar, +https: Bool) -> Jar:
2337  match m:
2338    case None{}:
2339      Jar{now, cs} = j
2340      Jar{now, cs}
2341    case Some{+c}:
2342      Jar{+now, +cs} = j
2343      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)))}
2344
2345def jar.put.one(j: Jar, +a: Url.Abs, x: String) -> Jar:
2346  Jar{+now, cs} = j
2347  jar.put.c(cookie.parse(now, a, x), Jar{now, cs}, cookie.https(a))
2348
2349def jar.put.all(xs: List<&2, String>, j: Jar, +a: Url.Abs) -> Jar:
2350  match xs:
2351    case Nil{}:
2352      j
2353    case Con{x, t}:
2354      jar.put.all(t, jar.put.one(j, a, x), a)
2355
2356# Every set-cookie field of h, in order, as received from a.
2357def jar.store.abs(j: Jar, +a: Url.Abs, +h: Map<&2, List<&2, String>>) -> Jar:
2358  jar.put.all(fields(h, "set-cookie"), j, a)
2359
2360def jar.store.url(j: Jar, u: Maybe<&2, Url.Abs>, +h: Map<&2, List<&2, String>>) -> Jar:
2361  match u:
2362    case None{}:
2363      j
2364    case Some{+a}:
2365      jar.store.abs(j, a, h)
2366
2367# The jar after res came from url, and res as it was. Header names are lowercase, as parse gives them.
2368# An unparsable url stores nothing.
2369def jar.store(j: Jar, url: String, res: Res) -> Jar & Res:
2370  Res{status, +headers, body} = res
2371  (jar.store.url(j, Url.absolute(url), headers), Res{status, headers, body})
2372
2373# §5.8.3: domain (exact when host-only), path, and Secure only over https.
2374def cookie.sends(+host: String, +path: String, +https: Bool, +c: Cookie) -> Bool:
2375  Cookie{n, v, +d, +ho, +p, s, o, ss, e} = c
2376  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)))
2377
2378def cookie.pick(cs: List<&2, Cookie>, +host: String, +path: String, +https: Bool) -> List<&2, Cookie>:
2379  match cs:
2380    case Nil{}:
2381      Nil{}
2382    case Con{+c, t}:
2383      List.filter.put(Cookie, c, cookie.pick(t, host, path, https), cookie.sends(host, path, https, c))
2384
2385# The sort order of §5.8.3: longer paths first; the stable sort keeps creation order among equals.
2386def cookie.longer(a: Cookie, b: Cookie) -> Bool:
2387  Cookie{n1, v1, d1, h1, p1, s1, o1, ss1, e1} = a
2388  Cookie{n2, v2, d2, h2, p2, s2, o2, ss2, e2} = b
2389  Bool.not(Nat.is_lt(String.length(p1), String.length(p2)))
2390
2391def cookie.pair(c: Cookie) -> String:
2392  Cookie{+n, +v, d, h, p, s, o, ss, e} = c
2393  Bool.pick(String, String.is_empty(n), v, n ++ "=" ++ v)
2394
2395def cookie.pairs(cs: List<&2, Cookie>) -> List<&2, String>:
2396  match cs:
2397    case Nil{}:
2398      Nil{}
2399    case Con{c, t}:
2400      Con{cookie.pair(c), cookie.pairs(t)}
2401
2402# §5.8.3: the cookie-string for a request to a, or "" when no cookie matches.
2403def jar.string(j: Jar, a: Url.Abs) -> String:
2404  Jar{now, cs} = j
2405  Url.Abs{scheme, +host, port, target} = a
2406  String.join(cookie.pairs(List.sort(~Cookie, ~cookie.longer, cookie.pick(cs, host, cookie.target_path(target), String.eq(scheme, "https")))), "; ")
2407
2408# One cookie field: the caller's own cookie values first, then the jar's.
2409def jar.header(+h: Map<&2, List<&2, String>>, +s: String) -> Map<&2, List<&2, String>>:
2410  +old = String.join(fields(h, "cookie"), "; ")
2411  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)))
2412
2413def jar.apply.url(j: Jar, u: Maybe<&2, Url.Abs>, +h: Map<&2, List<&2, String>>) -> Map<&2, List<&2, String>>:
2414  match u:
2415    case None{}:
2416      h
2417    case Some{a}:
2418      jar.header(h, jar.string(j, a))
2419
2420# The headers with the jar's cookies for a request to url in their cookie field (lowercase, as fetch
2421# sends names). An unparsable url adds nothing.
2422def jar.apply(j: Jar, url: String, +h: Map<&2, List<&2, String>>) -> Map<&2, List<&2, String>>:
2423  jar.apply.url(j, Url.absolute(url), h)
2424
2425# The jar, if any, that a fetch threads through its hops.
2426def jar.opt.apply(m: Maybe<&2, Jar>, a: Url.Abs, +h: Map<&2, List<&2, String>>) -> Map<&2, List<&2, String>>:
2427  match m:
2428    case None{}:
2429      h
2430    case Some{j}:
2431      jar.header(h, jar.string(j, a))
2432
2433def jar.opt.res(j: Jar, +a: Url.Abs, r: Result<&1, &1, Err, Res>) -> Maybe<&2, Jar> & Result<&1, &1, Err, Res>:
2434  match r:
2435    case Fail{e}:
2436      (Some{j}, Fail{e})
2437    case Done{res}:
2438      Res{status, +headers, body} = res
2439      (Some{jar.store.abs(j, a, headers)}, Done{Res{status, headers, body}})
2440
2441def jar.opt.store(m: Maybe<&2, Jar>, +a: Url.Abs, r: Result<&1, &1, Err, Res>) -> Maybe<&2, Jar> & Result<&1, &1, Err, Res>:
2442  match m:
2443    case None{}:
2444      (None{}, r)
2445    case Some{j}:
2446      jar.opt.res(j, a, r)
2447
2448def io.recv.words(tls: Bool, s: Socket, max: U32, ms: U32) -> IO(Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>):
2449  match tls:
2450    case True{}:
2451      Wire.tls.recv.words(s, max, ms)
2452    case False{}:
2453      Wire.recv.words(s, max, ms)
2454
2455def io.send(tls: Bool, s: Socket, data: String) -> IO(Socket & Result<&1, &1, U32 & String, Unit>):
2456  match tls:
2457    case True{}:
2458      Wire.tls.send(s, data)
2459    case False{}:
2460      Wire.send(s, data)
2461
2462def io.send.words(tls: Bool, s: Socket, +len: U32, buf: Array<U32>) -> IO(Socket & Result<&1, &1, U32 & String, Unit>):
2463  match tls:
2464    case True{}:
2465      Wire.tls.send.words(s, len, buf)
2466    case False{}:
2467      Wire.send.words(s, len, buf)
2468
2469def io.send.bytes(tls: Bool, s: Socket, b: Bytes.Bytes) -> IO(Socket & Result<&1, &1, U32 & String, Unit>):
2470  Bytes.Bytes{+len, buf} = b
2471  io.send.words(tls, s, len, buf)
2472
2473def io.close(tls: Bool, s: Socket) -> IO(Unit):
2474  match tls:
2475    case True{}:
2476      Wire.tls.close(s)
2477    case False{}:
2478      Socket.close(s)
2479
2480def fetch.close(tls: Bool, s: Socket, r: Result<&1, &1, Err, Res>) -> IO(Result<&1, &1, Err, Res>):
2481  do IO<Result<&1, &1, Err, Res>>:
2482    io.close(tls, s)
2483    return r
2484
2485# none: no response byte arrived, so an idempotent request may be retried (RFC 9112 §9.3.1).
2486# sock: the socket, when it can take another request.
2487type Out is Type:
2488  OutDone{res: Res, sock: Maybe<&1, Socket>, rest: Bytes.Bytes}
2489  OutFail{e: Err, none: Bool}
2490
2491def fetch.boxed(r: Result<&1, &1, Err, Res>, none: Bool) -> Out:
2492  match r:
2493    case Done{res}:
2494      OutDone{res, None{}, Bytes.new(0)}
2495    case Fail{e}:
2496      OutFail{e, none}
2497
2498def fetch.bad(tls: Bool, s: Socket, e: Maybe<&2, Err>) -> IO(Result<&1, &1, Err, Res>):
2499  match e:
2500    case None{}:
2501      fetch.close(tls, s, Fail{ErrBad{}})
2502    case Some{err}:
2503      fetch.close(tls, s, Fail{err})
2504
2505def fetch.shut(tls: Bool, s: Socket, r: Result<&1, &1, Err, Res>, none: Bool) -> IO(Out):
2506  do IO<Out>:
2507    x : Result<&1, &1, Err, Res> <- fetch.close(tls, s, r)
2508    return fetch.boxed(x, none)
2509
2510def fetch.hold.go(tls: Bool, s: Socket, res: Res, left: Maybe<&1, Bytes.Bytes>) -> IO(Out):
2511  match left:
2512    case Some{x}:
2513      IO.pure(Out, OutDone{res, Some{s}, x})
2514    case None{}:
2515      fetch.shut(tls, s, Done{res}, False{})
2516
2517def fetch.hold(tls: Bool, close: Bool, s: Socket, res: Res, left: Maybe<&1, Bytes.Bytes>) -> IO(Out):
2518  Res{status, +headers, body} = res
2519  fetch.hold.go(tls, s, Res{status, headers, body}, again(close, headers, left))
2520
2521def fetch.failout(tls: Bool, s: Socket, e: Maybe<&2, Err>, none: Bool) -> IO(Out):
2522  do IO<Out>:
2523    r : Result<&1, &1, Err, Res> <- fetch.bad(tls, s, e)
2524    return fetch.boxed(r, none)
2525
2526# Read state: the response so far and the bytes read, or how it ended.
2527# none: no byte arrived, so an idempotent request may be retried.
2528type Fl is Type:
2529  FlMore{rv: Rv, n: U32}
2530  FlBad{err: Maybe<&2, Err>, none: Bool}
2531  FlDone{res: Res, rest: Maybe<&1, Bytes.Bytes>}
2532
2533def fetch.rt(+n: U32, t: Rt) -> Fl:
2534  match t:
2535    case RtMore{rv}:
2536      FlMore{rv, n}
2537    case RtBad{}:
2538      FlBad{None{}, U32.is_zero(n)}
2539    case RtDone{res, rest}:
2540      FlDone{res, rest}
2541
2542# 64 KiB of head past the body cap, as serve allows.
2543def fetch.over(+n: U32) -> Bool:
2544  Nat.is_lt(Nat.add(fetch.max(), 65536n), U32.to_nat(n))
2545
2546def fetch.piece.cap(over: Bool, +head: Bool, rv: Rv, +n2: U32, +len: U32, buf: Array<U32>) -> Fl:
2547  match over:
2548    case True{}:
2549      FlBad{None{}, False{}}
2550    case False{}:
2551      fetch.rt(n2, rv.step(U32.is_zero(len), head, rv, Bytes.Bytes{len, buf}))
2552
2553def fetch.piece(+head: Bool, rv: Rv, +n: U32, p: U32 & Array<U32>) -> Fl:
2554  (+len, buf) = p
2555  +n2 = (n + len : U32)
2556  fetch.piece.cap(fetch.over(n2), head, rv, n2, len, buf)
2557
2558def fetch.next(+head: Bool, rv: Rv, +n: U32, m: Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>) -> Socket & Fl:
2559  (s, r) = m
2560  match r:
2561    case Fail{(+code, why)}:
2562      (s, FlBad{Some{err.or_late(code, ErrRead{code, why})}, U32.is_zero(n)})
2563    case Done{p}:
2564      (s, fetch.piece(head, rv, n, p))
2565
2566# Reads until the response is whole or cannot be; an empty read means the server closed.
2567@unsafe
2568def fetch.loop(+close: Bool, +head: Bool, +tls: Bool, +ms: U32, st: Socket & Fl) -> IO(Out):
2569  (s, fl) = st
2570  match fl:
2571    case FlMore{rv, +n}:
2572      do IO<Out>:
2573        m : Socket & Result<&1, &1, U32 & String, U32 & Array<U32>> <- io.recv.words(tls, s, 65536, ms)
2574        fetch.loop(close, head, tls, ms, fetch.next(head, rv, n, m))
2575    case FlBad{err, none}:
2576      fetch.failout(tls, s, err, none)
2577    case FlDone{res, rest}:
2578      fetch.hold(tls, close, s, res, rest)
2579
2580def exchange.sent(+tls: Bool, +ms: U32, +close: Bool, +head: Bool, m: Socket & Result<&1, &1, U32 & String, Unit>) -> IO(Out):
2581  (s, r) = m
2582  match r:
2583    case Fail{(+code, why)}:
2584      fetch.shut(tls, s, Fail{err.or_late(code, ErrWrite{code, why})}, True{})
2585    case Done{u}:
2586      fetch.loop(close, head, tls, ms, (s, FlMore{rv.start(), 0}))
2587
2588def exchange.go(+tls: Bool, +ms: U32, +close: Bool, +head: Bool, s: Socket, wire: Bytes.Bytes) -> IO(Out):
2589  do IO<Out>:
2590    sent : Socket & Result<&1, &1, U32 & String, Unit> <- io.send.bytes(tls, s, wire)
2591    exchange.sent(tls, ms, close, head, sent)
2592
2593def exchange.tup(o: Out) -> Maybe<&1, Socket> & Result<&1, &1, Err, Res> & Bytes.Bytes:
2594  match o:
2595    case OutFail{e, none}:
2596      (None{}, Fail{e}, Bytes.new(0))
2597    case OutDone{res, sock, rest}:
2598      (sock, Done{res}, rest)
2599
2600# One request on an open socket. Some{socket}: it can take another request.
2601def 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):
2602  do IO<Maybe<&1, Socket> & Result<&1, &1, Err, Res> & Bytes.Bytes>:
2603    o : Out <- exchange.go(tls, ms, close, head, s, wire)
2604    return exchange.tup(o)
2605
2606# Paths to a PEM client chain and its private key for mutual TLS.
2607type Cert is Data:
2608  Cert{chain: String, key: String}
2609
2610type Proxy is Data:
2611  ProxyDirect{}
2612  ProxyVia{host: String, port: U32, authorization: String}
2613
2614type Route is Data:
2615  RouteDirect{tls: Bool, host: String, port: U32, cert: Maybe<&2, Cert>}
2616  RouteProxy{tls: Bool, host: String, port: U32, sni: String,
2617    authority: String, authorization: String, cert: Maybe<&2, Cert>}
2618
2619# Connection pool: idle sockets by origin and client identity, newest first, at most cap per key.
2620# fetch uses a fresh pool per call.
2621
2622type Conn is Type:
2623  Conn{tls: Bool, s: Socket}
2624  ConnH2{s: Socket, client: H2.Client}
2625
2626type Send is Type:
2627  Send{method: String, target: String, authority: String,
2628    headers: Map<&2, List<&2, String>>, body: Bytes.Bytes}
2629
2630type H2Step is Type:
2631  H2Reply{s: Socket, reply: H2.Reply}
2632  H2Sent{client: H2.Client, events: List<&1, H2.ClientEvent>,
2633    sent: Result<&1, &1, Err, Socket>}
2634  H2Events{s: Socket, client: H2.Client, result: Result<&1, &1, Err, Maybe<&1, Res>>}
2635  H2Received{client: H2.Client,
2636    answer: Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>}
2637
2638type TunnelStep is Type:
2639  TunnelRead{s: Socket, raw: String}
2640  TunnelHead{s: Socket, raw: String, frame: Frame}
2641  TunnelGot{raw: String,
2642    answer: Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>}
2643
2644type Pool is Type:
2645  Pool{cap: U32, idle: Map<&1, List<&1, Conn>>}
2646
2647def pool.new.with(+cap: U32) -> Pool:
2648  Pool{cap, Map.new(&1, List<&1, Conn>)}
2649
2650# Up to 8 idle sockets per origin.
2651def pool.new() -> Pool:
2652  pool.new.with(8)
2653
2654def pool.key(+scheme: String, +host: String, +port: U32) -> String:
2655  scheme ++ "://" ++ host ++ ":" ++ U32.show(port)
2656
2657def pool.key.cert(+base: String, cert: Maybe<&2, Cert>) -> String:
2658  match cert:
2659    case None{}:
2660      base
2661    case Some{Cert{+chain, +key}}:
2662      base ++ "|cert:" ++ Nat.show(String.length(chain)) ++ ":" ++ chain
2663        ++ Nat.show(String.length(key)) ++ ":" ++ key
2664
2665def pool.take.of(+cap: U32, +key: String, r: Map<&1, List<&1, Conn>> & Maybe<&1, List<&1, Conn>>) -> Pool & Maybe<&1, Conn>:
2666  (m, got) = r
2667  match got:
2668    case None{}:
2669      (Pool{cap, m}, None{})
2670    case Some{xs}:
2671      match xs:
2672        case Nil{}:
2673          (Pool{cap, m}, None{})
2674        case Con{c, t}:
2675          (Pool{cap, Map.set(&1, List<&1, Conn>, m, key, t)}, Some{c})
2676
2677# The socket given back last.
2678def pool.take(p: Pool, +key: String) -> Pool & Maybe<&1, Conn>:
2679  Pool{+cap, idle} = p
2680  pool.take.of(cap, key, Map.pop(&1, List<&1, Conn>, idle, key))
2681
2682def conn.close(c: Conn) -> IO(Unit):
2683  match c:
2684    case Conn{tls, s}:
2685      io.close(tls, s)
2686    case ConnH2{s, client}:
2687      Wire.tls.close(s)
2688
2689# The first n sockets; the rest are closed.
2690def conns.cut(xs: List<&1, Conn>, n: Nat) -> IO(List<&1, Conn>):
2691  match xs:
2692    case Nil{}:
2693      IO.pure(List<&1, Conn>, Nil{})
2694    case Con{c, t}:
2695      match n:
2696        case 0n:
2697          do IO<List<&1, Conn>>:
2698            conn.close(c)
2699            conns.cut(t, 0n)
2700        case 1n+k:
2701          do IO<List<&1, Conn>>:
2702            r : List<&1, Conn> <- conns.cut(t, k)
2703            return c <> r
2704
2705def pool.give.of(+cap: U32, +key: String, c: Conn, limit: Nat,
2706    r: Map<&1, List<&1, Conn>> & Maybe<&1, List<&1, Conn>>) -> IO(Pool):
2707  (m, old) = r
2708  do IO<Pool>:
2709    xs : List<&1, Conn> <- conns.cut(c <> Maybe.default(&1, List<&1, Conn>, old, Nil{}), limit)
2710    return Pool{cap, Map.set(&1, List<&1, Conn>, m, key, xs)}
2711
2712# Past the limit (cap for HTTP/1.1, one session for HTTP/2), close the oldest idle connection.
2713def pool.give(p: Pool, +key: String, c: Conn) -> IO(Pool):
2714  Pool{+cap, idle} = p
2715  match c:
2716    case Conn{tls, s}:
2717      pool.give.of(cap, key, Conn{tls, s}, U32.to_nat(cap), Map.pop(&1, List<&1, Conn>, idle, key))
2718    case ConnH2{s, client}:
2719      pool.give.of(cap, key, ConnH2{s, client}, Bool.pick(Nat, U32.is_zero(cap), 0n, 1n),
2720        Map.pop(&1, List<&1, Conn>, idle, key))
2721
2722def pool.close.go(xs: List<&1, List<&1, Conn>>) -> IO(Unit):
2723  match xs:
2724    case Nil{}:
2725      IO.pure(Unit, Unit{})
2726    case Con{cs, t}:
2727      do IO<Unit>:
2728        none : List<&1, Conn> <- conns.cut(cs, 0n)
2729        pool.close.go(t)
2730
2731def pool.close(p: Pool) -> IO(Unit):
2732  Pool{cap, idle} = p
2733  pool.close.go(Map.values(&1, List<&1, Conn>, idle))
2734
2735# RFC 9110 §9.2.2
2736def pool.idempotent(+method: String) -> Bool:
2737  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"))))))
2738
2739def conn.tls(m: Socket & Result<&1, &1, U32 & String, Unit>) -> IO(Result<&1, &1, Err, Conn>):
2740  (s, r) = m
2741  match r:
2742    case Fail{(+code, why)}:
2743      do IO<Result<&1, &1, Err, Conn>>:
2744        Wire.tls.close(s)
2745        return Fail{err.or_late(code, ErrTls{code, why})}
2746    case Done{u}:
2747      IO.pure(Result<&1, &1, Err, Conn>, Done{Conn{True{}, s}})
2748
2749def conn.h2.sent(client: H2.Client, r: Socket & Result<&1, &1, U32 & String, Unit>) -> IO(Result<&1, &1, Err, Conn>):
2750  (s, sent) = r
2751  match sent:
2752    case Fail{(+code, why)}:
2753      do IO<Result<&1, &1, Err, Conn>>:
2754        Wire.tls.close(s)
2755        return Fail{err.or_late(code, ErrWrite{code, why})}
2756    case Done{u}:
2757      IO.pure(Result<&1, &1, Err, Conn>, Done{ConnH2{s, client}})
2758
2759def conn.h2.start(s: Socket, r: H2.Client & HBytes.Bytes) -> IO(Result<&1, &1, Err, Conn>):
2760  (client, HBytes.Bytes{len, buf}) = r
2761  do IO<Result<&1, &1, Err, Conn>>:
2762    sent : Socket & Result<&1, &1, U32 & String, Unit> <- Wire.tls.send.words(s, len, buf)
2763    conn.h2.sent(client, sent)
2764
2765def conn.tls.protocol(proto: String, s: Socket) -> IO(Result<&1, &1, Err, Conn>):
2766  match proto:
2767    case "h2":
2768      conn.h2.start(s, H2.client.start())
2769    case "http/1.1":
2770      IO.pure(Result<&1, &1, Err, Conn>, Done{Conn{True{}, s}})
2771    case "":
2772      IO.pure(Result<&1, &1, Err, Conn>, Done{Conn{True{}, s}})
2773    case other:
2774      do IO<Result<&1, &1, Err, Conn>>:
2775        Wire.tls.close(s)
2776        return Fail{ErrTls{71, "unsupported ALPN: " ++ other}}
2777
2778def conn.tls.alpn(m: Socket & Result<&1, &1, U32 & String, String>) -> IO(Result<&1, &1, Err, Conn>):
2779  (s, r) = m
2780  match r:
2781    case Fail{(+code, why)}:
2782      do IO<Result<&1, &1, Err, Conn>>:
2783        Wire.tls.close(s)
2784        return Fail{err.or_late(code, ErrTls{code, why})}
2785    case Done{proto}:
2786      conn.tls.protocol(proto, s)
2787
2788def conn.secure.no.cert(offer: Bool, s: Socket, host: String, +ms: U32) ->
2789    IO(Result<&1, &1, Err, Conn>):
2790  match offer:
2791    case True{}:
2792      do IO<Result<&1, &1, Err, Conn>>:
2793        hs : Socket & Result<&1, &1, U32 & String, String> <-
2794          Wire.tls.connect.alpn(s, host, ms, "h2,http/1.1")
2795        conn.tls.alpn(hs)
2796    case False{}:
2797      do IO<Result<&1, &1, Err, Conn>>:
2798        hs : Socket & Result<&1, &1, U32 & String, Unit> <- Wire.tls.connect(s, host, ms)
2799        conn.tls(hs)
2800
2801def conn.secure.tls(cert: Maybe<&2, Cert>, s: Socket, host: String, +ms: U32,
2802    offer: Bool) -> IO(Result<&1, &1, Err, Conn>):
2803  match cert:
2804    case None{}:
2805      conn.secure.no.cert(offer, s, host, ms)
2806    case Some{Cert{chain, key}}:
2807      do IO<Result<&1, &1, Err, Conn>>:
2808        hs : Socket & Result<&1, &1, U32 & String, Unit> <-
2809          Wire.tls.connect.cert(s, host, ms, chain, key)
2810        conn.tls(hs)
2811
2812# A failed handshake is an error, never plaintext.
2813def conn.secure(+ms: U32, sni: String, s: Socket, tls: Bool,
2814    cert: Maybe<&2, Cert>, offer: Bool) -> IO(Result<&1, &1, Err, Conn>):
2815  match tls:
2816    case False{}:
2817      IO.pure(Result<&1, &1, Err, Conn>, Done{Conn{False{}, s}})
2818    case True{}:
2819      conn.secure.tls(cert, s, sni, ms, offer)
2820
2821def conn.made(+ms: U32, sni: String, tls: Bool, cert: Maybe<&2, Cert>,
2822    offer: Bool, r: Result<&1, &1, U32 & String, Socket>) ->
2823    IO(Result<&1, &1, Err, Conn>):
2824  match r:
2825    case Fail{(+code, why)}:
2826      IO.pure(Result<&1, &1, Err, Conn>, Fail{err.or_late(code, ErrConnect{code, why})})
2827    case Done{s}:
2828      conn.secure(ms, sni, s, tls, cert, offer)
2829
2830def conn.open(+tls: Bool, +ms: U32, sni: String, ip: String, port: U32) ->
2831    IO(Result<&1, &1, Err, Conn>):
2832  do IO<Result<&1, &1, Err, Conn>>:
2833    c : Result<&1, &1, U32 & String, Socket> <- Wire.connect(ip, port, ms)
2834    conn.made(ms, sni, tls, None{}, False{}, c)
2835
2836# ponytail: addresses are tried in order, not raced; a broken first route can consume the step timeout.
2837type Dial is Type:
2838  Dial{port: U32, ms: U32, deadline: Nat, action: IO(Result<&1, &1, U32 & String, Socket>)}
2839
2840def conn.dial.time(+ip: String, +port: U32, +deadline: Nat, now: Nat, expired: Bool) ->
2841  IO(Result<&1, &1, U32 & String, Socket>):
2842  match expired:
2843    case True{}:
2844      IO.pure(Result<&1, &1, U32 & String, Socket>, Fail{(60, "connect timeout")})
2845    case False{}:
2846      Wire.connect(ip, port, U32.from_nat(Nat.sub(deadline, now)))
2847
2848def conn.dial.with(+ip: String, +port: U32, +ms: U32, +deadline: Nat, +now: Nat, unlimited: Bool) ->
2849  IO(Result<&1, &1, U32 & String, Socket>):
2850  match unlimited:
2851    case True{}:
2852      Wire.connect(ip, port, 0)
2853    case False{}:
2854      conn.dial.time(ip, port, deadline, now, Nat.is_le(deadline, now))
2855
2856def conn.dial.try(+ip: String, +port: U32, +ms: U32, +deadline: Nat) ->
2857  IO(Result<&1, &1, U32 & String, Socket>):
2858  do IO<Result<&1, &1, U32 & String, Socket>>:
2859    now : Nat <- IO.now()
2860    conn.dial.with(ip, port, ms, deadline, now, U32.is_zero(ms))
2861
2862def conn.dial.after(r: Result<&1, &1, U32 & String, Socket>, ip: String, +port: U32, +ms: U32, +deadline: Nat) ->
2863  IO(Result<&1, &1, U32 & String, Socket>):
2864  match r:
2865    case Done{s}:
2866      IO.pure(Result<&1, &1, U32 & String, Socket>, Done{s})
2867    case Fail{e}:
2868      conn.dial.try(ip, port, ms, deadline)
2869
2870def conn.dial.more(prev: IO(Result<&1, &1, U32 & String, Socket>), ip: String, +port: U32, +ms: U32, +deadline: Nat) ->
2871  IO(Result<&1, &1, U32 & String, Socket>):
2872  do IO<Result<&1, &1, U32 & String, Socket>>:
2873    r : Result<&1, &1, U32 & String, Socket> <- prev
2874    conn.dial.after(r, ip, port, ms, deadline)
2875
2876def conn.dial.fold(d: Dial, ip: String) -> Dial:
2877  Dial{+port, +ms, +deadline, action} = d
2878  Dial{port, ms, deadline, conn.dial.more(action, ip, port, ms, deadline)}
2879
2880def conn.dial.run(d: Dial) -> IO(Result<&1, &1, U32 & String, Socket>):
2881  Dial{port, ms, deadline, action} = d
2882  action
2883
2884def conn.dial.all(+port: U32, +ms: U32, +start: Nat, first: String, rest: List<&2, String>) ->
2885  IO(Result<&1, &1, U32 & String, Socket>):
2886  match rest:
2887    case Nil{}:
2888      Wire.connect(first, port, ms)
2889    case Con{ip, tail}:
2890      +deadline = Nat.add(start, U32.to_nat(ms))
2891      conn.dial.run(List.foldl(~&2, ~String, ~Dial, ~conn.dial.fold, Con{ip, tail},
2892        Dial{port, ms, deadline, Wire.connect(first, port, ms)}))
2893
2894def conn.open.all(+tls: Bool, +ms: U32, +host: String, +port: U32,
2895    ips: List<&2, String>, cert: Maybe<&2, Cert>, offer: Bool) ->
2896    IO(Result<&1, &1, Err, Conn>):
2897  match ips:
2898    case Nil{}:
2899      IO.pure(Result<&1, &1, Err, Conn>, Fail{ErrDns{}})
2900    case Con{addr, rest}:
2901      do IO<Result<&1, &1, Err, Conn>>:
2902        start : Nat <- IO.now()
2903        r : Result<&1, &1, U32 & String, Socket> <- conn.dial.all(port, ms, start, addr, rest)
2904        conn.made(ms, host, tls, cert, offer, r)
2905
2906def proxy.auth.safe(s: String) -> Bool:
2907  match s:
2908    case SNil{}:
2909      True{}
2910    case SCon{Chr{+c}, rest}:
2911      Bool.and(U32.is_ge(c, 32), Bool.and(U32.is_ne(c, 127), proxy.auth.safe(rest)))
2912
2913def proxy.auth.checked(+decoded: String, valid: Bool) -> Maybe<&2, String>:
2914  match valid:
2915    case False{}:
2916      None{}
2917    case True{}:
2918      Some{"Basic " ++ Bytes.to_base64(Bytes.from_string(decoded))}
2919
2920def proxy.auth.value(m: Maybe<&2, String>) -> Maybe<&2, String>:
2921  match m:
2922    case None{}:
2923      None{}
2924    case Some{+decoded}:
2925      proxy.auth.checked(decoded, Bool.and(Url.has(decoded, 58), proxy.auth.safe(decoded)))
2926
2927def proxy.from.abs(authorization: String, m: Maybe<&2, Url.Abs>) -> Maybe<&2, Proxy>:
2928  match m:
2929    case None{}:
2930      None{}
2931    case Some{Url.Abs{scheme, host, port, target}}:
2932      Some{ProxyVia{host, port, authorization}}
2933
2934def proxy.from.user(user: String, host: String) -> Maybe<&2, Proxy>:
2935  do Maybe<&2, Proxy>:
2936    authorization : String <- proxy.auth.value(Url.pct.decode(user))
2937    proxy.from.abs(authorization, Url.absolute("http://" ++ host))
2938
2939def proxy.from.authority(has_user: Bool, authority: String, split: String & String) ->
2940    Maybe<&2, Proxy>:
2941  match has_user:
2942    case False{}:
2943      proxy.from.abs("", Url.absolute("http://" ++ authority))
2944    case True{}:
2945      (user, host) = split
2946      proxy.from.user(user, host)
2947
2948def proxy.from.parts(parts: String & String) -> Maybe<&2, Proxy>:
2949  (+authority, path) = parts
2950  match path:
2951    case SNil{}:
2952      proxy.from.authority(Url.has(authority, 64), authority, Url.take_to(authority, 64))
2953    case other:
2954      None{}
2955
2956def proxy.from.url.if(valid: Bool, raw: String) -> Maybe<&2, Proxy>:
2957  match valid:
2958    case False{}:
2959      None{}
2960    case True{}:
2961      proxy.from.parts(Url.take_to(String.drop(raw, 7n), 47))
2962
2963def proxy.from.url(+raw: String) -> Maybe<&2, Proxy>:
2964  proxy.from.url.if(String.starts_with(String.to_lower(raw), "http://"), raw)
2965
2966def proxy.no.domain(+host: String, +suffix: String) -> Bool:
2967  Bool.or(String.eq(host, suffix), String.ends_with(host, "." ++ suffix))
2968
2969def proxy.no.suffix(+host: String, +raw: String) -> Bool:
2970  match raw:
2971    case SCon{Chr{46}, +suffix}:
2972      proxy.no.domain(host, suffix)
2973    case other:
2974      proxy.no.domain(host, raw)
2975
2976def proxy.no.port(valid: Bool, +host: String, suffix: String) -> Bool:
2977  match valid:
2978    case False{}:
2979      False{}
2980    case True{}:
2981      proxy.no.suffix(host, suffix)
2982
2983def proxy.no.named(+host: String, +port: U32, parts: String & String) -> Bool:
2984  (suffix, port_text) = parts
2985  match port_text:
2986    case SNil{}:
2987      proxy.no.suffix(host, suffix)
2988    case other:
2989      proxy.no.port(String.eq(port_text, U32.show(port)), host, suffix)
2990
2991def proxy.no.literal(+host: String, +port: U32, +name: String) -> Bool:
2992  Bool.or(String.eq(name, host), Bool.or(String.eq(name, "[" ++ host ++ "]"),
2993    Bool.or(String.eq(name, host ++ ":" ++ U32.show(port)),
2994      String.eq(name, "[" ++ host ++ "]:" ++ U32.show(port)))))
2995
2996def proxy.no.token(+host: String, +port: U32, token: String) -> Bool:
2997  +name = String.to_lower(trim(token))
2998  Bool.or(String.eq(name, "*"),
2999    Bool.or(proxy.no.literal(host, port, name),
3000      Bool.and(Bool.not(Url.has(host, 58)),
3001        proxy.no.named(host, port, Url.take_to(name, 58)))))
3002
3003def proxy.no.list(xs: List<&2, String>, +host: String, +port: U32) -> Bool:
3004  match xs:
3005    case Nil{}:
3006      False{}
3007    case Con{token, rest}:
3008      Bool.or(proxy.no.token(host, port, token), proxy.no.list(rest, host, port))
3009
3010def proxy.no_match(+host: String, +port: U32, no_proxy: String) -> Bool:
3011  proxy.no.list(String.split(no_proxy, ','), String.to_lower(host), port)
3012
3013def proxy.env.value(r: Result<&1, &1, U32 & String, String>) -> String:
3014  match r:
3015    case Fail{e}:
3016      ""
3017    case Done{value}:
3018      value
3019
3020def proxy.env.lower(r: Result<&1, &1, U32 & String, String>, upper: String) ->
3021    IO(String):
3022  match r:
3023    case Done{value}:
3024      IO.pure(String, value)
3025    case Fail{e}:
3026      do IO<String>:
3027        got : Result<&1, &1, U32 & String, String> <- IO.get_env(upper)
3028        return proxy.env.value(got)
3029
3030def proxy.env(lower: String, upper: String) -> IO(String):
3031  do IO<String>:
3032    got : Result<&1, &1, U32 & String, String> <- IO.get_env(lower)
3033    proxy.env.lower(got, upper)
3034
3035def proxy.from.env(value: String) -> Maybe<&2, Proxy>:
3036  match value:
3037    case SNil{}:
3038      Some{ProxyDirect{}}
3039    case other:
3040      proxy.from.url(value)
3041
3042def proxy.choose(bypass: Bool, value: String) -> Maybe<&2, Proxy>:
3043  match bypass:
3044    case True{}:
3045      Some{ProxyDirect{}}
3046    case False{}:
3047      proxy.from.env(value)
3048
3049def proxy.select(+scheme: String, +host: String, +port: U32) ->
3050    IO(Maybe<&2, Proxy>):
3051  +secure = String.eq(scheme, "https")
3052  do IO<Maybe<&2, Proxy>>:
3053    bypass : String <- proxy.env("no_proxy", "NO_PROXY")
3054    value : String <- proxy.env(Bool.pick(String, secure, "https_proxy", "http_proxy"),
3055      Bool.pick(String, secure, "HTTPS_PROXY", "HTTP_PROXY"))
3056    return proxy.choose(proxy.no_match(host, port, bypass), value)
3057
3058def h2.header.skip(+name: String) -> Bool:
3059  match name:
3060    case SCon{Chr{58}, rest}:
3061      True{}
3062    case other:
3063      Bool.or(req.reserved(name),
3064        Bool.or(String.eq(name, "keep-alive"),
3065          Bool.or(String.eq(name, "proxy-connection"),
3066            Bool.or(String.eq(name, "upgrade"), String.eq(name, "te")))))
3067
3068def h2.header.mode(+name: String) -> U32:
3069  Bool.pick(U32,
3070    Bool.or(String.eq(name, "authorization"),
3071      Bool.or(String.eq(name, "cookie"), String.eq(name, "proxy-authorization"))),
3072    2, 0)
3073
3074def h2.header.values(+name: String, +mode: U32, vs: List<&2, String>) -> List<&2, Hpack.Field>:
3075  match vs:
3076    case Nil{}:
3077      Nil{}
3078    case Con{v, tail}:
3079      Hpack.Field{name, sanitize(v), mode} <> h2.header.values(name, mode, tail)
3080
3081def h2.header.tokens(vs: List<&2, String>) -> List<&2, String>:
3082  match vs:
3083    case Nil{}:
3084      Nil{}
3085    case Con{value, rest}:
3086      List.append(&2, String, String.split(value, ','), h2.header.tokens(rest))
3087
3088def h2.header.nominated.one(enabled: Bool, vs: List<&2, String>,
3089    rest: List<&2, String>) -> List<&2, String>:
3090  match enabled:
3091    case True{}:
3092      List.append(&2, String, h2.header.tokens(vs), rest)
3093    case False{}:
3094      rest
3095
3096def h2.header.nominated(xs: List<&2, Sigma<&2, &2, String, _ => List<&2, String>>>) ->
3097    List<&2, String>:
3098  match xs:
3099    case Nil{}:
3100      Nil{}
3101    case (name, values) <> tail:
3102      h2.header.nominated.one(String.eq(String.to_lower(name), "connection"),
3103        values, h2.header.nominated(tail))
3104
3105def h2.header.has(xs: List<&2, String>, +key: String) -> Bool:
3106  match xs:
3107    case Nil{}:
3108      False{}
3109    case Con{value, rest}:
3110      Bool.or(String.eq(String.to_lower(trim(value)), key), h2.header.has(rest, key))
3111
3112def h2.header.item(skip: Bool, +name: String, vs: List<&2, String>,
3113    tail: List<&2, Hpack.Field>) -> List<&2, Hpack.Field>:
3114  match skip:
3115    case True{}:
3116      tail
3117    case False{}:
3118      List.append(&2, Hpack.Field, h2.header.values(name, h2.header.mode(name), vs), tail)
3119
3120def h2.header.items(xs: List<&2, Sigma<&2, &2, String, _ => List<&2, String>>>,
3121    +nominated: List<&2, String>) -> List<&2, Hpack.Field>:
3122  match xs:
3123    case Nil{}:
3124      Nil{}
3125    case (name, values) <> tail:
3126      +key = String.to_lower(name)
3127      h2.header.item(Bool.or(h2.header.skip(key), h2.header.has(nominated, key)),
3128        key, values, h2.header.items(tail, nominated))
3129
3130def h2.request.fields(+method: String, target: String, authority: String,
3131    headers: Map<&2, List<&2, String>>) -> List<&2, Hpack.Field>:
3132  +xs = Map.to_list(&2, List<&2, String>, headers)
3133  List.append(&2, Hpack.Field,
3134    [Hpack.Field{":method", method, 0}, Hpack.Field{":scheme", "https", 0},
3135      Hpack.Field{":authority", authority, 0}, Hpack.Field{":path", target, 0}],
3136    h2.header.items(xs, h2.header.nominated(xs)))
3137
3138def h2.response.status.value(+value: String, valid: Bool) -> Maybe<&2, U32>:
3139  match valid:
3140    case False{}:
3141      None{}
3142    case True{}:
3143      parse_u32(value)
3144
3145def h2.response.status(xs: List<&2, Hpack.Field>) -> Maybe<&2, U32>:
3146  match xs:
3147    case Nil{}:
3148      None{}
3149    case Con{Hpack.Field{name, +value, mode}, tail}:
3150      match name:
3151        case ":status":
3152          h2.response.status.value(value, Nat.is_eq(String.length(value), 3n))
3153        case other:
3154          h2.response.status(tail)
3155
3156def h2.response.headers(xs: List<&2, Hpack.Field>, acc: Map<&2, List<&2, String>>) ->
3157    Map<&2, List<&2, String>>:
3158  match xs:
3159    case Nil{}:
3160      acc
3161    case Con{Hpack.Field{name, value, mode}, tail}:
3162      match name:
3163        case SCon{Chr{58}, rest}:
3164          h2.response.headers(tail, acc)
3165        case other:
3166          h2.response.headers(tail, add(acc, String.to_lower(name), value))
3167
3168def h2.response.final(interim: Bool, +status: U32, headers: List<&2, Hpack.Field>,
3169    body: HBytes.Bytes) -> Result<&1, &1, Err, Maybe<&1, Res>>:
3170  match interim:
3171    case True{}:
3172      Done{None{}}
3173    case False{}:
3174      HBytes.Bytes{len, buf} = body
3175      Done{Some{Res{status, h2.response.headers(headers, empty()), Bytes.Bytes{len, buf}}}}
3176
3177def h2.response.valid(valid: Bool, +status: U32, headers: List<&2, Hpack.Field>,
3178    body: HBytes.Bytes) -> Result<&1, &1, Err, Maybe<&1, Res>>:
3179  match valid:
3180    case False{}:
3181      Fail{ErrBad{}}
3182    case True{}:
3183      h2.response.final(U32.is_lt(status, 200), status, headers, body)
3184
3185def h2.response.parsed(m: Maybe<&2, U32>, headers: List<&2, Hpack.Field>,
3186    body: HBytes.Bytes) -> Result<&1, &1, Err, Maybe<&1, Res>>:
3187  match m:
3188    case None{}:
3189      Fail{ErrBad{}}
3190    case Some{+status}:
3191      h2.response.valid(Bool.and(U32.is_ge(status, 100), U32.is_lt(status, 600)),
3192        status, headers, body)
3193
3194def h2.response(+fields: List<&2, Hpack.Field>, body: HBytes.Bytes) ->
3195    Result<&1, &1, Err, Maybe<&1, Res>>:
3196  h2.response.parsed(h2.response.status(fields), fields, body)
3197
3198def h2.event.fold(acc: Result<&1, &1, Err, Maybe<&1, Res>>,
3199    event: H2.ClientEvent) -> Result<&1, &1, Err, Maybe<&1, Res>>:
3200  match acc:
3201    case Fail{e}:
3202      Fail{e}
3203    case Done{Some{res}}:
3204      Done{Some{res}}
3205    case Done{None{}}:
3206      match event:
3207        case H2.Response{id, headers, body}:
3208          h2.response(headers, body)
3209        case H2.Reset{id, code}:
3210          Fail{ErrBad{}}
3211        case H2.Shutdown{last, code}:
3212          Done{None{}}
3213        case H2.Pong{data}:
3214          Done{None{}}
3215
3216def h2.send.report(r: Socket & Result<&1, &1, U32 & String, Unit>) ->
3217    IO(Result<&1, &1, Err, Socket>):
3218  (s, sent) = r
3219  match sent:
3220    case Fail{(+code, why)}:
3221      do IO<Result<&1, &1, Err, Socket>>:
3222        Wire.tls.close(s)
3223        return Fail{err.or_late(code, ErrWrite{code, why})}
3224    case Done{unit}:
3225      IO.pure(Result<&1, &1, Err, Socket>, Done{s})
3226
3227def h2.send.one(prev: Result<&1, &1, Err, Socket>, b: HBytes.Bytes) ->
3228    IO(Result<&1, &1, Err, Socket>):
3229  match prev:
3230    case Fail{e}:
3231      IO.pure(Result<&1, &1, Err, Socket>, Fail{e})
3232    case Done{s}:
3233      HBytes.Bytes{len, buf} = b
3234      do IO<Result<&1, &1, Err, Socket>>:
3235        sent : Socket & Result<&1, &1, U32 & String, Unit> <- Wire.tls.send.words(s, len, buf)
3236        h2.send.report(sent)
3237
3238def h2.send.fold(prev: IO(Result<&1, &1, Err, Socket>), b: HBytes.Bytes) ->
3239    IO(Result<&1, &1, Err, Socket>):
3240  do IO<Result<&1, &1, Err, Socket>>:
3241    r : Result<&1, &1, Err, Socket> <- prev
3242    h2.send.one(r, b)
3243
3244def h2.send(xs: List<&1, HBytes.Bytes>, s: Socket) -> IO(Result<&1, &1, Err, Socket>):
3245  List.foldl(~&1, ~HBytes.Bytes, ~IO(Result<&1, &1, Err, Socket>), ~h2.send.fold,
3246    xs, IO.pure(Result<&1, &1, Err, Socket>, Done{s}))
3247
3248def h2.received.step(over: Bool, s: Socket, client: H2.Client,
3249    +len: U32, buf: Array<U32>) -> H2Step:
3250  match over:
3251    case True{}:
3252      H2Reply{s, H2.Failed{H2.Error{1, True{}, 0}}}
3253    case False{}:
3254      H2Reply{s, H2.client.receive(client, HBytes.Bytes{len, buf})}
3255
3256def h2.fail(s: Socket, e: Err) -> IO(Result<&1, &1, Err, Conn & Res>):
3257  do IO<Result<&1, &1, Err, Conn & Res>>:
3258    Wire.tls.close(s)
3259    return Fail{e}
3260
3261def h2.loop(n: Nat, step: H2Step, +ms: U32, +used: U32) ->
3262    IO(Result<&1, &1, Err, Conn & Res>):
3263  match n:
3264    case 0n:
3265      match step:
3266        case H2Reply{s, reply}:
3267          h2.fail(s, ErrBad{})
3268        case H2Sent{client, events, sent}:
3269          match sent:
3270            case Fail{e}:
3271              IO.pure(Result<&1, &1, Err, Conn & Res>, Fail{e})
3272            case Done{s}:
3273              h2.fail(s, ErrBad{})
3274        case H2Events{s, client, result}:
3275          h2.fail(s, ErrBad{})
3276        case H2Received{client, answer}:
3277          (s, r) = answer
3278          h2.fail(s, ErrBad{})
3279    case 1n+p:
3280      match step:
3281        case H2Reply{s, reply}:
3282          match reply:
3283            case H2.Failed{error}:
3284              h2.fail(s, ErrBad{})
3285            case H2.Ready{client, writes, events}:
3286              do IO<Result<&1, &1, Err, Conn & Res>>:
3287                sent : Result<&1, &1, Err, Socket> <- h2.send(writes, s)
3288                h2.loop(p, H2Sent{client, events, sent}, ms, used)
3289        case H2Sent{client, events, sent}:
3290          match sent:
3291            case Fail{e}:
3292              IO.pure(Result<&1, &1, Err, Conn & Res>, Fail{e})
3293            case Done{s}:
3294              h2.loop(p, H2Events{s, client,
3295                List.foldl(~&1, ~H2.ClientEvent,
3296                  ~Result<&1, &1, Err, Maybe<&1, Res>>, ~h2.event.fold,
3297                  events, Done{None{}})}, ms, used)
3298        case H2Events{s, client, result}:
3299          match result:
3300            case Fail{e}:
3301              h2.fail(s, e)
3302            case Done{Some{res}}:
3303              IO.pure(Result<&1, &1, Err, Conn & Res>,
3304                Done{(ConnH2{s, client}, res)})
3305            case Done{None{}}:
3306              do IO<Result<&1, &1, Err, Conn & Res>>:
3307                r : Socket & Result<&1, &1, U32 & String, U32 & Array<U32>> <-
3308                  Wire.tls.recv.words(s, 16384, ms)
3309                h2.loop(p, H2Received{client, r}, ms, used)
3310        case H2Received{client, answer}:
3311          match answer:
3312            case (s, Fail{(+code, why)}):
3313              h2.fail(s, err.or_late(code, ErrRead{code, why}))
3314            case (s, Done{(0, buf)}):
3315              h2.fail(s, ErrBad{})
3316            case (s, Done{(+len, buf)}):
3317              +total = (used + len : U32)
3318              h2.loop(p, h2.received.step(fetch.over(total), s, client, len, buf), ms, total)
3319
3320def h2.exchange(s: Socket, client: H2.Client, +ms: U32, request: Send) ->
3321    IO(Result<&1, &1, Err, Conn & Res>):
3322  Send{method, target, authority, headers, Bytes.Bytes{len, buf}} = request
3323  h2.loop(Nat.mul(4n, Nat.add(fetch.max(), 65536n)),
3324    H2Reply{s, H2.client.request(client,
3325      h2.request.fields(method, target, authority, headers), HBytes.Bytes{len, buf})},
3326    ms, 0)
3327
3328def proxy.connect.fail(s: Socket, e: Err) -> IO(Result<&1, &1, Err, Conn>):
3329  do IO<Result<&1, &1, Err, Conn>>:
3330    io.close(False{}, s)
3331    return Fail{e}
3332
3333def proxy.connect.extra(m: Maybe<&2, String>, s: Socket, +ms: U32,
3334    sni: String, cert: Maybe<&2, Cert>) -> IO(Result<&1, &1, Err, Conn>):
3335  match m:
3336    case None{}:
3337      proxy.connect.fail(s, ErrBad{})
3338    case Some{rest}:
3339      match rest:
3340        case SNil{}:
3341          conn.secure(ms, sni, s, True{}, cert, True{})
3342        case other:
3343          proxy.connect.fail(s, ErrBad{})
3344
3345def proxy.connect.status(ok: Bool, +status: U32, raw: String, s: Socket,
3346    +ms: U32, sni: String, cert: Maybe<&2, Cert>) ->
3347    IO(Result<&1, &1, Err, Conn>):
3348  match ok:
3349    case False{}:
3350      proxy.connect.fail(s, ErrConnect{status, "proxy CONNECT refused"})
3351    case True{}:
3352      proxy.connect.extra(after(raw, True{}), s, ms, sni, cert)
3353
3354def proxy.connect.finish(res: Res, raw: String, s: Socket, +ms: U32,
3355    sni: String, cert: Maybe<&2, Cert>) -> IO(Result<&1, &1, Err, Conn>):
3356  Res{+status, headers, body} = res
3357  proxy.connect.status(Bool.and(U32.is_ge(status, 200), U32.is_lt(status, 300)),
3358    status, raw, s, ms, sni, cert)
3359
3360def proxy.connect.frame(raw: String, over: Bool) -> Frame:
3361  match over:
3362    case True{}:
3363      FrameBad{}
3364    case False{}:
3365      frame(raw, False{}, True{})
3366
3367def proxy.connect.chunk(empty: Bool, s: Socket, raw: String,
3368    +len: U32, buf: Array<U32>) -> TunnelStep:
3369  match empty:
3370    case True{}:
3371      TunnelHead{s, raw, FrameBad{}}
3372    case False{}:
3373      TunnelRead{s, raw ++ Bytes.to_string(Bytes.Bytes{len, buf})}
3374
3375def proxy.connect.loop(n: Nat, step: TunnelStep, +ms: U32, +sni: String,
3376    +cert: Maybe<&2, Cert>) -> IO(Result<&1, &1, Err, Conn>):
3377  match n:
3378    case 0n:
3379      match step:
3380        case TunnelRead{s, raw}:
3381          proxy.connect.fail(s, ErrBad{})
3382        case TunnelHead{s, raw, result}:
3383          proxy.connect.fail(s, ErrBad{})
3384        case TunnelGot{raw, answer}:
3385          (s, result) = answer
3386          proxy.connect.fail(s, ErrBad{})
3387    case 1n+p:
3388      match step:
3389        case TunnelRead{s, +raw}:
3390          proxy.connect.loop(p, TunnelHead{s, raw,
3391            proxy.connect.frame(raw, Nat.is_gt(String.length(raw), 65536n))},
3392            ms, sni, cert)
3393        case TunnelHead{s, raw, result}:
3394          match result:
3395            case FrameBad{}:
3396              proxy.connect.fail(s, ErrBad{})
3397            case FrameMore{}:
3398              do IO<Result<&1, &1, Err, Conn>>:
3399                answer : Socket & Result<&1, &1, U32 & String, U32 & Array<U32>> <-
3400                  io.recv.words(False{}, s, 4096, ms)
3401                proxy.connect.loop(p, TunnelGot{raw, answer}, ms, sni, cert)
3402            case FrameDone{res}:
3403              proxy.connect.finish(res, raw, s, ms, sni, cert)
3404        case TunnelGot{raw, answer}:
3405          match answer:
3406            case (s, Fail{(+code, why)}):
3407              proxy.connect.fail(s, err.or_late(code, ErrRead{code, why}))
3408            case (s, Done{(+len, buf)}):
3409              proxy.connect.loop(p,
3410                proxy.connect.chunk(U32.is_zero(len), s, raw, len, buf),
3411                ms, sni, cert)
3412
3413def proxy.connect.header(+authority: String, authorization: String) -> String:
3414  match authorization:
3415    case SNil{}:
3416      "CONNECT " ++ authority ++ " HTTP/1.1\r\nHost: " ++ authority ++ "\r\n\r\n"
3417    case other:
3418      "CONNECT " ++ authority ++ " HTTP/1.1\r\nHost: " ++ authority
3419        ++ "\r\nProxy-Authorization: " ++ authorization ++ "\r\n\r\n"
3420
3421def proxy.connect.sent(r: Socket & Result<&1, &1, U32 & String, Unit>,
3422    +ms: U32, sni: String, cert: Maybe<&2, Cert>) ->
3423    IO(Result<&1, &1, Err, Conn>):
3424  (s, sent) = r
3425  match sent:
3426    case Fail{(+code, why)}:
3427      proxy.connect.fail(s, err.or_late(code, ErrWrite{code, why}))
3428    case Done{unit}:
3429      proxy.connect.loop(Nat.mul(3n, 65536n), TunnelRead{s, ""}, ms, sni, cert)
3430
3431def proxy.connect(s: Socket, +ms: U32, sni: String, authority: String,
3432    authorization: String, cert: Maybe<&2, Cert>) ->
3433    IO(Result<&1, &1, Err, Conn>):
3434  do IO<Result<&1, &1, Err, Conn>>:
3435    sent : Socket & Result<&1, &1, U32 & String, Unit> <-
3436      io.send(False{}, s, proxy.connect.header(authority, authorization))
3437    proxy.connect.sent(sent, ms, sni, cert)
3438
3439def proxy.route.tls(tls: Bool, s: Socket, +ms: U32, sni: String,
3440    authority: String, authorization: String, cert: Maybe<&2, Cert>) ->
3441    IO(Result<&1, &1, Err, Conn>):
3442  match tls:
3443    case False{}:
3444      IO.pure(Result<&1, &1, Err, Conn>, Done{Conn{False{}, s}})
3445    case True{}:
3446      proxy.connect(s, ms, sni, authority, authorization, cert)
3447
3448def proxy.route.connected(tls: Bool, +ms: U32, sni: String, authority: String,
3449    authorization: String, cert: Maybe<&2, Cert>,
3450    r: Result<&1, &1, Err, Conn>) -> IO(Result<&1, &1, Err, Conn>):
3451  match r:
3452    case Fail{e}:
3453      IO.pure(Result<&1, &1, Err, Conn>, Fail{e})
3454    case Done{c}:
3455      match c:
3456        case Conn{plain, s}:
3457          proxy.route.tls(tls, s, ms, sni, authority, authorization, cert)
3458        case ConnH2{s, client}:
3459          do IO<Result<&1, &1, Err, Conn>>:
3460            Wire.tls.close(s)
3461            return Fail{ErrBad{}}
3462
3463def proxy.route.open(+ms: U32, +tls: Bool, +host: String, +port: U32,
3464    +sni: String, +authority: String, +authorization: String,
3465    cert: Maybe<&2, Cert>) -> IO(Result<&1, &1, Err, Conn>):
3466  do IO<Result<&1, &1, Err, Conn>>:
3467    ips : List<&2, String> <- Dns.resolve.all(host)
3468    conn : Result<&1, &1, Err, Conn> <-
3469      conn.open.all(False{}, ms, host, port, ips, None{}, False{})
3470    proxy.route.connected(tls, ms, sni, authority, authorization, cert, conn)
3471
3472def route.open(+ms: U32, route: Route) -> IO(Result<&1, &1, Err, Conn>):
3473  match route:
3474    case RouteDirect{tls, +host, port, cert}:
3475      do IO<Result<&1, &1, Err, Conn>>:
3476        ips : List<&2, String> <- Dns.resolve.all(host)
3477        conn.open.all(tls, ms, host, port, ips, cert, True{})
3478    case RouteProxy{tls, host, port, sni, authority, authorization, cert}:
3479      proxy.route.open(ms, tls, host, port, sni, authority, authorization, cert)
3480
3481def conn.ex.h1(+tls: Bool, s: Socket, +ms: U32, request: Send) -> IO(Out):
3482  Send{+method, target, authority, headers, body} = request
3483  exchange.go(tls, ms, False{}, String.eq(method, "HEAD"), s,
3484    encode_req.on(method, target, authority, headers, body, False{}))
3485
3486# A socket with bytes past the response is out of step with the server, so it is closed.
3487def pool.keep.s(p: Pool, +key: String, +tls: Bool, res: Res, s: Socket, clean: Bool) -> IO(Pool & Result<&1, &1, Err, Res>):
3488  match clean:
3489    case True{}:
3490      do IO<Pool & Result<&1, &1, Err, Res>>:
3491        p2 : Pool <- pool.give(p, key, Conn{tls, s})
3492        return (p2, Done{res})
3493    case False{}:
3494      do IO<Pool & Result<&1, &1, Err, Res>>:
3495        io.close(tls, s)
3496        return (p, Done{res})
3497
3498def pool.keep.m(p: Pool, +key: String, +tls: Bool, res: Res, +clean: Bool, sock: Maybe<&1, Socket>) -> IO(Pool & Result<&1, &1, Err, Res>):
3499  match sock:
3500    case None{}:
3501      IO.pure(Pool & Result<&1, &1, Err, Res>, (p, Done{res}))
3502    case Some{s}:
3503      pool.keep.s(p, key, tls, res, s, clean)
3504
3505def pool.keep(p: Pool, +key: String, +tls: Bool, res: Res, sock: Maybe<&1, Socket>, rest: Bytes.Bytes) -> IO(Pool & Result<&1, &1, Err, Res>):
3506  Bytes.Bytes{+len, buf} = rest
3507  pool.keep.m(p, key, tls, res, U32.is_zero(len), sock)
3508
3509def pool.after(p: Pool, +key: String, +tls: Bool, o: Out) -> IO(Pool & Result<&1, &1, Err, Res>):
3510  match o:
3511    case OutFail{e, none}:
3512      IO.pure(Pool & Result<&1, &1, Err, Res>, (p, Fail{e}))
3513    case OutDone{res, sock, rest}:
3514      pool.keep(p, key, tls, res, sock, rest)
3515
3516def pool.h2.reusable(c: Conn) -> Bool & Conn:
3517  match c:
3518    case Conn{tls, s}:
3519      (True{}, Conn{tls, s})
3520    case ConnH2{s, H2.Client{input, streams, encoder, decoder, +control}}:
3521      H2.Control{next, active, frame_max, initial, max_streams, send_window,
3522        recv_window, first, ack, continuation, +goaway} = control
3523      (Maybe.is_none(&2, U32, goaway),
3524        ConnH2{s, H2.Client{input, streams, encoder, decoder, control}})
3525
3526def pool.h2.keep(p: Pool, +key: String, res: Res, state: Bool & Conn) ->
3527    IO(Pool & Result<&1, &1, Err, Res>):
3528  (reusable, c) = state
3529  match reusable:
3530    case True{}:
3531      do IO<Pool & Result<&1, &1, Err, Res>>:
3532        next : Pool <- pool.give(p, key, c)
3533        return (next, Done{res})
3534    case False{}:
3535      do IO<Pool & Result<&1, &1, Err, Res>>:
3536        conn.close(c)
3537        return (p, Done{res})
3538
3539def pool.h2.result(p: Pool, +key: String, r: Result<&1, &1, Err, Conn & Res>) ->
3540    IO(Pool & Result<&1, &1, Err, Res>):
3541  match r:
3542    case Fail{e}:
3543      IO.pure(Pool & Result<&1, &1, Err, Res>, (p, Fail{e}))
3544    case Done{(c, res)}:
3545      pool.h2.keep(p, key, res, pool.h2.reusable(c))
3546
3547def pool.h2.ex(p: Pool, +key: String, +ms: U32, request: Send,
3548    s: Socket, client: H2.Client) -> IO(Pool & Result<&1, &1, Err, Res>):
3549  do IO<Pool & Result<&1, &1, Err, Res>>:
3550    r : Result<&1, &1, Err, Conn & Res> <- h2.exchange(s, client, ms, request)
3551    pool.h2.result(p, key, r)
3552
3553def pool.fresh.conn(p: Pool, +key: String, +ms: U32, request: Send,
3554    r: Result<&1, &1, Err, Conn>) -> IO(Pool & Result<&1, &1, Err, Res>):
3555  match r:
3556    case Fail{e}:
3557      IO.pure(Pool & Result<&1, &1, Err, Res>, (p, Fail{e}))
3558    case Done{c}:
3559      match c:
3560        case Conn{+tls, s}:
3561          do IO<Pool & Result<&1, &1, Err, Res>>:
3562            o : Out <- conn.ex.h1(tls, s, ms, request)
3563            pool.after(p, key, tls, o)
3564        case ConnH2{s, client}:
3565          pool.h2.ex(p, key, ms, request, s, client)
3566
3567def pool.fresh(p: Pool, +key: String, +ms: U32, request: Send, route: Route) ->
3568    IO(Pool & Result<&1, &1, Err, Res>):
3569  do IO<Pool & Result<&1, &1, Err, Res>>:
3570    c : Result<&1, &1, Err, Conn> <- route.open(ms, route)
3571    pool.fresh.conn(p, key, ms, request, c)
3572
3573# A reused socket the server already closed fails before any response byte.
3574def pool.retry(+none: Bool, +idem: Bool) -> Bool:
3575  Bool.and(none, idem)
3576
3577def pool.stale(p: Pool, +key: String, +ms: U32, request: Send,
3578    e: Err, again: Bool, route: Route) ->
3579    IO(Pool & Result<&1, &1, Err, Res>):
3580  match again:
3581    case True{}:
3582      pool.fresh(p, key, ms, request, route)
3583    case False{}:
3584      IO.pure(Pool & Result<&1, &1, Err, Res>, (p, Fail{e}))
3585
3586def pool.reused(p: Pool, +key: String, +tls: Bool, +ms: U32, +idem: Bool,
3587    spare: Send, o: Out, route: Route) ->
3588    IO(Pool & Result<&1, &1, Err, Res>):
3589  match o:
3590    case OutFail{e, +none}:
3591      pool.stale(p, key, ms, spare, e, pool.retry(none, idem), route)
3592    case OutDone{res, sock, rest}:
3593      pool.keep(p, key, tls, res, sock, rest)
3594
3595# Copy only the reused HTTP/1.1 request body, for a stale-socket retry.
3596def pool.idle.h1.bodies(p: Pool, +key: String, +tls: Bool, +ms: U32, +idem: Bool,
3597    s: Socket, +method: String, +target: String, +authority: String,
3598    +headers: Map<&2, List<&2, String>>, r: Bytes.Bytes & Bytes.Bytes,
3599    route: Route) -> IO(Pool & Result<&1, &1, Err, Res>):
3600  (wire, spare) = r
3601  do IO<Pool & Result<&1, &1, Err, Res>>:
3602    o : Out <- conn.ex.h1(tls, s, ms, Send{method, target, authority, headers, wire})
3603    pool.reused(p, key, tls, ms, idem,
3604      Send{method, target, authority, headers, spare}, o, route)
3605
3606def pool.idle.h1(p: Pool, +key: String, +tls: Bool, +ms: U32, +idem: Bool,
3607    s: Socket, request: Send, route: Route) ->
3608    IO(Pool & Result<&1, &1, Err, Res>):
3609  Send{+method, +target, +authority, +headers, body} = request
3610  pool.idle.h1.bodies(p, key, tls, ms, idem, s, method, target,
3611    authority, headers, Bytes.slice(body, 0, 4294967295), route)
3612
3613def pool.idle.reuse(p: Pool, +key: String, +ms: U32, +idem: Bool,
3614    c: Conn, request: Send, route: Route) ->
3615    IO(Pool & Result<&1, &1, Err, Res>):
3616  match c:
3617    case Conn{tls, s}:
3618      pool.idle.h1(p, key, tls, ms, idem, s, request, route)
3619    case ConnH2{s, client}:
3620      pool.h2.ex(p, key, ms, request, s, client)
3621
3622def pool.idle(taken: Pool & Maybe<&1, Conn>, +key: String, +ms: U32,
3623    +idem: Bool, request: Send, route: Route) ->
3624    IO(Pool & Result<&1, &1, Err, Res>):
3625  (p, m) = taken
3626  match m:
3627    case None{}:
3628      pool.fresh(p, key, ms, request, route)
3629    case Some{c}:
3630      pool.idle.reuse(p, key, ms, idem, c, request, route)
3631
3632def proxy.http.headers(headers: Map<&2, List<&2, String>>,
3633    authorization: String) -> Map<&2, List<&2, String>>:
3634  match authorization:
3635    case SNil{}:
3636      headers
3637    case other:
3638      set(headers, "proxy-authorization", authorization)
3639
3640def proxy.absolute(scheme: String, host_field: String, target: String) -> String:
3641  scheme ++ "://" ++ host_field ++ target
3642
3643def proxy.request(secure: Bool, +scheme: String, method: String,
3644    +target: String, +hf: String, headers: Map<&2, List<&2, String>>,
3645    body: Bytes.Bytes, authorization: String) -> Send:
3646  match secure:
3647    case True{}:
3648      Send{method, target, hf, Map.del(&2, List<&2, String>, headers,
3649        "proxy-authorization"), body}
3650    case False{}:
3651      Send{method, proxy.absolute(scheme, hf, target), hf,
3652        proxy.http.headers(headers, authorization), body}
3653
3654def pool.origin.proxy(p: Pool, +method: String, +ms: U32,
3655    headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, +hf: String,
3656    +scheme: String, +host: String, +port: U32, +target: String,
3657    +cert: Maybe<&2, Cert>, proxy: Proxy) ->
3658    IO(Pool & Result<&1, &1, Err, Res>):
3659  match proxy:
3660    case ProxyDirect{}:
3661      +key = pool.key.cert(pool.key(scheme, host, port), cert)
3662      pool.idle(pool.take(p, key), key, ms, pool.idempotent(method),
3663        Send{method, target, hf, headers, body},
3664        RouteDirect{String.eq(scheme, "https"), host, port, cert})
3665    case ProxyVia{+proxy_host, +proxy_port, +authorization}:
3666      +secure = String.eq(scheme, "https")
3667      +key = pool.key.cert(pool.key(scheme, host, port)
3668        ++ "|proxy:" ++ proxy_host ++ ":" ++ U32.show(proxy_port)
3669        ++ "|auth:" ++ authorization, cert)
3670      pool.idle(pool.take(p, key), key, ms, pool.idempotent(method),
3671        proxy.request(secure, scheme, method, target, hf, headers, body, authorization),
3672        RouteProxy{secure, proxy_host, proxy_port, host,
3673          Url.host_field.wrap(host, Url.has(host, 58)) ++ ":" ++ U32.show(port),
3674          authorization, cert})
3675
3676def pool.origin.choice(p: Pool, method: String, ms: U32,
3677    headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, hf: String,
3678    scheme: String, host: String, port: U32, target: String,
3679    cert: Maybe<&2, Cert>, choice: Maybe<&2, Proxy>) ->
3680    IO(Pool & Result<&1, &1, Err, Res>):
3681  match choice:
3682    case None{}:
3683      IO.pure(Pool & Result<&1, &1, Err, Res>, (p, Fail{ErrUrl{}}))
3684    case Some{proxy}:
3685      pool.origin.proxy(p, method, ms, headers, body, hf, scheme, host, port,
3686        target, cert, proxy)
3687
3688def pool.origin(p: Pool, method: String, ms: U32,
3689    headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, hf: String,
3690    a: Url.Abs, known: Bool, cert: Maybe<&2, Cert>,
3691    choice: Maybe<&2, Proxy>) ->
3692    IO(Pool & Result<&1, &1, Err, Res>):
3693  Url.Abs{scheme, host, port, target} = a
3694  match known:
3695    case False{}:
3696      IO.pure(Pool & Result<&1, &1, Err, Res>, (p, Fail{ErrUrl{}}))
3697    case True{}:
3698      pool.origin.choice(p, method, ms, headers, body, hf, scheme, host,
3699        port, target, cert, choice)
3700
3701def pool.scheme.ok(a: Url.Abs) -> Bool:
3702  Url.Abs{+scheme, host, port, target} = a
3703  Bool.or(String.eq(scheme, "http"), String.eq(scheme, "https"))
3704
3705def pool.one.back(h: Hop, pr: Pool & Result<&1, &1, Err, Res>) -> Pool & Result<&1, &1, Err, Res> & Hop:
3706  (p, r) = pr
3707  (p, r, h)
3708
3709# sent is headers plus any jar cookies; the hop keeps headers, so cookies never pile up across hops.
3710def pool.one.of(p: Pool, +method: String, +url: Url.Abs,
3711    headers: Map<&2, List<&2, String>>, sent: Map<&2, List<&2, String>>,
3712    +ms: U32, r: Bytes.Bytes & Bytes.Bytes, cert: Maybe<&2, Cert>) ->
3713    IO(Pool & Result<&1, &1, Err, Res> & Hop):
3714  Url.Abs{+scheme, +host, +port, target} = url
3715  (body, wire) = r
3716  do IO<Pool & Result<&1, &1, Err, Res> & Hop>:
3717    choice : Maybe<&2, Proxy> <- proxy.select(scheme, host, port)
3718    pr : Pool & Result<&1, &1, Err, Res> <-
3719      pool.origin(p, method, ms, sent, wire, Url.host_field(url),
3720        url, pool.scheme.ok(url), cert, choice)
3721    return pool.one.back(Hop{method, url, headers, body}, pr)
3722
3723# One request, on an idle socket to its origin when the pool has one. The hop comes back for the redirect.
3724def pool.one(p: Pool, h: Hop, +ms: U32, cert: Maybe<&2, Cert>, jar: Maybe<&2, Jar>) -> IO(Pool & Result<&1, &1, Err, Res> & Hop):
3725  Hop{+method, +url, +headers, body} = h
3726  pool.one.of(p, method, url, headers, jar.opt.apply(jar, url, headers), ms, Bytes.slice(body, 0, 4294967295), cert)
3727
3728type Next is Type:
3729  NDone{res: Result<&1, &1, Err, Res>}
3730  NStop{}
3731  NGo{left: Nat, hop: Hop}
3732
3733type Mode is Data:
3734  ModeFollow{}
3735  ModeManual{}
3736  ModeError{}
3737
3738# left: redirects still allowed after the request we just finished.
3739def fetch.hop(left: Nat, h: Hop) -> Next:
3740  match left:
3741    case 0n:
3742      NStop{}
3743    case 1n+p:
3744      NGo{p, h}
3745
3746def fetch.decide.r(left: Nat, r: Res, next: Maybe<&1, Hop>) -> Next:
3747  match next:
3748    case None{}:
3749      NDone{Done{r}}
3750    case Some{h}:
3751      fetch.hop(left, h)
3752
3753def fetch.decide.res(left: Nat, h: Hop, r: Res) -> Next:
3754  Res{+status, +headers, body} = r
3755  fetch.decide.r(left, Res{status, headers, body}, redirect(status, headers, h))
3756
3757def fetch.decide(left: Nat, h: Hop, m: Result<&1, &1, Err, Res>) -> Next:
3758  match m:
3759    case Fail{e}:
3760      NDone{Fail{e}}
3761    case Done{r}:
3762      fetch.decide.res(left, h, r)
3763
3764def fetch.error.res(r: Res, bad: Bool) -> Next:
3765  match bad:
3766    case True{}:
3767      NDone{Fail{ErrRedirect{}}}
3768    case False{}:
3769      NDone{Done{r}}
3770
3771def fetch.error(h: Hop, m: Result<&1, &1, Err, Res>) -> Next:
3772  match m:
3773    case Fail{e}:
3774      NDone{Fail{e}}
3775    case Done{r}:
3776      Res{+status, +headers, body} = r
3777      fetch.error.res(Res{status, headers, body}, Bool.and(redirect.code(status), has_header(headers, "location")))
3778
3779def fetch.policy(mode: Mode, left: Nat, h: Hop, m: Result<&1, &1, Err, Res>) -> Next:
3780  match mode:
3781    case ModeFollow{}:
3782      fetch.decide(left, h, m)
3783    case ModeManual{}:
3784      NDone{m}
3785    case ModeError{}:
3786      fetch.error(h, m)
3787
3788# A caller's own Accept-Encoding wins; enc is the codings fetch can undo.
3789def accept.enc(+h: Map<&2, List<&2, String>>, +enc: String) -> Map<&2, List<&2, String>>:
3790  Bool.pick(Map<&2, List<&2, String>>, has_header(h, "accept-encoding"), h, set(h, "accept-encoding", enc))
3791
3792def fetch.start(method: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, u: Maybe<&2, Url.Abs>, +enc: String) -> Next:
3793  match u:
3794    case None{}:
3795      NDone{Fail{ErrUrl{}}}
3796    case Some{a}:
3797      NGo{20n, Hop{method, a, accept.enc(req.put(Map.to_list(&2, List<&2, String>, headers), empty()), enc), body}}
3798
3799# The redirect loop's state: the pool, what to do next, the client identity, and the jar if any.
3800type Hops is Type:
3801  Hops{p: Pool, next: Next, cert: Maybe<&2, Cert>, jar: Maybe<&2, Jar>}
3802
3803def pool.next.move(p: Pool, +old: String, cert: Maybe<&2, Cert>, jar: Maybe<&2, Jar>, n: Next) -> Hops:
3804  match n:
3805    case NGo{left, h}:
3806      Hop{method, +url, headers, body} = h
3807      Hops{p, NGo{left, Hop{method, url, headers, body}},
3808        Bool.pick(Maybe<&2, Cert>, String.eq(old, redirect.origin(url)), cert, None{}), jar}
3809    case NDone{r}:
3810      Hops{p, NDone{r}, None{}, jar}
3811    case NStop{}:
3812      Hops{p, NStop{}, None{}, jar}
3813
3814def 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:
3815  (jar, m) = r
3816  pool.next.move(p, redirect.origin(url), cert, jar, fetch.policy(mode, left, h, m))
3817
3818# The jar takes the response's Set-Cookie fields first, redirect or not.
3819def pool.next(+mode: Mode, left: Nat, cert: Maybe<&2, Cert>, jar: Maybe<&2, Jar>, x: Pool & Result<&1, &1, Err, Res> & Hop) -> Hops:
3820  (p, m, h) = x
3821  Hop{method, +url, headers, body} = h
3822  pool.next.of(mode, left, cert, p, url, Hop{method, url, headers, body}, jar.opt.store(jar, url, m))
3823
3824def pool.hops.one(+mode: Mode, +ms: U32, +cert: Maybe<&2, Cert>, +jar: Maybe<&2, Jar>, p: Pool, h: Hop, left: Nat) -> IO(Hops):
3825  do IO<Hops>:
3826    x : Pool & Result<&1, &1, Err, Res> & Hop <- pool.one(p, h, ms, cert, jar)
3827    return pool.next(mode, left, cert, jar, x)
3828
3829# NGo.left is how many redirects may follow this request. 20 is WHATWG's limit.
3830# The jar, when there is one, gives cookies to every hop and takes them from every response.
3831@unsafe
3832def pool.hops(+mode: Mode, +ms: U32, st: Hops) -> IO(Pool & Result<&1, &1, Err, Res> & Maybe<&2, Jar>):
3833  Hops{p, n, cert, cj} = st
3834  match n:
3835    case NDone{m}:
3836      IO.pure(Pool & Result<&1, &1, Err, Res> & Maybe<&2, Jar>, (p, m, cj))
3837    case NStop{}:
3838      IO.pure(Pool & Result<&1, &1, Err, Res> & Maybe<&2, Jar>, (p, Fail{ErrRedirect{}}, cj))
3839    case NGo{+left, h}:
3840      do IO<Pool & Result<&1, &1, Err, Res> & Maybe<&2, Jar>>:
3841        next : Hops <- pool.hops.one(mode, ms, cert, cj, p, h, left)
3842        pool.hops(mode, ms, next)
3843
3844# Content-Encoding (RFC 9110 §8.4): each value, trimmed and lowercased, in the order applied.
3845def ce.keep(+w: String, +rest: List<&2, String>) -> List<&2, String>:
3846  Bool.pick(List<&2, String>, String.is_empty(w), rest, Con{w, rest})
3847
3848def ce.norm(xs: List<&2, String>) -> List<&2, String>:
3849  match xs:
3850    case Nil{}:
3851      Nil{}
3852    case Con{v, t}:
3853      ce.keep(String.to_lower(trim(v)), ce.norm(t))
3854
3855def ce.split(xs: List<&2, String>) -> List<&2, String>:
3856  match xs:
3857    case Nil{}:
3858      Nil{}
3859    case Con{v, t}:
3860      List.append(&2, String, ce.norm(String.split(v, ',')), ce.split(t))
3861
3862# Ok: decoded so far. Bad: a coding failed. Skip: a coding we cannot decode, so the body stays as sent.
3863type Dec is Data:
3864  DecOk{b: String}
3865  DecBad{}
3866  DecSkip{}
3867
3868def ce.of(m: Maybe<&2, String>) -> Dec:
3869  match m:
3870    case None{}:
3871      DecBad{}
3872    case Some{b}:
3873      DecOk{b}
3874
3875# Servers send deflate both with and without the zlib wrapper.
3876def ce.deflate(+b: String, m: Maybe<&2, String>) -> Dec:
3877  match m:
3878    case Some{out}:
3879      DecOk{out}
3880    case None{}:
3881      ce.of(Zlib.inflate(b))
3882
3883def ce.apply(+c: String, +b: String) -> Dec:
3884  Bool.pick(Dec, Bool.or(String.eq(c, "gzip"), String.eq(c, "x-gzip")), ce.of(Zlib.gunzip(b)),
3885    Bool.pick(Dec, String.eq(c, "deflate"), ce.deflate(b, Zlib.unzlib(b)),
3886      Bool.pick(Dec, String.eq(c, "identity"), DecOk{b}, DecSkip{})))
3887
3888def ce.go(cs: List<&2, String>, d: Dec) -> Dec:
3889  match cs:
3890    case Nil{}:
3891      d
3892    case Con{+c, t}:
3893      match d:
3894        case DecOk{+b}:
3895          ce.go(t, ce.apply(c, b))
3896        case DecBad{}:
3897          DecBad{}
3898        case DecSkip{}:
3899          DecSkip{}
3900
3901def decoded.pick(d: Dec, +status: U32, headers: Map<&2, List<&2, String>>, body: String) -> Result<&1, &1, Err, Res>:
3902  match d:
3903    case DecOk{b}:
3904      Done{Res{status, headers, Bytes.from_string(b)}}
3905    case DecBad{}:
3906      Fail{ErrBad{}}
3907    case DecSkip{}:
3908      Done{Res{status, headers, Bytes.from_string(body)}}
3909
3910# ponytail: the codings run on a String copy of the body; give zlib a Bytes input if gzip bodies get big.
3911def decoded.cs(+status: U32, +headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, cs: List<&2, String>) -> Result<&1, &1, Err, Res>:
3912  match cs:
3913    case Nil{}:
3914      Done{Res{status, headers, body}}
3915    case Con{c, t}:
3916      +s = Bytes.to_string(body)
3917      decoded.pick(ce.go(Con{c, t}, DecOk{s}), status, headers, s)
3918
3919def decoded.go(empty: Bool, +status: U32, +headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> Result<&1, &1, Err, Res>:
3920  match empty:
3921    case True{}:
3922      Done{Res{status, headers, body}}
3923    case False{}:
3924      decoded.cs(status, headers, body, List.reverse(&2, String, ce.split(fields(headers, "content-encoding"))))
3925
3926# The body decoded per Content-Encoding; the headers stay as sent. A corrupt body is ErrBad.
3927def decoded(res: Res) -> Result<&1, &1, Err, Res>:
3928  Res{+status, +headers, body} = res
3929  Bytes.Bytes{+len, buf} = body
3930  decoded.go(U32.is_zero(len), status, headers, Bytes.Bytes{len, buf})
3931
3932def decoded.m(r: Result<&1, &1, Err, Res>) -> Maybe<&1, Res>:
3933  match r:
3934    case Done{x}:
3935      Some{x}
3936    case Fail{e}:
3937      None{}
3938
3939def decoded.some(res: Res) -> Maybe<&1, Res>:
3940  decoded.m(decoded(res))
3941
3942def ce.words(r: Result<&1, &1, U32 & String, U32 & Array<U32>>) -> Maybe<&1, Bytes.Bytes>:
3943  match r:
3944    case Fail{e}:
3945      None{}
3946    case Done{(+len, buf)}:
3947      Some{Bytes.Bytes{len, buf}}
3948
3949# A decoded body stops at 16 MiB, like a received one.
3950def ce.eff(~eff: U32 -> U32 -> Array<U32> -> IO(Result<&1, &1, U32 & String, U32 & Array<U32>>), b: Bytes.Bytes) -> IO(Maybe<&1, Bytes.Bytes>):
3951  Bytes.Bytes{+len, buf} = b
3952  do IO<Maybe<&1, Bytes.Bytes>>:
3953    r : Result<&1, &1, U32 & String, U32 & Array<U32>> <- eff(16777216, len, buf)
3954    return ce.words(r)
3955
3956def ce.dec(d: Dec) -> Maybe<&1, Bytes.Bytes>:
3957  match d:
3958    case DecOk{b}:
3959      Some{Bytes.from_string(b)}
3960    case DecBad{}:
3961      None{}
3962    case DecSkip{}:
3963      None{}
3964
3965# ponytail: deflate runs on the pure decoder, which also takes raw DEFLATE; servers rarely send it.
3966def ce.io.deflate(on: Bool, b: Bytes.Bytes) -> IO(Maybe<&1, Bytes.Bytes>):
3967  match on:
3968    case True{}:
3969      +s = Bytes.to_string(b)
3970      IO.pure(Maybe<&1, Bytes.Bytes>, ce.dec(ce.deflate(s, Zlib.unzlib(s))))
3971    case False{}:
3972      IO.pure(Maybe<&1, Bytes.Bytes>, Some{b})
3973
3974def ce.io.zstd(on: Bool, +c: String, b: Bytes.Bytes) -> IO(Maybe<&1, Bytes.Bytes>):
3975  match on:
3976    case True{}:
3977      ce.eff(~Zlib.zstd.words, b)
3978    case False{}:
3979      ce.io.deflate(String.eq(c, "deflate"), b)
3980
3981def ce.io.br(on: Bool, +c: String, b: Bytes.Bytes) -> IO(Maybe<&1, Bytes.Bytes>):
3982  match on:
3983    case True{}:
3984      ce.eff(~Zlib.brotli.words, b)
3985    case False{}:
3986      ce.io.zstd(String.eq(c, "zstd"), c, b)
3987
3988# One known coding undone: gzip, x-gzip, br, zstd, deflate, or identity.
3989def ce.io.gz(on: Bool, +c: String, b: Bytes.Bytes) -> IO(Maybe<&1, Bytes.Bytes>):
3990  match on:
3991    case True{}:
3992      ce.eff(~Zlib.inflate.words, b)
3993    case False{}:
3994      ce.io.br(String.eq(c, "br"), c, b)
3995
3996def ce.io.go(cs: List<&2, String>, m: Maybe<&1, Bytes.Bytes>) -> IO(Maybe<&1, Bytes.Bytes>):
3997  match cs:
3998    case Nil{}:
3999      match m:
4000        case None{}:
4001          IO.pure(Maybe<&1, Bytes.Bytes>, None{})
4002        case Some{b}:
4003          IO.pure(Maybe<&1, Bytes.Bytes>, Some{b})
4004    case Con{+c, t}:
4005      match m:
4006        case None{}:
4007          IO.pure(Maybe<&1, Bytes.Bytes>, None{})
4008        case Some{b}:
4009          do IO<Maybe<&1, Bytes.Bytes>>:
4010            n : Maybe<&1, Bytes.Bytes> <- ce.io.gz(Bool.or(String.eq(c, "gzip"), String.eq(c, "x-gzip")), c, b)
4011            ce.io.go(t, n)
4012
4013def ce.has(xs: List<&2, String>, +c: String) -> Bool:
4014  match xs:
4015    case Nil{}:
4016      False{}
4017    case Con{x, t}:
4018      Bool.or(String.eq(c, x), ce.has(t, c))
4019
4020def ce.known(cs: List<&2, String>, +ok: List<&2, String>) -> Bool:
4021  match cs:
4022    case Nil{}:
4023      True{}
4024    case Con{c, t}:
4025      Bool.and(ce.has(ok, c), ce.known(t, ok))
4026
4027def decoded.io.pick(m: Maybe<&1, Bytes.Bytes>, +status: U32, headers: Map<&2, List<&2, String>>) -> Result<&1, &1, Err, Res>:
4028  match m:
4029    case Some{b}:
4030      Done{Res{status, headers, b}}
4031    case None{}:
4032      Fail{ErrBad{}}
4033
4034def 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>):
4035  match known:
4036    case True{}:
4037      do IO<Result<&1, &1, Err, Res>>:
4038        m : Maybe<&1, Bytes.Bytes> <- ce.io.go(cs, Some{body})
4039        return decoded.io.pick(m, status, headers)
4040    case False{}:
4041      IO.pure(Result<&1, &1, Err, Res>, Done{Res{status, headers, body}})
4042
4043def decoded.io.go(empty: Bool, +enc: String, +status: U32, +headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Result<&1, &1, Err, Res>):
4044  match empty:
4045    case True{}:
4046      IO.pure(Result<&1, &1, Err, Res>, Done{Res{status, headers, body}})
4047    case False{}:
4048      +cs = List.reverse(&2, String, ce.split(fields(headers, "content-encoding")))
4049      decoded.io.run(ce.known(cs, Con{"identity", Con{"x-gzip", ce.split(Con{enc, Nil{}})}}), status, headers, body, cs)
4050
4051# decoded through the C libraries, for the codings in enc. A body with any other coding stays as sent.
4052def decoded.io(+enc: String, res: Res) -> IO(Result<&1, &1, Err, Res>):
4053  Res{+status, +headers, body} = res
4054  Bytes.Bytes{+len, buf} = body
4055  decoded.io.go(U32.is_zero(len), enc, status, headers, Bytes.Bytes{len, buf})
4056
4057# An effect on empty input fails with ENOENT only when its library does not load.
4058def codings.ok(r: Result<&1, &1, U32 & String, U32 & Array<U32>>) -> Bool:
4059  match r:
4060    case Fail{(+c, why)}:
4061      Bool.not(U32.is_eq(c, 2))
4062    case Done{p}:
4063      True{}
4064
4065def codings.has(~eff: U32 -> U32 -> Array<U32> -> IO(Result<&1, &1, U32 & String, U32 & Array<U32>>), b: Bytes.Bytes) -> IO(Bool):
4066  Bytes.Bytes{+len, buf} = b
4067  do IO<Bool>:
4068    r : Result<&1, &1, U32 & String, U32 & Array<U32>> <- eff(0, len, buf)
4069    return codings.ok(r)
4070
4071def codings.add(has: Bool, +enc: String, +c: String) -> String:
4072  Bool.pick(String, has, enc ++ ", " ++ c, enc)
4073
4074# gzip and deflate, then br and zstd when their C library loads.
4075def codings() -> IO(String):
4076  do IO<String>:
4077    b : Bool <- codings.has(~Zlib.brotli.words, Bytes.new(0))
4078    z : Bool <- codings.has(~Zlib.zstd.words, Bytes.new(0))
4079    return codings.add(z, codings.add(b, "gzip, deflate", "br"), "zstd")
4080
4081# The final response of a fetch, after redirects.
4082def fetch.final(+enc: String, r: Result<&1, &1, Err, Res>) -> IO(Result<&1, &1, Err, Res>):
4083  match r:
4084    case Done{res}:
4085      decoded.io(enc, res)
4086    case Fail{e}:
4087      IO.pure(Result<&1, &1, Err, Res>, Fail{e})
4088
4089def pool.final(+enc: String, pr: Pool & Result<&1, &1, Err, Res> & Maybe<&2, Jar>) -> IO(Pool & Result<&1, &1, Err, Res>):
4090  (p, r, jar) = pr
4091  do IO<Pool & Result<&1, &1, Err, Res>>:
4092    d : Result<&1, &1, Err, Res> <- fetch.final(enc, r)
4093    return (p, d)
4094
4095def 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>):
4096  do IO<Pool & Result<&1, &1, Err, Res>>:
4097    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{}})
4098    pool.final(enc, pr)
4099
4100def 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>):
4101  do IO<Pool & Result<&1, &1, Err, Res>>:
4102    enc : String <- codings()
4103    pool.how.enc(enc, p, method, url, headers, body, ms, mode, cert)
4104
4105# pool.how(p, "GET", "https://example.com/x?y=1", headers, body, ms, mode) follows redirects
4106# on p's idle sockets. Fail is a bad URL, a failed lookup, connect, handshake, send, read,
4107# a malformed response, more than 20 redirects, or a step past ms. Bodies are bytes.
4108def 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>):
4109  pool.how.cert(p, method, url, headers, body, ms, mode, None{})
4110
4111def 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>):
4112  pool.how(p, method, url, headers, body, ms, ModeFollow{})
4113
4114def pool.fetch(p: Pool, method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Pool & Result<&1, &1, Err, Res>):
4115  pool.fetch.with(p, method, url, headers, body, 30000)
4116
4117def 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>):
4118  pool.how.cert(p, method, url, headers, body, ms, ModeFollow{}, Some{Cert{chain, key}})
4119
4120def 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>):
4121  pool.fetch.cert.with(p, method, url, headers, body, chain, key, 30000)
4122
4123# One request for fetch.all: the arguments of fetch, as a record.
4124type Fetch is Type:
4125  Fetch{method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes}
4126
4127def fetch.all.job(p: Pool, f: Fetch) -> IO(Pool & Result<&1, &1, Err, Res>):
4128  Fetch{method, url, headers, body} = f
4129  pool.fetch(p, method, url, headers, body)
4130
4131def fetch.all.pools(n: Nat) -> List<Pool>:
4132  match n:
4133    case 0n:
4134      Nil{}
4135    case 1n+p:
4136      pool.new() <> fetch.all.pools(p)
4137
4138def fetch.all.close(ps: List<Pool>) -> IO(Unit):
4139  match ps:
4140    case Nil{}:
4141      IO.pure(Unit, Unit{})
4142    case p <> rest:
4143      do IO<Unit>:
4144        pool.close(p)
4145        fetch.all.close(rest)
4146
4147def fetch.all.done(r: List<Pool> & List<Result<&1, &1, Err, Res>>) -> IO(List<Result<&1, &1, Err, Res>>):
4148  (ps, rs) = r
4149  do IO<List<Result<&1, &1, Err, Res>>>:
4150    fetch.all.close(ps)
4151    return rs
4152
4153# No requests start no workers, since Conc.pool needs at least one.
4154def fetch.all.go(xs: List<Fetch>, +workers: Nat) -> IO(List<Result<&1, &1, Err, Res>>):
4155  match xs:
4156    case Nil{}:
4157      IO.pure(List<Result<&1, &1, Err, Res>>, Nil{})
4158    case x <> rest:
4159      do IO<List<Result<&1, &1, Err, Res>>>:
4160        r : List<Pool> & List<Result<&1, &1, Err, Res>> <-
4161          Conc.pool(~Pool, ~Fetch, ~Result<&1, &1, Err, Res>, ~fetch.all.job, fetch.all.pools(workers), x <> rest)
4162        fetch.all.done(r)
4163
4164def fetch.all.of(+n: U32, nx: Nat & List<Fetch>) -> IO(List<Result<&1, &1, Err, Res>>):
4165  (+len, xs) = nx
4166  fetch.all.go(xs, Nat.min(len, Nat.max(1n, U32.to_nat(n))))
4167
4168# Each request as fetch would make it, on at most n workers (0 counts as 1, and
4169# never more workers than requests). Each worker owns its own Pool, so an idle
4170# socket is reused only by the worker that opened it; every pool is closed at the
4171# end. Results come back in the order of reqs.
4172def fetch.all(reqs: List<Fetch>, +n: U32) -> IO(List<Result<&1, &1, Err, Res>>):
4173  fetch.all.of(n, Conc.count(Fetch, reqs))
4174
4175# The hops always hand the jar back; j is only the type's fallback.
4176def 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>):
4177  (p, r, jar) = pr
4178  do IO<Pool & Jar & Result<&1, &1, Err, Res>>:
4179    d : Result<&1, &1, Err, Res> <- fetch.final(enc, r)
4180    return (p, Maybe.default(&2, Jar, jar, j), d)
4181
4182def 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>):
4183  do IO<Pool & Jar & Result<&1, &1, Err, Res>>:
4184    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}})
4185    pool.jar.final(enc, j, pr)
4186
4187# pool.fetch with a cookie jar (RFC 6265bis). Before every hop, redirects included, the jar's
4188# cookies for that URL join the request's cookie field; after every response, redirects included,
4189# its Set-Cookie fields go into the jar. The jar's clock is the caller's: advance it with jar.at.
4190def 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>):
4191  do IO<Pool & Jar & Result<&1, &1, Err, Res>>:
4192    enc : String <- codings()
4193    pool.jar.enc(enc, p, j, method, url, headers, body)
4194def fetch.end(pr: Pool & Result<&1, &1, Err, Res>) -> IO(Result<&1, &1, Err, Res>):
4195  (p, r) = pr
4196  do IO<Result<&1, &1, Err, Res>>:
4197    pool.close(p)
4198    return r
4199
4200# fetch is pool.how on a fresh pool that closes afterwards.
4201def 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>):
4202  do IO<Result<&1, &1, Err, Res>>:
4203    pr : Pool & Result<&1, &1, Err, Res> <- pool.how(pool.new(), method, url, headers, body, ms, mode)
4204    fetch.end(pr)
4205
4206def fetch.with(method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, ms: U32) -> IO(Result<&1, &1, Err, Res>):
4207  fetch.how(method, url, headers, body, ms, ModeFollow{})
4208
4209def 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>):
4210  do IO<Result<&1, &1, Err, Res>>:
4211    pr : Pool & Result<&1, &1, Err, Res> <- pool.fetch.cert.with(pool.new(), method, url, headers, body, chain, key, ms)
4212    fetch.end(pr)
4213
4214def 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>):
4215  fetch.cert.with(method, url, headers, body, chain, key, 30000)
4216
4217# fetch.with and a 30 s step timeout.
4218def fetch(method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Result<&1, &1, Err, Res>):
4219  fetch.with(method, url, headers, body, 30000)
4220
4221def get(url: String) -> IO(Result<&1, &1, Err, Res>):
4222  fetch("GET", url, empty(), Bytes.new(0))
4223
4224# POST v as compact JSON, with content-type: application/json.
4225def post.json(url: String, v: Json.Val) -> IO(Result<&1, &1, Err, Res>):
4226  fetch("POST", url, set(empty(), "content-type", "application/json"), Json.encode.bytes(v))
4227
4228# Base URLs: resolve(base, ref) is ref against the absolute http(s) URL base (RFC 3986 §5.2),
4229# written back as a URL for fetch. None when base is not absolute or ref has another scheme.
4230def resolve.show(a: Url.Abs) -> String:
4231  Url.Abs{+scheme, host, port, +target} = a
4232  scheme ++ "://" ++ Url.host_field(Url.Abs{scheme, host, port, target}) ++ target
4233
4234def resolve.to(m: Maybe<&2, Url.Abs>) -> Maybe<&2, String>:
4235  match m:
4236    case None{}:
4237      None{}
4238    case Some{a}:
4239      Some{resolve.show(a)}
4240
4241def resolve.base(m: Maybe<&2, Url.Abs>, +ref: String) -> Maybe<&2, String>:
4242  match m:
4243    case None{}:
4244      None{}
4245    case Some{b}:
4246      resolve.to(Url.resolve(b, ref))
4247
4248def resolve(base: String, +ref: String) -> Maybe<&2, String>:
4249  resolve.base(Url.absolute(base), ref)
4250
4251# Retry. The wait before retry n (0 first) is 500 ms doubled n times, at most 30 s;
4252# its upper half is jitter r: backoff(n, r) = half + r mod (half + 1).
4253def retry.cap() -> U32:
4254  30000
4255
4256def retry.base(n: Nat) -> U32:
4257  match n:
4258    case 0n:
4259      500
4260    case 1n+p:
4261      U32.min((retry.base(p) * 2 : U32), retry.cap())
4262
4263def retry.backoff.half(+half: U32, +r: U32) -> U32:
4264  (half + (r % (half + 1)) : U32)
4265
4266def retry.backoff(n: Nat, +r: U32) -> U32:
4267  retry.backoff.half((retry.base(n) / 2 : U32), r)
4268
4269# ms clamped to 0 .. retry.cap().
4270def retry.after.ms(+ms: Int.I64) -> U32:
4271  Bool.pick(U32, Int.I64.is_neg(ms), 0,
4272    Bool.pick(U32, Int.I64.is_lt(ms, Int.I64.from_u32(retry.cap())), Int.I64.to_u32(ms), retry.cap()))
4273
4274def retry.after.date(m: Maybe<&2, Time.Instant>, now: Time.Instant) -> Maybe<&2, U32>:
4275  match m:
4276    case None{}:
4277      None{}
4278    case Some{date}:
4279      Some{retry.after.ms(Time.Duration.to_ms(Time.Instant.since(date, now)))}
4280
4281# More than 5 digits is past the cap, and would overflow parse_u32.
4282def retry.after.secs(+v: String, now: Time.Instant, n: Maybe<&2, U32>) -> Maybe<&2, U32>:
4283  match n:
4284    case None{}:
4285      retry.after.date(Time.http_date.parse(v), now)
4286    case Some{s}:
4287      Some{Bool.pick(U32, Nat.is_lt(5n, String.length(v)), retry.cap(), U32.min((s * 1000 : U32), retry.cap()))}
4288
4289# Retry-After (RFC 9110 §10.2.3) as ms from now, at most retry.cap(): delay-seconds, or an
4290# HTTP-date (a past date is 0). None when v is empty or neither form.
4291def retry.after(+v: String, now: Time.Instant) -> Maybe<&2, U32>:
4292  retry.after.secs(v, now, parse_u32(v))
4293
4294def retry.wait(m: Maybe<&2, U32>, n: Nat, +r: U32) -> U32:
4295  match m:
4296    case None{}:
4297      retry.backoff(n, r)
4298    case Some{ms}:
4299      ms
4300
4301# The wait before retry n: Retry-After v when it reads as a delay, else backoff with jitter r.
4302def retry.delay(+v: String, now: Time.Instant, n: Nat, +r: U32) -> U32:
4303  retry.wait(retry.after(v, now), n, r)
4304
4305# Statuses a later try may clear.
4306def retry.status(+s: U32) -> Bool:
4307  Bool.or(Bool.or(U32.is_eq(s, 408), U32.is_eq(s, 429)),
4308    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))))
4309
4310# A refused connect or a timeout may clear; any other error would repeat.
4311def retry.fail(e: Err) -> Result<&1, &1, Err, Res> & Maybe<&2, String>:
4312  match e:
4313    case ErrConnect{code, why}:
4314      (Fail{ErrConnect{code, why}}, Some{""})
4315    case ErrTimeout{}:
4316      (Fail{ErrTimeout{}}, Some{""})
4317    case other:
4318      (Fail{other}, None{})
4319
4320def retry.res(res: Res) -> Result<&1, &1, Err, Res> & Maybe<&2, String>:
4321  Res{+status, +headers, body} = res
4322  (Done{Res{status, headers, body}}, Bool.pick(Maybe<&2, String>, retry.status(status), Some{header(headers, "retry-after")}, None{}))
4323
4324def retry.judge.try(r: Result<&1, &1, Err, Res>) -> Result<&1, &1, Err, Res> & Maybe<&2, String>:
4325  match r:
4326    case Fail{e}:
4327      retry.fail(e)
4328    case Done{res}:
4329      retry.res(res)
4330
4331# One try, judged: the result as it came, and Some{Retry-After value} ("" when absent)
4332# when an idempotent request may try again.
4333def retry.judge(idem: Bool, r: Result<&1, &1, Err, Res>) -> Result<&1, &1, Err, Res> & Maybe<&2, String>:
4334  match idem:
4335    case False{}:
4336      (r, None{})
4337    case True{}:
4338      retry.judge.try(r)
4339
4340# ponytail: a failed random source gives jitter 0, so the wait is the lower half.
4341def retry.jitter(r: Result<&1, &1, U32 & String, U32>) -> U32:
4342  match r:
4343    case Fail{e}:
4344      0
4345    case Done{x}:
4346      x
4347
4348def retry.sleep(+v: String, n: Nat) -> IO(Unit):
4349  do IO<Unit>:
4350    now : Time.Instant <- Time.now()
4351    rnd : Result<&1, &1, U32 & String, U32> <- IO.random_u32()
4352    IO.sleep(retry.delay(v, now, n, retry.jitter(rnd)))
4353
4354def retry.kept(body: Bytes.Bytes, j: Result<&1, &1, Err, Res> & Maybe<&2, String>) -> Bytes.Bytes & Result<&1, &1, Err, Res> & Maybe<&2, String>:
4355  (r, m) = j
4356  (body, r, m)
4357
4358# One fetch of the copy; the body comes back for the next try.
4359def retry.one(+idem: Bool, +method: String, +url: String, +headers: Map<&2, List<&2, String>>,
4360    r: Bytes.Bytes & Bytes.Bytes) -> IO(Bytes.Bytes & Result<&1, &1, Err, Res> & Maybe<&2, String>):
4361  (body, spare) = r
4362  do IO<Bytes.Bytes & Result<&1, &1, Err, Res> & Maybe<&2, String>>:
4363    got : Result<&1, &1, Err, Res> <- fetch(method, url, headers, spare)
4364    return retry.kept(body, retry.judge(idem, got))
4365
4366# left: retries still allowed. n: the retry to wait for next, 0 first.
4367def retry.go(left: Nat, +n: Nat, +idem: Bool, +method: String, +url: String,
4368    +headers: Map<&2, List<&2, String>>,
4369    t: Bytes.Bytes & Result<&1, &1, Err, Res> & Maybe<&2, String>) -> IO(Result<&1, &1, Err, Res>):
4370  match left:
4371    case 0n:
4372      (body, r, m) = t
4373      IO.pure(Result<&1, &1, Err, Res>, r)
4374    case 1n+p:
4375      (body, r, m) = t
4376      match m:
4377        case None{}:
4378          IO.pure(Result<&1, &1, Err, Res>, r)
4379        case Some{v}:
4380          do IO<Result<&1, &1, Err, Res>>:
4381            retry.sleep(v, n)
4382            tried : Bytes.Bytes & Result<&1, &1, Err, Res> & Maybe<&2, String> <-
4383              retry.one(idem, method, url, headers, Bytes.slice(body, 0, 4294967295))
4384            retry.go(p, 1n+n, idem, method, url, headers, tried)
4385
4386# fetch.retry(n, method, url, headers, body) is fetch, tried again up to n times while an
4387# idempotent method (GET, HEAD, OPTIONS, TRACE, PUT, DELETE) gets a connect error, a timeout,
4388# or 408, 429, 500, 502, 503, or 504. POST, PATCH and other methods get one try. It waits
4389# Retry-After (seconds or HTTP-date, at most 30 s) when given, else the backoff. When retries
4390# run out, the last response or error comes back as it was.
4391def retry.start(enabled: Bool, n: U32, +method: String, +url: String,
4392    +headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) ->
4393    IO(Result<&1, &1, Err, Res>):
4394  match enabled:
4395    case False{}:
4396      fetch(method, url, headers, body)
4397    case True{}:
4398      do IO<Result<&1, &1, Err, Res>>:
4399        first : Bytes.Bytes & Result<&1, &1, Err, Res> & Maybe<&2, String> <-
4400          retry.one(True{}, method, url, headers, Bytes.slice(body, 0, 4294967295))
4401        retry.go(U32.to_nat(n), 0n, True{}, method, url, headers, first)
4402
4403def fetch.retry(+n: U32, +method: String, +url: String,
4404    +headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) ->
4405    IO(Result<&1, &1, Err, Res>):
4406  retry.start(Bool.and(U32.is_ne(n, 0), pool.idempotent(method)),
4407    n, method, url, headers, body)
4408
4409# Streaming (a body read or sent in pieces). A decoded stream owns its decoders.
4410# What the next read returns: read more, a raw piece, a decoded piece, the end, or an error.
4411type Po is Type:
4412  PoNone{}
4413  PoPiece{b: Bytes.Bytes}
4414  PoReady{b: Bytes.Bytes}
4415  PoEnd{}
4416  PoBad{e: Err}
4417
4418type Stream is Type:
4419  Stream{tls: Bool, s: Socket, ms: U32, res: Res, rb: Rb, out: Po, decs: List<&1, Zlib.Decoder>}
4420
4421type Pc is Type:
4422  Pc{rb: Rb, out: Po}
4423
4424# A body piece, or none when empty: more reads the next piece, and not more is the end.
4425def pc.po(more: Bool, empty: Bool, b: Bytes.Bytes) -> Po:
4426  match empty:
4427    case True{}:
4428      Bool.pick(Po, more, PoNone{}, PoEnd{})
4429    case False{}:
4430      PoPiece{b}
4431
4432def pc.piece(more: Bool, +rb: Rb, b: Bytes.Bytes) -> Pc:
4433  Bytes.Bytes{+len, buf} = b
4434  Pc{rb, pc.po(more, U32.is_zero(len), Bytes.Bytes{len, buf})}
4435
4436def pc.fed.of(b: Bytes.Bytes, st: Rb) -> Pc:
4437  match st:
4438    case RbDone{}:
4439      pc.piece(False{}, RbDone{}, b)
4440    case RbBad{}:
4441      Pc{RbDone{}, PoBad{ErrBad{}}}
4442    case RbLen{n}:
4443      pc.piece(True{}, RbLen{n}, b)
4444    case RbChunk{st}:
4445      pc.piece(True{}, RbChunk{st}, b)
4446    case RbClose{}:
4447      pc.piece(True{}, RbClose{}, b)
4448
4449def pc.fed(bf: Bf) -> Pc:
4450  Bf{st, parts, rest} = bf
4451  pc.fed.of(rb.body(parts), st)
4452
4453# The body bytes that just arrived: what they add to the body, and how it ends.
4454def pc.of(rb: Rb, piece: Bytes.Bytes) -> Pc:
4455  pc.fed(rb.feed(rb, Nil{}, piece))
4456
4457# The server closed. Only a close-delimited body may end this way (RFC 9112 §8).
4458def pc.end(ok: Bool) -> Pc:
4459  match ok:
4460    case True{}:
4461      Pc{RbDone{}, PoEnd{}}
4462    case False{}:
4463      Pc{RbDone{}, PoBad{ErrBad{}}}
4464
4465def pc.eof(st: Rb) -> Pc:
4466  pc.end(rb.eof(st))
4467
4468def stream.mk(+tls: Bool, s: Socket, +ms: U32, res: Res, decs: List<&1, Zlib.Decoder>, pc: Pc) -> Stream:
4469  Pc{rb, out} = pc
4470  Stream{tls, s, ms, res, rb, out, decs}
4471
4472def stream.got.piece(+tls: Bool, s: Socket, +ms: U32, res: Res, decs: List<&1, Zlib.Decoder>, +rb: Rb, p: U32 & Array<U32>) -> Stream:
4473  (+len, buf) = p
4474  stream.mk(tls, s, ms, res, decs, Bool.pick(Pc, U32.is_zero(len), pc.eof(rb), pc.of(rb, Bytes.Bytes{len, buf})))
4475
4476def 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:
4477  (s, r) = m
4478  match r:
4479    case Fail{(+code, why)}:
4480      Stream{tls, s, ms, res, RbDone{}, PoBad{err.or_late(code, ErrRead{code, why})}, decs}
4481    case Done{p}:
4482      stream.got.piece(tls, s, ms, res, decs, rb, p)
4483
4484def stream.after(+rb: Rb) -> Po:
4485  match rb:
4486    case RbDone{}:
4487      PoEnd{}
4488    case RbBad{}:
4489      PoEnd{}
4490    case RbLen{n}:
4491      PoNone{}
4492    case RbChunk{st}:
4493      PoNone{}
4494    case RbClose{}:
4495      PoNone{}
4496
4497type Fed is Type:
4498  Fed{decs: List<&1, Zlib.Decoder>, body: Result<&1, &1, Err, Bytes.Bytes>}
4499
4500def stream.feed.received(done: List<&1, Zlib.Decoder>, m: Zlib.Decoder & Result<&1, &1, U32 & String, U32 & Array<U32>>) -> Fed:
4501  (d, r) = m
4502  match r:
4503    case Fail{e}:
4504      Fed{d <> done, Fail{ErrBad{}}}
4505    case Done{(+len, buf)}:
4506      Fed{d <> done, Done{Bytes.Bytes{len, buf}}}
4507
4508def stream.feed.step(st: Fed, d: Zlib.Decoder) -> IO(Fed):
4509  Fed{done, body} = st
4510  match body:
4511    case Fail{e}:
4512      IO.pure(Fed, Fed{d <> done, Fail{e}})
4513    case Done{b}:
4514      Bytes.Bytes{+len, buf} = b
4515      do IO<Fed>:
4516        m : Zlib.Decoder & Result<&1, &1, U32 & String, U32 & Array<U32>> <-
4517          Zlib.dec.feed.words(d, 16777216, len, buf)
4518        return stream.feed.received(done, m)
4519
4520def stream.feed.one(prev: IO(Fed), d: Zlib.Decoder) -> IO(Fed):
4521  do IO<Fed>:
4522    st : Fed <- prev
4523    stream.feed.step(st, d)
4524
4525def stream.feed.reverse(st: Fed) -> Fed:
4526  Fed{done, body} = st
4527  Fed{List.reverse(&1, Zlib.Decoder, done), body}
4528
4529def stream.feed.all(decs: List<&1, Zlib.Decoder>, b: Bytes.Bytes) -> IO(Fed):
4530  do IO<Fed>:
4531    st : Fed <- List.foldl(~&1, ~Zlib.Decoder, ~IO(Fed), ~stream.feed.one, decs,
4532      IO.pure(Fed, Fed{Nil{}, Done{b}}))
4533    return stream.feed.reverse(st)
4534
4535def stream.ready(empty: Bool, +rb: Rb, b: Bytes.Bytes) -> Po:
4536  match empty:
4537    case True{}:
4538      stream.after(rb)
4539    case False{}:
4540      PoReady{b}
4541
4542def stream.feed.got(+tls: Bool, s: Socket, +ms: U32, res: Res, +rb: Rb, st: Fed) -> Stream:
4543  Fed{decs, body} = st
4544  match body:
4545    case Fail{e}:
4546      Stream{tls, s, ms, res, rb, PoBad{e}, decs}
4547    case Done{b}:
4548      Bytes.Bytes{+len, buf} = b
4549      Stream{tls, s, ms, res, rb, stream.ready(U32.is_zero(len), rb, Bytes.Bytes{len, buf}), decs}
4550
4551def stream.feed.st(st: Stream, b: Bytes.Bytes) -> IO(Stream):
4552  Stream{+tls, s, +ms, res, +rb, out, decs} = st
4553  match decs:
4554    case Nil{}:
4555      IO.pure(Stream, Stream{tls, s, ms, res, rb, PoReady{b}, Nil{}})
4556    case Con{d, rest}:
4557      do IO<Stream>:
4558        fed : Fed <- stream.feed.all(Con{d, rest}, b)
4559        return stream.feed.got(tls, s, ms, res, rb, fed)
4560
4561def stream.finish.ok(r: Result<&1, &1, U32 & String, Unit>) -> Bool:
4562  match r:
4563    case Fail{e}:
4564      False{}
4565    case Done{u}:
4566      True{}
4567
4568def stream.finish(decs: List<&1, Zlib.Decoder>) -> IO(Bool):
4569  match decs:
4570    case Nil{}:
4571      IO.pure(Bool, True{})
4572    case Con{d, rest}:
4573      do IO<Bool>:
4574        r : Result<&1, &1, U32 & String, Unit> <- Zlib.dec.finish(d)
4575        tail : Bool <- stream.finish(rest)
4576        return Bool.and(stream.finish.ok(r), tail)
4577
4578def stream.ended(good: Bool, +tls: Bool, s: Socket, +ms: U32, res: Res, +rb: Rb) ->
4579  Stream & Result<&1, &1, Err, Maybe<&1, Bytes.Bytes>>:
4580  match good:
4581    case True{}:
4582      (Stream{tls, s, ms, res, rb, PoEnd{}, Nil{}}, Done{None{}})
4583    case False{}:
4584      (Stream{tls, s, ms, res, rb, PoBad{ErrBad{}}, Nil{}}, Fail{ErrBad{}})
4585
4586# The next piece of the body; None at the end. A piece is never empty.
4587@unsafe
4588def stream.read(st: Stream) -> IO(Stream & Result<&1, &1, Err, Maybe<&1, Bytes.Bytes>>):
4589  Stream{+tls, s, +ms, res, +rb, out, decs} = st
4590  match out:
4591    case PoPiece{b}:
4592      do IO<Stream & Result<&1, &1, Err, Maybe<&1, Bytes.Bytes>>>:
4593        next : Stream <- stream.feed.st(Stream{tls, s, ms, res, rb, PoNone{}, decs}, b)
4594        stream.read(next)
4595    case PoReady{b}:
4596      IO.pure(Stream & Result<&1, &1, Err, Maybe<&1, Bytes.Bytes>>,
4597        (Stream{tls, s, ms, res, rb, stream.after(rb), decs}, Done{Some{b}}))
4598    case PoEnd{}:
4599      do IO<Stream & Result<&1, &1, Err, Maybe<&1, Bytes.Bytes>>>:
4600        good : Bool <- stream.finish(decs)
4601        return stream.ended(good, tls, s, ms, res, rb)
4602    case PoBad{+e}:
4603      IO.pure(Stream & Result<&1, &1, Err, Maybe<&1, Bytes.Bytes>>,
4604        (Stream{tls, s, ms, res, rb, PoBad{e}, decs}, Fail{e}))
4605    case PoNone{}:
4606      do IO<Stream & Result<&1, &1, Err, Maybe<&1, Bytes.Bytes>>>:
4607        m : Socket & Result<&1, &1, U32 & String, U32 & Array<U32>> <- io.recv.words(tls, s, 65536, ms)
4608        stream.read(stream.got(tls, ms, res, decs, rb, m))
4609
4610# Status and headers. Its body is empty: read the body with stream.read.
4611def stream.res(st: Stream) -> Stream & Res:
4612  Stream{tls, s, ms, res, rb, out, decs} = st
4613  Res{+status, +headers, body} = res
4614  (Stream{tls, s, ms, Res{status, headers, body}, rb, out, decs}, Res{status, headers, Bytes.new(0)})
4615
4616def stream.close(st: Stream) -> IO(Unit):
4617  Stream{tls, s, ms, res, rb, out, decs} = st
4618  do IO<Unit>:
4619    good : Bool <- stream.finish(decs)
4620    io.close(tls, s)
4621
4622# Head read state: still scanning, cut short or bad, or the head with the bytes after it.
4623type Sh is Type:
4624  ShMore{buf: Bytes.Bytes, k: U32}
4625  ShBad{err: Maybe<&2, Err>}
4626  ShRes{res: Res, rb: Rb, rest: Bytes.Bytes}
4627
4628def sh.of(hs: Hs) -> Sh:
4629  match hs:
4630    case HsWait{buf, k}:
4631      ShMore{buf, k}
4632    case HsBad{}:
4633      ShBad{None{}}
4634    case HsSeek{buf, from, k}:
4635      ShBad{None{}}
4636    case HsRes{res, rb, rest}:
4637      ShRes{res, rb, rest}
4638
4639def sh.piece(+head: Bool, buf: Bytes.Bytes, +k: U32, p: U32 & Array<U32>) -> Sh:
4640  (+len, b) = p
4641  Bool.pick(Sh, U32.is_zero(len), ShBad{None{}}, sh.of(hs.more(head, k, buf, Bytes.Bytes{len, b})))
4642
4643def sh.next(+head: Bool, buf: Bytes.Bytes, +k: U32, m: Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>) -> Socket & Sh:
4644  (s, r) = m
4645  match r:
4646    case Fail{(+code, why)}:
4647      (s, ShBad{Some{err.or_late(code, ErrRead{code, why})}})
4648    case Done{p}:
4649      (s, sh.piece(head, buf, k, p))
4650
4651def fetch.fail.of(r: Result<&1, &1, Err, Res>) -> Result<&1, &1, Err, Stream>:
4652  match r:
4653    case Fail{e}:
4654      Fail{e}
4655    case Done{res}:
4656      Fail{ErrBad{}}
4657
4658# Reads until the final head is in; the body bytes that came with it are the first piece.
4659@unsafe
4660def stream.head(+tls: Bool, +ms: U32, +head: Bool, st: Socket & Sh) -> IO(Result<&1, &1, Err, Stream>):
4661  (s, sh) = st
4662  match sh:
4663    case ShMore{buf, +k}:
4664      do IO<Result<&1, &1, Err, Stream>>:
4665        m : Socket & Result<&1, &1, U32 & String, U32 & Array<U32>> <- io.recv.words(tls, s, 65536, ms)
4666        stream.head(tls, ms, head, sh.next(head, buf, k, m))
4667    case ShBad{err}:
4668      do IO<Result<&1, &1, Err, Stream>>:
4669        r : Result<&1, &1, Err, Res> <- fetch.bad(tls, s, err)
4670        return fetch.fail.of(r)
4671    case ShRes{res, rb, rest}:
4672      IO.pure(Result<&1, &1, Err, Stream>, Done{stream.mk(tls, s, ms, res, Nil{}, pc.of(rb, rest))})
4673
4674def stream.sent(+tls: Bool, +ms: U32, +head: Bool, m: Socket & Result<&1, &1, U32 & String, Unit>) -> IO(Result<&1, &1, Err, Stream>):
4675  (s, r) = m
4676  match r:
4677    case Fail{(+code, why)}:
4678      do IO<Result<&1, &1, Err, Stream>>:
4679        io.close(tls, s)
4680        return Fail{err.or_late(code, ErrWrite{code, why})}
4681    case Done{u}:
4682      stream.head(tls, ms, head, (s, ShMore{Bytes.new(0), 0}))
4683
4684def stream.conn(r: Result<&1, &1, Err, Conn>, +ms: U32, +head: Bool, wire: Bytes.Bytes) -> IO(Result<&1, &1, Err, Stream>):
4685  match r:
4686    case Fail{e}:
4687      IO.pure(Result<&1, &1, Err, Stream>, Fail{e})
4688    case Done{c}:
4689      match c:
4690        case Conn{+tls, s}:
4691          do IO<Result<&1, &1, Err, Stream>>:
4692            sent : Socket & Result<&1, &1, U32 & String, Unit> <- io.send.bytes(tls, s, wire)
4693            stream.sent(tls, ms, head, sent)
4694        case ConnH2{s, client}:
4695          do IO<Result<&1, &1, Err, Stream>>:
4696            Wire.tls.close(s)
4697            return Fail{ErrBad{}}
4698
4699# One connection per stream; the request says close.
4700def stream.origin(+ms: U32, +head: Bool, wire: Bytes.Bytes, a: Url.Abs, known: Bool) -> IO(Result<&1, &1, Err, Stream>):
4701  Url.Abs{+scheme, +host, +port, target} = a
4702  match known:
4703    case False{}:
4704      IO.pure(Result<&1, &1, Err, Stream>, Fail{ErrUrl{}})
4705    case True{}:
4706      do IO<Result<&1, &1, Err, Stream>>:
4707        ips : List<&2, String> <- Dns.resolve.all(host)
4708        c : Result<&1, &1, Err, Conn> <- conn.open.all(String.eq(scheme, "https"), ms, host, port, ips, None{}, False{})
4709        stream.conn(c, ms, head, wire)
4710
4711def 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>):
4712  Url.Abs{scheme, host, port, +target} = url
4713  (body, wire) = r
4714  do IO<Hop & Result<&1, &1, Err, Stream>>:
4715    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))
4716    return (Hop{method, url, headers, body}, got)
4717
4718# One request on its own connection. The hop comes back for the redirect.
4719def stream.one(h: Hop, +ms: U32) -> IO(Hop & Result<&1, &1, Err, Stream>):
4720  Hop{+method, +url, +headers, body} = h
4721  stream.one.of(method, url, headers, ms, Bytes.slice(body, 0, 4294967295))
4722
4723# Go: the next request. Drop: close this stream, then go on. Done: the answer.
4724type Sn is Type:
4725  SnGo{left: Nat, hop: Hop}
4726  SnDrop{st: Stream, next: Next}
4727  SnDone{r: Result<&1, &1, Err, Stream>}
4728
4729def sn.of(n: Next) -> Sn:
4730  match n:
4731    case NGo{l, h}:
4732      SnGo{l, h}
4733    case NStop{}:
4734      SnDone{Fail{ErrRedirect{}}}
4735    case NDone{m}:
4736      match m:
4737        case Fail{e}:
4738          SnDone{Fail{e}}
4739        case Done{r}:
4740          SnDone{Fail{ErrBad{}}}
4741
4742def stream.decide.n(st: Stream, n: Next) -> Sn:
4743  match n:
4744    case NDone{m}:
4745      SnDone{Done{st}}
4746    case NGo{l, h}:
4747      SnDrop{st, NGo{l, h}}
4748    case NStop{}:
4749      SnDrop{st, NStop{}}
4750
4751def stream.decide.of(+left: Nat, hop: Hop, sr: Stream & Res) -> Sn:
4752  (st, res) = sr
4753  stream.decide.n(st, fetch.decide(left, hop, Done{res}))
4754
4755def stream.decide(+left: Nat, x: Hop & Result<&1, &1, Err, Stream>) -> Sn:
4756  (hop, r) = x
4757  match r:
4758    case Fail{e}:
4759      SnDone{Fail{e}}
4760    case Done{st}:
4761      stream.decide.of(left, hop, stream.res(st))
4762
4763@unsafe
4764def stream.hops(+ms: U32, sn: Sn) -> IO(Result<&1, &1, Err, Stream>):
4765  match sn:
4766    case SnDone{r}:
4767      IO.pure(Result<&1, &1, Err, Stream>, r)
4768    case SnGo{+left, hop}:
4769      do IO<Result<&1, &1, Err, Stream>>:
4770        x : Hop & Result<&1, &1, Err, Stream> <- stream.one(hop, ms)
4771        stream.hops(ms, stream.decide(left, x))
4772    case SnDrop{st, next}:
4773      do IO<Result<&1, &1, Err, Stream>>:
4774        stream.close(st)
4775        stream.hops(ms, sn.of(next))
4776
4777type Opened is Type:
4778  Opened{decs: List<&1, Zlib.Decoder>, bad: Bool}
4779
4780def stream.open.got(st: Opened, r: Result<&1, &1, U32 & String, Zlib.Decoder>) -> Opened:
4781  Opened{decs, bad} = st
4782  match r:
4783    case Fail{e}:
4784      Opened{decs, True{}}
4785    case Done{d}:
4786      Opened{d <> decs, bad}
4787
4788def stream.open.add(st: Opened, m: IO(Result<&1, &1, U32 & String, Zlib.Decoder>)) -> IO(Opened):
4789  do IO<Opened>:
4790    r : Result<&1, &1, U32 & String, Zlib.Decoder> <- m
4791    return stream.open.got(st, r)
4792
4793def stream.open.zstd(zstd: Bool, st: Opened) -> IO(Opened):
4794  match zstd:
4795    case True{}:
4796      stream.open.add(st, Zlib.zstd.new())
4797    case False{}:
4798      IO.pure(Opened, st)
4799
4800def stream.open.br(br: Bool, +c: String, st: Opened) -> IO(Opened):
4801  match br:
4802    case True{}:
4803      stream.open.add(st, Zlib.brotli.new())
4804    case False{}:
4805      stream.open.zstd(String.eq(c, "zstd"), st)
4806
4807def stream.open.gz(gz: Bool, +c: String, st: Opened) -> IO(Opened):
4808  match gz:
4809    case True{}:
4810      stream.open.add(st, Zlib.inflate.new())
4811    case False{}:
4812      stream.open.br(String.eq(c, "br"), c, st)
4813
4814def stream.open.step(+c: String, st: Opened) -> IO(Opened):
4815  Opened{decs, bad} = st
4816  match bad:
4817    case True{}:
4818      IO.pure(Opened, Opened{decs, True{}})
4819    case False{}:
4820      stream.open.gz(Bool.or(String.eq(c, "gzip"), Bool.or(String.eq(c, "x-gzip"), String.eq(c, "deflate"))),
4821        c, Opened{decs, False{}})
4822
4823def stream.open.one(prev: IO(Opened), c: String) -> IO(Opened):
4824  do IO<Opened>:
4825    st : Opened <- prev
4826    stream.open.step(c, st)
4827
4828def stream.open.all(cs: List<&2, String>) -> IO(Opened):
4829  List.foldl(~&2, ~String, ~IO(Opened), ~stream.open.one, cs, IO.pure(Opened, Opened{Nil{}, False{}}))
4830
4831def stream.put.decs(st: Stream, decs: List<&1, Zlib.Decoder>) -> Stream:
4832  Stream{tls, s, ms, res, rb, out, old} = st
4833  Stream{tls, s, ms, res, rb, out, decs}
4834
4835def stream.init.opened(st: Stream, opened: Opened) -> IO(Result<&1, &1, Err, Stream>):
4836  Opened{decs, bad} = opened
4837  match bad:
4838    case True{}:
4839      do IO<Result<&1, &1, Err, Stream>>:
4840        stream.close(stream.put.decs(st, decs))
4841        return Fail{ErrBad{}}
4842    case False{}:
4843      IO.pure(Result<&1, &1, Err, Stream>, Done{stream.put.decs(st, List.reverse(&1, Zlib.Decoder, decs))})
4844
4845def stream.init.known(known: Bool, st: Stream, cs: List<&2, String>) -> IO(Result<&1, &1, Err, Stream>):
4846  match known:
4847    case False{}:
4848      IO.pure(Result<&1, &1, Err, Stream>, Done{st})
4849    case True{}:
4850      do IO<Result<&1, &1, Err, Stream>>:
4851        opened : Opened <- stream.open.all(cs)
4852        stream.init.opened(st, opened)
4853
4854def stream.init.st(+enc: String, st: Stream) -> IO(Result<&1, &1, Err, Stream>):
4855  Stream{tls, s, ms, res, rb, out, decs} = st
4856  Res{+status, +headers, body} = res
4857  +cs = List.reverse(&2, String, ce.split(fields(headers, "content-encoding")))
4858  stream.init.known(ce.known(cs, Con{"identity", Con{"x-gzip", ce.split(Con{enc, Nil{}})}}),
4859    Stream{tls, s, ms, Res{status, headers, body}, rb, out, decs}, cs)
4860
4861def stream.init(+enc: String, r: Result<&1, &1, Err, Stream>) -> IO(Result<&1, &1, Err, Stream>):
4862  match r:
4863    case Fail{e}:
4864      IO.pure(Result<&1, &1, Err, Stream>, Fail{e})
4865    case Done{st}:
4866      stream.init.st(enc, st)
4867
4868def stream.start(method: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, u: Maybe<&2, Url.Abs>) -> Sn:
4869  match u:
4870    case None{}:
4871      SnDone{Fail{ErrUrl{}}}
4872    case Some{a}:
4873      SnGo{20n, Hop{method, a, req.put(Map.to_list(&2, List<&2, String>, headers), empty()), body}}
4874
4875# Open a raw stream. Its body bytes and headers remain as sent.
4876def open.raw.with(method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, +ms: U32) -> IO(Result<&1, &1, Err, Stream>):
4877  stream.hops(ms, stream.start(method, headers, body, Url.absolute(url)))
4878
4879def open.raw(method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Result<&1, &1, Err, Stream>):
4880  open.raw.with(method, url, headers, body, 30000)
4881
4882def 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>):
4883  do IO<Result<&1, &1, Err, Stream>>:
4884    r : Result<&1, &1, Err, Stream> <-
4885      stream.hops(ms, stream.start(method, accept.enc(headers, enc), body, Url.absolute(url)))
4886    stream.init(enc, r)
4887
4888# Follow redirects, then decode each body piece by Content-Encoding. Unknown codings stay raw.
4889def open.with(method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes, +ms: U32) -> IO(Result<&1, &1, Err, Stream>):
4890  do IO<Result<&1, &1, Err, Stream>>:
4891    enc : String <- codings()
4892    open.with.enc(enc, method, url, headers, body, ms)
4893
4894def open(method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Result<&1, &1, Err, Stream>):
4895  open.with(method, url, headers, body, 30000)
4896
4897# Upload: the request body sent in chunks (RFC 9112 §7.1). err: the first failed write.
4898type Up is Type:
4899  Up{tls: Bool, s: Socket, ms: U32, head: Bool, err: Maybe<&2, Err>}
4900
4901def hex.digit(+n: U32) -> Char:
4902  Chr{Bool.pick(U32, U32.is_lt(n, 10), (48 + n : U32), (87 + n : U32))}
4903
4904def hex.go(k: Nat, +n: U32, acc: String) -> String:
4905  match k:
4906    case 0n:
4907      acc
4908    case 1n+p:
4909      hex.go(p, U32.shrn(n, 4n), SCon{hex.digit(U32.and(n, 15)), acc})
4910
4911def hex.trim(+s: String) -> String:
4912  match s:
4913    case SNil{}:
4914      SNil{}
4915    case SCon{Chr{+c}, +t}:
4916      Bool.pick(String, Bool.and(U32.is_eq(c, 48), Bool.not(String.is_empty(t))), hex.trim(t), SCon{Chr{c}, t})
4917
4918def hex(+n: U32) -> String:
4919  hex.trim(hex.go(8n, n, ""))
4920
4921def up.sent(+tls: Bool, +ms: U32, +head: Bool, m: Socket & Result<&1, &1, U32 & String, Unit>) -> Up:
4922  (s, r) = m
4923  match r:
4924    case Fail{(+code, why)}:
4925      Up{tls, s, ms, head, Some{err.or_late(code, ErrWrite{code, why})}}
4926    case Done{u}:
4927      Up{tls, s, ms, head, None{}}
4928
4929def up.conn(r: Result<&1, &1, Err, Conn>, +ms: U32, +head: Bool, wire: String) -> IO(Result<&1, &1, Err, Up>):
4930  match r:
4931    case Fail{e}:
4932      IO.pure(Result<&1, &1, Err, Up>, Fail{e})
4933    case Done{c}:
4934      match c:
4935        case Conn{+tls, s}:
4936          do IO<Result<&1, &1, Err, Up>>:
4937            sent : Socket & Result<&1, &1, U32 & String, Unit> <- io.send(tls, s, wire)
4938            return Done{up.sent(tls, ms, head, sent)}
4939        case ConnH2{s, client}:
4940          do IO<Result<&1, &1, Err, Up>>:
4941            Wire.tls.close(s)
4942            return Fail{ErrBad{}}
4943
4944def up.head(+method: String, +target: String, +hf: String, +headers: Map<&2, List<&2, String>>) -> String:
4945  request(method, target, set(set(set(req.put(Map.to_list(&2, List<&2, String>, headers), empty()), "host", hf), "connection", "close"), "transfer-encoding", "chunked"), "")
4946
4947def up.origin(+method: String, +ms: U32, headers: Map<&2, List<&2, String>>, a: Url.Abs, known: Bool) -> IO(Result<&1, &1, Err, Up>):
4948  Url.Abs{+scheme, +host, +port, +target} = a
4949  match known:
4950    case False{}:
4951      IO.pure(Result<&1, &1, Err, Up>, Fail{ErrUrl{}})
4952    case True{}:
4953      do IO<Result<&1, &1, Err, Up>>:
4954        ips : List<&2, String> <- Dns.resolve.all(host)
4955        c : Result<&1, &1, Err, Conn> <- conn.open.all(String.eq(scheme, "https"), ms, host, port, ips, None{}, False{})
4956        up.conn(c, ms, String.eq(method, "HEAD"), up.head(method, target, Url.host_field(a), headers))
4957
4958def up.url(+method: String, +ms: U32, headers: Map<&2, List<&2, String>>, u: Maybe<&2, Url.Abs>) -> IO(Result<&1, &1, Err, Up>):
4959  match u:
4960    case None{}:
4961      IO.pure(Result<&1, &1, Err, Up>, Fail{ErrUrl{}})
4962    case Some{+a}:
4963      up.origin(method, ms, headers, a, pool.scheme.ok(a))
4964
4965# Http.upload(method, url, headers) sends the head. A streamed body cannot be replayed, so redirects are not followed.
4966def upload.with(+method: String, url: String, headers: Map<&2, List<&2, String>>, +ms: U32) -> IO(Result<&1, &1, Err, Up>):
4967  up.url(method, ms, headers, Url.absolute(url))
4968
4969def upload(+method: String, url: String, headers: Map<&2, List<&2, String>>) -> IO(Result<&1, &1, Err, Up>):
4970  upload.with(method, url, headers, 30000)
4971
4972def up.wrote(+tls: Bool, +ms: U32, +head: Bool, m: Socket & Result<&1, &1, U32 & String, Unit>) -> Up & Result<&2, &2, Err, Unit>:
4973  (s, r) = m
4974  match r:
4975    case Fail{(+code, why)}:
4976      +e = err.or_late(code, ErrWrite{code, why})
4977      (Up{tls, s, ms, head, Some{e}}, Fail{e})
4978    case Done{u}:
4979      (Up{tls, s, ms, head, None{}}, Done{Unit{}})
4980
4981# One write per chunk, so the size line and the data do not wait on each other (Nagle).
4982def up.put(+tls: Bool, s: Socket, +ms: U32, +head: Bool, +len: U32, piece: Bytes.Bytes, skip: Bool) -> IO(Up & Result<&2, &2, Err, Unit>):
4983  match skip:
4984    case True{}:
4985      IO.pure(Up & Result<&2, &2, Err, Unit>, (Up{tls, s, ms, head, None{}}, Done{Unit{}}))
4986    case False{}:
4987      do IO<Up & Result<&2, &2, Err, Unit>>:
4988        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{}}}}))
4989        return up.wrote(tls, ms, head, sent)
4990
4991def up.chunk(+tls: Bool, s: Socket, +ms: U32, +head: Bool, piece: Bytes.Bytes) -> IO(Up & Result<&2, &2, Err, Unit>):
4992  Bytes.Bytes{+len, buf} = piece
4993  up.put(tls, s, ms, head, len, Bytes.Bytes{len, buf}, U32.is_zero(len))
4994
4995# One chunk. An empty piece sends nothing, since an empty chunk would end the body.
4996def upload.write(up: Up, piece: Bytes.Bytes) -> IO(Up & Result<&2, &2, Err, Unit>):
4997  Up{+tls, s, +ms, +head, err} = up
4998  match err:
4999    case Some{+e}:
5000      IO.pure(Up & Result<&2, &2, Err, Unit>, (Up{tls, s, ms, head, Some{e}}, Fail{e}))
5001    case None{}:
5002      up.chunk(tls, s, ms, head, piece)
5003
5004# Ends the body and returns the response as a stream.
5005def upload.finish(up: Up) -> IO(Result<&1, &1, Err, Stream>):
5006  Up{+tls, s, +ms, +head, err} = up
5007  match err:
5008    case Some{e}:
5009      do IO<Result<&1, &1, Err, Stream>>:
5010        io.close(tls, s)
5011        return Fail{e}
5012    case None{}:
5013      do IO<Result<&1, &1, Err, Stream>>:
5014        sent : Socket & Result<&1, &1, U32 & String, Unit> <- io.send(tls, s, "0\r\n\r\n")
5015        stream.sent(tls, ms, head, sent)
5016
5017def reply.bytes(res: Res, head: Bool, close: Bool) -> Bytes.Bytes:
5018  Res{+status, +headers, body} = res
5019  encode.on(Res{status, Bool.pick(Map<&2, List<&2, String>>, close, set(headers, "connection", "close"), headers), body}, head)
5020
5021def reply.fail.bytes(+status: U32) -> Res:
5022  Res{status, empty(), Bytes.from_string(reason(status))}
5023
5024def reply.sent.close(m: Socket & Result<&1, &1, U32 & String, Unit>) -> IO(Unit):
5025  (s, r) = m
5026  Socket.close(s)
5027
5028def reply_fail(s: Socket, +status: U32) -> IO(Unit):
5029  do IO<Unit>:
5030    sent : Socket & Result<&1, &1, U32 & String, Unit> <- io.send.bytes(False{}, s, encode(reply.fail.bytes(status)))
5031    reply.sent.close(sent)
5032
5033
5034# The head is parsed once, when it is whole. Body pieces are kept as they come and joined once.
5035type Sv is Type:
5036  SvHead{buf: Bytes.Bytes}
5037  SvLen{req: Req, v11: Bool, left: U32, parts: List<&1, Bytes.Bytes>}
5038  SvChunk{req: Req, v11: Bool, n: U32, st: Dc, parts: List<&1, Bytes.Bytes>}
5039
5040# More: read on, first answering 100 Continue when cont is set.
5041type Turn is Type:
5042  TurnClose{}
5043  TurnFail{status: U32}
5044  TurnReq{req: Req, rest: Bytes.Bytes, v11: Bool}
5045  TurnMore{sv: Sv, cont: Bool}
5046
5047def serve.max() -> Nat:
5048  fetch.max()
5049
5050def sv.none() -> Sv:
5051  SvHead{Bytes.new(0)}
5052
5053def sv.body(req: Req, +v11: Bool, parts: List<&1, Bytes.Bytes>, rest: Bytes.Bytes) -> Turn:
5054  Req{method, path, headers, body} = req
5055  TurnReq{Req{method, path, headers, rb.body(parts)}, rest, v11}
5056
5057def sv.len.cut(req: Req, +v11: Bool, parts: List<&1, Bytes.Bytes>, +len: U32, +left: U32, r: Bytes.Bytes & Bytes.Bytes) -> Turn:
5058  (piece, last) = r
5059  sv.body(req, v11, Con{last, parts}, bytes.snd(Bytes.slice(piece, left, (len - left : U32))))
5060
5061def sv.len.have(short: Bool, req: Req, +v11: Bool, +left: U32, parts: List<&1, Bytes.Bytes>, +len: U32, piece: Bytes.Bytes) -> Turn:
5062  match short:
5063    case True{}:
5064      TurnMore{SvLen{req, v11, (left - len : U32), Con{piece, parts}}, False{}}
5065    case False{}:
5066      sv.len.cut(req, v11, parts, len, left, Bytes.slice(piece, 0, left))
5067
5068def sv.len(req: Req, +v11: Bool, +left: U32, parts: List<&1, Bytes.Bytes>, piece: Bytes.Bytes) -> Turn:
5069  Bytes.Bytes{+len, buf} = piece
5070  sv.len.have(U32.is_lt(len, left), req, v11, left, parts, len, Bytes.Bytes{len, buf})
5071
5072def sv.chunk.of(req: Req, +v11: Bool, +n: U32, c: Ck) -> Turn:
5073  Ck{st, parts, rest} = c
5074  match st:
5075    case DcDone{}:
5076      sv.body(req, v11, parts, rest)
5077    case DcBad{}:
5078      TurnFail{400}
5079    case DcSize{a, b}:
5080      TurnMore{SvChunk{req, v11, n, DcSize{a, b}, parts}, False{}}
5081    case DcExt{x}:
5082      TurnMore{SvChunk{req, v11, n, DcExt{x}, parts}, False{}}
5083    case DcSizeLf{x}:
5084      TurnMore{SvChunk{req, v11, n, DcSizeLf{x}, parts}, False{}}
5085    case DcData{k}:
5086      TurnMore{SvChunk{req, v11, n, DcData{k}, parts}, False{}}
5087    case DcDataCr{}:
5088      TurnMore{SvChunk{req, v11, n, DcDataCr{}, parts}, False{}}
5089    case DcDataLf{}:
5090      TurnMore{SvChunk{req, v11, n, DcDataLf{}, parts}, False{}}
5091    case DcTr{j}:
5092      TurnMore{SvChunk{req, v11, n, DcTr{j}, parts}, False{}}
5093
5094def sv.chunk.cap(big: Bool, req: Req, +v11: Bool, +n: U32, st: Dc, parts: List<&1, Bytes.Bytes>, piece: Bytes.Bytes) -> Turn:
5095  match big:
5096    case True{}:
5097      TurnFail{413}
5098    case False{}:
5099      sv.chunk.of(req, v11, n, ck(piece, st, parts))
5100
5101def sv.chunk(+max: Nat, req: Req, +v11: Bool, +n: U32, st: Dc, parts: List<&1, Bytes.Bytes>, piece: Bytes.Bytes) -> Turn:
5102  Bytes.Bytes{+len, buf} = piece
5103  +n2 = (n + len : U32)
5104  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})
5105
5106# RFC 9110 §10.1.1: answer 100 Continue only when the body is still to come.
5107def sv.cont(want: Bool, t: Turn) -> Turn:
5108  match t:
5109    case TurnMore{sv, c}:
5110      TurnMore{sv, want}
5111    case TurnClose{}:
5112      TurnClose{}
5113    case TurnFail{s}:
5114      TurnFail{s}
5115    case TurnReq{req, rest, v11}:
5116      TurnReq{req, rest, v11}
5117
5118def sv.cl.k(big: Bool, req: Req, +v11: Bool, +k: U32, rest: Bytes.Bytes) -> Turn:
5119  match big:
5120    case True{}:
5121      TurnFail{413}
5122    case False{}:
5123      sv.len(req, v11, k, Nil{}, rest)
5124
5125def sv.cl(+max: Nat, req: Req, +v11: Bool, rest: Bytes.Bytes, n: Maybe<&2, U32>) -> Turn:
5126  match n:
5127    case None{}:
5128      TurnFail{400}
5129    case Some{+k}:
5130      sv.cl.k(Nat.is_lt(max, U32.to_nat(k)), req, v11, k, rest)
5131
5132def sv.frame(+max: Nat, req: Req, +v11: Bool, rest: Bytes.Bytes, te: Bool) -> Turn:
5133  Req{method, path, +headers, body} = req
5134  match te:
5135    case True{}:
5136      sv.chunk(max, Req{method, path, headers, body}, v11, 0, dc.start(), Nil{}, rest)
5137    case False{}:
5138      sv.cl(max, Req{method, path, headers, body}, v11, rest, parse_u32(header(headers, "content-length")))
5139
5140def sv.expects(+v11: Bool, +headers: Map<&2, List<&2, String>>) -> Bool:
5141  Bool.and(v11, String.eq(String.to_lower(header(headers, "expect")), "100-continue"))
5142
5143def sv.got.head(+max: Nat, +v11: Bool, rest: Bytes.Bytes, req: Req) -> Turn:
5144  Req{method, path, +headers, body} = req
5145  sv.cont(sv.expects(v11, headers), sv.frame(max, Req{method, path, headers, body}, v11, rest, has_header(headers, "transfer-encoding")))
5146
5147def sv.parsed(+max: Nat, +v11: Bool, rest: Bytes.Bytes, g: Got) -> Turn:
5148  match g:
5149    case GotBad{}:
5150      TurnFail{400}
5151    case GotMore{}:
5152      TurnFail{400}
5153    case GotReq{req}:
5154      TurnReq{req, rest, v11}
5155    case GotHead{req}:
5156      sv.got.head(max, v11, rest, req)
5157
5158def sv.split(+max: Nat, +hlen: U32, +len: U32, r: Bytes.Bytes & Bytes.Bytes) -> Turn:
5159  (buf, hb) = r
5160  +head = Bytes.to_string(hb)
5161  sv.parsed(max, req.v11(head), bytes.snd(Bytes.slice(buf, hlen, (len - hlen : U32))), parse.got(head))
5162
5163def sv.hit.none(big: Bool, buf: Bytes.Bytes) -> Turn:
5164  match big:
5165    case True{}:
5166      TurnFail{431}
5167    case False{}:
5168      TurnMore{SvHead{buf}, False{}}
5169
5170def sv.hit.some(big: Bool, +max: Nat, +hlen: U32, +len: U32, buf: Bytes.Bytes) -> Turn:
5171  match big:
5172    case True{}:
5173      TurnFail{431}
5174    case False{}:
5175      sv.split(max, hlen, len, Bytes.slice(buf, 0, hlen))
5176
5177# RFC 6585 §5: a head over 64 KiB is refused.
5178def sv.hit(+max: Nat, +len: U32, buf: Bytes.Bytes, at: Maybe<&2, U32>) -> Turn:
5179  match at:
5180    case None{}:
5181      sv.hit.none(U32.is_lt(65536, len), buf)
5182    case Some{+i}:
5183      +hlen = (i + 4 : U32)
5184      sv.hit.some(U32.is_lt(65536, hlen), max, hlen, len, buf)
5185
5186def sv.seek.of(+max: Nat, +len: U32, +from: U32, buf: Bytes.Bytes, r: Bytes.Bytes & Maybe<&2, U32>) -> Turn:
5187  (tail, m) = r
5188  sv.hit(max, len, buf, found.at(from, m))
5189
5190def sv.seek(+max: Nat, +len: U32, +from: U32, r: Bytes.Bytes & Bytes.Bytes) -> Turn:
5191  (buf, tail) = r
5192  sv.seek.of(max, len, from, buf, Bytes.find(tail, "\r\n\r\n"))
5193
5194# Only the new bytes, and the 3 before them, can finish the blank line.
5195def sv.head.at(+max: Nat, +from: U32, buf: Bytes.Bytes) -> Turn:
5196  Bytes.Bytes{+len, b} = buf
5197  sv.seek(max, len, from, Bytes.slice(Bytes.Bytes{len, b}, from, (len - from : U32)))
5198
5199def sv.head(+max: Nat, buf: Bytes.Bytes, piece: Bytes.Bytes) -> Turn:
5200  Bytes.Bytes{+ol, ob} = buf
5201  sv.head.at(max, Bool.pick(U32, U32.is_lt(ol, 3), 0, (ol - 3 : U32)), Bytes.append(Bytes.Bytes{ol, ob}, piece))
5202
5203def sv.closed.pick(empty: Bool) -> Turn:
5204  match empty:
5205    case True{}:
5206      TurnClose{}
5207    case False{}:
5208      TurnFail{400}
5209
5210def sv.closed.head(buf: Bytes.Bytes) -> Turn:
5211  Bytes.Bytes{+len, b} = buf
5212  sv.closed.pick(U32.is_eq(len, 0))
5213
5214# A close mid-request is a request cut short (RFC 9112 §8).
5215def sv.step(closed: Bool, +max: Nat, sv: Sv, piece: Bytes.Bytes) -> Turn:
5216  match closed:
5217    case True{}:
5218      match sv:
5219        case SvHead{buf}:
5220          sv.closed.head(buf)
5221        case SvLen{req, v11, left, parts}:
5222          TurnFail{400}
5223        case SvChunk{req, v11, n, st, parts}:
5224          TurnFail{400}
5225    case False{}:
5226      match sv:
5227        case SvHead{buf}:
5228          sv.head(max, buf, piece)
5229        case SvLen{req, +v11, +left, parts}:
5230          sv.len(req, v11, left, parts, piece)
5231        case SvChunk{req, +v11, +n, st, parts}:
5232          sv.chunk(max, req, v11, n, st, parts, piece)
5233
5234def sv.frame.req(t: Turn) -> Maybe<&1, String & String>:
5235  match t:
5236    case TurnReq{req, rest, v11}:
5237      Req{method, path, headers, body} = req
5238      Some{(Bytes.to_string(body), Bytes.to_string(rest))}
5239    case TurnMore{sv, c}:
5240      None{}
5241    case TurnFail{s}:
5242      None{}
5243    case TurnClose{}:
5244      None{}
5245
5246def sv.frame.go(xs: List<&2, String>, t: Turn) -> Maybe<&1, String & String>:
5247  match xs:
5248    case Nil{}:
5249      sv.frame.req(t)
5250    case Con{+x, rest}:
5251      match t:
5252        case TurnMore{sv, c}:
5253          sv.frame.go(rest, sv.step(False{}, serve.max(), sv, Bytes.from_string(x)))
5254        case TurnReq{req, r, v11}:
5255          sv.frame.req(TurnReq{req, r, v11})
5256        case TurnFail{s}:
5257          None{}
5258        case TurnClose{}:
5259          None{}
5260
5261# The body and the bytes after it, once the pieces make a whole request; None otherwise.
5262def serve.frame(xs: List<&2, String>) -> Maybe<&1, String & String>:
5263  sv.frame.go(xs, TurnMore{sv.none(), False{}})
5264
5265def talk.piece(+max: Nat, sv: Sv, p: U32 & Array<U32>) -> Turn:
5266  (+len, buf) = p
5267  sv.step(U32.is_eq(len, 0), max, sv, Bytes.Bytes{len, buf})
5268
5269def talk.next(+max: Nat, sv: Sv, m: Socket & Result<&1, &1, U32 & String, U32 & Array<U32>>) -> Socket & Turn:
5270  (s, r) = m
5271  match r:
5272    case Fail{e}:
5273      (s, TurnClose{})
5274    case Done{p}:
5275      (s, talk.piece(max, sv, p))
5276
5277def talk.after.pick(empty: Bool, +max: Nat, rest: Bytes.Bytes) -> Turn:
5278  match empty:
5279    case True{}:
5280      TurnMore{sv.none(), False{}}
5281    case False{}:
5282      sv.step(False{}, max, sv.none(), rest)
5283
5284def talk.after.rest(+max: Nat, rest: Bytes.Bytes, s: Socket) -> Socket & Turn:
5285  Bytes.Bytes{+len, buf} = rest
5286  (s, talk.after.pick(U32.is_eq(len, 0), max, Bytes.Bytes{len, buf}))
5287
5288def talk.after.keep(keep: Bool, +max: Nat, rest: Bytes.Bytes, s: Socket) -> Socket & Turn:
5289  match keep:
5290    case False{}:
5291      (s, TurnClose{})
5292    case True{}:
5293      talk.after.rest(max, rest, s)
5294
5295def talk.after(+max: Nat, keep: Bool, rest: Bytes.Bytes, m: Socket & Result<&1, &1, U32 & String, Unit>) -> Socket & Turn:
5296  (s, r) = m
5297  match r:
5298    case Fail{e}:
5299      (s, TurnClose{})
5300    case Done{u}:
5301      talk.after.keep(keep, max, rest, s)
5302
5303def talk.send(+max: Nat, s: Socket, rest: Bytes.Bytes, +headers: Map<&2, List<&2, String>>, v11: Bool, +head: Bool, res: Res) -> IO(Socket & Turn):
5304  Res{+status, +rh, body} = res
5305  +keep = serve.keep(headers, v11, status, rh)
5306  do IO<Socket & Turn>:
5307    sent : Socket & Result<&1, &1, U32 & String, Unit> <- io.send.bytes(False{}, s, reply.bytes(Res{status, rh, body}, head, Bool.not(keep)))
5308    return talk.after(max, keep, rest, sent)
5309
5310def talk.cont.sent(m: Socket & Result<&1, &1, U32 & String, Unit>) -> Socket:
5311  (s, r) = m
5312  s
5313
5314def talk.cont(cont: Bool, s: Socket) -> IO(Socket):
5315  match cont:
5316    case False{}:
5317      IO.pure(Socket, s)
5318    case True{}:
5319      do IO<Socket>:
5320        sent : Socket & Result<&1, &1, U32 & String, Unit> <- Wire.send(s, "HTTP/1.1 100 Continue\r\n\r\n")
5321        return talk.cont.sent(sent)
5322
5323@unsafe
5324def talk(~h: Req -> IO(Res), +max: Nat, st: Socket & Turn) -> IO(Unit):
5325  (s, t) = st
5326  match t:
5327    case TurnMore{sv, cont}:
5328      do IO<Unit>:
5329        s2 : Socket <- talk.cont(cont, s)
5330        m : Socket & Result<&1, &1, U32 & String, U32 & Array<U32>> <- Wire.recv.words(s2, 65536, 30000)
5331        talk(~h, max, talk.next(max, sv, m))
5332    case TurnReq{req, rest, v11}:
5333      Req{+method, path, +headers, body} = req
5334      do IO<Unit>:
5335        res : Res <- h(Req{method, path, headers, body})
5336        next : Socket & Turn <- talk.send(max, s, rest, headers, v11, String.eq(method, "HEAD"), res)
5337        talk(~h, max, next)
5338    case TurnFail{status}:
5339      reply_fail(s, status)
5340    case TurnClose{}:
5341      Socket.close(s)
5342
5343def conn(~h: Req -> IO(Res), +max: Nat, m: Listener & Result<&1, &1, U32 & String, Socket>) -> IO(Listener):
5344  (l, r) = m
5345  do IO<Listener>:
5346    s : Socket <- IO.pass(Socket, r)
5347    IO.spawn(Unit, talk(~h, max, (s, TurnMore{sv.none(), False{}})))
5348    return l
5349
5350@unsafe
5351def loop(~h: Req -> IO(Res), +max: Nat, l: Listener) -> IO(Unit):
5352  do IO<Unit>:
5353    m  : Listener & Result<&1, &1, U32 & String, Socket> <- TCP.accept(l)
5354    l2 : Listener <- conn(~h, max, m)
5355    loop(~h, max, l2)
5356
5357def serve.with(~h: Req -> IO(Res), +port: U32, +max: Nat) -> IO(Unit):
5358  do IO<Unit>:
5359    l : Listener <- IO.try(Listener, TCP.listen(port))
5360    IO.print("http://127.0.0.1:" ++ U32.show(port))
5361    loop(~h, max, l)
5362
5363def serve(~h: Req -> IO(Res), +port: U32) -> IO(Unit):
5364  serve.with(~h, port, serve.max())