oxirs-gql 0.2.4

GraphQL façade for OxiRS with automatic schema generation from RDF ontologies
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
//! # OxiRS GraphQL - GraphQL Interface for RDF
//!
//! [![Version](https://img.shields.io/badge/version-0.2.4-blue)](https://github.com/cool-japan/oxirs/releases)
//! [![docs.rs](https://docs.rs/oxirs-gql/badge.svg)](https://docs.rs/oxirs-gql)
//!
//! **Status**: Production Release (v0.2.4)
//! **Stability**: Public APIs are stable. Production-ready with comprehensive testing.
//!
//! GraphQL interface for RDF data with automatic schema generation from ontologies.
//! Enables modern GraphQL clients to query knowledge graphs with intuitive GraphQL syntax.
//!
//! ## Features
//!
//! - **Automatic Schema Generation** - Generate GraphQL schemas from RDF vocabularies
//! - **GraphQL to SPARQL** - Transparent translation of GraphQL queries to SPARQL
//! - **Type Mapping** - Map RDF classes to GraphQL types
//! - **Query Support** - Full GraphQL query capabilities
//! - **Subscriptions** - WebSocket-based subscriptions (experimental)
//!
//! ## See Also
//!
//! - [`oxirs-core`](https://docs.rs/oxirs-core) - RDF data model
//! - [`oxirs-arq`](https://docs.rs/oxirs-arq) - SPARQL query engine

use anyhow::Result;
use oxirs_core::model::{
    BlankNode, GraphName, Literal as OxiLiteral, NamedNode, Quad, Subject, Term, Variable,
};
use oxirs_core::ConcreteStore;
use std::sync::{Arc, Mutex};

// Re-export QueryResults for other modules
pub use oxirs_core::query::QueryResults;

// Module declarations are below after the main code

/// RDF store wrapper for GraphQL integration
pub struct RdfStore {
    store: Arc<Mutex<ConcreteStore>>,
}

impl std::fmt::Debug for RdfStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RdfStore")
            .field("store", &"Store { ... }")
            .finish()
    }
}

impl RdfStore {
    pub fn new() -> Result<Self> {
        Ok(Self {
            store: Arc::new(Mutex::new(ConcreteStore::new()?)),
        })
    }

    pub fn open<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
        Ok(Self {
            store: Arc::new(Mutex::new(ConcreteStore::open(path)?)),
        })
    }

    /// Execute a SPARQL query and return results
    pub fn query(&self, query: &str) -> Result<QueryResults> {
        use oxirs_core::query::{QueryEngine, QueryResult};

        let store = self
            .store
            .lock()
            .map_err(|e| anyhow::anyhow!("Mutex lock error: {}", e))?;
        let engine = QueryEngine::new();
        let result = engine
            .query(query, &*store)
            .map_err(|e| anyhow::anyhow!("SPARQL query error: {}", e))?;

        match result {
            QueryResult::Select {
                variables: _,
                bindings,
            } => {
                let mut solutions = Vec::new();
                for binding in bindings {
                    let mut solution = oxirs_core::query::Solution::new();
                    for (var_name, term) in binding {
                        if let Ok(var) = oxirs_core::model::Variable::new(&var_name) {
                            solution.bind(var, term);
                        }
                    }
                    solutions.push(solution);
                }
                Ok(QueryResults::Solutions(solutions))
            }
            QueryResult::Ask(result) => Ok(QueryResults::Boolean(result)),
            QueryResult::Construct(triples) => {
                // Return triples directly (not quads)
                Ok(QueryResults::Graph(triples))
            }
        }
    }

    /// Get count of triples in the store
    pub fn triple_count(&self) -> Result<usize> {
        let query = "SELECT (COUNT(*) as ?count) WHERE { ?s ?p ?o }";
        if let QueryResults::Solutions(solutions) = self.query(query)? {
            if let Some(solution) = solutions.first() {
                let count_var = Variable::new("count")
                    .map_err(|e| anyhow::anyhow!("Failed to create count variable: {}", e))?;
                if let Some(Term::Literal(lit)) = solution.get(&count_var) {
                    let count = lit.value().parse::<usize>().map_err(|e| {
                        anyhow::anyhow!("Failed to parse count value '{}': {}", lit.value(), e)
                    })?;
                    return Ok(count);
                }
            }
        }
        Ok(0)
    }

    /// Get subjects with optional limit
    pub fn get_subjects(&self, limit: Option<usize>) -> Result<Vec<String>> {
        let limit_clause = match limit {
            Some(l) => format!(" LIMIT {l}"),
            None => String::new(),
        };

        let query = format!("SELECT DISTINCT ?s WHERE {{ ?s ?p ?o }}{limit_clause}");
        let mut subjects = Vec::new();

        let subject_var = Variable::new("s")
            .map_err(|e| anyhow::anyhow!("Failed to create subject variable: {}", e))?;

        if let QueryResults::Solutions(solutions) = self.query(&query)? {
            for solution in &solutions {
                if let Some(subject) = solution.get(&subject_var) {
                    subjects.push(subject.to_string());
                }
            }
        }

        Ok(subjects)
    }

    /// Get predicates with optional limit
    pub fn get_predicates(&self, limit: Option<usize>) -> Result<Vec<String>> {
        let limit_clause = match limit {
            Some(l) => format!(" LIMIT {l}"),
            None => String::new(),
        };

        let query = format!("SELECT DISTINCT ?p WHERE {{ ?s ?p ?o }}{limit_clause}");
        let mut predicates = Vec::new();

        let predicate_var = Variable::new("p")
            .map_err(|e| anyhow::anyhow!("Failed to create predicate variable: {}", e))?;

        if let QueryResults::Solutions(solutions) = self.query(&query)? {
            for solution in &solutions {
                if let Some(predicate) = solution.get(&predicate_var) {
                    predicates.push(predicate.to_string());
                }
            }
        }

        Ok(predicates)
    }

    /// Get objects with optional limit
    pub fn get_objects(&self, limit: Option<usize>) -> Result<Vec<(String, String)>> {
        let limit_clause = match limit {
            Some(l) => format!(" LIMIT {l}"),
            None => String::new(),
        };

        let query = format!("SELECT DISTINCT ?o WHERE {{ ?s ?p ?o }}{limit_clause}");
        let mut objects = Vec::new();

        let object_var = Variable::new("o")
            .map_err(|e| anyhow::anyhow!("Failed to create object variable: {}", e))?;

        if let QueryResults::Solutions(solutions) = self.query(&query)? {
            for solution in &solutions {
                if let Some(object) = solution.get(&object_var) {
                    let object_type = match object {
                        Term::NamedNode(_) => "IRI".to_string(),
                        Term::BlankNode(_) => "BlankNode".to_string(),
                        Term::Literal(_) => "Literal".to_string(),
                        Term::Variable(_) => "Variable".to_string(),
                        Term::QuotedTriple(_) => "QuotedTriple".to_string(),
                    };
                    objects.push((object.to_string(), object_type));
                }
            }
        }

        Ok(objects)
    }

    /// Insert a triple into the store
    pub fn insert_triple(&mut self, subject: &str, predicate: &str, object: &str) -> Result<()> {
        // Parse terms
        let subject = if let Some(stripped) = subject.strip_prefix("_:") {
            Subject::BlankNode(BlankNode::new(stripped)?)
        } else {
            Subject::NamedNode(NamedNode::new(subject)?)
        };

        let predicate = NamedNode::new(predicate)?;

        let object = if object.starts_with("\"") && object.ends_with("\"") {
            // It's a literal
            let literal_value = &object[1..object.len() - 1];
            Term::Literal(OxiLiteral::new_simple_literal(literal_value))
        } else if let Some(stripped) = object.strip_prefix("_:") {
            // It's a blank node
            Term::BlankNode(BlankNode::new(stripped)?)
        } else {
            // It's a named node
            Term::NamedNode(NamedNode::new(object)?)
        };

        let quad = Quad::new(subject, predicate, object, GraphName::DefaultGraph);
        let store = self
            .store
            .lock()
            .map_err(|e| anyhow::anyhow!("Mutex lock error: {}", e))?;
        store.insert_quad(quad)?;
        Ok(())
    }

    /// Insert a quad into the store
    pub fn insert(&self, quad: &oxirs_core::model::Quad) -> Result<()> {
        let store = self
            .store
            .lock()
            .map_err(|e| anyhow::anyhow!("Mutex lock error: {}", e))?;
        store.insert_quad(quad.clone())?;
        Ok(())
    }

    /// Load data from a file
    pub fn load_file<P: AsRef<std::path::Path>>(&mut self, path: P, format: &str) -> Result<()> {
        use oxirs_core::parser::{Parser, RdfFormat};
        use std::fs;

        let format = match format.to_lowercase().as_str() {
            "turtle" | "ttl" => RdfFormat::Turtle,
            "ntriples" | "nt" => RdfFormat::NTriples,
            "rdfxml" | "rdf" => RdfFormat::RdfXml,
            "jsonld" | "json" => RdfFormat::JsonLd,
            _ => return Err(anyhow::anyhow!("Unsupported format: {}", format)),
        };

        // Read file content
        let content = fs::read_to_string(path)?;

        // Parse content to quads
        let parser = Parser::new(format);
        let quads = parser.parse_str_to_quads(&content)?;

        // Insert quads into store
        let store = self
            .store
            .lock()
            .map_err(|e| anyhow::anyhow!("Mutex lock error: {}", e))?;
        for quad in quads {
            store.insert_quad(quad)?;
        }

        Ok(())
    }
}

/// Mock store for testing GraphQL functionality
#[derive(Debug)]
pub struct MockStore;

impl MockStore {
    pub fn new() -> Result<Self> {
        Ok(Self)
    }

    pub fn open(_path: String) -> Result<Self> {
        Ok(Self)
    }
}

// Individual modules
pub mod aggregation;
pub mod ai;
pub mod api_explorer;
pub mod ast;
pub mod auto_caching_strategies;
pub mod custom_directives;
pub mod custom_type_mappings;
pub mod directive_registry;
pub mod enhanced_errors;
pub mod execution;
pub mod federation;
pub mod file_upload;
pub mod graphiql_integration;
pub mod historical_cost_estimator;
pub mod horizontal_scaling;
pub mod hybrid_optimizer;
pub mod intelligent_federation_gateway;
pub mod intelligent_query_cache;
pub mod introspection;
pub mod live_queries;
pub mod mapping;
pub mod ml_optimizer;
pub mod optimizer;
pub mod owl_enhanced_schema;
pub mod pagination_filtering;
pub mod parallel_field_resolver;
pub mod parser;
pub mod persisted_queries;
pub mod playground_integration;
pub mod quantum_optimizer;
pub mod query_builder;
pub mod query_debugger;
pub mod query_prefetcher;
pub mod rate_limiting;
pub mod rdf_scalars;
pub mod request_deduplication;
pub mod resolvers;
pub mod schema;
pub mod schema_cache;
pub mod schema_docs_generator;
pub mod server;
pub mod sse_subscriptions;
pub mod subscriptions;
pub mod types;
pub mod validation;
pub mod zero_trust_security;

// v0.2.0 Operational Enhancements
pub mod api_versioning;
pub mod blue_green_deployment;
pub mod canary_release;
pub mod circuit_breaker;
pub mod graphql_mesh;
pub mod multi_region;
pub mod performance_insights;
pub mod schema_changelog;
pub mod visual_schema_designer;

// v0.3.0 Security & Integration Features
pub mod content_security_policy;
pub mod edge_caching;
pub mod query_sanitization;
pub mod response_streaming;
pub mod webhook_support;

// v0.4.0 Advanced Observability & Protocol Features
pub mod cost_based_optimizer;
pub mod incremental_execution;
pub mod query_batching;
pub mod query_plan_visualizer;
pub mod query_result_streaming;

// v0.5.0 Advanced Observability & Monitoring
pub mod graphql_span_attributes;
pub mod performance_anomaly_detector;
pub mod performance_heatmap;
pub mod query_pattern_analyzer;
pub mod trace_correlation;
pub mod trace_sampling;
pub mod trace_visualization;
pub mod tracing_exporters;

// Advanced performance modules
pub mod advanced_cache;
pub mod advanced_security_system;
pub mod ai_query_predictor;
pub mod async_streaming;
pub mod benchmarking;
pub mod dataloader;
pub mod neuromorphic_query_processor;
pub mod performance;
pub mod predictive_analytics;
pub mod quantum_real_time_analytics;
pub mod system_monitor;

// Ultra-modern enterprise modules (July 5, 2025 enhancements)
pub mod advanced_query_planner;
pub mod advanced_subscriptions;
pub mod ai_orchestration_engine;
pub mod observability;

// Production-ready features (November 2025)
pub mod production;

// v0.6.0 Enhanced Subscriptions, Multi-tenancy, and Query Caching
pub mod cache;
pub mod multitenancy;
pub mod subscription;
// v1.1.0 Enhanced tenant module with schema registry, query filter, rate limiter
pub mod tenant;
// v1.1.0 Apollo Federation v2 Subgraph Support
pub mod federation_v2;

// v1.2.0 GraphQL Schema Version Registry
pub mod schema_registry;

// v1.1.0 Relay Cursor-based Pagination
pub mod cursor_pagination;

// v1.2.0 GraphQL subscription lifecycle management
pub mod subscription_manager;

// v1.2.0 DataLoader / batch resolver for GraphQL N+1 resolution
pub mod batch_resolver;

// v1.5.0 GraphQL __schema / __type introspection engine
pub mod type_introspection;

// Organized module groups
pub mod core;
pub mod distributed_cache;
pub mod docs;
pub mod dynamic_query_planner;
pub mod features;
pub mod networking;
pub mod rdf;

// v1.6.0 Field-level resolver pipeline with middleware
pub mod field_resolver;

// v1.7.0 GraphQL query complexity analysis and limiting
pub mod query_complexity;

// v1.8.0 GraphQL error formatting, classification, and aggregation
pub mod error_formatter;

// v1.9.0 Custom GraphQL directive processing engine
pub mod directive_processor;

// v1.10.0 GraphQL pagination handler (Relay cursor spec)
pub mod pagination_handler;

// v1.11.0 GraphQL field-level validation rules engine
pub mod field_validator;

// v1.1.0 round 16 GraphQL enum type resolution and coercion
pub mod enum_resolver;

// v1.1.0 round 15 GraphQL argument type coercion and validation
pub mod argument_coercer;

// Juniper-based implementation with proper RDF integration (enabled)
pub mod juniper_schema;
pub mod juniper_server; // Complex Hyper v1 version - API issues fixed
pub mod simple_juniper_server; // Simplified version

// Juniper integration - comprehensive RDF GraphQL support
pub use juniper_schema::{create_schema, GraphQLContext, Schema as JuniperSchema};
pub use simple_juniper_server::{
    start_graphql_server, start_graphql_server_with_config, GraphQLServerBuilder,
    GraphQLServerConfig, JuniperGraphQLServer,
};

// Intelligent query caching
pub use intelligent_query_cache::{
    IntelligentCacheConfig, IntelligentQueryCache, QueryPattern, QueryUsageStats,
};

// Advanced Juniper server with full Hyper v1 support
pub use juniper_server::{
    start_graphql_server as start_advanced_graphql_server,
    start_graphql_server_with_config as start_advanced_graphql_server_with_config,
    GraphQLServerBuilder as AdvancedGraphQLServerBuilder,
    GraphQLServerConfig as AdvancedGraphQLServerConfig,
    JuniperGraphQLServer as AdvancedJuniperGraphQLServer,
};

#[cfg(test)]
mod tests;

/// GraphQL server configuration
#[derive(Debug, Clone)]
pub struct GraphQLConfig {
    pub enable_introspection: bool,
    pub enable_playground: bool,
    pub max_query_depth: Option<usize>,
    pub max_query_complexity: Option<usize>,
    pub validation_config: validation::ValidationConfig,
    pub enable_query_validation: bool,
    pub distributed_cache_config: Option<distributed_cache::CacheConfig>,
}

impl Default for GraphQLConfig {
    fn default() -> Self {
        Self {
            enable_introspection: true,
            enable_playground: true,
            max_query_depth: Some(10),
            max_query_complexity: Some(1000),
            validation_config: validation::ValidationConfig::default(),
            enable_query_validation: true,
            distributed_cache_config: None, // Disabled by default
        }
    }
}

/// Main GraphQL server
pub struct GraphQLServer {
    config: GraphQLConfig,
    store: Arc<RdfStore>,
    cache: Option<Arc<distributed_cache::GraphQLQueryCache>>,
}

impl GraphQLServer {
    pub fn new(store: Arc<RdfStore>) -> Self {
        Self {
            config: GraphQLConfig::default(),
            store,
            cache: None,
        }
    }

    pub fn new_with_mock(_store: Arc<MockStore>) -> Result<Self> {
        // For backward compatibility during transition
        let rdf_store = Arc::new(
            RdfStore::new()
                .map_err(|e| anyhow::anyhow!("Failed to create RDF store for mock: {}", e))?,
        );
        Ok(Self {
            config: GraphQLConfig::default(),
            store: rdf_store,
            cache: None,
        })
    }

    pub fn with_config(mut self, config: GraphQLConfig) -> Self {
        self.config = config;
        self
    }

    /// Enable distributed caching
    pub async fn with_distributed_cache(
        mut self,
        cache_config: distributed_cache::CacheConfig,
    ) -> Result<Self> {
        let cache = Arc::new(distributed_cache::GraphQLQueryCache::new(cache_config).await?);
        self.cache = Some(cache);
        Ok(self)
    }

    /// Get cache statistics if caching is enabled
    pub async fn get_cache_stats(&self) -> Option<distributed_cache::CacheStats> {
        if let Some(cache) = &self.cache {
            cache.get_stats().await.ok()
        } else {
            None
        }
    }

    pub async fn start(&self, addr: &str) -> Result<()> {
        tracing::info!("Starting GraphQL server on {}", addr);

        // Create a basic schema with Query type
        let mut schema = types::Schema::new();

        // Add a Query type with more fields
        let mut query_type = types::ObjectType::new("Query".to_string())
            .with_description("The root query type for RDF data access".to_string())
            .with_field(
                "hello".to_string(),
                types::FieldType::new(
                    "hello".to_string(),
                    types::GraphQLType::Scalar(types::BuiltinScalars::string()),
                )
                .with_description("A simple greeting message".to_string()),
            )
            .with_field(
                "version".to_string(),
                types::FieldType::new(
                    "version".to_string(),
                    types::GraphQLType::Scalar(types::BuiltinScalars::string()),
                )
                .with_description("OxiRS GraphQL version".to_string()),
            )
            .with_field(
                "triples".to_string(),
                types::FieldType::new(
                    "triples".to_string(),
                    types::GraphQLType::Scalar(types::BuiltinScalars::int()),
                )
                .with_description("Count of triples in the store".to_string()),
            )
            .with_field(
                "subjects".to_string(),
                types::FieldType::new(
                    "subjects".to_string(),
                    types::GraphQLType::List(Box::new(types::GraphQLType::Scalar(
                        types::BuiltinScalars::string(),
                    ))),
                )
                .with_description("List of subject IRIs".to_string())
                .with_argument(
                    "limit".to_string(),
                    types::ArgumentType::new(
                        "limit".to_string(),
                        types::GraphQLType::Scalar(types::BuiltinScalars::int()),
                    )
                    .with_default_value(ast::Value::IntValue(10))
                    .with_description("Maximum number of subjects to return".to_string()),
                ),
            )
            .with_field(
                "predicates".to_string(),
                types::FieldType::new(
                    "predicates".to_string(),
                    types::GraphQLType::List(Box::new(types::GraphQLType::Scalar(
                        types::BuiltinScalars::string(),
                    ))),
                )
                .with_description("List of predicate IRIs".to_string())
                .with_argument(
                    "limit".to_string(),
                    types::ArgumentType::new(
                        "limit".to_string(),
                        types::GraphQLType::Scalar(types::BuiltinScalars::int()),
                    )
                    .with_default_value(ast::Value::IntValue(10))
                    .with_description("Maximum number of predicates to return".to_string()),
                ),
            )
            .with_field(
                "objects".to_string(),
                types::FieldType::new(
                    "objects".to_string(),
                    types::GraphQLType::List(Box::new(types::GraphQLType::Scalar(
                        types::BuiltinScalars::string(),
                    ))),
                )
                .with_description("List of objects".to_string())
                .with_argument(
                    "limit".to_string(),
                    types::ArgumentType::new(
                        "limit".to_string(),
                        types::GraphQLType::Scalar(types::BuiltinScalars::int()),
                    )
                    .with_default_value(ast::Value::IntValue(10))
                    .with_description("Maximum number of objects to return".to_string()),
                ),
            )
            .with_field(
                "sparql".to_string(),
                types::FieldType::new(
                    "sparql".to_string(),
                    types::GraphQLType::Scalar(types::BuiltinScalars::string()),
                )
                .with_description("Execute a raw SPARQL query".to_string())
                .with_argument(
                    "query".to_string(),
                    types::ArgumentType::new(
                        "query".to_string(),
                        types::GraphQLType::NonNull(Box::new(types::GraphQLType::Scalar(
                            types::BuiltinScalars::string(),
                        ))),
                    )
                    .with_description("The SPARQL query to execute".to_string()),
                ),
            );

        // Add introspection fields if enabled
        if self.config.enable_introspection {
            query_type = query_type
                .with_field(
                    "__schema".to_string(),
                    types::FieldType::new(
                        "__schema".to_string(),
                        types::GraphQLType::NonNull(Box::new(types::GraphQLType::Scalar(
                            types::ScalarType {
                                name: "__Schema".to_string(),
                                description: Some(
                                    "A GraphQL Schema defines the capabilities of a GraphQL server"
                                        .to_string(),
                                ),
                                serialize: |_| Ok(ast::Value::NullValue),
                                parse_value: |_| Err(anyhow::anyhow!("Cannot parse __Schema")),
                                parse_literal: |_| Err(anyhow::anyhow!("Cannot parse __Schema")),
                            },
                        ))),
                    )
                    .with_description("Access the current type schema of this server".to_string()),
                )
                .with_field(
                    "__type".to_string(),
                    types::FieldType::new(
                        "__type".to_string(),
                        types::GraphQLType::Scalar(types::ScalarType {
                            name: "__Type".to_string(),
                            description: Some(
                                "A GraphQL Schema defines the capabilities of a GraphQL server"
                                    .to_string(),
                            ),
                            serialize: |_| Ok(ast::Value::NullValue),
                            parse_value: |_| Err(anyhow::anyhow!("Cannot parse __Type")),
                            parse_literal: |_| Err(anyhow::anyhow!("Cannot parse __Type")),
                        }),
                    )
                    .with_description("Request the type information of a single type".to_string())
                    .with_argument(
                        "name".to_string(),
                        types::ArgumentType::new(
                            "name".to_string(),
                            types::GraphQLType::NonNull(Box::new(types::GraphQLType::Scalar(
                                types::BuiltinScalars::string(),
                            ))),
                        )
                        .with_description("The name of the type to introspect".to_string()),
                    ),
                );
        }

        schema.add_type(types::GraphQLType::Object(query_type));
        schema.set_query_type("Query".to_string());

        // Create the server with resolvers
        let schema_clone = schema.clone();
        let mut server = server::Server::new(schema.clone())
            .with_playground(self.config.enable_playground)
            .with_introspection(self.config.enable_introspection);

        // Configure validation if enabled
        if self.config.enable_query_validation {
            server =
                server.with_validation(self.config.validation_config.clone(), schema_clone.clone());
        }

        // Set up resolvers
        let query_resolvers = resolvers::QueryResolvers::new(Arc::clone(&self.store));
        server.add_resolver("Query".to_string(), query_resolvers.rdf_resolver());

        // Add introspection resolver
        let introspection_resolver = Arc::new(introspection::IntrospectionResolver::new(Arc::new(
            schema_clone,
        )));
        server.add_resolver("__Schema".to_string(), introspection_resolver.clone());
        server.add_resolver("__Type".to_string(), introspection_resolver.clone());
        server.add_resolver("__Field".to_string(), introspection_resolver.clone());
        server.add_resolver("__InputValue".to_string(), introspection_resolver.clone());
        server.add_resolver("__EnumValue".to_string(), introspection_resolver.clone());
        server.add_resolver("__Directive".to_string(), introspection_resolver);

        // Parse the address
        let socket_addr: std::net::SocketAddr = addr
            .parse()
            .map_err(|e| anyhow::anyhow!("Invalid address '{}': {}", addr, e))?;

        server.start(socket_addr).await
    }
}

// Comprehensive module declarations moved to top of file to avoid duplicates