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
//! Per-URL task processing.
//!
//! This module contains the logic for processing a single URL, including
//! success/failure/timeout handling.

use std::sync::atomic::Ordering;
use std::sync::Arc;

use crate::config::{RETRY_MAX_ATTEMPTS, URL_PROCESSING_TIMEOUT};
use crate::error_handling::ErrorType;
use crate::fetch::UrlProcessOutcome;
use crate::initialization::{HostRateLimiter, RateLimiter};
use crate::storage::failure::record_url_failure;
use crate::utils::ProcessUrlResult;

use super::invoke_progress_callback;
use super::resources::{ProgressCallback, UrlTaskParams};
use tokio_util::sync::CancellationToken;

/// Bundles progress counters and callback for task handlers (avoids `too_many_arguments`).
struct TaskProgress<'a> {
    successful_urls: &'a Arc<std::sync::atomic::AtomicUsize>,
    skipped_urls: &'a Arc<std::sync::atomic::AtomicUsize>,
    failed_urls: &'a Arc<std::sync::atomic::AtomicUsize>,
    total_urls_for_callback: usize,
    progress_callback: &'a ProgressCallback,
}

/// Process a single URL task.
///
/// This function is spawned as a Tokio task for each URL. It handles:
/// - Rate limiting (if configured)
/// - URL processing with timeout
/// - Success/failure/timeout outcome handling
///
/// # Arguments
///
/// * `params` - All parameters needed to process the URL
pub async fn process_url_task(params: UrlTaskParams) {
    let UrlTaskParams {
        url,
        ctx,
        cancel,
        permit: _permit, // Hold permit until task completes
        request_limiter,
        host_limiter,
        successful_urls,
        skipped_urls,
        failed_urls,
        total_urls_for_callback,
        progress_callback,
    } = params;

    let progress = TaskProgress {
        successful_urls: &successful_urls,
        skipped_urls: &skipped_urls,
        failed_urls: &failed_urls,
        total_urls_for_callback,
        progress_callback: &progress_callback,
    };

    if cancel.is_cancelled() {
        handle_cancelled(&url, &ctx, &progress).await;
        return;
    }

    if !wait_for_rate_limits(
        url.as_ref(),
        request_limiter.as_ref(),
        host_limiter.as_ref(),
        &cancel,
    )
    .await
    {
        handle_cancelled(&url, &ctx, &progress).await;
        return;
    }

    if cancel.is_cancelled() {
        handle_cancelled(&url, &ctx, &progress).await;
        return;
    }

    let process_start = std::time::Instant::now();
    let url_for_logging = Arc::clone(&url);

    // Process URL with timeout AND cancellation support.
    // Uses select! so Ctrl-C immediately aborts in-flight HTTP requests instead of
    // waiting for the full DRAIN_TIMEOUT.
    let result = tokio::select! {
        r = tokio::time::timeout(
            URL_PROCESSING_TIMEOUT,
            crate::utils::process_url(url, ctx.clone()),
        ) => r,
        () = cancel.cancelled() => {
            handle_cancelled(&url_for_logging, &ctx, &progress).await;
            return;
        }
    };

    match result {
        Ok(ProcessUrlResult {
            result: Ok(outcome),
            ..
        }) => handle_success(&url_for_logging, outcome, &progress),
        Ok(ProcessUrlResult {
            result: Err(e),
            retry_count,
        }) => {
            handle_failure(
                &url_for_logging,
                e,
                retry_count,
                process_start,
                &ctx,
                &progress,
            )
            .await;
        }
        Err(_) => handle_timeout(&url_for_logging, process_start, &ctx, &progress).await,
    }
}

/// Global then per-host admission. Returns `false` if cancelled while waiting.
async fn wait_for_rate_limits(
    url: &str,
    request_limiter: Option<&Arc<RateLimiter>>,
    host_limiter: Option<&Arc<HostRateLimiter>>,
    cancel: &CancellationToken,
) -> bool {
    if let Some(limiter) = request_limiter {
        tokio::select! {
            () = limiter.acquire() => {}
            () = cancel.cancelled() => return false,
        }
    }
    if let Some(limiter) = host_limiter {
        tokio::select! {
            () = limiter.acquire(url) => {}
            () = cancel.cancelled() => return false,
        }
    }
    true
}

/// Persist a `url_failures` row, then count the URL as failed.
///
/// Cooperative cancel used to increment `failed_urls` and return with no fact
/// row; finalize then overwrote `runs.failed_urls` from `url_failures` COUNT.
async fn handle_cancelled(
    url: &Arc<str>,
    ctx: &Arc<crate::fetch::ProcessingContext>,
    progress: &TaskProgress<'_>,
) {
    super::record_cooperative_cancel_failure(
        &ctx.pool,
        ctx.runtime.run_id.as_deref(),
        url.as_ref(),
    )
    .await;
    progress.failed_urls.fetch_add(1, Ordering::Relaxed);
    invoke_progress_callback(
        progress.progress_callback.as_ref(),
        progress.successful_urls,
        progress.failed_urls,
        progress.skipped_urls,
        progress.total_urls_for_callback,
    );
    ctx.runtime
        .error_stats
        .increment_error(ErrorType::ScanCancelled);
}

/// Handle successful URL processing.
fn handle_success(_url: &Arc<str>, outcome: UrlProcessOutcome, progress: &TaskProgress<'_>) {
    match outcome {
        UrlProcessOutcome::Inserted => {
            progress.successful_urls.fetch_add(1, Ordering::Relaxed);
        }
        UrlProcessOutcome::Updated => {
            // Same `(run_id, initial_domain)` as an earlier line: row refreshed, not a new success.
            progress.skipped_urls.fetch_add(1, Ordering::Relaxed);
        }
        UrlProcessOutcome::Skipped => {
            // Skips are finished work but not successes; counting them only in skipped_urls
            // keeps successful + failed + skipped ≈ attempted and avoids progress double-count.
            progress.skipped_urls.fetch_add(1, Ordering::Relaxed);
        }
    }
    invoke_progress_callback(
        progress.progress_callback.as_ref(),
        progress.successful_urls,
        progress.failed_urls,
        progress.skipped_urls,
        progress.total_urls_for_callback,
    );
}

/// Handle failed URL processing.
async fn handle_failure(
    url: &Arc<str>,
    error: anyhow::Error,
    retry_count: u32,
    process_start: std::time::Instant,
    ctx: &Arc<crate::fetch::ProcessingContext>,
    progress: &TaskProgress<'_>,
) {
    progress.failed_urls.fetch_add(1, Ordering::Relaxed);
    let elapsed = process_start.elapsed().as_secs_f64();
    invoke_progress_callback(
        progress.progress_callback.as_ref(),
        progress.successful_urls,
        progress.failed_urls,
        progress.skipped_urls,
        progress.total_urls_for_callback,
    );
    log::warn!("Failed to process URL {}: {error}", url.as_ref());

    let context = crate::storage::failure::extract_failure_context(&error);

    record_url_failure(crate::storage::failure::FailureRecordParams {
        pool: &ctx.pool,
        url: url.as_ref(),
        error: &error,
        context,
        retry_count,
        elapsed_time: elapsed,
        run_id: ctx.runtime.run_id.as_deref(),
    })
    .await;
}

/// Handle URL processing timeout.
async fn handle_timeout(
    url: &Arc<str>,
    process_start: std::time::Instant,
    ctx: &Arc<crate::fetch::ProcessingContext>,
    progress: &TaskProgress<'_>,
) {
    progress.failed_urls.fetch_add(1, Ordering::Relaxed);
    let elapsed = process_start.elapsed().as_secs_f64();
    invoke_progress_callback(
        progress.progress_callback.as_ref(),
        progress.successful_urls,
        progress.failed_urls,
        progress.skipped_urls,
        progress.total_urls_for_callback,
    );
    log::warn!(
        "Failed to process URL {} (timeout after {}s)",
        url.as_ref(),
        URL_PROCESSING_TIMEOUT.as_secs()
    );
    let timeout_error = anyhow::anyhow!(
        "Process URL timeout after {} seconds for {}",
        URL_PROCESSING_TIMEOUT.as_secs(),
        url.as_ref()
    );

    let context = crate::storage::failure::FailureContext {
        final_url: None,
        redirect_chain: Vec::new(),
        response_headers: Vec::new(),
    };

    // SAFETY: Cast from usize to u32 is safe here.
    // RETRY_MAX_ATTEMPTS is a compile-time constant set to 3, which is well within
    // the range of u32 (0 to 4,294,967,295).
    #[allow(clippy::cast_possible_truncation)]
    record_url_failure(crate::storage::failure::FailureRecordParams {
        pool: &ctx.pool,
        url: url.as_ref(),
        error: &timeout_error,
        context,
        retry_count: RETRY_MAX_ATTEMPTS as u32 - 1,
        elapsed_time: elapsed,
        run_id: ctx.runtime.run_id.as_deref(),
    })
    .await;

    ctx.runtime
        .error_stats
        .increment_error(ErrorType::ProcessUrlTimeout);
}

#[cfg(test)]
mod tests {
    use super::super::resources::UrlTaskParams;
    use super::*;
    use crate::error_handling::ProcessingStats;
    use crate::fetch::{NetworkContext, ProcessingContext, RuntimeContext};
    use crate::initialization::test_resolver;
    use crate::utils::TimingStats;
    use std::sync::atomic::AtomicUsize;
    use tokio::sync::Semaphore;
    use tokio_util::sync::CancellationToken;

    /// Builds a minimal `ProcessingContext` with migrations so `record_url_failure` can succeed.
    async fn minimal_ctx_with_migrations() -> Arc<ProcessingContext> {
        let pool = Arc::new(
            sqlx::SqlitePool::connect("sqlite::memory:")
                .await
                .expect("test pool"),
        );
        crate::storage::run_migrations(pool.as_ref())
            .await
            .expect("migrations");
        // Satisfy FK for url_failures.run_id when run_id is Some("run-1")
        sqlx::query("INSERT OR IGNORE INTO runs (run_id, start_time_ms) VALUES (?, ?)")
            .bind("run-1")
            .bind(chrono::Utc::now().timestamp_millis())
            .execute(pool.as_ref())
            .await
            .expect("insert run");
        let client = Arc::new(reqwest::Client::builder().build().expect("test client"));
        let redirect_client = Arc::new(
            reqwest::Client::builder()
                .redirect(reqwest::redirect::Policy::none())
                .build()
                .expect("test redirect client"),
        );
        let ctx = ProcessingContext::new(
            NetworkContext::new(client, redirect_client, test_resolver()),
            pool,
            RuntimeContext::new(
                Arc::new(ProcessingStats::new()),
                Arc::new(TimingStats::new()),
                Some("run-1".to_string()),
                false,
                std::path::PathBuf::from("/tmp/domain_status_whois_test"),
                false,
                Arc::new(crate::runtime_metrics::RuntimeMetrics::default()),
                true,
            ),
            Arc::new(crate::fingerprint::FingerprintRuleset::empty_for_tests()),
        );
        Arc::new(ctx)
    }

    #[tokio::test]
    async fn test_handle_success_counts_inserted_url_as_successful() {
        let url: Arc<str> = Arc::from("https://example.com");
        let successful_urls = Arc::new(AtomicUsize::new(0));
        let skipped_urls = Arc::new(AtomicUsize::new(0));
        let failed_urls = Arc::new(AtomicUsize::new(0));
        let progress = TaskProgress {
            successful_urls: &successful_urls,
            skipped_urls: &skipped_urls,
            failed_urls: &failed_urls,
            total_urls_for_callback: 1,
            progress_callback: &None,
        };

        handle_success(&url, UrlProcessOutcome::Inserted, &progress);

        assert_eq!(successful_urls.load(Ordering::SeqCst), 1);
        assert_eq!(skipped_urls.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn test_handle_success_counts_skipped_url_separately() {
        let url: Arc<str> = Arc::from("https://example.com");
        let successful_urls = Arc::new(AtomicUsize::new(0));
        let skipped_urls = Arc::new(AtomicUsize::new(0));
        let failed_urls = Arc::new(AtomicUsize::new(0));
        let progress = TaskProgress {
            successful_urls: &successful_urls,
            skipped_urls: &skipped_urls,
            failed_urls: &failed_urls,
            total_urls_for_callback: 1,
            progress_callback: &None,
        };

        handle_success(&url, UrlProcessOutcome::Skipped, &progress);

        assert_eq!(successful_urls.load(Ordering::SeqCst), 0);
        assert_eq!(skipped_urls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn test_handle_success_counts_updated_as_skipped_for_accounting() {
        let url: Arc<str> = Arc::from("https://example.com");
        let successful_urls = Arc::new(AtomicUsize::new(0));
        let skipped_urls = Arc::new(AtomicUsize::new(0));
        let failed_urls = Arc::new(AtomicUsize::new(0));
        let progress = TaskProgress {
            successful_urls: &successful_urls,
            skipped_urls: &skipped_urls,
            failed_urls: &failed_urls,
            total_urls_for_callback: 2,
            progress_callback: &None,
        };

        handle_success(&url, UrlProcessOutcome::Updated, &progress);

        assert_eq!(successful_urls.load(Ordering::SeqCst), 0);
        assert_eq!(skipped_urls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn test_handle_failure_increments_failed_urls_and_invokes_callback() {
        let url: Arc<str> = Arc::from("https://example.com/fail");
        let failed_urls = Arc::new(AtomicUsize::new(0));
        let skipped_urls = Arc::new(AtomicUsize::new(0));
        let ctx = minimal_ctx_with_migrations().await;
        let progress_calls = Arc::new(AtomicUsize::new(0));
        let callback: ProgressCallback = Some(Arc::new({
            let progress_calls = Arc::clone(&progress_calls);
            move |completed, failed, _skipped, _total| {
                progress_calls.store(completed + failed, Ordering::SeqCst);
            }
        }));

        let progress = TaskProgress {
            successful_urls: &Arc::new(AtomicUsize::new(0)),
            skipped_urls: &skipped_urls,
            failed_urls: &failed_urls,
            total_urls_for_callback: 1,
            progress_callback: &callback,
        };
        let err = anyhow::anyhow!("simulated failure");
        handle_failure(&url, err, 0, std::time::Instant::now(), &ctx, &progress).await;

        assert_eq!(failed_urls.load(Ordering::SeqCst), 1);
        assert_eq!(progress_calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn test_handle_failure_with_429_error_completes_without_panic() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .respond_with(wiremock::ResponseTemplate::new(429))
            .mount(&server)
            .await;

        let resp = reqwest::get(server.uri()).await.unwrap();
        let err = resp.error_for_status().unwrap_err();
        let anyhow_err = anyhow::anyhow!(err);

        let url: Arc<str> = Arc::from(server.uri().as_str());
        let failed_urls = Arc::new(AtomicUsize::new(0));
        let skipped_urls = Arc::new(AtomicUsize::new(0));
        let ctx = minimal_ctx_with_migrations().await;
        let progress = TaskProgress {
            successful_urls: &Arc::new(AtomicUsize::new(0)),
            skipped_urls: &skipped_urls,
            failed_urls: &failed_urls,
            total_urls_for_callback: 1,
            progress_callback: &None,
        };

        handle_failure(
            &url,
            anyhow_err,
            1,
            std::time::Instant::now(),
            &ctx,
            &progress,
        )
        .await;

        assert_eq!(failed_urls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn test_handle_failure_with_non_429_error_does_not_panic() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .respond_with(wiremock::ResponseTemplate::new(500))
            .mount(&server)
            .await;

        let resp = reqwest::get(server.uri()).await.unwrap();
        let err = resp.error_for_status().unwrap_err();
        let anyhow_err = anyhow::anyhow!(err);

        let url: Arc<str> = Arc::from(server.uri().as_str());
        let failed_urls = Arc::new(AtomicUsize::new(0));
        let skipped_urls = Arc::new(AtomicUsize::new(0));
        let ctx = minimal_ctx_with_migrations().await;
        let progress = TaskProgress {
            successful_urls: &Arc::new(AtomicUsize::new(0)),
            skipped_urls: &skipped_urls,
            failed_urls: &failed_urls,
            total_urls_for_callback: 1,
            progress_callback: &None,
        };

        handle_failure(
            &url,
            anyhow_err,
            0,
            std::time::Instant::now(),
            &ctx,
            &progress,
        )
        .await;

        assert_eq!(failed_urls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn test_handle_timeout_increments_failed_urls_and_error_stats() {
        let url: Arc<str> = Arc::from("https://example.com/timeout");
        let failed_urls = Arc::new(AtomicUsize::new(0));
        let skipped_urls = Arc::new(AtomicUsize::new(0));
        let ctx = minimal_ctx_with_migrations().await;
        let progress_calls = Arc::new(AtomicUsize::new(0));
        let callback: ProgressCallback = Some(Arc::new({
            let progress_calls = Arc::clone(&progress_calls);
            move |completed, failed, _skipped, _total| {
                progress_calls.store(completed + failed, Ordering::SeqCst);
            }
        }));

        let progress = TaskProgress {
            successful_urls: &Arc::new(AtomicUsize::new(0)),
            skipped_urls: &skipped_urls,
            failed_urls: &failed_urls,
            total_urls_for_callback: 1,
            progress_callback: &callback,
        };
        handle_timeout(&url, std::time::Instant::now(), &ctx, &progress).await;

        assert_eq!(failed_urls.load(Ordering::SeqCst), 1);
        assert_eq!(progress_calls.load(Ordering::SeqCst), 1);
        assert_eq!(
            ctx.runtime
                .error_stats
                .get_error_count(crate::error_handling::ErrorType::ProcessUrlTimeout),
            1
        );
    }

    #[tokio::test]
    async fn test_handle_failure_records_failure_when_db_ok() {
        let url: Arc<str> = Arc::from("https://example.com/record-fail");
        let failed_urls = Arc::new(AtomicUsize::new(0));
        let skipped_urls = Arc::new(AtomicUsize::new(0));
        let ctx = minimal_ctx_with_migrations().await;
        let progress_calls = Arc::new(AtomicUsize::new(0));
        let callback: ProgressCallback = Some(Arc::new({
            let progress_calls = Arc::clone(&progress_calls);
            move |_completed, failed, _skipped, _total| {
                progress_calls.store(failed, Ordering::SeqCst);
            }
        }));

        let progress = TaskProgress {
            successful_urls: &Arc::new(AtomicUsize::new(0)),
            skipped_urls: &skipped_urls,
            failed_urls: &failed_urls,
            total_urls_for_callback: 1,
            progress_callback: &callback,
        };
        let err = anyhow::anyhow!("simulated failure");
        handle_failure(&url, err, 0, std::time::Instant::now(), &ctx, &progress).await;

        assert_eq!(failed_urls.load(Ordering::SeqCst), 1);
        assert_eq!(progress_calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn test_process_url_task_cancel_persists_url_failure() {
        let ctx = minimal_ctx_with_migrations().await;
        let cancel = CancellationToken::new();
        cancel.cancel();
        let semaphore = Arc::new(Semaphore::new(1));
        let permit = semaphore.acquire_owned().await.expect("permit");
        let successful_urls = Arc::new(AtomicUsize::new(0));
        let skipped_urls = Arc::new(AtomicUsize::new(0));
        let failed_urls = Arc::new(AtomicUsize::new(0));

        process_url_task(UrlTaskParams {
            url: Arc::from("https://example.com/cancelled"),
            ctx: Arc::clone(&ctx),
            cancel,
            permit,
            request_limiter: None,
            host_limiter: None,
            successful_urls,
            skipped_urls,
            failed_urls: Arc::clone(&failed_urls),
            total_urls_for_callback: 1,
            progress_callback: None,
        })
        .await;

        assert_eq!(failed_urls.load(Ordering::SeqCst), 1);
        assert_eq!(
            ctx.runtime
                .error_stats
                .get_error_count(ErrorType::ScanCancelled),
            1
        );
        let count: i64 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM url_failures WHERE error_type = ? AND attempted_url = ?",
        )
        .bind(ErrorType::ScanCancelled.as_str())
        .bind("https://example.com/cancelled")
        .fetch_one(ctx.pool.as_ref())
        .await
        .expect("count url_failures");
        assert_eq!(count, 1, "cooperative cancel must leave a url_failures row");
    }
}