Skip to main content

pagesift_api/
server.rs

1//! HTTP server routing: Firecrawl v1/v2 compatibility layers, Jina Reader adapter,
2//! health checks, and Prometheus metrics.
3
4use std::collections::HashMap;
5use std::future::Future;
6use std::pin::{Pin, pin};
7use std::sync::Arc;
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::task::{Context, Poll};
10use std::time::{Duration, Instant};
11
12use axum::body::{Body, Bytes, HttpBody};
13use axum::extract::rejection::JsonRejection;
14use axum::extract::{Request, State};
15use axum::http::{HeaderMap, Method, StatusCode, header};
16use axum::middleware::{self, Next};
17use axum::response::{IntoResponse, Response};
18use axum::routing::get;
19use axum::{Json, Router};
20use http_body::{Frame, SizeHint};
21use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
22use hyper_util::server::conn::auto;
23use hyper_util::server::graceful::GracefulShutdown;
24use hyper_util::service::TowerToHyperService;
25use pagesift_store::Store;
26use tokio::net::TcpListener;
27use tokio::sync::Mutex;
28use tokio::time::Sleep;
29
30use crate::engine::Engine;
31use crate::error::{ApiError, ErrorCode};
32use crate::jobs::Jobs;
33use crate::limits::{Caller, KeyLimits, Limiter};
34use crate::metrics::Metrics;
35use crate::webhook::{WebhookConfig, WebhookSettings, Webhooks};
36
37/// Maximum documents per page when querying job status.
38pub const PAGE_SIZE: usize = 100;
39pub const DEFAULT_BATCH_CONCURRENCY: usize = 8;
40
41/// 服务端超时,防 slowloris 和挂死的请求。
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct Timeouts {
44    /// 读完请求头的时限(HTTP/1),超时直接断开连接。只在 [`serve_with`] 里生效。
45    pub header_read: Duration,
46    /// 从请求进来到读完请求体的总时限,不是两次读之间的间隔:每 5 秒滴 1 字节也会超时。
47    pub body: Duration,
48    /// 整个请求(到响应头发出为止)的时限。要比同步 scrape 的 `timeout` 上限大,
49    /// crawl/batch 只是创建任务,很快返回,不受影响。
50    pub request: Duration,
51}
52
53impl Default for Timeouts {
54    fn default() -> Self {
55        Self {
56            header_read: Duration::from_secs(30),
57            body: Duration::from_secs(30),
58            request: Duration::from_millis(crate::validate::MAX_SCRAPE_TIMEOUT_MS)
59                + Duration::from_secs(60),
60        }
61    }
62}
63
64#[derive(Clone, Default)]
65pub struct Config {
66    /// When empty, authentication is disabled; otherwise requires `Authorization: Bearer <key>`.
67    pub api_keys: Vec<String>,
68    /// Public URL for building absolute resource links.
69    pub public_url: Option<String>,
70    pub max_batch_concurrency: Option<usize>,
71    /// Persistent store for jobs and resume capability.
72    pub store: Option<Store>,
73    /// Per-key custom limits.
74    pub key_limits: HashMap<String, KeyLimits>,
75    /// Default limits applied to other keys or unauthenticated callers.
76    pub default_limits: KeyLimits,
77    pub webhook: WebhookSettings,
78    /// 请求体和整请求超时;请求头超时由 [`serve_with`] 的参数决定。
79    pub timeouts: Timeouts,
80}
81
82impl std::fmt::Debug for Config {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        f.debug_struct("Config")
85            .field("api_keys", &self.api_keys.len())
86            .field("public_url", &self.public_url)
87            .field("max_batch_concurrency", &self.max_batch_concurrency)
88            .field("store", &self.store.is_some())
89            .field("key_limits", &self.key_limits.len())
90            .field("default_limits", &self.default_limits)
91            .field("webhook", &self.webhook)
92            .field("timeouts", &self.timeouts)
93            .finish()
94    }
95}
96
97#[derive(Clone)]
98pub struct AppState {
99    pub engine: Arc<dyn Engine>,
100    pub keys: Arc<HashMap<String, Arc<KeyLimits>>>,
101    pub default_limits: Arc<KeyLimits>,
102    pub public_url: Option<String>,
103    pub batch_concurrency: usize,
104    pub jobs: Jobs,
105    pub limiter: Arc<Limiter>,
106    pub webhooks: Webhooks,
107    pub extracts: Arc<Mutex<HashMap<String, ExtractJob>>>,
108    pub metrics: Arc<Metrics>,
109}
110
111pub struct ExtractJob {
112    pub status: &'static str,
113    pub data: Option<serde_json::Value>,
114    pub error: Option<ApiError>,
115    pub created: std::time::SystemTime,
116}
117
118/// Construct complete HTTP router with Firecrawl v1/v2, Jina Reader, and metrics.
119pub fn router(engine: Arc<dyn Engine>, config: Config) -> Router {
120    let timeouts = config.timeouts;
121    let default_limits = Arc::new(config.default_limits);
122    let mut keys: HashMap<String, Arc<KeyLimits>> = config
123        .api_keys
124        .into_iter()
125        .map(|k| (k, default_limits.clone()))
126        .collect();
127    keys.extend(config.key_limits.into_iter().map(|(k, l)| (k, Arc::new(l))));
128
129    let accounts: HashMap<String, Arc<KeyLimits>> = keys
130        .iter()
131        .map(|(k, l)| {
132            (
133                Caller::new(Some(k), l.clone()).account.to_string(),
134                l.clone(),
135            )
136        })
137        .collect();
138
139    let metrics = Arc::new(Metrics::default());
140    let limiter = Arc::new(Limiter::new(config.store.clone()));
141    let webhooks = Webhooks::new(config.webhook, metrics.clone());
142    let jobs = Jobs::new(
143        config.store,
144        limiter.clone(),
145        Some(webhooks.clone()),
146        metrics.clone(),
147    );
148
149    if tokio::runtime::Handle::try_current().is_ok() {
150        let fallback = default_limits.clone();
151        jobs.restore(&engine, &|account| {
152            accounts
153                .get(account)
154                .cloned()
155                .unwrap_or_else(|| fallback.clone())
156        });
157    } else {
158        tracing::warn!("router built outside a tokio runtime: saved jobs are not resumed");
159    }
160
161    let state = AppState {
162        engine: engine.clone(),
163        keys: Arc::new(keys),
164        default_limits,
165        public_url: config
166            .public_url
167            .map(|u| u.trim_end_matches('/').to_string()),
168        batch_concurrency: config
169            .max_batch_concurrency
170            .unwrap_or(DEFAULT_BATCH_CONCURRENCY),
171        jobs,
172        limiter,
173        webhooks,
174        extracts: Arc::default(),
175        metrics,
176    };
177
178    let firecrawl = crate::firecrawl::firecrawl_routes()
179        .route_layer(middleware::from_fn_with_state(state.clone(), auth));
180    let jina = crate::jina::jina_router(engine);
181
182    Router::new()
183        .route("/healthz", get(|| async { "ok" }))
184        .route("/metrics", get(render_metrics))
185        .merge(firecrawl)
186        .with_state(state.clone())
187        .merge(jina)
188        .fallback(|| async { ApiError::new(ErrorCode::NotFound, "no such endpoint") })
189        .layer(middleware::from_fn(uniform_errors))
190        .layer(middleware::from_fn_with_state(timeouts, deadline))
191        .layer(middleware::from_fn_with_state(state.clone(), observe))
192}
193
194/// 用默认超时在 `listener` 上提供服务,`shutdown` 完成后优雅退出。
195pub async fn serve(
196    listener: TcpListener,
197    app: Router,
198    shutdown: impl Future<Output = ()> + Send,
199) -> std::io::Result<()> {
200    serve_with(listener, app, Timeouts::default(), shutdown).await
201}
202
203/// 和 `axum::serve(..).with_graceful_shutdown(..)` 行为相同,另外给 HTTP/1 设了请求头读取超时
204/// (axum::serve 设不了):收到 `shutdown` 后停止 accept,通知每个连接优雅关闭,等它们都结束再返回。
205pub async fn serve_with(
206    listener: TcpListener,
207    app: Router,
208    timeouts: Timeouts,
209    shutdown: impl Future<Output = ()> + Send,
210) -> std::io::Result<()> {
211    let mut builder = auto::Builder::new(TokioExecutor::new());
212    builder
213        .http1()
214        .timer(TokioTimer::new())
215        .header_read_timeout(timeouts.header_read);
216    let graceful = GracefulShutdown::new();
217    let mut shutdown = pin!(shutdown);
218    loop {
219        let stream = tokio::select! {
220            r = listener.accept() => match r {
221                Ok((stream, _)) => stream,
222                Err(e) => {
223                    // 和 axum::serve 一样:单个连接的错误忽略,其他错误(比如文件描述符用完)歇 1 秒再接
224                    if !matches!(
225                        e.kind(),
226                        std::io::ErrorKind::ConnectionRefused
227                            | std::io::ErrorKind::ConnectionAborted
228                            | std::io::ErrorKind::ConnectionReset
229                    ) {
230                        tracing::error!(error = %e, "accept failed");
231                        tokio::time::sleep(Duration::from_secs(1)).await;
232                    }
233                    continue;
234                }
235            },
236            () = &mut shutdown => break,
237        };
238        let conn = builder
239            .serve_connection_with_upgrades(
240                TokioIo::new(stream),
241                TowerToHyperService::new(app.clone()),
242            )
243            .into_owned();
244        let conn = graceful.watch(conn);
245        tokio::spawn(async move {
246            if let Err(e) = conn.await {
247                tracing::trace!(error = %e, "connection ended with an error");
248            }
249        });
250    }
251    drop(listener);
252    graceful.shutdown().await;
253    Ok(())
254}
255
256/// 请求体加总时限;整个请求加时限。超时都回统一的 JSON 错误(408 TIMEOUT)。
257async fn deadline(State(t): State<Timeouts>, req: Request, next: Next) -> Response {
258    let fired = Arc::new(AtomicBool::new(false));
259    let req = if req.body().is_end_stream() {
260        req
261    } else {
262        let fired = fired.clone();
263        req.map(|inner| {
264            Body::new(DeadlineBody {
265                inner,
266                sleep: Box::pin(tokio::time::sleep(t.body)),
267                fired,
268            })
269        })
270    };
271    match tokio::time::timeout(t.request, next.run(req)).await {
272        // 读请求体超时时提取器给的是 400,这里换成 408
273        Ok(_) if fired.load(Ordering::Relaxed) => ApiError::new(
274            ErrorCode::Timeout,
275            format!(
276                "request body was not received within {} s",
277                t.body.as_secs_f64()
278            ),
279        )
280        .into_response(),
281        Ok(resp) => resp,
282        Err(_) => ApiError::new(
283            ErrorCode::Timeout,
284            format!(
285                "request did not complete within {} s",
286                t.request.as_secs_f64()
287            ),
288        )
289        .into_response(),
290    }
291}
292
293/// 到点还没读完就报错的请求体。
294struct DeadlineBody {
295    inner: Body,
296    sleep: Pin<Box<Sleep>>,
297    fired: Arc<AtomicBool>,
298}
299
300impl HttpBody for DeadlineBody {
301    type Data = Bytes;
302    type Error = axum::Error;
303
304    fn poll_frame(
305        self: Pin<&mut Self>,
306        cx: &mut Context<'_>,
307    ) -> Poll<Option<Result<Frame<Bytes>, axum::Error>>> {
308        let this = self.get_mut();
309        if let Poll::Ready(frame) = Pin::new(&mut this.inner).poll_frame(cx) {
310            return Poll::Ready(frame);
311        }
312        if this.sleep.as_mut().poll(cx).is_ready() {
313            this.fired.store(true, Ordering::Relaxed);
314            return Poll::Ready(Some(Err(axum::Error::new("request body timed out"))));
315        }
316        Poll::Pending
317    }
318
319    fn is_end_stream(&self) -> bool {
320        self.inner.is_end_stream()
321    }
322
323    fn size_hint(&self) -> SizeHint {
324        self.inner.size_hint()
325    }
326}
327
328/// axum 自带的拒绝(查询参数、路径参数、JSON 解析失败、405 等)是纯文本或空 body,
329/// 统一换成 `{success: false, code, error}`,状态码和 `Allow` 等响应头不变。
330async fn uniform_errors(req: Request, next: Next) -> Response {
331    let resp = next.run(req).await;
332    let status = resp.status();
333    // 自己的错误都带 ErrorCode 扩展,不用动
334    if !status.is_client_error() || resp.extensions().get::<ErrorCode>().is_some() {
335        return resp;
336    }
337    let plain = resp
338        .headers()
339        .get(header::CONTENT_TYPE)
340        .is_none_or(|v| v.as_bytes().starts_with(b"text/plain"));
341    if !plain {
342        return resp;
343    }
344    let (parts, body) = resp.into_parts();
345    let text = axum::body::to_bytes(body, 64 * 1024)
346        .await
347        .map(|b| String::from_utf8_lossy(&b).trim().to_string())
348        .unwrap_or_default();
349    let code = match status {
350        StatusCode::NOT_FOUND => ErrorCode::NotFound,
351        StatusCode::PAYLOAD_TOO_LARGE => ErrorCode::TooLarge,
352        StatusCode::UNAUTHORIZED => ErrorCode::Unauthorized,
353        _ => ErrorCode::InvalidRequest,
354    };
355    let message = if text.is_empty() {
356        status
357            .canonical_reason()
358            .unwrap_or("bad request")
359            .to_lowercase()
360    } else {
361        text
362    };
363    let mut out = ApiError::new(code, message).into_response();
364    *out.status_mut() = status;
365    for (name, value) in &parts.headers {
366        if name != header::CONTENT_TYPE && name != header::CONTENT_LENGTH {
367            out.headers_mut().append(name, value.clone());
368        }
369    }
370    out
371}
372
373/// Authentication and rate limiting middleware.
374async fn auth(
375    State(s): State<AppState>,
376    headers: HeaderMap,
377    mut req: Request,
378    next: Next,
379) -> Response {
380    let caller = if s.keys.is_empty() {
381        Caller::new(None, s.default_limits.clone())
382    } else {
383        let key = headers
384            .get(header::AUTHORIZATION)
385            .and_then(|v| v.to_str().ok())
386            .and_then(|v| v.strip_prefix("Bearer "))
387            .map(str::trim);
388        match key.and_then(|k| s.keys.get(k).map(|l| (k, l))) {
389            Some((k, l)) => Caller::new(Some(k), l.clone()),
390            None => {
391                return ApiError::new(ErrorCode::Unauthorized, "missing or invalid API key")
392                    .into_response();
393            }
394        }
395    };
396    if req.method() == Method::POST
397        && let Err(e) = s.limiter.check_rate(&caller)
398    {
399        let mut resp = e.into_response();
400        resp.extensions_mut().insert(caller);
401        return resp;
402    }
403    req.extensions_mut().insert(caller.clone());
404    let mut resp = next.run(req).await;
405    resp.extensions_mut().insert(caller);
406    resp
407}
408
409/// Metrics and structured request tracing middleware.
410async fn observe(State(s): State<AppState>, req: Request, next: Next) -> Response {
411    let route = req
412        .extensions()
413        .get::<axum::extract::MatchedPath>()
414        .map(|p| p.as_str().to_string())
415        .unwrap_or_else(|| "unmatched".into());
416    let method = req.method().clone();
417    let started = Instant::now();
418    s.metrics.request_started();
419    let resp = next.run(req).await;
420    let elapsed = started.elapsed();
421    let status = resp.status().as_u16();
422    s.metrics.request_finished(&route, status, elapsed);
423    let code = resp.extensions().get::<ErrorCode>().map(|c| c.as_str());
424    if let Some(code) = code {
425        s.metrics.error(code, "http");
426    }
427    let account = resp.extensions().get::<Caller>().map(|c| c.account.clone());
428    let latency_ms = elapsed.as_secs_f64() * 1000.0;
429    if route.starts_with("/v2/") || route.starts_with("/v1/") || route.starts_with("/r") {
430        tracing::info!(
431            target: "pagesift::http",
432            %method, %route, status, latency_ms, account = account.as_deref(), code,
433            "request"
434        );
435    } else {
436        tracing::debug!(target: "pagesift::http", %method, %route, status, latency_ms, "request");
437    }
438    resp
439}
440
441pub fn body<T>(r: Result<Json<T>, JsonRejection>) -> Result<T, ApiError> {
442    r.map(|Json(v)| v)
443        .map_err(|e| ApiError::invalid(format!("invalid request body: {}", e.body_text())))
444}
445
446pub fn base_url(s: &AppState, headers: &HeaderMap) -> String {
447    if let Some(u) = &s.public_url {
448        return u.clone();
449    }
450    let host = headers
451        .get(header::HOST)
452        .and_then(|v| v.to_str().ok())
453        .unwrap_or("localhost:3002");
454    format!("http://{host}")
455}
456
457pub fn webhook(
458    s: &AppState,
459    v: Option<&serde_json::Value>,
460) -> Result<Option<WebhookConfig>, ApiError> {
461    v.filter(|v| !v.is_null())
462        .map(|v| WebhookConfig::parse(v, s.webhooks.ssrf()))
463        .transpose()
464}
465
466async fn render_metrics(State(s): State<AppState>) -> impl IntoResponse {
467    let out = s.metrics.render(&s.jobs.counts().await);
468    (
469        StatusCode::OK,
470        [(header::CONTENT_TYPE, "text/plain; version=0.0.4")],
471        out,
472    )
473}