Skip to main content

opendal_service_tos/
config.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;
19
20use opendal_core::Configurator;
21use opendal_core::OperatorUri;
22use opendal_core::Result;
23use serde::Deserialize;
24use serde::Serialize;
25
26use crate::backend::TosBuilder;
27
28/// Config for Volcengine TOS service.
29#[derive(Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
30#[serde(default)]
31#[non_exhaustive]
32pub struct TosConfig {
33    /// root of this backend.
34    ///
35    /// All operations will happen under this root.
36    ///
37    /// default to `/` if not set.
38    pub root: Option<String>,
39    /// bucket name of this backend.
40    ///
41    /// required.
42    pub bucket: String,
43    /// endpoint of this backend.
44    ///
45    /// Endpoint must be full uri, e.g.
46    /// - TOS: `https://tos-cn-beijing.volces.com`
47    /// - TOS with region: `https://tos-{region}.volces.com`
48    ///
49    /// If user inputs endpoint without scheme like "tos-cn-beijing.volces.com", we
50    /// will prepend "https://" before it.
51    pub endpoint: Option<String>,
52    /// Region represent the signing region of this endpoint.
53    ///
54    /// Required if endpoint is not provided.
55    ///
56    /// - If region is set, we will take user's input first.
57    /// - If not, we will try to load it from environment.
58    /// - If still not set, default to `cn-beijing`.
59    pub region: Option<String>,
60    /// access_key_id of this backend.
61    ///
62    /// - If access_key_id is set, we will take user's input first.
63    /// - If not, we will try to load it from environment.
64    #[serde(alias = "tos_access_key_id", alias = "volcengine_access_key_id")]
65    pub access_key_id: Option<String>,
66    /// secret_access_key of this backend.
67    ///
68    /// - If secret_access_key is set, we will take user's input first.
69    /// - If not, we will try to load it from environment.
70    #[serde(
71        alias = "tos_secret_access_key",
72        alias = "volcengine_secret_access_key"
73    )]
74    pub secret_access_key: Option<String>,
75    /// security_token of this backend.
76    ///
77    /// This token will expire after sometime, it's recommended to set security_token
78    /// by hand.
79    #[serde(alias = "tos_security_token", alias = "volcengine_session_token")]
80    pub security_token: Option<String>,
81    /// Disable config load so that opendal will not load config from
82    /// environment.
83    ///
84    /// For examples:
85    ///
86    /// - envs like `VOLCENGINE_ACCESS_KEY_ID`
87    pub disable_config_load: bool,
88    /// Skip signature will skip loading credentials and signing requests.
89    pub skip_signature: bool,
90}
91
92impl Debug for TosConfig {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        f.debug_struct("TosConfig")
95            .field("root", &self.root)
96            .field("bucket", &self.bucket)
97            .field("endpoint", &self.endpoint)
98            .field("region", &self.region)
99            .finish_non_exhaustive()
100    }
101}
102
103impl Configurator for TosConfig {
104    type Builder = TosBuilder;
105
106    fn from_uri(uri: &OperatorUri) -> Result<Self> {
107        let mut map = uri.options().clone();
108
109        if let Some(name) = uri.name() {
110            map.insert("bucket".to_string(), name.to_string());
111        }
112
113        if let Some(root) = uri.root() {
114            map.insert("root".to_string(), root.to_string());
115        }
116
117        Self::from_iter(map)
118    }
119
120    fn into_builder(self) -> Self::Builder {
121        TosBuilder { config: self }
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use std::iter;
128
129    use super::*;
130    use opendal_core::Configurator;
131    use opendal_core::OperatorUri;
132
133    #[test]
134    fn test_tos_config_original_field_names() {
135        let json = r#"{
136            "bucket": "test-bucket",
137            "access_key_id": "test-key",
138            "secret_access_key": "test-secret",
139            "region": "cn-beijing",
140            "endpoint": "https://tos-cn-beijing.volces.com"
141        }"#;
142
143        let config: TosConfig = serde_json::from_str(json).unwrap();
144        assert_eq!(config.bucket, "test-bucket");
145        assert_eq!(config.access_key_id, Some("test-key".to_string()));
146        assert_eq!(config.secret_access_key, Some("test-secret".to_string()));
147        assert_eq!(config.region, Some("cn-beijing".to_string()));
148        assert_eq!(
149            config.endpoint,
150            Some("https://tos-cn-beijing.volces.com".to_string())
151        );
152    }
153
154    #[test]
155    fn test_tos_config_tos_prefixed_aliases() {
156        let json = r#"{
157            "tos_access_key_id": "test-key",
158            "tos_secret_access_key": "test-secret",
159            "tos_security_token": "test-token"
160        }"#;
161
162        let config: TosConfig = serde_json::from_str(json).unwrap();
163        assert_eq!(config.access_key_id, Some("test-key".to_string()));
164        assert_eq!(config.secret_access_key, Some("test-secret".to_string()));
165        assert_eq!(config.security_token, Some("test-token".to_string()));
166    }
167
168    #[test]
169    fn test_tos_config_volcengine_prefixed_aliases() {
170        let json = r#"{
171            "volcengine_access_key_id": "test-key",
172            "volcengine_secret_access_key": "test-secret",
173            "volcengine_session_token": "test-token"
174        }"#;
175
176        let config: TosConfig = serde_json::from_str(json).unwrap();
177        assert_eq!(config.access_key_id, Some("test-key".to_string()));
178        assert_eq!(config.secret_access_key, Some("test-secret".to_string()));
179        assert_eq!(config.security_token, Some("test-token".to_string()));
180    }
181
182    #[test]
183    fn from_uri_extracts_bucket_and_root() {
184        let uri = OperatorUri::new("tos://example-bucket/path/to/root", iter::empty()).unwrap();
185        let cfg = TosConfig::from_uri(&uri).unwrap();
186        assert_eq!(cfg.bucket, "example-bucket");
187        assert_eq!(cfg.root.as_deref(), Some("path/to/root"));
188    }
189
190    #[test]
191    fn from_uri_extracts_endpoint() {
192        let uri = OperatorUri::new(
193            "tos://example-bucket/path/to/root?endpoint=https%3A%2F%2Fcustom-tos-endpoint.com",
194            iter::empty(),
195        )
196        .unwrap();
197        let cfg = TosConfig::from_uri(&uri).unwrap();
198        assert_eq!(cfg.bucket, "example-bucket");
199        assert_eq!(cfg.root.as_deref(), Some("path/to/root"));
200        assert_eq!(
201            cfg.endpoint.as_deref(),
202            Some("https://custom-tos-endpoint.com")
203        );
204    }
205}