1use 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
37pub const PAGE_SIZE: usize = 100;
39pub const DEFAULT_BATCH_CONCURRENCY: usize = 8;
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct Timeouts {
47 pub header_read: Duration,
49 pub body: Duration,
51 pub upload_body: Duration,
54 pub request: Duration,
57}
58
59impl Default for Timeouts {
60 fn default() -> Self {
61 Self {
62 header_read: Duration::from_secs(30),
63 body: Duration::from_secs(30),
64 upload_body: Duration::from_secs(120),
65 request: Duration::from_millis(crate::validate::MAX_SCRAPE_TIMEOUT_MS)
66 + Duration::from_secs(60),
67 }
68 }
69}
70
71#[derive(Clone, Default)]
72pub struct Config {
73 pub api_keys: Vec<String>,
75 pub public_url: Option<String>,
77 pub max_batch_concurrency: Option<usize>,
78 pub store: Option<Store>,
80 pub key_limits: HashMap<String, KeyLimits>,
82 pub default_limits: KeyLimits,
84 pub webhook: WebhookSettings,
85 pub timeouts: Timeouts,
87 pub ledger: Option<Arc<pagesift_cluster::Ledger>>,
90 pub job_mirror: Option<Arc<crate::JobMirror>>,
92 pub extra_metrics: Option<ExtraMetrics>,
94 pub monitor_leader: Option<crate::monitor::Leader>,
96}
97
98pub type ExtraMetrics = Arc<dyn Fn() -> String + Send + Sync>;
100
101impl std::fmt::Debug for Config {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 f.debug_struct("Config")
104 .field("api_keys", &self.api_keys.len())
105 .field("public_url", &self.public_url)
106 .field("max_batch_concurrency", &self.max_batch_concurrency)
107 .field("store", &self.store.is_some())
108 .field("key_limits", &self.key_limits.len())
109 .field("default_limits", &self.default_limits)
110 .field("webhook", &self.webhook)
111 .field("timeouts", &self.timeouts)
112 .field("ledger", &self.ledger.is_some())
113 .field("job_mirror", &self.job_mirror.is_some())
114 .field("extra_metrics", &self.extra_metrics.is_some())
115 .finish()
116 }
117}
118
119#[derive(Clone)]
120pub struct AppState {
121 pub engine: Arc<dyn Engine>,
122 pub keys: Arc<HashMap<String, Arc<KeyLimits>>>,
123 pub default_limits: Arc<KeyLimits>,
124 pub public_url: Option<String>,
125 pub batch_concurrency: Option<usize>,
127 pub jobs: Jobs,
128 pub limiter: Arc<Limiter>,
129 pub webhooks: Webhooks,
130 pub extracts: Arc<Mutex<HashMap<String, ExtractJob>>>,
131 pub agents: crate::agent::Agents,
132 pub(crate) monitors: crate::monitor::Monitors,
133 pub metrics: Arc<Metrics>,
134 pub extra_metrics: Option<ExtraMetrics>,
135}
136
137impl AppState {
138 pub fn batch_concurrency_for(&self, requested: Option<usize>) -> usize {
142 batch_concurrency(
143 requested,
144 self.engine.admitted_concurrency(),
145 self.batch_concurrency,
146 )
147 }
148}
149
150fn batch_concurrency(
151 requested: Option<usize>,
152 admitted: Option<usize>,
153 cap: Option<usize>,
154) -> usize {
155 let admitted = admitted.unwrap_or(cap.unwrap_or(DEFAULT_BATCH_CONCURRENCY));
156 requested
157 .unwrap_or(admitted)
158 .min(admitted)
159 .min(cap.unwrap_or(usize::MAX))
160 .max(1)
161}
162
163pub struct ExtractJob {
164 pub status: &'static str,
165 pub data: Option<serde_json::Value>,
166 pub error: Option<ApiError>,
167 pub created: std::time::SystemTime,
168}
169
170pub fn router(engine: Arc<dyn Engine>, config: Config) -> Router {
172 let timeouts = config.timeouts;
173 let default_limits = Arc::new(config.default_limits);
174 let mut keys: HashMap<String, Arc<KeyLimits>> = config
175 .api_keys
176 .into_iter()
177 .map(|k| (k, default_limits.clone()))
178 .collect();
179 keys.extend(config.key_limits.into_iter().map(|(k, l)| (k, Arc::new(l))));
180
181 let accounts: HashMap<String, Arc<KeyLimits>> = keys
182 .iter()
183 .map(|(k, l)| {
184 (
185 Caller::new(Some(k), l.clone()).account.to_string(),
186 l.clone(),
187 )
188 })
189 .collect();
190
191 let metrics = Arc::new(Metrics::default());
192 let limiter = Arc::new(match config.ledger {
193 Some(ledger) => {
194 let mut all = accounts.clone();
196 all.entry("anonymous".into())
197 .or_insert_with(|| default_limits.clone());
198 Limiter::with_ledger(ledger, &all)
199 }
200 None => Limiter::new(config.store.clone()),
201 });
202 if let Some(s) = &config.store
204 && tokio::runtime::Handle::try_current().is_ok()
205 {
206 crate::attachments::sweep_expired(crate::attachments::Disk {
207 store: s.clone(),
208 mirror: config.job_mirror.clone(),
209 });
210 }
211 let mut webhooks = Webhooks::new(config.webhook, metrics.clone());
212 webhooks.mirror = config.job_mirror.clone();
213 let agents = crate::agent::Agents::new(
214 config.store.clone(),
215 Some(webhooks.clone()),
216 Some(limiter.clone()),
217 );
218 let jobs = Jobs::new(
219 config.store,
220 limiter.clone(),
221 Some(webhooks.clone()),
222 metrics.clone(),
223 config.job_mirror,
224 );
225
226 if tokio::runtime::Handle::try_current().is_ok() {
227 let fallback = default_limits.clone();
228 jobs.restore(&engine, &|account| {
229 accounts
230 .get(account)
231 .cloned()
232 .unwrap_or_else(|| fallback.clone())
233 });
234 } else {
235 tracing::warn!("router built outside a tokio runtime: saved jobs are not resumed");
236 }
237
238 let monitors = crate::monitor::Monitors {
239 accounts: Arc::new(accounts),
240 default_limits: default_limits.clone(),
241 ..Default::default()
242 };
243 let state = AppState {
244 engine: engine.clone(),
245 keys: Arc::new(keys),
246 default_limits,
247 public_url: config
248 .public_url
249 .map(|u| u.trim_end_matches('/').to_string()),
250 batch_concurrency: config.max_batch_concurrency,
251 jobs,
252 limiter,
253 webhooks,
254 extracts: Arc::default(),
255 agents,
256 monitors,
257 metrics,
258 extra_metrics: config.extra_metrics,
259 };
260
261 if tokio::runtime::Handle::try_current().is_ok() {
263 crate::monitor::start_scheduler(state.clone(), config.monitor_leader.clone());
264 }
265 let api = crate::firecrawl::firecrawl_routes()
266 .merge(crate::jina::jina_routes())
267 .merge(crate::monitor::routes())
268 .route_layer(middleware::from_fn_with_state(state.clone(), auth));
269
270 Router::new()
271 .route("/healthz", get(|| async { "ok" }))
272 .route("/metrics", get(render_metrics))
273 .merge(api)
274 .with_state(state.clone())
275 .fallback(|| async { ApiError::new(ErrorCode::NotFound, "no such endpoint") })
276 .layer(middleware::from_fn(uniform_errors))
277 .layer(middleware::from_fn_with_state(timeouts, deadline))
278 .layer(middleware::from_fn_with_state(state.clone(), observe))
279}
280
281pub async fn serve(
283 listener: TcpListener,
284 app: Router,
285 shutdown: impl Future<Output = ()> + Send,
286) -> std::io::Result<()> {
287 serve_with(listener, app, Timeouts::default(), shutdown).await
288}
289
290const ACCEPT_RETRY_CAP: Duration = Duration::from_secs(1);
294
295pub async fn serve_with(
298 listener: TcpListener,
299 app: Router,
300 timeouts: Timeouts,
301 shutdown: impl Future<Output = ()> + Send,
302) -> std::io::Result<()> {
303 let mut builder = auto::Builder::new(TokioExecutor::new());
304 builder
305 .http1()
306 .timer(TokioTimer::new())
307 .header_read_timeout(timeouts.header_read);
308 let graceful = GracefulShutdown::new();
309 let mut shutdown = pin!(shutdown);
310 let released = Arc::new(tokio::sync::Notify::new());
312 loop {
313 let stream = tokio::select! {
314 r = listener.accept() => match r {
315 Ok((stream, _)) => stream,
316 Err(e) => {
317 if !matches!(
322 e.kind(),
323 std::io::ErrorKind::ConnectionRefused
324 | std::io::ErrorKind::ConnectionAborted
325 | std::io::ErrorKind::ConnectionReset
326 ) {
327 tracing::error!(error = %e, "accept failed");
328 tokio::select! {
329 () = released.notified() => {}
330 () = tokio::time::sleep(ACCEPT_RETRY_CAP) => {}
331 () = &mut shutdown => break,
332 }
333 }
334 continue;
335 }
336 },
337 () = &mut shutdown => break,
338 };
339 let _ = stream.set_nodelay(true);
341 let conn = builder
342 .serve_connection_with_upgrades(
343 TokioIo::new(stream),
344 TowerToHyperService::new(app.clone()),
345 )
346 .into_owned();
347 let conn = graceful.watch(conn);
348 let released = released.clone();
349 tokio::spawn(async move {
350 if let Err(e) = conn.await {
351 tracing::trace!(error = %e, "connection ended with an error");
352 }
353 released.notify_one();
354 });
355 }
356 drop(listener);
357 graceful.shutdown().await;
358 Ok(())
359}
360
361async fn deadline(State(t): State<Timeouts>, req: Request, next: Next) -> Response {
363 let fired = Arc::new(AtomicBool::new(false));
364 let (body_limit, request_limit) = if req.uri().path() == "/v2/parse" {
366 (
367 t.upload_body,
368 t.request + t.upload_body.saturating_sub(t.body),
369 )
370 } else {
371 (t.body, t.request)
372 };
373 let req = if req.body().is_end_stream() {
374 req
375 } else {
376 let fired = fired.clone();
377 req.map(|inner| {
378 Body::new(DeadlineBody {
379 inner,
380 sleep: Box::pin(tokio::time::sleep(body_limit)),
381 fired,
382 })
383 })
384 };
385 match tokio::time::timeout(request_limit, next.run(req)).await {
386 Ok(_) if fired.load(Ordering::Relaxed) => ApiError::new(
388 ErrorCode::Timeout,
389 format!(
390 "request body was not received within {} s",
391 body_limit.as_secs_f64()
392 ),
393 )
394 .into_response(),
395 Ok(resp) => resp,
396 Err(_) => ApiError::new(
397 ErrorCode::Timeout,
398 format!(
399 "request did not complete within {} s",
400 request_limit.as_secs_f64()
401 ),
402 )
403 .into_response(),
404 }
405}
406
407struct DeadlineBody {
409 inner: Body,
410 sleep: Pin<Box<Sleep>>,
411 fired: Arc<AtomicBool>,
412}
413
414impl HttpBody for DeadlineBody {
415 type Data = Bytes;
416 type Error = axum::Error;
417
418 fn poll_frame(
419 self: Pin<&mut Self>,
420 cx: &mut Context<'_>,
421 ) -> Poll<Option<Result<Frame<Bytes>, axum::Error>>> {
422 let this = self.get_mut();
423 if let Poll::Ready(frame) = Pin::new(&mut this.inner).poll_frame(cx) {
424 return Poll::Ready(frame);
425 }
426 if this.sleep.as_mut().poll(cx).is_ready() {
427 this.fired.store(true, Ordering::Relaxed);
428 return Poll::Ready(Some(Err(axum::Error::new("request body timed out"))));
429 }
430 Poll::Pending
431 }
432
433 fn is_end_stream(&self) -> bool {
434 self.inner.is_end_stream()
435 }
436
437 fn size_hint(&self) -> SizeHint {
438 self.inner.size_hint()
439 }
440}
441
442async fn uniform_errors(req: Request, next: Next) -> Response {
445 let resp = next.run(req).await;
446 let status = resp.status();
447 if !status.is_client_error() || resp.extensions().get::<ErrorCode>().is_some() {
449 return resp;
450 }
451 let plain = resp
452 .headers()
453 .get(header::CONTENT_TYPE)
454 .is_none_or(|v| v.as_bytes().starts_with(b"text/plain"));
455 if !plain {
456 return resp;
457 }
458 let (parts, body) = resp.into_parts();
459 let text = axum::body::to_bytes(body, 64 * 1024)
460 .await
461 .map(|b| String::from_utf8_lossy(&b).trim().to_string())
462 .unwrap_or_default();
463 let code = match status {
464 StatusCode::NOT_FOUND => ErrorCode::NotFound,
465 StatusCode::PAYLOAD_TOO_LARGE => ErrorCode::TooLarge,
466 StatusCode::UNAUTHORIZED => ErrorCode::Unauthorized,
467 _ => ErrorCode::InvalidRequest,
468 };
469 let message = if text.is_empty() {
470 status
471 .canonical_reason()
472 .unwrap_or("bad request")
473 .to_lowercase()
474 } else {
475 text
476 };
477 let mut out = ApiError::new(code, message).into_response();
478 *out.status_mut() = status;
479 for (name, value) in &parts.headers {
480 if name != header::CONTENT_TYPE && name != header::CONTENT_LENGTH {
481 out.headers_mut().append(name, value.clone());
482 }
483 }
484 out
485}
486
487async fn auth(
489 State(s): State<AppState>,
490 headers: HeaderMap,
491 mut req: Request,
492 next: Next,
493) -> Response {
494 let caller = if s.keys.is_empty() {
495 Caller::new(None, s.default_limits.clone())
496 } else {
497 let key = headers
498 .get(header::AUTHORIZATION)
499 .and_then(|v| v.to_str().ok())
500 .and_then(|v| v.strip_prefix("Bearer "))
501 .map(str::trim);
502 match key.and_then(|k| s.keys.get(k).map(|l| (k, l))) {
503 Some((k, l)) => Caller::new(Some(k), l.clone()),
504 None => {
505 return ApiError::new(ErrorCode::Unauthorized, "missing or invalid API key")
506 .into_response();
507 }
508 }
509 };
510 let path = req.uri().path();
512 if (req.method() == Method::POST || path.starts_with("/r/") || path.starts_with("/s/"))
513 && let Err(e) = s.limiter.check_rate(&caller)
514 {
515 let mut resp = e.into_response();
516 resp.extensions_mut().insert(caller);
517 return resp;
518 }
519 req.extensions_mut().insert(caller.clone());
520 let mut resp = next.run(req).await;
521 resp.extensions_mut().insert(caller);
522 resp
523}
524
525async fn observe(State(s): State<AppState>, req: Request, next: Next) -> Response {
527 let route = req
528 .extensions()
529 .get::<axum::extract::MatchedPath>()
530 .map(|p| p.as_str().to_string())
531 .unwrap_or_else(|| "unmatched".into());
532 let method = req.method().clone();
533 let started = Instant::now();
534 s.metrics.request_started();
535 let resp = next.run(req).await;
536 let elapsed = started.elapsed();
537 let status = resp.status().as_u16();
538 s.metrics.request_finished(&route, status, elapsed);
539 let code = resp.extensions().get::<ErrorCode>().map(|c| c.as_str());
540 if let Some(code) = code {
541 s.metrics.error(code, "http");
542 }
543 let account = resp.extensions().get::<Caller>().map(|c| c.account.clone());
544 let latency_ms = elapsed.as_secs_f64() * 1000.0;
545 if route.starts_with("/v2/") || route.starts_with("/v1/") || route.starts_with("/r") {
546 tracing::info!(
547 target: "pagesift::http",
548 %method, %route, status, latency_ms, account = account.as_deref(), code,
549 "request"
550 );
551 } else {
552 tracing::debug!(target: "pagesift::http", %method, %route, status, latency_ms, "request");
553 }
554 resp
555}
556
557pub fn body<T>(r: Result<Json<T>, JsonRejection>) -> Result<T, ApiError> {
558 r.map(|Json(v)| v)
559 .map_err(|e| ApiError::invalid(format!("invalid request body: {}", e.body_text())))
560}
561
562pub fn lenient_body<T: serde::de::DeserializeOwned>(
565 r: Result<Json<serde_json::Value>, JsonRejection>,
566 known: &[&[&str]],
567) -> Result<(T, Vec<String>), ApiError> {
568 use crate::fields;
569 let value = body(r)?;
570 let mut ignored = Vec::new();
571 if let Some(obj) = value.as_object() {
572 ignored = fields::unknown(obj, known);
573 if let Some(nested) = obj.get("scrapeOptions").and_then(|v| v.as_object()) {
574 let scrape = [
575 fields::names::<crate::types::ScrapeOptions>(),
576 fields::CLIENT_IDENTITY,
577 ];
578 ignored.extend(
579 fields::unknown(nested, &scrape)
580 .into_iter()
581 .map(|k| format!("scrapeOptions.{k}")),
582 );
583 }
584 }
585 let parsed = serde_json::from_value(value)
586 .map_err(|e| ApiError::invalid(format!("invalid request body: {e}")))?;
587 Ok((parsed, ignored))
588}
589
590pub fn base_url(s: &AppState, headers: &HeaderMap) -> String {
591 if let Some(u) = &s.public_url {
592 return u.clone();
593 }
594 let host = headers
595 .get(header::HOST)
596 .and_then(|v| v.to_str().ok())
597 .unwrap_or("localhost:3002");
598 format!("http://{host}")
599}
600
601pub fn webhook(
602 s: &AppState,
603 v: Option<&serde_json::Value>,
604) -> Result<Option<WebhookConfig>, ApiError> {
605 v.filter(|v| !v.is_null())
606 .map(|v| WebhookConfig::parse(v, s.webhooks.ssrf()))
607 .transpose()
608}
609
610async fn render_metrics(State(s): State<AppState>) -> impl IntoResponse {
611 let mut out = s.metrics.render(&s.jobs.counts().await);
612 if let Some(extra) = &s.extra_metrics {
613 out.push_str(&extra());
614 }
615 (
616 StatusCode::OK,
617 [(header::CONTENT_TYPE, "text/plain; version=0.0.4")],
618 out,
619 )
620}
621
622#[cfg(test)]
623mod batch_concurrency_tests {
624 use super::batch_concurrency;
625
626 #[test]
629 fn admission_decides_and_the_user_caps() {
630 assert_eq!(batch_concurrency(None, None, None), 8);
631 assert_eq!(batch_concurrency(Some(20), None, None), 8);
632 assert_eq!(batch_concurrency(Some(3), None, None), 3);
633 assert_eq!(batch_concurrency(None, None, Some(32)), 32);
634 assert_eq!(batch_concurrency(Some(64), None, Some(32)), 32);
635 assert_eq!(batch_concurrency(None, Some(50), None), 50);
636 assert_eq!(batch_concurrency(None, Some(50), Some(32)), 32);
637 assert_eq!(batch_concurrency(Some(5), Some(50), None), 5);
638 assert_eq!(batch_concurrency(Some(0), Some(0), None), 1);
639 }
640}