Skip to main content

Crate smeltery_sparks

Crate smeltery_sparks 

Source
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 @sparksScripts in Mold views, and the routes POST /_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 the pub async fn methods of the #[actions] block are callable; #[guard(auth)] / #[guard(guest)] on actions; mount, updated and rendering hooks. The state’s keys are the field names: #[serde(rename …)], alias and flatten on 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 and APP_URL addresses), redirect_away (http/https URLs), dispatch, flash, validate.
  • Nested components keyed by key (or position), each with its own state.
  • TemporaryUpload fields with size and extension rules, store / store_as into storage/app/{public,private}.
  • An Alpine.js bridge in sparks.js (with Alpine 3.13 or newer on the page): $spark reads 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 a TestApp page; testing::BroadcastSpy records what a Broadcast pushes.

Licensed under either of Apache License 2.0 or MIT license at your option.

Modules§

testing
Test helpers: drive a component on a page rendered by TestApp, like the browser would.

Structs§

ActionInfo
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.
ListenerInfo
A listener: a method that runs when event is broadcast on the channel channel names (#[on("anvil:private-orders.{order_id}", "OrderShipped")]).
SparkCtx
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 Broadcast addressed to one target.
TemporaryUpload
A file uploaded through wire:model on a file input, waiting in storage/framework/sparks/ until the component stores it. Use it as an Option<TemporaryUpload> field marked #[spark(upload(...))].
UploadRule
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 v of 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.
SparksExt
Installs Sparks on an AppBuilder: .sparks(app::sparks::register) in bootstrap/app.rs.

Functions§

extend
Add components to an app whose Sparks are installed, from an on_boot hook: how a framework crate (such as Watchfire’s live dashboard) registers its own components without the app listing them. Returns false when the app has no Sparks (.sparks(…) was not called).
stream_token
The stream token of instance id of component name: the value of wire:stream="…" that lets a page subscribe to that name and id on GET /_sparks/stream. Renders of #[spark(stream)] components write it themselves (when their can_stream hook 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 to session and the user signed in with auth (the request’s): the stream accepts it only from that session and user, and ends when that session is signed out. Pass None for both only on a page without a session.