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

Wisp

Testing and Mixing with Rust Code

In Process

wisp::prepare::<App>().await?;
let mut req = wisp::Request::new("GET", "/posts?page=2");
req.header("accept", "text/html");
let reply = wisp::handle::<App>(req).await; // reply.status, .headers (Vec<(name, value)>), .body (wisp::Body)

Same parser, limits, hooks and CSRF check as the server.

Your Own Listener

wisp::serve_on::<App>(listener) serves on a std::net::TcpListener you bound (port 0, a socket systemd handed over, or one shared with another server). It runs init first, errs if that fails, if the socket is unusable, or when the OS cannot start the clock thread (cannot start the clock thread: {e}), and runs until its future is dropped. wisp::serve::<App>(addr) binds for you. Both need your own tokio runtime and wisp::app!(); in place of wisp::main!();:

wisp::app!();

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
    wisp::serve_on::<App>(listener).await
}

Testing an App

Smaller tests (one component, a Cx by hand, a mocked API call), coverage and Playwright are on the Testing page. wisp::test::client needs no port and keeps cookies:

// tests/app.rs
wisp::app!();

#[test]
fn counter() {
    let mut app = wisp::test::client::<App>();
    assert!(app.get("/").text().contains("Clicked 0 times"));
    app.post_form("/?/increment", &[]);
    assert!(app.get("/").text().contains("Clicked 1 times"));
    assert!(app.cookie("user").is_none());
}
MethodWhat it does
get(path)GET
post_form(target, &[(name, value)])form POST with a browser's Host, Origin (the app's ORIGIN, else http://localhost) and Sec-Fetch-Site: same-origin
header(name, value)a header for the next request ("" leaves one out)
send(req)any request
next_chunk(&mut reply)next chunk of a stream
cookie(name)a stored cookie

More in OpenAPI and tests and wisp-ref/api.md. In process nothing upgrades, so Response::websocket is 501; test WebSockets against the running server (tests/app/tests/http.rs).

WebSockets

A +server.rs upgrades with Response::websocket. The connection closes when the handler returns.

// src/routes/ws/+server.rs
fn get() -> Response {
    Response::websocket(|ws| async move {
        while let Some(msg) = ws.recv().await {
            ws.send(msg).await?; // a String is text, a Vec<u8> binary
        }
        Ok(())
    })
}
  • ws.recv() is the next wisp::Message (Text or Binary, with msg.text() and msg.bytes()), or None once the client or server is gone. The server answers pings and joins fragments.
  • ws.send(msg) fails once the connection closes. recv and send can overlap (tokio::select!, or wisp::spawn a sender with ws.clone()). Dropping a send or recv after it wrote part of a frame ends the socket.
  • While recv waits, a client quiet for 30 s is pinged and closed (1001) after 60 s. WISP_WS_IDLE sets the 60 (0 means never). A send-only handler has no timeout. A message sent in pieces must make progress every 10 s and come whole at 1 KB/s after that, or the socket closes with 1008, whatever WISP_WS_IDLE is.
  • A message over the route's BODY_LIMIT (1 MB default) closes the connection with 1009.
  • A cross-site page gets 403 (Origin must name the host, or ORIGIN). A request that does not upgrade gets 426. before runs first.
  • Only the built-in server upgrades. tower, edge targets and the test client answer 501.

The tower Feature

Wisp becomes a tower::Service; the default build keeps its two deps.

wisp = { git = "https://wisp.ar0.eu/", features = ["tower"] }
let wisp = wisp::tower::service::<App>().await?; // Service<http::Request<B>>

axum answers its own routes and Wisp the rest (examples/axum):

wisp::app!();

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let listener = tokio::net::TcpListener::bind(wisp::address()).await?;
    let wisp = wisp::tower::service::<App>().await?;
    let app = axum::Router::new()
        .route("/api/hello", axum::routing::get(|| async { "hello from axum" }))
        .fallback_service(wisp);
    axum::serve(listener, app).await
}

Wrap it in a tower::ServiceBuilder for middleware such as tower_http::compression::CompressionLayer.

hyper:

let svc = hyper_util::service::TowerToHyperService::new(wisp::tower::service::<App>().await?);
hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new())
    .serve_connection(hyper_util::rt::TokioIo::new(stream), svc)
    .await?;

Lambda with a main of your own (--target lambda needs no code). Put WISP_SECRET in the function's environment:

wisp::app!();

#[tokio::main]
async fn main() -> Result<(), lambda_http::Error> {
    lambda_http::run(wisp::tower::service::<App>().await?).await
}

Axum Inside Wisp

Send paths to an axum Router from before (or a catch-all +server.rs). Some answers instead of the route; async fn before takes every route off the no-wait fast path.

// src/hooks.rs
async fn before(cx: &mut Cx) -> Result<Option<Response>> {
    if cx.path().starts_with("/api") {
        let mut api = api_router(); // an axum::Router
        return Ok(Some(wisp::tower::call(&mut api, cx).await?));
    }
    Ok(None)
}

Is This Page Useful?

View This Page's Source

Type to search every docs page and heading.