volcengine_rust_sdk/volcengine/
config.rs

1/*
2 * @Author: Jerry.Yang
3 * @Date: 2024-10-16 17:41:31
4 * @LastEditors: Jerry.Yang
5 * @LastEditTime: 2025-02-05 14:08:39
6 * @Description: Utility configuration for Volcengine.
7 */
8
9use crate::volcengine::credentials::credentials; // Importing the Credentials struct
10use crate::volcengine::error::error; // Importing the custom Error type
11
12/// Represents the configuration settings required for connecting to Volcengine services.
13///
14/// The `Config` struct holds essential parameters such as the service region, endpoint,
15/// SSL settings, and authentication credentials. It is designed to be used with a builder
16/// pattern (`ConfigBuilder`) to allow flexible and structured configuration.
17///
18/// # Fields
19/// - `region` (`String`): Specifies the geographical region for the service.
20/// - `endpoint` (`String`): The base URL of the API service. If manually set, this overrides
21///   the default endpoint.
22/// - `disable_ssl` (`bool`): Determines whether SSL/TLS is disabled.
23///   - `true`: SSL is disabled (not recommended for production).
24///   - `false`: SSL is enabled for secure communication.
25/// - `credentials` (`credentials::Credentials`): Stores authentication credentials,
26///   including access keys and secret keys, required for making API requests.
27///
28/// # Example
29/// ```rust
30/// let config = Config {
31///     region: "us-west-2".to_string(),
32///     endpoint: "https://api.volcengine.com".to_string(),
33///     disable_ssl: false,
34///     credentials: credentials::Credentials::new("access_key", "secret_key"),
35/// };
36/// ```
37#[derive(Debug, Clone)]
38pub struct Config {
39    pub region: String,    // The geographical region where the service is deployed.
40    pub endpoint: String,  // The API endpoint for the service.
41    pub disable_ssl: bool, // Indicates whether SSL/TLS is disabled.
42    pub credentials: credentials::Credentials, // Authentication credentials for accessing the service.
43}
44
45/// Implementation of the `Config` struct, providing utility methods  
46/// for managing application configuration settings.  
47///  
48/// This implementation includes a builder method to facilitate  
49/// constructing a `Config` instance step-by-step using the `ConfigBuilder`.  
50///  
51/// ## Key Functionalities  
52/// - `builder()`: Returns a new `ConfigBuilder` instance with default values,  
53///   allowing users to set configuration properties before building a `Config` object.  
54///  
55/// The `Config` struct encapsulates essential configuration parameters such as  
56/// service region, endpoint URL, SSL settings, and authentication credentials.  
57/// This implementation ensures that configuration objects are created in  
58/// a structured and validated manner.  
59impl Config {
60    /// Creates a new `ConfigBuilder` instance to facilitate the construction of a `Config` object.
61    ///
62    /// This method returns a `ConfigBuilder` with default values, allowing users to configure
63    /// the settings step by step before building a complete `Config` instance.
64    ///
65    /// # Example
66    /// ```rust
67    /// let builder = Config::builder();
68    /// ```
69    pub fn builder() -> ConfigBuilder {
70        ConfigBuilder::default() // Returns a new ConfigBuilder with default values.
71    }
72}
73
74/// A builder for constructing a `Config` instance in a structured manner.
75///
76/// The `ConfigBuilder` struct allows users to set configuration parameters individually,
77/// ensuring required fields are provided before building the final `Config` instance.
78///
79/// # Fields
80/// - `region` (`Option<String>`): Optional region value.
81/// - `endpoint` (`Option<String>`): Optional endpoint value.
82/// - `disable_ssl` (`Option<bool>`): Optional SSL flag.
83/// - `credentials` (`Option<credentials::Credentials>`): Optional authentication credentials.
84pub struct ConfigBuilder {
85    region: Option<String>,                        // Optional region value.
86    endpoint: Option<String>,                      // Optional endpoint value.
87    disable_ssl: Option<bool>,                     // Optional SSL flag.
88    credentials: Option<credentials::Credentials>, // Optional credentials.
89}
90
91/// Provides a default implementation for `ConfigBuilder`,  
92/// initializing all fields to `None`.  
93///  
94/// This implementation ensures that when a `ConfigBuilder` instance is created  
95/// without any parameters, it starts with no predefined values. The user can  
96/// then set specific fields as needed before calling `build()`.  
97///  
98/// ## Default Values  
99/// - `region`: `None` (must be provided if required for the configuration)  
100/// - `endpoint`: `None` (must be provided if required for the configuration)  
101/// - `disable_ssl`: `None` (defaults to `false` if not explicitly set)  
102/// - `credentials`: `None` (mandatory; `build()` will return an error if not provided)  
103///  
104/// Using the builder pattern with a default constructor allows flexibility  
105/// while enforcing validation rules in the `build()` method.  
106impl Default for ConfigBuilder {
107    fn default() -> Self {
108        Self {
109            region: None,      // Default region is None.
110            endpoint: None,    // Default endpoint is None.
111            disable_ssl: None, // Default SSL flag is None.
112            credentials: None, // Default credentials are None.
113        }
114    }
115}
116
117/// Implementation of the `ConfigBuilder` struct, which provides a fluent interface  
118/// for constructing a `Config` instance step-by-step.  
119///  
120/// The builder pattern allows for greater flexibility when creating configuration objects  
121/// by enabling method chaining to set individual parameters. This approach ensures  
122/// that required fields are validated before the final `Config` instance is created.  
123///  
124/// ## Example Usage  
125/// ```rust  
126/// use crate::volcengine::config::Config;  
127///  
128/// let config = Config::builder()  
129///     .with_region("us-east-1")  
130///     .with_endpoint("https://example.com")  
131///     .with_disable_ssl(true)  
132///     .with_credentials(credentials)  
133///     .build()  
134///     .expect("Failed to build config");  
135/// ```  
136///  
137/// Each setter method in `ConfigBuilder` accepts an argument, modifies the corresponding  
138/// field, and returns `self` to allow method chaining. The `build` method performs final  
139/// validation and returns a `Config` instance or an error if mandatory fields are missing.  
140impl ConfigBuilder {
141    /// Sets the region for the configuration.
142    ///
143    /// # Arguments
144    /// - `region` (`&str`): The service region to be set.
145    ///
146    /// # Returns
147    /// - `Self`: The updated `ConfigBuilder` instance with the specified region.
148    pub fn with_region(mut self, region: &str) -> Self {
149        self.region = Some(region.to_string()); // Store the region as an `Option<String>`.
150        self
151    }
152
153    /// Sets the endpoint URL for the configuration.
154    ///
155    /// # Arguments
156    /// - `endpoint` (`&str`): The service endpoint to be set.
157    ///
158    /// # Returns
159    /// - `Self`: The updated `ConfigBuilder` instance with the specified endpoint.
160    pub fn with_endpoint(mut self, endpoint: &str) -> Self {
161        self.endpoint = Some(endpoint.to_string()); // Store the endpoint as an `Option<String>`.
162        self
163    }
164
165    /// Enables or disables SSL in the configuration.
166    ///
167    /// # Arguments
168    /// - `disable_ssl` (`bool`): Set to `true` to disable SSL, or `false` to enable it.
169    ///
170    /// # Returns
171    /// - `Self`: The updated `ConfigBuilder` instance with the specified SSL setting.
172    pub fn with_disable_ssl(mut self, disable_ssl: bool) -> Self {
173        self.disable_ssl = Some(disable_ssl); // Store the SSL flag as an `Option<bool>`.
174        self
175    }
176
177    /// Sets the credentials for the configuration.
178    ///
179    /// # Arguments
180    /// - `credentials` (`credentials::Credentials`): Authentication credentials.
181    ///
182    /// # Returns
183    /// - `Self`: The updated `ConfigBuilder` instance with the specified credentials.
184    pub fn with_credentials(mut self, credentials: credentials::Credentials) -> Self {
185        self.credentials = Some(credentials); // Store the credentials as an `Option<Credentials>`.
186        self
187    }
188
189    /// Builds the final `Config` object.
190    ///
191    /// This method ensures that all required fields (such as credentials) are provided before
192    /// constructing the `Config` instance. If any required field is missing, an error is returned.
193    ///
194    /// # Returns
195    /// - `Ok(Config)`: The successfully built `Config` instance.
196    /// - `Err(error::Error)`: Returns an error if required fields (e.g., credentials) are missing.
197    ///
198    /// # Example
199    /// ```rust
200    /// let config = Config::builder()
201    ///     .with_region("us-west-2")
202    ///     .with_endpoint("https://api.volcengine.com")
203    ///     .with_disable_ssl(false)
204    ///     .with_credentials(credentials::Credentials::new("access_key", "secret_key"))
205    ///     .build();
206    ///
207    /// match config {
208    ///     Ok(cfg) => println!("Configuration built successfully!"),
209    ///     Err(err) => println!("Failed to build configuration: {:?}", err),
210    /// }
211    /// ```
212    pub fn build(self) -> Result<Config, error::Error> {
213        // Ensure that credentials are provided; return an error if missing.
214        if self.credentials.is_none() {
215            return Err(error::Error::ErrUtilConfigBuildConfigNoCredentials);
216        }
217
218        // Construct and return a `Config` instance, using default values where necessary.
219        Ok(Config {
220            region: self.region.unwrap_or_default(), // Defaults to an empty string if region is not set.
221            endpoint: self.endpoint.unwrap_or_default(), // Defaults to an empty string if endpoint is not set.
222            disable_ssl: self.disable_ssl.unwrap_or_default(), // Defaults to `false` if not set.
223            credentials: self.credentials.unwrap(), // Credentials are required and safely unwrapped.
224        })
225    }
226}