Skip to main content

waratah_geo/
write.rs

1//! WritePlugin: rewrite geo literals into native terms on the insert path.
2//!
3//! Runs **before** hexastore encoding in the write path (and the offline import
4//! twin): every quad whose object is a `geo:wktLiteral` / `geo:wkbLiteral`
5//! gets parsed, CRS84-transformed, validated, and — on success — recorded as
6//! a sparse object rewrite ([`PreparedInsert::object_rewrites`]) to a native
7//! [`EncodedTerm::LiteralPoint`] / [`EncodedTerm::LiteralGeometry`], with
8//! registry blob puts and O-axis geometry-index postings attached. A stored
9//! put that cannot become a native indexed term fails the batch; otherwise a
10//! trusted geo index could silently omit the row. Deletes use rewrite-only
11//! preparation: they derive the native term key without retaining blob
12//! payloads or index postings, and retain the plain typed-literal encoding on
13//! failure so legacy unindexed rows remain deletable. Exactly collinear
14//! zero-area spikes retain their original blob and native term but carry the
15//! spike-reduction flag; accepted spikes produce batch warnings with the
16//! subject and removed-vertex count. The overlay is sparse so the temporal
17//! write plugin composes over the same batch.
18
19use std::sync::Arc;
20
21use waratah_compute::ComputeError;
22use waratah_compute::plugin::{PreparedInsert, WritePlugin};
23use waratah_storage::{CommitTs, StorageOp};
24
25use crate::encode::is_geo_datatype;
26
27/// GeoSPARQL write hook.
28#[derive(Debug, Default)]
29pub struct GeoWritePlugin;
30
31impl WritePlugin for GeoWritePlugin {
32    fn prepare_insert(
33        &self,
34        quads: &[oxrdf::Quad],
35        commit_ts: CommitTs,
36        op: StorageOp,
37    ) -> Result<PreparedInsert, ComputeError> {
38        let mut out = PreparedInsert {
39            object_rewrites: Vec::new(),
40            blobs: Vec::new(),
41            geo_puts: Vec::new(),
42            temporal_puts: Vec::new(),
43            text_docs: Vec::new(),
44            warnings: Vec::new(),
45            spike_reductions: 0,
46        };
47        for (index, quad) in quads.iter().enumerate() {
48            if let oxrdf::Term::Literal(literal) = &quad.object
49                && is_geo_datatype(literal.datatype())
50            {
51                let prepared = match if op == StorageOp::Put {
52                    crate::encode::prepare_geometry_literal(literal)
53                } else {
54                    crate::encode::prepare_geometry_literal_for_rewrite(literal)
55                } {
56                    Ok(prepared) => prepared,
57                    Err(error) if op == StorageOp::Put => {
58                        return Err(ComputeError::InvalidLiteral(format!(
59                            "geo literal at quad {index} (subject {}, predicate {}): {error}",
60                            quad.subject, quad.predicate
61                        )));
62                    }
63                    Err(_) => continue,
64                };
65                if op == StorageOp::Put && prepared.removed_spike_vertices != 0 {
66                    out.spike_reductions += 1;
67                    out.warnings.push(format!(
68                        "geo literal at quad {index} (subject {}, predicate {}) retained a zero-area spike; indexing the reduced geometry after removing {} backtracking {}",
69                        quad.subject,
70                        quad.predicate,
71                        prepared.removed_spike_vertices,
72                        if prepared.removed_spike_vertices == 1 {
73                            "vertex"
74                        } else {
75                            "vertices"
76                        }
77                    ));
78                }
79                // Stamp the batch's commit ts onto the postings; the term
80                // bytes ride every posting (leaf for points, covering cells
81                // for geometries).
82                let term_bytes = waratah_storage::encode_term_bytes(&prepared.term);
83                let mut postings = prepared.postings;
84                for put in &mut postings {
85                    put.commit_ts = commit_ts;
86                    put.term.clone_from(&term_bytes);
87                }
88                // Plugin output shares payloads (`Arc<[u8]>`): the encoder's
89                // owned `Vec<u8>` moves into the Arc — no copy — and the
90                // write path clones the Arc per batch frame / retry / cache
91                // pre-warm.
92                if op == StorageOp::Put {
93                    out.blobs.extend(
94                        prepared
95                            .blobs
96                            .into_iter()
97                            .map(|(blob_id, payload)| (blob_id, Arc::from(payload))),
98                    );
99                    out.geo_puts.extend(postings);
100                }
101                out.object_rewrites.push((index, prepared.term));
102            }
103        }
104        Ok(out)
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111    use oxrdf::{GraphName, Literal, NamedNode, Quad};
112    use waratah_storage::EncodedTerm;
113
114    fn geometry_quad(wkt: &str) -> Quad {
115        Quad::new(
116            NamedNode::new_unchecked("http://ex/s"),
117            NamedNode::new_unchecked("http://ex/hasGeometry"),
118            Literal::new_typed_literal(wkt, NamedNode::new_unchecked(crate::GEO_WKT_LITERAL)),
119            GraphName::DefaultGraph,
120        )
121    }
122
123    #[test]
124    fn delete_prepares_native_rewrite_without_blobs_or_postings() {
125        let quad = geometry_quad("POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))");
126        let prepared = GeoWritePlugin
127            .prepare_insert(std::slice::from_ref(&quad), CommitTs(1), StorageOp::Delete)
128            .unwrap();
129        assert_eq!(prepared.object_rewrites.len(), 1);
130        assert!(matches!(
131            &prepared.object_rewrites[0].1,
132            EncodedTerm::LiteralGeometry { .. }
133        ));
134        assert!(prepared.blobs.is_empty());
135        assert!(prepared.geo_puts.is_empty());
136        assert!(prepared.warnings.is_empty());
137        assert_eq!(prepared.spike_reductions, 0);
138    }
139
140    #[test]
141    fn tolerated_spike_warns_with_subject_and_removed_count() {
142        let quad = geometry_quad("POLYGON((0 0, 2 0, 2 -1, 2 2, 0 2, 0 0))");
143        let prepared = GeoWritePlugin
144            .prepare_insert(std::slice::from_ref(&quad), CommitTs(1), StorageOp::Put)
145            .unwrap();
146        assert_eq!(prepared.warnings.len(), 1);
147        assert_eq!(prepared.spike_reductions, 1);
148        assert!(prepared.warnings[0].contains("http://ex/s"));
149        assert!(prepared.warnings[0].contains("removing 1"));
150        assert!(prepared.object_rewrites[0].1.requires_spike_reduction());
151    }
152
153    #[test]
154    fn invalid_put_returns_an_invalid_literal_error() {
155        let quad = geometry_quad("POLYGON((0 0, 2 2, 2 0, 0 2, 0 0))");
156        let error = GeoWritePlugin
157            .prepare_insert(std::slice::from_ref(&quad), CommitTs(1), StorageOp::Put)
158            .unwrap_err();
159        assert!(matches!(error, ComputeError::InvalidLiteral(_)));
160    }
161}