systemprompt_content/config/
validated.rs1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3use systemprompt_identifiers::{CategoryId, SourceId};
4use systemprompt_models::{
5 Category, ContentConfigError, ContentConfigErrors, ContentConfigRaw, ContentRouting,
6 ContentSourceConfigRaw, IndexingConfig, Metadata, SitemapConfig, SourceBranding,
7};
8
9const SOURCE_WEB: &str = "web";
10const SOURCE_UNKNOWN: &str = "unknown";
11
12#[derive(Debug, Clone)]
13pub struct ContentConfigValidated {
14 content_sources: HashMap<String, ContentSourceConfigValidated>,
15 metadata: Metadata,
16 categories: HashMap<String, Category>,
17 base_path: PathBuf,
18}
19
20#[derive(Debug, Clone)]
21pub struct ContentSourceConfigValidated {
22 pub path: PathBuf,
23 pub source_id: SourceId,
24 pub category_id: CategoryId,
25 pub enabled: bool,
26 pub description: String,
27 pub allowed_content_types: Vec<String>,
28 pub indexing: IndexingConfig,
29 pub sitemap: Option<SitemapConfig>,
30 pub branding: Option<SourceBranding>,
31}
32
33pub type ValidationResult = Result<ContentConfigValidated, ContentConfigErrors>;
34
35impl ContentConfigValidated {
36 pub fn from_raw(raw: ContentConfigRaw, base_path: PathBuf) -> ValidationResult {
37 let mut errors = ContentConfigErrors::new();
38
39 let categories = validate_categories(&raw.categories, &mut errors);
40 let content_sources = validate_sources(&raw, &categories, &base_path, &mut errors);
41
42 errors.into_result(Self {
43 content_sources,
44 metadata: raw.metadata,
45 categories,
46 base_path,
47 })
48 }
49
50 pub const fn content_sources(&self) -> &HashMap<String, ContentSourceConfigValidated> {
51 &self.content_sources
52 }
53
54 pub const fn metadata(&self) -> &Metadata {
55 &self.metadata
56 }
57
58 pub const fn categories(&self) -> &HashMap<String, Category> {
59 &self.categories
60 }
61
62 pub const fn base_path(&self) -> &PathBuf {
63 &self.base_path
64 }
65
66 pub fn is_html_page(&self, path: &str) -> bool {
67 if path == "/" {
68 return true;
69 }
70
71 self.content_sources
72 .values()
73 .filter(|source| source.enabled)
74 .filter_map(|source| source.sitemap.as_ref())
75 .filter(|sitemap| sitemap.enabled)
76 .any(|sitemap| Self::matches_url_pattern(&sitemap.url_pattern, path))
77 }
78
79 fn matches_url_pattern(pattern: &str, path: &str) -> bool {
80 let pattern_parts: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect();
81 let path_parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
82
83 if pattern_parts.len() != path_parts.len() {
84 return false;
85 }
86
87 pattern_parts
88 .iter()
89 .zip(path_parts.iter())
90 .all(|(pattern_part, path_part)| *pattern_part == "{slug}" || pattern_part == path_part)
91 }
92
93 pub fn determine_source(&self, path: &str) -> String {
94 if path == "/" {
95 return SOURCE_WEB.to_string();
96 }
97
98 self.content_sources
99 .iter()
100 .filter(|(_, source)| source.enabled)
101 .find_map(|(name, source)| {
102 source.sitemap.as_ref().and_then(|sitemap| {
103 (sitemap.enabled && Self::matches_url_pattern(&sitemap.url_pattern, path))
104 .then(|| name.clone())
105 })
106 })
107 .unwrap_or_else(|| SOURCE_UNKNOWN.to_string())
108 }
109}
110
111impl ContentRouting for ContentConfigValidated {
112 fn is_html_page(&self, path: &str) -> bool {
113 ContentConfigValidated::is_html_page(self, path)
114 }
115
116 fn determine_source(&self, path: &str) -> String {
117 ContentConfigValidated::determine_source(self, path)
118 }
119}
120
121fn validate_categories(
122 raw: &HashMap<String, Category>,
123 errors: &mut ContentConfigErrors,
124) -> HashMap<String, Category> {
125 let mut validated = HashMap::new();
126
127 for (id, cat) in raw {
128 if cat.name.is_empty() {
129 errors.push(ContentConfigError::Validation {
130 field: format!("categories.{id}.name"),
131 message: "Category name cannot be empty".to_string(),
132 suggestion: Some("Provide a non-empty name".to_string()),
133 });
134 continue;
135 }
136 validated.insert(id.clone(), cat.clone());
137 }
138
139 validated
140}
141
142fn validate_sources(
143 raw: &ContentConfigRaw,
144 categories: &HashMap<String, Category>,
145 base_path: &Path,
146 errors: &mut ContentConfigErrors,
147) -> HashMap<String, ContentSourceConfigValidated> {
148 let mut validated = HashMap::new();
149
150 for (name, source) in &raw.content_sources {
151 if let Some(validated_source) =
152 validate_single_source(name, source, categories, base_path, errors)
153 {
154 validated.insert(name.clone(), validated_source);
155 }
156 }
157
158 validated
159}
160
161fn validate_single_source(
162 name: &str,
163 source: &ContentSourceConfigRaw,
164 categories: &HashMap<String, Category>,
165 base_path: &Path,
166 errors: &mut ContentConfigErrors,
167) -> Option<ContentSourceConfigValidated> {
168 let field_prefix = format!("content_sources.{name}");
169
170 if source.path.is_empty() {
171 errors.push(ContentConfigError::Validation {
172 field: format!("{field_prefix}.path"),
173 message: "Source path is required".to_string(),
174 suggestion: Some("Add a path to the content directory".to_string()),
175 });
176 return None;
177 }
178
179 if source.source_id.as_str().is_empty() {
180 errors.push(ContentConfigError::Validation {
181 field: format!("{field_prefix}.source_id"),
182 message: "source_id is required".to_string(),
183 suggestion: Some("Add a unique source_id".to_string()),
184 });
185 return None;
186 }
187
188 if source.category_id.as_str().is_empty() {
189 errors.push(ContentConfigError::Validation {
190 field: format!("{field_prefix}.category_id"),
191 message: "category_id is required".to_string(),
192 suggestion: Some("Add a category_id that references a defined category".to_string()),
193 });
194 return None;
195 }
196
197 if !categories.contains_key(source.category_id.as_str()) {
198 errors.push(ContentConfigError::Validation {
199 field: format!("{field_prefix}.category_id"),
200 message: format!("Referenced category '{}' not found", source.category_id),
201 suggestion: Some("Add this category to the categories section".to_string()),
202 });
203 }
204
205 let resolved_path = if source.path.starts_with('/') {
206 PathBuf::from(&source.path)
207 } else {
208 base_path.join(&source.path)
209 };
210
211 let Ok(canonical_path) = std::fs::canonicalize(&resolved_path) else {
212 errors.push(ContentConfigError::Validation {
213 field: format!("{field_prefix}.path"),
214 message: "Content source directory does not exist".to_string(),
215 suggestion: Some("Create the directory or fix the path".to_string()),
216 });
217 return None;
218 };
219
220 Some(ContentSourceConfigValidated {
221 path: canonical_path,
222 source_id: source.source_id.clone(),
223 category_id: source.category_id.clone(),
224 enabled: source.enabled,
225 description: source.description.clone(),
226 allowed_content_types: source.allowed_content_types.clone(),
227 indexing: source.indexing.unwrap_or(IndexingConfig {
228 clear_before: false,
229 recursive: false,
230 override_existing: false,
231 }),
232 sitemap: source.sitemap.clone(),
233 branding: source.branding.clone(),
234 })
235}