-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.rs
More file actions
2014 lines (1833 loc) · 80.7 KB
/
app.rs
File metadata and controls
2014 lines (1833 loc) · 80.7 KB
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
use std::sync::Arc;
#[cfg(feature = "utoipa")]
use axum::Json;
#[cfg(any(feature = "embed-ui", feature = "embed-docs"))]
use axum::response::Response;
#[cfg(any(feature = "sso", feature = "saml"))]
use axum::routing::post;
use axum::{Router, routing::get};
#[cfg(any(feature = "embed-ui", feature = "embed-docs"))]
use axum::{body::Body, response::IntoResponse};
#[cfg(any(feature = "embed-ui", feature = "embed-docs"))]
use http::StatusCode;
use http::header;
use reqwest::Client;
#[cfg(any(feature = "embed-ui", feature = "embed-docs"))]
use rust_embed::Embed;
use tokio_util::task::TaskTracker;
use tower_http::{
limit::RequestBodyLimitLayer,
services::{ServeDir, ServeFile},
set_header::SetResponseHeaderLayer,
trace::TraceLayer,
};
#[cfg(feature = "utoipa")]
use utoipa_scalar::{Scalar, Servable};
#[cfg(feature = "prometheus")]
use crate::observability;
#[cfg(feature = "utoipa")]
use crate::openapi;
use crate::{
auth, authz, cache, catalog, config, db, dlq, events, guardrails,
init::create_provider_instance, jobs, middleware, models, pricing, providers, routes, secrets,
services, usage_buffer,
};
/// Embedded UI assets from ui/dist directory.
/// These are compiled into the binary at build time.
#[cfg(feature = "embed-ui")]
#[derive(Embed)]
#[folder = "ui/dist"]
#[allow_missing = true]
struct UiAssets;
/// Embedded documentation site assets from docs/out directory.
/// These are compiled into the binary at build time.
#[cfg(feature = "embed-docs")]
#[derive(Embed)]
#[folder = "docs/out"]
#[allow_missing = true]
struct DocsAssets;
/// Handler for serving embedded UI assets
#[cfg(feature = "embed-ui")]
async fn serve_embedded_asset(
axum::extract::Path(path): axum::extract::Path<String>,
) -> impl IntoResponse {
serve_embedded_file(&path)
}
/// Handler for serving embedded UI index at root
#[cfg(feature = "embed-ui")]
async fn serve_embedded_index() -> Response {
serve_embedded_file("index.html")
}
#[cfg(feature = "embed-ui")]
fn serve_embedded_file(path: &str) -> Response {
// Try to get the file, or fall back to index.html for SPA routing
let file = UiAssets::get(path).or_else(|| UiAssets::get("index.html"));
match file {
Some(content) => {
// rust-embed with mime-guess feature provides mimetype in metadata
let content_type = content.metadata.mimetype();
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, content_type)
.body(Body::from(content.data.into_owned()))
.unwrap()
}
None => Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::from("Not Found"))
.unwrap(),
}
}
/// Add routes for serving static UI files
fn add_ui_routes(app: Router<AppState>, config: &config::GatewayConfig) -> Router<AppState> {
use config::AssetSource;
let ui_path = config.ui.path.trim_end_matches('/');
match &config.ui.assets.source {
AssetSource::Filesystem { path } => {
let assets_path = std::path::Path::new(path);
let index_file = assets_path.join("index.html");
if !assets_path.exists() {
tracing::warn!(path = %path, "UI assets directory does not exist");
return app;
}
tracing::info!(path = %path, ui_path = %ui_path, "Serving UI from filesystem");
// ServeDir with fallback to index.html for SPA routing
let serve_dir = ServeDir::new(path).fallback(ServeFile::new(&index_file));
// Add cache-control header for assets
let cache_control = config.ui.assets.cache_control.clone();
let serve_dir_with_headers = tower::ServiceBuilder::new()
.layer(SetResponseHeaderLayer::if_not_present(
header::CACHE_CONTROL,
header::HeaderValue::from_str(&cache_control).unwrap_or_else(|_| {
header::HeaderValue::from_static("public, max-age=3600")
}),
))
.service(serve_dir);
if ui_path.is_empty() || ui_path == "/" {
// Serve at root - use fallback_service so other routes take precedence
app.fallback_service(serve_dir_with_headers)
} else {
// Serve at a specific path
app.nest_service(ui_path, serve_dir_with_headers)
}
}
#[cfg(feature = "embed-ui")]
AssetSource::Embedded => {
tracing::info!(ui_path = %ui_path, "Serving UI from embedded assets");
// Create routes for embedded assets (stateless, so use Router<()>)
let embedded_routes: Router<()> = Router::new()
.route("/", get(serve_embedded_index))
.route("/{*path}", get(serve_embedded_asset));
if ui_path.is_empty() || ui_path == "/" {
// Serve at root - use fallback so other routes take precedence
app.fallback_service(embedded_routes)
} else {
// Serve at a specific path - convert to service for nesting
app.nest_service(ui_path, embedded_routes)
}
}
#[cfg(not(feature = "embed-ui"))]
AssetSource::Embedded => {
tracing::warn!(
"Embedded UI assets requested but 'embed-ui' feature is not enabled, skipping"
);
app
}
AssetSource::Cdn { base_url } => {
tracing::info!(base_url = %base_url, "UI assets served from CDN (no server-side serving)");
app
}
}
}
/// Handler for serving embedded docs assets
#[cfg(feature = "embed-docs")]
async fn serve_docs_embedded_asset(
axum::extract::Path(path): axum::extract::Path<String>,
) -> impl IntoResponse {
serve_docs_embedded_file(&path)
}
/// Handler for serving embedded docs index at root
#[cfg(feature = "embed-docs")]
async fn serve_docs_embedded_index() -> Response {
serve_docs_embedded_file("index.html")
}
/// Serve a file from the embedded docs assets.
/// Unlike the SPA UI, docs use static site routing:
/// - Try exact path first
/// - If path ends with /, try path + index.html
/// - If path doesn't end with /, try path/index.html
/// - Return 404 if not found (no fallback to root index.html)
#[cfg(feature = "embed-docs")]
fn serve_docs_embedded_file(path: &str) -> Response {
// Try exact path first
if let Some(content) = DocsAssets::get(path) {
return build_docs_response(content);
}
// For paths ending with /, try index.html
if path.ends_with('/') {
let index_path = format!("{}index.html", path);
if let Some(content) = DocsAssets::get(&index_path) {
return build_docs_response(content);
}
} else {
// For paths without trailing slash, try path/index.html
let index_path = format!("{}/index.html", path);
if let Some(content) = DocsAssets::get(&index_path) {
return build_docs_response(content);
}
}
// Return 404
Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::from("Not Found"))
.unwrap()
}
#[cfg(feature = "embed-docs")]
fn build_docs_response(content: rust_embed::EmbeddedFile) -> Response {
let content_type = content.metadata.mimetype();
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, content_type)
.body(Body::from(content.data.into_owned()))
.unwrap()
}
/// Add routes for serving static documentation files
fn add_docs_routes(app: Router<AppState>, config: &config::GatewayConfig) -> Router<AppState> {
use config::AssetSource;
let docs_path = config.docs.path.trim_end_matches('/');
match &config.docs.assets.source {
AssetSource::Filesystem { path } => {
let assets_path = std::path::Path::new(path);
if !assets_path.exists() {
tracing::warn!(path = %path, "Documentation assets directory does not exist");
return app;
}
tracing::info!(path = %path, docs_path = %docs_path, "Serving documentation from filesystem");
// ServeDir without SPA fallback (static site)
let serve_dir = ServeDir::new(path);
// Add cache-control header for assets
let cache_control = config.docs.assets.cache_control.clone();
let serve_dir_with_headers = tower::ServiceBuilder::new()
.layer(SetResponseHeaderLayer::if_not_present(
header::CACHE_CONTROL,
header::HeaderValue::from_str(&cache_control).unwrap_or_else(|_| {
header::HeaderValue::from_static("public, max-age=3600")
}),
))
.service(serve_dir);
// Docs are always at a specific path (never root)
app.nest_service(docs_path, serve_dir_with_headers)
}
#[cfg(feature = "embed-docs")]
AssetSource::Embedded => {
tracing::info!(docs_path = %docs_path, "Serving documentation from embedded assets");
// Create routes for embedded assets (stateless)
let embedded_routes: Router<()> = Router::new()
.route("/", get(serve_docs_embedded_index))
.route("/{*path}", get(serve_docs_embedded_asset));
// Docs are always at a specific path (never root)
app.nest_service(docs_path, embedded_routes)
}
#[cfg(not(feature = "embed-docs"))]
AssetSource::Embedded => {
tracing::warn!(
"Embedded docs assets requested but 'embed-docs' feature is not enabled, skipping"
);
app
}
AssetSource::Cdn { base_url } => {
tracing::info!(base_url = %base_url, "Documentation assets served from CDN (no server-side serving)");
app
}
}
}
#[derive(Clone)]
pub struct AppState {
pub http_client: Client,
pub config: Arc<config::GatewayConfig>,
pub db: Option<Arc<db::DbPool>>,
pub services: Option<services::Services>,
pub cache: Option<Arc<dyn cache::Cache>>,
pub secrets: Option<Arc<dyn secrets::SecretManager>>,
pub dlq: Option<Arc<dyn dlq::DeadLetterQueue>>,
pub pricing: Arc<pricing::PricingConfig>,
/// Registry of circuit breakers for providers.
/// Shared across requests to persist failure tracking.
pub circuit_breakers: providers::CircuitBreakerRegistry,
/// Registry of provider health check states.
/// Updated by background health checker, queried by admin API.
pub provider_health: jobs::ProviderHealthStateRegistry,
/// Task tracker for background tasks (usage logging, etc.)
/// Ensures all spawned tasks complete during graceful shutdown.
pub task_tracker: TaskTracker,
/// Registry of per-organization OIDC authenticators.
/// Loaded from org_sso_configs table at startup for multi-tenant SSO.
#[cfg(feature = "sso")]
pub oidc_registry: Option<Arc<auth::OidcAuthenticatorRegistry>>,
/// Registry of per-organization SAML authenticators.
/// Loaded from org_sso_configs table at startup for multi-tenant SSO.
#[cfg(feature = "saml")]
pub saml_registry: Option<Arc<auth::SamlAuthenticatorRegistry>>,
/// Registry of per-org gateway JWT validators.
/// Routes incoming JWTs to the correct org-scoped validator by issuer.
pub gateway_jwt_registry: Option<Arc<auth::GatewayJwtRegistry>>,
/// Registry of per-organization RBAC policies.
/// Loaded from org_rbac_policies table at startup for per-org authorization.
pub policy_registry: Option<Arc<authz::PolicyRegistry>>,
/// Async buffer for usage log entries.
/// Batches writes to reduce database pressure.
pub usage_buffer: Option<Arc<usage_buffer::UsageLogBuffer>>,
/// Response cache for chat completions.
/// Caches deterministic responses to reduce latency and costs.
pub response_cache: Option<Arc<cache::ResponseCache>>,
/// Semantic cache for chat completions.
/// Uses vector similarity to find cached responses for semantically similar requests.
pub semantic_cache: Option<Arc<cache::SemanticCache>>,
/// Input guardrails evaluator for pre-request content filtering.
/// Evaluates user input against guardrails policies before sending to the LLM.
pub input_guardrails: Option<Arc<guardrails::InputGuardrails>>,
/// Output guardrails evaluator for post-response content filtering.
/// Evaluates LLM output against guardrails policies before returning to the user.
pub output_guardrails: Option<Arc<guardrails::OutputGuardrails>>,
/// Event bus for broadcasting server events to WebSocket subscribers.
/// Used for real-time monitoring dashboards and push notifications.
pub event_bus: Arc<events::EventBus>,
/// File search service for RAG (Retrieval Augmented Generation).
/// Used by the file_search tool in the Responses API to search vector stores.
pub file_search_service: Option<Arc<services::FileSearchService>>,
/// Document processor for chunking and embedding files added to vector stores.
/// Used by the Vector Store Files API to process uploaded files.
#[cfg(any(
feature = "document-extraction-basic",
feature = "document-extraction-full"
))]
pub document_processor: Option<Arc<services::DocumentProcessor>>,
/// Default user ID for when auth is disabled.
/// Created on startup to allow anonymous users to create conversations.
pub default_user_id: Option<uuid::Uuid>,
/// Default organization ID for when auth is disabled.
/// Created on startup to allow anonymous users to create projects.
pub default_org_id: Option<uuid::Uuid>,
/// Provider metrics service for querying LLM provider statistics.
/// Uses Prometheus when configured, or local /metrics parsing for single-node.
pub provider_metrics: Arc<services::ProviderMetricsService>,
/// Model catalog registry for enriching API responses with model metadata.
/// Loaded from embedded data at startup and optionally synced at runtime.
pub model_catalog: catalog::ModelCatalogRegistry,
}
impl AppState {
pub async fn new(config: config::GatewayConfig) -> Result<Self, Box<dyn std::error::Error>> {
// Build a single shared HTTP client for all outbound provider requests.
// This is efficient because reqwest maintains per-host connection pools internally,
// so each provider (OpenAI, Anthropic, etc.) gets its own pool of connections.
// See HttpClientConfig docs for architecture details and tuning options.
let http_client = config
.server
.http_client
.build_client()
.map_err(|e| format!("Failed to build HTTP client: {}", e))?;
tracing::debug!(
timeout_secs = config.server.http_client.timeout_secs,
connect_timeout_secs = config.server.http_client.connect_timeout_secs,
pool_max_idle_per_host = config.server.http_client.pool_max_idle_per_host,
http2_prior_knowledge = config.server.http_client.http2_prior_knowledge,
"HTTP client configured"
);
// Initialize event bus early so it can be passed to services
// Use channel capacity from WebSocket config
let event_bus = Arc::new(events::EventBus::with_capacity(
config.features.websocket.channel_capacity,
));
// Initialize database and services if configured
#[allow(unreachable_patterns)]
let (db, services) = match &config.database {
config::DatabaseConfig::None => (None, None),
_ => {
let pool = db::DbPool::from_config(&config.database).await?;
// Run migrations on startup
pool.run_migrations().await?;
let db = Arc::new(pool);
// Create file storage backend from config
let file_storage = services::create_file_storage(&config.storage.files, db.clone())
.await
.map_err(|e| format!("Failed to initialize file storage: {}", e))?;
tracing::info!(
backend = %file_storage.backend_name(),
"File storage backend initialized"
);
let max_expr_len = config.auth.rbac.max_expression_length;
let services = services::Services::with_event_bus(
db.clone(),
file_storage,
event_bus.clone(),
max_expr_len,
);
(Some(db), Some(services))
}
};
// Initialize cache if configured
let cache: Option<Arc<dyn cache::Cache>> = match &config.cache {
config::CacheConfig::None => None,
config::CacheConfig::Memory(cfg) => Some(Arc::new(cache::MemoryCache::new(cfg))),
config::CacheConfig::Redis(cfg) => {
#[cfg(feature = "redis")]
{
Some(Arc::new(cache::RedisCache::from_config(cfg).await?))
}
#[cfg(not(feature = "redis"))]
{
let _ = cfg;
return Err("Redis cache configured but 'redis' feature not enabled. \
Rebuild with: cargo build --features redis"
.into());
}
}
};
// Initialize secrets manager based on configuration
let secrets: Arc<dyn secrets::SecretManager> = match &config.secrets {
config::SecretsConfig::None => {
// Default behavior: use env vars for local mode, memory for db mode
if db.is_some() {
tracing::warn!(
"No secrets manager configured. Using in-memory storage which does NOT \
persist across restarts. Per-org SSO will fail after restart. \
Configure [secrets] in hadrian.toml for production use."
);
Arc::new(secrets::MemorySecretManager::new())
} else {
Arc::new(secrets::EnvSecretManager)
}
}
config::SecretsConfig::Env => Arc::new(secrets::EnvSecretManager),
#[cfg(feature = "vault")]
config::SecretsConfig::Vault(vault_config) => {
use config::VaultAuth;
use secrets::SecretManager;
// Build VaultConfig based on auth method
let vault_cfg = match &vault_config.auth {
VaultAuth::Token { token } => {
secrets::VaultConfig::new(&vault_config.address, token)
}
VaultAuth::AppRole {
role_id,
secret_id,
auth_mount,
} => secrets::VaultConfig::with_approle(
&vault_config.address,
role_id,
secret_id,
)
.with_auth_mount(auth_mount),
VaultAuth::Kubernetes {
role,
token_path,
auth_mount,
} => {
// Read the ServiceAccount token from the file
let jwt = std::fs::read_to_string(token_path).map_err(|e| {
format!(
"Failed to read Kubernetes ServiceAccount token from '{}': {}",
token_path, e
)
})?;
secrets::VaultConfig::with_kubernetes(
&vault_config.address,
role,
jwt.trim(),
)
.with_auth_mount(auth_mount)
}
}
.with_mount(&vault_config.mount)
.with_path_prefix(&vault_config.path_prefix);
let manager = secrets::VaultSecretManager::new(vault_cfg)
.await
.map_err(|e| format!("Failed to create Vault client: {}", e))?;
// Verify connectivity on startup
manager
.health_check()
.await
.map_err(|e| format!("Vault health check failed: {}", e))?;
let auth_method = match &vault_config.auth {
VaultAuth::Token { .. } => "token",
VaultAuth::AppRole { .. } => "approle",
VaultAuth::Kubernetes { .. } => "kubernetes",
};
tracing::info!(
address = %vault_config.address,
mount = %vault_config.mount,
path_prefix = %vault_config.path_prefix,
auth_method = %auth_method,
"Connected to Vault secrets manager"
);
Arc::new(manager)
}
#[cfg(feature = "secrets-aws")]
config::SecretsConfig::Aws(aws_config) => {
use secrets::SecretManager;
let mut cfg = match &aws_config.region {
Some(region) => secrets::AwsSecretsManagerConfig::new(region),
None => secrets::AwsSecretsManagerConfig::from_env(),
}
.with_prefix(&aws_config.prefix);
if let Some(endpoint_url) = &aws_config.endpoint_url {
cfg = cfg.with_endpoint_url(endpoint_url);
}
let manager = secrets::AwsSecretsManager::new(cfg)
.await
.map_err(|e| format!("Failed to create AWS Secrets Manager client: {}", e))?;
// Verify connectivity on startup
manager
.health_check()
.await
.map_err(|e| format!("AWS Secrets Manager health check failed: {}", e))?;
tracing::info!(
region = ?aws_config.region,
prefix = %aws_config.prefix,
"Connected to AWS Secrets Manager"
);
Arc::new(manager)
}
#[cfg(feature = "secrets-azure")]
config::SecretsConfig::Azure(azure_config) => {
use secrets::SecretManager;
let cfg = secrets::AzureKeyVaultConfig::new(&azure_config.vault_url)
.with_prefix(&azure_config.prefix);
let manager = secrets::AzureKeyVaultManager::new(cfg)
.await
.map_err(|e| format!("Failed to create Azure Key Vault client: {}", e))?;
// Verify connectivity on startup
manager
.health_check()
.await
.map_err(|e| format!("Azure Key Vault health check failed: {}", e))?;
tracing::info!(
vault_url = %azure_config.vault_url,
prefix = %azure_config.prefix,
"Connected to Azure Key Vault"
);
Arc::new(manager)
}
#[cfg(feature = "secrets-gcp")]
config::SecretsConfig::Gcp(gcp_config) => {
use secrets::SecretManager;
let cfg = secrets::GcpSecretManagerConfig::new(&gcp_config.project_id)
.with_prefix(&gcp_config.prefix);
let manager = secrets::GcpSecretManager::new(cfg)
.await
.map_err(|e| format!("Failed to create GCP Secret Manager client: {}", e))?;
// Verify connectivity on startup
manager
.health_check()
.await
.map_err(|e| format!("GCP Secret Manager health check failed: {}", e))?;
tracing::info!(
project_id = %gcp_config.project_id,
prefix = %gcp_config.prefix,
"Connected to GCP Secret Manager"
);
Arc::new(manager)
}
};
// Initialize model catalog registry from embedded data (if available)
let model_catalog = catalog::ModelCatalogRegistry::new();
match catalog::embedded_catalog() {
Some(json) => match model_catalog.load_from_json(&json) {
Ok(()) => {
tracing::info!(
model_count = model_catalog.model_count(),
"Loaded embedded model catalog"
);
}
Err(e) => {
tracing::error!(error = %e, "Failed to parse embedded model catalog");
}
},
None => {
tracing::info!(
"No embedded model catalog available; \
enable the 'embed-catalog' feature or configure runtime sync"
);
}
}
// Initialize pricing from defaults + config + provider configs + catalog
let pricing = Arc::new(pricing::PricingConfig::from_config_with_catalog(
&config.pricing,
&config.providers,
Some(&model_catalog),
));
// Initialize dead-letter queue if configured
let dlq = dlq::create_dlq(&config.observability.dead_letter_queue, db.as_ref())
.await
.map_err(|e| format!("Failed to initialize DLQ: {}", e))?;
if dlq.is_some() {
tracing::info!("Dead-letter queue initialized");
}
// Initialize circuit breaker registry from provider config
let circuit_breakers = providers::CircuitBreakerRegistry::from_config_with_event_bus(
&config.providers,
event_bus.clone(),
);
// Get session config from UI auth config
// Note: Global OIDC config has been removed. Session config is used for per-org SSO.
#[cfg(feature = "sso")]
let session_config = config.auth.session.clone().unwrap_or_default();
// Initialize per-org OIDC authenticator registry from database
// This replaces the global OIDC authenticator
#[cfg(feature = "sso")]
let oidc_registry = if let Some(ref svc) = services {
// Create session store for org authenticators (shared across all orgs)
let enhanced = session_config.enhanced.enabled;
let session_store = auth::create_session_store_with_enhanced(cache.clone(), enhanced);
// Get default session config
let default_session_config = session_config.clone();
// No default redirect URI - per-org SSO configs must specify their own
let default_redirect_uri: Option<String> = None;
match auth::OidcAuthenticatorRegistry::initialize_from_db(
&svc.org_sso_configs,
secrets.as_ref(),
session_store.clone(),
default_session_config.clone(),
default_redirect_uri.clone(),
)
.await
{
Ok(registry) => {
let count = registry.len().await;
if count > 0 {
tracing::info!(count, "Per-org SSO authenticator registry initialized");
} else {
tracing::debug!("Per-org SSO registry initialized (empty, will lazy load)");
}
// Always create the registry to support lazy loading from database
Some(Arc::new(registry))
}
Err(e) => {
// Create an empty registry instead of None - this allows lazy loading
// to work when requests come in, even if startup initialization failed
tracing::warn!(
error = %e,
"Failed to initialize org SSO registry from database, \
creating empty registry for lazy loading"
);
let empty_registry = auth::OidcAuthenticatorRegistry::new(
session_store,
default_session_config,
default_redirect_uri,
);
Some(Arc::new(empty_registry))
}
}
} else {
None
};
// Initialize per-org SAML authenticator registry from database
#[cfg(feature = "saml")]
let saml_registry = if let Some(ref svc) = services {
// Create session store for org authenticators (shared across all orgs)
let enhanced = session_config.enhanced.enabled;
let session_store = auth::create_session_store_with_enhanced(cache.clone(), enhanced);
// Get default session config
let default_session_config = session_config.clone();
// Build default ACS URL from server config
let default_acs_url = format!(
"{}://{}:{}/auth/saml/acs",
if config.server.tls.is_some() {
"https"
} else {
"http"
},
config.server.host,
config.server.port
);
match auth::SamlAuthenticatorRegistry::initialize_from_db(
&svc.org_sso_configs,
secrets.as_ref(),
session_store,
default_session_config,
default_acs_url,
)
.await
{
Ok(registry) if !registry.is_empty().await => {
tracing::info!(
count = registry.len().await,
"Per-org SAML authenticator registry initialized"
);
Some(Arc::new(registry))
}
Ok(_) => {
tracing::debug!("No SAML org SSO configs found, registry empty");
None
}
Err(e) => {
tracing::warn!(error = %e, "Failed to initialize SAML org SSO registry");
None
}
}
} else {
None
};
// Initialize per-org gateway JWT registry for multi-tenant JWT auth on /v1/*.
// Validators are pre-loaded in a background task so server startup isn't
// blocked by N sequential OIDC discovery HTTP requests.
let gateway_jwt_registry = if db.is_some() {
Some(Arc::new(auth::GatewayJwtRegistry::new()))
} else {
None
};
// Initialize per-org RBAC policy registry from database
let policy_registry = if let (Some(svc), Some(db_pool)) = (&services, &db)
&& config.auth.rbac.enabled
{
let engine = Arc::new(
authz::AuthzEngine::new(config.auth.rbac.clone())
.expect("Failed to create AuthzEngine for policy registry"),
);
// Get config values for the registry
let version_check_ttl =
std::time::Duration::from_millis(config.auth.rbac.policy_cache_ttl_ms);
let max_cached_orgs = config.auth.rbac.max_cached_orgs;
let eviction_batch_size = config.auth.rbac.policy_eviction_batch_size;
if config.auth.rbac.lazy_load_policies {
// Lazy loading: policies loaded on-demand when org is first accessed
let registry = authz::PolicyRegistry::new_lazy(
engine,
config.auth.rbac.default_effect,
cache.clone(),
db_pool.org_rbac_policies(),
version_check_ttl,
max_cached_orgs,
eviction_batch_size,
);
tracing::info!(
max_cached_orgs,
eviction_batch_size,
"RBAC policy registry initialized (lazy loading)"
);
Some(Arc::new(registry))
} else {
// Eager loading: load all policies at startup
match authz::PolicyRegistry::initialize_from_db(
&svc.org_rbac_policies,
engine,
config.auth.rbac.default_effect,
cache.clone(),
db_pool.org_rbac_policies(),
version_check_ttl,
max_cached_orgs,
eviction_batch_size,
)
.await
{
Ok(registry) => {
let org_count = registry.org_count().await;
let policy_count = registry.policy_count().await;
if org_count > 0 {
tracing::info!(
org_count,
policy_count,
max_cached_orgs,
"RBAC policy registry initialized (eager loading)"
);
} else {
tracing::debug!("RBAC policy registry initialized (no org policies)");
}
Some(Arc::new(registry))
}
Err(e) => {
tracing::warn!(error = %e, "Failed to initialize RBAC policy registry");
None
}
}
}
} else {
None
};
// Initialize usage log buffer with configured buffer settings and EventBus
let usage_buffer = {
let buffer_config =
usage_buffer::UsageBufferConfig::from(&config.observability.usage.buffer);
let buffer = Arc::new(usage_buffer::UsageLogBuffer::with_event_bus(
buffer_config,
event_bus.clone(),
));
Some(buffer)
};
// Initialize response cache if configured and cache is available
let response_cache = match (&config.features.response_caching, &cache) {
(Some(caching_config), Some(cache_instance)) if caching_config.enabled => {
tracing::info!(
ttl_secs = caching_config.ttl_secs,
only_deterministic = caching_config.only_deterministic,
max_size_bytes = caching_config.max_size_bytes,
"Response caching enabled"
);
Some(Arc::new(cache::ResponseCache::new(
cache_instance.clone(),
caching_config.clone(),
)))
}
(Some(caching_config), None) if caching_config.enabled => {
tracing::warn!(
"Response caching is enabled but no cache backend is configured. \
Add [cache] configuration to enable response caching."
);
None
}
_ => None,
};
// Create the task tracker for background tasks
let task_tracker = TaskTracker::new();
// Initialize semantic cache if configured
let semantic_cache = Self::init_semantic_cache(
&config,
cache.as_ref(),
db.as_ref(),
&circuit_breakers,
http_client.clone(),
&task_tracker,
)
.await;
// Initialize input guardrails if configured
let input_guardrails = match &config.features.guardrails {
Some(guardrails_config) => {
match guardrails::InputGuardrails::from_config(guardrails_config, &http_client) {
Ok(Some(evaluator)) => {
tracing::info!(
provider = %evaluator.provider_name(),
"Input guardrails enabled"
);
Some(Arc::new(evaluator))
}
Ok(None) => {
tracing::debug!("Input guardrails disabled or not configured");
None
}
Err(e) => {
tracing::warn!(error = %e, "Failed to initialize input guardrails");
None
}
}
}
None => None,
};
// Initialize output guardrails if configured
let output_guardrails = match &config.features.guardrails {
Some(guardrails_config) => {
match guardrails::OutputGuardrails::from_config(guardrails_config, &http_client) {
Ok(Some(evaluator)) => {
tracing::info!(
provider = %evaluator.provider_name(),
"Output guardrails enabled"
);
Some(Arc::new(evaluator))
}
Ok(None) => {
tracing::debug!("Output guardrails disabled or not configured");
None
}
Err(e) => {
tracing::warn!(error = %e, "Failed to initialize output guardrails");
None
}
}
}
None => None,
};
// Initialize file search service if configured
// This requires both semantic cache components (embedding service + vector store)
// and file_search configuration
let file_search_service = Self::init_file_search_service(
&config,
db.as_ref(),
&circuit_breakers,
http_client.clone(),
)
.await;
// Initialize document processor for RAG file processing
// This reuses the embedding service and vector store from file_search_service
#[cfg(any(
feature = "document-extraction-basic",
feature = "document-extraction-full"
))]
let document_processor = Self::init_document_processor(
&config,
db.as_ref(),
services.as_ref(),
file_search_service.as_ref(),
);
// Create default user and organization when auth is disabled (for anonymous access)
let (default_user_id, default_org_id) = if !config.auth.is_auth_enabled() {
if let Some(ref svc) = services {
let user_id = match Self::ensure_default_user(svc).await {
Ok(id) => {
tracing::info!(user_id = %id, "Default anonymous user available");
Some(id)
}
Err(e) => {
tracing::warn!(error = %e, "Failed to create default user");
None
}
};
let org_id = match Self::ensure_default_org(svc).await {
Ok(id) => {
tracing::info!(org_id = %id, "Default local organization available");
Some(id)
}
Err(e) => {
tracing::warn!(error = %e, "Failed to create default organization");
None
}
};
// Add user to org if both exist
if let (Some(uid), Some(oid)) = (user_id, org_id)
&& let Err(e) = Self::ensure_default_org_membership(svc, uid, oid).await
{
tracing::warn!(error = %e, "Failed to add user to default organization");
}
(user_id, org_id)
} else {
(None, None)
}
} else {
(None, None)
};
// Initialize provider metrics service
// Uses Prometheus API when prometheus_query_url is configured, otherwise local /metrics
let provider_metrics = {
#[cfg(feature = "prometheus")]
{
if let Some(ref prometheus_url) = config.observability.metrics.prometheus_query_url
{