escher-execution-engine 0.1.2

Production-ready async execution engine for system commands
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Command building utilities
//!
//! Converts Command enum to tokio::process::Command for execution.

use crate::errors::{ExecutionError, ValidationError};
use crate::types::{Command, ExecutionRequest};
use std::path::{Path, PathBuf};
use tokio::process::Command as TokioCommand;

/// Build tokio::process::Command from ExecutionRequest
pub fn build_command(request: &ExecutionRequest) -> Result<TokioCommand, ExecutionError> {
    let mut cmd = match &request.command {
        Command::Shell { command, shell } => {
            validate_shell_command(command)?;
            build_shell_command(command, shell)
        }
        Command::Exec { program, args } => {
            validate_exec_command(program)?;
            build_exec_command(program, args)
        }
        Command::Script { path, interpreter } => {
            validate_script_path(path)?;
            build_script_command(path, interpreter)?
        }
        Command::AwsCli {
            service,
            operation,
            args,
            profile,
            region,
        } => {
            validate_aws_cli(service, operation)?;
            build_aws_cli_command(
                service,
                operation,
                args,
                profile.as_deref(),
                region.as_deref(),
            )
        }
    };

    // Set environment variables
    for (key, value) in &request.env {
        cmd.env(key, value);
    }

    // Set working directory
    if let Some(working_dir) = &request.working_dir {
        validate_working_directory(working_dir)?;
        cmd.current_dir(working_dir);
    }

    // Configure stdout/stderr
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    // Kill on drop (ensure child processes are cleaned up)
    cmd.kill_on_drop(true);

    Ok(cmd)
}

// ============================================================================
// Command builders for each variant
// ============================================================================

fn build_shell_command(command: &str, shell: &str) -> TokioCommand {
    let mut cmd = TokioCommand::new(shell);

    // Platform-specific shell invocation
    if cfg!(target_os = "windows") {
        if shell == "powershell" {
            cmd.args(["-Command", command]);
        } else {
            // cmd.exe
            cmd.args(["/C", command]);
        }
    } else {
        // Unix shells (bash, sh, zsh, etc.)
        cmd.args(["-c", command]);
    }

    cmd
}

fn build_exec_command(program: &str, args: &[String]) -> TokioCommand {
    let mut cmd = TokioCommand::new(program);
    cmd.args(args);
    cmd
}

fn build_script_command(
    path: &PathBuf,
    interpreter: &Option<String>,
) -> Result<TokioCommand, ExecutionError> {
    if let Some(interp) = interpreter {
        // Explicit interpreter specified
        let mut cmd = TokioCommand::new(interp);
        cmd.arg(path);
        Ok(cmd)
    } else {
        // Try to detect interpreter from shebang or use script directly
        #[cfg(unix)]
        {
            use std::fs::File;
            use std::io::{BufRead, BufReader};

            // Check if executable
            use std::os::unix::fs::PermissionsExt;
            let metadata = std::fs::metadata(path).map_err(ExecutionError::Io)?;
            let permissions = metadata.permissions();

            if permissions.mode() & 0o111 != 0 {
                // Script is executable, run directly
                Ok(TokioCommand::new(path))
            } else {
                // Try to read shebang
                let file = File::open(path).map_err(ExecutionError::Io)?;
                let mut reader = BufReader::new(file);
                let mut first_line = String::new();
                reader
                    .read_line(&mut first_line)
                    .map_err(ExecutionError::Io)?;

                if first_line.starts_with("#!") {
                    let interp_path = first_line.trim_start_matches("#!").trim();
                    let mut cmd = TokioCommand::new(interp_path);
                    cmd.arg(path);
                    Ok(cmd)
                } else {
                    Err(ValidationError::ScriptNotExecutable(path.clone()).into())
                }
            }
        }

        #[cfg(not(unix))]
        {
            // On Windows, try to execute directly
            Ok(TokioCommand::new(path))
        }
    }
}

fn build_aws_cli_command(
    service: &str,
    operation: &str,
    args: &[String],
    profile: Option<&str>,
    region: Option<&str>,
) -> TokioCommand {
    let mut cmd = TokioCommand::new("aws");

    // Add service and operation
    cmd.arg(service);
    cmd.arg(operation);

    // Add optional profile
    if let Some(prof) = profile {
        cmd.arg("--profile");
        cmd.arg(prof);
    }

    // Add optional region
    if let Some(reg) = region {
        cmd.arg("--region");
        cmd.arg(reg);
    }

    // Add additional args
    cmd.args(args);

    // Always output JSON
    cmd.arg("--output");
    cmd.arg("json");

    cmd
}

// ============================================================================
// Validation functions
// ============================================================================

fn validate_shell_command(command: &str) -> Result<(), ValidationError> {
    if command.trim().is_empty() {
        return Err(ValidationError::EmptyCommand);
    }
    Ok(())
}

fn validate_exec_command(program: &str) -> Result<(), ValidationError> {
    if program.trim().is_empty() {
        return Err(ValidationError::EmptyCommand);
    }
    Ok(())
}

fn validate_script_path(path: &PathBuf) -> Result<(), ValidationError> {
    if !path.exists() {
        return Err(ValidationError::ScriptNotFound(path.clone()));
    }
    if !path.is_file() {
        return Err(ValidationError::InvalidCommand(format!(
            "Script path is not a file: {path:?}"
        )));
    }
    Ok(())
}

fn validate_aws_cli(service: &str, operation: &str) -> Result<(), ValidationError> {
    if service.trim().is_empty() {
        return Err(ValidationError::MissingField("service".to_string()));
    }
    if operation.trim().is_empty() {
        return Err(ValidationError::MissingField("operation".to_string()));
    }
    Ok(())
}

fn validate_working_directory(path: &Path) -> Result<(), ValidationError> {
    if !path.exists() {
        return Err(ValidationError::WorkingDirNotFound(path.to_path_buf()));
    }
    if !path.is_dir() {
        return Err(ValidationError::InvalidWorkingDir(path.to_path_buf()));
    }
    Ok(())
}

// ============================================================================
// Helper functions
// ============================================================================

/// Get command string representation for logging
pub fn command_to_string(cmd: &Command) -> String {
    match cmd {
        Command::Shell { command, shell } => {
            format!("{shell} -c '{command}'")
        }
        Command::Exec { program, args } => {
            format!("{} {}", program, args.join(" "))
        }
        Command::Script { path, interpreter } => {
            if let Some(interp) = interpreter {
                format!("{interp} {path:?}")
            } else {
                format!("{path:?}")
            }
        }
        Command::AwsCli {
            service,
            operation,
            args,
            profile,
            region,
        } => {
            let mut parts = vec!["aws".to_string(), service.clone(), operation.clone()];
            if let Some(prof) = profile {
                parts.push(format!("--profile {prof}"));
            }
            if let Some(reg) = region {
                parts.push(format!("--region {reg}"));
            }
            parts.extend(args.clone());
            parts.join(" ")
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use uuid::Uuid;

    fn create_test_request(command: Command) -> ExecutionRequest {
        ExecutionRequest {
            id: Uuid::new_v4(),
            command,
            env: HashMap::new(),
            working_dir: None,
            timeout_ms: None,
            output_log_path: None,
            metadata: Default::default(),
        }
    }

    #[test]
    fn test_build_shell_command() {
        let request = create_test_request(Command::Shell {
            command: "echo hello".to_string(),
            shell: "bash".to_string(),
        });

        let cmd = build_command(&request).unwrap();
        let program = cmd.as_std().get_program();

        #[cfg(unix)]
        assert_eq!(program, "bash");

        #[cfg(windows)]
        assert!(program.to_str().unwrap().contains("bash"));
    }

    #[test]
    fn test_build_exec_command() {
        let request = create_test_request(Command::Exec {
            program: "ls".to_string(),
            args: vec!["-la".to_string()],
        });

        let cmd = build_command(&request).unwrap();
        let program = cmd.as_std().get_program();
        assert_eq!(program, "ls");
    }

    #[test]
    fn test_build_aws_cli_command() {
        let request = create_test_request(Command::AwsCli {
            service: "ec2".to_string(),
            operation: "describe-instances".to_string(),
            args: vec!["--max-items".to_string(), "10".to_string()],
            profile: Some("prod".to_string()),
            region: Some("us-west-2".to_string()),
        });

        let cmd = build_command(&request).unwrap();
        let program = cmd.as_std().get_program();
        assert_eq!(program, "aws");
    }

    #[test]
    fn test_command_with_env_vars() {
        let mut env = HashMap::new();
        env.insert("TEST_VAR".to_string(), "test_value".to_string());

        let mut request = create_test_request(Command::Shell {
            command: "echo $TEST_VAR".to_string(),
            shell: "bash".to_string(),
        });
        request.env = env;

        let cmd = build_command(&request).unwrap();
        // Environment variables are set on the command
        assert!(cmd.as_std().get_envs().any(|(k, _)| k == "TEST_VAR"));
    }

    #[test]
    fn test_validate_empty_shell_command() {
        let err = validate_shell_command("   ").unwrap_err();
        assert!(matches!(err, ValidationError::EmptyCommand));
    }

    #[test]
    fn test_validate_empty_program() {
        let err = validate_exec_command("").unwrap_err();
        assert!(matches!(err, ValidationError::EmptyCommand));
    }

    #[test]
    fn test_validate_missing_script() {
        let path = PathBuf::from("/nonexistent/script.sh");
        let err = validate_script_path(&path).unwrap_err();
        assert!(matches!(err, ValidationError::ScriptNotFound(_)));
    }

    #[test]
    fn test_validate_aws_cli_missing_service() {
        let err = validate_aws_cli("", "describe-instances").unwrap_err();
        assert!(matches!(err, ValidationError::MissingField(_)));
    }

    #[test]
    fn test_command_to_string_shell() {
        let cmd = Command::Shell {
            command: "ls -la".to_string(),
            shell: "bash".to_string(),
        };
        let s = command_to_string(&cmd);
        assert!(s.contains("bash"));
        assert!(s.contains("ls -la"));
    }

    #[test]
    fn test_command_to_string_exec() {
        let cmd = Command::Exec {
            program: "python3".to_string(),
            args: vec!["script.py".to_string(), "--verbose".to_string()],
        };
        let s = command_to_string(&cmd);
        assert!(s.contains("python3"));
        assert!(s.contains("script.py"));
        assert!(s.contains("--verbose"));
    }

    #[test]
    fn test_command_to_string_aws_cli() {
        let cmd = Command::AwsCli {
            service: "s3".to_string(),
            operation: "ls".to_string(),
            args: vec![],
            profile: Some("dev".to_string()),
            region: Some("us-east-1".to_string()),
        };
        let s = command_to_string(&cmd);
        assert!(s.contains("aws"));
        assert!(s.contains("s3"));
        assert!(s.contains("ls"));
        assert!(s.contains("--profile dev"));
        assert!(s.contains("--region us-east-1"));
    }
}