Skip to main content

pagesift_api/
validate.rs

1//! 请求校验:绕过类参数和引擎做不到的功能一律明确报错(PRD 6.5.1),不悄悄降级。
2
3use crate::engine::Engine;
4use crate::error::ApiError;
5use crate::types::{PdfParser, ScrapeOptions};
6
7/// URL 最长 8 KB:再长的 URL 浏览器和多数服务器都不接受,只会白白占内存。
8pub const MAX_URL_LEN: usize = 8 * 1024;
9/// 同步 scrape 的 `timeout` 上限(毫秒);整请求超时按它留余量。
10pub const MAX_SCRAPE_TIMEOUT_MS: u64 = 300_000;
11/// `waitFor` 上限(毫秒)。
12pub const MAX_WAIT_FOR_MS: u64 = 60_000;
13/// crawl 的 `limit` 上限。
14pub const MAX_CRAWL_LIMIT: usize = 100_000;
15/// crawl 的 `maxDiscoveryDepth` / `maxDepth` 上限。
16pub const MAX_CRAWL_DEPTH: u64 = 100;
17/// map 的 `limit` 上限,和 Firecrawl 文档一致。
18pub const MAX_MAP_LIMIT: usize = 100_000;
19/// batch scrape、extract 一次最多带多少个 URL。
20pub const MAX_URLS: usize = 10_000;
21
22pub fn check_url(raw: &str) -> Result<(), ApiError> {
23    if raw.len() > MAX_URL_LEN {
24        return Err(ApiError::invalid(format!(
25            "URL is too long: {} bytes, the maximum is {MAX_URL_LEN}",
26            raw.len()
27        )));
28    }
29    match url::Url::parse(raw) {
30        Ok(u) if matches!(u.scheme(), "http" | "https") && u.host().is_some() => Ok(()),
31        Ok(_) => Err(ApiError::invalid(format!(
32            "only http(s) URLs are supported: {raw}"
33        ))),
34        Err(e) => Err(ApiError::invalid(format!("invalid URL {raw:?}: {e}"))),
35    }
36}
37
38pub fn check_scrape_options(opts: &ScrapeOptions, engine: &dyn Engine) -> Result<(), ApiError> {
39    if opts
40        .formats
41        .iter()
42        .filter_map(|f| f.options.get("schema"))
43        .any(|schema| !schema.is_object())
44    {
45        return Err(ApiError::invalid("formats[].schema must be an object"));
46    }
47    // `POST /v2/scrape` 和 MCP 的 `pagesift_scrape` 在校验前取走这个字段;走到这里的是别的入口
48    if opts.keep_session {
49        return Err(ApiError::invalid(
50            "keepSession is only available on POST /v2/scrape",
51        ));
52    }
53    if opts.discover_scripts
54        && (opts.engine.as_deref() != Some("http")
55            || !opts.wants("links")
56            || opts.egress.is_some()
57            || !opts.headers.is_empty()
58            || opts.if_none_match.is_some()
59            || opts.if_modified_since.is_some())
60    {
61        return Err(ApiError::unsupported(
62            "discoverScripts requires HTTP engine, links, and no custom headers/egress/conditional request",
63        ));
64    }
65    if let Some(p) = opts.proxy.as_deref()
66        && !matches!(p, "basic" | "auto")
67    {
68        let valid_url = url::Url::parse(p)
69            .ok()
70            .is_some_and(|u| matches!(u.scheme(), "http" | "https" | "socks5" | "socks5h"));
71        if !valid_url {
72            return Err(ApiError::unsupported(format!(
73                "proxy {p:?} is not supported: use \"basic\", \"auto\", or a valid http/https/socks5 URL"
74            )));
75        }
76    }
77    if let Some(e) = opts.engine.as_deref()
78        && !matches!(e, "http" | "browser" | "auto")
79    {
80        return Err(ApiError::invalid(format!(
81            "engine must be http, browser or auto, got {e:?}"
82        )));
83    }
84    if let Some(t) = opts.respond_timing.as_deref() {
85        if !crate::types::RESPOND_TIMINGS.contains(&t) {
86            return Err(ApiError::invalid(format!(
87                "respondTiming must be one of {}",
88                crate::types::RESPOND_TIMINGS.join(", ")
89            )));
90        }
91        if t != "html" && opts.engine.as_deref() == Some("http") {
92            return Err(ApiError::invalid(format!(
93                "respondTiming {t:?} waits for the rendered page and needs engine browser or auto"
94            )));
95        }
96    }
97    if let Some(c) = &opts.chunking {
98        const KINDS: [&str; 8] = [
99            "recursive",
100            "headings",
101            "paragraphs",
102            "sentences",
103            "fixed_tokens",
104            "sliding_window",
105            "overlapping",
106            "regex",
107        ];
108        let kind = c.get("type").and_then(|t| t.as_str());
109        if !kind.is_some_and(|k| KINDS.contains(&k)) {
110            return Err(ApiError::invalid(format!(
111                "chunking.type must be one of {}",
112                KINDS.join(", ")
113            )));
114        }
115    }
116    let supported = engine.supported_formats();
117    if let Some(f) = opts
118        .formats
119        .iter()
120        .find(|f| !supported.contains(&f.kind.as_str()))
121    {
122        return Err(ApiError::unsupported(format!(
123            "format {:?} is not supported by this build (supported: {})",
124            f.kind,
125            supported.join(", ")
126        )));
127    }
128    if !opts.actions.is_empty() {
129        if !engine.supports_actions() {
130            return Err(ApiError::unsupported(engine.actions_unavailable()));
131        }
132        if opts.engine.as_deref() == Some("http") {
133            return Err(ApiError::invalid(
134                "actions run in a browser and cannot be combined with engine \"http\"",
135            ));
136        }
137        if opts.respond_timing.as_deref() == Some("html") {
138            return Err(ApiError::invalid(
139                "actions run in a browser and cannot be combined with respondTiming \"html\"",
140            ));
141        }
142    }
143    if let Some(t) = opts.timeout {
144        if t < 1000 {
145            return Err(ApiError::invalid("timeout must be at least 1000 ms"));
146        }
147        if t > MAX_SCRAPE_TIMEOUT_MS {
148            return Err(ApiError::invalid(format!(
149                "timeout must not exceed {MAX_SCRAPE_TIMEOUT_MS} ms"
150            )));
151        }
152        if opts.wait_for > t / 2 {
153            return Err(ApiError::invalid("waitFor must not exceed half of timeout"));
154        }
155    }
156    if opts.wait_for > MAX_WAIT_FOR_MS {
157        return Err(ApiError::invalid(format!(
158            "waitFor must not exceed {MAX_WAIT_FOR_MS} ms"
159        )));
160    }
161    // 抓到的是 PDF 时才用得上,但写错的 parsers 在抓取前就报出来(parse 也走这里)
162    PdfParser::from_parsers(opts.parsers.as_ref())?;
163    Ok(())
164}
165
166/// URL 数量的上限检查:batch scrape 和 extract 共用。
167pub fn check_url_count(n: usize) -> Result<(), ApiError> {
168    if n > MAX_URLS {
169        return Err(ApiError::invalid(format!(
170            "too many URLs: {n}, the maximum is {MAX_URLS}"
171        )));
172    }
173    Ok(())
174}
175
176/// `/v2/parse` 上传文件的大小上限,和 Firecrawl 一致(50 MB)。
177pub const MAX_PARSE_FILE_BYTES: usize = 50 * 1024 * 1024;
178
179/// `/v2/parse` 的选项:先过和 scrape 相同的检查,再拒绝只对网址有意义的选项
180/// (照 Firecrawl `getUnsupportedParseOptionError`,另加 pagesift 自己的抓取类扩展)。
181pub fn check_parse_options(opts: &ScrapeOptions, engine: &dyn Engine) -> Result<(), ApiError> {
182    check_scrape_options(opts, engine)?;
183    for kind in ["screenshot", "branding", "changeTracking"] {
184        if opts.wants(kind) {
185            return Err(ApiError::unsupported(format!(
186                "parse uploads do not support the {kind} format"
187            )));
188        }
189    }
190    let unsupported = [
191        (!opts.actions.is_empty(), "actions"),
192        (opts.wait_for > 0, "waitFor"),
193        (opts.location.is_some(), "location"),
194        (opts.mobile, "mobile"),
195        (
196            opts.engine.as_deref() == Some("browser"),
197            "engine \"browser\"",
198        ),
199        (opts.egress.is_some(), "egress"),
200        (opts.discover_scripts, "discoverScripts"),
201        (
202            opts.if_none_match.is_some() || opts.if_modified_since.is_some(),
203            "conditional requests",
204        ),
205        (
206            opts.proxy
207                .as_deref()
208                .is_some_and(|p| !matches!(p, "basic" | "auto")),
209            "proxy other than basic or auto",
210        ),
211    ];
212    if let Some((_, what)) = unsupported.iter().find(|(on, _)| *on) {
213        return Err(ApiError::unsupported(format!(
214            "parse uploads do not support {what}"
215        )));
216    }
217    Ok(())
218}