oxirs-gql 0.2.2

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
757
758
759
760
761
762
763
764
//! GraphQL Mesh Integration
//!
//! This module provides integration with GraphQL Mesh concepts for combining
//! multiple data sources into a unified GraphQL API.
//!
//! ## Features
//!
//! - **Source Management**: Define and manage multiple data sources
//! - **Transform Pipelines**: Apply transforms to source schemas
//! - **Type Merging**: Merge types across sources
//! - **Cross-Source Relationships**: Define relationships between sources
//! - **Caching Layer**: Unified caching across sources

use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use tokio::sync::RwLock;

/// Data source type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SourceType {
    /// GraphQL endpoint
    GraphQL,
    /// REST API
    REST,
    /// OpenAPI specification
    OpenAPI,
    /// SOAP service
    SOAP,
    /// gRPC service
    GRPC,
    /// OData endpoint
    OData,
    /// Database (SQL)
    Database,
    /// JSON Schema
    JsonSchema,
    /// Custom source
    Custom,
}

/// Data source configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataSource {
    /// Source identifier
    pub id: String,
    /// Source name
    pub name: String,
    /// Source type
    pub source_type: SourceType,
    /// Endpoint URL
    pub endpoint: String,
    /// Schema (SDL for GraphQL, spec for OpenAPI, etc.)
    pub schema: Option<String>,
    /// Authentication configuration
    pub auth: Option<AuthConfig>,
    /// Headers to include
    pub headers: HashMap<String, String>,
    /// Transforms to apply
    pub transforms: Vec<Transform>,
    /// Cache configuration
    pub cache: Option<CacheConfig>,
    /// Health check endpoint
    pub health_check: Option<String>,
    /// Is enabled
    pub enabled: bool,
    /// Metadata
    pub metadata: HashMap<String, String>,
}

impl DataSource {
    /// Create a new data source
    pub fn new(id: &str, name: &str, source_type: SourceType, endpoint: &str) -> Self {
        Self {
            id: id.to_string(),
            name: name.to_string(),
            source_type,
            endpoint: endpoint.to_string(),
            schema: None,
            auth: None,
            headers: HashMap::new(),
            transforms: Vec::new(),
            cache: None,
            health_check: None,
            enabled: true,
            metadata: HashMap::new(),
        }
    }

    /// Add authentication
    pub fn with_auth(mut self, auth: AuthConfig) -> Self {
        self.auth = Some(auth);
        self
    }

    /// Add header
    pub fn with_header(mut self, key: &str, value: &str) -> Self {
        self.headers.insert(key.to_string(), value.to_string());
        self
    }

    /// Add transform
    pub fn with_transform(mut self, transform: Transform) -> Self {
        self.transforms.push(transform);
        self
    }

    /// Set cache configuration
    pub fn with_cache(mut self, cache: CacheConfig) -> Self {
        self.cache = Some(cache);
        self
    }
}

/// Authentication configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AuthConfig {
    /// No authentication
    None,
    /// Basic authentication
    Basic { username: String, password: String },
    /// Bearer token
    Bearer { token: String },
    /// API key
    ApiKey { key: String, header: String },
    /// OAuth2
    OAuth2 {
        client_id: String,
        client_secret: String,
        token_url: String,
        scopes: Vec<String>,
    },
    /// Custom
    Custom { config: HashMap<String, String> },
}

/// Transform type
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Transform {
    /// Prefix type names
    Prefix { value: String },
    /// Rename type
    Rename { from: String, to: String },
    /// Filter types
    FilterTypes { include: Vec<String> },
    /// Filter fields
    FilterFields {
        type_name: String,
        include: Vec<String>,
    },
    /// Add field
    AddField {
        type_name: String,
        field_name: String,
        field_type: String,
    },
    /// Encapsulate with namespace
    Encapsulate { namespace: String },
    /// Snapshot (freeze schema)
    Snapshot { name: String },
    /// Custom transform
    Custom {
        name: String,
        config: HashMap<String, String>,
    },
}

/// Cache configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheConfig {
    /// Cache TTL
    pub ttl: Duration,
    /// Max cache entries
    pub max_entries: usize,
    /// Cache key strategy
    pub key_strategy: CacheKeyStrategy,
    /// Invalidation events
    pub invalidation_events: Vec<String>,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            ttl: Duration::from_secs(60),
            max_entries: 1000,
            key_strategy: CacheKeyStrategy::default(),
            invalidation_events: Vec::new(),
        }
    }
}

/// Cache key strategy
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub enum CacheKeyStrategy {
    /// Full query hash
    #[default]
    QueryHash,
    /// Field-level caching
    FieldLevel,
    /// Custom key
    Custom { template: String },
}

/// Type merge configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeMergeConfig {
    /// Type name
    pub type_name: String,
    /// Field to use as key
    pub key_field: String,
    /// Sources that provide this type
    pub sources: Vec<String>,
    /// Resolution strategy
    pub resolution: MergeResolution,
}

/// Merge resolution strategy
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MergeResolution {
    /// First source wins
    First,
    /// Last source wins
    Last,
    /// Merge all fields
    MergeAll,
    /// Fail on conflict
    FailOnConflict,
}

/// Cross-source relationship
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrossSourceRelation {
    /// Source type
    pub source_type: String,
    /// Source field
    pub source_field: String,
    /// Source ID
    pub source_id: String,
    /// Target type
    pub target_type: String,
    /// Target field for lookup
    pub target_key_field: String,
    /// Target source ID
    pub target_source_id: String,
    /// Relation type
    pub relation_type: RelationType,
}

/// Relation type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RelationType {
    /// One to one
    OneToOne,
    /// One to many
    OneToMany,
    /// Many to one
    ManyToOne,
    /// Many to many
    ManyToMany,
}

/// Mesh configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MeshConfig {
    /// Name
    pub name: String,
    /// Data sources
    pub sources: Vec<DataSource>,
    /// Type merges
    pub type_merges: Vec<TypeMergeConfig>,
    /// Cross-source relations
    pub relations: Vec<CrossSourceRelation>,
    /// Global transforms
    pub global_transforms: Vec<Transform>,
    /// Enable introspection
    pub enable_introspection: bool,
    /// Serve config
    pub serve: ServeConfig,
}

impl Default for MeshConfig {
    fn default() -> Self {
        Self {
            name: "mesh".to_string(),
            sources: Vec::new(),
            type_merges: Vec::new(),
            relations: Vec::new(),
            global_transforms: Vec::new(),
            enable_introspection: true,
            serve: ServeConfig::default(),
        }
    }
}

/// Server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServeConfig {
    /// Host
    pub host: String,
    /// Port
    pub port: u16,
    /// Enable playground
    pub playground: bool,
    /// CORS origins
    pub cors: Vec<String>,
}

impl Default for ServeConfig {
    fn default() -> Self {
        Self {
            host: "0.0.0.0".to_string(),
            port: 4000,
            playground: true,
            cors: vec!["*".to_string()],
        }
    }
}

/// Source health status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SourceHealth {
    /// Source ID
    pub source_id: String,
    /// Is healthy
    pub healthy: bool,
    /// Last check time
    pub last_check: SystemTime,
    /// Last error
    pub last_error: Option<String>,
    /// Latency (ms)
    pub latency_ms: u64,
}

/// Internal state
struct MeshState {
    /// Config
    config: MeshConfig,
    /// Source health
    source_health: HashMap<String, SourceHealth>,
    /// Merged schema SDL
    merged_schema: Option<String>,
    /// Last merge time
    last_merge: Option<SystemTime>,
}

impl MeshState {
    fn new(config: MeshConfig) -> Self {
        Self {
            config,
            source_health: HashMap::new(),
            merged_schema: None,
            last_merge: None,
        }
    }
}

/// GraphQL Mesh Manager
///
/// Manages multiple data sources and combines them into a unified GraphQL API.
pub struct GraphQLMesh {
    /// Internal state
    state: Arc<RwLock<MeshState>>,
}

impl GraphQLMesh {
    /// Create a new mesh from config
    pub fn new(config: MeshConfig) -> Self {
        Self {
            state: Arc::new(RwLock::new(MeshState::new(config))),
        }
    }

    /// Add a data source
    pub async fn add_source(&self, source: DataSource) -> Result<()> {
        let mut state = self.state.write().await;

        if state.config.sources.iter().any(|s| s.id == source.id) {
            return Err(anyhow!("Source '{}' already exists", source.id));
        }

        state.config.sources.push(source);
        state.merged_schema = None; // Invalidate merged schema

        Ok(())
    }

    /// Remove a data source
    pub async fn remove_source(&self, source_id: &str) -> Result<()> {
        let mut state = self.state.write().await;

        let initial_len = state.config.sources.len();
        state.config.sources.retain(|s| s.id != source_id);

        if state.config.sources.len() == initial_len {
            return Err(anyhow!("Source '{}' not found", source_id));
        }

        state.source_health.remove(source_id);
        state.merged_schema = None;

        Ok(())
    }

    /// Get all sources
    pub async fn get_sources(&self) -> Vec<DataSource> {
        let state = self.state.read().await;
        state.config.sources.clone()
    }

    /// Get source by ID
    pub async fn get_source(&self, source_id: &str) -> Option<DataSource> {
        let state = self.state.read().await;
        state
            .config
            .sources
            .iter()
            .find(|s| s.id == source_id)
            .cloned()
    }

    /// Update source health
    pub async fn update_source_health(
        &self,
        source_id: &str,
        healthy: bool,
        error: Option<String>,
        latency_ms: u64,
    ) {
        let mut state = self.state.write().await;

        state.source_health.insert(
            source_id.to_string(),
            SourceHealth {
                source_id: source_id.to_string(),
                healthy,
                last_check: SystemTime::now(),
                last_error: error,
                latency_ms,
            },
        );
    }

    /// Get source health
    pub async fn get_source_health(&self, source_id: &str) -> Option<SourceHealth> {
        let state = self.state.read().await;
        state.source_health.get(source_id).cloned()
    }

    /// Get all source health
    pub async fn get_all_health(&self) -> Vec<SourceHealth> {
        let state = self.state.read().await;
        state.source_health.values().cloned().collect()
    }

    /// Add type merge configuration
    pub async fn add_type_merge(&self, merge: TypeMergeConfig) {
        let mut state = self.state.write().await;
        state.config.type_merges.push(merge);
        state.merged_schema = None;
    }

    /// Add cross-source relation
    pub async fn add_relation(&self, relation: CrossSourceRelation) {
        let mut state = self.state.write().await;
        state.config.relations.push(relation);
        state.merged_schema = None;
    }

    /// Build merged schema
    pub async fn build_schema(&self) -> Result<String> {
        let mut state = self.state.write().await;

        let mut sdl = String::new();

        // Build Query type from all sources
        sdl.push_str("type Query {\n");

        for source in &state.config.sources {
            if !source.enabled {
                continue;
            }

            // Apply prefix transform if present
            let prefix = source
                .transforms
                .iter()
                .find_map(|t| match t {
                    Transform::Prefix { value } => Some(value.clone()),
                    _ => None,
                })
                .unwrap_or_default();

            sdl.push_str(&format!(
                "  # Source: {} ({})\n",
                source.name,
                source.source_type.name()
            ));
            sdl.push_str(&format!(
                "  {}health: Boolean @source(name: \"{}\")\n",
                prefix.to_lowercase(),
                source.id
            ));
        }

        sdl.push_str("}\n\n");

        // Add directive definition
        sdl.push_str("directive @source(name: String!) on FIELD_DEFINITION\n");

        state.merged_schema = Some(sdl.clone());
        state.last_merge = Some(SystemTime::now());

        Ok(sdl)
    }

    /// Get merged schema
    pub async fn get_merged_schema(&self) -> Option<String> {
        let state = self.state.read().await;
        state.merged_schema.clone()
    }

    /// Get configuration
    pub async fn get_config(&self) -> MeshConfig {
        let state = self.state.read().await;
        state.config.clone()
    }

    /// Validate configuration
    pub async fn validate(&self) -> Vec<ValidationError> {
        let state = self.state.read().await;
        let mut errors = Vec::new();

        // Check for duplicate source IDs
        let mut seen_ids = std::collections::HashSet::new();
        for source in &state.config.sources {
            if !seen_ids.insert(&source.id) {
                errors.push(ValidationError {
                    path: format!("sources.{}", source.id),
                    message: "Duplicate source ID".to_string(),
                });
            }
        }

        // Check type merges reference existing sources
        for merge in &state.config.type_merges {
            for source_id in &merge.sources {
                if !state.config.sources.iter().any(|s| &s.id == source_id) {
                    errors.push(ValidationError {
                        path: format!("type_merges.{}.sources", merge.type_name),
                        message: format!("Unknown source: {}", source_id),
                    });
                }
            }
        }

        // Check relations reference existing sources
        for relation in &state.config.relations {
            if !state
                .config
                .sources
                .iter()
                .any(|s| s.id == relation.source_id)
            {
                errors.push(ValidationError {
                    path: format!("relations.{}.source_id", relation.source_field),
                    message: format!("Unknown source: {}", relation.source_id),
                });
            }
            if !state
                .config
                .sources
                .iter()
                .any(|s| s.id == relation.target_source_id)
            {
                errors.push(ValidationError {
                    path: format!("relations.{}.target_source_id", relation.source_field),
                    message: format!("Unknown source: {}", relation.target_source_id),
                });
            }
        }

        errors
    }

    /// Export configuration as YAML
    pub async fn export_yaml(&self) -> Result<String> {
        let state = self.state.read().await;
        let yaml = serde_json::to_string_pretty(&state.config)?;
        Ok(yaml)
    }
}

impl SourceType {
    /// Get source type name
    pub fn name(&self) -> &'static str {
        match self {
            SourceType::GraphQL => "GraphQL",
            SourceType::REST => "REST",
            SourceType::OpenAPI => "OpenAPI",
            SourceType::SOAP => "SOAP",
            SourceType::GRPC => "gRPC",
            SourceType::OData => "OData",
            SourceType::Database => "Database",
            SourceType::JsonSchema => "JSON Schema",
            SourceType::Custom => "Custom",
        }
    }
}

/// Validation error
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationError {
    /// Error path
    pub path: String,
    /// Error message
    pub message: String,
}

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

    #[tokio::test]
    async fn test_mesh_creation() {
        let config = MeshConfig::default();
        let mesh = GraphQLMesh::new(config);

        let sources = mesh.get_sources().await;
        assert!(sources.is_empty());
    }

    #[tokio::test]
    async fn test_add_source() {
        let mesh = GraphQLMesh::new(MeshConfig::default());

        let source = DataSource::new(
            "users",
            "Users API",
            SourceType::GraphQL,
            "https://api.example.com/graphql",
        );

        mesh.add_source(source).await.expect("should succeed");

        let sources = mesh.get_sources().await;
        assert_eq!(sources.len(), 1);
        assert_eq!(sources[0].id, "users");
    }

    #[tokio::test]
    async fn test_duplicate_source() {
        let mesh = GraphQLMesh::new(MeshConfig::default());

        let source1 = DataSource::new(
            "api",
            "API 1",
            SourceType::GraphQL,
            "https://api1.example.com",
        );
        let source2 = DataSource::new(
            "api",
            "API 2",
            SourceType::GraphQL,
            "https://api2.example.com",
        );

        mesh.add_source(source1).await.expect("should succeed");
        let result = mesh.add_source(source2).await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_remove_source() {
        let mesh = GraphQLMesh::new(MeshConfig::default());

        let source = DataSource::new(
            "users",
            "Users",
            SourceType::GraphQL,
            "https://api.example.com",
        );
        mesh.add_source(source).await.expect("should succeed");

        mesh.remove_source("users").await.expect("should succeed");

        let sources = mesh.get_sources().await;
        assert!(sources.is_empty());
    }

    #[tokio::test]
    async fn test_source_health() {
        let mesh = GraphQLMesh::new(MeshConfig::default());

        let source = DataSource::new("api", "API", SourceType::GraphQL, "https://api.example.com");
        mesh.add_source(source).await.expect("should succeed");

        mesh.update_source_health("api", true, None, 50).await;

        let health = mesh.get_source_health("api").await.expect("should succeed");
        assert!(health.healthy);
        assert_eq!(health.latency_ms, 50);
    }

    #[tokio::test]
    async fn test_build_schema() {
        let mesh = GraphQLMesh::new(MeshConfig::default());

        let source = DataSource::new(
            "users",
            "Users",
            SourceType::GraphQL,
            "https://api.example.com",
        )
        .with_transform(Transform::Prefix {
            value: "Users_".to_string(),
        });

        mesh.add_source(source).await.expect("should succeed");

        let schema = mesh.build_schema().await.expect("should succeed");
        assert!(schema.contains("type Query"));
        assert!(schema.contains("users_health"));
    }

    #[tokio::test]
    async fn test_validation() {
        let mesh = GraphQLMesh::new(MeshConfig::default());

        mesh.add_type_merge(TypeMergeConfig {
            type_name: "User".to_string(),
            key_field: "id".to_string(),
            sources: vec!["nonexistent".to_string()],
            resolution: MergeResolution::MergeAll,
        })
        .await;

        let errors = mesh.validate().await;
        assert!(!errors.is_empty());
    }

    #[test]
    fn test_data_source_builder() {
        let source = DataSource::new("api", "API", SourceType::REST, "https://api.example.com")
            .with_auth(AuthConfig::Bearer {
                token: "secret".to_string(),
            })
            .with_header("X-Custom", "value")
            .with_cache(CacheConfig::default());

        assert!(source.auth.is_some());
        assert!(source.headers.contains_key("X-Custom"));
        assert!(source.cache.is_some());
    }

    #[test]
    fn test_source_type_name() {
        assert_eq!(SourceType::GraphQL.name(), "GraphQL");
        assert_eq!(SourceType::REST.name(), "REST");
        assert_eq!(SourceType::GRPC.name(), "gRPC");
    }
}