openauth_core/context/
request_state.rs1use std::any::Any;
2use std::cell::RefCell;
3use std::collections::HashMap;
4use std::future::Future;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::{Arc, OnceLock};
7
8use crate::db::{Session, User};
9use crate::error::OpenAuthError;
10use serde_json::Value;
11
12tokio::task_local! {
13 static REQUEST_STATE: RefCell<RequestStateStore>;
14}
15
16static NEXT_KEY: AtomicU64 = AtomicU64::new(1);
17
18#[derive(Default)]
20pub struct RequestStateStore {
21 values: HashMap<RequestStateKey, Box<dyn Any + Send>>,
22}
23
24impl RequestStateStore {
25 pub fn new() -> Self {
26 Self::default()
27 }
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub struct RequestStateKey(u64);
32
33impl RequestStateKey {
34 fn new() -> Self {
35 Self(NEXT_KEY.fetch_add(1, Ordering::Relaxed))
36 }
37}
38
39pub struct RequestState<T> {
41 key: RequestStateKey,
42 init: Arc<dyn Fn() -> T + Send + Sync>,
43}
44
45impl<T> Clone for RequestState<T> {
46 fn clone(&self) -> Self {
47 Self {
48 key: self.key,
49 init: Arc::clone(&self.init),
50 }
51 }
52}
53
54impl<T> RequestState<T>
55where
56 T: Clone + Send + 'static,
57{
58 pub fn get(&self) -> Result<T, OpenAuthError> {
60 with_current_store(|store| {
61 if let Some(value) = store.values.get(&self.key) {
62 return value
63 .downcast_ref::<T>()
64 .cloned()
65 .ok_or(OpenAuthError::RequestStateTypeMismatch);
66 }
67
68 let value = (self.init)();
69 store.values.insert(self.key, Box::new(value.clone()));
70 Ok(value)
71 })
72 }
73
74 pub fn set(&self, value: T) -> Result<(), OpenAuthError> {
76 with_current_store(|store| {
77 store.values.insert(self.key, Box::new(value));
78 Ok(())
79 })
80 }
81
82 pub fn key(&self) -> RequestStateKey {
84 self.key
85 }
86}
87
88pub fn define_request_state<T>(init: impl Fn() -> T + Send + Sync + 'static) -> RequestState<T>
90where
91 T: Clone + Send + 'static,
92{
93 RequestState {
94 key: RequestStateKey::new(),
95 init: Arc::new(init),
96 }
97}
98
99static CURRENT_SESSION_USER: OnceLock<RequestState<Option<Value>>> = OnceLock::new();
100static CURRENT_SESSION: OnceLock<RequestState<Option<CurrentSession>>> = OnceLock::new();
101static CURRENT_NEW_SESSION: OnceLock<RequestState<Option<NewSession>>> = OnceLock::new();
102static CURRENT_REQUEST_PATH: OnceLock<RequestState<Option<String>>> = OnceLock::new();
103
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct NewSession {
106 pub session: Session,
107 pub user: User,
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct CurrentSession {
112 pub session: Session,
113 pub user: User,
114}
115
116fn current_session_user_state() -> &'static RequestState<Option<Value>> {
117 CURRENT_SESSION_USER.get_or_init(|| define_request_state(|| None))
118}
119
120fn current_request_path_state() -> &'static RequestState<Option<String>> {
121 CURRENT_REQUEST_PATH.get_or_init(|| define_request_state(|| None))
122}
123
124pub fn set_current_session_user(user: Value) -> Result<(), OpenAuthError> {
126 current_session_user_state().set(Some(user))
127}
128
129pub fn current_session_user() -> Result<Option<Value>, OpenAuthError> {
131 current_session_user_state().get()
132}
133
134fn current_session_state() -> &'static RequestState<Option<CurrentSession>> {
135 CURRENT_SESSION.get_or_init(|| define_request_state(|| None))
136}
137
138pub fn set_current_session(session: Session, user: User) -> Result<(), OpenAuthError> {
139 current_session_state().set(Some(CurrentSession { session, user }))
140}
141
142pub fn current_session() -> Result<Option<CurrentSession>, OpenAuthError> {
143 current_session_state().get()
144}
145
146fn current_new_session_state() -> &'static RequestState<Option<NewSession>> {
147 CURRENT_NEW_SESSION.get_or_init(|| define_request_state(|| None))
148}
149
150pub fn set_current_new_session(session: Session, user: User) -> Result<(), OpenAuthError> {
151 current_new_session_state().set(Some(NewSession { session, user }))
152}
153
154pub fn current_new_session() -> Result<Option<NewSession>, OpenAuthError> {
155 current_new_session_state().get()
156}
157
158pub fn set_current_request_path(path: impl Into<String>) -> Result<(), OpenAuthError> {
160 current_request_path_state().set(Some(path.into()))
161}
162
163pub fn current_request_path() -> Result<Option<String>, OpenAuthError> {
165 current_request_path_state().get()
166}
167
168pub async fn run_with_request_state<F>(future: F) -> F::Output
170where
171 F: Future,
172{
173 REQUEST_STATE
174 .scope(RefCell::new(RequestStateStore::new()), future)
175 .await
176}
177
178pub fn has_request_state() -> bool {
180 REQUEST_STATE.try_with(|_| ()).is_ok()
181}
182
183fn with_current_store<T>(
184 operation: impl FnOnce(&mut RequestStateStore) -> Result<T, OpenAuthError>,
185) -> Result<T, OpenAuthError> {
186 REQUEST_STATE
187 .try_with(|store| operation(&mut store.borrow_mut()))
188 .map_err(|_| OpenAuthError::RequestStateMissing)?
189}