Rodolfo is a tiny Sinatra-inspired microframework for Kex. A router
is a block of HTTP verbs — Kex's Block<[A]> collection blocks turn the route
list into a plain do...end body instead of an explicit array, which keeps the
DSL comletely immutable:
using Rodolfo
main do
let site = Rodolfo.router do
get "/" do
"Hello from Kex!"
end
get "/hello/:name" do |env|
let name = env.param("name").or("world")
"Hello, ${name}!"
end
end
site.start(3000).try
endrouter collects the declarations; nothing binds a socket until you start
it. get, post, put, patch, delete, head, and options are plain
functions, and route "METHOD", path declares anything else. A route block
that never needs the request can drop the parameter entirely — get "/" do "Hello from Kex!" end — no |_| required.
Rodolfo is a Tey package, published by tagging this repository.
Use the commands:
tey add rodolfo --git https://github.com/kexhq/rodolfo --tag "~> 0.2"
tey installOr pull it in manually in your own package's package.kex:
tey("rodolfo", git: "https://github.com/kexhq/rodolfo", tag: "~> 0.2")The tag is the release, and ~> 0.2 takes the newest 0.2.x; Tey resolves it
against this repository's tags and records the exact commit in tey.lock.
A route block that returns a String — or anything else showable — sends it
as a 200 text/plain body, which is why do "hello" end is a complete
route. Return one of the Response records to say more. Each carries a
status that defaults to a sensible one and headers that default to none,
so the usual case is a body and nothing else:
| Reply | Sends | Default status |
|---|---|---|
Response.JSON { body } |
application/json |
200 |
Response.Text { body } |
text/plain; charset=utf-8 |
200 |
Response.HTML { body } |
text/html; charset=utf-8 |
200 |
Response.Raw { body, contentType } |
bytes, as you say | 200 |
Response.Empty {} |
no body | 204 |
Response.Redirect { location } |
a Location header |
302 |
get "/health" do
Response.JSON { body: JSON.stringify({ "status": "ok" }) }
end
post "/things" do
Response.Text {
status: 201,
body: "made",
headers: Net.HTTP.Headers.empty.add("X-Created-By", "rodolfo").try
}
endA reply's own Content-Type wins; the record's kind only fills the gap, so
Response.Text with an explicit application/rss+xml sends that.
A route block may .try, and a failure that escapes it is answered for you:
- an empty Optional (
None) is a404 Not Found, so a lookup that comes up empty is a missing page; - a failed Result (
Error(reason)) is logged and answered500 Internal Server Error, like any other application bug.
get "/books/:id" do |env|
let book = Library.find(env.param("id").try).try # no such book: 404
Response.JSON { body: JSON.stringify({ "title": book.title }) }
endWhere a failure deserves a different answer, a 400 for input that doesn't
parse, say, catch it with trying before it escapes:
get "/api/books/:id" do |env|
trying do
let id = Integer.parse(env.param("id").try).try
Response.JSON { body: JSON.stringify({ "id": id }) }
rescue |e|
Response.JSON { status: 400, body: JSON.stringify({ "error": e.message }) }
end
endKex attaches a bare rescue to named functions, not to blocks, so
trying is the form that works inside do |env| ... end.
Plugs never see the failure itself: by the time a plug's wrapped handler
returns, a None or Error is already the 404 or 500 reply.
A route that raises rather than returning, with a run-time error such as a
division by zero three calls deep, is answered 500 Internal Server Error
too, and logged with the route and the reason:
Rodolfo: GET /divide/:n raised: runtime error: division by zero
A ws handler has no reply left to send, so a raise there, or an Error
it returns, is logged the same way (Rodolfo: WS /chat failed: ...) and the
connection ends.
A plug wraps every route declared in the same router or scope, so a
check that would otherwise be repeated inside each handler — response
headers, request logging, an auth gate — is written once. Write a plug as a
value (let name = do |inner| ... end), never as a named function passed by
name or by ~ — both currently break for a function that returns a function,
which is exactly Plug's shape (Handler -> Handler); see
docs/kex-issues.md #21 if you're curious what breaks:
poweredBy : Rodolfo.Plug
let poweredBy = do |inner|
do |env|
match inner(env) do
Response.Text { status, body, headers } =>
Response.Text { status: status, body: body, headers: headers.add("X-Powered-By", "Rodolfo").or(headers) }
reply => reply
end
end
endinner is the handler (or the next plug in) being wrapped. Calling it and
using the result — as above — is an around-style plug: code can run before
inner, after it, or both, which is also how a request-logging plug looks.
Plug.around builds the same plug from one two-argument block instead of
the nested closures — still a closure literal, so it's exactly as safe with
respect to #21 as the form above:
poweredBy : Rodolfo.Plug
let poweredBy = Plug.around do |inner, env|
match inner(env) do
Response.Text { status, body, headers } =>
Response.Text { status: status, body: body, headers: headers.add("X-Powered-By", "Rodolfo").or(
8000
span>headers) }
reply => reply
end
endNot calling inner at all is how a plug halts a request:
requireToken : String -> Rodolfo.Plug
let requireToken(expected) = Plug.around do |inner, env|
if env.query("token") == Just(expected)
inner(env)
else
Response.Text { status: 401, body: "missing or wrong token" }
end
endplug(...) adds one to the router or scope it's declared in — parenthesized,
since a bare plug someValue without a trailing call or string doesn't
parse. Plugs run in declaration order, first-declared outermost:
Rodolfo.router do
plug(logged) # every route, wrapping everything below
plug(poweredBy)
get "/" do Response.Text { body: "hello" } end
scope "/admin" do
plug(requireToken("let-me-in")) # only routes inside this scope
get "/stats" do Response.Text { body: "42 requests served" } end
end
endscope "/prefix" do ... end also prefixes every path declared inside it,
nested scopes included, and its own plugs stack after the enclosing router's
or scope's — so /admin/stats above runs logged, then poweredBy, then
requireToken, then the handler. See examples/plugs for the runnable
version of this.
A Router is a value, so a large application's routes don't have to live in
one router do ... end body. mount nests an already-built router under a
path prefix — like scope, but the declarations were collected elsewhere:
let admin = Rodolfo.router do
get "/stats" do "42 requests" end
end
let api = Rodolfo.router do
mount("/admin", admin)
get "/" do "home" end
end+ combines two routers' routes unprefixed. Each side keeps its own plugs
scoped to its own routes — router1 + router2 does not flatten both into one
shared scope, so a plug on router2 never reaches router1's routes:
let combined = coreRoutes + adminRoutes + healthRoutespublicFolder serves a directory, each file at the path it has inside it —
the name Sinatra and Kemal give the same thing:
Rodolfo.router do
get "/" do "home" end
publicFolder("public") # GET /css/site.css sends public/css/site.css
endIt is a catch-all GET route, and the first route that matches a request
wins, so it goes after the routes that share its prefix: a request it
matches is not passed on to a later route when the file is missing. Inside a
scope the directory is served beneath the scope's prefix, and the scope's
plugs wrap it like any other route:
scope "/assets" do
publicFolder("public") # GET /assets/css/site.css
endsendFile sends one file from a route of your own:
get "/favicon.ico" do |env| sendFile(env, "assets/favicon.ico") endEither way the reply is the file with:
- a
Content-Typefrom its extension —Rodolfo.Static.mimeType(path)is the table, and anything it does not know isapplication/octet-stream; - an
ETagand aLast-Modified, so a request carrying a matchingIf-None-MatchorIf-Modified-Sinceis answered304with no body; - a
404when the path is missing or is not a regular file. A directory has no index page and no listing.
A requested path never leaves the directory. It is resolved the way
realpath(3) does and compared with the directory's own real path, so a ..
segment and a symlink pointing outside are both a 404, while a symlink that
stays inside is followed. sendFile(env, path) is the exception, because
that path is yours and not the request's — when it does come from the
request, name the directory it must stay in:
get "/_theme/*path" do |env|
sendFile(env, env.param("path").try, from: theme.directory)
endCaching headers are a second argument to publicFolder, sent with every
file and with every 304:
publicFolder("public", Net.HTTP.Headers.empty.add("Cache-Control", "public, max-age=3600").try)sendFile takes them as headers:, alongside the directory:
get "/_theme/*path" do |env|
sendFile(env, env.param("path").try, from: theme.directory, headers: noStore)
endPaths are relative to the working directory unless absolute, and a file is read whole into memory before it is sent — right for stylesheets, scripts, images, and fonts, not for streaming video.
ws declares a route that upgrades on a completed RFC 6455 handshake,
handing the block the request environment (the same Context an ordinary
route gets — query string, headers, cookies) and a live Connection —
there's no subprotocol negotiation or handshake rejection at the handshake
itself; every request that upgrades is accepted, so reading env and
closing the connection right away is how a ws route rejects one after the
fact:
using Net.HTTP.WebSocket, only: [Message, Text, BinaryMessage, CloseMessage]
Rodolfo.router do
ws "/echo" do |env, socket|
loop do
match socket.receiveMessage.try do
Text(text) => socket.send(Text(text)).try
CloseMessage(_, _) => break
_ => Void
end
end
end
endws routes take part in path prefixing exactly like any other route — one
declared inside a scope "/api" do ... end answers at /api/echo — but not
in the plug stack: a Context -> Connection -> Void handler isn't shaped
like a Handler, and an upgraded connection's lifecycle isn't a single
request/response the way an ordinary route's is.
Message, Text, BinaryMessage, and CloseMessage aren't re-exported by
using Rodolfo — Text would collide with Response.Text — so a ws
handler brings them in itself, as above. Reach for
Net.HTTP.WebSocket.upgrade directly from an ordinary get route instead of
ws when a client needs to negotiate a subprotocol or be rejected before the
101 response goes out.
Handing the Connection to another process (a shared room, a pub/sub
registry) to push to it from outside its own handler now works too —
kexhq/kex#370 (a server-side connection couldn't be sent to while idle,
which is the normal state of a listener that isn't currently typing) is
fixed. See examples/chat for a broadcast room built on exactly that, with
a real browser UI, a display name per connection, and a shared room
password checked from env.query(...) inside the ws handler.
start blocks, which is what a main wants; background returns a
Server.Running you can stop, which is what specs and managed lifecycles
want. Given only a port, both bind loopback — this machine and nothing
else:
site.start(3000).try # http://localhost:3000
let server = site.background(3000).try # returns a handle
server.stop().tryA port bound on every interface is reachable by every machine on the network, which is rarely what a program under development means, so widening it is a written-out address rather than the default:
site.start("0.0.0.0", 3000).try # every interface — the network
site.start("192.168.1.20", 3000).try # one interface
site.start("0.0.0.0", 3000, options).try # with Net.HTTP.ServerOptionsPort 0 asks the operating system for a free port, which is how a spec takes an
ephemeral one — see spec/rodolfo.spec.kex:
let server = site.background("127.0.0.1", 0).try
let port = server.localAddress.port.valuesite.httpRouter is the Net.HTTP.Router the declarations compile to, for
serving it by hand or mounting it elsewhere, and site.routes is the compiled
route list in declaration order.
Each example is a Kex package of its own, using Rodolfo exactly the way an application would:
examples/hello— dynamic parameters and request bodiesexamples/statusapi— JSON health and catalog API, with a rescued routeexamples/website— server-rendered HTML responses, with a stylesheet served frompublic/bypublicFolderexamples/requestinfo— reusable route-handler wrappingexamples/plugs— request logging, response headers, and a scoped token-gated admin route, usingplugandscopeexamples/library— a book-management CRUD interface: list, search, add, edit, delete, lend, and return, in plain HTML formsexamples/chat— a broadcast WebSocket chat room with a shared room password and a display name per connection, usingwsandPlug.around
The catalogue above is what examples/library serves on the first run: the
opening books from mock_data.kex, rendered from .ket templates, with the search
box, the status pills, and the row actions the rest of the example implements.
Two browser tabs chatting with each other above — examples/chat serves the
login form and the room itself from chat/views.kex, and broadcasts each
message to every connection currently joined.
The examples are workspace members, so they resolve Rodolfo from this checkout
rather than from a published tag — one tey install at the root covers them:
tey install
cd examples/hello
tey run # serves http://localhost:3000The library example reads two variables: PORT moves it off 3000, and
LIBRARY_FILE names the tab-separated file its catalogue is kept in
(books.tsv by default, written with fourteen books on the first run):
cd examples/library
PORT=4000 LIBRARY_FILE=/tmp/books.tsv tey runtey test in an example runs its spec/ directory: examples/library has
specs for its pure catalogue rules, its pages' escaping, and its file store,
and examples/chat for its broadcast wire format and both of its pages,
including what a display name may not do once it reaches the page's own
<script>.
Every example also has browser specs in spec/browser/, which drive it in
Chrome through Shakespeare. tey test
leaves them out; two commands run them, from an example for its own or from
the root for all of them:
tey test:browser # headless, in the background
tey test:watch # a visible Chrome, each action highlighted and pacedChrome is found at CHROME_PATH or its usual macOS and Linux locations.
tey install # fetch dependencies
tey build # compile src/ into ebin/
tey test # run spec/*.spec.kex on the BEAMRodolfo needs Kex >= 0.4.0-beta.5; pick a toolchain with tey kex install.
The floor is not cosmetic. Before that release a labelled call could land in
a longer overload of the same name, so sendFile(env, path, from: dir)
reached the form that also takes headers: and failed at request time.
sendFile and publicFolder also read a file's size and modification time
through FS.File.info, which arrived in 0.4.0-beta.4, and before
0.4.0-beta.3 an application function could displace a library's
private do helper of the same name and arity, which silently disabled the
escaping behind html$. spec/rodolfo.spec.kex defines
rendered, interleave, and field at the top precisely to collide with
Rodolfo's internals, and those cases fail on an older toolchain.
git tag -a v0.2.0 -m "Rodolfo 0.2.0" && git push origin v0.2.0The tag is the release — tey add ... --tag "~> 0.2" resolves against it.
Keep the tag in step with version in package.kex.