Smeltery
Get started

The basics

v0.1

Routes and controllers

rust
use smeltery::prelude::*;

async fn home() -> Html<&'static str> {
    Html("<h1>Welcome</h1>")
}

async fn show(Path(id): Path<u64>) -> Result<String> {
    if id == 0 {
        return Err(Error::not_found());
    }
    Ok(format!("post {id}"))
}

async fn index() -> &'static str { "all posts" }
async fn dashboard() -> &'static str { "admin" }

pub fn routes(r: &mut Router) {
    r.get("/", home).name("home");
    r.resource("/posts").index(index).show(show);
    r.group("/admin", |r| {
        r.get("/", dashboard).name("dashboard");
    })
    .name("admin.")
    .middleware("auth");
}
  • get, post, put, patch, delete, any; .name("…"); .middleware("alias").
  • Paths use {param} placeholders and {*rest} for a catch-all tail.
  • group(prefix, …) with .name("prefix.") and .middleware("alias") for every route in it.
  • resource("/posts") declares the actions you pick:
Action Method Path Name
index GET /posts posts.index
create GET /posts/create posts.create
store POST /posts posts.store
show GET /posts/{post} posts.show
edit GET /posts/{post}/edit posts.edit
update PUT, PATCH /posts/{post} posts.update
destroy DELETE /posts/{post} posts.destroy
  • app.url("posts.show", &[("post", "7")]) builds /posts/7; extra parameters become the query string.
  • HTML forms send PUT, PATCH and DELETE as a POST with a _method field (or the X-HTTP-Method-Override header).
  • Routes from routes/api.rs are registered with api_routes and live under /api.
  • Files in public/ are served as-is when no route matches, with ETag, Last-Modified and the Cache-Control of STATIC_CACHE_CONTROL (default no-cache: browsers revalidate and get a 304 while the file is unchanged). Apps whose asset URLs change with their content can set public, max-age=31536000, immutable.
  • Files under /storage (uploads, after smeltery storage:link) also get Content-Security-Policy: sandbox, so a stored HTML or SVG file never runs as a page of the site, X-Content-Type-Options: nosniff, and Content-Disposition: attachment unless they are a PNG, JPEG, GIF, WebP, AVIF, BMP or icon image, a PDF, plain text, video or audio. PDFs get no sandbox (browsers do not show a sandboxed PDF). The headers follow the file that is served: any file from public/ whose real path (links followed) lies in storage/app/public or public/storage gets them, whatever URL reached it. A static-file path with a segment that ends in . or a space, or holds : or \ (/storage./…, /storage%2e/…, /storage::$INDEX_ALLOCATION/…), answers 404 on every OS, because Windows opens such names as another file.
  • The framework adds GET /up, a health check for load balancers and uptime monitors: 200 with the text OK and Cache-Control: no-store, without a session or CSRF check. route:list shows it. An app route at GET /up replaces it; AppBuilder::without_health_route() leaves it out.
  • .middleware("throttle:5,1") allows a route 5 requests a minute per client (throttle:<max>,<minutes>; throttle:<max> counts per minute). The client is the authenticated user (the request's principal: a signed-in session on web routes, or the principal an auth: alias listed before throttle: stored, see Guards and the principal), else the address after TRUSTED_PROXIES (an IPv6 client by its /64). Each route counts on its own, by its path pattern, so /reset-password/{token} has one counter for every token. The count lives in the app's cache store (CACHE_STORE), so the processes of an app (serve --no-agents beside work, several web processes) share it on the database, redis, memcached and file stores; with CACHE_STORE=null it lives in the process's memory. A cache error answers 500 rather than letting the request through. Responses carry X-RateLimit-Limit and X-RateLimit-Remaining. Past the limit a form on a web route is sent back (303, its input flashed) with "Too many attempts. Please try again in N seconds." on the field email (throttle:5,1,name puts it on name), and JSON clients and API routes get 429 "Too Many Requests" with Retry-After. An invalid value (throttle:0, throttle:x) stops the app at boot. The windows are fixed and follow the clock (throttle:5,1 counts per calendar minute): a client that sends 5 requests at the end of one minute and 5 at the start of the next gets all 10 through within a few seconds.
  • Aliases with arguments (throttle:5,1, auth:web) come from middleware families: a prefix and a function that builds the middleware for each route from the arguments and the route (POST /login), while the app builds. An error from it stops the app at boot. Core has the families throttle and auth; AppBuilder::middleware_family adds others:
rust
use smeltery::middleware::{BoxedMiddleware, Next, Request};
use smeltery::{AppBuilder, Error};

fn build(app: AppBuilder) -> AppBuilder {
    // `.middleware("tag:beta")` adds `X-Tag: beta` to the route's responses.
    app.middleware_family("tag", |args, _route| {
        let value = smeltery::http::HeaderValue::from_str(args)
            .map_err(|_| Error::internal(format!("invalid tag `{args}`")))?;
        Ok(BoxedMiddleware::new(move |req: Request, next: Next| {
            let value = value.clone();
            async move {
                let mut res = next.run(req).await;
                res.headers_mut().insert("x-tag", value);
                res
            }
        }))
    })
}

Two families with one prefix, a prefix that is empty or holds :, and a plain alias that starts with a family's <prefix>: stop the app at boot. route:list shows the alias as written.

Handlers are async functions. Their arguments are extractors: Path, Query, Form, Json (Axum's, re-exported in smeltery::http), App, ClientInfo (the client's IP, scheme and host, see The server), and Config<T> for your config structs. They return anything that implements IntoResponse, usually smeltery::Result<T>, or a Mold template struct (below). smeltery::http::wants_json(&headers) tells whether a client asks for JSON (its Accept names application/json or a +json type: error pages, auth and verified answer JSON then) and smeltery::http::is_inertia(&headers) whether a request is an Inertia visit (X-Inertia: true).

↑↓ moveEnter openEsc close