server_context.rs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. use parking_lot::RwLock;
  2. use std::any::Any;
  3. use std::collections::HashMap;
  4. use std::sync::Arc;
  5. type SendSyncAnyMap =
  6. std::collections::HashMap<std::any::TypeId, Box<dyn Any + Send + Sync + 'static>>;
  7. /// A shared context for server functions that contains information about the request and middleware state.
  8. /// This allows you to pass data between your server framework and the server functions. This can be used to pass request information or information about the state of the server. For example, you could pass authentication data though this context to your server functions.
  9. ///
  10. /// You should not construct this directly inside components. Instead use the `HasServerContext` trait to get the server context from the scope.
  11. #[derive(Clone)]
  12. pub struct DioxusServerContext {
  13. shared_context: std::sync::Arc<RwLock<SendSyncAnyMap>>,
  14. response_parts: std::sync::Arc<RwLock<http::response::Parts>>,
  15. pub(crate) parts: Arc<RwLock<http::request::Parts>>,
  16. }
  17. #[allow(clippy::derivable_impls)]
  18. impl Default for DioxusServerContext {
  19. fn default() -> Self {
  20. Self {
  21. shared_context: std::sync::Arc::new(RwLock::new(HashMap::new())),
  22. response_parts: std::sync::Arc::new(RwLock::new(
  23. http::response::Response::new(()).into_parts().0,
  24. )),
  25. parts: std::sync::Arc::new(RwLock::new(http::request::Request::new(()).into_parts().0)),
  26. }
  27. }
  28. }
  29. mod server_fn_impl {
  30. use super::*;
  31. use parking_lot::{RwLockReadGuard, RwLockWriteGuard};
  32. use std::any::{Any, TypeId};
  33. impl DioxusServerContext {
  34. /// Create a new server context from a request
  35. pub fn new(parts: http::request::Parts) -> Self {
  36. Self {
  37. parts: Arc::new(RwLock::new(parts)),
  38. shared_context: Arc::new(RwLock::new(SendSyncAnyMap::new())),
  39. response_parts: std::sync::Arc::new(RwLock::new(
  40. http::response::Response::new(()).into_parts().0,
  41. )),
  42. }
  43. }
  44. /// Create a server context from a shared parts
  45. #[allow(unused)]
  46. pub(crate) fn from_shared_parts(parts: Arc<RwLock<http::request::Parts>>) -> Self {
  47. Self {
  48. parts,
  49. shared_context: Arc::new(RwLock::new(SendSyncAnyMap::new())),
  50. response_parts: std::sync::Arc::new(RwLock::new(
  51. http::response::Response::new(()).into_parts().0,
  52. )),
  53. }
  54. }
  55. /// Clone a value from the shared server context
  56. pub fn get<T: Any + Send + Sync + Clone + 'static>(&self) -> Option<T> {
  57. self.shared_context
  58. .read()
  59. .get(&TypeId::of::<T>())
  60. .map(|v| v.downcast_ref::<T>().unwrap().clone())
  61. }
  62. /// Insert a value into the shared server context
  63. pub fn insert<T: Any + Send + Sync + 'static>(&self, value: T) {
  64. self.shared_context
  65. .write()
  66. .insert(TypeId::of::<T>(), Box::new(value));
  67. }
  68. /// Insert a Boxed `Any` value into the shared server context
  69. pub fn insert_any(&self, value: Box<dyn Any + Send + Sync>) {
  70. self.shared_context
  71. .write()
  72. .insert((*value).type_id(), value);
  73. }
  74. /// Get the response parts from the server context
  75. pub fn response_parts(&self) -> RwLockReadGuard<'_, http::response::Parts> {
  76. self.response_parts.read()
  77. }
  78. /// Get the response parts from the server context
  79. pub fn response_parts_mut(&self) -> RwLockWriteGuard<'_, http::response::Parts> {
  80. self.response_parts.write()
  81. }
  82. /// Get the request that triggered:
  83. /// - The initial SSR render if called from a ScopeState or ServerFn
  84. /// - The server function to be called if called from a server function after the initial render
  85. pub fn request_parts(&self) -> parking_lot::RwLockReadGuard<'_, http::request::Parts> {
  86. self.parts.read()
  87. }
  88. /// Get the request that triggered:
  89. /// - The initial SSR render if called from a ScopeState or ServerFn
  90. /// - The server function to be called if called from a server function after the initial render
  91. pub fn request_parts_mut(&self) -> parking_lot::RwLockWriteGuard<'_, http::request::Parts> {
  92. self.parts.write()
  93. }
  94. /// Extract some part from the request
  95. pub async fn extract<R: std::error::Error, T: FromServerContext<Rejection = R>>(
  96. &self,
  97. ) -> Result<T, R> {
  98. T::from_request(self).await
  99. }
  100. }
  101. }
  102. std::thread_local! {
  103. pub(crate) static SERVER_CONTEXT: std::cell::RefCell<Box<DioxusServerContext>> = Default::default();
  104. }
  105. /// Get information about the current server request.
  106. ///
  107. /// This function will only provide the current server context if it is called from a server function or on the server rendering a request.
  108. pub fn server_context() -> DioxusServerContext {
  109. SERVER_CONTEXT.with(|ctx| *ctx.borrow().clone())
  110. }
  111. /// Extract some part from the current server request.
  112. ///
  113. /// This function will only provide the current server context if it is called from a server function or on the server rendering a request.
  114. pub async fn extract<E: FromServerContext<I>, I>() -> Result<E, E::Rejection> {
  115. E::from_request(&server_context()).await
  116. }
  117. /// Run a function inside of the server context.
  118. pub fn with_server_context<O>(context: DioxusServerContext, f: impl FnOnce() -> O) -> O {
  119. // before polling the future, we need to set the context
  120. let prev_context = SERVER_CONTEXT.with(|ctx| ctx.replace(Box::new(context)));
  121. // poll the future, which may call server_context()
  122. let result = f();
  123. // after polling the future, we need to restore the context
  124. SERVER_CONTEXT.with(|ctx| ctx.replace(prev_context));
  125. result
  126. }
  127. /// A future that provides the server context to the inner future
  128. #[pin_project::pin_project]
  129. pub struct ProvideServerContext<F: std::future::Future> {
  130. context: DioxusServerContext,
  131. #[pin]
  132. f: F,
  133. }
  134. impl<F: std::future::Future> ProvideServerContext<F> {
  135. /// Create a new future that provides the server context to the inner future
  136. pub fn new(f: F, context: DioxusServerContext) -> Self {
  137. Self { f, context }
  138. }
  139. }
  140. impl<F: std::future::Future> std::future::Future for ProvideServerContext<F> {
  141. type Output = F::Output;
  142. fn poll(
  143. self: std::pin::Pin<&mut Self>,
  144. cx: &mut std::task::Context<'_>,
  145. ) -> std::task::Poll<Self::Output> {
  146. let this = self.project();
  147. let context = this.context.clone();
  148. with_server_context(context, || this.f.poll(cx))
  149. }
  150. }
  151. /// A trait for extracting types from the server context
  152. #[async_trait::async_trait]
  153. pub trait FromServerContext<I = ()>: Sized {
  154. /// The error type returned when extraction fails. This type must implement `std::error::Error`.
  155. type Rejection: std::error::Error;
  156. /// Extract this type from the server context.
  157. async fn from_request(req: &DioxusServerContext) -> Result<Self, Self::Rejection>;
  158. }
  159. /// A type was not found in the server context
  160. pub struct NotFoundInServerContext<T: 'static>(std::marker::PhantomData<T>);
  161. impl<T: 'static> std::fmt::Debug for NotFoundInServerContext<T> {
  162. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  163. let type_name = std::any::type_name::<T>();
  164. write!(f, "`{type_name}` not found in server context")
  165. }
  166. }
  167. impl<T: 'static> std::fmt::Display for NotFoundInServerContext<T> {
  168. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  169. let type_name = std::any::type_name::<T>();
  170. write!(f, "`{type_name}` not found in server context")
  171. }
  172. }
  173. impl<T: 'static> std::error::Error for NotFoundInServerContext<T> {}
  174. /// Extract a value from the server context provided through the launch builder context or [`DioxusServerContext::insert`]
  175. ///
  176. /// Example:
  177. /// ```rust, no_run
  178. /// use dioxus::prelude::*;
  179. ///
  180. /// LaunchBuilder::new()
  181. /// // You can provide context to your whole app (including server functions) with the `with_context` method on the launch builder
  182. /// .with_context(server_only! {
  183. /// 1234567890u32
  184. /// })
  185. /// .launch(app);
  186. ///
  187. /// #[server]
  188. /// async fn read_context() -> Result<u32, ServerFnError> {
  189. /// // You can extract values from the server context with the `extract` function
  190. /// let FromContext(value) = extract().await?;
  191. /// Ok(value)
  192. /// }
  193. ///
  194. /// fn app() -> Element {
  195. /// let future = use_resource(read_context);
  196. /// rsx! {
  197. /// h1 { "{future:?}" }
  198. /// }
  199. /// }
  200. /// ```
  201. pub struct FromContext<T: std::marker::Send + std::marker::Sync + Clone + 'static>(pub T);
  202. #[async_trait::async_trait]
  203. impl<T: Send + Sync + Clone + 'static> FromServerContext for FromContext<T> {
  204. type Rejection = NotFoundInServerContext<T>;
  205. async fn from_request(req: &DioxusServerContext) -> Result<Self, Self::Rejection> {
  206. Ok(Self(req.get::<T>().ok_or({
  207. NotFoundInServerContext::<T>(std::marker::PhantomData::<T>)
  208. })?))
  209. }
  210. }
  211. #[cfg(feature = "axum")]
  212. #[cfg_attr(docsrs, doc(cfg(feature = "axum")))]
  213. /// An adapter for axum extractors for the server context
  214. pub struct Axum;
  215. #[cfg(feature = "axum")]
  216. #[async_trait::async_trait]
  217. impl<
  218. I: axum::extract::FromRequestParts<(), Rejection = R>,
  219. R: axum::response::IntoResponse + std::error::Error,
  220. > FromServerContext<Axum> for I
  221. {
  222. type Rejection = R;
  223. #[allow(clippy::all)]
  224. async fn from_request(req: &DioxusServerContext) -> Result<Self, Self::Rejection> {
  225. let mut lock = req.request_parts_mut();
  226. I::from_request_parts(&mut lock, &()).await
  227. }
  228. }