roost
The roost module is an axum-style web framework on Tern's tasks: a router with path parameters, middleware, WebSockets, server-sent events, and (covered on this page) static files, file uploads, streamed request bodies, HTTPS, connection limits and graceful shutdown. It is plain Tern on the server engine in http: roost.Request and roost.Response are http.Request and http.Response under another name, so the request and response functions on that page work on them too. Every function is listed at the top of library/roost/roost.tn; the reference has the one-line summary.
import roost
fn main():
r = roost.router()
r.get("/hello/{name}", fn(req) roost.text("hello " + req.param("name")))
r.files("/", "./public") # everything else: files from ./public
roost.serve(r, 8080)Static files
fn files(r: mut Router, prefix: str, dir: str)
fn file_response(path: str, req: Request) Responser.files("/assets", "./public") answers GET /assets/css/app.css with ./public/css/app.css (and GET /assets/ with ./public/index.html). It sets Content-Type from the file extension, sends ETag and Last-Modified and answers 304 Not Modified to a client that already has the file, serves single byte ranges (206, for video seeking and resumed downloads), and streams big files from disk instead of reading them into memory. Paths containing .., and dot files other than .well-known, are 404, so a request can't reach outside dir or read .env. roost.file_response(path, req) sends one file from a handler, with the same headers; path is relative to the working directory (or absolute), and a path with .. is refused the same way. r.files("/", dir) serves a whole site, including / itself (from dir/index.html).
File uploads
fn parts(req: Request) [Part]
fn part(req: Request, name: str) PartAn HTML form with enctype="multipart/form-data" (any form with a file input) sends its fields as parts. req.parts() returns them all; Part has name (the form field), filename ("" for a plain field), content_type and data. These read the request's buffered body, which is limited to TERN_WEB_MAX_BODY_MB (16 MB by default).
import fs
import roost
fn upload(req: roost.Request) roost.Response:
f = req.part("photo")
if f.filename == "":
return roost.status(400, "no file")
fs.write("uploads/" + f.filename.replace("/", "_"), f.data)
return roost.text(f"saved {len(f.data)} bytes")
fn main():
r = roost.router()
r.post("/upload", upload)
roost.serve(r, 8080)Streamed request bodies
fn post_stream(r: mut Router, path: str, h: fn(Request) Response)
fn put_stream(r: mut Router, path: str, h: fn(Request) Response)
fn read_body(req: Request, max: int) str the next piece ("" at the end)
fn save_body(req: Request, path: str) int the rest into a file: bytes, or -1
fn next_part(req: Request, p: mut Part) bool multipart: the next part (its data is "")
fn read_part(req: Request, max: int) str
fn save_part(req: Request, path: str) intFor uploads of any size in constant memory, register the route with post_stream (or put_stream). Its handler runs as soon as the request's headers arrive, with req.body empty, and reads the body itself, a piece at a time; Content-Length and chunked bodies both work, and the size limit doesn't apply. Whatever the handler doesn't read is skipped before the next request on the connection. Read the body in the handler's own task (not in a task it spawns).
import roost
fn upload(req: roost.Request) roost.Response:
saved = ""
p = roost.Part("", "", "", "")
while req.next_part(&p):
if p.filename != "":
n = req.save_part("/tmp/upload-" + p.name)
saved += f"{p.filename}: {n} bytes\n"
return roost.text(saved)
fn main():
r = roost.router()
r.post_stream("/upload", upload)
roost.serve(r, 8080)Validating input
fn check() Check
fn required(v: mut Check, field: str, value: str)
fn min_len(v: mut Check, field: str, value: str, n: int) fn max_len(...)
fn between(v: mut Check, field: str, value: int, lo: int, hi: int)
fn one_of(v: mut Check, field: str, value: str, options: [str])
fn email(v: mut Check, field: str, value: str)
fn fail(v: mut Check, field: str, message: str)
fn valid(v: Check) bool
fn problems(v: Check) ResponseA Check collects every problem with a request (each field keeps its first), so the client learns about all of them at once; v.problems() answers 422 with {"errors": {"name": "is required", "age": "must be between 13 and 120"}}.
import roost
struct Signup:
name: str
email: str
age: int
fn signup(req: roost.Request) roost.Response:
s = Signup("", "", 0)
if not req.json(&s):
return roost.status(400, "expected JSON")
v = roost.check()
v.required("name", s.name)
v.max_len("name", s.name, 100)
v.email("email", s.email)
v.between("age", s.age, 13, 120)
if not v.valid():
return v.problems()
return roost.text("welcome, " + s.name)
fn main():
r = roost.router()
r.post("/signup", signup)
roost.serve(r, 8080)Rate limiting and client addresses
fn rate_limit(per_second: float, burst: int) middleware
fn rate_limit_by(per_second: float, burst: int, key: fn(Request) str) middleware
fn peer(req: Request) str "1.2.3.4:5678"
fn client_ip(req: Request) str
fn trust_proxies(n: int)
fn matched_route(req: Request) str "/users/{id}", once track_routes() was called
fn track_routes()roost.rate_limit(5.0, 20) gives each client IP a token bucket that holds 20 requests and refills at 5 a second; past it, requests get 429 Too Many Requests with Retry-After. rate_limit_by buckets by your own key instead (an API key header, a user id). Buckets are shared by all threads and idle ones are forgotten.
req.client_ip() is the connection's address. Behind a load balancer or reverse proxy, call roost.trust_proxies(n) with the number of proxies in front of the server: client_ip then takes the X-Forwarded-For entry those proxies added, counting n from the right. The entries further left were sent by the client and can't be trusted.
req.matched_route() is the pattern of the route that matched ("/users/{id}"), for error trackers and logs that group requests by route; "" when none matched. The server records it only after roost.track_routes() was called, so servers that don't ask pay nothing (sentry.middleware calls it).
Metrics
fn metrics(r: mut Router, path: str)
fn metric_add(name: str, labels: str, value: float) a counter
fn metric_set(name: str, labels: str, value: float) a gauger.metrics("/metrics") serves Prometheus' text format: tern_http_requests_total and a tern_http_request_duration_seconds histogram by route pattern, method and status, tern_http_connections, and the process's CPU seconds, peak memory and uptime, plus whatever the program records with roost.metric_add("jobs_total", "queue=\"email\"", 1.0) and roost.metric_set("queue_depth", "", 42.0). Counting starts when a router asks for metrics, and costs a timer read and a short lock per request.
HTTPS
fn serve_tls(r: Router, port: int, cert: str, key: str)
fn start_tls(r: Router, host: str, port: int, cert: str, key: str) ServerWith import tls, a server can speak HTTPS: cert is the PEM certificate chain and key its private key. See tls, which also covers https:// URLs in the client (http.get).
Connection limits and shutdown
fn max_connections(r: mut Router, n: int)r.max_connections(n) (or TERN_WEB_MAX_CONNS=n) caps the connections open at once; at the cap the server stops accepting until one closes, and new clients wait in the kernel's queue instead of being refused.
roost.serve shuts down gracefully on SIGINT (Ctrl-C) and SIGTERM (what kill, systemd and container runtimes send): it stops accepting, closes idle keep-alive connections, lets the requests in progress finish for up to TERN_WEB_DRAIN_SEC seconds (default 10; a second signal cuts it short), then returns, so code after roost.serve runs and the program exits 0.
$ ./app
tern: serving http://localhost:8080 on 14 threads
^Ctern: SIGINT: shutting down (finishing 3 connections, up to 10s)