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
135                            read: true,
136
137                            write: true,
138                            write_can_empty: true,
139                            write_can_multi: true,
140                            write_multi_min_size: Some(5 * 1024 * 1024),
141
142                            copy: true,
143
144                            list: true,
145                            list_with_limit: true,
146
147                            shared: true,
148
149                            ..Default::default()
150                        });
151
152                    // allow deprecated api here for compatibility
153                    #[allow(deprecated)]
154                    if let Some(client) = self.http_client {
155                        am.update_http_client(|_| client);
156                    }
157
158                    am.into()
159                },
160                root,
161                token,
162            }),
163        })
164    }
165}
166
167/// Backend for VercelBlob services.
168#[derive(Debug, Clone)]
169pub struct VercelBlobBackend {
170    core: Arc<VercelBlobCore>,
171}
172
173impl Access for VercelBlobBackend {
174    type Reader = HttpBody;
175    type Writer = VercelBlobWriters;
176    type Lister = oio::PageLister<VercelBlobLister>;
177    type Deleter = ();
178
179    fn info(&self) -> Arc<AccessorInfo> {
180        self.core.info.clone()
181    }
182
183    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
184        let resp = self.core.head(path).await?;
185
186        let status = resp.status();
187
188        match status {
189            StatusCode::OK => {
190                let bs = resp.into_body();
191
192                let resp: Blob =
193                    serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
194
195                parse_blob(&resp).map(RpStat::new)
196            }
197            _ => Err(parse_error(resp)),
198        }
199    }
200
201    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
202        let resp = self.core.download(path, args.range(), &args).await?;
203
204        let status = resp.status();
205
206        match status {
207            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
208                Ok((RpRead::default(), resp.into_body()))
209            }
210            _ => {
211                let (part, mut body) = resp.into_parts();
212                let buf = body.to_buffer().await?;
213                Err(parse_error(Response::from_parts(part, buf)))
214            }
215        }
216    }
217
218    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
219        let concurrent = args.concurrent();
220        let writer = VercelBlobWriter::new(self.core.clone(), args, path.to_string());
221
222        let w = oio::MultipartWriter::new(self.core.info.clone(), writer, concurrent);
223
224        Ok((RpWrite::default(), w))
225    }
226
227    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
228        let resp = self.core.copy(from, to).await?;
229
230        let status = resp.status();
231
232        match status {
233            StatusCode::OK => Ok(RpCopy::default()),
234            _ => Err(parse_error(resp)),
235        }
236    }
237
238    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
239        let l = VercelBlobLister::new(self.core.clone(), path, args.limit());
240        Ok((RpList::default(), oio::PageLister::new(l)))
241    }
242}