Skip to main content

waveless_commons/
project.rs

1// Waveless
2// Copyright (C) 2026 Oscar Alvarez Gonzalez
3
4//!
5//! The Waveless's project's 'project.toml' file will be divided into: compiler settings, runtime settings, authentication and database authentication credentials
6//! Both Authentication and [`CheapVec<DatabaseAuth>`] will be shared with the compiler and the runtime.
7//!
8//! TODO: maybe implement default variants
9//!
10
11use crate::*;
12
13use auth::*;
14use databases::*;
15use endpoint::{generator::*, *};
16
17/// Includes all the project's config
18#[derive(Clone, PartialEq, Constructor, Serialize, Deserialize, Getters, MutGetters, Debug)]
19#[getset(get = "pub", get_mut = "pub")]
20pub struct Project {
21    #[serde(flatten)]
22    config: Config,
23    compiler: Compiler,
24    server: Executor,
25}
26
27impl Default for Project {
28    fn default() -> Self {
29        Self {
30            config: Default::default(),
31            compiler: Default::default(),
32            server: Default::default(),
33        }
34    }
35}
36
37#[derive(Clone, PartialEq, Constructor, Serialize, Deserialize, Getters, MutGetters, Debug)]
38#[getset(get = "pub", get_mut = "pub")]
39/// General settings that will be shared across Waveless's components
40pub struct Config {
41    /// Project's name.
42    name: CompactString,
43
44    /// Contains all project's databases.
45    #[serde(default, skip_serializing_if = "should_skip_cheapvec")]
46    databases: CheapVec<DatabaseConfig, 0>,
47
48    /// Contains authentication settings.
49    #[serde(default, skip_serializing_if = "should_skip_option")]
50    authentication: Option<Authentication>,
51
52    /// Contains admin settings.
53    admin: Admin,
54}
55
56impl Default for Config {
57    fn default() -> Self {
58        Self {
59            name: "Example".into(),
60            databases: CheapVec::from_vec(vec![
61                Default::default(),
62                DatabaseConfig {
63                    id: "secondary".into(),
64                    is_primary: false,
65                    connection: Arc::new(ExternalDBConnectionConfig {
66                        id: "custom_database_driver".into(),
67                        connection: "...".into(),
68                    }),
69                    pool_min_size: None,
70                    pool_max_size: None,
71                },
72            ]),
73            authentication: Default::default(),
74            admin: Default::default(),
75        }
76    }
77}
78
79/// Compiler settings: these parameters will be used by the API's compiler exclusively
80#[derive(Clone, Constructor, Serialize, Deserialize, Getters, MutGetters, Debug)]
81#[getset(get = "pub", get_mut = "pub")]
82pub struct Compiler {
83    /// this is the directory where all the user defined endpoints will be located
84    endpoints_dir: CompactString,
85
86    /// Defines the compiler's strategy to analyze the databases' data schema
87    /// to generate endpoints.
88    /// NOTE: there might be many different types that implement the
89    /// [`AnyEndpointGenerator`] trait for a single database type.
90    /// For example, given a single database type (like MySQL), there might be an
91    /// ad-hoc schema discovery implementation and a simple endpoint geneator,
92    /// also, there might be a more complex [`AnyEndpointGenerator`] that
93    /// chains the internal MySQL schema analyzer and enhances the endpoint generation.
94    #[serde(default, skip_serializing_if = "should_skip_cheapvec")]
95    endpoint_generators: CheapVec<EndpointGeneratorConfig>,
96}
97
98impl PartialEq for Compiler {
99    fn eq(&self, other: &Self) -> bool {
100        self.endpoints_dir == other.endpoints_dir
101    }
102}
103
104impl Default for Compiler {
105    fn default() -> Self {
106        Self {
107            endpoints_dir: "./endpoints/".into(),
108            endpoint_generators: CheapVec::new_const(),
109        }
110    }
111}
112
113/// Runtime settings: these parameters will be used by the server exclusively
114#[derive(Clone, PartialEq, Constructor, Serialize, Deserialize, Getters, MutGetters, Debug)]
115#[getset(get = "pub", get_mut = "pub")]
116pub struct Executor {
117    /// can be set through cli parameters or env variables
118    #[serde(default, skip_serializing_if = "should_skip_option")]
119    listening_addr: Option<SocketAddr>,
120
121    /// the files on the specified path will be served
122    #[serde(default, skip_serializing_if = "should_skip_option")]
123    static_files: Option<CompactString>,
124
125    /// prefix for all api endpoints
126    api_prefix: CompactString,
127
128    /// the compiler will generate a checksum of the schema of each database, if this option is marked, the server executor will check whether the checksum on each start
129    check_databases_cheksums: bool,
130
131    /// set the http cache time header
132    http_cache_time: usize,
133}
134
135impl Default for Executor {
136    fn default() -> Self {
137        Self {
138            listening_addr: Some(SocketAddr::new("127.0.0.1".parse().unwrap(), 8080)),
139            static_files: Some("./static/".into()),
140            api_prefix: "/api".into(),
141            check_databases_cheksums: true,
142            http_cache_time: 0,
143        }
144    }
145}
146
147/// Defines a database to be used by Waveless
148#[serde_as]
149#[derive(Clone, Constructor, Serialize, Deserialize, Getters, MutGetters, Debug)]
150#[getset(get = "pub", get_mut = "pub")]
151pub struct DatabaseConfig {
152    /// Unique identifier of the database.
153    id: DatabaseId,
154
155    /// Indicates whether this database is primary (no need to set database id on auth, session and role storage).
156    #[serde(default, skip_serializing_if = "should_skip")]
157    is_primary: bool,
158
159    /// Defines credentials for all database backends.
160    #[serde_as(as = "IfIsHumanReadable<_, JsonString>")] // Explore müsli to avoid this.
161    connection: Arc<dyn AnyDatabaseConnectionConfig>,
162
163    /// Defines the minimum number of simultaneous connections, by default this will be half the `pool_max_size`.
164    #[serde(default, skip_serializing_if = "should_skip_option")]
165    pool_min_size: Option<usize>,
166
167    /// Defines the maximum number of simultaneous connections, by default this will be twice the number of available cores.
168    #[serde(default, skip_serializing_if = "should_skip_option")]
169    pool_max_size: Option<usize>,
170}
171
172impl PartialEq for DatabaseConfig {
173    fn eq(&self, other: &Self) -> bool {
174        self.id == other.id
175    }
176}
177
178impl Default for DatabaseConfig {
179    fn default() -> Self {
180        Self {
181            id: "main".into(),
182            is_primary: true,
183            connection: Arc::new(ExternalDBConnectionConfig {
184                id: "mysql".into(),
185                connection: "...".into(),
186            }),
187            pool_min_size: Some(std::thread::available_parallelism().unwrap().get() * 2),
188            pool_max_size: Some(std::thread::available_parallelism().unwrap().get() * 2),
189        }
190    }
191}
192
193/// TODO: add documentation.
194#[typetag::serde]
195#[async_trait]
196pub trait AnyDatabaseConnectionConfig: Any + BoxedAny + DynClone + Send + Sync + Debug {
197    async fn new_conn(
198        &self,
199        id: CompactString,
200        pool_min_size: Option<usize>,
201        pool_max_size: Option<usize>,
202    ) -> Result<(Arc<dyn AnyDatabaseConnection>, Box<dyn Any>)>;
203}
204
205/// TODO: load custom database drivers.
206#[derive(Clone, Serialize, Deserialize, BoxedAny, Display, Debug)]
207#[display("{:?}: {}", id, connection)]
208pub struct ExternalDBConnectionConfig {
209    id: ExternalDriverId,
210    connection: CompactString,
211}
212
213impl PartialEq for ExternalDBConnectionConfig {
214    fn eq(&self, other: &Self) -> bool {
215        self.id == other.id
216    }
217}
218
219#[typetag::serde]
220#[async_trait]
221impl AnyDatabaseConnectionConfig for ExternalDBConnectionConfig {
222    async fn new_conn(
223        &self,
224        _id: CompactString,
225        _pool_min_size: Option<usize>,
226        _pool_max_size: Option<usize>,
227    ) -> Result<(Arc<dyn AnyDatabaseConnection>, Box<dyn Any>)> {
228        todo!("Not implemented yet.");
229    }
230}
231
232/// Defines parameters for the endpoint generator.
233#[serde_as]
234#[derive(Clone, Constructor, Serialize, Deserialize, Getters, Debug)]
235#[getset(get = "pub")]
236pub struct EndpointGeneratorConfig {
237    /// Strategy to discover endpoints.
238    #[serde_as(as = "IfIsHumanReadable<_, JsonString>")] // Explore müsli to avoid this.
239    backend: Arc<dyn AnyEndpointGenerator>,
240
241    // Whether to generate a checksum of the schema if available.
242    #[serde(default, skip_serializing_if = "should_skip")]
243    checksum: bool,
244}
245
246/// The external module will use the project's hooks ti establish a database connection.
247/// TODO: load custom schema discovery drivers.
248#[derive(Clone, Constructor, Serialize, Deserialize, BoxedAny, Display, Debug)]
249#[display("{:?}: {:?}", id, config)]
250pub struct ExternalEndpointGenerator {
251    id: DataSchemaDiscoveryMethodId,
252    config: HashMap<CompactString, Bytes>,
253}
254
255impl PartialEq for ExternalEndpointGenerator {
256    fn eq(&self, other: &Self) -> bool {
257        self.id == other.id
258    }
259}
260
261impl AnyExt for ExternalEndpointGenerator {
262    fn name(&self) -> &str {
263        "external_endpoint_generator"
264    }
265}
266
267#[typetag::serde]
268#[async_trait]
269impl AnyEndpointGenerator for ExternalEndpointGenerator {
270    async fn generate(&self, _db_conns: DbConns) -> Result<(Endpoints, Option<Bytes>)> {
271        todo!("Not implemented yet.")
272    }
273
274    fn id(&self) -> Result<Bytes> {
275        todo!("Not implemented yet.")
276    }
277}
278
279/// Defines how the server executor can handle authentication
280#[serde_as]
281#[derive(Clone, Constructor, Serialize, Deserialize, Getters, MutGetters, Debug)]
282#[getset(get = "pub", get_mut = "pub")]
283pub struct Authentication {
284    /// All the available methods to authenticate.
285    #[serde(default, skip_serializing_if = "should_skip_cheapvec")]
286    #[serde_as(as = "IfIsHumanReadable<_, JsonString>")] // Explore müsli to avoid this.
287    backends: CheapVec<Arc<dyn AnyAuthenticationMethod>, 0>,
288
289    /// The method for manage sessions.
290    #[serde_as(as = "IfIsHumanReadable<_, JsonString>")] // Explore müsli to avoid this.
291    session: Arc<dyn AnySessionMethod>,
292
293    /// The method for manage roles.
294    #[serde_as(as = "IfIsHumanReadable<_, JsonString>")] // Explore müsli to avoid this.
295    role: Option<Arc<dyn AnyRoleMethod>>,
296
297    /// Default role when users sign up.
298    #[serde(default, skip_serializing_if = "should_skip_option")]
299    default_role: Option<CompactString>,
300
301    /// Whether to read the session token from the cookie header.
302    /// NOTE: if set, the session token will be read from the Authorization header
303    /// and will fallback to the cookie header.
304    session_cookie: bool,
305
306    /// Whether to allow user signup.
307    allow_signup: bool,
308}
309
310impl PartialEq for Authentication {
311    fn eq(&self, other: &Self) -> bool {
312        self.default_role == other.default_role && self.allow_signup == other.allow_signup
313    }
314}
315
316/// Defines admin settings and privileges on the server.
317#[derive(Clone, PartialEq, Constructor, Serialize, Deserialize, Getters, MutGetters, Debug)]
318#[getset(get = "pub", get_mut = "pub")]
319pub struct Admin {
320    /// Whether to enable the admin panel.
321    enable_panel: bool, // TODO
322
323    /// All roles that are considered admins.
324    #[serde(default, skip_serializing_if = "should_skip_cheapvec")]
325    allowed_roles: CheapVec<CompactString, 0>,
326
327    /// Whether to gather statistics or not.
328    statistics: bool, // TODO
329}
330
331impl Default for Admin {
332    fn default() -> Self {
333        Self {
334            enable_panel: true,
335            allowed_roles: CheapVec::from_vec(vec!["admin".into()]),
336            statistics: false,
337        }
338    }
339}
340
341#[cfg(test)]
342mod tests {
343    use super::*;
344
345    use eyre::Context;
346
347    #[test]
348    fn default_into_toml_and_back() -> Result<()> {
349        let project_config = Project::default();
350
351        let serialized = toml::to_string_pretty(&project_config)
352            .wrap_err("Cannot serialize default project config into TOML.")?;
353        let deserialized = toml::from_str::<Project>(&serialized)
354            .wrap_err("Cannot deserialize default TOML config.")?;
355
356        assert_eq!(project_config, deserialized);
357
358        println!("{:#?}\n", project_config);
359        println!("{}", serialized);
360        Ok(())
361    }
362}