Skip to main content

waveless_commons/endpoint/
mod.rs

1// Waveless
2// Copyright (C) 2026 Oscar Alvarez Gonzalez
3
4pub mod generator;
5
6use crate::*;
7
8use databases::*;
9
10use http_executor::*;
11use socket_executor::*;
12
13/// Holds all the endpoints, is a wrapper of the [`CheapVec<Endpoint>`] type.
14#[derive(Clone, PartialEq, Serialize, Deserialize, Getters, MutGetters, Debug)]
15#[getset(get = "pub", get_mut = "pub")]
16#[serde(default)]
17pub struct Endpoints {
18    #[serde(
19        rename = "endpoints",
20        default,
21        skip_serializing_if = "should_skip_cheapvec"
22    )]
23    inner: CheapVec<Endpoint, 0>,
24}
25
26impl Endpoints {
27    /// Constructor that checks whether the given endpoints are valid.
28    pub fn new(inner: CheapVec<Endpoint>) -> Result<Self> {
29        for i in 0..inner.len() {
30            for j in (i + 1)..inner.len() {
31                if inner.get(i).unwrap() == inner.get(j).unwrap() {
32                    bail!(
33                        "An equivalent endpoint already exists: you were trying to add '{}', but '{}' is equivalent.",
34                        inner.get(i).unwrap(),
35                        inner.get(j).unwrap()
36                    )
37                }
38            }
39        }
40
41        Ok(Self { inner })
42    }
43
44    /// NOTE: this constructor variant won't check whether the given endpoints are valid whatsoever.
45    pub fn new_unchecked(inner: CheapVec<Endpoint>) -> Self {
46        Self { inner }
47    }
48
49    /// Adds a new endpoint. This will check that there is no endpoint with the same method, route and version.
50    pub fn add(&mut self, new_endpoint: Endpoint) -> Result<()> {
51        let search = self.inner.iter().find(|endpoint| new_endpoint.eq(endpoint));
52
53        match search {
54            Some(endpoint) => Err(eyre!(
55                "An equivalent endpoint already exists: you were trying to add '{}', but '{}' is equivalent.",
56                new_endpoint,
57                endpoint
58            )),
59            None => {
60                self.inner.push(new_endpoint);
61                Ok(())
62            }
63        }
64    }
65
66    /// Merges two endpoints buffers
67    pub fn merge(&mut self, new_endpoints: Endpoints) -> Result<()> {
68        for endpoint in new_endpoints.inner {
69            if let Err(err) = self.add(endpoint.to_owned()) {
70                bail!(
71                    "Cannot add endpoint '{}' to the endpoints buffer. {}",
72                    endpoint.id,
73                    err.to_string()
74                );
75            }
76        }
77        Ok(())
78    }
79}
80
81impl Default for Endpoints {
82    fn default() -> Self {
83        Self {
84            inner: Default::default(),
85        }
86    }
87}
88
89/// The main endpoint definition.
90/// This will be then included in the Waveless project's binary.
91#[derive(Clone, Serialize, Deserialize, Constructor, Builder, Getters, Display, Debug)]
92#[display("{} ({:?}))", id, description)]
93#[builder(default, pattern = "mutable", setter(strip_option))]
94#[getset(get = "pub")]
95pub struct Endpoint {
96    /// Endpoint's unique identifier
97    id: CompactString,
98
99    /// Sets the databases that this endpoint will operate on.
100    #[serde(default, skip_serializing_if = "should_skip_cheapvec")]
101    databases: CheapVec<DatabaseId>,
102
103    /// Target variant.
104    execution_target: ExecutionTarget,
105
106    /// Sets the endpoint description.
107    #[serde(default, skip_serializing_if = "should_skip_option")]
108    description: Option<CompactString>,
109
110    /// Sets the tags of this endpoint. By default the target table name will be adde as a tag.
111    #[serde(default, skip_serializing_if = "should_skip_cheapvec")]
112    tags: CheapVec<CompactString, 0>,
113
114    /// Whether to require auth.
115    auth: Auth,
116
117    /// Whether this endpoint is deprecated.
118    #[serde(default, skip_serializing_if = "should_skip")]
119    deprecated: bool,
120}
121
122impl DatabaseConsumer for Endpoint {
123    fn databases(&self) -> CheapVec<DatabaseId> {
124        self.databases.to_owned()
125    }
126}
127
128impl PartialEq for Endpoint {
129    fn eq(&self, other: &Self) -> bool {
130        self.id == other.id || self.execution_target == other.execution_target
131    }
132}
133
134impl Default for Endpoint {
135    fn default() -> Self {
136        Self {
137            id: "".into(),
138            databases: Default::default(),
139            execution_target: ExecutionTarget::Http(Default::default()),
140            description: None,
141            tags: CheapVec::new_const(),
142            auth: Default::default(),
143            deprecated: false,
144        }
145    }
146}
147
148#[derive(
149    Clone, PartialEq, Serialize, Deserialize, Constructor, Builder, Getters, Display, Debug,
150)]
151#[display("{} (allowed roles: {:?}))", level, allowed_roles)]
152#[builder(default, pattern = "mutable", setter(strip_option))]
153#[getset(get = "pub")]
154pub struct Auth {
155    /// Whether to require auth.
156    level: AuthLevel,
157
158    /// All allowed roles to query the endpoint.
159    #[serde(default, skip_serializing_if = "should_skip_cheapvec")]
160    allowed_roles: CheapVec<CompactString, 0>,
161}
162
163impl Default for Auth {
164    fn default() -> Self {
165        Self {
166            level: AuthLevel::None,
167            allowed_roles: Default::default(),
168        }
169    }
170}
171
172/// Defines all levels of authentication an endpoint might require.
173#[derive(Clone, PartialEq, Serialize, Deserialize, Display, Debug)]
174pub enum AuthLevel {
175    Required,
176    InjectWhenAvailable,
177    None,
178}
179
180/// Defines every kind of connection that a given endpoint may accept.
181#[derive(Clone, PartialEq, Serialize, Deserialize, Display, Debug)]
182pub enum ExecutionTarget {
183    Http(HttpTarget),
184    Socket(SocketTarget),
185}
186
187/// The HTTP endpoint definition that will be either created by the user or discovered by the compiler.
188#[serde_as]
189#[derive(Clone, Serialize, Deserialize, Constructor, Builder, Getters, Display, Debug)]
190#[display("{} -> ({}, {:?})", route, method, version)]
191#[builder(default, pattern = "mutable", setter(strip_option))]
192#[getset(get = "pub")]
193pub struct HttpTarget {
194    /// Route of the endpoint. Note that this will be prefixed with `{api_prefix}/{version}` (if version is set).
195    route: CompactString,
196
197    /// The version of the endpoint, if no version is set the endpoint will be accessible from `{api_prefix}/{route}`.
198    #[serde(default, skip_serializing_if = "should_skip_option")]
199    version: Option<CompactString>,
200
201    /// Method of the endpoint
202    method: HttpMethod,
203
204    /// Establishes the execution pipeline. Note that if no executor is set, the server will try to handle the request internally.
205    #[serde(default, skip_serializing_if = "should_skip_option")]
206    execution_pipeline: Option<ExecutionAtom>,
207
208    /// Sets the accepted query parameters.
209    #[serde(default, skip_serializing_if = "should_skip_cheapvec")]
210    query_params: CheapVec<CompactString, 0>,
211
212    /// Sets the accepted body parameters.
213    #[serde(default, skip_serializing_if = "should_skip_cheapvec")]
214    body_params: CheapVec<CompactString, 0>,
215
216    /// Whether to capture all the request's params.
217    /// Useful for internal executors and generic trait implementations.
218    #[serde(default, skip_serializing_if = "should_skip")]
219    capture_all_params: bool,
220
221    /// Whether this endpoint has been automatically generated.
222    #[serde(default, skip_serializing_if = "auto_generated_skip")]
223    auto_generated: bool,
224}
225
226/// Available HTTP methods
227#[derive(Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, Display, Debug)]
228#[serde(rename_all = "snake_case")]
229pub enum HttpMethod {
230    Get,
231    Post,
232    Put,
233    Delete,
234    Unknown,
235}
236
237impl From<&str> for HttpMethod {
238    fn from(value: &str) -> Self {
239        match value.to_lowercase().as_str() {
240            "get" => HttpMethod::Get,
241            "post" => HttpMethod::Post,
242            "put" => HttpMethod::Put,
243            "delete" => HttpMethod::Delete,
244            _ => HttpMethod::Unknown,
245        }
246    }
247}
248
249fn auto_generated_skip(value: &bool) -> bool {
250    should_skip(&(!*value))
251}
252
253impl Into<ExecutionTarget> for HttpTarget {
254    fn into(self) -> ExecutionTarget {
255        ExecutionTarget::Http(self)
256    }
257}
258
259impl PartialEq for HttpTarget {
260    fn eq(&self, other: &Self) -> bool {
261        self.route.trim().trim_matches('/') == other.route.trim().trim_matches('/')
262            && self
263                .version
264                .to_owned()
265                .map(|version| version.trim().trim_matches('/').to_owned())
266                == other
267                    .version
268                    .to_owned()
269                    .map(|version| version.trim().trim_matches('/').to_owned())
270            && self.method == other.method
271    }
272}
273
274impl Default for HttpTarget {
275    fn default() -> Self {
276        Self {
277            route: "".into(),
278            version: None,
279            method: HttpMethod::Get,
280            execution_pipeline: None.into(),
281            query_params: Default::default(),
282            body_params: Default::default(),
283            capture_all_params: false,
284            auto_generated: false,
285        }
286    }
287}
288
289/// The socket endpoint definition.
290#[serde_as]
291#[derive(Clone, Serialize, Deserialize, Constructor, Builder, Getters, Display, Debug)]
292#[display("(Socket) {:?}", executor)]
293#[builder(default, pattern = "mutable", setter(strip_option))]
294#[getset(get = "pub")]
295pub struct SocketTarget {
296    /// Establishes the endpoint handler.
297    #[serde(default, skip_serializing_if = "should_skip_option")]
298    #[serde_as(as = "IfIsHumanReadable<_, JsonString>")] // Explore müsli to avoid this.
299    executor: Option<Arc<dyn AnySocketExecutor>>,
300}
301
302impl Into<ExecutionTarget> for SocketTarget {
303    fn into(self) -> ExecutionTarget {
304        ExecutionTarget::Socket(self)
305    }
306}
307
308impl PartialEq for SocketTarget {
309    fn eq(&self, _: &Self) -> bool {
310        false
311    }
312}
313
314impl Default for SocketTarget {
315    fn default() -> Self {
316        Self { executor: None }
317    }
318}