rusty_express/core/
context.rs

1#![allow(dead_code)]
2#![allow(clippy::borrowed_box)]
3
4use crate::core::http::{Request, Response};
5use crate::parking_lot::RwLock;
6
7const ERR_STR: &str = "The context has not been initialized...";
8static mut CONTEXT: Option<RwLock<Box<ServerContextProvider>>> = None;
9
10pub type ServerContextProvider = ContextProvider + Sync + Send;
11
12pub trait ContextProvider {
13    fn update(&mut self, req: &Box<Request>, resp: &mut Box<Response>) -> Result<(), &'static str>;
14    fn process(&self, req: &Box<Request>, resp: &mut Box<Response>) -> Result<(), &'static str>;
15}
16
17/// Move the ownership of the context object to the server, such that it can be managed when
18/// it receives new requests.
19pub fn set_context(context: Box<ServerContextProvider>) {
20    if let Some(ctx) = unsafe { CONTEXT.as_mut() } {
21        let mut ctx = ctx.write();
22        *ctx = context;
23        return;
24    }
25
26    unsafe {
27        CONTEXT = Some(RwLock::new(context));
28    }
29}
30
31/// Update the context content. This will invoke the `RwLock` to gain the exclusive access
32/// to the underlying context object, hence impacting the performance. You don't need to lock
33/// the object again, unless it's also shared with other threads not interacting with the TCP
34/// stream.
35///
36/// For examples, see [`https://github.com/Chopinsky/Rusty_Express/blob/master/examples/use_router.rs`]
37pub fn update_context(req: &Box<Request>, resp: &mut Box<Response>) -> Result<(), &'static str> {
38    if let Some(ctx) = unsafe { CONTEXT.as_mut() } {
39        let mut ctx = ctx.write();
40        return ctx.update(req, resp);
41    }
42
43    Err(ERR_STR)
44}
45
46/// Access the context content. This will invoke the read lock of the `RwLock` to gain the
47/// shared access to the underlying context object, the impact to the performance should consider
48/// normal. You don't need to lock the object again, unless it's also shared with other threads
49/// not interacting with the TCP stream.
50///
51/// For examples, see [`https://github.com/Chopinsky/Rusty_Express/blob/master/examples/use_router.rs`]
52pub fn process_with_context(
53    req: &Box<Request>,
54    resp: &mut Box<Response>,
55) -> Result<(), &'static str> {
56    if let Some(ctx) = unsafe { CONTEXT.as_ref() } {
57        let ctx = ctx.read();
58        return ctx.process(req, resp);
59    }
60
61    Err(ERR_STR)
62}