pavex_session/
incoming.rs

1use crate::{SessionId, State, config::SessionCookieConfig, wire::WireClientState};
2use pavex::{cookie::RequestCookies, methods};
3use pavex_tracing::fields::{ERROR_DETAILS, ERROR_MESSAGE, error_details, error_message};
4
5/// The session information attached to the incoming request.
6///
7/// Built using [`IncomingSession::extract`].
8pub struct IncomingSession {
9    pub(crate) id: SessionId,
10    pub(crate) client_state: State,
11}
12
13#[methods]
14impl IncomingSession {
15    /// Extract a session cookie from the incoming request, if it exists.
16    ///
17    /// If the cookie is not found, or if the cookie is invalid, this method will return `None`.
18    #[request_scoped]
19    pub fn extract(cookies: &RequestCookies<'_>, config: &SessionCookieConfig) -> Option<Self> {
20        let cookie = cookies.get(&config.name)?;
21        match serde_json::from_str::<WireClientState>(cookie.value()) {
22            Ok(s) => Some(Self {
23                id: s.session_id,
24                client_state: s.user_values.into_owned(),
25            }),
26            Err(e) => {
27                tracing::event!(
28                    tracing::Level::WARN,
29                    { ERROR_MESSAGE } = error_message(&e),
30                    { ERROR_DETAILS } = error_details(&e),
31                    "Invalid client state for session, creating a new session."
32                );
33                None
34            }
35        }
36    }
37
38    /// Build an [`IncomingSession`] instance from its parts.
39    pub fn from_parts(id: SessionId, state: State) -> Self {
40        Self {
41            id,
42            client_state: state,
43        }
44    }
45}