Skip to main content

kcl_lib/
test_server.rs

1//! Types used to send data to the test server.
2
3use std::path::PathBuf;
4
5use kittycad_modeling_cmds::websocket::RawFile;
6
7use crate::ConnectionError;
8use crate::ExecError;
9use crate::KclError;
10use crate::KclErrorWithOutputs;
11use crate::Program;
12use crate::engine::new_zoo_client;
13use crate::errors::ExecErrorWithState;
14use crate::execution::EnvironmentRef;
15use crate::execution::ExecState;
16use crate::execution::ExecutorContext;
17use crate::execution::ExecutorSettings;
18
19#[derive(serde::Deserialize, serde::Serialize)]
20pub struct RequestBody {
21    pub kcl_program: String,
22    #[serde(default)]
23    pub test_name: String,
24}
25
26/// Executes a kcl program and takes a snapshot of the result.
27/// This returns the bytes of the snapshot.
28pub async fn execute_and_snapshot(code: &str, current_file: Option<PathBuf>) -> Result<image::DynamicImage, ExecError> {
29    let ctx = new_context(true, current_file).await?;
30    let program = Program::parse_no_errs(code).map_err(KclErrorWithOutputs::no_outputs)?;
31    let res = do_execute_and_snapshot(&ctx, program)
32        .await
33        .map(|(_, _, snap)| snap)
34        .map_err(|err| err.error);
35    ctx.close().await;
36    res
37}
38
39pub struct Snapshot3d {
40    /// Bytes of the snapshot.
41    pub image: image::DynamicImage,
42    /// Various GLTF files for the resulting export.
43    pub gltf: Vec<RawFile>,
44}
45
46/// Executes a kcl program and takes a snapshot of the result.
47pub async fn execute_and_snapshot_3d(code: &str, current_file: Option<PathBuf>) -> Result<Snapshot3d, ExecError> {
48    let ctx = new_context(true, current_file).await?;
49    let program = Program::parse_no_errs(code).map_err(KclErrorWithOutputs::no_outputs)?;
50    let image = do_execute_and_snapshot(&ctx, program)
51        .await
52        .map(|(_, _, snap)| snap)
53        .map_err(|err| err.error)?;
54    let gltf_res = ctx
55        .export(kittycad_modeling_cmds::format::OutputFormat3d::Gltf(Default::default()))
56        .await;
57    let gltf = match gltf_res {
58        Err(err) if err.message() == "Nothing to export" => Vec::new(),
59        Err(err) => {
60            eprintln!("Error exporting: {}", err.message());
61            Vec::new()
62        }
63        Ok(x) => x,
64    };
65    ctx.close().await;
66    Ok(Snapshot3d { image, gltf })
67}
68/// Executes a kcl program and takes a snapshot of the result.
69/// This returns the bytes of the snapshot.
70#[cfg(test)]
71pub async fn execute_and_snapshot_ast(
72    ast: Program,
73    current_file: Option<PathBuf>,
74    with_export_step: bool,
75) -> Result<
76    (
77        ExecState,
78        ExecutorContext,
79        EnvironmentRef,
80        image::DynamicImage,
81        Option<Vec<u8>>,
82    ),
83    ExecErrorWithState,
84> {
85    let ctx = new_context(true, current_file).await?;
86    let (exec_state, env, img) = match do_execute_and_snapshot(&ctx, ast).await {
87        Ok((exec_state, env_ref, img)) => (exec_state, env_ref, img),
88        Err(err) => {
89            // If there was an error executing the program, return it.
90            // Close the context to avoid any resource leaks.
91            ctx.close().await;
92            return Err(err);
93        }
94    };
95    let mut step = None;
96    if with_export_step {
97        let files = match ctx.export_step(true).await {
98            Ok(f) => f,
99            Err(err) => {
100                // Close the context to avoid any resource leaks.
101                ctx.close().await;
102                return Err(ExecErrorWithState::new(
103                    ExecError::BadExport(format!("Export failed: {err:?}")),
104                    exec_state.clone(),
105                ));
106            }
107        };
108
109        step = files.into_iter().next().map(|f| f.contents);
110    }
111    ctx.close().await;
112    Ok((exec_state, ctx, env, img, step))
113}
114
115pub async fn execute_and_snapshot_no_auth(
116    code: &str,
117    current_file: Option<PathBuf>,
118) -> Result<(image::DynamicImage, EnvironmentRef), ExecError> {
119    let ctx = new_context(false, current_file).await?;
120    let program = Program::parse_no_errs(code).map_err(KclErrorWithOutputs::no_outputs)?;
121    let res = do_execute_and_snapshot(&ctx, program)
122        .await
123        .map(|(_, env_ref, snap)| (snap, env_ref))
124        .map_err(|err| err.error);
125    ctx.close().await;
126    res
127}
128
129async fn do_execute_and_snapshot(
130    ctx: &ExecutorContext,
131    program: Program,
132) -> Result<(ExecState, EnvironmentRef, image::DynamicImage), ExecErrorWithState> {
133    let mut exec_state = ExecState::new(ctx);
134    let result = ctx
135        .run(&program, &mut exec_state)
136        .await
137        .map_err(|err| ExecErrorWithState::new(err.into(), exec_state.clone()))?;
138    for e in exec_state.errors() {
139        if e.severity.is_err() {
140            return Err(ExecErrorWithState::new(
141                KclErrorWithOutputs::no_outputs(KclError::new_semantic(e.clone().into())).into(),
142                exec_state.clone(),
143            ));
144        }
145    }
146    let snapshot_png_bytes = ctx
147        .prepare_snapshot()
148        .await
149        .map_err(|err| ExecErrorWithState::new(err, exec_state.clone()))?
150        .contents
151        .0;
152
153    // Decode the snapshot, return it.
154    let img = image::ImageReader::new(std::io::Cursor::new(snapshot_png_bytes))
155        .with_guessed_format()
156        .map_err(|e| ExecError::BadPng(e.to_string()))
157        .and_then(|x| x.decode().map_err(|e| ExecError::BadPng(e.to_string())))
158        .map_err(|err| ExecErrorWithState::new(err, exec_state.clone()))?;
159
160    Ok((exec_state, result.0, img))
161}
162
163pub async fn new_context(with_auth: bool, current_file: Option<PathBuf>) -> Result<ExecutorContext, ConnectionError> {
164    let mut client = new_zoo_client(if with_auth { None } else { Some("bad_token".to_string()) }, None)
165        .map_err(ConnectionError::CouldNotMakeClient)?;
166    if !with_auth {
167        // Use prod, don't override based on env vars.
168        // We do this so even in the engine repo, tests that need to run with
169        // no auth can fail in the same way as they would in prod.
170        client.set_base_url("https://api.zoo.dev".to_string());
171    }
172
173    let mut settings = ExecutorSettings {
174        highlight_edges: true,
175        enable_ssao: false,
176        show_grid: false,
177        replay: None,
178        project_directory: None,
179        current_file: None,
180        fixed_size_grid: true,
181    };
182    if let Some(current_file) = current_file {
183        settings.with_current_file(crate::TypedPath(current_file));
184    }
185    let ctx = ExecutorContext::new(&client, settings)
186        .await
187        .map_err(ConnectionError::Establishing)?;
188    Ok(ctx)
189}
190
191pub async fn execute_and_export_step(
192    code: &str,
193    current_file: Option<PathBuf>,
194) -> Result<
195    (
196        ExecState,
197        EnvironmentRef,
198        Vec<kittycad_modeling_cmds::websocket::RawFile>,
199    ),
200    ExecErrorWithState,
201> {
202    let ctx = new_context(true, current_file).await?;
203    let mut exec_state = ExecState::new(&ctx);
204    let program = Program::parse_no_errs(code)
205        .map_err(|err| ExecErrorWithState::new(KclErrorWithOutputs::no_outputs(err).into(), exec_state.clone()))?;
206    let result = ctx
207        .run(&program, &mut exec_state)
208        .await
209        .map_err(|err| ExecErrorWithState::new(err.into(), exec_state.clone()))?;
210    for e in exec_state.errors() {
211        if e.severity.is_err() {
212            return Err(ExecErrorWithState::new(
213                KclErrorWithOutputs::no_outputs(KclError::new_semantic(e.clone().into())).into(),
214                exec_state.clone(),
215            ));
216        }
217    }
218
219    let files = match ctx.export_step(true).await {
220        Ok(f) => f,
221        Err(err) => {
222            return Err(ExecErrorWithState::new(
223                ExecError::BadExport(format!("Export failed: {err:?}")),
224                exec_state.clone(),
225            ));
226        }
227    };
228
229    ctx.close().await;
230
231    Ok((exec_state, result.0, files))
232}