1use std::sync::{Arc, Mutex, MutexGuard};
9
10use serde::Serialize;
11use serde::de::DeserializeOwned;
12use serde_json::{Map, Value};
13
14use crate::cookies::{Cookie, Cookies, SameSite};
15use crate::error::Result;
16
17pub(crate) const COOKIE_NAME: &str = "_glacier_session";
18const FLASH_KEY: &str = "_flash";
19
20#[derive(Clone)]
21pub struct Session {
22 state: Arc<Mutex<State>>,
23 cookies: Cookies,
24 secure: bool,
25}
26
27#[derive(Default)]
28struct State {
29 loaded: bool,
30 dirty: bool,
31 data: Map<String, Value>,
32 flash: Map<String, Value>,
34 flash_read: bool,
36 flash_set: Vec<String>,
38}
39
40impl Session {
41 pub(crate) fn new(cookies: Cookies, secure: bool) -> Self {
42 Self {
43 state: Arc::default(),
44 cookies,
45 secure,
46 }
47 }
48
49 fn state(&self) -> MutexGuard<'_, State> {
50 let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
51 if !state.loaded {
52 state.loaded = true;
53 let found = self.cookies.get_private_rotated(COOKIE_NAME);
54 if found.as_ref().is_some_and(|(_, old)| *old) {
56 state.dirty = true;
57 }
58 if let Some(Value::Object(data)) =
59 found.and_then(|(raw, _)| serde_json::from_str(&raw).ok())
60 {
61 if let Some(Value::Object(flash)) = data.get(FLASH_KEY) {
64 state.flash = flash.clone();
65 }
66 state.data = data;
67 }
68 }
69 state
70 }
71
72 pub fn get<T: DeserializeOwned>(&self, key: &str) -> Option<T> {
73 let value = self.state().data.get(key)?.clone();
74 serde_json::from_value(value).ok()
75 }
76
77 pub fn insert<T: Serialize>(&self, key: &str, value: T) -> Result<()> {
78 let value = serde_json::to_value(value)?;
79 let mut state = self.state();
80 state.data.insert(key.to_owned(), value);
81 state.dirty = true;
82 Ok(())
83 }
84
85 pub fn remove(&self, key: &str) {
86 let mut state = self.state();
87 if state.data.remove(key).is_some() {
88 state.dirty = true;
89 }
90 }
91
92 pub fn clear(&self) {
94 let mut state = self.state();
95 state.data.clear();
96 state.dirty = true;
97 }
98
99 pub fn flash(&self, kind: &str) -> Option<String> {
102 let mut state = self.state();
103 if !state.flash.is_empty() && !state.flash_read {
104 state.flash_read = true;
105 state.dirty = true;
106 }
107 state
108 .flash
109 .get(kind)
110 .and_then(Value::as_str)
111 .map(str::to_owned)
112 }
113
114 pub fn flash_now(&self, kind: &str, message: impl Into<String>) {
117 self.state()
118 .flash
119 .insert(kind.to_owned(), Value::String(message.into()));
120 }
121
122 pub fn put_flash(&self, kind: &str, message: impl Into<String>) {
124 let mut state = self.state();
125 let flash = state
126 .data
127 .entry(FLASH_KEY)
128 .or_insert_with(|| Value::Object(Map::new()));
129 if let Value::Object(flash) = flash {
130 flash.insert(kind.to_owned(), Value::String(message.into()));
131 }
132 state.flash_set.push(kind.to_owned());
133 state.dirty = true;
134 }
135
136 pub(crate) fn commit(&self) {
138 let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
139 if !state.loaded || !state.dirty {
140 return;
141 }
142 if state.flash_read {
144 let set = std::mem::take(&mut state.flash_set);
145 let kept: Map<String, Value> = match state.data.remove(FLASH_KEY) {
146 Some(Value::Object(flash)) => flash
147 .into_iter()
148 .filter(|(kind, _)| set.contains(kind))
149 .collect(),
150 _ => Map::new(),
151 };
152 if !kept.is_empty() {
153 state.data.insert(FLASH_KEY.to_owned(), Value::Object(kept));
154 }
155 }
156 if state.data.is_empty() {
157 if self.cookies.get(COOKIE_NAME).is_some() {
158 self.cookies.remove(COOKIE_NAME);
159 }
160 return;
161 }
162 let json = Value::Object(state.data.clone()).to_string();
163 self.cookies.add_private(
164 Cookie::build((COOKIE_NAME, json))
165 .path("/")
166 .http_only(true)
167 .same_site(SameSite::Lax)
168 .secure(self.secure),
169 );
170 }
171}