oxirs-fuseki 0.2.4

SPARQL 1.1/1.2 HTTP protocol server with Fuseki-compatible configuration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! SHACL Validation HTTP Handler
//!
//! Provides HTTP endpoint for SHACL validation following Apache Jena Fuseki's pattern.
//!
//! POST /shacl?graph={graph-uri}
//! - Body: SHACL shapes graph (Turtle format)
//! - Returns: SHACL validation report
//!
//! Query parameters:
//! - graph: Target graph URI (or "default"/"union")
//! - target: Optional target node URI for focused validation

use async_graphql::indexmap::IndexMap;
use axum::{
    body::Bytes,
    extract::{Query, State},
    http::{header, HeaderMap, StatusCode},
    response::{IntoResponse, Response},
    Json,
};
use oxirs_core::Store;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Instant;
use tracing::{debug, info, warn};

/// SHACL validation query parameters
#[derive(Debug, Clone, Deserialize)]
pub struct ShaclParams {
    /// Target graph to validate ("default", "union", or graph URI)
    #[serde(default = "default_graph")]
    pub graph: String,

    /// Optional target node for focused validation
    pub target: Option<String>,
}

fn default_graph() -> String {
    "default".to_string()
}

/// SHACL validation error
#[derive(Debug, thiserror::Error)]
pub enum ShaclError {
    #[error("Graph not found: {0}")]
    GraphNotFound(String),

    #[error("Bad request: {0}")]
    BadRequest(String),

    #[error("Parse error: {0}")]
    ParseError(String),

    #[error("Validation error: {0}")]
    ValidationError(String),

    #[error("Store error: {0}")]
    StoreError(String),

    #[error("Internal error: {0}")]
    Internal(String),
}

impl ShaclError {
    fn status_code(&self) -> StatusCode {
        match self {
            ShaclError::GraphNotFound(_) => StatusCode::NOT_FOUND,
            ShaclError::BadRequest(_) => StatusCode::BAD_REQUEST,
            ShaclError::ParseError(_) => StatusCode::BAD_REQUEST,
            ShaclError::ValidationError(_) => StatusCode::BAD_REQUEST,
            ShaclError::StoreError(_) => StatusCode::INTERNAL_SERVER_ERROR,
            ShaclError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

impl IntoResponse for ShaclError {
    fn into_response(self) -> Response {
        let status = self.status_code();
        let message = self.to_string();

        (
            status,
            Json(serde_json::json!({
                "error": message,
                "status": status.as_u16(),
            })),
        )
            .into_response()
    }
}

/// SHACL validation report summary
#[derive(Debug, Clone, Serialize)]
pub struct ValidationSummary {
    /// Whether the data conforms to the shapes
    pub conforms: bool,

    /// Number of validation errors
    pub error_count: usize,

    /// Graph validated
    pub graph: String,

    /// Validation duration in milliseconds
    pub duration_ms: u64,

    /// Optional target node
    pub target_node: Option<String>,
}

/// Handle SHACL validation POST request
///
/// POST /shacl?graph={graph-uri}&target={node-uri}
/// Content-Type: text/turtle (SHACL shapes)
///
/// Returns: SHACL validation report in Turtle format
pub async fn handle_shacl_validation<S: Store + Send + Sync + 'static>(
    Query(params): Query<ShaclParams>,
    State(store): State<Arc<S>>,
    headers: HeaderMap,
    body: Bytes,
) -> Result<Response, ShaclError> {
    let start = Instant::now();

    info!(
        "SHACL validation request: graph={}, target={:?}",
        params.graph, params.target
    );

    // 1. Parse Content-Type (expect Turtle)
    let content_type = headers
        .get(header::CONTENT_TYPE)
        .and_then(|h| h.to_str().ok())
        .unwrap_or("text/turtle");

    if !content_type.contains("turtle") {
        return Err(ShaclError::BadRequest(format!(
            "Expected text/turtle, got {}",
            content_type
        )));
    }

    // 2. Parse shapes graph from request body
    let shapes_text = std::str::from_utf8(&body)
        .map_err(|e| ShaclError::ParseError(format!("UTF-8 error: {}", e)))?;

    debug!("Parsing SHACL shapes graph ({} bytes)", shapes_text.len());

    let parser = oxirs_core::parser::Parser::new(oxirs_core::parser::RdfFormat::Turtle);
    let shapes_triples: Vec<oxirs_core::model::Triple> = parser
        .parse_str_to_quads(shapes_text)
        .map_err(|e| ShaclError::ParseError(format!("Turtle parse error: {}", e)))?
        .into_iter()
        .map(|quad| quad.to_triple())
        .collect();

    info!("Parsed {} shape triples", shapes_triples.len());

    // 3. Get target data graph
    let data_triples = get_graph_triples(&params.graph, store.as_ref())?;

    info!(
        "Retrieved {} data triples from graph '{}'",
        data_triples.len(),
        params.graph
    );

    // 4. Run SHACL validation using oxirs-shacl validator
    let conforms = validate_shapes(&shapes_triples, &data_triples, params.target.as_deref())?;

    let duration = start.elapsed();

    info!(
        "SHACL validation completed: conforms={}, duration={:?}",
        conforms, duration
    );

    // 5. Build validation report
    let report =
        build_validation_report(conforms, &params.graph, params.target.as_deref(), duration);

    // 6. Serialize report as Turtle
    let report_turtle = serialize_validation_report(&report)?;

    // 7. Return response
    let status = if conforms {
        StatusCode::OK
    } else {
        StatusCode::BAD_REQUEST
    };

    Response::builder()
        .status(status)
        .header(header::CONTENT_TYPE, "text/turtle")
        .header("X-SHACL-Conforms", conforms.to_string())
        .header("X-Duration-Ms", duration.as_millis().to_string())
        .body(axum::body::Body::from(report_turtle))
        .map_err(|e| ShaclError::Internal(format!("Response build error: {}", e)))
}

/// Get triples from specified graph
fn get_graph_triples<S: Store>(
    graph_param: &str,
    store: &S,
) -> Result<Vec<oxirs_core::model::Triple>, ShaclError> {
    use oxirs_core::model::GraphName;

    let graph_name = match graph_param {
        "default" => GraphName::DefaultGraph,
        "union" => {
            // Union: get all triples
            return store
                .find_quads(None, None, None, None)
                .map(|quads| {
                    quads
                        .into_iter()
                        .map(|q| {
                            oxirs_core::model::Triple::new(
                                q.subject().clone(),
                                q.predicate().clone(),
                                q.object().clone(),
                            )
                        })
                        .collect()
                })
                .map_err(|e| ShaclError::StoreError(e.to_string()));
        }
        uri => {
            let node = oxirs_core::model::NamedNode::new(uri)
                .map_err(|e| ShaclError::BadRequest(format!("Invalid graph URI: {}", e)))?;
            GraphName::NamedNode(node)
        }
    };

    // Get quads from specified graph
    let quads = store
        .find_quads(None, None, None, Some(&graph_name))
        .map_err(|e| ShaclError::StoreError(e.to_string()))?;

    if quads.is_empty() {
        return Err(ShaclError::GraphNotFound(graph_param.to_string()));
    }

    // Convert quads to triples
    Ok(quads
        .into_iter()
        .map(|q| {
            oxirs_core::model::Triple::new(
                q.subject().clone(),
                q.predicate().clone(),
                q.object().clone(),
            )
        })
        .collect())
}

/// Validate data against shapes using actual oxirs-shacl validator
fn validate_shapes(
    shapes_triples: &[oxirs_core::model::Triple],
    data_triples: &[oxirs_core::model::Triple],
    target_node: Option<&str>,
) -> Result<bool, ShaclError> {
    debug!(
        "Validating {} data triples against {} shape triples",
        data_triples.len(),
        shapes_triples.len()
    );

    if let Some(target) = target_node {
        debug!("Focused validation on target node: {}", target);
    }

    // 1. Parse shapes from triples using oxirs-shacl
    let shapes_store = oxirs_core::rdf_store::ConcreteStore::new().map_err(|e| {
        ShaclError::ValidationError(format!("Failed to create shapes store: {}", e))
    })?;

    for triple in shapes_triples {
        shapes_store.insert_triple(triple.clone()).map_err(|e| {
            ShaclError::ValidationError(format!("Failed to insert shape triple: {}", e))
        })?;
    }

    // 2. Use ShapeParser to extract SHACL shapes from the RDF graph
    let mut shape_parser = oxirs_shacl::ShapeParser::new();
    let shapes_vec = shape_parser
        .parse_shapes_from_store(&shapes_store, None) // None = default graph
        .map_err(|e| ShaclError::ValidationError(format!("Shape parsing failed: {}", e)))?;

    if shapes_vec.is_empty() {
        warn!("No SHACL shapes found in the shapes graph");
        return Ok(true); // No shapes = no constraints to violate
    }

    // Convert Vec<Shape> to IndexMap<ShapeId, Shape> for the validation engine
    let shapes: IndexMap<_, _> = shapes_vec
        .into_iter()
        .map(|shape| (shape.id.clone(), shape))
        .collect();

    info!("Parsed {} SHACL shapes", shapes.len());

    // 3. Create data store for validation
    let data_store = oxirs_core::rdf_store::ConcreteStore::new()
        .map_err(|e| ShaclError::ValidationError(format!("Failed to create data store: {}", e)))?;

    for triple in data_triples {
        data_store.insert_triple(triple.clone()).map_err(|e| {
            ShaclError::ValidationError(format!("Failed to insert data triple: {}", e))
        })?;
    }

    // 4. Configure validation
    let config = oxirs_shacl::ValidationConfig {
        max_violations: 0, // Unlimited violations for comprehensive reports
        include_info: true,
        include_warnings: true,
        fail_fast: false, // Get all violations
        max_recursion_depth: 100,
        timeout_ms: Some(60000), // 60 second timeout
        parallel: true,          // Enable parallel validation for performance
        context: std::collections::HashMap::new(),
        strategy: oxirs_shacl::ValidationStrategy::Optimized,
    };

    // 5. Create validation engine
    let mut engine = oxirs_shacl::ValidationEngine::new(&shapes, config);

    // 6. Run validation
    let report = if let Some(target_iri) = target_node {
        // Focused validation on specific target node against all shapes
        let target_term = oxirs_core::model::NamedNode::new(target_iri)
            .map_err(|e| ShaclError::ValidationError(format!("Invalid target node IRI: {}", e)))?;

        let target_terms = vec![oxirs_core::model::Term::NamedNode(target_term)];

        // Validate the target node(s) against all shapes
        let mut combined_report = oxirs_shacl::ValidationReport::new();
        for shape in shapes.values() {
            let shape_report = engine
                .validate_nodes(&data_store, shape, &target_terms)
                .map_err(|e| ShaclError::ValidationError(format!("Validation failed: {}", e)))?;
            combined_report.merge_result(shape_report);
        }
        combined_report
    } else {
        // Full store validation
        engine
            .validate_store(&data_store)
            .map_err(|e| ShaclError::ValidationError(format!("Validation failed: {}", e)))?
    };

    // 7. Check if data conforms to shapes
    let conforms = report.conforms;

    debug!(
        "Validation complete: conforms={}, violations={}",
        conforms,
        report.violations.len()
    );

    Ok(conforms)
}

/// Build SHACL validation report
fn build_validation_report(
    conforms: bool,
    graph: &str,
    target_node: Option<&str>,
    duration: std::time::Duration,
) -> ValidationSummary {
    ValidationSummary {
        conforms,
        error_count: if conforms { 0 } else { 1 },
        graph: graph.to_string(),
        duration_ms: duration.as_millis() as u64,
        target_node: target_node.map(|s| s.to_string()),
    }
}

/// Serialize validation report as Turtle
fn serialize_validation_report(report: &ValidationSummary) -> Result<String, ShaclError> {
    // Build SHACL validation report in Turtle format
    // Following W3C SHACL specification

    let turtle = format!(
        r#"@prefix sh: <http://www.w3.org/ns/shacl#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

[]
    a sh:ValidationReport ;
    sh:conforms {} ;
    sh:result [] .
"#,
        if report.conforms { "true" } else { "false" }
    );

    Ok(turtle)
}

/// Server-specific handler that works with AppState
pub async fn handle_shacl_validation_server(
    Query(params): Query<ShaclParams>,
    State(state): State<std::sync::Arc<crate::server::AppState>>,
    headers: HeaderMap,
    body: Bytes,
) -> Response {
    match handle_shacl_validation(
        Query(params),
        State(std::sync::Arc::new(state.store.clone())),
        headers,
        body,
    )
    .await
    {
        Ok(response) => response,
        Err(err) => err.into_response(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use oxirs_core::rdf_store::ConcreteStore;

    fn setup_test_store() -> Arc<ConcreteStore> {
        let store = ConcreteStore::new().unwrap();

        // Add test data
        let turtle_data = r#"@prefix ex: <http://example.org/> .
ex:Alice <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ex:Person .
ex:Alice ex:name "Alice" .
ex:Alice ex:age "30" .
"#;

        let triples = oxirs_core::format::turtle::TurtleParser::new()
            .parse_str(turtle_data)
            .unwrap();
        for triple in triples {
            store.insert_triple(triple).unwrap();
        }

        Arc::new(store)
    }

    #[tokio::test]
    async fn test_shacl_params_default() {
        let params = ShaclParams {
            graph: "default".to_string(),
            target: None,
        };

        assert_eq!(params.graph, "default");
        assert!(params.target.is_none());
    }

    #[test]
    fn test_get_graph_triples_default() {
        let store = setup_test_store();
        let result = get_graph_triples("default", store.as_ref());

        assert!(result.is_ok());
        let triples = result.unwrap();
        assert!(!triples.is_empty());
    }

    #[test]
    fn test_validate_shapes_placeholder() {
        let shapes = vec![];
        let data = vec![];

        let result = validate_shapes(&shapes, &data, None);
        assert!(result.is_ok());
        assert!(result.unwrap()); // Placeholder returns true
    }

    #[test]
    fn test_build_validation_report() {
        let report =
            build_validation_report(true, "default", None, std::time::Duration::from_millis(100));

        assert!(report.conforms);
        assert_eq!(report.error_count, 0);
        assert_eq!(report.graph, "default");
    }

    #[test]
    fn test_serialize_validation_report() {
        let report = ValidationSummary {
            conforms: true,
            error_count: 0,
            graph: "default".to_string(),
            duration_ms: 100,
            target_node: None,
        };

        let turtle = serialize_validation_report(&report).unwrap();
        assert!(turtle.contains("sh:ValidationReport"));
        assert!(turtle.contains("sh:conforms true"));
    }
}