module use "std/server.nib"
Server
A web server in one call: Server.run(host, port, handler) binds, accepts, speaks HTTP/1.1 with keep-alive, and answers each request with your handler.
Server is the loop around a website. A site is a handler — a function from Http.Request to Http.Response — and Server.run does everything else: binds the port, accepts connections, gives each one its own fibre so a slow client never holds up the rest, reads requests, keeps HTTP/1.1 connections alive, and enforces the limits a public server needs.
use "std/http.nib"
use "std/io.nib"
use "std/net.nib"
use "std/route.nib"
use "std/server.nib"
use "std/time.nib"
module Site where
func handle :: r: Http.Request -> Http.Response =
Route.dispatch(#[
Route.get("/", { r, ps -> Http.html(200, "<h1>hello</h1>\n") }),
Route.get("/hello/:name", { r, ps -> Http.text(200, "hello, {Map.get_or(ps, "name", "")}\n") })
], r, { r -> Http.text(404, "no page at {Route.path(r)}\n") })
func main :: -> () ! Net.Socket, Io.Print, Server.Seats, Time.Clock raises BadHeader, BadStatus, Err.BindFailed, Err.IndexOutOfRange, HandleRefused =
Server.run("127.0.0.1", 8080, Site.handle)
wire Serve runs Site.main where
Server.Seats = Server.Count,
Net.Socket = Net.Native,
Time.Clock = Time.System,
Io.Print = Io.Stdout
The wire supplies four things: the sockets (Net.Native), the clock that times requests out (Time.System), somewhere to log (Io.Stdout), and the connection count (Server.Count).
Testing a handler
A handler is a pure function, so the routes are tested by building requests as values and calling it — no port, no socket:
let handle = { r -> Route.dispatch(#[
Route.get("/hello/:name", { r, ps -> Http.text(200, "hello, {Map.get_or(ps, "name", "")}") })
], r, { r -> Http.text(404, "no page at {Route.path(r)}") }) };
let ask = { t -> handle(Http.Request{ method: "GET", target: t, version: "HTTP/1.1", headers: #[], body: "" }) };
let a = ask("/hello/Ada%20L");
let b = ask("/nope");
((a.status, a.body), (b.status, b.body))
((200, "hello, Ada L"), (404, "no page at /nope"))
The handler answers; it does not raise
run takes a handler with no raises row. Each connection runs in its own fibre, and an error escaping a fibre would end that connection with no answer, so a handler that can fail catches its own errors and answers with a status:
use "std/http.nib"
module Site where
func page :: r: Http.Request -> Http.Response =
try
let lang = Http.header(r, "Accept-Language");
Http.text(200, "language: {lang}")
rescue Err.Missing(_) => Http.text(400, "say which language you want")
rescue Err.IndexOutOfRange(_) => Http.text(500, "something went wrong")
end
func main :: -> String =
let a = Site.page(Http.Request{ method: "GET", target: "/", version: "HTTP/1.1", headers: #[Http.Header{ name: "accept-language", value: "fr" }], body: "" });
let b = Site.page(Http.Request{ method: "GET", target: "/", version: "HTTP/1.1", headers: #[], body: "" });
"{a.status} {a.body} / {b.status} {b.body}"
wire W runs Site.main
200 language: fr / 400 say which language you want
A handler's effects are allowed: if it reads a file or the clock, it says so in its row, and the program's wire supplies them along with the server's own.
Interfaces
interface Seats where
enter(limit: Int) -> Bool;
leave() -> ()
The connection count Server.run keeps. enter(limit) takes a seat and answers true, or answers false when limit seats are already held; leave() gives one back. Bind it to Server.Count.
Effectors
effector Count is Seats where
var held :: () => Int = 0;
The standard Server.Seats: a counter that starts at zero. Every server's wire binds Server.Seats = Server.Count.
use "std/server.nib"
module Demo where
func main :: -> Vec<Bool> ! Server.Seats =
let a = @Server.Seats.enter(2);
let b = @Server.Seats.enter(2);
let c = @Server.Seats.enter(2);
let _ = @Server.Seats.leave();
let d = @Server.Seats.enter(2);
#[a, b, c, d]
wire W runs Demo.main where Server.Seats = Server.Count
#[true, true, false, true]
Functions
func accept_ms :: -> Int
How long one accept waits before the loop goes round again: 500 ms.
func idle_ms :: -> Int
The longest an idle kept-alive connection is held between requests: 30000 ms. In practice a silent client is dropped sooner, when a single read gives up after 10 seconds.
func request_ms :: -> Int
How long a request has from its first byte to its last: 2500 ms.
func run :: host: String, port: Int, handler: pin (Http.Request) -> Http.Response -> () ! Net.Socket, Io.Print, Server.Seats, Time.Clock raises BadHeader, BadStatus, Err.BindFailed, Err.IndexOutOfRange, HandleRefused
Binds host:port, then serves forever, answering every request with handler. It never returns normally. It raises Err.BindFailed if the port cannot be bound.
What it does for each connection:
- Concurrency. Every accepted connection gets its own fibre, so a slow or silent client holds one parked fibre while every other connection is answered.
- Keep-alive. An HTTP/1.1 request without
Connection: closekeeps the connection open, and the bytes after one request are read as the next.Connection: closeand HTTP/1.0 close after one answer. - No connection cap. Every connection is taken; how many a server can hold is up to the process's descriptors and memory, not a number in the library.
Server.run_cappedsets a cap when the program wants one. - Out of file descriptors. When the process has no descriptor (or memory) for a waiting connection,
acceptwaits for one to free — 5 ms, doubling to 1 s — and asks again, saying on stderr when it starts to wait. The listener stays up and the open connections keep being served. - Time limits. A request must arrive in full within
Server.request_msof its first byte, so a client cannot hold a seat by sending one byte at a time. An idle kept-alive connection is closed after at mostServer.idle_ms. - Size limits. A head over 64 KiB is answered
400; a declared body over 1 MiB is answered413before any of it is read. A request that cannot be parsed is answered400.
Request bodies are read by Content-Length only; a chunked request body is refused.
func run_capped :: cap: Int, host: String, port: Int, handler: pin (Http.Request) -> Http.Response -> () ! Net.Socket, Io.Print, Server.Seats, Time.Clock raises BadHeader, BadStatus, Err.BindFailed, Err.IndexOutOfRange, HandleRefused
Server.run with a connection cap: past cap open connections, the next is answered 503 and closed without a fibre, so it cannot grow the server. A cap of 0 or less is no cap — Server.run(host, port, handler) is Server.run_capped(0, host, port, handler). A cap bounds a server's memory and descriptors by its own policy, and sheds load with a fast answer instead of a slow one.
Internal helpers
These are reachable — nib has no private functions — but they are the module's own plumbing, not an interface it promises to keep.
12 signature(s)
data Arrival where Arrived(Handle); NoArrival
data Step where More(String); Answered(String); Done
func seats_for :: cap: Int -> Int
func drain_chunks :: -> Int
func accept_loop :: cap: Int, handler: pin (Http.Request) -> Http.Response, sw: Switch -> () ! Net.Socket, Io.Print, Server.Seats, Time.Clock raises BadHeader, BadStatus, Err.BindFailed, Err.IndexOutOfRange, HandleRefused
func refuse :: cap: Int, conn: Handle -> () ! Net.Socket, Io.Print raises BadHeader, BadStatus, Err.IndexOutOfRange, HandleRefused
func drain :: conn: Handle, at: Int -> Bool ! Net.Socket raises HandleRefused
func serve_conn :: handler: pin (Http.Request) -> Http.Response, conn: Handle -> () ! Net.Socket, Server.Seats, Time.Clock
func conn_loop :: handler: pin (Http.Request) -> Http.Response, conn: Handle, buf: String, since: Int -> () ! Net.Socket, Time.Clock raises BadHeader, BadStatus, Err.IndexOutOfRange, HandleRefused
func answer_one :: handler: pin (Http.Request) -> Http.Response, conn: Handle, buf: String -> Server.Step ! Net.Socket raises BadHeader, BadStatus, Err.IndexOutOfRange, HandleRefused
func answer :: conn: Handle, r: Http.Response -> () ! Net.Socket raises BadHeader, BadStatus, Err.IndexOutOfRange, HandleRefused
func answer_with :: conn: Handle, r: Http.Response, connection: String -> () ! Net.Socket raises BadHeader, BadStatus, Err.IndexOutOfRange, HandleRefused