1use awp_types::BusinessContext;
4
5#[derive(Debug, thiserror::Error)]
7pub enum AwpConfigError {
8 #[error("failed to read {path}: {source}")]
10 FileRead { path: String, source: std::io::Error },
11
12 #[error("invalid TOML in {path}: {source}")]
14 TomlParse { path: String, source: toml::de::Error },
15
16 #[error("validation error in capability {index}: {field} must not be empty")]
18 ValidationError { index: usize, field: String },
19
20 #[error("file watcher error: {0}")]
22 WatcherError(String),
23
24 #[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
31pub 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 #[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 let parsed: BusinessContext = toml::from_str(&toml_str).unwrap();
106 assert_eq!(ctx, parsed);
107 }
108}