gouqi 0.20.0

Rust interface for Jira
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! Configuration management for gouqi Jira client
//!
//! This module provides comprehensive configuration management including:
//! - Loading from files (JSON, YAML, TOML)
//! - Environment variable support
//! - Programmatic configuration
//! - Configuration validation and merging

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::time::Duration;

use crate::{Error, Result};

/// Main configuration structure for the Jira client
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct GouqiConfig {
    /// Timeout configuration
    pub timeout: TimeoutConfig,
    /// Connection pool configuration
    pub connection_pool: ConnectionPoolConfig,
    /// Cache configuration
    pub cache: CacheConfig,
    /// Metrics collection configuration
    pub metrics: MetricsConfig,
    /// Retry policy configuration
    pub retry: RetryConfig,
    /// Rate limiting configuration
    pub rate_limiting: RateLimitingConfig,
    /// Observability configuration
    #[cfg(any(feature = "metrics", feature = "cache"))]
    pub observability: crate::observability::ObservabilityConfig,
}

/// Timeout configuration for various operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimeoutConfig {
    /// Default request timeout
    #[serde(with = "humantime_serde")]
    pub default: Duration,
    /// Connection timeout
    #[serde(with = "humantime_serde")]
    pub connect: Duration,
    /// Read timeout
    #[serde(with = "humantime_serde")]
    pub read: Duration,
}

/// Connection pool configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionPoolConfig {
    /// Maximum connections per host
    pub max_connections_per_host: usize,
    /// Idle timeout for connections
    #[serde(with = "humantime_serde")]
    pub idle_timeout: Duration,
    /// Enable HTTP/2
    pub http2: bool,
    /// Keep-alive timeout
    #[serde(with = "humantime_serde")]
    pub keep_alive_timeout: Duration,
}

/// Cache configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheConfig {
    /// Enable caching
    pub enabled: bool,
    /// Default TTL for cache entries
    #[serde(with = "humantime_serde")]
    pub default_ttl: Duration,
    /// Maximum number of cache entries
    pub max_entries: usize,
    /// Cache strategies per endpoint
    pub strategies: HashMap<String, CacheStrategy>,
}

/// Cache strategy for different endpoints
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheStrategy {
    /// TTL for this endpoint
    #[serde(with = "humantime_serde")]
    pub ttl: Duration,
    /// Whether to cache errors
    pub cache_errors: bool,
    /// Whether to use ETag validation
    pub use_etag: bool,
}

/// Metrics collection configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricsConfig {
    /// Enable metrics collection
    pub enabled: bool,
    /// Metrics collection interval
    #[serde(with = "humantime_serde")]
    pub collection_interval: Duration,
    /// Metrics to collect
    pub collect_request_times: bool,
    pub collect_error_rates: bool,
    pub collect_cache_stats: bool,
    /// Export configuration
    pub export: MetricsExportConfig,
}

/// Metrics export configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricsExportConfig {
    /// Export format (prometheus, json, etc.)
    pub format: String,
    /// Export endpoint
    pub endpoint: Option<String>,
    /// Export interval
    #[serde(with = "humantime_serde")]
    pub interval: Duration,
}

/// Retry policy configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetryConfig {
    /// Maximum number of retry attempts
    pub max_attempts: u32,
    /// Base delay between retries
    #[serde(with = "humantime_serde")]
    pub base_delay: Duration,
    /// Maximum delay between retries
    #[serde(with = "humantime_serde")]
    pub max_delay: Duration,
    /// Backoff multiplier
    pub backoff_multiplier: f64,
    /// HTTP status codes that should be retried
    pub retry_status_codes: Vec<u16>,
    /// Whether to retry on connection errors
    pub retry_on_connection_errors: bool,
}

/// Rate limiting configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitingConfig {
    /// Enable rate limiting
    pub enabled: bool,
    /// Requests per second limit
    pub requests_per_second: f64,
    /// Burst capacity
    pub burst_capacity: u32,
    /// Rate limit per endpoint overrides
    pub endpoint_overrides: HashMap<String, RateLimitOverride>,
}

/// Rate limit override for specific endpoints
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitOverride {
    /// Requests per second for this endpoint
    pub requests_per_second: f64,
    /// Burst capacity for this endpoint
    pub burst_capacity: u32,
}

impl Default for TimeoutConfig {
    fn default() -> Self {
        Self {
            default: Duration::from_secs(30),
            connect: Duration::from_secs(10),
            read: Duration::from_secs(30),
        }
    }
}

impl Default for ConnectionPoolConfig {
    fn default() -> Self {
        Self {
            max_connections_per_host: 10,
            idle_timeout: Duration::from_secs(30),
            http2: true,
            keep_alive_timeout: Duration::from_secs(90),
        }
    }
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            default_ttl: Duration::from_secs(300), // 5 minutes
            max_entries: 1000,
            strategies: HashMap::new(),
        }
    }
}

impl Default for MetricsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            collection_interval: Duration::from_secs(60),
            collect_request_times: true,
            collect_error_rates: true,
            collect_cache_stats: true,
            export: MetricsExportConfig::default(),
        }
    }
}

impl Default for MetricsExportConfig {
    fn default() -> Self {
        Self {
            format: "json".to_string(),
            endpoint: None,
            interval: Duration::from_secs(300), // 5 minutes
        }
    }
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_attempts: 3,
            base_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(30),
            backoff_multiplier: 2.0,
            retry_status_codes: vec![429, 500, 502, 503, 504],
            retry_on_connection_errors: true,
        }
    }
}

impl Default for RateLimitingConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            requests_per_second: 10.0,
            burst_capacity: 20,
            endpoint_overrides: HashMap::new(),
        }
    }
}

impl GouqiConfig {
    /// Load configuration from file
    ///
    /// # Panics
    ///
    /// This function will panic if the file cannot be read or contains invalid configuration
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let config_str = std::fs::read_to_string(&path).map_err(Error::IO)?;
        let config = match path.as_ref().extension().and_then(|ext| ext.to_str()) {
            Some("json") => serde_json::from_str(&config_str).map_err(Error::Serde)?,
            #[cfg(feature = "yaml")]
            Some("yaml") | Some("yml") => {
                serde_yaml::from_str(&config_str).map_err(|e| Error::ConfigError {
                    message: format!("YAML parsing error: {}", e),
                })?
            }
            #[cfg(feature = "toml-support")]
            Some("toml") => toml::from_str(&config_str).map_err(|e| Error::ConfigError {
                message: format!("TOML parsing error: {}", e),
            })?,
            Some(ext) => {
                return Err(Error::ConfigError {
                    message: format!("Unsupported config file format: .{}", ext),
                });
            }
            None => {
                return Err(Error::ConfigError {
                    message: "Config file must have an extension (.json, .yaml, .toml)".to_string(),
                });
            }
        };
        Ok(config)
    }

    /// Save configuration to file
    ///
    /// # Panics
    ///
    /// This function will panic if the file cannot be written or the configuration cannot be serialized
    pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let config_str = match path.as_ref().extension().and_then(|ext| ext.to_str()) {
            Some("json") => serde_json::to_string_pretty(self).map_err(Error::Serde)?,
            #[cfg(feature = "yaml")]
            Some("yaml") | Some("yml") => {
                serde_yaml::to_string(self).map_err(|e| Error::ConfigError {
                    message: format!("YAML serialization error: {}", e),
                })?
            }
            #[cfg(feature = "toml-support")]
            Some("toml") => toml::to_string_pretty(self).map_err(|e| Error::ConfigError {
                message: format!("TOML serialization error: {}", e),
            })?,
            Some(ext) => {
                return Err(Error::ConfigError {
                    message: format!("Unsupported config file format: .{}", ext),
                });
            }
            None => {
                return Err(Error::ConfigError {
                    message: "Config file must have an extension (.json, .yaml, .toml)".to_string(),
                });
            }
        };

        std::fs::write(path, config_str).map_err(Error::IO)?;
        Ok(())
    }

    /// Merge with another configuration (other takes precedence)
    pub fn merge(self, other: Self) -> Self {
        Self {
            timeout: other.timeout,
            connection_pool: other.connection_pool,
            cache: other.cache,
            metrics: other.metrics,
            retry: other.retry,
            rate_limiting: other.rate_limiting,
            #[cfg(any(feature = "metrics", feature = "cache"))]
            observability: other.observability,
        }
    }

    /// Validate the configuration
    pub fn validate(&self) -> Result<()> {
        // Validate timeout settings
        if self.timeout.default.as_millis() == 0 {
            return Err(Error::ConfigError {
                message: "Default timeout must be greater than 0".to_string(),
            });
        }

        if self.timeout.connect > self.timeout.default {
            return Err(Error::ConfigError {
                message: "Connect timeout cannot be greater than default timeout".to_string(),
            });
        }

        if self.timeout.read > self.timeout.default {
            return Err(Error::ConfigError {
                message: "Read timeout cannot be greater than default timeout".to_string(),
            });
        }

        // Validate connection pool settings
        if self.connection_pool.max_connections_per_host == 0 {
            return Err(Error::ConfigError {
                message: "Connection pool size must be greater than 0".to_string(),
            });
        }

        // Validate retry settings
        if self.retry.max_attempts == 0 {
            return Err(Error::ConfigError {
                message: "Max retry attempts must be greater than 0".to_string(),
            });
        }

        if self.retry.base_delay.as_millis() == 0 {
            return Err(Error::ConfigError {
                message: "Base retry delay must be greater than 0".to_string(),
            });
        }

        if self.retry.max_delay < self.retry.base_delay {
            return Err(Error::ConfigError {
                message: "Max retry delay cannot be less than base delay".to_string(),
            });
        }

        if self.retry.backoff_multiplier <= 0.0 {
            return Err(Error::ConfigError {
                message: "Backoff multiplier must be greater than 0".to_string(),
            });
        }

        // Validate cache settings
        if self.cache.enabled && self.cache.max_entries == 0 {
            return Err(Error::ConfigError {
                message: "Cache max entries must be greater than 0 when caching is enabled"
                    .to_string(),
            });
        }

        if self.cache.enabled && self.cache.default_ttl.as_millis() == 0 {
            return Err(Error::ConfigError {
                message: "Cache default TTL must be greater than 0 when caching is enabled"
                    .to_string(),
            });
        }

        // Validate rate limiting settings
        if self.rate_limiting.enabled {
            if self.rate_limiting.requests_per_second <= 0.0 {
                return Err(Error::ConfigError {
                    message: "Rate limit requests per second must be greater than 0".to_string(),
                });
            }

            if self.rate_limiting.burst_capacity == 0 {
                return Err(Error::ConfigError {
                    message: "Rate limit burst capacity must be greater than 0".to_string(),
                });
            }
        }

        Ok(())
    }

    /// Create a configuration optimized for high-throughput scenarios
    pub fn high_throughput() -> Self {
        Self {
            timeout: TimeoutConfig {
                default: Duration::from_secs(60),
                connect: Duration::from_secs(5),
                read: Duration::from_secs(60),
            },
            connection_pool: ConnectionPoolConfig {
                max_connections_per_host: 50,
                idle_timeout: Duration::from_secs(60),
                http2: true,
                keep_alive_timeout: Duration::from_secs(120),
            },
            cache: CacheConfig {
                enabled: true,
                default_ttl: Duration::from_secs(120),
                max_entries: 5000,
                strategies: HashMap::new(),
            },
            retry: RetryConfig {
                max_attempts: 5,
                base_delay: Duration::from_millis(50),
                max_delay: Duration::from_secs(10),
                backoff_multiplier: 1.5,
                retry_status_codes: vec![429, 500, 502, 503, 504],
                retry_on_connection_errors: true,
            },
            rate_limiting: RateLimitingConfig {
                enabled: true,
                requests_per_second: 50.0,
                burst_capacity: 100,
                endpoint_overrides: HashMap::new(),
            },
            ..Default::default()
        }
    }

    /// Create a configuration optimized for low-resource environments
    pub fn low_resource() -> Self {
        Self {
            timeout: TimeoutConfig {
                default: Duration::from_secs(15),
                connect: Duration::from_secs(5),
                read: Duration::from_secs(15),
            },
            connection_pool: ConnectionPoolConfig {
                max_connections_per_host: 2,
                idle_timeout: Duration::from_secs(15),
                http2: false,
                keep_alive_timeout: Duration::from_secs(30),
            },
            cache: CacheConfig {
                enabled: true,
                default_ttl: Duration::from_secs(600),
                max_entries: 100,
                strategies: HashMap::new(),
            },
            retry: RetryConfig {
                max_attempts: 2,
                base_delay: Duration::from_millis(500),
                max_delay: Duration::from_secs(5),
                backoff_multiplier: 2.0,
                retry_status_codes: vec![429, 500, 502, 503, 504],
                retry_on_connection_errors: true,
            },
            rate_limiting: RateLimitingConfig {
                enabled: true,
                requests_per_second: 2.0,
                burst_capacity: 5,
                endpoint_overrides: HashMap::new(),
            },
            metrics: MetricsConfig {
                enabled: false,
                ..Default::default()
            },
            #[cfg(any(feature = "metrics", feature = "cache"))]
            observability: crate::observability::ObservabilityConfig {
                enable_metrics: false,
                enable_caching: false,
                ..Default::default()
            },
        }
    }
}