1use waratah_storage::text_index::{
29 ANALYZERS, DEFAULT_ANALYZER, DEFAULT_SEED_CHARS, MAX_SEED_CHARS, registered_analyzer,
30};
31
32pub const FINGERPRINT_PREFIX: &str = "text-index-v2";
34
35pub const DEFAULT_TEXT_PREDICATES: &[&str] = &[
47 "http://www.w3.org/2000/01/rdf-schema#label",
49 "http://www.w3.org/2000/01/rdf-schema#comment",
50 "http://www.w3.org/2004/02/skos/core#prefLabel",
52 "http://www.w3.org/2004/02/skos/core#altLabel",
53 "http://www.w3.org/2004/02/skos/core#hiddenLabel",
54 "http://www.w3.org/2004/02/skos/core#definition",
55 "http://www.w3.org/2004/02/skos/core#note",
56 "http://www.w3.org/2004/02/skos/core#scopeNote",
57 "http://purl.org/dc/terms/title",
59 "http://purl.org/dc/terms/description",
60 "http://purl.org/dc/terms/abstract",
61 "http://purl.org/dc/terms/subject",
62 "https://schema.org/name",
64 "https://schema.org/alternateName",
65 "https://schema.org/description",
66 "https://schema.org/text",
67 "https://schema.org/headline",
68 "https://schema.org/keywords",
69 "http://www.w3.org/ns/dcat#keyword",
71 "http://xmlns.com/foaf/0.1/name",
73 "http://xmlns.com/foaf/0.1/givenName",
74 "http://xmlns.com/foaf/0.1/familyName",
75 "http://xmlns.com/foaf/0.1/nick",
76];
77
78fn default_predicates() -> Vec<String> {
79 DEFAULT_TEXT_PREDICATES
80 .iter()
81 .map(|predicate| (*predicate).to_owned())
82 .collect()
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct TextPluginConfig {
88 pub enabled: bool,
92 pub analyzer: String,
94 pub seed_chars: usize,
96 pub predicates: Vec<String>,
103}
104
105impl Default for TextPluginConfig {
106 fn default() -> Self {
107 Self {
108 enabled: false,
109 analyzer: DEFAULT_ANALYZER.to_owned(),
110 seed_chars: DEFAULT_SEED_CHARS,
111 predicates: default_predicates(),
112 }
113 }
114}
115
116impl TextPluginConfig {
117 pub fn validate(&self) -> Result<(), String> {
119 if registered_analyzer(&self.analyzer).is_none() {
120 let names: Vec<&str> = ANALYZERS.iter().map(|(name, _)| *name).collect();
121 return Err(format!(
122 "unknown analyzer {:?}; expected one of {}",
123 self.analyzer,
124 names.join(", ")
125 ));
126 }
127 if self.seed_chars == 0 || self.seed_chars > MAX_SEED_CHARS {
128 return Err(format!(
129 "seed_chars must be between 1 and {MAX_SEED_CHARS}, got {}",
130 self.seed_chars
131 ));
132 }
133 for predicate in &self.predicates {
134 if oxrdf::NamedNode::new(predicate).is_err() {
135 return Err(format!(
136 "predicates must be absolute IRIs, got {predicate:?}"
137 ));
138 }
139 }
140 Ok(())
141 }
142
143 pub fn normalized_predicates(&self) -> Vec<&str> {
145 let mut predicates: Vec<&str> = self.predicates.iter().map(String::as_str).collect();
146 predicates.sort_unstable();
147 predicates.dedup();
148 predicates
149 }
150
151 pub fn predicate_allowlist(
153 &self,
154 ) -> Option<std::collections::HashSet<waratah_storage::StrHash>> {
155 let predicates = self.normalized_predicates();
156 if predicates.is_empty() {
157 return None;
158 }
159 Some(
160 predicates
161 .into_iter()
162 .map(waratah_storage::StrHash::new)
163 .collect(),
164 )
165 }
166
167 pub fn fingerprint(&self) -> String {
181 let mut fingerprint = format!(
182 "{FINGERPRINT_PREFIX};analyzer={};seed_chars={}",
183 self.analyzer, self.seed_chars
184 );
185 let predicates = self.normalized_predicates();
186 if !predicates.is_empty() {
187 fingerprint.push_str(";predicates=");
188 fingerprint.push_str(
189 &predicates
190 .iter()
191 .map(|predicate| predicate.replace('%', "%25").replace(',', "%2C"))
192 .collect::<Vec<_>>()
193 .join(","),
194 );
195 }
196 fingerprint
197 }
198
199 pub fn from_toml(text: &str) -> Result<Self, String> {
201 #[derive(serde::Deserialize, Default)]
202 #[serde(deny_unknown_fields)]
203 struct Raw {
204 enabled: Option<bool>,
205 analyzer: Option<String>,
206 seed_chars: Option<usize>,
207 predicates: Option<Vec<String>>,
208 }
209 let raw: Raw = toml::from_str(text).map_err(|error| error.to_string())?;
210 let config = Self {
211 enabled: raw.enabled.unwrap_or(false),
212 analyzer: raw.analyzer.unwrap_or_else(|| DEFAULT_ANALYZER.to_owned()),
213 seed_chars: raw.seed_chars.unwrap_or(DEFAULT_SEED_CHARS),
214 predicates: raw.predicates.unwrap_or_else(default_predicates),
215 };
216 config.validate()?;
217 Ok(config)
218 }
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224
225 #[test]
226 fn defaults_are_disabled_with_the_default_analyzer() {
227 let config = TextPluginConfig::default();
228 assert!(
229 !config.enabled,
230 "the plugin indexes string literals: off by default"
231 );
232 config.validate().unwrap();
233 assert_eq!(
234 config.predicates.len(),
235 DEFAULT_TEXT_PREDICATES.len(),
236 "absent config = the built-in text predicate allowlist"
237 );
238 let fingerprint = config.fingerprint();
239 assert!(fingerprint.starts_with("text-index-v2;analyzer=simple;seed_chars=16;predicates="));
240 assert!(fingerprint.contains("https://schema.org/name"));
241 }
242
243 #[test]
244 fn toml_round_trip_and_rejects() {
245 let parsed = TextPluginConfig::from_toml(
246 "enabled = true\nanalyzer = \"en_stem\"\nseed_chars = 10\n",
247 )
248 .unwrap();
249 assert!(parsed.enabled);
250 assert_eq!(parsed.analyzer, "en_stem");
251 assert_eq!(parsed.seed_chars, 10);
252 assert!(parsed.fingerprint().contains("analyzer=en_stem"));
253 assert!(parsed.fingerprint().contains("seed_chars=10"));
254 assert_eq!(
255 parsed.predicates.len(),
256 DEFAULT_TEXT_PREDICATES.len(),
257 "an absent predicates key means the default allowlist"
258 );
259 assert!(TextPluginConfig::from_toml("seed_chars = 0\n").is_err());
260 assert!(TextPluginConfig::from_toml("seed_chars = 65\n").is_err());
261 assert!(TextPluginConfig::from_toml("analyzer = \"klingon\"\n").is_err());
262 assert!(TextPluginConfig::from_toml("unknown = 1\n").is_err());
263 let parked = TextPluginConfig::from_toml("enabled = false\n").unwrap();
265 assert!(!parked.enabled);
266 }
267
268 #[test]
269 fn fingerprint_covers_the_schema_affecting_settings_only() {
270 let base = TextPluginConfig::default();
271 let mut other = base.clone();
272 other.seed_chars = 10;
273 assert_ne!(base.fingerprint(), other.fingerprint());
274 other.seed_chars = base.seed_chars;
275 other.analyzer = "en_stem".to_owned();
276 assert_ne!(base.fingerprint(), other.fingerprint());
277 other.analyzer = base.analyzer.clone();
278 other.enabled = true;
279 assert_eq!(
280 base.fingerprint(),
281 other.fingerprint(),
282 "enabled is a behaviour switch, not a schema setting"
283 );
284 }
285
286 #[test]
287 fn predicate_allowlist_is_validated_and_changes_the_fingerprint() {
288 let base = TextPluginConfig::default();
289 let mut listed = base.clone();
290 listed.predicates = vec![
291 "https://schema.org/name".to_owned(),
292 "https://schema.org/description".to_owned(),
293 ];
294 listed.validate().unwrap();
295 assert_ne!(base.fingerprint(), listed.fingerprint());
296 assert!(listed.fingerprint().contains("predicates="));
297 assert_eq!(listed.predicate_allowlist().unwrap().len(), 2);
298 assert_eq!(
299 base.predicate_allowlist().unwrap().len(),
300 DEFAULT_TEXT_PREDICATES.len()
301 );
302 let all = TextPluginConfig::from_toml("predicates = []\n").unwrap();
304 assert!(all.predicate_allowlist().is_none());
305 assert!(!all.fingerprint().contains("predicates="));
306 let mut reordered = listed.clone();
308 reordered.predicates.reverse();
309 assert_eq!(listed.fingerprint(), reordered.fingerprint());
310 let mut bad = base.clone();
312 bad.predicates = vec!["not an iri".to_owned()];
313 assert!(bad.validate().is_err());
314 assert!(
315 TextPluginConfig::from_toml("predicates = [\"https://schema.org/name\"]\n").is_ok()
316 );
317 }
318
319 #[test]
320 fn the_predicate_list_encoding_is_injective() {
321 let comma_inside = TextPluginConfig {
325 predicates: vec!["http://ex/a,b".to_owned()],
326 ..TextPluginConfig::default()
327 };
328 comma_inside.validate().unwrap();
329 let two_predicates = TextPluginConfig {
330 predicates: vec!["http://ex/a".to_owned(), "http://ex/b".to_owned()],
331 ..TextPluginConfig::default()
332 };
333 two_predicates.validate().unwrap();
334 assert_ne!(comma_inside.fingerprint(), two_predicates.fingerprint());
335
336 let literal_escape = TextPluginConfig {
339 predicates: vec!["http://ex/a%2Cb".to_owned()],
340 ..TextPluginConfig::default()
341 };
342 literal_escape.validate().unwrap();
343 assert_ne!(comma_inside.fingerprint(), literal_escape.fingerprint());
344 }
345
346 #[test]
347 fn default_allowlist_names_the_well_known_text_predicates() {
348 for iri in [
349 "http://www.w3.org/2000/01/rdf-schema#label",
350 "http://www.w3.org/2004/02/skos/core#prefLabel",
351 "http://purl.org/dc/terms/title",
352 "https://schema.org/name",
353 "https://schema.org/keywords",
354 "http://www.w3.org/ns/dcat#keyword",
355 "http://xmlns.com/foaf/0.1/name",
356 ] {
357 assert!(DEFAULT_TEXT_PREDICATES.contains(&iri), "missing {iri}");
358 }
359 assert!(
361 !DEFAULT_TEXT_PREDICATES
362 .iter()
363 .any(|predicate| predicate.starts_with("http://schema.org/"))
364 );
365 }
366}