Skip to main content

waratah_text/
write.rs

1//! Write hook: one `TextIndexDoc` per distinct `(predicate, literal)` pair of
2//! a batch.
3//!
4//! Runs on ingest AND offline import, before the hexastore RPC (the compute
5//! write path sends the documents ahead of the three axis `InsertQuads`
6//! calls — the C3 ordering). Term encoding must match what the O partition
7//! stores exactly: the compute write path encodes the same quad, and the
8//! geo/temporal plugins never rewrite plain string literals, so encoding
9//! the raw object literal here is the canonical term.
10
11use std::collections::HashSet;
12
13use waratah_compute::ComputeError;
14use waratah_compute::plugin::{PreparedInsert, WritePlugin};
15use waratah_storage::{CommitTs, EncodedTerm, StorageOp, StrHash, TextIndexDoc, encode_term_bytes};
16
17/// Datatype IRIs that are text: `xsd:string` and `rdf:langString`.
18const XSD_STRING: &str = "http://www.w3.org/2001/XMLSchema#string";
19const RDF_LANGSTRING: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString";
20
21/// Write-path hook building text-index documents.
22///
23/// `allow` is the optional predicate allowlist from `text.toml`: when set,
24/// string literals under any other predicate are not indexed at all. The
25/// document identity is `(predicate, literal)`, so the same literal under two
26/// allowed predicates produces two documents.
27///
28/// There is deliberately no `Default`: an implicit construction would index
29/// every predicate, while the plugin's own default config indexes the built-in
30/// text-predicate list. Every caller states its policy through [`Self::new`].
31#[derive(Debug)]
32pub struct TextWritePlugin {
33    allow: Option<HashSet<StrHash>>,
34}
35
36impl TextWritePlugin {
37    /// Build the hook from the config's predicate allowlist (empty = all).
38    pub fn new(predicates: &[String]) -> Self {
39        let allow = if predicates.is_empty() {
40            None
41        } else {
42            Some(predicates.iter().map(|p| StrHash::new(p)).collect())
43        };
44        Self { allow }
45    }
46
47    fn predicate_indexed(&self, predicate: &oxrdf::NamedNode) -> bool {
48        self.allow
49            .as_ref()
50            .is_none_or(|allow| allow.contains(&StrHash::new(predicate.as_str())))
51    }
52}
53
54/// Whether this literal's datatype is one of the indexed families
55/// (`xsd:string` / `rdf:langString` only — IRIs, numbers, dates, and plugin
56/// datatypes are not text).
57pub fn is_text_datatype(datatype: &str) -> bool {
58    datatype == XSD_STRING || datatype == RDF_LANGSTRING
59}
60
61/// The encoded term for a text literal, shared by the write hook and the
62/// rebuild walk (which mints the same term from the resolved lexical).
63#[allow(dead_code)] // used by the rebuild driver shell in waratah_bin
64pub fn encode_text_literal(lexical: &str, language: Option<&str>) -> EncodedTerm {
65    match language {
66        Some(language) => EncodedTerm::from(
67            &oxrdf::Literal::new_language_tagged_literal_unchecked(lexical, language),
68        ),
69        None => EncodedTerm::from(&oxrdf::Literal::new_simple_literal(lexical)),
70    }
71}
72
73impl WritePlugin for TextWritePlugin {
74    fn prepare_insert(
75        &self,
76        quads: &[oxrdf::Quad],
77        _commit_ts: CommitTs,
78        _op: StorageOp,
79    ) -> Result<PreparedInsert, ComputeError> {
80        // One document per distinct `(predicate, literal)` pair: the same
81        // pair in several quads of one batch posts once. Documents are never
82        // retracted on delete; the rebuild is the only cleaner.
83        let mut seen: HashSet<Vec<u8>> = HashSet::new();
84        let mut docs: Vec<TextIndexDoc> = Vec::new();
85        for quad in quads {
86            let oxrdf::Term::Literal(literal) = &quad.object else {
87                continue;
88            };
89            if !is_text_datatype(literal.datatype().as_str()) {
90                continue;
91            }
92            if !self.predicate_indexed(&quad.predicate) {
93                continue;
94            }
95            let term_bytes = encode_term_bytes(&EncodedTerm::from(literal));
96            let predicate_bytes = encode_term_bytes(&EncodedTerm::from(&quad.predicate));
97            if !seen.insert(waratah_storage::text_index::text_index_key(
98                &predicate_bytes,
99                &term_bytes,
100            )) {
101                continue;
102            }
103            docs.push(TextIndexDoc {
104                term: term_bytes,
105                predicate: predicate_bytes,
106                lexical: literal.value().to_owned(),
107                language: literal.language().map(str::to_owned),
108            });
109        }
110        Ok(PreparedInsert {
111            text_docs: docs,
112            ..PreparedInsert::default()
113        })
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120    use oxrdf::{Literal, NamedNode, Quad, Term};
121
122    fn quad(object: Term) -> Quad {
123        Quad::new(
124            NamedNode::new_unchecked("http://ex/s"),
125            NamedNode::new_unchecked("http://ex/p"),
126            object,
127            // RDF unnamed graph.
128            oxrdf::GraphName::DefaultGraph,
129        )
130    }
131
132    fn quad_p(predicate: &str, object: Term) -> Quad {
133        Quad::new(
134            NamedNode::new_unchecked("http://ex/s"),
135            NamedNode::new_unchecked(predicate),
136            object,
137            oxrdf::GraphName::DefaultGraph,
138        )
139    }
140
141    #[test]
142    fn the_same_literal_under_two_predicates_posts_twice() {
143        let quads = vec![
144            quad_p(
145                "http://ex/a",
146                Term::Literal(Literal::new_simple_literal("report")),
147            ),
148            quad_p(
149                "http://ex/b",
150                Term::Literal(Literal::new_simple_literal("report")),
151            ),
152        ];
153        let prepared = TextWritePlugin::new(&[])
154            .prepare_insert(&quads, CommitTs(1), StorageOp::Put)
155            .unwrap();
156        assert_eq!(
157            prepared.text_docs.len(),
158            2,
159            "one document per (predicate, literal)"
160        );
161        assert_ne!(
162            prepared.text_docs[0].predicate, prepared.text_docs[1].predicate,
163            "the predicates are the distinguishing half of the identity"
164        );
165    }
166
167    #[test]
168    fn the_predicate_allowlist_filters_at_the_source() {
169        let quads = vec![
170            quad_p(
171                "http://ex/name",
172                Term::Literal(Literal::new_simple_literal("report")),
173            ),
174            quad_p(
175                "http://ex/url",
176                Term::Literal(Literal::new_simple_literal("report")),
177            ),
178        ];
179        let plugin = TextWritePlugin::new(&["http://ex/name".to_owned()]);
180        let prepared = plugin
181            .prepare_insert(&quads, CommitTs(1), StorageOp::Put)
182            .unwrap();
183        assert_eq!(
184            prepared.text_docs.len(),
185            1,
186            "the excluded predicate never reaches the index"
187        );
188        // An empty allowlist indexes every predicate.
189        let prepared = TextWritePlugin::new(&[])
190            .prepare_insert(&quads, CommitTs(1), StorageOp::Put)
191            .unwrap();
192        assert_eq!(prepared.text_docs.len(), 2);
193    }
194
195    #[test]
196    fn string_and_lang_literals_become_documents() {
197        let quads = vec![
198            quad(Term::Literal(Literal::new_simple_literal("hello world"))),
199            quad(Term::Literal(
200                Literal::new_language_tagged_literal_unchecked("bonjour", "fr"),
201            )),
202            quad(Term::Literal(Literal::new_typed_literal(
203                "42",
204                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#integer"),
205            ))),
206            quad(Term::NamedNode(NamedNode::new_unchecked("http://ex/iri"))),
207        ];
208        let prepared = TextWritePlugin::new(&[])
209            .prepare_insert(&quads, CommitTs(1), StorageOp::Put)
210            .unwrap();
211        assert_eq!(
212            prepared.text_docs.len(),
213            2,
214            "integers and IRIs are not text"
215        );
216        assert_eq!(prepared.text_docs[0].lexical, "hello world");
217        assert_eq!(prepared.text_docs[0].language, None);
218        assert_eq!(prepared.text_docs[1].lexical, "bonjour");
219        assert_eq!(prepared.text_docs[1].language.as_deref(), Some("fr"));
220    }
221
222    #[test]
223    fn repeated_literals_dedupe_within_a_batch() {
224        let quads = vec![
225            quad(Term::Literal(Literal::new_simple_literal("dup"))),
226            quad(Term::Literal(Literal::new_simple_literal("dup"))),
227            quad(Term::Literal(
228                Literal::new_language_tagged_literal_unchecked("dup", "en"),
229            )),
230        ];
231        let prepared = TextWritePlugin::new(&[])
232            .prepare_insert(&quads, CommitTs(1), StorageOp::Put)
233            .unwrap();
234        assert_eq!(
235            prepared.text_docs.len(),
236            2,
237            "same lexical + language posts once; a language tag makes a distinct term"
238        );
239    }
240
241    #[test]
242    fn documents_encode_the_same_term_the_hexastore_stores() {
243        let literal = Literal::new_simple_literal("aligned");
244        let quads = vec![quad(Term::Literal(literal.clone()))];
245        let prepared = TextWritePlugin::new(&[])
246            .prepare_insert(&quads, CommitTs(1), StorageOp::Put)
247            .unwrap();
248        let expected = encode_term_bytes(&EncodedTerm::from(&literal));
249        assert_eq!(prepared.text_docs[0].term, expected);
250        assert!(matches!(
251            EncodedTerm::from(&literal),
252            EncodedTerm::SmallStringLiteral(_) | EncodedTerm::BigStringLiteral { .. }
253        ));
254    }
255}