~/bend-docscommunity

src/server.bend source

src/server.bend on the hub · documented module

# ezhttp/src/server: listen, accept, and serve each connection on its own# fork: parse one request, write one response (Connection: close). Sockets# are Base's (listen) and bend-kit-wire's (accept with a deadline, recv,# send.words), whose effects park on the event loop, so connections overlap.# A `_with` serve hands the handler a context value and the request as text# with its body's octets, and takes a reply as text, packed octets or a# stream of octet chunks; the plain serves are those with a text handler.# Every decision after an effect is step.bend's or http.bend's, proved under# laws/ (the server's guarantees, such as laws/BadRequestAnswers400.bend);# this module runs the effects in order (trusted below).## Trusted, not proved: Base's TCP effects (listen, accept, send) and# bend-kit-wire's `recv` on an accepted socket report a failure as `Fail`# and never end the process themselves; `recv` answers the octets that# arrived, one character each, and no octets once the peer has closed. They# are foreign C in Bend's runtime (`effs/tcp_*.c`) and in bend-kit-wire# (`effs/wire.c`), which no law reaches.## Trusted, not proved: this module acts on step.bend's answers in order. It# listens, then accepts with bend-kit-wire's `accept.deadline` one# connection at a time, and serves each accepted connection on its own fork# (`IO.spawn`); with a concurrency limit `max` other than 0 it takes a slot# before forking and gives it back when the connection is closed, so at most# `max` connections are served at once. On each connection it receives the# request until the octets `step.need` names have arrived (the head, its# blank line and its Content-Length), the peer closes, or 65536 receives# have been made, parses it, calls the handler only for a `Call`, with the# serve's context and the request `step.text` and `step.octets` give, writes# the reply `step.bare` shapes (a text reply as the UTF-8 of `respond`, a# packed octets reply as `respond.head` and its octets, a streamed one as# `respond.stream`, then each chunk the channel gives as `chunk.frame`# writes it until the channel is closed, then `chunk.end`) with# bend-kit-wire's `send.words`, and closes the socket; a lost connection's# line is written to stderr and the socket closed. `http.serve`,# `http.serve_with`, `http.serve_io` and `http.serve_io_with` stop accepting# after `limit` connections, a failed accept counting as one and an accept# whose deadline passed not counting, and return once every connection they# forked is closed; `http.serve_forever` and `http.serve_forever_with` do# not stop. It is IO sequencing over Base's and bend-kit-wire's effects and# the runtime's `IO.spawn` and channels: the checker cannot run an IO# program and no law can state what happens after an effect, or which fork# runs when. The serve_forever defs are also `@unsafe` recursion, outside# the termination check.import Baseimport bend-kit-wire@0.4.6.1/wire.bend as Wimport bend-kit-bytes@0.3.2.0/bytes.bend as Bytesimport ./http.bend as Httpimport ./cors.bend as Corsimport ./step.bend as Stepimport ./wirespec.bend as Spec# what a `_with` handler gets: the request as text (step.text) and its# body's octets as they arrived (step.octets)type Req is Type:  # noqa: L001 it holds Bytes; step.text and step.octets fill it  Req{method: String, target: String, headers: List<&2, Http.Header>,    body: String, bytes: Bytes.Bytes}# what a `_with` handler answers: a text body (written as UTF-8), packed# octets written unchanged, or a stream of octet chunks from a channel,# written chunked until the channel is closed# (laws/ReplyHeadFramesBody.bend, laws/StreamedRepliesAreChunked.bend)type Answer is Type:  # noqa: L001 it holds Bytes and a channel; the reply laws cover its writing  TextReply{status: U32, headers: List<&2, Http.Header>, body: String}  OctetsReply{status: U32, headers: List<&2, Http.Header>, bytes: Bytes.Bytes}  StreamReply{status: U32, headers: List<&2, Http.Header>,    chunks: Chan(Bytes.Bytes)}# the most octets one receive asks fordef server.max() -> U32:  65536# the most receives one request takesdef server.reads() -> Nat:  65536n# how long one accept waits before it is asked again, in msdef server.wait() -> U32:  3600000# how many idle accepts in a row a limited serve allows before it stopsdef server.idles() -> Nat:  1000000n# how long a failed accept waits before the next, so EMFILE does not spindef server.pause() -> U32:  100# listen on a host address and port, e.g. "127.0.0.1" or "0.0.0.0"def server.listen(host: String, port: U32) -> IO(Listener):  IO.try(Listener, TCP.listen(host, port))# accept one connection, waiting at most server.wait() msdef server.accept.un(  r: Listener & Result<&1, &1, U32 & String, Socket>) -> IO(Listener & Step.Accept<Socket>):  (lst, res) = r  IO.pure(Listener & Step.Accept<Socket>, (lst, Step.step.accepted(Socket, res)))def server.accept(listener: Listener) -> IO(Listener & Step.Accept<Socket>):  IO.bind(Listener & Result<&1, &1, U32 & String, Socket>,    Listener & Step.Accept<Socket>,    W.accept.deadline(listener, server.wait()), server.accept.un)# a lost connection logs its line and closesdef server.lose(sock: Socket, line: String) -> IO(Unit):  IO.bind(Unit, Unit, IO.print_err(line), _u => Socket.close(sock))# --- reading a request ---# the request once it has all arrived (or the peer closed, or the receives# ran out): its pieces put together and parseddef server.read.done(  sock: Socket,  ps: List<&2, String>) -> IO(Socket & Step.Got<Http.Request>):  IO.pure(Socket & Step.Got<Http.Request>,    (sock, Step.Kept{Http.ask(Spec.wire.join(ps))}))# what the request needs, kept once its head has endeddef server.read.needs(  m: Maybe<&2, Nat>,  ps: List<&2, String>) -> Maybe<&2, Nat>:  match m:    case None{}:      Step.step.need(Spec.wire.join(ps))    case Some{n}:      Some{n}# whether as much has arrived as the request needsdef server.read.whole(m: Maybe<&2, Nat>, +have: Nat) -> Bool:  match m:    case None{}:      False{}    case Some{n}:      Nat.is_ge(have, n)# octets that arrived: stop when the request is whole, else read againdef server.read.more(  sock: Socket,  +ps: List<&2, String>,  +have: Nat,  +need: Maybe<&2, Nat>,  whole: Bool,  rest: Socket -> List<&2, String> -> Nat -> Maybe<&2, Nat> -> IO(Socket & Step.Got<Http.Request>)) -> IO(Socket & Step.Got<Http.Request>):  match whole:    case True{}:      server.read.done(sock, ps)    case False{}:      rest(sock)(ps)(have)(need)# octets added to the pieces: is the request now whole?def server.read.add(  sock: Socket,  +ps: List<&2, String>,  +have: Nat,  need: Maybe<&2, Nat>,  rest: Socket -> List<&2, String> -> Nat -> Maybe<&2, Nat> -> IO(Socket & Step.Got<Http.Request>)) -> IO(Socket & Step.Got<Http.Request>):  +need2 = server.read.needs(need, ps)  server.read.more(sock, ps, have, need2, server.read.whole(need2, have), rest)# octets that arrived, or none once the peer has closeddef server.read.text(  sock: Socket,  +ps: List<&2, String>,  +have: Nat,  need: Maybe<&2, Nat>,  +text: String,  closed: Bool,  rest: Socket -> List<&2, String> -> Nat -> Maybe<&2, Nat> -> IO(Socket & Step.Got<Http.Request>)) -> IO(Socket & Step.Got<Http.Request>):  match closed:    case True{}:      server.read.done(sock, ps)    case False{}:      server.read.add(sock, text <> ps, Nat.add(have, String.length(text)),        need, rest)# a receive's answer: a failure loses the connection, no octets is the peer# closing, octets go onto the piecesdef server.read.got(  +ps: List<&2, String>,  +have: Nat,  need: Maybe<&2, Nat>,  r: Socket & Result<&1, &1, U32 & String, String>,  rest: Socket -> List<&2, String> -> Nat -> Maybe<&2, Nat> -> IO(Socket & Step.Got<Http.Request>)) -> IO(Socket & Step.Got<Http.Request>):  (sock, res) = r  match res:    case Fail{(code, why)}:      IO.pure(Socket & Step.Got<Http.Request>,        (sock, Step.Dropped{Step.step.line("read", why)}))    case Done{+text}:      server.read.text(sock, ps, have, need, text, String.is_empty(text), rest)# receive until the head has ended and its Content-Length has arrived, the# peer closes, or the receives run outdef server.read.go(  fuel: Nat,  sock: Socket,  +ps: List<&2, String>,  +have: Nat,  +need: Maybe<&2, Nat>) -> IO(Socket & Step.Got<Http.Request>):  match fuel:    case 0n:      server.read.done(sock, ps)    case 1n+f:      IO.bind(Socket & Result<&1, &1, U32 & String, String>,        Socket & Step.Got<Http.Request>,        W.recv(sock, server.max(), 0),        r => server.read.got(ps, have, need, r,          s => p => h => m => server.read.go(f, s, p, h, m)))# receive then parse an HTTP request (RFC 9112 §3)def server.read(sock: Socket) -> IO(Socket & Step.Got<Http.Request>):  server.read.go(server.reads(), sock, [], 0n, None{})# --- writing a reply ---# after a send: the socket, or the line of a lost connectiondef server.sent.un(  r: Socket & Result<&1, &1, U32 & String, Unit>) -> IO(Socket & Step.Got<Unit>):  (sock, res) = r  IO.pure(Socket & Step.Got<Unit>, (sock, Step.step.got(Unit, "write", res)))# send octetsdef server.send(sock: Socket, b: Bytes.Bytes) -> IO(Socket & Step.Got<Unit>):  Bytes.Bytes{+len, buf} = b  IO.bind(Socket & Result<&1, &1, U32 & String, Unit>, Socket & Step.Got<Unit>,    W.send.words(sock, len, buf), server.sent.un)# send text as its UTF-8 octetsdef server.send.text(sock: Socket, text: String) -> IO(Socket & Step.Got<Unit>):  server.send(sock, Bytes.from_string(Spec.wire.payload(text)))# after the last send: close, logging first when it faileddef server.close(r: Socket & Step.Got<Unit>) -> IO(Unit):  (sock, got) = r  match got:    case Step.Dropped{line}:      server.lose(sock, line)    case Step.Kept{_u}:      Socket.close(sock)# after a send in the middle: go on, or lose the connectiondef server.then(  r: Socket & Step.Got<Unit>,  more: Socket -> IO(Unit)) -> IO(Unit):  (sock, got) = r  match got:    case Step.Dropped{line}:      server.lose(sock, line)    case Step.Kept{_u}:      more(sock)# a text reply shaped for the request's method# (laws/HeadAndNoContentHaveNoBody.bend), then closedef server.answer(sock: Socket, method: String, reply: Http.Reply) -> IO(Unit):  IO.bind(Socket & Step.Got<Unit>, Unit,    server.send.text(sock, Http.respond.of(Http.reply.for(method, reply))),    server.close)# an octets reply once its length is known: its head, then its octets unless# it is bare (laws/ReplyHeadFramesBody.bend,# laws/BareRepliesWriteHeadOnly.bend)def server.octets.go(  sock: Socket,  +status: U32,  headers: List<&2, Http.Header>,  r: Bytes.Bytes & U32,  bare: Bool) -> IO(Unit):  (b, +n) = r  match bare:    case True{}:      IO.bind(Socket & Step.Got<Unit>, Unit,        server.send.text(sock, Http.respond.head(status, headers, 0n)),        server.close)    case False{}:      IO.bind(Socket & Step.Got<Unit>, Unit,        server.send(sock, Bytes.append(Bytes.from_string(          Http.respond.head(status, headers, U32.to_nat(n))), b)),        server.close)# the most chunks one streamed reply writesdef server.chunks() -> Nat:  4294967295n# one chunk the channel gave: framed and sent, or skipped when emptydef server.chunk.put(  sock: Socket,  c: Http.Chunk,  b: Bytes.Bytes,  more: Socket -> IO(Unit)) -> IO(Unit):  match c:    case Http.NoChunk{}:      more(sock)    case Http.Chunk{line}:      IO.bind(Socket & Step.Got<Unit>, Unit,        server.send(sock, Bytes.append(Bytes.append(Bytes.from_string(line), b),          Bytes.from_string("\r\n"))),        r => server.then(r, more))# a chunk with its length knowndef server.chunk.sized(  sock: Socket,  r: Bytes.Bytes & U32,  more: Socket -> IO(Unit)) -> IO(Unit):  (b, +n) = r  server.chunk.put(sock, Http.chunk.frame(n), b, more)# what the channel gave: a chunk, or its close, which ends the bodydef server.chunk.got(  sock: Socket,  m: Maybe<&1, Bytes.Bytes>,  more: Socket -> IO(Unit)) -> IO(Unit):  match m:    case None{}:      IO.bind(Socket & Step.Got<Unit>, Unit,        server.send.text(sock, Http.chunk.end()), server.close)    case Some{b}:      server.chunk.sized(sock, Bytes.length(b), more)# every chunk the channel gives, until it is closeddef server.stream.go(  fuel: Nat,  sock: Socket,  +ch: Chan(Bytes.Bytes)) -> IO(Unit):  match fuel:    case 0n:      IO.bind(Socket & Step.Got<Unit>, Unit,        server.send.text(sock, Http.chunk.end()), server.close)    case 1n+f:      IO.bind(Maybe<&1, Bytes.Bytes>, Unit, Chan.recv(Bytes.Bytes, ch),        m => server.chunk.got(sock, m, s => server.stream.go(f, s, ch)))# a streamed reply after its head: its chunks, or nothing when it is baredef server.stream.body(  sock: Socket,  +ch: Chan(Bytes.Bytes),  bare: Bool) -> IO(Unit):  match bare:    case True{}:      IO.bind(Unit, Unit, Chan.close(Bytes.Bytes, ch), _u => Socket.close(sock))    case False{}:      server.stream.go(server.chunks(), sock, ch)# a handler's answer, shaped for the request's method# (laws/HeadAndNoContentHaveNoBody.bend, laws/ReplyHeadFramesBody.bend,# laws/StreamedRepliesAreChunked.bend, laws/BareRepliesWriteHeadOnly.bend)def server.reply(sock: Socket, +method: String, a: Answer) -> IO(Unit):  match a:    case TextReply{status, headers, body}:      server.answer(sock, method, Http.Reply{status, headers, body})    case OctetsReply{+status, headers, bytes}:      server.octets.go(sock, status, headers, Bytes.length(bytes),        Step.step.bare(method, status))    case StreamReply{+status, +headers, +chunks}:      IO.bind(Socket & Step.Got<Unit>, Unit,        server.send.text(sock, Http.respond.stream(status, headers)),        r => server.then(r,          s => server.stream.body(s, chunks, Step.step.bare(method, status))))# --- one connection ---# the handler's request: the request as text and its body's octetsdef server.req(req: Http.Request, +octets: String) -> Req:  match req:    case Http.Bad{why}:      Req{"", "", [], why, Bytes.from_string(octets)}    case Http.Request{method, target, headers, body}:      Req{method, target, headers, body, Bytes.from_string(octets)}# answer now, or call the handler: step.bend decides which# (laws/BadRequestAnswers400.bend, laws/HandlerGetsRequestText.bend,# laws/WithServesGetOctetsAndContext.bend)def server.step(  ~C: Data,  ~handle: C -> Req -> IO(Answer),  +ctx: C,  sock: Socket,  +method: String,  +octets: String,  step: Step.Step) -> IO(Unit):  match step:    case Step.Answer{reply}:      server.answer(sock, method, reply)    case Step.Call{req}:      IO.bind(Answer, Unit, handle(ctx)(server.req(req, octets)),        a => server.reply(sock, method, a))# after the read: a lost connection, or a request to stepdef server.conn.got(  ~C: Data,  ~handle: C -> Req -> IO(Answer),  +ctx: C,  r: Socket & Step.Got<Http.Request>) -> IO(Unit):  (sock, got) = r  match got:    case Step.Dropped{line}:      server.lose(sock, line)    case Step.Kept{+raw}:      +req = Step.step.text(raw)      server.step(~C, handle, ctx, sock, Http.method.of(req),        Step.step.octets(raw), Step.step.of(req))# one connection: read, decide, maybe handle, write, closedef server.conn(  ~C: Data,  ~handle: C -> Req -> IO(Answer),  +ctx: C,  sock: Socket) -> IO(Unit):  IO.bind(Socket & Step.Got<Http.Request>, Unit, server.read(sock),    r => server.conn.got(~C, handle, ctx, r))# --- the accept loop ---# give a slot backdef server.slot.give(+slots: Chan(Unit), limited: Bool) -> IO(Unit):  match limited:    case True{}:      IO.bind(Maybe<&1, Unit>, Unit, Chan.recv(Unit, slots),        _m => IO.pure(Unit, Unit{}))    case False{}:      IO.pure(Unit, Unit{})# take a slot, waiting while every one is takendef server.slot.take(+slots: Chan(Unit), limited: Bool) -> IO(Unit):  match limited:    case True{}:      IO.bind(Result<&1, &1, Unit, Unit>, Unit, Chan.send(Unit, slots, Unit{}),        _r => IO.pure(Unit, Unit{}))    case False{}:      IO.pure(Unit, Unit{})# say a fork is done, when the serve waits for its forksdef server.done(+done: Chan(Unit), tracked: Bool) -> IO(Unit):  match tracked:    case True{}:      IO.bind(Result<&1, &1, Unit, Unit>, Unit, Chan.send(Unit, done, Unit{}),        _r => IO.pure(Unit, Unit{}))    case False{}:      IO.pure(Unit, Unit{})# a connection's fork: serve it, give its slot back, and say it is donedef server.fork.body(  ~C: Data,  ~handle: C -> Req -> IO(Answer),  +ctx: C,  sock: Socket,  +pool: Step.Pool) -> IO(Unit):  Step.Pool{slots, limited, done, tracked} = pool  IO.bind(Unit, Unit, server.conn(~C, handle, ctx, sock),    _u => IO.bind(Unit, Unit, server.slot.give(slots, limited),      _v => server.done(done, tracked)))# serve an accepted connection on its own fork, a slot taken firstdef server.fork(  ~C: Data,  ~handle: C -> Req -> IO(Answer),  +ctx: C,  sock: Socket,  +pool: Step.Pool) -> IO(Unit):  Step.Pool{slots, limited, done, tracked} = pool  IO.bind(Unit, Unit, server.slot.take(slots, limited),    _u => IO.spawn(Unit, server.fork.body(~C, handle, ctx, sock, pool)))# wait for n forks to say they are donedef server.join(n: Nat, +done: Chan(Unit)) -> IO(Unit):  match n:    case 0n:      IO.pure(Unit, Unit{})    case 1n+p:      IO.bind(Maybe<&1, Unit>, Unit, Chan.recv(Unit, done),        _m => server.join(p, done))# what an accept brought, for the loop: `took` serves a connection and goes# on with one connection fewer, `idle` accepts again, `missed` logs, pauses# and goes on with one fewer (a failed accept counts toward the limit)def server.loop.got(  ~C: Data,  ~handle: C -> Req -> IO(Answer),  +ctx: C,  +pool: Step.Pool,  r: Listener & Step.Accept<Socket>,  took: Listener -> IO(Unit),  idle: Listener -> IO(Unit),  missed: Listener -> IO(Unit)) -> IO(Unit):  (lst, got) = r  match got:    case Step.Took{sock}:      IO.bind(Unit, Unit, server.fork(~C, handle, ctx, sock, pool),        _u => took(lst))    case Step.Idle{}:      idle(lst)    case Step.Missed{line}:      IO.bind(Unit, Unit, IO.print_err(line), _u =>        IO.bind(Unit, Unit, IO.sleep(server.pause()), _v => missed(lst)))# the limited accept loop: `fuel` connections left, `idles` idle accepts in# a row left, `forks` forked so far; its pool is tracked, so the loop joins# its forks on `done` before it returnsdef server.loop.go(  ~C: Data,  ~handle: C -> Req -> IO(Answer),  +ctx: C,  fuel: Nat,  idles: Nat,  +forks: Nat,  +pool: Step.Pool,  listener: Listener) -> IO(Unit):  match fuel idles:    case 0n _:      IO.bind(Unit, Unit, Listener.close(listener),        _u => server.join(forks, Step.step.pool.done(pool)))    case 1n+_f 0n:      IO.bind(Unit, Unit, Listener.close(listener),        _u => server.join(forks, Step.step.pool.done(pool)))    case 1n+f0 1n+i:      +f = f0      IO.bind(Listener & Step.Accept<Socket>, Unit, server.accept(listener),        r => server.loop.got(~C, handle, ctx, pool, r,          l => server.loop.go(~C, handle, ctx, f, server.idles(), 1n+forks,            pool, l),          l => server.loop.go(~C, handle, ctx, 1n+f, i, forks, pool, l),          l => server.loop.go(~C, handle, ctx, f, server.idles(), forks, pool,            l)))# the slots a concurrency limit allows (max 0: no limit)def server.slots(+max: U32) -> IO(Chan(Unit)):  Chan.new(Unit, Bool.pick(U32, U32.is_eq(max, 0), 1, max))# listen and serve up to `limit` connections, each on its own fork, at most# `max` at once (0: no limit), with a context value for the handler; returns# once every fork is done (trusted above)def server.serve_io_with(  ~C: Data,  ~handle: C -> Req -> IO(Answer),  +ctx: C,  host: String,  port: U32,  limit: U32,  +max: U32) -> IO(Unit):  do IO<Unit>:    lst : Listener <- server.listen(host, port)    +slots : Chan(Unit) <- server.slots(max)    +done : Chan(Unit) <- Chan.new(Unit, 1024)    server.loop.go(~C, handle, ctx, U32.to_nat(limit), server.idles(), 0n,      Step.step.pool(slots, max, done, True{}), lst)# a pure handler as an IO onedef server.lift.with(  ~C: Data,  ~handle: C -> Req -> Answer,  +ctx: C,  req: Req) -> IO(Answer):  IO.pure(Answer, handle(ctx)(req))# listen and serve with a pure handler and a context valuedef server.serve_with(  ~C: Data,  ~handle: C -> Req -> Answer,  +ctx: C,  host: String,  port: U32,  limit: U32,  max: U32) -> IO(Unit):  server.serve_io_with(~C, ~(c => r => server.lift.with(~C, handle, c, r)), ctx,    host, port, limit, max)# the accept loop with no limit: it runs until the process is stopped; its# pool is untracked, so its forks never say they are done@unsafe def server.forever.go(  ~C: Data,  ~handle: C -> Req -> IO(Answer),  +ctx: C,  +pool: Step.Pool,  listener: Listener) -> IO(Unit):  IO.bind(Listener & Step.Accept<Socket>, Unit, server.accept(listener),    r => server.loop.got(~C, handle, ctx, pool, r,      l => server.forever.go(~C, handle, ctx, pool, l),      l => server.forever.go(~C, handle, ctx, pool, l),      l => server.forever.go(~C, handle, ctx, pool, l)))# listen and serve with an IO handler and a context value until the process# is stopped, at most `max` connections at once (0: no limit)@unsafe def server.serve_forever_with(  ~C: Data,  ~handle: C -> Req -> IO(Answer),  +ctx: C,  host: String,  port: U32,  +max: U32) -> IO(Unit):  do IO<Unit>:    lst : Listener <- server.listen(host, port)    +slots : Chan(Unit) <- server.slots(max)    +done : Chan(Unit) <- Chan.new(Unit, 1)    server.forever.go(~C, handle, ctx,      Step.step.pool(slots, max, done, False{}), lst)# --- the text handlers (no context) ---# a `_with` request as the text request a plain handler takesdef server.plain(r: Req) -> Http.Request:  Req{method, target, headers, body, bytes} = r  Http.Request{method, target, headers, body}# a text reply as an answerdef server.text(reply: Http.Reply) -> IO(Answer):  match reply:    case Http.Torn{why}:      IO.pure(Answer, TextReply{500, [], why})    case Http.Reply{status, headers, body}:      IO.pure(Answer, TextReply{status, headers, body})# a plain IO handler as a `_with` onedef server.wrap.io(  ~handle: Http.Request -> IO(Http.Reply),  r: Req) -> IO(Answer):  IO.bind(Http.Reply, Answer, handle(server.plain(r)), server.text)# listen and serve up to `limit` connections with an IO handlerdef server.serve_io(  ~handle: Http.Request -> IO(Http.Reply),  host: String,  port: U32,  limit: U32) -> IO(Unit):  server.serve_io_with(~Unit, ~(_u => r => server.wrap.io(handle, r)), Unit{},    host, port, limit, 0)# a pure handler as an IO onedef server.lift(  ~handle: Http.Request -> Http.Reply,  req: Http.Request) -> IO(Http.Reply):  IO.pure(Http.Reply, handle(req))# listen and serve up to `limit` connectionsdef server.serve(  ~handle: Http.Request -> Http.Reply,  host: String,  port: U32,  limit: U32) -> IO(Unit):  server.serve_io(~(req => server.lift(handle, req)), host, port, limit)# serve exactly one connection then stopdef server.once(  ~handle: Http.Request -> Http.Reply,  host: String,  port: U32) -> IO(Unit):  server.serve(handle, host, port, 1)# listen and serve with an IO handler until the process is stopped@unsafe def server.serve_forever(  ~handle: Http.Request -> IO(Http.Reply),  host: String,  port: U32) -> IO(Unit):  server.serve_forever_with(~Unit, ~(_u => r => server.wrap.io(handle, r)), Unit{},    host, port, 0)# --- CORS (cors.bend), for pure handlers ---# turn a bad request into 400; otherwise call the handlerdef server.dispatch(  ~handle: Http.Request -> Http.Reply,  req: Http.Request) -> Http.Reply:  match req:    case Http.Bad{why}:      Http.Reply{400, [], why}    case Http.Request{method, target, headers, body}:      handle(Http.Request{method, target, headers, body})# apply HEAD body stripping once the method token is knowndef server.reply.built(  ~handle: Http.Request -> Http.Reply,  method: String,  req: Http.Request) -> Http.Reply:  Http.reply.for(method, server.dispatch(handle, req))# HEAD responses are written with an empty body (RFC 9110 §9.3.2)def server.reply.text(  ~handle: Http.Request -> Http.Reply,  req: Http.Request) -> Http.Reply:  match req:    case Http.Bad{why}:      server.dispatch(handle, Http.Bad{why})    case Http.Request{+method, target, headers, body}:      server.reply.built(handle, method,        Http.Request{method, target, headers, body})# CORS preflight or simple headers, after HEAD bodies are droppeddef server.cors_reply(  ~handle: Http.Request -> Http.Reply,  cfg: Cors.Cfg,  +req: Http.Request) -> Http.Reply:  Cors.cors.on(cfg, req, server.reply.text(handle, req))