Skip to main content

conductor/configuration/
settings.rs

1// Copyright {{.Year}} Conductor OSS
2// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
3
4use std::env;
5use std::time::{Duration, Instant};
6
7/// Main configuration for Conductor client.
8#[derive(Debug, Clone)]
9pub struct Configuration {
10    /// Conductor server API URL (e.g., "<http://localhost:8080/api>").
11    pub server_api_url: String,
12
13    /// UI host URL for viewing executions.
14    pub ui_host: String,
15
16    /// Authentication key (optional).
17    pub auth_key: Option<String>,
18
19    /// Authentication secret (optional).
20    pub auth_secret: Option<String>,
21
22    /// Current authentication token (managed internally).
23    pub auth_token: Option<String>,
24
25    /// Time when the token was last updated.
26    pub token_update_time: Option<Instant>,
27
28    /// Token time-to-live duration (default: 45 minutes).
29    pub auth_token_ttl: Duration,
30
31    /// Whether authentication is disabled (e.g., OSS Conductor without auth).
32    pub auth_disabled: bool,
33
34    /// Request timeout.
35    pub timeout: Duration,
36
37    /// Connection timeout.
38    pub connect_timeout: Duration,
39
40    /// Enable debug logging.
41    pub debug: bool,
42}
43
44impl Default for Configuration {
45    fn default() -> Self {
46        Self::from_env()
47    }
48}
49
50impl Configuration {
51    /// Default token TTL in minutes (45 minutes).
52    const DEFAULT_TOKEN_TTL_MINUTES: u64 = 45;
53
54    /// Create configuration from environment variables.
55    ///
56    /// Environment variables:
57    /// - `CONDUCTOR_SERVER_URL`: Conductor server API URL (default: <http://localhost:8080/api>)
58    /// - `CONDUCTOR_AUTH_KEY`: Authentication key ID for Orkes Conductor
59    /// - `CONDUCTOR_AUTH_SECRET`: Authentication secret for Orkes Conductor
60    /// - `CONDUCTOR_DEBUG`: Enable debug mode (true/false)
61    /// - `CONDUCTOR_TIMEOUT_SECS`: Request timeout in seconds (default: 30)
62    /// - `CONDUCTOR_AUTH_TOKEN_TTL_MINS`: Token TTL in minutes (default: 45)
63    ///
64    /// The SDK automatically handles token refresh when using Orkes Conductor.
65    /// For open-source Conductor without authentication, simply omit the auth variables.
66    #[must_use]
67    pub fn from_env() -> Self {
68        // Load .env file if present
69        let _ = dotenvy::dotenv();
70
71        let server_api_url = env::var("CONDUCTOR_SERVER_URL")
72            .unwrap_or_else(|_| "http://localhost:8080/api".to_owned());
73
74        // Derive UI host from server URL
75        let ui_host =
76            env::var("CONDUCTOR_UI_SERVER_URL").unwrap_or_else(|_| derive_ui_host(&server_api_url));
77
78        let auth_key = env::var("CONDUCTOR_AUTH_KEY").ok();
79        let auth_secret = env::var("CONDUCTOR_AUTH_SECRET").ok();
80
81        let debug =
82            env::var("CONDUCTOR_DEBUG").is_ok_and(|v| v.to_lowercase() == "true" || v == "1");
83
84        let timeout_secs = env::var("CONDUCTOR_TIMEOUT_SECS")
85            .ok()
86            .and_then(|v| v.parse().ok())
87            .unwrap_or(30);
88
89        let token_ttl_mins = env::var("CONDUCTOR_AUTH_TOKEN_TTL_MINS")
90            .ok()
91            .and_then(|v| v.parse().ok())
92            .unwrap_or(Self::DEFAULT_TOKEN_TTL_MINUTES);
93
94        Self {
95            server_api_url,
96            ui_host,
97            auth_key,
98            auth_secret,
99            auth_token: None,
100            token_update_time: None,
101            auth_token_ttl: Duration::from_secs(token_ttl_mins * 60),
102            auth_disabled: false,
103            timeout: Duration::from_secs(timeout_secs),
104            connect_timeout: Duration::from_secs(10),
105            debug,
106        }
107    }
108
109    /// Create a new configuration with custom settings.
110    pub fn new(server_api_url: impl Into<String>) -> Self {
111        let server_api_url = server_api_url.into();
112        let ui_host = derive_ui_host(&server_api_url);
113
114        Self {
115            server_api_url,
116            ui_host,
117            auth_key: None,
118            auth_secret: None,
119            auth_token: None,
120            token_update_time: None,
121            auth_token_ttl: Duration::from_secs(Self::DEFAULT_TOKEN_TTL_MINUTES * 60),
122            auth_disabled: false,
123            timeout: Duration::from_secs(30),
124            connect_timeout: Duration::from_secs(10),
125            debug: false,
126        }
127    }
128
129    /// Set authentication credentials.
130    #[must_use]
131    pub fn with_auth(mut self, key: impl Into<String>, secret: impl Into<String>) -> Self {
132        self.auth_key = Some(key.into());
133        self.auth_secret = Some(secret.into());
134        self
135    }
136
137    /// Set token TTL (time-to-live) duration.
138    #[must_use]
139    pub fn with_token_ttl(mut self, ttl: Duration) -> Self {
140        self.auth_token_ttl = ttl;
141        self
142    }
143
144    /// Set timeout.
145    #[must_use]
146    pub fn with_timeout(mut self, timeout: Duration) -> Self {
147        self.timeout = timeout;
148        self
149    }
150
151    /// Enable debug mode.
152    #[must_use]
153    pub fn with_debug(mut self, debug: bool) -> Self {
154        self.debug = debug;
155        self
156    }
157
158    /// Update the authentication token.
159    pub fn update_token(&mut self, token: String) {
160        self.auth_token = Some(token);
161        self.token_update_time = Some(Instant::now());
162    }
163
164    /// Clear the authentication token (e.g., after auth failure).
165    pub fn clear_token(&mut self) {
166        self.auth_token = None;
167        self.token_update_time = None;
168    }
169
170    /// Disable authentication (e.g., when server doesn't require it).
171    pub fn disable_auth(&mut self) {
172        self.auth_disabled = true;
173        self.auth_key = None;
174        self.auth_secret = None;
175        self.auth_token = None;
176        self.token_update_time = None;
177    }
178
179    /// Check if authentication is configured and not disabled.
180    #[must_use]
181    pub fn has_auth(&self) -> bool {
182        !self.auth_disabled && self.auth_key.is_some() && self.auth_secret.is_some()
183    }
184
185    /// Check if the token needs to be refreshed based on TTL.
186    #[must_use]
187    pub fn token_needs_refresh(&self) -> bool {
188        // No token yet
189        if self.auth_token.is_none() {
190            return true;
191        }
192
193        // Check if token has expired based on TTL
194        if let Some(update_time) = self.token_update_time {
195            let elapsed = update_time.elapsed();
196            return elapsed >= self.auth_token_ttl;
197        }
198
199        // No update time recorded, needs refresh
200        true
201    }
202
203    /// Get the execution URL for a workflow.
204    #[must_use]
205    pub fn execution_url(&self, workflow_id: &str) -> String {
206        format!("{}/execution/{}", self.ui_host, workflow_id)
207    }
208}
209
210/// Derive UI host from server API URL.
211fn derive_ui_host(server_url: &str) -> String {
212    // Remove /api suffix if present
213    let base = server_url.trim_end_matches("/api").trim_end_matches('/');
214
215    // If it's localhost:8080, UI is typically on :5000
216    if base.contains("localhost:8080") || base.contains("127.0.0.1:8080") {
217        base.replace(":8080", ":5000")
218    } else {
219        base.to_owned()
220    }
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    #[test]
228    fn test_default_config() {
229        let config = Configuration::new("http://localhost:8080/api");
230        assert!(config.server_api_url.contains("localhost:8080"));
231        assert!(!config.auth_disabled);
232        assert_eq!(config.auth_token_ttl, Duration::from_secs(45 * 60));
233    }
234
235    #[test]
236    fn test_derive_ui_host() {
237        assert_eq!(
238            derive_ui_host("http://localhost:8080/api"),
239            "http://localhost:5000"
240        );
241        assert_eq!(
242            derive_ui_host("https://conductor.example.com/api"),
243            "https://conductor.example.com"
244        );
245    }
246
247    #[test]
248    fn test_execution_url() {
249        let config = Configuration::new("http://localhost:8080/api");
250        assert_eq!(
251            config.execution_url("abc123"),
252            "http://localhost:5000/execution/abc123"
253        );
254    }
255
256    #[test]
257    fn test_with_auth() {
258        let config =
259            Configuration::new("http://localhost:8080/api").with_auth("key123", "secret456");
260
261        assert!(config.has_auth());
262        assert_eq!(config.auth_key, Some("key123".to_owned()));
263        assert_eq!(config.auth_secret, Some("secret456".to_owned()));
264    }
265
266    #[test]
267    fn test_token_needs_refresh() {
268        let mut config = Configuration::new("http://localhost:8080/api");
269
270        // No token - needs refresh
271        assert!(config.token_needs_refresh());
272
273        // Add token
274        config.update_token("test-token".to_owned());
275
276        // Just updated - doesn't need refresh
277        assert!(!config.token_needs_refresh());
278
279        // Simulate expired token by setting a very short TTL
280        config.auth_token_ttl = Duration::from_millis(1);
281        std::thread::sleep(Duration::from_millis(10));
282
283        // Now needs refresh
284        assert!(config.token_needs_refresh());
285    }
286
287    #[test]
288    fn test_disable_auth() {
289        let mut config = Configuration::new("http://localhost:8080/api").with_auth("key", "secret");
290
291        assert!(config.has_auth());
292
293        config.update_token("test-token".to_owned());
294        assert!(config.auth_token.is_some());
295
296        config.disable_auth();
297
298        assert!(!config.has_auth());
299        assert!(config.auth_disabled);
300        assert!(config.auth_key.is_none());
301        assert!(config.auth_secret.is_none());
302        assert!(config.auth_token.is_none());
303    }
304
305    #[test]
306    fn test_clear_token() {
307        let mut config = Configuration::new("http://localhost:8080/api");
308        config.update_token("test-token".to_owned());
309
310        assert!(config.auth_token.is_some());
311        assert!(config.token_update_time.is_some());
312
313        config.clear_token();
314
315        assert!(config.auth_token.is_none());
316        assert!(config.token_update_time.is_none());
317    }
318
319    #[test]
320    fn test_with_token_ttl() {
321        let config = Configuration::new("http://localhost:8080/api")
322            .with_token_ttl(Duration::from_secs(30 * 60)); // 30 minutes
323
324        assert_eq!(config.auth_token_ttl, Duration::from_secs(30 * 60));
325    }
326}