1use serde::{Deserialize, Serialize};
7use std::path::Path;
8use std::time::Duration;
9
10use crate::core::license::DEFAULT_GRACE_PERIOD_HOURS;
11use crate::error::{ConfigError, PhyTraceResult};
12use crate::models::enums::SourceType;
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct PhyTraceConfig {
17 pub source: SourceConfig,
19
20 #[serde(default)]
22 pub transport: TransportConfig,
23
24 #[serde(default)]
26 pub license: LicenseConfig,
27
28 #[serde(default)]
30 pub buffer: BufferConfig,
31
32 #[serde(default)]
34 pub retry: RetryConfig,
35
36 #[serde(default)]
38 pub provenance: ProvenanceConfig,
39
40 #[serde(default)]
42 pub emitter: EmitterConfig,
43
44 #[serde(default)]
46 pub logging: LoggingConfig,
47
48 #[serde(default)]
50 pub heartbeat: HeartbeatConfig,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60pub struct HeartbeatConfig {
61 #[serde(default = "default_true")]
63 pub enabled: bool,
64 #[serde(default = "default_heartbeat_interval")]
66 pub interval_secs: u64,
67}
68
69impl Default for HeartbeatConfig {
70 fn default() -> Self {
71 Self {
72 enabled: true,
73 interval_secs: default_heartbeat_interval(),
74 }
75 }
76}
77
78fn default_heartbeat_interval() -> u64 {
79 60
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct SourceConfig {
85 pub source_id: String,
87
88 #[serde(default)]
90 pub source_type: SourceType,
91
92 #[serde(skip_serializing_if = "Option::is_none")]
94 pub fleet_id: Option<String>,
95
96 #[serde(skip_serializing_if = "Option::is_none")]
98 pub site_id: Option<String>,
99
100 #[serde(skip_serializing_if = "Option::is_none")]
102 pub organization_id: Option<String>,
103
104 #[serde(default)]
106 pub tags: Vec<String>,
107}
108
109#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct TransportConfig {
112 #[serde(default = "default_transport_type")]
114 pub transport_type: String,
115
116 #[serde(default)]
118 pub endpoint: String,
119
120 #[serde(skip_serializing_if = "Option::is_none")]
122 pub api_key: Option<String>,
123
124 #[serde(default = "default_connect_timeout")]
126 pub connect_timeout_secs: u64,
127
128 #[serde(default = "default_request_timeout")]
130 pub request_timeout_secs: u64,
131
132 #[serde(default = "default_true")]
134 pub tls_verify: bool,
135
136 #[serde(skip_serializing_if = "Option::is_none")]
138 pub ca_cert_path: Option<String>,
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct LicenseConfig {
144 #[serde(skip_serializing_if = "Option::is_none")]
146 pub token: Option<String>,
147
148 #[serde(default = "default_grace_period")]
150 pub grace_period_hours: i64,
151}
152
153impl Default for LicenseConfig {
154 fn default() -> Self {
155 Self {
156 token: None,
157 grace_period_hours: DEFAULT_GRACE_PERIOD_HOURS,
158 }
159 }
160}
161
162fn default_grace_period() -> i64 {
163 DEFAULT_GRACE_PERIOD_HOURS
164}
165
166#[derive(Debug, Clone, Serialize, Deserialize)]
168pub struct BufferConfig {
169 #[serde(default = "default_true")]
171 pub enabled: bool,
172
173 #[serde(default = "default_buffer_path")]
175 pub path: String,
176
177 #[serde(default = "default_max_buffer_size")]
179 pub max_size_bytes: u64,
180
181 #[serde(default = "default_max_age")]
183 pub max_age_secs: u64,
184
185 #[serde(default = "default_flush_interval")]
187 pub flush_interval_secs: u64,
188
189 #[serde(default = "default_batch_size")]
191 pub batch_size: usize,
192
193 #[serde(default = "default_true")]
195 pub compress: bool,
196}
197
198#[derive(Debug, Clone, Serialize, Deserialize)]
200pub struct RetryConfig {
201 #[serde(default = "default_max_retries")]
203 pub max_retries: u32,
204
205 #[serde(default = "default_initial_backoff")]
207 pub initial_backoff_ms: u64,
208
209 #[serde(default = "default_max_backoff")]
211 pub max_backoff_ms: u64,
212
213 #[serde(default = "default_backoff_multiplier")]
215 pub backoff_multiplier: f64,
216
217 #[serde(default = "default_true")]
219 pub jitter: bool,
220}
221
222#[derive(Debug, Clone, Serialize, Deserialize)]
224pub struct ProvenanceConfig {
225 #[serde(default)]
227 pub enabled: bool,
228
229 #[serde(default = "default_algorithm")]
231 pub algorithm: String,
232
233 #[serde(skip_serializing_if = "Option::is_none")]
235 pub key_id: Option<String>,
236
237 #[serde(skip_serializing_if = "Option::is_none")]
239 pub secret_key: Option<String>,
240
241 #[serde(default, skip_serializing_if = "Vec::is_empty")]
245 pub signed_fields: Vec<String>,
246
247 #[serde(default, skip_serializing_if = "Option::is_none")]
251 pub sequence_path: Option<String>,
252
253 #[serde(default)]
255 pub attestation: AttestationConfig,
256
257 #[serde(default)]
259 pub batch_signing: BatchSigningConfig,
260}
261
262#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
268pub struct AttestationConfig {
269 #[serde(default)]
271 pub enabled: bool,
272 #[serde(default = "default_attestation_interval")]
274 pub interval_secs: u64,
275 #[serde(default = "default_pcrs")]
277 pub pcrs: String,
278}
279
280impl Default for AttestationConfig {
281 fn default() -> Self {
282 Self {
283 enabled: false,
284 interval_secs: default_attestation_interval(),
285 pcrs: default_pcrs(),
286 }
287 }
288}
289
290fn default_attestation_interval() -> u64 {
291 3600
292}
293
294fn default_pcrs() -> String {
295 crate::core::signer::DEFAULT_PCRS.to_string()
296}
297
298#[derive(Debug, Clone, Serialize, Deserialize)]
300pub struct EmitterConfig {
301 #[serde(default = "default_emit_interval")]
303 pub interval_ms: u64,
304
305 #[serde(default = "default_true")]
307 pub on_change_enabled: bool,
308
309 #[serde(default = "default_change_threshold")]
311 pub change_threshold: f64,
312}
313
314#[derive(Debug, Clone, Serialize, Deserialize)]
316pub struct LoggingConfig {
317 #[serde(default = "default_log_level")]
319 pub level: String,
320
321 #[serde(default)]
323 pub structured: bool,
324}
325
326fn default_transport_type() -> String {
328 "http".to_string()
329}
330
331fn default_connect_timeout() -> u64 {
332 10
333}
334
335fn default_request_timeout() -> u64 {
336 30
337}
338
339fn default_true() -> bool {
340 true
341}
342
343fn default_buffer_path() -> String {
344 "./phytrace_buffer".to_string()
345}
346
347fn default_max_buffer_size() -> u64 {
348 100 * 1024 * 1024 }
350
351fn default_max_age() -> u64 {
352 86400 }
354
355fn default_flush_interval() -> u64 {
356 5
357}
358
359fn default_batch_size() -> usize {
360 100
361}
362
363fn default_max_retries() -> u32 {
364 5
365}
366
367fn default_initial_backoff() -> u64 {
368 100
369}
370
371fn default_max_backoff() -> u64 {
372 30000
373}
374
375fn default_backoff_multiplier() -> f64 {
376 2.0
377}
378
379fn default_algorithm() -> String {
380 "hmac-sha256".to_string()
381}
382
383fn default_emit_interval() -> u64 {
384 1000
385}
386
387fn default_change_threshold() -> f64 {
388 0.01
389}
390
391fn default_log_level() -> String {
392 "info".to_string()
393}
394
395impl Default for TransportConfig {
396 fn default() -> Self {
397 Self {
398 transport_type: default_transport_type(),
399 endpoint: String::new(),
400 api_key: None,
401 connect_timeout_secs: default_connect_timeout(),
402 request_timeout_secs: default_request_timeout(),
403 tls_verify: true,
404 ca_cert_path: None,
405 }
406 }
407}
408
409impl Default for BufferConfig {
410 fn default() -> Self {
411 Self {
412 enabled: true,
413 path: default_buffer_path(),
414 max_size_bytes: default_max_buffer_size(),
415 max_age_secs: default_max_age(),
416 flush_interval_secs: default_flush_interval(),
417 batch_size: default_batch_size(),
418 compress: true,
419 }
420 }
421}
422
423impl Default for RetryConfig {
424 fn default() -> Self {
425 Self {
426 max_retries: default_max_retries(),
427 initial_backoff_ms: default_initial_backoff(),
428 max_backoff_ms: default_max_backoff(),
429 backoff_multiplier: default_backoff_multiplier(),
430 jitter: true,
431 }
432 }
433}
434
435impl Default for ProvenanceConfig {
436 fn default() -> Self {
437 Self {
438 enabled: false,
439 algorithm: default_algorithm(),
440 key_id: None,
441 secret_key: None,
442 signed_fields: Vec::new(),
443 sequence_path: None,
444 attestation: AttestationConfig::default(),
445 batch_signing: BatchSigningConfig::default(),
446 }
447 }
448}
449
450#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
457pub struct BatchSigningConfig {
458 #[serde(default)]
460 pub enabled: bool,
461 #[serde(default = "default_batch_signing_size")]
463 pub max_size: usize,
464 #[serde(default = "default_batch_signing_latency")]
466 pub max_latency_ms: u64,
467}
468
469impl Default for BatchSigningConfig {
470 fn default() -> Self {
471 Self {
472 enabled: false,
473 max_size: default_batch_signing_size(),
474 max_latency_ms: default_batch_signing_latency(),
475 }
476 }
477}
478
479fn default_batch_signing_size() -> usize {
480 64
481}
482
483fn default_batch_signing_latency() -> u64 {
484 500
485}
486
487impl Default for EmitterConfig {
488 fn default() -> Self {
489 Self {
490 interval_ms: default_emit_interval(),
491 on_change_enabled: true,
492 change_threshold: default_change_threshold(),
493 }
494 }
495}
496
497impl Default for LoggingConfig {
498 fn default() -> Self {
499 Self {
500 level: default_log_level(),
501 structured: false,
502 }
503 }
504}
505
506impl PhyTraceConfig {
507 pub fn new(source_id: impl Into<String>) -> Self {
509 Self {
510 source: SourceConfig {
511 source_id: source_id.into(),
512 source_type: SourceType::default(),
513 fleet_id: None,
514 site_id: None,
515 organization_id: None,
516 tags: Vec::new(),
517 },
518 transport: TransportConfig::default(),
519 license: LicenseConfig::default(),
520 buffer: BufferConfig::default(),
521 retry: RetryConfig::default(),
522 provenance: ProvenanceConfig::default(),
523 emitter: EmitterConfig::default(),
524 logging: LoggingConfig::default(),
525 heartbeat: HeartbeatConfig::default(),
526 }
527 }
528
529 pub fn from_file<P: AsRef<Path>>(path: P) -> PhyTraceResult<Self> {
531 let content = std::fs::read_to_string(path.as_ref())
532 .map_err(|e| ConfigError::FileRead(e.to_string()))?;
533 Self::from_yaml(&content)
534 }
535
536 pub fn from_yaml(yaml: &str) -> PhyTraceResult<Self> {
538 serde_yaml::from_str(yaml).map_err(|e| ConfigError::Parse(e.to_string()).into())
539 }
540
541 pub fn to_yaml(&self) -> PhyTraceResult<String> {
543 serde_yaml::to_string(self).map_err(|e| ConfigError::Parse(e.to_string()).into())
544 }
545
546 pub fn with_env_overrides(mut self) -> Self {
555 if let Ok(source_id) = std::env::var("PHYTRACE_SOURCE_ID") {
556 self.source.source_id = source_id;
557 }
558 if let Ok(endpoint) = std::env::var("PHYTRACE_ENDPOINT") {
559 self.transport.endpoint = endpoint;
560 }
561 if let Ok(api_key) = std::env::var("PHYTRACE_API_KEY") {
562 self.transport.api_key = Some(api_key);
563 }
564 if let Ok(buffer_path) = std::env::var("PHYTRACE_BUFFER_PATH") {
565 self.buffer.path = buffer_path;
566 }
567 if let Ok(sequence_path) = std::env::var("PHYTRACE_SEQUENCE_PATH") {
568 self.provenance.sequence_path = Some(sequence_path);
569 }
570 self
571 }
572
573 pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
575 self.transport.endpoint = endpoint.into();
576 self
577 }
578
579 pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
581 self.transport.api_key = Some(api_key.into());
582 self
583 }
584
585 pub fn with_source_type(mut self, source_type: SourceType) -> Self {
587 self.source.source_type = source_type;
588 self
589 }
590
591 pub fn with_signing(
593 mut self,
594 key_id: impl Into<String>,
595 secret_key: impl Into<String>,
596 ) -> Self {
597 self.provenance.enabled = true;
598 self.provenance.key_id = Some(key_id.into());
599 self.provenance.secret_key = Some(secret_key.into());
600 self
601 }
602
603 pub fn validate(&self) -> Result<(), ConfigError> {
605 if self.source.source_id.is_empty() {
606 return Err(ConfigError::Validation("source_id is required".to_string()));
607 }
608 if self.transport.endpoint.is_empty() && self.transport.transport_type != "mock" {
609 return Err(ConfigError::Validation(
610 "endpoint is required for non-mock transport".to_string(),
611 ));
612 }
613 if self.provenance.enabled && self.provenance.secret_key.is_none() {
614 return Err(ConfigError::Validation(
615 "secret_key is required when provenance is enabled".to_string(),
616 ));
617 }
618 Ok(())
619 }
620
621 pub fn connect_timeout(&self) -> Duration {
623 Duration::from_secs(self.transport.connect_timeout_secs)
624 }
625
626 pub fn request_timeout(&self) -> Duration {
628 Duration::from_secs(self.transport.request_timeout_secs)
629 }
630
631 pub fn emit_interval(&self) -> Duration {
633 Duration::from_millis(self.emitter.interval_ms)
634 }
635}
636
637#[cfg(test)]
638mod tests {
639 use super::*;
640
641 #[test]
642 fn test_config_creation() {
643 let config = PhyTraceConfig::new("robot-001");
644 assert_eq!(config.source.source_id, "robot-001");
645 assert_eq!(config.source.source_type, SourceType::Amr);
646 }
647
648 #[test]
649 fn test_config_builder() {
650 let config = PhyTraceConfig::new("robot-001")
651 .with_endpoint("https://api.phyware.io")
652 .with_api_key("test-key")
653 .with_source_type(SourceType::DeliveryRobot);
654
655 assert_eq!(config.transport.endpoint, "https://api.phyware.io");
656 assert_eq!(config.transport.api_key, Some("test-key".to_string()));
657 assert_eq!(config.source.source_type, SourceType::DeliveryRobot);
658 }
659
660 #[test]
661 fn test_config_yaml_roundtrip() {
662 let config = PhyTraceConfig::new("robot-001").with_endpoint("https://api.phyware.io");
663
664 let yaml = config.to_yaml().unwrap();
665 let parsed = PhyTraceConfig::from_yaml(&yaml).unwrap();
666
667 assert_eq!(parsed.source.source_id, "robot-001");
668 assert_eq!(parsed.transport.endpoint, "https://api.phyware.io");
669 }
670
671 #[test]
672 fn test_config_validation() {
673 let config = PhyTraceConfig {
675 source: SourceConfig {
676 source_id: String::new(),
677 source_type: SourceType::Amr,
678 fleet_id: None,
679 site_id: None,
680 organization_id: None,
681 tags: Vec::new(),
682 },
683 transport: TransportConfig::default(),
684 license: LicenseConfig::default(),
685 buffer: BufferConfig::default(),
686 retry: RetryConfig::default(),
687 provenance: ProvenanceConfig::default(),
688 emitter: EmitterConfig::default(),
689 logging: LoggingConfig::default(),
690 heartbeat: HeartbeatConfig::default(),
691 };
692
693 assert!(config.validate().is_err());
694 }
695
696 #[test]
697 fn test_default_values() {
698 let config = PhyTraceConfig::new("test");
699
700 assert_eq!(config.retry.max_retries, 5);
701 assert_eq!(config.buffer.batch_size, 100);
702 assert!(config.buffer.enabled);
703 assert!(!config.provenance.enabled);
704 }
705}