fraiseql-cli 2.0.0-rc.13

CLI tools for FraiseQL v2 - Schema compilation and development utilities
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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
//! Complete TOML schema configuration supporting types, queries, mutations, federation, observers,
//! caching
//!
//! This module extends FraiseQLConfig to support the full TOML-based schema definition.

use std::{collections::BTreeMap, path::PathBuf};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

use super::runtime::{DatabaseRuntimeConfig, ServerRuntimeConfig};
use super::expand_env_vars;

/// Domain-based schema organization
///
/// Automatically discovers schema files in domain directories:
/// ```toml
/// [schema.domain_discovery]
/// enabled = true
/// root_dir = "schema"
/// ```
///
/// Expects structure:
/// ```text
/// schema/
/// ├── auth/
/// │   ├── types.json
/// │   ├── queries.json
/// │   └── mutations.json
/// ├── products/
/// │   ├── types.json
/// │   ├── queries.json
/// │   └── mutations.json
/// ```
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct DomainDiscovery {
    /// Enable automatic domain discovery
    pub enabled:  bool,
    /// Root directory containing domains
    pub root_dir: String,
}

/// Represents a discovered domain
#[derive(Debug, Clone)]
pub struct Domain {
    /// Domain name (directory name)
    pub name: String,
    /// Path to domain root
    pub path: PathBuf,
}

impl DomainDiscovery {
    /// Discover all domains in root_dir
    pub fn resolve_domains(&self) -> Result<Vec<Domain>> {
        if !self.enabled {
            return Ok(Vec::new());
        }

        let root = PathBuf::from(&self.root_dir);
        if !root.is_dir() {
            anyhow::bail!("Domain discovery root not found: {}", self.root_dir);
        }

        let mut domains = Vec::new();

        for entry in std::fs::read_dir(&root)
            .context(format!("Failed to read domain root: {}", self.root_dir))?
        {
            let entry = entry.context("Failed to read directory entry")?;
            let path = entry.path();

            if path.is_dir() {
                let name = path
                    .file_name()
                    .and_then(|n| n.to_str())
                    .map(std::string::ToString::to_string)
                    .ok_or_else(|| anyhow::anyhow!("Invalid domain name: {}", path.display()))?;

                domains.push(Domain { name, path });
            }
        }

        // Sort for deterministic ordering
        domains.sort_by(|a, b| a.name.cmp(&b.name));

        Ok(domains)
    }
}

/// Schema includes for multi-file composition (glob patterns)
///
/// Supports glob patterns for flexible file inclusion:
/// ```toml
/// [schema.includes]
/// types = ["schema/types/**/*.json"]
/// queries = ["schema/queries/**/*.json"]
/// mutations = ["schema/mutations/**/*.json"]
/// ```
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct SchemaIncludes {
    /// Glob patterns for type files
    pub types:     Vec<String>,
    /// Glob patterns for query files
    pub queries:   Vec<String>,
    /// Glob patterns for mutation files
    pub mutations: Vec<String>,
}

impl SchemaIncludes {
    /// Check if any includes are specified
    pub fn is_empty(&self) -> bool {
        self.types.is_empty() && self.queries.is_empty() && self.mutations.is_empty()
    }

    /// Resolve glob patterns to actual file paths
    ///
    /// # Returns
    /// ResolvedIncludes with expanded file paths, or error if resolution fails
    pub fn resolve_globs(&self) -> Result<ResolvedIncludes> {
        use glob::glob as glob_pattern;

        let mut type_paths = Vec::new();
        let mut query_paths = Vec::new();
        let mut mutation_paths = Vec::new();

        // Resolve type globs
        for pattern in &self.types {
            for entry in glob_pattern(pattern)
                .context(format!("Invalid glob pattern for types: {pattern}"))?
            {
                match entry {
                    Ok(path) => type_paths.push(path),
                    Err(e) => {
                        anyhow::bail!("Error resolving type glob pattern '{pattern}': {e}");
                    },
                }
            }
        }

        // Resolve query globs
        for pattern in &self.queries {
            for entry in glob_pattern(pattern)
                .context(format!("Invalid glob pattern for queries: {pattern}"))?
            {
                match entry {
                    Ok(path) => query_paths.push(path),
                    Err(e) => {
                        anyhow::bail!("Error resolving query glob pattern '{pattern}': {e}");
                    },
                }
            }
        }

        // Resolve mutation globs
        for pattern in &self.mutations {
            for entry in glob_pattern(pattern)
                .context(format!("Invalid glob pattern for mutations: {pattern}"))?
            {
                match entry {
                    Ok(path) => mutation_paths.push(path),
                    Err(e) => {
                        anyhow::bail!("Error resolving mutation glob pattern '{pattern}': {e}");
                    },
                }
            }
        }

        // Sort for deterministic ordering
        type_paths.sort();
        query_paths.sort();
        mutation_paths.sort();

        // Remove duplicates
        type_paths.dedup();
        query_paths.dedup();
        mutation_paths.dedup();

        Ok(ResolvedIncludes {
            types:     type_paths,
            queries:   query_paths,
            mutations: mutation_paths,
        })
    }
}

/// Resolved glob patterns to actual file paths
#[derive(Debug, Clone)]
pub struct ResolvedIncludes {
    /// Resolved type file paths
    pub types:     Vec<PathBuf>,
    /// Resolved query file paths
    pub queries:   Vec<PathBuf>,
    /// Resolved mutation file paths
    pub mutations: Vec<PathBuf>,
}

/// Complete TOML schema configuration
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct TomlSchema {
    /// Schema metadata
    #[serde(rename = "schema")]
    pub schema: SchemaMetadata,

    /// Database connection pool configuration (optional — all fields have defaults).
    ///
    /// Supports `${VAR}` environment variable interpolation in the `url` field.
    #[serde(rename = "database")]
    pub database: DatabaseRuntimeConfig,

    /// HTTP server runtime configuration (optional — all fields have defaults).
    ///
    /// CLI flags (`--port`, `--bind`) take precedence over these settings.
    #[serde(rename = "server")]
    pub server: ServerRuntimeConfig,

    /// Type definitions
    #[serde(rename = "types")]
    pub types: BTreeMap<String, TypeDefinition>,

    /// Query definitions
    #[serde(rename = "queries")]
    pub queries: BTreeMap<String, QueryDefinition>,

    /// Mutation definitions
    #[serde(rename = "mutations")]
    pub mutations: BTreeMap<String, MutationDefinition>,

    /// Federation configuration
    #[serde(rename = "federation")]
    pub federation: FederationConfig,

    /// Security configuration
    #[serde(rename = "security")]
    pub security: SecuritySettings,

    /// Observers/event system configuration
    #[serde(rename = "observers")]
    pub observers: ObserversConfig,

    /// Result caching configuration
    #[serde(rename = "caching")]
    pub caching: CachingConfig,

    /// Analytics configuration
    #[serde(rename = "analytics")]
    pub analytics: AnalyticsConfig,

    /// Observability configuration
    #[serde(rename = "observability")]
    pub observability: ObservabilityConfig,

    /// Schema includes configuration for multi-file composition
    #[serde(default)]
    pub includes: SchemaIncludes,

    /// Domain discovery configuration for domain-based organization
    #[serde(default)]
    pub domain_discovery: DomainDiscovery,
}

/// Schema metadata
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct SchemaMetadata {
    /// Schema name
    pub name:            String,
    /// Schema version
    pub version:         String,
    /// Optional schema description
    pub description:     Option<String>,
    /// Target database (postgresql, mysql, sqlite, sqlserver)
    pub database_target: String,
}

impl Default for SchemaMetadata {
    fn default() -> Self {
        Self {
            name:            "myapp".to_string(),
            version:         "1.0.0".to_string(),
            description:     None,
            database_target: "postgresql".to_string(),
        }
    }
}

/// Type definition in TOML
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct TypeDefinition {
    /// SQL source table or view
    pub sql_source:  String,
    /// Human-readable type description
    pub description: Option<String>,
    /// Field definitions
    pub fields:      BTreeMap<String, FieldDefinition>,
}

impl Default for TypeDefinition {
    fn default() -> Self {
        Self {
            sql_source:  "v_entity".to_string(),
            description: None,
            fields:      BTreeMap::new(),
        }
    }
}

/// Field definition
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FieldDefinition {
    /// GraphQL field type (ID, String, Int, Boolean, DateTime, etc.)
    #[serde(rename = "type")]
    pub field_type:  String,
    /// Whether field can be null
    #[serde(default)]
    pub nullable:    bool,
    /// Field description
    pub description: Option<String>,
}

/// Query definition in TOML
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct QueryDefinition {
    /// Return type name
    pub return_type:  String,
    /// Whether query returns an array
    #[serde(default)]
    pub return_array: bool,
    /// SQL source for the query
    pub sql_source:   String,
    /// Query description
    pub description:  Option<String>,
    /// Query arguments
    pub args:         Vec<ArgumentDefinition>,
}

impl Default for QueryDefinition {
    fn default() -> Self {
        Self {
            return_type:  "String".to_string(),
            return_array: false,
            sql_source:   "v_entity".to_string(),
            description:  None,
            args:         vec![],
        }
    }
}

/// Mutation definition in TOML
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct MutationDefinition {
    /// Return type name
    pub return_type: String,
    /// SQL function or procedure source
    pub sql_source:  String,
    /// Operation type (CREATE, UPDATE, DELETE)
    pub operation:   String,
    /// Mutation description
    pub description: Option<String>,
    /// Mutation arguments
    pub args:        Vec<ArgumentDefinition>,
}

impl Default for MutationDefinition {
    fn default() -> Self {
        Self {
            return_type: "String".to_string(),
            sql_source:  "fn_operation".to_string(),
            operation:   "CREATE".to_string(),
            description: None,
            args:        vec![],
        }
    }
}

/// Argument definition
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ArgumentDefinition {
    /// Argument name
    pub name:        String,
    /// Argument type
    #[serde(rename = "type")]
    pub arg_type:    String,
    /// Whether argument is required
    #[serde(default)]
    pub required:    bool,
    /// Default value if not provided
    pub default:     Option<serde_json::Value>,
    /// Argument description
    pub description: Option<String>,
}

/// Circuit breaker configuration for a specific federated database/service
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PerDatabaseCircuitBreakerOverride {
    /// Database or service name matching a federation entity
    pub database:             String,
    /// Override: number of consecutive failures before opening (must be > 0)
    pub failure_threshold:    Option<u32>,
    /// Override: seconds to wait before attempting recovery (must be > 0)
    pub recovery_timeout_secs: Option<u64>,
    /// Override: successes required in half-open state to close the breaker (must be > 0)
    pub success_threshold:    Option<u32>,
}

/// Circuit breaker configuration for Apollo Federation fan-out requests
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct FederationCircuitBreakerConfig {
    /// Enable circuit breaker protection on federation fan-out
    pub enabled:              bool,
    /// Consecutive failures before the breaker opens (default: 5, must be > 0)
    pub failure_threshold:    u32,
    /// Seconds to wait before attempting a probe request (default: 30, must be > 0)
    pub recovery_timeout_secs: u64,
    /// Probe successes needed to transition from half-open to closed (default: 2, must be > 0)
    pub success_threshold:    u32,
    /// Per-database overrides (database name must match a defined federation entity)
    pub per_database:         Vec<PerDatabaseCircuitBreakerOverride>,
}

impl Default for FederationCircuitBreakerConfig {
    fn default() -> Self {
        Self {
            enabled:              true,
            failure_threshold:    5,
            recovery_timeout_secs: 30,
            success_threshold:    2,
            per_database:         vec![],
        }
    }
}

/// Federation configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct FederationConfig {
    /// Enable Apollo federation
    #[serde(default)]
    pub enabled:         bool,
    /// Apollo federation version
    pub apollo_version:  Option<u32>,
    /// Federated entities
    pub entities:        Vec<FederationEntity>,
    /// Circuit breaker configuration for federation fan-out requests
    pub circuit_breaker: Option<FederationCircuitBreakerConfig>,
}

impl Default for FederationConfig {
    fn default() -> Self {
        Self {
            enabled:         false,
            apollo_version:  Some(2),
            entities:        vec![],
            circuit_breaker: None,
        }
    }
}

/// Federation entity
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FederationEntity {
    /// Entity name
    pub name:       String,
    /// Key fields for entity resolution
    pub key_fields: Vec<String>,
}

/// Security configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct SecuritySettings {
    /// Default policy to apply if none specified
    pub default_policy: Option<String>,
    /// Custom authorization rules
    pub rules:          Vec<AuthorizationRule>,
    /// Authorization policies
    pub policies:       Vec<AuthorizationPolicy>,
    /// Field-level authorization rules
    pub field_auth:     Vec<FieldAuthRule>,
    /// Enterprise security configuration
    pub enterprise:     EnterpriseSecurityConfig,
}

impl Default for SecuritySettings {
    fn default() -> Self {
        Self {
            default_policy: Some("authenticated".to_string()),
            rules:          vec![],
            policies:       vec![],
            field_auth:     vec![],
            enterprise:     EnterpriseSecurityConfig::default(),
        }
    }
}

/// Authorization rule (custom expressions)
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AuthorizationRule {
    /// Rule name
    pub name:              String,
    /// Rule expression or condition
    pub rule:              String,
    /// Rule description
    pub description:       Option<String>,
    /// Whether rule result can be cached
    #[serde(default)]
    pub cacheable:         bool,
    /// Cache time-to-live in seconds
    pub cache_ttl_seconds: Option<u32>,
}

/// Authorization policy (RBAC/ABAC)
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AuthorizationPolicy {
    /// Policy name
    pub name:              String,
    /// Policy type (RBAC, ABAC, CUSTOM, HYBRID)
    #[serde(rename = "type")]
    pub policy_type:       String,
    /// Optional rule expression
    pub rule:              Option<String>,
    /// Roles this policy applies to
    pub roles:             Vec<String>,
    /// Combination strategy (ANY, ALL, EXACTLY)
    pub strategy:          Option<String>,
    /// Attributes for attribute-based access control
    #[serde(default)]
    pub attributes:        Vec<String>,
    /// Policy description
    pub description:       Option<String>,
    /// Cache time-to-live in seconds
    pub cache_ttl_seconds: Option<u32>,
}

/// Field-level authorization rule
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FieldAuthRule {
    /// Type name this rule applies to
    pub type_name:  String,
    /// Field name this rule applies to
    pub field_name: String,
    /// Policy to enforce
    pub policy:     String,
}

/// Enterprise security configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct EnterpriseSecurityConfig {
    /// Enable rate limiting
    pub rate_limiting_enabled:        bool,
    /// Max requests per auth endpoint
    pub auth_endpoint_max_requests:   u32,
    /// Rate limit window in seconds
    pub auth_endpoint_window_seconds: u64,
    /// Enable audit logging
    pub audit_logging_enabled:        bool,
    /// Audit log backend service
    pub audit_log_backend:            String,
    /// Audit log retention in days
    pub audit_retention_days:         u32,
    /// Enable error sanitization
    pub error_sanitization:           bool,
    /// Hide implementation details in errors
    pub hide_implementation_details:  bool,
    /// Enable constant-time token comparison
    pub constant_time_comparison:     bool,
    /// Enable PKCE for OAuth flows
    pub pkce_enabled:                 bool,
}

impl Default for EnterpriseSecurityConfig {
    fn default() -> Self {
        Self {
            rate_limiting_enabled:        true,
            auth_endpoint_max_requests:   100,
            auth_endpoint_window_seconds: 60,
            audit_logging_enabled:        true,
            audit_log_backend:            "postgresql".to_string(),
            audit_retention_days:         365,
            error_sanitization:           true,
            hide_implementation_details:  true,
            constant_time_comparison:     true,
            pkce_enabled:                 true,
        }
    }
}

/// Observers/event system configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct ObserversConfig {
    /// Enable observers system
    #[serde(default)]
    pub enabled:   bool,
    /// Backend service (redis, nats, postgresql, mysql, in-memory)
    pub backend:   String,
    /// Redis connection URL (required when backend = "redis")
    pub redis_url: Option<String>,
    /// NATS connection URL (required when backend = "nats")
    ///
    /// Example: `nats://localhost:4222`
    /// Can be overridden at runtime via the `FRAISEQL_NATS_URL` environment variable.
    pub nats_url:  Option<String>,
    /// Event handlers
    pub handlers:  Vec<EventHandler>,
}

impl Default for ObserversConfig {
    fn default() -> Self {
        Self {
            enabled:   false,
            backend:   "redis".to_string(),
            redis_url: None,
            nats_url:  None,
            handlers:  vec![],
        }
    }
}

/// Event handler configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EventHandler {
    /// Handler name
    pub name:           String,
    /// Event type to handle
    pub event:          String,
    /// Action to perform (slack, email, sms, webhook, push, etc.)
    pub action:         String,
    /// Webhook URL for webhook actions
    pub webhook_url:    Option<String>,
    /// Retry strategy
    pub retry_strategy: Option<String>,
    /// Maximum retry attempts
    pub max_retries:    Option<u32>,
    /// Handler description
    pub description:    Option<String>,
}

/// Caching configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct CachingConfig {
    /// Enable caching
    #[serde(default)]
    pub enabled:   bool,
    /// Cache backend (redis, memory, postgresql)
    pub backend:   String,
    /// Redis connection URL
    pub redis_url: Option<String>,
    /// Cache invalidation rules
    pub rules:     Vec<CacheRule>,
}

impl Default for CachingConfig {
    fn default() -> Self {
        Self {
            enabled:   false,
            backend:   "redis".to_string(),
            redis_url: None,
            rules:     vec![],
        }
    }
}

/// Cache invalidation rule
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct CacheRule {
    /// Query pattern to cache
    pub query:                 String,
    /// Time-to-live in seconds
    pub ttl_seconds:           u32,
    /// Events that trigger cache invalidation
    pub invalidation_triggers: Vec<String>,
}

/// Analytics configuration
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct AnalyticsConfig {
    /// Enable analytics
    #[serde(default)]
    pub enabled: bool,
    /// Analytics queries
    pub queries: Vec<AnalyticsQuery>,
}

/// Analytics query definition
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AnalyticsQuery {
    /// Query name
    pub name:        String,
    /// SQL source for the query
    pub sql_source:  String,
    /// Query description
    pub description: Option<String>,
}

/// Observability configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct ObservabilityConfig {
    /// Enable Prometheus metrics
    pub prometheus_enabled:            bool,
    /// Port for Prometheus metrics endpoint
    pub prometheus_port:               u16,
    /// Enable OpenTelemetry tracing
    pub otel_enabled:                  bool,
    /// OpenTelemetry exporter type
    pub otel_exporter:                 String,
    /// Jaeger endpoint for trace collection
    pub otel_jaeger_endpoint:          Option<String>,
    /// Enable health check endpoint
    pub health_check_enabled:          bool,
    /// Health check interval in seconds
    pub health_check_interval_seconds: u32,
    /// Log level threshold
    pub log_level:                     String,
    /// Log output format (json, text)
    pub log_format:                    String,
}

impl Default for ObservabilityConfig {
    fn default() -> Self {
        Self {
            prometheus_enabled:            false,
            prometheus_port:               9090,
            otel_enabled:                  false,
            otel_exporter:                 "jaeger".to_string(),
            otel_jaeger_endpoint:          None,
            health_check_enabled:          true,
            health_check_interval_seconds: 30,
            log_level:                     "info".to_string(),
            log_format:                    "json".to_string(),
        }
    }
}

impl TomlSchema {
    /// Load schema from TOML file
    pub fn from_file(path: &str) -> Result<Self> {
        let content =
            std::fs::read_to_string(path).context(format!("Failed to read TOML file: {path}"))?;
        Self::parse_toml(&content)
    }

    /// Parse schema from TOML string.
    ///
    /// Expands `${VAR}` environment variable placeholders before parsing.
    pub fn parse_toml(content: &str) -> Result<Self> {
        let expanded = expand_env_vars(content);
        toml::from_str(&expanded).context("Failed to parse TOML schema")
    }

    /// Validate schema
    pub fn validate(&self) -> Result<()> {
        // Validate that all query return types exist
        for (query_name, query_def) in &self.queries {
            if !self.types.contains_key(&query_def.return_type) {
                anyhow::bail!(
                    "Query '{query_name}' references undefined type '{}'",
                    query_def.return_type
                );
            }
        }

        // Validate that all mutation return types exist
        for (mut_name, mut_def) in &self.mutations {
            if !self.types.contains_key(&mut_def.return_type) {
                anyhow::bail!(
                    "Mutation '{mut_name}' references undefined type '{}'",
                    mut_def.return_type
                );
            }
        }

        // Validate field auth rules reference existing policies
        for field_auth in &self.security.field_auth {
            let policy_exists = self.security.policies.iter().any(|p| p.name == field_auth.policy);
            if !policy_exists {
                anyhow::bail!("Field auth references undefined policy '{}'", field_auth.policy);
            }
        }

        // Validate federation entities reference existing types
        for entity in &self.federation.entities {
            if !self.types.contains_key(&entity.name) {
                anyhow::bail!("Federation entity '{}' references undefined type", entity.name);
            }
        }

        self.server.validate()?;
        self.database.validate()?;

        // Validate federation circuit breaker configuration
        if let Some(cb) = &self.federation.circuit_breaker {
            if cb.failure_threshold == 0 {
                anyhow::bail!(
                    "federation.circuit_breaker.failure_threshold must be greater than 0"
                );
            }
            if cb.recovery_timeout_secs == 0 {
                anyhow::bail!(
                    "federation.circuit_breaker.recovery_timeout_secs must be greater than 0"
                );
            }
            if cb.success_threshold == 0 {
                anyhow::bail!(
                    "federation.circuit_breaker.success_threshold must be greater than 0"
                );
            }

            // Validate per-database overrides reference defined entity names
            let entity_names: std::collections::HashSet<&str> =
                self.federation.entities.iter().map(|e| e.name.as_str()).collect();
            for override_cfg in &cb.per_database {
                if !entity_names.contains(override_cfg.database.as_str()) {
                    anyhow::bail!(
                        "federation.circuit_breaker.per_database entry '{}' does not match \
                         any defined federation entity",
                        override_cfg.database
                    );
                }
                if override_cfg.failure_threshold == Some(0) {
                    anyhow::bail!(
                        "federation.circuit_breaker.per_database['{}'].failure_threshold \
                         must be greater than 0",
                        override_cfg.database
                    );
                }
                if override_cfg.recovery_timeout_secs == Some(0) {
                    anyhow::bail!(
                        "federation.circuit_breaker.per_database['{}'].recovery_timeout_secs \
                         must be greater than 0",
                        override_cfg.database
                    );
                }
                if override_cfg.success_threshold == Some(0) {
                    anyhow::bail!(
                        "federation.circuit_breaker.per_database['{}'].success_threshold \
                         must be greater than 0",
                        override_cfg.database
                    );
                }
            }
        }

        Ok(())
    }

    /// Convert to intermediate schema format (compatible with language-generated types.json)
    pub fn to_intermediate_schema(&self) -> serde_json::Value {
        let mut types_json = serde_json::Map::new();

        for (type_name, type_def) in &self.types {
            let mut fields_json = serde_json::Map::new();

            for (field_name, field_def) in &type_def.fields {
                fields_json.insert(
                    field_name.clone(),
                    serde_json::json!({
                        "type": field_def.field_type,
                        "nullable": field_def.nullable,
                        "description": field_def.description,
                    }),
                );
            }

            types_json.insert(
                type_name.clone(),
                serde_json::json!({
                    "name": type_name,
                    "sql_source": type_def.sql_source,
                    "description": type_def.description,
                    "fields": fields_json,
                }),
            );
        }

        let mut queries_json = serde_json::Map::new();

        for (query_name, query_def) in &self.queries {
            let args: Vec<serde_json::Value> = query_def
                .args
                .iter()
                .map(|arg| {
                    serde_json::json!({
                        "name": arg.name,
                        "type": arg.arg_type,
                        "required": arg.required,
                        "default": arg.default,
                        "description": arg.description,
                    })
                })
                .collect();

            queries_json.insert(
                query_name.clone(),
                serde_json::json!({
                    "name": query_name,
                    "return_type": query_def.return_type,
                    "return_array": query_def.return_array,
                    "sql_source": query_def.sql_source,
                    "description": query_def.description,
                    "args": args,
                }),
            );
        }

        serde_json::json!({
            "types": types_json,
            "queries": queries_json,
        })
    }
}

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

    #[test]
    fn test_parse_toml_schema() {
        let toml = r#"
[schema]
name = "myapp"
version = "1.0.0"
database_target = "postgresql"

[types.User]
sql_source = "v_user"

[types.User.fields.id]
type = "ID"
nullable = false

[types.User.fields.name]
type = "String"
nullable = false

[queries.users]
return_type = "User"
return_array = true
sql_source = "v_user"
"#;
        let schema = TomlSchema::parse_toml(toml).expect("Failed to parse");
        assert_eq!(schema.schema.name, "myapp");
        assert!(schema.types.contains_key("User"));
    }

    #[test]
    fn test_validate_schema() {
        let schema = TomlSchema::default();
        assert!(schema.validate().is_ok());
    }

    // --- Issue #38: nats_url ---

    #[test]
    fn test_observers_config_nats_url_round_trip() {
        let toml = r#"
[schema]
name = "myapp"
version = "1.0.0"
database_target = "postgresql"

[observers]
enabled = true
backend = "nats"
nats_url = "nats://localhost:4222"
"#;
        let schema = TomlSchema::parse_toml(toml).expect("Failed to parse");
        assert_eq!(schema.observers.backend, "nats");
        assert_eq!(
            schema.observers.nats_url.as_deref(),
            Some("nats://localhost:4222")
        );
        assert!(schema.observers.redis_url.is_none());
    }

    #[test]
    fn test_observers_config_redis_url_unchanged() {
        let toml = r#"
[schema]
name = "myapp"
version = "1.0.0"
database_target = "postgresql"

[observers]
enabled = true
backend = "redis"
redis_url = "redis://localhost:6379"
"#;
        let schema = TomlSchema::parse_toml(toml).expect("Failed to parse");
        assert_eq!(schema.observers.backend, "redis");
        assert_eq!(
            schema.observers.redis_url.as_deref(),
            Some("redis://localhost:6379")
        );
        assert!(schema.observers.nats_url.is_none());
    }

    #[test]
    fn test_observers_config_nats_url_default_is_none() {
        let config = ObserversConfig::default();
        assert!(config.nats_url.is_none());
    }

    // --- Issue #39: federation circuit breaker ---

    #[test]
    fn test_federation_circuit_breaker_round_trip() {
        let toml = r#"
[schema]
name = "myapp"
version = "1.0.0"
database_target = "postgresql"

[types.Product]
sql_source = "v_product"

[federation]
enabled = true
apollo_version = 2

[[federation.entities]]
name = "Product"
key_fields = ["id"]

[federation.circuit_breaker]
enabled = true
failure_threshold = 3
recovery_timeout_secs = 60
success_threshold = 1
"#;
        let schema = TomlSchema::parse_toml(toml).expect("Failed to parse");
        let cb = schema.federation.circuit_breaker.as_ref().expect("Expected circuit_breaker");
        assert!(cb.enabled);
        assert_eq!(cb.failure_threshold, 3);
        assert_eq!(cb.recovery_timeout_secs, 60);
        assert_eq!(cb.success_threshold, 1);
        assert!(cb.per_database.is_empty());
    }

    #[test]
    fn test_federation_circuit_breaker_zero_failure_threshold_rejected() {
        let toml = r#"
[schema]
name = "myapp"
version = "1.0.0"
database_target = "postgresql"

[federation]
enabled = true

[federation.circuit_breaker]
enabled = true
failure_threshold = 0
recovery_timeout_secs = 30
success_threshold = 2
"#;
        let schema = TomlSchema::parse_toml(toml).expect("Failed to parse");
        let err = schema.validate().unwrap_err();
        assert!(err.to_string().contains("failure_threshold"), "{err}");
    }

    #[test]
    fn test_federation_circuit_breaker_zero_recovery_timeout_rejected() {
        let toml = r#"
[schema]
name = "myapp"
version = "1.0.0"
database_target = "postgresql"

[federation]
enabled = true

[federation.circuit_breaker]
enabled = true
failure_threshold = 5
recovery_timeout_secs = 0
success_threshold = 2
"#;
        let schema = TomlSchema::parse_toml(toml).expect("Failed to parse");
        let err = schema.validate().unwrap_err();
        assert!(err.to_string().contains("recovery_timeout_secs"), "{err}");
    }

    #[test]
    fn test_federation_circuit_breaker_per_database_unknown_entity_rejected() {
        let toml = r#"
[schema]
name = "myapp"
version = "1.0.0"
database_target = "postgresql"

[types.Product]
sql_source = "v_product"

[federation]
enabled = true

[[federation.entities]]
name = "Product"
key_fields = ["id"]

[federation.circuit_breaker]
enabled = true
failure_threshold = 5
recovery_timeout_secs = 30
success_threshold = 2

[[federation.circuit_breaker.per_database]]
database = "NonExistentEntity"
failure_threshold = 3
"#;
        let schema = TomlSchema::parse_toml(toml).expect("Failed to parse");
        let err = schema.validate().unwrap_err();
        assert!(err.to_string().contains("NonExistentEntity"), "{err}");
    }

    #[test]
    fn test_federation_circuit_breaker_per_database_valid() {
        let toml = r#"
[schema]
name = "myapp"
version = "1.0.0"
database_target = "postgresql"

[types.Product]
sql_source = "v_product"

[federation]
enabled = true

[[federation.entities]]
name = "Product"
key_fields = ["id"]

[federation.circuit_breaker]
enabled = true
failure_threshold = 5
recovery_timeout_secs = 30
success_threshold = 2

[[federation.circuit_breaker.per_database]]
database = "Product"
failure_threshold = 3
recovery_timeout_secs = 15
"#;
        let schema = TomlSchema::parse_toml(toml).expect("Failed to parse");
        assert!(schema.validate().is_ok());
        let cb = schema.federation.circuit_breaker.as_ref().unwrap();
        assert_eq!(cb.per_database.len(), 1);
        assert_eq!(cb.per_database[0].database, "Product");
        assert_eq!(cb.per_database[0].failure_threshold, Some(3));
        assert_eq!(cb.per_database[0].recovery_timeout_secs, Some(15));
    }

    #[test]
    fn test_toml_schema_parses_server_section() {
        let toml = r#"
[schema]
name = "myapp"
version = "1.0.0"
database_target = "postgresql"

[server]
host = "127.0.0.1"
port = 9999

[server.cors]
origins = ["https://example.com"]
"#;
        let schema = TomlSchema::parse_toml(toml).expect("Failed to parse");
        assert_eq!(schema.server.host, "127.0.0.1");
        assert_eq!(schema.server.port, 9999);
        assert_eq!(schema.server.cors.origins, ["https://example.com"]);
    }

    #[test]
    fn test_toml_schema_database_uses_runtime_config() {
        let toml = r#"
[schema]
name = "myapp"
version = "1.0.0"
database_target = "postgresql"

[database]
url      = "postgresql://localhost/mydb"
pool_min = 5
pool_max = 30
ssl_mode = "require"
"#;
        let schema = TomlSchema::parse_toml(toml).expect("Failed to parse");
        assert_eq!(schema.database.url, Some("postgresql://localhost/mydb".to_string()));
        assert_eq!(schema.database.pool_min, 5);
        assert_eq!(schema.database.pool_max, 30);
        assert_eq!(schema.database.ssl_mode, "require");
    }

    #[test]
    fn test_env_var_expansion_in_toml_schema() {
        temp_env::with_var("SCHEMA_TEST_DB_URL", Some("postgres://test/fraiseql"), || {
            let toml = r#"
[schema]
name = "myapp"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "${SCHEMA_TEST_DB_URL}"
"#;
            let schema = TomlSchema::parse_toml(toml).expect("Failed to parse");
            assert_eq!(
                schema.database.url,
                Some("postgres://test/fraiseql".to_string())
            );
        });
    }

    #[test]
    fn test_toml_schema_defaults_without_server_section() {
        let toml = r#"
[schema]
name = "myapp"
version = "1.0.0"
database_target = "postgresql"
"#;
        let schema = TomlSchema::parse_toml(toml).expect("Failed to parse");
        // Defaults should apply
        assert_eq!(schema.server.host, "0.0.0.0");
        assert_eq!(schema.server.port, 8080);
        assert_eq!(schema.database.pool_min, 2);
        assert_eq!(schema.database.pool_max, 20);
        assert!(schema.database.url.is_none());
    }
}