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
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! 路由处理函数
//!
//! 从 mod.rs 拆出的 routes/health_check/version 函数实现。

// teams feature 关闭时不导入 teams 相关类型
#[cfg(feature = "teams")]
use crate::infrastructure::database::repositories::database_geo_restriction_repo::DatabaseGeoRestrictionRepository;
use crate::infrastructure::database::repositories::task_repo_impl::TaskRepositoryImpl;
// webhook feature 关闭时不导入 WebhookRepoImpl
#[cfg(feature = "webhook")]
use crate::infrastructure::database::repositories::webhook_repo_impl::WebhookRepoImpl;
use crate::presentation::handlers::{
    audit_handler, crawl_handler, extract_handler, metrics_handler, scrape_handler, search_handler,
    task_handler,
};
// webhook-off 时 webhook_handler 模块不编译
#[cfg(feature = "webhook")]
use crate::presentation::handlers::webhook_handler;
// teams-off 时 team_handler 模块不编译
#[cfg(feature = "teams")]
use crate::presentation::handlers::team_handler;
use axum::{
    routing::{get, post},
    Extension, Json, Router,
};
use dbnexus::sea_orm::ConnectionTrait;
use dbnexus::DbPool;
use std::sync::Arc;
use std::time::Duration;
// put 仅在 teams-on 时被使用(v1/teams/geo-restrictions PUT)
#[cfg(feature = "teams")]
use axum::routing::put;
use serde_json::json;

/// 创建应用路由
///
/// # 返回值
///
/// 返回配置好的路由
///
/// feature-off 时跳过对应路由注册。
/// `bootstrap/routes.rs::build_api_app_with_state` 是主装配入口,
/// 此函数保留用于 routes/mod.rs 单元测试。
pub fn routes() -> Router {
    let app = Router::new()
        .route("/health", get(health_check))
        .route("/metrics", get(metrics_handler::metrics))
        .route("/v1/version", get(version))
        .route("/v1/scrape", post(scrape_handler::create_scrape))
        .route("/v1/scrape/{id}", get(scrape_handler::get_scrape_status))
        .route(
            "/v1/scrape/{id}/_cancel",
            post(scrape_handler::cancel_scrape),
        )
        .route("/v1/crawl", post(crawl_handler::create_crawl))
        .route("/v1/crawl/{id}", get(crawl_handler::get_crawl))
        .route(
            "/v1/crawl/{id}/results",
            get(crawl_handler::get_crawl_results),
        )
        .route("/v1/crawl/{id}/_cancel", post(crawl_handler::cancel_crawl))
        .route("/v1/search", post(search_handler::search));

    // extract 路由按 teams feature 分裂
    #[cfg(feature = "teams")]
    let app = app.route(
        "/v1/extract",
        post(extract_handler::extract::<DatabaseGeoRestrictionRepository>),
    );
    #[cfg(not(feature = "teams"))]
    let app = app.route("/v1/extract", post(extract_handler::extract));

    // v1/webhooks 路由按 webhook feature 分裂
    #[cfg(feature = "webhook")]
    let app = app.route(
        "/v1/webhooks",
        post(webhook_handler::create_webhook::<WebhookRepoImpl>),
    );

    // v1/teams/* 路由按 teams feature 分裂
    #[cfg(feature = "teams")]
    let app = app
        .route(
            "/v1/teams/geo-restrictions",
            get(team_handler::get_team_geo_restrictions::<DatabaseGeoRestrictionRepository>),
        )
        .route(
            "/v1/teams/geo-restrictions",
            put(team_handler::update_team_geo_restrictions::<DatabaseGeoRestrictionRepository>),
        );

    app.route("/v1/audit/logs", get(audit_handler::get_audit_logs))
        .route("/v1/audit/denied", get(audit_handler::get_denied_requests))
        .route(
            "/v1/tasks/_query",
            post(task_handler::query_tasks::<TaskRepositoryImpl>),
        )
        .route(
            "/v1/tasks/_cancel",
            post(task_handler::cancel_tasks::<TaskRepositoryImpl>),
        )
}

/// 健康检查端点(liveness probe)
///
/// 这是 Kubernetes liveness probe — 总是返回 200 OK + "healthy",
/// 表示进程存活。不检查依赖(数据库、缓存)— 避免依赖短暂故障导致 pod 重启。
/// 如需 readiness probe(检查依赖是否就绪),应单独实现 /ready endpoint
/// 注入 CrawlRsState 检查数据库连接池、缓存可用性等。
///
/// # 返回值
///
/// 返回JSON格式的健康状态 + 版本号
pub async fn health_check() -> Json<serde_json::Value> {
    Json(json!({
        "status": "healthy",
        "version": env!("CARGO_PKG_VERSION"),
    }))
}

/// 版本信息端点
///
/// # 返回值
///
/// 返回应用版本号
pub async fn version() -> &'static str {
    env!("CARGO_PKG_VERSION")
}

/// 就绪检查端点(readiness probe)
///
/// Kubernetes readiness probe — 检查关键依赖(PostgreSQL、缓存)是否就绪。
/// 与 liveness probe(`/health`)不同,此端点验证实际依赖可用性。
///
/// # 返回值
///
/// - 200 OK + `"status": "ready"` — 所有依赖就绪
/// - 503 Service Unavailable + `"status": "not_ready"` — 任一依赖不可用
///
/// # 依赖检查
///
/// - PostgreSQL: 执行 `SELECT 1`,超时 3 秒
/// - 缓存: 执行 `get("__readiness_probe__")`,超时 1 秒
pub async fn readiness_check(
    Extension(db_pool): Extension<Arc<DbPool>>,
    Extension(cache_service): Extension<Arc<dyn crate::infrastructure::oxcache::CacheService>>,
) -> (axum::http::StatusCode, Json<serde_json::Value>) {
    use axum::http::StatusCode;

    let mut details = serde_json::Map::new();

    let (db_ready, db_status) = check_database(&db_pool).await;
    details.insert("database".to_string(), db_status);

    let (cache_ready, cache_status) = check_cache(&cache_service).await;
    details.insert("cache".to_string(), cache_status);

    // 连接池结构化健康快照(吸收自研 dbnexus `health-check`)
    //
    // `SELECT 1` 验证真实连通性;快照补充池视角(容量/空闲/等待等),
    // 仅作诊断信息附加,不影响就绪判定(快照失败不阻断响应)。
    details.insert(
        "database_pool".to_string(),
        database_pool_snapshot(&db_pool).await,
    );

    let all_ready = db_ready && cache_ready;
    let status = if all_ready { "ready" } else { "not_ready" };
    let status_code = if all_ready {
        StatusCode::OK
    } else {
        StatusCode::SERVICE_UNAVAILABLE
    };

    (
        status_code,
        Json(json!({
            "status": status,
            "checks": details,
            "version": env!("CARGO_PKG_VERSION"),
        })),
    )
}

/// PostgreSQL 就绪检查(`SELECT 1`,3 秒超时;自 [`readiness_check`] 提取)。
async fn check_database(db_pool: &Arc<DbPool>) -> (bool, serde_json::Value) {
    let db_check = async {
        let session = db_pool
            .get_session("system")
            .await
            .map_err(|e| e.to_string())?;
        let conn = session.connection().map_err(|e| e.to_string())?;
        conn.execute_unprepared("SELECT 1")
            .await
            .map_err(|e| e.to_string())?;
        Ok::<_, String>(())
    };

    match tokio::time::timeout(Duration::from_secs(3), db_check).await {
        Ok(Ok(())) => (true, json!({"status": "up"})),
        Ok(Err(e)) => {
            log::warn!("Readiness check: PostgreSQL down - {e}");
            (false, json!({"status": "down", "error": e}))
        }
        Err(_) => {
            log::warn!("Readiness check: PostgreSQL timeout (3s)");
            (false, json!({"status": "down", "error": "timeout"}))
        }
    }
}

/// 缓存就绪检查(`get("__readiness_probe__")`,1 秒超时;自 [`readiness_check`] 提取)。
async fn check_cache(
    cache_service: &Arc<dyn crate::infrastructure::oxcache::CacheService>,
) -> (bool, serde_json::Value) {
    let cache_check = async {
        cache_service
            .get("__readiness_probe__")
            .await
            .map_err(|e| e.to_string())?;
        Ok::<_, String>(())
    };

    match tokio::time::timeout(Duration::from_secs(1), cache_check).await {
        Ok(Ok(())) => (true, json!({"status": "up"})),
        Ok(Err(e)) => {
            log::warn!("Readiness check: cache down - {e}");
            (false, json!({"status": "down", "error": e}))
        }
        Err(_) => {
            log::warn!("Readiness check: cache timeout (1s)");
            (false, json!({"status": "down", "error": "timeout"}))
        }
    }
}

/// 连接池结构化健康快照 + prepare-cache 统计(自 [`readiness_check`] 提取)。
async fn database_pool_snapshot(db_pool: &Arc<DbPool>) -> serde_json::Value {
    let mut pool_snapshot =
        match tokio::time::timeout(Duration::from_secs(1), db_pool.health_snapshot()).await {
            Ok(snapshot) => snapshot,
            Err(_) => {
                log::warn!("Readiness check: pool health snapshot timeout (1s)");
                json!({"status": "timeout"})
            }
        };
    // 附带 prepare-cache 命中统计(dbnexus prepare-cache 启用且有统计时)
    if let Some(stats) = db_pool.prepare_cache_stats() {
        pool_snapshot["prepare_cache"] = json!({
            "size": stats.size,
            "hits": stats.hits,
            "misses": stats.misses,
            "evictions": stats.evictions,
        });
    }
    pool_snapshot
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::test_support::testcontainers_fixtures as tcf;
    use crate::infrastructure::database::dbnexus_connection::create_pool_with_retry;
    use crate::infrastructure::oxcache::CacheService;
    use axum::body::Body;
    use axum::http::{Method, Request, StatusCode};
    use axum::routing::get;
    use axum::Router;
    use std::sync::atomic::{AtomicBool, Ordering};
    use tower::ServiceExt;

    /// Mock CacheService that can be configured to succeed or fail.
    struct MockCacheService {
        should_fail: AtomicBool,
    }

    impl MockCacheService {
        fn new(should_fail: bool) -> Self {
            Self {
                should_fail: AtomicBool::new(should_fail),
            }
        }
    }

    impl CacheService for MockCacheService {
        fn get(
            &self,
            _key: &str,
        ) -> std::pin::Pin<
            Box<dyn std::future::Future<Output = anyhow::Result<Option<String>>> + Send + '_>,
        > {
            let should_fail = self.should_fail.load(Ordering::Relaxed);
            Box::pin(async move {
                if should_fail {
                    Err(anyhow::anyhow!("mock cache error"))
                } else {
                    Ok(None)
                }
            })
        }

        fn set(
            &self,
            _key: &str,
            _value: &str,
            _ttl_seconds: u64,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send + '_>>
        {
            Box::pin(async { Ok(()) })
        }

        fn delete(
            &self,
            _key: &str,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send + '_>>
        {
            Box::pin(async { Ok(()) })
        }

        fn exists(
            &self,
            _key: &str,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<bool>> + Send + '_>>
        {
            Box::pin(async { Ok(false) })
        }
    }

    async fn require_docker() -> bool {
        tcf::docker_available().await
    }

    /// Build a test router with readiness_check handler.
    fn build_ready_router(db_pool: Arc<DbPool>, cache_service: Arc<dyn CacheService>) -> Router {
        Router::new()
            .route("/ready", get(readiness_check))
            .layer(Extension(db_pool))
            .layer(Extension(cache_service))
    }

    /// 启动 testcontainers PostgreSQL 并创建连接池;环境级瞬时故障自愈。
    ///
    /// WSL2 Docker Desktop 高负载下端口转发可能出现持续断连
    /// (`ConnectionClosed`,同端口重试无法恢复)。本助手在池创建连续失败时
    /// 丢弃容器重启一次(新容器获得新映射端口);仍失败则返回 `None`,
    /// 调用方以显式 `[skip]` 降级(与 Docker 不可用路径同等语义),避免
    /// 环境抖动污染套件结果。
    async fn start_db_with_pool() -> Option<(tcf::DbHandle, Arc<DbPool>)> {
        for attempt in 1..=2 {
            let handle = match tcf::DbHandle::start().await {
                Ok(h) => h,
                Err(e) => {
                    eprintln!("[skip] failed to start DB container (attempt {attempt}): {e}");
                    return None;
                }
            };
            let settings = tcf::database_settings(&handle.pg.url);
            match create_pool_with_retry(&settings, 3, 1).await {
                Ok(pool) => return Some((handle, Arc::new(pool))),
                Err(e) => {
                    eprintln!(
                        "[warn] testcontainers DB pool creation failed (attempt {attempt}), \
                         restarting container: {e}"
                    );
                    // handle drop → 容器停止;下一次循环获得全新端口
                }
            }
        }
        eprintln!("[skip] testcontainers DB pool creation failed after container restart");
        None
    }

    #[tokio::test]
    async fn tc_readiness_all_up_returns_200() {
        if !require_docker().await {
            eprintln!("[skip] Docker unavailable — tc_readiness_all_up_returns_200");
            return;
        }
        let Some((_handle, pool)) = start_db_with_pool().await else {
            eprintln!("[skip] DB unavailable — tc_readiness_all_up_returns_200");
            return;
        };
        let cache = Arc::new(MockCacheService::new(false));
        let app = build_ready_router(pool, cache);

        let response = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/ready")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), 4096)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["status"], "ready");
        assert_eq!(json["checks"]["database"]["status"], "up");
        assert_eq!(json["checks"]["cache"]["status"], "up");
        assert!(json["version"].is_string());
    }

    #[tokio::test]
    async fn tc_readiness_cache_down_returns_503() {
        if !require_docker().await {
            eprintln!("[skip] Docker unavailable — tc_readiness_cache_down_returns_503");
            return;
        }
        let Some((_handle, pool)) = start_db_with_pool().await else {
            eprintln!("[skip] DB unavailable — tc_readiness_cache_down_returns_503");
            return;
        };
        let cache = Arc::new(MockCacheService::new(true)); // fails
        let app = build_ready_router(pool, cache);

        let response = app
            .oneshot(
                Request::builder()
                    .method(Method::GET)
                    .uri("/ready")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        let body = axum::body::to_bytes(response.into_body(), 4096)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["status"], "not_ready");
        assert_eq!(json["checks"]["database"]["status"], "up");
        assert_eq!(json["checks"]["cache"]["status"], "down");
    }
}