limiteron 0.2.4

Unified flow control framework for Rust
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
492
493
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! 配置加载器 - 使用 serde 从文件加载配置

use crate::LimiteronError;
use crate::config::FlowControlConfig;
use std::fs;
use std::path::Path;

/// 配置加载器
pub struct ConfigLoader;

impl ConfigLoader {
    /// 从配置文件加载配置
    ///
    /// 支持 YAML、TOML、JSON 格式,根据文件扩展名自动检测
    pub fn load_from_file<P: AsRef<Path>>(path: P) -> Result<FlowControlConfig, LimiteronError> {
        let path = path.as_ref();

        if !path.exists() {
            return Err(LimiteronError::ConfigError(format!(
                "Config file not found: {}",
                path.display()
            )));
        }

        let content = fs::read_to_string(path).map_err(|e| {
            LimiteronError::ConfigError(format!("Failed to read config file: {}", e))
        })?;

        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_lowercase();

        let config: FlowControlConfig = match ext.as_str() {
            "yaml" | "yml" => serde_yaml::from_str(&content).map_err(|e| {
                LimiteronError::ConfigError(format!("Failed to parse YAML config: {}", e))
            })?,
            "toml" => toml::from_str(&content).map_err(|e| {
                LimiteronError::ConfigError(format!("Failed to parse TOML config: {}", e))
            })?,
            "json" => serde_json::from_str(&content).map_err(|e| {
                LimiteronError::ConfigError(format!("Failed to parse JSON config: {}", e))
            })?,
            _ => {
                return Err(LimiteronError::ConfigError(format!(
                    "Unsupported config file format: {}. Supported: yaml, yml, toml, json",
                    ext
                )));
            }
        };

        Ok(config)
    }

    /// 从配置文件加载配置并应用环境变量覆盖
    ///
    /// 先调用 `load_from_file` 加载基础配置,然后检查以下环境变量并覆盖对应字段:
    /// - `LIMITERON_GLOBAL_STORAGE`: 覆盖 `global.storage`(memory/postgresql/redis)
    /// - `LIMITERON_GLOBAL_CACHE`: 覆盖 `global.cache`
    /// - `LIMITERON_GLOBAL_METRICS`: 覆盖 `global.metrics`
    ///
    /// 环境变量值为空或未设置时不覆盖。无效值会返回 ConfigError。
    pub fn load_from_file_with_env<P: AsRef<Path>>(
        path: P,
    ) -> Result<FlowControlConfig, LimiteronError> {
        let mut config = Self::load_from_file(path)?;

        if let Ok(storage_str) = std::env::var("LIMITERON_GLOBAL_STORAGE") {
            if !storage_str.trim().is_empty() {
                let storage_type = crate::config::StorageType::parse(&storage_str)
                    .ok_or_else(|| {
                        LimiteronError::ConfigError(format!(
                            "Invalid LIMITERON_GLOBAL_STORAGE value: {}. Valid: memory, postgresql, redis",
                            storage_str
                        ))
                    })?;
                config.global.storage = storage_type;
            }
        }

        if let Ok(cache_str) = std::env::var("LIMITERON_GLOBAL_CACHE") {
            if !cache_str.trim().is_empty() {
                let cache_backend = crate::config::CacheBackend::parse(cache_str.trim())
                    .ok_or_else(|| {
                        LimiteronError::ConfigError(format!(
                            "Invalid LIMITERON_GLOBAL_CACHE value: {}. Valid: memory, redis, none",
                            cache_str
                        ))
                    })?;
                config.global.cache = cache_backend;
            }
        }

        if let Ok(metrics_str) = std::env::var("LIMITERON_GLOBAL_METRICS") {
            if !metrics_str.trim().is_empty() {
                let metrics_backend =
                    crate::config::MetricsBackend::parse(metrics_str.trim()).ok_or_else(|| {
                        LimiteronError::ConfigError(format!(
                            "Invalid LIMITERON_GLOBAL_METRICS value: {}. Valid: prometheus, statsd, none",
                            metrics_str
                        ))
                    })?;
                config.global.metrics = metrics_backend;
            }
        }

        Ok(config)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    fn valid_yaml() -> String {
        r#"
version: "0.1.0"
global:
  storage: memory
  cache: memory
  metrics: none
rules:
  - id: "rule1"
    name: "Test"
    priority: 100
    matchers:
      - type: User
        user_ids: ["u1"]
    limiters:
      - type: TokenBucket
        capacity: 100
        refill_rate: 10
    action:
      on_exceed: degrade
"#
        .into()
    }

    #[test]
    fn test_load_yaml() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(valid_yaml().as_bytes()).unwrap();
        let path = file.path().with_extension("yaml");
        std::fs::copy(file.path(), &path).unwrap();
        let result = ConfigLoader::load_from_file(&path);
        std::fs::remove_file(&path).ok();
        assert!(result.is_ok());
    }

    #[test]
    fn test_load_toml() {
        let toml = r#"
version = "0.1.0"
[global]
storage = "memory"
cache = "memory"
metrics = "none"

[[rules]]
id = "rule1"
name = "Test"
priority = 100

[[rules.matchers]]
type = "User"
user_ids = ["u1"]

[[rules.limiters]]
type = "TokenBucket"
capacity = 100
refill_rate = 10

[rules.action]
on_exceed = "degrade"
"#;
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(toml.as_bytes()).unwrap();
        let path = file.path().with_extension("toml");
        std::fs::copy(file.path(), &path).unwrap();
        let result = ConfigLoader::load_from_file(&path);
        std::fs::remove_file(&path).ok();
        assert!(result.is_ok());
    }

    #[test]
    fn test_load_json() {
        let json = r#"{
  "version": "0.1.0",
  "global": {
    "storage": "memory",
    "cache": "memory",
    "metrics": "none"
  },
  "rules": [
    {
      "id": "rule1",
      "name": "Test",
      "priority": 100,
      "matchers": [{"type": "User", "user_ids": ["u1"]}],
      "limiters": [{"type": "TokenBucket", "capacity": 100, "refill_rate": 10}],
      "action": {"on_exceed": "degrade"}
    }
  ]
}"#;
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(json.as_bytes()).unwrap();
        let path = file.path().with_extension("json");
        std::fs::copy(file.path(), &path).unwrap();
        let result = ConfigLoader::load_from_file(&path);
        std::fs::remove_file(&path).ok();
        assert!(result.is_ok());
    }

    #[test]
    fn test_load_file_not_found() {
        let result = ConfigLoader::load_from_file("/tmp/limiteron_nonexistent_config.yaml");
        assert!(result.is_err());
        match result {
            Err(LimiteronError::ConfigError(msg)) => assert!(msg.contains("not found")),
            _ => panic!("expected ConfigError"),
        }
    }

    #[test]
    fn test_load_invalid_yaml() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(b"invalid: yaml: content: :").unwrap();
        let path = file.path().with_extension("yaml");
        std::fs::copy(file.path(), &path).unwrap();
        let result = ConfigLoader::load_from_file(&path);
        std::fs::remove_file(&path).ok();
        assert!(result.is_err());
    }

    #[test]
    fn test_load_unsupported_format() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(b"content").unwrap();
        let path = file.path().with_extension("txt");
        std::fs::copy(file.path(), &path).unwrap();
        let result = ConfigLoader::load_from_file(&path);
        std::fs::remove_file(&path).ok();
        assert!(result.is_err());
        match result {
            Err(LimiteronError::ConfigError(msg)) => assert!(msg.contains("Unsupported")),
            _ => panic!("expected ConfigError"),
        }
    }

    #[test]
    fn test_load_invalid_toml() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(b"this is = = invalid toml [[[").unwrap();
        let path = file.path().with_extension("toml");
        std::fs::copy(file.path(), &path).unwrap();
        let result = ConfigLoader::load_from_file(&path);
        std::fs::remove_file(&path).ok();
        assert!(result.is_err());
        match result {
            Err(LimiteronError::ConfigError(msg)) => assert!(msg.contains("TOML")),
            _ => panic!("expected ConfigError for invalid TOML"),
        }
    }

    #[test]
    fn test_load_invalid_json() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(b"{ this is not valid json }").unwrap();
        let path = file.path().with_extension("json");
        std::fs::copy(file.path(), &path).unwrap();
        let result = ConfigLoader::load_from_file(&path);
        std::fs::remove_file(&path).ok();
        assert!(result.is_err());
        match result {
            Err(LimiteronError::ConfigError(msg)) => assert!(msg.contains("JSON")),
            _ => panic!("expected ConfigError for invalid JSON"),
        }
    }

    #[test]
    fn test_load_no_extension() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(b"content").unwrap();
        let path = file.path().with_extension("");
        std::fs::copy(file.path(), &path).unwrap();
        let result = ConfigLoader::load_from_file(&path);
        std::fs::remove_file(&path).ok();
        assert!(result.is_err());
        match result {
            Err(LimiteronError::ConfigError(msg)) => assert!(msg.contains("Unsupported")),
            _ => panic!("expected ConfigError for no extension"),
        }
    }

    #[test]
    fn test_load_yaml_with_yml_extension() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(valid_yaml().as_bytes()).unwrap();
        let path = file.path().with_extension("yml");
        std::fs::copy(file.path(), &path).unwrap();
        let result = ConfigLoader::load_from_file(&path);
        std::fs::remove_file(&path).ok();
        assert!(result.is_ok());
    }

    // 覆盖 line 30:path 存在但 read_to_string 失败(如目录)
    #[test]
    fn test_load_directory_as_file() {
        let dir = tempfile::tempdir().unwrap();
        let result = ConfigLoader::load_from_file(dir.path());
        assert!(result.is_err());
        match result {
            Err(LimiteronError::ConfigError(msg)) => {
                assert!(msg.contains("Failed to read"));
            }
            _ => panic!("expected ConfigError for directory read failure"),
        }
    }

    // ===== load_from_file_with_env 测试 =====
    // 注意:环境变量是进程级全局状态,并行测试会互相污染。
    // 使用 mutex 序列化所有 env 相关测试,确保它们不会同时运行。

    use std::sync::{Mutex, OnceLock};

    fn env_test_lock() -> &'static Mutex<()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
    }

    fn write_temp_config(content: &str, ext: &str) -> std::path::PathBuf {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(content.as_bytes()).unwrap();
        let path = file.path().with_extension(ext);
        std::fs::copy(file.path(), &path).unwrap();
        path
    }

    #[test]
    fn test_load_from_file_with_env_no_override() {
        let _guard = env_test_lock().lock().unwrap();
        let path = write_temp_config(&valid_yaml(), "yaml");
        // 确保环境变量未设置
        unsafe { std::env::remove_var("LIMITERON_GLOBAL_STORAGE") };
        unsafe { std::env::remove_var("LIMITERON_GLOBAL_CACHE") };
        unsafe { std::env::remove_var("LIMITERON_GLOBAL_METRICS") };

        let result = ConfigLoader::load_from_file_with_env(&path);
        std::fs::remove_file(&path).ok();
        assert!(result.is_ok());
        let config = result.unwrap();
        // 默认值应保持不变(valid_yaml 中 storage=memory)
        assert_eq!(
            config.global.storage,
            crate::config::types::StorageType::Memory
        );
    }

    #[test]
    fn test_load_from_file_with_env_storage_override() {
        let _guard = env_test_lock().lock().unwrap();
        let path = write_temp_config(&valid_yaml(), "yaml");
        unsafe { std::env::set_var("LIMITERON_GLOBAL_STORAGE", "redis") };

        let result = ConfigLoader::load_from_file_with_env(&path);
        unsafe { std::env::remove_var("LIMITERON_GLOBAL_STORAGE") };
        std::fs::remove_file(&path).ok();

        assert!(result.is_ok());
        let config = result.unwrap();
        assert_eq!(
            config.global.storage,
            crate::config::types::StorageType::Redis
        );
    }

    #[test]
    fn test_load_from_file_with_env_invalid_storage() {
        let _guard = env_test_lock().lock().unwrap();
        let path = write_temp_config(&valid_yaml(), "yaml");
        unsafe { std::env::set_var("LIMITERON_GLOBAL_STORAGE", "invalid_storage") };

        let result = ConfigLoader::load_from_file_with_env(&path);
        unsafe { std::env::remove_var("LIMITERON_GLOBAL_STORAGE") };
        std::fs::remove_file(&path).ok();

        assert!(result.is_err());
        match result {
            Err(LimiteronError::ConfigError(msg)) => {
                assert!(msg.contains("Invalid LIMITERON_GLOBAL_STORAGE"));
            }
            _ => panic!("expected ConfigError for invalid storage env"),
        }
    }

    #[test]
    fn test_load_from_file_with_env_empty_value_no_override() {
        let _guard = env_test_lock().lock().unwrap();
        let path = write_temp_config(&valid_yaml(), "yaml");
        unsafe { std::env::set_var("LIMITERON_GLOBAL_STORAGE", "") };

        let result = ConfigLoader::load_from_file_with_env(&path);
        unsafe { std::env::remove_var("LIMITERON_GLOBAL_STORAGE") };
        std::fs::remove_file(&path).ok();

        assert!(result.is_ok());
        let config = result.unwrap();
        // 空值不应覆盖,保持原值 memory
        assert_eq!(
            config.global.storage,
            crate::config::types::StorageType::Memory
        );
    }

    #[test]
    fn test_load_from_file_with_env_cache_override() {
        let _guard = env_test_lock().lock().unwrap();
        let path = write_temp_config(&valid_yaml(), "yaml");
        unsafe { std::env::set_var("LIMITERON_GLOBAL_CACHE", "redis") };

        let result = ConfigLoader::load_from_file_with_env(&path);
        unsafe { std::env::remove_var("LIMITERON_GLOBAL_CACHE") };
        std::fs::remove_file(&path).ok();

        assert!(result.is_ok());
        let config = result.unwrap();
        assert_eq!(
            config.global.cache,
            crate::config::types::CacheBackend::Redis
        );
    }

    #[test]
    fn test_load_from_file_with_env_metrics_override() {
        let _guard = env_test_lock().lock().unwrap();
        let path = write_temp_config(&valid_yaml(), "yaml");
        unsafe { std::env::set_var("LIMITERON_GLOBAL_METRICS", "statsd") };

        let result = ConfigLoader::load_from_file_with_env(&path);
        unsafe { std::env::remove_var("LIMITERON_GLOBAL_METRICS") };
        std::fs::remove_file(&path).ok();

        assert!(result.is_ok());
        let config = result.unwrap();
        assert_eq!(
            config.global.metrics,
            crate::config::types::MetricsBackend::Statsd
        );
    }

    #[test]
    fn test_load_from_file_with_env_invalid_cache() {
        let _guard = env_test_lock().lock().unwrap();
        let path = write_temp_config(&valid_yaml(), "yaml");
        unsafe { std::env::set_var("LIMITERON_GLOBAL_CACHE", "invalid_cache") };

        let result = ConfigLoader::load_from_file_with_env(&path);
        unsafe { std::env::remove_var("LIMITERON_GLOBAL_CACHE") };
        std::fs::remove_file(&path).ok();

        assert!(result.is_err());
        match result {
            Err(LimiteronError::ConfigError(msg)) => {
                assert!(msg.contains("Invalid LIMITERON_GLOBAL_CACHE"));
            }
            _ => panic!("expected ConfigError for invalid cache env"),
        }
    }

    #[test]
    fn test_load_from_file_with_env_invalid_metrics() {
        let _guard = env_test_lock().lock().unwrap();
        let path = write_temp_config(&valid_yaml(), "yaml");
        unsafe { std::env::set_var("LIMITERON_GLOBAL_METRICS", "invalid_metrics") };

        let result = ConfigLoader::load_from_file_with_env(&path);
        unsafe { std::env::remove_var("LIMITERON_GLOBAL_METRICS") };
        std::fs::remove_file(&path).ok();

        assert!(result.is_err());
        match result {
            Err(LimiteronError::ConfigError(msg)) => {
                assert!(msg.contains("Invalid LIMITERON_GLOBAL_METRICS"));
            }
            _ => panic!("expected ConfigError for invalid metrics env"),
        }
    }
}