dioxus_fullstack/
server_context.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use parking_lot::RwLock;
use std::any::Any;
use std::collections::HashMap;
use std::sync::Arc;

type SendSyncAnyMap = std::collections::HashMap<std::any::TypeId, ContextType>;

/// A shared context for server functions that contains information about the request and middleware state.
///
/// You should not construct this directly inside components or server functions. Instead use [`server_context()`] to get the server context from the current request.
///
/// # Example
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// #[server]
/// async fn read_headers() -> Result<(), ServerFnError> {
///     let server_context = server_context();
///     let headers: http::HeaderMap = server_context.extract().await?;
///     println!("{:?}", headers);
///     Ok(())
/// }
/// ```
#[derive(Clone)]
pub struct DioxusServerContext {
    shared_context: std::sync::Arc<RwLock<SendSyncAnyMap>>,
    response_parts: std::sync::Arc<RwLock<http::response::Parts>>,
    pub(crate) parts: Arc<RwLock<http::request::Parts>>,
}

enum ContextType {
    Factory(Box<dyn Fn() -> Box<dyn Any> + Send + Sync>),
    Value(Box<dyn Any + Send + Sync>),
}

impl ContextType {
    fn downcast<T: Clone + 'static>(&self) -> Option<T> {
        match self {
            ContextType::Value(value) => value.downcast_ref::<T>().cloned(),
            ContextType::Factory(factory) => factory().downcast::<T>().ok().map(|v| *v),
        }
    }
}

#[allow(clippy::derivable_impls)]
impl Default for DioxusServerContext {
    fn default() -> Self {
        Self {
            shared_context: std::sync::Arc::new(RwLock::new(HashMap::new())),
            response_parts: std::sync::Arc::new(RwLock::new(
                http::response::Response::new(()).into_parts().0,
            )),
            parts: std::sync::Arc::new(RwLock::new(http::request::Request::new(()).into_parts().0)),
        }
    }
}

mod server_fn_impl {
    use super::*;
    use parking_lot::{RwLockReadGuard, RwLockWriteGuard};
    use std::any::{Any, TypeId};

    impl DioxusServerContext {
        /// Create a new server context from a request
        pub fn new(parts: http::request::Parts) -> Self {
            Self {
                parts: Arc::new(RwLock::new(parts)),
                shared_context: Arc::new(RwLock::new(SendSyncAnyMap::new())),
                response_parts: std::sync::Arc::new(RwLock::new(
                    http::response::Response::new(()).into_parts().0,
                )),
            }
        }

        /// Create a server context from a shared parts
        #[allow(unused)]
        pub(crate) fn from_shared_parts(parts: Arc<RwLock<http::request::Parts>>) -> Self {
            Self {
                parts,
                shared_context: Arc::new(RwLock::new(SendSyncAnyMap::new())),
                response_parts: std::sync::Arc::new(RwLock::new(
                    http::response::Response::new(()).into_parts().0,
                )),
            }
        }

        /// Clone a value from the shared server context. If you are using [`DioxusRouterExt`](crate::prelude::DioxusRouterExt), any values you insert into
        /// the launch context will also be available in the server context.
        ///
        /// Example:
        /// ```rust, no_run
        /// use dioxus::prelude::*;
        ///
        /// LaunchBuilder::new()
        ///     // You can provide context to your whole app (including server functions) with the `with_context` method on the launch builder
        ///     .with_context(server_only! {
        ///         1234567890u32
        ///     })
        ///     .launch(app);
        ///
        /// #[server]
        /// async fn read_context() -> Result<u32, ServerFnError> {
        ///     // You can extract values from the server context with the `extract` function
        ///     let FromContext(value) = extract().await?;
        ///     Ok(value)
        /// }
        ///
        /// fn app() -> Element {
        ///     let future = use_resource(read_context);
        ///     rsx! {
        ///         h1 { "{future:?}" }
        ///     }
        /// }
        /// ```
        pub fn get<T: Any + Send + Sync + Clone + 'static>(&self) -> Option<T> {
            self.shared_context
                .read()
                .get(&TypeId::of::<T>())
                .map(|v| v.downcast::<T>().unwrap())
        }

        /// Insert a value into the shared server context
        pub fn insert<T: Any + Send + Sync + 'static>(&self, value: T) {
            self.insert_any(Box::new(value));
        }

        /// Insert a boxed `Any` value into the shared server context
        pub fn insert_any(&self, value: Box<dyn Any + Send + Sync + 'static>) {
            self.shared_context
                .write()
                .insert((*value).type_id(), ContextType::Value(value));
        }

        /// Insert a factory that creates a non-sync value for the shared server context
        pub fn insert_factory<F, T>(&self, value: F)
        where
            F: Fn() -> T + Send + Sync + 'static,
            T: 'static,
        {
            self.shared_context.write().insert(
                TypeId::of::<T>(),
                ContextType::Factory(Box::new(move || Box::new(value()))),
            );
        }

        /// Insert a boxed factory that creates a non-sync value for the shared server context
        pub fn insert_boxed_factory(&self, value: Box<dyn Fn() -> Box<dyn Any> + Send + Sync>) {
            self.shared_context
                .write()
                .insert((*value()).type_id(), ContextType::Factory(value));
        }

        /// Get the response parts from the server context
        ///
        #[doc = include_str!("../docs/request_origin.md")]
        ///
        /// # Example
        ///
        /// ```rust, no_run
        /// # use dioxus::prelude::*;
        /// #[server]
        /// async fn set_headers() -> Result<(), ServerFnError> {
        ///     let server_context = server_context();
        ///     let response_parts = server_context.response_parts();
        ///     let cookies = response_parts
        ///         .headers
        ///         .get("Cookie")
        ///         .ok_or_else(|| ServerFnError::new("failed to find Cookie header in the response"))?;
        ///     println!("{:?}", cookies);
        ///     Ok(())
        /// }
        /// ```
        pub fn response_parts(&self) -> RwLockReadGuard<'_, http::response::Parts> {
            self.response_parts.read()
        }

        /// Get the response parts from the server context
        ///
        #[doc = include_str!("../docs/request_origin.md")]
        ///
        /// # Example
        ///
        /// ```rust, no_run
        /// # use dioxus::prelude::*;
        /// #[server]
        /// async fn set_headers() -> Result<(), ServerFnError> {
        ///     let server_context = server_context();
        ///     server_context.response_parts_mut()
        ///         .headers
        ///         .insert("Cookie", http::HeaderValue::from_static("dioxus=fullstack"));
        ///     Ok(())
        /// }
        /// ```
        pub fn response_parts_mut(&self) -> RwLockWriteGuard<'_, http::response::Parts> {
            self.response_parts.write()
        }

        /// Get the request parts
        ///
        #[doc = include_str!("../docs/request_origin.md")]
        ///
        /// # Example
        ///
        /// ```rust, no_run
        /// # use dioxus::prelude::*;
        /// #[server]
        /// async fn read_headers() -> Result<(), ServerFnError> {
        ///     let server_context = server_context();
        ///     let request_parts = server_context.request_parts();
        ///     let id: &i32 = request_parts
        ///         .extensions
        ///         .get()
        ///         .ok_or_else(|| ServerFnError::new("failed to find i32 extension in the request"))?;
        ///     println!("{:?}", id);
        ///     Ok(())
        /// }
        /// ```
        pub fn request_parts(&self) -> parking_lot::RwLockReadGuard<'_, http::request::Parts> {
            self.parts.read()
        }

        /// Get the request parts mutably
        ///
        #[doc = include_str!("../docs/request_origin.md")]
        ///
        /// # Example
        ///
        /// ```rust, no_run
        /// # use dioxus::prelude::*;
        /// #[server]
        /// async fn read_headers() -> Result<(), ServerFnError> {
        ///     let server_context = server_context();
        ///     let id: i32 = server_context.request_parts_mut()
        ///         .extensions
        ///         .remove()
        ///         .ok_or_else(|| ServerFnError::new("failed to find i32 extension in the request"))?;
        ///     println!("{:?}", id);
        ///     Ok(())
        /// }
        /// ```
        pub fn request_parts_mut(&self) -> parking_lot::RwLockWriteGuard<'_, http::request::Parts> {
            self.parts.write()
        }

        /// Extract part of the request.
        ///
        #[doc = include_str!("../docs/request_origin.md")]
        ///
        /// # Example
        ///
        /// ```rust, no_run
        /// # use dioxus::prelude::*;
        /// #[server]
        /// async fn read_headers() -> Result<(), ServerFnError> {
        ///     let server_context = server_context();
        ///     let headers: http::HeaderMap = server_context.extract().await?;
        ///     println!("{:?}", headers);
        ///     Ok(())
        /// }
        /// ```
        pub async fn extract<M, T: FromServerContext<M>>(&self) -> Result<T, T::Rejection> {
            T::from_request(self).await
        }
    }
}

#[test]
fn server_context_as_any_map() {
    let parts = http::Request::new(()).into_parts().0;
    let server_context = DioxusServerContext::new(parts);
    server_context.insert_boxed_factory(Box::new(|| Box::new(1234u32)));
    assert_eq!(server_context.get::<u32>().unwrap(), 1234u32);
}

std::thread_local! {
    pub(crate) static SERVER_CONTEXT: std::cell::RefCell<Box<DioxusServerContext>> = Default::default();
}

/// Get information about the current server request.
///
/// This function will only provide the current server context if it is called from a server function or on the server rendering a request.
pub fn server_context() -> DioxusServerContext {
    SERVER_CONTEXT.with(|ctx| *ctx.borrow().clone())
}

/// Extract some part from the current server request.
///
/// This function will only provide the current server context if it is called from a server function or on the server rendering a request.
pub async fn extract<E: FromServerContext<I>, I>() -> Result<E, E::Rejection> {
    E::from_request(&server_context()).await
}

/// Run a function inside of the server context.
pub fn with_server_context<O>(context: DioxusServerContext, f: impl FnOnce() -> O) -> O {
    // before polling the future, we need to set the context
    let prev_context = SERVER_CONTEXT.with(|ctx| ctx.replace(Box::new(context)));
    // poll the future, which may call server_context()
    let result = f();
    // after polling the future, we need to restore the context
    SERVER_CONTEXT.with(|ctx| ctx.replace(prev_context));
    result
}

/// A future that provides the server context to the inner future
#[pin_project::pin_project]
pub struct ProvideServerContext<F: std::future::Future> {
    context: DioxusServerContext,
    #[pin]
    f: F,
}

impl<F: std::future::Future> ProvideServerContext<F> {
    /// Create a new future that provides the server context to the inner future
    pub fn new(f: F, context: DioxusServerContext) -> Self {
        Self { f, context }
    }
}

impl<F: std::future::Future> std::future::Future for ProvideServerContext<F> {
    type Output = F::Output;

    fn poll(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        let this = self.project();
        let context = this.context.clone();
        with_server_context(context, || this.f.poll(cx))
    }
}

/// A trait for extracting types from the server context
#[async_trait::async_trait]
pub trait FromServerContext<I = ()>: Sized {
    /// The error type returned when extraction fails. This type must implement `std::error::Error`.
    type Rejection;

    /// Extract this type from the server context.
    async fn from_request(req: &DioxusServerContext) -> Result<Self, Self::Rejection>;
}

/// A type was not found in the server context
pub struct NotFoundInServerContext<T: 'static>(std::marker::PhantomData<T>);

impl<T: 'static> std::fmt::Debug for NotFoundInServerContext<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let type_name = std::any::type_name::<T>();
        write!(f, "`{type_name}` not found in server context")
    }
}

impl<T: 'static> std::fmt::Display for NotFoundInServerContext<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let type_name = std::any::type_name::<T>();
        write!(f, "`{type_name}` not found in server context")
    }
}

impl<T: 'static> std::error::Error for NotFoundInServerContext<T> {}

/// Extract a value from the server context provided through the launch builder context or [`DioxusServerContext::insert`]
///
/// Example:
/// ```rust, no_run
/// use dioxus::prelude::*;
///
/// dioxus::LaunchBuilder::new()
///     // You can provide context to your whole app (including server functions) with the `with_context` method on the launch builder
///     .with_context(server_only! {
///         1234567890u32
///     })
///     .launch(app);
///
/// #[server]
/// async fn read_context() -> Result<u32, ServerFnError> {
///     // You can extract values from the server context with the `extract` function
///     let FromContext(value) = extract().await?;
///     Ok(value)
/// }
///
/// fn app() -> Element {
///     let future = use_resource(read_context);
///     rsx! {
///         h1 { "{future:?}" }
///     }
/// }
/// ```
pub struct FromContext<T: std::marker::Send + std::marker::Sync + Clone + 'static>(pub T);

#[async_trait::async_trait]
impl<T: Send + Sync + Clone + 'static> FromServerContext for FromContext<T> {
    type Rejection = NotFoundInServerContext<T>;

    async fn from_request(req: &DioxusServerContext) -> Result<Self, Self::Rejection> {
        Ok(Self(req.get::<T>().ok_or({
            NotFoundInServerContext::<T>(std::marker::PhantomData::<T>)
        })?))
    }
}

#[cfg(feature = "axum")]
#[cfg_attr(docsrs, doc(cfg(feature = "axum")))]
/// An adapter for axum extractors for the server context
pub struct Axum;

#[cfg(feature = "axum")]
#[async_trait::async_trait]
impl<I: axum::extract::FromRequestParts<()>> FromServerContext<Axum> for I {
    type Rejection = I::Rejection;

    #[allow(clippy::all)]
    async fn from_request(req: &DioxusServerContext) -> Result<Self, Self::Rejection> {
        let mut lock = req.request_parts_mut();
        I::from_request_parts(&mut lock, &()).await
    }
}