Skip to main content

ocre/storage/
s3.rs

1//! Multipart uploads beyond the browser (another service uploads the parts),
2//! the S3 API calls the R2 binding lacks (ListParts, ListMultipartUploads),
3//! and presigned URLs in development, served by the Worker from the local bucket.
4
5use serde::{Deserialize, Serialize};
6
7use crate::percent_encode;
8
9/// Path of the development route serving presigned URLs from the local bucket: `/ocre/dev/storage/<key>`.
10///
11/// In debug builds (`ocre dev`, `ocre test`), [`presign_get`](crate::storage::presign_get),
12/// [`presign_put`](crate::storage::presign_put), [`presign_part`](crate::storage::presign_part),
13/// [`direct_upload`](crate::storage::direct_upload) and
14/// [`serve_redirect`](crate::storage::serve_redirect) answer URLs on this
15/// route of the app (`APP_URL`, else `http://localhost:8787`) instead of
16/// R2's, and [`serve`](crate::serve) mounts it: `GET` (with `Range`), `PUT`
17/// and `PUT ?partNumber=&uploadId=` work on the local bucket as on R2, so
18/// development never touches the real bucket and needs no `R2_*` setting.
19/// Release builds have no such route. The URLs are not signed: the route
20/// exists only on a developer's machine.
21///
22/// # Examples
23///
24/// ```
25/// assert_eq!(ocre::storage::DEV_STORAGE_PATH, "/ocre/dev/storage");
26/// ```
27pub const DEV_STORAGE_PATH: &str = "/ocre/dev/storage";
28
29/// Marker objects of the development emulation of ListParts and ListMultipartUploads, under this prefix of the local bucket.
30pub(crate) const DEV_MARKERS: &str = ".ocre-dev-storage/";
31
32/// Default app address in development when `APP_URL` is not set.
33pub(crate) const DEV_APP_URL: &str = "http://localhost:8787";
34
35/// A part stored in a multipart upload, as [`list_parts`](crate::storage::list_parts) reports it.
36///
37/// # Examples
38///
39/// ```
40/// let part = ocre::storage::StoredPart { part_number: 1, etag: "abc".into(), size: 5_242_880 };
41/// assert_eq!(part.completed().etag, "abc");
42/// ```
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct StoredPart {
45    /// From 1.
46    pub part_number: u16,
47    /// The part's `ETag`, without quotes.
48    pub etag: String,
49    /// Bytes.
50    pub size: u64,
51}
52
53impl StoredPart {
54    /// The part as [`complete_multipart`](crate::storage::complete_multipart) takes it.
55    pub fn completed(&self) -> super::CompletedPart {
56        super::CompletedPart { part_number: self.part_number, etag: self.etag.clone() }
57    }
58}
59
60/// A multipart upload not completed or aborted yet, as [`list_multipart_uploads`](crate::storage::list_multipart_uploads) reports it.
61///
62/// # Examples
63///
64/// ```
65/// let upload = ocre::storage::PendingUpload {
66///     key: "videos/1/source.mp4".into(),
67///     upload_id: "u1".into(),
68///     initiated: "2026-10-18T10:00:00.000Z".into(),
69/// };
70/// assert_eq!(upload.key, "videos/1/source.mp4");
71/// ```
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73pub struct PendingUpload {
74    /// The object the upload will create.
75    pub key: String,
76    /// R2's id of the upload.
77    pub upload_id: String,
78    /// When it started, as text that sorts in time order (ISO 8601 on R2).
79    pub initiated: String,
80}
81
82/// The text of each `<tag>...</tag>` of `xml`, in order (S3's flat answers: no attributes, no nesting of the same tag).
83fn elements<'a>(xml: &'a str, tag: &str) -> Vec<&'a str> {
84    let (open, close) = (format!("<{tag}>"), format!("</{tag}>"));
85    let mut found = Vec::new();
86    let mut rest = xml;
87    while let Some(start) = rest.find(&open) {
88        let after = &rest[start + open.len()..];
89        let Some(end) = after.find(&close) else { break };
90        found.push(&after[..end]);
91        rest = &after[end + close.len()..];
92    }
93    found
94}
95
96/// The unescaped text of the first `<tag>` of `xml`.
97fn element(xml: &str, tag: &str) -> Option<String> {
98    elements(xml, tag).first().map(|text| {
99        text.trim()
100            .replace("&quot;", "\"")
101            .replace("&apos;", "'")
102            .replace("&lt;", "<")
103            .replace("&gt;", ">")
104            .replace("&amp;", "&")
105    })
106}
107
108/// Whether a listing says more pages follow.
109fn truncated(xml: &str) -> bool {
110    element(xml, "IsTruncated").as_deref() == Some("true")
111}
112
113/// The parts of a ListParts answer, and the marker of the next page.
114pub(crate) fn parse_parts(xml: &str) -> (Vec<StoredPart>, Option<String>) {
115    let parts = elements(xml, "Part")
116        .into_iter()
117        .filter_map(|part| {
118            Some(StoredPart {
119                part_number: element(part, "PartNumber")?.parse().ok()?,
120                etag: element(part, "ETag")?.trim_matches('"').to_owned(),
121                size: element(part, "Size")?.parse().ok()?,
122            })
123        })
124        .collect();
125    let next = truncated(xml).then(|| element(xml, "NextPartNumberMarker")).flatten();
126    (parts, next)
127}
128
129/// The uploads of a ListMultipartUploads answer, and the key and upload id markers of the next page.
130pub(crate) fn parse_uploads(xml: &str) -> (Vec<PendingUpload>, Option<(String, String)>) {
131    let uploads = elements(xml, "Upload")
132        .into_iter()
133        .filter_map(|upload| {
134            Some(PendingUpload {
135                key: element(upload, "Key")?,
136                upload_id: element(upload, "UploadId")?,
137                initiated: element(upload, "Initiated").unwrap_or_default(),
138            })
139        })
140        .collect();
141    let next = truncated(xml).then(|| element(xml, "NextKeyMarker").zip(element(xml, "NextUploadIdMarker"))).flatten();
142    (uploads, next)
143}
144
145/// Whether an R2 error message says the multipart upload no longer exists (completed, aborted or expired).
146pub(crate) fn upload_gone(message: &str) -> bool {
147    message.contains("NoSuchUpload") || message.contains("does not exist")
148}
149
150/// The development URL standing for a presigned one: `<base>/ocre/dev/storage/<key>?<query>&X-Amz-Expires=<n>`.
151///
152/// `X-Amz-Expires` is not checked; it shows the lifetime as on R2.
153pub(crate) fn dev_url(base: &str, key: &str, query: &[(&str, &str)], expires_in: u64) -> String {
154    let expires = expires_in.to_string();
155    let query: Vec<String> = query
156        .iter()
157        .chain(&[("X-Amz-Expires", expires.as_str())])
158        .map(|(name, value)| format!("{}={}", percent_encode(name, false), percent_encode(value, false)))
159        .collect();
160    format!("{}{DEV_STORAGE_PATH}/{}?{}", base.trim().trim_end_matches('/'), percent_encode(key, true), query.join("&"))
161}
162
163/// The marker of a multipart upload in progress: `.ocre-dev-storage/uploads/<key>/<upload id>`.
164pub(crate) fn dev_upload_marker(key: &str, upload_id: &str) -> String {
165    format!("{DEV_MARKERS}uploads/{key}/{}", percent_encode(upload_id, false))
166}
167
168/// The upload of a marker made by [`dev_upload_marker`], if it is one.
169pub(crate) fn dev_upload_from_marker(marker: &str, initiated: String) -> Option<PendingUpload> {
170    let (key, upload_id) = marker.strip_prefix(DEV_MARKERS)?.strip_prefix("uploads/")?.rsplit_once('/')?;
171    let upload_id = percent_decode(upload_id)?;
172    Some(PendingUpload { key: key.to_owned(), upload_id, initiated })
173}
174
175/// The prefix of the part markers of an upload: `.ocre-dev-storage/parts/<upload id>/`.
176pub(crate) fn dev_parts_prefix(upload_id: &str) -> String {
177    format!("{DEV_MARKERS}parts/{}/", percent_encode(upload_id, false))
178}
179
180/// `%XX` sequences back to bytes; `None` when the result is not UTF-8 or a sequence is malformed.
181fn percent_decode(text: &str) -> Option<String> {
182    let bytes = text.as_bytes();
183    let mut out = Vec::with_capacity(bytes.len());
184    let mut i = 0;
185    while i < bytes.len() {
186        if bytes[i] == b'%' {
187            let hex = text.get(i + 1..i + 3)?;
188            out.push(u8::from_str_radix(hex, 16).ok()?);
189            i += 3;
190        } else {
191            out.push(bytes[i]);
192            i += 1;
193        }
194    }
195    String::from_utf8(out).ok()
196}
197
198/// The query of a `PUT` on the development route: a part of a multipart upload, or a whole object.
199#[derive(Debug, Default, Deserialize)]
200pub(crate) struct DevPut {
201    #[serde(rename = "partNumber")]
202    pub(crate) part_number: Option<u16>,
203    #[serde(rename = "uploadId")]
204    pub(crate) upload_id: Option<String>,
205}
206
207/// The query of a `GET` on the development route: R2's response overrides.
208#[derive(Debug, Default, Deserialize)]
209pub(crate) struct DevGet {
210    #[serde(rename = "response-content-type")]
211    pub(crate) content_type: Option<String>,
212    #[serde(rename = "response-content-disposition")]
213    pub(crate) content_disposition: Option<String>,
214}
215
216#[cfg(test)]
217#[path = "../../tests/storage/s3.rs"]
218mod tests;