-
Notifications
You must be signed in to change notification settings - Fork 949
Expand file tree
/
Copy pathconfig.go
More file actions
3961 lines (3584 loc) · 140 KB
/
Copy pathconfig.go
File metadata and controls
3961 lines (3584 loc) · 140 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
// Package lib provides core functionality for the Bifrost HTTP service,
// including context propagation, header management, and integration with monitoring systems.
package lib
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/google/uuid"
bifrost "github.com/maximhq/bifrost/core"
"github.com/maximhq/bifrost/core/schemas"
"github.com/maximhq/bifrost/framework"
"github.com/maximhq/bifrost/framework/configstore"
configstoreTables "github.com/maximhq/bifrost/framework/configstore/tables"
"github.com/maximhq/bifrost/framework/encrypt"
"github.com/maximhq/bifrost/framework/logstore"
"github.com/maximhq/bifrost/framework/modelcatalog"
"github.com/maximhq/bifrost/framework/vectorstore"
"github.com/maximhq/bifrost/plugins/semanticcache"
"gorm.io/gorm"
)
// HandlerStore provides access to runtime configuration values for handlers.
// This interface allows handlers to access only the configuration they need
// without depending on the entire ConfigStore, improving testability and decoupling.
type HandlerStore interface {
// ShouldAllowDirectKeys returns whether direct API keys in headers are allowed
ShouldAllowDirectKeys() bool
// GetHeaderFilterConfig returns the global header filter configuration
GetHeaderFilterConfig() *configstoreTables.GlobalHeaderFilterConfig
}
// Retry backoff constants for validation
const (
MinRetryBackoff = 100 * time.Millisecond // Minimum retry backoff: 100ms
MaxRetryBackoff = 1000000 * time.Millisecond // Maximum retry backoff: 1000000ms (1000 seconds)
)
// getWeight safely dereferences a *float64 weight pointer, returning 1.0 as default if nil.
// This allows distinguishing between "not set" (nil -> 1.0) and "explicitly set to 0" (0.0).
func getWeight(w *float64) float64 {
if w == nil {
return 1.0
}
return *w
}
// ConfigData represents the configuration data for the Bifrost HTTP transport.
// It contains the client configuration, provider configurations, MCP configuration,
// vector store configuration, config store configuration, and logs store configuration.
type ConfigData struct {
Client *configstore.ClientConfig `json:"client"`
EncryptionKey string `json:"encryption_key"`
AuthConfig *configstore.AuthConfig `json:"auth_config,omitempty"`
Providers map[string]configstore.ProviderConfig `json:"providers"`
FrameworkConfig *framework.FrameworkConfig `json:"framework,omitempty"`
MCP *schemas.MCPConfig `json:"mcp,omitempty"`
Governance *configstore.GovernanceConfig `json:"governance,omitempty"`
VectorStoreConfig *vectorstore.Config `json:"vector_store,omitempty"`
ConfigStoreConfig *configstore.Config `json:"config_store,omitempty"`
LogsStoreConfig *logstore.Config `json:"logs_store,omitempty"`
Plugins []*schemas.PluginConfig `json:"plugins,omitempty"`
}
// UnmarshalJSON unmarshals the ConfigData from JSON using internal unmarshallers
// for VectorStoreConfig, ConfigStoreConfig, and LogsStoreConfig to ensure proper
// type safety and configuration parsing.
func (cd *ConfigData) UnmarshalJSON(data []byte) error {
// First, unmarshal into a temporary struct to get all fields except the complex configs
type TempConfigData struct {
FrameworkConfig json.RawMessage `json:"framework,omitempty"`
Client *configstore.ClientConfig `json:"client"`
EncryptionKey string `json:"encryption_key"`
AuthConfig *configstore.AuthConfig `json:"auth_config,omitempty"`
Providers map[string]configstore.ProviderConfig `json:"providers"`
MCP *schemas.MCPConfig `json:"mcp,omitempty"`
Governance *configstore.GovernanceConfig `json:"governance,omitempty"`
VectorStoreConfig json.RawMessage `json:"vector_store,omitempty"`
ConfigStoreConfig json.RawMessage `json:"config_store,omitempty"`
LogsStoreConfig json.RawMessage `json:"logs_store,omitempty"`
Plugins []*schemas.PluginConfig `json:"plugins,omitempty"`
}
var temp TempConfigData
if err := json.Unmarshal(data, &temp); err != nil {
return fmt.Errorf("failed to unmarshal config data: %w", err)
}
// Set simple fields
cd.Client = temp.Client
cd.EncryptionKey = temp.EncryptionKey
cd.AuthConfig = temp.AuthConfig
cd.Providers = temp.Providers
cd.MCP = temp.MCP
cd.Governance = temp.Governance
cd.Plugins = temp.Plugins
// Initialize providers map if nil
if cd.Providers == nil {
cd.Providers = make(map[string]configstore.ProviderConfig)
}
// Extract provider configs from virtual keys.
// Keys can be either full definitions (with value) or references (name only).
// References are resolved by looking up the key by name from the providers section.
// NOTE: Only FULL key definitions (with Value) should be added to the provider.
// Reference lookups are for virtual key resolution only - they should NOT be added
// back to the provider since they already exist there.
if cd.Governance != nil && cd.Governance.VirtualKeys != nil {
for _, virtualKey := range cd.Governance.VirtualKeys {
if virtualKey.ProviderConfigs != nil {
for _, providerConfig := range virtualKey.ProviderConfigs {
// Only collect keys with Value (full definitions) to add to provider
var keysToAddToProvider []schemas.Key
for _, tableKey := range providerConfig.Keys {
if tableKey.Value != "" {
// Full key definition - add to provider
keysToAddToProvider = append(keysToAddToProvider, schemas.Key{
ID: tableKey.KeyID,
Name: tableKey.Name,
Value: tableKey.Value,
Models: tableKey.Models,
Weight: getWeight(tableKey.Weight),
Enabled: tableKey.Enabled,
UseForBatchAPI: tableKey.UseForBatchAPI,
AzureKeyConfig: tableKey.AzureKeyConfig,
VertexKeyConfig: tableKey.VertexKeyConfig,
BedrockKeyConfig: tableKey.BedrockKeyConfig,
})
}
// Reference lookups (no Value) are NOT added to provider - they already exist there
}
// Merge or create provider entry - only for full key definitions
if len(keysToAddToProvider) > 0 {
if existing, ok := cd.Providers[providerConfig.Provider]; ok {
existing.Keys = append(existing.Keys, keysToAddToProvider...)
cd.Providers[providerConfig.Provider] = existing
} else {
cd.Providers[providerConfig.Provider] = configstore.ProviderConfig{
Keys: keysToAddToProvider,
}
}
}
}
}
}
}
// Parse VectorStoreConfig using its internal unmarshaler
if len(temp.VectorStoreConfig) > 0 {
var vectorStoreConfig vectorstore.Config
if err := json.Unmarshal(temp.VectorStoreConfig, &vectorStoreConfig); err != nil {
return fmt.Errorf("failed to unmarshal vector store config: %w", err)
}
cd.VectorStoreConfig = &vectorStoreConfig
}
// Parse FrameworkConfig using its internal unmarshaler
if len(temp.FrameworkConfig) > 0 {
var frameworkConfig framework.FrameworkConfig
if err := json.Unmarshal(temp.FrameworkConfig, &frameworkConfig); err != nil {
return fmt.Errorf("failed to unmarshal framework config: %w", err)
}
cd.FrameworkConfig = &frameworkConfig
}
// Parse ConfigStoreConfig using its internal unmarshaler
if len(temp.ConfigStoreConfig) > 0 {
var configStoreConfig configstore.Config
if err := json.Unmarshal(temp.ConfigStoreConfig, &configStoreConfig); err != nil {
return fmt.Errorf("failed to unmarshal config store config: %w", err)
}
cd.ConfigStoreConfig = &configStoreConfig
}
// Parse LogsStoreConfig using its internal unmarshaler
if len(temp.LogsStoreConfig) > 0 {
var logsStoreConfig logstore.Config
if err := json.Unmarshal(temp.LogsStoreConfig, &logsStoreConfig); err != nil {
return fmt.Errorf("failed to unmarshal logs store config: %w", err)
}
cd.LogsStoreConfig = &logsStoreConfig
}
return nil
}
// Config represents a high-performance in-memory configuration store for Bifrost.
// It provides thread-safe access to provider configurations with database persistence.
//
// Features:
// - Pure in-memory storage for ultra-fast access
// - Environment variable processing for API keys and key-level configurations
// - Thread-safe operations with read-write mutexes
// - Real-time configuration updates via HTTP API
// - Automatic database persistence for all changes
// - Support for provider-specific key configurations (Azure, Vertex, Bedrock)
// - Lock-free plugin reads via atomic.Pointer for minimal hot-path latency
type Config struct {
Mu sync.RWMutex // Exported for direct access from handlers (governance plugin)
muMCP sync.RWMutex
client *bifrost.Bifrost
configPath string
// Stores
ConfigStore configstore.ConfigStore
VectorStore vectorstore.VectorStore
LogsStore logstore.LogStore
// In-memory storage
ClientConfig configstore.ClientConfig
Providers map[schemas.ModelProvider]configstore.ProviderConfig
MCPConfig *schemas.MCPConfig
GovernanceConfig *configstore.GovernanceConfig
FrameworkConfig *framework.FrameworkConfig
ProxyConfig *configstoreTables.GlobalProxyConfig
// Track which keys come from environment variables
EnvKeys map[string][]configstore.EnvKeyInfo
// Plugin configs - atomic for lock-free reads with CAS updates
Plugins atomic.Pointer[[]schemas.Plugin]
// Plugin configs from config file/database
PluginConfigs []*schemas.PluginConfig
// Pricing manager
PricingManager *modelcatalog.ModelCatalog
}
var DefaultClientConfig = configstore.ClientConfig{
DropExcessRequests: false,
PrometheusLabels: []string{},
InitialPoolSize: schemas.DefaultInitialPoolSize,
EnableLogging: true,
DisableContentLogging: false,
EnableGovernance: true,
EnforceGovernanceHeader: false,
AllowDirectKeys: false,
AllowedOrigins: []string{"*"},
MaxRequestBodySizeMB: 100,
EnableLiteLLMFallbacks: false,
}
// initializeEncryption initializes the encryption key
func (c *Config) initializeEncryption(configKey string) error {
encryptionKey := ""
if configKey != "" {
if strings.HasPrefix(configKey, "env.") {
var err error
if encryptionKey, _, err = c.processEnvValue(configKey); err != nil {
return fmt.Errorf("failed to process encryption key: %w", err)
}
} else {
logger.Warn("encryption_key should reference an environment variable (env.VAR_NAME) rather than storing the key directly in the config file")
encryptionKey = configKey
}
}
if encryptionKey == "" {
if os.Getenv("BIFROST_ENCRYPTION_KEY") != "" {
encryptionKey = os.Getenv("BIFROST_ENCRYPTION_KEY")
}
}
encrypt.Init(encryptionKey, logger)
return nil
}
// LoadConfig loads initial configuration from a JSON config file into memory
// with full preprocessing including environment variable resolution and key config parsing.
// All processing is done upfront to ensure zero latency when retrieving data.
//
// If the config file doesn't exist, the system starts with default configuration
// and users can add providers dynamically via the HTTP API.
//
// This method handles:
// - JSON config file parsing
// - Environment variable substitution for API keys (env.VARIABLE_NAME)
// - Key-level config processing for Azure, Vertex, and Bedrock (Endpoint, APIVersion, ProjectID, Region, AuthCredentials)
// - Case conversion for provider names (e.g., "OpenAI" -> "openai")
// - In-memory storage for ultra-fast access during request processing
// - Graceful handling of missing config files
func LoadConfig(ctx context.Context, configDirPath string) (*Config, error) {
// Initialize separate database connections for optimal performance at scale
configFilePath := filepath.Join(configDirPath, "config.json")
configDBPath := filepath.Join(configDirPath, "config.db")
logsDBPath := filepath.Join(configDirPath, "logs.db")
// Initialize config
config := &Config{
configPath: configFilePath,
EnvKeys: make(map[string][]configstore.EnvKeyInfo),
Providers: make(map[schemas.ModelProvider]configstore.ProviderConfig),
Plugins: atomic.Pointer[[]schemas.Plugin]{},
}
// Getting absolute path for config file
absConfigFilePath, err := filepath.Abs(configFilePath)
if err != nil {
return nil, fmt.Errorf("failed to get absolute path for config file: %w", err)
}
// Check if config file exists
data, err := os.ReadFile(configFilePath)
if err != nil {
// If config file doesn't exist, we will directly use the config store (create one if it doesn't exist)
if os.IsNotExist(err) {
logger.Info("config file not found at path: %s, initializing with default values", absConfigFilePath)
return loadConfigFromDefaults(ctx, config, configDBPath, logsDBPath)
}
return nil, fmt.Errorf("failed to read config file: %w", err)
}
// If file exists, we will do a quick check if that file includes "$schema":"https://www.getbifrost.ai/schema", If not we will show a warning in a box - yellow color
var schema map[string]interface{}
if err := json.Unmarshal(data, &schema); err != nil {
return nil, fmt.Errorf("failed to unmarshal schema: %w", err)
}
if schema["$schema"] != "https://www.getbifrost.ai/schema" {
// Print warning in yellow ASCII box
yellowColor := "\033[33m"
resetColor := "\033[0m"
message := fmt.Sprintf("config file %s does not include \"$schema\":\"https://www.getbifrost.ai/schema\". Use our official schema file to avoid unexpected behavior.", absConfigFilePath)
// Fixed box width, content width is box - 4 (for "║ " and " ║")
boxWidth := 100
contentWidth := boxWidth - 4
// Word wrap the message into lines
words := strings.Fields(message)
var lines []string
currentLine := ""
for _, word := range words {
if currentLine == "" {
currentLine = word
} else if len(currentLine)+1+len(word) <= contentWidth {
currentLine += " " + word
} else {
lines = append(lines, currentLine)
currentLine = word
}
}
if currentLine != "" {
lines = append(lines, currentLine)
}
// Print top border
fmt.Printf("%s╔%s╗%s\n", yellowColor, strings.Repeat("═", boxWidth-2), resetColor)
// Print each line with proper padding
for _, l := range lines {
padding := contentWidth - len(l)
if padding < 0 {
padding = 0
}
fmt.Printf("%s║ %s%s ║%s\n", yellowColor, l, strings.Repeat(" ", padding), resetColor)
}
// Print bottom border
fmt.Printf("%s╚%s╝%s\n", yellowColor, strings.Repeat("═", boxWidth-2), resetColor)
fmt.Println("")
logger.Warn("config file %s does not include \"$schema\":\"https://www.getbifrost.ai/schema\". Use our official schema file to avoid unexpected behavior.", absConfigFilePath)
}
// If config file exists, we will use it to bootstrap config tables
logger.Info("loading configuration from: %s", absConfigFilePath)
return loadConfigFromFile(ctx, config, data)
}
// loadConfigFromFile initializes configuration from a JSON config file.
// It merges config file data with existing database config, with store taking priority.
func loadConfigFromFile(ctx context.Context, config *Config, data []byte) (*Config, error) {
var configData ConfigData
if err := json.Unmarshal(data, &configData); err != nil {
return nil, fmt.Errorf("failed to unmarshal config: %w", err)
}
var err error
// Initialize stores from config file
if err = initStoresFromFile(ctx, config, &configData); err != nil {
return nil, err
}
// From now on, config store gets priority if enabled and we find data.
// If we don't find any data in the store, then we resort to config file.
// NOTE: We follow a standard practice: store -> config file -> update store.
// Load client config
loadClientConfigFromFile(ctx, config, &configData)
// Load providers config with hash reconciliation
if err = loadProvidersFromFile(ctx, config, &configData); err != nil {
return nil, err
}
// Load MCP config
loadMCPConfigFromFile(ctx, config, &configData)
// Load governance config
loadGovernanceConfigFromFile(ctx, config, &configData)
// Load auth config
loadAuthConfigFromFile(ctx, config, &configData)
// Load plugins
loadPluginsFromFile(ctx, config, &configData)
// Load env keys
loadEnvKeysFromFile(ctx, config)
// Initialize framework config and pricing manager
initFrameworkConfigFromFile(ctx, config, &configData)
// Initialize encryption
if err = initEncryptionFromFile(config, &configData); err != nil {
return nil, err
}
return config, nil
}
// initStoresFromFile initializes config, logs, and vector stores from config file
func initStoresFromFile(ctx context.Context, config *Config, configData *ConfigData) error {
var err error
// Initialize config store
if configData.ConfigStoreConfig != nil && configData.ConfigStoreConfig.Enabled {
config.ConfigStore, err = configstore.NewConfigStore(ctx, configData.ConfigStoreConfig, logger)
if err != nil {
return err
}
logger.Info("config store initialized")
// Clear restart required flag on server startup
if err = config.ConfigStore.ClearRestartRequiredConfig(ctx); err != nil {
logger.Warn("failed to clear restart required config: %v", err)
}
}
// Initialize log store
if configData.LogsStoreConfig != nil && configData.LogsStoreConfig.Enabled {
config.LogsStore, err = logstore.NewLogStore(ctx, configData.LogsStoreConfig, logger)
if err != nil {
return err
}
logger.Info("logs store initialized")
}
// Initialize vector store
if configData.VectorStoreConfig != nil && configData.VectorStoreConfig.Enabled {
logger.Info("connecting to vectorstore")
config.VectorStore, err = vectorstore.NewVectorStore(ctx, configData.VectorStoreConfig, logger)
if err != nil {
logger.Fatal("failed to connect to vector store: %v", err)
}
if config.ConfigStore != nil {
if err = config.ConfigStore.UpdateVectorStoreConfig(ctx, configData.VectorStoreConfig); err != nil {
logger.Warn("failed to update vector store config: %v", err)
}
}
}
return nil
}
// loadClientConfigFromFile loads and merges client config from file with store
func loadClientConfigFromFile(ctx context.Context, config *Config, configData *ConfigData) {
var clientConfig *configstore.ClientConfig
var err error
if config.ConfigStore != nil {
clientConfig, err = config.ConfigStore.GetClientConfig(ctx)
if err != nil {
logger.Warn("failed to get client config from store: %v", err)
}
}
if clientConfig != nil {
config.ClientConfig = *clientConfig
// For backward compatibility, handle cases where max request body size is not set
if config.ClientConfig.MaxRequestBodySizeMB == 0 {
config.ClientConfig.MaxRequestBodySizeMB = DefaultClientConfig.MaxRequestBodySizeMB
}
// Merge with config file if present
if configData.Client != nil {
mergeClientConfig(&config.ClientConfig, configData.Client)
// Update store with merged config
if config.ConfigStore != nil {
logger.Debug("updating merged client config in store")
if err = config.ConfigStore.UpdateClientConfig(ctx, &config.ClientConfig); err != nil {
logger.Warn("failed to update merged client config: %v", err)
}
}
}
} else {
logger.Debug("client config not found in store, using config file")
if configData.Client != nil {
config.ClientConfig = *configData.Client
if config.ClientConfig.MaxRequestBodySizeMB == 0 {
config.ClientConfig.MaxRequestBodySizeMB = DefaultClientConfig.MaxRequestBodySizeMB
}
} else {
config.ClientConfig = DefaultClientConfig
}
if config.ConfigStore != nil {
logger.Debug("updating client config in store")
if err = config.ConfigStore.UpdateClientConfig(ctx, &config.ClientConfig); err != nil {
logger.Warn("failed to update client config: %v", err)
}
}
}
}
// mergeClientConfig merges config file values into existing client config
// DB takes priority, but fill in empty/zero values from config file
func mergeClientConfig(dbConfig *configstore.ClientConfig, fileConfig *configstore.ClientConfig) {
logger.Debug("merging client config from config file with store")
if dbConfig.InitialPoolSize == 0 && fileConfig.InitialPoolSize != 0 {
dbConfig.InitialPoolSize = fileConfig.InitialPoolSize
}
if len(dbConfig.PrometheusLabels) == 0 && len(fileConfig.PrometheusLabels) > 0 {
dbConfig.PrometheusLabels = fileConfig.PrometheusLabels
}
if len(dbConfig.AllowedOrigins) == 0 && len(fileConfig.AllowedOrigins) > 0 {
dbConfig.AllowedOrigins = fileConfig.AllowedOrigins
}
if dbConfig.MaxRequestBodySizeMB == 0 && fileConfig.MaxRequestBodySizeMB != 0 {
dbConfig.MaxRequestBodySizeMB = fileConfig.MaxRequestBodySizeMB
}
// Boolean fields: only override if DB has false and config file has true
if !dbConfig.DropExcessRequests && fileConfig.DropExcessRequests {
dbConfig.DropExcessRequests = fileConfig.DropExcessRequests
}
if !dbConfig.EnableLogging && fileConfig.EnableLogging {
dbConfig.EnableLogging = fileConfig.EnableLogging
}
if !dbConfig.DisableContentLogging && fileConfig.DisableContentLogging {
dbConfig.DisableContentLogging = fileConfig.DisableContentLogging
}
if !dbConfig.EnableGovernance && fileConfig.EnableGovernance {
dbConfig.EnableGovernance = fileConfig.EnableGovernance
}
if !dbConfig.EnforceGovernanceHeader && fileConfig.EnforceGovernanceHeader {
dbConfig.EnforceGovernanceHeader = fileConfig.EnforceGovernanceHeader
}
if !dbConfig.AllowDirectKeys && fileConfig.AllowDirectKeys {
dbConfig.AllowDirectKeys = fileConfig.AllowDirectKeys
}
if !dbConfig.EnableLiteLLMFallbacks && fileConfig.EnableLiteLLMFallbacks {
dbConfig.EnableLiteLLMFallbacks = fileConfig.EnableLiteLLMFallbacks
}
// Merge HeaderFilterConfig: DB takes priority, but fill in empty values from config file
if dbConfig.HeaderFilterConfig == nil && fileConfig.HeaderFilterConfig != nil {
dbConfig.HeaderFilterConfig = fileConfig.HeaderFilterConfig
} else if dbConfig.HeaderFilterConfig != nil && fileConfig.HeaderFilterConfig != nil {
// Merge individual lists: DB values take priority, but if empty, use file values
if len(dbConfig.HeaderFilterConfig.Allowlist) == 0 && len(fileConfig.HeaderFilterConfig.Allowlist) > 0 {
dbConfig.HeaderFilterConfig.Allowlist = fileConfig.HeaderFilterConfig.Allowlist
}
if len(dbConfig.HeaderFilterConfig.Denylist) == 0 && len(fileConfig.HeaderFilterConfig.Denylist) > 0 {
dbConfig.HeaderFilterConfig.Denylist = fileConfig.HeaderFilterConfig.Denylist
}
}
}
// loadProvidersFromFile loads and merges providers from file with store using hash reconciliation
func loadProvidersFromFile(ctx context.Context, config *Config, configData *ConfigData) error {
var providersInConfigStore map[schemas.ModelProvider]configstore.ProviderConfig
var err error
if config.ConfigStore != nil {
logger.Debug("getting providers config from store")
providersInConfigStore, err = config.ConfigStore.GetProvidersConfig(ctx)
if err != nil {
logger.Warn("failed to get providers config from store: %v", err)
}
}
if providersInConfigStore == nil {
logger.Debug("no providers config found in store, processing from config file")
providersInConfigStore = make(map[schemas.ModelProvider]configstore.ProviderConfig)
}
// Process provider configurations from file
if configData.Providers != nil {
for providerName, providerCfgInFile := range configData.Providers {
if err = processProviderFromFile(ctx, config, providerName, providerCfgInFile, providersInConfigStore); err != nil {
logger.Warn("failed to process provider %s: %v", providerName, err)
}
}
} else {
config.autoDetectProviders(ctx)
}
// Update store and config
if config.ConfigStore != nil {
logger.Debug("updating providers config in store")
if err = config.ConfigStore.UpdateProvidersConfig(ctx, providersInConfigStore); err != nil {
logger.Fatal("failed to update providers config: %v", err)
}
if err = config.ConfigStore.UpdateEnvKeys(ctx, config.EnvKeys); err != nil {
logger.Fatal("failed to update env keys: %v", err)
}
}
config.Providers = providersInConfigStore
return nil
}
// processProviderFromFile processes a single provider configuration from config file
func processProviderFromFile(
ctx context.Context,
config *Config,
providerName string,
providerCfgInFile configstore.ProviderConfig,
providersInConfigStore map[schemas.ModelProvider]configstore.ProviderConfig,
) error {
newEnvKeys := make(map[string]struct{})
provider := schemas.ModelProvider(strings.ToLower(providerName))
// Process environment variables in keys (including key-level configs)
for i, providerKeyInFile := range providerCfgInFile.Keys {
if providerKeyInFile.ID == "" {
providerCfgInFile.Keys[i].ID = uuid.NewString()
}
// Process API key value
processedValue, envVar, err := config.processEnvValue(providerKeyInFile.Value)
if err != nil {
config.cleanupEnvKeys(provider, "", newEnvKeys)
if strings.Contains(err.Error(), "not found") {
logger.Info("%s: %v", provider, err)
} else {
logger.Warn("failed to process env vars in keys for %s: %v", provider, err)
}
continue
}
providerCfgInFile.Keys[i].Value = processedValue
// Track environment key if it came from env
if envVar != "" {
newEnvKeys[envVar] = struct{}{}
config.EnvKeys[envVar] = append(config.EnvKeys[envVar], configstore.EnvKeyInfo{
EnvVar: envVar,
Provider: provider,
KeyType: "api_key",
ConfigPath: fmt.Sprintf("providers.%s.keys[%s]", provider, providerKeyInFile.ID),
KeyID: providerKeyInFile.ID,
})
}
// Process Azure key config if present
if providerKeyInFile.AzureKeyConfig != nil {
if err := config.processAzureKeyConfigEnvVars(&providerCfgInFile.Keys[i], provider, newEnvKeys); err != nil {
config.cleanupEnvKeys(provider, "", newEnvKeys)
logger.Warn("failed to process Azure key config env vars for %s: %v", provider, err)
continue
}
}
// Process Vertex key config if present
if providerKeyInFile.VertexKeyConfig != nil {
if err := config.processVertexKeyConfigEnvVars(&providerCfgInFile.Keys[i], provider, newEnvKeys); err != nil {
config.cleanupEnvKeys(provider, "", newEnvKeys)
logger.Warn("failed to process Vertex key config env vars for %s: %v", provider, err)
continue
}
}
// Process Bedrock key config if present
if providerKeyInFile.BedrockKeyConfig != nil {
if err := config.processBedrockKeyConfigEnvVars(&providerCfgInFile.Keys[i], provider, newEnvKeys); err != nil {
config.cleanupEnvKeys(provider, "", newEnvKeys)
logger.Warn("failed to process Bedrock key config env vars for %s: %v", provider, err)
continue
}
}
}
// Generate hash from config.json provider config
fileProviderConfigHash, err := providerCfgInFile.GenerateConfigHash(string(provider))
if err != nil {
logger.Warn("failed to generate config hash for %s: %v", provider, err)
}
providerCfgInFile.ConfigHash = fileProviderConfigHash
// Merge with existing config using hash-based reconciliation
mergeProviderWithHash(provider, providerCfgInFile, providersInConfigStore)
return nil
}
// mergeProviderWithHash merges provider config using hash-based reconciliation
func mergeProviderWithHash(
provider schemas.ModelProvider,
providerCfgInFile configstore.ProviderConfig,
providersInConfigStore map[schemas.ModelProvider]configstore.ProviderConfig,
) {
existingCfg, exists := providersInConfigStore[provider]
if !exists {
// New provider - add from config.json
providersInConfigStore[provider] = providerCfgInFile
return
}
// Provider exists in DB - compare hashes
if existingCfg.ConfigHash != providerCfgInFile.ConfigHash {
// Hash mismatch - config.json was changed, sync from file
logger.Debug("config hash mismatch for provider %s, syncing from config file", provider)
mergedKeys := mergeProviderKeys(provider, providerCfgInFile.Keys, existingCfg.Keys)
providerCfgInFile.Keys = mergedKeys
providersInConfigStore[provider] = providerCfgInFile
} else {
// Provider hash matches - but still check individual keys
logger.Debug("config hash matches for provider %s, checking individual keys", provider)
mergedKeys := reconcileProviderKeys(provider, providerCfgInFile.Keys, existingCfg.Keys)
existingCfg.Keys = mergedKeys
providersInConfigStore[provider] = existingCfg
}
}
// mergeProviderKeys merges keys when provider hash has changed
func mergeProviderKeys(provider schemas.ModelProvider, fileKeys, dbKeys []schemas.Key) []schemas.Key {
mergedKeys := fileKeys
for _, dbKey := range dbKeys {
found := false
for i, fileKey := range fileKeys {
// Compare by hash to detect changes
fileKeyHash, err := configstore.GenerateKeyHash(fileKey)
if err != nil {
logger.Warn("failed to generate key hash for file key %s (%s): %v, falling back to name comparison", fileKey.Name, provider, err)
if fileKey.Name == dbKey.Name {
fileKeys[i].ID = dbKey.ID
found = true
break
}
continue
}
// Use stored ConfigHash for comparison if available
if dbKey.ConfigHash != "" {
if fileKeyHash == dbKey.ConfigHash || fileKey.Name == dbKey.Name {
fileKeys[i].ID = dbKey.ID
found = true
break
}
} else {
// No stored hash (legacy) - fall back to generating fresh hash
dbKeyHash, err := configstore.GenerateKeyHash(schemas.Key{
Name: dbKey.Name,
Value: dbKey.Value,
Models: dbKey.Models,
Weight: dbKey.Weight,
AzureKeyConfig: dbKey.AzureKeyConfig,
VertexKeyConfig: dbKey.VertexKeyConfig,
BedrockKeyConfig: dbKey.BedrockKeyConfig,
})
if err != nil {
logger.Warn("failed to generate key hash for db key %s (%s): %v, falling back to name comparison", dbKey.Name, provider, err)
if fileKey.Name == dbKey.Name {
fileKeys[i].ID = dbKey.ID
found = true
break
}
continue
}
if fileKeyHash == dbKeyHash || fileKey.Name == dbKey.Name {
fileKeys[i].ID = dbKey.ID
found = true
break
}
}
}
if !found {
// Key exists in DB but not in file - preserve it (added via dashboard)
mergedKeys = append(mergedKeys, dbKey)
}
}
return mergedKeys
}
// reconcileProviderKeys reconciles keys when provider hash matches
func reconcileProviderKeys(provider schemas.ModelProvider, fileKeys, dbKeys []schemas.Key) []schemas.Key {
mergedKeys := make([]schemas.Key, 0)
fileKeysByName := make(map[string]int) // name -> index in file keys
for i, fileKey := range fileKeys {
fileKeysByName[fileKey.Name] = i
}
// Process DB keys - check if they exist in file and compare hashes
for _, dbKey := range dbKeys {
if fileIdx, exists := fileKeysByName[dbKey.Name]; exists {
fileKey := fileKeys[fileIdx]
fileKeyHash, err := configstore.GenerateKeyHash(fileKey)
if err != nil {
logger.Warn("failed to generate key hash for file key %s (%s): %v", fileKey.Name, provider, err)
mergedKeys = append(mergedKeys, dbKey)
delete(fileKeysByName, dbKey.Name)
continue
}
// Compare file hash against STORED config hash (not fresh hash from DB values)
// This ensures DB updates are preserved when config.json hasn't changed
if dbKey.ConfigHash != "" {
if fileKeyHash == dbKey.ConfigHash {
// File unchanged - keep DB version (preserves user updates)
mergedKeys = append(mergedKeys, dbKey)
} else {
// File changed - use file version but preserve ID
logger.Debug("key %s changed in config file for provider %s, updating", fileKey.Name, provider)
fileKey.ID = dbKey.ID
mergedKeys = append(mergedKeys, fileKey)
}
} else {
// No stored hash (legacy) - fall back to generating fresh hash for comparison
dbKeyHash, err := configstore.GenerateKeyHash(schemas.Key{
Name: dbKey.Name,
Value: dbKey.Value,
Models: dbKey.Models,
Weight: dbKey.Weight,
AzureKeyConfig: dbKey.AzureKeyConfig,
VertexKeyConfig: dbKey.VertexKeyConfig,
BedrockKeyConfig: dbKey.BedrockKeyConfig,
})
if err != nil {
logger.Warn("failed to generate key hash for db key %s (%s): %v", dbKey.Name, provider, err)
mergedKeys = append(mergedKeys, dbKey)
delete(fileKeysByName, dbKey.Name)
continue
}
if fileKeyHash != dbKeyHash {
// Key changed in file - use file version but preserve ID
logger.Debug("key %s changed in config file for provider %s, updating", fileKey.Name, provider)
fileKey.ID = dbKey.ID
mergedKeys = append(mergedKeys, fileKey)
} else {
// Key unchanged - keep DB version
mergedKeys = append(mergedKeys, dbKey)
}
}
delete(fileKeysByName, dbKey.Name) // Mark as processed
} else {
// Key only in DB - preserve it (added via dashboard)
mergedKeys = append(mergedKeys, dbKey)
}
}
// Add keys only in file (new keys from config.json)
for _, idx := range fileKeysByName {
mergedKeys = append(mergedKeys, fileKeys[idx])
}
return mergedKeys
}
// loadMCPConfigFromFile loads and merges MCP config from file
func loadMCPConfigFromFile(ctx context.Context, config *Config, configData *ConfigData) {
var mcpConfig *schemas.MCPConfig
var err error
if config.ConfigStore != nil {
logger.Debug("getting MCP config from store")
mcpConfig, err = config.ConfigStore.GetMCPConfig(ctx)
if err != nil {
logger.Warn("failed to get MCP config from store: %v", err)
}
}
if mcpConfig != nil {
config.MCPConfig = mcpConfig
// Merge with config file if present
if configData.MCP != nil && len(configData.MCP.ClientConfigs) > 0 {
mergeMCPConfig(ctx, config, configData, mcpConfig)
}
} else if configData.MCP != nil {
// MCP config not in store, use config file
logger.Debug("no MCP config found in store, processing from config file")
config.MCPConfig = configData.MCP
if err := config.processMCPEnvVars(); err != nil {
logger.Warn("failed to process MCP env vars: %v", err)
}
if config.ConfigStore != nil && config.MCPConfig != nil {
logger.Debug("updating MCP config in store")
for _, clientConfig := range config.MCPConfig.ClientConfigs {
if err := config.ConfigStore.CreateMCPClientConfig(ctx, clientConfig, config.EnvKeys); err != nil {
logger.Warn("failed to create MCP client config: %v", err)
}
}
}
}
}
// mergeMCPConfig merges MCP config from file with store
func mergeMCPConfig(ctx context.Context, config *Config, configData *ConfigData, mcpConfig *schemas.MCPConfig) {
logger.Debug("merging MCP config from config file with store")
// Process env vars for config file MCP configs
tempMCPConfig := configData.MCP
originalMCPConfig := config.MCPConfig
config.MCPConfig = tempMCPConfig
if err := config.processMCPEnvVars(); err != nil {
logger.Warn("failed to process MCP env vars: %v", err)
config.MCPConfig = originalMCPConfig
return
}
// Merge ClientConfigs arrays by ID or Name
clientConfigsToAdd := make([]schemas.MCPClientConfig, 0)
for _, newClientConfig := range tempMCPConfig.ClientConfigs {
found := false
for _, existingClientConfig := range mcpConfig.ClientConfigs {
if (newClientConfig.ID != "" && existingClientConfig.ID == newClientConfig.ID) ||
(newClientConfig.Name != "" && existingClientConfig.Name == newClientConfig.Name) {
found = true
break
}
}
if !found {
clientConfigsToAdd = append(clientConfigsToAdd, newClientConfig)
}
}
// Add new client configs to existing ones
config.MCPConfig.ClientConfigs = append(mcpConfig.ClientConfigs, clientConfigsToAdd...)
// Update store with merged config
if config.ConfigStore != nil && len(clientConfigsToAdd) > 0 {
logger.Debug("updating MCP config in store with %d new client configs", len(clientConfigsToAdd))
for _, clientConfig := range clientConfigsToAdd {
if err := config.ConfigStore.CreateMCPClientConfig(ctx, clientConfig, config.EnvKeys); err != nil {
logger.Warn("failed to create MCP client config: %v", err)
}
}
}
}
// loadGovernanceConfigFromFile loads and merges governance config from file
func loadGovernanceConfigFromFile(ctx context.Context, config *Config, configData *ConfigData) {
var governanceConfig *configstore.GovernanceConfig
var err error
if config.ConfigStore != nil {
logger.Debug("getting governance config from store")
governanceConfig, err = config.ConfigStore.GetGovernanceConfig(ctx)
if err != nil {
logger.Warn("failed to get governance config from store: %v", err)
}
} else {
logger.Debug("config.ConfigStore is nil, skipping store lookup")
}
if governanceConfig != nil {
config.GovernanceConfig = governanceConfig
// Merge with config file if present
if configData.Governance != nil {
mergeGovernanceConfig(ctx, config, configData, governanceConfig)
}
} else if configData.Governance != nil {
// No governance config in store, use config file
logger.Debug("no governance config found in store, processing from config file")
config.GovernanceConfig = configData.Governance
createGovernanceConfigInStore(ctx, config)
} else {
logger.Debug("no governance config in store or config file")
}
}
// mergeGovernanceConfig merges governance config from file with store
func mergeGovernanceConfig(ctx context.Context, config *Config, configData *ConfigData, governanceConfig *configstore.GovernanceConfig) {
logger.Debug("merging governance config from config file with store")
// Merge Budgets by ID with hash comparison
budgetsToAdd := make([]configstoreTables.TableBudget, 0)
budgetsToUpdate := make([]configstoreTables.TableBudget, 0)
for i, newBudget := range configData.Governance.Budgets {
fileBudgetHash, err := configstore.GenerateBudgetHash(newBudget)
if err != nil {
logger.Warn("failed to generate budget hash for %s: %v", newBudget.ID, err)
continue
}
configData.Governance.Budgets[i].ConfigHash = fileBudgetHash
found := false
for j, existingBudget := range governanceConfig.Budgets {
if existingBudget.ID == newBudget.ID {
found = true
if existingBudget.ConfigHash != fileBudgetHash {
logger.Debug("config hash mismatch for budget %s, syncing from config file", newBudget.ID)
configData.Governance.Budgets[i].ConfigHash = fileBudgetHash
budgetsToUpdate = append(budgetsToUpdate, configData.Governance.Budgets[i])
governanceConfig.Budgets[j] = configData.Governance.Budgets[i]
} else {
logger.Debug("config hash matches for budget %s, keeping DB config", newBudget.ID)
}
break
}
}
if !found {
configData.Governance.Budgets[i].ConfigHash = fileBudgetHash