Net.HTTP.Server

lib/Net/HTTP/Server.gob

An HTTP/1 server: connections taken from a Net.Listener, each served by a task of its own, its requests read and responded to in order, one at a time.

fun handle(req : Request Incoming, r : Respond) -> Done = match (req.method, req.target.path) {
    (GET | HEAD, "/health") -> respond(r, body(OK, MediaType.plainText, "ok"))
    (POST(content), "/orders") -> respond(r, create(content))
    _ -> respond(r, NotFound)
}

Server.serve(TCP.listen(address, 8080)?, Server.defaultConfig, handle)

A handler sends its response through its Respond. It takes the request and a Respond, and ends in respond(r, x), where x is a ToResponse: a ServerResponse, or a value that becomes one, its own error type among them. respond writes the whole response, a stream's body and trailers included, before it returns, so whatever the handler holds open -- a file, an upstream connection whose body it relays -- is open for as long as the response needs it. The respond call is the commit point.

Every path responds, once. respond returns a Done, whose constructor is hidden, and a handler must return one, so a handler that returns has sent a response. A second respond is not sent: it is reported to onError, as RespondedTwice.

Versions. HTTP/1.1 and HTTP/1.0 requests are served. A 1.0 request's connection is closed after its response, and a body of unknown length is sent to it until the close, since it cannot read chunks. Any other version gets a 505.

HEAD reaches the handler as itself. respond sends the head of the response, with the length or the chunking a GET would have, and no body, and never calls a stream's function. A handler that treats both alike matches both: (GET | HEAD, "/") ->.

Request bodies. A handler reaches a body only through receive/limited on the method's payload, under a limit it names. When the client waits for 100 Continue, it is sent from inside that first read, after the limit is checked, so a body declared too large is refused before the client sends it. The body stays readable while respond writes, so a stream's function can write its response as it reads the request. A body still unread when respond returns is read and discarded if at most drainBytes of it remain, so the connection can carry the next request; a longer one, or one the client has not started sending, closes the connection instead.

Closing while the client sends. Closing a connection whose client is still sending makes the system send a reset, which can destroy the response before the client reads it (RFC 9112 ยง9.6). So after an unread body, or a refused request, the server shuts down its own side, then reads and discards what comes, for at most lingerIdle between reads and lingerTotal in all, and only then closes. That happens after the handler has returned.

Waits are bounded by Limits:

A deadline or a failure part-way through a message closes the connection, which is never used again.

Stopping. start runs a server as a task in the enclosing Task.runScope and returns it; stop closes the listener, closes the connections waiting for a request, lets those in an exchange, and the background tasks, finish (each connection closes after its response) until the drain time is up, and then closes the connections left, which ends their waits. A handler streaming without end is cut off then. wait returns once every connection and every background task has ended. Closing the listener by other means stops the server the same way, with no drain time.

Errors go to the configuration's onError, and nowhere by default.

type Config

How a server runs: its Limits, and where it reports what goes wrong. A set of overrides, as Limits is: empty keeps every default, each function below overrides one setting, and <> joins two, the right side winning where both set one.

let defaultConfig : Net.HTTP.Server.Config
fun limits : fun(Limits) -> Net.HTTP.Server.Config

Returns a configuration with l over the default limits.

fun onError : fun(fun(ServerEvent) -> Unit) -> Net.HTTP.Server.Config

Returns a configuration that reports each ServerEvent to f, which runs in the task of the connection it is about, and must not wait long.

type ServerEvent = AcceptFailed(IOError) | Refused(Refusal) | ConnectionFailed(SomeError) | ResponseAborted(SomeError) | BadSwitch(Token) | HandlerFailed(HTTPError) | RespondedTwice(Net.HTTP.Status.Status) | NoResponse

What went wrong, as a server reports it to onError. None of them stops the server.

  • AcceptFailed: the listener failed to take a connection, for a reason other than being closed, such as running out of descriptors. The server waits a little, longer each time up to a second, and tries again.
  • Refused: a request the codec refused. It got a response of the refusal's status, and its connection was closed.
  • ConnectionFailed: a read or a write failed or timed out part-way through a request or its response, and the connection was closed.
  • ResponseAborted: a response failed after its head was sent: its stream's function failed, wrote other than its declared length, or the function a switch ran failed. The connection was closed.
  • BadSwitch: a handler responded with switch to a request that cannot be switched to that protocol. It got a 500 instead.
  • HandlerFailed: a handler called failed.
  • RespondedTwice: a handler called respond again, with a response of this status, which was not sent.
  • NoResponse: a handler returned a Done it did not get from its own Respond. The request got a 500.
type Respond

What a handler sends the response to one request through. respond, inform and failed take it.

It reaches the connection through closures, so that a handler's type names no transport, and one handler serves TCP, TLS and in-memory connections alike. It is meant for the handler's own task; a task the handler starts may call inform or respond only while the handler waits for it.

type Done

Proof that a request got its response: only respond and failed make one.

fun respond : [ToResponse x] fun(Respond, x) -> Done

Writes the response x becomes, its body and trailers included, and returns once it is written or has failed. A failure is reported to onError, and the connection is closed after the handler returns. A second call sends nothing, and is reported as RespondedTwice.

fun inform : fun(Respond, Net.HTTP.Status.Status, Headers) -> Either HTTPError Unit

Sends the informational response status with headers, before the final one. Sends nothing to an HTTP/1.0 client, which cannot read one, and nothing for a second 100 Continue, which the server may have sent already. Transport with an IOError of kind Closed once a final response has begun, or the connection's own failure. Panics unless status is a 1xx other than 101, which switch sends.

fun failed : fun(Respond, HTTPError) -> Done

Sends 502 Bad Gateway if no final response has begun, and otherwise closes the connection at once, so that a response cut short is not taken for a whole one. Reports e to onError as HandlerFailed.

fun background : fun(Respond, fun() -> Unit) -> Unit

Runs f as a task the server owns, which may outlive the request: a cache filled from an upstream that later requests wait on, say. stop and wait wait for it. Once the server has stopped accepting and every connection has ended, f runs in the caller's task instead.

fun setStall : fun(Respond, Duration) -> Unit

Sets the stall limit for the rest of this request's reads and writes to d, in place of Limits' stall. Panics if d is not positive.

type Server
fun serve : [Listener l, Connection (Accepted l), HasConnectionInfo (Accepted l), Error (ReadError (Accepted l)), Error (WriteError (Accepted l))] fun(l, Net.HTTP.Server.Config, fun(Request Incoming, Respond) -> Done) -> Unit

Serves the connections l accepts, each request with handler, until l is closed and every connection has ended.

fun start : [Listener l, Connection (Accepted l), HasConnectionInfo (Accepted l), Error (ReadError (Accepted l)), Error (WriteError (Accepted l))] fun(l, Net.HTTP.Server.Config, fun(Request Incoming, Respond) -> Done) -> Spawn Server

Returns a server of the connections l accepts, each request with handler, running as a task of the enclosing Task.runScope, which waits for it.

fun stop : fun(Server, Duration) -> Unit

Stops server: closes its listener and its idle connections, lets the requests in flight and the background tasks finish for up to drain, then closes every connection left. Returns once the connections are closed, which is before their tasks have necessarily ended; wait waits for those.

fun wait : fun(Server) -> Unit

Returns once server has stopped, and every connection it served and every background task has ended.

instance Semigroup Net.HTTP.Server.Config
instance Monoid Net.HTTP.Server.Config
instance Show ServerEvent
instance Read (Guarded c) : Connection c
instance Write (Guarded c) : Connection c

A write is made in pieces of at most piece bytes, each with its own stall deadline, so that the limit is on progress: a large write that a slow client takes steadily goes on, and one it stops taking is cut.