Smeltery
Get started

Sparks

v0.1

Sparks: live components

Sparks (smeltery::sparks) are interactive components written in Rust and Mold, with no JavaScript to write. A Spark is a struct (its state) with #[derive(Spark)], a view in resources/views/sparks/<name>.mold.html, and actions in an #[actions] impl block. The page renders it on the server; the client runtime (sparks.js, served by the app at /_sparks/sparks.js) sends clicks and input to the server, which runs the action, re-renders the view and answers the new HTML, which the runtime morphs into the page.

rust
use smeltery::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Default, Spark)]
#[spark(name = "counter")]          // view: resources/views/sparks/counter.mold.html
pub struct Counter {
    pub count: i64,                 // server-only: the page cannot set it
    #[spark(model)]
    pub step: i64,                  // wire:model may set it
}

#[actions]
impl Counter {
    /// Runs on the first render, with the props of `@spark("counter", { start: 5 })`.
    pub async fn mount(&mut self, ctx: &mut SparkCtx) -> Result<()> {
        self.count = ctx.prop("start").unwrap_or(0);
        self.step = 1;
        Ok(())
    }

    pub async fn increment(&mut self) -> Result<()> {
        self.count += self.step;
        Ok(())
    }

    pub async fn add(&mut self, ctx: &mut SparkCtx, n: i64) -> Result<()> {
        self.count += n;
        ctx.dispatch("counted", json!({ "count": self.count }));
        Ok(())
    }

    #[guard(auth)]                  // only for a signed-in user
    pub async fn reset(&mut self) -> Result<()> {
        self.count = 0;
        Ok(())
    }
}
text
{{-- resources/views/sparks/counter.mold.html --}}
<div>
  <p>Count: {{ count }}</p>
  <input type="number" wire:model.live="step">
  <button wire:click="increment">+{{ step }}</button>
  <button wire:click="add(10)">+10</button>
  <span wire:loading>Saving…</span>
</div>

A page shows it with @spark("counter", { start: 5 }) and loads the runtime once with @sparksScripts (in the layout's <head>; it also writes the CSRF meta tag). app/sparks/mod.rs registers the components and bootstrap/app.rs wires them with .sparks(app::sparks::register) (the trait is smeltery::sparks::SparksExt, in the prelude):

rust
// app/sparks/mod.rs
pub mod counter;

pub fn register(s: &mut smeltery::sparks::Sparks) {
    s.add::<counter::Counter>();
    // smeltery:sparks
}

#[spark(...)] takes name (default: the struct name in snake case), view (default sparks/<name>) and stream (see below). Props whose name is a field set that field before mount; every prop is readable with ctx.prop("name"). The view renders like any Mold view: from the template files with hot reload in debug builds, compiled into the binary in release builds.

Actions are the pub async fn methods of the #[actions] block that take &mut self; nothing else can be called from the page. After &mut self an action may take ctx: &mut SparkCtx, then parameters deserialized from the call (wire:click="add(10)", remove('a')). #[guard(auth)] requires a signed-in user (#[guard(guest)] the opposite). Three hooks (and can_stream for streamed components, below): async fn mount(&mut self, ctx: &mut SparkCtx), async fn updated(&mut self, ctx: &mut SparkCtx, field: &str) (after a wire:model update) and async fn rendering(&mut self, ctx: &mut SparkCtx) (before every render, $refresh included: load fresh data).

In the view Does
wire:click="action", wire:click="action(1, 'a')", .prevent calls the action on click
wire:submit="save" calls on form submit (the browser's submit is prevented)
wire:keydown.enter="save" calls on that key (enter, escape, tab, space, arrows, letters)
wire:model="field" binds an input to a #[spark(model)] field; sent with the next action
wire:model.live, .debounce.300ms, .blur, .change sends after typing pauses (150 ms, or the given time), on blur, on change
wire:loading, .remove, .class="…", .attr="disabled", .flex, .block shown / hidden / classes / attribute while a request runs
wire:target="save,step" limits wire:loading to those actions and fields
wire:poll.5s="action" calls the action (or re-renders) every interval while the tab is visible
wire:key="…" keeps list items matched across re-renders
wire:click="$refresh" re-renders without an action

Inputs bound with wire:model show the component's state; text from inputs is converted to the field's type ("3" → 3, a checkbox → bool), and a value that does not fit shows "The step field is invalid." through @error("step"). A value for a #[spark(model)] field is text, a number, a boolean, null or a list of those, never an object, and it never sets a struct (a list that serde would read as one is refused too), so the page cannot fill a struct field with keys the view does not show; null clears an optional one. A struct field takes the keys listed in #[spark(model(fields = "title, body"))], one at a time (wire:model="form.title", or $spark.$set('form', { title: 'Hi' }) with listed keys only); any other key is refused (403). When a re-render adds elements with autofocus (which browsers ignore on elements added after the page loaded), the runtime focuses the first of them once, after filling its wire:model value, unless focus is on an element outside that Spark (a field or button of another Spark, a link in the page).

SparkCtx gives actions app(), db(), auth(), user_id(), session(), prop(name), redirect(url) (the browser goes there: a path on this site such as /posts/3, or an address on APP_URL), redirect_away(url) (another site, an http:// or https:// URL; any other target given to either fails the update with 500 and a log line, so a URL from data never runs script), dispatch(event, payload) (a CustomEvent on window, the payload as its detail), flash(key, value) and validate(self). With #[derive(Validate)] on the component, ctx.validate(self).await? checks its rules; on failure the component re-renders with the messages, which @error("field") inside its view shows.

Nesting: a component's view may use @spark("item", { key: post.id, … }). Each child keeps its own state and updates on its own; when the parent re-renders, existing children (matched by key, or by position) stay as they are, new keys mount new children, and children left out disappear.

Uploads: a field #[spark(upload(max = 2048, mimes = "png,jpg"))] pub photo: Option<TemporaryUpload> (max in kilobytes, mimes as file extensions) bound with <input type="file" wire:model="photo"> receives the file as soon as it is chosen. The file waits in storage/framework/sparks/; a file that is too large or of another type shows its message through @error("photo"). photo.store(ctx, "public/avatars").await? moves it to storage/app/public/avatars/<random>.png and returns public/avatars/<random>.png (store_as(ctx, dir, name) picks the name). Only public/… and private/… directories are accepted; files under storage/app/public are served at /storage/… after smeltery storage:link. Temp files are deleted 24 hours after the upload (by a later upload request). mimes checks the extension of the file's name, not its content. store keeps the name's extension only when it is on the list of safe extensions that UploadedFile::store uses (smeltery::http::is_safe_extension); any other is stored as .bin. One session may send 30 uploads and 100 MiB per 10 minutes (s.upload_quota(files, bytes, per) in app/sparks/mod.rs), and one client address 120 uploads and 400 MiB in the same window (s.upload_address_quota(files, bytes); the address is ClientInfo::ip, which honours TRUSTED_PROXIES); past either an upload answers 429 without reading the file. #[validate(...)] rules work on upload fields too (with #[derive(Validate)] and ctx.validate(self)): required passes once a file is chosen, min, max and between count kilobytes, and mimes = "png,jpg" checks the name's extension.

Push from the server: a component declared with #[spark(stream)] listens on GET /_sparks/stream (one connection per page). Broadcast (a handler argument, or app.service::<Broadcast>()) sends to it by component name or instance id: refresh() makes the page re-fetch the component, emit(event, payload) fires a browser event. A page subscribes with the stream token each render of the component carries (wire:stream="…", valid for the snapshot time to live); the hook async fn can_stream(&mut self, ctx: &mut SparkCtx) -> Result<bool> in the #[actions] block decides per render whether the visitor gets one (default: yes), so a visitor it refuses cannot subscribe. A token is bound to the session and the signed-in user of the render: the stream accepts it only with that session's cookie, and ends when that session signs out (logout, logout_other_devices, a password change or reset, end_credentials, in any process of the app) and when the tokens expire. After a sign-out the page does not open it again; otherwise it opens it again with the tokens of its latest render, after 5 seconds, doubling with each failure in a row up to 5 minutes. One client address (an IPv6 client by its /64) may open 60 streams a minute (s.stream_opens_per_minute(n), counted in process memory); past that a stream answers 429. Visitors behind one NAT or proxy address share that budget, one stream per page load: raise it for such audiences. The stream carries refresh signals (the page then sends an ordinary update with its own session and snapshot) and emit payloads, which every page subscribed to that name or id receives, so a payload never holds private data. A process keeps at most 1000 streams open (s.max_streams(n)); past that a stream answers 503 and the page retries. emit refuses event names starting with anvil: (it sends nothing and returns 0): they belong to listeners (below). refresh() and emit() deliver to the pages connected to the sending process at once and return how many those are; they also hand the message to the app's PubSub, which carries it to the pages held by the app's other processes, so an agent in a work process reaches the pages of a serve --no-agents process. That hand-over never blocks the caller: it goes through a queue of 1024 messages, and a message the queue or the driver cannot take is dropped, counted and logged; delivery to other processes is at most once. A Watchfire agent can drive a live counter:

rust
use smeltery::sparks::Broadcast;
use smeltery::watchfire::prelude::*;

pub fn register(w: &mut Watchfire) {
    w.every(5.secs(), "live-counter", |ctx| async move {
        if let Some(broadcast) = ctx.service::<Broadcast>() {
            broadcast.to("counter").refresh();
        }
        Ok(())
    });
}

Listening to broadcasts: with Anvil installed, a #[spark(stream)] component reacts to broadcast events without any JavaScript: a method of its #[actions] block marked #[on("anvil:<channel>", "<event>")] runs when that event is broadcast on that channel, by any process of the app.

rust
use smeltery::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Default, Spark)]
#[spark(name = "order-status", stream)]
pub struct OrderStatus {
    pub order_id: i64,
    pub status: String,
}

/// The event's data.
#[derive(Deserialize)]
pub struct Shipped {
    pub tracking: String,
}

#[actions]
impl OrderStatus {
    #[on("anvil:private-orders.{order_id}", "App\\Events\\OrderShipped")]
    pub async fn shipped(&mut self, ctx: &mut SparkCtx, event: Shipped) -> Result<()> {
        self.status = format!("Shipped: {}", event.tracking);
        ctx.dispatch("order-shipped", smeltery::json!({ "id": self.order_id }));
        Ok(())
    }
}
  • The channel is the full name (private-…, presence-… or a public name); {order_id} is the value of that state field when the component renders (a string or an integer of letters, digits and _ - = @ , ;). The event name is the name the event is sent with: App\Events\OrderShipped for #[derive(BroadcastEvent)] struct OrderShipped (see Events).
  • Each render asks the app's channel rules (routes/channels.rs, the same callbacks as POST /broadcasting/auth, with the visitor's session) whether this visitor may receive each channel; the stream asks again when it opens. Only allowed channels reach the page. An event sent with .except(socket) reaches listeners too.
  • The page receives the event through its Sparks stream, as a message signed for that component instance, and sends it back with an ordinary update request; the method then runs with the event's data deserialized into its last argument (400 when it does not fit), with the visitor's session and a fresh snapshot, like an action. Before anything of the request runs, the server checks the signature, that the message is at most 60 seconds old, that a listener takes that event on that channel, and asks the channel rules again for the visitor (403 otherwise). At the listener's turn, after the request's other updates and calls (the page sends pending wire:model values with it), the channel is resolved from the state as it is then: when the state names another channel, nothing runs. Each message runs once, whatever snapshot of the component it comes with: the app's cache remembers it for 60 seconds (with a shared cache store, across the app's processes), and a cache failure refuses it (503). A message that did not run because an earlier call of the same request failed validation can be sent again.
  • A listener is not an action: the page cannot call it by name. It may take &mut SparkCtx and one more argument (the data), and takes no #[guard]. A method may carry several #[on]; a component at most 16.
  • The browser also gets the window event anvil:<event> with the data (detail), once per listening component, for Alpine code that only shows something. It comes from the page itself and any script on the page can fire one: act on events in the listener, on the server.
  • Delivery is at most once: an event broadcast while the page's stream is reconnecting does not reach the listener (the page refreshes its components after a reconnect). Event data over 64 KiB is not sent to listeners.
  • Without Anvil installed, on a component without stream, with a {field} the struct does not have, or with CACHE_STORE=null (listeners need a cache store that keeps values), the app does not start.

Alpine.js: Alpine attributes (x-data, x-show, @click, …) work in Mold views as they are; where an event name is also a Mold directive, write the long form (x-on:error). A server value inside Alpine code goes through the json filter, never between quotes: x-data="{ name: {{ name | json }} }", @click="pick({{ id | json }})" (see Mold templates); inside a Spark, $spark reads the state without any echo. With Alpine.js 3.13 or newer loaded after @sparksScripts (both scripts defer), Alpine code inside a Spark reaches that Spark as $spark:

text
{{-- resources/views/sparks/search.mold.html --}}
<div x-data="{ open: $spark.$entangle('open'), q: $spark.$entangle('query').live }">
  <p>Found <span x-text="$spark.total"></span></p>
  <button @click="$spark.more(10)">More</button>
  <button @click="open = !open">Filters</button>
  <div x-show="open">…</div>
  <input x-model="q">
</div>
In Alpine code Does
$spark.total, $spark.$get('total') reads a field; Alpine updates when a response changes it or a wire:model input of that field changes
$spark.step = 2 sets a field, sent with the next request (like wire:model)
$spark.$set('step', 2) sets a field and sends it now ($set('step', 2, false) waits for the next request)
$spark.more(10), $spark.$call('more', 10) calls an action with those parameters
$spark.$refresh(), $spark.$commit() re-renders; sends the recorded field updates
$spark.$entangle('open') in x-data: an Alpine property bound both ways to the field; Alpine's changes go with the next request
$spark.$entangle('open').live, $spark.$entangle('open', true) the same, each change sent at once
$spark.$id, $spark.$name, $spark.$el the instance id, the component name, the Spark's root element

$spark goes through the same requests as wire:*, so it reaches only what the server allows: a field without #[spark(model)] or a name that is not an action is refused (403) with the whole request, and a value set from Alpine shows until the next response replaces it. $spark.<name> reads the field of that name when the state has one; any other name calls the action of that name, except the $ helpers, the built-in object names (toString, constructor, …), then, toJSON and names starting with __ (call those with $call). Read fields in bindings (x-text, :class, …) and call actions from events (@click, …): a binding that calls an action ($spark.total()) sends it each time the binding re-runs, and an action called while the morph renders the bindings is not sent (the console shows a warning). With an Alpine older than 3.13 there is no $spark, and the console says so. When a Spark re-renders with Alpine 3.13 or newer on the page, the morph keeps Alpine's state: x-data elements keep their data, what Alpine renders (x-text, x-show, :class, …) is rendered from that data into the new HTML before the diff (Alpine's cloneNode, as in Alpine's morph plugin), x-model inputs keep their values, and the rows of x-for and the element of x-if stay. New elements from the server are initialised by Alpine. Elements are matched by wire:key, id, or tag and position: give Alpine components in lists a wire:key. sparks.js does not depend on Alpine: without Alpine on the page there is no $spark, and everything else is the same.

Security: the state travels in the page signed with a key derived from APP_KEY (HMAC-SHA256), so it cannot be changed, but it can be read: secrets never go into component fields. The snapshot is bound to the session it was rendered for (a hash of the session's CSRF secret) and to the signed-in user, and is accepted for the session lifetime after it was issued (s.snapshot_ttl(duration)); every response issues a fresh one. A snapshot copied to another browser, kept past a logout or a sign-in, or older than that answers 419 and the page reloads. Within its own session an older snapshot of the page can be sent again, so an action checks permission itself, with ctx.auth() and the database, for every record it touches: a field set in mount is not proof that the user may act on it. Updates are POST /_sparks/update and uploads POST /_sparks/upload, web routes with the session and the CSRF check. A changed state, a CSRF mismatch or an APP_KEY that changed answers 419 too. Updating a field without #[spark(model)], calling a method that is not an action, or an unknown component is refused (403 / 404) and logged, and nothing runs. A request carries at most one component (s.max_components(n)) with at most 50 action calls (s.max_calls(n)); a larger request answers 413 before anything runs. The limits are set on the registry in app/sparks/mod.rs (s.max_calls(20); next to s.add::<…>()).

Testing: smeltery::sparks::testing::TestSpark drives a component on a page from TestApp:

rust
let page = app.get("/counter");
let mut counter = TestSpark::from_html(&page.text(), "counter").unwrap();
counter.set("step", 2).call("increment", json!([])).send(&app);
assert!(counter.html().contains("Count: 7"));
assert_eq!(counter.data()["count"], 7);

smeltery::sparks::testing::BroadcastSpy records what a Broadcast pushes: BroadcastSpy::of(app.app()), then spy.pushes() returns the messages since the last call (target, kind, event, payload; is_refresh_of("counter")). It listens like an open page, so it counts in what refresh() returns.

↑↓ moveEnter openEsc close