Skip to main content

phytrace_sdk/core/
config.rs

1//! Configuration management for PhyTrace SDK.
2//!
3//! Supports loading configuration from YAML files, environment variables,
4//! or programmatic construction.
5
6use 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/// Main SDK configuration.
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct PhyTraceConfig {
17    /// Source configuration.
18    pub source: SourceConfig,
19
20    /// Transport configuration.
21    #[serde(default)]
22    pub transport: TransportConfig,
23
24    /// License configuration.
25    #[serde(default)]
26    pub license: LicenseConfig,
27
28    /// Buffer configuration.
29    #[serde(default)]
30    pub buffer: BufferConfig,
31
32    /// Retry configuration.
33    #[serde(default)]
34    pub retry: RetryConfig,
35
36    /// Provenance configuration.
37    #[serde(default)]
38    pub provenance: ProvenanceConfig,
39
40    /// Emitter configuration.
41    #[serde(default)]
42    pub emitter: EmitterConfig,
43
44    /// Logging configuration.
45    #[serde(default)]
46    pub logging: LoggingConfig,
47
48    /// Liveness heartbeats.
49    #[serde(default)]
50    pub heartbeat: HeartbeatConfig,
51}
52
53/// Liveness heartbeat settings (issue #402).
54///
55/// The agent sends a signed `system_heartbeat` event every `interval_secs`.
56/// Heartbeats are buffered and retried like other events, so PhyCloud can
57/// tell a device that was offline (heartbeats delivered late) from one that
58/// was off or removed (none captured).
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60pub struct HeartbeatConfig {
61    /// Send heartbeats.
62    #[serde(default = "default_true")]
63    pub enabled: bool,
64    /// Seconds between heartbeats.
65    #[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/// Source identification configuration.
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct SourceConfig {
85    /// Unique source identifier (e.g., robot ID).
86    pub source_id: String,
87
88    /// Type of source.
89    #[serde(default)]
90    pub source_type: SourceType,
91
92    /// Fleet identifier (optional).
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub fleet_id: Option<String>,
95
96    /// Site identifier (optional).
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub site_id: Option<String>,
99
100    /// Organization identifier (optional).
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub organization_id: Option<String>,
103
104    /// Additional tags.
105    #[serde(default)]
106    pub tags: Vec<String>,
107}
108
109/// Transport layer configuration.
110#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct TransportConfig {
112    /// Transport type (http, grpc, mqtt, etc.).
113    #[serde(default = "default_transport_type")]
114    pub transport_type: String,
115
116    /// Base URL for the API endpoint.
117    #[serde(default)]
118    pub endpoint: String,
119
120    /// API key for authentication.
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub api_key: Option<String>,
123
124    /// Connection timeout in seconds.
125    #[serde(default = "default_connect_timeout")]
126    pub connect_timeout_secs: u64,
127
128    /// Request timeout in seconds.
129    #[serde(default = "default_request_timeout")]
130    pub request_timeout_secs: u64,
131
132    /// Enable TLS verification.
133    #[serde(default = "default_true")]
134    pub tls_verify: bool,
135
136    /// Custom CA certificate path (optional).
137    #[serde(skip_serializing_if = "Option::is_none")]
138    pub ca_cert_path: Option<String>,
139}
140
141/// License configuration.
142#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct LicenseConfig {
144    /// JWT license token from PhyWare customer portal.
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub token: Option<String>,
147
148    /// Grace period in hours (default 72).
149    #[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/// Buffer configuration for offline/reliability.
167#[derive(Debug, Clone, Serialize, Deserialize)]
168pub struct BufferConfig {
169    /// Enable buffering.
170    #[serde(default = "default_true")]
171    pub enabled: bool,
172
173    /// Buffer directory path.
174    #[serde(default = "default_buffer_path")]
175    pub path: String,
176
177    /// Maximum buffer size in bytes.
178    #[serde(default = "default_max_buffer_size")]
179    pub max_size_bytes: u64,
180
181    /// Maximum age of buffered events in seconds.
182    #[serde(default = "default_max_age")]
183    pub max_age_secs: u64,
184
185    /// Flush interval in seconds.
186    #[serde(default = "default_flush_interval")]
187    pub flush_interval_secs: u64,
188
189    /// Maximum events per batch.
190    #[serde(default = "default_batch_size")]
191    pub batch_size: usize,
192
193    /// Enable compression for buffered data.
194    #[serde(default = "default_true")]
195    pub compress: bool,
196}
197
198/// Retry configuration.
199#[derive(Debug, Clone, Serialize, Deserialize)]
200pub struct RetryConfig {
201    /// Maximum retry attempts.
202    #[serde(default = "default_max_retries")]
203    pub max_retries: u32,
204
205    /// Initial backoff delay in milliseconds.
206    #[serde(default = "default_initial_backoff")]
207    pub initial_backoff_ms: u64,
208
209    /// Maximum backoff delay in milliseconds.
210    #[serde(default = "default_max_backoff")]
211    pub max_backoff_ms: u64,
212
213    /// Backoff multiplier.
214    #[serde(default = "default_backoff_multiplier")]
215    pub backoff_multiplier: f64,
216
217    /// Add jitter to backoff.
218    #[serde(default = "default_true")]
219    pub jitter: bool,
220}
221
222/// Provenance (signing) configuration.
223#[derive(Debug, Clone, Serialize, Deserialize)]
224pub struct ProvenanceConfig {
225    /// Enable event signing.
226    #[serde(default)]
227    pub enabled: bool,
228
229    /// Signing algorithm.
230    #[serde(default = "default_algorithm")]
231    pub algorithm: String,
232
233    /// Key ID.
234    #[serde(skip_serializing_if = "Option::is_none")]
235    pub key_id: Option<String>,
236
237    /// Secret key (base64-encoded for HMAC).
238    #[serde(skip_serializing_if = "Option::is_none")]
239    pub secret_key: Option<String>,
240
241    /// No longer supported and must be left empty: signatures always cover
242    /// the whole event.  Kept so that configs that still set it fail with a
243    /// clear error instead of having the list silently ignored.
244    #[serde(default, skip_serializing_if = "Vec::is_empty")]
245    pub signed_fields: Vec<String>,
246
247    /// State file that keeps provenance sequence numbers increasing across
248    /// restarts.  Unset: an in-memory counter that restarts from 1, for
249    /// development only.
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub sequence_path: Option<String>,
252
253    /// Device attestation in each event's provenance (issue #453).
254    #[serde(default)]
255    pub attestation: AttestationConfig,
256
257    /// Merkle batch signing (issue #392).
258    #[serde(default)]
259    pub batch_signing: BatchSigningConfig,
260}
261
262/// Device attestation settings.
263///
264/// With a TPM signer, the agent quotes the TPM's PCRs over a PhyCloud
265/// nonce at start and every `interval_secs`, and each event references the
266/// latest quote; without one, the block is marked `mode: software`.
267#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
268pub struct AttestationConfig {
269    /// Add `device_attestation` to each event's provenance.
270    #[serde(default)]
271    pub enabled: bool,
272    /// Seconds between TPM quotes.
273    #[serde(default = "default_attestation_interval")]
274    pub interval_secs: u64,
275    /// PCR selection to quote, e.g. `sha256:0,1,2,3,4,5,6,7`.
276    #[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/// Emitter configuration.
299#[derive(Debug, Clone, Serialize, Deserialize)]
300pub struct EmitterConfig {
301    /// Default emission interval in milliseconds.
302    #[serde(default = "default_emit_interval")]
303    pub interval_ms: u64,
304
305    /// Enable on-change detection.
306    #[serde(default = "default_true")]
307    pub on_change_enabled: bool,
308
309    /// Minimum change threshold for on-change emission.
310    #[serde(default = "default_change_threshold")]
311    pub change_threshold: f64,
312}
313
314/// Logging configuration.
315#[derive(Debug, Clone, Serialize, Deserialize)]
316pub struct LoggingConfig {
317    /// Log level (trace, debug, info, warn, error).
318    #[serde(default = "default_log_level")]
319    pub level: String,
320
321    /// Enable structured logging.
322    #[serde(default)]
323    pub structured: bool,
324}
325
326// Default value functions
327fn 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 // 100 MB
349}
350
351fn default_max_age() -> u64 {
352    86400 // 24 hours
353}
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/// Merkle batch signing settings (issue #392).
451///
452/// A TPM makes roughly 5-50 signatures per second.  With batch signing
453/// the agent collects up to `max_size` events (or what arrived within
454/// `max_latency_ms`), hashes them into a Merkle tree and signs only the
455/// root, once per batch; each event carries its inclusion proof.
456#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
457pub struct BatchSigningConfig {
458    /// Sign events in Merkle batches instead of one by one.
459    #[serde(default)]
460    pub enabled: bool,
461    /// Most events per batch.
462    #[serde(default = "default_batch_signing_size")]
463    pub max_size: usize,
464    /// Longest an event waits for its batch to be signed.
465    #[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    /// Create a minimal configuration with required fields.
508    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    /// Load configuration from a YAML file.
530    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    /// Parse configuration from YAML string.
537    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    /// Serialize configuration to YAML string.
542    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    /// Apply environment variable overrides.
547    ///
548    /// Supported environment variables:
549    /// - PHYTRACE_SOURCE_ID
550    /// - PHYTRACE_ENDPOINT
551    /// - PHYTRACE_API_KEY
552    /// - PHYTRACE_BUFFER_PATH
553    /// - PHYTRACE_SEQUENCE_PATH
554    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    /// Set the transport endpoint.
574    pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
575        self.transport.endpoint = endpoint.into();
576        self
577    }
578
579    /// Set the API key.
580    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    /// Set the source type.
586    pub fn with_source_type(mut self, source_type: SourceType) -> Self {
587        self.source.source_type = source_type;
588        self
589    }
590
591    /// Enable provenance signing with a secret key.
592    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    /// Validate the configuration.
604    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    /// Get connect timeout as Duration.
622    pub fn connect_timeout(&self) -> Duration {
623        Duration::from_secs(self.transport.connect_timeout_secs)
624    }
625
626    /// Get request timeout as Duration.
627    pub fn request_timeout(&self) -> Duration {
628        Duration::from_secs(self.transport.request_timeout_secs)
629    }
630
631    /// Get emit interval as Duration.
632    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        // Missing source_id
674        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}