1use parking_lot::RwLock;
24use serde::{Deserialize, Serialize};
25use std::collections::{BTreeMap, HashMap};
26use std::fs;
27use std::path::Path;
28use tracing::info;
29
30pub const DEFAULT_DB_ALIAS: &str = "default";
32
33pub mod env;
34pub mod log;
35pub use env::{detect_profile, merge_env_overrides, parse_args};
36pub use log::init as init_log;
37
38#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct AppConfig {
41 #[serde(default = "default_app_name")]
43 pub app_name: String,
44
45 #[serde(default = "default_profile")]
47 pub profile: String,
48
49 #[serde(default)]
51 pub server: ServerConfig,
52
53 #[serde(default)]
55 pub log: LogConfig,
56
57 #[serde(default)]
59 pub database: DatabaseConfig,
60
61 #[serde(default)]
66 pub databases: BTreeMap<String, DatabaseConfig>,
67
68 #[serde(default)]
70 pub redis: RedisConfig,
71
72 #[serde(default)]
74 pub cache: CacheConfig,
75
76 #[serde(default)]
78 pub fs: FsConfig,
79
80 #[serde(default)]
82 pub middleware: MiddlewareConfig,
83
84 #[serde(default)]
86 pub router: RouterConfig,
87
88 #[serde(default)]
90 pub plugins: PluginsConfig,
91
92 #[serde(default)]
94 pub upload: UploadConfig,
95
96 #[serde(default)]
98 pub download: DownloadConfig,
99
100 #[serde(default)]
102 pub template: TemplateConfig,
103
104 #[serde(default)]
106 pub static_files: StaticConfig,
107
108 #[serde(default)]
110 pub custom: HashMap<String, serde_json::Value>,
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct ServerConfig {
116 #[serde(default = "default_listen")]
118 pub listen: String,
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct LogConfig {
124 #[serde(default = "default_log_level")]
126 pub level: String,
127
128 #[serde(default = "default_log_format")]
130 pub format: String,
131
132 #[serde(default)]
134 pub dir: Option<String>,
135
136 #[serde(default = "default_log_prefix")]
138 pub file_prefix: String,
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct DatabaseConfig {
144 #[serde(default = "default_true")]
146 pub enabled: bool,
147
148 #[serde(default = "default_db_type")]
150 pub r#type: String,
151
152 #[serde(default = "default_host")]
154 pub host: String,
155
156 pub port: Option<u16>,
158
159 #[serde(default)]
161 pub name: String,
162
163 #[serde(default)]
165 pub user: String,
166
167 #[serde(default)]
169 pub password: String,
170
171 #[serde(default)]
173 pub password_encrypted: bool,
174
175 #[serde(default = "default_pool_size")]
177 pub max_connections: u32,
178
179 #[serde(default = "default_min_idle")]
181 pub min_connections: u32,
182
183 #[serde(default = "default_timeout")]
185 pub connect_timeout: u64,
186
187 #[serde(default)]
189 pub sql_logging: bool,
190
191 #[serde(default)]
193 pub slow_query_ms: u64,
194
195 #[serde(default)]
197 pub migration: MigrationConfig,
198}
199
200#[derive(Debug, Clone, Serialize, Deserialize)]
202pub struct RedisConfig {
203 #[serde(default)]
205 pub enabled: bool,
206
207 #[serde(default = "default_redis_url")]
209 pub url: String,
210
211 #[serde(default = "default_pool_size")]
213 pub max_connections: u32,
214}
215
216#[derive(Debug, Clone, Serialize, Deserialize)]
218pub struct CacheConfig {
219 #[serde(default = "default_cache_type")]
221 pub r#type: String,
222
223 #[serde(default = "default_cache_capacity")]
225 pub max_capacity: u64,
226
227 #[serde(default = "default_ttl")]
230 pub default_ttl: u64,
231}
232
233#[derive(Debug, Clone, Serialize, Deserialize, Default)]
235pub struct FsConfig {
236 #[serde(default = "default_fs_backend")]
238 pub backend: String,
239
240 #[serde(default = "default_fs_root")]
242 pub root_dir: String,
243
244 #[serde(default)]
246 pub endpoint: String,
247
248 #[serde(default)]
250 pub bucket: String,
251
252 #[serde(default)]
254 pub access_key: String,
255
256 #[serde(default)]
258 pub secret_key: String,
259
260 #[serde(default = "default_fs_region")]
262 pub region: String,
263}
264
265#[derive(Debug, Clone, Serialize, Deserialize, Default)]
273pub struct NonceConfig {
274 #[serde(default)]
276 pub enabled: bool,
277
278 #[serde(default = "default_nonce_availability")]
283 pub availability: String,
284
285 #[serde(default = "default_true")]
287 pub require_for_write: bool,
288
289 #[serde(default = "default_nonce_ttl")]
291 pub ttl_secs: u64,
292}
293
294fn default_nonce_ttl() -> u64 {
295 300
296}
297
298fn default_nonce_availability() -> String {
299 "best_effort".to_string()
300}
301
302fn default_tenant_header() -> String {
303 "X-Tenant-Id".to_string()
304}
305
306#[derive(Debug, Clone, Serialize, Deserialize)]
308pub struct AuditRoute {
309 #[serde(default)]
311 pub method: String,
312
313 pub path: String,
316
317 pub action: String,
319}
320
321#[derive(Debug, Clone, Serialize, Deserialize)]
328pub struct AuditMiddlewareConfig {
329 #[serde(default)]
331 pub enabled: bool,
332
333 #[serde(default = "default_audit_sink")]
335 pub sink: String,
336
337 #[serde(default = "default_audit_path")]
339 pub path: String,
340
341 #[serde(default = "default_audit_max_bytes")]
345 pub max_bytes: u64,
346
347 #[serde(default = "default_audit_table")]
350 pub table: String,
351
352 #[serde(default = "default_audit_capacity")]
354 pub capacity: usize,
355
356 #[serde(default = "default_audit_max_batch")]
358 pub max_batch: usize,
359
360 #[serde(default = "default_audit_flush_secs")]
362 pub flush_interval_secs: u64,
363
364 #[serde(default = "default_audit_overflow")]
367 pub on_overflow: String,
368
369 #[serde(default = "default_audit_overflow_path")]
371 pub overflow_path: String,
372
373 #[serde(default = "default_audit_shutdown_timeout")]
375 pub shutdown_timeout_secs: u64,
376
377 #[serde(default)]
379 pub routes: Vec<AuditRoute>,
380}
381
382fn default_audit_sink() -> String {
383 "jsonl".to_string()
384}
385fn default_audit_path() -> String {
386 "logs/audit.log".to_string()
387}
388fn default_audit_max_bytes() -> u64 {
389 32 * 1024 * 1024
390}
391fn default_audit_table() -> String {
392 "audit_log".to_string()
393}
394fn default_audit_capacity() -> usize {
395 4096
396}
397fn default_audit_max_batch() -> usize {
398 128
399}
400fn default_audit_flush_secs() -> u64 {
401 1
402}
403fn default_audit_overflow() -> String {
404 "drop".to_string()
405}
406fn default_audit_overflow_path() -> String {
407 "logs/audit-overflow.log".to_string()
408}
409fn default_audit_shutdown_timeout() -> u64 {
410 3
411}
412
413impl Default for AuditMiddlewareConfig {
414 fn default() -> Self {
415 Self {
416 enabled: false,
417 sink: default_audit_sink(),
418 path: default_audit_path(),
419 max_bytes: default_audit_max_bytes(),
420 table: default_audit_table(),
421 capacity: default_audit_capacity(),
422 max_batch: default_audit_max_batch(),
423 flush_interval_secs: default_audit_flush_secs(),
424 on_overflow: default_audit_overflow(),
425 overflow_path: default_audit_overflow_path(),
426 shutdown_timeout_secs: default_audit_shutdown_timeout(),
427 routes: Vec::new(),
428 }
429 }
430}
431
432#[derive(Debug, Clone, Serialize, Deserialize)]
434pub struct MiddlewareConfig {
435 #[serde(default)]
437 pub request_id: bool,
438
439 #[serde(default)]
441 pub request_log: bool,
442
443 #[serde(default)]
445 pub request_log_config: RequestLogConfig,
446
447 #[serde(default)]
449 pub auth: AuthMiddlewareConfig,
450
451 #[serde(default)]
453 pub cors: CorsConfig,
454
455 #[serde(default)]
457 pub compression: CompressConfig,
458
459 #[serde(default)]
461 pub rate_limit: RateLimitConfig,
462
463 #[serde(default)]
465 pub security_headers: SecurityHeadersConfig,
466
467 #[serde(default)]
469 pub permission: PermissionConfig,
470
471 #[serde(default)]
473 pub nonce: NonceConfig,
474
475 #[serde(default)]
477 pub audit: AuditMiddlewareConfig,
478
479 #[serde(default = "default_tenant_header")]
481 pub tenant_header: String,
482}
483
484#[derive(Debug, Clone, Serialize, Deserialize)]
486pub struct RequestLogConfig {
487 #[serde(default)]
489 pub exclude_paths: Vec<String>,
490
491 #[serde(default = "default_true")]
493 pub log_duration: bool,
494
495 #[serde(default)]
498 pub print_body: bool,
499
500 #[serde(default)]
503 pub report_multiline: bool,
504}
505
506#[derive(Debug, Clone, Serialize, Deserialize)]
508pub struct AuthMiddlewareConfig {
509 #[serde(default)]
510 pub enabled: bool,
511
512 #[serde(default)]
514 pub ignore_paths: Vec<String>,
515
516 #[serde(default = "default_api_prefixes")]
520 pub api_prefixes: Vec<String>,
521
522 #[serde(default = "default_session_ttl")]
524 pub session_ttl_secs: u64,
525
526 #[serde(default = "default_access_token_expire")]
528 pub access_token_expire_secs: u64,
529
530 #[serde(default = "default_refresh_token_expire")]
532 pub refresh_token_expire_secs: u64,
533}
534
535fn default_api_prefixes() -> Vec<String> {
536 Vec::new()
539}
540
541#[derive(Debug, Clone, Serialize, Deserialize)]
543pub struct CorsConfig {
544 #[serde(default)]
545 pub enabled: bool,
546
547 #[serde(default)]
548 pub allow_origins: Vec<String>,
549
550 #[serde(default)]
551 pub allow_methods: Vec<String>,
552
553 #[serde(default)]
554 pub allow_headers: Vec<String>,
555
556 #[serde(default = "default_true")]
557 pub allow_credentials: bool,
558
559 #[serde(default = "default_cors_max_age")]
560 pub max_age_secs: u64,
561}
562
563#[derive(Debug, Clone, Serialize, Deserialize)]
565pub struct CompressConfig {
566 #[serde(default)]
568 pub enabled: bool,
569
570 #[serde(default = "default_compress_level")]
572 pub level: u32,
573}
574
575#[derive(Debug, Clone, Serialize, Deserialize)]
577pub struct RateLimitConfig {
578 #[serde(default)]
579 pub enabled: bool,
580
581 #[serde(default = "default_rate_limit_requests")]
583 pub requests_per_window: u64,
584
585 #[serde(default = "default_rate_limit_window")]
587 pub window_secs: u64,
588
589 #[serde(default)]
594 pub trust_xff: bool,
595
596 #[serde(default)]
601 pub trusted_proxies: Vec<String>,
602}
603
604#[derive(Debug, Clone, Serialize, Deserialize)]
609pub struct SecurityHeadersConfig {
610 #[serde(default = "default_true")]
612 pub enabled: bool,
613
614 #[serde(default = "default_true")]
616 pub nosniff: bool,
617
618 #[serde(default = "default_true")]
620 pub frame_options: bool,
621
622 #[serde(default = "default_true")]
624 pub hsts: bool,
625
626 #[serde(default = "default_hsts_max_age")]
628 pub hsts_max_age_secs: u64,
629
630 #[serde(default = "default_true")]
632 pub hsts_include_subdomains: bool,
633
634 #[serde(default = "default_true")]
636 pub csp: bool,
637
638 #[serde(default = "default_csp_value")]
640 pub csp_value: String,
641
642 #[serde(default = "default_true")]
644 pub referrer_policy: bool,
645
646 #[serde(default = "default_referrer_policy_value")]
648 pub referrer_policy_value: String,
649
650 #[serde(default)]
652 pub permissions_policy: bool,
653
654 #[serde(default = "default_permissions_policy_value")]
656 pub permissions_policy_value: String,
657}
658
659#[derive(Debug, Clone, Serialize, Deserialize, Default)]
665pub struct PermissionConfig {
666 #[serde(default)]
668 pub enabled: bool,
669
670 #[serde(default)]
672 pub rules: Vec<PermissionRule>,
673}
674
675#[derive(Debug, Clone, Serialize, Deserialize, Default)]
677pub struct PermissionRule {
678 pub path: String,
680 #[serde(default)]
682 pub methods: Vec<String>,
683 pub permission: String,
685}
686
687#[derive(Debug, Clone, Serialize, Deserialize, Default)]
689pub struct RouterConfig {
690 #[serde(default)]
692 pub prefix: String,
693 #[serde(default)]
695 pub not_found: NotFoundConfig,
696}
697
698#[derive(Debug, Clone, Serialize, Deserialize)]
700pub struct NotFoundConfig {
701 #[serde(default = "default_true")]
703 pub enabled: bool,
704 #[serde(default = "default_not_found_msg")]
706 pub message: String,
707}
708
709#[derive(Debug, Clone, Serialize, Deserialize)]
711pub struct MigrationConfig {
712 #[serde(default)]
714 pub enabled: bool,
715
716 #[serde(default = "default_migration_path")]
718 pub path: String,
719
720 #[serde(default)]
722 pub auto_migrate: bool,
723}
724
725#[derive(Debug, Clone, Serialize, Deserialize)]
727pub struct UploadConfig {
728 #[serde(default = "default_upload_path")]
730 pub path: String,
731
732 #[serde(default = "default_max_size")]
734 pub max_size_mb: u64,
735}
736
737#[derive(Debug, Clone, Serialize, Deserialize)]
739pub struct DownloadConfig {
740 #[serde(default = "default_download_path")]
742 pub path: String,
743}
744
745#[derive(Debug, Clone, Serialize, Deserialize)]
747pub struct TemplateConfig {
748 #[serde(default = "default_template_path")]
750 pub path: String,
751}
752
753#[derive(Debug, Clone, Serialize, Deserialize)]
755pub struct StaticConfig {
756 #[serde(default = "default_static_path")]
758 pub path: String,
759
760 #[serde(default)]
762 pub enabled: bool,
763}
764
765#[derive(Debug, Clone, Serialize, Deserialize, Default)]
767pub struct PluginsConfig {
768 #[serde(default)]
770 pub enabled: Vec<String>,
771
772 #[serde(default)]
774 pub scheduler: SchedulerConfig,
775}
776
777#[derive(Debug, Clone, Serialize, Deserialize, Default)]
778pub struct SchedulerConfig {
779 #[serde(default = "default_workers")]
781 pub workers: usize,
782}
783
784pub const DEFAULT_APP_NAME: &str = "Wordval";
787pub const DEFAULT_PROFILE: &str = "dev";
788pub const DEFAULT_LISTEN: &str = "8023";
789pub const DEFAULT_LOG_LEVEL: &str = "info";
790pub const DEFAULT_LOG_FORMAT: &str = "text";
791pub const DEFAULT_LOG_PREFIX: &str = "wordval";
792pub const DEFAULT_DB_TYPE: &str = "postgres";
793pub const DEFAULT_HOST: &str = "localhost";
794pub const DEFAULT_REDIS_URL: &str = "redis://127.0.0.1:6379";
795pub const DEFAULT_CACHE_TYPE: &str = "local";
796pub const DEFAULT_FS_BACKEND: &str = "local";
797pub const DEFAULT_FS_ROOT: &str = "uploads";
798pub const DEFAULT_FS_REGION: &str = "us-east-1";
799pub const DEFAULT_CSP_VALUE: &str = "default-src 'self'";
800pub const DEFAULT_REFERRER_POLICY_VALUE: &str = "strict-origin-when-cross-origin";
801pub const DEFAULT_PERMISSIONS_POLICY_VALUE: &str = "camera=(), microphone=(), geolocation=()";
802pub const DEFAULT_MIGRATION_PATH: &str = "migrations";
803pub const DEFAULT_UPLOAD_PATH: &str = "uploads";
804pub const DEFAULT_DOWNLOAD_PATH: &str = "downloads";
805pub const DEFAULT_TEMPLATE_PATH: &str = "templates";
806pub const DEFAULT_STATIC_PATH: &str = "static";
807pub const DEFAULT_NOT_FOUND_MSG: &str = "请求的资源不存在";
808
809fn default_app_name() -> String {
812 DEFAULT_APP_NAME.to_string()
813}
814fn default_profile() -> String {
815 DEFAULT_PROFILE.to_string()
816}
817fn default_listen() -> String {
818 DEFAULT_LISTEN.to_string()
819}
820fn default_log_level() -> String {
821 DEFAULT_LOG_LEVEL.to_string()
822}
823fn default_log_format() -> String {
824 DEFAULT_LOG_FORMAT.to_string()
825}
826fn default_log_prefix() -> String {
827 DEFAULT_LOG_PREFIX.to_string()
828}
829fn default_db_type() -> String {
830 DEFAULT_DB_TYPE.to_string()
831}
832fn default_host() -> String {
833 DEFAULT_HOST.to_string()
834}
835fn default_true() -> bool {
836 true
837}
838fn default_pool_size() -> u32 {
839 10
840}
841fn default_min_idle() -> u32 {
842 2
843}
844fn default_timeout() -> u64 {
845 10
846}
847fn default_workers() -> usize {
848 4
849}
850fn default_redis_url() -> String {
851 DEFAULT_REDIS_URL.to_string()
852}
853fn default_cache_type() -> String {
854 DEFAULT_CACHE_TYPE.to_string()
855}
856fn default_fs_backend() -> String {
857 DEFAULT_FS_BACKEND.to_string()
858}
859fn default_fs_root() -> String {
860 DEFAULT_FS_ROOT.to_string()
861}
862fn default_fs_region() -> String {
863 DEFAULT_FS_REGION.to_string()
864}
865fn default_cache_capacity() -> u64 {
866 10000
867}
868fn default_ttl() -> u64 {
869 3600
870}
871fn default_session_ttl() -> u64 {
872 86400
873}
874fn default_access_token_expire() -> u64 {
875 7200
876}
877fn default_refresh_token_expire() -> u64 {
878 604800
879}
880fn default_cors_max_age() -> u64 {
881 86400
882}
883fn default_compress_level() -> u32 {
884 6
885}
886fn default_rate_limit_requests() -> u64 {
887 100
888}
889fn default_rate_limit_window() -> u64 {
890 60
891}
892fn default_hsts_max_age() -> u64 {
893 31536000
894}
895fn default_csp_value() -> String {
896 DEFAULT_CSP_VALUE.to_string()
897}
898fn default_referrer_policy_value() -> String {
899 DEFAULT_REFERRER_POLICY_VALUE.to_string()
900}
901fn default_permissions_policy_value() -> String {
902 DEFAULT_PERMISSIONS_POLICY_VALUE.to_string()
903}
904fn default_migration_path() -> String {
905 DEFAULT_MIGRATION_PATH.to_string()
906}
907fn default_upload_path() -> String {
908 DEFAULT_UPLOAD_PATH.to_string()
909}
910fn default_download_path() -> String {
911 DEFAULT_DOWNLOAD_PATH.to_string()
912}
913fn default_template_path() -> String {
914 DEFAULT_TEMPLATE_PATH.to_string()
915}
916fn default_static_path() -> String {
917 DEFAULT_STATIC_PATH.to_string()
918}
919fn default_not_found_msg() -> String {
920 DEFAULT_NOT_FOUND_MSG.to_string()
921}
922fn default_max_size() -> u64 {
923 10
924}
925
926impl Default for AppConfig {
927 fn default() -> Self {
928 Self {
929 app_name: default_app_name(),
930 profile: default_profile(),
931 server: ServerConfig::default(),
932 log: LogConfig::default(),
933 database: DatabaseConfig::default(),
934 databases: BTreeMap::new(),
935 redis: RedisConfig::default(),
936 cache: CacheConfig::default(),
937 fs: FsConfig::default(),
938 middleware: MiddlewareConfig::default(),
939 router: RouterConfig::default(),
940 plugins: PluginsConfig::default(),
941 upload: UploadConfig::default(),
942 download: DownloadConfig::default(),
943 template: TemplateConfig::default(),
944 static_files: StaticConfig::default(),
945 custom: HashMap::new(),
946 }
947 }
948}
949
950impl AppConfig {
951 pub fn normalize_databases(&mut self) {
956 if self.database.enabled && !self.databases.contains_key(DEFAULT_DB_ALIAS) {
957 tracing::warn!(
958 "检测到旧版 [database] 配置,已映射为 [databases.default];建议迁移到命名表写法"
959 );
960 self.databases
961 .insert(DEFAULT_DB_ALIAS.to_string(), self.database.clone());
962 }
963 }
964
965 pub fn validate(&self) -> Result<(), String> {
969 let mut errs: Vec<String> = Vec::new();
970
971 match self.server.listen.rsplit(':').next() {
973 Some(port) if port.parse::<u16>().is_ok_and(|p| p > 0) => {}
974 _ => errs.push(format!(
975 "server.listen 格式无效: {} (应为 host:port 或 :port)",
976 self.server.listen
977 )),
978 }
979
980 if self.database.enabled {
982 if self.database.host.is_empty() {
983 errs.push("database.host 不能为空".to_string());
984 }
985 if self.database.name.is_empty() {
986 errs.push("database.name 不能为空".to_string());
987 }
988 }
989
990 for (alias, db) in &self.databases {
992 let valid_alias = !alias.is_empty()
993 && alias.trim() == alias
994 && alias
995 .chars()
996 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
997 if !valid_alias {
998 errs.push(format!(
999 "databases 别名无效: '{alias}' (仅允许字母/数字/下划线/连字符)"
1000 ));
1001 }
1002 if !db.enabled {
1003 continue;
1004 }
1005 if db.host.is_empty() {
1006 errs.push(format!("databases.{alias}.host 不能为空"));
1007 }
1008 if db.name.is_empty() {
1009 errs.push(format!("databases.{alias}.name 不能为空"));
1010 }
1011 }
1012 if self.databases.values().any(|d| d.enabled)
1014 && !self.databases.contains_key(DEFAULT_DB_ALIAS)
1015 {
1016 errs.push(format!(
1017 "databases 缺少 '{}' 别名(db() 需要默认库)",
1018 DEFAULT_DB_ALIAS
1019 ));
1020 }
1021
1022 if self.redis.enabled && self.redis.url.is_empty() {
1024 errs.push("redis.url 不能为空".to_string());
1025 }
1026
1027 if !matches!(self.cache.r#type.as_str(), "local" | "redis") {
1029 errs.push(format!(
1030 "cache.type 无效: {} (应为 local 或 redis)",
1031 self.cache.r#type
1032 ));
1033 }
1034
1035 if self.middleware.rate_limit.enabled {
1037 if self.middleware.rate_limit.requests_per_window == 0 {
1038 errs.push("middleware.rate_limit.limit 必须为正数".to_string());
1039 }
1040 if self.middleware.rate_limit.window_secs == 0 {
1041 errs.push("middleware.rate_limit.window_secs 必须为正数".to_string());
1042 }
1043 }
1044
1045 if self.middleware.nonce.enabled && self.middleware.nonce.ttl_secs == 0 {
1047 errs.push("middleware.nonce.ttl_secs 必须为正数".to_string());
1048 }
1049
1050 if self.upload.max_size_mb == 0 {
1053 errs.push("upload.max_size_mb 必须为正数(0 会拒绝所有请求体)".to_string());
1054 }
1055
1056 let audit = &self.middleware.audit;
1058 if !matches!(audit.sink.as_str(), "jsonl" | "db") {
1059 errs.push(format!(
1060 "middleware.audit.sink 无效: {} (应为 jsonl 或 db)",
1061 audit.sink
1062 ));
1063 }
1064 if !matches!(audit.on_overflow.as_str(), "drop" | "file") {
1065 errs.push(format!(
1066 "middleware.audit.on_overflow 无效: {} (应为 drop 或 file)",
1067 audit.on_overflow
1068 ));
1069 }
1070 if audit.capacity == 0 {
1071 errs.push("middleware.audit.capacity 必须为正数".to_string());
1072 }
1073 if audit.max_batch == 0 {
1074 errs.push("middleware.audit.max_batch 必须为正数".to_string());
1075 }
1076 if audit.flush_interval_secs == 0 {
1077 errs.push("middleware.audit.flush_interval_secs 必须为正数".to_string());
1078 }
1079 if audit.shutdown_timeout_secs == 0 {
1080 errs.push("middleware.audit.shutdown_timeout_secs 必须为正数".to_string());
1081 }
1082 for (i, r) in audit.routes.iter().enumerate() {
1083 if r.path.trim().is_empty() {
1084 errs.push(format!("middleware.audit.routes[{i}].path 不能为空"));
1085 }
1086 if r.action.trim().is_empty() {
1087 errs.push(format!("middleware.audit.routes[{i}].action 不能为空"));
1088 }
1089 }
1090
1091 if self.middleware.tenant_header.trim().is_empty() {
1093 errs.push("middleware.tenant_header 不能为空".to_string());
1094 }
1095
1096 if errs.is_empty() {
1097 Ok(())
1098 } else {
1099 Err(errs.join("; "))
1100 }
1101 }
1102}
1103
1104impl Default for ServerConfig {
1105 fn default() -> Self {
1106 Self {
1107 listen: default_listen(),
1108 }
1109 }
1110}
1111impl Default for LogConfig {
1112 fn default() -> Self {
1113 Self {
1114 level: default_log_level(),
1115 format: default_log_format(),
1116 dir: None,
1117 file_prefix: default_log_prefix(),
1118 }
1119 }
1120}
1121impl Default for DatabaseConfig {
1122 fn default() -> Self {
1123 Self {
1124 enabled: false,
1125 r#type: default_db_type(),
1126 host: default_host(),
1127 port: None,
1128 name: String::new(),
1129 user: String::new(),
1130 password: String::new(),
1131 password_encrypted: false,
1132 max_connections: default_pool_size(),
1133 min_connections: default_min_idle(),
1134 connect_timeout: default_timeout(),
1135 sql_logging: false,
1136 slow_query_ms: 0,
1137 migration: MigrationConfig::default(),
1138 }
1139 }
1140}
1141impl Default for RedisConfig {
1142 fn default() -> Self {
1143 Self {
1144 enabled: false,
1145 url: default_redis_url(),
1146 max_connections: default_pool_size(),
1147 }
1148 }
1149}
1150impl Default for CacheConfig {
1151 fn default() -> Self {
1152 Self {
1153 r#type: default_cache_type(),
1154 max_capacity: default_cache_capacity(),
1155 default_ttl: default_ttl(),
1156 }
1157 }
1158}
1159impl Default for MiddlewareConfig {
1160 fn default() -> Self {
1161 Self {
1162 request_id: false,
1163 request_log: false,
1164 request_log_config: RequestLogConfig::default(),
1165 auth: AuthMiddlewareConfig::default(),
1166 cors: CorsConfig::default(),
1167 compression: CompressConfig::default(),
1168 rate_limit: RateLimitConfig::default(),
1169 security_headers: SecurityHeadersConfig::default(),
1170 permission: PermissionConfig::default(),
1171 nonce: NonceConfig::default(),
1172 audit: AuditMiddlewareConfig::default(),
1173 tenant_header: default_tenant_header(),
1174 }
1175 }
1176}
1177impl Default for RequestLogConfig {
1178 fn default() -> Self {
1179 Self {
1180 exclude_paths: vec![],
1181 log_duration: true,
1182 print_body: false,
1183 report_multiline: false,
1184 }
1185 }
1186}
1187impl Default for AuthMiddlewareConfig {
1188 fn default() -> Self {
1189 Self {
1190 enabled: false,
1191 ignore_paths: vec![],
1192 api_prefixes: default_api_prefixes(),
1193 session_ttl_secs: default_session_ttl(),
1194 access_token_expire_secs: default_access_token_expire(),
1195 refresh_token_expire_secs: default_refresh_token_expire(),
1196 }
1197 }
1198}
1199impl Default for CorsConfig {
1200 fn default() -> Self {
1201 Self {
1202 enabled: false,
1203 allow_origins: vec![],
1204 allow_methods: vec![],
1205 allow_headers: vec![],
1206 allow_credentials: false,
1210 max_age_secs: default_cors_max_age(),
1211 }
1212 }
1213}
1214impl Default for CompressConfig {
1215 fn default() -> Self {
1216 Self {
1217 enabled: false,
1218 level: default_compress_level(),
1219 }
1220 }
1221}
1222impl Default for RateLimitConfig {
1223 fn default() -> Self {
1224 Self {
1225 enabled: false,
1226 requests_per_window: default_rate_limit_requests(),
1227 window_secs: default_rate_limit_window(),
1228 trust_xff: false,
1229 trusted_proxies: vec![],
1230 }
1231 }
1232}
1233impl Default for SecurityHeadersConfig {
1234 fn default() -> Self {
1235 Self {
1236 enabled: true,
1237 nosniff: true,
1238 frame_options: true,
1239 hsts: true,
1240 hsts_max_age_secs: default_hsts_max_age(),
1241 hsts_include_subdomains: true,
1242 csp: true,
1243 csp_value: default_csp_value(),
1244 referrer_policy: true,
1245 referrer_policy_value: default_referrer_policy_value(),
1246 permissions_policy: false,
1247 permissions_policy_value: default_permissions_policy_value(),
1248 }
1249 }
1250}
1251impl Default for NotFoundConfig {
1252 fn default() -> Self {
1253 Self {
1254 enabled: true,
1255 message: default_not_found_msg(),
1256 }
1257 }
1258}
1259impl Default for MigrationConfig {
1260 fn default() -> Self {
1261 Self {
1262 enabled: false,
1263 path: default_migration_path(),
1264 auto_migrate: false,
1265 }
1266 }
1267}
1268impl Default for UploadConfig {
1269 fn default() -> Self {
1270 Self {
1271 path: default_upload_path(),
1272 max_size_mb: default_max_size(),
1273 }
1274 }
1275}
1276impl Default for DownloadConfig {
1277 fn default() -> Self {
1278 Self {
1279 path: default_download_path(),
1280 }
1281 }
1282}
1283impl Default for TemplateConfig {
1284 fn default() -> Self {
1285 Self {
1286 path: default_template_path(),
1287 }
1288 }
1289}
1290impl Default for StaticConfig {
1291 fn default() -> Self {
1292 Self {
1293 path: default_static_path(),
1294 enabled: false,
1295 }
1296 }
1297}
1298
1299pub struct ConfigManager {
1303 pub static_config: AppConfig,
1305 pub dynamic: RwLock<HashMap<String, serde_json::Value>>,
1307}
1308
1309impl Clone for ConfigManager {
1310 fn clone(&self) -> Self {
1311 Self {
1313 static_config: self.static_config.clone(),
1314 dynamic: RwLock::new(self.dynamic.read().clone()),
1315 }
1316 }
1317}
1318
1319impl ConfigManager {
1320 pub fn load(config_dir: Option<&str>) -> Self {
1322 let dir = std::env::var("WORDVAL_CONFIG_DIR")
1324 .ok()
1325 .filter(|v| !v.is_empty())
1326 .unwrap_or_else(|| config_dir.unwrap_or("config").to_string());
1327 let profile = detect_profile();
1328
1329 let mut cfg = Self::load_file(&dir, &profile);
1330
1331 merge_env_overrides(&mut cfg);
1333
1334 cfg.normalize_databases();
1336
1337 if let Err(e) = cfg.validate() {
1339 panic!("配置校验失败:{e}");
1340 }
1341
1342 info!(
1343 "配置加载完成 profile={}, listen={}",
1344 cfg.profile, cfg.server.listen
1345 );
1346
1347 Self {
1348 static_config: cfg,
1349 dynamic: RwLock::new(HashMap::new()),
1350 }
1351 }
1352
1353 fn load_file(dir: &str, profile: &str) -> AppConfig {
1354 let base_path = Path::new(dir).join("config.toml");
1357 let mut table = if base_path.exists() {
1358 let content = fs::read_to_string(&base_path)
1361 .unwrap_or_else(|e| panic!("读取配置文件 {} 失败: {e}", base_path.display()));
1362 match toml::from_str::<toml::Table>(&content) {
1363 Ok(t) => t,
1364 Err(e) => panic!("解析配置文件 {} 失败: {e}", base_path.display()),
1365 }
1366 } else {
1367 toml::Table::new()
1368 };
1369
1370 let profile_path = Path::new(dir).join(format!("config-{}.toml", profile));
1373 if profile_path.exists() {
1374 let overlay = fs::read_to_string(&profile_path)
1375 .map_err(|e| e.to_string())
1376 .and_then(|c| toml::from_str::<toml::Table>(&c).map_err(|e| e.to_string()));
1377 match overlay {
1378 Ok(overlay) => table = merge_tables(&table, &overlay),
1379 Err(e) => {
1380 eprintln!(
1383 "wordval-config: profile 配置 {} 解析失败,已跳过: {e}",
1384 profile_path.display()
1385 );
1386 tracing::warn!(
1387 "profile 配置 {} 解析失败,已跳过: {e}",
1388 profile_path.display()
1389 );
1390 }
1391 }
1392 }
1393
1394 let mut cfg: AppConfig = toml::from_str(&table.to_string())
1395 .unwrap_or_else(|e| panic!("解析合并后的配置失败: {e}"));
1396 cfg.profile = profile.to_string();
1397 cfg
1398 }
1399
1400 pub fn get(&self) -> &AppConfig {
1402 &self.static_config
1403 }
1404
1405 pub fn get_dynamic(&self, key: &str) -> Option<serde_json::Value> {
1407 self.dynamic.read().get(key).cloned()
1408 }
1409
1410 pub fn with_dynamic<R>(&self, key: &str, f: impl FnOnce(Option<&serde_json::Value>) -> R) -> R {
1412 let guard = self.dynamic.read();
1413 f(guard.get(key))
1414 }
1415
1416 pub fn normalized_databases(mut self) -> Self {
1421 self.static_config.normalize_databases();
1422 self
1423 }
1424
1425 pub fn set_dynamic(&self, key: &str, value: serde_json::Value) {
1427 self.dynamic.write().insert(key.to_string(), value);
1428 }
1429
1430 pub fn remove_dynamic(&self, key: &str) {
1432 self.dynamic.write().remove(key);
1433 }
1434
1435 pub fn generate_default(dir: &str) -> std::io::Result<()> {
1437 let config_dir = Path::new(dir);
1438 fs::create_dir_all(config_dir)?;
1439
1440 let cfg = AppConfig::default();
1441 let toml_str = toml::to_string_pretty(&cfg)
1442 .map_err(|e| std::io::Error::other(e.to_string()))?;
1443
1444 let header = r#"# Wordval 默认配置文件
1445# 修改后保存即可生效(需重启服务)
1446#
1447# 使用 --gen-config 参数可重新生成此文件到 config/config.toml
1448# 多环境:创建 config/config-dev.toml, config/config-prod.toml
1449# 通过环境变量或命令行 --profile=prod 指定
1450
1451"#;
1452
1453 fs::write(
1454 config_dir.join("config.toml"),
1455 format!("{}{}", header, toml_str),
1456 )?;
1457 info!("默认配置文件已生成到 {}/config.toml", dir);
1458 Ok(())
1459 }
1460}
1461
1462fn merge_tables(base: &toml::Table, overlay: &toml::Table) -> toml::Table {
1468 let mut result = base.clone();
1469 for (key, value) in overlay {
1470 match (result.get_mut(key), value) {
1471 (Some(toml::Value::Table(base_sub)), toml::Value::Table(overlay_sub)) => {
1472 let merged = merge_tables(base_sub, overlay_sub);
1473 result.insert(key.clone(), toml::Value::Table(merged));
1474 }
1475 _ => {
1476 result.insert(key.clone(), value.clone());
1477 }
1478 }
1479 }
1480 result
1481}
1482
1483#[cfg(test)]
1484mod tests {
1485 use super::*;
1486
1487 #[test]
1488 fn test_default_config_serialization() {
1489 let cfg = AppConfig::default();
1490 let toml_str = toml::to_string_pretty(&cfg).unwrap();
1491 assert!(toml_str.contains("listen = \"8023\""));
1492 assert!(toml_str.contains("level = \"info\""));
1493 }
1494}