Skip to main content

waratah_api/
backend.rs

1//! Backend trait so the HTTP layer can be tested without a live cluster.
2
3use std::future::Future;
4
5use waratah_compute::{
6    BlobStoreClient, ComputeError, ComputeNode, HexastoreAdmin, HexastoreCatalog, HexastoreFlush,
7    HexastoreGeo, HexastoreInsert, HexastoreScan, HexastoreStats, InsertResult, QueryContext,
8    QueryOutput, QueryResults, RegistryAdmin, StatsProfile, StringRegister, StringRegistryFlush,
9    StringResolve, http_origin,
10};
11use waratah_storage::{CommitTs, Quad, SnapshotId};
12
13/// One static cluster member `/cors_proxy` may forward HTTP to.
14///
15/// Origins are the configured RDF4J and `/waratah` URLs, not a caller-supplied
16/// address and not a live probe.
17#[derive(Debug, Clone)]
18pub struct CorsProxyTarget {
19    /// Compute id from cluster config.
20    pub id: String,
21    /// Origin of the configured RDF4J URL (`http://host:port`).
22    pub rdf4j_origin: String,
23    /// Origin of the configured `/waratah` URL.
24    pub admin_origin: String,
25}
26
27/// Operations the RDF4J facade and Waratah ingest API need from compute.
28pub trait ComputeBackend: Send + Sync {
29    /// Run a SPARQL `SELECT` / `ASK` / `CONSTRUCT` / `DESCRIBE`.
30    fn query(
31        &self,
32        sparql: &str,
33        ctx: &QueryContext,
34    ) -> impl Future<Output = Result<QueryResults, ComputeError>> + Send;
35
36    /// SELECT as encoded rows plus a resolved string map; otherwise [`QueryOutput::Ready`].
37    ///
38    /// Default wraps [`Self::query`] as [`QueryOutput::Ready`] so mocks that
39    /// only implement decoded [`QueryResults`] keep working.
40    fn query_output(
41        &self,
42        sparql: &str,
43        ctx: &QueryContext,
44    ) -> impl Future<Output = Result<QueryOutput, ComputeError>> + Send {
45        let fut = self.query(sparql, ctx);
46        async move { Ok(QueryOutput::Ready(fut.await?)) }
47    }
48
49    /// Count visible quads as of `snapshot`.
50    fn quad_count(
51        &self,
52        snapshot: SnapshotId,
53    ) -> impl Future<Output = Result<u64, ComputeError>> + Send;
54
55    /// Count visible quads across the default graph **and** every named
56    /// graph — the coverage of the ai-context summary and its ETag
57    /// validator (`quad_count` above pins the default graph, RDF4J
58    /// `/size` semantics). Default: same as `quad_count` (test mocks).
59    fn union_quad_count(
60        &self,
61        snapshot: SnapshotId,
62    ) -> impl Future<Output = Result<u64, ComputeError>> + Send {
63        async move { self.quad_count(snapshot).await }
64    }
65
66    /// Schema summary for `GET /waratah/repositories/{id}/ai-context`
67    /// (contract S2).
68    ///
69    /// Default: unsupported, so query-only test mocks compile unchanged;
70    /// the live implementation is on `ComputeNode`.
71    fn schema_summary(
72        &self,
73        _params: &waratah_compute::SchemaSummaryParams,
74    ) -> impl Future<Output = Result<waratah_compute::SchemaSummary, ComputeError>> + Send {
75        async {
76            Err(ComputeError::UnsupportedSparql(
77                "schema summary requires a live compute node".to_owned(),
78            ))
79        }
80    }
81
82    /// Local planner sketch cache (empty when stats have not been rolled up).
83    fn planner_profile(&self) -> StatsProfile {
84        StatsProfile::default()
85    }
86
87    /// SPARQL default-graph fallback copied onto each [`QueryContext`].
88    fn default_union(&self) -> bool {
89        false
90    }
91
92    /// Inner-join seating comparator copied onto each [`QueryContext`]
93    /// (`false` = legacy `driver_cost` decision).
94    fn seat_by_total_cost(&self) -> bool {
95        false
96    }
97
98    /// Base [`QueryContext`] for a query at `snapshot` — the engine's own:
99    /// default-graph fallback, index trust epochs, spill root.
100    ///
101    /// Derived from the engine rather than re-assembled at call sites because
102    /// the geo / temporal index trust epochs live only there. A context that
103    /// misses them is not merely incomplete: a `None` temporal epoch gates
104    /// the temporal comparison rewrite OFF, so those queries would silently
105    /// fall back to the unindexed residual (correct answers, no index, no
106    /// diagnostic). Geo's gate is more forgiving — it reads a missing epoch as
107    /// trusted — which is precisely why the dropped epoch went unnoticed:
108    /// geo kept working while temporal quietly degraded.
109    ///
110    /// The default is built from this trait's own defaults so query-only test
111    /// mocks keep working unchanged.
112    fn query_context(&self, snapshot: SnapshotId) -> QueryContext {
113        QueryContext::from_snapshot(snapshot)
114            .with_default_union(self.default_union())
115            .with_seat_by_total_cost(self.seat_by_total_cost())
116    }
117
118    /// Spill root copied onto each [`QueryContext`] (`None` = `std::env::temp_dir`).
119    ///
120    /// Default `None` so query-only test mocks keep working.
121    fn spill_dir(&self) -> Option<std::path::PathBuf> {
122        None
123    }
124
125    /// Fan out encoded quads to the string registry and S/P/O.
126    ///
127    /// Default: [`ComputeError::IngestUnsupported`] (query-only test mocks).
128    fn insert_quads(
129        &self,
130        _quads: &[Quad],
131        _commit_ts: CommitTs,
132    ) -> impl Future<Output = Result<InsertResult, ComputeError>> + Send {
133        async { Err(ComputeError::IngestUnsupported) }
134    }
135
136    /// Flush MemTables after ingest. Default is a no-op.
137    fn flush_memtables(&self) -> impl Future<Output = Result<(), ComputeError>> + Send {
138        async { Ok(()) }
139    }
140
141    /// Reload planner sketches after ingest. Default returns an empty profile.
142    fn refresh_stats(&self) -> impl Future<Output = Result<StatsProfile, ComputeError>> + Send {
143        async { Ok(StatsProfile::default()) }
144    }
145
146    /// Cluster snapshot for `/waratah/cluster`. Default: this process has no view.
147    fn cluster_snapshot(
148        &self,
149    ) -> impl Future<Output = Option<waratah_compute::ClusterSnapshot>> + Send {
150        async { None }
151    }
152
153    /// Static cluster members `/cors_proxy` may forward to.
154    ///
155    /// Default is empty so query-only mocks do not accept proxied calls.
156    fn cors_proxy_targets(&self) -> Vec<CorsProxyTarget> {
157        Vec::new()
158    }
159}
160
161impl<H, R> ComputeBackend for ComputeNode<H, R>
162where
163    H: HexastoreScan
164        + HexastoreCatalog
165        + HexastoreInsert
166        + HexastoreFlush
167        + HexastoreStats
168        + HexastoreAdmin
169        + HexastoreGeo
170        + Send
171        + Sync,
172    R: StringResolve
173        + StringRegister
174        + StringRegistryFlush
175        + RegistryAdmin
176        + BlobStoreClient
177        + Send
178        + Sync,
179{
180    async fn query(&self, sparql: &str, ctx: &QueryContext) -> Result<QueryResults, ComputeError> {
181        ComputeNode::query_with(self, sparql, ctx).await
182    }
183
184    async fn query_output(
185        &self,
186        sparql: &str,
187        ctx: &QueryContext,
188    ) -> Result<QueryOutput, ComputeError> {
189        ComputeNode::query_output(self, sparql, ctx).await
190    }
191
192    async fn quad_count(&self, snapshot: SnapshotId) -> Result<u64, ComputeError> {
193        ComputeNode::quad_count(self, snapshot).await
194    }
195
196    async fn union_quad_count(&self, snapshot: SnapshotId) -> Result<u64, ComputeError> {
197        ComputeNode::union_quad_count(self, snapshot).await
198    }
199
200    async fn schema_summary(
201        &self,
202        params: &waratah_compute::SchemaSummaryParams,
203    ) -> Result<waratah_compute::SchemaSummary, ComputeError> {
204        ComputeNode::schema_summary(self, params).await
205    }
206
207    fn planner_profile(&self) -> StatsProfile {
208        self.queries().profile()
209    }
210
211    fn default_union(&self) -> bool {
212        self.queries().default_union()
213    }
214
215    fn seat_by_total_cost(&self) -> bool {
216        self.queries().seat_by_total_cost()
217    }
218
219    fn query_context(&self, snapshot: SnapshotId) -> QueryContext {
220        ComputeNode::context(self, snapshot)
221    }
222
223    fn spill_dir(&self) -> Option<std::path::PathBuf> {
224        self.spill_root().map(std::path::Path::to_path_buf)
225    }
226
227    async fn insert_quads(
228        &self,
229        quads: &[Quad],
230        commit_ts: CommitTs,
231    ) -> Result<InsertResult, ComputeError> {
232        ComputeNode::insert_quads(self, quads, commit_ts).await
233    }
234
235    async fn flush_memtables(&self) -> Result<(), ComputeError> {
236        ComputeNode::flush_memtables(self).await
237    }
238
239    async fn refresh_stats(&self) -> Result<StatsProfile, ComputeError> {
240        ComputeNode::refresh_stats(self).await
241    }
242
243    async fn cluster_snapshot(&self) -> Option<waratah_compute::ClusterSnapshot> {
244        let knobs = waratah_compute::ClusterKnobs::main_only(
245            self.queries().describe_mode(),
246            self.queries().default_union(),
247        )
248        .with_standalone(self.standalone());
249        ComputeNode::cluster_snapshot(self, knobs).await
250    }
251
252    fn cors_proxy_targets(&self) -> Vec<CorsProxyTarget> {
253        let Some(config) = self.cluster_config() else {
254            return Vec::new();
255        };
256        config
257            .computes()
258            .iter()
259            .filter_map(|spec| {
260                Some(CorsProxyTarget {
261                    id: spec.id.clone(),
262                    rdf4j_origin: http_origin(&spec.rdf4j_url)?,
263                    admin_origin: http_origin(&spec.admin_url)?,
264                })
265            })
266            .collect()
267    }
268}