drifter 0.1.11

A TUI-based S3 multipart uploader featuring resumable transfers and ClamAV integration.
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
use crate::app::state::AppEvent;
use crate::core::config::Config;
use crate::db::{self, JobRow};
use crate::services::scanner::{ScanResult, Scanner};
use crate::services::uploader::Uploader;
use anyhow::Result;
use rusqlite::Connection;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;
use tokio::sync::Mutex as AsyncMutex;

use crate::utils::{lock_async_mutex, lock_mutex};
use std::collections::HashMap;
use tracing::{error, info};

#[derive(Debug, Clone)]
pub struct ProgressInfo {
    pub percent: f64, // < 0.0 means "Calculating/Indeterminate"
    pub details: String,
    pub parts_done: usize,
    pub parts_total: usize,
}

#[derive(Clone)]
pub struct Coordinator {
    conn: Arc<Mutex<Connection>>,
    config: Arc<AsyncMutex<Config>>,
    scanner: Scanner,
    uploader: Uploader,
    progress: Arc<AsyncMutex<HashMap<i64, ProgressInfo>>>,
    cancellation_tokens: Arc<AsyncMutex<HashMap<i64, Arc<AtomicBool>>>>,
    app_tx: mpsc::Sender<AppEvent>,
}

impl Coordinator {
    pub fn new(
        conn: Arc<Mutex<Connection>>,
        config: Arc<AsyncMutex<Config>>,
        progress: Arc<AsyncMutex<HashMap<i64, ProgressInfo>>>,
        cancellation_tokens: Arc<AsyncMutex<HashMap<i64, Arc<AtomicBool>>>>,
        app_tx: mpsc::Sender<AppEvent>,
    ) -> Result<Self> {
        // We need lock to init scanner/uploader but they are just helpers now or cheap to init
        // Note: Initializing services might need config, but for now we assume they don't deep copy config state
        // OR we need to async lock here. But new() is sync.
        // Scanner/Uploader::new take &Config.
        // Block on the lock since we are in initialization phase (likely sync main) or create detached?
        // Actually Uploader::new takes &Config but just creates Self {}. It doesn't use it.
        // Scanner::new takes &Config and stores clamav host/port.
        // We need to peek at config.

        let cfg = futures::executor::block_on(config.lock());
        let scanner = Scanner::new(&cfg);
        let uploader = Uploader::new(&cfg);
        drop(cfg);

        Ok(Self {
            conn,
            config,
            scanner,
            uploader,
            progress,
            cancellation_tokens,
            app_tx,
        })
    }

    pub async fn run(&self) {
        loop {
            if let Err(e) = self.process_cycle().await {
                eprintln!("Coordinator error: {}", e);
            }
            tokio::time::sleep(Duration::from_secs(1)).await;
        }
    }

    async fn check_and_report(&self, session_id: &str) -> Result<()> {
        let pending = {
            let conn = lock_mutex(&self.conn)?;
            db::count_pending_session_jobs(&conn, session_id)?
        };

        if pending == 0 {
            let config = lock_async_mutex(&self.config).await.clone();
            let conn = lock_mutex(&self.conn)?;
            info!("Session {} complete. Generating report.", session_id);
            use crate::services::reporter::Reporter;
            Reporter::generate_report(&conn, &config, session_id)?;
        }
        Ok(())
    }

    pub async fn process_cycle(&self) -> Result<()> {
        // 1. Check for retryable jobs
        {
            let conn = lock_mutex(&self.conn)?;
            if let Ok(retry_jobs) = db::list_retryable_jobs(&conn) {
                for job in retry_jobs {
                    let next_status = if job.scan_status.as_deref() == Some("clean")
                        || job.scan_status.as_deref() == Some("scanned")
                    {
                        "scanned"
                    } else {
                        "queued"
                    };

                    info!("Retrying job {} (Attempt #{})", job.id, job.retry_count + 1);
                    db::update_job_retry_state(
                        &conn,
                        job.id,
                        job.retry_count + 1,
                        None,
                        next_status,
                        "Retrying...",
                    )?;
                    db::insert_event(
                        &conn,
                        job.id,
                        "retry",
                        &format!("Auto-retry attempt #{}", job.retry_count + 1),
                    )?;
                }
            }
        }

        // 2. Try starting scans (Limit: 2 concurrent file scans)
        let scanner_enabled = lock_async_mutex(&self.config).await.scanner_enabled;
        let active_scans = {
            let conn = lock_mutex(&self.conn)?;
            db::count_jobs_with_status(&conn, "scanning")?
        };

        if active_scans < 2 {
            let queued_job = {
                let conn = lock_mutex(&self.conn)?;
                if let Some(job) = db::get_next_job(&conn, "queued")? {
                    if scanner_enabled {
                        db::update_scan_status(&conn, job.id, "scanning", "scanning")?;
                        Some(job)
                    } else {
                        db::update_scan_status(&conn, job.id, "skipped", "scanned")?;
                        db::insert_event(&conn, job.id, "scan", "scan skipped by policy")?;
                        None
                    }
                } else {
                    None
                }
            };

            if let Some(job) = queued_job {
                let coord = self.clone();
                tokio::spawn(async move {
                    let _ = coord.process_scan(&job).await;
                });
            }
        }

        // 3. Try starting uploads
        let (max_uploads, active_uploads) = {
            let cfg = lock_async_mutex(&self.config).await;
            let conn = lock_mutex(&self.conn)?;
            (
                cfg.concurrency_upload_global,
                db::count_jobs_with_status(&conn, "uploading")?,
            )
        };

        if active_uploads < max_uploads as i64 {
            let scanned_job = {
                let conn = lock_mutex(&self.conn)?;
                if let Some(job) = db::get_next_job(&conn, "scanned")? {
                    db::update_upload_status(&conn, job.id, "uploading", "uploading")?;
                    Some(job)
                } else {
                    None
                }
            };

            if let Some(job) = scanned_job {
                let coord = self.clone();
                tokio::spawn(async move {
                    let _ = coord.process_upload(&job).await;
                });
            }
        }

        Ok(())
    }

    async fn process_scan(&self, job: &JobRow) -> Result<()> {
        let path = match &job.staged_path {
            Some(p) => p,
            None => {
                let conn = lock_mutex(&self.conn)?;
                db::update_job_error(&conn, job.id, "failed", "no staged path")?;
                return Ok(());
            }
        };

        let start_time = std::time::Instant::now();
        match self.scanner.scan_file(path).await {
            Ok(ScanResult::Clean) => {
                let duration = start_time.elapsed().as_millis() as i64;
                let conn = lock_mutex(&self.conn)?;
                db::update_scan_status(&conn, job.id, "clean", "scanned")?;
                db::update_scan_duration(&conn, job.id, duration)?;
                db::insert_event(
                    &conn,
                    job.id,
                    "scan",
                    &format!("scan completed in {}ms", duration),
                )?;
            }
            Ok(ScanResult::Infected(virus_name)) => {
                let (quarantine_dir, _delete_source) = {
                    let cfg = lock_async_mutex(&self.config).await;
                    (
                        PathBuf::from(&cfg.quarantine_dir),
                        cfg.delete_source_after_upload,
                    )
                };

                if !quarantine_dir.exists() {
                    let _ = std::fs::create_dir_all(&quarantine_dir);
                }

                let file_name = std::path::Path::new(path).file_name();
                let mut quarantine_path_str = String::new();

                if let Some(fname) = file_name {
                    let dest = quarantine_dir.join(fname);
                    if let Err(e) = std::fs::rename(path, &dest) {
                        eprintln!("Failed to quarantine file: {}", e);
                    } else {
                        quarantine_path_str = dest.to_string_lossy().to_string();
                    }
                }

                {
                    let conn = lock_mutex(&self.conn)?;
                    db::update_scan_status(&conn, job.id, "infected", "quarantined")?;

                    // Store virus name in error column so it appears in details
                    db::update_job_error(
                        &conn,
                        job.id,
                        "quarantined",
                        &format!("Infected: {}", virus_name),
                    )?;

                    if !quarantine_path_str.is_empty() {
                        let _ = db::update_job_staged(
                            &conn,
                            job.id,
                            &quarantine_path_str,
                            "quarantined",
                        );
                    }
                    db::insert_event(
                        &conn,
                        job.id,
                        "scan",
                        &format!("scan failed: infected with {}", virus_name),
                    )?;
                }
                self.check_and_report(&job.session_id).await?;
            }
            Err(e) => {
                {
                    let conn = lock_mutex(&self.conn)?;
                    db::update_job_error(&conn, job.id, "failed", &format!("scan error: {}", e))?;
                }
                self.check_and_report(&job.session_id).await?;
            }
        }
        Ok(())
    }

    async fn process_upload(&self, job: &JobRow) -> Result<()> {
        let path = match &job.staged_path {
            Some(p) => p.clone(),
            None => return Ok(()),
        };

        let config = {
            let config_guard = lock_async_mutex(&self.config).await;
            config_guard.clone()
        };

        // Set status to "uploading" BEFORE starting upload
        {
            let conn = lock_mutex(&self.conn)?;
            db::update_upload_status(&conn, job.id, "starting", "uploading")?;
        }

        let cancel_token = Arc::new(AtomicBool::new(false));
        {
            lock_async_mutex(&self.cancellation_tokens)
                .await
                .insert(job.id, cancel_token.clone());
        }

        let start_time = std::time::Instant::now();
        let res = self
            .uploader
            .upload_file(
                &config,
                &path,
                job.id,
                self.progress.clone(),
                self.conn.clone(),
                job.s3_upload_id.clone(),
                cancel_token,
            )
            .await;

        // Remove token
        {
            lock_async_mutex(&self.cancellation_tokens)
                .await
                .remove(&job.id);
        }

        match res {
            Ok(true) => {
                {
                    let duration = start_time.elapsed().as_millis() as i64;
                    let conn = lock_mutex(&self.conn)?;
                    db::update_upload_status(&conn, job.id, "completed", "complete")?;
                    db::update_upload_duration(&conn, job.id, duration)?;
                    db::insert_event(
                        &conn,
                        job.id,
                        "upload",
                        &format!("upload completed in {}ms", duration),
                    )?;
                }

                let staged_path = std::path::Path::new(&path);
                if job.source_path != path {
                    let _ = std::fs::remove_file(staged_path);
                    if let Some(parent) = staged_path.parent() {
                        let _ = std::fs::remove_dir(parent);
                    }
                } else if config.delete_source_after_upload {
                    let _ = std::fs::remove_file(staged_path);
                }

                // Signal TUI to refresh remote panel
                let _ = self.app_tx.send(AppEvent::RefreshRemote);

                self.check_and_report(&job.session_id).await?;
            }
            Ok(false) => {
                // Cancelled or Paused
                {
                    let conn = lock_mutex(&self.conn)?;
                    let current_status = db::get_job(&conn, job.id)?
                        .map(|j| j.status)
                        .unwrap_or_else(|| "unknown".to_string());

                    if current_status == "paused" {
                        db::insert_event(&conn, job.id, "upload", "upload paused")?;
                    } else {
                        db::insert_event(&conn, job.id, "upload", "upload cancelled")?;
                    }
                }
                self.check_and_report(&job.session_id).await?;
            }
            Err(e) => {
                let max_retries = 5;
                let should_report = {
                    let conn = lock_mutex(&self.conn)?;
                    if job.retry_count < max_retries {
                        // Exponential backoff: 5s, 10s, 20s, 40s, 80s
                        let backoff_secs = Self::calculate_backoff_seconds(job.retry_count);
                        let next_retry =
                            chrono::Utc::now() + chrono::Duration::seconds(backoff_secs as i64);
                        let next_retry_str = next_retry.to_rfc3339();

                        error!(
                            "Upload failed for job {}: {}. Retrying in {}s...",
                            job.id, e, backoff_secs
                        );

                        db::update_job_retry_state(
                            &conn,
                            job.id,
                            job.retry_count,
                            Some(&next_retry_str),
                            "retry_pending",
                            &format!("Failed: {}. Retry pending.", e),
                        )?;

                        db::insert_event(
                            &conn,
                            job.id,
                            "retry_scheduled",
                            &format!("Scheduled retry in {}s", backoff_secs),
                        )?;
                        false
                    } else {
                        error!(
                            "Upload failed for job {} after {} retries: {}",
                            job.id, job.retry_count, e
                        );
                        db::update_job_error(
                            &conn,
                            job.id,
                            "failed",
                            &format!("Max retries exceeded. Error: {}", e),
                        )?;
                        true
                    }
                };

                if should_report {
                    self.check_and_report(&job.session_id).await?;
                }
            }
        }

        // Check for report if we failed permanently (max retries)
        // We can't do it easily inside the match arm above without refactoring the if/else or using drop.
        // But wait, I need to check report only on failure terminal state.

        Ok(())
    }

    /// Calculate exponential backoff delay in seconds
    /// Formula: 5 * (2^retry_count)
    /// Results: 5s, 10s, 20s, 40s, 80s...
    pub fn calculate_backoff_seconds(retry_count: i64) -> u64 {
        5 * (2_u64.pow(retry_count as u32))
    }
}

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

    // --- Exponential Backoff Tests ---

    #[test]
    fn test_calculate_backoff_first_retry() {
        let backoff = Coordinator::calculate_backoff_seconds(0);
        assert_eq!(backoff, 5, "First retry should wait 5 seconds");
    }

    #[test]
    fn test_calculate_backoff_second_retry() {
        let backoff = Coordinator::calculate_backoff_seconds(1);
        assert_eq!(backoff, 10, "Second retry should wait 10 seconds");
    }

    #[test]
    fn test_calculate_backoff_third_retry() {
        let backoff = Coordinator::calculate_backoff_seconds(2);
        assert_eq!(backoff, 20, "Third retry should wait 20 seconds");
    }

    #[test]
    fn test_calculate_backoff_fourth_retry() {
        let backoff = Coordinator::calculate_backoff_seconds(3);
        assert_eq!(backoff, 40, "Fourth retry should wait 40 seconds");
    }

    #[test]
    fn test_calculate_backoff_fifth_retry() {
        let backoff = Coordinator::calculate_backoff_seconds(4);
        assert_eq!(backoff, 80, "Fifth retry should wait 80 seconds");
    }

    #[test]
    fn test_calculate_backoff_sequence() {
        // Verify the complete retry sequence: 5s, 10s, 20s, 40s, 80s
        let expected = [5, 10, 20, 40, 80];

        for (retry_count, expected_delay) in expected.iter().enumerate() {
            let backoff = Coordinator::calculate_backoff_seconds(retry_count as i64);
            assert_eq!(
                backoff, *expected_delay,
                "Retry {} should have backoff of {}s, got {}s",
                retry_count, expected_delay, backoff
            );
        }
    }

    #[test]
    fn test_calculate_backoff_doubles_each_time() {
        // Verify exponential growth property
        for retry_count in 0..5 {
            let current = Coordinator::calculate_backoff_seconds(retry_count);
            let next = Coordinator::calculate_backoff_seconds(retry_count + 1);

            assert_eq!(
                next,
                current * 2,
                "Backoff should double: retry {} = {}s, retry {} = {}s",
                retry_count,
                current,
                retry_count + 1,
                next
            );
        }
    }

    #[test]
    fn test_calculate_backoff_large_retry_count() {
        // Test with larger retry count (though app limits to 5)
        let backoff = Coordinator::calculate_backoff_seconds(10);
        assert_eq!(backoff, 5 * 1024); // 5 * 2^10 = 5120 seconds
    }

    #[test]
    fn test_calculate_backoff_max_retries_boundary() {
        // Test at the max retry boundary (5 retries = retry_count 0-4)
        let max_retries = 5;
        let last_backoff = Coordinator::calculate_backoff_seconds((max_retries - 1) as i64);

        // After 5th retry (retry_count=4), backoff should be 80s
        assert_eq!(last_backoff, 80);

        // Total wait time across all retries: 5 + 10 + 20 + 40 + 80 = 155 seconds
        let total_wait: u64 = (0..max_retries)
            .map(|i| Coordinator::calculate_backoff_seconds(i as i64))
            .sum();
        assert_eq!(total_wait, 155);
    }

    // --- Orchestration Tests ---

    fn setup_test_db() -> Result<Connection> {
        let conn = Connection::open_in_memory()?;
        conn.execute_batch(
            "
            CREATE TABLE jobs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                session_id TEXT NOT NULL DEFAULT 'legacy',
                created_at TEXT NOT NULL,
                status TEXT NOT NULL,
                source_path TEXT NOT NULL,
                staged_path TEXT,
                size_bytes INTEGER NOT NULL,
                scan_status TEXT,
                upload_status TEXT,
                s3_bucket TEXT,
                s3_key TEXT,
                s3_upload_id TEXT,
                checksum TEXT,
                remote_checksum TEXT,
                error TEXT,
                priority INTEGER DEFAULT 0,
                retry_count INTEGER DEFAULT 0,
                next_retry_at TEXT,
                scan_duration_ms INTEGER,
                upload_duration_ms INTEGER
            );
            CREATE TABLE uploads (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                job_id INTEGER NOT NULL,
                upload_id TEXT,
                part_size INTEGER NOT NULL,
                status TEXT NOT NULL,
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL,
                FOREIGN KEY(job_id) REFERENCES jobs(id)
            );
            CREATE TABLE parts (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                upload_id INTEGER NOT NULL,
                part_number INTEGER NOT NULL,
                etag TEXT,
                checksum_sha256 TEXT,
                size_bytes INTEGER NOT NULL,
                status TEXT NOT NULL,
                retries INTEGER NOT NULL DEFAULT 0,
                updated_at TEXT NOT NULL,
                FOREIGN KEY(upload_id) REFERENCES uploads(id)
            );
            CREATE TABLE events (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                job_id INTEGER NOT NULL,
                event_type TEXT NOT NULL,
                message TEXT NOT NULL,
                created_at TEXT NOT NULL,
                FOREIGN KEY(job_id) REFERENCES jobs(id)
            );
            CREATE TABLE secrets (
                key TEXT PRIMARY KEY,
                value TEXT NOT NULL
            );
            CREATE TABLE settings (
                key TEXT PRIMARY KEY,
                value TEXT NOT NULL
            );
            ",
        )?;
        Ok(conn)
    }

    // Helper to setup a test coordinator
    async fn setup_coordinator(
        scanner_enabled: bool,
    ) -> Result<(Coordinator, Arc<Mutex<Connection>>)> {
        let conn = Arc::new(Mutex::new(setup_test_db()?));
        let config = Config {
            scanner_enabled,
            s3_bucket: Some("test-bucket".to_string()),
            ..Default::default()
        };

        let config = Arc::new(AsyncMutex::new(config));
        let progress = Arc::new(AsyncMutex::new(HashMap::new()));
        let cancel = Arc::new(AsyncMutex::new(HashMap::new()));
        let (app_tx, _app_rx) = mpsc::channel();

        let coord = Coordinator::new(conn.clone(), config, progress, cancel, app_tx)?;
        Ok((coord, conn))
    }

    #[tokio::test]
    async fn test_coordinator_skips_scan_when_disabled() -> Result<()> {
        let (coord, conn) = setup_coordinator(false).await?;

        // Create a queued job
        let job_id = {
            let c = lock_mutex(&conn)?;
            let id = db::create_job(&c, "session1", "/tmp/file.txt", 100, None)?;
            db::update_job_staged(&c, id, "/tmp/staged.txt", "queued")?;
            id
        };

        // Run cycle
        coord.process_cycle().await?;

        // Verify state changed. It might reach 'uploading' in one cycle if uploader is also ready
        let c = lock_mutex(&conn)?;
        let job = db::get_job(&c, job_id)?.expect("Job not found");

        // It goes queued -> scanned (skipped) -> uploading
        assert_eq!(job.status, "uploading");
        assert_eq!(job.scan_status, Some("skipped".to_string()));

        Ok(())
    }

    #[tokio::test]
    async fn test_coordinator_picks_up_upload() -> Result<()> {
        let (coord, conn) = setup_coordinator(true).await?;

        // Create a scanned job ready for upload
        let job_id = {
            let c = lock_mutex(&conn)?;
            let id = db::create_job(&c, "session1", "/tmp/file.txt", 100, None)?;
            db::update_job_staged(&c, id, "/tmp/staged.txt", "queued")?;
            db::update_scan_status(&c, id, "clean", "scanned")?;
            id
        };

        // Run cycle
        // This will spawn the upload task, but we only care about the synchronous state update
        // that happens BEFORE the spawn.
        coord.process_cycle().await?;

        // Verify state changed to 'uploading'
        let c = lock_mutex(&conn)?;
        let job = db::get_job(&c, job_id)?.expect("Job not found");

        assert_eq!(job.status, "uploading");
        assert_eq!(job.upload_status, Some("uploading".to_string()));

        Ok(())
    }
}