Wisp is in pre-release, self-hosted since GitHub suspended us. Install it, or see the changelog.

Wisp

Auth, Limits, Jobs and Config

Auth

Keys:

  • cx.need_bearer("API_KEY")?: 401 unless Authorization: Bearer <API_KEY's value> (constant time, an unset key matches nothing).
  • cx.writes() is true for POST/PUT/PATCH/DELETE. cx.bearer() is the token. cx.basic_auth() is Option<(user, password)>. Also wisp::secure_eq(a, b).

Sessions:

  • cx.sign_in(id) after wisp::password::check(&typed, user_hash).await? (None for no such user, as slow). Also hash(&password).await?.
  • cx.signed_in()? or cx.user()? where only members go (cx.login/signup: Auth and integrations). Signed out: 303 to /login on a page (wisp::sign_in_page("/x")), 401 (signed_out) for an endpoint or JSON client.
  • cx.sign_out() ends it here. The id stays in a signed cookie for 30 days.
  • wisp::sign_out_everywhere(id)? ends all earlier sessions of id on every device (saved table wisp_sign_outs). A store failure is its Err.

Put guards in before (hooks.rs: every route. +server.rs: each handler). Give data to the route with cx.set:

fn before(cx: &mut Cx) -> Result<()> {
    if cx.path().starts_with("/api/admin/") {
        let user = users::by_token(cx.bearer().unwrap_or("")).or_status(401)?;
        if !user.admin {
            return error(403, "Admins only");
        }
        cx.set(user); // a route reads it with cx.get::<User>()
    }
    Ok(())
}

Rate Limits

static LOGINS: RateLimit = RateLimit::per_minute(10);

fn post(cx: &mut Cx, name: String, password: String) -> Result<()> {
    LOGINS.check(cx.client_ip())?; // 429 + retry-after once the ten are used
    ...
}
  • A key is anything hashable (IP, API key, user id). It can spend all its uses at once, then refills steadily.
  • Behind a proxy, set WISP_CLIENT_IP_HEADER.
  • Behind Tor every client has one address: key by cx.visitor() and count with cx.limit(&LOGINS)?, or use const RATE_LIMIT. Backoff is a lockout that lengthens (Auth).
  • A 429 from a form action shows the form again with what was typed and the wait in words on a native build.
  • BODY_LIMIT caps bodies per route.

Live Updates

wisp::channel("notes").send(wisp::to_json(&note)); // anywhere

// SSE
fn get() -> Response {
    wisp::channel("notes").events()
}
// both ways
fn get() -> Response {
    wisp::channel("chat").websocket()
}
  • subscribe() (recv().await) feeds your own Response::events or websocket. connect(&ws) joins an existing socket.
  • Channels are per process. To relay between servers (Redis pub/sub, Postgres LISTEN), use a task started in init.

Background Jobs

// src/hooks.rs
fn init() {
    wisp::every(Duration::from_secs(3600), || async {
        db::delete_expired_sessions().await;
    });
}
  • every runs until stop, never two at once. A panicking run is reported and the next starts on time.
  • wisp::spawn runs one task. Outside a tokio runtime it logs a line and does not run the task. Durable queues, cron: Data, files and jobs.
  • A health check is a route: fn get() -> &'static str { "ok" } (/_wisp/health exists).

Configuration and Databases

  • wisp::env("KEY") reads the process env, else .env in the working directory, once at start. The process env wins. On the edge it reads the worker's env.
  • wisp::env_or("WORKERS", 4) parses with a default.
  • Read settings once in init: wisp::provide(v), then wisp::state::<T>()? (a logged 500 if none was provided) (or #[derive(Config)], wisp-ref/hooks.md).

Wisp has no database layer. Open the database in init, provide it, read it with state.

wisp::provide(sqlx::PgPool::connect(&url).await?) // in `async fn init`
wisp::state::<sqlx::PgPool>()? // in a handler

For Postgres, open one connection per worker instead of sharing a pool: no request waits on another thread. Each worker is a current-thread runtime, so a connection opened in a handler (in a thread_local, its I/O task started with wisp::spawn) stays on that worker, and the requests on it share it, pipelined. Example: bench/tfb/db/wisp/src/pg.rs. Reopen it when is_closed(). Use a pool for transactions.

  • rusqlite is sync: provide a Mutex<Connection>, hold the lock briefly, or use spawn_blocking.
  • redis: provide(redis::Client::open(url)?).
  • These need tokio (binary, Docker, Lambda), not the edge. On the edge, use HTTP databases through wisp::edge::fetch.

Is This Page Useful?

View This Page's Source

Type to search every docs page and heading.