Sessions with tower-sessions
Server-side sessions from tower-sessions, read in a handler as Ext<Session> through an adopt entry.
A cookie-keyed server-side session store for HTTP routes. SessionManagerLayer loads the session for each request and puts a Session in the request's extensions. .adopt::<Session>() copies it into the execution, where a handler, guard or execution-scoped service reads it as Ext<Session>.
The recipe builds on examples/17-http-pre-dispatch. It compiled and ran on port 0 against tower-sessions 0.15.0 with its in-memory store, and tower 0.5.3.
tower-sessions = "0.15"The code
use tower_sessions::{MemoryStore, Session, SessionManagerLayer};
use ulo::{App, AppBuilder, BoxError, Ext, Module, ModuleDef, ModuleIdentity, controller, handlers, module};
use ulo_http::PreDispatch;
pub struct SessionModule;
impl Module for SessionModule {
fn identity(&self) -> ModuleIdentity {
ModuleIdentity::of_type::<Self>()
}
fn register(&self, m: &mut ModuleDef<'_>) {
m.meta::<PreDispatch>()
.layer(SessionManagerLayer::new(MemoryStore::default()).with_secure(false))
.adopt::<Session>();
}
}
#[controller]
pub struct VisitsController;
#[handlers]
impl VisitsController {
#[ulo_http::get("/visits")]
async fn visits(&self, session: Ext<Session>) -> Result<String, BoxError> {
let seen: u32 = session.get("visits").await?.unwrap_or(0) + 1;
session.insert("visits", seen).await?;
Ok(format!("visit {seen}"))
}
}
#[module(imports = [SessionModule], controllers = [VisitsController])]
pub struct AppModule;
pub fn builder() -> AppBuilder {
App::builder(AppModule)
}What each seam does
SessionManagerLayer::new(store) is a tower::Layer. It reads the session id cookie, loads the session from store, makes a Session handle available to inner services and writes the cookie back on the way out. with_secure(false) allows the cookie over plain HTTP for local use. The default is true, and the cookie carries HttpOnly and SameSite=Strict by default (read in the source; the observed cookie has both).
.adopt::<Session>() is an entry written after the layer, at its place in declaration order. It copies the Session the layer put into the request's http::Extensions into the execution. Session is Clone and cheap to clone, which adopt requires.
Observed with curl -c jar -b jar against GET /visits:
| Request | Answer |
|---|---|
| first, no cookie | 200 visit 1, set-cookie: id=Zlehde6fB7co0ggH0Cw58w; HttpOnly; SameSite=Strict; Path=/ |
| second, with the cookie | 200 visit 2, the same cookie value |
| third, with the cookie | 200 visit 3 |
| no cookie again | 200 visit 1, a different id |
Failure modes
Omitting .adopt::<Session>() fails per request, not at startup. With the entry removed, every GET /visits answered 500 with internal error: the Ext<Session> lookup finds nothing in the execution, which is LookupError::NotFound. The server started and bound normally. A handler that reads the session as Host<Session> reads the request's extensions directly (from the Host documentation, not run).
The in-memory store forgets on restart and is per process. MemoryStore is for development and tests, and a second instance behind a balancer does not share it. Other stores implement the SessionStore trait and plug into SessionManagerLayer::new unchanged (read in the tower-sessions source, not run).
Session methods are async and fallible. get and insert return Result, so the handler returns Result<_, BoxError> and ? carries a store failure to the error chain.
The cookie is set on every response. The observed replies each carried set-cookie, including the ones that renewed an existing session.
A session is not a login. The recipe stores a counter. Authentication belongs in a guard that reads Ext<Session>, which is what adopt makes possible.
Reference
- Middleware:
layer,adoptandHost<T>. - Core types:
Ext<T>and the execution's extensions. - Guards: where a session check belongs.