Expand description
§smeltery-sparks
Sparks are the live components of the Smeltery framework: a Rust struct (the
state) with a Mold view and async actions, rendered on the server and kept in sync with the browser by a small
client runtime (js/sparks.js, embedded in this crate and served at /_sparks/sparks.js). Apps use it through the
facade as smeltery::sparks, with #[derive(smeltery::Spark)] and #[smeltery::actions]; the full guide is the
“Sparks: live components” section of the Smeltery README.
use smeltery::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Default, Spark)]
#[spark(name = "counter")] // resources/views/sparks/counter.mold.html
pub struct Counter {
pub count: i64,
#[spark(model)]
pub step: i64,
}
#[actions]
impl Counter {
pub async fn increment(&mut self, ctx: &mut SparkCtx) -> Result<()> {
self.count += self.step;
ctx.dispatch("counted", json!({ "count": self.count }));
Ok(())
}
}
// app/sparks/mod.rs: `pub fn register(s: &mut Sparks) { s.add::<counter::Counter>(); }`
// bootstrap/app.rs: `app.sparks(app::sparks::register)` (`smeltery::sparks::SparksExt`)What it has:
SparksExt::sparks(register): the registry,@spark("name", { props })and@sparksScriptsin Mold views, and the routesPOST /_sparks/update,POST /_sparks/upload(session + CSRF),GET /_sparks/sparks.js,GET /_sparks/stream.- Signed snapshots (HMAC-SHA256 under a key derived from
APP_KEY), bound to the session and the signed-in user they were rendered for and accepted for the session lifetime (Sparks::snapshot_ttl); a tampered, foreign or expired snapshot, a CSRF mismatch or another protocol version answers 419 and the page reloads. - Only
#[spark(model)]fields accept updates (never an object; a struct field takes the keys listed in#[spark(model(fields = "…"))]) and only thepub async fnmethods of the#[actions]block are callable;#[guard(auth)]/#[guard(guest)]on actions;mount,updatedandrenderinghooks. The state’s keys are the field names:#[serde(rename …)],aliasandflattenon a Spark are compile errors. - Request limits on the registry:
max_components(default 1),max_calls(default 50),upload_quota(default 30 files and 100 MiB per session per 10 minutes),upload_address_quota(default 120 files and 400 MiB per client address in that window),max_streams(default 1000). SparkCtx:app,db,auth,user_id,session,prop,redirect(paths on this site andAPP_URLaddresses),redirect_away(http/httpsURLs),dispatch,flash,validate.- Nested components keyed by
key(or position), each with its own state. TemporaryUploadfields with size and extension rules,store/store_asintostorage/app/{public,private}.- An Alpine.js bridge in
sparks.js(with Alpine 3.13 or newer on the page):$sparkreads and sets fields, calls actions and binds Alpine properties to fields ($spark.$entangle('open'),.live); the morph keeps Alpine’s state. Broadcast: server push over server-sent events (to(target).refresh(),.emit(event, payload)), to the pages of every process of the app through its PubSub. Stream tokens are bound to the session and user of the render; a stream ends when that session signs out and when its tokens expire.- Listeners:
#[on("anvil:private-orders.{order_id}", "OrderShipped")]on a method of a#[spark(stream)]component runs it when that event is broadcast on that channel (with Anvil installed). Channels are authorized for the viewer at render, when the stream opens and before the method runs; the event reaches the page as a message signed for the instance (sparks.listen), which runs once (a seen-set in the app’s cache) and at most 60 seconds after it was sent, only when the state names the channel at the moment the listener runs. testing::TestSpark: drives a component on aTestApppage;testing::BroadcastSpyrecords what aBroadcastpushes.
Licensed under either of Apache License 2.0 or MIT license at your option.
Modules§
Structs§
- Action
Info - An action’s name and guards.
- Broadcast
- Pushes to live components on open pages (components declared with
#[spark(stream)]): a refresh (the page re-fetches the component through its normal update request) or a browser event. - Listener
Info - A listener: a method that runs when
eventis broadcast on the channelchannelnames (#[on("anvil:private-orders.{order_id}", "OrderShipped")]). - Spark
Ctx - The context of an action or hook: the app, the visitor’s session and sign-in, the mount props, and the effects to send back to the browser (redirect, browser events).
- Sparks
- The components of an app, registered in
app/sparks/mod.rs: - Target
- A
Broadcastaddressed to one target. - Temporary
Upload - A file uploaded through
wire:modelon a file input, waiting instorage/framework/sparks/until the component stores it. Use it as anOption<TemporaryUpload>field marked#[spark(upload(...))]. - Upload
Rule - The rules of an upload field (
#[spark(upload(max = 2048, mimes = "png,jpg"))]).
Enums§
- Guard
- A requirement an action checks before it runs (
#[guard(auth)]).
Constants§
- PROTOCOL_
VERSION - The wire protocol version (the
vof snapshots and requests). - SPARKS_
JS - The client runtime, embedded in the crate.
- VERSION
- The crate version, which the client runtime’s URL carries (
/_sparks/sparks.js?v=…).
Traits§
- Actions
- The callable actions and the hooks of a component.
#[actions]on the component’s impl block implements it. - Spark
- A live component: its state (the struct’s fields) and its Mold view.
#[derive(Spark)]implements it. - Sparks
Ext - Installs Sparks on an
AppBuilder:.sparks(app::sparks::register)inbootstrap/app.rs.
Functions§
- extend
- Add components to an app whose Sparks are installed, from an
on_boothook: how a framework crate (such as Watchfire’s live dashboard) registers its own components without the app listing them. Returnsfalsewhen the app has no Sparks (.sparks(…)was not called). - stream_
token - The stream token of instance
idof componentname: the value ofwire:stream="…"that lets a page subscribe to that name and id onGET /_sparks/stream. Renders of#[spark(stream)]components write it themselves (when theircan_streamhook allows); this is for components whose wrapper is rendered outside the normal mount path. Call it only after checking that the viewer may receive the component’s pushes. It is valid for the snapshot time to live (Sparks::snapshot_ttl, default the session lifetime) and bound tosessionand the user signed in withauth(the request’s): the stream accepts it only from that session and user, and ends when that session is signed out. PassNonefor both only on a page without a session.