Skip to main content

file_storage/system/r2/file/
read.rs

1use crate::system::r2::r2_path::RUNTIME;
2use crate::system::{R2Path, R2ReadOp};
3use crate::Error;
4use crate::Operation::Read;
5use aws_sdk_s3::error::SdkError;
6use aws_sdk_s3::operation::get_object::{GetObjectError, GetObjectOutput};
7
8impl<'a> R2Path<'a> {
9    //! Read
10
11    async fn get_object_output(self) -> Result<Option<GetObjectOutput>, Error> {
12        let result: Result<GetObjectOutput, SdkError<GetObjectError>> =
13            Self::get_client(self.account_id)
14                .await
15                .get_object()
16                .bucket(self.bucket)
17                .key(self.key)
18                .send()
19                .await;
20        match result {
21            Ok(get_object_output) => Ok(Some(get_object_output)),
22            Err(error) => {
23                if matches!(error.as_service_error(), Some(GetObjectError::NoSuchKey(_))) {
24                    Ok(None)
25                } else {
26                    Err(Error::from_source(
27                        self.path.clone(),
28                        Read,
29                        std::io::Error::other(error),
30                    ))
31                }
32            }
33        }
34    }
35
36    /// See `FilePath::read_if_exists`.
37    async fn read_if_exists_async(self) -> Result<Option<R2ReadOp>, Error> {
38        if let Some(object) = self.get_object_output().await? {
39            Ok(Some(R2ReadOp::from(object)))
40        } else {
41            Ok(None)
42        }
43    }
44
45    /// See `FilePath::read_if_exists`.
46    pub fn read_if_exists(self) -> Result<Option<R2ReadOp>, Error> {
47        RUNTIME.block_on(self.read_if_exists_async())
48    }
49
50    /// See `FilePath::read_to_vec_if_exists`.
51    pub fn read_to_vec_if_exists(self, target: &mut Vec<u8>) -> Result<Option<usize>, Error> {
52        RUNTIME.block_on(self.read_to_vec_if_exists_async(target))
53    }
54
55    /// See `FilePath::read_to_vec_if_exists`.
56    pub async fn read_to_vec_if_exists_async(
57        self,
58        target: &mut Vec<u8>,
59    ) -> Result<Option<usize>, Error> {
60        if let Some(object) = self.get_object_output().await? {
61            let mut body: aws_sdk_s3::primitives::ByteStream = object.body;
62            let min_size: u64 = body.size_hint().0;
63            if min_size > 0 && min_size <= usize::MAX as u64 {
64                target.reserve(min_size as usize);
65            }
66            let mut total: usize = 0;
67            while let Some(chunk) = body
68                .try_next()
69                .await
70                .map_err(|error| Error::from_source(self.path.clone(), Read, error))?
71            {
72                target.extend_from_slice(&chunk);
73                total += chunk.len();
74            }
75            Ok(Some(total))
76        } else {
77            Ok(None)
78        }
79    }
80}