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
//! Event system for Execution Engine
//!
//! Pluggable event handlers for real-time execution updates.
//! See docs/types.md for event type reference.

use crate::types::{ExecutionResult, ExecutionStatus};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// Events emitted during execution
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "event_type", rename_all = "snake_case")]
pub enum ExecutionEvent {
    /// Execution started
    Started {
        execution_id: Uuid,
        command: String,
        timestamp: DateTime<Utc>,
    },

    /// Standard output line
    Stdout {
        execution_id: Uuid,
        line: String,
        timestamp: DateTime<Utc>,
    },

    /// Standard error line
    Stderr {
        execution_id: Uuid,
        line: String,
        timestamp: DateTime<Utc>,
    },

    /// Execution completed
    Completed {
        execution_id: Uuid,
        result: ExecutionResult,
        timestamp: DateTime<Utc>,
    },

    /// Execution failed
    Failed {
        execution_id: Uuid,
        error: String,
        timestamp: DateTime<Utc>,
    },

    /// Execution cancelled
    Cancelled {
        execution_id: Uuid,
        timestamp: DateTime<Utc>,
    },

    /// Execution timeout
    Timeout {
        execution_id: Uuid,
        timeout_ms: u64,
        timestamp: DateTime<Utc>,
    },

    /// Plan progress update
    Progress {
        plan_id: Uuid,
        completed: usize,
        total: usize,
        current_command: Option<String>,
        timestamp: DateTime<Utc>,
    },

    /// Status changed
    StatusChanged {
        execution_id: Uuid,
        old_status: ExecutionStatus,
        new_status: ExecutionStatus,
        timestamp: DateTime<Utc>,
    },
}

impl ExecutionEvent {
    /// Get the execution ID for this event (if applicable)
    #[must_use]
    pub fn execution_id(&self) -> Option<Uuid> {
        match self {
            ExecutionEvent::Started { execution_id, .. }
            | ExecutionEvent::Stdout { execution_id, .. }
            | ExecutionEvent::Stderr { execution_id, .. }
            | ExecutionEvent::Completed { execution_id, .. }
            | ExecutionEvent::Failed { execution_id, .. }
            | ExecutionEvent::Cancelled { execution_id, .. }
            | ExecutionEvent::Timeout { execution_id, .. }
            | ExecutionEvent::StatusChanged { execution_id, .. } => Some(*execution_id),
            ExecutionEvent::Progress { .. } => None,
        }
    }

    /// Get the plan ID for this event (if applicable)
    #[must_use]
    pub fn plan_id(&self) -> Option<Uuid> {
        match self {
            ExecutionEvent::Progress { plan_id, .. } => Some(*plan_id),
            _ => None,
        }
    }

    /// Get the timestamp for this event
    #[must_use]
    pub fn timestamp(&self) -> DateTime<Utc> {
        match self {
            ExecutionEvent::Started { timestamp, .. }
            | ExecutionEvent::Stdout { timestamp, .. }
            | ExecutionEvent::Stderr { timestamp, .. }
            | ExecutionEvent::Completed { timestamp, .. }
            | ExecutionEvent::Failed { timestamp, .. }
            | ExecutionEvent::Cancelled { timestamp, .. }
            | ExecutionEvent::Timeout { timestamp, .. }
            | ExecutionEvent::Progress { timestamp, .. }
            | ExecutionEvent::StatusChanged { timestamp, .. } => *timestamp,
        }
    }

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

    /// Get event type name
    #[must_use]
    pub fn event_type_name(&self) -> &str {
        match self {
            ExecutionEvent::Started { .. } => "started",
            ExecutionEvent::Stdout { .. } => "stdout",
            ExecutionEvent::Stderr { .. } => "stderr",
            ExecutionEvent::Completed { .. } => "completed",
            ExecutionEvent::Failed { .. } => "failed",
            ExecutionEvent::Cancelled { .. } => "cancelled",
            ExecutionEvent::Timeout { .. } => "timeout",
            ExecutionEvent::Progress { .. } => "progress",
            ExecutionEvent::StatusChanged { .. } => "status_changed",
        }
    }
}

/// Event handler trait
///
/// Implement this trait to receive execution events.
#[async_trait]
pub trait EventHandler: Send + Sync {
    /// Handle an execution event
    async fn handle_event(&self, event: ExecutionEvent);

    /// Handle error in event processing
    async fn handle_error(&self, error: String) {
        eprintln!("Event handler error: {error}");
    }
}

/// No-op event handler (does nothing)
pub struct NoopEventHandler;

#[async_trait]
impl EventHandler for NoopEventHandler {
    async fn handle_event(&self, _event: ExecutionEvent) {
        // Do nothing
    }
}

/// Logging event handler (logs to stderr)
pub struct LoggingEventHandler {
    pub verbose: bool,
}

impl LoggingEventHandler {
    #[must_use]
    pub fn new(verbose: bool) -> Self {
        Self { verbose }
    }
}

#[async_trait]
impl EventHandler for LoggingEventHandler {
    async fn handle_event(&self, event: ExecutionEvent) {
        if self.verbose {
            eprintln!(
                "[{}] Event: {} - {:?}",
                event.timestamp().format("%Y-%m-%d %H:%M:%S"),
                event.event_type_name(),
                event
            );
        } else {
            match event {
                ExecutionEvent::Started { command, .. } => {
                    eprintln!("Started: {command}");
                }
                ExecutionEvent::Completed { execution_id, .. } => {
                    eprintln!("Completed: {execution_id}");
                }
                ExecutionEvent::Failed { error, .. } => {
                    eprintln!("Failed: {error}");
                }
                _ => {}
            }
        }
    }
}

/// Multi-handler that broadcasts to multiple handlers
pub struct MultiEventHandler {
    handlers: Vec<Box<dyn EventHandler>>,
}

impl MultiEventHandler {
    #[must_use]
    pub fn new() -> Self {
        Self {
            handlers: Vec::new(),
        }
    }

    pub fn add_handler(&mut self, handler: Box<dyn EventHandler>) {
        self.handlers.push(handler);
    }
}

impl Default for MultiEventHandler {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl EventHandler for MultiEventHandler {
    async fn handle_event(&self, event: ExecutionEvent) {
        for handler in &self.handlers {
            handler.handle_event(event.clone()).await;
        }
    }

    async fn handle_error(&self, error: String) {
        for handler in &self.handlers {
            handler.handle_error(error.clone()).await;
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::ExecutionResult;
    use std::time::Duration;

    #[test]
    fn test_execution_event_execution_id() {
        let id = Uuid::new_v4();
        let event = ExecutionEvent::Started {
            execution_id: id,
            command: "test".to_string(),
            timestamp: Utc::now(),
        };
        assert_eq!(event.execution_id(), Some(id));

        let plan_id = Uuid::new_v4();
        let event = ExecutionEvent::Progress {
            plan_id,
            completed: 1,
            total: 5,
            current_command: None,
            timestamp: Utc::now(),
        };
        assert_eq!(event.execution_id(), None);
        assert_eq!(event.plan_id(), Some(plan_id));
    }

    #[test]
    fn test_execution_event_is_terminal() {
        let id = Uuid::new_v4();

        let event = ExecutionEvent::Started {
            execution_id: id,
            command: "test".to_string(),
            timestamp: Utc::now(),
        };
        assert!(!event.is_terminal());

        let event = ExecutionEvent::Stdout {
            execution_id: id,
            line: "output".to_string(),
            timestamp: Utc::now(),
        };
        assert!(!event.is_terminal());

        let result = ExecutionResult {
            id,
            status: ExecutionStatus::Completed,
            success: true,
            exit_code: 0,
            stdout: "".to_string(),
            stderr: "".to_string(),
            duration: Duration::from_secs(1),
            started_at: Utc::now(),
            completed_at: Some(Utc::now()),
            error: None,
            stdout_overflow_file: None,
            stderr_overflow_file: None,
        };

        let event = ExecutionEvent::Completed {
            execution_id: id,
            result,
            timestamp: Utc::now(),
        };
        assert!(event.is_terminal());

        let event = ExecutionEvent::Failed {
            execution_id: id,
            error: "error".to_string(),
            timestamp: Utc::now(),
        };
        assert!(event.is_terminal());

        let event = ExecutionEvent::Cancelled {
            execution_id: id,
            timestamp: Utc::now(),
        };
        assert!(event.is_terminal());

        let event = ExecutionEvent::Timeout {
            execution_id: id,
            timeout_ms: 5000,
            timestamp: Utc::now(),
        };
        assert!(event.is_terminal());
    }

    #[test]
    fn test_event_type_name() {
        let id = Uuid::new_v4();

        let event = ExecutionEvent::Started {
            execution_id: id,
            command: "test".to_string(),
            timestamp: Utc::now(),
        };
        assert_eq!(event.event_type_name(), "started");

        let event = ExecutionEvent::Stdout {
            execution_id: id,
            line: "output".to_string(),
            timestamp: Utc::now(),
        };
        assert_eq!(event.event_type_name(), "stdout");

        let event = ExecutionEvent::StatusChanged {
            execution_id: id,
            old_status: ExecutionStatus::Pending,
            new_status: ExecutionStatus::Running,
            timestamp: Utc::now(),
        };
        assert_eq!(event.event_type_name(), "status_changed");
    }

    #[tokio::test]
    async fn test_noop_event_handler() {
        let handler = NoopEventHandler;
        let event = ExecutionEvent::Started {
            execution_id: Uuid::new_v4(),
            command: "test".to_string(),
            timestamp: Utc::now(),
        };
        handler.handle_event(event).await;
        // Should not panic
    }

    #[tokio::test]
    async fn test_logging_event_handler() {
        let handler = LoggingEventHandler::new(false);
        let event = ExecutionEvent::Started {
            execution_id: Uuid::new_v4(),
            command: "test".to_string(),
            timestamp: Utc::now(),
        };
        handler.handle_event(event).await;
        // Should log to stderr
    }

    #[tokio::test]
    async fn test_multi_event_handler() {
        let mut multi = MultiEventHandler::new();
        multi.add_handler(Box::new(NoopEventHandler));
        multi.add_handler(Box::new(LoggingEventHandler::new(false)));

        let event = ExecutionEvent::Started {
            execution_id: Uuid::new_v4(),
            command: "test".to_string(),
            timestamp: Utc::now(),
        };
        multi.handle_event(event).await;
        // Should broadcast to all handlers
    }

    #[test]
    fn test_event_serialization() {
        let event = ExecutionEvent::Started {
            execution_id: Uuid::new_v4(),
            command: "echo hello".to_string(),
            timestamp: Utc::now(),
        };

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

        let deserialized: ExecutionEvent = serde_json::from_str(&json).unwrap();
        match deserialized {
            ExecutionEvent::Started { command, .. } => {
                assert_eq!(command, "echo hello");
            }
            _ => panic!("Wrong event type"),
        }
    }
}