Skip to main content

ocre/
storage.rs

1//! File storage in Cloudflare R2: multipart uploads, attachments, streamed downloads.
2//!
3//! Like Active Storage without its extra tables: a file lives in the R2 bucket
4//! bound as `STORAGE` in cloudflare.config.ts, and the record that owns it keeps four
5//! columns (`<name>_key`, `<name>_filename`, `<name>_content_type`,
6//! `<name>_size`), read back as an [`Attachment`].
7//!
8//! The flow of an upload: the [`Multipart`] extractor reads the request,
9//! [`MultipartForm::file`] takes an [`Upload`], [`Validator::file`](crate::Validator::file)
10//! checks it against [`Rules`], [`store`] writes it to R2 and returns the
11//! [`Attachment`] to save with [`columns`] / [`column_changes`]. Downloads go
12//! through [`serve`] (ETag/304, `Range`, safe `Content-Disposition`); [`read`],
13//! [`delete`] and [`delete_attachments`] cover the rest. [`store_bytes`] stores
14//! app-made files and [`store_body`] streams a raw request body.
15//!
16//! Beyond the Worker: [`head`], [`exists`] and [`list`] inspect the bucket;
17//! [`presign_get`] / [`serve_redirect`] let browsers download straight from
18//! R2's S3 API; [`direct_upload`] and [`attach_direct_upload`] let them
19//! upload straight to it (no 100 MB request limit, no Worker memory), and
20//! [`purge_unattached`] deletes direct uploads no row adopted. [`analyze`]
21//! reads a file's real type and image size, [`Variant`] builds Cloudflare
22//! Image Transformations URLs, [`public_url`] links to a public bucket.
23//!
24//! Files another service writes or reads: [`create_multipart`],
25//! [`presign_part`], [`list_parts`], [`complete_multipart`],
26//! [`abort_multipart`] and [`list_multipart_uploads`] drive a multipart
27//! upload the app hands out (a GPU worker's output); [`read_range`] reads
28//! a piece of a large file and [`copy`] duplicates one inside the bucket.
29//!
30//! In debug builds (`ocre dev`, `ocre test`), every presigned URL points to
31//! the app's [`DEV_STORAGE_PATH`] route on the local bucket, so uploads and
32//! downloads that skip the Worker in production work locally too, without
33//! `R2_*` settings and without touching the real bucket.
34//!
35//! Keys are random (`<prefix>/<22 characters>`, 128 bits, never derived from
36//! file names) and never reused, so a stored object never changes: replacing
37//! a file means storing a new key and deleting the old one. `ocre g scaffold
38//! Post avatar:attachment` adds the binding, `ocre dev` keeps a local copy
39//! under `.wrangler/state`, `ocre deploy` creates the bucket.
40//!
41//! # Free plan
42//!
43//! R2 (free every month): 10 GB-month stored, 1M class A operations (each
44//! upload is one), 10M class B operations (each download or 304 is one),
45//! deletes free, no egress fees. R2 has to be enabled once in the dashboard,
46//! which asks for a payment method even for the free tier.
47//! Listing is a class A operation per call (up to 1,000 keys), `head` a
48//! class B one; presigning costs no operation (the browser's `PUT` or
49//! `GET` on the URL does).
50//!
51//! CPU: downloads never pass through WebAssembly ([`serve`] hands R2's stream
52//! to [`crate::serve`]). Uploads are read into memory and split: about 1.2 ms
53//! per 10 MB in WebAssembly, plus 0.15 ms per 10 MB to copy them to R2. A
54//! Worker has 128 MB and Cloudflare refuses request bodies over 100 MB on the
55//! Free plan, so keep limits in the tens of MB.
56//!
57//! # Examples
58//!
59//! ```rust,no_run
60//! use axum::{
61//!     extract::{Path, State},
62//!     http::HeaderMap,
63//!     response::Response,
64//! };
65//! use ocre::storage::{self, Attachment, Disposition, Multipart, Rules};
66//! use ocre::{Ctx, Error, IntoParam, OptionExt, Result, Validator, params};
67//!
68//! const AVATAR: Rules = Rules { max_bytes: 5 * 1024 * 1024, content_types: &["image/png", "image/jpeg"] };
69//! const FORM_LIMIT: usize = AVATAR.max_bytes as usize + 1024 * 1024;
70//!
71//! async fn upload(
72//!     State(ctx): State<Ctx>,
73//!     Path(id): Path<i64>,
74//!     Multipart(mut form): Multipart<FORM_LIMIT>,
75//! ) -> Result<String> {
76//!     let upload = form.file("avatar").ok_or_else(|| Error::bad_request("Choose a file"))?;
77//!     Validator::new().file("avatar", &upload, &AVATAR).finish()?;
78//!     let avatar = storage::store(&ctx, "users/avatar", upload).await?;
79//!     let mut values = Vec::from(storage::columns(Some(&avatar)));
80//!     values.push(id.into_param());
81//!     let sql = "UPDATE users SET avatar_key = ?1, avatar_filename = ?2, avatar_content_type = ?3, \
82//!                avatar_size = ?4 WHERE id = ?5";
83//!     if let Err(err) = ctx.db()?.execute(sql, values).await {
84//!         storage::delete(&ctx, &avatar.key).await?; // no row points to it
85//!         return Err(err);
86//!     }
87//!     Ok(avatar.key)
88//! }
89//!
90//! async fn download(State(ctx): State<Ctx>, Path(id): Path<i64>, headers: HeaderMap) -> Result<Response> {
91//!     let sql = "SELECT avatar_key AS key, avatar_filename AS filename, avatar_content_type AS content_type, \
92//!                avatar_size AS size FROM users WHERE id = ?1 AND avatar_key IS NOT NULL";
93//!     let avatar: Attachment = ctx.db()?.first(sql, params![id]).await?.or_404()?;
94//!     storage::serve(&ctx, &avatar, &headers, Disposition::Inline).await
95//! }
96//! ```
97
98mod analyze;
99mod multipart;
100mod presign;
101mod resumable;
102mod s3;
103mod variant;
104
105use std::fmt::Write as _;
106
107use axum::{
108    body::{Body, Bytes},
109    http::{HeaderMap, HeaderValue, StatusCode, header},
110    response::Response,
111};
112use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
113use serde::{Deserialize, Serialize};
114
115pub use crate::runtime::resumable::multipart_uploads;
116pub use crate::runtime::s3::{
117    abort_multipart, complete_multipart, copy, create_multipart, list_multipart_uploads, list_parts, presign_part,
118    read_range,
119};
120pub use crate::runtime::storage::{
121    attach_direct_upload, delete, delete_attachments, direct_upload, exists, head, list, presign_get, presign_put,
122    public_url, purge_unattached, read, read_first, serve, serve_redirect, store, store_body, store_bytes,
123};
124use crate::{Error, IntoParam, Param, Result, Validator, token::random_bytes};
125pub use analyze::{Analysis, analyze};
126pub use multipart::{Multipart, MultipartForm};
127pub use presign::{
128    DirectUpload, DirectUploadRequest, MAX_EXPIRES_IN, R2_ACCESS_KEY_ID, R2_ACCOUNT_ID, R2_BUCKET,
129    R2_SECRET_ACCESS_KEY, S3Endpoint,
130};
131pub(crate) use presign::{
132    attachment_from_head, check_expires_in, dev_get_url, presign_get_url, r2_endpoint, sign_key, upload_secret,
133    verify_key,
134};
135pub(crate) use resumable::check_part_numbers;
136pub use resumable::{
137    CompletedPart, FinishRequest, MAX_PART, MAX_PARTS, MAX_PARTS_PER_REQUEST, MAX_WORKER_PART, MultipartUpload,
138    PART_SIZE, PartUrls, PartsRequest, check_multipart, part_layout, presign_parts,
139};
140pub(crate) use s3::{
141    DEV_APP_URL, DEV_MARKERS, DevGet, DevPut, dev_parts_prefix, dev_upload_from_marker, dev_upload_marker, dev_url,
142    parse_parts, parse_uploads, upload_gone,
143};
144pub use s3::{DEV_STORAGE_PATH, PendingUpload, StoredPart};
145pub use variant::{Fit, Variant};
146
147/// Name of the R2 binding holding every file: `STORAGE: bindings.r2({ name: "<app>-storage" })` in cloudflare.config.ts.
148///
149/// The bucket itself is `<app>-storage`; the first generator that needs it
150/// adds the entry, and `ocre deploy` creates the bucket. Every function of
151/// this module fails with [`Error::Internal`] naming
152/// this entry when the binding is missing.
153///
154/// # Examples
155///
156/// ```
157/// assert_eq!(ocre::storage::STORAGE_BINDING, "STORAGE");
158/// ```
159pub const STORAGE_BINDING: &str = "STORAGE";
160
161/// `Cache-Control` of files sent by [`serve`]: browsers keep them but revalidate each time.
162///
163/// While the `ETag` matches, the browser gets a body-less `304 Not Modified`
164/// (still one R2 class B operation). `private` keeps shared caches from
165/// storing files that may belong to one user. Override the header on the
166/// returned response for files that may be cached longer.
167///
168/// # Examples
169///
170/// ```no_run
171/// use axum::{extract::State, http::{HeaderMap, HeaderValue, header}, response::Response};
172/// use ocre::{Ctx, Result, storage::{self, Attachment, Disposition}};
173///
174/// async fn logo(State(ctx): State<Ctx>, headers: HeaderMap) -> Result<Response> {
175///     let logo = Attachment {
176///         key: "public/logo".into(),
177///         filename: "logo.png".into(),
178///         content_type: "image/png".into(),
179///         size: 4096,
180///     };
181///     let mut response = storage::serve(&ctx, &logo, &headers, Disposition::Inline).await?;
182///     // Keys never change, so a public file can be cached for a year.
183///     let forever = HeaderValue::from_static("public, max-age=31536000, immutable");
184///     response.headers_mut().insert(header::CACHE_CONTROL, forever);
185///     Ok(response)
186/// }
187/// # assert_eq!(storage::CACHE_CONTROL, "private, no-cache");
188/// ```
189pub const CACHE_CONTROL: &str = "private, no-cache";
190
191/// A stored file, as saved with its record in four columns.
192///
193/// The columns of an attachment named `avatar` are `avatar_key`,
194/// `avatar_filename`, `avatar_content_type` and `avatar_size` (NULL-able for
195/// an optional attachment). [`store`] returns it, [`columns`] /
196/// [`column_changes`] bind it, and it deserializes from a row whose columns
197/// are aliased to `key`, `filename`, `content_type` and `size` (generated
198/// models expose it as `photo.image()`). It also serializes to JSON as is.
199///
200/// # Examples
201///
202/// ```
203/// use ocre::storage::Attachment;
204///
205/// let avatar = Attachment {
206///     key: "posts/avatar/2u1Vd0zJ8sQqS6rJq0rVmA".into(),
207///     filename: "me.png".into(),
208///     content_type: "image/png".into(),
209///     size: 2048,
210/// };
211/// assert_eq!(avatar.human_size(), "2 KB");
212///
213/// let row = serde_json::json!({ "key": "k", "filename": "a.pdf", "content_type": "application/pdf", "size": 10 });
214/// let from_row: Attachment = serde_json::from_value(row).unwrap();
215/// assert_eq!(from_row.filename, "a.pdf");
216/// ```
217#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
218pub struct Attachment {
219    /// Object key in the R2 bucket: `<prefix>/<22 random URL-safe characters>`.
220    pub key: String,
221    /// The uploader's file name, without directories or control characters.
222    pub filename: String,
223    /// Content type, lowercase and without parameters (`image/png`).
224    pub content_type: String,
225    /// Size in bytes.
226    pub size: i64,
227}
228
229impl Attachment {
230    /// A new attachment with a fresh random key under `prefix`, a cleaned-up
231    /// filename and a normalized content type.
232    pub(crate) fn prepare(prefix: &str, filename: &str, content_type: &str, size: u64) -> Self {
233        Self {
234            key: new_key(prefix),
235            filename: sanitize_filename(filename),
236            content_type: essence(content_type),
237            size: i64::try_from(size).unwrap_or(i64::MAX),
238        }
239    }
240
241    /// Formats the size for people with [`human_size`]: `512 bytes`, `2 KB`, `1.5 MB`.
242    ///
243    /// A negative size (only possible from a hand-edited row) reads `0 bytes`.
244    ///
245    /// # Examples
246    ///
247    /// ```
248    /// let file = ocre::storage::Attachment { size: 1536 * 1024, ..Default::default() };
249    /// assert_eq!(file.human_size(), "1.5 MB");
250    /// ```
251    pub fn human_size(&self) -> String {
252        human_size(u64::try_from(self.size).unwrap_or(0))
253    }
254}
255
256/// A file received in a `multipart/form-data` request, before it is stored.
257///
258/// Get it with [`MultipartForm::file`], check it with
259/// [`Validator::file`](crate::Validator::file), store it with [`store`]. The
260/// bytes are a slice of the request body held in memory (no copy until R2
261/// gets them).
262///
263/// # Examples
264///
265/// ```
266/// use ocre::storage::Upload;
267///
268/// let upload = Upload { filename: "notes.txt".into(), content_type: "text/plain".into(), bytes: "hi".into() };
269/// assert_eq!(upload.size(), 2);
270/// ```
271#[derive(Debug, Clone, Default, PartialEq)]
272pub struct Upload {
273    /// File name sent by the browser, cleaned up.
274    ///
275    /// Directories (`C:\Users\me\` from old Windows browsers) and control
276    /// characters are removed, the name is trimmed to 200 characters with its
277    /// extension kept, and `file` stands in when nothing is left.
278    pub filename: String,
279    /// Content type sent by the browser, lowercase without parameters.
280    ///
281    /// `application/octet-stream` when none was sent. The client chooses it:
282    /// check it against an allowlist with [`Validator::file`](crate::Validator::file).
283    pub content_type: String,
284    /// The file's bytes.
285    pub bytes: axum::body::Bytes,
286}
287
288impl Upload {
289    /// An upload made by the app (Active Storage's `attach(io:, filename:, content_type:)`), cleaned up like a browser's.
290    ///
291    /// For bytes that did not come from a form: a generated PDF, a fetched
292    /// image, a test fixture. The file name loses directories and control
293    /// characters, the content type is lowercased without parameters, as
294    /// [`MultipartForm::file`] does. Hand it to a model (`NewPhoto { image:
295    /// Some(upload), .. }`) or to [`store`]; [`store_bytes`] stores bytes directly.
296    ///
297    /// # Examples
298    ///
299    /// ```
300    /// use ocre::storage::Upload;
301    ///
302    /// let upload = Upload::new("reports/2026.pdf", "Application/PDF; x=y", b"%PDF-1.7".to_vec());
303    /// assert_eq!((upload.filename.as_str(), upload.content_type.as_str()), ("2026.pdf", "application/pdf"));
304    /// assert_eq!(upload.size(), 8);
305    /// ```
306    pub fn new(filename: &str, content_type: &str, bytes: impl Into<Bytes>) -> Self {
307        Self { filename: sanitize_filename(filename), content_type: essence(content_type), bytes: bytes.into() }
308    }
309
310    /// Returns the size of the file in bytes.
311    ///
312    /// # Examples
313    ///
314    /// ```
315    /// use ocre::storage::{Upload, human_size};
316    ///
317    /// let upload = Upload { bytes: vec![0; 1536].into(), ..Default::default() };
318    /// assert_eq!(upload.size(), 1536);
319    /// assert_eq!(human_size(upload.size()), "1.5 KB");
320    /// ```
321    pub fn size(&self) -> u64 {
322        self.bytes.len() as u64
323    }
324}
325
326/// An object in the bucket, as [`head`] and [`list`] describe it (without its bytes).
327///
328/// # Examples
329///
330/// ```
331/// use ocre::storage::StoredObject;
332///
333/// let object = StoredObject {
334///     key: "uploads/2u1Vd0zJ8sQqS6rJq0rVmA".into(),
335///     size: 2048,
336///     content_type: "image/png".into(),
337///     etag: "b6ab5f279cbcf9a1b96b3ab5b207cf94".into(),
338///     uploaded_at: 1_790_000_000,
339///     filename: None,
340/// };
341/// let attachment = object.attachment("C:\\me.png");
342/// assert_eq!((attachment.filename.as_str(), attachment.size), ("me.png", 2048));
343/// ```
344#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
345pub struct StoredObject {
346    /// Object key.
347    pub key: String,
348    /// Size in bytes.
349    pub size: u64,
350    /// Content type recorded with the object (`application/octet-stream` when none was).
351    pub content_type: String,
352    /// R2's entity tag, unquoted (the MD5 of the content for single-part uploads).
353    pub etag: String,
354    /// Upload time, in Unix seconds (compare with [`crate::now`]).
355    pub uploaded_at: i64,
356    /// File name recorded by [`store`] and friends; `None` for objects uploaded directly.
357    pub filename: Option<String>,
358}
359
360impl StoredObject {
361    /// The [`Attachment`] of this object under `filename` (cleaned up), with its recorded size and type.
362    ///
363    /// Check the object against [`Rules`] first ([`attach_direct_upload`] does both).
364    ///
365    /// # Examples
366    ///
367    /// ```
368    /// let object = ocre::storage::StoredObject { key: "k".into(), size: 3, content_type: "text/plain".into(), ..Default::default() };
369    /// assert_eq!(object.attachment("a.txt").content_type, "text/plain");
370    /// ```
371    pub fn attachment(&self, filename: &str) -> Attachment {
372        Attachment {
373            key: self.key.clone(),
374            filename: sanitize_filename(filename),
375            content_type: essence(&self.content_type),
376            size: i64::try_from(self.size).unwrap_or(i64::MAX),
377        }
378    }
379}
380
381/// One page of [`list`]: the objects, and the cursor of the next page.
382///
383/// # Examples
384///
385/// ```
386/// use ocre::storage::Listing;
387///
388/// let last_page = Listing { objects: vec![], cursor: None };
389/// assert!(last_page.cursor.is_none());
390/// ```
391#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
392pub struct Listing {
393    /// Objects in key order.
394    pub objects: Vec<StoredObject>,
395    /// Pass it to the next [`list`] call; `None` on the last page.
396    pub cursor: Option<String>,
397}
398
399/// What one [`purge_unattached`] call did: the keys it deleted, and where the next call resumes.
400///
401/// # Examples
402///
403/// ```
404/// let purged = ocre::storage::Purged { deleted: vec!["uploads/a".into()], cursor: None };
405/// assert_eq!(purged.deleted.len(), 1);
406/// ```
407#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
408pub struct Purged {
409    /// Keys deleted by this call.
410    pub deleted: Vec<String>,
411    /// Cursor of the next page of the listing; `None` once the prefix was listed to the end.
412    pub cursor: Option<String>,
413}
414
415/// Name of the Worker variable holding the base URL of a public bucket, for [`public_url`].
416///
417/// An `r2.dev` URL or a custom domain connected to the bucket (dashboard:
418/// R2 > bucket > Settings > Public access), as
419/// `STORAGE_PUBLIC_URL: bindings.text("https://files.example.com"),` in `worker.env`.
420///
421/// # Examples
422///
423/// ```
424/// assert_eq!(ocre::storage::STORAGE_PUBLIC_URL, "STORAGE_PUBLIC_URL");
425/// ```
426pub const STORAGE_PUBLIC_URL: &str = "STORAGE_PUBLIC_URL";
427
428/// `<base>/<key>`, with each key segment percent-encoded.
429pub(crate) fn join_public_url(base: Option<String>, key: &str) -> Result<String> {
430    let base = base.filter(|base| !base.trim().is_empty()).ok_or_else(|| {
431        Error::internal(format!(
432            "public file URLs need the {STORAGE_PUBLIC_URL} variable. Fix: allow public access to the bucket (dashboard: \
433             R2 > bucket > Settings > Public access: an r2.dev URL or a custom domain), then add \
434             `{STORAGE_PUBLIC_URL}: bindings.text(\"https://files.example.com\"),` to worker.env in cloudflare.config.ts"
435        ))
436    })?;
437    let mut url = base.trim().trim_end_matches('/').to_owned();
438    for segment in key.split('/') {
439        url.push('/');
440        for byte in segment.bytes() {
441            if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
442                url.push(byte as char);
443            } else {
444                write!(url, "%{byte:02X}").expect("writing to a String");
445            }
446        }
447    }
448    Ok(url)
449}
450
451/// `302 Found` to a presigned URL; browsers and shared caches may reuse it for half its lifetime.
452pub(crate) fn redirect_response(url: &str, expires_in: u64) -> Response {
453    let mut response = Response::new(Body::empty());
454    *response.status_mut() = StatusCode::FOUND;
455    response.headers_mut().insert(header::LOCATION, header_value(url));
456    let cache = format!("private, max-age={}", expires_in / 2);
457    response.headers_mut().insert(header::CACHE_CONTROL, header_value(&cache));
458    response
459}
460
461/// Largest page [`list`] asks R2 for.
462pub(crate) const MAX_LIST: u32 = 1000;
463
464/// Largest number of keys looked up per D1 query (D1 binds at most 100 parameters).
465pub(crate) const KEYS_PER_QUERY: usize = 100;
466
467/// Keys of the objects uploaded before `cutoff` (Unix seconds).
468pub(crate) fn stale_keys(objects: &[StoredObject], cutoff: i64) -> Vec<String> {
469    objects.iter().filter(|object| object.uploaded_at < cutoff).map(|object| object.key.clone()).collect()
470}
471
472/// `SELECT <column> AS key FROM <table> WHERE <column> IN (?1, ...)` for `count` keys.
473///
474/// `table` and `column` come from app code, never from requests; anything
475/// but ASCII letters, digits and `_` is refused.
476pub(crate) fn referenced_keys_sql(table: &str, column: &str, count: usize) -> Result<String> {
477    let identifier = |name: &str| {
478        !name.is_empty()
479            && !name.starts_with(|c: char| c.is_ascii_digit())
480            && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
481    };
482    if !identifier(table) || !identifier(column) {
483        return Err(Error::internal(format!(
484            "purge_unattached takes a table and a column name (letters, digits, `_`), not `{table}` / `{column}`"
485        )));
486    }
487    let placeholders: Vec<String> = (1..=count).map(|n| format!("?{n}")).collect();
488    Ok(format!("SELECT {column} AS key FROM {table} WHERE {column} IN ({})", placeholders.join(", ")))
489}
490
491/// Describes what a file field accepts: a size limit and a content-type allowlist.
492///
493/// Checked by [`Validator::file`](crate::Validator::file) before anything is
494/// stored. A `const`, so the [`Multipart`] request limit can be computed from
495/// it (generated forms use the sum of their files' limits plus 1 MB). The
496/// content type comes from the browser: the allowlist limits it, and
497/// [`Validator::file_content`](crate::Validator::file_content) checks the bytes match it.
498///
499/// # Examples
500///
501/// ```
502/// use ocre::storage::Rules;
503///
504/// const AVATAR: Rules = Rules { max_bytes: 5 * 1024 * 1024, content_types: &["image/png", "image/jpeg"] };
505/// const FORM_LIMIT: usize = AVATAR.max_bytes as usize + 1024 * 1024;
506/// assert_eq!(FORM_LIMIT, 6 * 1024 * 1024);
507/// assert!(AVATAR.allows("image/PNG"));
508/// assert!(!AVATAR.allows("image/svg+xml"));
509/// ```
510#[derive(Debug, Clone, Copy, PartialEq, Eq)]
511pub struct Rules {
512    /// Largest accepted file, in bytes (`u64`: multipart uploads take files
513    /// over 4 GB, more than a `usize` holds in WebAssembly). Request limits
514    /// are `usize`: `RULES.max_bytes as usize`.
515    pub max_bytes: u64,
516    /// Accepted content types, exact and lowercase (`image/png`).
517    ///
518    /// There is no wildcard: `image/*` would admit SVG, which can carry scripts.
519    pub content_types: &'static [&'static str],
520}
521
522impl Rules {
523    /// Returns whether `content_type` is in the allowlist, ignoring case and parameters.
524    ///
525    /// `Image/PNG; charset=binary` is compared as `image/png`; an empty type
526    /// counts as `application/octet-stream`. There is no wildcard matching.
527    ///
528    /// # Examples
529    ///
530    /// ```
531    /// use ocre::storage::Rules;
532    ///
533    /// const DOC: Rules = Rules { max_bytes: 1024, content_types: &["application/pdf", "text/plain"] };
534    /// assert!(DOC.allows("text/plain; charset=utf-8"));
535    /// assert!(DOC.allows("Application/PDF"));
536    /// assert!(!DOC.allows("text/html"));
537    /// assert!(!DOC.allows(""));
538    /// ```
539    pub fn allows(&self, content_type: &str) -> bool {
540        let essence = essence(content_type);
541        self.content_types.contains(&essence.as_str())
542    }
543}
544
545impl Validator {
546    /// Checks an uploaded file against `rules`: its size and its content type.
547    ///
548    /// Adds "is too large (maximum is 5 MB)" when the file is over
549    /// [`Rules::max_bytes`] and "has an unsupported type (allowed: image/png,
550    /// image/jpeg)" when [`Rules::allows`] refuses its type; both can be
551    /// reported at once. Run it before [`store`], so a refused file costs no
552    /// R2 operation. Returns `self` for chaining; [`finish`](crate::Validator::finish)
553    /// turns the collected messages into a 422.
554    ///
555    /// # Examples
556    ///
557    /// ```
558    /// use ocre::{Validator, storage::{Rules, Upload}};
559    ///
560    /// const DOC: Rules = Rules { max_bytes: 4, content_types: &["text/plain"] };
561    /// let upload = Upload { filename: "a.html".into(), content_type: "text/html".into(), bytes: "<p>hello</p>".into() };
562    /// let err = Validator::new().file("doc", &upload, &DOC).finish().unwrap_err();
563    /// assert_eq!(
564    ///     err.to_string(),
565    ///     "invalid: Doc is too large (maximum is 4 bytes), Doc has an unsupported type (allowed: text/plain)"
566    /// );
567    ///
568    /// let note = Upload { filename: "a.txt".into(), content_type: "text/plain".into(), bytes: "ok".into() };
569    /// assert!(Validator::new().file("doc", &note, &DOC).finish().is_ok());
570    /// ```
571    pub fn file(&mut self, field: &str, upload: &Upload, rules: &Rules) -> &mut Self {
572        self.file_size_and_type(field, upload.size(), &upload.content_type, rules)
573    }
574
575    /// [`Validator::file`]'s checks on a size and a content type (declared for a direct upload, or read by `head`).
576    pub(crate) fn file_size_and_type(
577        &mut self,
578        field: &str,
579        size: u64,
580        content_type: &str,
581        rules: &Rules,
582    ) -> &mut Self {
583        let too_large = size > rules.max_bytes;
584        self.check(field, too_large, format!("is too large (maximum is {})", human_size(rules.max_bytes)));
585        let allowed = rules.content_types.join(", ");
586        self.check(field, !rules.allows(content_type), format!("has an unsupported type (allowed: {allowed})"))
587    }
588}
589
590/// Tells [`serve`] whether the browser shows a file or downloads it.
591///
592/// Either way `Content-Disposition` carries the original file name (ASCII in
593/// `filename=`, UTF-8 in `filename*=` when needed, RFC 6266).
594///
595/// # Examples
596///
597/// ```
598/// use ocre::storage::Disposition;
599///
600/// // A download link: `?download=1` forces the "Save as" dialog.
601/// let download = true;
602/// let disposition = if download { Disposition::Download } else { Disposition::Inline };
603/// assert_eq!(disposition, Disposition::Download);
604/// ```
605#[derive(Debug, Clone, Copy, PartialEq, Eq)]
606pub enum Disposition {
607    /// Shows the file in the page or tab when its type is safe to display, and downloads anything else.
608    ///
609    /// Safe types: raster images (PNG, JPEG, GIF, WebP, AVIF, BMP, TIFF,
610    /// icons), PDF, plain text, audio and video (MPEG, Ogg, WAV, WebM, MP4).
611    /// HTML, SVG, XML and JavaScript are sent as `application/octet-stream`
612    /// downloads, so an uploaded file never runs as part of the app (Rails'
613    /// `content_types_allowed_inline` / `content_types_to_serve_as_binary`).
614    Inline,
615    /// Always downloads the file, with its original name.
616    Download,
617}
618
619/// Builds the query parameters for the four columns of one attachment, in column order.
620///
621/// The order is `<name>_key, <name>_filename, <name>_content_type,
622/// <name>_size`; `None` binds four NULLs (an optional attachment left empty).
623/// Generated `create` functions extend their `params!` with it. Reading the
624/// columns back needs no helper: `Attachment` deserializes from a row with
625/// `key`, `filename`, `content_type` and `size` columns.
626///
627/// # Examples
628///
629/// ```
630/// use ocre::{params, storage::{self, Attachment}};
631///
632/// let avatar = Attachment { key: "k".into(), filename: "a.png".into(), content_type: "image/png".into(), size: 3 };
633/// let mut values = params!["Ada"];
634/// values.extend(storage::columns(Some(&avatar)));
635/// assert_eq!(values, params!["Ada", "k", "a.png", "image/png", 3_i64]);
636///
637/// let empty = storage::columns(None);
638/// assert_eq!(empty[..], params![None::<i64>, None::<i64>, None::<i64>, None::<i64>]);
639/// ```
640pub fn columns(attachment: Option<&Attachment>) -> [Param; 4] {
641    match attachment {
642        Some(file) => [
643            file.key.as_str().into_param(),
644            file.filename.as_str().into_param(),
645            file.content_type.as_str().into_param(),
646            file.size.into_param(),
647        ],
648        None => {
649            [None::<i64>.into_param(), None::<i64>.into_param(), None::<i64>.into_param(), None::<i64>.into_param()]
650        }
651    }
652}
653
654/// Builds the parameters of an `UPDATE` of one attachment's columns: a change flag, then the four [`columns`].
655///
656/// `None` keeps the stored file (flag `false`, four NULLs that the SQL
657/// ignores), `Some(None)` clears the columns (flag `true`, four NULLs),
658/// `Some(Some(file))` points them to `file`. The generated SQL reads
659/// `avatar_key = CASE WHEN ?1 THEN ?2 ELSE avatar_key END, ...`, so one
660/// statement handles "unchanged", "removed" and "replaced" without building
661/// SQL at runtime. Deleting the replaced object is up to the caller
662/// ([`delete_attachments`], after the write succeeds).
663///
664/// # Examples
665///
666/// ```
667/// use ocre::{params, storage::{self, Attachment}};
668///
669/// let photo = Attachment { key: "k".into(), filename: "a.png".into(), content_type: "image/png".into(), size: 3 };
670/// assert_eq!(storage::column_changes(Some(Some(&photo))), params![true, "k", "a.png", "image/png", 3_i64][..]);
671/// let null = None::<i64>;
672/// assert_eq!(storage::column_changes(Some(None))[..], params![true, null, null, null, null]);
673/// assert_eq!(storage::column_changes(None)[0], params![false][0]);
674/// ```
675pub fn column_changes(change: Option<Option<&Attachment>>) -> [Param; 5] {
676    let [key, filename, content_type, size] = columns(change.flatten());
677    [change.is_some().into_param(), key, filename, content_type, size]
678}
679
680/// Formats a byte count for people, in powers of 1024 like Rails' `number_to_human_size`.
681///
682/// Below 1024 the count is exact (`1 byte`, `512 bytes`); above, it is
683/// rounded to one decimal, dropped when it is zero (`2 KB`, `1.5 MB`,
684/// `10 GB`). Units stop at TB. Used in the "is too large (maximum is 5 MB)"
685/// validation message and the 413 of [`Multipart`].
686///
687/// # Examples
688///
689/// ```
690/// use ocre::storage::human_size;
691///
692/// assert_eq!(human_size(1), "1 byte");
693/// assert_eq!(human_size(512), "512 bytes");
694/// assert_eq!(human_size(2048), "2 KB");
695/// assert_eq!(human_size(1536 * 1024), "1.5 MB");
696/// assert_eq!(human_size(10 * 1024 * 1024), "10 MB");
697/// assert_eq!(human_size(3 * 1024_u64.pow(5)), "3072 TB");
698/// ```
699pub fn human_size(bytes: u64) -> String {
700    const UNITS: [&str; 4] = ["KB", "MB", "GB", "TB"];
701    if bytes < 1024 {
702        return format!("{bytes} {}", if bytes == 1 { "byte" } else { "bytes" });
703    }
704    let mut value = bytes as f64 / 1024.0;
705    let mut unit = 0;
706    while value >= 1024.0 && unit < UNITS.len() - 1 {
707        value /= 1024.0;
708        unit += 1;
709    }
710    let rounded = (value * 10.0).round() / 10.0;
711    if rounded.fract() == 0.0 {
712        format!("{rounded:.0} {}", UNITS[unit])
713    } else {
714        format!("{rounded:.1} {}", UNITS[unit])
715    }
716}
717
718/// Sends bytes built by the handler as a file (Rails' `send_data`): a CSV export, a generated image, an `.ics` file.
719///
720/// Sets `Content-Type`, `Content-Length` and `Content-Disposition` with
721/// `filename` (sanitized; non-ASCII names kept in `filename*`). As with
722/// [`serve`], [`Disposition::Inline`] shows only types that are safe to
723/// display (images, PDF, plain text, audio, video) and downloads the rest,
724/// and types a browser could run (HTML, SVG, XML, JavaScript) are sent as
725/// `application/octet-stream`. Files already in R2 go through [`serve`]
726/// instead: it streams them without copying through WebAssembly, and
727/// answers `Range` and `If-None-Match` (Rails' `send_file`). The whole body
728/// is in memory, and the Worker's 128 MB memory limit applies; building it
729/// counts toward the 10 ms CPU budget.
730///
731/// # Examples
732///
733/// ```
734/// use ocre::storage::{Disposition, send_data};
735///
736/// let csv = "id,title\n1,Hello\n";
737/// let response = send_data(csv, "posts.csv", "text/csv", Disposition::Download);
738/// assert_eq!(response.headers()["content-type"], "text/csv");
739/// assert_eq!(response.headers()["content-disposition"], "attachment; filename=\"posts.csv\"");
740/// ```
741pub fn send_data(data: impl Into<Bytes>, filename: &str, content_type: &str, disposition: Disposition) -> Response {
742    data_response(data.into(), filename, content_type, disposition)
743}
744
745/// The browser side of direct uploads (Active Storage's `activestorage.js`):
746/// a script that sends the files of `<input type="file"
747/// data-direct-upload-url="...">` to R2 before its form is submitted.
748///
749/// Each file is signed by a POST to the input's URL (a handler calling
750/// [`direct_upload`]), then `PUT` to R2 with progress events
751/// (`direct-upload:start|progress|error|end`); the form then submits
752/// `<name>_key` and `<name>_filename` for [`attach_direct_upload`] instead
753/// of the file. It also uploads the files dropped into a Trix editor with
754/// `data-embeds-url` (Action Text attachments). Serve it with [`direct_upload_script`].
755pub const DIRECT_UPLOAD_JS: &str = include_str!("storage/direct_upload.js");
756
757/// Serves [`DIRECT_UPLOAD_JS`] at `GET /ocre/direct-upload.js`: merge it into
758/// the routes, then load it in the layout with
759/// `<script src="/ocre/direct-upload.js" defer></script>`.
760///
761/// # Examples
762///
763/// ```
764/// use axum::Router;
765/// use ocre::Ctx;
766///
767/// fn routes() -> Router<Ctx> {
768///     Router::new().merge(ocre::storage::direct_upload_script())
769/// }
770/// # let _ = routes;
771/// ```
772pub fn direct_upload_script<S: Clone + Send + Sync + 'static>() -> axum::Router<S> {
773    let script = || async {
774        let headers =
775            [(header::CONTENT_TYPE, "text/javascript; charset=utf-8"), (header::CACHE_CONTROL, "public, max-age=3600")];
776        (headers, DIRECT_UPLOAD_JS)
777    };
778    axum::Router::new().route("/ocre/direct-upload.js", axum::routing::get(script))
779}
780
781fn data_response(data: Bytes, filename: &str, content_type: &str, disposition: Disposition) -> Response {
782    let filename = sanitize_filename(filename);
783    let content_type = essence(content_type);
784    let binary = BINARY_TYPES.contains(&content_type.as_str());
785    let sent_type = if binary { "application/octet-stream" } else { &content_type };
786    let disposition = content_disposition(disposition, &filename, &content_type);
787    let length = HeaderValue::from(data.len());
788    let mut response = Response::new(Body::from(data));
789    let headers = response.headers_mut();
790    headers.insert(header::CONTENT_TYPE, header_value(sent_type));
791    headers.insert(header::CONTENT_DISPOSITION, header_value(&disposition));
792    headers.insert(header::CONTENT_LENGTH, length);
793    response
794}
795
796/// `<prefix>/<22 random URL-safe characters>` (128 random bits).
797pub(crate) fn new_key(prefix: &str) -> String {
798    let id = URL_SAFE_NO_PAD.encode(random_bytes::<16>());
799    match prefix.trim_matches('/') {
800        "" => id,
801        prefix => format!("{prefix}/{id}"),
802    }
803}
804
805/// Longest kept file name, in characters.
806const MAX_FILENAME: usize = 200;
807
808/// The last path segment (browsers on Windows used to send `C:\...`),
809/// without control characters, trimmed, at most 200 characters with the
810/// extension kept; `file` when nothing is left.
811pub(crate) fn sanitize_filename(raw: &str) -> String {
812    let base = raw.rsplit(['/', '\\']).next().unwrap_or_default();
813    let clean: String = base.chars().filter(|c| !c.is_control()).collect();
814    let clean = clean.trim();
815    if clean.is_empty() || clean == "." || clean == ".." {
816        return "file".to_owned();
817    }
818    if clean.chars().count() <= MAX_FILENAME {
819        return clean.to_owned();
820    }
821    let extension = clean.rsplit_once('.').map(|(_, ext)| ext).filter(|ext| ext.chars().count() <= 16);
822    match extension {
823        Some(ext) => {
824            let stem: String = clean.chars().take(MAX_FILENAME - ext.chars().count() - 1).collect();
825            format!("{stem}.{ext}")
826        }
827        None => clean.chars().take(MAX_FILENAME).collect(),
828    }
829}
830
831/// `Image/PNG; charset=x` -> `image/png`; empty -> `application/octet-stream`.
832pub(crate) fn essence(content_type: &str) -> String {
833    let essence = content_type.split(';').next().unwrap_or_default().trim().to_ascii_lowercase();
834    if essence.is_empty() { "application/octet-stream".to_owned() } else { essence }
835}
836
837/// Types a browser displays without running scripts in the app's origin
838/// (Rails' `content_types_allowed_inline`, plus common media).
839const INLINE_TYPES: &[&str] = &[
840    "image/png",
841    "image/jpeg",
842    "image/gif",
843    "image/webp",
844    "image/avif",
845    "image/bmp",
846    "image/tiff",
847    "image/vnd.microsoft.icon",
848    "image/x-icon",
849    "application/pdf",
850    "text/plain",
851    "audio/mpeg",
852    "audio/ogg",
853    "audio/wav",
854    "audio/webm",
855    "video/mp4",
856    "video/ogg",
857    "video/webm",
858];
859
860/// Types a browser could run as a page or script: served as
861/// `application/octet-stream`, like Rails' `content_types_to_serve_as_binary`.
862const BINARY_TYPES: &[&str] = &[
863    "text/html",
864    "text/javascript",
865    "text/xml",
866    "application/xml",
867    "application/xhtml+xml",
868    "application/javascript",
869    "application/mathml+xml",
870    "image/svg+xml",
871    "text/cache-manifest",
872];
873
874/// `inline` or `attachment`, with the file name as ASCII (`filename=`) and,
875/// when that loses characters, UTF-8 (`filename*=`, RFC 6266).
876pub(crate) fn content_disposition(disposition: Disposition, filename: &str, content_type: &str) -> String {
877    let kind = match disposition {
878        Disposition::Inline if INLINE_TYPES.contains(&content_type) => "inline",
879        _ => "attachment",
880    };
881    let ascii: String = filename
882        .chars()
883        .map(|c| if c.is_ascii() && !c.is_ascii_control() && c != '"' && c != '\\' { c } else { '_' })
884        .collect();
885    let mut value = format!("{kind}; filename=\"{ascii}\"");
886    if ascii != filename {
887        value.push_str("; filename*=UTF-8''");
888        for byte in filename.bytes() {
889            if byte.is_ascii_alphanumeric() || b"!#$&+-.^_`|~".contains(&byte) {
890                value.push(byte as char);
891            } else {
892                write!(value, "%{byte:02X}").expect("writing to a String");
893            }
894        }
895    }
896    value
897}
898
899/// Which bytes a `Range` header asks for, checked against the file size.
900#[derive(Debug, Clone, Copy, PartialEq, Eq)]
901pub(crate) enum ByteRange {
902    /// No (usable) range: the whole file, status 200.
903    Full,
904    /// `length` bytes from `offset`, status 206.
905    Partial { offset: u64, length: u64 },
906    /// Starts past the end: status 416.
907    Unsatisfiable,
908}
909
910/// One `bytes=a-b`, `bytes=a-` or `bytes=-n` range (RFC 9110). Several
911/// ranges, other units and malformed values are ignored: the whole file is
912/// sent, which the RFC allows.
913pub(crate) fn byte_range(header: Option<&str>, size: u64) -> ByteRange {
914    let Some(spec) = header.and_then(|value| value.trim().strip_prefix("bytes=")) else {
915        return ByteRange::Full;
916    };
917    let Some((start, end)) = spec.split_once('-').filter(|_| !spec.contains(',')) else {
918        return ByteRange::Full;
919    };
920    let (start, end) = (start.trim(), end.trim());
921    let parse = |text: &str| text.parse::<u64>().ok();
922    if start.is_empty() {
923        return match parse(end) {
924            Some(0) => ByteRange::Unsatisfiable,
925            Some(_) if size == 0 => ByteRange::Unsatisfiable,
926            Some(suffix) => ByteRange::Partial { offset: size - suffix.min(size), length: suffix.min(size) },
927            None => ByteRange::Full,
928        };
929    }
930    let Some(offset) = parse(start) else { return ByteRange::Full };
931    let last = if end.is_empty() {
932        size.saturating_sub(1)
933    } else {
934        match parse(end) {
935            Some(last) if last >= offset => last.min(size.saturating_sub(1)),
936            _ => return ByteRange::Full,
937        }
938    };
939    if offset >= size { ByteRange::Unsatisfiable } else { ByteRange::Partial { offset, length: last - offset + 1 } }
940}
941
942/// The entity tag of `If-None-Match`, unquoted, for R2's `etagDoesNotMatch`.
943/// Only the first tag of a list is used; `*` is ignored.
944pub(crate) fn if_none_match(header: Option<&str>) -> Option<String> {
945    let first = header?.split(',').next()?.trim();
946    let tag = first.strip_prefix("W/").unwrap_or(first).trim_matches('"');
947    (!tag.is_empty() && tag != "*").then(|| tag.to_owned())
948}
949
950/// What [`serve`] asks R2 for, read from the request headers.
951#[derive(Debug, Clone, PartialEq, Eq)]
952pub(crate) struct Fetch {
953    pub range: ByteRange,
954    pub if_none_match: Option<String>,
955}
956
957impl Fetch {
958    /// `If-Range` is not compared: when present, the whole file is sent.
959    pub(crate) fn from_headers(headers: &HeaderMap, size: i64) -> Self {
960        let text = |name| headers.get(name).and_then(|value: &HeaderValue| value.to_str().ok());
961        let size = u64::try_from(size).unwrap_or(0);
962        let range = if headers.contains_key(header::IF_RANGE) {
963            ByteRange::Full
964        } else {
965            byte_range(text(header::RANGE), size)
966        };
967        Self { range, if_none_match: if_none_match(text(header::IF_NONE_MATCH)) }
968    }
969}
970
971fn header_value(text: &str) -> HeaderValue {
972    HeaderValue::from_str(text).unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"))
973}
974
975/// A file response: 200 with the whole body, or 206 with `range`.
976pub(crate) fn file_response(
977    attachment: &Attachment,
978    disposition: Disposition,
979    etag: &str,
980    range: ByteRange,
981    body: Body,
982) -> Response {
983    let size = u64::try_from(attachment.size).unwrap_or(0);
984    let content_type = if BINARY_TYPES.contains(&attachment.content_type.as_str()) {
985        "application/octet-stream"
986    } else {
987        &attachment.content_type
988    };
989    let mut response = Response::new(body);
990    let headers = response.headers_mut();
991    headers.insert(header::CONTENT_TYPE, header_value(content_type));
992    headers.insert(
993        header::CONTENT_DISPOSITION,
994        header_value(&content_disposition(disposition, &attachment.filename, &attachment.content_type)),
995    );
996    headers.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
997    headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(CACHE_CONTROL));
998    headers.insert(header::ETAG, header_value(etag));
999    let length = match range {
1000        ByteRange::Partial { offset, length } => {
1001            *response.status_mut() = StatusCode::PARTIAL_CONTENT;
1002            let last = offset + length - 1;
1003            response
1004                .headers_mut()
1005                .insert(header::CONTENT_RANGE, header_value(&format!("bytes {offset}-{last}/{size}")));
1006            length
1007        }
1008        _ => size,
1009    };
1010    response.headers_mut().insert(header::CONTENT_LENGTH, HeaderValue::from(length));
1011    response
1012}
1013
1014/// `304 Not Modified`: the browser's copy is current.
1015pub(crate) fn not_modified(etag: &str) -> Response {
1016    let mut response = Response::new(Body::empty());
1017    *response.status_mut() = StatusCode::NOT_MODIFIED;
1018    response.headers_mut().insert(header::ETAG, header_value(etag));
1019    response.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(CACHE_CONTROL));
1020    response
1021}
1022
1023/// `416 Range Not Satisfiable`, with the file size in `Content-Range`.
1024pub(crate) fn unsatisfiable(size: i64) -> Response {
1025    let mut response = Response::new(Body::empty());
1026    *response.status_mut() = StatusCode::RANGE_NOT_SATISFIABLE;
1027    response.headers_mut().insert(header::CONTENT_RANGE, header_value(&format!("bytes */{size}")));
1028    response
1029}
1030
1031/// Error for a missing `STORAGE` binding, naming the cloudflare.config.ts entry.
1032pub(crate) fn missing_binding(detail: &str) -> crate::Error {
1033    crate::Error::internal(format!(
1034        "R2 binding `{STORAGE_BINDING}` is missing ({detail}). Fix: add `{STORAGE_BINDING}: bindings.r2({{ name: \"<app>-storage\" }}),` to worker.env in cloudflare.config.ts\n(`ocre g scaffold <Model> <name>:attachment` adds it; `ocre deploy` creates the bucket)"
1035    ))
1036}
1037
1038#[cfg(test)]
1039#[path = "../tests/storage.rs"]
1040mod tests;