Skip to main content

utf8_forge/
fetcher.rs

1//! Optional remote download (`DESIGN.md §8`).
2//!
3//! Compiled only with the `remote` feature (default). Reuses the exact same
4//! `detect()` / `transcode()` pipeline as the local path — only the source of
5//! `raw_bytes` changes. Downloaded content is treated as untrusted text:
6//! strict decoding rejects malformed byte sequences, no shell is executed,
7//! no recursive link following.
8
9use std::path::PathBuf;
10use std::time::Duration;
11
12use crate::error::ForgeError;
13
14/// Fetch `url` into memory, capped by `max_size`.
15///
16/// `Content-Length` is checked before reading when present; the buffered
17/// body is checked again after reading (covers chunked responses without a
18/// declared length). Redirects are limited to 5; total timeout is 120 s,
19/// connect timeout 30 s (`DESIGN.md §8.4`).
20pub fn fetch_bytes(url: &str, max_size: u64) -> Result<Vec<u8>, ForgeError> {
21    let client = reqwest::blocking::Client::builder()
22        .connect_timeout(Duration::from_secs(30))
23        .timeout(Duration::from_secs(120))
24        .redirect(reqwest::redirect::Policy::limited(5))
25        .build()
26        .map_err(|e| ForgeError::Fetch(format!("client build failed: {e}")))?;
27
28    let resp = client
29        .get(url)
30        .send()
31        .map_err(|e| ForgeError::Fetch(format!("request failed: {e}")))?
32        .error_for_status()
33        .map_err(|e| ForgeError::Fetch(format!("http status: {e}")))?;
34
35    if let Some(len) = resp.content_length() {
36        if len > max_size {
37            return Err(ForgeError::TooLarge {
38                size: len,
39                max: max_size,
40            });
41        }
42    }
43
44    let body = resp
45        .bytes()
46        .map_err(|e| ForgeError::Fetch(format!("read body failed: {e}")))?;
47    let len = body.len() as u64;
48    if len > max_size {
49        return Err(ForgeError::TooLarge {
50            size: len,
51            max: max_size,
52        });
53    }
54    Ok(body.to_vec())
55}
56
57/// Derive the output path from the URL when `--output` is omitted
58/// (`DESIGN.md §8.2`):
59///
60/// - last non-empty path segment with an extension is kept verbatim
61///   (`.../legacy.cpp` → `legacy.cpp`);
62/// - a segment without an extension gets `.utf8` appended (`.../foo` → `foo.utf8`);
63/// - no usable segment → `download.utf8`.
64pub fn derive_output_path(url: &str) -> PathBuf {
65    let segment = url::Url::parse(url)
66        .ok()
67        .and_then(|u| {
68            u.path_segments()?
69                .next_back()
70                .map(str::to_owned)
71                .filter(|s| !s.is_empty())
72        });
73
74    match segment {
75        Some(seg) if has_extension(&seg) => PathBuf::from(seg),
76        Some(seg) => PathBuf::from(format!("{seg}.utf8")),
77        None => PathBuf::from("download.utf8"),
78    }
79}
80
81/// True when the last URL segment looks like a filename with an extension.
82fn has_extension(segment: &str) -> bool {
83    std::path::Path::new(segment)
84        .extension()
85        .map(|e| !e.is_empty())
86        .unwrap_or(false)
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92
93    #[test]
94    fn derive_keeps_extensioned_segments() {
95        assert_eq!(
96            derive_output_path("https://example.com/data/legacy.cpp"),
97            PathBuf::from("legacy.cpp")
98        );
99    }
100
101    #[test]
102    fn derive_appends_utf8_without_extension() {
103        assert_eq!(
104            derive_output_path("https://example.com/foo"),
105            PathBuf::from("foo.utf8")
106        );
107    }
108
109    #[test]
110    fn derive_falls_back_when_no_segment() {
111        assert_eq!(
112            derive_output_path("https://example.com/"),
113            PathBuf::from("download.utf8")
114        );
115        assert_eq!(
116            derive_output_path("not a url"),
117            PathBuf::from("download.utf8")
118        );
119    }
120
121    #[test]
122    fn derive_ignores_query_string() {
123        assert_eq!(
124            derive_output_path("https://example.com/a.cpp?raw=1"),
125            PathBuf::from("a.cpp")
126        );
127    }
128
129    #[test]
130    fn derive_treats_trailing_dot_as_missing_extension() {
131        assert_eq!(
132            derive_output_path("https://example.com/foo."),
133            PathBuf::from("foo..utf8")
134        );
135    }
136}