domain-status 0.2.1

Concurrent URL status checker that captures comprehensive metadata in SQLite.
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
//! URL scanning orchestration module.
//!
//! This module contains the main `run_scan` function and supporting types
//! for executing URL scans. The implementation is decomposed into:
//!
//! - `resources` - Data structures for scan state and resources
//! - `init` - Resource initialization logic
//! - `task` - Per-URL task processing
//! - `finalize` - Scan finalization and cleanup

mod finalize;
mod init;
mod resources;
mod task;

use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::atomic::Ordering;
use std::sync::{Arc, Mutex};

use log::warn;
use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken;

use crate::app::{log_progress, validate_and_normalize_url};
use crate::config::{LOGGING_INTERVAL, STATUS_SERVER_LOGGING_INTERVAL_SECS};
use crate::error_handling::ErrorType;
use crate::security::validate_url_safe;
use crate::storage::insert::insert_url_failure;
use crate::storage::models::UrlFailureRecord;
use crate::storage::DbPool;

/// RAII guard that registers a URL with the in-flight registry on construction
/// and removes it on drop.
///
/// The drain phase reads what's still in the registry when its deadline fires
/// to record a `url_failures` row for every abandoned URL. The guard's `Drop`
/// runs synchronously even when a task future is aborted at an `.await` point,
/// so successful tasks remove themselves before the drain snapshot, and aborted
/// tasks remain visible — exactly the distinction we need.
struct InFlightGuard {
    registry: Arc<Mutex<HashSet<String>>>,
    url: Option<String>,
}

impl InFlightGuard {
    fn register(registry: Arc<Mutex<HashSet<String>>>, url: String) -> Self {
        if let Ok(mut set) = registry.lock() {
            set.insert(url.clone());
        }
        Self {
            registry,
            url: Some(url),
        }
    }
}

impl Drop for InFlightGuard {
    fn drop(&mut self) {
        if let Some(url) = self.url.take() {
            if let Ok(mut set) = self.registry.lock() {
                set.remove(&url);
            }
        }
    }
}

fn domain_from_url_or_raw(url: &str) -> String {
    url::Url::parse(url)
        .ok()
        .and_then(|u| u.host_str().map(str::to_string))
        .unwrap_or_else(|| url.to_string())
}

async fn insert_abort_url_failure(
    pool: &DbPool,
    run_id: Option<&str>,
    url: &str,
    error_type: ErrorType,
    error_message: String,
    elapsed_time_seconds: Option<f64>,
) -> bool {
    let record = UrlFailureRecord {
        url: url.to_string(),
        final_url: None,
        domain: domain_from_url_or_raw(url),
        final_domain: None,
        error_type,
        error_message,
        http_status: None,
        retry_count: 0,
        elapsed_time_seconds,
        timestamp: chrono::Utc::now().timestamp_millis(),
        run_id: run_id.map(str::to_string),
        redirect_chain: vec![],
        response_headers: vec![],
    };
    match insert_url_failure(pool.as_ref(), &record).await {
        Ok(_) => true,
        Err(e) => {
            log::error!("Failed to insert {error_type} url_failures row for {url}: {e}");
            false
        }
    }
}

/// Records a `url_failures` row for each URL whose task was abandoned at the
/// drain timeout. Returns the number of rows successfully inserted.
///
/// Failures here are best-effort: an insert failure is logged but does not
/// abort the rest of the loop, since the alternative (leaving the URL with
/// no record at all) is worse than logging.
async fn record_drain_timeout_failures(
    pool: &DbPool,
    run_id: &str,
    drain_timeout_secs: u64,
    abandoned: &[String],
) -> usize {
    let mut inserted = 0usize;
    for url in abandoned {
        let ok = insert_abort_url_failure(
            pool,
            Some(run_id),
            url,
            ErrorType::ProcessUrlTimeout,
            format!(
                "Aborted at scan drain timeout ({drain_timeout_secs}s expired); task did not finish in time"
            ),
            None,
        )
        .await;
        if ok {
            inserted += 1;
        }
    }
    inserted
}

/// Persists a `url_failures` row when a worker sees cooperative cancel (Ctrl-C).
///
/// Drain timeout uses [`record_drain_timeout_failures`]; this path must also write
/// a fact row so finalize `COUNT(*)` matches live `failed_urls`.
pub(super) async fn record_cooperative_cancel_failure(
    pool: &DbPool,
    run_id: Option<&str>,
    url: &str,
) {
    let _ = insert_abort_url_failure(
        pool,
        run_id,
        url,
        ErrorType::ScanCancelled,
        format!("Scan cancelled before URL finished processing: {url}"),
        None,
    )
    .await;
}

pub use resources::{ScanLoopResult, ScanResources, UrlTaskParams};

// Re-export for public API
pub use init::init_scan_resources;

/// Results of a URL scanning run.
///
/// Contains summary statistics and metadata about the completed scan.
#[derive(Debug, Clone)]
pub struct ScanReport {
    /// Total number of URLs processed
    pub total_urls: usize,
    /// Number of URLs successfully processed
    pub successful: usize,
    /// Number of URLs that failed to process
    pub failed: usize,
    /// Number of URLs intentionally skipped (e.g. duplicate domain in same run)
    pub skipped: usize,
    /// Path to the `SQLite` database containing results
    pub db_path: PathBuf,
    /// Run identifier (format: `run_<timestamp_millis>`)
    pub run_id: String,
    /// Elapsed time in seconds
    pub elapsed_seconds: f64,
}

/// Helper function to invoke the progress callback if provided.
///
/// This reduces code duplication by centralizing the callback invocation logic.
#[allow(clippy::type_complexity)] // Matches the progress_callback type from Config; alias would add indirection
fn invoke_progress_callback(
    callback: Option<&Arc<dyn Fn(usize, usize, usize, usize) + Send + Sync>>,
    successful: &Arc<std::sync::atomic::AtomicUsize>,
    failed: &Arc<std::sync::atomic::AtomicUsize>,
    skipped: &Arc<std::sync::atomic::AtomicUsize>,
    total: usize,
) {
    if let Some(cb) = callback {
        cb(
            successful.load(Ordering::Relaxed),
            failed.load(Ordering::Relaxed),
            skipped.load(Ordering::Relaxed),
            total,
        );
    }
}

/// Records an early skip (invalid URL / SSRF-unsafe) and notifies progress.
fn skip_url(
    resources: &ScanResources,
    progress_callback: &resources::ProgressCallback,
    total_lines: usize,
) {
    resources
        .total_urls_attempted
        .fetch_add(1, Ordering::Relaxed);
    resources.skipped_urls.fetch_add(1, Ordering::Relaxed);
    invoke_progress_callback(
        progress_callback.as_ref(),
        &resources.successful_urls,
        &resources.failed_urls,
        &resources.skipped_urls,
        total_lines,
    );
}

/// Builds [`crate::status_server::StatusState`] from scan resources (Arc field wiring only).
fn build_status_state(resources: &ScanResources) -> crate::status_server::StatusState {
    crate::status_server::StatusState {
        total_urls: Arc::clone(&resources.total_urls_in_file),
        total_urls_attempted: Arc::clone(&resources.total_urls_attempted),
        successful_urls: Arc::clone(&resources.successful_urls),
        failed_urls: Arc::clone(&resources.failed_urls),
        skipped_urls: Arc::clone(&resources.skipped_urls),
        start_time: Arc::new(resources.start_time),
        error_stats: Arc::clone(&resources.shared_ctx.runtime.error_stats),
        timing_stats: Some(Arc::clone(&resources.shared_ctx.runtime.timing_stats)),
        request_limiter: resources.request_limiter.as_ref().map(Arc::clone),
        runtime_metrics: Arc::clone(&resources.shared_ctx.runtime.runtime_metrics),
        run_id: Some(resources.run_id.clone()),
        run_start_time_unix_secs: Some({
            #[allow(clippy::cast_precision_loss)]
            // Epoch millis fits in f64 mantissa until year 2255
            {
                (resources.start_time_epoch as f64) / 1000.0
            }
        }),
        phase: Arc::clone(&resources.phase),
        throughput_window: Arc::clone(&resources.throughput_window),
        max_concurrency: Some(resources.config.max_concurrency),
        semaphore: Some(Arc::clone(&resources.semaphore)),
    }
}

/// Drains remaining `JoinSet` tasks until empty or the wall-clock drain deadline.
///
/// On timeout: snapshots in-flight URLs, records drain-timeout failures, increments
/// `failed_urls`, aborts remaining tasks, and cancels the token. Does not change
/// [`InFlightGuard`] registration/drop semantics.
async fn drain_join_set(
    resources: &ScanResources,
    tasks: &mut JoinSet<()>,
    cancel: &CancellationToken,
) {
    let drain_timeout_secs = resources.config.drain_timeout_secs;
    let drain_timeout = std::time::Duration::from_secs(drain_timeout_secs);
    let drain_deadline = tokio::time::Instant::now() + drain_timeout;
    loop {
        let remaining = drain_deadline.saturating_duration_since(tokio::time::Instant::now());
        if remaining.is_zero() {
            // Snapshot the URLs whose tasks are still in flight BEFORE aborting them.
            // The InFlightGuard::Drop removes URLs on natural completion, so the set
            // we read here is exactly the set that did NOT finish in time.
            let abandoned: Vec<String> = resources
                .in_flight_urls
                .lock()
                .map(|set| set.iter().cloned().collect())
                .unwrap_or_default();
            let abandoned_count = abandoned.len();
            if abandoned_count > 0 {
                log::warn!(
                    "Drain timeout ({drain_timeout_secs}s) reached, recording {abandoned_count} in-flight task(s) as failures and aborting"
                );
                let inserted = record_drain_timeout_failures(
                    &resources.shared_ctx.pool,
                    &resources.run_id,
                    drain_timeout_secs,
                    &abandoned,
                )
                .await;
                if inserted < abandoned_count {
                    log::warn!(
                        "Recorded {inserted}/{abandoned_count} drain-timeout failures (the rest hit DB errors; see preceding log lines)"
                    );
                }
                resources
                    .failed_urls
                    .fetch_add(abandoned_count, Ordering::Relaxed);
            } else {
                log::info!("Drain timeout ({drain_timeout_secs}s) reached, no remaining tasks");
            }
            tasks.abort_all();
            cancel.cancel();
            break;
        }
        match tokio::time::timeout(remaining, tasks.join_next()).await {
            Ok(Some(task_result)) => {
                if let Err(join_error) = task_result {
                    resources.failed_urls.fetch_add(1, Ordering::Relaxed);
                    log::warn!("Failed to join task (panicked): {join_error:?}");
                }
            }
            Ok(None) => break,
            #[allow(clippy::needless_continue)]
            // Explicit continue clarifies intent: retry after timeout
            Err(_) => continue, // Deadline check at top of loop handles the abort
        }
    }
}

/// Runs a URL scan with the provided configuration.
///
/// This is the main entry point for the library. It reads URLs from the input file,
/// processes them concurrently, and stores results in a `SQLite` database.
///
/// # Arguments
///
/// * `config` - Configuration for the scan (file path, concurrency, timeouts, etc.)
///
/// # Returns
///
/// Returns a `ScanReport` containing summary statistics, or an error if the scan
/// failed to complete.
///
/// # Errors
///
/// This function will return an error if:
/// - The input file cannot be opened
/// - Database initialization fails
/// - Network resources cannot be initialized
///
/// # Example
///
/// ```no_run
/// use domain_status::{Config, run_scan};
/// use std::path::PathBuf;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let config = Config {
///     file: PathBuf::from("urls.txt"),
///     ..Default::default()
/// };
/// let report = run_scan(config).await?;
/// println!("Processed {} URLs", report.total_urls);
/// # Ok(())
/// # }
/// ```
#[allow(clippy::cognitive_complexity)] // Multi-phase scan: init, status server, logging, URL loop, drain, finalize
#[allow(clippy::too_many_lines)] // Still >100 after helper extraction; loop + select dominate
pub async fn run_scan(
    config: crate::config::Config,
) -> Result<ScanReport, crate::error_handling::RunScanError> {
    // Phase 1: Initialize all resources
    let (resources, mut url_source, total_lines, progress_callback) = init_scan_resources(config)
        .await
        .map_err(|e| crate::error_handling::RunScanError::Startup(e.into()))?;

    // Phase 2: Start status server if configured
    let mut status_server = if let Some(port) = resources.config.status_port {
        Some(
            crate::status_server::spawn_status_server(port, build_status_state(&resources))
                .await
                .map_err(|e| crate::error_handling::RunScanError::Startup(e.into()))?,
        )
    } else {
        None
    };

    // Phase 3: Start progress logging and run the main scan loop
    let cancel = CancellationToken::new();
    let cancel_for_signal = cancel.clone();
    tokio::spawn(async move {
        if tokio::signal::ctrl_c().await.is_ok() {
            cancel_for_signal.cancel();
        }
    });
    let cancel_logging = cancel.child_token();

    let successful_urls_for_logging = Arc::clone(&resources.successful_urls);
    let failed_urls_for_logging = Arc::clone(&resources.failed_urls);
    let skipped_urls_for_logging = Arc::clone(&resources.skipped_urls);
    let total_urls_for_logging = Arc::clone(&resources.total_urls_in_file);
    let start_time = resources.start_time;

    let logging_interval_secs = if resources.config.status_port.is_none() {
        LOGGING_INTERVAL as u64
    } else {
        STATUS_SERVER_LOGGING_INTERVAL_SECS
    };

    let mut logging_task = Some(tokio::task::spawn(async move {
        let mut interval =
            tokio::time::interval(std::time::Duration::from_secs(logging_interval_secs));
        loop {
            tokio::select! {
                _ = interval.tick() => {
                    log_progress(
                        start_time,
                        &successful_urls_for_logging,
                        &failed_urls_for_logging,
                        &skipped_urls_for_logging,
                        Some(&total_urls_for_logging),
                    );
                }
                () = cancel_logging.cancelled() => {
                    break;
                }
            }
        }
    }));

    // Phase 4: Run the main scan loop
    // Use JoinSet instead of FuturesUnordered for better memory efficiency.
    // JoinSet allows interleaved spawning and reaping, preventing memory accumulation
    // when processing large URL lists (1M+ URLs).
    let mut tasks: JoinSet<()> = JoinSet::new();
    let mut consecutive_errors = 0;
    const MAX_CONSECUTIVE_ERRORS: usize = 10;

    loop {
        // Interleaved reaping: Try to reap any completed tasks before spawning new ones.
        // This prevents JoinHandle accumulation when tasks complete faster than new ones are read.
        // Using timeout(Duration::ZERO) for non-blocking check - if a task is ready, we get it;
        // otherwise we immediately continue to spawn new tasks.
        while let Ok(Some(task_result)) =
            tokio::time::timeout(std::time::Duration::ZERO, tasks.join_next()).await
        {
            if let Err(join_error) = task_result {
                resources.failed_urls.fetch_add(1, Ordering::Relaxed);
                log::warn!("Failed to join task (panicked): {join_error:?}");
            }
        }

        tokio::select! {
            line_result = url_source.next_line() => {
                let line = match line_result {
                    Ok(Some(line)) => {
                        consecutive_errors = 0;
                        line
                    }
                    Ok(None) => break,
                    Err(e) => {
                        consecutive_errors += 1;
                        if consecutive_errors > MAX_CONSECUTIVE_ERRORS {
                            crate::app::shutdown_gracefully(
                                cancel.clone(),
                                logging_task.take(),
                                resources.rate_limiter_shutdown.clone(),
                                status_server.take(),
                            )
                            .await;
                            return Err(crate::error_handling::RunScanError::Runtime(
                                anyhow::anyhow!(
                                    "Too many consecutive read errors ({consecutive_errors}): {e}"
                                ),
                            ));
                        }
                        warn!("Failed to read line from input: {e}");
                        continue;
                    }
                };

                let trimmed = line.trim();
                if trimmed.is_empty() || trimmed.starts_with('#') {
                    continue;
                }

                let Some(url) = validate_and_normalize_url(trimmed) else {
                    skip_url(&resources, &progress_callback, total_lines);
                    continue;
                };

                // SSRF protection: reject private IPs, localhost, and unsafe schemes on the initial URL.
                // IP literals bypass the HTTP client's SafeResolver (no DNS lookup), so we must validate here.
                // allow_localhost_for_tests lets integration tests use mock servers bound to 127.0.0.1/::1.
                if !resources.config.allow_localhost_for_tests {
                    if let Err(e) = validate_url_safe(&url) {
                        warn!("Skipping SSRF-unsafe URL: {e}");
                        skip_url(&resources, &progress_callback, total_lines);
                        continue;
                    }
                }

                // Race semaphore acquisition against cancellation so we don't block on the
                // permit wait with no way to respond to Ctrl-C (avoids deadlock when all
                // worker permits are in use).
                let permit = tokio::select! {
                    result = Arc::clone(&resources.semaphore).acquire_owned() => {
                        if let Ok(p) = result { p } else {
                            warn!("Semaphore closed, skipping URL: {url}");
                            resources
                                .total_urls_attempted
                                .fetch_add(1, Ordering::Relaxed);
                            resources
                                .failed_urls
                                .fetch_add(1, Ordering::Relaxed);
                            continue;
                        }
                    }
                    () = cancel.cancelled() => {
                        log::info!("Received interrupt (Ctrl-C), finishing current work and finalizing...");
                        break;
                    }
                };

                resources
                    .total_urls_attempted
                    .fetch_add(1, Ordering::Relaxed);

                let task_params = UrlTaskParams {
                    url: Arc::from(url.as_str()),
                    ctx: Arc::clone(&resources.shared_ctx),
                    cancel: cancel.clone(),
                    permit,
                    request_limiter: resources.request_limiter.as_ref().map(Arc::clone),
                    host_limiter: resources.host_limiter.as_ref().map(Arc::clone),
                    successful_urls: Arc::clone(&resources.successful_urls),
                    skipped_urls: Arc::clone(&resources.skipped_urls),
                    failed_urls: Arc::clone(&resources.failed_urls),
                    total_urls_for_callback: total_lines,
                    progress_callback: progress_callback.clone(),
                };

                // Wrap the task so an InFlightGuard registers the URL on entry and
                // removes it on drop. The drain phase reads what is still registered
                // when its deadline fires to record a url_failures row for every URL
                // that was aborted, instead of silently incrementing a counter.
                let registry = Arc::clone(&resources.in_flight_urls);
                let url_for_registry = url.clone();
                // JoinSet::spawn() is like FuturesUnordered::push(tokio::spawn(...))
                // but manages the JoinHandle internally without accumulating them all in memory
                tasks.spawn(async move {
                    let _guard = InFlightGuard::register(registry, url_for_registry);
                    task::process_url_task(task_params).await;
                });
            }
            () = cancel.cancelled() => {
                log::info!("Received interrupt (Ctrl-C), finishing current work and finalizing...");
                break;
            }
        }
    }

    // Phase 5: Drain remaining tasks with timeout so Ctrl-C doesn't hang indefinitely.
    // Use a single wall-clock deadline for the entire drain, not per-task timeouts,
    // so N slow tasks can't extend the shutdown to N * timeout.
    resources
        .phase
        .set(crate::status_server::ScanPhase::Draining);
    drain_join_set(&resources, &mut tasks, &cancel).await;

    // Phase 6: Finalize
    let loop_result = ScanLoopResult {
        cancel,
        logging_task,
        status_server,
    };

    finalize::finalize_scan(resources, loop_result)
        .await
        .map_err(crate::error_handling::RunScanError::Runtime)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{Config, FailOn, LogFormat, LogLevel};
    use tempfile::NamedTempFile;

    #[tokio::test]
    async fn test_run_scan_validation_failure() {
        let config = Config {
            max_concurrency: 0, // Invalid - should fail validation
            ..Default::default()
        };

        let result = run_scan(config).await;
        assert!(result.is_err(), "Should fail with invalid configuration");
        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("Configuration validation failed")
                || error_msg.contains("max_concurrency")
                || error_msg.contains("greater than 0"),
            "Expected validation error, got: {}",
            error_msg
        );
    }

    #[tokio::test]
    async fn test_run_scan_file_not_found() {
        let config = Config {
            file: std::path::PathBuf::from("/nonexistent/file/that/does/not/exist.txt"),
            ..Default::default()
        };

        let result = run_scan(config).await;
        assert!(result.is_err(), "Should fail when file doesn't exist");
        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("Failed to open input file")
                || error_msg.contains("No such file")
                || error_msg.contains("not found"),
            "Expected file not found error, got: {}",
            error_msg
        );
    }

    #[tokio::test]
    async fn test_run_scan_database_initialization_failure() {
        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        // Parent path is a file, so SQLite cannot create a DB underneath it.
        let db_path = temp_file.path().join("nested").join("domain_status.db");
        let fp = NamedTempFile::new().expect("fp");
        std::fs::write(fp.path(), "{}").expect("empty fingerprints");

        let config = Config {
            file: std::path::PathBuf::from("/dev/null"),
            db_path,
            fingerprints: Some(fp.path().to_string_lossy().into_owned()),
            ..Default::default()
        };

        let result = run_scan(config).await;
        assert!(
            result.is_err(),
            "run_scan should fail when db_path parent is not a directory"
        );
        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("database")
                || error_msg.contains("Database")
                || error_msg.contains("Failed to")
                || error_msg.contains("No such file")
                || error_msg.contains("os error")
                || error_msg.contains("unable to open")
                || error_msg.contains("not a directory"),
            "Expected database init error, got: {error_msg}"
        );
    }

    #[tokio::test]
    async fn test_run_scan_empty_file() {
        let temp_input = NamedTempFile::new().expect("Failed to create temp file");
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");

        let config = Config {
            file: temp_input.path().to_path_buf(),
            db_path: temp_db.path().to_path_buf(),
            max_concurrency: 30,
            timeout_seconds: 10,
            rate_limit_rps: 15,
            fail_on: FailOn::Never,
            fail_on_pct_threshold: 10,
            enable_whois: false,
            cache_dir: None,
            scan_external_scripts: false,
            log_level: LogLevel::Info,
            log_level_filter_override: None,
            log_format: LogFormat::Plain,
            user_agent: crate::config::DEFAULT_USER_AGENT.to_string(),
            fingerprints: None,
            geoip: None,
            status_port: None,
            log_file: None,
            progress_callback: None,
            dependency_overrides: None,
            allow_localhost_for_tests: false,
            drain_timeout_secs: 10,
            allow_degraded_fingerprints: true,
        };

        let result = run_scan(config).await;
        match result {
            Ok(report) => {
                assert_eq!(report.total_urls, 0);
                assert_eq!(report.successful, 0);
                assert_eq!(report.failed, 0);
                assert_eq!(report.skipped, 0);

                // Verify finalize_scan wrote run stats to DB (run row matches report)
                let pool =
                    sqlx::SqlitePool::connect(&format!("sqlite:{}", report.db_path.display()))
                        .await
                        .expect("connect to test db");
                let row: (i64, i64, i64, i64) = sqlx::query_as(
                    "SELECT total_urls, successful_urls, failed_urls, skipped_urls FROM runs WHERE run_id = ?",
                )
                .bind(&report.run_id)
                .fetch_one(&pool)
                .await
                .expect("run row should exist");
                assert_eq!(
                    usize::try_from(row.0).expect("total_urls non-negative"),
                    report.total_urls,
                    "DB total_urls should match report"
                );
                assert_eq!(
                    usize::try_from(row.1).expect("successful_urls non-negative"),
                    report.successful,
                    "DB successful_urls should match report"
                );
                assert_eq!(
                    usize::try_from(row.2).expect("failed_urls non-negative"),
                    report.failed,
                    "DB failed_urls should match report"
                );
                assert_eq!(
                    usize::try_from(row.3).expect("skipped_urls non-negative"),
                    report.skipped,
                    "DB skipped_urls should match report"
                );
            }
            Err(e) => {
                let error_msg = e.to_string();
                assert!(
                    error_msg.contains("database")
                        || error_msg.contains("Database")
                        || error_msg.contains("migration")
                        || error_msg.contains("Failed to initialize"),
                    "Expected database/setup error for empty file test, got: {}",
                    error_msg
                );
            }
        }
    }

    #[tokio::test]
    async fn test_run_scan_file_with_comments() {
        let temp_input = NamedTempFile::new().expect("Failed to create temp file");
        std::fs::write(
            temp_input.path(),
            "# This is a comment\nhttps://example.com\n# Another comment\n",
        )
        .expect("Failed to write test file");

        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let fp_dir = tempfile::TempDir::new().expect("fp dir");
        let fp_path = fp_dir.path().join("technologies.json");
        std::fs::write(&fp_path, "{}").expect("empty fingerprints");

        let config = Config {
            file: temp_input.path().to_path_buf(),
            db_path: temp_db.path().to_path_buf(),
            max_concurrency: 1,
            timeout_seconds: 10,
            rate_limit_rps: 15,
            fail_on: FailOn::Never,
            fail_on_pct_threshold: 10,
            enable_whois: false,
            cache_dir: None,
            scan_external_scripts: false,
            log_level: LogLevel::Info,
            log_level_filter_override: None,
            log_format: LogFormat::Plain,
            user_agent: crate::config::DEFAULT_USER_AGENT.to_string(),
            fingerprints: Some(fp_path.to_string_lossy().into_owned()),
            geoip: None,
            status_port: None,
            log_file: None,
            progress_callback: None,
            dependency_overrides: None,
            allow_localhost_for_tests: false,
            drain_timeout_secs: 10,
            allow_degraded_fingerprints: false,
        };

        // Comment lines are skipped; the remaining URL is attempted. Use empty local
        // fingerprints so this never soft-passes on network fingerprint failure.
        let report = run_scan(config)
            .await
            .expect("scan with local fingerprints must not fail init");
        assert_eq!(
            report.total_urls, 1,
            "File with one URL and comments should result in one URL attempted"
        );
    }
}