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::VercelArtifactsCore;
23use super::core::parse_error;
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
155    fn info(&self) -> ServiceInfo {
156        self.core.info.clone()
157    }
158
159    fn capability(&self) -> Capability {
160        self.core.capability
161    }
162
163    async fn create_dir(
164        &self,
165        _ctx: &OperationContext,
166        _path: &str,
167        _args: OpCreateDir,
168    ) -> Result<RpCreateDir> {
169        Err(Error::new(
170            ErrorKind::Unsupported,
171            "operation is not supported",
172        ))
173    }
174
175    async fn stat(&self, ctx: &OperationContext, path: &str, _args: OpStat) -> Result<RpStat> {
176        let response = self.core.vercel_artifacts_stat(ctx, path).await?;
177
178        let status = response.status();
179
180        match status {
181            StatusCode::OK => {
182                let meta = parse_into_metadata(path, response.headers())?;
183                Ok(RpStat::new(meta))
184            }
185
186            _ => Err(parse_error(response)),
187        }
188    }
189    fn read(&self, ctx: &OperationContext, path: &str, args: OpRead) -> Result<Self::Reader> {
190        let output: oio::StreamReader<VercelArtifactsReader> = {
191            Ok(oio::StreamReader::new(VercelArtifactsReader::new(
192                self.clone(),
193                ctx.clone(),
194                path,
195                args,
196            )))
197        }?;
198
199        Ok(output)
200    }
201
202    fn write(&self, ctx: &OperationContext, path: &str, args: OpWrite) -> Result<Self::Writer> {
203        let output: oio::OneShotWriter<VercelArtifactsWriter> = {
204            Ok(oio::OneShotWriter::new(VercelArtifactsWriter::new(
205                self.core.clone(),
206                ctx.clone(),
207                args,
208                path.to_string(),
209            )))
210        }?;
211
212        Ok(output)
213    }
214
215    fn delete(&self, _ctx: &OperationContext) -> Result<Self::Deleter> {
216        Err(Error::new(
217            ErrorKind::Unsupported,
218            "operation is not supported",
219        ))
220    }
221
222    fn list(&self, _ctx: &OperationContext, _path: &str, _args: OpList) -> Result<Self::Lister> {
223        Err(Error::new(
224            ErrorKind::Unsupported,
225            "operation is not supported",
226        ))
227    }
228
229    fn copy(
230        &self,
231        _ctx: &OperationContext,
232        _from: &str,
233        _to: &str,
234        _args: OpCopy,
235        _opts: OpCopier,
236    ) -> Result<Self::Copier> {
237        Err(Error::new(
238            ErrorKind::Unsupported,
239            "operation is not supported",
240        ))
241    }
242
243    async fn rename(
244        &self,
245        _ctx: &OperationContext,
246        _from: &str,
247        _to: &str,
248        _args: OpRename,
249    ) -> Result<RpRename> {
250        Err(Error::new(
251            ErrorKind::Unsupported,
252            "operation is not supported",
253        ))
254    }
255
256    async fn presign(
257        &self,
258        _ctx: &OperationContext,
259        _path: &str,
260        _args: OpPresign,
261    ) -> Result<RpPresign> {
262        Err(Error::new(
263            ErrorKind::Unsupported,
264            "operation is not supported",
265        ))
266    }
267}