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
//! Dynamic Configuration with Hot-Reloading
//!
//! Runtime configuration changes with file system monitoring for zero-downtime updates.
//!
//! # Features
//!
//! - File-based configuration watching
//! - Runtime reload without restart
//! - Thread-safe config updates via `Arc< RwLock<> >`
//! - Configuration validation before applying
//! - JSON configuration format
//!
//! # Benefits
//!
//! - Zero-downtime configuration updates
//! - A/B testing different configurations
//! - Dynamic scaling of rate limits
//! - Environment-specific tuning without restart
#[ cfg( feature = "dynamic-config" ) ]
mod private
{
use std::path::{ Path, PathBuf };
use std::sync::Arc;
use std::time::Duration;
use parking_lot::RwLock;
use serde::{ Serialize, Deserialize };
use notify::{ Watcher, RecommendedWatcher, RecursiveMode, Event };
/// Runtime configuration that can be hot-reloaded
#[ derive( Debug, Clone, Serialize, Deserialize, PartialEq ) ]
pub struct RuntimeConfig
{
/// Base URL for API requests (default: <https://api.anthropic.com>)
#[ serde( default = "default_base_url" ) ]
pub base_url : String,
/// API version (default : "2023-06-01")
#[ serde( default = "default_api_version" ) ]
pub api_version : String,
/// Request timeout in milliseconds (default : 300000 = 5 minutes)
#[ serde( default = "default_timeout_ms" ) ]
pub timeout_ms : u64,
/// Enable retry logic (default : true)
#[ serde( default = "default_true" ) ]
pub enable_retry : bool,
/// Maximum retry attempts (default : 3)
#[ serde( default = "default_max_retries" ) ]
pub max_retries : u32,
/// Enable circuit breaker (default : true)
#[ serde( default = "default_true" ) ]
pub enable_circuit_breaker : bool,
/// Circuit breaker failure threshold (default : 5)
#[ serde( default = "default_failure_threshold" ) ]
pub circuit_breaker_threshold : u32,
/// Enable rate limiting (default : false)
#[ serde( default ) ]
pub enable_rate_limiting : bool,
/// Rate limit : requests per second (default : 10)
#[ serde( default = "default_rate_limit" ) ]
pub rate_limit_rps : u32,
}
#[ inline ]
fn default_base_url() -> String
{
"https://api.anthropic.com".to_string()
}
#[ inline ]
fn default_api_version() -> String
{
"2023-06-01".to_string()
}
#[ inline ]
fn default_timeout_ms() -> u64
{
300_000
}
#[ inline ]
fn default_true() -> bool
{
true
}
#[ inline ]
fn default_max_retries() -> u32
{
3
}
#[ inline ]
fn default_failure_threshold() -> u32
{
5
}
#[ inline ]
fn default_rate_limit() -> u32
{
10
}
impl RuntimeConfig
{
/// Create new runtime config with defaults
#[ inline ]
#[ must_use ]
pub fn new() -> Self
{
Self
{
base_url : default_base_url(),
api_version : default_api_version(),
timeout_ms : default_timeout_ms(),
enable_retry : default_true(),
max_retries : default_max_retries(),
enable_circuit_breaker : default_true(),
circuit_breaker_threshold : default_failure_threshold(),
enable_rate_limiting : false,
rate_limit_rps : default_rate_limit(),
}
}
/// Load config from JSON file
///
/// # Errors
///
/// Returns an error if file cannot be read or parsed
#[ inline ]
pub fn from_json_file( path : &Path ) -> Result< Self, Box< dyn std::error::Error > >
{
let contents = std::fs::read_to_string( path )?;
let config : Self = serde_json::from_str( &contents )?;
config.validate()?;
Ok( config )
}
// TOML support can be added by enabling toml dependency if needed
// For now, JSON-only configuration is supported
/// Validate configuration values
///
/// # Errors
///
/// Returns an error if any configuration value is invalid
#[ inline ]
pub fn validate( &self ) -> Result< (), String >
{
if self.base_url.is_empty()
{
return Err( "base_url cannot be empty".to_string() );
}
if self.api_version.is_empty()
{
return Err( "api_version cannot be empty".to_string() );
}
if self.timeout_ms == 0
{
return Err( "timeout_ms must be greater than 0".to_string() );
}
if self.max_retries > 10
{
return Err( "max_retries cannot exceed 10".to_string() );
}
if self.circuit_breaker_threshold == 0
{
return Err( "circuit_breaker_threshold must be greater than 0".to_string() );
}
if self.rate_limit_rps == 0
{
return Err( "rate_limit_rps must be greater than 0".to_string() );
}
Ok( () )
}
/// Get timeout as Duration
#[ inline ]
#[ must_use ]
pub fn timeout( &self ) -> Duration
{
Duration::from_millis( self.timeout_ms )
}
}
impl Default for RuntimeConfig
{
#[ inline ]
fn default() -> Self
{
Self::new()
}
}
/// Configuration watcher for hot-reloading
#[ derive( Debug ) ]
pub struct ConfigWatcher
{
config : Arc< RwLock< RuntimeConfig > >,
config_path : PathBuf,
_watcher : RecommendedWatcher,
}
impl ConfigWatcher
{
/// Create new config watcher
///
/// # Arguments
///
/// * `config_path` - Path to configuration file
/// * `initial_config` - Initial configuration to use before file is loaded
///
/// # Errors
///
/// Returns an error if the watcher cannot be created or the config file cannot be read
#[ inline ]
pub fn new
(
config_path : PathBuf,
initial_config : RuntimeConfig,
) -> Result< Self, Box< dyn std::error::Error > >
{
let config = Arc::new( RwLock::new( initial_config ) );
let config_clone = config.clone();
let path_clone = config_path.clone();
let mut watcher = notify::recommended_watcher( move | res : Result< Event, notify::Error > |
{
match res
{
Ok( event ) =>
{
// Reload on write events
if event.kind.is_modify()
{
// Check if the event is for our config file
if event.paths.iter().any( | p | p == &path_clone )
{
if let Ok( new_config ) = RuntimeConfig::from_json_file( &path_clone )
{
*config_clone.write() = new_config;
}
}
}
}
Err( e ) =>
{
eprintln!( "Watch error : {e:?}" );
}
}
} )?;
// Watch the parent directory (file may not exist yet)
let watch_path = if config_path.exists()
{
config_path.clone()
}
else
{
config_path.parent().ok_or( "Config path has no parent" )?.to_path_buf()
};
watcher.watch( &watch_path, RecursiveMode::NonRecursive )?;
// Load initial config from file if it exists
if config_path.exists()
{
if let Ok( loaded_config ) = RuntimeConfig::from_json_file( &config_path )
{
*config.write() = loaded_config;
}
}
Ok( Self
{
config,
config_path,
_watcher : watcher,
} )
}
/// Get current configuration (read-only)
#[ inline ]
#[ must_use ]
pub fn config( &self ) -> RuntimeConfig
{
self.config.read().clone()
}
/// Get shared config reference for concurrent access
#[ inline ]
#[ must_use ]
pub fn config_ref( &self ) -> Arc< RwLock< RuntimeConfig > >
{
self.config.clone()
}
/// Manually reload configuration from file
///
/// # Errors
///
/// Returns an error if the file cannot be read or parsed
#[ inline ]
pub fn reload( &self ) -> Result< (), Box< dyn std::error::Error > >
{
let new_config = RuntimeConfig::from_json_file( &self.config_path )?;
*self.config.write() = new_config;
Ok( () )
}
/// Update configuration programmatically
///
/// # Errors
///
/// Returns an error if the new configuration is invalid
#[ inline ]
pub fn update( &self, new_config : RuntimeConfig ) -> Result< (), String >
{
new_config.validate()?;
*self.config.write() = new_config;
Ok( () )
}
}
}
#[ cfg( feature = "dynamic-config" ) ]
crate::mod_interface!
{
exposed use
{
RuntimeConfig,
ConfigWatcher,
};
}