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