crawlrs 0.2.0

crawlrs - Enterprise-grade web scraping and crawling platform built with Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Aggregated application dependency extractor.
//!
//! `CrawlRsDeps` bundles the five most-commonly-needed request extensions
//! (task queue, settings, task repository, rate-limiting service, and
//! auth state) into a single axum extractor so that handler signatures
//! stay concise and consistent.
//!
//! # Usage
//!
//! ```rust,ignore
//! async fn my_handler(CrawlRsDeps { queue, settings, task_repo, rate_limiting_service, auth_state }: CrawlRsDeps) -> impl IntoResponse {
//!     // ...
//! }
//! ```

use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde_json::json;
use std::sync::Arc;

use crate::config::settings::Settings;
use crate::domain::repositories::task_repository::TaskRepository;
use crate::domain::services::rate_limiting_service::RateLimitingService;
use crate::presentation::middleware::auth_middleware::AuthState;
use crate::queue::task_queue::TaskQueue;

/// Aggregated application dependencies extracted from request extensions.
///
/// # Fields
///
/// * `queue` - The task queue for enqueueing work items.
/// * `settings` - Application settings / configuration.
/// * `task_repo` - Repository for task persistence.
/// * `rate_limiting_service` - Rate-limiting service for quota / concurrency checks.
/// * `auth_state` - Authenticated caller state (team id, api key id).
#[derive(Clone)]
pub struct CrawlRsDeps {
    pub queue: Arc<dyn TaskQueue>,
    pub settings: Arc<Settings>,
    pub task_repo: Arc<dyn TaskRepository>,
    pub rate_limiting_service: Arc<dyn RateLimitingService>,
    pub auth_state: AuthState,
}

/// Rejection type returned when a required extension is missing.
fn missing_extension(name: &str) -> Response {
    let status = StatusCode::INTERNAL_SERVER_ERROR;
    let body = Json(json!({ "error": format!("Missing extension: {}", name) }));
    (status, body).into_response()
}

impl<S> FromRequestParts<S> for CrawlRsDeps
where
    S: Send + Sync,
{
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let queue = parts
            .extensions
            .get::<Arc<dyn TaskQueue>>()
            .cloned()
            .ok_or_else(|| missing_extension("TaskQueue"))?;

        let settings = parts
            .extensions
            .get::<Arc<Settings>>()
            .cloned()
            .ok_or_else(|| missing_extension("Settings"))?;

        let task_repo = parts
            .extensions
            .get::<Arc<dyn TaskRepository>>()
            .cloned()
            .ok_or_else(|| missing_extension("TaskRepository"))?;

        let rate_limiting_service = parts
            .extensions
            .get::<Arc<dyn RateLimitingService>>()
            .cloned()
            .ok_or_else(|| missing_extension("RateLimitingService"))?;

        let auth_state = parts
            .extensions
            .get::<AuthState>()
            .cloned()
            .ok_or_else(|| missing_extension("AuthState"))?;

        Ok(CrawlRsDeps {
            queue,
            settings,
            task_repo,
            rate_limiting_service,
            auth_state,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use axum::extract::FromRequestParts;
    use axum::http::request::Parts;
    use axum::http::Request;
    use std::collections::HashSet;
    use std::sync::Arc;

    use crate::common::test_helpers::create_test_db_pool;
    use crate::domain::auth::ApiKeyScope;
    use crate::domain::models::Task;
    use crate::domain::repositories::task_repository::{RepositoryError, TaskQueryParams};
    use crate::domain::services::rate_limiting_service::{
        BacklogService, ConcurrencyConfig, ConcurrencyControlService, ConcurrencyResult,
        QuotaService, RateLimitConfig, RateLimitResult, RateLimitService, RateLimitingError,
    };
    use crate::queue::task_queue::QueueError;

    // Mock types

    struct MockTaskQueue;

    #[async_trait]
    impl TaskQueue for MockTaskQueue {
        async fn enqueue(&self, task: Task) -> Result<Task, QueueError> {
            Ok(task)
        }
        async fn dequeue(
            &self,
            _worker_id: crate::domain::id::Id,
        ) -> Result<Option<Task>, QueueError> {
            Ok(None)
        }
        async fn complete(&self, _task_id: crate::domain::id::Id) -> Result<(), QueueError> {
            Ok(())
        }
        async fn fail(&self, _task_id: crate::domain::id::Id) -> Result<(), QueueError> {
            Ok(())
        }
        async fn cancel(&self, _task_id: crate::domain::id::Id) -> Result<(), QueueError> {
            Ok(())
        }
    }

    struct MockTaskRepo;

    #[async_trait]
    impl crate::domain::repositories::task_repository::TaskRepository for MockTaskRepo {
        async fn create(&self, task: &Task) -> Result<Task, RepositoryError> {
            Ok(task.clone())
        }
        async fn find_by_id(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<Option<Task>, RepositoryError> {
            Ok(None)
        }
        async fn update(&self, task: &Task) -> Result<Task, RepositoryError> {
            Ok(task.clone())
        }
        async fn acquire_next(
            &self,
            _worker_id: crate::domain::id::Id,
        ) -> Result<Option<Task>, RepositoryError> {
            Ok(None)
        }
        async fn mark_completed(
            &self,
            _id: crate::domain::id::Id,
            _lock_token: Option<crate::domain::id::Id>,
        ) -> Result<u64, RepositoryError> {
            Ok(1)
        }
        async fn mark_failed(
            &self,
            _id: crate::domain::id::Id,
            _lock_token: Option<crate::domain::id::Id>,
        ) -> Result<u64, RepositoryError> {
            Ok(1)
        }
        async fn mark_cancelled(&self, _id: crate::domain::id::Id) -> Result<u64, RepositoryError> {
            Ok(1)
        }
        async fn exists_by_url(&self, _url: &str) -> Result<bool, RepositoryError> {
            Ok(false)
        }
        async fn find_existing_urls(
            &self,
            _urls: &[String],
        ) -> Result<HashSet<String>, RepositoryError> {
            Ok(HashSet::new())
        }
        async fn reset_stuck_tasks(
            &self,
            _timeout: chrono::Duration,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }
        async fn cancel_tasks_by_crawl_id(
            &self,
            _crawl_id: crate::domain::id::Id,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }
        async fn expire_tasks(&self) -> Result<u64, RepositoryError> {
            Ok(0)
        }
        async fn find_by_crawl_id(
            &self,
            _crawl_id: crate::domain::id::Id,
        ) -> Result<Vec<Task>, RepositoryError> {
            Ok(vec![])
        }
        async fn query_tasks(
            &self,
            _params: TaskQueryParams,
        ) -> Result<(Vec<Task>, u64), RepositoryError> {
            Ok((vec![], 0))
        }
        async fn batch_cancel(
            &self,
            _task_ids: Vec<crate::domain::id::Id>,
            _team_id: crate::domain::id::Id,
            _force: bool,
        ) -> Result<
            (
                Vec<crate::domain::id::Id>,
                Vec<(crate::domain::id::Id, String)>,
            ),
            RepositoryError,
        > {
            Ok((vec![], vec![]))
        }

        async fn renew_lock(
            &self,
            _task_id: crate::domain::id::Id,
            _worker_id: crate::domain::id::Id,
            _extend_seconds: i64,
        ) -> Result<bool, RepositoryError> {
            Ok(true)
        }
    }

    struct MockRateLimitService;

    #[async_trait]
    impl RateLimitService for MockRateLimitService {
        async fn check_rate_limit(
            &self,
            _api_key: &str,
            _endpoint: &str,
        ) -> Result<RateLimitResult, RateLimitingError> {
            Ok(RateLimitResult::Allowed)
        }
        async fn get_team_rate_limit_config(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<RateLimitConfig, RateLimitingError> {
            Ok(RateLimitConfig::default())
        }
        async fn update_team_rate_limit_config(
            &self,
            _team_id: crate::domain::id::Id,
            _config: RateLimitConfig,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }
        async fn cleanup_expired_rate_limits(&self) -> Result<u64, RateLimitingError> {
            Ok(0)
        }
    }

    #[async_trait]
    impl ConcurrencyControlService for MockRateLimitService {
        async fn check_team_concurrency(
            &self,
            _team_id: crate::domain::id::Id,
            _task_id: crate::domain::id::Id,
        ) -> Result<ConcurrencyResult, RateLimitingError> {
            Ok(ConcurrencyResult::Allowed)
        }
        async fn release_team_concurrency_slot(
            &self,
            _team_id: crate::domain::id::Id,
            _task_id: crate::domain::id::Id,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }
        async fn get_team_current_concurrency(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<u32, RateLimitingError> {
            Ok(0)
        }
        async fn get_team_concurrency_config(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<ConcurrencyConfig, RateLimitingError> {
            Ok(ConcurrencyConfig::default())
        }
        async fn update_team_concurrency_config(
            &self,
            _team_id: crate::domain::id::Id,
            _config: ConcurrencyConfig,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }
    }

    #[async_trait]
    impl BacklogService for MockRateLimitService {
        async fn process_backlog_tasks(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<u32, RateLimitingError> {
            Ok(0)
        }
    }

    #[async_trait]
    impl QuotaService for MockRateLimitService {
        async fn check_and_deduct_quota(
            &self,
            _team_id: crate::domain::id::Id,
            _amount: i64,
            _transaction_type: crate::domain::models::CreditsTransactionType,
            _description: String,
            _reference_id: Option<crate::domain::id::Id>,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }
        async fn get_quota_balance(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<i64, RateLimitingError> {
            Ok(1000)
        }

        async fn refund_quota(
            &self,
            _team_id: crate::domain::id::Id,
            _amount: i64,
            _description: String,
            _reference_id: Option<crate::domain::id::Id>,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }
    }

    #[async_trait]
    impl RateLimitingService for MockRateLimitService {}

    // Helper

    fn make_parts_with_extensions() -> Parts {
        let request = Request::builder().body(()).unwrap();
        let (mut parts, _) = request.into_parts();

        parts
            .extensions
            .insert(Arc::new(MockTaskQueue) as Arc<dyn TaskQueue>);
        parts
            .extensions
            .insert(Arc::new(Settings::default()) as Arc<Settings>);
        parts
            .extensions
            .insert(Arc::new(MockTaskRepo) as Arc<dyn TaskRepository>);
        parts
            .extensions
            .insert(Arc::new(MockRateLimitService) as Arc<dyn RateLimitingService>);
        parts.extensions.insert(AuthState::new(
            create_test_db_pool(),
            crate::domain::id::Id::generate(),
            crate::domain::id::Id::generate(),
            ApiKeyScope::default(),
        ));

        parts
    }

    // Tests

    #[tokio::test]
    async fn test_app_deps_extracts_all_fields() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let mut parts = make_parts_with_extensions();
        let result = CrawlRsDeps::from_request_parts(&mut parts, &()).await;
        assert!(result.is_ok(), "CrawlRsDeps should extract successfully");
    }

    #[tokio::test]
    async fn test_app_deps_missing_task_queue_returns_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let request = Request::builder().body(()).unwrap();
        let (mut parts, _) = request.into_parts();
        parts
            .extensions
            .insert(Arc::new(Settings::default()) as Arc<Settings>);
        parts
            .extensions
            .insert(Arc::new(MockTaskRepo) as Arc<dyn TaskRepository>);
        parts
            .extensions
            .insert(Arc::new(MockRateLimitService) as Arc<dyn RateLimitingService>);
        parts.extensions.insert(AuthState::new(
            create_test_db_pool(),
            crate::domain::id::Id::generate(),
            crate::domain::id::Id::generate(),
            ApiKeyScope::default(),
        ));

        let result = CrawlRsDeps::from_request_parts(&mut parts, &()).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_app_deps_missing_settings_returns_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let request = Request::builder().body(()).unwrap();
        let (mut parts, _) = request.into_parts();
        parts
            .extensions
            .insert(Arc::new(MockTaskQueue) as Arc<dyn TaskQueue>);
        parts
            .extensions
            .insert(Arc::new(MockTaskRepo) as Arc<dyn TaskRepository>);
        parts
            .extensions
            .insert(Arc::new(MockRateLimitService) as Arc<dyn RateLimitingService>);
        parts.extensions.insert(AuthState::new(
            create_test_db_pool(),
            crate::domain::id::Id::generate(),
            crate::domain::id::Id::generate(),
            ApiKeyScope::default(),
        ));

        let result = CrawlRsDeps::from_request_parts(&mut parts, &()).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_app_deps_missing_task_repo_returns_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let request = Request::builder().body(()).unwrap();
        let (mut parts, _) = request.into_parts();
        parts
            .extensions
            .insert(Arc::new(MockTaskQueue) as Arc<dyn TaskQueue>);
        parts
            .extensions
            .insert(Arc::new(Settings::default()) as Arc<Settings>);
        parts
            .extensions
            .insert(Arc::new(MockRateLimitService) as Arc<dyn RateLimitingService>);
        parts.extensions.insert(AuthState::new(
            create_test_db_pool(),
            crate::domain::id::Id::generate(),
            crate::domain::id::Id::generate(),
            ApiKeyScope::default(),
        ));

        let result = CrawlRsDeps::from_request_parts(&mut parts, &()).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_app_deps_missing_rate_limit_returns_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let request = Request::builder().body(()).unwrap();
        let (mut parts, _) = request.into_parts();
        parts
            .extensions
            .insert(Arc::new(MockTaskQueue) as Arc<dyn TaskQueue>);
        parts
            .extensions
            .insert(Arc::new(Settings::default()) as Arc<Settings>);
        parts
            .extensions
            .insert(Arc::new(MockTaskRepo) as Arc<dyn TaskRepository>);
        parts.extensions.insert(AuthState::new(
            create_test_db_pool(),
            crate::domain::id::Id::generate(),
            crate::domain::id::Id::generate(),
            ApiKeyScope::default(),
        ));

        let result = CrawlRsDeps::from_request_parts(&mut parts, &()).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_app_deps_missing_auth_state_returns_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let request = Request::builder().body(()).unwrap();
        let (mut parts, _) = request.into_parts();
        parts
            .extensions
            .insert(Arc::new(MockTaskQueue) as Arc<dyn TaskQueue>);
        parts
            .extensions
            .insert(Arc::new(Settings::default()) as Arc<Settings>);
        parts
            .extensions
            .insert(Arc::new(MockTaskRepo) as Arc<dyn TaskRepository>);
        parts
            .extensions
            .insert(Arc::new(MockRateLimitService) as Arc<dyn RateLimitingService>);

        let result = CrawlRsDeps::from_request_parts(&mut parts, &()).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_app_deps_empty_extensions_returns_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let request = Request::builder().body(()).unwrap();
        let (mut parts, _) = request.into_parts();

        let result = CrawlRsDeps::from_request_parts(&mut parts, &()).await;
        assert!(result.is_err());
    }

    #[test]
    fn test_app_deps_clone() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let deps = CrawlRsDeps {
            queue: Arc::new(MockTaskQueue),
            settings: Arc::new(Settings::default()),
            task_repo: Arc::new(MockTaskRepo),
            rate_limiting_service: Arc::new(MockRateLimitService),
            auth_state: AuthState::new(
                create_test_db_pool(),
                crate::domain::id::Id::generate(),
                crate::domain::id::Id::generate(),
                ApiKeyScope::default(),
            ),
        };
        let cloned = deps.clone();
        assert_eq!(cloned.auth_state.team_id, deps.auth_state.team_id);
        assert_eq!(cloned.auth_state.api_key_id, deps.auth_state.api_key_id);
    }

    #[test]
    fn test_app_deps_struct_fields_accessible() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let deps = CrawlRsDeps {
            queue: Arc::new(MockTaskQueue),
            settings: Arc::new(Settings::default()),
            task_repo: Arc::new(MockTaskRepo),
            rate_limiting_service: Arc::new(MockRateLimitService),
            auth_state: AuthState::new(
                create_test_db_pool(),
                crate::domain::id::Id::generate(),
                crate::domain::id::Id::generate(),
                ApiKeyScope::default(),
            ),
        };
        // Verify all 5 fields are accessible
        let _ = &deps.queue;
        let _ = &deps.settings;
        let _ = &deps.task_repo;
        let _ = &deps.rate_limiting_service;
        let _ = &deps.auth_state;
    }
}