audiobook-forge 2.10.0

CLI tool for converting audiobook directories to M4B format with chapters and metadata
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
//! Error recovery and retry logic

use anyhow::Result;
use std::time::Duration;
use tokio::time::sleep;

/// Retry configuration
#[derive(Debug, Clone)]
pub struct RetryConfig {
    /// Maximum number of retry attempts
    pub max_retries: usize,
    /// Initial delay between retries
    pub initial_delay: Duration,
    /// Maximum delay between retries
    pub max_delay: Duration,
    /// Backoff multiplier (exponential backoff)
    pub backoff_multiplier: f64,
}

impl RetryConfig {
    /// Create a new retry config with sensible defaults
    pub fn new() -> Self {
        Self {
            max_retries: 2,
            initial_delay: Duration::from_secs(1),
            max_delay: Duration::from_secs(30),
            backoff_multiplier: 2.0,
        }
    }

    /// Create a retry config with custom settings
    pub fn with_settings(
        max_retries: usize,
        initial_delay: Duration,
        max_delay: Duration,
        backoff_multiplier: f64,
    ) -> Self {
        Self {
            max_retries,
            initial_delay,
            max_delay,
            backoff_multiplier,
        }
    }

    /// No retries
    pub fn no_retry() -> Self {
        Self {
            max_retries: 0,
            initial_delay: Duration::from_secs(0),
            max_delay: Duration::from_secs(0),
            backoff_multiplier: 1.0,
        }
    }

    /// Calculate delay for retry attempt
    pub fn calculate_delay(&self, attempt: usize) -> Duration {
        if attempt == 0 {
            return self.initial_delay;
        }

        let delay_secs = self.initial_delay.as_secs_f64()
            * self.backoff_multiplier.powi(attempt as i32);

        let delay = Duration::from_secs_f64(delay_secs);

        // Clamp to max_delay
        if delay > self.max_delay {
            self.max_delay
        } else {
            delay
        }
    }
}

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

/// Execute a function with retry logic
pub async fn retry_async<F, Fut, T>(config: &RetryConfig, mut f: F) -> Result<T>
where
    F: FnMut() -> Fut,
    Fut: std::future::Future<Output = Result<T>>,
{
    let mut last_error = None;

    for attempt in 0..=config.max_retries {
        match f().await {
            Ok(result) => {
                if attempt > 0 {
                    tracing::info!("Retry successful after {} attempt(s)", attempt);
                }
                return Ok(result);
            }
            Err(e) => {
                last_error = Some(e);

                if attempt < config.max_retries {
                    let delay = config.calculate_delay(attempt);
                    tracing::warn!(
                        "Attempt {} failed, retrying in {:?}...",
                        attempt + 1,
                        delay
                    );
                    sleep(delay).await;
                } else {
                    tracing::error!("All {} retry attempts failed", config.max_retries + 1);
                }
            }
        }
    }

    // If we get here, all retries failed
    Err(last_error.unwrap())
}

/// Error classification for smart retry logic
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorType {
    /// Transient errors (worth retrying)
    Transient,
    /// Permanent errors (no point retrying)
    Permanent,
}

/// Classify an error to determine if retry is worthwhile
pub fn classify_error(error: &anyhow::Error) -> ErrorType {
    let error_msg = error.to_string().to_lowercase();

    // HTTP-specific errors
    // 429 rate limit is transient
    if error_msg.contains("429") || error_msg.contains("rate limit") {
        return ErrorType::Transient;
    }

    // 5xx server errors are transient
    if error_msg.contains("500") || error_msg.contains("502")
        || error_msg.contains("503") || error_msg.contains("504")
        || error_msg.contains("server error")
    {
        return ErrorType::Transient;
    }

    // 4xx client errors are permanent (except 429 handled above)
    if error_msg.contains("400") || error_msg.contains("401")
        || error_msg.contains("403") || error_msg.contains("404")
        || error_msg.contains("client error")
    {
        return ErrorType::Permanent;
    }

    // Transient errors (worth retrying)
    if error_msg.contains("timeout")
        || error_msg.contains("connection")
        || error_msg.contains("temporarily unavailable")
        || error_msg.contains("too many open files")
        || error_msg.contains("resource temporarily unavailable")
        || error_msg.contains("resource deadlock")
        || error_msg.contains("try again")
    {
        return ErrorType::Transient;
    }

    // Permanent errors - File system issues
    if error_msg.contains("file not found")
        || error_msg.contains("no such file")
        || error_msg.contains("permission denied")
        || error_msg.contains("access denied")
        || error_msg.contains("read-only")
        || error_msg.contains("disk full")
        || error_msg.contains("no space left")
    {
        return ErrorType::Permanent;
    }

    // Permanent errors - FFmpeg codec/format issues
    if error_msg.contains("invalid data found")
        || error_msg.contains("codec not found")
        || error_msg.contains("unsupported codec")
        || error_msg.contains("unknown codec")
        || error_msg.contains("invalid audio")
        || error_msg.contains("invalid sample rate")
        || error_msg.contains("invalid bit rate")
        || error_msg.contains("invalid channel")
        || error_msg.contains("not supported")
        || error_msg.contains("does not contain any stream")
        || error_msg.contains("no decoder")
        || error_msg.contains("no encoder")
        || error_msg.contains("moov atom not found")
        || error_msg.contains("invalid argument")
        || error_msg.contains("protocol not found")
    {
        return ErrorType::Permanent;
    }

    // Permanent errors - Data corruption
    if error_msg.contains("corrupted")
        || error_msg.contains("corrupt")
        || error_msg.contains("truncated")
        || error_msg.contains("header missing")
        || error_msg.contains("malformed")
        || error_msg.contains("end of file")
    {
        return ErrorType::Permanent;
    }

    // Default to transient (conservative approach)
    ErrorType::Transient
}

/// Execute with smart retry (only retry transient errors)
pub async fn smart_retry_async<F, Fut, T>(config: &RetryConfig, mut f: F) -> Result<T>
where
    F: FnMut() -> Fut,
    Fut: std::future::Future<Output = Result<T>>,
{
    let mut last_error = None;

    for attempt in 0..=config.max_retries {
        match f().await {
            Ok(result) => {
                if attempt > 0 {
                    tracing::info!("Smart retry successful after {} attempt(s)", attempt);
                }
                return Ok(result);
            }
            Err(e) => {
                let error_type = classify_error(&e);

                if error_type == ErrorType::Permanent {
                    tracing::error!("Permanent error detected, not retrying: {:?}", e);
                    return Err(e);
                }

                if attempt < config.max_retries {
                    let delay = config.calculate_delay(attempt);
                    tracing::warn!(
                        "Transient error on attempt {}: {:?}",
                        attempt + 1,
                        e
                    );
                    tracing::warn!(
                        "Retrying in {:?}... ({} attempts remaining)",
                        delay,
                        config.max_retries - attempt
                    );
                    sleep(delay).await;
                } else {
                    tracing::error!(
                        "All {} retry attempts exhausted. Final error: {:?}",
                        config.max_retries + 1,
                        e
                    );
                }

                last_error = Some(e);
            }
        }
    }

    Err(last_error.unwrap())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    #[test]
    fn test_retry_config_creation() {
        let config = RetryConfig::new();
        assert_eq!(config.max_retries, 2);
        assert_eq!(config.initial_delay, Duration::from_secs(1));
        assert_eq!(config.backoff_multiplier, 2.0);
    }

    #[test]
    fn test_retry_config_no_retry() {
        let config = RetryConfig::no_retry();
        assert_eq!(config.max_retries, 0);
    }

    #[test]
    fn test_calculate_delay() {
        let config = RetryConfig::new();

        assert_eq!(config.calculate_delay(0), Duration::from_secs(1));
        assert_eq!(config.calculate_delay(1), Duration::from_secs(2));
        assert_eq!(config.calculate_delay(2), Duration::from_secs(4));
        assert_eq!(config.calculate_delay(3), Duration::from_secs(8));

        // Test max delay clamping
        let config = RetryConfig::with_settings(
            5,
            Duration::from_secs(1),
            Duration::from_secs(5),
            2.0,
        );
        assert_eq!(config.calculate_delay(10), Duration::from_secs(5));
    }

    #[tokio::test]
    async fn test_retry_async_success_first_try() {
        let config = RetryConfig::new();
        let counter = Arc::new(AtomicUsize::new(0));

        let result: Result<i32> = retry_async(&config, || {
            let counter = Arc::clone(&counter);
            async move {
                counter.fetch_add(1, Ordering::Relaxed);
                Ok::<i32, anyhow::Error>(42)
            }
        })
        .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 42);
        assert_eq!(counter.load(Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn test_retry_async_success_after_retries() {
        let config = RetryConfig::with_settings(
            3,
            Duration::from_millis(10),
            Duration::from_millis(100),
            2.0,
        );
        let counter = Arc::new(AtomicUsize::new(0));

        let result = retry_async(&config, || {
            let counter = Arc::clone(&counter);
            async move {
                let count = counter.fetch_add(1, Ordering::Relaxed);
                if count < 2 {
                    anyhow::bail!("Transient error");
                }
                Ok::<i32, anyhow::Error>(42)
            }
        })
        .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 42);
        assert_eq!(counter.load(Ordering::Relaxed), 3);
    }

    #[tokio::test]
    async fn test_retry_async_all_fail() {
        let config = RetryConfig::with_settings(
            2,
            Duration::from_millis(10),
            Duration::from_millis(100),
            2.0,
        );
        let counter = Arc::new(AtomicUsize::new(0));

        let result: Result<i32> = retry_async(&config, || {
            let counter = Arc::clone(&counter);
            async move {
                counter.fetch_add(1, Ordering::Relaxed);
                anyhow::bail!("Always fails")
            }
        })
        .await;

        assert!(result.is_err());
        assert_eq!(counter.load(Ordering::Relaxed), 3); // Initial + 2 retries
    }

    #[test]
    fn test_classify_error() {
        let transient = anyhow::anyhow!("Connection timeout");
        assert_eq!(classify_error(&transient), ErrorType::Transient);

        let permanent = anyhow::anyhow!("File not found");
        assert_eq!(classify_error(&permanent), ErrorType::Permanent);

        let unknown = anyhow::anyhow!("Some random error");
        assert_eq!(classify_error(&unknown), ErrorType::Transient);
    }

    #[tokio::test]
    async fn test_smart_retry_permanent_error() {
        let config = RetryConfig::new();
        let counter = Arc::new(AtomicUsize::new(0));

        let result: Result<i32> = smart_retry_async(&config, || {
            let counter = Arc::clone(&counter);
            async move {
                counter.fetch_add(1, Ordering::Relaxed);
                anyhow::bail!("File not found")
            }
        })
        .await;

        assert!(result.is_err());
        assert_eq!(counter.load(Ordering::Relaxed), 1); // No retries for permanent error
    }

    #[tokio::test]
    async fn test_smart_retry_transient_error() {
        let config = RetryConfig::with_settings(
            2,
            Duration::from_millis(10),
            Duration::from_millis(100),
            2.0,
        );
        let counter = Arc::new(AtomicUsize::new(0));

        let result = smart_retry_async(&config, || {
            let counter = Arc::clone(&counter);
            async move {
                let count = counter.fetch_add(1, Ordering::Relaxed);
                if count < 2 {
                    anyhow::bail!("Connection timeout");
                }
                Ok::<i32, anyhow::Error>(42)
            }
        })
        .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 42);
        assert_eq!(counter.load(Ordering::Relaxed), 3);
    }
}