Smeltery
Get started

Smeltery

v0.1

Documentation

Prologue

  • IntroductionBatteries-included full-stack Rust: routing, typed configuration from .env, an application container, middleware, error pages, the Mold template engine…

Getting started

  • InstallThis installs the smeltery command.
  • Create an appsmeltery new asks a few questions.
  • Pages and CSSA new web app opens on a welcome page and has styled log-in, register, password-reset and dashboard pages, in light and dark (following the system setting)…
  • The app layoutThe app is one crate: bootstrap/app.rs is the library root and pulls each folder in as a module, so crate::app::controllers::home is app/controllers/home.rs.
  • ConfigurationConfig lives in typed structs under config/, read from .env with env(key, default).
  • Wiring: bootstrap/app.rsconfig(value) / service(value) register a value by type; handlers take Config<T>, other code calls app.config::<T>() / app.service::<T>().

The basics

  • Routes and controllersHandlers are async functions.
  • Mold templatesViews are resources/views/<name>.mold.html files with an @-directive syntax.
  • SessionsEvery route from routes/web.rs runs inside the session middleware; /api routes do not.
  • CSRFOn web routes, every request whose method is not GET, HEAD, OPTIONS or TRACE (POST, PUT, PATCH, DELETE, and any other method a Router::any route answers)…
  • Validation#[derive(Validate)] puts rules on a form struct, and the Valid<T> extractor reads, checks and hands it over.
  • Flash messagessession.flash("status", "Post saved.") followed by a redirect shows the message on the next page only.
  • ErrorsReturn smeltery::Error from a handler: Error::not_found(), forbidden(), unauthorized(), bad_request(msg), http(status, msg), internal(msg)…
  • The serversmeltery serve (or the app binary with serve) binds SERVER_HOST:SERVER_PORT.

Ingot (database)

  • Database and modelsThe database is set by DATABASE_URL in .env.
  • MigrationsMigrations live in database/migrations/, one file each, registered in order in database/migrations/mod.rs and wired with…
  • Seeders and factoriesA seeder fills the database; database/seeders/mod.rs registers them, wired with .seeders(database::seeders::register).

Digging deeper

  • Cachesmeltery::cache::Cache is the app's cache: a handler argument (or app.cache(), or ctx.cache() in Watchfire agents and jobs) on the default store, CACHE_STORE.
  • PubSub: messages between processessmeltery::pubsub::PubSub carries messages between the processes of one app (Sparks' Broadcast sends through it).
  • Console commandsThe app binary runs these commands (the smeltery command forwards them).
  • MailMail (smeltery::mail) is wired with .mail() in bootstrap/app.rs (the trait is smeltery::mail::MailExt, in the prelude).

Security

  • AuthenticationThe user model implements smeltery::auth::Authenticatable, and bootstrap/app.rs registers it with .auth::<User>().
  • Temper: the authentication routesTemper (smeltery::temper) puts the flows above behind routes: login, logout, registration, password reset, e-mail verification, password confirmation and…
  • Guards and the principalWho made a request is its principal (smeltery::auth::Principal): the user's id (user_id), the guard that proved it (guard), the credential (credential…
  • Encryption and random tokenssmeltery::crypto holds the helpers every part of Smeltery uses: random_token(len) (letters and digits from the OS random source, every character equally…

Hallmark (API tokens)

  • API tokensHallmark (smeltery::hallmark) gives an app personal access tokens: API clients, mobile and desktop apps, command-line tools and other backends send…
  • SPA authenticationA JavaScript frontend served from the app's own origin (from public/, or through a proxy or a Vite dev server under the same origin) can call auth:hallmark…

Sparks

  • Sparks: live componentsSparks (smeltery::sparks) are interactive components written in Rust and Mold, with no JavaScript to write.

Alloy

  • Alloy: React and VueAlloy (smeltery::alloy) is the server side of the Inertia protocol, version 3.
  • Rendering pagesThe component name is resolved by the client; in the kits it is the file under resources/js/pages/ without its extension.
  • Shared propsAlloy::share(f) adds props to every page, under the page's own (a page prop with the same key wins); the page's sharedProps lists their keys. f gets a…
  • Errors and flashprops.errors is on every page: the errors of the previous request's failed validation, the first message per field ({ "email": "The email field must be a…
  • Redirects and historyRedirect::to(url) and Back answer 303.
  • ViteThe kits build the JavaScript with Vite.
  • Testing pagesget_alloy(path) visits a page as Inertia's client does (with the current asset version), reload_alloy(path, component, &[props]) is a partial reload, and…
  • The React and Vue starter kitssmeltery new my-app --frontend react (or vue) writes the Rust side of a Mold app with Alloy instead of Mold pages and Sparks.

Anvil (broadcasting)

  • BroadcastingAnvil (smeltery::anvil) is a WebSocket server inside the app that speaks the Pusher Channels protocol 7, on the app's own port.
  • ChannelsThe signature in auth is HMAC-SHA256 under ANVIL_APP_SECRET (by default a secret derived from APP_KEY), over the socket id, the channel and who was…
  • EventsAn event is a struct that serializes to its data.
  • ClientsA client connects to ws://<host>/app/<ANVIL_APP_KEY>?protocol=7 (wss:// behind HTTPS) and receives pusher:connection_established with its socket_id and…
  • Settings and limitsA timer value outside its range in .env is replaced by the nearest bound, with a warning; outside its range in Settings passed to anvil_with, it stops the…
  • Testing broadcastsAnvilSpy records every send, the last 10,000 (sent(), sent_on(channel, name), nothing_sent()); TestSocket connects to the hub without a network (subscribe…
  • SearchProspect (smeltery::prospect) is full-text search for models.

Watchfire

  • AgentsWatchfire (smeltery::watchfire) runs the app's background work on one runtime: agents (long-lived, supervised tasks such as pollers, scrapers and bots)…
  • SupervisionStates: starting (waiting for a group or global slot), running, paused, stopping, stopped, backing_off, completed, failed, and standby (another process runs…
  • The context (AgentCtx)name(), run_id(), cancellation (cancelled(), is_cancelled(), token()), heartbeat(), sleep(d) and interval(d) (both return false once cancelled), http()…
  • HTTP and rate limitsctx.http() sends requests with a timeout (WATCHFIRE_HTTP_TIMEOUT, 30 s; 10 s to connect), retries connect errors, timeouts, 429 and 5xx up to 3 times with…
  • Jobs and the queueA job is a serializable struct (smeltery make:job SendWelcome), registered with w.job::<SendWelcome>().
  • The schedulerw.schedule() takes a target, .job(J) (dispatches it), .call(name, closure) or .agent(name) (starts it when it is stopped, completed, failed or backing off)…
  • Persistence and run historyWith a database, Watchfire keeps the agent registry, run history, checkpoints and (with the database queue driver) the job queue and the dead letters in…
  • Several processesserve runs the web server and the background work together. serve --no-agents (or WATCHFIRE_IN_SERVE=false) serves the web only, so a deployment can run web…
  • Dashboard and APIUnder /_watchfire/api (no sessions, no CSRF check).
  • LLM helpers(the llm feature: smeltery = { …, features = ["llm"] }). smeltery::watchfire::llm has the Provider trait (complete(Request) -> Response with the system…
  • Testing agentsTestApp leaves Watchfire off (dispatched jobs wait in the queue); TestApp::new(build).with_agents() starts it. smeltery::watchfire::testing::Harness runs…

Bellows

Deployment

  • DeploymentA Smeltery app runs on a server as one program: the release binary, started by systemd, behind Caddy or nginx for HTTPS.
  • BuildIt builds public/assets/css/app.css with Tailwind (--minify) when Tailwind is installed (see Pages and CSS; without it the committed app.css is kept) and…
  • React and Vue appssmeltery build runs npm run build, which writes public/build/ (the hashed JavaScript and CSS and manifest.json); deploy it with public/.
  • Server layoutA system user without a login shell runs the app.
  • Production .env--show only prints a fresh key: it reads no .env and writes nothing, so any user can run it.
  • First deployWith the binary, public/, .env and the folders in place.
  • systemd: start on boot, restart on crashserve runs the web server and the Watchfire agents, queue workers and scheduler together: one unit is a complete deployment.
  • HTTPS: Caddy or nginxThe app listens on 127.0.0.1:8000; a reverse proxy on the same machine terminates HTTPS.
  • The Watchfire dashboard in productionOutside APP_ENV=local, /_watchfire is open only to signed-in users that the app's dashboard gate admits; without a gate nobody gets in.
  • UpdatingWith two processes: migrate, then sudo systemctl restart myapp-work myapp-web.
  • Operationsjournalctl -u myapp (-f follows, --since "1 hour ago"); with LOG_FILE, also storage/logs/smeltery.log and its .1 backup.
  • Checklistsmeltery build on Linux; binary, public/ (with app.css), storage/, database/ on the server

Quench (testing)

  • TestingTestApp::new(build) builds the whole app (all middleware, error pages and static files) with APP_ENV=testing; get, get_json, post_form, post_json…

Reference

  • The smeltery commandThe make:* commands create new files only: they refuse when a target file exists, and they add pub mod and registration lines above the // smeltery:… marker…
  • Demo appsThree apps in examples/, each listing the exact commands in its README (the two Smeltery apps are built with the smeltery generators).

↑↓ moveEnter openEsc close