Skip to main content

waveless_commons/
object.rs

1// Waveless
2// Copyright (C) 2026 Oscar Alvarez Gonzalez
3
4//!
5//! -- The Waveless's binary format --
6//! Waveless follows a compiler-like design:
7//! - There is the frontend/compiler, which generates the binary that represents the whole api: all endpoints all server configuration, database checksums...
8//!   This is built upon user-defined endpoints and automatically generated endpoints from various discovery strategies.
9//! - The server executor/runtime, which loads the Waveless's project's binary and serves all endpoints, static files, interfaces with every database, generates statistics, manages authentication and session logic, admin panel...
10//! Note that when the binary is built, the magic bytes are appended to the beginning of the file
11//!
12use crate::*;
13
14use endpoint::{generator::*, *};
15use project::*;
16
17/// The project's build artifact.
18#[derive(Clone, PartialEq, Constructor, Serialize, Deserialize, Getters, MutGetters, Debug)]
19#[getset(get = "pub", get_mut = "pub")]
20pub struct ObjectArtifact {
21    /// Contains general settings shared with the frontend/compiler.
22    config: Config,
23
24    /// Specific executor (server) settings.
25    executor: project::Executor,
26
27    /// Defines all the API endpoints.
28    endpoints: Endpoints,
29
30    /// Contains all the databases' checksum.
31    /// TODO: in the future there will be a method to checksum all the database's
32    /// schema regardless of whether they have been 'discovered'.
33    databases_checksums: CheapVec<EndpointGeneratorChecksum, 0>,
34}
35
36impl ObjectArtifact {
37    /// Serializes the binary and appends the magic bytes to the beginning of the buffer.
38    /// NOTE: the `BINARY_MODE` flag is set as a workaround of the issue <https://github.com/serde-rs/serde/issues/1732>,
39    /// so now we can safely serialize all repository's structures and enums regardless whether the serializer being
40    /// self-descriptive or not.
41    pub fn encode_binary(&self) -> Result<Bytes> {
42        BINARY_MODE.set(true);
43        debug!(
44            "Binary mode is set, as the serializer requires `#[serde(skip_serializing_if = '...')]` to be disabled."
45        );
46        let mut buffer = self.encode().map_err(|error| eyre!(error))?;
47        buffer.insert_from_slice(0, BINARY_MAGIC);
48        BINARY_MODE.set(false);
49        Ok(buffer)
50    }
51
52    /// Removes the magic bytes from the beginning of the file and deserializes the binary.
53    pub fn decode_binary(buffer: &Bytes) -> Result<Self> {
54        ObjectArtifact::decode(&buffer[BINARY_MAGIC.len()..]).map_err(|error| eyre!(error))
55    }
56}
57
58/// Default implementation for testing and validation.
59impl Default for ObjectArtifact {
60    fn default() -> Self {
61        Self {
62            config: Default::default(),
63            executor: Default::default(),
64            endpoints: Endpoints::new_unchecked(CheapVec::from_vec(vec![Endpoint::default()])),
65            databases_checksums: CheapVec::new_const(),
66        }
67    }
68}
69
70/// Matches a schema with it's checksum.
71#[serde_as]
72#[derive(Clone, Constructor, Serialize, Deserialize, Getters, Debug)]
73#[getset(get = "pub")]
74pub struct EndpointGeneratorChecksum {
75    /// Strategy used to discover the endpoints.
76    #[serde_as(as = "IfIsHumanReadable<_, JsonString>")] // Explore müsli to avoid this.
77    pub(crate) method: Arc<dyn AnyEndpointGenerator>,
78
79    pub(crate) checksum: Bytes,
80}
81
82impl PartialEq for EndpointGeneratorChecksum {
83    fn eq(&self, other: &Self) -> bool {
84        self.method().name() == other.method().name() && self.checksum == other.checksum
85    }
86}
87
88/// Default implementation for testing and validation
89impl Default for EndpointGeneratorChecksum {
90    fn default() -> Self {
91        Self {
92            method: Arc::new(ExternalEndpointGenerator::new(
93                CompactString::const_new(""),
94                HashMap::new(),
95            )),
96            checksum: CheapVec::from_elem(0, 8),
97        }
98    }
99}
100
101/// Note that for this test `postcard_codec` flag must be set, this will be disable some serde attributes as skipping field serialization and enum type format.
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    use eyre::Context;
107
108    #[test]
109    fn default_into_bin_and_back() -> Result<()> {
110        let build = ObjectArtifact::default();
111
112        let serialized = build
113            .encode_binary()
114            .wrap_err("Cannot serialize project build.")?;
115
116        let deserialized = ObjectArtifact::decode_binary(&serialized)
117            .context("Cannot deserialize project build.")?;
118
119        assert_eq!(build, deserialized);
120
121        println!("Build file structure: {:#?}\n", build);
122        println!("Binary representation: {:?}", serialized);
123
124        Ok(())
125    }
126}