Storing data
A handler keeps the data that requests share in a database its own Rust code connects to, with the connection in the router's state. The page also covers telling the streams of every server process about a change.
Where the data lives
hypersig has no storage of its own. An action's handler is a Rust function that reads and writes the data however its code says, and hypersig sends the Page or Patches it returns to the browser. Which store fits depends on how long the data has to last and where the server runs.
| Store | Lasts | Example |
|---|---|---|
The router's state in memory, such as an Arc<Mutex<..>> | Until the process stops, and only in that process | todo and the other examples |
| A database the server opens with a driver: SQLite, PostgreSQL, MySQL, DynamoDB | Past a restart, and every process on the database reads it | database (SQLite), postgres |
| A database the host binds to the worker: D1, KV, a Durable Object | Past a restart, and every isolate reads it | The Cloudflare template |
| Another service, called over its HTTP API | As long as the service keeps it | api, which Calling another service's API covers |
The examples live under examples/ in the repository, and each runs with cargo run -p example-<name>.
The connection in the router's state
The first line of routes!, fn pages(Router<AppState>);, names the router's state type, and each page and action handler receives a clone of that state as its first argument. A handler is a Handler: Fn(St, A) -> O, or Fn(St, E, A) -> O with an extractor E between the state and the arguments. Put the connection, or a pool of connections, in the state, and have each handler read and write through it. The pages, actions, and signals stay as they were, because a handler still returns the same Page and Patches.
The sample below needs rusqlite, whose bundled feature compiles SQLite into the program, so the server does not depend on a SQLite installed on the machine:
[dependencies]
rusqlite = { version = "0.39", features = ["bundled"] }use std::sync::{Arc, Mutex};
use rusqlite::Connection;
#[derive(Signals, Serialize, Deserialize)]
struct Todos {
count: i32,
}
#[derive(Clone)]
struct AppState {
db: Arc<Mutex<Connection>>,
}
#[derive(Debug)]
struct DbError(rusqlite::Error);
impl IntoResponse for DbError {
fn into_response(self) -> Response {
eprintln!("database: {}", self.0);
let message = "The list could not be read. Try again.";
(StatusCode::INTERNAL_SERVER_ERROR, message).into_response()
}
}
async fn titles(state: &AppState) -> Result<Vec<String>, DbError> {
let db = Arc::clone(&state.db);
// rusqlite blocks the thread until SQLite answers.
tokio::task::spawn_blocking(move || -> rusqlite::Result<Vec<String>> {
let db = db.lock().expect("database lock poisoned");
db.prepare("SELECT title FROM todos ORDER BY id")?
.query_map([], |row| row.get(0))?
.collect()
})
.await
.expect("query panicked")
.map_err(DbError)
}
async fn index(state: AppState, (): ()) -> Result<Page<Todos>, DbError> {
let titles = titles(&state).await?;
let count = i32::try_from(titles.len()).unwrap_or(i32::MAX);
let list = ul().children(titles.into_iter().map(|title| li().text(title)));
Ok(Page::new("Todos", Todos { count }).child(list))
}
hypersig::routes! {
fn pages(Router<AppState>);
const INDEX: Route = "/" => index;
}
let db = Connection::open("todos.db")?;
db.execute_batch(
"CREATE TABLE IF NOT EXISTS todos (id INTEGER PRIMARY KEY, title TEXT NOT NULL)",
)?;
let state = AppState { db: Arc::new(Mutex::new(db)) };
let _app: Router = pages(Router::new()).hypersig_runtime().with_state(state);axum clones the state for each request, so it is Clone, and a rusqlite Connection is Send but not Sync, so the state holds it in an Arc<Mutex<..>>. rusqlite's calls block the thread until SQLite answers. The thread it blocks would be one of the tokio workers that serve every request, so each query runs in tokio::task::spawn_blocking, on threads kept for blocking work.
A handler of another state
The state a handler takes has to be the router's. A handler of AppState named in a Router<()> fails to compile with E0277. The message names the function's type and says it cannot serve this page or action, and a note says that the state is the router's:
#[derive(Clone)]
struct AppState;
async fn index(_state: AppState, (): ()) -> Page<Todos> {
Page::new("Todos", Todos { count: 0 })
}
hypersig::routes! {
// The router's state is `()`, and `index` takes an `AppState`.
fn pages(Router<()>);
const INDEX: Route = "/" => index;
}When a query fails
A page handler may return Result<Page<S>, E>, and an action handler Result<Patches<S>, E>, where E implements axum's IntoResponse. The handler passes a failed query on with ?, and the error's into_response is the answer. The sample's DbError logs the database's message on the server, because that message can hold the query and the connection string, and answers with a sentence for the visitor:
HTTP/1.1 500 Internal Server Error
content-type: text/plain; charset=utf-8
The list could not be read. Try again.A browser that loads the page shows that text in place of the page. When an action fails, the runtime writes the same text/plain body to the signal given to Call::error, so write a sentence the visitor can act on. Errors and logging covers the handler's errors in general.
A Result is a page's answer only when its error implements IntoResponse. Without that impl the line of routes! fails to compile with E0277, which says that the trait bound DbError: IntoResponse is not satisfied:
#[derive(Debug)]
struct DbError(String);
// `DbError` has no `IntoResponse`, so the router has no answer for it.
async fn index(_state: AppState, (): ()) -> Result<Page<Todos>, DbError> {
Err(DbError("no such table: todos".to_owned()))
}
hypersig::routes! {
fn pages(Router<AppState>);
const INDEX: Route = "/" => index;
}A driver with async calls
sqlx, which examples/postgres uses, has async functions, so a handler awaits the query and needs no spawn_blocking, and the worker thread serves other requests while it waits. Its pool, PgPool, is Clone and shares its connections between the clones, so it goes in the state without an Arc:
[dependencies]
sqlx = { version = "0.9", default-features = false, features = ["postgres", "runtime-tokio", "tls-rustls"] }use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
#[derive(Clone)]
struct AppState {
db: PgPool,
}
#[derive(Debug)]
struct DbError(sqlx::Error);
impl From<sqlx::Error> for DbError {
fn from(error: sqlx::Error) -> Self {
Self(error)
}
}
impl IntoResponse for DbError {
fn into_response(self) -> Response {
eprintln!("database: {}", self.0);
let message = "The list could not be read. Try again.";
(StatusCode::INTERNAL_SERVER_ERROR, message).into_response()
}
}
async fn index(state: AppState, (): ()) -> Result<Page<Todos>, DbError> {
let titles: Vec<String> = sqlx::query_scalar("SELECT title FROM todos ORDER BY id")
.fetch_all(&state.db)
.await?;
let count = i32::try_from(titles.len()).unwrap_or(i32::MAX);
let list = ul().children(titles.into_iter().map(|title| li().text(title)));
Ok(Page::new("Todos", Todos { count }).child(list))
}
hypersig::routes! {
fn pages(Router<AppState>);
const INDEX: Route = "/" => index;
}
let url = std::env::var("DATABASE_URL").expect("DATABASE_URL names the database");
let db = PgPoolOptions::new().max_connections(5).connect(&url).await?;
let _app: Router = pages(Router::new()).hypersig_runtime().with_state(AppState { db });For MySQL, turn on sqlx's mysql feature in place of postgres, use a MySqlPool and a mysql:// URL, and write ? in place of $1 in the queries. The query in this sample is a string the compiler does not read. SQL the compiler checks shows the macros that check it when the program is built.
Updates with more than one process
A stream that sends the list after each change hears of the change through a tokio::sync::broadcast channel in the router's state, and that channel belongs to one process. In examples/database, a second process on the same SQLite file reads the same todos, but a write by one process sends nothing to the other process's streams, so a tab served by the other process shows the write when it loads the page again.
PostgreSQL's LISTEN and NOTIFY
The migration of examples/postgres creates a trigger that calls pg_notify after each statement that changes the table, and PostgreSQL delivers the notification when the transaction commits:
CREATE FUNCTION notify_todos_changed() RETURNS trigger AS $$
BEGIN
PERFORM pg_notify('todos_changed', '');
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER todos_changed
AFTER INSERT OR UPDATE OR DELETE ON todos
FOR EACH STATEMENT EXECUTE FUNCTION notify_todos_changed();Each process listens on that channel with sqlx's PgListener and forwards what it hears to its own broadcast, so every open tab shows the write at once. A write by this process reaches its own streams the same way, through the trigger, so an action that writes needs to send nothing to changed itself:
use std::time::Duration;
use futures::{Stream, StreamExt as _, stream};
use sqlx::PgPool;
use sqlx::postgres::{PgListener, PgPoolOptions};
use tokio::sync::broadcast::{self, error::RecvError};
#[derive(Signals, Serialize, Deserialize)]
struct Todos {
titles: Vec<String>,
}
#[derive(Clone)]
struct AppState {
db: PgPool,
/// Tells this process's streams that the table changed.
changed: broadcast::Sender<()>,
}
async fn titles(db: &PgPool) -> Result<Vec<String>, sqlx::Error> {
sqlx::query_scalar("SELECT title FROM todos ORDER BY id")
.fetch_all(db)
.await
}
async fn index(state: AppState, (): ()) -> Page<Todos> {
let titles = titles(&state.db).await.unwrap_or_else(|error| {
// The stream sends the list again once it opens.
eprintln!("database: {error}");
Vec::new()
});
Page::new("Todos", Todos { titles }).child(
ul().on_load(UPDATES.call().reconnect())
.child(each(Todos::titles(), |title| li().bind_text(title.value()))),
)
}
/// Sends the list once, then again after each change any process makes.
fn updates(state: AppState, (): ()) -> impl Stream<Item = Patches<Todos>> {
let changes = stream::unfold(state.changed.subscribe(), |mut changes| async move {
match changes.recv().await {
// A receiver that fell behind missed some changes, and reading
// the list again covers them.
Ok(()) | Err(RecvError::Lagged(_)) => Some(((), changes)),
Err(RecvError::Closed) => None,
}
});
stream::once(async {}).chain(changes).filter_map(move |()| {
let db = state.db.clone();
async move {
match titles(&db).await {
Ok(titles) => Some(Todos::titles().patch(titles).into()),
Err(error) => {
eprintln!("database: {error}");
None
}
}
}
})
}
/// Forwards each notification on `todos_changed` to this process's streams.
async fn listen(mut listener: PgListener, changed: broadcast::Sender<()>) {
loop {
// After an error, the next `recv` connects again. A notification
// sent in between is lost, so the streams read the list again.
if let Err(error) = listener.recv().await {
eprintln!("database: {error}");
tokio::time::sleep(Duration::from_secs(1)).await;
}
let _ = changed.send(());
}
}
hypersig::routes! {
fn pages(Router<AppState>);
const INDEX: Route = "/" => index;
stream UPDATES: StreamAction<Todos> = "/todos/updates" => updates;
}
let url = std::env::var("DATABASE_URL").expect("DATABASE_URL names the database");
let db = PgPoolOptions::new().max_connections(5).connect(&url).await?;
let mut listener = PgListener::connect_with(&db).await?;
listener.listen("todos_changed").await?;
let (changed, _) = broadcast::channel(16);
tokio::spawn(listen(listener, changed.clone()));
let _app: Router = pages(Router::new())
.hypersig_runtime()
.with_state(AppState { db, changed });The page opens the stream with on_load(UPDATES.call().reconnect()), and the stream sends a patch that replaces titles once when it opens and again after each notification. A read that fails is logged and skipped, so the tab keeps the list it shows. A receiver of broadcast that falls behind the channel's 16 messages gets RecvError::Lagged, and the stream reads the list again then too. Streams covers the stream itself.
PgListener waits for notifications on the connection that sent LISTEN, so on PostgreSQL's side that connection has to stay with the listener too. A pooler in transaction mode hands its connection to PostgreSQL to another client after each transaction, and PgBouncer's feature table lists LISTEN as never supported in that mode, so a listener opened through one hears nothing. Where the pool connects through such a pooler, as on Vercel, open the listener with PgListener::connect and a connection string that reaches the database directly or through the pooler's session mode.
Redis's PUBLISH and SUBSCRIBE
Without PostgreSQL, a service that delivers each message to every subscriber can take its place. examples/redis keeps the todos in Redis, and each write is a Lua script that changes the keys and runs PUBLISH on one channel. Redis runs the script with no other command in between, so no write reaches the keys without telling the other processes. In each process a task spawned in main, as listen is above, subscribes with SUBSCRIBE and sends on changed for each message. The streams are the same code in both examples. Redis keeps no message for a subscriber that is not connected, so after the subscription breaks, the task subscribes again and sends on changed once more, and the streams read the list again.
database they check that each process serves what the other wrote, and for postgres and redis that an open tab of one process shows a write through the other without a reload. The postgres and redis tests run their database in Docker.Next
- A database without SQL keeps the client of DynamoDB in the state the same way.
- SQL the compiler checks turns a misspelled column into a compile error.
- Hosted PostgreSQL and MySQL lists the connection settings of Supabase, PlanetScale, Cloud SQL, and RDS.
- The database each host can reach covers SQLite in a container and the bindings of a Cloudflare Worker.