hyperlane_plugin_session/struct.rs
1use super::*;
2
3/// Configuration controlling cookie attributes, signing, TTL, and capacity for [`SessionPlugin`].
4#[derive(Clone, Data, Debug, Eq, PartialEq)]
5pub struct SessionConfig {
6 /// Cookie name carrying the session token (default `"hyperlane_sid"`).
7 pub(crate) cookie_name: String,
8 /// Cookie `Path` attribute (default `"/"`).
9 pub(crate) cookie_path: String,
10 /// Optional cookie `Domain` attribute.
11 #[get(type(clone))]
12 pub(crate) cookie_domain: Option<String>,
13 /// Cookie `SameSite` policy (`"Lax"`, `"Strict"`, `"None"`).
14 pub(crate) same_site: String,
15 /// Sets `HttpOnly` flag on session cookies when `true`.
16 #[get(type(copy))]
17 pub(crate) http_only: bool,
18 /// Sets `Secure` flag on session cookies when `true`.
19 #[get(type(copy))]
20 pub(crate) secure: bool,
21 /// Session idle TTL in seconds (also emitted as cookie `Max-Age`).
22 #[get(type(copy))]
23 pub(crate) ttl_secs: u64,
24 /// Maximum active sessions allowed in the built-in [`InMemorySessionStore`].
25 #[get(type(copy))]
26 pub(crate) max_sessions: usize,
27 /// Optional HMAC-SHA256 secret signing cookie values (`<sid>.<mac>`).
28 #[get(type(clone))]
29 pub(crate) signing_secret: Option<Vec<u8>>,
30}
31
32/// Mutable per-request session state tracking dirty writes, regeneration, and destruction.
33#[derive(Clone, Debug)]
34pub(crate) struct SessionState {
35 /// Current session identifier.
36 pub(crate) id: String,
37 /// Previous session identifier deleted from the store after [`SessionHandle::regenerate_id`].
38 pub(crate) previous_id: Option<String>,
39 /// Shared copy-on-write key-value session attributes.
40 pub(crate) values: Arc<HashMap<String, String>>,
41 /// `true` when loaded from an existing persisted session.
42 pub(crate) existed: bool,
43 /// `true` when modified during this request (drives zero-write read optimization).
44 pub(crate) dirty: bool,
45 /// `true` when [`SessionHandle::destroy`] was called.
46 pub(crate) destroyed: bool,
47}
48
49/// Precomputed SHA-256 ipad and opad midstates for zero-allocation session cookie HMAC.
50#[derive(Clone, Copy, Debug, Eq, PartialEq)]
51pub(crate) struct HmacSha256Key {
52 /// SHA-256 state after compressing the 64-byte `key ^ 0x36` inner pad block.
53 pub(crate) ipad_state: [u32; 8],
54 /// SHA-256 state after compressing the 64-byte `key ^ 0x5c` outer pad block.
55 pub(crate) opad_state: [u32; 8],
56}
57
58/// Shared per-request session handle interior combining a lock-free dirty flag and mutex-protected state.
59#[derive(Debug)]
60pub(crate) struct SessionHandleInner {
61 /// Lock-free dirty flag enabling zero-lock zero-clone read-only response persistence checks.
62 pub(crate) dirty: AtomicBool,
63 /// Protected per-request session state.
64 pub(crate) state: Mutex<SessionState>,
65}
66
67/// Thread-safe handle stored in Hyperlane [`Context`] allowing handlers to read and mutate the active session.
68#[derive(Clone, Debug)]
69pub struct SessionHandle {
70 /// Shared per-request handle state.
71 pub(crate) inner: Arc<SessionHandleInner>,
72}
73
74/// Internal record stored inside each shard of [`InMemorySessionStore`].
75#[derive(Clone)]
76pub(crate) struct StoredSession {
77 /// Shared immutable snapshot of persisted key-value pairs for zero-clone reads.
78 pub(crate) values: Arc<HashMap<String, String>>,
79 /// Expiration Unix timestamp in seconds.
80 pub(crate) expires_at_secs: u64,
81}
82
83/// Shared interior state of [`InMemorySessionStore`].
84pub(crate) struct InMemorySessionStoreInner {
85 /// Maximum tracked concurrent sessions across all shards.
86 pub(crate) max_sessions: usize,
87 /// Lock-free active session counter.
88 pub(crate) count: AtomicUsize,
89 /// 64-way lock-striped session tables.
90 pub(crate) shards: SessionShardArray,
91}
92
93/// High-concurrency 64-way sharded bounded in-memory [`SessionStore`].
94#[derive(Clone)]
95pub struct InMemorySessionStore {
96 /// Shared sharded store state.
97 pub(crate) inner: Arc<InMemorySessionStoreInner>,
98}
99
100/// Precompiled cookie template and HMAC key states derived once from [`SessionConfig`].
101#[derive(Clone, Debug)]
102pub(crate) struct SessionCompiled {
103 /// Precomputed HMAC-SHA256 midstates when signing is enabled.
104 pub(crate) hmac_key: Option<HmacSha256Key>,
105 /// Preformatted `"<cookie_name>="` prefix.
106 pub(crate) cookie_prefix: String,
107 /// Preformatted `"; Max-Age=...; Path=...; ..."` suffix matching `CookieBuilder::build`.
108 pub(crate) cookie_suffix: String,
109 /// Preformatted expiration `Set-Cookie` header string for cleared sessions.
110 pub(crate) clear_cookie: String,
111 /// Whether `CookieBuilder::try_build` accepted the configured name and attributes.
112 pub(crate) valid_cookie_config: bool,
113}
114
115/// Process-wide [`SessionPlugin`] singleton storing [`SessionConfig`] and a pluggable [`SessionStore`].
116#[derive(Clone)]
117pub struct SessionPlugin {
118 /// Cookie, signing, and TTL configuration.
119 pub(crate) config: SessionConfig,
120 /// Backing session store.
121 pub(crate) store: SharedSessionStore,
122 /// Precompiled HMAC key and `Set-Cookie` templates.
123 pub(crate) compiled: Arc<SessionCompiled>,
124 /// Optional direct handle to the built-in [`InMemorySessionStore`] bypassing boxed async futures.
125 pub(crate) fast_store: Option<InMemorySessionStore>,
126}
127
128/// Opt-in request middleware loading the incoming session cookie into [`SessionHandle`].
129#[derive(Clone, Copy, Debug, Default)]
130#[hyperlane::request_middleware(-85)]
131pub struct SessionRequestHook;
132
133/// Opt-in response middleware persisting modified/regenerated/destroyed sessions and emitting `Set-Cookie`.
134#[derive(Clone, Copy, Debug, Default)]
135#[hyperlane::response_middleware(-70)]
136pub struct SessionResponseHook;