fraiseql-server 2.16.0

HTTP server for FraiseQL v2 GraphQL engine
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
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
//! Server configuration (`*Config` types).
//!
//! These are developer-facing configuration types loaded from `fraiseql.toml`,
//! environment variables, or CLI flags. They are mutable between deployments.
//!
//! For the distinction between `*Config` (developer-facing, mutable) and
//! `*Settings` (compiled into `schema.compiled.json`, immutable at runtime),
//! see `docs/architecture/config-vs-settings.md`.

pub mod admin_sql;
pub mod async_operations;
#[cfg(feature = "cdc-outbound")]
pub mod cdc_outbound;
pub(crate) mod defaults;
pub mod hs256;
mod methods;
pub mod observers;
#[cfg(feature = "auth-saml")]
pub mod saml;
pub mod scim;
pub mod session_state;
pub mod storage;
pub mod subscription_kafka;
pub mod tls;

#[cfg(test)]
mod tests;

use std::{collections::HashMap, net::SocketAddr, path::PathBuf};

pub use admin_sql::AdminSqlConfig;
pub use async_operations::AsyncOperationsConfig;
#[cfg(feature = "cdc-outbound")]
pub use cdc_outbound::{CdcOutboundConfig, CdcSinkSectionConfig};
use defaults::{
    default_bind_addr, default_database_url, default_graphql_path, default_health_path,
    default_introspection_path, default_liveness_path, default_max_header_bytes,
    default_max_header_count, default_max_request_body_bytes, default_metrics_json_path,
    default_metrics_path, default_playground_path, default_pool_max_size, default_pool_min_size,
    default_pool_timeout, default_readiness_path, default_schema_path,
    default_shutdown_timeout_secs, default_subscription_auth_recheck_secs,
    default_subscription_path,
};
use fraiseql_core::{
    db::postgres::{HnswIterativeScan, IvfflatIterativeScan},
    security::OidcConfig,
};
pub use hs256::Hs256Config;
pub use observers::AdmissionConfig;
#[cfg(feature = "observers")]
pub use observers::{
    ObserverConfig, ObserverPoolConfig, ObserverRedisConfig, ObserverRuntimeSettings,
    ObserverTransportConfig,
};
#[cfg(feature = "auth-saml")]
pub use saml::{SamlIdpEntry, SamlServerConfig};
pub use scim::ScimServerConfig;
use serde::{Deserialize, Serialize};
pub use session_state::SessionStateServerConfig;
pub use storage::{ResolvedStorage, build_storage_state, resolve_storage_section};
pub use subscription_kafka::SubscriptionKafkaConfig;
pub use tls::{DatabaseTlsConfig, PlaygroundTool, TlsServerConfig};

use crate::middleware::{RateLimitConfig, RateLimitOverrides};

/// Server configuration.
///
/// Deserialized **directly** from the `--config` TOML file — the keys below are
/// top-level (no `[server]`/`[database]` grouping tables), and an unknown key
/// refuses to parse rather than being silently discarded (#839: a config whose
/// every key landed in an unknown table booted on defaults with zero warnings).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ServerConfig {
    /// Path to compiled schema JSON file.
    #[serde(default = "defaults::default_schema_path")]
    pub schema_path: PathBuf,

    /// Fail boot if any declared `sql_source` (query view / mutation function) is
    /// not backed by the database (#487), or the server's role may not use it (#1426).
    ///
    /// Default `false` — the boot path is unchanged. Postgres-only. The
    /// `--validate-sql-sources` CLI flag and the `FRAISEQL_VALIDATE_SQL_SOURCES`
    /// environment variable both override this (env/flag win over the config key).
    #[serde(default)]
    pub validate_sql_sources: bool,

    /// Check a failed mutation's `error_detail.errors[]` (#1425): `"off"` (default) or
    /// `"warn"`. With `"warn"`, a failure carrying no `errors` array, or an entry whose
    /// `identifier` is not a translation key, is logged at `warn` and counted in
    /// `fraiseql_mutation_error_shape_violations_total`. The response is unchanged.
    #[serde(default)]
    pub mutation_error_shape_check: fraiseql_core::runtime::MutationErrorShapeCheck,

    /// Database connection URL (PostgreSQL — the only supported backend since
    /// v2.15.0).
    #[serde(default = "defaults::default_database_url")]
    pub database_url: String,

    /// Server bind address.
    #[serde(default = "defaults::default_bind_addr")]
    pub bind_addr: SocketAddr,

    /// Arrow Flight gRPC bind address (requires `arrow` feature).
    ///
    /// Defaults to loopback `127.0.0.1:50051` (#874 — parity with
    /// [`bind_addr`](Self::bind_addr); binding other interfaces is an explicit
    /// operator decision). Override with the `--flight-bind-addr` flag or the
    /// `FRAISEQL_FLIGHT_BIND_ADDR` environment variable — which follow the
    /// standard CLI > env > file > default precedence and refuse startup on a
    /// malformed value — or with this field in the config file.
    #[cfg(feature = "arrow")]
    #[serde(default = "defaults::default_flight_bind_addr")]
    pub flight_bind_addr: SocketAddr,

    /// Tables an authenticated Arrow Flight client may `Upload` into (#953).
    ///
    /// **Empty (the default) disables `Upload` entirely** — the fail-closed
    /// position, and the only safe default: an `Upload` is a raw, client-directed
    /// INSERT whose target table is named by the *request*, and it does not pass
    /// through the mutation pipeline, so it carries no operation authorizer and no
    /// field RBAC. Ungated, any holder of a valid Flight session token could write
    /// every table the connection role can write.
    ///
    /// Allow-list only tables every `Upload`-capable client is permitted to write.
    /// Naming an audit, `_system` or outbox table here hands those clients the
    /// ledger.
    ///
    /// The rows and their `core.tb_entity_change_log` outbox rows are written in one
    /// transaction, so an allow-listed Upload is visible to the Change Spine and to
    /// CDC like any other write.
    ///
    /// ```toml
    /// flight_upload_tables = ["ta_measurements", "ta_events"]
    /// ```
    #[cfg(feature = "arrow")]
    #[serde(default)]
    pub flight_upload_tables: Vec<String>,

    /// Views the Arrow Flight `OptimizedView` ticket may serve (default: none).
    ///
    /// That ticket reads a view **whole**, with no row policy, field gate or authorizer
    /// (#716): every Flight-authenticated principal can read every row and column of a
    /// view named here. Name only views whose entire contents every such principal may
    /// read. Plain identifiers (resolved through the connection's `search_path`); each is
    /// typed from one of its rows at boot, so a view empty at boot is not served. A
    /// `wire-backend` build reads no arbitrary SQL, and serves none.
    ///
    /// ```toml
    /// flight_views = ["va_public_metrics"]
    /// ```
    #[cfg(feature = "arrow")]
    #[serde(default)]
    pub flight_views: Vec<String>,

    /// Enable CORS.
    #[serde(default = "defaults::default_true")]
    pub cors_enabled: bool,

    /// CORS allowed origins (if empty, allows all).
    #[serde(default)]
    pub cors_origins: Vec<String>,

    /// Enable framework-level response compression.
    ///
    /// Defaults to `false`. In production FraiseQL is typically deployed
    /// behind a reverse proxy (Nginx, Caddy, cloud load balancer) that
    /// handles compression more efficiently (brotli, shared across upstreams,
    /// cacheable). Enable this only for single-binary / no-proxy deployments.
    #[serde(default = "defaults::default_false")]
    pub compression_enabled: bool,

    /// Accept the HTTP `QUERY` method (RFC 10008) on the GraphQL endpoint (#508).
    ///
    /// Default `false`. `QUERY` is "GET with a request body": safe, idempotent and
    /// cacheable, but carrying a payload. Routing GraphQL reads over `POST` tells
    /// caches, proxies and retry layers "unsafe, do not cache, do not retry", which
    /// is the wrong signal for a deterministic read.
    ///
    /// When enabled, `QUERY` is parsed exactly like a `POST` body and then
    /// **restricted to query operations**: a `mutation` or `subscription` is
    /// refused with `405`. That restriction is the security property, not a
    /// convenience — an intermediary is entitled to retry a safe method, so a
    /// state-changing operation must never travel over one.
    ///
    /// `GET` and `POST` behaviour is unchanged whether this is on or off.
    #[serde(default = "defaults::default_false")]
    pub enable_http_query: bool,

    /// Enable request tracing.
    #[serde(default = "defaults::default_true")]
    pub tracing_enabled: bool,

    /// OTLP exporter endpoint for distributed tracing.
    ///
    /// When set (e.g. `"http://otel-collector:4317"`), the server initializes an
    /// `OpenTelemetry` OTLP exporter. When `None`, the `OTEL_EXPORTER_OTLP_ENDPOINT`
    /// environment variable is checked as a fallback. If neither is set, no OTLP
    /// export occurs (zero overhead).
    #[serde(default)]
    pub otlp_endpoint: Option<String>,

    /// OTLP exporter timeout in seconds (default: 10).
    #[serde(default = "defaults::default_otlp_timeout_secs")]
    pub otlp_export_timeout_secs: u64,

    /// Service name for distributed tracing (default: `"fraiseql"`).
    #[serde(default = "defaults::default_service_name")]
    pub tracing_service_name: String,

    /// Enable APQ (Automatic Persisted Queries).
    #[serde(default = "defaults::default_true")]
    pub apq_enabled: bool,

    /// Enable query caching.
    #[serde(default = "defaults::default_true")]
    pub cache_enabled: bool,

    /// GraphQL endpoint path.
    #[serde(default = "defaults::default_graphql_path")]
    pub graphql_path: String,

    /// Operator-facing status endpoint path.
    ///
    /// Returns the full subsystem report: 200 when healthy or degraded, **503 when the
    /// database is unreachable**. It is not a liveness probe — see `liveness_path`, and
    /// #1217 for what pointing a `livenessProbe` at this costs during a failover.
    #[serde(default = "defaults::default_health_path")]
    pub health_path: String,

    /// Liveness probe endpoint path.
    ///
    /// Always 200, with no dependency call at all. Kubernetes `livenessProbe` points
    /// here (#1217).
    #[serde(default = "defaults::default_liveness_path")]
    pub liveness_path: String,

    /// Readiness probe endpoint path.
    ///
    /// Returns 200 when the server is ready to serve traffic (database reachable),
    /// 503 otherwise. Kubernetes `readinessProbe` should point here.
    #[serde(default = "defaults::default_readiness_path")]
    pub readiness_path: String,

    /// Introspection endpoint path.
    #[serde(default = "defaults::default_introspection_path")]
    pub introspection_path: String,

    /// Metrics endpoint path (Prometheus format).
    #[serde(default = "defaults::default_metrics_path")]
    pub metrics_path: String,

    /// Metrics JSON endpoint path.
    #[serde(default = "defaults::default_metrics_json_path")]
    pub metrics_json_path: String,

    /// Playground (GraphQL IDE) endpoint path.
    #[serde(default = "defaults::default_playground_path")]
    pub playground_path: String,

    /// Enable GraphQL playground/IDE (default: false for production safety).
    ///
    /// When enabled, serves a GraphQL IDE (`GraphiQL` or Apollo Sandbox)
    /// at the configured `playground_path`.
    ///
    /// **Security**: Disabled by default for production safety. Set to true for development
    /// environments only. The playground exposes schema information and can be a
    /// reconnaissance vector for attackers.
    #[serde(default)]
    pub playground_enabled: bool,

    /// Which GraphQL IDE to use.
    ///
    /// - `graphiql`: The classic GraphQL IDE (default)
    /// - `apollo-sandbox`: Apollo's embeddable sandbox
    #[serde(default)]
    pub playground_tool: PlaygroundTool,

    /// `WebSocket` endpoint path for GraphQL subscriptions.
    #[serde(default = "defaults::default_subscription_path")]
    pub subscription_path: String,

    /// Enable GraphQL subscriptions over `WebSocket`.
    ///
    /// When enabled, provides graphql-ws (graphql-transport-ws) protocol
    /// support for real-time subscription events.
    #[serde(default = "defaults::default_true")]
    pub subscriptions_enabled: bool,

    /// Enable metrics endpoints.
    ///
    /// **Security**: Disabled by default for production safety.
    /// When enabled, requires `metrics_token` to be set for authentication.
    #[serde(default)]
    pub metrics_enabled: bool,

    /// Bearer token for metrics endpoint authentication.
    ///
    /// Required when `metrics_enabled` is true. Requests must include:
    /// `Authorization: Bearer <token>`
    ///
    /// **Security**: Use a strong, random token (e.g., 32+ characters).
    #[serde(default)]
    pub metrics_token: Option<String>,

    /// Enable admin API endpoints (default: false for production safety).
    ///
    /// **Security**: Disabled by default. When enabled, requires `admin_token` to be set.
    /// Admin endpoints allow schema reloading, cache management, and config inspection.
    #[serde(default)]
    pub admin_api_enabled: bool,

    /// Bearer token for admin API authentication.
    ///
    /// Required when `admin_api_enabled` is true. Requests must include:
    /// `Authorization: Bearer <token>`
    ///
    /// **Security**: Use a strong, random token (minimum 32 characters).
    /// This token grants access to **destructive** admin operations:
    /// `reload-schema`, `cache/clear`.
    ///
    /// If `admin_readonly_token` is set, this token is restricted to write
    /// operations only. If `admin_readonly_token` is not set, this token
    /// also grants access to read-only endpoints (backwards-compatible).
    #[serde(default)]
    pub admin_token: Option<String>,

    /// Optional separate bearer token for read-only admin operations.
    ///
    /// When set, restricts `admin_token` to destructive operations only
    /// (`reload-schema`, `cache/clear`) and uses this token for read-only
    /// endpoints (`config`, `cache/stats`, `explain`, `grafana-dashboard`).
    ///
    /// Operators and monitoring tools can use this token without gaining
    /// the ability to modify server state or reload the schema.
    ///
    /// **Security**: Must be different from `admin_token` and at least 32
    /// characters. Requires `admin_api_enabled = true` and `admin_token` set.
    #[serde(default)]
    pub admin_readonly_token: Option<String>,

    /// Enable introspection endpoint (default: false for production safety).
    ///
    /// **Security**: Disabled by default. When enabled, the introspection endpoint
    /// exposes the complete GraphQL schema structure. Combined with `introspection_require_auth`,
    /// you can optionally protect it with OIDC authentication.
    #[serde(default)]
    pub introspection_enabled: bool,

    /// Require authentication for introspection endpoint (default: true).
    ///
    /// When true and OIDC is configured, introspection requires same auth as GraphQL endpoint.
    /// When false, introspection is publicly accessible (use only in development).
    #[serde(default = "defaults::default_true")]
    pub introspection_require_auth: bool,

    /// Require authentication for the schema metadata endpoint (default: None).
    ///
    /// When `Some(true)`, the `/api/v1/schema/metadata` endpoint requires OIDC auth
    /// independently of introspection. When `Some(false)`, metadata is publicly
    /// accessible regardless of introspection auth. When `None` (default), falls
    /// back to `introspection_require_auth` for backwards compatibility.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata_require_auth: Option<bool>,

    /// Require authentication for schema export endpoints (default: None).
    ///
    /// Controls `/api/v1/schema.graphql` and `/api/v1/schema.json` independently of
    /// introspection auth. When `Some(true)`, schema export requires OIDC auth. When
    /// `Some(false)`, schema export is publicly accessible. When `None` (default),
    /// falls back to `introspection_require_auth` for backwards compatibility.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema_export_require_auth: Option<bool>,

    /// Require authentication for the GraphQL Playground endpoint (default: None).
    ///
    /// Controls the playground independently of introspection auth. When `Some(true)`,
    /// the playground requires OIDC auth. When `Some(false)`, the playground is publicly
    /// accessible. When `None` (default), falls back to `introspection_require_auth`
    /// for backwards compatibility.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub playground_require_auth: Option<bool>,

    /// Require authentication for the `WebSocket` subscription endpoint (default: None).
    ///
    /// Controls the `/subscriptions` endpoint independently of introspection auth.
    /// When `Some(true)`, the subscription endpoint requires OIDC auth. When `Some(false)`,
    /// subscriptions are publicly accessible. When `None` (default), falls back to
    /// `introspection_require_auth` for backwards compatibility.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subscription_require_auth: Option<bool>,

    /// How often (seconds) a live `WebSocket` subscription re-checks its principal's
    /// authorization — token expiry and, when a revocation store is configured,
    /// revocation (#771). Default: 30.
    ///
    /// A JWT is validated once at the upgrade; without this re-check an expired or
    /// revoked token would keep receiving policy-scoped events until the client
    /// disconnects. The check is cheap (a clock comparison, plus one revocation-store
    /// lookup per interval — never a round-trip to the `IdP`). Token expiry is
    /// additionally enforced on every event delivery regardless of this interval.
    /// `0` disables the periodic re-check (the per-delivery expiry check remains).
    #[serde(default = "defaults::default_subscription_auth_recheck_secs")]
    pub subscription_auth_recheck_secs: u64,

    /// Require authentication for design audit API endpoints (default: true).
    ///
    /// Design audit endpoints expose system architecture and optimization opportunities.
    /// When true and OIDC is configured, design endpoints require same auth as GraphQL endpoint.
    /// When false, design endpoints are publicly accessible (use only in development).
    #[serde(default = "defaults::default_true")]
    pub design_api_require_auth: bool,

    /// Database connection pool minimum size.
    #[serde(default = "defaults::default_pool_min_size")]
    pub pool_min_size: usize,

    /// Database connection pool maximum size.
    #[serde(default = "defaults::default_pool_max_size")]
    pub pool_max_size: usize,

    /// Database connection pool timeout in seconds.
    #[serde(default = "defaults::default_pool_timeout")]
    pub pool_timeout_secs: u64,

    /// How many pool connections streaming reads may hold at once (#958).
    ///
    /// `None` (the default) derives a quarter of `pool_max_size`, at least 1.
    ///
    /// A streaming read — an NDJSON/CSV/XLSX export, a gRPC server-streaming RPC —
    /// keeps its connection for as long as the client is reading, which on a large
    /// export is unbounded. Raise this on a server whose job is bulk export; lower
    /// it on one where exports are incidental and must never cost interactive
    /// requests their connections.
    #[serde(default)]
    pub pool_max_streaming_reads: Option<usize>,

    /// `hnsw.iterative_scan` for every database connection (#1116).
    ///
    /// `strict_order` (the default) makes a filtered similarity search keep
    /// scanning until `k` rows survive the filter, in exact distance order.
    /// pgvector's own default is `off`, which hands the filter one bounded
    /// candidate list: once the filter is selective, that list is exhausted
    /// first and the query **succeeds with fewer rows than asked for** —
    /// measured at 100 000 documents and a 1%-selective filter, two rows out of
    /// ten and a recall of 0.20.
    ///
    /// `relaxed_order` skips the ordering guarantee for a cheaper scan; `off`
    /// sets nothing at all, leaving whatever the server or `ALTER DATABASE`
    /// established.
    #[serde(default)]
    pub vector_hnsw_iterative_scan: HnswIterativeScan,

    /// `ivfflat.iterative_scan` for every database connection (#1116).
    ///
    /// The `IVFFlat` sibling of [`vector_hnsw_iterative_scan`](Self::vector_hnsw_iterative_scan),
    /// with the same failure mode and the same default posture. pgvector defines
    /// no `strict_order` for `IVFFlat`, so this setting has only `relaxed_order`
    /// (the default) and `off`.
    #[serde(default)]
    pub vector_ivfflat_iterative_scan: IvfflatIterativeScan,

    /// `hnsw.ef_search` for every database connection, or `None` to leave
    /// pgvector's default of 40 (#1116).
    ///
    /// Reach for this when filtered similarity searches still return fewer than
    /// `k` rows with `vector_hnsw_iterative_scan` on. Measured on 20 000 rows ×
    /// 64 dimensions with a 1% filter, `k = 10`: `iterative_scan` alone returned
    /// 10, 5 and 4 rows over three datasets; raising `ef_search` to 1000 returned
    /// 10 every time; raising `max_scan_tuples` 100× instead changed nothing.
    ///
    /// Unset by default because it is a latency/recall trade paid by **every**
    /// search on the deployment, and its right value is a property of the corpus
    /// rather than something FraiseQL can pick.
    #[serde(default)]
    pub vector_hnsw_ef_search: Option<u32>,

    /// Enable incremental delivery on the GraphQL endpoint (#387, #958).
    /// Default `false`.
    ///
    /// When enabled, a request carrying `Accept: text/event-stream` or
    /// `Accept: multipart/mixed` receives its response incrementally, and
    /// `@stream(initialCount: N)` / `@defer` become live rather than advisory:
    /// `@stream` delivers an initial payload with `N` items then batches
    /// re-executed through the full pipeline (auth, validation, RLS, caching) with
    /// paginated variables; `@defer` splits the one execution's result into an
    /// immediate payload and one payload per deferred fragment.
    ///
    /// This gates the **capability**, not one framing of it: SSE and
    /// `multipart/mixed` are two envelopes over the same payload sequence, and an
    /// operator opting out of one is opting out of both. (It was
    /// `enable_graphql_sse` until #958 added the second framing, at which point
    /// the name no longer described what the flag did.)
    ///
    /// When disabled (default), both `Accept` headers are ignored and behaviour is
    /// byte-for-byte unchanged; `@stream`/`@defer` remain advisory no-ops.
    #[serde(default)]
    pub enable_graphql_incremental: bool,

    /// Continuation batch size for `@stream` deliveries (#387).
    ///
    /// Rows per incremental batch after the initial payload, on either framing.
    /// Optional; defaults to 100. Setting it while
    /// [`enable_graphql_incremental`](Self::enable_graphql_incremental) is `false` is
    /// a configuration error (the value would be inert).
    #[serde(default)]
    pub graphql_incremental_batch_size: Option<u32>,

    /// Read replica connection URLs (#407). Empty = no replicas.
    ///
    /// When set, compiled GraphQL *queries* (and every other structurally
    /// read-only adapter path) are served round-robin from these replicas, while
    /// mutations and all mixed-use surfaces stay on
    /// [`database_url`](Self::database_url). Each replica pool inherits the
    /// primary pool's sizing, timeout and `[database_tls]` settings. A replica
    /// that is unreachable at boot refuses startup; one that fails at runtime is
    /// skipped, falling back to the primary.
    #[serde(default)]
    pub read_replica_urls: Vec<String>,

    /// Read-your-writes pin window in milliseconds (#407).
    ///
    /// After any mutation, reads keep routing to the primary for this long so
    /// replication lag cannot serve a client its own stale write. Set it to at
    /// least the worst replica lag you tolerate. Defaults to 5000 ms when
    /// replicas are configured; setting it **without**
    /// [`read_replica_urls`](Self::read_replica_urls) is a configuration error.
    #[serde(default)]
    pub read_replica_pin_after_write_ms: Option<u64>,

    /// Bounded staleness for replica-served reads, in milliseconds (#957).
    ///
    /// Where [`read_replica_pin_after_write_ms`](Self::read_replica_pin_after_write_ms)
    /// is an *assertion* about worst-case lag that covers a client's own writes,
    /// this is a *measurement* that covers everyone else's: a replica whose
    /// probed replay lag — aged by how long ago it was probed — exceeds this
    /// budget is skipped, and the read is served by the primary.
    ///
    /// Unset means no lag-based routing: replicas serve reads however far behind
    /// they are. A replica whose lag cannot be measured (never probed, probe
    /// failing, promoted out of recovery by a failover) is never eligible while
    /// this is set.
    ///
    /// Must exceed
    /// [`read_replica_health_probe_interval_ms`](Self::read_replica_health_probe_interval_ms);
    /// setting it **without** [`read_replica_urls`](Self::read_replica_urls) is a
    /// configuration error.
    #[serde(default)]
    pub read_replica_max_lag_ms: Option<u64>,

    /// How often each replica is probed for recovery state and replay lag, in
    /// milliseconds (#957).
    ///
    /// Probing runs whenever replicas are configured, with or without a
    /// staleness budget: the boot health check happens once, so a replica that a
    /// failover promotes afterwards would otherwise keep taking reads as a
    /// writable server with no one ever noticing.
    ///
    /// Defaults to 1000 ms when replicas are configured; setting it **without**
    /// [`read_replica_urls`](Self::read_replica_urls) is a configuration error.
    #[serde(default)]
    pub read_replica_health_probe_interval_ms: Option<u64>,

    /// OIDC authentication configuration (optional).
    ///
    /// When set, enables JWT authentication using OIDC discovery.
    /// Supports Auth0, Keycloak, Okta, Cognito, Azure AD, and any
    /// OIDC-compliant provider.
    ///
    /// # Example (TOML)
    ///
    /// ```toml
    /// [auth]
    /// issuer = "https://your-tenant.auth0.com/"
    /// audience = "your-api-identifier"
    /// ```
    #[serde(default)]
    pub auth: Option<OidcConfig>,

    /// HS256 symmetric-key authentication (optional).
    ///
    /// Alternative to `auth` (OIDC) for integration testing and internal
    /// service-to-service scenarios. Mutually exclusive with `auth`.
    ///
    /// Validation is fully local — no discovery endpoint, no JWKS fetch.
    /// Not recommended for public-facing production.
    ///
    /// # Example (TOML)
    ///
    /// ```toml
    /// [auth_hs256]
    /// secret_env = "FRAISEQL_HS256_SECRET"
    /// issuer = "my-test-suite"
    /// audience = "my-api"
    /// ```
    #[serde(default)]
    pub auth_hs256: Option<Hs256Config>,

    /// SAML 2.0 SP-initiated SSO (#381, requires the `auth-saml` feature).
    ///
    /// Mounts `GET /auth/saml/login` and `POST /auth/saml/acs`. Requires
    /// `[auth_hs256]` (assertions mint sessions the server itself validates)
    /// and a database pool (sessions and account linking are Postgres-backed).
    #[cfg(feature = "auth-saml")]
    #[serde(default)]
    pub saml: Option<SamlServerConfig>,

    /// SCIM 2.0 provisioning (#946).
    ///
    /// Mounts `/scim/v2/*` behind a provisioning bearer token, and
    /// `/api/scim/tokens` behind the admin token. Requires a database pool and
    /// `admin_token`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scim: Option<ScimServerConfig>,

    /// The operator SQL console (#962).
    ///
    /// Mounts `POST /api/v1/admin/sql`, which runs statements the operator typed
    /// — the only such surface on the server. Requires the `admin-sql` cargo
    /// feature, `admin_api_enabled` and `admin_token`; each missing piece is a
    /// boot error naming itself.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub admin_sql: Option<AdminSqlConfig>,

    /// Name of the environment variable holding the server HMAC secret.
    ///
    /// When set, the per-dispatch idempotency token surfaced to functions is
    /// HMAC-signed with a subkey derived from this secret, making it unforgeable —
    /// required before it is exposed externally as a VERP delivery-tracking
    /// Return-Path. Unset → the token is an unsigned digest (the zero-config
    /// default). The secret must be **stable across restarts and shared across
    /// instances** (a per-process random value would break resume + multi-instance
    /// idempotency); resolved from the environment at startup, never the config file.
    ///
    /// ```toml
    /// hmac_secret_env = "FRAISEQL_HMAC_SECRET"
    /// ```
    #[serde(default)]
    pub hmac_secret_env: Option<String>,

    /// TLS/SSL configuration for HTTPS and encrypted connections.
    ///
    /// When set, enables TLS enforcement for HTTP/gRPC endpoints and
    /// optionally requires mutual TLS (mTLS) for client certificates.
    ///
    /// # Example (TOML)
    ///
    /// ```toml
    /// [tls]
    /// enabled = true
    /// cert_path = "/etc/fraiseql/cert.pem"
    /// key_path = "/etc/fraiseql/key.pem"
    /// require_client_cert = false
    /// min_version = "1.2"  # "1.2" or "1.3"
    /// ```
    #[serde(default)]
    pub tls: Option<TlsServerConfig>,

    /// Database TLS configuration.
    ///
    /// Enables TLS for database connections and configures
    /// per-database TLS settings (PostgreSQL, Redis, `ClickHouse`, etc.).
    ///
    /// # Example (TOML)
    ///
    /// ```toml
    /// [database_tls]
    /// postgres_ssl_mode = "require"  # disable, allow, prefer, require, verify-ca, verify-full
    /// redis_ssl = true               # Use rediss:// protocol
    /// clickhouse_https = true         # Use HTTPS
    /// elasticsearch_https = true      # Use HTTPS
    /// verify_certificates = true      # Verify server certificates
    /// ```
    #[serde(default)]
    pub database_tls: Option<DatabaseTlsConfig>,

    /// Require `Content-Type: application/json` on POST requests (default: true).
    ///
    /// CSRF protection: rejects POST requests with non-JSON Content-Type
    /// (e.g. `text/plain`, `application/x-www-form-urlencoded`) with 415.
    #[serde(default = "defaults::default_true")]
    pub require_json_content_type: bool,

    /// Maximum request body size in bytes (default: 1 MB).
    ///
    /// Requests exceeding this limit receive 413 Payload Too Large.
    /// Set to 0 to use axum's default (no limit).
    #[serde(default = "defaults::default_max_request_body_bytes")]
    pub max_request_body_bytes: usize,

    /// Maximum number of HTTP headers per request (default: 100).
    ///
    /// Requests with more headers than this limit receive 431 Request Header Fields Too Large.
    /// Prevents header-flooding `DoS` attacks that exhaust memory.
    #[serde(default = "defaults::default_max_header_count")]
    pub max_header_count: usize,

    /// Maximum total size of all HTTP headers in bytes (default: 32 `KiB`).
    ///
    /// Requests whose combined header name+value bytes exceed this limit receive
    /// 431 Request Header Fields Too Large. Prevents memory exhaustion from
    /// oversized header values.
    #[serde(default = "defaults::default_max_header_bytes")]
    pub max_header_bytes: usize,

    /// Per-request processing timeout in seconds (default: `None` — no timeout).
    ///
    /// When set, each HTTP request must complete within this many seconds or
    /// the server returns **408 Request Timeout**.  This is a defence-in-depth
    /// measure against slow or runaway database queries.
    ///
    /// **Recommendation**: set to `60` for production deployments.
    ///
    /// # Why this is not defaulted
    ///
    /// Its only consumer is a `TimeoutLayer` applied to the **whole** application
    /// (`server::routing::middleware`), so a default here would also cap the responses
    /// that are long-lived by design: the NDJSON, CSV and XLSX exports, and every SSE
    /// stream. A deployment that set it to bound a runaway read would be truncating its
    /// own exports as the price, and an export cut at the timeout is a partial file
    /// delivered under a `200` — the failure this codebase refuses elsewhere by
    /// refusing up front (`RESUME_TOO_FAR_BEHIND`).
    ///
    /// So it stays opt-in, and work that needs bounding is bounded where it is decided:
    /// `?select=` embedding, the runaway this note was written for, is one composed
    /// statement scored by `[security.cost_budget] per_request_max` before it is sent.
    /// Defaulting this knob would require moving the layer off the global router and
    /// onto the non-streaming routes first.
    ///
    /// # Example (TOML)
    ///
    /// ```toml
    /// request_timeout_secs = 60
    /// ```
    #[serde(default)]
    pub request_timeout_secs: Option<u64>,

    /// Maximum byte length for a query string delivered via HTTP GET.
    ///
    /// GET queries are URL-encoded and passed as a query parameter. Very long
    /// strings are either a `DoS` attempt or a sign that the caller should use
    /// POST instead. Default: `100_000` (100 `KiB`).
    ///
    /// # Example (TOML)
    ///
    /// ```toml
    /// max_get_query_bytes = 50000
    /// ```
    #[serde(default = "defaults::default_max_get_query_bytes")]
    pub max_get_query_bytes: usize,

    /// Rate limiting configuration for GraphQL requests.
    ///
    /// When configured, enables per-IP and per-user rate limiting with token bucket algorithm.
    /// Defaults to enabled with sensible per-IP limits for security-by-default.
    ///
    /// # Example (TOML)
    ///
    /// ```toml
    /// [rate_limiting]
    /// enabled = true
    /// rps_per_ip = 100      # 100 requests/second per IP
    /// rps_per_user = 1000   # 1000 requests/second per authenticated user
    /// burst_size = 500      # Allow bursts up to 500 requests
    /// ```
    #[serde(default)]
    pub rate_limiting: Option<RateLimitConfig>,

    /// Rate-limit values supplied by CLI flags or environment variables.
    ///
    /// Not a config-file key — `#[serde(skip)]` — because it exists to record what
    /// the *operator* overrode at launch, which is the layer that must win over both
    /// `[rate_limiting]` above and the compiled schema's `[security.rate_limiting]`.
    /// These used to be merged into `rate_limiting` on arrival, which erased which
    /// fields were set and left the compiled schema shadowing them entirely (#774).
    #[serde(skip)]
    pub rate_limit_overrides: RateLimitOverrides,

    /// Observer runtime configuration (optional, requires `observers` feature).
    #[cfg(feature = "observers")]
    #[serde(default)]
    pub observers: Option<ObserverConfig>,

    /// Scheduled-ingress source scheduler configuration (optional, requires the
    /// `sources` feature). The source *definitions* live in the compiled schema;
    /// this `[sources]` section tunes the runtime (global on/off, connector SSRF
    /// allowlist).
    ///
    /// Boxed to keep `ServerConfig` small: this section is rarely set and read once
    /// at startup, so it does not belong inline in a struct that sits on the
    /// request-handling futures (an inline copy tips borderline futures past
    /// clippy's `large_futures` stack budget).
    #[cfg(feature = "sources")]
    #[serde(default)]
    pub sources: Option<Box<SourcesConfig>>,

    /// Connection pool pressure monitoring configuration.
    ///
    /// When `enabled = true`, the server spawns a background task that monitors
    /// pool metrics and emits scaling recommendations via Prometheus metrics and
    /// log lines. **The pool is not resized at runtime** — act on
    /// `fraiseql_pool_tuning_*` events by adjusting `max_connections` and restarting.
    ///
    /// # Example (TOML)
    ///
    /// ```toml
    /// [pool_tuning]
    /// enabled = true
    /// min_pool_size = 5
    /// max_pool_size = 50
    /// tuning_interval_ms = 30000
    /// ```
    #[serde(default)]
    pub pool_tuning: Option<crate::config::pool_tuning::PoolPressureMonitorConfig>,

    /// Admission control configuration.
    ///
    /// When set, enforces a maximum number of concurrent in-flight requests and
    /// a maximum queue depth.  Requests that exceed either limit receive
    /// `503 Service Unavailable` immediately instead of stalling under load.
    ///
    /// # Example (TOML)
    ///
    /// ```toml
    /// [admission_control]
    /// max_concurrent = 500
    /// max_queue_depth = 1000
    /// ```
    #[serde(default)]
    pub admission_control: Option<AdmissionConfig>,

    /// Security contact email for `/.well-known/security.txt` (RFC 9116).
    ///
    /// When set, the server exposes a `/.well-known/security.txt` endpoint
    /// with this email address as the security contact. This helps security
    /// researchers report vulnerabilities responsibly.
    ///
    /// # Example (TOML)
    ///
    /// ```toml
    /// security_contact = "security@example.com"
    /// ```
    #[serde(default)]
    pub security_contact: Option<String>,

    /// Query validation overrides (depth and complexity limits).
    ///
    /// When present, these values take precedence over the limits baked into
    /// the compiled schema, allowing operators to tune validation without
    /// recompiling.
    ///
    /// # Example (TOML)
    ///
    /// ```toml
    /// [validation]
    /// max_query_depth = 15
    /// max_query_complexity = 200
    /// ```
    #[serde(default)]
    pub validation: Option<fraiseql_core::schema::ValidationConfig>,

    /// Maximum failed admin bearer auth attempts per IP within a 60-second
    /// window before the IP is blocked with 429 Too Many Requests (default: 10).
    ///
    /// Set to `0` to disable brute-force protection entirely (not recommended).
    ///
    /// # Example (TOML)
    ///
    /// ```toml
    /// admin_auth_max_failures = 5
    /// ```
    #[serde(default = "defaults::default_admin_auth_max_failures")]
    pub admin_auth_max_failures: u32,

    /// Bearer token protecting the storage REST API (`/storage/v1/`).
    ///
    /// When set, all requests to storage endpoints must include an
    /// `Authorization: Bearer <token>` header that matches this value.  Requests
    /// without a valid token receive **401 Unauthorized**.
    ///
    /// **Security**: This token protects *all* storage operations (upload, download,
    /// delete, presigned URL).  Use a strong random string (minimum 32 characters).
    /// Omit the field (or set `None`) to leave storage endpoints open — appropriate
    /// only in development or when the storage API is behind a trusted network boundary.
    ///
    /// # Example (TOML)
    ///
    /// ```toml
    /// storage_token = "your-strong-random-token-here"
    /// ```
    #[serde(default)]
    pub storage_token: Option<String>,

    /// Graceful shutdown drain timeout in seconds (default: 30).
    ///
    /// After a SIGTERM or Ctrl+C signal, the server stops accepting new connections and
    /// waits for in-flight requests and background runtimes (observers) to finish.
    /// If the drain takes longer than this value, the process logs a warning and exits
    /// immediately instead of hanging indefinitely.
    ///
    /// Set this to match `terminationGracePeriodSeconds` in your Kubernetes pod spec
    /// minus a small buffer (e.g., 25s when `terminationGracePeriodSeconds = 30`).
    ///
    /// Override with `FRAISEQL_SHUTDOWN_TIMEOUT_SECS`.
    #[serde(default = "defaults::default_shutdown_timeout_secs")]
    pub shutdown_timeout_secs: u64,

    /// Usage counter persistence configuration (optional).
    ///
    /// When set, mutation usage counters are periodically flushed to PostgreSQL
    /// and restored on server startup.  Requires a PostgreSQL database URL.
    ///
    /// ```toml
    /// [usage]
    /// flush_interval_secs = 60
    /// ```
    ///
    /// When absent (default), counters are in-memory only and reset on restart.
    #[serde(default)]
    pub usage: Option<crate::config::UsagePersistenceConfig>,

    /// Named object-storage backend configurations, keyed by storage name.
    ///
    /// Each `[storage.<name>]` section is wired into a mounted `/storage/v1/*`
    /// route group on startup (PostgreSQL only — the object-metadata repository
    /// requires a `sqlx::PgPool`). The section name is the logical bucket name in
    /// the URL path (`/storage/v1/object/<name>/<key>`). See
    /// [`StorageSectionConfig`].
    ///
    /// **v1 supports a single section.** Configuring more than one
    /// `[storage.<name>]` is a startup error (multiplexing several physical
    /// backends behind one route group is a planned follow-up).
    ///
    /// # Example (TOML)
    ///
    /// ```toml
    /// [storage.uploads]
    /// backend = "local"
    /// path = "/var/lib/fraiseql/uploads"
    /// access = "public_read"
    /// ```
    #[serde(default)]
    pub storage: HashMap<String, StorageSectionConfig>,

    /// Named file-upload route configurations, keyed by route name.
    ///
    /// **Not yet wired into the binary** (tracked as a `[storage]` follow-up).
    /// The section is parsed only so the server can warn at startup rather than
    /// silently dropping it. See [`FileSectionConfig`].
    #[serde(default)]
    pub files: HashMap<String, FileSectionConfig>,

    /// Inbound webhook receiver routes (`[webhooks.<name>]`), keyed by route name.
    ///
    /// Each entry mounts `POST /webhooks/<name>`: the delivery is signature-verified
    /// (per `provider`, secret from `secret_env`), normalized to an `InboundMessage`,
    /// and persisted onto the durable spine. Requires the `inbound` feature and a
    /// PostgreSQL pool; empty by default.
    #[cfg(feature = "inbound")]
    #[serde(default)]
    pub webhooks: HashMap<String, crate::config::WebhookRouteConfig>,

    /// Connected mailbox accounts (`[mailbox.<name>]`), keyed by account name.
    ///
    /// Each account carries an optional poll-IMAP receive half
    /// (`[mailbox.<name>.imap]`) — a background poll worker that fetches new
    /// messages by UID watermark, normalizes their MIME to an `InboundMessage` on
    /// the durable spine, and fires `after:ingest:email` functions — and (via the
    /// hardening `send_email` transport) an SMTP send half. Requires the
    /// `inbound-email` feature and a PostgreSQL pool; empty by default.
    #[cfg(feature = "inbound-email")]
    #[serde(default)]
    pub mailbox: HashMap<String, crate::inbound::email::MailboxConfig>,

    /// Delivery-feedback send policy (`[send]`).
    ///
    /// Governs how the correlation step reacts to inbound bounces / challenges /
    /// replies — currently the challenge-suppression threshold
    /// (`challenge_suppress_after`, default 2). Requires the `inbound-email`
    /// feature; defaults apply when the section is absent.
    #[cfg(feature = "inbound-email")]
    #[serde(default)]
    pub send: crate::inbound::email::SendSettings,

    /// Multi-tenant executor runtime configuration.
    ///
    /// Off by default. Enable with `[tenancy.runtime] enabled = true` to mount the
    /// multi-tenant runtime in the off-the-shelf binary: the per-tenant executor
    /// registry, `X-Tenant-ID` / JWT `tenant_id` / Host dispatch, and the
    /// `/api/v1/admin/tenants/*` lifecycle API. Runtime tenant provisioning
    /// (registering a tenant with its own connection) is PostgreSQL-only.
    ///
    /// ```toml
    /// [tenancy.runtime]
    /// enabled = true
    /// ```
    #[serde(default)]
    pub tenancy: TenancyServerConfig,

    /// REST export-format settings (`[export]`).
    ///
    /// Export is a *runtime* response-serialization concern, so
    /// [`ExportConfig`](crate::routes::rest::export_config::ExportConfig) lives in this
    /// crate rather than in the compiled schema — the layering rule its module doc
    /// states. This field is the deserialization site it had been missing entirely:
    /// every consumer built `ExportConfig::default()`, so all seven keys were accepted
    /// by the config parser and then ignored (#917).
    ///
    /// ```toml
    /// [export]
    /// csv_delimiter = ";"
    /// xlsx_max_rows = 50000
    /// export_formats = ["csv"]   # an explicit list; empty disables all exports
    /// ```
    #[cfg(feature = "rest")]
    #[serde(default)]
    pub export: crate::routes::rest::export_config::ExportConfig,

    /// Enriched-identity resolution (#539): `[identity.enrichment]` /
    /// `[identity.sender]`. Top-level (not under `[auth]`) so it applies under
    /// any auth mode — HS256/OIDC parity by construction. Gated on `auth`
    /// because enrichment requires an authenticated subject and the auth DB pool.
    #[cfg(feature = "auth")]
    #[serde(default)]
    pub identity: Option<crate::identity::IdentityConfig>,

    /// Durable per-thread conversation / session state (#389):
    /// `[session_state]`. Presence enables the subsystem — `backend =
    /// "postgres"` requires a database pool and refuses to boot when its table
    /// cannot be initialised (never a silent in-memory downgrade). Gated on
    /// `auth` because the store lives in `fraiseql-auth` and the `session_id`
    /// comes from the authenticated context.
    #[cfg(feature = "auth")]
    #[serde(default)]
    pub session_state: Option<SessionStateServerConfig>,

    /// Durable long-running operations (#391): `[async_operations]`. Presence
    /// mounts `POST/GET/DELETE /operations/v1/…` (a new HTTP surface — an
    /// explicit operator decision) and starts the worker pool; requires a
    /// database pool and refuses to boot when `_system.async_operations`
    /// cannot be initialised. The `operations` allowlist is required and
    /// fail-closed.
    #[serde(default)]
    pub async_operations: Option<AsyncOperationsConfig>,

    /// Outbound change-data-capture to external brokers (#382).
    ///
    /// Present ⇒ the server drains the change-log outbox to the configured
    /// sinks on its own task set. Absent ⇒ no drain runs. A configured section
    /// with no database pool, an unreachable broker, or delivery-state DDL
    /// that will not apply is a boot refusal — a server that boots without its
    /// drain is silent data loss for every downstream consumer.
    #[cfg(feature = "cdc-outbound")]
    #[serde(default)]
    pub cdc_outbound: Option<CdcOutboundConfig>,

    /// `[subscription_kafka]` — mirror subscription deliveries to a Kafka topic (#1102).
    ///
    /// Present ⇒ every payload the subscription manager broadcasts is also published to
    /// Kafka. Absent ⇒ no producer is built. A configured section whose endpoint is
    /// refused by the transport guard is a **boot refusal**: this path carries entity
    /// after-images and pre-images, so falling back to an unguarded connection is the
    /// one outcome that must not be possible.
    ///
    /// Not a change stream — see [`SubscriptionKafkaConfig`] for why `[cdc_outbound]` is
    /// the section for that.
    #[cfg(feature = "subscription-kafka")]
    #[serde(default)]
    pub subscription_kafka: Option<SubscriptionKafkaConfig>,
}

/// A single `[storage.<name>]` configuration section.
///
/// Combines the storage *backend* connection settings (mapped to
/// [`fraiseql_storage::config::StorageConfig`] and passed to
/// `fraiseql_storage::create_backend`) with the optional *logical-bucket* access
/// policy (mapped to `fraiseql_storage::config::BucketConfig`). The section name
/// becomes the logical bucket name in the URL path.
///
/// `[sources]` — runtime configuration for the scheduled-ingress source scheduler
/// (#573, requires the `sources` feature).
///
/// The source *definitions* (name, schedule, function, `run_as`) come from the
/// compiled schema; this section is operator-facing runtime tuning. Both fields are
/// overridable by environment variables (env > TOML > default) so production can
/// tune without recompiling:
///
/// - `FRAISEQL_SOURCES_ENABLED` — global on/off (`false`/`0`/`no`/`off` disables).
/// - `FRAISEQL_SOURCES_ALLOWED_DOMAINS` — comma-separated SSRF allowlist.
/// - `FRAISEQL_SOURCES_ALLOWED_ENV_VARS` — comma-separated env-var allowlist (#840).
#[cfg(feature = "sources")]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SourcesConfig {
    /// Global on/off for the source scheduler. Per-source `enabled` in the compiled
    /// schema still applies; this disables the whole scheduler without recompiling.
    /// Default: `true`.
    #[serde(default = "defaults::default_true")]
    pub enabled: bool,

    /// SSRF allowlist (glob patterns) for source connectors' outbound fetches.
    /// Deny-by-default: empty permits no outbound host.
    #[serde(default)]
    pub allowed_domains: Vec<String>,

    /// Environment variables source connectors may read via `fraiseql_env_var`
    /// (#840). Deny-by-default: empty grants no variable. Overridable by
    /// `FRAISEQL_SOURCES_ALLOWED_ENV_VARS` (comma-separated).
    #[serde(default)]
    pub allowed_env_vars: Vec<String>,

    /// Log each firing's trigger payload at debug (default: `false`).
    ///
    /// Off-by-default mirrors the observer `log_payloads` gate. A source's trigger
    /// payload carries only schedule context (the external data the connector fetches
    /// never reaches the poller), so the risk is low — but payload logging stays an
    /// operator opt-in for a uniform PII stance.
    #[serde(default)]
    pub log_payloads: bool,
}

#[cfg(feature = "sources")]
impl Default for SourcesConfig {
    fn default() -> Self {
        Self {
            enabled:          true,
            allowed_domains:  Vec::new(),
            allowed_env_vars: Vec::new(),
            log_payloads:     false,
        }
    }
}

/// The connection fields mirror [`fraiseql_storage::config::StorageConfig`].
///
/// The policy fields (`access`, `max_object_bytes`, `allowed_mime_types`,
/// `serve_inline`) are optional and default to a private, force-download bucket.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StorageSectionConfig {
    /// Backend type: `"local"`, `"s3"` (and S3-compatible providers `"hetzner"`,
    /// `"scaleway"`, `"ovh"`, `"exoscale"`, `"backblaze"`, `"r2"`), `"gcs"`,
    /// `"azure"`. Non-local backends require the matching Cargo feature
    /// (`aws-s3`, `gcs`, `azure-blob`) to be compiled in.
    pub backend: String,

    /// Filesystem path for the `local` backend.
    #[serde(default)]
    pub path: Option<String>,

    /// Physical bucket name for S3/GCS/Azure backends.
    #[serde(default)]
    pub bucket: Option<String>,

    /// Region for S3-compatible backends.
    #[serde(default)]
    pub region: Option<String>,

    /// Custom endpoint URL for S3-compatible services and cloud emulators.
    #[serde(default)]
    pub endpoint: Option<String>,

    /// GCP project ID for the GCS backend.
    #[serde(default)]
    pub project_id: Option<String>,

    /// Azure storage account name.
    #[serde(default)]
    pub account_name: Option<String>,

    /// Access policy for the logical bucket: `"private"` (default) or
    /// `"public_read"`. An unrecognised value is a startup error.
    #[serde(default)]
    pub access: Option<String>,

    /// Maximum object size in bytes for the logical bucket (None = unlimited,
    /// subject to the route-wide body limit).
    #[serde(default)]
    pub max_object_bytes: Option<u64>,

    /// Allowed MIME types for uploads (None = any). Supports `image/*`-style
    /// wildcards.
    #[serde(default)]
    pub allowed_mime_types: Option<Vec<String>>,

    /// Serve downloads with `Content-Disposition: inline` instead of the default
    /// `attachment`. Active-content types (`text/html`, `image/svg+xml`, …) are
    /// always served as `attachment` regardless of this flag.
    #[serde(default)]
    pub serve_inline: Option<bool>,

    /// Lifetime of a resumable-upload session in seconds (#369; default 24
    /// hours). An expired session answers `410 Gone` and is reaped: staged
    /// bytes are discarded and a reservation the session created is released.
    #[serde(default)]
    pub upload_ttl_secs: Option<u64>,

    /// Per-bucket access policy (#371): a list of permit rules that REPLACES
    /// the coarse `access` mode for this bucket. Every request is denied
    /// unless a rule permits it.
    ///
    /// ```toml
    /// [[storage.docs.policies]]
    /// methods = ["read"]
    /// principal = "role:auditor"
    /// key_prefix = "reports/"
    /// ```
    ///
    /// An unknown method or principal spelling is a startup error, never a
    /// silently-denying rule.
    #[serde(default)]
    pub policies: Option<Vec<PolicyRuleConfig>>,

    /// Named transform presets for the render endpoint (#370), e.g.
    /// `transform_presets = [{ name = "thumb", width = 200, format = "webp" }]`.
    /// Served only when the server is built with the `storage-transforms`
    /// feature; configuring presets without it is a startup error, not a
    /// silently absent endpoint.
    #[serde(default)]
    pub transform_presets: Option<Vec<TransformPresetConfig>>,

    /// Resize mode applied to a render that names none (#973). Defaults to
    /// `contain`, the behaviour the render endpoint shipped with. An unknown
    /// name is a startup error, not a silently different rendering.
    #[serde(default)]
    pub default_resize_mode: Option<String>,

    /// Path to the font file backing text watermarks (#973). Read and parsed
    /// at boot: a missing or unreadable font refuses to start rather than
    /// failing on the first render. Buckets without one refuse
    /// `?watermark_text=` by name.
    #[serde(default)]
    pub watermark_font: Option<String>,
}

/// One permit rule in a `[[storage.<name>.policies]]` list (#371).
///
/// There is deliberately no `effect` field: rules permit, and denial is the
/// fallthrough. See `fraiseql_storage::policy` for why.
///
/// This *is* `fraiseql_storage::PolicyRuleSpec`, not a config-side copy of its
/// shape. A policy now reaches the runtime through two doors — this section at
/// boot and `PUT /api/v1/admin/storage/{bucket}/policies` at runtime (#974) —
/// and one type means one parse, so the two cannot come to disagree about which
/// policies are valid.
pub type PolicyRuleConfig = fraiseql_storage::PolicyRuleSpec;

/// One named transform preset in a `[storage.<name>]` section (#370).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TransformPresetConfig {
    /// The preset name used as `?preset=<name>`.
    pub name:        String,
    /// Target width in pixels.
    #[serde(default)]
    pub width:       Option<u32>,
    /// Target height in pixels.
    #[serde(default)]
    pub height:      Option<u32>,
    /// Output format: `webp` | `jpeg` | `png` | `avif`.
    #[serde(default)]
    pub format:      Option<String>,
    /// Encoder quality (1-100) for lossy formats. Refused at boot for `png`
    /// and `webp`, which this server encodes losslessly (#973).
    #[serde(default)]
    pub quality:     Option<u8>,
    /// How the resize fills the box: `contain` (default) | `stretch` | `fit` |
    /// `fill` | `cover-blur` | `cover-mirror` (#973).
    #[serde(default)]
    pub resize_mode: Option<String>,
    /// Where a `fill` keeps its content, or a crop is taken from: a compass
    /// point, `center`, or `smart` (#973).
    #[serde(default)]
    pub gravity:     Option<String>,
}

/// A single `[files.<name>]` configuration section.
///
/// File-upload routes are **not yet wired** into the binary; this type exists so
/// the server can warn rather than silently ignore the section. All fields are
/// optional to keep parsing tolerant.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FileSectionConfig {
    /// Named storage backend this upload route writes to.
    #[serde(default)]
    pub storage: Option<String>,

    /// Maximum upload size (e.g. `"50MB"`).
    #[serde(default)]
    pub max_size: Option<String>,

    /// URL path prefix override.
    #[serde(default)]
    pub path: Option<String>,
}

/// Multi-tenant runtime configuration (`[tenancy]`).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TenancyServerConfig {
    /// Per-tenant executor runtime settings (`[tenancy.runtime]`).
    #[serde(default)]
    pub runtime: TenancyRuntimeConfig,
}

/// Per-tenant executor runtime settings (`[tenancy.runtime]`).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TenancyRuntimeConfig {
    /// Mount the multi-tenant executor runtime (registry + admin tenant API +
    /// `X-Tenant-ID` / JWT / Host dispatch). Defaults to `false`.
    #[serde(default)]
    pub enabled: bool,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            schema_path: default_schema_path(),
            validate_sql_sources: false,
            mutation_error_shape_check: fraiseql_core::runtime::MutationErrorShapeCheck::Off,
            database_url: default_database_url(),
            bind_addr: default_bind_addr(),
            #[cfg(feature = "arrow")]
            flight_bind_addr: defaults::default_flight_bind_addr(),
            // #953: fail-closed — Upload is off until an operator names tables.
            #[cfg(feature = "arrow")]
            flight_upload_tables: Vec::new(),
            // Fail-closed: `OptimizedView` serves nothing until an operator names views.
            #[cfg(feature = "arrow")]
            flight_views: Vec::new(),
            cors_enabled: true,
            cors_origins: Vec::new(),
            compression_enabled: false,
            enable_http_query: false, // #508: opt-in; POST/GET unchanged
            tracing_enabled: true,
            otlp_endpoint: None,
            otlp_export_timeout_secs: defaults::default_otlp_timeout_secs(),
            tracing_service_name: defaults::default_service_name(),
            apq_enabled: true,
            cache_enabled: true,
            graphql_path: default_graphql_path(),
            health_path: default_health_path(),
            liveness_path: default_liveness_path(),
            readiness_path: default_readiness_path(),
            introspection_path: default_introspection_path(),
            metrics_path: default_metrics_path(),
            metrics_json_path: default_metrics_json_path(),
            playground_path: default_playground_path(),
            playground_enabled: false, // Disabled by default for security
            playground_tool: PlaygroundTool::default(),
            subscription_path: default_subscription_path(),
            subscriptions_enabled: true,
            metrics_enabled: false, // Disabled by default for security
            metrics_token: None,
            admin_api_enabled: false, // Disabled by default for security
            admin_token: None,
            admin_readonly_token: None,
            introspection_enabled: false, // Disabled by default for security
            introspection_require_auth: true, // Require auth when enabled
            metadata_require_auth: None,  // Falls back to introspection_require_auth
            schema_export_require_auth: None, // Falls back to introspection_require_auth
            playground_require_auth: None, // Falls back to introspection_require_auth
            subscription_require_auth: None, // Falls back to introspection_require_auth
            subscription_auth_recheck_secs: default_subscription_auth_recheck_secs(),
            design_api_require_auth: true, // Require auth for design endpoints
            pool_min_size: default_pool_min_size(),
            pool_max_size: default_pool_max_size(),
            pool_timeout_secs: default_pool_timeout(),
            pool_max_streaming_reads: None, // a quarter of pool_max_size (#958)
            vector_hnsw_iterative_scan: HnswIterativeScan::default(),
            vector_ivfflat_iterative_scan: IvfflatIterativeScan::default(),
            vector_hnsw_ef_search: None,
            enable_graphql_incremental: false, // incremental delivery is opt-in (#387)
            graphql_incremental_batch_size: None, // 100 when incremental delivery is enabled
            read_replica_urls: Vec::new(),     // Primary-only by default
            read_replica_pin_after_write_ms: None, // 5000 ms when replicas are set
            read_replica_max_lag_ms: None,     // No lag-based routing by default (#957)
            read_replica_health_probe_interval_ms: None, // 1000 ms when replicas are set

            auth: None, // No auth by default
            auth_hs256: None,
            #[cfg(feature = "auth-saml")]
            saml: None, // No HS256 auth by default
            scim: None,            // Provisioning is opt-in
            admin_sql: None,       // The SQL console is opt-in (#962)
            hmac_secret_env: None, // No HMAC secret → unsigned idempotency token
            tls: None,             // TLS disabled by default
            database_tls: None,    /* Database TLS disabled
                                    * by default */
            require_json_content_type: true, // CSRF protection
            max_request_body_bytes: default_max_request_body_bytes(), // 1 MB
            max_header_count: default_max_header_count(), // 100 headers
            max_header_bytes: default_max_header_bytes(), // 32 KiB
            rate_limiting: None,             // Rate limiting uses defaults
            rate_limit_overrides: RateLimitOverrides::default(), // Set from CLI flags / env vars
            #[cfg(feature = "observers")]
            observers: None, // Observers disabled by default
            #[cfg(feature = "sources")]
            sources: None, /* Source scheduler configured from the compiled
                                              * schema by default */
            pool_tuning: None,       // Pool pressure monitoring disabled by default
            admission_control: None, // Admission control disabled by default
            security_contact: None,  // No security.txt by default
            validation: None,        // Use compiled schema defaults
            shutdown_timeout_secs: default_shutdown_timeout_secs(),
            request_timeout_secs: None,
            max_get_query_bytes: defaults::default_max_get_query_bytes(),
            admin_auth_max_failures: defaults::default_admin_auth_max_failures(),
            storage_token: None,
            usage: None,             // Usage persistence disabled by default
            storage: HashMap::new(), // No storage backends wired by default
            files: HashMap::new(),   // No file-upload routes by default
            #[cfg(feature = "inbound")]
            webhooks: HashMap::new(), // No inbound webhook routes by default
            #[cfg(feature = "inbound-email")]
            mailbox: HashMap::new(), // No connected mailboxes by default
            #[cfg(feature = "inbound-email")]
            send: crate::inbound::email::SendSettings::default(),
            tenancy: TenancyServerConfig::default(),
            #[cfg(feature = "rest")]
            export: crate::routes::rest::export_config::ExportConfig::default(), /* Multi-tenant runtime off by default */
            #[cfg(feature = "auth")]
            identity: None, // Enriched-identity resolution off by default
            #[cfg(feature = "auth")]
            session_state: None, // Session-state subsystem off by default
            async_operations: None, // Async-operations surface off by default
            // Outbound CDC drains only when [cdc_outbound] is configured (#382).
            #[cfg(feature = "cdc-outbound")]
            cdc_outbound: None,
            // No Kafka producer unless [subscription_kafka] asks for one (#1102).
            #[cfg(feature = "subscription-kafka")]
            subscription_kafka: None,
        }
    }
}