Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

The platform · the server

Roc compiled to native code, in a Rust host

An app's server is one executable: your Roc compiled to machine code, linked with a Rust host (tokio and hyper). The host answers HTTP, runs your code for each request, keeps a crash to its request, and frees the memory used. Your Roc decides what each request gets; the host carries it out.

Running it#

rocx dev runs the server with --dev. A built executable takes these options (with the environment variable that does the same in parentheses):

The app's executable
<app> --port 8080 --host 127.0.0.1        where to listen (PORT)
      --static DIR, --file /PATH=FILE     files served as they are
      --context-file FILE                 what the app's init! is given, once, as it starts
      --env-file FILE                     settings for the environment, read as it starts (none without it: a .env here isn't read unless named); the environment wins
      --database-url URL                  the database (DATABASE_URL): postgres://…, or sqlite:<path> (turso:<path>) for a SQLite (Turso) app's file elsewhere
      --actor-idle-ms 900000              an actor idle this long is let go (0: never; kept in the database)
      --kv-max-mb 64                      Kv's limit (KV_MAX_MB): the least recently used goes past it
      --images-dir data/images            where enhanced:src's copies of photos are kept
      --images-max-mb 1024                the most they take: the least recently used go past it
      --images-wait                       a page waits for its photos' copies (a static build's server)
      --max-body 16MiB                    the most a request's body may be (MAX_BODY): bytes, or KiB, MiB, GiB; 413 beyond
      --public-url https://app.example    where the app is, for links it sends (PUBLIC_URL; else where it listens)
      --dev                               reload pages on restart, show crashes, plugins' dev pages (/__rocx/mail)
      --debug                             GET /__rocx/allocations and /__rocx/plugin-files, and plugins' debug paths
      --live-beat-ms 15000                how often a channel stream beats, and its checks run again
      --roc-threads N                     the threads Roc runs on (ROCX_ROC_THREADS; one a core)

The log#

Every line on stderr is an event: a level, a message and fields, from your app, the host (starting, stopping, a crash with its method, URL and error) or a plugin (a migration applied, a failed job). Keep messages fixed and details in fields, for log collectors to filter on. Log with Log.info!, Log.debug!, Log.warn! or Log.error!, a message and a record of fields ({} for none); Log.line! logs a message alone. The program sets the format:

An event, and the log's format
Log.info!("gate failed", { path: request.path, error: why })

program = {
	..App.program({ init! }),
	logs: { format: Auto }, # or Pretty, or Json
}
The line, pretty and as JSON
14:03:12 info  gate failed  path=/admin error="no session"
{"time":"2026-11-21T13:03:12.345Z","level":"info","msg":"gate failed","error":"no session","path":"/admin"}

Auto, the default, follows ROCX_LOG (pretty or json) if set; otherwise pretty lines to a terminal, and JSON elsewhere. A field named time, level or msg is written as fields.msg and so on, so it can't replace the line's own.

A pretty line is the time, the level, the message, then the fields. At a terminal the time and the fields' names are dimmed and the level coloured, so the message and the values stand out. A request's path, method and status come first, then durations: a number named <x>_ns, <x>_us or <x>_ms is shown in the unit that reads best (duration_ns=12345 is duration=12µs). JSON keeps the fields as they are.

Under --dev, as the server starts
10:36:32 info  rocx plugins: jobs, email, auth
10:36:32 info  rocx server: http://127.0.0.1:8080 (Roc, native)
               ➜ Stories   http://127.0.0.1:8080/__rocx/stories
               ➜ OpenAPI   http://127.0.0.1:8080/openapi.html
               ➜ Mailbox   http://127.0.0.1:8080/__rocx/mail
               ➜ Sign in   http://127.0.0.1:8080/sign-in

Under --dev, the server lists the places to open under its address: the app's stories, its OpenAPI page if a route serves one, what plugins add (the dev mailbox, the sign-in page) and the app's own (App.program({ links: [{ label: "Jobs", path: "/admin/jobs" }] })).

Logging never waits for stderr: a thread of its own writes queued events in order, flushing when the queue empties and before exit. When the queue is full (64k events), the caller waits rather than lose a line.

Deploying#

rocx build writes dist/server, migrations inside, and dist/static (rocx). --target arm64musl (or x64musl) makes a static Linux executable, from macOS too: the prebuilt host carries musl's C library and unwinder. To deploy:

CI builds and tests every example app on Linux (arm64).

An app whose pages need no server once rendered (docs, a blog, a landing page) can be deployed as files: rocx build app --static writes every page, its data and what it loads, for GitHub Pages or a CDN (a static copy).

What is Rust, what is Roc#

The host gives Roc general building blocks. Everything built on them is Roc, in the platform or packages, and an app could write its own:

The platform reference lists every effect, with its type.

A call pauses while it waits#

Your Roc runs on threads of its own (one per CPU core, or --roc-threads / ROCX_ROC_THREADS), beside tokio's, which handle HTTP, sockets and timers. Each call into Roc (a request and its page, a stream, an actor's turn, a background loop) is a coroutine with its own stack.

When an effect waits (a query, a socket, another server, a sleep), the call pauses and its thread runs other calls; it resumes on the same thread when the wait ends. A waiting call holds no thread, so any number can wait at once. In the tests, eight requests each waiting 0.3 s on Postgres take about 0.3 s together, and 2,000 each waiting a second, on two threads, about a second.

The costs:

Each call has its own context (its open transaction, rooms joined, topics listened to, sockets), given back when it ends. A value Roc makes belongs to its call until the call returns; then the host owns it, and may move it to another call (a stream's, to the call that sends it) but never shares it.

A crash ends one call#

In Roc, a crash or an integer overflow stops the program, but Roc's ABI lets the host choose how: roc_crashed must never return, so it can end the process or jump out of the Roc code that called it. This host jumps. A guard (server/host/src/guard.c) sets a jump target around every call into Roc, so a crash ends only that call:

A crash skips only Roc's frames and a small trampoline's, so no Rust destructor is skipped.

Memory#

So that a crash leaks nothing, every allocation a call makes goes into a list the call owns. When the call returns, the answer's strings are copied out and the list is freed (a stream's once the call sending it is done); when it crashes, everything in the list is freed. Roc's reference counts are atomic in native builds, so a value moved to another thread stays correct.

The tests crash 200 requests at once, half after allocating 2,000 strings, then check that Roc holds no allocation (--debug serves the count at /__rocx/allocations). This site's tests check the same after rendering its pages over and over.

Streams of events#

An endpoint can answer with server-sent events: a loop, Events.stream(|{ send!, sleep! }| …), which the host runs as its own call while the stream is open. send! writes an event; sleep! pauses. When the client leaves, sleep! wakes early and the next send! returns Err(Gone), so ? ends the loop. A sleeping stream holds no thread: the tests keep 2,000 open on two threads and still answer a request at once. Events shows one, with a component listening.

For live data that pages follow, a channel is usually better: a tab's channels share one stream the host keeps without a call, and Roc runs only briefly, for a check or hook.

Pages, rendered on the server#

A page is one tree of components: its layouts, the page, and what they contain. The host renders it whole with rocx-engine, the engine the browser and the phones run, in its server mode (engine/src/server.rs): each component and hole runs once, nothing is tracked or waits, and a memo is computed when made. HTML comments mark each hole for hydration; markup inside <NoHydration> is plain HTML, never hydrated. The site's tests check that the host and the site's browser half, rendering in Node with the same engine, write every page the same, byte for byte.

A component's endpoint read (.read!(), a GET of the app's own path) is made in-process: through the app's respond! and the route directories' middleware, with accept: application/json, the page's headers (cookies included) and the app's context, so it gets the answer the browser would. Each URL is asked once per render. The answers go, by URL, into a script at the end of the page, before /rocx/start.js, and the browser reads them there instead of asking again. Reads inside a <NoHydration> aren't recorded: the browser never makes them.

On a failure (a context nothing provides, a failed memo, an endpoint answering anything but 200), the nearest <Errored> shows its fallback, as in the browser. An endpoint's redirect redirects the page; a crash ends the render with a 500.

Photos' copies#

Write a photo as <img enhanced:src={path} alt="…" /> and the server makes smaller WebP copies of it, 160 to 1920 pixels wide. The first page to show it gets the plain src, and the photo joins a queue two of the host's workers take from. Later pages get the copies: a srcset, sizes, and the photo's width and height, so the layout keeps its room. No page waits, and there is nothing to set up: no job, no build step.

Every so often, and as it stops#

Process.set_interval!(ms, tick!) runs tick! every ms milliseconds while the server runs, and Process.on_stop!(last!) runs last! once as it stops: a buffer kept in memory, written now and then, and once more on the way out. Both are set at the start, in your init! or a plugin's start; the auth plugin writes who was last seen this way, and the PostHog plugin sends the errors it kept.

main.roc, in part
init! = |started| {
    _clear = Process.set_interval!(10_000, flush!)   # clear!() stops it
    Process.on_stop!(flush!)
    Ok(started)
}

Background loops and isolated calls#

At start, the server asks the platform's Roc which loops to run in the background: plugins' loops (the jobs plugin's workers, schedules and hourly sweep of finished jobs) and checks (the email plugin's look at the SMTP server). Each runs as its own call until the server stops; one that crashes restarts a second later. A loop sleeps with Live.next!, which wakes on a publish to a topic it listens to, when its time is up, or with Gone at shutdown. Db.notify! (and Postgres's NOTIFY) publish on db:<channel>: that is how job workers sleep until a job is queued.

An isolated call runs Roc inside another call, guarded on its own: a crash ends it alone, and the caller learns why. Plugins use them (Plugin.isolated!); the jobs plugin runs each job in one, so a crashing job just fails and the worker goes on.

An actor's turn is a guarded call too: its mailbox, in the host, runs it with the kind, key, state and message as strings, so a crash frees them all. No lock is taken: one task routes each message to its actor's mailbox, and each actor handles its messages one at a time (actors).

Plugins#

A plugin is a package that adds what only the server runs: tables, background loops, files, scripts every page loads, development pages, work at start, checks; never a route. Name the package in the app's header and list its plugin in the program. The jobs, email, auth, push, Stripe and audio packages, among others, are plugins.

main.roc
app [program] { pf: platform "../server/platform/main.roc", acme: "../packages/acme/main.roc" }

import acme.Acme

program = App.program({
	init!,
	plugins: [Acme.plugin({})],
})

A plugin is one value, a Plugin.Value, made by its package from its own options:

At start, the server checks every plugin and stops on any problem, listing them all: two development pages at one method and path, a file at the root where the app has a route, two files at one place, a name used twice, a need not met. Then it names the plugins on one line of the log (what each added too, under --debug).

A plugin package names the server platform in its header, as an app does; a second header, browser.roc, lists the modules the browser's copy of the app can compile too.

A plugin's files are embedded at build (with an import … : List(U8), below) and handed to the host at start. The host serves them before anything else, the app's middleware included, so a sign-in guard never blocks a service worker or script: at /rocx/plugins/<plugin>/<path>, or /<path> with at: Root (a service worker, whose scope is where it is), to GET and HEAD, with its content type and an ETag of its bytes (304 when the browser has them). Every server-rendered page loads the files listed as scripts, as modules before start.js. Such a script can register browser effects that Browser.call! finds as <plugin>.<effect>; each gets { under }, which puts a URL under the site's base path. The push plugin serves its service worker at the root and its script this way, and the audio plugin its player.

A plugin's files
import "static/push-sw.js" as worker : List(U8)
import "static/push.js" as script : List(U8)

files: [
	{ path: "push-sw.js", at: Root, content_type: "text/javascript", body: worker },
	{ path: "push.js", at: Plugin, content_type: "text/javascript", body: script },
],
scripts: ["push.js"],

Sockets and randomness#

Tcp.connect! (or connect_tls!, or start_tls! on an open socket) opens a socket for the call. write_bytes!, read_exactly!, read_up_to! and read_until! pause the call while they wait; close! closes it, and the call's end closes any left open. read_within!(tcp, max, ms) waits ms milliseconds at most and answers TimedOut if nothing came, the connection still open and nothing lost, so a loop can send a heartbeat and read on (the WebSocket package does). TLS is rustls, checked against the web's certificate authorities. Random.bytes! and Random.seed_u64! are the OS's secure randomness (crypto). The email package's SMTP client, the WebSocket package's client and roc-pg, a Postgres client in Roc, are built on these.

Not yet#