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