Skip to main content

opendal_core/raw/oio/write/
multipart_write.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::sync::Arc;
19
20use futures::Future;
21use futures::FutureExt;
22use futures::select;
23
24use crate::raw::*;
25use crate::*;
26
27/// MultipartWrite is used to implement [`oio::Write`] based on multipart
28/// uploads. By implementing MultipartWrite, services don't need to
29/// care about the details of uploading parts.
30///
31/// # Architecture
32///
33/// The architecture after adopting [`MultipartWrite`]:
34///
35/// - Services impl `MultipartWrite`
36/// - `MultipartWriter` impl `Write`
37/// - Expose `MultipartWriter` as `Service::Writer`
38///
39/// # Notes
40///
41/// `MultipartWrite` has an oneshot optimization when `write` has been called only once:
42///
43/// ```no_build
44/// w.write(bs).await?;
45/// w.close().await?;
46/// ```
47///
48/// We will use `write_once` instead of starting a new multipart upload.
49///
50/// # Requirements
51///
52/// Services that implement `MultipartWrite` must fulfill the following requirements:
53///
54/// - Must be a http service that could accept `AsyncBody`.
55/// - Don't need initialization before writing.
56/// - Upload ID is generated by the service via `initiate_part`.
57/// - Complete upload by an ordered part list.
58pub trait MultipartWrite: Send + Sync + Unpin + 'static {
59    /// write_once is used to write the data to underlying storage at once.
60    ///
61    /// MultipartWriter will call this API when:
62    ///
63    /// - All the data has been written to the buffer and we can perform the upload at once.
64    fn write_once(
65        &self,
66        size: u64,
67        body: Buffer,
68    ) -> impl Future<Output = Result<Metadata>> + MaybeSend;
69
70    /// initiate_part will call start a multipart upload and return the upload id.
71    ///
72    /// MultipartWriter will call this when:
73    ///
74    /// - the total size of data is unknown.
75    /// - the total size of data is known, but the size of current write
76    ///   is less than the total size.
77    fn initiate_part(&self) -> impl Future<Output = Result<String>> + MaybeSend;
78
79    /// write_part will write a part of the data and returns the result
80    /// [`MultipartPart`].
81    ///
82    /// MultipartWriter will call this API and stores the result in
83    /// order.
84    ///
85    /// - part_number is the index of the part, starting from 0.
86    fn write_part(
87        &self,
88        upload_id: &str,
89        part_number: usize,
90        size: u64,
91        body: Buffer,
92    ) -> impl Future<Output = Result<MultipartPart>> + MaybeSend;
93
94    /// Copy one absolute bounded source range into a multipart part.
95    fn copy_part(
96        &self,
97        _upload_id: &str,
98        _part_number: usize,
99        _path: &str,
100        _args: OpRead,
101        _range: BytesRange,
102    ) -> impl Future<Output = Result<MultipartPart>> + MaybeSend {
103        async {
104            Err(Error::new(
105                ErrorKind::Unsupported,
106                "multipart writer doesn't support native copy",
107            ))
108        }
109    }
110
111    /// complete_part will complete the multipart upload to build the final
112    /// file.
113    fn complete_part(
114        &self,
115        upload_id: &str,
116        parts: &[MultipartPart],
117    ) -> impl Future<Output = Result<Metadata>> + MaybeSend;
118
119    /// abort_part will cancel the multipart upload and purge all data.
120    fn abort_part(&self, upload_id: &str) -> impl Future<Output = Result<()>> + MaybeSend;
121}
122
123/// The result of [`MultipartWrite::write_part`].
124///
125/// services implement should convert MultipartPart to their own represents.
126///
127/// - `part_number` is the index of the part, starting from 0.
128/// - `etag` is the `ETag` of the part.
129/// - `checksum` is the optional checksum of the part.
130#[derive(Clone)]
131pub struct MultipartPart {
132    /// The number of the part, starting from 0.
133    pub part_number: usize,
134    /// The etag of the part.
135    pub etag: String,
136    /// The checksum of the part.
137    pub checksum: Option<String>,
138    /// The size of the part in bytes.
139    pub size: Option<u64>,
140}
141
142enum MultipartInput {
143    Write(Buffer),
144    Copy {
145        path: String,
146        args: Box<OpRead>,
147        range: BytesRange,
148    },
149}
150
151struct WriteInput<W: MultipartWrite> {
152    w: Arc<W>,
153    executor: Executor,
154    upload_id: Arc<String>,
155    part_number: usize,
156    input: MultipartInput,
157}
158
159/// MultipartWriter will implement [`oio::Write`] based on multipart
160/// uploads.
161pub struct MultipartWriter<W: MultipartWrite> {
162    w: Arc<W>,
163    executor: Executor,
164
165    upload_id: Option<Arc<String>>,
166    parts: Vec<MultipartPart>,
167    cache: Option<Buffer>,
168    next_part_number: usize,
169
170    tasks: ConcurrentTasks<WriteInput<W>, MultipartPart>,
171}
172
173/// # Safety
174///
175/// wasm32 is a special target that we only have one event-loop for this state.
176impl<W: MultipartWrite> MultipartWriter<W> {
177    /// Create a new MultipartWriter.
178    pub fn new(executor: impl Into<Executor>, inner: W, concurrent: usize) -> Self {
179        let executor = executor.into();
180        let w = Arc::new(inner);
181        Self {
182            w,
183            executor: executor.clone(),
184            upload_id: None,
185            parts: Vec::new(),
186            cache: None,
187            next_part_number: 0,
188
189            tasks: ConcurrentTasks::new(executor, concurrent, 0, |input| {
190                Box::pin({
191                    async move {
192                        let fut = async {
193                            match &input.input {
194                                MultipartInput::Write(bytes) => {
195                                    input
196                                        .w
197                                        .write_part(
198                                            &input.upload_id,
199                                            input.part_number,
200                                            bytes.len() as u64,
201                                            bytes.clone(),
202                                        )
203                                        .await
204                                }
205                                MultipartInput::Copy { path, args, range } => {
206                                    input
207                                        .w
208                                        .copy_part(
209                                            &input.upload_id,
210                                            input.part_number,
211                                            path,
212                                            args.as_ref().clone(),
213                                            *range,
214                                        )
215                                        .await
216                                }
217                            }
218                        };
219                        match input.executor.timeout() {
220                            None => {
221                                let result = fut.await;
222                                (input, result)
223                            }
224                            Some(timeout) => {
225                                let result = select! {
226                                    result = fut.fuse() => {
227                                        result
228                                    }
229                                    _ = timeout.fuse() => {
230                                        Err(Error::new(
231                                            ErrorKind::Unexpected, "write part timeout")
232                                                .with_context("upload_id", input.upload_id.to_string())
233                                                .with_context("part_number", input.part_number.to_string())
234                                                .set_temporary())
235                                    }
236                                };
237                                (input, result)
238                            }
239                        }
240                    }
241                })
242            }),
243        }
244    }
245
246    fn fill_cache(&mut self, bs: Buffer) -> usize {
247        let size = bs.len();
248        assert!(self.cache.is_none());
249        self.cache = Some(bs);
250        size
251    }
252
253    async fn upload_id(&mut self) -> Result<Arc<String>> {
254        if let Some(upload_id) = &self.upload_id {
255            return Ok(upload_id.clone());
256        }
257
258        let upload_id = Arc::new(self.w.initiate_part().await?);
259        self.upload_id = Some(upload_id.clone());
260        Ok(upload_id)
261    }
262
263    async fn schedule(&mut self, upload_id: Arc<String>, input: MultipartInput) -> Result<()> {
264        let part_number = self.next_part_number;
265        self.tasks
266            .execute(WriteInput {
267                w: self.w.clone(),
268                executor: self.executor.clone(),
269                upload_id,
270                part_number,
271                input,
272            })
273            .await?;
274        self.next_part_number += 1;
275        Ok(())
276    }
277}
278
279impl<W> oio::Write for MultipartWriter<W>
280where
281    W: MultipartWrite,
282{
283    async fn write(&mut self, bs: Buffer) -> Result<()> {
284        if self.cache.is_none() {
285            self.fill_cache(bs);
286            return Ok(());
287        }
288
289        let upload_id = self.upload_id().await?;
290        let bytes = self.cache.clone().expect("pending write must exist");
291        self.schedule(upload_id, MultipartInput::Write(bytes))
292            .await?;
293        self.cache = None;
294        self.fill_cache(bs);
295        Ok(())
296    }
297
298    async fn copy_from(&mut self, path: &str, args: OpRead, range: BytesRange) -> Result<()> {
299        if range.is_suffix() || range.size().is_none() {
300            return Err(Error::new(
301                ErrorKind::Unexpected,
302                "native writer copy requires an absolute bounded range",
303            ));
304        }
305
306        let upload_id = self.upload_id().await?;
307        if let Some(bytes) = self.cache.clone() {
308            self.schedule(upload_id.clone(), MultipartInput::Write(bytes))
309                .await?;
310            self.cache = None;
311        }
312        self.schedule(
313            upload_id,
314            MultipartInput::Copy {
315                path: path.to_string(),
316                args: Box::new(args),
317                range,
318            },
319        )
320        .await?;
321        Ok(())
322    }
323
324    async fn close(&mut self) -> Result<Metadata> {
325        let upload_id = match self.upload_id.clone() {
326            Some(v) => v,
327            None => {
328                let (size, body) = match self.cache.clone() {
329                    Some(cache) => (cache.len(), cache),
330                    None => (0, Buffer::new()),
331                };
332
333                // Call write_once if there is no upload_id.
334                let meta = self.w.write_once(size as u64, body).await?;
335                // make sure to clear the cache only after write_once succeeds; otherwise, retries may fail.
336                self.cache = None;
337                return Ok(meta);
338            }
339        };
340
341        if let Some(cache) = self.cache.clone() {
342            self.schedule(upload_id.clone(), MultipartInput::Write(cache))
343                .await?;
344            self.cache = None;
345        }
346
347        loop {
348            let Some(result) = self.tasks.next().await.transpose()? else {
349                break;
350            };
351            self.parts.push(result)
352        }
353
354        if self.parts.len() != self.next_part_number {
355            return Err(Error::new(
356                ErrorKind::Unexpected,
357                "multipart part numbers mismatch, please report bug to opendal",
358            )
359            .with_context("expected", self.next_part_number)
360            .with_context("actual", self.parts.len())
361            .with_context("upload_id", upload_id));
362        }
363        self.w.complete_part(&upload_id, &self.parts).await
364    }
365
366    async fn abort(&mut self) -> Result<()> {
367        let Some(upload_id) = self.upload_id.clone() else {
368            return Ok(());
369        };
370
371        self.tasks.clear();
372        self.cache = None;
373        self.w.abort_part(&upload_id).await?;
374        Ok(())
375    }
376}
377
378#[cfg(test)]
379mod tests {
380    use asyncband::mutex::Mutex;
381    use pretty_assertions::assert_eq;
382    use rand::{Rng, RngExt, rng};
383    use tokio::time::sleep;
384    use tokio::time::timeout;
385
386    use super::*;
387    use crate::raw::oio::Write;
388
389    struct TestWrite {
390        upload_id: String,
391        part_numbers: Vec<usize>,
392        length: u64,
393        content: Option<Buffer>,
394        fail_randomly: bool,
395    }
396
397    impl TestWrite {
398        pub fn new() -> Arc<Mutex<Self>> {
399            Self::new_with_failures(true)
400        }
401
402        pub fn new_stable() -> Arc<Mutex<Self>> {
403            Self::new_with_failures(false)
404        }
405
406        fn new_with_failures(fail_randomly: bool) -> Arc<Mutex<Self>> {
407            let v = Self {
408                upload_id: uuid::Uuid::new_v4().to_string(),
409                part_numbers: Vec::new(),
410                length: 0,
411                content: None,
412                fail_randomly,
413            };
414
415            Arc::new(Mutex::new(v))
416        }
417    }
418
419    impl MultipartWrite for Arc<Mutex<TestWrite>> {
420        async fn write_once(&self, size: u64, body: Buffer) -> Result<Metadata> {
421            sleep(Duration::from_nanos(50)).await;
422
423            if self.lock().await.fail_randomly && rng().random_bool(1.0 / 10.0) {
424                return Err(
425                    Error::new(ErrorKind::Unexpected, "I'm a crazy monkey!").set_temporary()
426                );
427            }
428
429            let mut this = self.lock().await;
430            this.length = size;
431            this.content = Some(body);
432            Ok({
433                let mut metadata = MetadataBuilder::unknown();
434                metadata.set_file(size);
435                metadata.build()
436            })
437        }
438
439        async fn initiate_part(&self) -> Result<String> {
440            let upload_id = self.lock().await.upload_id.clone();
441            Ok(upload_id)
442        }
443
444        async fn write_part(
445            &self,
446            upload_id: &str,
447            part_number: usize,
448            size: u64,
449            _: Buffer,
450        ) -> Result<MultipartPart> {
451            {
452                let test = self.lock().await;
453                assert_eq!(upload_id, test.upload_id);
454            }
455
456            // Add an async sleep here to enforce some pending.
457            sleep(Duration::from_nanos(50)).await;
458
459            // We will have 10% percent rate for write part to fail.
460            if self.lock().await.fail_randomly && rng().random_bool(1.0 / 10.0) {
461                return Err(
462                    Error::new(ErrorKind::Unexpected, "I'm a crazy monkey!").set_temporary()
463                );
464            }
465
466            {
467                let mut test = self.lock().await;
468                test.part_numbers.push(part_number);
469                test.length += size;
470            }
471
472            Ok(MultipartPart {
473                part_number,
474                etag: "etag".to_string(),
475                checksum: None,
476                size: None,
477            })
478        }
479
480        async fn copy_part(
481            &self,
482            upload_id: &str,
483            part_number: usize,
484            _: &str,
485            _: OpRead,
486            range: BytesRange,
487        ) -> Result<MultipartPart> {
488            let size = range.size().expect("test range must be bounded");
489            let mut test = self.lock().await;
490            assert_eq!(upload_id, test.upload_id);
491            test.part_numbers.push(part_number);
492            test.length += size;
493            Ok(MultipartPart {
494                part_number,
495                etag: "copied-etag".to_string(),
496                checksum: None,
497                size: Some(size),
498            })
499        }
500
501        async fn complete_part(
502            &self,
503            upload_id: &str,
504            parts: &[MultipartPart],
505        ) -> Result<Metadata> {
506            let test = self.lock().await;
507            assert_eq!(upload_id, test.upload_id);
508            assert_eq!(parts.len(), test.part_numbers.len());
509
510            Ok({
511                let mut metadata = MetadataBuilder::unknown();
512                metadata.set_file(test.length);
513                metadata.build()
514            })
515        }
516
517        async fn abort_part(&self, upload_id: &str) -> Result<()> {
518            let test = self.lock().await;
519            assert_eq!(upload_id, test.upload_id);
520
521            Ok(())
522        }
523    }
524
525    struct TimeoutExecutor {
526        exec: Arc<dyn Execute>,
527    }
528
529    impl TimeoutExecutor {
530        pub fn new() -> Self {
531            Self {
532                exec: Executor::new().into_inner(),
533            }
534        }
535    }
536
537    impl Execute for TimeoutExecutor {
538        fn execute(&self, f: BoxedStaticFuture<()>) {
539            self.exec.execute(f)
540        }
541
542        fn timeout(&self) -> Option<BoxedStaticFuture<()>> {
543            let time = rng().random_range(0..100);
544            Some(Box::pin(tokio::time::sleep(Duration::from_nanos(time))))
545        }
546    }
547
548    #[tokio::test]
549    async fn test_multipart_upload_writer_with_concurrent_errors() {
550        let mut rng = rng();
551
552        let executor = Executor::with(TimeoutExecutor::new());
553
554        let mut w = MultipartWriter::new(executor, TestWrite::new(), 200);
555        let mut total_size = 0u64;
556
557        for _ in 0..1000 {
558            let size = rng.random_range(1..1024);
559            total_size += size as u64;
560
561            let mut bs = vec![0; size];
562            rng.fill_bytes(&mut bs);
563
564            loop {
565                match timeout(Duration::from_nanos(10), w.write(bs.clone().into())).await {
566                    Ok(Ok(_)) => break,
567                    Ok(Err(_)) => continue,
568                    Err(_) => {
569                        continue;
570                    }
571                }
572            }
573        }
574
575        loop {
576            match timeout(Duration::from_nanos(10), w.close()).await {
577                Ok(Ok(_)) => break,
578                Ok(Err(_)) => continue,
579                Err(_) => {
580                    continue;
581                }
582            }
583        }
584
585        let actual_parts: Vec<_> = w.parts.into_iter().map(|v| v.part_number).collect();
586        let expected_parts: Vec<_> = (0..1000).collect();
587        assert_eq!(actual_parts, expected_parts);
588
589        let actual_size = w.w.lock().await.length;
590        assert_eq!(actual_size, total_size);
591    }
592
593    #[tokio::test]
594    async fn test_multipart_writer_with_retry_when_write_once_error() {
595        let mut rng = rng();
596
597        for _ in 0..100 {
598            let mut w = MultipartWriter::new(Executor::default(), TestWrite::new(), 200);
599            let size = rng.random_range(1..1024);
600            let mut bs = vec![0; size];
601            rng.fill_bytes(&mut bs);
602
603            loop {
604                match w.write(bs.clone().into()).await {
605                    Ok(_) => break,
606                    Err(_) => continue,
607                }
608            }
609
610            loop {
611                match w.close().await {
612                    Ok(_) => break,
613                    Err(_) => continue,
614                }
615            }
616
617            let inner = w.w.lock().await;
618            assert_eq!(inner.length, size as u64);
619            assert!(inner.content.is_some());
620            assert_eq!(inner.content.clone().unwrap().to_bytes(), bs);
621        }
622    }
623
624    #[tokio::test]
625    async fn test_multipart_writer_interleaves_writes_and_copies() -> Result<()> {
626        let inner = TestWrite::new_stable();
627        let mut writer = MultipartWriter::new(Executor::default(), inner.clone(), 1);
628
629        writer.write(Buffer::from("local-a")).await?;
630        writer
631            .copy_from("source", OpRead::new(), BytesRange::new(10, Some(11)))
632            .await?;
633        writer.write(Buffer::from("local-b")).await?;
634        writer
635            .copy_from("source", OpRead::new(), BytesRange::new(30, Some(13)))
636            .await?;
637        let metadata = loop {
638            match writer.close().await {
639                Ok(metadata) => break metadata,
640                Err(err) if err.is_temporary() => continue,
641                Err(err) => return Err(err),
642            }
643        };
644
645        assert_eq!(metadata.content_length(), 7 + 11 + 7 + 13);
646        assert_eq!(inner.lock().await.part_numbers, vec![0, 1, 2, 3]);
647        Ok(())
648    }
649}