Skip to content

Commit 3b92e32

Browse files
authored
Add response_body function to r2::ObjectBody. (#462)
This commit adds a new function to `r2::ObjectBody` to allow the underlying `ReadableStream` for the body of an R2 object to be used to create a `ResponseBody`, via the `ResponseBody::Stream` variant. This adds support for cases where workers can hand a reference to the R2 object to the workers runtime for streaming to the client, unmodified. Importantly, this allows the worker to avoid CPU usage while streaming the object. Before this commit, `ObjectBody::Stream` could be used but that would result in unexpected CPU usage during the streaming process leading to the working hitting the CPU limit for large (> 150 MB) R2 objects. Closes #389
1 parent 4663a8a commit 3b92e32

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

worker/src/r2/mod.rs

+16-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ use worker_sys::{
1212
R2UploadedPart as EdgeR2UploadedPart,
1313
};
1414

15-
use crate::{env::EnvBinding, ByteStream, Date, Error, FixedLengthStream, Headers, Result};
15+
use crate::{
16+
env::EnvBinding, ByteStream, Date, Error, FixedLengthStream, Headers, ResponseBody, Result,
17+
};
1618

1719
mod builder;
1820

@@ -282,6 +284,19 @@ impl<'body> ObjectBody<'body> {
282284
})
283285
}
284286

287+
/// Returns a [ResponseBody] containing the data in the [Object].
288+
///
289+
/// This function can be used to hand off the [Object] data to the workers runtime for streaming
290+
/// to the client in a [crate::Response]. This ensures that the worker does not consume CPU time
291+
/// while the streaming occurs, which can be significant if instead [ObjectBody::stream] is used.
292+
pub fn response_body(self) -> Result<ResponseBody> {
293+
if self.inner.body_used() {
294+
return Err(Error::BodyUsed);
295+
}
296+
297+
Ok(ResponseBody::Stream(self.inner.body()))
298+
}
299+
285300
pub async fn bytes(self) -> Result<Vec<u8>> {
286301
let js_buffer = JsFuture::from(self.inner.array_buffer()).await?;
287302
let js_buffer = Uint8Array::new(&js_buffer);

0 commit comments

Comments
 (0)