waratah_api/lib.rs
1//! RDF4J-compatible HTTP facade over an in-process [`ComputeNode`].
2//!
3//! The router mounts `/rdf4j`, `/waratah`, `/cors_proxy`, the AI services
4//! (discovery + LLM egress proxy under `/waratah/ai`,
5//! `/waratah/repositories/{id}/ai-context`), the pre-built
6//! grevillea console at `/`, and — when the notebook service is enabled —
7//! the jupyter reverse proxy at `/jupyter` (`waratah_notebook`). `GET`/`HEAD`
8//! paths outside those API prefixes return the SPA
9//! `index.html`, except `/assets/…`, `/sw.js`, and `/favicon.ico`, which are
10//! exact files from the embedded `dist-console`. `/download/…` is not served.
11//!
12//! The MVP mounts under `/rdf4j` and implements protocol version,
13//! SPARQL `SELECT` / `ASK` / `CONSTRUCT` / `DESCRIBE` on repository `main`,
14//! `GET /rdf4j/repositories` (lists `main`), repository size, namespace list, and a
15//! Waratah-specific `.../explain` endpoint that returns Jena SSE, SPARQL, or a
16//! row-estimate plan tree (`format`, `pretty` query params). Remaining RDF4J
17//! paths return `501 Not Implemented`. Serialization of SPARQL Results uses
18//! Oxigraph's `sparesults` crate; graph results use `oxrdfio` (Turtle /
19//! N-Triples / RDF/XML).
20//!
21//! SELECT and ASK responses default to `text/csv` when the client sends no
22//! usable `Accept` (absent, `*`, `*/*`); CONSTRUCT / DESCRIBE default to
23//! Turtle, and the repository / namespace listings default to JSON. The
24//! whole router compresses response bodies per the client's
25//! `Accept-Encoding` — brotli at level 4 or gzip at level 5, brotli winning
26//! equal-weight ties — and marks compressed responses with `Content-Encoding`
27//! and `Vary: Accept-Encoding`. Buffered bodies under 256 bytes stay
28//! identity, which keeps every ASK boolean serialization uncompressed
29//! (`waratah_api/src/compress.rs`).
30//!
31//! Staging ingest (list / upload / snippet / ingest) is a Waratah-specific
32//! API under `/waratah/repositories/{id}/ingest`, not RDF4J. Files are staged
33//! under `{ingest_dir}/{repository_id}` (repository is `main`). The same
34//! `/waratah` prefix serves `GET /waratah/health` (this process),
35//! `GET /waratah/cluster` (coordinator snapshot of computes + storage), and
36//! `GET /waratah/repositories/{id}/queries` — the read-only published query
37//! library behind `--queries-dir` (or the inline `--load-demo` samples;
38//! `waratah_api/src/query_library.rs`). `/cors_proxy/{compute_id}/rdf4j|waratah/…`
39//! streams that request to a cluster member's configured HTTP origin. There
40//! are no browser CORS headers.
41
42#![deny(unused_must_use)]
43#![warn(missing_docs)]
44
45mod backend;
46mod compress;
47mod console;
48mod debug;
49mod error;
50mod query_library;
51mod repos;
52mod routes;
53mod serialize;
54mod state;
55
56mod ai;
57
58pub use ai::{AiConfig, AiConfigError, AiService, AiToml, AiUpstream};
59
60pub use backend::{ComputeBackend, CorsProxyTarget};
61pub use console::{console_is_stub, console_missing_worker};
62pub use debug::{QueryDebug, QuerySpan};
63pub use error::ApiError;
64pub use query_library::{QueryLibrary, QueryLibraryError, ServerQuery};
65pub use repos::{RepositoryCatalog, RepositoryState};
66pub use serialize::{
67 negotiate_graph_format, negotiate_results_format, negotiate_results_format_with_default,
68 serialize_query_results, serialize_query_results_with_default,
69};
70pub use state::AppState;
71/// Default repository ID served by the MVP (on-disk layout and HTTP URLs).
72pub use waratah_storage::MAIN_REPOSITORY_ID;
73
74use std::net::SocketAddr;
75
76use axum::Router;
77use axum::middleware::from_fn;
78use waratah_compute::ComputeNode;
79
80use crate::compress::middleware as compress_response;
81use crate::console::console_fallback;
82use crate::routes::{cors_proxy_router, rdf4j_router, waratah_router};
83
84/// RDF4J protocol version advertised by `GET /rdf4j/protocol`.
85pub const PROTOCOL_VERSION: &str = "10";
86
87/// Build the HTTP router for `state`.
88///
89/// `/rdf4j`, `/waratah`, and `/cors_proxy` are matched first, then `/jupyter`
90/// when the notebook service is enabled. Other `GET`/`HEAD` requests fall
91/// back to the embedded console.
92pub fn router<C>(state: AppState<C>) -> Router
93where
94 C: ComputeBackend + Clone + Send + Sync + 'static,
95{
96 let mut router = Router::new()
97 .nest("/rdf4j", rdf4j_router(state.clone()))
98 .nest("/waratah", waratah_router(state.clone()));
99 // Only mounted when the notebook service is enabled; `/jupyter` stays a
100 // 404 API prefix (not console SPA HTML) either way — see `console.rs`.
101 if let Some(notebooks) = state.notebooks.clone() {
102 router = router.nest_service("/jupyter", waratah_notebook::proxy::router(notebooks));
103 }
104 router
105 .nest("/cors_proxy", cors_proxy_router(state))
106 .fallback(console_fallback)
107 .layer(from_fn(compress_response))
108}
109
110/// Convenience: serve RDF4J over a live [`ComputeNode`].
111pub fn router_for_compute(compute: ComputeNode) -> Router {
112 router(AppState::new(compute))
113}
114
115/// Bind `addr` and serve until the listener fails.
116pub async fn serve<C>(addr: SocketAddr, state: AppState<C>) -> Result<(), std::io::Error>
117where
118 C: ComputeBackend + Clone + Send + Sync + 'static,
119{
120 let listener = tokio::net::TcpListener::bind(addr).await?;
121 axum::serve(listener, router(state)).await
122}
123
124/// Bind `addr` for the RDF4J HTTP facade, returning the listener before any
125/// request is served.
126///
127/// Callers that must report readiness only once the socket is actually
128/// bound (the daemonized `waratah start` handshake) bind first, report, then
129/// hand the listener to [`serve_bound_with_shutdown`] — a bind failure
130/// (address in use) then surfaces as an ordinary `Err` BEFORE readiness is
131/// ever reported, instead of as a ready-reported process that dies during
132/// teardown.
133pub async fn bind_http(addr: SocketAddr) -> Result<tokio::net::TcpListener, std::io::Error> {
134 tokio::net::TcpListener::bind(addr).await
135}
136
137/// Bind `addr` and serve until `shutdown` resolves or the listener fails.
138///
139/// Stops accepting once `shutdown` fires, then waits for outstanding requests
140/// to drain. Note that long-lived kernel WebSocket tunnels never "finish":
141/// the caller that needs a bounded exit should race this future and drop it
142/// (`waratah_bin` does exactly that).
143pub async fn serve_with_shutdown<C>(
144 addr: SocketAddr,
145 state: AppState<C>,
146 shutdown: impl std::future::Future<Output = ()> + Send + 'static,
147) -> Result<(), std::io::Error>
148where
149 C: ComputeBackend + Clone + Send + Sync + 'static,
150{
151 let listener = bind_http(addr).await?;
152 serve_bound_with_shutdown(listener, state, shutdown).await
153}
154
155/// Serve the RDF4J HTTP facade on an already-bound listener until
156/// `shutdown` resolves or the listener fails.
157///
158/// Same drain semantics as [`serve_with_shutdown`]: stops accepting once
159/// `shutdown` fires, then waits for outstanding requests; long-lived kernel
160/// WebSocket tunnels never "finish", so a bounded exit races and drops this
161/// future.
162pub async fn serve_bound_with_shutdown<C>(
163 listener: tokio::net::TcpListener,
164 state: AppState<C>,
165 shutdown: impl std::future::Future<Output = ()> + Send + 'static,
166) -> Result<(), std::io::Error>
167where
168 C: ComputeBackend + Clone + Send + Sync + 'static,
169{
170 axum::serve(listener, router(state))
171 .with_graceful_shutdown(shutdown)
172 .await
173}
174
175/// Bind `addr` and serve a live [`ComputeNode`].
176pub async fn serve_compute(addr: SocketAddr, compute: ComputeNode) -> Result<(), std::io::Error> {
177 serve(addr, AppState::new(compute)).await
178}