Skip to main content

file_storage/system/r2/file/
r2_write_op.rs

1use crate::system::r2::r2_path::RUNTIME;
2use crate::system::R2Path;
3use aws_sdk_s3::primitives::ByteStream;
4use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart};
5use bytes::Bytes;
6use std::io;
7
8/// The minimum part size for multipart uploads (5 MiB).
9const MIN_PART_SIZE: usize = 5 * 1024 * 1024;
10
11/// An R2 write operation.
12///
13/// Streams data to R2 via multipart upload.
14///
15/// # Close
16/// The object is only created by `close`. Multipart uploads reject non-final parts smaller than
17/// `MIN_PART_SIZE`, so buffered data below that threshold cannot be committed before then and
18/// `flush` is not a durability point. Dropping the operation without calling `close` aborts the
19/// upload and the object is never created.
20pub struct R2WriteOp {
21    account_id: String,
22    bucket: String,
23    key: String,
24    upload_id: String,
25    buffer: Vec<u8>,
26    part_number: i32,
27    completed_parts: Vec<CompletedPart>,
28    completed: bool,
29}
30
31impl R2WriteOp {
32    //! Create
33
34    /// Creates a new multipart upload.
35    pub(crate) async fn create(
36        account_id: &str,
37        bucket: &str,
38        key: &str,
39    ) -> Result<Self, io::Error> {
40        let response = R2Path::get_client(account_id)
41            .await
42            .create_multipart_upload()
43            .bucket(bucket)
44            .key(key)
45            .send()
46            .await
47            .map_err(io::Error::other)?;
48
49        let upload_id: String = response
50            .upload_id()
51            .ok_or_else(|| io::Error::other("missing upload id"))?
52            .to_string();
53
54        Ok(Self {
55            account_id: account_id.to_string(),
56            bucket: bucket.to_string(),
57            key: key.to_string(),
58            upload_id,
59            buffer: Vec::new(),
60            part_number: 1,
61            completed_parts: Vec::new(),
62            completed: false,
63        })
64    }
65}
66
67impl R2WriteOp {
68    //! Upload Part
69
70    async fn upload_part_async(&mut self, data: Vec<u8>) -> Result<(), io::Error> {
71        let body: ByteStream = ByteStream::from(Bytes::from(data));
72        let output: aws_sdk_s3::operation::upload_part::UploadPartOutput = R2Path::get_client(&self.account_id)
73            .await
74            .upload_part()
75            .bucket(&self.bucket)
76            .key(&self.key)
77            .upload_id(&self.upload_id)
78            .part_number(self.part_number)
79            .body(body)
80            .send()
81            .await
82            .map_err(io::Error::other)?;
83
84        self.completed_parts.push(
85            CompletedPart::builder()
86                .part_number(self.part_number)
87                .set_e_tag(output.e_tag().map(|s| s.to_string()))
88                .build(),
89        );
90        self.part_number += 1;
91        Ok(())
92    }
93}
94
95impl R2WriteOp {
96    //! Upload Full Parts
97
98    /// Uploads every buffered part that has reached `MIN_PART_SIZE`.
99    ///
100    /// The remainder stays buffered for `close` to upload as the final part.
101    fn upload_full_parts(&mut self) -> io::Result<()> {
102        while self.buffer.len() >= MIN_PART_SIZE {
103            let remainder: Vec<u8> = self.buffer.split_off(MIN_PART_SIZE);
104            let part_data: Vec<u8> = std::mem::replace(&mut self.buffer, remainder);
105            RUNTIME.block_on(self.upload_part_async(part_data))?;
106        }
107        Ok(())
108    }
109}
110
111impl io::Write for R2WriteOp {
112    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
113        self.buffer.extend_from_slice(buf);
114        self.upload_full_parts()?;
115        Ok(buf.len())
116    }
117
118    /// Uploads every part that has reached `MIN_PART_SIZE`.
119    ///
120    /// This is not a durability point: multipart uploads reject non-final parts smaller than
121    /// `MIN_PART_SIZE`, so the trailing remainder can only be committed by `close`.
122    fn flush(&mut self) -> io::Result<()> {
123        self.upload_full_parts()
124    }
125}
126
127impl R2WriteOp {
128    //! Close
129
130    /// Completes the multipart upload to R2, creating the object.
131    ///
132    /// This must be called. Dropping the operation instead aborts the upload.
133    pub fn close(mut self) -> Result<(), io::Error> {
134        let result: Result<(), io::Error> = RUNTIME.block_on(self.close_async());
135        if result.is_ok() {
136            self.completed = true;
137        }
138        result
139    }
140
141    async fn close_async(&mut self) -> Result<(), io::Error> {
142        // Upload remaining buffer as the final part.
143        if !self.buffer.is_empty() || self.completed_parts.is_empty() {
144            let data: Vec<u8> = std::mem::take(&mut self.buffer);
145            self.upload_part_async(data).await?;
146        }
147
148        // Complete the multipart upload.
149        let parts: Vec<CompletedPart> = std::mem::take(&mut self.completed_parts);
150        let upload: CompletedMultipartUpload = CompletedMultipartUpload::builder()
151            .set_parts(Some(parts))
152            .build();
153
154        R2Path::get_client(&self.account_id)
155            .await
156            .complete_multipart_upload()
157            .bucket(&self.bucket)
158            .key(&self.key)
159            .upload_id(&self.upload_id)
160            .multipart_upload(upload)
161            .send()
162            .await
163            .map_err(io::Error::other)?;
164
165        Ok(())
166    }
167}
168
169impl Drop for R2WriteOp {
170    /// Aborts the multipart upload unless it was completed by `close`.
171    fn drop(&mut self) {
172        if !self.completed {
173            let account_id: String = std::mem::take(&mut self.account_id);
174            let bucket: String = std::mem::take(&mut self.bucket);
175            let key: String = std::mem::take(&mut self.key);
176            let upload_id: String = std::mem::take(&mut self.upload_id);
177            RUNTIME.spawn(async move {
178                let _result = R2Path::get_client(&account_id)
179                    .await
180                    .abort_multipart_upload()
181                    .bucket(&bucket)
182                    .key(&key)
183                    .upload_id(&upload_id)
184                    .send()
185                    .await;
186            });
187        }
188    }
189}