hairpin.bend

bend-kit-hairpin@0.14.0.0 · 501 lines · 71 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.38.1.1/http.bend as Http
4import bend-kit-time@0.3.0.0/time.bend as Time
5import bend-kit-url@0.4.1.0/url.bend as Url
6import bend-kit-json@0.7.0.0/json.bend as Json
7import bend-kit-bytes@0.3.3.0/bytes.bend as Bytes
8import bend-kit-retry@0.3.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
97# Close a stream from open.as. A body read to its end gives its connection to the client's pool.
98def stream.close(c: Client, st: Http.Stream) -> IO(Client):
99  Client{o, pool, j, br} = c
100  do IO<Client>:
101    p : Http.Pool <- Http.pool.stream.close(pool, st)
102    return Client{o, p, j, br}
103
104def target.pick(none: Bool, b: String, ref: String) -> Maybe<&2, String>:
105  match none:
106    case True{}:
107      Some{ref}
108    case False{}:
109      Http.resolve(b, ref)
110
111# ref against the base (RFC 3986 §5.2); with no base, ref as given. None when the base is not absolute.
112def target(+b: String, ref: String) -> Maybe<&2, String>:
113  target.pick(String.is_empty(b), b, ref)
114
115def target.abs(m: Maybe<&2, String>) -> Maybe<&2, Url.Abs>:
116  match m:
117    case None{}:
118      None{}
119    case Some{s}:
120      Url.absolute(s)
121
122# The defaults under the request headers, names lowercased; a request header replaces a default of its name.
123# Host, Connection, Content-Length, and Transfer-Encoding are the client's own, so both sides drop them.
124def merge(defaults: Map<&2, List<&2, String>>, headers: Map<&2, List<&2, String>>) -> Map<&2, List<&2, String>>:
125  Http.req.put(Map.to_list(&2, List<&2, String>, headers), Http.req.put(Map.to_list(&2, List<&2, String>, defaults), Http.empty()))
126
127def jar.now(j: Maybe<&2, Http.Jar>) -> IO(Maybe<&2, Http.Jar>):
128  match j:
129    case None{}:
130      IO.pure(Maybe<&2, Http.Jar>, None{})
131    case Some{jar}:
132      do IO<Maybe<&2, Http.Jar>>:
133        now : Time.Instant <- Time.now()
134        return Some{Http.jar.at(jar, now)}
135
136def once.final(+enc: String, x: Http.Pool & Result<&1, &1, Http.Err, Http.Res> & Maybe<&2, Http.Jar>) ->
137    IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Res>):
138  (p, r, j) = x
139  do IO<Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Res>>:
140    d : Result<&1, &1, Http.Err, Http.Res> <- Http.fetch.final(enc, r)
141    return (p, j, d)
142
143# One try: the redirect loop on the pool, with the jar, the certificate, and the CA file, then the body decoded.
144def once(+ms: U32, +mode: Http.Mode, +cert: Maybe<&2, Http.Cert>, +ca: String, +enc: String, p: Http.Pool, j: Maybe<&2, Http.Jar>,
145    +method: String, +u: Maybe<&2, Url.Abs>, +headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) ->
146    IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Res>):
147  do IO<Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Res>>:
148    now : Maybe<&2, Http.Jar> <- jar.now(j)
149    x : Http.Pool & Result<&1, &1, Http.Err, Http.Res> & Maybe<&2, Http.Jar> <-
150      Http.pool.hops(mode, ms, Http.Hops{p, Http.fetch.start(method, headers, body, u, enc), cert, now, ca})
151    once.final(enc, x)
152
153def hint.ms(m: Maybe<&2, U32>) -> Maybe<&2, Nat>:
154  match m:
155    case None{}:
156      None{}
157    case Some{ms}:
158      Some{U32.to_nat(ms)}
159
160# A judge's verdict on one attempt. Ok: a success. Caller: the request is at fault (a 4xx), so it stops
161# and the breaker does not count it. Target: the target failed in a way another try would repeat, so it
162# stops and the breaker counts it. Again: another try may help; after is the Retry-After value, "" for none.
163type Verdict is Data:
164  VerdictOk{}
165  VerdictCaller{}
166  VerdictTarget{}
167  VerdictAgain{after: String}
168
169# Ok is Settled, Caller is Rejected, and Target is Failed. Again is Transient for an idempotent request, else Unsafe.
170def outcome(+idem: Bool, v: Verdict, now: Time.Instant) -> Retry.Outcome:
171  match v:
172    case VerdictOk{}:
173      Retry.Settled{}
174    case VerdictCaller{}:
175      Retry.Rejected{}
176    case VerdictTarget{}:
177      Retry.Failed{}
178    case VerdictAgain{+after}:
179      Bool.pick(Retry.Outcome, idem, Retry.Transient{hint.ms(Http.retry.after(after, now))}, Retry.Unsafe{})
180
181def lift(-R: Type, r: Result<&1, &1, Http.Err, R>) -> Result<&1, &1, Err, R>:
182  match r:
183    case Fail{e}:
184      Fail{ErrHttp{e}}
185    case Done{res}:
186      Done{res}
187
188# The live state of one request between attempts. R: a response or a stream. last: the result of the last
189# attempt, None before the first.
190type Step<-R: Type> is Type:
191  Step{pool: Http.Pool, jar: Maybe<&2, Http.Jar>, breaker: Retry.Breaker, budget: Retry.Budget, body: Bytes.Bytes,
192    last: Maybe<&1, Result<&1, &1, Err, R>>, plan: Retry.Plan}
193
194# The clock, read only when a decision depends on it; 0 otherwise, which no such decision reads.
195def clock(need: Bool) -> IO(Nat):
196  match need:
197    case True{}:
198      Time.mono.ms()
199    case False{}:
200      IO.pure(Nat, 0n)
201
202def breaker.on(br: Retry.Breaker) -> Bool:
203  match br:
204    case Retry.BreakerOff{}:
205      False{}
206    case Retry.BreakerOn{c, s}:
207      True{}
208
209def transient(o: Retry.Outcome) -> Bool:
210  match o:
211    case Retry.Transient{after}:
212      True{}
213    case Retry.Settled{}:
214      False{}
215    case Retry.Unsafe{}:
216      False{}
217    case Retry.Failed{}:
218      False{}
219    case Retry.Rejected{}:
220      False{}
221
222def some(m: Maybe<&2, Nat>) -> Bool:
223  match m:
224    case None{}:
225      False{}
226    case Some{t}:
227      True{}
228
229def deadline.some(b: Retry.Budget) -> Bool:
230  Retry.Budget{l, d} = b
231  some(d)
232
233# The wall clock dates a Retry-After, so it is read only for Again.
234def outcome.io(+idem: Bool, v: Verdict) -> IO(Retry.Outcome):
235  match v:
236    case VerdictAgain{after}:
237      do IO<Retry.Outcome>:
238        wall : Time.Instant <- Time.now()
239        return outcome(idem, VerdictAgain{after}, wall)
240    case VerdictOk{}:
241      IO.pure(Retry.Outcome, Retry.Settled{})
242    case VerdictCaller{}:
243      IO.pure(Retry.Outcome, Retry.Rejected{})
244    case VerdictTarget{}:
245      IO.pure(Retry.Outcome, Retry.Failed{})
246
247# Jitter for the backoff, drawn only when a retry may follow.
248def jitter.io(need: Bool) -> IO(Nat):
249  match need:
250    case True{}:
251      do IO<Nat>:
252        rnd : Result<&1, &1, U32 & String, U32> <- IO.random_u32()
253        return U32.to_nat(Http.retry.jitter(rnd))
254    case False{}:
255      IO.pure(Nat, 0n)
256
257def settle.at(-R: Type, +now: Nat, +rnd: Nat, +p: Retry.Policy, +n: Nat, +o: Retry.Outcome, br: Retry.Breaker, +b: Retry.Budget,
258    body: Bytes.Bytes, pool: Http.Pool, jar: Maybe<&2, Http.Jar>, r: Result<&1, &1, Http.Err, R>) -> Step<R>:
259  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)}
260
261# The attempt has ended: tell the breaker, and plan the next step.
262def settle.outcome(-R: Type, +p: Retry.Policy, +n: Nat, +o: Retry.Outcome, +br: Retry.Breaker, b: Retry.Budget, body: Bytes.Bytes,
263    pool: Http.Pool, jar: Maybe<&2, Http.Jar>, r: Result<&1, &1, Http.Err, R>) -> IO(Step<R>):
264  do IO<Step<R>>:
265    now : Nat <- clock(Bool.or(breaker.on(br), transient(o)))
266    rnd : Nat <- jitter.io(transient(o))
267    return settle.at(R, now, rnd, p, n, o, br, b, body, pool, jar, r)
268
269def settle.judged(-R: Type, +p: Retry.Policy, +idem: Bool, +n: Nat, br: Retry.Breaker, b: Retry.Budget, body: Bytes.Bytes,
270    pool: Http.Pool, jar: Maybe<&2, Http.Jar>, j: Result<&1, &1, Http.Err, R> & Verdict) -> IO(Step<R>):
271  (r, +v) = j
272  do IO<Step<R>>:
273    o : Retry.Outcome <- outcome.io(idem, v)
274    settle.outcome(R, p, n, o, br, b, body, pool, jar, r)
275
276# A status that Http.retry.judge does not retry: below 400 is Ok, a 4xx is Caller, and the rest is Target.
277def judge.status(+s: U32) -> Verdict:
278  Bool.pick(Verdict, U32.is_lt(s, 400), VerdictOk{}, Bool.pick(Verdict, U32.is_lt(s, 500), VerdictCaller{}, VerdictTarget{}))
279
280def judge.settled(r: Result<&1, &1, Http.Err, Http.Res>) -> Result<&1, &1, Http.Err, Http.Res> & Verdict:
281  match r:
282    case Fail{e}:
283      (Fail{e}, VerdictTarget{})
284    case Done{res}:
285      Http.Res{+s, h, b} = res
286      (Done{Http.Res{s, h, b}}, judge.status(s))
287
288def judge.of(x: Result<&1, &1, Http.Err, Http.Res> & Maybe<&2, String>) -> Result<&1, &1, Http.Err, Http.Res> & Verdict:
289  (r, m) = x
290  match m:
291    case Some{after}:
292      (r, VerdictAgain{after})
293    case None{}:
294      judge.settled(r)
295
296# The default judge: Http.retry.judge, as if the request were idempotent, picks Again; outcome then applies idem.
297def judge(r: Result<&1, &1, Http.Err, Http.Res>) -> Result<&1, &1, Http.Err, Http.Res> & Verdict:
298  judge.of(Http.retry.judge(True{}, r))
299
300def settle(~R: Type, ~judge: Result<&1, &1, Http.Err, R> -> Result<&1, &1, Http.Err, R> & Verdict,
301    +p: Retry.Policy, +idem: Bool, +n: Nat, br: Retry.Breaker, b: Retry.Budget, body: Bytes.Bytes,
302    x: Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, R>) -> IO(Step<R>):
303  (pool, jar, r) = x
304  settle.judged(R, p, idem, n, br, b, body, pool, jar, judge(r))
305
306# The inputs of one attempt. u: the target, None when it is not absolute. headers: the merged headers.
307type Call is Data:
308  Call{enc: String, method: String, u: Maybe<&2, Url.Abs>, headers: Map<&2, List<&2, String>>}
309
310# One attempt that reads a whole response: the redirect loop on the pool, with the jar and the certificate.
311def try.res(o: Opts, call: Call, pool: Http.Pool, jar: Maybe<&2, Http.Jar>, body: Bytes.Bytes) ->
312    IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Res>):
313  Opts{base, h, +ms, +mode, p, +cert, +ca} = o
314  Call{+enc, +method, +u, +headers} = call
315  once(ms, mode, cert, ca, enc, pool, jar, method, u, headers, body)
316
317# One attempt that opens a stream on the pool: the redirect loop with the mode, the jar, and the certificate,
318# then the body decoded by enc.
319def try.stream(o: Opts, call: Call, pool: Http.Pool, jar: Maybe<&2, Http.Jar>, body: Bytes.Bytes) ->
320    IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Stream>):
321  Opts{base, h, +ms, mode, p, cert, ca} = o
322  Call{+enc, method, u, headers} = call
323  do IO<Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Stream>>:
324    now : Maybe<&2, Http.Jar> <- jar.now(jar)
325    r : Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, Http.Stream> <-
326      Http.stream.hops(mode, ms, (pool, Http.StreamHops{Http.stream.start(method, Http.accept.enc(headers, enc), body, u), cert, now, ca}))
327    Http.stream.init.pool(enc, r)
328
329def close.res(r: Http.Res) -> IO(Unit):
330  IO.pure(Unit, Unit{})
331
332def close.last(~R: Type, ~close: R -> IO(Unit), last: Maybe<&1, Result<&1, &1, Err, R>>) -> IO(Unit):
333  match last:
334    case None{}:
335      IO.pure(Unit, Unit{})
336    case Some{r}:
337      match r:
338        case Fail{e}:
339          IO.pure(Unit, Unit{})
340        case Done{x}:
341          close(x)
342
343def attempt.run(~R: Type, ~judge: Result<&1, &1, Http.Err, R> -> Result<&1, &1, Http.Err, R> & Verdict,
344    ~try: Opts -> Call -> Http.Pool -> Maybe<&2, Http.Jar> -> Bytes.Bytes -> IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, R>),
345    +o: Opts, +call: Call, +idem: Bool, +n: Nat, pool: Http.Pool, jar: Maybe<&2, Http.Jar>, br: Retry.Breaker,
346    b: Retry.Budget, r: Bytes.Bytes & Bytes.Bytes) -> IO(Step<R>):
347  Opts{base, h, ms, mode, +p, cert, ca} = o
348  (body, spare) = r
349  do IO<Step<R>>:
350    x : Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, R> <- try(o, call, pool, jar, spare)
351    settle(~R, ~judge, p, idem, n, br, b, body, x)
352
353def denied(-R: Type, why: Retry.Deny, last: Maybe<&1, Result<&1, &1, Err, R>>) -> Maybe<&1, Result<&1, &1, Err, R>>:
354  match last:
355    case None{}:
356      Some{Fail{ErrDenied{why}}}
357    case Some{r}:
358      Some{r}
359
360# A refused stream closes only when the next attempt is admitted, so a denied attempt still returns it.
361def attempt.gate(~R: Type, ~judge: Result<&1, &1, Http.Err, R> -> Result<&1, &1, Http.Err, R> & Verdict,
362    ~try: Opts -> Call -> Http.Pool -> Maybe<&2, Http.Jar> -> Bytes.Bytes -> IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, R>),
363    ~close: R -> IO(Unit),
364    x: Retry.Breaker & Retry.Budget & Retry.Gate, +o: Opts, +call: Call, +idem: Bool, +n: Nat, pool: Http.Pool,
365    jar: Maybe<&2, Http.Jar>, body: Bytes.Bytes, last: Maybe<&1, Result<&1, &1, Err, R>>) -> IO(Step<R>):
366  (br, b, g) = x
367  match g:
368    case Retry.GateNo{why}:
369      IO.pure(Step<R>, Step{pool, jar, br, b, body, denied(R, why, last), Retry.PlanStop{}})
370    case Retry.GateGo{}:
371      do IO<Step<R>>:
372        close.last(~R, ~close, last)
373        attempt.run(~R, ~judge, ~try, o, call, idem, n, pool, jar, br, b, Bytes.slice(body, 0, 4294967295))
374
375# Ask the gate; when it admits, make attempt n (0 first) of this layer. With no deadline and no breaker,
376# admission does not read the clock.
377def attempt(~R: Type, ~judge: Result<&1, &1, Http.Err, R> -> Result<&1, &1, Http.Err, R> & Verdict,
378    ~try: Opts -> Call -> Http.Pool -> Maybe<&2, Http.Jar> -> Bytes.Bytes -> IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, R>),
379    ~close: R -> IO(Unit),
380    +o: Opts, +call: Call, +idem: Bool, +n: Nat, s: Step<R>) -> IO(Step<R>):
381  Step{pool, jar, +br, +b, body, last, plan} = s
382  do IO<Step<R>>:
383    now : Nat <- clock(Bool.or(breaker.on(br), deadline.some(b)))
384    attempt.gate(~R, ~judge, ~try, ~close, Retry.admit(br, b, now), o, call, idem, n, pool, jar, body, last)
385
386def pause(ms: Nat) -> IO(Unit):
387  match ms:
388    case 0n:
389      IO.pure(Unit, Unit{})
390    case 1n+k:
391      IO.sleep(U32.from_nat(1n+k))
392
393# left: attempts this layer may still make. n: attempts made so far. Each turn follows the plan of the last step.
394def go(~R: Type, ~judge: Result<&1, &1, Http.Err, R> -> Result<&1, &1, Http.Err, R> & Verdict,
395    ~try: Opts -> Call -> Http.Pool -> Maybe<&2, Http.Jar> -> Bytes.Bytes -> IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, R>),
396    ~close: R -> IO(Unit),
397    left: Nat, +n: Nat, +o: Opts, +call: Call, +idem: Bool, s: Step<R>) -> IO(Step<R>):
398  match left:
399    case 0n:
400      IO.pure(Step<R>, s)
401    case 1n+rest:
402      Step{pool, jar, br, b, body, last, plan} = s
403      match plan:
404        case Retry.PlanStop{}:
405          IO.pure(Step<R>, Step{pool, jar, br, b, body, last, Retry.PlanStop{}})
406        case Retry.PlanWait{ms}:
407          do IO<Step<R>>:
408            pause(ms)
409            next : Step<R> <- attempt(~R, ~judge, ~try, ~close, o, call, idem, n, Step{pool, jar, br, b, body, last, Retry.PlanStop{}})
410            go(~R, ~judge, ~try, ~close, rest, 1n+n, o, call, idem, next)
411
412def result.of(-R: Type, m: Maybe<&1, Result<&1, &1, Err, R>>) -> Result<&1, &1, Err, R>:
413  match m:
414    case None{}:
415      Fail{ErrDenied{Retry.DenySpent{}}}
416    case Some{r}:
417      r
418
419def request.done(-R: Type, +o: Opts, s: Step<R>) -> Client & Retry.Budget & Result<&1, &1, Err, R>:
420  Step{pool, jar, br, b, body, last, plan} = s
421  (Client{o, pool, jar, br}, b, result.of(R, last))
422
423def attempts(p: Retry.Policy) -> Nat:
424  Retry.Policy{a, base, cap, d} = p
425  a
426
427# The budget of one plain request: the policy's attempts, and its deadline from now. The clock is read only for a deadline.
428def budget(c: Client) -> IO(Client & Retry.Budget):
429  Client{+o, pool, jar, br} = c
430  Opts{base, h, ms, mode, Retry.Policy{+a, bs, cap, +d}, cert, ca} = o
431  do IO<Client & Retry.Budget>:
432    now : Nat <- clock(some(d))
433    return (Client{o, pool, jar, br}, Retry.Budget.new(a, now, d))
434
435def run(~R: Type, ~judge: Result<&1, &1, Http.Err, R> -> Result<&1, &1, Http.Err, R> & Verdict,
436    ~try: Opts -> Call -> Http.Pool -> Maybe<&2, Http.Jar> -> Bytes.Bytes -> IO(Http.Pool & Maybe<&2, Http.Jar> & Result<&1, &1, Http.Err, R>),
437    ~close: R -> IO(Unit),
438    c: Client, b: Retry.Budget, +idem: Bool, enc: String, method: String, url: String,
439    headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Client & Retry.Budget & Result<&1, &1, Err, R>):
440  Client{+o, pool, jar, br} = c
441  Opts{+base, +h, ms, mode, +p, cert, ca} = o
442  +call = {Call{enc, method, target.abs(target(base, url)), merge(h, headers)} : Call}
443  do IO<Client & Retry.Budget & Result<&1, &1, Err, R>>:
444    s : Step<R> <- go(~R, ~judge, ~try, ~close, attempts(p), 0n, o, call, idem, Step{pool, jar, br, b, body, None{}, Retry.PlanWait{0n}})
445    return request.done(R, o, s)
446
447# One request inside a caller's retry layer, with every choice explicit. Every attempt takes from b, the
448# caller's shared budget, and obeys its deadline; the client's own policy caps the attempts of this call.
449# The budget left comes back beside the result: pass it to the next call, so nested layers never reset or
450# multiply it. The client's own deadline does not apply here; b's does.
451# judge: the Verdict on each attempt; Hairpin.judge is the default. idem: the request is safe to repeat, so
452# Again is retried; else the breaker counts it and it never repeats. enc: the Accept-Encoding codings.
453def request.as(~judge: Result<&1, &1, Http.Err, Http.Res> -> Result<&1, &1, Http.Err, Http.Res> & Verdict,
454    c: Client, b: Retry.Budget, +idem: Bool, +enc: String, +method: String, url: String,
455    headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Client & Retry.Budget & Result<&1, &1, Err, Http.Res>):
456  run(~Http.Res, ~judge, ~try.res, ~close.res, c, b, idem, enc, method, url, headers, body)
457
458# A streamed request under the same budget, deadline, backoff, and breaker as request.as. The stream opens on
459# the client's pool. It follows the client's redirect mode, presents its certificate, and sends and stores
460# cookies through its jar, as request.as does. judge reads the status and headers through Http.stream.res.
461# A refused stream closes before the next attempt; the last one comes back open, so the caller can read its
462# body. Close it with stream.close to give its connection back to the pool.
463def open.as(~judge: Result<&1, &1, Http.Err, Http.Stream> -> Result<&1, &1, Http.Err, Http.Stream> & Verdict,
464    c: Client, b: Retry.Budget, +idem: Bool, +enc: String, +method: String, url: String,
465    headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) -> IO(Client & Retry.Budget & Result<&1, &1, Err, Http.Stream>):
466  run(~Http.Stream, ~judge, ~try.stream, ~Http.stream.close, c, b, idem, enc, method, url, headers, body)
467
468# request.as with judge, the idempotency of method, and every coding Http decodes.
469def request.in(c: Client, b: Retry.Budget, +method: String, url: String, headers: Map<&2, List<&2, String>>,
470    body: Bytes.Bytes) -> IO(Client & Retry.Budget & Result<&1, &1, Err, Http.Res>):
471  do IO<Client & Retry.Budget & Result<&1, &1, Err, Http.Res>>:
472    enc : String <- Http.codings()
473    request.as(~judge, c, b, Http.pool.idempotent(method), enc, method, url, headers, body)
474
475def request.drop(x: Client & Retry.Budget & Result<&1, &1, Err, Http.Res>) -> Client & Result<&1, &1, Err, Http.Res>:
476  (c, b, r) = x
477  (c, r)
478
479def request.budget(+method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes,
480    x: Client & Retry.Budget) -> IO(Client & Retry.Budget & Result<&1, &1, Err, Http.Res>):
481  (c, b) = x
482  request.in(c, b, method, url, headers, body)
483
484# url resolves against the base; headers go over the defaults. Redirects follow the client's mode, at most 20.
485# Each request gets a fresh budget from budget(c). Before each attempt the deadline, the
486# budget, and the breaker must admit it. GET, HEAD, OPTIONS, TRACE, PUT, and DELETE try again after a connect
487# error, a timeout, or 408, 429, 500, 502, 503, or 504, as Http.retry.judge says, on the same pool.
488# When the attempts run out, the last result comes back; when none started, ErrDenied says why.
489def request(c: Client, +method: String, url: String, headers: Map<&2, List<&2, String>>, body: Bytes.Bytes) ->
490    IO(Client & Result<&1, &1, Err, Http.Res>):
491  do IO<Client & Result<&1, &1, Err, Http.Res>>:
492    y : Client & Retry.Budget <- budget(c)
493    x : Client & Retry.Budget & Result<&1, &1, Err, Http.Res> <- request.budget(method, url, headers, body, y)
494    return request.drop(x)
495
496def get(c: Client, url: String) -> IO(Client & Result<&1, &1, Err, Http.Res>):
497  request(c, "GET", url, Http.empty(), Bytes.new(0))
498
499# POST v as compact JSON, with content-type: application/json.
500def post.json(c: Client, url: String, v: Json.Val) -> IO(Client & Result<&1, &1, Err, Http.Res>):
501  request(c, "POST", url, Http.set(Http.empty(), "content-type", "application/json"), Json.encode.bytes(v))