Skip to main content

waveless_compiler/
workspace.rs

1// Waveless
2// Copyright (C) 2026 Oscar Alvarez Gonzalez
3
4//!
5//! The Waveless' project's builder.
6//! The builder tasks are:
7//! 1. Serialize the `project.toml` file.
8//! 2. Load user's endpoints.
9//! 3. Discover the endpoints (optional).
10//! 4. Hash the current state of the databases (optional).
11//! 5. Build and serialize the project's binary file.
12//!
13use crate::*;
14
15use generator::*;
16
17/// Builds the project in the current path (if no `project.toml` file is present in the current directory it will be searched in parent directories)
18#[instrument(skip_all)]
19pub async fn load<T: 'static>() -> Result<Either<ObjectArtifact, Bytes>> {
20    let cx = CompilerCx::acquire();
21
22    let project = cx.project();
23    let workspace_root = cx.workspace_root();
24
25    debug!(
26        "Started building at {} with the following settings {:#?}.",
27        chrono::Local::now(),
28        project
29    );
30
31    // Deserializes user's endpoints.
32    let mut endpoints = Endpoints::new_unchecked(CheapVec::new_const());
33    {
34        let endpoints_dir = workspace_root.join(project.compiler().endpoints_dir());
35
36        let endpoints_path = read_dir(endpoints_dir)
37            .context("Unexpected error, the endpoints directory cannot be listed.")?;
38
39        for endpoint_path in endpoints_path {
40            let endpoint_path = endpoint_path?;
41            match read(endpoint_path.path()) {
42                Ok(file_buffer) => {
43                    match toml::from_slice::<Endpoints>(&file_buffer) {
44                        Ok(new_endpoints) => endpoints.merge(new_endpoints)?,
45                        Err(err) => Err(err).wrap_err(format!(
46                            "Cannot deserialize the endpoints definition file '{}'.",
47                            endpoint_path.file_name().display(),
48                        ))?,
49                    };
50                }
51                Err(err) => Err(err).wrap_err(format!(
52                    "Cannot open the endpoints definition file '{}'.",
53                    endpoint_path.file_name().display(),
54                ))?,
55            }
56        }
57
58        debug!("Deserialized user's endpoints: {:#?}", endpoints);
59    }
60
61    // Discovers the endpoints and checksums the database's schema.
62    let generated_endpoints = GeneratedEndpoints::generate().await?;
63
64    if create_dir(workspace_root.join(".generated_endpoints")).is_ok() {
65        debug!("'.generated_endpoints' directory does't exist, a new one will be created.")
66    };
67
68    let mut endpoint_generator_checksums = CheapVec::new_const();
69
70    for (generator_id, (new_endpoints, checksum)) in generated_endpoints.get() {
71        let target_file = workspace_root
72            .join(".generated_endpoints")
73            .join(format!("{}.toml", hex::encode(generator_id)));
74
75        write(
76            &target_file,
77            toml::to_string_pretty(&new_endpoints)?.as_bytes(),
78        )?;
79
80        info!(
81            "Generated endpoints from `{}` were dumped into `{}` ({}).",
82            hex::encode(generator_id),
83            target_file.display(),
84            String::from_utf8(generator_id.to_vec()).unwrap_or("?".into())
85        );
86
87        if let Some(checksum) = checksum {
88            endpoint_generator_checksums.push(checksum.to_owned());
89        }
90
91        endpoints.merge(new_endpoints.to_owned())?;
92    }
93
94    // Serializes the project's build.
95    let build = ObjectArtifact::new(
96        project.config().to_owned(),
97        project.server().to_owned(),
98        endpoints,
99        endpoint_generator_checksums,
100    );
101
102    if TypeId::of::<T>() == TypeId::of::<Bytes>() {
103        let buff = build.encode_binary()?;
104
105        debug!(
106            "Finished building project successfully at {}.",
107            chrono::Local::now(),
108        );
109
110        Ok(Right(buff))
111    } else if TypeId::of::<T>() == TypeId::of::<ObjectArtifact>() {
112        Ok(Left(build))
113    } else {
114        panic!("Unexpected type.")
115    }
116}
117
118/// Generates the binary's file from the provided buffer.
119pub fn binary_file_from_buff(buff: Bytes) -> Result<ResultContext> {
120    let cx = CompilerCx::acquire();
121
122    let project = cx.project();
123    let workspace_root = cx.workspace_root();
124
125    // Set the build file's name a combination of its CRC32 hash and the current timestamp
126    let build_name = format!(
127        "{}_{}_{}.wv",
128        project.config().name(),
129        chrono::Local::now().format("%d_%m_%Y_%H_%M"),
130        crc32fast::hash(buff.as_slice())
131    );
132
133    let target_file = workspace_root.join("target").join(build_name);
134
135    if create_dir(workspace_root.join("target")).is_ok() {
136        debug!("`target` directory doesn't exist, a new one will be created.")
137    };
138
139    write(&target_file, buff)?;
140
141    debug!("Emitted build file on {}", target_file.display());
142
143    Ok(format!(
144        "'{}' has been built at {}",
145        project.config().name(),
146        target_file
147            .file_name()
148            .ok_or(eyre!("No build file name."))?
149            .display()
150    )
151    .into())
152}