opendal/services/vercel_blob/
backend.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::fmt::Debug;
19use std::fmt::Formatter;
20use std::sync::Arc;
21
22use bytes::Buf;
23use http::Response;
24use http::StatusCode;
25use log::debug;
26
27use super::core::parse_blob;
28use super::core::Blob;
29use super::core::VercelBlobCore;
30use super::error::parse_error;
31use super::lister::VercelBlobLister;
32use super::writer::VercelBlobWriter;
33use super::writer::VercelBlobWriters;
34use crate::raw::*;
35use crate::services::VercelBlobConfig;
36use crate::*;
37
38impl Configurator for VercelBlobConfig {
39    type Builder = VercelBlobBuilder;
40
41    #[allow(deprecated)]
42    fn into_builder(self) -> Self::Builder {
43        VercelBlobBuilder {
44            config: self,
45            http_client: None,
46        }
47    }
48}
49
50/// [VercelBlob](https://vercel.com/docs/storage/vercel-blob) services support.
51#[doc = include_str!("docs.md")]
52#[derive(Default)]
53pub struct VercelBlobBuilder {
54    config: VercelBlobConfig,
55
56    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
57    http_client: Option<HttpClient>,
58}
59
60impl Debug for VercelBlobBuilder {
61    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
62        let mut d = f.debug_struct("VercelBlobBuilder");
63
64        d.field("config", &self.config);
65        d.finish_non_exhaustive()
66    }
67}
68
69impl VercelBlobBuilder {
70    /// Set root of this backend.
71    ///
72    /// All operations will happen under this root.
73    pub fn root(mut self, root: &str) -> Self {
74        self.config.root = if root.is_empty() {
75            None
76        } else {
77            Some(root.to_string())
78        };
79
80        self
81    }
82
83    /// Vercel Blob token.
84    ///
85    /// Get from Vercel environment variable `BLOB_READ_WRITE_TOKEN`.
86    /// It is required.
87    pub fn token(mut self, token: &str) -> Self {
88        if !token.is_empty() {
89            self.config.token = Some(token.to_string());
90        }
91        self
92    }
93
94    /// Specify the http client that used by this service.
95    ///
96    /// # Notes
97    ///
98    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
99    /// during minor updates.
100    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
101    #[allow(deprecated)]
102    pub fn http_client(mut self, client: HttpClient) -> Self {
103        self.http_client = Some(client);
104        self
105    }
106}
107
108impl Builder for VercelBlobBuilder {
109    const SCHEME: Scheme = Scheme::VercelBlob;
110    type Config = VercelBlobConfig;
111
112    /// Builds the backend and returns the result of VercelBlobBackend.
113    fn build(self) -> Result<impl Access> {
114        debug!("backend build started: {:?}", &self);
115
116        let root = normalize_root(&self.config.root.clone().unwrap_or_default());
117        debug!("backend use root {}", &root);
118
119        // Handle token.
120        let Some(token) = self.config.token.clone() else {
121            return Err(Error::new(ErrorKind::ConfigInvalid, "token is empty")
122                .with_operation("Builder::build")
123                .with_context("service", Scheme::VercelBlob));
124        };
125
126        Ok(VercelBlobBackend {
127            core: Arc::new(VercelBlobCore {
128                info: {
129                    let am = AccessorInfo::default();
130                    am.set_scheme(Scheme::VercelBlob)
131                        .set_root(&root)
132                        .set_native_capability(Capability {
133                            stat: true,
134                            stat_has_content_type: true,
135                            stat_has_content_length: true,
136                            stat_has_last_modified: true,
137                            stat_has_content_disposition: true,
138
139                            read: true,
140
141                            write: true,
142                            write_can_empty: true,
143                            write_can_multi: true,
144                            write_multi_min_size: Some(5 * 1024 * 1024),
145
146                            copy: true,
147
148                            list: true,
149                            list_with_limit: true,
150                            list_has_content_type: true,
151                            list_has_content_length: true,
152                            list_has_last_modified: true,
153                            list_has_content_disposition: true,
154
155                            shared: true,
156
157                            ..Default::default()
158                        });
159
160                    // allow deprecated api here for compatibility
161                    #[allow(deprecated)]
162                    if let Some(client) = self.http_client {
163                        am.update_http_client(|_| client);
164                    }
165
166                    am.into()
167                },
168                root,
169                token,
170            }),
171        })
172    }
173}
174
175/// Backend for VercelBlob services.
176#[derive(Debug, Clone)]
177pub struct VercelBlobBackend {
178    core: Arc<VercelBlobCore>,
179}
180
181impl Access for VercelBlobBackend {
182    type Reader = HttpBody;
183    type Writer = VercelBlobWriters;
184    type Lister = oio::PageLister<VercelBlobLister>;
185    type Deleter = ();
186    type BlockingReader = ();
187    type BlockingWriter = ();
188    type BlockingLister = ();
189    type BlockingDeleter = ();
190
191    fn info(&self) -> Arc<AccessorInfo> {
192        self.core.info.clone()
193    }
194
195    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
196        let resp = self.core.head(path).await?;
197
198        let status = resp.status();
199
200        match status {
201            StatusCode::OK => {
202                let bs = resp.into_body();
203
204                let resp: Blob =
205                    serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
206
207                parse_blob(&resp).map(RpStat::new)
208            }
209            _ => Err(parse_error(resp)),
210        }
211    }
212
213    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
214        let resp = self.core.download(path, args.range(), &args).await?;
215
216        let status = resp.status();
217
218        match status {
219            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
220                Ok((RpRead::default(), resp.into_body()))
221            }
222            _ => {
223                let (part, mut body) = resp.into_parts();
224                let buf = body.to_buffer().await?;
225                Err(parse_error(Response::from_parts(part, buf)))
226            }
227        }
228    }
229
230    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
231        let concurrent = args.concurrent();
232        let writer = VercelBlobWriter::new(self.core.clone(), args, path.to_string());
233
234        let w = oio::MultipartWriter::new(self.core.info.clone(), writer, concurrent);
235
236        Ok((RpWrite::default(), w))
237    }
238
239    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
240        let resp = self.core.copy(from, to).await?;
241
242        let status = resp.status();
243
244        match status {
245            StatusCode::OK => Ok(RpCopy::default()),
246            _ => Err(parse_error(resp)),
247        }
248    }
249
250    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
251        let l = VercelBlobLister::new(self.core.clone(), path, args.limit());
252        Ok((RpList::default(), oio::PageLister::new(l)))
253    }
254}