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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Execution Engine Types
//!
//! Core data types for execution requests and results.
//! See docs/types.md for complete reference.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::Duration;
use uuid::Uuid;

// ============================================================================
// Input Types
// ============================================================================

/// Single command execution request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionRequest {
    /// Unique identifier for this request
    pub id: Uuid,

    /// Command to execute
    pub command: Command,

    /// Environment variables
    #[serde(default)]
    pub env: HashMap<String, String>,

    /// Working directory (optional)
    pub working_dir: Option<PathBuf>,

    /// Timeout in milliseconds (optional)
    pub timeout_ms: Option<u64>,

    /// Optional path to save stdout/stderr output to a file
    pub output_log_path: Option<PathBuf>,

    /// Metadata for tracking
    #[serde(default)]
    pub metadata: ExecutionMetadata,
}

/// Plan for executing multiple commands
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionPlan {
    /// Unique identifier for this plan
    pub id: Uuid,

    /// Human-readable description
    pub description: String,

    /// Execution strategy
    pub strategy: ExecutionStrategy,

    /// Commands to execute
    pub commands: Vec<ExecutionRequest>,

    /// Metadata
    #[serde(default)]
    pub metadata: ExecutionMetadata,
}

/// Standardized command types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Command {
    /// Execute a script file
    Script {
        path: PathBuf,
        interpreter: Option<String>,
    },

    /// Execute command with arguments
    Exec { program: String, args: Vec<String> },

    /// Execute shell command string
    Shell {
        command: String,
        #[serde(default = "default_shell")]
        shell: String,
    },

    /// AWS CLI command (convenience)
    AwsCli {
        service: String,
        operation: String,
        #[serde(default)]
        args: Vec<String>,
        profile: Option<String>,
        region: Option<String>,
    },
}

fn default_shell() -> String {
    if cfg!(target_os = "windows") {
        "powershell".to_string()
    } else {
        "bash".to_string()
    }
}

/// Strategy for executing multiple commands
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ExecutionStrategy {
    /// Execute sequentially, stop on error
    Serial {
        #[serde(default = "default_stop_on_error")]
        stop_on_error: bool,
    },

    /// Execute concurrently
    Parallel { max_concurrency: Option<usize> },

    /// Execute based on dependency graph
    DependencyGraph {
        dependencies: HashMap<usize, Vec<usize>>,
    },
}

fn default_stop_on_error() -> bool {
    true
}

// ============================================================================
// Output Types
// ============================================================================

/// Result of a single command execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionResult {
    /// Execution ID
    pub id: Uuid,

    /// Final status
    pub status: ExecutionStatus,

    /// Success flag (exit_code == 0)
    pub success: bool,

    /// Process exit code
    pub exit_code: i32,

    /// Standard output
    pub stdout: String,

    /// Standard error
    pub stderr: String,

    /// Execution duration
    pub duration: Duration,

    /// Start timestamp
    pub started_at: DateTime<Utc>,

    /// Completion timestamp
    pub completed_at: Option<DateTime<Utc>>,

    /// Error message (if failed)
    pub error: Option<String>,

    /// Path to overflow stdout file (when using StreamToFile strategy)
    pub stdout_overflow_file: Option<PathBuf>,

    /// Path to overflow stderr file (when using StreamToFile strategy)
    pub stderr_overflow_file: Option<PathBuf>,
}

/// Result of executing a plan
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlanExecutionResult {
    /// Plan ID
    pub plan_id: Uuid,

    /// Overall status
    pub status: ExecutionStatus,

    /// Results for each command
    pub results: Vec<ExecutionResult>,

    /// Total duration
    pub total_duration: Duration,

    /// Statistics
    pub stats: ExecutionStats,
}

/// Status enum for executions
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionStatus {
    Pending,
    Running,
    Completed,
    Failed,
    Cancelled,
    Timeout,
}

impl ExecutionStatus {
    /// Check if status is terminal (execution is finished)
    #[must_use]
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            ExecutionStatus::Completed
                | ExecutionStatus::Failed
                | ExecutionStatus::Cancelled
                | ExecutionStatus::Timeout
        )
    }
}

/// Statistics for plan execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionStats {
    pub total: usize,
    pub completed: usize,
    pub failed: usize,
    pub cancelled: usize,
    pub timeout: usize,
}

impl ExecutionStats {
    /// Create new empty stats
    #[must_use]
    pub fn new(total: usize) -> Self {
        Self {
            total,
            completed: 0,
            failed: 0,
            cancelled: 0,
            timeout: 0,
        }
    }

    /// Update stats based on status
    pub fn update(&mut self, status: ExecutionStatus) {
        match status {
            ExecutionStatus::Completed => self.completed += 1,
            ExecutionStatus::Failed => self.failed += 1,
            ExecutionStatus::Cancelled => self.cancelled += 1,
            ExecutionStatus::Timeout => self.timeout += 1,
            _ => {}
        }
    }
}

// ============================================================================
// Metadata Types
// ============================================================================

/// Metadata for tracking executions
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ExecutionMetadata {
    /// Source of request
    pub source: Option<String>,

    /// Related conversation ID
    pub conversation_id: Option<Uuid>,

    /// Custom tags
    #[serde(default)]
    pub tags: HashMap<String, String>,
}

/// Summary information for listing executions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionSummary {
    pub id: Uuid,
    pub status: ExecutionStatus,
    pub started_at: DateTime<Utc>,
    pub duration: Option<Duration>,
}

// ============================================================================
// Internal Types (not part of public API)
// ============================================================================

/// Internal state tracking
#[derive(Debug, Clone)]
pub struct ExecutionState {
    pub id: Uuid,
    pub request: ExecutionRequest,
    pub status: ExecutionStatus,
    pub started_at: DateTime<Utc>,
    pub completed_at: Option<DateTime<Utc>>,
    pub stdout: String,
    pub stderr: String,
    pub exit_code: Option<i32>,
    pub error: Option<String>,
    pub stdout_overflow_file: Option<PathBuf>,
    pub stderr_overflow_file: Option<PathBuf>,
}

impl ExecutionState {
    /// Create new execution state
    #[must_use]
    pub fn new(request: ExecutionRequest) -> Self {
        Self {
            id: request.id,
            request,
            status: ExecutionStatus::Pending,
            started_at: Utc::now(),
            completed_at: None,
            stdout: String::new(),
            stderr: String::new(),
            exit_code: None,
            error: None,
            stdout_overflow_file: None,
            stderr_overflow_file: None,
        }
    }

    /// Convert to ExecutionResult
    #[must_use]
    pub fn to_result(&self) -> ExecutionResult {
        let duration = if let Some(completed) = self.completed_at {
            (completed - self.started_at)
                .to_std()
                .unwrap_or(Duration::from_secs(0))
        } else {
            Duration::from_secs(0)
        };

        ExecutionResult {
            id: self.id,
            status: self.status,
            success: self.exit_code == Some(0),
            exit_code: self.exit_code.unwrap_or(-1),
            stdout: self.stdout.clone(),
            stderr: self.stderr.clone(),
            duration,
            started_at: self.started_at,
            completed_at: self.completed_at,
            error: self.error.clone(),
            stdout_overflow_file: self.stdout_overflow_file.clone(),
            stderr_overflow_file: self.stderr_overflow_file.clone(),
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_execution_status_terminal() {
        assert!(!ExecutionStatus::Pending.is_terminal());
        assert!(!ExecutionStatus::Running.is_terminal());
        assert!(ExecutionStatus::Completed.is_terminal());
        assert!(ExecutionStatus::Failed.is_terminal());
        assert!(ExecutionStatus::Cancelled.is_terminal());
        assert!(ExecutionStatus::Timeout.is_terminal());
    }

    #[test]
    fn test_execution_stats_update() {
        let mut stats = ExecutionStats::new(5);
        assert_eq!(stats.total, 5);
        assert_eq!(stats.completed, 0);

        stats.update(ExecutionStatus::Completed);
        assert_eq!(stats.completed, 1);

        stats.update(ExecutionStatus::Failed);
        assert_eq!(stats.failed, 1);

        stats.update(ExecutionStatus::Timeout);
        assert_eq!(stats.timeout, 1);
    }

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

        let json = serde_json::to_string(&cmd).unwrap();
        assert!(json.contains("shell"));
        assert!(json.contains("echo hello"));

        let deserialized: Command = serde_json::from_str(&json).unwrap();
        match deserialized {
            Command::Shell { command, shell } => {
                assert_eq!(command, "echo hello");
                assert_eq!(shell, "bash");
            }
            _ => panic!("Wrong variant"),
        }
    }

    #[test]
    fn test_execution_request_default_fields() {
        let request = ExecutionRequest {
            id: Uuid::new_v4(),
            command: Command::Shell {
                command: "ls".to_string(),
                shell: "bash".to_string(),
            },
            env: HashMap::new(),
            working_dir: None,
            timeout_ms: None,
            output_log_path: None,
            metadata: ExecutionMetadata::default(),
        };

        assert!(request.env.is_empty());
        assert!(request.working_dir.is_none());
        assert!(request.timeout_ms.is_none());
        assert!(request.metadata.source.is_none());
    }

    #[test]
    fn test_execution_state_to_result() {
        let request = ExecutionRequest {
            id: Uuid::new_v4(),
            command: Command::Shell {
                command: "echo test".to_string(),
                shell: "bash".to_string(),
            },
            env: HashMap::new(),
            working_dir: None,
            timeout_ms: None,
            output_log_path: None,
            metadata: ExecutionMetadata::default(),
        };

        let mut state = ExecutionState::new(request);
        state.status = ExecutionStatus::Completed;
        state.exit_code = Some(0);
        state.stdout = "test output".to_string();
        state.completed_at = Some(Utc::now());

        let result = state.to_result();
        assert_eq!(result.status, ExecutionStatus::Completed);
        assert!(result.success);
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "test output");
    }

    #[test]
    fn test_default_shell() {
        let shell = default_shell();
        if cfg!(target_os = "windows") {
            assert_eq!(shell, "powershell");
        } else {
            assert_eq!(shell, "bash");
        }
    }

    #[test]
    fn test_execution_metadata_default() {
        let metadata = ExecutionMetadata::default();
        assert!(metadata.source.is_none());
        assert!(metadata.conversation_id.is_none());
        assert!(metadata.tags.is_empty());
    }

    #[test]
    fn test_execution_strategy_serialization() {
        let strategy = ExecutionStrategy::Serial {
            stop_on_error: true,
        };

        let json = serde_json::to_string(&strategy).unwrap();
        assert!(json.contains("serial"));
        assert!(json.contains("stop_on_error"));
    }
}