Skip to main content

adk_awp/
config.rs

1//! AWP configuration error types and TOML serialization utilities.
2
3use awp_types::BusinessContext;
4
5/// Errors that can occur when loading or validating AWP configuration.
6#[derive(Debug, thiserror::Error)]
7pub enum AwpConfigError {
8    /// Failed to read a configuration file from disk.
9    #[error("failed to read {path}: {source}")]
10    FileRead { path: String, source: std::io::Error },
11
12    /// The TOML content could not be parsed.
13    #[error("invalid TOML in {path}: {source}")]
14    TomlParse { path: String, source: toml::de::Error },
15
16    /// A capability failed validation (e.g. empty name or endpoint).
17    #[error("validation error in capability {index}: {field} must not be empty")]
18    ValidationError { index: usize, field: String },
19
20    /// An error from the file watcher subsystem.
21    #[error("file watcher error: {0}")]
22    WatcherError(String),
23
24    /// The business context could not be serialized to TOML (spec 3.5 §10 X4).
25    #[error(
26        "failed to serialize the business context to TOML: {0}; TOML integers stop at i64::MAX"
27    )]
28    Serialize(#[source] toml::ser::Error),
29}
30
31/// Serialize a [`BusinessContext`] to a pretty-printed TOML string.
32///
33/// # Errors
34///
35/// Returns [`AwpConfigError::Serialize`] if the context cannot be represented in TOML, such
36/// as a product price above `i64::MAX`.
37///
38/// # Example
39///
40/// ```
41/// use adk_awp::business_context_to_toml;
42/// use awp_types::BusinessContext;
43///
44/// let toml = business_context_to_toml(&BusinessContext::core("Shop", "A shop", "example.com")).unwrap();
45/// assert!(toml.contains("site_name = \"Shop\""));
46/// ```
47pub fn business_context_to_toml(ctx: &BusinessContext) -> Result<String, AwpConfigError> {
48    toml::to_string_pretty(ctx).map_err(AwpConfigError::Serialize)
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54    use awp_types::{BusinessCapability, BusinessPolicy, TrustLevel};
55
56    #[test]
57    fn test_business_context_to_toml_round_trip() {
58        let mut ctx = BusinessContext::core("Test Site", "A test", "example.com");
59        ctx.capabilities = vec![BusinessCapability {
60            name: "read".to_string(),
61            description: "Read data".to_string(),
62            endpoint: "/api/read".to_string(),
63            method: "GET".to_string(),
64            access_level: TrustLevel::Anonymous,
65            input_schema: None,
66            output_schema: None,
67        }];
68        ctx.policies = vec![BusinessPolicy {
69            name: "privacy".to_string(),
70            description: "Privacy policy".to_string(),
71            policy_type: "privacy".to_string(),
72        }];
73        ctx.contact = Some("admin@example.com".to_string());
74
75        let toml_str = business_context_to_toml(&ctx).unwrap();
76        let parsed: BusinessContext = toml::from_str(&toml_str).unwrap();
77        assert_eq!(ctx, parsed);
78    }
79
80    /// Serialization failures have their own variant, not `WatcherError` (spec 3.5 §10 X4).
81    #[test]
82    fn test_business_context_to_toml_reports_serialize_errors() {
83        let mut ctx = BusinessContext::core("Shop", "A shop", "example.com");
84        ctx.products = vec![awp_types::Product {
85            sku: "X".to_string(),
86            name: "Out of TOML range".to_string(),
87            price: u64::MAX,
88            inventory: 0,
89            tags: vec![],
90            description: None,
91        }];
92        let err = business_context_to_toml(&ctx).unwrap_err();
93        assert!(matches!(err, AwpConfigError::Serialize(_)), "{err:?}");
94        assert!(err.to_string().starts_with("failed to serialize the business context to TOML"));
95        assert!(std::error::Error::source(&err).is_some());
96    }
97
98    #[test]
99    fn test_business_context_to_toml_no_contact() {
100        let ctx = BusinessContext::core("Test", "Test", "example.com");
101
102        let toml_str = business_context_to_toml(&ctx).unwrap();
103        assert!(toml_str.contains("site_name"));
104        // Round-trip
105        let parsed: BusinessContext = toml::from_str(&toml_str).unwrap();
106        assert_eq!(ctx, parsed);
107    }
108}