waratah_geo/lib.rs
1//! Waratah GeoSPARQL v1 plugin: native geo terms, S2 candidate index, and
2//! `geof:sfContains` / `sfWithin` / `sfIntersects` FILTER rewrite.
3//!
4//! One crate implements all four [`waratah_compute::plugin`] hooks — write
5//! ([`GeoWritePlugin`]), encode ([`GeoEncodePlugin`]), plan
6//! ([`GeoPlannerPlugin`]), and execute ([`GeoExecutorPlugin`]) — because
7//! ingest and query constants share one parse/transform/validation path and
8//! the planner/executor own the same payload types.
9//!
10//! Register at compute startup via [`register`]: the binary composes every
11//! plugin crate (geo + temporal) onto ONE
12//! [`waratah_compute::PluginHost`] and installs the composed set exactly
13//! once (`PluginHost::install_process_wide`) — the three `geof:*` custom
14//! functions (residual cache-aware retry plus the ground fallback) land on the
15//! same process custom-function map **before any query is lowered**, so an
16//! unregistered `geof:*` FILTER errors in `split_filter` (`Unsupported`), never plans
17//! wrong. [`install`] remains only as a single-plugin test shim: two
18//! self-installs would silently drop the second plugin (both registries are
19//! first-install-wins).
20//!
21//! v1 boundaries: stored puts require a native indexed form. `Other` CRS,
22//! EMPTY, ill-formed WKT/WKB, and validation failures outside the narrow
23//! `MultiPolygon` contact tolerances are hard errors; query-authored constants
24//! may use the ordinary typed-literal fallback because they create no index
25//! entry. Z/M takes the native blob route (see `encode`'s module docs);
26//! GML/GeoJSON are unparsed; planar `geo` Relate on CRS84 lon/lat is a
27//! documented limitation near the antimeridian and poles.
28
29#![warn(missing_docs)]
30
31mod canonical;
32mod covering;
33mod crs;
34mod encode;
35mod exec;
36mod materialize;
37mod plan;
38mod rebuild;
39mod relate;
40mod validation;
41mod write;
42
43/// Stable plugin id carried by every CustomOp the geo plugin mints.
44pub const PLUGIN_ID: &str = "geosparql";
45
46pub use covering::{
47 CovererConfig, DEFAULT_DENSIFY_STEP_DEG, DENSIFICATION_FIXTURE_HEXAGON_WKT,
48 MIN_DENSIFY_STEP_DEG, WindowQueryShape, coverer_config, covering_estimate_rows,
49 geometry_covering, geometry_envelope, intervals_for_covering, point_leaf_cell,
50 set_coverer_config, should_store_envelope, window_query_shape,
51};
52pub use encode::{GEO_WKB_LITERAL, GEO_WKT_LITERAL, encode_literal, geometry_from_crs84_ewkb};
53pub use exec::{GeoExecutorPlugin, GeoScanPayload, eval_geof_function, geof_custom_functions};
54pub use materialize::materialize_lexical;
55pub use plan::{GEO_SCAN_OP_ID, GeoPlannerPlugin};
56pub use rebuild::{RebuildReport, UpgradeOutcome, postings_for_geo_term, upgrade_outcome};
57pub use write::GeoWritePlugin;
58
59use oxrdf::Literal;
60use waratah_compute::plugin::{EncodePlugin, PluginHost, RegisteredPlugin};
61use waratah_storage::EncodedTerm;
62use waratah_storage::StrHash;
63
64/// Encode/decode hook: datatype map + lexical materialization.
65#[derive(Debug, Default)]
66pub struct GeoEncodePlugin;
67
68impl EncodePlugin for GeoEncodePlugin {
69 fn datatypes(&self) -> &[oxrdf::NamedNode] {
70 static DATATYPES: std::sync::OnceLock<[oxrdf::NamedNode; 2]> = std::sync::OnceLock::new();
71 DATATYPES.get_or_init(encode::geo_datatypes)
72 }
73
74 fn encode_literal(&self, literal: &Literal) -> (EncodedTerm, Vec<(StrHash, Vec<u8>)>) {
75 encode::encode_literal(literal)
76 }
77
78 fn decode_literal(&self, term: &EncodedTerm, payload: Option<&[u8]>) -> Option<String> {
79 match materialize::materialize_lexical(term, payload) {
80 Some(Ok(lexical)) => Some(lexical),
81 // Errors keep the term unresolved (consumers fall back or fail).
82 Some(Err(_)) | None => None,
83 }
84 }
85}
86
87/// Register the geo plugin bundle + the three `geof:*` custom functions on
88/// `host` (the composition point every plugin crate shares; the binary then
89/// installs the composed host exactly once, BEFORE any `QueryEngine` is
90/// constructed). Datatype-IRI claim conflicts and duplicate function IRIs
91/// propagate to the caller — a conflicting plugin set is a deployment error
92/// and must fail at the composition site, not silently no-op at install.
93pub fn register(host: &mut PluginHost) -> Result<(), waratah_compute::ComputeError> {
94 host.register(RegisteredPlugin {
95 id: PLUGIN_ID,
96 write: Some(std::sync::Arc::new(GeoWritePlugin)),
97 encode: Some(std::sync::Arc::new(GeoEncodePlugin)),
98 planner: Some(std::sync::Arc::new(GeoPlannerPlugin)),
99 executor: Some(std::sync::Arc::new(GeoExecutorPlugin)),
100 })?;
101 host.register_functions(geof_custom_functions())
102}
103
104/// Test convenience: install ONLY the geo plugin + `geof:*` custom functions
105/// on the process registries (first install wins; one guarded host install
106/// per process, so repeat calls are no-ops). Production composes every
107/// plugin crate via [`register`] + one
108/// [`waratah_compute::PluginHost::install_process_wide`] instead — a second
109/// plugin's self-install would otherwise be a silent no-op. The ordering
110/// constraint is unchanged: BEFORE any `QueryEngine` is constructed (the
111/// engine installs the plain builtins on first use, which would leave
112/// `geof:*` unregistered — the safe-but-unhelpful `Unsupported` error).
113pub fn install() {
114 static INSTALLED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
115 INSTALLED.get_or_init(|| {
116 let mut host = PluginHost::new();
117 register(&mut host).expect("the geo plugin registers exactly one datatype set");
118 host.install_process_wide();
119 });
120}
121
122/// Blob-id helper for tests and the rebuild path: content-address of EWKB.
123pub fn blob_id_of_ewkb(ewkb: &[u8]) -> StrHash {
124 StrHash::from_bytes(ewkb)
125}
126
127/// Test support: point `PROJ_DATA` at the vendored tree (tests fail closed
128/// when it is missing — no CDN access).
129#[cfg(test)]
130pub(crate) mod test_support {
131 /// Fail the test process when the vendored `proj-data` tree is absent:
132 /// transforms must never silently hit the PROJ CDN.
133 pub(crate) fn require_proj_data() {
134 let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/proj-data");
135 assert!(
136 std::path::Path::new(&dir).join("proj.db").exists(),
137 "vendored proj-data missing at {dir}"
138 );
139 // SAFETY: test startup, before any transform thread spawns.
140 unsafe { std::env::set_var("PROJ_DATA", dir) };
141 unsafe { std::env::set_var("PROJ_NETWORK", "OFF") };
142 }
143}