Skip to main content

ocre/runtime/
s3.rs

1//! Storage operations for files another service uploads or reads (ranged
2//! reads, copies, multipart uploads driven by the app, ListParts and
3//! ListMultipartUploads on R2's S3 API) and the development route that
4//! stands for presigned URLs.
5
6use axum::{
7    Router,
8    body::Body,
9    extract::{Path, Query, State},
10    http::{HeaderMap, HeaderValue, StatusCode, header},
11    response::{IntoResponse, Response},
12    routing::get,
13};
14use futures_util::StreamExt as _;
15use worker::{
16    Env, FixedLengthStream, HttpMetadata, Include, Range, ResponseBody, UploadedPart, send::SendFuture, web_sys,
17};
18
19use super::{
20    Ctx,
21    storage::{bucket, dev_base, endpoint},
22};
23use crate::{
24    ApiError, Error, Result, http,
25    storage::{
26        CompletedPart, DEV_MARKERS, DEV_STORAGE_PATH, DevGet, DevPut, Disposition, MAX_PARTS, PendingUpload,
27        StoredPart, check_expires_in, dev_parts_prefix, dev_upload_from_marker, dev_upload_marker, dev_url, essence,
28        parse_parts, parse_uploads, upload_gone,
29    },
30};
31
32/// Pages of a ListParts or ListMultipartUploads read at most (1,000 entries each).
33const MAX_PAGES: usize = 10;
34
35/// How long the Worker's own signed S3 calls are valid.
36const S3_CALL_EXPIRES_IN: u64 = 300;
37
38/// Largest single `PUT` R2 accepts (5 GiB less 5 MiB); [`copy`] copies larger objects in parts.
39const MAX_SINGLE_PUT: u64 = 5 * 1024 * 1024 * 1024 - 5 * 1024 * 1024;
40
41/// Parts of a large [`copy`]: 1 GiB, two subrequests each.
42const COPY_PART: u64 = 1024 * 1024 * 1024;
43
44fn r2_error(action: &str, key: &str, err: impl std::fmt::Display) -> Error {
45    Error::internal(format!("R2 could not {action} `{key}`: {err}"))
46}
47
48/// The JavaScript stream of an R2 object's body, to write it elsewhere without copying it into WebAssembly.
49fn js_stream(object: &worker::Object) -> Result<Option<web_sys::ReadableStream>> {
50    let Some(body) = object.body() else { return Ok(None) };
51    match body.response_body()? {
52        ResponseBody::Stream(stream) => Ok(Some(stream)),
53        _ => Err(Error::internal("R2 answered a body that is not a stream")),
54    }
55}
56
57/// Reads `length` bytes of an object from `offset` (fewer at its end), or returns `None` when `key` does not exist.
58///
59/// For files read piece by piece without holding them whole: a video's
60/// index at its end, a ZIP's central directory, the header of a large
61/// file. [`read_first`](crate::storage::read_first) reads from the start.
62///
63/// Free plan: one R2 class B operation (10M free per month).
64///
65/// # Errors
66///
67/// [`Error::Internal`](crate::Error::Internal) (500) when the `STORAGE`
68/// binding is missing, or R2 fails (an `offset` past the end of the object
69/// is a failure of R2's).
70///
71/// # Examples
72///
73/// ```no_run
74/// use ocre::{Ctx, Result, storage};
75///
76/// // The last 64 KB of a file (a ZIP's central directory).
77/// async fn tail(ctx: &Ctx, key: &str) -> Result<Option<Vec<u8>>> {
78///     let Some(object) = storage::head(ctx, key).await? else { return Ok(None) };
79///     let length = object.size.min(64 * 1024);
80///     storage::read_range(ctx, key, object.size - length, length).await
81/// }
82/// ```
83pub fn read_range(
84    ctx: &Ctx,
85    key: &str,
86    offset: u64,
87    length: u64,
88) -> impl Future<Output = Result<Option<Vec<u8>>>> + Send + use<> {
89    let env = ctx.env().clone();
90    let key = key.to_owned();
91    let length = length.max(1);
92    SendFuture::new(async move {
93        let range = Range::OffsetWithLength { offset, length };
94        let object = bucket(&env)?.get(&key).range(range).execute().await.map_err(|err| r2_error("read", &key, err))?;
95        let Some(object) = object else { return Ok(None) };
96        match object.body() {
97            Some(body) => Ok(Some(body.bytes().await?)),
98            None => Ok(Some(Vec::new())),
99        }
100    })
101}
102
103/// Copies the object at `from` to `to` inside the bucket (content type kept) and returns its size, or `None` when `from` does not exist.
104///
105/// The bytes stream from R2 to R2 through the Worker without being held in
106/// memory. Objects up to 5 GiB are one `PUT`; larger ones are copied in
107/// parts of 1 GiB (a 10 GB file: 10 parts, about 20 subrequests). An
108/// object already at `to` is replaced.
109///
110/// Free plan: one class B operation per read (one per part) and one class
111/// A operation per write (plus the create and complete of a multipart copy).
112///
113/// # Errors
114///
115/// [`Error::Internal`](crate::Error::Internal) (500) when the `STORAGE`
116/// binding is missing or R2 fails (a multipart copy is aborted then).
117///
118/// # Examples
119///
120/// ```no_run
121/// use ocre::{Ctx, Result, storage};
122///
123/// // Keeps a copy of a reported file before its owner can delete it.
124/// async fn preserve(ctx: &Ctx, key: &str, report_id: i64) -> Result<bool> {
125///     Ok(storage::copy(ctx, key, &format!("evidence/{report_id}")).await?.is_some())
126/// }
127/// ```
128pub fn copy(ctx: &Ctx, from: &str, to: &str) -> impl Future<Output = Result<Option<u64>>> + Send + use<> {
129    let env = ctx.env().clone();
130    let (from, to) = (from.to_owned(), to.to_owned());
131    SendFuture::new(async move {
132        let bucket = bucket(&env)?;
133        let Some(head) = bucket.head(&from).await.map_err(|err| r2_error("read", &from, err))? else {
134            return Ok(None);
135        };
136        let size = head.size();
137        let metadata = head.http_metadata();
138        if size <= MAX_SINGLE_PUT {
139            let object = bucket.get(&from).execute().await.map_err(|err| r2_error("read", &from, err))?;
140            let Some(stream) = object.as_ref().map(js_stream).transpose()?.flatten() else { return Ok(None) };
141            bucket
142                .put(&to, worker::Data::ReadableStream(stream))
143                .http_metadata(metadata)
144                .execute()
145                .await
146                .map_err(|err| r2_error("write", &to, err))?;
147            return Ok(Some(size));
148        }
149        let upload = bucket
150            .create_multipart_upload(&to)
151            .http_metadata(metadata)
152            .execute()
153            .await
154            .map_err(|err| r2_error("start the copy to", &to, err))?;
155        let mut parts = Vec::new();
156        let (mut offset, mut number) = (0, 1);
157        while offset < size {
158            let length = COPY_PART.min(size - offset);
159            let read = bucket.get(&from).range(Range::OffsetWithLength { offset, length }).execute().await;
160            let stream = match read {
161                Ok(object) => object.as_ref().map(js_stream).transpose()?.flatten(),
162                Err(err) => {
163                    upload.abort().await.ok();
164                    return Err(r2_error("read", &from, err));
165                }
166            };
167            let Some(stream) = stream else {
168                upload.abort().await.ok();
169                return Ok(None);
170            };
171            match upload.upload_part(number, worker::Data::ReadableStream(stream)).await {
172                Ok(part) => parts.push(part),
173                Err(err) => {
174                    upload.abort().await.ok();
175                    return Err(r2_error("copy a part to", &to, err));
176                }
177            }
178            offset += length;
179            number += 1;
180        }
181        upload.complete(parts).await.map_err(|err| r2_error("assemble the copy", &to, err))?;
182        Ok(Some(size))
183    })
184}
185
186/// Starts a multipart upload of `key` with `content_type`, and returns its upload id.
187///
188/// For uploads the app drives itself: a service (a GPU worker, a partner's
189/// API) uploads the parts to [`presign_part`] URLs, then the app lists them
190/// ([`list_parts`]) and assembles the object ([`complete_multipart`]).
191/// Browser uploads of a form's file use
192/// [`multipart_uploads`](crate::storage::multipart_uploads) instead. Parts
193/// are 5 MiB at least (but the last) and number 1 to 10,000. R2 drops an
194/// upload left unfinished after 7 days; [`abort_multipart`] drops it at
195/// once.
196///
197/// Free plan: one R2 class A operation, then one per part and one for the
198/// completion.
199///
200/// # Errors
201///
202/// [`Error::Internal`](crate::Error::Internal) (500) when the `STORAGE`
203/// binding is missing or R2 fails.
204///
205/// # Examples
206///
207/// ```no_run
208/// use ocre::{Ctx, Result, storage};
209///
210/// // Where a GPU worker uploads a 3-part result: the upload id and one URL per part, valid a day.
211/// async fn output_target(ctx: &Ctx, job_id: i64) -> Result<(String, Vec<String>)> {
212///     let key = format!("processed/{job_id}.mp4");
213///     let upload_id = storage::create_multipart(ctx, &key, "video/mp4").await?;
214///     let urls = (1..=3).map(|part| storage::presign_part(ctx, &key, &upload_id, part, 86_400)).collect::<Result<_>>()?;
215///     Ok((upload_id, urls))
216/// }
217/// ```
218pub fn create_multipart(
219    ctx: &Ctx,
220    key: &str,
221    content_type: &str,
222) -> impl Future<Output = Result<String>> + Send + use<> {
223    let env = ctx.env().clone();
224    let (key, content_type) = (key.to_owned(), essence(content_type));
225    SendFuture::new(async move { create(&env, &key, content_type).await })
226}
227
228pub(super) async fn create(env: &Env, key: &str, content_type: String) -> Result<String> {
229    let metadata = HttpMetadata { content_type: Some(content_type), ..Default::default() };
230    let bucket = bucket(env)?;
231    let upload = bucket
232        .create_multipart_upload(key)
233        .http_metadata(metadata)
234        .execute()
235        .await
236        .map_err(|err| r2_error("start the upload of", key, err))?;
237    let upload_id = upload.upload_id().await;
238    if dev_base(env).is_some() {
239        bucket
240            .put(dev_upload_marker(key, &upload_id), Vec::new())
241            .execute()
242            .await
243            .map_err(|err| r2_error("record the upload of", key, err))?;
244    }
245    Ok(upload_id)
246}
247
248/// Presigns the `PUT` of part `part_number` of the multipart upload `upload_id` of `key`, valid `expires_in` seconds.
249///
250/// The uploader `PUT`s the part's bytes to the URL; R2 answers its `ETag`
251/// (also found later with [`list_parts`]). In debug builds the URL is the
252/// app's development route on the local bucket. Signing is local: no R2
253/// operation.
254///
255/// # Errors
256///
257/// - [`Error::BadRequest`](crate::Error::BadRequest) (400) when
258///   `part_number` is not 1 to 10,000.
259/// - [`Error::Internal`](crate::Error::Internal) (500) when an `R2_*`
260///   setting is missing in a release build, or `expires_in` is 0 or over 7 days.
261pub fn presign_part(ctx: &Ctx, key: &str, upload_id: &str, part_number: u16, expires_in: u64) -> Result<String> {
262    if part_number == 0 || u64::from(part_number) > MAX_PARTS {
263        return Err(Error::bad_request(format!("part {part_number} is not between 1 and {MAX_PARTS}")));
264    }
265    let number = part_number.to_string();
266    let query = [("partNumber", number.as_str()), ("uploadId", upload_id)];
267    match dev_base(ctx.env()) {
268        Some(base) => {
269            check_expires_in(expires_in)?;
270            Ok(dev_url(&base, key, &query, expires_in))
271        }
272        None => endpoint(ctx.env())?.presign("PUT", key, &[], &query, crate::now(), expires_in),
273    }
274}
275
276/// Assembles the multipart upload `upload_id` of `key` from `parts`; `false` when the upload no longer exists.
277///
278/// `parts` are every part, in order, with the `ETag` R2 answered (quoted
279/// or not): the uploader's report, or [`list_parts`] mapped with
280/// [`StoredPart::completed`](crate::storage::StoredPart::completed). The
281/// object exists once this returns `true`. `false` means the upload was
282/// completed (perhaps by a concurrent call: check the object with
283/// [`head`](crate::storage::head)), aborted, or expired.
284///
285/// Free plan: one R2 class A operation.
286///
287/// # Errors
288///
289/// [`Error::BadRequest`](crate::Error::BadRequest) (400) when R2 refuses
290/// the parts (a missing part, a wrong `ETag`, a part under 5 MiB but the
291/// last); [`Error::Internal`](crate::Error::Internal) when the `STORAGE`
292/// binding is missing.
293///
294/// # Examples
295///
296/// ```no_run
297/// use ocre::{Ctx, Result, storage};
298///
299/// // The worker said it is done: assemble whatever parts it stored.
300/// async fn finish(ctx: &Ctx, key: &str, upload_id: &str) -> Result<bool> {
301///     let Some(parts) = storage::list_parts(ctx, key, upload_id).await? else {
302///         return storage::exists(ctx, key).await; // completed already
303///     };
304///     let parts: Vec<_> = parts.iter().map(storage::StoredPart::completed).collect();
305///     storage::complete_multipart(ctx, key, upload_id, &parts).await
306/// }
307/// ```
308pub fn complete_multipart(
309    ctx: &Ctx,
310    key: &str,
311    upload_id: &str,
312    parts: &[CompletedPart],
313) -> impl Future<Output = Result<bool>> + Send + use<> {
314    let env = ctx.env().clone();
315    let (key, upload_id, parts) = (key.to_owned(), upload_id.to_owned(), parts.to_vec());
316    SendFuture::new(async move { complete(&env, &key, &upload_id, &parts).await })
317}
318
319pub(super) async fn complete(env: &Env, key: &str, upload_id: &str, parts: &[CompletedPart]) -> Result<bool> {
320    if parts.is_empty() {
321        return Err(Error::bad_request("complete needs the parts"));
322    }
323    let bucket = bucket(env)?;
324    let upload = bucket.resume_multipart_upload(key, upload_id)?;
325    // R2 answers a part's ETag in quotes to a presigned PUT, without them to the binding.
326    let uploaded = parts.iter().map(|part| UploadedPart::new(part.part_number, part.etag.trim_matches('"').to_owned()));
327    if let Err(err) = upload.complete(uploaded).await {
328        let message = err.to_string();
329        if upload_gone(&message) {
330            return Ok(false);
331        }
332        return Err(Error::bad_request(format!("R2 could not assemble `{key}`: {message}")));
333    }
334    forget_dev_upload(env, key, upload_id).await?;
335    Ok(true)
336}
337
338/// Drops the multipart upload `upload_id` of `key` and its parts; an upload already gone is not an error.
339///
340/// Free plan: aborting is free.
341///
342/// # Errors
343///
344/// [`Error::Internal`](crate::Error::Internal) (500) when the `STORAGE`
345/// binding is missing or R2 fails.
346pub fn abort_multipart(ctx: &Ctx, key: &str, upload_id: &str) -> impl Future<Output = Result<()>> + Send + use<> {
347    let env = ctx.env().clone();
348    let (key, upload_id) = (key.to_owned(), upload_id.to_owned());
349    SendFuture::new(async move { abort(&env, &key, &upload_id).await })
350}
351
352pub(super) async fn abort(env: &Env, key: &str, upload_id: &str) -> Result<()> {
353    let upload = bucket(env)?.resume_multipart_upload(key, upload_id)?;
354    if let Err(err) = upload.abort().await {
355        let message = err.to_string();
356        if !upload_gone(&message) {
357            return Err(r2_error("abort the upload of", key, message));
358        }
359    }
360    forget_dev_upload(env, key, upload_id).await
361}
362
363/// Development: removes the markers of a finished upload.
364async fn forget_dev_upload(env: &Env, key: &str, upload_id: &str) -> Result<()> {
365    if dev_base(env).is_none() {
366        return Ok(());
367    }
368    let bucket = bucket(env)?;
369    let parts = bucket.list().prefix(dev_parts_prefix(upload_id)).execute().await?;
370    let mut markers: Vec<String> = parts.objects().iter().map(worker::Object::key).collect();
371    markers.push(dev_upload_marker(key, upload_id));
372    bucket.delete_multiple(markers).await?;
373    Ok(())
374}
375
376/// The parts stored so far in the multipart upload `upload_id` of `key`, by part number; `None` when the upload no longer exists.
377///
378/// The R2 binding cannot list parts: this calls ListParts on R2's S3 API
379/// (one subrequest per 1,000 parts), so it needs the `R2_*` settings of
380/// [`presign_get`](crate::storage::presign_get). In debug builds it lists
381/// the parts uploaded through the development route instead.
382///
383/// Free plan: one R2 class A operation per 1,000 parts.
384///
385/// # Errors
386///
387/// [`Error::Internal`](crate::Error::Internal) (500) when an `R2_*` setting
388/// is missing (release builds), or R2 answers an error.
389pub fn list_parts(
390    ctx: &Ctx,
391    key: &str,
392    upload_id: &str,
393) -> impl Future<Output = Result<Option<Vec<StoredPart>>>> + Send + use<> {
394    let env = ctx.env().clone();
395    let (key, upload_id) = (key.to_owned(), upload_id.to_owned());
396    SendFuture::new(async move {
397        if dev_base(&env).is_some() {
398            return dev_list_parts(&env, &key, &upload_id).await;
399        }
400        let endpoint = endpoint(&env)?;
401        let mut parts = Vec::new();
402        let mut marker: Option<String> = None;
403        for _ in 0..MAX_PAGES {
404            let mut query = vec![("uploadId", upload_id.as_str()), ("max-parts", "1000")];
405            if let Some(marker) = &marker {
406                query.push(("part-number-marker", marker));
407            }
408            let url = endpoint.presign("GET", &key, &[], &query, crate::now(), S3_CALL_EXPIRES_IN)?;
409            let response = http::Request::get(url).send().await?;
410            match response.status {
411                404 => return Ok(None),
412                200 => {
413                    let (page, next) = parse_parts(&response.text());
414                    parts.extend(page);
415                    marker = next;
416                    if marker.is_none() {
417                        parts.sort_by_key(|part: &StoredPart| part.part_number);
418                        return Ok(Some(parts));
419                    }
420                }
421                status => return Err(r2_error("list the parts of", &key, format!("{status} {}", response.text()))),
422            }
423        }
424        Err(r2_error("list the parts of", &key, "more than 10,000 parts"))
425    })
426}
427
428/// The multipart uploads in progress whose key starts with `prefix`, oldest first.
429///
430/// For a cleanup task that aborts uploads left behind, or for completing
431/// the upload of an output whose uploader never reported. Calls
432/// ListMultipartUploads on R2's S3 API (one subrequest per 1,000 uploads;
433/// `R2_*` settings as [`list_parts`]); in debug builds, the uploads started
434/// with [`create_multipart`] or
435/// [`multipart_uploads`](crate::storage::multipart_uploads) and not
436/// finished.
437///
438/// Free plan: one R2 class A operation per 1,000 uploads.
439///
440/// # Errors
441///
442/// [`Error::Internal`](crate::Error::Internal) (500) when an `R2_*` setting
443/// is missing (release builds), or R2 answers an error.
444///
445/// # Examples
446///
447/// ```no_run
448/// use ocre::{Ctx, Result, storage};
449///
450/// // Keeps only the newest upload of each output (a retried task starts a new one).
451/// async fn drop_older_uploads(ctx: &Ctx, key: &str) -> Result<()> {
452///     let mut uploads = storage::list_multipart_uploads(ctx, key).await?;
453///     uploads.retain(|upload| upload.key == key);
454///     uploads.pop(); // the newest
455///     for upload in uploads {
456///         storage::abort_multipart(ctx, key, &upload.upload_id).await?;
457///     }
458///     Ok(())
459/// }
460/// ```
461pub fn list_multipart_uploads(
462    ctx: &Ctx,
463    prefix: &str,
464) -> impl Future<Output = Result<Vec<PendingUpload>>> + Send + use<> {
465    let env = ctx.env().clone();
466    let prefix = prefix.to_owned();
467    SendFuture::new(async move {
468        let mut uploads = if dev_base(&env).is_some() {
469            dev_list_uploads(&env, &prefix).await?
470        } else {
471            s3_list_uploads(&env, &prefix).await?
472        };
473        uploads.sort_by(|a, b| a.initiated.cmp(&b.initiated));
474        Ok(uploads)
475    })
476}
477
478async fn s3_list_uploads(env: &Env, prefix: &str) -> Result<Vec<PendingUpload>> {
479    let endpoint = endpoint(env)?;
480    let mut uploads = Vec::new();
481    let mut markers: Option<(String, String)> = None;
482    for _ in 0..MAX_PAGES {
483        let mut query = vec![("uploads", ""), ("prefix", prefix), ("max-uploads", "1000")];
484        if let Some((key, id)) = &markers {
485            query.extend([("key-marker", key.as_str()), ("upload-id-marker", id.as_str())]);
486        }
487        let url = endpoint.presign("GET", "", &[], &query, crate::now(), S3_CALL_EXPIRES_IN)?;
488        let response = http::Request::get(url).send().await?;
489        if response.status != 200 {
490            return Err(r2_error("list the uploads under", prefix, format!("{} {}", response.status, response.text())));
491        }
492        let (page, next) = parse_uploads(&response.text());
493        uploads.extend(page);
494        markers = next;
495        if markers.is_none() {
496            return Ok(uploads);
497        }
498    }
499    Err(r2_error("list the uploads under", prefix, "more than 10,000 uploads"))
500}
501
502async fn dev_list_parts(env: &Env, key: &str, upload_id: &str) -> Result<Option<Vec<StoredPart>>> {
503    let bucket = bucket(env)?;
504    if bucket.head(dev_upload_marker(key, upload_id)).await?.is_none() {
505        return Ok(None);
506    }
507    let listed =
508        bucket.list().prefix(dev_parts_prefix(upload_id)).include(vec![Include::CustomMetadata]).execute().await?;
509    let mut parts: Vec<StoredPart> = listed
510        .objects()
511        .iter()
512        .filter_map(|object| {
513            let meta = object.custom_metadata().ok()?;
514            Some(StoredPart {
515                part_number: object.key().rsplit('/').next()?.parse().ok()?,
516                etag: meta.get("etag")?.clone(),
517                size: meta.get("size")?.parse().ok()?,
518            })
519        })
520        .collect();
521    parts.sort_by_key(|part| part.part_number);
522    Ok(Some(parts))
523}
524
525async fn dev_list_uploads(env: &Env, prefix: &str) -> Result<Vec<PendingUpload>> {
526    let listed = bucket(env)?.list().prefix(format!("{DEV_MARKERS}uploads/{prefix}")).execute().await?;
527    Ok(listed
528        .objects()
529        .iter()
530        .filter_map(|object| {
531            let initiated = format!("{:020}", object.uploaded().as_millis());
532            dev_upload_from_marker(&object.key(), initiated)
533        })
534        .collect())
535}
536
537/// `/ocre/dev/storage/{*key}`: presigned URLs in debug builds, on the local bucket (see [`DEV_STORAGE_PATH`]).
538pub(crate) fn dev_routes() -> Router<Ctx> {
539    Router::new().route(
540        &format!("{DEV_STORAGE_PATH}/{{*key}}"),
541        get(|State(ctx): State<Ctx>, Path(key): Path<String>, Query(query): Query<DevGet>, headers: HeaderMap| {
542            dev_get(ctx, key, query, headers)
543        })
544        .put(
545            |State(ctx): State<Ctx>,
546             Path(key): Path<String>,
547             Query(query): Query<DevPut>,
548             headers: HeaderMap,
549             body: Body| {
550                SendFuture::new(async move {
551                    dev_put(&ctx, &key, &query, &headers, body).await.map_err(ApiError::from).into_response()
552                })
553            },
554        ),
555    )
556}
557
558/// A `GET` of a presigned URL: the file, with `Range` and the URL's response overrides.
559fn dev_get(ctx: Ctx, key: String, query: DevGet, headers: HeaderMap) -> impl Future<Output = Response> + Send {
560    SendFuture::new(async move {
561        let found = super::storage::head(&ctx, &key).await;
562        let object = match found {
563            Ok(Some(object)) => object,
564            Ok(None) => return StatusCode::NOT_FOUND.into_response(),
565            Err(err) => return ApiError::from(err).into_response(),
566        };
567        let filename = key.rsplit('/').next().unwrap_or(&key).to_owned();
568        let attachment = object.attachment(&filename);
569        let mut response = match super::storage::serve(&ctx, &attachment, &headers, Disposition::Inline).await {
570            Ok(response) => response,
571            Err(err) => return ApiError::from(err).into_response(),
572        };
573        let overrides =
574            [(header::CONTENT_TYPE, query.content_type), (header::CONTENT_DISPOSITION, query.content_disposition)];
575        for (name, value) in overrides {
576            if let Some(value) = value.and_then(|value| HeaderValue::from_str(&value).ok()) {
577                response.headers_mut().insert(name, value);
578            }
579        }
580        response
581    })
582}
583
584/// Streams `size` bytes of `body` as part `part` of the upload `upload_id` of `key`, and returns its `ETag`.
585///
586/// In development, also records the part for [`list_parts`].
587pub(super) async fn upload_part(
588    env: &Env,
589    key: &str,
590    upload_id: &str,
591    part: u16,
592    size: u64,
593    body: Body,
594) -> Result<String> {
595    let bucket = bucket(env)?;
596    let upload = bucket.resume_multipart_upload(key, upload_id)?;
597    let stored = upload.upload_part(part, fixed_length(body, size)).await.map_err(|err| match err.to_string() {
598        // The upload was completed, aborted or expired: the uploader starts over.
599        message if upload_gone(&message) => Error::NotFound,
600        message => Error::bad_request(format!("R2 refused part {part} of `{key}`: {message}")),
601    })?;
602    if dev_base(env).is_some() {
603        let marker = format!("{}{part}", dev_parts_prefix(upload_id));
604        let metadata = [("etag".to_owned(), stored.etag()), ("size".to_owned(), size.to_string())];
605        bucket.put(marker, Vec::new()).custom_metadata(metadata).execute().await?;
606    }
607    Ok(stored.etag())
608}
609
610/// A request body of `size` bytes as a stream R2 accepts (it needs the length up front).
611fn fixed_length(body: Body, size: u64) -> FixedLengthStream {
612    let chunks = body
613        .into_data_stream()
614        .map(|chunk| chunk.map(|bytes| bytes.to_vec()).map_err(|err| worker::Error::RustError(err.to_string())));
615    FixedLengthStream::wrap(chunks, size)
616}
617
618/// A `PUT` of a presigned URL: a whole object, or a part of a multipart upload. Answers its `ETag`.
619async fn dev_put(ctx: &Ctx, key: &str, query: &DevPut, headers: &HeaderMap, body: Body) -> Result<Response> {
620    let env = ctx.env();
621    let size: u64 = headers
622        .get(header::CONTENT_LENGTH)
623        .and_then(|value| value.to_str().ok()?.parse().ok())
624        .ok_or_else(|| Error::bad_request("a PUT needs a Content-Length"))?;
625    let etag = match (query.part_number, &query.upload_id) {
626        (Some(part), Some(upload_id)) => upload_part(env, key, upload_id, part, size, body).await?,
627        _ => {
628            let content_type = headers.get(header::CONTENT_TYPE).and_then(|value| value.to_str().ok()).map(essence);
629            let metadata = HttpMetadata { content_type, ..Default::default() };
630            let object = bucket(env)?.put(key, fixed_length(body, size)).http_metadata(metadata).execute().await?;
631            object.map(|object| object.etag()).unwrap_or_default()
632        }
633    };
634    let mut response = StatusCode::OK.into_response();
635    if let Ok(value) = HeaderValue::from_str(&format!("\"{}\"", etag.trim_matches('"'))) {
636        response.headers_mut().insert(header::ETAG, value);
637    }
638    Ok(response)
639}