Skip to main content

Module async_state

Module async_state 

Source
Available on crate feature http2 only.
Expand description

Async-capable state-aware application — requires the http2 feature (tokio).

AsyncAppWithState<S> is the async counterpart to AppWithState<S>: handlers are async fn closures that can await database queries, HTTP clients, or any other async I/O without blocking the OS thread.

Where a handler runs:

  • The async servers (HTTP/1.1, HTTP/2, HTTP/3) await it through Application::execute_async when nothing synchronous wraps the app (every middleware layer is_passthrough): on the connection’s own runtime when that’s the shared multi_thread one, on the process-wide rws-async runtime under per-core (current_thread) runtimes.
  • Otherwise — a middleware layer in front, the HTTP/1.1-only build, TestClient::send, any direct Application::execute call — the calling thread waits while it runs on rws-async.

Either way the runtime outlives the request, so tasks a handler leaves behind run: a DbPool gets its connection back (sqlx returns it from a spawned task) instead of closing it. Handlers must not block their thread — they share worker threads with other requests.

Unmatched routes fall through to the built-in App controller chain, synchronously, without touching a runtime.

§Example

use std::sync::Arc;
use rust_web_server::async_state::AsyncAppWithState;
use rust_web_server::core::New;
use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
use rust_web_server::range::Range;
use rust_web_server::mime_type::MimeType;
use rust_web_server::router::PathParams;
use rust_web_server::request::Request;
use rust_web_server::server::ConnectionInfo;

struct AppState {
    greeting: String,
}

let app = AsyncAppWithState::new(AppState { greeting: "Hello".to_string() })
    .get("/greet/:name", |_req, params, _conn, state| async move {
        let name = params.get("name").unwrap_or("world");
        let body = format!("{}, {}!", state.greeting, name);
        let mut r = Response::new();
        r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
        r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
        r.content_range_list = vec![
            Range::get_content_range(body.into_bytes(), MimeType::TEXT_PLAIN.to_string())
        ];
        r
    });

Structs§

AsyncAppWithState
An Application whose route handlers are async functions.