Route.bend source
Route.bend on the hub · documented module
import Baseimport hhefesto-wire@1.0.0.0/Wire.bend as Wimport hhefesto-json@1.0.0.0/Json.bend as Jimport hhefesto-json@1.0.0.0/Codec.bend as C# Route: an HTTP API as a value (servant's job in the Haskell backend).## An API is a description: literal path segments, captures, query# parameters, headers, the peer, a body, a method and the shape of what it# answers, a raw application, and choices between APIs. What it means:## rt.In(api) the type of what a request gives it (servant's handler# arguments, plus which choice was taken: a sum)# rt.go(api, r) a request read as that: a hit, a miss (try elsewhere:# 404, 405, 415 or a capture that does not read, 400), or a# bad request (final, 400): a partial function from# requests to In(api)# rt.Server(api) the type of what serves it (servant's Server type# family, here a function on the description): a choice# is a pair of servers, a capture a function of its value,# a method an IO of its reply# rt.serve = apply the server to what go read, and write its reply## A choice is left-biased: the first alternative that hits, or the first# final error, else the more telling miss. Laws (LAWS.bend): choice is# associative with `rt.Nothing{}` as its identity, a segment distributes# over a choice, and what `rt.link` writes for a value reads back as it.## Every def is prefixed `rt.` (a program's defs share one namespace).# What a capture or a query parameter holds: a natural number, an integer# (servant's Int), text, a decimal (servant's Double)type rt.Ty is Data: rt.TNat{} rt.TInt{} rt.TText{} rt.TNum{}# an integer: its sign and sizetype rt.Int is Data: rt.Int{neg: Bool, n: Nat}type rt.Api is Data: rt.Seg{s: String, k: rt.Api} rt.Cap{name: String, t: rt.Ty, k: rt.Api} rt.Qry{name: String, t: rt.Ty, k: rt.Api} rt.Hdr{name: String, k: rt.Api} rt.Peer{k: rt.Api} rt.Body{s: C.js.Sh, k: rt.Api} rt.Bytes{k: rt.Api} rt.Verb{m: String, s: C.js.Sh} rt.Raw{} rt.Alt{a: rt.Api, b: rt.Api} rt.Nothing{}# What a handler answers: a value (200, as JSON), with headers, or an error# (servant's throwError): a status, headers and a body.type rt.Reply<-A: Data> is Data: rt.Ok{hs: List<&2, W.wr.H>, v: A} rt.Err{status: U32, hs: List<&2, W.wr.H>, body: String}# Why an alternative missed, from least to most telling (servant's order).type rt.Why is Data: rt.NotFound{} rt.NotAllowed{} rt.Unsupported{} rt.Unread{msg: String}type rt.Res<-A: Data> is Data: rt.No{why: rt.Why} rt.Bad{msg: String} rt.Hit{v: A}# a choice whose branches are computed only when taken (Bool.pick computes# both)def rt.if(-A: Data, b: Bool, t: Unit -> A, e: Unit -> A) -> A: match b: case True{}: t(Unit{}) case False{}: e(Unit{})# Meaning# -------def rt.TVal(t: rt.Ty) -> Data: match t: case rt.TNat{}: Nat case rt.TInt{}: rt.Int case rt.TText{}: String case rt.TNum{}: J.js.Numdef rt.In(a: rt.Api) -> Data: match a: case rt.Seg{s, k}: rt.In(k) case rt.Cap{+n, t, k}: C.js.P<rt.TVal(t), rt.In(k)> case rt.Qry{n, t, k}: C.js.P<Maybe<&2, rt.TVal(t)>, rt.In(k)> case rt.Hdr{n, k}: C.js.P<Maybe<&2, String>, rt.In(k)> case rt.Peer{k}: C.js.P<String, rt.In(k)> case rt.Body{s, k}: C.js.P<C.js.Val(s), rt.In(k)> case rt.Bytes{k}: C.js.P<List<&2, U32>, rt.In(k)> case rt.Verb{m, s}: Unit case rt.Raw{}: W.wr.Req case rt.Alt{a, b}: Either<&2, &2, rt.In(a), rt.In(b)> case rt.Nothing{}: Emptydef rt.Server(a: rt.Api) -> Type: match a: case rt.Seg{s, k}: rt.Server(k) case rt.Cap{+n, t, k}: rt.TVal(t) -> rt.Server(k) case rt.Qry{n, t, k}: Maybe<&2, rt.TVal(t)> -> rt.Server(k) case rt.Hdr{n, k}: Maybe<&2, String> -> rt.Server(k) case rt.Peer{k}: String -> rt.Server(k) case rt.Body{s, k}: C.js.Val(s) -> rt.Server(k) case rt.Bytes{k}: List<&2, U32> -> rt.Server(k) case rt.Verb{m, s}: IO(rt.Reply<C.js.Val(s)>) case rt.Raw{}: W.wr.Req -> IO(W.wr.Resp) case rt.Alt{a, b}: rt.Server(a) & rt.Server(b) case rt.Nothing{}: Unit# Reading values (as http-api-data reads them)# --------------------------------------------def rt.unparsed(+s: String, more: String) -> String: "could not parse: `" ++ s ++ "'" ++ more# Decimal digits: the value, and what is left after them (Data.Text.Read's# decimal).type rt.Dec is Data: rt.Dec{n: Nat, rest: String}def rt.dec.at(d: Maybe<&2, J.js.D>, +n: Nat, h: Char, t: String, more: Nat -> rt.Dec) -> rt.Dec: match d: case Some{x}: more(Nat.add(Nat.mul(n, 10n), J.js.d.val(x))) case None{}: rt.Dec{n, SCon{h, t}}def rt.dec.go(cs: String, +n: Nat) -> rt.Dec: match cs: case SNil{}: rt.Dec{n, ""} case SCon{Chr{+c}, +t}: rt.dec.at(J.js.d.of(c), n, Chr{c}, t, m => rt.dec.go(t, m))def rt.nat.fin(+s: String, d: rt.Dec) -> Result<&2, &2, String, Nat>: match d: case rt.Dec{n, SNil{}}: Done{n} case rt.Dec{n, r}: Fail{rt.unparsed(s, "")}def rt.nat.first(m: Maybe<&2, J.js.D>, +s: String, ds: String) -> Result<&2, &2, String, Nat>: match m: case Some{d}: rt.nat.fin(s, rt.dec.go(ds, 0n)) case None{}: Fail{rt.unparsed(s, " (input does not start with a digit)")}# a natural number in decimal, the whole of s (ds: what is left of s)def rt.nat.read(+s: String, ds: String) -> Result<&2, &2, String, Nat>: match ds: case SNil{}: Fail{rt.unparsed(s, " (input does not start with a digit)")} case SCon{Chr{+c}, t}: rt.nat.first(J.js.d.of(c), s, SCon{Chr{c}, t})def rt.int.sign(neg: Bool, r: Result<&2, &2, String, Nat>) -> Result<&2, &2, String, rt.Int>: match r: case Fail{e}: Fail{e} case Done{n}: Done{rt.Int{neg, n}}def rt.int.at(minus: Bool, plus: Bool, +s: String, t: String) -> Result<&2, &2, String, rt.Int>: match minus plus: case True{} _: rt.int.sign(True{}, rt.nat.read(s, t)) case False{} True{}: rt.int.sign(False{}, rt.nat.read(s, t)) case False{} False{}: rt.int.sign(False{}, rt.nat.read(s, s))# an integer: a sign ("-", "+" or none), then decimal digitsdef rt.int.read(+s: String) -> Result<&2, &2, String, rt.Int>: match s: case SNil{}: Fail{rt.unparsed("", " (input does not start with a digit)")} case SCon{Chr{+c}, +t}: rt.int.at(U32.is_eq(c, 45), U32.is_eq(c, 43), SCon{Chr{c}, t}, t)def rt.num.got(+s: String, m: Maybe<&2, J.js.Json>) -> Result<&2, &2, String, J.js.Num>: match m: case Some{J.js.Number{n}}: Done{n} case x: Fail{rt.unparsed(s, "")}def rt.num.first(m: Maybe<&2, J.js.D>, minus: Bool, +s: String) -> Result<&2, &2, String, J.js.Num>: match m minus: case None{} False{}: Fail{rt.unparsed(s, " (input does not start with a digit)")} case x y: rt.num.got(s, J.js.parse(s))# a decimal (as JSON writes one)def rt.num.read(+s: String) -> Result<&2, &2, String, J.js.Num>: match s: case SNil{}: Fail{rt.unparsed("", " (input does not start with a digit)")} case SCon{Chr{+c}, +t}: rt.num.first(J.js.d.of(c), U32.is_eq(c, 45), SCon{Chr{c}, t})# A value of a type read from text (a capture's segment, a parameter's value)def rt.parse(t: rt.Ty, +s: String) -> Result<&2, &2, String, rt.TVal(t)>: match t: case rt.TNat{}: rt.nat.read(s, s) case rt.TInt{}: rt.int.read(s) case rt.TText{}: Done{s} case rt.TNum{}: rt.num.read(s)# and written back as textdef rt.print(t: rt.Ty, v: rt.TVal(t)) -> String: match t v: case rt.TNat{} n: Nat.show(n) case rt.TInt{} rt.Int{neg, n}: Bool.pick(String, neg, "-", "") ++ Nat.show(n) case rt.TText{} x: x case rt.TNum{} n: J.js.num(n, "")# Requests read# -------------# servant's order of misses: keep the first unless the second tells moredef rt.why.max(a: rt.Why, b: rt.Why) -> rt.Why: match a b: case rt.NotFound{} y: y case rt.NotAllowed{} rt.NotFound{}: rt.NotAllowed{} case rt.NotAllowed{} y: y case rt.Unsupported{} rt.Unread{m}: rt.Unread{m} case rt.Unsupported{} y: rt.Unsupported{} case rt.Unread{m} y: rt.Unread{m}def rt.alt.second(-A: Data, -B: Data, w: rt.Why, r: rt.Res<B>) -> rt.Res<Either<&2, &2, A, B>>: match r: case rt.Hit{v}: rt.Hit{Inr{v}} case rt.Bad{m}: rt.Bad{m} case rt.No{w2}: rt.No{rt.why.max(w, w2)}# a, else b: the first hit, or the first final error, or the more telling missdef rt.alt(-A: Data, -B: Data, r: rt.Res<A>, more: Unit -> rt.Res<B>) -> rt.Res<Either<&2, &2, A, B>>: match r: case rt.Hit{v}: rt.Hit{Inl{v}} case rt.Bad{m}: rt.Bad{m} case rt.No{w}: rt.alt.second(A, B, w, more(Unit{}))def rt.seg.at(-A: Data, hit: Bool, more: Unit -> rt.Res<A>) -> rt.Res<A>: match hit: case True{}: more(Unit{}) case False{}: rt.No{rt.NotFound{}}# an input read where the rest of the API hits: its error, the rest's, or bothdef rt.input(-V: Data, -K: Data, rest: rt.Res<K>, r: Result<&2, &2, String, V>) -> rt.Res<C.js.P<V, K>>: match rest r: case rt.No{w} x: rt.No{w} case y Fail{m}: rt.Bad{m} case rt.Bad{m} Done{v}: rt.Bad{m} case rt.Hit{k} Done{v}: rt.Hit{C.js.P{v, k}}def rt.cap.at(-V: Data, -K: Data, +name: String, r: Result<&2, &2, String, V>, more: Unit -> rt.Res<K>) -> rt.Res<C.js.P<V, K>>: match r: case Fail{e}: rt.No{rt.Unread{"Error parsing capture " ++ name ++ " failed: " ++ e}} case Done{v}: rt.input(V, K, more(Unit{}), Done{v})def rt.qparse.got(+name: String, -t: rt.Ty, r: Result<&2, &2, String, rt.TVal(t)>) -> Result<&2, &2, String, Maybe<&2, rt.TVal(t)>>: match r: case Fail{e}: Fail{"Error parsing query parameter " ++ name ++ " failed: " ++ e} case Done{v}: Done{Some{v}}def rt.qparse(+name: String, +t: rt.Ty, m: Maybe<&2, String>) -> Result<&2, &2, String, Maybe<&2, rt.TVal(t)>>: match m: case None{}: Done{None{}} case Some{+s}: rt.qparse.got(name, t, rt.parse(t, s))def rt.hdr(hs: List<&2, W.wr.H>, +name: String) -> Maybe<&2, String>: match hs: case Nil{}: None{} case Con{W.wr.H{+n, +v}, t}: rt.if(Maybe<&2, String>, String.eq(n, name), u => Some{v}, u => rt.hdr(t, name))def rt.mime.cut(ps: List<&2, String>) -> String: match ps: case Con{p, t}: p case Nil{}: ""# the request's media type (before any ";"), lower case; "" nonedef rt.mime(+hs: List<&2, W.wr.H>) -> String: String.to_lower(String.trim(rt.mime.cut(String.split(W.wr.header(hs, "content-type"), ';'))))def rt.body.in(-V: Data, -K: Data, ok: Bool, rest: rt.Res<K>, r: Result<&2, &2, String, V>) -> rt.Res<C.js.P<V, K>>: match ok rest: case x rt.No{w}: rt.No{w} case False{} y: rt.No{rt.Unsupported{}} case True{} y: rt.input(V, K, y, r)def rt.json.got(-sh: C.js.Sh, m: Maybe<&2, C.js.Val(sh)>) -> Result<&2, &2, String, C.js.Val(sh)>: match m: case Some{v}: Done{v} case None{}: Fail{"Error in $: the body is not the JSON wanted"}def rt.req.path(r: W.wr.Req, ps: List<&2, String>) -> W.wr.Req: match r: case W.wr.Req{m, v, p, raw, q, hs, b, x}: W.wr.Req{m, v, ps, raw, q, hs, b, x}def rt.done(ps: List<&2, String>) -> Bool: match ps: case Nil{}: True{} case Con{SNil{}, Nil{}}: True{} case x: False{}def rt.verb.at(done: Bool, ok: Bool) -> rt.Res<Unit>: match done ok: case False{} x: rt.No{rt.NotFound{}} case True{} False{}: rt.No{rt.NotAllowed{}} case True{} True{}: rt.Hit{Unit{}}def rt.method.ok(+want: String, +m: String) -> Bool: String.eq(want, m) || (String.eq(want, "GET") && String.eq(m, "HEAD"))# What a request means to an API, its path still to go being ps.def rt.go(+a: rt.Api, +req: W.wr.Req, +ps: List<&2, String>) -> rt.Res<rt.In(a)>: match a ps: case rt.Seg{+s, +k} Con{+p, +rest}: rt.seg.at(rt.In(k), String.eq(s, p), u => rt.go(k, req, rest)) case rt.Seg{s, k} Nil{}: rt.No{rt.NotFound{}} case rt.Cap{+n, +t, +k} Con{+p, +rest}: rt.cap.at(rt.TVal(t), rt.In(k), n, rt.parse(t, p), u => rt.go(k, req, rest)) case rt.Cap{n, t, k} Nil{}: rt.No{rt.NotFound{}} case rt.Qry{+n, +t, +k} qs: rt.input(Maybe<&2, rt.TVal(t)>, rt.In(k), rt.go(k, req, qs), rt.qparse(n, t, W.wr.param(W.wr.req.query(req), n))) case rt.Hdr{+n, +k} qs: rt.input(Maybe<&2, String>, rt.In(k), rt.go(k, req, qs), Done{rt.hdr(W.wr.req.headers(req), n)}) case rt.Peer{+k} qs: rt.input(String, rt.In(k), rt.go(k, req, qs), Done{W.wr.req.peer(req)}) case rt.Body{+sh, +k} qs: rt.body.in(C.js.Val(sh), rt.In(k), String.eq(rt.mime(W.wr.req.headers(req)), "application/json"), rt.go(k, req, qs), rt.json.got(sh, C.js.decode(sh, W.wr.utf8(W.wr.req.body(req))))) case rt.Bytes{+k} qs: rt.body.in(List<&2, U32>, rt.In(k), String.eq(rt.mime(W.wr.req.headers(req)), "application/octet-stream") || String.eq(rt.mime(W.wr.req.headers(req)), ""), rt.go(k, req, qs), Done{W.wr.req.body(req)}) case rt.Verb{+m, s} qs: rt.verb.at(rt.done(qs), rt.method.ok(m, W.wr.req.method(req))) case rt.Raw{} qs: rt.Hit{rt.req.path(req, qs)} case rt.Alt{+x, +y} qs: rt.alt(rt.In(x), rt.In(y), rt.go(x, req, qs), u => rt.go(y, req, qs)) case rt.Nothing{} qs: rt.No{rt.NotFound{}}# a request read by an APIdef rt.route(+a: rt.Api, +req: W.wr.Req) -> rt.Res<rt.In(a)>: rt.go(a, req, W.wr.req.path(req))# Serving# -------def rt.json.type() -> W.wr.H: W.wr.H{"Content-Type", "application/json;charset=utf-8"}def rt.render(+sh: C.js.Sh, r: rt.Reply<C.js.Val(sh)>) -> W.wr.Resp: match r: case rt.Ok{hs, v}: W.wr.Resp{200, rt.json.type() <> hs, W.wr.Text{C.js.encode(sh, v)}} case rt.Err{st, hs, b}: W.wr.Resp{st, hs, W.wr.Text{b}}def rt.answer(+sh: C.js.Sh, io: IO(rt.Reply<C.js.Val(sh)>)) -> IO(W.wr.Resp): do IO<W.wr.Resp>: r : rt.Reply<C.js.Val(sh)> <- io return rt.render(sh, r)# what serves an API, given what a request gave itdef rt.apply(+a: rt.Api, s: rt.Server(a), i: rt.In(a)) -> IO(W.wr.Resp): match a s i: case rt.Seg{x, +k} f j: rt.apply(k, f, j) case rt.Cap{n, t, +k} f C.js.P{v, j}: rt.apply(k, f(v), j) case rt.Qry{n, t, +k} f C.js.P{v, j}: rt.apply(k, f(v), j) case rt.Hdr{n, +k} f C.js.P{v, j}: rt.apply(k, f(v), j) case rt.Peer{+k} f C.js.P{v, j}: rt.apply(k, f(v), j) case rt.Body{sh, +k} f C.js.P{v, j}: rt.apply(k, f(v), j) case rt.Bytes{+k} f C.js.P{v, j}: rt.apply(k, f(v), j) case rt.Verb{m, +sh} io u: rt.answer(sh, io) case rt.Raw{} f r: f(r) case rt.Alt{+x, +y} Tuple{sa, sb} Inl{j}: rt.apply(x, sa, j) case rt.Alt{+x, +y} Tuple{sa, sb} Inr{j}: rt.apply(y, sb, j) case rt.Nothing{} u e: match e:def rt.miss(w: rt.Why) -> W.wr.Resp: match w: case rt.NotFound{}: W.wr.Resp{404, [], W.wr.Text{""}} case rt.NotAllowed{}: W.wr.Resp{405, [], W.wr.Text{""}} case rt.Unsupported{}: W.wr.Resp{415, [], W.wr.Text{""}} case rt.Unread{m}: W.wr.Resp{400, [], W.wr.Text{m}}def rt.fin(+a: rt.Api, s: rt.Server(a), r: rt.Res<rt.In(a)>) -> IO(W.wr.Resp): match r: case rt.Hit{i}: rt.apply(a, s, i) case rt.No{w}: IO.pure(W.wr.Resp, rt.miss(w)) case rt.Bad{m}: IO.pure(W.wr.Resp, W.wr.Resp{400, [], W.wr.Text{m}})# A request served: read by the API, then answered by the serverdef rt.serve(+a: rt.Api, s: rt.Server(a), +req: W.wr.Req) -> IO(W.wr.Resp): rt.fin(a, s, rt.route(a, req))# Docs# ----def rt.ty.name(t: rt.Ty) -> String: match t: case rt.TNat{}: "natural" case rt.TInt{}: "integer" case rt.TText{}: "text" case rt.TNum{}: "decimal"# Each endpoint as a line: its method, path (":name" a capture), query# parameters and what else it reads.def rt.docs(a: rt.Api, +path: String, +more: String) -> List<&2, String>: match a: case rt.Seg{s, k}: rt.docs(k, path ++ "/" ++ s, more) case rt.Cap{+n, t, k}: rt.docs(k, path ++ "/:" ++ n, more ++ " " ++ n ++ ":" ++ rt.ty.name(t)) case rt.Qry{n, t, k}: rt.docs(k, path, more ++ " ?" ++ n ++ ":" ++ rt.ty.name(t)) case rt.Hdr{n, k}: rt.docs(k, path, more ++ " [" ++ n ++ "]") case rt.Peer{k}: rt.docs(k, path, more ++ " [peer]") case rt.Body{s, k}: rt.docs(k, path, more ++ " <json>") case rt.Bytes{k}: rt.docs(k, path, more ++ " <bytes>") case rt.Verb{m, s}: [m ++ " " ++ path ++ more] case rt.Raw{}: ["* " ++ path ++ "/..." ++ more] case rt.Alt{x, y}: List.append(&2, String, rt.docs(x, path, more), rt.docs(y, path, more)) case rt.Nothing{}: []