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