Skip to main content

opendal_service_vercel_artifacts/
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::sync::Arc;
19
20use http::StatusCode;
21
22use super::core::parse_error;
23use super::core::{ErrorContext, VercelArtifactsCore};
24use super::reader::*;
25use super::writer::VercelArtifactsWriter;
26use opendal_core::raw::*;
27use opendal_core::*;
28
29#[doc = include_str!("docs.md")]
30use std::fmt::Debug;
31
32use super::VERCEL_ARTIFACTS_SCHEME;
33use super::config::VercelArtifactsConfig;
34
35/// [Vercel Cache](https://vercel.com/docs/concepts/monorepos/remote-caching) backend support.
36#[doc = include_str!("docs.md")]
37#[derive(Default)]
38pub struct VercelArtifactsBuilder {
39    pub(super) config: VercelArtifactsConfig,
40}
41
42impl Debug for VercelArtifactsBuilder {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        f.debug_struct("VercelArtifactsBuilder")
45            .field("config", &self.config)
46            .finish_non_exhaustive()
47    }
48}
49
50impl VercelArtifactsBuilder {
51    /// set the bearer access token for Vercel
52    ///
53    /// default: no access token, which leads to failure
54    pub fn access_token(mut self, access_token: &str) -> Self {
55        self.config.access_token = Some(access_token.to_string());
56        self
57    }
58
59    /// Set the endpoint for the Vercel artifacts API.
60    ///
61    /// Default: `https://api.vercel.com`
62    pub fn endpoint(mut self, endpoint: &str) -> Self {
63        if !endpoint.is_empty() {
64            self.config.endpoint = Some(endpoint.trim_end_matches('/').to_string());
65        }
66        self
67    }
68
69    /// Set the Vercel team ID.
70    ///
71    /// When set, the `teamId` query parameter is appended to all requests.
72    pub fn team_id(mut self, team_id: &str) -> Self {
73        if !team_id.is_empty() {
74            self.config.team_id = Some(team_id.to_string());
75        }
76        self
77    }
78
79    /// Set the Vercel team slug.
80    ///
81    /// When set, the `slug` query parameter is appended to all requests.
82    pub fn team_slug(mut self, team_slug: &str) -> Self {
83        if !team_slug.is_empty() {
84            self.config.team_slug = Some(team_slug.to_string());
85        }
86        self
87    }
88}
89
90impl Builder for VercelArtifactsBuilder {
91    type Config = VercelArtifactsConfig;
92
93    fn build(self) -> Result<impl Service> {
94        let info = ServiceInfo::new(VERCEL_ARTIFACTS_SCHEME, "", "");
95        let capability = Capability {
96            stat: true,
97
98            read: true,
99            read_with_suffix: true,
100
101            write: true,
102
103            shared: true,
104
105            ..Default::default()
106        };
107
108        let access_token = self
109            .config
110            .access_token
111            .ok_or_else(|| Error::new(ErrorKind::ConfigInvalid, "access_token not set"))?;
112
113        let endpoint = self
114            .config
115            .endpoint
116            .unwrap_or_else(|| "https://api.vercel.com".to_string());
117
118        let mut query_params = Vec::new();
119        if let Some(team_id) = &self.config.team_id {
120            query_params.push(format!("teamId={team_id}"));
121        }
122        if let Some(slug) = &self.config.team_slug {
123            query_params.push(format!("slug={slug}"));
124        }
125        let query_string = if query_params.is_empty() {
126            String::new()
127        } else {
128            format!("?{}", query_params.join("&"))
129        };
130
131        Ok(VercelArtifactsBackend {
132            core: Arc::new(VercelArtifactsCore {
133                info,
134                capability,
135                access_token,
136                endpoint,
137                query_string,
138            }),
139        })
140    }
141}
142
143#[derive(Clone, Debug)]
144pub struct VercelArtifactsBackend {
145    pub core: Arc<VercelArtifactsCore>,
146}
147
148impl Service for VercelArtifactsBackend {
149    type Reader = oio::StreamReader<VercelArtifactsReader>;
150    type Writer = oio::OneShotWriter<VercelArtifactsWriter>;
151    type Lister = ();
152    type Deleter = ();
153    type Copier = ();
154    type Composer = ();
155
156    fn info(&self) -> ServiceInfo {
157        self.core.info.clone()
158    }
159
160    fn capability(&self) -> Capability {
161        self.core.capability
162    }
163
164    async fn create_dir(
165        &self,
166        _ctx: &OperationContext,
167        _path: &str,
168        _args: OpCreateDir,
169    ) -> Result<RpCreateDir> {
170        Err(Error::new(
171            ErrorKind::Unsupported,
172            "operation is not supported",
173        ))
174    }
175
176    async fn stat(&self, ctx: &OperationContext, path: &str, _args: OpStat) -> Result<RpStat> {
177        let response = self.core.vercel_artifacts_stat(ctx, path).await?;
178
179        let status = response.status();
180
181        match status {
182            StatusCode::OK => {
183                let meta = parse_into_metadata(path, response.headers())?;
184                Ok(RpStat::new(meta))
185            }
186
187            _ => Err(parse_error(
188                ErrorContext::new(ServiceOperation("HeadArtifact")),
189                response,
190            )),
191        }
192    }
193    fn read(&self, ctx: &OperationContext, path: &str, args: OpRead) -> Result<Self::Reader> {
194        let output: oio::StreamReader<VercelArtifactsReader> = {
195            Ok(oio::StreamReader::new(VercelArtifactsReader::new(
196                self.clone(),
197                ctx.clone(),
198                path,
199                args,
200            )))
201        }?;
202
203        Ok(output)
204    }
205
206    fn write(&self, ctx: &OperationContext, path: &str, args: OpWrite) -> Result<Self::Writer> {
207        let output: oio::OneShotWriter<VercelArtifactsWriter> = {
208            Ok(oio::OneShotWriter::new(VercelArtifactsWriter::new(
209                self.core.clone(),
210                ctx.clone(),
211                args,
212                path.to_string(),
213            )))
214        }?;
215
216        Ok(output)
217    }
218
219    fn delete(&self, _ctx: &OperationContext) -> Result<Self::Deleter> {
220        Err(Error::new(
221            ErrorKind::Unsupported,
222            "operation is not supported",
223        ))
224    }
225
226    fn list(&self, _ctx: &OperationContext, _path: &str, _args: OpList) -> Result<Self::Lister> {
227        Err(Error::new(
228            ErrorKind::Unsupported,
229            "operation is not supported",
230        ))
231    }
232
233    fn copy(
234        &self,
235        _ctx: &OperationContext,
236        _from: &str,
237        _to: &str,
238        _args: OpCopy,
239    ) -> Result<Self::Copier> {
240        Err(Error::new(
241            ErrorKind::Unsupported,
242            "operation is not supported",
243        ))
244    }
245
246    async fn rename(
247        &self,
248        _ctx: &OperationContext,
249        _from: &str,
250        _to: &str,
251        _args: OpRename,
252    ) -> Result<RpRename> {
253        Err(Error::new(
254            ErrorKind::Unsupported,
255            "operation is not supported",
256        ))
257    }
258
259    async fn presign(
260        &self,
261        _ctx: &OperationContext,
262        _path: &str,
263        _args: OpPresign,
264    ) -> Result<RpPresign> {
265        Err(Error::new(
266            ErrorKind::Unsupported,
267            "operation is not supported",
268        ))
269    }
270}