Skip to main content

qualia_core_db/sparql_library/
sparql_federated.rs

1//! SPARQL 1.1 Federated Query (SERVICE)
2//!
3//! Implements federated query support with DID integration for CORS handling.
4
5use crate::sparql_ast::*;
6use crate::sparql_executor::QueryExecutor;
7use crate::sparql_parser;
8use crate::sparql_planner::QueryPlanner;
9use crate::NQuin;
10
11use std::collections::HashMap;
12
13/// SERVICE endpoint configuration
14#[repr(C)]
15#[derive(Debug, Clone, Copy)]
16pub struct ServiceEndpoint {
17    pub did: u64,          // DID identifier
18    pub endpoint_url: u64, // Hash of URL string
19    pub auth_method: u8,   // 0=none, 1=DID-LD, 2=JWT
20    pub timeout_ms: u32,
21}
22
23/// Federated query result
24#[repr(C)]
25#[derive(Debug, Clone, Copy)]
26pub struct FederatedResult {
27    pub endpoint_did: u64,
28    pub row_count: u16,
29    pub success: bool,
30}
31
32/// SPARQL Federated Query Handler — a DID-registry front over the URL-based
33/// [`FederatedQueryEngine`]. It maps a DID to a concrete endpoint URL string and
34/// dispatches remote SPARQL requests through the same real HTTP transport.
35pub struct FederatedQueryHandler<'a> {
36    pub local_quins: &'a [NQuin],
37    pub endpoints: [Option<ServiceEndpoint>; 16],
38    pub endpoint_count: u8,
39    pub cache_enabled: bool,
40    /// DID → concrete endpoint URL string (a `u64` hash cannot be un-hashed to a URL,
41    /// so the resolvable URL is stored alongside for real remote execution).
42    endpoint_urls: HashMap<u64, String>,
43}
44
45impl<'a> FederatedQueryHandler<'a> {
46    /// Creates `FederatedQueryHandler` with the given state.
47    pub fn new(quins: &'a [NQuin]) -> Self {
48        Self {
49            local_quins: quins,
50            endpoints: [None; 16],
51            endpoint_count: 0,
52            cache_enabled: true,
53            endpoint_urls: HashMap::new(),
54        }
55    }
56
57    /// Associate a DID with a concrete endpoint URL so remote queries can actually be
58    /// dispatched over HTTP (the `ServiceEndpoint.endpoint_url` hash is not reversible).
59    pub fn set_endpoint_url(&mut self, did: u64, url: &str) {
60        self.endpoint_urls.insert(did, url.to_string());
61    }
62
63    /// Register a federated endpoint
64    pub fn register_endpoint(&mut self, endpoint: ServiceEndpoint) -> Result<u8, String> {
65        if self.endpoint_count >= 16 {
66            return Err("Endpoint overflow".to_string());
67        }
68        let idx = self.endpoint_count;
69        self.endpoints[idx as usize] = Some(endpoint);
70        self.endpoint_count += 1;
71        Ok(idx)
72    }
73
74    /// Resolve DID to endpoint URL
75    pub fn resolve_did(&self, did: u64) -> Result<u64, String> {
76        // In production, this would:
77        // 1. Resolve DID using DID resolver
78        // 2. Extract service endpoint from DID document
79        // 3. Return the endpoint URL hash
80
81        // Simplified: return DID as URL hash
82        for i in 0..self.endpoint_count as usize {
83            if let Some(endpoint) = self.endpoints[i] {
84                if endpoint.did == did {
85                    return Ok(endpoint.endpoint_url);
86                }
87            }
88        }
89
90        Err("DID not found in endpoint registry".to_string())
91    }
92
93    /// Execute a federated query against the endpoint registered for `did`, over the
94    /// real HTTP SPARQL 1.1 Protocol transport.
95    ///
96    /// Requires a resolvable endpoint URL registered via
97    /// [`set_endpoint_url`](Self::set_endpoint_url) (the `ServiceEndpoint.endpoint_url`
98    /// hash is not reversible to a URL). Authenticated (DID-LD/JWT) endpoints must be
99    /// signed by the identity layer; only the **no-auth** path is dispatched here — no
100    /// fabricated auth header. Network egress: makes a real outbound request.
101    pub fn execute_service(
102        &self,
103        did: u64,
104        query: &str,
105        _format: &str,
106    ) -> Result<FederatedResult, String> {
107        let endpoint = (0..self.endpoint_count as usize)
108            .filter_map(|i| self.endpoints[i])
109            .find(|e| e.did == did)
110            .ok_or("DID not found in endpoint registry")?;
111        if endpoint.auth_method != 0 {
112            return Err(
113                "authenticated (DID-LD/JWT) federation must be signed by the \
114                        identity layer; only no-auth remote endpoints are dispatched here"
115                    .to_string(),
116            );
117        }
118        let url = self.endpoint_urls.get(&did).ok_or(
119            "no resolvable endpoint URL registered for this DID (call set_endpoint_url); \
120             the endpoint_url hash is not reversible",
121        )?;
122        let body = fetch_remote_sparql(url, query, endpoint.timeout_ms, None)?;
123        let (_vars, rows, _lexicon) = parse_sparql_results_json(&body)?;
124        Ok(FederatedResult {
125            endpoint_did: did,
126            row_count: rows.len() as u16,
127            success: true,
128        })
129    }
130
131    /// Execute federated query with local data
132    pub fn execute_federated(
133        &self,
134        _service_did: u64,
135        _service_query: &str,
136        _local_pattern: PatternId,
137        _ctx: &SparqlQueryContext,
138    ) -> Result<Vec<BindingRow>, String> {
139        // Execute remote SERVICE query
140        // let _remote_result = self.execute_service(service_did, service_query, "json")?;
141
142        // Parse remote query to get variables
143        // let (_sparql_query, mut remote_ctx) = sparql_parser::parse_sparql(service_query)?;
144
145        // Execute local pattern
146        // let plan = QueryPlanner::from_pattern(local_pattern, ctx)?;
147        // let executor = QueryExecutor::new(self.local_quins);
148        // let local_results = executor.execute(&plan, ctx)?;
149
150        // Merge results (simplified: just return empty for now)
151        // In production, this would:
152        // 1. Get remote results from HTTP response
153        // 2. Join with local results on common variables
154        // 3. Return merged bindings
155
156        Ok(vec![])
157    }
158
159    /// Check CORS using DID-based authentication
160    pub fn check_cors_allowed(&self, did: u64, origin_did: u64) -> Result<bool, String> {
161        // In production, this would:
162        // 1. Resolve both DIDs
163        // 2. Check if origin_did is in the service endpoint's allowed origins list
164        // 3. Verify DID relationship (e.g., same controller, trusted relationship)
165
166        // Simplified: allow if DIDs are same
167        Ok(did == origin_did)
168    }
169
170    /// Generate CORS headers using DID
171    pub fn generate_cors_headers(&self, did: u64) -> Result<Vec<(u64, u64)>, String> {
172        // In production, this would generate proper CORS headers
173        // based on DID resolution and trust relationships
174
175        let access_control_origin: u64 = 0x41432D4F72696769; // "Access-Control-Origin" (truncated)
176        let access_control_methods: u64 = 0x41432D4D65746F64; // "Access-Control-Methods" (truncated)
177        let access_control_headers: u64 = 0x41432D4865616465; // "Access-Control-Headers" (truncated)
178
179        Ok(vec![
180            (access_control_origin, did),                     // Use DID as origin
181            (access_control_methods, 0x4745540000000000_u64), // "GET"
182            (access_control_headers, 0x436F6E74656E742D_u64), // "Content-Type" (truncated)
183        ])
184    }
185}
186
187impl<'a> Default for FederatedQueryHandler<'a> {
188    fn default() -> Self {
189        Self::new(&[])
190    }
191}
192
193// =============================================================================
194// FederatedQueryEngine — string-URL based federated query execution.
195//
196// This is a higher-level engine than the DID-hash `FederatedQueryHandler` above.
197// It works with human-readable endpoint URLs (`local:`, `qualia:`, `http://...`)
198// and is the entry point used by the SPARQL `SERVICE` clause evaluator.
199// =============================================================================
200
201/// A federated service endpoint identified by a readable URL string.
202///
203/// URL schemes:
204/// - `local:<graph>` / `qualia:<graph>` — execute against the local QualiaDB instance
205/// - `http://` / `https://`           — remote SPARQL endpoint (HTTP transport)
206#[derive(Debug, Clone)]
207pub struct FederatedService {
208    /// Endpoint URL, e.g. `local:default`, `qualia:graph1`, `https://db.example.org/sparql`.
209    pub endpoint: String,
210    /// 0 = none, 1 = DID-LD, 2 = JWT (forwarded to remote endpoints).
211    pub auth_method: u8,
212    /// Request timeout in milliseconds (remote endpoints only).
213    pub timeout_ms: u32,
214}
215
216impl FederatedService {
217    /// Create a new service endpoint with no auth and a 30s default timeout.
218    pub fn new(endpoint: &str) -> Self {
219        Self {
220            endpoint: endpoint.to_string(),
221            auth_method: 0,
222            timeout_ms: 30_000,
223        }
224    }
225
226    /// Returns true when the endpoint targets the local QualiaDB instance and
227    /// should be executed in-process rather than over HTTP.
228    pub fn is_local(&self) -> bool {
229        self.endpoint.starts_with("local:") || self.endpoint.starts_with("qualia:")
230    }
231
232    /// Returns the local graph identifier portion of a `local:`/`qualia:` endpoint,
233    /// or `None` for remote endpoints.
234    pub fn local_graph(&self) -> Option<&str> {
235        if let Some(rest) = self.endpoint.strip_prefix("local:") {
236            return Some(rest);
237        }
238        if let Some(rest) = self.endpoint.strip_prefix("qualia:") {
239            return Some(rest);
240        }
241        None
242    }
243}
244
245/// The outcome of executing a single query against a single federated service.
246#[derive(Debug, Clone)]
247pub struct FederatedQueryResult {
248    /// The endpoint URL the query was dispatched to.
249    pub service_endpoint: String,
250    /// The SPARQL query string that was executed.
251    pub query: String,
252    /// Result bindings — real rows for both local execution and successful remote
253    /// (HTTP) execution. Each slot holds a term hash resolvable via [`Self::lexicon`]
254    /// (remote) or the local graph lexicon (local).
255    pub results: Vec<BindingRow>,
256    /// Result variable names in slot order (populated for remote SPARQL-results
257    /// responses; empty for a bare local execution that carries its own ctx).
258    pub variables: Vec<String>,
259    /// Hash → text (+ lang/datatype) for the terms in `results`, so remote string
260    /// terms are resolvable in the local u64-term model. Empty for local execution
261    /// (whose terms resolve via the local graph lexicon).
262    pub lexicon: LiteralTable,
263    /// Whether execution succeeded.
264    pub success: bool,
265    /// Error message when `success` is false.
266    pub error: Option<String>,
267    /// For remote endpoints, the fully-constructed query URL that was fetched (kept
268    /// for provenance/debugging). `None` for local execution.
269    pub remote_query_url: Option<String>,
270}
271
272impl FederatedQueryResult {
273    /// Number of result rows.
274    pub fn row_count(&self) -> usize {
275        self.results.len()
276    }
277}
278
279/// A federated query: a SPARQL query to run across one or more services.
280#[derive(Debug, Clone)]
281pub struct FederatedQuery {
282    /// Services to dispatch the query to.
283    pub services: Vec<FederatedService>,
284    /// The SPARQL query string.
285    pub query: String,
286}
287
288impl FederatedQuery {
289    /// Create a new federated query targeting a single service.
290    pub fn new(query: &str) -> Self {
291        Self {
292            services: Vec::new(),
293            query: query.to_string(),
294        }
295    }
296
297    /// Add a service to the federated query.
298    pub fn with_service(mut self, service: FederatedService) -> Self {
299        self.services.push(service);
300        self
301    }
302}
303
304/// Federated query engine — dispatches queries across local and remote services.
305///
306/// Local services (`local:`/`qualia:`) are executed in-process via the standard
307/// SPARQL parser → planner → executor pipeline. Remote HTTP(S) services are executed
308/// over the **real SPARQL 1.1 Protocol** (`fetch_remote_sparql` +
309/// `parse_sparql_results_json`): a `application/sparql-query` POST, the
310/// `application/sparql-results+json` response parsed into binding rows + a resolvable
311/// lexicon. Remote execution is real network egress and runs only for endpoints the
312/// caller explicitly targets.
313pub struct FederatedQueryEngine<'a> {
314    /// Local Quins the engine executes local services against.
315    pub local_quins: &'a [NQuin],
316    /// Registered service endpoints keyed by endpoint URL.
317    pub services: HashMap<String, FederatedService>,
318    /// Whether [`initialize`](Self::initialize) has been called.
319    pub initialized: bool,
320}
321
322impl<'a> FederatedQueryEngine<'a> {
323    /// Create a new engine over a slice of local Quins.
324    pub fn new(quins: &'a [NQuin]) -> Self {
325        Self {
326            local_quins: quins,
327            services: HashMap::new(),
328            initialized: false,
329        }
330    }
331
332    /// Initialize the engine for use. Clears any stale state and marks the
333    /// engine ready. Calling this is required before executing federated
334    /// queries so that downstream code can rely on a deterministic start state.
335    pub fn initialize(&mut self) -> Result<(), String> {
336        // Reset to a clean, known-good state. Registered services are preserved
337        // (registration may happen before or after initialize), but the
338        // initialized flag is what gates execution.
339        self.initialized = true;
340        Ok(())
341    }
342
343    /// Register a federated service endpoint. Re-registering an existing
344    /// endpoint URL updates its configuration in place.
345    pub fn register_service(&mut self, service: FederatedService) {
346        self.services.insert(service.endpoint.clone(), service);
347    }
348
349    /// List the endpoint URLs of all registered services.
350    pub fn list_services(&self) -> Vec<String> {
351        let mut endpoints: Vec<String> = self.services.keys().cloned().collect();
352        endpoints.sort();
353        endpoints
354    }
355
356    /// Execute a query against a single federated service.
357    ///
358    /// - Local endpoints (`local:`/`qualia:`) are executed in-process and
359    ///   return real result bindings.
360    /// - Remote HTTP endpoints return a placeholder result containing the
361    ///   constructed query URL (`<endpoint>?query=<encoded>`). The HTTP fetch
362    ///   itself requires an async runtime which is not available in this
363    ///   synchronous module; the placeholder is structured so a transport layer
364    ///   can be plugged in later without changing the call sites.
365    pub fn execute_service(
366        &self,
367        service: &FederatedService,
368        query: &str,
369    ) -> Result<FederatedQueryResult, String> {
370        if service.is_local() {
371            // Execute locally through the standard pipeline.
372            let (sparql_query, ctx) = match sparql_parser::parse_sparql(query) {
373                Ok(parsed) => parsed,
374                Err(e) => {
375                    return Ok(Self::failed(
376                        service,
377                        query,
378                        format!("Parse error: {e}"),
379                        None,
380                    ))
381                }
382            };
383            let plan = match QueryPlanner::plan(&sparql_query, &ctx) {
384                Ok(plan) => plan,
385                Err(e) => {
386                    return Ok(Self::failed(
387                        service,
388                        query,
389                        format!("Planning error: {e}"),
390                        None,
391                    ))
392                }
393            };
394            let executor = QueryExecutor::new(self.local_quins);
395            match executor.execute(&plan, &ctx) {
396                Ok(results) => Ok(FederatedQueryResult {
397                    service_endpoint: service.endpoint.clone(),
398                    query: query.to_string(),
399                    results,
400                    variables: Vec::new(),
401                    lexicon: LiteralTable::new(),
402                    success: true,
403                    error: None,
404                    remote_query_url: None,
405                }),
406                Err(e) => Ok(Self::failed(
407                    service,
408                    query,
409                    format!("Execution error: {e}"),
410                    None,
411                )),
412            }
413        } else {
414            // Remote HTTP SPARQL endpoint: perform a real SPARQL 1.1 Protocol request and
415            // parse the `application/sparql-results+json` response into binding rows.
416            //
417            // Network egress: this makes a real outbound HTTP request, and runs only when
418            // a caller explicitly dispatches to a remote `FederatedService`. Authenticated
419            // (DID-LD/JWT) endpoints need the identity layer to sign the request; the
420            // no-auth path is supported here directly (no synthetic/fake auth header).
421            let query_url = build_remote_query_url(&service.endpoint, query);
422            match fetch_remote_sparql(&service.endpoint, query, service.timeout_ms, None) {
423                Ok(body) => match parse_sparql_results_json(&body) {
424                    Ok((variables, results, lexicon)) => Ok(FederatedQueryResult {
425                        service_endpoint: service.endpoint.clone(),
426                        query: query.to_string(),
427                        results,
428                        variables,
429                        lexicon,
430                        success: true,
431                        error: None,
432                        remote_query_url: Some(query_url),
433                    }),
434                    Err(e) => Ok(Self::failed(
435                        service,
436                        query,
437                        format!("Remote result parse error: {e}"),
438                        Some(query_url),
439                    )),
440                },
441                Err(e) => Ok(Self::failed(service, query, e, Some(query_url))),
442            }
443        }
444    }
445
446    /// Construct a failed [`FederatedQueryResult`] carrying an error message.
447    fn failed(
448        service: &FederatedService,
449        query: &str,
450        error: String,
451        remote_query_url: Option<String>,
452    ) -> FederatedQueryResult {
453        FederatedQueryResult {
454            service_endpoint: service.endpoint.clone(),
455            query: query.to_string(),
456            results: Vec::new(),
457            variables: Vec::new(),
458            lexicon: LiteralTable::new(),
459            success: false,
460            error: Some(error),
461            remote_query_url,
462        }
463    }
464
465    /// Execute a federated query across all of its services.
466    ///
467    /// Each service is dispatched via [`execute_service`](Self::execute_service)
468    /// and the per-service results are collected. Results are concatenated
469    /// (simple merge); full SPARQL join semantics across services are a
470    /// separate task.
471    pub fn execute_federated(
472        &self,
473        query: &FederatedQuery,
474    ) -> Result<Vec<FederatedQueryResult>, String> {
475        if !self.initialized {
476            return Err("FederatedQueryEngine not initialized".to_string());
477        }
478        if query.services.is_empty() {
479            return Err("Federated query has no services".to_string());
480        }
481
482        let mut results = Vec::with_capacity(query.services.len());
483        for service in &query.services {
484            // A per-service failure does not abort the whole federated query;
485            // the error is captured in the result so callers can decide.
486            let result = self.execute_service(service, &query.query)?;
487            results.push(result);
488        }
489        Ok(results)
490    }
491}
492
493impl<'a> Default for FederatedQueryEngine<'a> {
494    fn default() -> Self {
495        Self::new(&[])
496    }
497}
498
499/// Build the HTTP query URL for a remote SPARQL endpoint using simple
500/// percent-encoding of the query string. This is the URL an HTTP transport
501/// layer would GET/POST.
502fn build_remote_query_url(endpoint: &str, query: &str) -> String {
503    let encoded = percent_encode_query(query);
504    let separator = if endpoint.contains('?') { '&' } else { '?' };
505    format!("{}{}query={}", endpoint, separator, encoded)
506}
507
508/// Minimal percent-encoder for the SPARQL query parameter. Encodes characters
509/// that are not unreserved per RFC 3986. Kept dependency-free and synchronous.
510fn percent_encode_query(input: &str) -> String {
511    let mut out = String::with_capacity(input.len());
512    for &b in input.as_bytes() {
513        // Unreserved: A-Z a-z 0-9 - _ . ~
514        let unreserved = b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~');
515        if unreserved {
516            out.push(b as char);
517        } else {
518            out.push('%');
519            out.push_str(&format!("{:02X}", b));
520        }
521    }
522    out
523}
524
525/// Execute a SPARQL query against a remote HTTP endpoint (SPARQL 1.1 Protocol) and
526/// return the raw `application/sparql-results+json` response body.
527///
528/// Uses a **blocking** HTTP client run on a dedicated thread, so it is safe to call from
529/// within a Tokio runtime (a blocking client cannot be created on an async worker
530/// thread). `timeout_ms` bounds the whole request. `auth`, when present, is sent as the
531/// `Authorization` header value.
532///
533/// **Network egress.** This performs a real outbound HTTP request to `endpoint`.
534#[cfg(not(target_arch = "wasm32"))]
535fn fetch_remote_sparql(
536    endpoint: &str,
537    query: &str,
538    timeout_ms: u32,
539    auth: Option<&str>,
540) -> Result<String, String> {
541    let endpoint = endpoint.to_string();
542    let query = query.to_string();
543    let auth = auth.map(|s| s.to_string());
544    std::thread::spawn(move || -> Result<String, String> {
545        let client = reqwest::blocking::Client::builder()
546            .timeout(std::time::Duration::from_millis(timeout_ms.max(1) as u64))
547            .build()
548            .map_err(|e| format!("http client build failed: {e}"))?;
549        let mut req = client
550            .post(&endpoint)
551            .header(reqwest::header::CONTENT_TYPE, "application/sparql-query")
552            .header(reqwest::header::ACCEPT, "application/sparql-results+json")
553            .body(query);
554        if let Some(a) = auth {
555            req = req.header(reqwest::header::AUTHORIZATION, a);
556        }
557        let resp = req
558            .send()
559            .map_err(|e| format!("remote request failed: {e}"))?;
560        let status = resp.status();
561        let text = resp
562            .text()
563            .map_err(|e| format!("reading remote response failed: {e}"))?;
564        if !status.is_success() {
565            let snippet: String = text.chars().take(200).collect();
566            return Err(format!("remote endpoint returned HTTP {status}: {snippet}"));
567        }
568        Ok(text)
569    })
570    .join()
571    .map_err(|_| "remote fetch thread panicked".to_string())?
572}
573
574/// wasm has no synchronous HTTP transport — remote federation is a native capability.
575#[cfg(target_arch = "wasm32")]
576fn fetch_remote_sparql(
577    _endpoint: &str,
578    _query: &str,
579    _timeout_ms: u32,
580    _auth: Option<&str>,
581) -> Result<String, String> {
582    Err("remote SPARQL federation is not available on the wasm target".to_string())
583}
584
585/// Parse an `application/sparql-results+json` document into `(variables, rows, lexicon)`:
586/// the result variable names in order, one [`BindingRow`] per solution (each slot a term
587/// hash), and a [`LiteralTable`] mapping those hashes back to text (with lang/datatype),
588/// so remote string terms are resolvable in the local u64-term model. Also handles the
589/// ASK form `{ "boolean": … }` (a single row with slot 0 = 1/0).
590fn parse_sparql_results_json(
591    body: &str,
592) -> Result<(Vec<String>, Vec<BindingRow>, LiteralTable), String> {
593    let v: serde_json::Value =
594        serde_json::from_str(body).map_err(|e| format!("invalid SPARQL results JSON: {e}"))?;
595    let mut lexicon = LiteralTable::new();
596
597    // ASK result → a single row, slot 0 = 1/0.
598    if let Some(b) = v.get("boolean").and_then(|b| b.as_bool()) {
599        let mut row = BindingRow::new();
600        row.slots[0] = Some(if b { 1 } else { 0 });
601        return Ok((Vec::new(), vec![row], lexicon));
602    }
603
604    let vars: Vec<String> = v
605        .get("head")
606        .and_then(|h| h.get("vars"))
607        .and_then(|a| a.as_array())
608        .map(|a| {
609            a.iter()
610                .filter_map(|x| x.as_str().map(String::from))
611                .collect()
612        })
613        .unwrap_or_default();
614
615    let bindings = v
616        .get("results")
617        .and_then(|r| r.get("bindings"))
618        .and_then(|b| b.as_array())
619        .cloned()
620        .unwrap_or_default();
621
622    let mut rows = Vec::with_capacity(bindings.len());
623    for binding in &bindings {
624        let mut row = BindingRow::new();
625        for (i, var) in vars.iter().enumerate() {
626            if i >= MAX_BINDINGS {
627                break; // fixed-capacity binding row (§6)
628            }
629            if let Some(term) = binding.get(var) {
630                let value = term.get("value").and_then(|x| x.as_str()).unwrap_or("");
631                let lang = term.get("xml:lang").and_then(|x| x.as_str());
632                let datatype = term.get("datatype").and_then(|x| x.as_str());
633                // Hash consistently with the local term model; intern text + any tags so
634                // the remote term round-trips through the resolver and STR/LANG/DATATYPE.
635                let hash = crate::sparql_ast::literal_term_hash(value, lang, datatype);
636                lexicon.intern_tagged(hash, value, lang, datatype);
637                row.slots[i] = Some(hash);
638            }
639        }
640        rows.push(row);
641    }
642    Ok((vars, rows, lexicon))
643}
644
645/// DID-based CORS helper
646pub struct DidCorsHelper;
647
648impl DidCorsHelper {
649    /// Verify a DID signature for a CORS preflight.
650    ///
651    /// The SPARQL federation layer holds **no key material** and receives only opaque
652    /// `u64` hashes (not the actual signature/challenge/public-key bytes), so it cannot
653    /// perform a real cryptographic verification here. It therefore **fails closed** with
654    /// a named error rather than returning a fabricated `true` (which would let any origin
655    /// pass). Real verification must go through the identity/key-vault layer, which holds
656    /// the resolved DID public key and the raw bytes.
657    pub fn verify_did_signature(
658        _did: u64,
659        _signature: u64,
660        _challenge: u64,
661    ) -> Result<bool, String> {
662        Err(
663            "DID signature verification must be performed by the identity/key-vault layer \
664             (the SPARQL federation layer holds no keys); refusing to fabricate a result"
665                .to_string(),
666        )
667    }
668
669    /// Generate DID-based challenge for CORS
670    pub fn generate_challenge(did: u64) -> u64 {
671        // In production, generate cryptographically secure challenge
672        did ^ 0xDEADBEEFCAFEBABE
673    }
674}
675
676#[cfg(test)]
677mod tests {
678    use super::*;
679
680    #[test]
681    fn test_federated_handler_creation() {
682        let quins = vec![];
683        let handler = FederatedQueryHandler::new(&quins);
684        assert_eq!(handler.endpoint_count, 0);
685    }
686
687    #[test]
688    fn test_register_endpoint() {
689        let quins = vec![];
690        let mut handler = FederatedQueryHandler::new(&quins);
691
692        let endpoint = ServiceEndpoint {
693            did: 1,
694            endpoint_url: 2,
695            auth_method: 0,
696            timeout_ms: 5000,
697        };
698
699        let result = handler.register_endpoint(endpoint);
700        assert!(result.is_ok());
701        assert_eq!(handler.endpoint_count, 1);
702    }
703
704    #[test]
705    fn test_resolve_did() {
706        let quins = vec![];
707        let mut handler = FederatedQueryHandler::new(&quins);
708
709        let endpoint = ServiceEndpoint {
710            did: 123,
711            endpoint_url: 456,
712            auth_method: 0,
713            timeout_ms: 5000,
714        };
715
716        handler.register_endpoint(endpoint).unwrap();
717        let url_hash = handler.resolve_did(123).unwrap();
718        assert_eq!(url_hash, 456);
719    }
720
721    #[test]
722    fn test_cors_check() {
723        let quins = vec![];
724        let handler = FederatedQueryHandler::new(&quins);
725
726        let allowed = handler.check_cors_allowed(123, 123).unwrap();
727        assert!(allowed);
728
729        let not_allowed = handler.check_cors_allowed(123, 456).unwrap();
730        assert!(!not_allowed);
731    }
732
733    #[test]
734    fn test_did_signature_verification_fails_closed() {
735        // The SPARQL layer holds no keys → verification is an honest error, NOT a
736        // fabricated `true` (which would let any origin pass a CORS preflight).
737        assert!(DidCorsHelper::verify_did_signature(123, 456, 789).is_err());
738    }
739
740    // ---- FederatedQueryEngine tests ----
741
742    #[test]
743    fn test_engine_creation() {
744        let quins = vec![];
745        let engine = FederatedQueryEngine::new(&quins);
746        assert!(!engine.initialized);
747        assert!(engine.services.is_empty());
748    }
749
750    #[test]
751    fn test_engine_initialize() {
752        let quins = vec![];
753        let mut engine = FederatedQueryEngine::new(&quins);
754        assert!(!engine.initialized);
755        engine.initialize().unwrap();
756        assert!(engine.initialized);
757    }
758
759    #[test]
760    fn test_register_and_list_services() {
761        let quins = vec![];
762        let mut engine = FederatedQueryEngine::new(&quins);
763        engine.register_service(FederatedService::new("local:default"));
764        engine.register_service(FederatedService::new("https://remote.example.org/sparql"));
765
766        let services = engine.list_services();
767        assert_eq!(services.len(), 2);
768        assert!(services.contains(&"local:default".to_string()));
769        assert!(services.contains(&"https://remote.example.org/sparql".to_string()));
770    }
771
772    #[test]
773    fn test_register_service_overwrites() {
774        let quins = vec![];
775        let mut engine = FederatedQueryEngine::new(&quins);
776        let mut svc = FederatedService::new("local:default");
777        svc.auth_method = 0;
778        engine.register_service(svc);
779        let mut svc2 = FederatedService::new("local:default");
780        svc2.auth_method = 2;
781        engine.register_service(svc2);
782
783        // Same endpoint URL → single entry, updated config.
784        assert_eq!(engine.list_services().len(), 1);
785        assert_eq!(engine.services.get("local:default").unwrap().auth_method, 2);
786    }
787
788    #[test]
789    fn test_service_is_local() {
790        assert!(FederatedService::new("local:default").is_local());
791        assert!(FederatedService::new("qualia:graph1").is_local());
792        assert!(!FederatedService::new("https://remote.example.org/sparql").is_local());
793        assert!(!FederatedService::new("http://remote.example.org/sparql").is_local());
794    }
795
796    #[test]
797    fn test_service_local_graph() {
798        assert_eq!(
799            FederatedService::new("local:default").local_graph(),
800            Some("default")
801        );
802        assert_eq!(
803            FederatedService::new("qualia:graph1").local_graph(),
804            Some("graph1")
805        );
806        assert_eq!(
807            FederatedService::new("https://remote.example.org/sparql").local_graph(),
808            None
809        );
810    }
811
812    #[test]
813    fn test_execute_service_local() {
814        let quins = vec![];
815        let engine = FederatedQueryEngine::new(&quins);
816        let service = FederatedService::new("local:default");
817        let result = engine
818            .execute_service(&service, "SELECT ?s WHERE { ?s ?p ?o }")
819            .unwrap();
820        assert_eq!(result.service_endpoint, "local:default");
821        assert!(
822            result.success,
823            "local execution should succeed: {:?}",
824            result.error
825        );
826        assert!(result.remote_query_url.is_none());
827        // No quins → no rows, but still a successful local execution.
828        assert_eq!(result.row_count(), 0);
829    }
830
831    #[test]
832    fn test_execute_service_local_parse_error() {
833        let quins = vec![];
834        let engine = FederatedQueryEngine::new(&quins);
835        let service = FederatedService::new("local:default");
836        let result = engine
837            .execute_service(&service, "this is not sparql")
838            .unwrap();
839        assert!(!result.success);
840        assert!(result.error.is_some());
841        assert_eq!(result.row_count(), 0);
842    }
843
844    #[test]
845    #[ignore = "makes a real (localhost) network connection — integration test"]
846    fn test_execute_service_remote_unreachable_fails_gracefully() {
847        let quins = vec![];
848        let engine = FederatedQueryEngine::new(&quins);
849        let mut service = FederatedService::new("http://127.0.0.1:1/sparql");
850        service.timeout_ms = 300;
851        let result = engine
852            .execute_service(&service, "SELECT ?s WHERE { ?s ?p ?o }")
853            .unwrap();
854        // A real fetch to an unreachable endpoint fails GRACEFULLY: success=false with a
855        // named error, and the constructed query URL is retained for provenance.
856        assert!(!result.success);
857        assert!(result.error.is_some());
858        assert!(result.remote_query_url.is_some());
859        assert_eq!(result.row_count(), 0);
860    }
861
862    #[test]
863    fn test_execute_federated_across_local_services() {
864        // Federation orchestration across multiple services, network-free (both local).
865        let quins = vec![];
866        let mut engine = FederatedQueryEngine::new(&quins);
867        engine.initialize().unwrap();
868
869        let query = FederatedQuery::new("SELECT ?s WHERE { ?s ?p ?o }")
870            .with_service(FederatedService::new("local:default"))
871            .with_service(FederatedService::new("qualia:graph1"));
872
873        let results = engine.execute_federated(&query).unwrap();
874        assert_eq!(results.len(), 2);
875        assert_eq!(results[0].service_endpoint, "local:default");
876        assert!(results[0].success);
877        assert!(results[0].remote_query_url.is_none());
878        assert_eq!(results[1].service_endpoint, "qualia:graph1");
879        assert!(results[1].success);
880    }
881
882    #[test]
883    fn test_parse_sparql_results_json_select() {
884        // A standard application/sparql-results+json SELECT response → real binding rows
885        // + a resolvable lexicon (incl. a language-tagged and a datatyped literal).
886        let body = r#"{
887          "head": { "vars": ["s", "name", "age"] },
888          "results": { "bindings": [
889            { "s": {"type":"uri","value":"http://ex/a"},
890              "name": {"type":"literal","xml:lang":"en","value":"Alice"},
891              "age": {"type":"literal","datatype":"http://www.w3.org/2001/XMLSchema#integer","value":"30"} }
892          ] }
893        }"#;
894        let (vars, rows, lexicon) = parse_sparql_results_json(body).unwrap();
895        assert_eq!(vars, vec!["s", "name", "age"]);
896        assert_eq!(rows.len(), 1);
897        let name_hash = rows[0].slots[1].unwrap();
898        assert_eq!(lexicon.resolve(name_hash), Some("Alice"));
899        assert_eq!(lexicon.lang(name_hash), Some("en"));
900        let age_hash = rows[0].slots[2].unwrap();
901        assert_eq!(
902            lexicon.datatype(age_hash),
903            Some("http://www.w3.org/2001/XMLSchema#integer")
904        );
905    }
906
907    #[test]
908    fn test_parse_sparql_results_json_ask() {
909        let (vars, rows, _lex) =
910            parse_sparql_results_json(r#"{ "head": {}, "boolean": true }"#).unwrap();
911        assert!(vars.is_empty());
912        assert_eq!(rows.len(), 1);
913        assert_eq!(rows[0].slots[0], Some(1));
914    }
915
916    #[test]
917    fn test_execute_federated_not_initialized() {
918        let quins = vec![];
919        let engine = FederatedQueryEngine::new(&quins);
920        let query = FederatedQuery::new("SELECT ?s WHERE { ?s ?p ?o }")
921            .with_service(FederatedService::new("local:default"));
922        let err = engine.execute_federated(&query).unwrap_err();
923        assert!(err.contains("not initialized"));
924    }
925
926    #[test]
927    fn test_execute_federated_no_services() {
928        let quins = vec![];
929        let mut engine = FederatedQueryEngine::new(&quins);
930        engine.initialize().unwrap();
931        let query = FederatedQuery::new("SELECT ?s WHERE { ?s ?p ?o }");
932        let err = engine.execute_federated(&query).unwrap_err();
933        assert!(err.contains("no services"));
934    }
935
936    #[test]
937    fn test_percent_encode_query() {
938        let encoded = percent_encode_query("SELECT ?s WHERE { ?s ?p ?o }");
939        assert!(!encoded.contains(' '));
940        assert!(encoded.contains("SELECT"));
941        // '?' should be encoded as %3F.
942        assert!(encoded.contains("%3F"));
943    }
944
945    #[test]
946    fn test_build_remote_query_url_joins_with_ampersand_when_query_present() {
947        // Endpoint already carrying a query string joins with '&', not a second '?'.
948        let url = build_remote_query_url("https://example.org/sparql?dataset=foo", "SELECT ?s");
949        assert!(url.contains("&query="));
950        assert!(!url.contains(' '));
951    }
952
953    #[test]
954    fn test_build_remote_query_url() {
955        let url = build_remote_query_url("https://example.org/sparql", "SELECT ?s");
956        assert!(url.starts_with("https://example.org/sparql?query="));
957        assert!(!url.contains(' '));
958    }
959}