Skip to main content

file_storage/system/r2/file/
write.rs

1use crate::system::r2::r2_path::RUNTIME;
2use crate::system::{R2Path, R2WriteOp};
3use crate::Error;
4use crate::Headers;
5use crate::Operation::Write;
6use aws_sdk_s3::error::ProvideErrorMetadata;
7use aws_sdk_s3::error::SdkError;
8use aws_sdk_s3::operation::put_object::builders::PutObjectFluentBuilder;
9use aws_sdk_s3::primitives::ByteStream;
10use bytes::Bytes;
11
12impl<'a> R2Path<'a> {
13    //! Write
14
15    /// See `FilePath::write_if_not_exists`.
16    pub fn write_if_not_exists(self) -> Result<Option<R2WriteOp>, Error> {
17        RUNTIME.block_on(self.write_if_not_exists_async())
18    }
19
20    /// See `FilePath::write_if_not_exists`.
21    async fn write_if_not_exists_async(self) -> Result<Option<R2WriteOp>, Error> {
22        if self.exists_async().await? {
23            return Ok(None);
24        }
25        let op: R2WriteOp = R2WriteOp::create(self.account_id, self.bucket, self.key)
26            .await
27            .map_err(|e| Error::from_source(self.path.clone(), Write, e))?;
28        Ok(Some(op))
29    }
30
31    /// See `FilePath::write_data_if_not_exists`.
32    pub fn write_data_if_not_exists<D>(self, data: D) -> Result<bool, Error>
33    where
34        D: AsRef<[u8]>,
35    {
36        self.write_with_headers_if_not_exists(data, &Headers::default())
37    }
38
39    /// See `FilePath::write_data_if_not_exists`.
40    pub async fn write_data_if_not_exists_async<D>(self, data: D) -> Result<bool, Error>
41    where
42        D: AsRef<[u8]>,
43    {
44        self.write_with_headers_if_not_exists_async(data.as_ref(), &Headers::default())
45            .await
46    }
47}
48
49impl<'a> R2Path<'a> {
50    //! Write: Headers
51
52    /// See `FilePath::write_with_headers`.
53    pub fn write_with_headers<D>(self, data: D, headers: &Headers) -> Result<(), Error>
54    where
55        D: AsRef<[u8]>,
56    {
57        RUNTIME.block_on(self.write_with_headers_async(data.as_ref(), headers))
58    }
59
60    /// See `FilePath::write_with_headers`.
61    pub async fn write_with_headers_async(self, data: &[u8], headers: &Headers) -> Result<(), Error> {
62        let request: PutObjectFluentBuilder = self.put_request(data, headers).await;
63        match request.send().await {
64            Ok(_response) => Ok(()),
65            Err(error) => Err(Error::from_source(
66                self.path.clone(),
67                Write,
68                std::io::Error::other(error),
69            )),
70        }
71    }
72
73    /// See `FilePath::write_with_headers_if_not_exists`.
74    pub fn write_with_headers_if_not_exists<D>(
75        self,
76        data: D,
77        headers: &Headers,
78    ) -> Result<bool, Error>
79    where
80        D: AsRef<[u8]>,
81    {
82        RUNTIME.block_on(self.write_with_headers_if_not_exists_async(data.as_ref(), headers))
83    }
84
85    /// See `FilePath::write_with_headers_if_not_exists`.
86    pub async fn write_with_headers_if_not_exists_async(
87        self,
88        data: &[u8],
89        headers: &Headers,
90    ) -> Result<bool, Error> {
91        let request: PutObjectFluentBuilder = self
92            .put_request(data, headers)
93            .await
94            .set_if_none_match(Some("*".to_string()));
95        match request.send().await {
96            Ok(_response) => Ok(true),
97            Err(SdkError::ServiceError(error))
98                if error.err().code() == Some("PreconditionFailed") =>
99            {
100                Ok(false)
101            }
102            Err(error) => Err(Error::from_source(
103                self.path.clone(),
104                Write,
105                std::io::Error::other(error),
106            )),
107        }
108    }
109
110    /// Builds a `put_object` request with the `data` body and `headers` applied.
111    ///
112    /// Recognized response headers map to their typed setters; any others are set as object
113    /// metadata.
114    async fn put_request(self, data: &[u8], headers: &Headers) -> PutObjectFluentBuilder {
115        let body: ByteStream = ByteStream::from(Bytes::copy_from_slice(data));
116        let mut request: PutObjectFluentBuilder = Self::get_client(self.account_id)
117            .await
118            .put_object()
119            .bucket(self.bucket)
120            .key(self.key)
121            .body(body);
122        for (name, value) in headers.iter() {
123            request = match name.to_ascii_lowercase().as_str() {
124                "content-type" => request.content_type(value),
125                "cache-control" => request.cache_control(value),
126                "content-encoding" => request.content_encoding(value),
127                "content-disposition" => request.content_disposition(value),
128                "content-language" => request.content_language(value),
129                _ => request.metadata(name, value),
130            };
131        }
132        request
133    }
134}