Skip to main content

graphrt_core/
file.rs

1//! File access contract.
2//!
3//! The runtime never touches storage itself. Nodes that need file bytes (document
4//! extraction, uploads, vision) ask the [`FileResolver`] registered in
5//! [`crate::node::Services`] as `Arc<dyn FileResolver>`. Hosts plug in their own
6//! storage (S3, blob store, database); this module provides an in-process
7//! resolver for inline data URLs and a [`ChainResolver`] to combine several.
8
9use std::fmt;
10use std::sync::Arc;
11
12use futures::future::BoxFuture;
13
14use crate::value::{File, FileTransfer};
15
16/// Error reading or storing a file.
17#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
18#[non_exhaustive]
19pub enum FileError {
20    #[error("no resolver can read file `{0}`")]
21    Unsupported(String),
22    #[error("file `{name}` exceeds the {limit}-byte limit")]
23    TooLarge { name: String, limit: u64 },
24    #[error("file `{name}` not found")]
25    NotFound { name: String },
26    #[error("access to file `{name}` denied: {reason}")]
27    Denied { name: String, reason: String },
28    #[error("reading file `{name}` failed: {message}")]
29    Io { name: String, message: String },
30    #[error("invalid file `{name}`: {message}")]
31    Invalid { name: String, message: String },
32}
33
34impl FileError {
35    /// Whether retrying might succeed (transient I/O).
36    pub fn is_retryable(&self) -> bool {
37        matches!(self, FileError::Io { .. })
38    }
39}
40
41/// File content with its detected media type.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct FileBytes {
44    pub bytes: Vec<u8>,
45    /// Media type if known (from the source or the file metadata).
46    pub mime_type: Option<String>,
47}
48
49/// Reads (and optionally stores) file content.
50pub trait FileResolver: Send + Sync + fmt::Debug {
51    /// Read the whole file, failing with [`FileError::TooLarge`] past `max_bytes`.
52    /// Return [`FileError::Unsupported`] for files this resolver does not handle,
53    /// so a [`ChainResolver`] can try the next one.
54    fn read<'a>(&'a self, file: &'a File, max_bytes: u64) -> BoxFuture<'a, Result<FileBytes, FileError>>;
55
56    /// Persist bytes produced by a node and return a [`File`] referencing them.
57    /// Default: unsupported.
58    fn store<'a>(
59        &'a self,
60        name: &'a str,
61        mime_type: Option<&'a str>,
62        bytes: Vec<u8>,
63    ) -> BoxFuture<'a, Result<File, FileError>> {
64        let _ = (mime_type, bytes);
65        Box::pin(futures::future::ready(Err(FileError::Unsupported(name.to_owned()))))
66    }
67}
68
69/// Turns an image file into a URL a model request can carry.
70///
71/// Nodes with `vision` ask the preparer registered in [`crate::node::Services`]
72/// as `Arc<dyn ImagePreparer>` for every image they send to a model. Without
73/// one, they send the file's own URL untouched. A preparer is where a host
74/// checks what an image really is, bounds its size and pixel count, removes
75/// metadata and downscales it (the `graphrt-image` crate provides one).
76pub trait ImagePreparer: Send + Sync + fmt::Debug {
77    /// A URL for `file`: `https://...` or `data:<media type>;base64,...`.
78    ///
79    /// [`FileError::Unsupported`] means "not mine": the node falls back to
80    /// the file's own URL. Every other error fails the node, so an image that
81    /// was refused is never sent anyway.
82    fn prepare<'a>(&'a self, file: &'a File) -> BoxFuture<'a, Result<String, FileError>>;
83}
84
85/// Resolves `inline` files and any file whose `url` is a `data:` URL.
86#[derive(Clone, Copy, Debug, Default)]
87pub struct DataUrlResolver;
88
89impl FileResolver for DataUrlResolver {
90    fn read<'a>(&'a self, file: &'a File, max_bytes: u64) -> BoxFuture<'a, Result<FileBytes, FileError>> {
91        let result = match file.url.as_deref() {
92            Some(url) if url.starts_with("data:") => decode_data_url(&file.name, url, max_bytes),
93            _ if file.transfer == FileTransfer::Inline => {
94                Err(FileError::Invalid { name: file.name.clone(), message: "inline file without a data URL".into() })
95            }
96            _ => Err(FileError::Unsupported(file.name.clone())),
97        };
98        let result = result.map(|mut fb| {
99            if fb.mime_type.is_none() {
100                fb.mime_type.clone_from(&file.mime_type);
101            }
102            fb
103        });
104        Box::pin(futures::future::ready(result))
105    }
106}
107
108/// Tries resolvers in order; the first one not returning `Unsupported` wins.
109#[derive(Clone, Debug, Default)]
110pub struct ChainResolver {
111    resolvers: Vec<Arc<dyn FileResolver>>,
112}
113
114impl ChainResolver {
115    pub fn new() -> Self {
116        Self::default()
117    }
118
119    /// Chain starting with the [`DataUrlResolver`].
120    pub fn with_data_urls() -> Self {
121        Self::new().then(Arc::new(DataUrlResolver))
122    }
123
124    pub fn then(mut self, resolver: Arc<dyn FileResolver>) -> Self {
125        self.resolvers.push(resolver);
126        self
127    }
128}
129
130impl FileResolver for ChainResolver {
131    fn read<'a>(&'a self, file: &'a File, max_bytes: u64) -> BoxFuture<'a, Result<FileBytes, FileError>> {
132        Box::pin(async move {
133            for resolver in &self.resolvers {
134                match resolver.read(file, max_bytes).await {
135                    Err(FileError::Unsupported(_)) => continue,
136                    other => return other,
137                }
138            }
139            Err(FileError::Unsupported(file.name.clone()))
140        })
141    }
142
143    fn store<'a>(
144        &'a self,
145        name: &'a str,
146        mime_type: Option<&'a str>,
147        bytes: Vec<u8>,
148    ) -> BoxFuture<'a, Result<File, FileError>> {
149        Box::pin(async move {
150            // Only the first resolver that supports storage is used; bytes cannot be
151            // cloned cheaply, so resolvers are probed in order with the same buffer.
152            let mut bytes = Some(bytes);
153            for resolver in &self.resolvers {
154                let Some(b) = bytes.take() else { break };
155                match resolver.store(name, mime_type, b.clone()).await {
156                    Err(FileError::Unsupported(_)) => bytes = Some(b),
157                    other => return other,
158                }
159            }
160            Err(FileError::Unsupported(name.to_owned()))
161        })
162    }
163}
164
165/// Decode a `data:[<mime>][;base64],<payload>` URL.
166pub fn decode_data_url(name: &str, url: &str, max_bytes: u64) -> Result<FileBytes, FileError> {
167    let invalid = |m: &str| FileError::Invalid { name: name.to_owned(), message: m.to_owned() };
168    let rest = url.strip_prefix("data:").ok_or_else(|| invalid("not a data URL"))?;
169    let (meta, payload) = rest.split_once(',').ok_or_else(|| invalid("data URL without ','"))?;
170    // The `;base64` flag is case-insensitive (RFC 2397 media-type parameters).
171    let is_base64 = meta.len() >= 7 && meta.get(meta.len() - 7..).is_some_and(|s| s.eq_ignore_ascii_case(";base64"));
172    let meta = if is_base64 { meta.get(..meta.len() - 7).unwrap_or_default() } else { meta };
173    let mime = meta.split(';').next().filter(|m| !m.is_empty()).map(str::to_owned);
174    let too_large = || FileError::TooLarge { name: name.to_owned(), limit: max_bytes };
175    let bytes = if is_base64 {
176        // Reject before decoding: base64 yields 3 bytes per 4 characters.
177        let estimate = u64::try_from(payload.len() / 4 * 3).unwrap_or(u64::MAX);
178        if estimate > max_bytes.saturating_add(3) {
179            return Err(too_large());
180        }
181        base64_decode(payload).ok_or_else(|| invalid("invalid base64 payload"))?
182    } else {
183        percent_decode(payload)
184    };
185    if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > max_bytes {
186        return Err(FileError::TooLarge { name: name.to_owned(), limit: max_bytes });
187    }
188    Ok(FileBytes { bytes, mime_type: mime })
189}
190
191/// Standard and URL-safe base64 decoder (padding optional, whitespace ignored).
192pub fn base64_decode(input: &str) -> Option<Vec<u8>> {
193    fn val(c: u8) -> Option<u32> {
194        match c {
195            b'A'..=b'Z' => Some(u32::from(c - b'A')),
196            b'a'..=b'z' => Some(u32::from(c - b'a') + 26),
197            b'0'..=b'9' => Some(u32::from(c - b'0') + 52),
198            b'+' | b'-' => Some(62),
199            b'/' | b'_' => Some(63),
200            _ => None,
201        }
202    }
203    let mut out = Vec::with_capacity(input.len() * 3 / 4);
204    let mut buf: u32 = 0;
205    let mut bits = 0u32;
206    let mut padding = false;
207    for c in input.bytes() {
208        if c.is_ascii_whitespace() {
209            continue;
210        }
211        if c == b'=' {
212            padding = true;
213            continue;
214        }
215        // Data after padding means a corrupted or concatenated payload.
216        if padding {
217            return None;
218        }
219        buf = (buf << 6) | val(c)?;
220        bits += 6;
221        if bits >= 8 {
222            bits -= 8;
223            out.push(u8::try_from((buf >> bits) & 0xff).ok()?);
224        }
225    }
226    // A single leftover character cannot encode a byte.
227    if bits >= 6 {
228        return None;
229    }
230    Some(out)
231}
232
233/// Standard base64 encoder with padding.
234pub fn base64_encode(bytes: &[u8]) -> String {
235    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
236    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
237    for chunk in bytes.chunks(3) {
238        let b = [
239            chunk.first().copied().unwrap_or(0),
240            chunk.get(1).copied().unwrap_or(0),
241            chunk.get(2).copied().unwrap_or(0),
242        ];
243        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
244        for i in 0..4 {
245            if i <= chunk.len() {
246                let idx = usize::try_from((n >> (18 - 6 * i)) & 63).unwrap_or(0);
247                out.push(char::from(TABLE.get(idx).copied().unwrap_or(b'A')));
248            } else {
249                out.push('=');
250            }
251        }
252    }
253    out
254}
255
256fn percent_decode(s: &str) -> Vec<u8> {
257    let bytes = s.as_bytes();
258    let mut out = Vec::with_capacity(bytes.len());
259    let mut i = 0;
260    while let Some(&b) = bytes.get(i) {
261        if b == b'%' {
262            let hex = bytes.get(i + 1..i + 3).and_then(|h| std::str::from_utf8(h).ok());
263            if let Some(v) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) {
264                out.push(v);
265                i += 3;
266                continue;
267            }
268        }
269        out.push(b);
270        i += 1;
271    }
272    out
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278
279    #[test]
280    fn base64_roundtrip() {
281        for s in ["", "a", "ab", "abc", "hello world", "\u{0}\u{1}\u{ff}"] {
282            let enc = base64_encode(s.as_bytes());
283            assert_eq!(base64_decode(&enc).unwrap(), s.as_bytes(), "{s:?}");
284        }
285        assert_eq!(base64_encode(b"hello"), "aGVsbG8=");
286    }
287
288    #[test]
289    fn data_url_decoding() {
290        let fb = decode_data_url("f", "data:text/plain;base64,aGVsbG8=", 100).unwrap();
291        assert_eq!(fb.bytes, b"hello");
292        assert_eq!(fb.mime_type.as_deref(), Some("text/plain"));
293        let fb = decode_data_url("f", "data:,a%20b", 100).unwrap();
294        assert_eq!(fb.bytes, b"a b");
295        // `;BASE64` is the same flag.
296        let fb = decode_data_url("f", "data:text/plain;BASE64,aGVsbG8=", 100).unwrap();
297        assert_eq!(fb.bytes, b"hello");
298        // Oversized payloads are rejected before decoding.
299        let big = format!("data:;base64,{}", "A".repeat(4000));
300        assert!(matches!(decode_data_url("f", &big, 100), Err(FileError::TooLarge { .. })));
301    }
302
303    #[test]
304    fn base64_rejects_trailing_garbage() {
305        assert_eq!(base64_decode("aGk="), Some(b"hi".to_vec()));
306        assert_eq!(base64_decode("aGk=aGk="), None);
307        assert_eq!(base64_decode("aGVsbG8"), Some(b"hello".to_vec()));
308        assert_eq!(base64_decode("a"), None);
309        assert!(matches!(decode_data_url("f", "data:,abc", 2), Err(FileError::TooLarge { .. })));
310    }
311
312    #[test]
313    fn chain_falls_through_unsupported() {
314        let chain = ChainResolver::with_data_urls();
315        let remote = File { name: "x".into(), url: Some("https://e.com/x".into()), ..File::default() };
316        let r = futures::executor::block_on(chain.read(&remote, 10));
317        assert!(matches!(r, Err(FileError::Unsupported(_))));
318        let inline = File { name: "y".into(), url: Some("data:,hi".into()), ..File::default() };
319        let r = futures::executor::block_on(chain.read(&inline, 10)).unwrap();
320        assert_eq!(r.bytes, b"hi");
321    }
322}