Auth, Limits, Jobs and Config
Auth
Keys:
cx.need_bearer("API_KEY")?: 401 unlessAuthorization: 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()isOption<(user, password)>. Alsowisp::secure_eq(a, b).
Sessions:
cx.sign_in(id)afterwisp::password::check(&typed, user_hash).await?(Nonefor no such user, as slow). Alsohash(&password).await?.cx.signed_in()?orcx.user()?where only members go (cx.login/signup: Auth and integrations). Signed out: 303 to/loginon 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 ofidon every device (saved tablewisp_sign_outs). A store failure is itsErr.
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 withcx.limit(&LOGINS)?, or useconst RATE_LIMIT.Backoffis 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_LIMITcaps bodies per route.
Live Updates
wisp::channel("notes").send(wisp::to_json(¬e)); // anywhere
// SSE
fn get() -> Response {
wisp::channel("notes").events()
}
// both ways
fn get() -> Response {
wisp::channel("chat").websocket()
}
subscribe()(recv().await) feeds your ownResponse::eventsorwebsocket.connect(&ws)joins an existing socket.- Channels are per process. To relay between servers (Redis pub/sub, Postgres
LISTEN), use a task started ininit.
Background Jobs
// src/hooks.rs
fn init() {
wisp::every(Duration::from_secs(3600), || async {
db::delete_expired_sessions().await;
});
}
everyruns until stop, never two at once. A panicking run is reported and the next starts on time.wisp::spawnruns 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/healthexists).
Configuration and Databases
wisp::env("KEY")reads the process env, else.envin 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), thenwisp::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 usespawn_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?