Skip to main content

waratah_text/
config.rs

1//! Plugin configuration and the config fingerprint.
2//!
3//! `{config-dir}/text.toml` (found through `config_dir::find`, new `TEXT`
4//! entry) or `--with-text`:
5//!
6//! ```toml
7//! enabled = true
8//! analyzer = "en_stem"     # one global analyzer for the `text` field
9//! seed_chars = 16          # chars stored in text_begin / text_end
10//! predicates = [           # optional allowlist; ABSENT = the built-in list
11//!   "https://schema.org/name",   # below; an explicit [] = every predicate
12//!   "https://schema.org/description",
13//! ]
14//! ```
15//!
16//! With no `predicates` key, the built-in
17//! [`DEFAULT_TEXT_PREDICATES`] list applies (labels, names, descriptions,
18//! definitions, titles, keywords, FOAF names, Schema.org text). That is the
19//! useful default: it keeps a common-word drain out of identifiers, URLs, and
20//! dates. `predicates = []` restores the index-everything behaviour.
21//!
22//! Disabled by default: the plugin still indexes every *allowlisted* string
23//! literal, so always-on would change the write latency and disk baseline of
24//! every deployment. Changing `analyzer`, `seed_chars`, or `predicates`
25//! changes the fingerprint and requires an offline rebuild (stop, delete the
26//! index directory, start).
27
28use waratah_storage::text_index::{
29    ANALYZERS, DEFAULT_ANALYZER, DEFAULT_SEED_CHARS, MAX_SEED_CHARS, registered_analyzer,
30};
31
32/// Analyzer menu value for the analyzed `text` field.
33pub const FINGERPRINT_PREFIX: &str = "text-index-v2";
34
35/// The built-in predicate allowlist used when `text.toml` does not set
36/// `predicates`.
37///
38/// These are the well-known "human text" predicates: labels, names,
39/// descriptions, definitions, titles, keywords, and person/org names. A
40/// deployment that wants the old index-everything behaviour sets
41/// `predicates = []`; one that wants a narrower set lists its own IRIs.
42///
43/// The list is deliberately conservative about what counts as searchable
44/// prose: identifiers, URLs, dates, and opaque values are absent, which is
45/// what keeps a common-word drain from pulling in an unrelated vocabulary.
46pub const DEFAULT_TEXT_PREDICATES: &[&str] = &[
47    // RDFS
48    "http://www.w3.org/2000/01/rdf-schema#label",
49    "http://www.w3.org/2000/01/rdf-schema#comment",
50    // SKOS labels and definitions
51    "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    // Dublin Core terms
58    "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    // Schema.org (https, the current namespace)
63    "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    // Dataset keywords
70    "http://www.w3.org/ns/dcat#keyword",
71    // FOAF names
72    "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/// Plugin configuration.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct TextPluginConfig {
88    /// Whether the index is maintained. The enablement switch: a config
89    /// file may be parked on disk with `enabled = false` without
90    /// uninstalling the plugin at the composition site.
91    pub enabled: bool,
92    /// Analyzer for the full-text field (one menu entry of [`ANALYZERS`]).
93    pub analyzer: String,
94    /// Characters stored in the bounded prefix and suffix fields.
95    pub seed_chars: usize,
96    /// Optional allowlist of predicate IRIs to index. Absent in `text.toml`
97    /// means [`DEFAULT_TEXT_PREDICATES`]; an explicit empty array (`[]`)
98    /// means every string-literal predicate (the old behaviour); a populated
99    /// list keeps the index to the predicates an application actually
100    /// searches (`sdo:name`, `sdo:description`, …) and skips the rest at
101    /// write time.
102    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    /// Reject values the index engine cannot honour.
118    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    /// The predicate allowlist as a canonical, sorted, deduplicated list.
144    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    /// The allowlist as IRI hashes, or `None` when every predicate is indexed.
152    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    /// Canonical, version-stable identity of the schema-affecting settings.
168    ///
169    /// Carried in `RebuildTextIndexRequest` and compared against the
170    /// partition's `Describe` at startup and against the
171    /// `QueryContext::text_index_fingerprint` at plan time. Human-readable
172    /// on purpose (it appears in `waratah text status`), and not a hash, so
173    /// a collision cannot silently trust an index built by other settings.
174    ///
175    /// The predicate list is comma-separated, and a comma is legal inside an
176    /// IRI (`http://ex/a,b`), so each IRI escapes `%` and then `,` before the
177    /// join. Without that, `["http://ex/a,b"]` and `["http://ex/a",
178    /// "http://ex/b"]` would produce the same fingerprint, and an index built
179    /// for one list would be trusted by the other.
180    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    /// Parse a TOML document into a validated config.
200    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        // A parked config with enabled = false validates but stays off.
264        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        // An explicit empty array opts into every predicate.
303        let all = TextPluginConfig::from_toml("predicates = []\n").unwrap();
304        assert!(all.predicate_allowlist().is_none());
305        assert!(!all.fingerprint().contains("predicates="));
306        // Canonical order regardless of input order.
307        let mut reordered = listed.clone();
308        reordered.predicates.reverse();
309        assert_eq!(listed.fingerprint(), reordered.fingerprint());
310        // A non-IRI is rejected.
311        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        // A comma is legal inside an IRI, so the list encoding must escape the
322        // separator: otherwise these two configs share a fingerprint and each
323        // would adopt the other's index.
324        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        // And the escape itself is escaped, so a literal `%2C` in an IRI does
337        // not collide with an escaped comma.
338        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        // The current schema.org namespace is https, never the legacy http.
360        assert!(
361            !DEFAULT_TEXT_PREDICATES
362                .iter()
363                .any(|predicate| predicate.starts_with("http://schema.org/"))
364        );
365    }
366}