Net.HTTP.Server
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.
inform(r, status, headers)sends a 1xx before the final response, any number of them: 103 Early Hints, 104 for a resumable upload, or a proxy relaying its upstream's. An HTTP/1.0 client gets none.failed(r, e)sends a 502 if nothing has been sent, and otherwise closes the connection, so a response cut short cannot pass as complete.background(r, f)runsfas a task the server owns, for work that must outlive the request;stopwaits for it.setStall(r, d)sets this request's stall limit, for a client known to be slow.
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:
- the first request's head, and the TLS handshake before it, within
headTimeoutof the connection's start, and each later head withinheadTimeoutof its first byte; - a kept-alive connection waits
idleTimeoutfor the next request; - a read or write in an exchange that moves no bytes for
stallfails, so a client that stops sending a body, or stops reading the response, is cut off. Time in which the handler reads and writes nothing does not count, so a quiet stream is never cut for being quiet; - at most
connectionsare served at once. The next waits in the listener's backlog until one ends.
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.
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.
Returns a configuration with l over the default limits.
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.
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 aswitchran failed. The connection was closed.BadSwitch: a handler responded withswitchto a request that cannot be switched to that protocol. It got a 500 instead.HandlerFailed: a handler calledfailed.RespondedTwice: a handler calledrespondagain, with a response of this status, which was not sent.NoResponse: a handler returned aDoneit did not get from its ownRespond. The request got a 500.
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.
Proof that a request got its response: only respond and failed make
one.
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.
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.
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.
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.
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.
Serves the connections l accepts, each request with handler, until
l is closed and every connection has ended.
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.
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.
Returns once server has stopped, and every connection it served and
every background task has ended.
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.