Skip to main content

weave_image/
lib.rs

1use std::io::Cursor;
2use std::time::Duration;
3
4use image::imageops::FilterType;
5use image::{DynamicImage, ImageReader};
6use sha2::{Digest, Sha256};
7
8/// Maximum source image download size (5 MB).
9const MAX_DOWNLOAD_BYTES: u64 = 5 * 1024 * 1024;
10
11/// Download timeout.
12const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15);
13
14/// Output thumbnail dimensions.
15const THUMB_WIDTH: u32 = 256;
16const THUMB_HEIGHT: u32 = 256;
17
18/// Maximum output thumbnail size (50 KB).
19const MAX_OUTPUT_BYTES: usize = 50 * 1024;
20
21/// SHA-256 hex prefix length for thumbnail keys.
22const KEY_HEX_LEN: usize = 32;
23
24/// Result of processing a thumbnail.
25#[derive(Debug, Clone)]
26pub struct ThumbnailResult {
27    /// Object key for storage: `thumbnails/{sha256_hex[0..32]}.webp`
28    pub key: String,
29    /// WebP image bytes.
30    pub data: Vec<u8>,
31}
32
33/// Errors that can occur during thumbnail processing.
34#[derive(Debug)]
35pub enum Error {
36    Download(String),
37    TooLarge(u64),
38    Decode(String),
39    Encode(String),
40}
41
42impl std::fmt::Display for Error {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        match self {
45            Self::Download(msg) => write!(f, "download failed: {msg}"),
46            Self::TooLarge(size) => write!(
47                f,
48                "source too large: {size} bytes (max {MAX_DOWNLOAD_BYTES})"
49            ),
50            Self::Decode(msg) => write!(f, "image decode failed: {msg}"),
51            Self::Encode(msg) => write!(f, "webp encode failed: {msg}"),
52        }
53    }
54}
55
56impl std::error::Error for Error {}
57
58/// Compute the thumbnail object key from a source URL.
59///
60/// Returns `thumbnails/{sha256_hex(url)[0..32]}.webp`.
61#[must_use]
62pub fn thumbnail_key(source_url: &str) -> String {
63    let mut hasher = Sha256::new();
64    hasher.update(source_url.as_bytes());
65    let hash = hasher.finalize();
66    let hex = hex_encode(&hash);
67    format!("thumbnails/{}.webp", &hex[..KEY_HEX_LEN])
68}
69
70/// Download image bytes from a URL.
71///
72/// Enforces a 5 MB size limit and 15s timeout.
73///
74/// # Errors
75///
76/// Returns `Error::Download` on network failure or non-success HTTP status,
77/// `Error::TooLarge` if the response exceeds 5 MB.
78pub fn download(url: &str) -> Result<Vec<u8>, Error> {
79    let rt = tokio::runtime::Builder::new_current_thread()
80        .enable_all()
81        .build()
82        .map_err(|e| Error::Download(e.to_string()))?;
83
84    rt.block_on(download_async(url))
85}
86
87async fn download_async(url: &str) -> Result<Vec<u8>, Error> {
88    let client = reqwest::Client::builder()
89        .timeout(DOWNLOAD_TIMEOUT)
90        .build()
91        .map_err(|e| Error::Download(e.to_string()))?;
92
93    let response = client
94        .get(url)
95        .send()
96        .await
97        .map_err(|e| Error::Download(e.to_string()))?;
98
99    if !response.status().is_success() {
100        return Err(Error::Download(format!("HTTP {}", response.status())));
101    }
102
103    if let Some(len) = response.content_length()
104        && len > MAX_DOWNLOAD_BYTES
105    {
106        return Err(Error::TooLarge(len));
107    }
108
109    let bytes = response
110        .bytes()
111        .await
112        .map_err(|e| Error::Download(e.to_string()))?;
113
114    if bytes.len() as u64 > MAX_DOWNLOAD_BYTES {
115        return Err(Error::TooLarge(bytes.len() as u64));
116    }
117
118    Ok(bytes.to_vec())
119}
120
121/// Resize image bytes to a WebP thumbnail with cover crop from center.
122///
123/// # Errors
124///
125/// Returns `Error::Decode` if the image cannot be parsed,
126/// `Error::Encode` if WebP encoding fails or output exceeds 50 KB.
127pub fn resize_to_webp(bytes: &[u8]) -> Result<Vec<u8>, Error> {
128    let img = decode_image(bytes)?;
129    let thumb = cover_crop(&img, THUMB_WIDTH, THUMB_HEIGHT);
130    encode_webp(&thumb)
131}
132
133/// Download an image, resize to thumbnail, and compute the storage key.
134///
135/// # Errors
136///
137/// Returns errors from download or resize stages.
138pub fn process_thumbnail(url: &str) -> Result<ThumbnailResult, Error> {
139    let key = thumbnail_key(url);
140    let bytes = download(url)?;
141    let data = resize_to_webp(&bytes)?;
142    Ok(ThumbnailResult { key, data })
143}
144
145fn decode_image(bytes: &[u8]) -> Result<DynamicImage, Error> {
146    let cursor = Cursor::new(bytes);
147    let reader = ImageReader::new(cursor)
148        .with_guessed_format()
149        .map_err(|e| Error::Decode(e.to_string()))?;
150    reader.decode().map_err(|e| Error::Decode(e.to_string()))
151}
152
153/// Center-crop and resize to exactly `width x height`.
154fn cover_crop(img: &DynamicImage, width: u32, height: u32) -> DynamicImage {
155    let (iw, ih) = (img.width(), img.height());
156    let target_ratio = f64::from(width) / f64::from(height);
157    let source_ratio = f64::from(iw) / f64::from(ih);
158
159    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
160    let cropped = if source_ratio > target_ratio {
161        let new_w = (f64::from(ih) * target_ratio) as u32;
162        let x = (iw - new_w) / 2;
163        img.crop_imm(x, 0, new_w, ih)
164    } else {
165        let new_h = (f64::from(iw) / target_ratio) as u32;
166        let y = (ih - new_h) / 2;
167        img.crop_imm(0, y, iw, new_h)
168    };
169
170    cropped.resize_exact(width, height, FilterType::Lanczos3)
171}
172
173fn encode_webp(img: &DynamicImage) -> Result<Vec<u8>, Error> {
174    let mut buf = Cursor::new(Vec::new());
175    img.write_with_encoder(image::codecs::webp::WebPEncoder::new_lossless(&mut buf))
176        .map_err(|e| Error::Encode(e.to_string()))?;
177
178    let data = buf.into_inner();
179    if data.len() > MAX_OUTPUT_BYTES {
180        return Err(Error::Encode(format!(
181            "output too large: {} bytes (max {MAX_OUTPUT_BYTES})",
182            data.len()
183        )));
184    }
185
186    Ok(data)
187}
188
189fn hex_encode(bytes: &[u8]) -> String {
190    bytes
191        .iter()
192        .fold(String::with_capacity(bytes.len() * 2), |mut s, b| {
193            use std::fmt::Write;
194            let _ = write!(s, "{b:02x}");
195            s
196        })
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202    use image::ImageFormat;
203
204    #[test]
205    fn thumbnail_key_is_deterministic() {
206        let key1 = thumbnail_key("https://example.com/photo.jpg");
207        let key2 = thumbnail_key("https://example.com/photo.jpg");
208        assert_eq!(key1, key2);
209    }
210
211    #[test]
212    fn thumbnail_key_different_urls_differ() {
213        let key1 = thumbnail_key("https://example.com/a.jpg");
214        let key2 = thumbnail_key("https://example.com/b.jpg");
215        assert_ne!(key1, key2);
216    }
217
218    #[test]
219    fn thumbnail_key_format() {
220        let key = thumbnail_key("https://example.com/photo.jpg");
221        assert!(key.starts_with("thumbnails/"));
222        assert!(key.ends_with(".webp"));
223        let hex_part = &key["thumbnails/".len()..key.len() - ".webp".len()];
224        assert_eq!(hex_part.len(), KEY_HEX_LEN);
225        assert!(hex_part.chars().all(|c| c.is_ascii_hexdigit()));
226    }
227
228    #[test]
229    fn resize_to_webp_produces_valid_output() {
230        let img = DynamicImage::new_rgb8(800, 600);
231        let mut png_bytes = Vec::new();
232        img.write_to(&mut Cursor::new(&mut png_bytes), ImageFormat::Png)
233            .ok();
234
235        let webp = resize_to_webp(&png_bytes);
236        assert!(webp.is_ok());
237        let data = webp.ok();
238        assert!(data.is_some());
239        let data = data.unwrap_or_default();
240        assert!(!data.is_empty());
241        assert!(data.len() <= MAX_OUTPUT_BYTES);
242    }
243
244    #[test]
245    fn resize_to_webp_is_256x256() {
246        let img = DynamicImage::new_rgb8(1024, 768);
247        let mut png_bytes = Vec::new();
248        img.write_to(&mut Cursor::new(&mut png_bytes), ImageFormat::Png)
249            .ok();
250
251        let webp = resize_to_webp(&png_bytes);
252        assert!(webp.is_ok());
253        let data = webp.unwrap_or_default();
254
255        let decoded = ImageReader::new(Cursor::new(&data))
256            .with_guessed_format()
257            .ok()
258            .and_then(|r| r.decode().ok());
259        assert!(decoded.is_some());
260        let decoded = decoded.unwrap_or_else(|| DynamicImage::new_rgb8(0, 0));
261        assert_eq!(decoded.width(), THUMB_WIDTH);
262        assert_eq!(decoded.height(), THUMB_HEIGHT);
263    }
264
265    #[test]
266    fn resize_to_webp_portrait_image() {
267        let img = DynamicImage::new_rgb8(400, 1200);
268        let mut png_bytes = Vec::new();
269        img.write_to(&mut Cursor::new(&mut png_bytes), ImageFormat::Png)
270            .ok();
271
272        let webp = resize_to_webp(&png_bytes);
273        assert!(webp.is_ok());
274    }
275
276    #[test]
277    fn resize_to_webp_square_image() {
278        let img = DynamicImage::new_rgb8(500, 500);
279        let mut png_bytes = Vec::new();
280        img.write_to(&mut Cursor::new(&mut png_bytes), ImageFormat::Png)
281            .ok();
282
283        let webp = resize_to_webp(&png_bytes);
284        assert!(webp.is_ok());
285    }
286
287    #[test]
288    fn resize_to_webp_tiny_image() {
289        let img = DynamicImage::new_rgb8(16, 16);
290        let mut png_bytes = Vec::new();
291        img.write_to(&mut Cursor::new(&mut png_bytes), ImageFormat::Png)
292            .ok();
293
294        let webp = resize_to_webp(&png_bytes);
295        assert!(webp.is_ok());
296    }
297
298    #[test]
299    fn resize_to_webp_invalid_bytes_fails() {
300        let result = resize_to_webp(b"not an image");
301        assert!(result.is_err());
302    }
303
304    #[test]
305    fn download_invalid_url_fails() {
306        let result = download("not-a-url");
307        assert!(result.is_err());
308    }
309
310    #[test]
311    fn hex_encode_works() {
312        assert_eq!(hex_encode(&[0x00, 0xff, 0xab]), "00ffab");
313    }
314}