zenith-foundation 0.1.0

Zenith 核心基础设施:统一错误类型、FrameToken 所有权令牌、FramePool、分层资源账本、恒定时间比较
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! Zenith 配置系统
//!
//! 基于 TOML 的统一配置管理,支持:
//! - 从文件加载配置
//! - 序列化/反序列化
//! - 运行时热更新
//! - 配置校验

use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;
use std::str::FromStr;
use thiserror::Error;

/// 配置加载与校验过程中可能发生的错误。
#[derive(Debug, Error)]
pub enum ConfigError {
    /// 读取配置文件时的 I/O 错误。
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// TOML 反序列化错误。
    #[error("TOML parse error: {0}")]
    Toml(#[from] toml::de::Error),

    /// TOML 序列化错误。
    #[error("TOML serialize error: {0}")]
    Serialize(#[from] toml::ser::Error),

    /// 配置值未通过业务校验。
    #[error("Validation error: {0}")]
    Validation(String),

    /// 指定的配置文件未找到。
    #[error("Config not found: {0}")]
    NotFound(String),
}

/// Zenith 框架的顶层配置根,聚合全部子配置段。
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Default)]
pub struct ZenithConfig {
    /// 服务器监听与连接相关配置。
    pub server: ServerConfig,
    /// 运行时线程模型与加速特性配置。
    pub runtime: RuntimeConfig,
    /// 缓存分片与淘汰策略配置。
    pub cache: CacheConfig,
    /// 安全(TLS、常量时间、eBPF 完整性)配置。
    pub security: SecurityConfig,
    /// 可观测性(指标、追踪、日志)配置。
    pub observability: ObservabilityConfig,
}


impl ZenithConfig {
    /// 从指定文件路径加载并校验配置。
    ///
    /// # Errors
    /// - 文件不存在(`ErrorKind::NotFound`)→ [`ConfigError::NotFound`]
    /// - 其他文件读取失败 → [`ConfigError::Io`]
    /// - TOML 解析失败 → [`ConfigError::Toml`]
    /// - 业务校验失败 → [`ConfigError::Validation`]
    pub fn from_file(path: &Path) -> Result<Self, ConfigError> {
        // 文件不存在单独映射为 NotFound,与权限不足等其他 I/O 错误区分
        let content = fs::read_to_string(path).map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                ConfigError::NotFound(path.display().to_string())
            } else {
                ConfigError::Io(e)
            }
        })?;
        let config: ZenithConfig = toml::from_str(&content)?;
        config.validate()?;
        Ok(config)
    }

    /// 将当前配置序列化为美观格式的 TOML 字符串。
    ///
    /// # Errors
    /// 当 TOML 序列化失败时返回 [`ConfigError::Serialize`]。
    pub fn to_toml(&self) -> Result<String, ConfigError> {
        toml::to_string_pretty(self).map_err(ConfigError::from)
    }

    /// 将当前配置写入指定文件路径(覆盖写入)。
    ///
    /// # Errors
    /// 当序列化或文件写入失败时返回 [`ConfigError`]。
    pub fn save_to_file(&self, path: &Path) -> Result<(), ConfigError> {
        let content = self.to_toml()?;
        fs::write(path, content)?;
        Ok(())
    }

    /// 递归校验全部子配置段的业务约束。
    ///
    /// # Errors
    /// 当任一子配置段未通过校验时返回对应的 [`ConfigError::Validation`]。
    pub fn validate(&self) -> Result<(), ConfigError> {
        self.server.validate()?;
        self.runtime.validate()?;
        self.cache.validate()?;
        self.security.validate()?;
        self.observability.validate()?;
        Ok(())
    }
}

/// 通过 [`std::str::FromStr`] 从 TOML 字符串加载配置,避免与标准 trait 命名冲突。
impl FromStr for ZenithConfig {
    type Err = ConfigError;

    fn from_str(s: &str) -> Result<Self, ConfigError> {
        let config: ZenithConfig = toml::from_str(s)?;
        config.validate()?;
        Ok(config)
    }
}

/// 服务器监听与连接生命周期配置。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    /// 监听地址(`ip:port`)。
    pub listen_addr: String,
    /// 最大并发连接数上限。
    pub max_connections: u32,
    /// 连接建立后的空闲超时(毫秒)。
    pub connection_timeout_ms: u64,
    /// Keepalive 探测间隔(毫秒)。
    pub keepalive_interval_ms: u64,
    /// `/metrics` 端点认证令牌(Bearer Token)。
    ///
    /// - `None`:`/metrics` 端点不存在(返回 404),防止未显式配置时暴露观测数据。
    /// - `Some(token)`:请求须携带 `Authorization: Bearer {token}` 头(恒定时间比较),
    ///   不匹配返回 401。
    pub metrics_auth_token: Option<String>,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            listen_addr: "0.0.0.0:8080".to_string(),
            max_connections: 65536,
            connection_timeout_ms: 5000,
            keepalive_interval_ms: 30000,
            metrics_auth_token: None,
        }
    }
}

impl ServerConfig {
    /// 校验服务器配置的业务约束。
    ///
    /// # Errors
    /// 当 `max_connections`、`connection_timeout_ms` 或 `keepalive_interval_ms` 为 0 时返回错误。
    pub fn validate(&self) -> Result<(), ConfigError> {
        if self.max_connections == 0 {
            return Err(ConfigError::Validation("max_connections must be > 0".into()));
        }
        if self.connection_timeout_ms == 0 {
            return Err(ConfigError::Validation("connection_timeout_ms must be > 0".into()));
        }
        if self.keepalive_interval_ms == 0 {
            return Err(ConfigError::Validation("keepalive_interval_ms must be > 0".into()));
        }
        Ok(())
    }
}

/// 运行时线程模型与内核加速特性配置。
///
/// 全标量字段(`usize` × 4 + `bool` × 3),按 AGENT.md §6.1.3 实现 `Copy`,
/// 避免热路径上的 `Clone` 开销。
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct RuntimeConfig {
    /// 业务工作线程数。
    pub worker_threads: usize,
    /// I/O 轮询线程数。
    pub io_threads: usize,
    /// 定时器轮询线程数。
    pub time_threads: usize,
    /// 阻塞任务线程数。
    pub blocking_threads: usize,
    /// 是否启用 eBPF 加速。
    pub enable_ebpf: bool,
    /// 是否启用 XDP/AF_XDP 零拷贝。
    pub enable_xsk: bool,
    /// 是否启用 NUMA 感知内存分配。
    pub numa_aware: bool,
}

impl Default for RuntimeConfig {
    fn default() -> Self {
        Self {
            worker_threads: 4,
            io_threads: 2,
            time_threads: 1,
            blocking_threads: 4,
            enable_ebpf: true,
            enable_xsk: true,
            numa_aware: true,
        }
    }
}

impl RuntimeConfig {
    /// 校验运行时配置的业务约束。
    ///
    /// # Errors
    /// 当 `worker_threads`、`io_threads`、`time_threads` 或 `blocking_threads` 为 0 时返回错误。
    pub fn validate(&self) -> Result<(), ConfigError> {
        if self.worker_threads == 0 {
            return Err(ConfigError::Validation("worker_threads must be > 0".into()));
        }
        if self.io_threads == 0 {
            return Err(ConfigError::Validation("io_threads must be > 0".into()));
        }
        if self.time_threads == 0 {
            return Err(ConfigError::Validation("time_threads must be > 0".into()));
        }
        if self.blocking_threads == 0 {
            return Err(ConfigError::Validation("blocking_threads must be > 0".into()));
        }
        Ok(())
    }
}

/// 缓存分片与淘汰策略配置。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheConfig {
    /// 分片数量(必须为 2 的幂,用于位掩码取模)。
    pub shard_count: usize,
    /// 每个分片的容量上限(条目数)。
    pub per_shard_capacity: usize,
    /// 单个缓存条目的最大字节数。
    pub max_entry_size: usize,
    /// 淘汰策略名称(白名单:`"lru"` / `"fifo"` / `"random"`)。
    pub eviction_policy: String,
    /// 默认 TTL(秒)。
    pub ttl_seconds: u64,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            shard_count: 16,
            per_shard_capacity: 65536,
            max_entry_size: 1048576,
            eviction_policy: "lru".to_string(),
            ttl_seconds: 3600,
        }
    }
}

impl CacheConfig {
    /// 校验缓存配置的业务约束。
    ///
    /// # Errors
    /// 以下任一不满足时返回 [`ConfigError::Validation`]:
    /// - `shard_count` 非 2 的幂
    /// - `per_shard_capacity` 为 0
    /// - `max_entry_size` 为 0
    /// - `eviction_policy` 不在白名单 `"lru" | "fifo" | "random"` 内
    /// - `ttl_seconds` 为 0
    pub fn validate(&self) -> Result<(), ConfigError> {
        if self.shard_count == 0 || !self.shard_count.is_power_of_two() {
            return Err(ConfigError::Validation("shard_count must be a power of 2".into()));
        }
        if self.per_shard_capacity == 0 {
            return Err(ConfigError::Validation("per_shard_capacity must be > 0".into()));
        }
        if self.max_entry_size == 0 {
            return Err(ConfigError::Validation("max_entry_size must be > 0".into()));
        }
        // 淘汰策略收敛到受支持的白名单,杜绝拼写错误导致的静默行为分歧
        if !matches!(self.eviction_policy.as_str(), "lru" | "fifo" | "random") {
            return Err(ConfigError::Validation(
                "eviction_policy must be one of \"lru\" | \"fifo\" | \"random\"".into(),
            ));
        }
        if self.ttl_seconds == 0 {
            return Err(ConfigError::Validation("ttl_seconds must be > 0".into()));
        }
        Ok(())
    }
}

/// 安全相关配置(TLS、常量时间比较、eBPF 完整性)。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
    /// 是否启用 TLS 终止。
    pub enable_tls: bool,
    /// TLS 证书文件路径(启用 TLS 时必填)。
    pub cert_path: Option<String>,
    /// TLS 私钥文件路径(启用 TLS 时必填)。
    pub key_path: Option<String>,
    /// 是否启用常量时间比较(防时序攻击)。
    pub enable_constant_time: bool,
    /// 是否启用 eBPF 自身完整性校验。
    pub enable_ebpf_integrity: bool,
    /// 令牌最大生命周期(毫秒)。
    pub max_token_lifetime_ms: u64,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            enable_tls: false,
            cert_path: None,
            key_path: None,
            enable_constant_time: true,
            enable_ebpf_integrity: true,
            max_token_lifetime_ms: 3600000,
        }
    }
}

impl SecurityConfig {
    /// 校验安全配置的业务约束。
    ///
    /// # Errors
    /// - 当启用 TLS 但未提供证书或私钥路径时返回错误
    /// - 当 `max_token_lifetime_ms` 为 0 时返回错误
    pub fn validate(&self) -> Result<(), ConfigError> {
        if self.enable_tls
            && (self.cert_path.is_none() || self.key_path.is_none()) {
                return Err(ConfigError::Validation("TLS requires cert_path and key_path".into()));
        }
        if self.max_token_lifetime_ms == 0 {
            return Err(ConfigError::Validation("max_token_lifetime_ms must be > 0".into()));
        }
        Ok(())
    }
}

/// 可观测性配置(指标、追踪、日志)。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObservabilityConfig {
    /// 是否启用 Prometheus 指标导出。
    pub enable_metrics: bool,
    /// 指标导出监听地址。
    pub metrics_addr: String,
    /// 是否启用分布式追踪。
    pub enable_tracing: bool,
    /// 追踪级别(如 `info`、`debug`)。
    pub tracing_level: String,
    /// 是否启用结构化日志。
    pub enable_logging: bool,
    /// 日志级别(如 `info`、`debug`)。
    pub log_level: String,
}

impl Default for ObservabilityConfig {
    fn default() -> Self {
        Self {
            enable_metrics: true,
            metrics_addr: "0.0.0.0:9090".to_string(),
            enable_tracing: false,
            tracing_level: "info".to_string(),
            enable_logging: true,
            log_level: "info".to_string(),
        }
    }
}

impl ObservabilityConfig {
    /// 校验可观测性配置的业务约束。
    ///
    /// # Errors
    /// 当 `log_level` 或 `tracing_level` 不在
    /// `"trace" | "debug" | "info" | "warn" | "error"` 白名单内时返回
    /// [`ConfigError::Validation`]。
    pub fn validate(&self) -> Result<(), ConfigError> {
        // 级别收敛到 tracing/log 生态通用白名单,拒绝拼写错误或未知级别
        const LEVELS: [&str; 5] = ["trace", "debug", "info", "warn", "error"];
        if !LEVELS.contains(&self.log_level.as_str()) {
            return Err(ConfigError::Validation(
                "log_level must be one of \"trace\" | \"debug\" | \"info\" | \"warn\" | \"error\""
                    .into(),
            ));
        }
        if !LEVELS.contains(&self.tracing_level.as_str()) {
            return Err(ConfigError::Validation(
                "tracing_level must be one of \"trace\" | \"debug\" | \"info\" | \"warn\" | \"error\""
                    .into(),
            ));
        }
        Ok(())
    }
}

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

    #[test]
    fn test_default_config() {
        let config = ZenithConfig::default();
        assert!(config.validate().is_ok());
        assert_eq!(config.server.listen_addr, "0.0.0.0:8080");
        assert!(config.runtime.enable_ebpf);
    }

    #[test]
    fn test_metrics_auth_token_default_none() {
        let config = ZenithConfig::default();
        assert!(config.server.metrics_auth_token.is_none());
    }

    #[test]
    fn test_metrics_auth_token_from_toml() {
        let toml_str = r#"
[server]
listen_addr = "0.0.0.0:8080"
max_connections = 100
connection_timeout_ms = 5000
keepalive_interval_ms = 30000
metrics_auth_token = "s3cr3t-t0ken"

[runtime]
worker_threads = 4
io_threads = 2
time_threads = 1
blocking_threads = 4
enable_ebpf = false
enable_xsk = false
numa_aware = false

[cache]
shard_count = 16
per_shard_capacity = 4096
max_entry_size = 1048576
eviction_policy = "lru"
ttl_seconds = 300

[security]
enable_tls = false
enable_constant_time = true
enable_ebpf_integrity = true
max_token_lifetime_ms = 3600000

[observability]
enable_metrics = true
metrics_addr = "0.0.0.0:9091"
enable_tracing = false
tracing_level = "info"
enable_logging = true
log_level = "info"
"#;
        let config = ZenithConfig::from_str(toml_str).unwrap();
        assert_eq!(config.server.metrics_auth_token.as_deref(), Some("s3cr3t-t0ken"));
    }

    #[test]
    fn test_config_roundtrip() {
        let config = ZenithConfig::default();
        let toml_str = config.to_toml().unwrap();
        let parsed = ZenithConfig::from_str(&toml_str).unwrap();
        assert_eq!(parsed.server.listen_addr, config.server.listen_addr);
        assert_eq!(parsed.runtime.worker_threads, config.runtime.worker_threads);
    }

    #[test]
    fn test_config_validation() {
        let mut config = ZenithConfig::default();
        config.server.max_connections = 0;
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_config_tls_validation() {
        let mut config = ZenithConfig::default();
        config.security.enable_tls = true;
        assert!(config.validate().is_err());

        config.security.cert_path = Some("/path/to/cert".to_string());
        config.security.key_path = Some("/path/to/key".to_string());
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_cache_validation() {
        let mut config = ZenithConfig::default();
        config.cache.shard_count = 3;
        assert!(config.validate().is_err());

        config.cache.shard_count = 16;
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_custom_values() {
        let toml_str = r#"
[server]
listen_addr = "127.0.0.1:9090"
max_connections = 10000
connection_timeout_ms = 3000
keepalive_interval_ms = 15000

[runtime]
worker_threads = 8
io_threads = 4
time_threads = 2
blocking_threads = 8
enable_ebpf = true
enable_xsk = true
numa_aware = true

[cache]
shard_count = 32
per_shard_capacity = 131072
max_entry_size = 2097152
eviction_policy = "fifo"
ttl_seconds = 7200

[security]
enable_tls = false
enable_constant_time = true
enable_ebpf_integrity = true
max_token_lifetime_ms = 7200000

[observability]
enable_metrics = true
metrics_addr = "0.0.0.0:8081"
enable_tracing = true
tracing_level = "debug"
enable_logging = true
log_level = "debug"
"#;
        let config = ZenithConfig::from_str(toml_str).unwrap();
        assert_eq!(config.server.listen_addr, "127.0.0.1:9090");
        assert_eq!(config.runtime.worker_threads, 8);
        assert_eq!(config.cache.shard_count, 32);
        assert_eq!(config.observability.metrics_addr, "0.0.0.0:8081");
    }

    #[test]
    fn test_from_file_not_found_maps_to_not_found() {
        // 不存在的配置文件必须映射为 ConfigError::NotFound(而非笼统的 Io)
        let path = Path::new("zzz_zenith_definitely_missing_config_x7q9.toml");
        let result = ZenithConfig::from_file(path);
        match result {
            Err(ConfigError::NotFound(msg)) => {
                assert!(msg.contains("zzz_zenith_definitely_missing_config_x7q9.toml"));
            }
            other => panic!("expected ConfigError::NotFound, got {other:?}"),
        }
        // 现有文件路径不受影响(默认配置仍可通过往返加载)
        let config = ZenithConfig::default();
        assert!(config.validate().is_ok());
    }

    fn default_cache() -> CacheConfig {
        CacheConfig::default()
    }

    #[test]
    fn test_cache_validate_eviction_policy_whitelist() {
        // 白名单内策略全部通过
        for policy in ["lru", "fifo", "random"] {
            let mut cache = default_cache();
            cache.eviction_policy = policy.to_string();
            assert!(cache.validate().is_ok(), "policy {policy} should pass");
        }
        // 白名单外(含旧文档示例 "lfu")必须拒绝
        for policy in ["lfu", "LRU", "", "clock"] {
            let mut cache = default_cache();
            cache.eviction_policy = policy.to_string();
            assert!(
                matches!(cache.validate(), Err(ConfigError::Validation(_))),
                "policy {policy} should be rejected"
            );
        }
    }

    #[test]
    fn test_cache_validate_max_entry_size_positive() {
        let mut cache = default_cache();
        cache.max_entry_size = 0;
        assert!(matches!(cache.validate(), Err(ConfigError::Validation(_))));

        let mut cache = default_cache();
        cache.max_entry_size = 1;
        assert!(cache.validate().is_ok());
    }

    #[test]
    fn test_observability_validate_level_whitelist() {
        // 白名单内级别全部通过
        for level in ["trace", "debug", "info", "warn", "error"] {
            let obs = ObservabilityConfig {
                log_level: level.to_string(),
                tracing_level: level.to_string(),
                ..Default::default()
            };
            assert!(obs.validate().is_ok(), "level {level} should pass");
        }
        // log_level 非法
        let obs = ObservabilityConfig {
            log_level: "verbose".to_string(),
            ..Default::default()
        };
        assert!(matches!(obs.validate(), Err(ConfigError::Validation(_))));
        // tracing_level 非法(区分大小写)
        let obs = ObservabilityConfig {
            tracing_level: "TRACE".to_string(),
            ..Default::default()
        };
        assert!(matches!(obs.validate(), Err(ConfigError::Validation(_))));
        // 非法级别会从 ZenithConfig::validate 递归传播
        let mut config = ZenithConfig::default();
        config.observability.log_level = "nope".to_string();
        assert!(matches!(config.validate(), Err(ConfigError::Validation(_))));
    }
}