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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
# Configuration Guide

**Crate**: `cloudops-execution-engine`

Complete configuration reference for the Execution Engine.

---

## ExecutionConfig

Main configuration structure for the execution engine.

```rust
pub struct ExecutionConfig {
    /// Default timeout in milliseconds
    pub default_timeout_ms: u64,

    /// Maximum allowed timeout in milliseconds
    pub max_timeout_ms: u64,

    /// Enable real-time output streaming
    pub stream_output: bool,

    /// Custom log directory (None = system temp dir)
    pub log_dir: Option<PathBuf>,

    /// Maximum concurrent executions (enforced via Semaphore)
    pub max_concurrent_executions: usize,

    /// Maximum executions to keep in memory
    pub max_in_memory_executions: usize,

    /// Auto-cleanup executions older than this (seconds)
    pub execution_retention_secs: u64,

    /// Enable automatic cleanup background task
    pub enable_auto_cleanup: bool,

    /// Maximum output to buffer per stream (bytes)
    pub max_output_size_bytes: usize,

    /// Truncate output if exceeded
    pub truncate_large_output: bool,

    /// How to handle oversized output
    pub oversized_output_strategy: OversizedOutputStrategy,
}

pub enum OversizedOutputStrategy {
    /// Truncate with warning marker
    TruncateWithWarning,
    /// Fail execution with error
    FailExecution,
    /// Stream to temporary file
    StreamToFile,
}
```

---

## Default Configuration

```rust
impl Default for ExecutionConfig {
    fn default() -> Self {
        Self {
            default_timeout_ms: 120_000,        // 2 minutes
            max_timeout_ms: 600_000,            // 10 minutes
            stream_output: true,
            log_dir: None,                      // System temp dir
            max_concurrent_executions: 100,     // Semaphore-enforced
            max_in_memory_executions: 1000,     // Memory cleanup threshold
            execution_retention_secs: 3600,     // 1 hour
            enable_auto_cleanup: true,          // Auto cleanup background task
            max_output_size_bytes: 10_485_760,  // 10 MB per stream
            truncate_large_output: true,        // Truncate instead of fail
            oversized_output_strategy: OversizedOutputStrategy::TruncateWithWarning,
        }
    }
}
```

**Usage:**
```rust
let config = ExecutionConfig::default();
let engine = ExecutionEngine::new(config);
```

---

## Configuration Options

### Timeout Settings

#### `default_timeout_ms`

Default timeout for commands that don't specify a timeout.

```rust
let config = ExecutionConfig {
    default_timeout_ms: 300_000, // 5 minutes
    ..Default::default()
};
```

#### `max_timeout_ms`

Maximum allowed timeout. Commands exceeding this will be rejected.

```rust
let config = ExecutionConfig {
    max_timeout_ms: 1_800_000, // 30 minutes
    ..Default::default()
};
```

### Output Streaming

#### `stream_output`

Enable/disable real-time output streaming via events.

```rust
let config = ExecutionConfig {
    stream_output: true,  // Enable streaming
    ..Default::default()
};
```

**When to disable:**
- Not using event handlers
- Performance-sensitive scenarios
- Only care about final result

### Log Directory

#### `log_dir`

Custom directory for execution logs.

```rust
let config = ExecutionConfig {
    log_dir: Some(PathBuf::from("/var/log/cloudops")),
    ..Default::default()
};
```

**Default behavior (None):**
- Uses system temp directory
- Path: `/tmp/cloudops-executions/` on Unix
- Path: `C:\Users\{user}\AppData\Local\Temp\cloudops-executions\` on Windows

### Concurrency

#### `max_concurrent_executions`

Maximum number of parallel executions (enforced via `tokio::sync::Semaphore`).

```rust
let config = ExecutionConfig {
    max_concurrent_executions: 20,
    ..Default::default()
};
```

**Implementation:**
- Uses Semaphore for concurrency limiting
- Executions block if limit is reached
- Prevents resource exhaustion from too many concurrent processes

---

### Memory Management

#### `max_in_memory_executions`

Maximum number of executions to keep in memory before triggering cleanup.

```rust
let config = ExecutionConfig {
    max_in_memory_executions: 2000,  // Keep 2000 executions
    ..Default::default()
};
```

**Default:** 1000 executions

**When to increase:**
- Long-running applications
- Need access to older execution history
- Sufficient memory available

**When to decrease:**
- Memory-constrained environments
- Short execution retention needs

#### `execution_retention_secs`

Auto-cleanup executions older than this duration (in seconds).

```rust
let config = ExecutionConfig {
    execution_retention_secs: 7200,  // 2 hours
    ..Default::default()
};
```

**Default:** 3600 seconds (1 hour)

**Common values:**
- `300` - 5 minutes (high-volume systems)
- `1800` - 30 minutes (typical)
- `3600` - 1 hour (default)
- `7200` - 2 hours (need longer history)

#### `enable_auto_cleanup`

Enable automatic background cleanup task.

```rust
let config = ExecutionConfig {
    enable_auto_cleanup: true,  // Enable cleanup
    ..Default::default()
};
```

**Default:** `true` (enabled)

**Behavior when enabled:**
- Background task runs every 5 minutes
- Removes executions older than `execution_retention_secs`
- Removes oldest executions if count exceeds `max_in_memory_executions`
- Logs cleanup activity

**When to disable:**
- Manual cleanup control needed
- Testing scenarios
- Very short-lived applications

---

### Output Management

#### `max_output_size_bytes`

Maximum output to buffer per stream (stdout/stderr).

```rust
let config = ExecutionConfig {
    max_output_size_bytes: 52_428_800,  // 50 MB
    ..Default::default()
};
```

**Default:** 10,485,760 bytes (10 MB)

**Common values:**
- `1_048_576` - 1 MB (strict limits)
- `10_485_760` - 10 MB (default, typical)
- `52_428_800` - 50 MB (large outputs)
- `104_857_600` - 100 MB (very large, use with caution)

#### `truncate_large_output`

Truncate output if size limit exceeded (alternative to failing).

```rust
let config = ExecutionConfig {
    truncate_large_output: true,  // Truncate instead of fail
    ..Default::default()
};
```

**Default:** `true`

**When true:**
- Output is truncated at limit
- Warning marker added to output
- Execution continues normally

**When false:**
- Execution fails with OversizedOutput error
- No output returned

#### `oversized_output_strategy`

How to handle output exceeding size limits.

```rust
let config = ExecutionConfig {
    oversized_output_strategy: OversizedOutputStrategy::StreamToFile,
    ..Default::default()
};
```

**Default:** `OversizedOutputStrategy::TruncateWithWarning`

**Strategies:**

1. **TruncateWithWarning** (default)
   - Truncate at limit
   - Add `\n[... output truncated at 10MB ...]` marker
   - Execution succeeds

2. **FailExecution**
   - Fail with `ExecutionError::OversizedOutput`
   - No output returned
   - Use for strict size enforcement

3. **StreamToFile**
   - Stream output to temporary file
   - Return file path in result
   - Use for very large outputs

**Example - Fail on large output:**
```rust
let config = ExecutionConfig {
    max_output_size_bytes: 5_242_880,  // 5 MB
    truncate_large_output: false,
    oversized_output_strategy: OversizedOutputStrategy::FailExecution,
    ..Default::default()
};
```

**Example - Stream to file:**
```rust
let config = ExecutionConfig {
    max_output_size_bytes: 10_485_760,  // 10 MB
    oversized_output_strategy: OversizedOutputStrategy::StreamToFile,
    ..Default::default()
};

// Result includes file path
let result = engine.get_result(execution_id).await?;
if let Some(file_path) = result.output_file {
    println!("Large output written to: {}", file_path);
}
```

---

## Configuration Examples

### Production Configuration

```rust
let config = ExecutionConfig {
    default_timeout_ms: 300_000,        // 5 minutes
    max_timeout_ms: 1_800_000,          // 30 minutes
    stream_output: true,
    log_dir: Some(PathBuf::from("/var/log/cloudops")),
    max_concurrent_executions: 100,
    max_in_memory_executions: 2000,
    execution_retention_secs: 7200,     // 2 hours
    enable_auto_cleanup: true,
    max_output_size_bytes: 52_428_800,  // 50 MB
    truncate_large_output: true,
    oversized_output_strategy: OversizedOutputStrategy::TruncateWithWarning,
};
```

### Development Configuration

```rust
let config = ExecutionConfig {
    default_timeout_ms: 60_000,         // 1 minute
    max_timeout_ms: 300_000,            // 5 minutes
    stream_output: true,
    log_dir: None,                      // Use temp dir
    max_concurrent_executions: 10,
    max_in_memory_executions: 100,
    execution_retention_secs: 1800,     // 30 minutes
    enable_auto_cleanup: true,
    max_output_size_bytes: 10_485_760,  // 10 MB
    truncate_large_output: true,
    oversized_output_strategy: OversizedOutputStrategy::TruncateWithWarning,
};
```

### Testing Configuration

```rust
let config = ExecutionConfig {
    default_timeout_ms: 10_000,         // 10 seconds
    max_timeout_ms: 30_000,             // 30 seconds
    stream_output: false,               // Disable streaming
    log_dir: Some(PathBuf::from("/tmp/test-logs")),
    max_concurrent_executions: 1,       // Serial only
    max_in_memory_executions: 10,       // Very small
    execution_retention_secs: 300,      // 5 minutes
    enable_auto_cleanup: false,         // Manual cleanup
    max_output_size_bytes: 1_048_576,   // 1 MB
    truncate_large_output: true,
    oversized_output_strategy: OversizedOutputStrategy::TruncateWithWarning,
};
```

### High-Volume Configuration

```rust
let config = ExecutionConfig {
    default_timeout_ms: 300_000,        // 5 minutes
    max_timeout_ms: 1_800_000,          // 30 minutes
    stream_output: true,
    log_dir: Some(PathBuf::from("/var/log/cloudops")),
    max_concurrent_executions: 200,     // High concurrency
    max_in_memory_executions: 5000,     // Large buffer
    execution_retention_secs: 300,      // 5 minutes (fast cleanup)
    enable_auto_cleanup: true,
    max_output_size_bytes: 5_242_880,   // 5 MB (strict)
    truncate_large_output: true,
    oversized_output_strategy: OversizedOutputStrategy::TruncateWithWarning,
};
```

### Memory-Constrained Configuration

```rust
let config = ExecutionConfig {
    default_timeout_ms: 120_000,        // 2 minutes
    max_timeout_ms: 600_000,            // 10 minutes
    stream_output: false,               // Reduce overhead
    log_dir: Some(PathBuf::from("/var/log/cloudops")),
    max_concurrent_executions: 5,       // Low concurrency
    max_in_memory_executions: 50,       // Small buffer
    execution_retention_secs: 600,      // 10 minutes
    enable_auto_cleanup: true,
    max_output_size_bytes: 1_048_576,   // 1 MB (strict)
    truncate_large_output: true,
    oversized_output_strategy: OversizedOutputStrategy::TruncateWithWarning,
};
```

---

## Environment-based Configuration

```rust
use std::env;

fn load_config_from_env() -> ExecutionConfig {
    ExecutionConfig {
        default_timeout_ms: env::var("EXEC_DEFAULT_TIMEOUT_MS")
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or(120_000),

        max_timeout_ms: env::var("EXEC_MAX_TIMEOUT_MS")
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or(600_000),

        stream_output: env::var("EXEC_STREAM_OUTPUT")
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or(true),

        log_dir: env::var("EXEC_LOG_DIR")
            .ok()
            .map(PathBuf::from),

        max_concurrent_executions: env::var("EXEC_MAX_CONCURRENT")
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or(10),
    }
}
```

---

## Configuration Files

### TOML Configuration

```toml
# config/execution.toml
[execution]
default_timeout_ms = 300000
max_timeout_ms = 1800000
stream_output = true
log_dir = "/var/log/cloudops"
max_concurrent_executions = 50
```

```rust
use serde::Deserialize;

#[derive(Deserialize)]
struct ConfigFile {
    execution: ExecutionConfig,
}

fn load_config_from_file(path: &str) -> Result<ExecutionConfig, Box<dyn std::error::Error>> {
    let content = std::fs::read_to_string(path)?;
    let config_file: ConfigFile = toml::from_str(&content)?;
    Ok(config_file.execution)
}
```

### JSON Configuration

```json
{
  "default_timeout_ms": 300000,
  "max_timeout_ms": 1800000,
  "stream_output": true,
  "log_dir": "/var/log/cloudops",
  "max_concurrent_executions": 50
}
```

```rust
fn load_config_from_json(path: &str) -> Result<ExecutionConfig, Box<dyn std::error::Error>> {
    let content = std::fs::read_to_string(path)?;
    let config: ExecutionConfig = serde_json::from_str(&content)?;
    Ok(config)
}
```

---

## Best Practices

### 1. Set Appropriate Timeouts

```rust
// Too short - may timeout frequently
default_timeout_ms: 10_000  // 10 seconds

// Recommended for AWS operations
default_timeout_ms: 120_000  // 2 minutes

// For long-running operations
default_timeout_ms: 600_000  // 10 minutes
```

### 2. Tune Concurrency

```rust
// Low concurrency for resource-constrained systems
max_concurrent_executions: 5

// Medium concurrency for typical workloads
max_concurrent_executions: 10-20

// High concurrency for powerful systems
max_concurrent_executions: 50-100
```

### 3. Use Structured Logs

```rust
let config = ExecutionConfig {
    log_dir: Some(PathBuf::from("/var/log/cloudops")),
    ..Default::default()
};

// Logs will be written to:
// /var/log/cloudops/{execution_id}.log
```

### 4. Disable Streaming When Not Needed

```rust
// If not using event handlers, disable streaming
let config = ExecutionConfig {
    stream_output: false,
    ..Default::default()
};
```

---

## Validation

Configuration is validated on engine creation:

```rust
let config = ExecutionConfig {
    default_timeout_ms: 700_000,  // Exceeds max
    max_timeout_ms: 600_000,
    ..Default::default()
};

// This will panic or return error
let engine = ExecutionEngine::new(config);
```

---

## Related Documents

- [API Reference]api.md
- [Usage Examples]usage.md
- [Error Handling]error-handling.md