markdown-translator 0.1.1

A translation library with DeepLX API integration, rate limiting, and smart text chunking
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
//! 简化的翻译配置管理模块
//!
//! 这个模块提供了一个精简的配置管理系统,专注于核心配置功能,
//! 使用函数式编程风格和建造者模式。
//!
//! ## 设计原则
//!
//! - **简单优先**: 只保留最核心的配置选项
//! - **函数式**: 使用不可变配置和建造者模式
//! - **易于使用**: 提供合理的默认值和链式配置API
//! - **类型安全**: 编译时检查配置的有效性

use serde::{Deserialize, Serialize};
use std::time::Duration;

// ============================================================================
// 核心配置结构
// ============================================================================

/// 简化的翻译配置
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SimpleTranslationConfig {
    /// 是否启用翻译
    pub enabled: bool,
    /// 目标语言
    pub target_lang: String,
    /// 源语言(默认"auto"自动检测)
    pub source_lang: String,
    /// API地址
    pub api_url: String,
    /// 请求频率限制(每秒)
    pub requests_per_second: f64,
    /// 最大文本长度
    pub max_text_length: usize,
    /// 是否启用缓存
    pub cache_enabled: bool,
    /// 缓存TTL(秒)
    pub cache_ttl_seconds: u64,
}

impl Default for SimpleTranslationConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            target_lang: "zh".to_string(),
            source_lang: "auto".to_string(),
            api_url: "http://localhost:1188/translate".to_string(),
            requests_per_second: 1.0,
            max_text_length: 3000,
            cache_enabled: true,
            cache_ttl_seconds: 3600,
        }
    }
}

impl SimpleTranslationConfig {
    /// 创建配置构建器
    pub fn builder() -> ConfigBuilder {
        ConfigBuilder::new()
    }

    /// 从环境变量创建配置
    pub fn from_env() -> Self {
        let mut config = Self::default();
        
        if let Ok(enabled) = std::env::var("TRANSLATION_ENABLED") {
            config.enabled = enabled.parse().unwrap_or(true);
        }
        
        if let Ok(target_lang) = std::env::var("TRANSLATION_TARGET_LANG") {
            config.target_lang = target_lang;
        }
        
        if let Ok(source_lang) = std::env::var("TRANSLATION_SOURCE_LANG") {
            config.source_lang = source_lang;
        }
        
        if let Ok(api_url) = std::env::var("TRANSLATION_API_URL") {
            config.api_url = api_url;
        }
        
        if let Ok(rate) = std::env::var("TRANSLATION_REQUESTS_PER_SECOND") {
            config.requests_per_second = rate.parse().unwrap_or(1.0);
        }
        
        if let Ok(max_len) = std::env::var("TRANSLATION_MAX_TEXT_LENGTH") {
            config.max_text_length = max_len.parse().unwrap_or(3000);
        }
        
        if let Ok(cache_enabled) = std::env::var("TRANSLATION_CACHE_ENABLED") {
            config.cache_enabled = cache_enabled.parse().unwrap_or(true);
        }
        
        if let Ok(cache_ttl) = std::env::var("TRANSLATION_CACHE_TTL_SECONDS") {
            config.cache_ttl_seconds = cache_ttl.parse().unwrap_or(3600);
        }
        
        config
    }

    /// 快速创建配置
    pub fn quick(target_lang: &str, api_url: Option<&str>) -> Self {
        Self {
            target_lang: target_lang.to_string(),
            api_url: api_url.unwrap_or("http://localhost:1188/translate").to_string(),
            ..Default::default()
        }
    }

    /// 验证配置有效性
    pub fn validate(&self) -> Result<(), String> {
        if self.target_lang.is_empty() {
            return Err("Target language cannot be empty".to_string());
        }
        
        if self.api_url.is_empty() {
            return Err("API URL cannot be empty".to_string());
        }
        
        if self.requests_per_second <= 0.0 {
            return Err("Requests per second must be positive".to_string());
        }
        
        if self.max_text_length == 0 {
            return Err("Max text length must be positive".to_string());
        }
        
        Ok(())
    }

    /// 获取请求间隔时间
    pub fn request_interval(&self) -> Duration {
        Duration::from_secs_f64(1.0 / self.requests_per_second)
    }

    /// 获取缓存TTL时长
    pub fn cache_ttl(&self) -> Duration {
        Duration::from_secs(self.cache_ttl_seconds)
    }
}

// ============================================================================
// 配置构建器
// ============================================================================

/// 配置构建器,提供链式API
#[derive(Debug)]
pub struct ConfigBuilder {
    config: SimpleTranslationConfig,
}

impl ConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: SimpleTranslationConfig::default(),
        }
    }

    /// 设置是否启用翻译
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.config.enabled = enabled;
        self
    }

    /// 设置目标语言
    pub fn target_lang<S: Into<String>>(mut self, lang: S) -> Self {
        self.config.target_lang = lang.into();
        self
    }

    /// 设置源语言
    pub fn source_lang<S: Into<String>>(mut self, lang: S) -> Self {
        self.config.source_lang = lang.into();
        self
    }

    /// 设置API地址
    pub fn api_url<S: Into<String>>(mut self, url: S) -> Self {
        self.config.api_url = url.into();
        self
    }

    /// 设置请求频率
    pub fn requests_per_second(mut self, rate: f64) -> Self {
        self.config.requests_per_second = rate;
        self
    }

    /// 设置最大文本长度
    pub fn max_text_length(mut self, length: usize) -> Self {
        self.config.max_text_length = length;
        self
    }

    /// 设置缓存启用状态
    pub fn cache_enabled(mut self, enabled: bool) -> Self {
        self.config.cache_enabled = enabled;
        self
    }

    /// 设置缓存TTL
    pub fn cache_ttl_seconds(mut self, seconds: u64) -> Self {
        self.config.cache_ttl_seconds = seconds;
        self
    }

    /// 构建配置
    pub fn build(self) -> Result<SimpleTranslationConfig, String> {
        self.config.validate()?;
        Ok(self.config)
    }

    /// 构建配置(不验证)
    pub fn build_unchecked(self) -> SimpleTranslationConfig {
        self.config
    }
}

impl Default for ConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// 配置管理器
// ============================================================================

/// 简化的配置管理器
pub struct SimpleConfigManager {
    config: SimpleTranslationConfig,
}

impl SimpleConfigManager {
    /// 从默认配置创建
    pub fn new() -> Self {
        Self {
            config: SimpleTranslationConfig::default(),
        }
    }

    /// 从配置创建
    pub fn with_config(config: SimpleTranslationConfig) -> Self {
        Self { config }
    }

    /// 从环境变量创建
    pub fn from_env() -> Self {
        Self {
            config: SimpleTranslationConfig::from_env(),
        }
    }

    /// 获取配置的引用
    pub fn config(&self) -> &SimpleTranslationConfig {
        &self.config
    }

    /// 获取配置的克隆
    pub fn config_cloned(&self) -> SimpleTranslationConfig {
        self.config.clone()
    }

    /// 更新配置
    pub fn update_config(&mut self, config: SimpleTranslationConfig) {
        self.config = config;
    }

    /// 使用配置构建器更新
    pub fn update_with_builder<F>(&mut self, f: F) -> Result<(), String>
    where
        F: FnOnce(ConfigBuilder) -> ConfigBuilder,
    {
        let builder = ConfigBuilder {
            config: self.config.clone(),
        };
        let new_config = f(builder).build()?;
        self.config = new_config;
        Ok(())
    }

    /// 验证当前配置
    pub fn validate(&self) -> Result<(), String> {
        self.config.validate()
    }
}

impl Default for SimpleConfigManager {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// 便利函数
// ============================================================================

/// 创建快速配置
pub fn quick_config(target_lang: &str, api_url: Option<&str>) -> SimpleTranslationConfig {
    SimpleTranslationConfig::quick(target_lang, api_url)
}

/// 创建配置构建器
pub fn config_builder() -> ConfigBuilder {
    ConfigBuilder::new()
}

/// 从环境变量加载配置
pub fn load_config_from_env() -> SimpleTranslationConfig {
    SimpleTranslationConfig::from_env()
}

/// 验证配置
pub fn validate_config(config: &SimpleTranslationConfig) -> Result<(), String> {
    config.validate()
}

// ============================================================================
// 预设配置
// ============================================================================

/// 预设配置模块
pub mod presets {
    use super::*;

    /// 开发环境配置
    pub fn development() -> SimpleTranslationConfig {
        SimpleTranslationConfig {
            enabled: true,
            target_lang: "zh".to_string(),
            source_lang: "auto".to_string(),
            api_url: "http://localhost:1188/translate".to_string(),
            requests_per_second: 2.0,
            max_text_length: 1000,
            cache_enabled: true,
            cache_ttl_seconds: 1800, // 30分钟
        }
    }

    /// 生产环境配置
    pub fn production() -> SimpleTranslationConfig {
        SimpleTranslationConfig {
            enabled: true,
            target_lang: "zh".to_string(),
            source_lang: "auto".to_string(),
            api_url: "http://localhost:1188/translate".to_string(),
            requests_per_second: 1.0,
            max_text_length: 3000,
            cache_enabled: true,
            cache_ttl_seconds: 3600, // 1小时
        }
    }

    /// 测试环境配置
    pub fn testing() -> SimpleTranslationConfig {
        SimpleTranslationConfig {
            enabled: false, // 测试时默认禁用
            target_lang: "zh".to_string(),
            source_lang: "auto".to_string(),
            api_url: "http://localhost:1188/translate".to_string(),
            requests_per_second: 10.0, // 测试时允许高频率
            max_text_length: 500,
            cache_enabled: false, // 测试时禁用缓存
            cache_ttl_seconds: 300, // 5分钟
        }
    }

    /// 高性能配置
    pub fn high_performance() -> SimpleTranslationConfig {
        SimpleTranslationConfig {
            enabled: true,
            target_lang: "zh".to_string(),
            source_lang: "auto".to_string(),
            api_url: "http://localhost:1188/translate".to_string(),
            requests_per_second: 5.0,
            max_text_length: 5000,
            cache_enabled: true,
            cache_ttl_seconds: 7200, // 2小时
        }
    }
}

// ============================================================================
// 测试
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let config = SimpleTranslationConfig::default();
        assert!(config.enabled);
        assert_eq!(config.target_lang, "zh");
        assert_eq!(config.source_lang, "auto");
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_builder() {
        let config = ConfigBuilder::new()
            .target_lang("en")
            .api_url("http://example.com/translate")
            .requests_per_second(2.0)
            .build()
            .unwrap();

        assert_eq!(config.target_lang, "en");
        assert_eq!(config.api_url, "http://example.com/translate");
        assert_eq!(config.requests_per_second, 2.0);
    }

    #[test]
    fn test_quick_config() {
        let config = SimpleTranslationConfig::quick("ja", Some("http://api.example.com"));
        assert_eq!(config.target_lang, "ja");
        assert_eq!(config.api_url, "http://api.example.com");
    }

    #[test]
    fn test_config_validation() {
        let mut config = SimpleTranslationConfig::default();
        assert!(config.validate().is_ok());

        config.target_lang = "".to_string();
        assert!(config.validate().is_err());

        config.target_lang = "zh".to_string();
        config.requests_per_second = -1.0;
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_config_manager() {
        let mut manager = SimpleConfigManager::new();
        assert!(manager.validate().is_ok());

        let result = manager.update_with_builder(|builder| {
            builder.target_lang("ko").requests_per_second(3.0)
        });
        assert!(result.is_ok());
        assert_eq!(manager.config().target_lang, "ko");
        assert_eq!(manager.config().requests_per_second, 3.0);
    }

    #[test]
    fn test_presets() {
        let dev_config = presets::development();
        assert!(dev_config.enabled);
        assert_eq!(dev_config.requests_per_second, 2.0);

        let prod_config = presets::production();
        assert_eq!(prod_config.max_text_length, 3000);

        let test_config = presets::testing();
        assert!(!test_config.enabled);
        assert!(!test_config.cache_enabled);
    }

    #[test]
    fn test_convenience_functions() {
        let config = quick_config("fr", Some("http://api.example.com"));
        assert_eq!(config.target_lang, "fr");

        let builder = config_builder().target_lang("de");
        let config = builder.build().unwrap();
        assert_eq!(config.target_lang, "de");
    }

    #[test]
    fn test_duration_helpers() {
        let config = SimpleTranslationConfig::default();
        let interval = config.request_interval();
        assert_eq!(interval, Duration::from_secs(1));

        let ttl = config.cache_ttl();
        assert_eq!(ttl, Duration::from_secs(3600));
    }
}