1use super::*;
2
3impl Hasher for SessionFxHasher {
5 #[inline(always)]
11 fn finish(&self) -> u64 {
12 let Self { hash } = self;
13 *hash
14 }
15
16 #[inline(always)]
22 fn write(&mut self, bytes: &[u8]) {
23 let Self { hash } = self;
24 let word: u64 = fx_hash_bytes(bytes);
25 *hash = (hash.rotate_left(5) ^ word).wrapping_mul(FX_HASH_K);
26 }
27
28 #[inline(always)]
34 fn write_usize(&mut self, i: usize) {
35 let Self { hash } = self;
36 *hash = (hash.rotate_left(5) ^ (i as u64)).wrapping_mul(FX_HASH_K);
37 }
38}
39
40impl BuildHasher for SessionFxBuildHasher {
42 type Hasher = SessionFxHasher;
43
44 #[inline(always)]
50 fn build_hasher(&self) -> Self::Hasher {
51 SessionFxHasher { hash: 0 }
52 }
53}
54
55impl Default for SessionConfig {
57 fn default() -> Self {
59 Self {
60 cookie_name: DEFAULT_SESSION_COOKIE_NAME.to_owned(),
61 cookie_path: DEFAULT_SESSION_COOKIE_PATH.to_owned(),
62 cookie_domain: None,
63 same_site: DEFAULT_SESSION_SAME_SITE.to_owned(),
64 http_only: true,
65 secure: true,
66 ttl_secs: DEFAULT_SESSION_TTL_SECS,
67 max_sessions: DEFAULT_MAX_SESSIONS,
68 signing_secret: None,
69 }
70 }
71}
72
73impl SessionConfig {
75 pub fn with_cookie_name<N>(mut self, name: N) -> Self
85 where
86 N: Into<String>,
87 {
88 self.set_cookie_name(name.into());
89 self
90 }
91
92 pub fn with_signing_secret<S>(mut self, secret: S) -> Self
102 where
103 S: Into<Vec<u8>>,
104 {
105 self.set_signing_secret(Some(secret.into()));
106 self
107 }
108
109 pub fn with_ttl_secs(mut self, ttl_secs: u64) -> Self {
119 self.set_ttl_secs(ttl_secs);
120 self
121 }
122
123 pub fn with_secure(mut self, secure: bool) -> Self {
133 self.set_secure(secure);
134 self
135 }
136}
137
138impl SessionHandle {
140 pub(crate) fn new(id: String, values: Arc<HashMap<String, String>>, existed: bool) -> Self {
152 Self {
153 inner: Arc::new(SessionHandleInner {
154 dirty: AtomicBool::new(false),
155 state: Mutex::new(SessionState {
156 id,
157 previous_id: None,
158 values,
159 existed,
160 dirty: false,
161 destroyed: false,
162 }),
163 }),
164 }
165 }
166
167 pub fn id(&self) -> String {
173 let Self { inner } = self;
174 inner
175 .state
176 .lock()
177 .map(|guard: MutexGuard<'_, SessionState>| guard.id.clone())
178 .unwrap_or_default()
179 }
180
181 pub fn get(&self, key: &str) -> Option<String> {
191 let Self { inner } = self;
192 inner
193 .state
194 .lock()
195 .ok()
196 .and_then(|guard: MutexGuard<'_, SessionState>| guard.values.get(key).cloned())
197 }
198
199 pub fn insert<K, V>(&self, key: K, value: V)
206 where
207 K: Into<String>,
208 V: Into<String>,
209 {
210 let Self { inner } = self;
211 if let Ok(mut guard) = inner.state.lock() {
212 Arc::make_mut(&mut guard.values).insert(key.into(), value.into());
213 guard.dirty = true;
214 guard.destroyed = false;
215 inner.dirty.store(true, Ordering::Release);
216 }
217 }
218
219 pub fn remove(&self, key: &str) -> Option<String> {
229 let Self { inner } = self;
230 let mut guard: MutexGuard<'_, SessionState> = inner.state.lock().ok()?;
231 if !guard.values.contains_key(key) {
232 return None;
233 }
234 let removed: Option<String> = Arc::make_mut(&mut guard.values).remove(key);
235 if removed.is_some() {
236 guard.dirty = true;
237 inner.dirty.store(true, Ordering::Release);
238 }
239 removed
240 }
241
242 pub fn regenerate_id(&self) -> String {
248 let Self { inner } = self;
249 let next_id: String = generate_session_id();
250 if let Ok(mut guard) = inner.state.lock() {
251 if guard.previous_id.is_none() && guard.existed {
252 guard.previous_id = Some(guard.id.clone());
253 }
254 guard.id = next_id.clone();
255 guard.dirty = true;
256 guard.destroyed = false;
257 inner.dirty.store(true, Ordering::Release);
258 }
259 next_id
260 }
261
262 pub fn destroy(&self) {
264 let Self { inner } = self;
265 if let Ok(mut guard) = inner.state.lock() {
266 guard.values = Arc::clone(empty_session_values());
267 guard.destroyed = true;
268 guard.dirty = true;
269 inner.dirty.store(true, Ordering::Release);
270 }
271 }
272
273 #[inline]
279 pub fn is_dirty(&self) -> bool {
280 let Self { inner } = self;
281 inner.dirty.load(Ordering::Acquire)
282 }
283
284 #[inline]
290 pub(crate) fn snapshot_if_dirty(&self) -> Option<SessionState> {
291 let Self { inner } = self;
292 if !inner.dirty.load(Ordering::Acquire) {
293 return None;
294 }
295 inner
296 .state
297 .lock()
298 .ok()
299 .and_then(|guard: MutexGuard<'_, SessionState>| {
300 if guard.dirty {
301 Some(guard.clone())
302 } else {
303 None
304 }
305 })
306 }
307}
308
309impl Default for InMemorySessionStore {
311 fn default() -> Self {
313 Self::new(DEFAULT_MAX_SESSIONS)
314 }
315}
316
317impl InMemorySessionStore {
319 pub fn new(max_sessions: usize) -> Self {
329 let shards: Box<[SessionShard; SESSION_SHARD_COUNT]> =
330 Box::new(from_fn(|_: usize| SessionShard {
331 map: RwLock::new(HashMap::with_hasher(SessionFxBuildHasher)),
332 }));
333 Self {
334 inner: Arc::new(InMemorySessionStoreInner {
335 max_sessions: max_sessions.max(1),
336 count: AtomicUsize::new(0),
337 shards,
338 }),
339 }
340 }
341
342 #[inline]
348 pub fn len(&self) -> usize {
349 let Self { inner } = self;
350 inner.count.load(Ordering::Relaxed)
351 }
352
353 #[inline]
359 pub fn is_empty(&self) -> bool {
360 self.len() == 0
361 }
362
363 #[inline]
373 pub(crate) fn load_sync_shared(
374 &self,
375 session_id: &str,
376 ) -> Option<Arc<HashMap<String, String>>> {
377 let Self { inner } = self;
378 let idx: usize = session_shard_index(session_id);
379 let mut expired: bool = false;
380 if let Ok(map) = inner.shards[idx].map.read() {
381 let entry: &StoredSession = map.get(session_id)?;
382 let now: u64 = session_now_secs();
383 if now < entry.expires_at_secs {
384 return Some(Arc::clone(&entry.values));
385 }
386 expired = true;
387 }
388 if expired
389 && let Ok(mut map) = inner.shards[idx].map.write()
390 && map.remove(session_id).is_some()
391 {
392 inner.count.fetch_sub(1, Ordering::Relaxed);
393 }
394 None
395 }
396
397 #[inline]
405 pub(crate) fn save_sync_shared(
406 &self,
407 session_id: &str,
408 values: Arc<HashMap<String, String>>,
409 ttl_secs: u64,
410 ) {
411 let Self { inner } = self;
412 let now: u64 = session_now_secs();
413 if inner.count.load(Ordering::Relaxed) >= inner.max_sessions {
414 let _: usize = self.purge_expired();
415 }
416 let idx: usize = session_shard_index(session_id);
417 let expires_at_secs: u64 = now.saturating_add(ttl_secs.max(1));
418 if let Ok(mut map) = inner.shards[idx].map.write() {
419 if let Some(existing) = map.get_mut(session_id) {
420 existing.values = values;
421 existing.expires_at_secs = expires_at_secs;
422 } else if inner.count.load(Ordering::Relaxed) < inner.max_sessions {
423 map.insert(
424 session_id.to_owned(),
425 StoredSession {
426 values,
427 expires_at_secs,
428 },
429 );
430 inner.count.fetch_add(1, Ordering::Relaxed);
431 }
432 }
433 }
434
435 #[inline]
443 pub(crate) fn save_sync_owned(
444 &self,
445 session_id: String,
446 values: Arc<HashMap<String, String>>,
447 ttl_secs: u64,
448 ) {
449 let Self { inner } = self;
450 let now: u64 = session_now_secs();
451 if inner.count.load(Ordering::Relaxed) >= inner.max_sessions {
452 let _: usize = self.purge_expired();
453 }
454 let idx: usize = session_shard_index(&session_id);
455 let expires_at_secs: u64 = now.saturating_add(ttl_secs.max(1));
456 if let Ok(mut map) = inner.shards[idx].map.write() {
457 match map.entry(session_id) {
458 Entry::Occupied(mut occupied) => {
459 occupied.insert(StoredSession {
460 values,
461 expires_at_secs,
462 });
463 }
464 Entry::Vacant(vacant) => {
465 if inner.count.load(Ordering::Relaxed) < inner.max_sessions {
466 vacant.insert(StoredSession {
467 values,
468 expires_at_secs,
469 });
470 inner.count.fetch_add(1, Ordering::Relaxed);
471 }
472 }
473 }
474 }
475 }
476
477 #[inline]
487 pub(crate) fn delete_sync(&self, session_id: &str) -> bool {
488 let Self { inner } = self;
489 let idx: usize = session_shard_index(session_id);
490 let removed: bool = inner.shards[idx]
491 .map
492 .write()
493 .ok()
494 .and_then(
495 |mut map: RwLockWriteGuard<'_, SessionFxHashMap<String, StoredSession>>| {
496 map.remove(session_id)
497 },
498 )
499 .is_some();
500 if removed {
501 inner.count.fetch_sub(1, Ordering::Relaxed);
502 }
503 removed
504 }
505}
506
507impl SessionStore for InMemorySessionStore {
509 fn load<'a>(
520 &'a self,
521 session_id: &'a str,
522 ) -> SessionFuture<'a, Option<HashMap<String, String>>> {
523 let outcome: Option<HashMap<String, String>> = self
524 .load_sync_shared(session_id)
525 .map(|values: Arc<HashMap<String, String>>| (*values).clone());
526 Box::pin(async move { outcome })
527 }
528
529 fn save(
541 &self,
542 session_id: String,
543 values: HashMap<String, String>,
544 ttl_secs: u64,
545 ) -> SessionFuture<'_, ()> {
546 self.save_sync_owned(session_id, Arc::new(values), ttl_secs);
547 Box::pin(async {})
548 }
549
550 fn delete<'a>(&'a self, session_id: &'a str) -> SessionFuture<'a, bool> {
561 let removed: bool = self.delete_sync(session_id);
562 Box::pin(async move { removed })
563 }
564
565 fn purge_expired(&self) -> usize {
571 let Self { inner } = self;
572 let now: u64 = session_now_secs();
573 let mut evicted: usize = 0;
574 for shard in inner.shards.iter() {
575 let non_empty: bool = shard
576 .map
577 .read()
578 .map(
579 |map: RwLockReadGuard<'_, SessionFxHashMap<String, StoredSession>>| {
580 !map.is_empty()
581 },
582 )
583 .unwrap_or(false);
584 if !non_empty {
585 continue;
586 }
587 if let Ok(mut map) = shard.map.write() {
588 let before: usize = map.len();
589 map.retain(|_: &String, entry: &mut StoredSession| now < entry.expires_at_secs);
590 evicted += before.saturating_sub(map.len());
591 }
592 }
593 if evicted > 0 {
594 inner.count.fetch_sub(evicted, Ordering::Relaxed);
595 }
596 evicted
597 }
598}
599
600impl SessionCompiled {
602 pub(crate) fn from_config(config: &SessionConfig) -> Self {
612 let valid_cookie_name: bool = is_valid_cookie_name(config.get_cookie_name());
613 let hmac_key: Option<HmacSha256Key> = config
614 .get_signing_secret()
615 .map(|secret: Vec<u8>| precompute_hmac_sha256_key(&secret));
616 let mut live_builder: CookieBuilder =
617 CookieBuilder::new(config.get_cookie_name(), COOKIE_TEMPLATE_VALUE);
618 live_builder
619 .set_path(config.get_cookie_path())
620 .set_same_site(config.get_same_site());
621 if let Some(domain) = config.get_cookie_domain() {
622 live_builder.set_domain(domain);
623 }
624 if config.get_http_only() {
625 live_builder.http_only();
626 }
627 if config.get_secure() {
628 live_builder.secure();
629 }
630 live_builder.set_max_age(config.get_ttl_secs() as i64);
631 let live_sample: String = live_builder.build();
632 let mut clear_builder: CookieBuilder = CookieBuilder::new(config.get_cookie_name(), "");
633 clear_builder
634 .set_path(config.get_cookie_path())
635 .set_same_site(config.get_same_site());
636 if let Some(domain) = config.get_cookie_domain() {
637 clear_builder.set_domain(domain);
638 }
639 if config.get_http_only() {
640 clear_builder.http_only();
641 }
642 if config.get_secure() {
643 clear_builder.secure();
644 }
645 clear_builder.set_max_age(0i64);
646 let clear_cookie: String = clear_builder.build();
647 let prefix_len: usize = config.get_cookie_name().len() + 1;
648 let sentinel_end: usize = prefix_len + COOKIE_TEMPLATE_VALUE.len();
649 if live_sample.len() >= sentinel_end {
650 Self {
651 hmac_key,
652 cookie_prefix: live_sample[..prefix_len].to_owned(),
653 cookie_suffix: live_sample[sentinel_end..].to_owned(),
654 clear_cookie,
655 valid_cookie_config: true,
656 valid_cookie_name,
657 }
658 } else {
659 Self {
660 hmac_key,
661 cookie_prefix: String::new(),
662 cookie_suffix: String::new(),
663 clear_cookie,
664 valid_cookie_config: false,
665 valid_cookie_name,
666 }
667 }
668 }
669}
670
671impl SessionPlugin {
673 pub(crate) fn from_parts(
685 config: SessionConfig,
686 store: Arc<dyn SessionStore>,
687 fast_store: Option<InMemorySessionStore>,
688 ) -> Self {
689 let compiled: Arc<SessionCompiled> = Arc::new(SessionCompiled::from_config(&config));
690 Self {
691 config,
692 store,
693 compiled,
694 fast_store,
695 }
696 }
697
698 pub fn init(config: SessionConfig) -> &'static Self {
708 let mem_store: InMemorySessionStore = InMemorySessionStore::new(config.get_max_sessions());
709 let store: Arc<dyn SessionStore> = Arc::new(mem_store.clone());
710 SESSION_PLUGIN.get_or_init(|| Self::from_parts(config, store, Some(mem_store)))
711 }
712
713 pub fn init_with_store(config: SessionConfig, store: Arc<dyn SessionStore>) -> &'static Self {
724 SESSION_PLUGIN.get_or_init(|| Self::from_parts(config, store, None))
725 }
726
727 pub fn get() -> Option<&'static Self> {
733 SESSION_PLUGIN.get()
734 }
735
736 pub fn get_config(&self) -> &SessionConfig {
742 &self.config
743 }
744
745 pub fn get_store(&self) -> &Arc<dyn SessionStore> {
751 &self.store
752 }
753
754 pub fn current(ctx: &Context) -> Option<SessionHandle> {
764 ctx.try_get_attribute(ATTR_SESSION_HANDLE)
765 }
766
767 #[inline]
778 fn format_live_set_cookie_stack<'a>(
779 &self,
780 session_id: &str,
781 buf: &'a mut [u8; SET_COOKIE_STACK_CAP],
782 ) -> Option<&'a str> {
783 let Self { compiled, .. } = self;
784 if !compiled.valid_cookie_config || !is_valid_set_cookie_value(session_id) {
785 return Some("");
786 }
787 let sig_extra: usize = if compiled.hmac_key.is_some() { 65 } else { 0 };
788 let total: usize = compiled.cookie_prefix.len()
789 + session_id.len()
790 + sig_extra
791 + compiled.cookie_suffix.len();
792 if total > SET_COOKIE_STACK_CAP {
793 return None;
794 }
795 let mut pos: usize = 0;
796 let prefix: &[u8] = compiled.cookie_prefix.as_bytes();
797 buf[pos..pos + prefix.len()].copy_from_slice(prefix);
798 pos += prefix.len();
799 let sid_bytes: &[u8] = session_id.as_bytes();
800 buf[pos..pos + sid_bytes.len()].copy_from_slice(sid_bytes);
801 pos += sid_bytes.len();
802 if let Some(key) = &compiled.hmac_key {
803 buf[pos] = BYTE_DOT;
804 pos += 1;
805 let mac: [u8; 32] = hmac_sha256_with_key(key, sid_bytes);
806 let hex: [u8; 64] = encode_hex_32_stack(&mac);
807 buf[pos..pos + hex.len()].copy_from_slice(&hex);
808 pos += hex.len();
809 }
810 let suffix: &[u8] = compiled.cookie_suffix.as_bytes();
811 buf[pos..pos + suffix.len()].copy_from_slice(suffix);
812 pos += suffix.len();
813 from_utf8(&buf[..pos]).ok()
814 }
815
816 #[inline]
827 pub fn build_set_cookie(&self, session_id: &str, clear: bool) -> String {
828 let Self { compiled, .. } = self;
829 if !compiled.valid_cookie_config {
830 return String::new();
831 }
832 if clear {
833 return compiled.clear_cookie.clone();
834 }
835 if !is_valid_set_cookie_value(session_id) {
836 return String::new();
837 }
838 let sig_extra: usize = if compiled.hmac_key.is_some() { 65 } else { 0 };
839 let total: usize = compiled.cookie_prefix.len()
840 + session_id.len()
841 + sig_extra
842 + compiled.cookie_suffix.len();
843 let mut out: String = String::with_capacity(total);
844 out.push_str(&compiled.cookie_prefix);
845 out.push_str(session_id);
846 if let Some(key) = &compiled.hmac_key {
847 let mac: [u8; 32] = hmac_sha256_with_key(key, session_id.as_bytes());
848 let hex: [u8; 64] = encode_hex_32_stack(&mac);
849 out.push(COOKIE_SIG_DELIMITER);
850 if let Ok(sig) = from_utf8(&hex) {
851 out.push_str(sig);
852 }
853 }
854 out.push_str(&compiled.cookie_suffix);
855 out
856 }
857
858 #[inline]
872 fn install_handle(
873 ctx: &mut Context,
874 sid: &str,
875 owned_sid: Option<String>,
876 values: Arc<HashMap<String, String>>,
877 existed: bool,
878 ) -> SessionHandle {
879 if let Some(slot) = ctx
880 .get_mut_attributes()
881 .get_mut(ATTR_SESSION_HANDLE_MAP_KEY)
882 {
883 if let Some(any_mut) = Arc::get_mut(slot)
884 && let Some(existing) = any_mut.downcast_mut::<SessionHandle>()
885 {
886 if let Some(inner_mut) = Arc::get_mut(&mut existing.inner)
887 && let Ok(state) = inner_mut.state.get_mut()
888 {
889 if let Some(id_owned) = owned_sid {
890 state.id = id_owned;
891 } else {
892 state.id.clear();
893 state.id.push_str(sid);
894 }
895 state.previous_id = None;
896 state.values = values;
897 state.existed = existed;
898 state.dirty = false;
899 state.destroyed = false;
900 *inner_mut.dirty.get_mut() = false;
901 return existing.clone();
902 }
903 let id_string: String = owned_sid.unwrap_or_else(|| sid.to_owned());
904 let handle: SessionHandle = SessionHandle::new(id_string, values, existed);
905 *existing = handle.clone();
906 return handle;
907 }
908 let id_string: String = owned_sid.unwrap_or_else(|| sid.to_owned());
909 let handle: SessionHandle = SessionHandle::new(id_string, values, existed);
910 *slot = Arc::new(handle.clone());
911 return handle;
912 }
913 let id_string: String = owned_sid.unwrap_or_else(|| sid.to_owned());
914 let handle: SessionHandle = SessionHandle::new(id_string, values, existed);
915 ctx.get_mut_attributes().insert(
916 ATTR_SESSION_HANDLE_MAP_KEY.to_owned(),
917 Arc::new(handle.clone()),
918 );
919 handle
920 }
921
922 pub async fn load_into_context(&self, ctx: &mut Context) -> SessionHandle {
932 let Self {
933 config,
934 store,
935 compiled,
936 fast_store,
937 } = self;
938 let mut sid_stack: [u8; SID_STACK_CAP] = [0u8; SID_STACK_CAP];
939 let mut sid_len: usize = 0;
940 let mut owned_sid: Option<String> = None;
941 let mut loaded_values: Option<Arc<HashMap<String, String>>> = None;
942 if let Some(raw_cookie) = ctx
943 .get_request()
944 .get_headers()
945 .get(COOKIE)
946 .and_then(|values: &VecDeque<String>| values.back())
947 .map(String::as_str)
948 && let Some(raw_val) = find_cookie_value_trusted(
949 raw_cookie,
950 config.get_cookie_name(),
951 compiled.valid_cookie_name,
952 )
953 {
954 let verified_sid: Option<&str> = match &compiled.hmac_key {
955 Some(key) => verify_session_cookie_with_key(raw_val, key),
956 None => {
957 if raw_val.is_empty() {
958 None
959 } else {
960 Some(raw_val)
961 }
962 }
963 };
964 if let Some(sid) = verified_sid {
965 let maybe_values: Option<Arc<HashMap<String, String>>> =
966 if let Some(mem_store) = fast_store {
967 mem_store.load_sync_shared(sid)
968 } else {
969 store.load(sid).await.map(Arc::new)
970 };
971 if let Some(values) = maybe_values {
972 let sid_bytes: &[u8] = sid.as_bytes();
973 if sid_bytes.len() <= SID_STACK_CAP {
974 sid_stack[..sid_bytes.len()].copy_from_slice(sid_bytes);
975 sid_len = sid_bytes.len();
976 } else {
977 owned_sid = Some(sid.to_owned());
978 }
979 loaded_values = Some(values);
980 }
981 }
982 }
983 if let Some(values) = loaded_values {
984 let sid_ref: &str = from_utf8(&sid_stack[..sid_len]).unwrap_or_default();
985 return Self::install_handle(ctx, sid_ref, owned_sid, values, true);
986 }
987 let fresh_id: [u8; 32] = generate_session_id_bytes();
988 let fresh_str: &str = from_utf8(&fresh_id).unwrap_or_default();
989 Self::install_handle(
990 ctx,
991 fresh_str,
992 None,
993 Arc::clone(empty_session_values()),
994 false,
995 )
996 }
997
998 pub async fn persist_from_context(&self, ctx: &mut Context) {
1004 let Self {
1005 config,
1006 store,
1007 compiled,
1008 fast_store,
1009 } = self;
1010 if let Some(mem_store) = fast_store {
1011 let mut cookie_buf: [u8; SET_COOKIE_STACK_CAP] = [0u8; SET_COOKIE_STACK_CAP];
1012 let mut cookie_len: Option<usize> = None;
1013 let mut cookie_fallback: Option<String> = None;
1014 let mut emit_clear: bool = false;
1015 {
1016 let Some(handle) = ctx
1017 .get_attributes()
1018 .get(ATTR_SESSION_HANDLE_MAP_KEY)
1019 .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<SessionHandle>())
1020 else {
1021 return;
1022 };
1023 if !handle.inner.dirty.load(Ordering::Acquire) {
1024 return;
1025 }
1026 let Ok(guard) = handle.inner.state.lock() else {
1027 return;
1028 };
1029 if !guard.dirty {
1030 return;
1031 }
1032 if let Some(old_id) = guard.previous_id.as_deref() {
1033 let _: bool = mem_store.delete_sync(old_id);
1034 }
1035 if guard.destroyed {
1036 let _: bool = mem_store.delete_sync(&guard.id);
1037 emit_clear = compiled.valid_cookie_config;
1038 } else {
1039 mem_store.save_sync_shared(
1040 &guard.id,
1041 Arc::clone(&guard.values),
1042 config.get_ttl_secs(),
1043 );
1044 if let Some(cookie_str) =
1045 self.format_live_set_cookie_stack(&guard.id, &mut cookie_buf)
1046 {
1047 cookie_len = Some(cookie_str.len());
1048 } else {
1049 cookie_fallback = Some(self.build_set_cookie(&guard.id, false));
1050 }
1051 }
1052 }
1053 if emit_clear {
1054 ctx.get_mut_response()
1055 .add_header(SET_COOKIE, &compiled.clear_cookie);
1056 } else if let Some(len) = cookie_len {
1057 if let Ok(cookie_str) = from_utf8(&cookie_buf[..len]) {
1058 ctx.get_mut_response().add_header(SET_COOKIE, cookie_str);
1059 }
1060 } else if let Some(set_cookie) = cookie_fallback {
1061 ctx.get_mut_response().add_header(SET_COOKIE, set_cookie);
1062 }
1063 return;
1064 }
1065 let Some(state) = ctx
1066 .get_attributes()
1067 .get(ATTR_SESSION_HANDLE_MAP_KEY)
1068 .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<SessionHandle>())
1069 .and_then(SessionHandle::snapshot_if_dirty)
1070 else {
1071 return;
1072 };
1073 if let Some(old_id) = state.previous_id {
1074 let _: bool = store.delete(&old_id).await;
1075 }
1076 if state.destroyed {
1077 let _: bool = store.delete(&state.id).await;
1078 if compiled.valid_cookie_config {
1079 ctx.get_mut_response()
1080 .add_header(SET_COOKIE, &compiled.clear_cookie);
1081 }
1082 return;
1083 }
1084 let mut cookie_buf: [u8; SET_COOKIE_STACK_CAP] = [0u8; SET_COOKIE_STACK_CAP];
1085 let stack_len: Option<usize> = self
1086 .format_live_set_cookie_stack(&state.id, &mut cookie_buf)
1087 .map(str::len);
1088 let fallback: Option<String> = if stack_len.is_none() {
1089 Some(self.build_set_cookie(&state.id, false))
1090 } else {
1091 None
1092 };
1093 let owned_values: HashMap<String, String> = Arc::try_unwrap(state.values)
1094 .unwrap_or_else(|shared: Arc<HashMap<String, String>>| (*shared).clone());
1095 store
1096 .save(state.id, owned_values, config.get_ttl_secs())
1097 .await;
1098 if let Some(len) = stack_len {
1099 if let Ok(cookie_str) = from_utf8(&cookie_buf[..len]) {
1100 ctx.get_mut_response().add_header(SET_COOKIE, cookie_str);
1101 }
1102 } else if let Some(set_cookie) = fallback {
1103 ctx.get_mut_response().add_header(SET_COOKIE, set_cookie);
1104 }
1105 }
1106}
1107
1108impl ServerHook for SessionRequestHook {
1110 async fn new(_: &mut Stream, _: &mut Context) -> Self {
1121 Self
1122 }
1123
1124 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
1136 let Some(plugin) = SessionPlugin::get() else {
1137 return Status::Continue;
1138 };
1139 let _: SessionHandle = plugin.load_into_context(ctx).await;
1140 Status::Continue
1141 }
1142}
1143
1144impl ServerHook for SessionResponseHook {
1146 async fn new(_: &mut Stream, _: &mut Context) -> Self {
1157 Self
1158 }
1159
1160 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
1172 let Some(plugin) = SessionPlugin::get() else {
1173 return Status::Continue;
1174 };
1175 plugin.persist_from_context(ctx).await;
1176 Status::Continue
1177 }
1178}