Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Zero-cost, compile-time app state #951

Open
musjj opened this issue Jan 21, 2025 · 0 comments
Open

Zero-cost, compile-time app state #951

musjj opened this issue Jan 21, 2025 · 0 comments
Labels
enhancement New feature or request

Comments

@musjj
Copy link

musjj commented Jan 21, 2025

Description of the feature

axum has an extractor called State. This is similar to poem's Data, but the difference is that axum's State is zero-cost and verified on compile-time. So it's impossible to compile handlers that requests a certain state, without providing that state during registration.

poem currently relies on http's Extensions for storing state, which is a hashmap. This means that your app can error on run-time when you forget to inject the data. This also incurs a performance cost because you need to perform a hashmap lookup on every request (probably negligible, but still).

Code example (if possible)

We can have a new State extractor as an alternative to Data:

use poem::{get, handler, listener::TcpListener, Route, Server, State};

struct AppState {}

#[handler]
fn use_state(state: State<AppState>) -> String {
    todo!()
}

#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
    if std::env::var_os("RUST_LOG").is_none() {
        std::env::set_var("RUST_LOG", "poem=debug");
    }
    tracing_subscriber::fmt::init();

    let state = AppState {};

    let app = Route::new()
        .at("/use-state", get(use_state))
        .with_state(state); // comment out this line to trigger a compile-time error

    Server::new(TcpListener::bind("0.0.0.0:3000"))
        .name("app-state")
        .run(app)
        .await
}
@musjj musjj added the enhancement New feature or request label Jan 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant