hairpin.bend

bend-kit-hairpin@0.10.0.0 · 463 lines · 0 definitions

1# Hairpin: an HTTP client with a base URL, default headers, a pool, cookies, mTLS, redirects, and proven retries. Source: https://github.com/paymog/bend-kit/tree/main/hairpin
2import Base
3import bend-kit-http@0.36.0.0/http.bend as Http
4import bend-kit-time@0.2.0.0/time.bend as Time
5import bend-kit-url@0.4.1.0/url.bend as Url
6import bend-kit-json@0.6.1.1/json.bend as Json
7import bend-kit-bytes@0.3.2.0/bytes.bend as Bytes
8import bend-kit-retry@0.2.0.0/retry.bend as Retry
9
10# base: "" for none. headers: lowercase names. ms: the step timeout. policy: attempts, backoff, and deadline of each request.
11# ca: a PEM CA file to trust; "" trusts the default store.
12type Opts is Data:
13  Opts{base: String, headers: Map<&2, List<&2, String>>, ms: U32, mode: Http.Mode, policy: Retry.Policy, cert: Maybe<&2, Http.Cert>, ca: String}
14
15# breaker: the circuit breaker of every request on this client.
16type Client is Type:
17  Client{opts: Opts, pool: Http.Pool, jar: Maybe<&2, Http.Jar>, breaker: Retry.Breaker}
18
19# ErrHttp: the last attempt failed. ErrDenied: no attempt started, for why.
20type Err is Data:
21  ErrHttp{error: Http.Err}
22  ErrDenied{why: Retry.Deny}
23
24# One attempt, the first included; backoff from 500 ms, doubled to at most 30 s; no deadline.
25def policy() -> Retry.Policy:
26  Retry.Policy{1n, 500n, 30000, None{}}
27
28# A pool of up to cap idle sockets per origin, no base, no default headers, 30 s steps, follow redirects,
29# no retries, and no circuit breaker.
30def new.with(+cap: U32) -> Client:
31  Client{Opts{"", Http.empty(), 30000, Http.ModeFollow{}, policy(), None{}, ""}, Http.pool.new.with(cap), None{}, Retry.BreakerOff{}}
32
33def new() -> Client:
34  new.with(8)
35
36def base(c: Client, url: String) -> Client:
37  Client{Opts{b, h, ms, mode, p, cert, ca}, pool, j, br} = c
38  Client{Opts{url, h, ms, mode, p, cert, ca}, pool, j, br}
39
40# A default header. It replaces an earlier default of the same name; a request header of that name replaces it.
41def header(c: Client, k: String, v: String) -> Client:
42  Client{Opts{b, h, ms, mode, p, cert, ca}, pool, j, br} = c
43  Client{Opts{b, Http.set(h, String.to_lower(k), v), ms, mode, p, cert, ca}, pool, j, br}
44
45def timeout(c: Client, ms: U32) -> Client:
46  Client{Opts{b, h, old, mode, p, cert, ca}, pool, j, br} = c
47  Client{Opts{b, h, ms, mode, p, cert, ca}, pool, j, br}
48
49def redirect(c: Client, mode: Http.Mode) -> Client:
50  Client{Opts{b, h, ms, old, p, cert, ca}, pool, j, br} = c
51  Client{Opts{b, h, ms, mode, p, cert, ca}, pool, j, br}
52
53# Up to n retries after the first attempt: n + 1 attempts in all.
54def retry(c: Client, n: U32) -> Client:
55  Client{Opts{b, h, ms, mode, Retry.Policy{old, base, cap, d}, cert, ca}, pool, j, br} = c
56  Client{Opts{b, h, ms, mode, Retry.Policy{1n+U32.to_nat(n), base, cap, d}, cert, ca}, pool, j, br}
57
58# No attempt of a request starts ms or more after the request starts.
59def deadline(c: Client, ms: U32) -> Client:
60  Client{Opts{b, h, t, mode, Retry.Policy{a, base, cap, old}, cert, ca}, pool, j, br} = c
61  Client{Opts{b, h, t, mode, Retry.Policy{a, base, cap, Some{U32.to_nat(ms)}}, cert, ca}, pool, j, br}
62
63# A circuit breaker in front of every request, starting closed.
64def circuit(c: Client, circ: Retry.Circuit) -> Client:
65  Client{o, pool, j, old} = c
66  Client{o, pool, j, Retry.Breaker.new(circ)}
67
68# The breaker, for inspection.
69def breaker.of(c: Client) -> Client & Retry.Breaker:
70  Client{o, pool, j, +br} = c
71  (Client{o, pool, j, br}, br)
72
73# Paths to a PEM client chain and its private key, presented to every HTTPS origin.
74def cert(c: Client, chain: String, key: String) -> Client:
75  Client{Opts{b, h, ms, mode, p, old, ca}, pool, j, br} = c
76  Client{Opts{b, h, ms, mode, p, Some{Http.Cert{chain, key}}, ca}, pool, j, br}
77
78# Path to a PEM CA file, trusted in place of the default store. Like the certificate, it follows same-origin redirects only.
79def ca(c: Client, path: String) -> Client:
80  Client{Opts{b, h, ms, mode, p, cert, old}, pool, j, br} = c
81  Client{Opts{b, h, ms, mode, p, cert, path}, pool, j, br}
82
83# Every request stores and sends cookies through jar. Its clock moves to Time.now() before each try.
84def jar(c: Client, jar: Http.Jar) -> Client:
85  Client{o, pool, old, br} = c
86  Client{o, pool, Some{jar}, br}
87
88# The jar, if the client has one.
89def jar.of(c: Client) -> Client & Maybe<&2, Http.Jar>:
90  Client{o, pool, +j, br} = c
91  (Client{o, pool, j, br}, j)
92
93def close(c: Client) -> IO(Unit):
94  Client{o, pool, j, br} = c
95  Http.pool.close(pool)
96
97def target.pick(none: Bool, b: String, ref: String) -> Maybe<&2, String>:
98  match none:
99    case True{}:
100      Some{ref}
101    case False{}:
102      Http.resolve(b, ref)
103
104# ref against the base (RFC 3986 §5.2); with no base, ref as given. None when the base is not absolute.
105def target(+b: String, ref: String) -> Maybe<&2, String>:
106  target.pick(String.is_empty(b), b, ref)
107
108def target.abs(m: Maybe<&2, String>) -> Maybe<&2, Url.Abs>:
109  match m:
110    case None{}:
111      None{}
112    case Some{s}:
113      Url.absolute(s)
114
115# The defaults under the request headers, names lowercased; a request header replaces a default of its name.
116# Host, Connection, Content-Length, and Transfer-Encoding are the client's own, so both sides drop them.
117def merge(defaults: Map<&2, List<&2, String>>, headers: Map<&2, List<&2, String>>) -> Map<&2, List<&2, String>>:
118  Http.req.put(Map.to_list(&2, List<&2, String>, headers), Http.req.put(Map.to_list(&2, List<&2, String>, defaults), Http.empty()))
119
120def jar.now(j: Maybe<&2, Http.Jar>) -> IO(Maybe<&2, Http.Jar>):
121  match j:
122    case None{}:
123      IO.pure(Maybe<&2, Http.Jar>, None{})
124    case Some{jar}:
125      do IO<Maybe<&2, Http.Jar>>:
126        now : Time.Instant <- Time.now()
127        return Some{Http.jar.at(jar, now)}
128
129def once.final(+enc: String, x: Http.Pool & Result<&1, &1, Http.Err, Http.Res> & Maybe<&2, Http.Jar>) ->
130    IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Res>):
131  (p, r, j) = x
132  do IO<Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Res>>:
133    d : Result<&1, &1, Http.Err, Http.Res> <- Http.fetch.final(enc, r)
134    return (p, j, d)
135
136# One try: the redirect loop on the pool, with the jar, the certificate, and the CA file, then the body decoded.
137def once(+ms: U32, +mode: Http.Mode, +cert: Maybe<&2, Http.Cert>, +ca: String, +enc: String, p: Http.Pool, j: Maybe<&2, Http.Jar>,
138    +method: String, +u: Maybe<&2, Url.Abs>, +headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) ->
139    IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Res>):
140  do IO<Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Res>>:
141    now : Maybe<&2, Http.Jar> <- jar.now(j)
142    x : Http.Pool & Result<&1, &1, Http.Err, Http.Res> & Maybe<&2, Http.Jar> <-
143      Http.pool.hops(mode, ms, Http.Hops{p, Http.fetch.start(method, headers, body, u, enc), cert, now, ca})
144    once.final(enc, x)
145
146def hint.ms(m: Maybe<&2, U32>) -> Maybe<&2, Nat>:
147  match m:
148    case None{}:
149      None{}
150    case Some{ms}:
151      Some{U32.to_nat(ms)}
152
153# m is Http.retry.judge's verdict for an idempotent request: Some{Retry-After} when another try may help.
154# None is Settled, so the breaker counts any other response or error as a success.
155# A non-idempotent request with that verdict is Unsafe: the breaker counts it, but it never repeats.
156def outcome(+idem: Bool, m: Maybe<&2, String>, now: Time.Instant) -> Retry.Outcome:
157  match m:
158    case None{}:
159      Retry.Settled{}
160    case Some{+v}:
161      Bool.pick(Retry.Outcome, idem, Retry.Transient{hint.ms(Http.retry.after(v, now))}, Retry.Unsafe{})
162
163def lift(-R: Type, r: Result<&1, &1, Http.Err, R>) -> Result<&1, &1, Err, R>:
164  match r:
165    case Fail{e}:
166      Fail{ErrHttp{e}}
167    case Done{res}:
168      Done{res}
169
170# The live state of one request between attempts. R: a response or a stream. last: the result of the last
171# attempt, None before the first.
172type Step<-R: Type> is Type:
173  Step{pool: Http.Pool, jar: Maybe<&2, Http.Jar>, breaker: Retry.Breaker, budget: Retry.Budget, body: Bytes.Bytes,
174    last: Maybe<&1, Result<&1, &1, Err, R>>, plan: Retry.Plan}
175
176# The clock, read only when a decision depends on it; 0 otherwise, which no such decision reads.
177def clock(need: Bool) -> IO(Nat):
178  match need:
179    case True{}:
180      Time.mono.ms()
181    case False{}:
182      IO.pure(Nat, 0n)
183
184def breaker.on(br: Retry.Breaker) -> Bool:
185  match br:
186    case Retry.BreakerOff{}:
187      False{}
188    case Retry.BreakerOn{c, s}:
189      True{}
190
191def transient(o: Retry.Outcome) -> Bool:
192  match o:
193    case Retry.Transient{after}:
194      True{}
195    case Retry.Settled{}:
196      False{}
197    case Retry.Unsafe{}:
198      False{}
199    case Retry.Failed{}:
200      False{}
201
202def some(m: Maybe<&2, Nat>) -> Bool:
203  match m:
204    case None{}:
205      False{}
206    case Some{t}:
207      True{}
208
209def deadline.some(b: Retry.Budget) -> Bool:
210  Retry.Budget{l, d} = b
211  some(d)
212
213# The wall clock dates a Retry-After, so it is read only for a transient failure.
214def outcome.io(+idem: Bool, m: Maybe<&2, String>) -> IO(Retry.Outcome):
215  match m:
216    case None{}:
217      IO.pure(Retry.Outcome, Retry.Settled{})
218    case Some{v}:
219      do IO<Retry.Outcome>:
220        wall : Time.Instant <- Time.now()
221        return outcome(idem, Some{v}, wall)
222
223# Jitter for the backoff, drawn only when a retry may follow.
224def jitter.io(need: Bool) -> IO(Nat):
225  match need:
226    case True{}:
227      do IO<Nat>:
228        rnd : Result<&1, &1, U32 & String, U32> <- IO.random_u32()
229        return U32.to_nat(Http.retry.jitter(rnd))
230    case False{}:
231      IO.pure(Nat, 0n)
232
233def settle.at(-R: Type, +now: Nat, +rnd: Nat, +p: Retry.Policy, +n: Nat, +o: Retry.Outcome, br: Retry.Breaker, +b: Retry.Budget,
234    body: Bytes.Bytes, pool: Http.Pool, jar: Maybe<&2, Http.Jar>, r: Result<&1, &1, Http.Err, R>) -> Step<R>:
235  Step{pool, jar, Retry.Breaker.done(br, now, Retry.failed(o)), b, body, Some{lift(R, r)}, Retry.plan(o, p, b, n, now, rnd)}
236
237# The attempt has ended: tell the breaker, and plan the next step.
238def settle.outcome(-R: Type, +p: Retry.Policy, +n: Nat, +o: Retry.Outcome, +br: Retry.Breaker, b: Retry.Budget, body: Bytes.Bytes,
239    pool: Http.Pool, jar: Maybe<&2, Http.Jar>, r: Result<&1, &1, Http.Err, R>) -> IO(Step<R>):
240  do IO<Step<R>>:
241    now : Nat <- clock(Bool.or(breaker.on(br), transient(o)))
242    rnd : Nat <- jitter.io(transient(o))
243    return settle.at(R, now, rnd, p, n, o, br, b, body, pool, jar, r)
244
245def settle.judged(-R: Type, +p: Retry.Policy, +idem: Bool, +n: Nat, br: Retry.Breaker, b: Retry.Budget, body: Bytes.Bytes,
246    pool: Http.Pool, jar: Maybe<&2, Http.Jar>, j: Result<&1, &1, Http.Err, R> & Maybe<&2, String>) -> IO(Step<R>):
247  (r, m) = j
248  do IO<Step<R>>:
249    o : Retry.Outcome <- outcome.io(idem, m)
250    settle.outcome(R, p, n, o, br, b, body, pool, jar, r)
251
252# The default judge: Http.retry.judge, as if the request were idempotent; outcome then applies idem.
253def judge(r: Result<&1, &1, Http.Err, Http.Res>) -> Result<&1, &1, Http.Err, Http.Res> & Maybe<&2, String>:
254  Http.retry.judge(True{}, r)
255
256def settle(~R: Type, ~judge: Result<&1, &1, Http.Err, R> -> Result<&1, &1, Http.Err, R> & Maybe<&2, String>,
257    +p: Retry.Policy, +idem: Bool, +n: Nat, br: Retry.Breaker, b: Retry.Budget, body: Bytes.Bytes,
258    x: Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, R>) -> IO(Step<R>):
259  (pool, jar, r) = x
260  settle.judged(R, p, idem, n, br, b, body, pool, jar, judge(r))
261
262# The inputs of one attempt. u: the target, None when it is not absolute. headers: the merged headers.
263type Call is Data:
264  Call{enc: String, method: String, u: Maybe<&2, Url.Abs>, headers: Map<&2, List<&2, String>>}
265
266# One attempt that reads a whole response: the redirect loop on the pool, with the jar and the certificate.
267def try.res(o: Opts, call: Call, pool: Http.Pool, jar: Maybe<&2, Http.Jar>, body: Bytes.Bytes) ->
268    IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Res>):
269  Opts{base, h, +ms, +mode, p, +cert, +ca} = o
270  Call{+enc, +method, +u, +headers} = call
271  once(ms, mode, cert, ca, enc, pool, jar, method, u, headers, body)
272
273def try.stream.got(pool: Http.Pool, x: Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Stream>) ->
274    Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Stream>:
275  (jar, s) = x
276  (pool, jar, s)
277
278# One attempt that opens a stream on its own connection, outside the pool: the redirect loop with the mode,
279# the jar, and the certificate, then the body decoded by enc.
280def try.stream(o: Opts, call: Call, pool: Http.Pool, jar: Maybe<&2, Http.Jar>, body: Bytes.Bytes) ->
281    IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Stream>):
282  Opts{base, h, +ms, mode, p, cert, ca} = o
283  Call{+enc, method, u, headers} = call
284  do IO<Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Stream>>:
285    now : Maybe<&2, Http.Jar> <- jar.now(jar)
286    r : Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Stream> <-
287      Http.stream.hops(mode, ms, Http.StreamHops{Http.stream.start(method, Http.accept.enc(headers, enc), body, u), cert, now, ca})
288    x : Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Stream> <- Http.stream.init.jar(enc, r)
289    return try.stream.got(pool, x)
290
291def close.res(r: Http.Res) -> IO(Unit):
292  IO.pure(Unit, Unit{})
293
294def close.last(~R: Type, ~close: R -> IO(Unit), last: Maybe<&1, Result<&1, &1, Err, R>>) -> IO(Unit):
295  match last:
296    case None{}:
297      IO.pure(Unit, Unit{})
298    case Some{r}:
299      match r:
300        case Fail{e}:
301          IO.pure(Unit, Unit{})
302        case Done{x}:
303          close(x)
304
305def attempt.run(~R: Type, ~judge: Result<&1, &1, Http.Err, R> -> Result<&1, &1, Http.Err, R> & Maybe<&2, String>,
306    ~try: Opts -> Call -> Http.Pool -> Maybe<&2, Http.Jar> -> Bytes.Bytes -> IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, R>),
307    +o: Opts, +call: Call, +idem: Bool, +n: Nat, pool: Http.Pool, jar: Maybe<&2, Http.Jar>, br: Retry.Breaker,
308    b: Retry.Budget, r: Bytes.Bytes & Bytes.Bytes) -> IO(Step<R>):
309  Opts{base, h, ms, mode, +p, cert, ca} = o
310  (body, spare) = r
311  do IO<Step<R>>:
312    x : Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, R> <- try(o, call, pool, jar, spare)
313    settle(~R, ~judge, p, idem, n, br, b, body, x)
314
315def denied(-R: Type, why: Retry.Deny, last: Maybe<&1, Result<&1, &1, Err, R>>) -> Maybe<&1, Result<&1, &1, Err, R>>:
316  match last:
317    case None{}:
318      Some{Fail{ErrDenied{why}}}
319    case Some{r}:
320      Some{r}
321
322# A refused stream closes only when the next attempt is admitted, so a denied attempt still returns it.
323def attempt.gate(~R: Type, ~judge: Result<&1, &1, Http.Err, R> -> Result<&1, &1, Http.Err, R> & Maybe<&2, String>,
324    ~try: Opts -> Call -> Http.Pool -> Maybe<&2, Http.Jar> -> Bytes.Bytes -> IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, R>),
325    ~close: R -> IO(Unit),
326    x: Retry.Breaker & Retry.Budget & Retry.Gate, +o: Opts, +call: Call, +idem: Bool, +n: Nat, pool: Http.Pool,
327    jar: Maybe<&2, Http.Jar>, body: Bytes.Bytes, last: Maybe<&1, Result<&1, &1, Err, R>>) -> IO(Step<R>):
328  (br, b, g) = x
329  match g:
330    case Retry.GateNo{why}:
331      IO.pure(Step<R>, Step{pool, jar, br, b, body, denied(R, why, last), Retry.PlanStop{}})
332    case Retry.GateGo{}:
333      do IO<Step<R>>:
334        close.last(~R, ~close, last)
335        attempt.run(~R, ~judge, ~try, o, call, idem, n, pool, jar, br, b, Bytes.slice(body, 0, 4294967295))
336
337# Ask the gate; when it admits, make attempt n (0 first) of this layer. With no deadline and no breaker,
338# admission does not read the clock.
339def attempt(~R: Type, ~judge: Result<&1, &1, Http.Err, R> -> Result<&1, &1, Http.Err, R> & Maybe<&2, String>,
340    ~try: Opts -> Call -> Http.Pool -> Maybe<&2, Http.Jar> -> Bytes.Bytes -> IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, R>),
341    ~close: R -> IO(Unit),
342    +o: Opts, +call: Call, +idem: Bool, +n: Nat, s: Step<R>) -> IO(Step<R>):
343  Step{pool, jar, +br, +b, body, last, plan} = s
344  do IO<Step<R>>:
345    now : Nat <- clock(Bool.or(breaker.on(br), deadline.some(b)))
346    attempt.gate(~R, ~judge, ~try, ~close, Retry.admit(br, b, now), o, call, idem, n, pool, jar, body, last)
347
348def pause(ms: Nat) -> IO(Unit):
349  match ms:
350    case 0n:
351      IO.pure(Unit, Unit{})
352    case 1n+k:
353      IO.sleep(U32.from_nat(1n+k))
354
355# left: attempts this layer may still make. n: attempts made so far. Each turn follows the plan of the last step.
356def go(~R: Type, ~judge: Result<&1, &1, Http.Err, R> -> Result<&1, &1, Http.Err, R> & Maybe<&2, String>,
357    ~try: Opts -> Call -> Http.Pool -> Maybe<&2, Http.Jar> -> Bytes.Bytes -> IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, R>),
358    ~close: R -> IO(Unit),
359    left: Nat, +n: Nat, +o: Opts, +call: Call, +idem: Bool, s: Step<R>) -> IO(Step<R>):
360  match left:
361    case 0n:
362      IO.pure(Step<R>, s)
363    case 1n+rest:
364      Step{pool, jar, br, b, body, last, plan} = s
365      match plan:
366        case Retry.PlanStop{}:
367          IO.pure(Step<R>, Step{pool, jar, br, b, body, last, Retry.PlanStop{}})
368        case Retry.PlanWait{ms}:
369          do IO<Step<R>>:
370            pause(ms)
371            next : Step<R> <- attempt(~R, ~judge, ~try, ~close, o, call, idem, n, Step{pool, jar, br, b, body, last, Retry.PlanStop{}})
372            go(~R, ~judge, ~try, ~close, rest, 1n+n, o, call, idem, next)
373
374def result.of(-R: Type, m: Maybe<&1, Result<&1, &1, Err, R>>) -> Result<&1, &1, Err, R>:
375  match m:
376    case None{}:
377      Fail{ErrDenied{Retry.DenySpent{}}}
378    case Some{r}:
379      r
380
381def request.done(-R: Type, +o: Opts, s: Step<R>) -> Client & Retry.Budget & Result<&1, &1, Err, R>:
382  Step{pool, jar, br, b, body, last, plan} = s
383  (Client{o, pool, jar, br}, b, result.of(R, last))
384
385def attempts(p: Retry.Policy) -> Nat:
386  Retry.Policy{a, base, cap, d} = p
387  a
388
389# The budget of one plain request: the policy's attempts, and its deadline from now. The clock is read only for a deadline.
390def budget(c: Client) -> IO(Client & Retry.Budget):
391  Client{+o, pool, jar, br} = c
392  Opts{base, h, ms, mode, Retry.Policy{+a, bs, cap, +d}, cert, ca} = o
393  do IO<Client & Retry.Budget>:
394    now : Nat <- clock(some(d))
395    return (Client{o, pool, jar, br}, Retry.Budget.new(a, now, d))
396
397def run(~R: Type, ~judge: Result<&1, &1, Http.Err, R> -> Result<&1, &1, Http.Err, R> & Maybe<&2, String>,
398    ~try: Opts -> Call -> Http.Pool -> Maybe<&2, Http.Jar> -> Bytes.Bytes -> IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, R>),
399    ~close: R -> IO(Unit),
400    c: Client, b: Retry.Budget, +idem: Bool, enc: String, method: String, url: String,
401    headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Client & Retry.Budget & Result<&1, &1, Err, R>):
402  Client{+o, pool, jar, br} = c
403  Opts{+base, +h, ms, mode, +p, cert, ca} = o
404  +call = {Call{enc, method, target.abs(target(base, url)), merge(h, headers)} : Call}
405  do IO<Client & Retry.Budget & Result<&1, &1, Err, R>>:
406    s : Step<R> <- go(~R, ~judge, ~try, ~close, attempts(p), 0n, o, call, idem, Step{pool, jar, br, b, body, None{}, Retry.PlanWait{0n}})
407    return request.done(R, o, s)
408
409# One request inside a caller's retry layer, with every choice explicit. Every attempt takes from b, the
410# caller's shared budget, and obeys its deadline; the client's own policy caps the attempts of this call.
411# The budget left comes back beside the result: pass it to the next call, so nested layers never reset or
412# multiply it. The client's own deadline does not apply here; b's does.
413# judge: Some{Retry-After} when another attempt may help. idem: the request is safe to repeat, so a judged
414# failure is retried; else the breaker counts it and it never repeats. enc: the Accept-Encoding codings.
415def request.as(~judge: Result<&1, &1, Http.Err, Http.Res> -> Result<&1, &1, Http.Err, Http.Res> & Maybe<&2, String>,
416    c: Client, b: Retry.Budget, +idem: Bool, +enc: String, +method: String, url: String,
417    headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Client & Retry.Budget & Result<&1, &1, Err, Http.Res>):
418  run(~Http.Res, ~judge, ~try.res, ~close.res, c, b, idem, enc, method, url, headers, body)
419
420# A streamed request under the same budget, deadline, backoff, and breaker as request.as. The stream opens its
421# own connection outside the pool. It follows the client's redirect mode, presents its certificate, and sends
422# and stores cookies through its jar, as request.as does. judge reads the status and headers through
423# Http.stream.res. A refused stream closes before the next attempt; the last one comes back open, so the
424# caller can read its body.
425def open.as(~judge: Result<&1, &1, Http.Err, Http.Stream> -> Result<&1, &1, Http.Err, Http.Stream> & Maybe<&2, String>,
426    c: Client, b: Retry.Budget, +idem: Bool, +enc: String, +method: String, url: String,
427    headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Client & Retry.Budget & Result<&1, &1, Err, Http.Stream>):
428  run(~Http.Stream, ~judge, ~try.stream, ~Http.stream.close, c, b, idem, enc, method, url, headers, body)
429
430# request.as with judge, the idempotency of method, and every coding Http decodes.
431def request.in(c: Client, b: Retry.Budget, +method: String, url: String, headers: Map<&2, List<&2, String>>,
432    body: Bytes.Bytes) -> IO(Client & Retry.Budget & Result<&1, &1, Err, Http.Res>):
433  do IO<Client & Retry.Budget & Result<&1, &1, Err, Http.Res>>:
434    enc : String <- Http.codings()
435    request.as(~judge, c, b, Http.pool.idempotent(method), enc, method, url, headers, body)
436
437def request.drop(x: Client & Retry.Budget & Result<&1, &1, Err, Http.Res>) -> Client & Result<&1, &1, Err, Http.Res>:
438  (c, b, r) = x
439  (c, r)
440
441def request.budget(+method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes,
442    x: Client & Retry.Budget) -> IO(Client & Retry.Budget & Result<&1, &1, Err, Http.Res>):
443  (c, b) = x
444  request.in(c, b, method, url, headers, body)
445
446# url resolves against the base; headers go over the defaults. Redirects follow the client's mode, at most 20.
447# Each request gets a fresh budget from budget(c). Before each attempt the deadline, the
448# budget, and the breaker must admit it. GET, HEAD, OPTIONS, TRACE, PUT, and DELETE try again after a connect
449# error, a timeout, or 408, 429, 500, 502, 503, or 504, as Http.retry.judge says, on the same pool.
450# When the attempts run out, the last result comes back; when none started, ErrDenied says why.
451def request(c: Client, +method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) ->
452    IO(Client & Result<&1, &1, Err, Http.Res>):
453  do IO<Client & Result<&1, &1, Err, Http.Res>>:
454    y : Client & Retry.Budget <- budget(c)
455    x : Client & Retry.Budget & Result<&1, &1, Err, Http.Res> <- request.budget(method, url, headers, body, y)
456    return request.drop(x)
457
458def get(c: Client, url: String) -> IO(Client & Result<&1, &1, Err, Http.Res>):
459  request(c, "GET", url, Http.empty(), Bytes.new(0))
460
461# POST v as compact JSON, with content-type: application/json.
462def post.json(c: Client, url: String, v: Json.Val) -> IO(Client & Result<&1, &1, Err, Http.Res>):
463  request(c, "POST", url, Http.set(Http.empty(), "content-type", "application/json"), Json.encode.bytes(v))