pub async fn session_layer(
pool: &AnyPool,
secure: bool,
) -> Result<SessionManagerLayer<SessionBackend>, AppError>Expand description
Builds the session layer for a Larust app, over pool (typically
larust_support::orm::pool()) - or, when Config::session_driver is
"file", over a directory instead, pool going unused for this call
entirely. Dispatches to whichever of AnySessionStore/
FileSessionStore is active (see this module’s own doc comment),
preparing it before returning: the database store’s idempotent
CREATE TABLE IF NOT EXISTS, or the file store’s create_dir_all -
no separate migration file needed in any app’s database/migrations/
either way.
Reads Config::session_driver/AppPaths through larust_core:: try_config()/try_paths(), not config()/paths() - the same
non-panicking fallback cookie_name already uses, and for the
identical reason: a handful of narrow test harnesses (see that
function’s own doc comment) build a session-bearing router directly off
a bare pool, with no Application::new() call anywhere in the test, so
nothing has ever published either singleton. Both fall back to
"database" behavior when unset - not "file" - so calling this the
way every existing test in this codebase already does (session_layer( &pool, secure), database-backed) keeps behaving identically whether or
not an Application happened to be constructed first.
secure controls the cookie’s Secure attribute (tower-sessions
defaults this to true). Browsers only treat loopback addresses and
the literal name localhost as secure contexts over plain HTTP - a
custom local dev hostname (e.g. a .test domain resolved via
/etc/hosts, even one that points at 127.0.0.1) is not on that list,
so a Secure cookie is silently dropped and sessions/CSRF stop working
with no error surfaced anywhere. Router::with_sessions(pool, secure)
is how callers set this - see Config::session_secure_cookie for the
SESSION_SECURE_COOKIE-env-driven value apps are expected to pass.
Also spawns a background task that periodically deletes expired
sessions (every EXPIRED_SESSION_CLEANUP_INTERVAL) - a persistent
store means expired sessions actually accumulate (rows or files) over
time, unlike an in-memory store where every session vanishes on its own
at the next restart regardless. This doesn’t affect expiry itself
(tower-sessions already treats an expired session as logged-out the
moment it’s read, with or without this task) - only how long stale
rows/files linger.