docker-wrapper 0.11.1

A Docker CLI wrapper for Rust
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
//! Debugging and reliability features for Docker commands.

use crate::command::{CommandExecutor, CommandOutput};
use crate::error::Result;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::sleep;
use tracing::{debug, info, instrument, trace, warn};

/// Configuration for dry-run mode and debugging
#[derive(Debug, Clone)]
pub struct DebugConfig {
    /// Enable dry-run mode (commands are not executed)
    pub dry_run: bool,

    /// Enable verbose output
    pub verbose: bool,

    /// Log all commands to this vector
    pub command_log: Arc<Mutex<Vec<String>>>,

    /// Custom prefix for dry-run output
    pub dry_run_prefix: String,
}

impl Default for DebugConfig {
    fn default() -> Self {
        Self {
            dry_run: false,
            verbose: false,
            command_log: Arc::new(Mutex::new(Vec::new())),
            dry_run_prefix: "[DRY RUN]".to_string(),
        }
    }
}

impl DebugConfig {
    /// Create a new debug configuration
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable dry-run mode
    #[must_use]
    pub fn dry_run(mut self, enabled: bool) -> Self {
        self.dry_run = enabled;
        self
    }

    /// Enable verbose output
    #[must_use]
    pub fn verbose(mut self, enabled: bool) -> Self {
        self.verbose = enabled;
        self
    }

    /// Set custom dry-run prefix
    #[must_use]
    pub fn dry_run_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.dry_run_prefix = prefix.into();
        self
    }

    /// Log a command
    pub fn log_command(&self, command: &str) {
        if let Ok(mut log) = self.command_log.lock() {
            log.push(command.to_string());
        }
    }

    /// Get logged commands
    #[must_use]
    pub fn get_command_log(&self) -> Vec<String> {
        self.command_log
            .lock()
            .map(|log| log.clone())
            .unwrap_or_default()
    }

    /// Clear command log
    pub fn clear_log(&self) {
        if let Ok(mut log) = self.command_log.lock() {
            log.clear();
        }
    }
}

/// Type alias for retry callback function
pub type RetryCallback = Arc<dyn Fn(u32, &str) + Send + Sync>;

/// Retry policy for handling transient failures
#[derive(Clone)]
pub struct RetryPolicy {
    /// Maximum number of attempts
    pub max_attempts: u32,

    /// Backoff strategy between retries
    pub backoff: BackoffStrategy,

    /// Callback for retry events
    pub on_retry: Option<RetryCallback>,
}

impl std::fmt::Debug for RetryPolicy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RetryPolicy")
            .field("max_attempts", &self.max_attempts)
            .field("backoff", &self.backoff)
            .field("on_retry", &self.on_retry.is_some())
            .finish()
    }
}

/// Backoff strategy for retries
#[derive(Debug, Clone)]
pub enum BackoffStrategy {
    /// Fixed delay between retries
    Fixed(Duration),

    /// Linear increase in delay
    Linear {
        /// Initial delay duration
        initial: Duration,
        /// Increment added for each retry
        increment: Duration,
    },

    /// Exponential backoff
    Exponential {
        /// Initial delay duration
        initial: Duration,
        /// Maximum delay duration
        max: Duration,
        /// Multiplier for exponential growth
        multiplier: f64,
    },
}

impl Default for RetryPolicy {
    fn default() -> Self {
        Self {
            max_attempts: 3,
            backoff: BackoffStrategy::Exponential {
                initial: Duration::from_millis(100),
                max: Duration::from_secs(10),
                multiplier: 2.0,
            },
            on_retry: None,
        }
    }
}

impl RetryPolicy {
    /// Create a new retry policy
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set maximum attempts
    #[must_use]
    pub fn max_attempts(mut self, attempts: u32) -> Self {
        self.max_attempts = attempts;
        self
    }

    /// Set backoff strategy
    #[must_use]
    pub fn backoff(mut self, strategy: BackoffStrategy) -> Self {
        self.backoff = strategy;
        self
    }

    /// Set retry callback
    #[must_use]
    pub fn on_retry<F>(mut self, callback: F) -> Self
    where
        F: Fn(u32, &str) + Send + Sync + 'static,
    {
        self.on_retry = Some(Arc::new(callback));
        self
    }

    /// Calculate delay for attempt number
    #[must_use]
    pub fn calculate_delay(&self, attempt: u32) -> Duration {
        match &self.backoff {
            BackoffStrategy::Fixed(delay) => *delay,

            BackoffStrategy::Linear { initial, increment } => {
                *initial + (*increment * (attempt - 1))
            }

            BackoffStrategy::Exponential {
                initial,
                max,
                multiplier,
            } => {
                #[allow(clippy::cast_precision_loss, clippy::cast_possible_wrap)]
                let delay_ms =
                    initial.as_millis() as f64 * multiplier.powi(attempt.saturating_sub(1) as i32);
                #[allow(clippy::cast_precision_loss)]
                let capped_ms = delay_ms.min(max.as_millis() as f64);
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                Duration::from_millis(capped_ms as u64)
            }
        }
    }

    /// Check if an error is retryable
    #[must_use]
    pub fn is_retryable(error_str: &str) -> bool {
        // Common retryable Docker errors
        error_str.contains("connection refused")
            || error_str.contains("timeout")
            || error_str.contains("temporarily unavailable")
            || error_str.contains("resource temporarily unavailable")
            || error_str.contains("Cannot connect to the Docker daemon")
            || error_str.contains("503 Service Unavailable")
            || error_str.contains("502 Bad Gateway")
    }
}

/// Enhanced command executor with debugging features
#[derive(Debug, Clone)]
pub struct DebugExecutor {
    /// Base executor
    pub executor: CommandExecutor,

    /// Debug configuration
    pub debug_config: DebugConfig,

    /// Retry policy
    pub retry_policy: Option<RetryPolicy>,
}

impl DebugExecutor {
    /// Create a new debug executor
    #[must_use]
    pub fn new() -> Self {
        Self {
            executor: CommandExecutor::new(),
            debug_config: DebugConfig::default(),
            retry_policy: None,
        }
    }

    /// Enable dry-run mode
    #[must_use]
    pub fn dry_run(mut self, enabled: bool) -> Self {
        self.debug_config = self.debug_config.dry_run(enabled);
        self
    }

    /// Enable verbose mode
    #[must_use]
    pub fn verbose(mut self, enabled: bool) -> Self {
        self.debug_config = self.debug_config.verbose(enabled);
        self
    }

    /// Set retry policy
    #[must_use]
    pub fn with_retry(mut self, policy: RetryPolicy) -> Self {
        self.retry_policy = Some(policy);
        self
    }

    /// Execute a command with debug features
    ///
    /// # Errors
    ///
    /// Returns an error if the command fails after all retry attempts
    #[instrument(
        name = "debug.execute",
        skip(self, args),
        fields(
            command = %command_name,
            dry_run = self.debug_config.dry_run,
            has_retry = self.retry_policy.is_some(),
        )
    )]
    pub async fn execute_command(
        &self,
        command_name: &str,
        args: Vec<String>,
    ) -> Result<CommandOutput> {
        let command_str = format!("docker {} {}", command_name, args.join(" "));

        // Log the command
        self.debug_config.log_command(&command_str);

        trace!(command = %command_str, "executing debug command");

        // Verbose output
        if self.debug_config.verbose {
            eprintln!("[VERBOSE] Executing: {command_str}");
        }

        // Dry-run mode
        if self.debug_config.dry_run {
            let message = format!(
                "{} Would execute: {}",
                self.debug_config.dry_run_prefix, command_str
            );
            eprintln!("{message}");
            info!(command = %command_str, "dry-run mode, command not executed");

            return Ok(CommandOutput {
                stdout: message,
                stderr: String::new(),
                exit_code: 0,
                success: true,
            });
        }

        // Execute with retry if configured
        if let Some(ref policy) = self.retry_policy {
            self.execute_with_retry(command_name, args, policy).await
        } else {
            self.executor.execute_command(command_name, args).await
        }
    }

    /// Execute command with retry logic
    #[instrument(
        name = "debug.retry",
        skip(self, args, policy),
        fields(
            command = %command_name,
            max_attempts = policy.max_attempts,
        )
    )]
    async fn execute_with_retry(
        &self,
        command_name: &str,
        args: Vec<String>,
        policy: &RetryPolicy,
    ) -> Result<CommandOutput> {
        let mut attempt = 0;
        let mut last_error = None;

        debug!(
            max_attempts = policy.max_attempts,
            "starting command execution with retry"
        );

        while attempt < policy.max_attempts {
            attempt += 1;

            trace!(attempt = attempt, "executing attempt");

            if self.debug_config.verbose && attempt > 1 {
                eprintln!(
                    "[VERBOSE] Retry attempt {}/{}",
                    attempt, policy.max_attempts
                );
            }

            match self
                .executor
                .execute_command(command_name, args.clone())
                .await
            {
                Ok(output) => {
                    if attempt > 1 {
                        info!(attempt = attempt, "command succeeded after retry");
                    }
                    return Ok(output);
                }
                Err(e) => {
                    let error_str = e.to_string();

                    // Check if retryable
                    if !RetryPolicy::is_retryable(&error_str) {
                        debug!(
                            error = %error_str,
                            "error is not retryable, failing immediately"
                        );
                        return Err(e);
                    }

                    // Last attempt?
                    if attempt >= policy.max_attempts {
                        warn!(
                            attempt = attempt,
                            max_attempts = policy.max_attempts,
                            error = %error_str,
                            "all retry attempts exhausted"
                        );
                        return Err(e);
                    }

                    // Call retry callback
                    if let Some(ref callback) = policy.on_retry {
                        callback(attempt, &error_str);
                    }

                    // Calculate and apply delay
                    let delay = policy.calculate_delay(attempt);

                    #[allow(clippy::cast_possible_truncation)]
                    let delay_ms = delay.as_millis() as u64;
                    warn!(
                        attempt = attempt,
                        max_attempts = policy.max_attempts,
                        error = %error_str,
                        delay_ms = delay_ms,
                        "command failed, will retry after delay"
                    );

                    if self.debug_config.verbose {
                        eprintln!("[VERBOSE] Waiting {delay:?} before retry");
                    }
                    sleep(delay).await;

                    last_error = Some(e);
                }
            }
        }

        Err(last_error.unwrap_or_else(|| crate::error::Error::custom("Retry failed")))
    }

    /// Get command history
    #[must_use]
    pub fn get_command_log(&self) -> Vec<String> {
        self.debug_config.get_command_log()
    }

    /// Clear command history
    pub fn clear_log(&self) {
        self.debug_config.clear_log();
    }
}

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

/// Helper for previewing commands without executing them
pub struct DryRunPreview {
    /// Commands that would be executed
    pub commands: Vec<String>,
}

impl DryRunPreview {
    /// Create a preview of commands
    #[must_use]
    pub fn new(commands: Vec<String>) -> Self {
        Self { commands }
    }

    /// Print the preview
    pub fn print(&self) {
        if self.commands.is_empty() {
            println!("No commands would be executed.");
            return;
        }

        println!("Would execute the following commands:");
        for (i, cmd) in self.commands.iter().enumerate() {
            println!("  {}. {}", i + 1, cmd);
        }
    }
}

impl std::fmt::Display for DryRunPreview {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.commands.is_empty() {
            return write!(f, "No commands would be executed.");
        }

        writeln!(f, "Would execute the following commands:")?;
        for (i, cmd) in self.commands.iter().enumerate() {
            writeln!(f, "  {}. {}", i + 1, cmd)?;
        }
        Ok(())
    }
}

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

    #[test]
    fn test_debug_config() {
        let config = DebugConfig::new()
            .dry_run(true)
            .verbose(true)
            .dry_run_prefix("[TEST]");

        assert!(config.dry_run);
        assert!(config.verbose);
        assert_eq!(config.dry_run_prefix, "[TEST]");
    }

    #[test]
    fn test_retry_policy_delay() {
        // Fixed backoff
        let policy = RetryPolicy::new().backoff(BackoffStrategy::Fixed(Duration::from_millis(100)));
        assert_eq!(policy.calculate_delay(1), Duration::from_millis(100));
        assert_eq!(policy.calculate_delay(3), Duration::from_millis(100));

        // Linear backoff
        let policy = RetryPolicy::new().backoff(BackoffStrategy::Linear {
            initial: Duration::from_millis(100),
            increment: Duration::from_millis(50),
        });
        assert_eq!(policy.calculate_delay(1), Duration::from_millis(100));
        assert_eq!(policy.calculate_delay(2), Duration::from_millis(150));
        assert_eq!(policy.calculate_delay(3), Duration::from_millis(200));

        // Exponential backoff
        let policy = RetryPolicy::new().backoff(BackoffStrategy::Exponential {
            initial: Duration::from_millis(100),
            max: Duration::from_secs(1),
            multiplier: 2.0,
        });
        assert_eq!(policy.calculate_delay(1), Duration::from_millis(100));
        assert_eq!(policy.calculate_delay(2), Duration::from_millis(200));
        assert_eq!(policy.calculate_delay(3), Duration::from_millis(400));
        assert_eq!(policy.calculate_delay(5), Duration::from_secs(1)); // Capped at max
    }

    #[test]
    fn test_retryable_errors() {
        assert!(RetryPolicy::is_retryable("connection refused"));
        assert!(RetryPolicy::is_retryable("operation timeout"));
        assert!(RetryPolicy::is_retryable(
            "Cannot connect to the Docker daemon"
        ));
        assert!(!RetryPolicy::is_retryable("image not found"));
        assert!(!RetryPolicy::is_retryable("permission denied"));
    }

    #[test]
    fn test_command_logging() {
        let config = DebugConfig::new();
        config.log_command("docker ps -a");
        config.log_command("docker run nginx");

        let log = config.get_command_log();
        assert_eq!(log.len(), 2);
        assert_eq!(log[0], "docker ps -a");
        assert_eq!(log[1], "docker run nginx");

        config.clear_log();
        assert_eq!(config.get_command_log().len(), 0);
    }

    #[test]
    fn test_dry_run_preview() {
        let commands = vec![
            "docker pull nginx".to_string(),
            "docker run -d nginx".to_string(),
        ];

        let preview = DryRunPreview::new(commands);
        let output = preview.to_string();

        assert!(output.contains("Would execute"));
        assert!(output.contains("1. docker pull nginx"));
        assert!(output.contains("2. docker run -d nginx"));
    }
}