Skip to main content

waveless_runtime/
runtime_cx.rs

1// Waveless
2// Copyright (C) 2026 Oscar Alvarez Gonzalez
3
4use crate::*;
5
6#[derive(Constructor, Getters, Debug)]
7#[getset(get = "pub")]
8pub struct RuntimeCx {
9    build: RwLock<ObjectArtifact>,
10    router: EndpointRouter,
11    _loaded_from: Option<PathBuf>,
12}
13
14impl RuntimeCx {
15    pub fn acquire() -> &'static Self {
16        RUNTIME_CX
17            .get()
18            .ok_or(eyre!("Runtime's context should have been initialized."))
19            .unwrap()
20    }
21
22    /// Sets the [`RUNTIME_CX`]'s `OnceLock`.
23    /// NOTE: If runtime's context is set this method will panic.
24    pub fn set_cx(self) {
25        if !RUNTIME_CX.initialized() {
26            RUNTIME_CX.set(self).unwrap();
27        } else {
28            panic!("Runtime's context has already been initialized.");
29        }
30    }
31
32    /// Builds the runtime's context by loading the project's build
33    /// from the given **build** and building the router.
34    pub async fn from_build(build: ObjectArtifact) -> Result<Self> {
35        let cx = Self::new(RwLock::new(build), EndpointRouter::new(), None);
36        cx.build_router().await?;
37        Ok(cx)
38    }
39
40    /// Builds the runtime's context by loading the project's build
41    /// from the given **path** and building the router.
42    pub async fn from_path(path: PathBuf) -> Result<Self> {
43        match read(path.to_owned()) {
44            Ok(file_buffer) => {
45                match ObjectArtifact::decode_binary(&CheapVec::from_vec(file_buffer)) {
46                    Ok(build) => {
47                        let cx = Self::new(RwLock::new(build), EndpointRouter::new(), Some(path));
48                        cx.build_router().await?;
49                        Ok(cx)
50                    }
51                    Err(err) => Err(err).wrap_err(format!(
52                        "Cannot deserialize the project's binary '{}'.",
53                        path.display(),
54                    )),
55                }
56            }
57            Err(err) => Err(err)
58                .wrap_err(format!("Cannot open '{}'.", path.display(),))
59                .suggestion("Are you sure that you have the file's permissions?"),
60        }
61    }
62
63    /// Builds the endpoint router from the given runtime's context.
64    pub async fn build_router(&self) -> Result<()> {
65        let Self { build, router, .. } = self;
66
67        let prefix = build.read().await.executor().api_prefix().to_owned();
68
69        let mut endpoints = build.read().await.endpoints().inner().to_owned();
70
71        // Add authentication endpoints if enabled.
72        if let Some(auth_config) = build.read().await.config().authentication().to_owned() {
73            for (kind, endpoint) in INTERNAL_ENDPOINTS.iter() {
74                if let InternalEndpointKind::Authentication = kind {
75                    // Check whether we are trying to add the signup endpoint while being disabled.
76                    if !auth_config.allow_signup() && endpoint.id() == SIGNUP_ENDPOINT_ID {
77                        continue;
78                    }
79
80                    endpoints.push(endpoint.to_owned());
81                }
82            }
83        }
84
85        // Add all other internal endpoints.
86        INTERNAL_ENDPOINTS.iter().for_each(|(kind, endpoint)| {
87            if let InternalEndpointKind::Other = kind {
88                endpoints.push(endpoint.to_owned());
89            }
90        });
91
92        // Reset the router to prevent deleted endpoints to persist.
93        for method_router in router.to_owned().iter() {
94            router.remove(method_router.key());
95        }
96
97        // Add all endpoints to the router.
98        let prefix = prefix.trim_matches('/');
99
100        for endpoint in endpoints {
101            if let ExecutionTarget::Http(http_target) = endpoint.execution_target() {
102                let route_parts: CheapVec<Option<CompactString>, 3> = CheapVec::from_buf([
103                    Some(prefix.into()),
104                    http_target
105                        .version()
106                        .to_owned()
107                        .map(|version| version.trim_matches('/').into()),
108                    Some(http_target.route().trim_matches('/').into()),
109                ]);
110
111                let route = route_parts.into_iter().flatten().join_compact("/");
112
113                if let Some(mut router) = router.get_mut(http_target.method()) {
114                    let _ = router.insert(route, endpoint.to_owned()); // the error here is ignored.
115                } else {
116                    let mut new_router = Router::new();
117                    new_router.insert(route, endpoint.to_owned())?;
118
119                    let _ = router.insert(http_target.method().to_owned(), new_router);
120                }
121            }
122        }
123
124        Ok(())
125    }
126}