Skip to main content

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/// Thread-safe handle stored in Hyperlane [`Context`] allowing handlers to read and mutate the active session.
33#[derive(Clone, Debug)]
34pub struct SessionHandle {
35    /// Shared per-request handle state.
36    pub(crate) inner: Arc<SessionHandleInner>,
37}
38
39/// High-concurrency 64-way sharded bounded in-memory [`SessionStore`].
40#[derive(Clone)]
41pub struct InMemorySessionStore {
42    /// Shared sharded store state.
43    pub(crate) inner: Arc<InMemorySessionStoreInner>,
44}
45
46/// Process-wide [`SessionPlugin`] singleton storing [`SessionConfig`] and a pluggable [`SessionStore`].
47#[derive(Clone)]
48pub struct SessionPlugin {
49    /// Cookie, signing, and TTL configuration.
50    pub(crate) config: SessionConfig,
51    /// Backing session store.
52    pub(crate) store: Arc<dyn SessionStore>,
53    /// Precompiled HMAC key and `Set-Cookie` templates.
54    pub(crate) compiled: Arc<SessionCompiled>,
55    /// Optional direct handle to the built-in [`InMemorySessionStore`] bypassing boxed async futures.
56    pub(crate) fast_store: Option<InMemorySessionStore>,
57}
58
59/// Opt-in request middleware loading the incoming session cookie into [`SessionHandle`].
60#[derive(Clone, Copy, Debug, Default)]
61#[hyperlane::request_middleware(-85)]
62pub struct SessionRequestHook;
63
64/// Opt-in response middleware persisting modified/regenerated/destroyed sessions and emitting `Set-Cookie`.
65#[derive(Clone, Copy, Debug, Default)]
66#[hyperlane::response_middleware(-70)]
67pub struct SessionResponseHook;
68
69/// Fast zero-allocation 8-byte-word FxHash hasher for internal session shard maps.
70#[derive(Default)]
71pub(crate) struct SessionFxHasher {
72    /// Running 64-bit hash state.
73    pub(crate) hash: u64,
74}
75
76/// Zero-size [`BuildHasher`] producing [`SessionFxHasher`] instances.
77#[derive(Clone, Copy, Default)]
78pub(crate) struct SessionFxBuildHasher;
79
80/// Cache-line-aligned session shard preventing false sharing between concurrent readers and writers.
81#[repr(align(64))]
82pub(crate) struct SessionShard {
83    /// Lock-protected map of session IDs to stored snapshots.
84    pub(crate) map: RwLock<SessionFxHashMap<String, StoredSession>>,
85}
86
87/// Mutable per-request session state tracking dirty writes, regeneration, and destruction.
88#[derive(Clone, Debug)]
89pub(crate) struct SessionState {
90    /// Current session identifier.
91    pub(crate) id: String,
92    /// Previous session identifier deleted from the store after [`SessionHandle::regenerate_id`].
93    pub(crate) previous_id: Option<String>,
94    /// Shared copy-on-write key-value session attributes.
95    pub(crate) values: Arc<HashMap<String, String>>,
96    /// `true` when loaded from an existing persisted session.
97    pub(crate) existed: bool,
98    /// `true` when modified during this request (drives zero-write read optimization).
99    pub(crate) dirty: bool,
100    /// `true` when [`SessionHandle::destroy`] was called.
101    pub(crate) destroyed: bool,
102}
103
104/// Precomputed SHA-256 ipad and opad midstates for zero-allocation session cookie HMAC.
105#[derive(Clone, Copy, Debug, Eq, PartialEq)]
106pub(crate) struct HmacSha256Key {
107    /// SHA-256 state after compressing the 64-byte `key ^ 0x36` inner pad block.
108    pub(crate) ipad_state: [u32; 8],
109    /// SHA-256 state after compressing the 64-byte `key ^ 0x5c` outer pad block.
110    pub(crate) opad_state: [u32; 8],
111}
112
113/// Shared per-request session handle interior combining a lock-free dirty flag and mutex-protected state.
114#[derive(Debug)]
115pub(crate) struct SessionHandleInner {
116    /// Lock-free dirty flag enabling zero-lock zero-clone read-only response persistence checks.
117    pub(crate) dirty: AtomicBool,
118    /// Protected per-request session state.
119    pub(crate) state: Mutex<SessionState>,
120}
121
122/// Internal record stored inside each shard of [`InMemorySessionStore`].
123#[derive(Clone)]
124pub(crate) struct StoredSession {
125    /// Shared immutable snapshot of persisted key-value pairs for zero-clone reads.
126    pub(crate) values: Arc<HashMap<String, String>>,
127    /// Expiration Unix timestamp in seconds.
128    pub(crate) expires_at_secs: u64,
129}
130
131/// Shared interior state of [`InMemorySessionStore`].
132pub(crate) struct InMemorySessionStoreInner {
133    /// Maximum tracked concurrent sessions across all shards.
134    pub(crate) max_sessions: usize,
135    /// Lock-free active session counter.
136    pub(crate) count: AtomicUsize,
137    /// 64-way cache-aligned lock-striped session tables.
138    pub(crate) shards: Box<[SessionShard; SESSION_SHARD_COUNT]>,
139}
140
141/// Precompiled cookie template and HMAC key states derived once from [`SessionConfig`].
142#[derive(Clone, Debug)]
143pub(crate) struct SessionCompiled {
144    /// Precomputed HMAC-SHA256 midstates when signing is enabled.
145    pub(crate) hmac_key: Option<HmacSha256Key>,
146    /// Preformatted `"<cookie_name>="` prefix.
147    pub(crate) cookie_prefix: String,
148    /// Preformatted `"; Max-Age=...; Path=...; ..."` suffix matching `CookieBuilder::build`.
149    pub(crate) cookie_suffix: String,
150    /// Preformatted expiration `Set-Cookie` header string for cleared sessions.
151    pub(crate) clear_cookie: String,
152    /// Whether `CookieBuilder::try_build` accepted the configured name and attributes.
153    pub(crate) valid_cookie_config: bool,
154    /// Whether the configured cookie name is a valid RFC 6265 token.
155    pub(crate) valid_cookie_name: bool,
156}