|
| 1 | +package dbos |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net/url" |
| 6 | + "os" |
| 7 | + |
| 8 | + "github.com/spf13/viper" |
| 9 | +) |
| 10 | + |
| 11 | +const dbosConfigFileName = "dbos_config.yaml" |
| 12 | + |
| 13 | +type configFile struct { |
| 14 | + Name string `yaml:"name"` |
| 15 | + DatabaseURL string `yaml:"database_url"` |
| 16 | +} |
| 17 | + |
| 18 | +func LoadConfig() (*configFile, error) { |
| 19 | + v := viper.New() |
| 20 | + v.SetConfigFile(dbosConfigFileName) |
| 21 | + v.AutomaticEnv() |
| 22 | + |
| 23 | + if err := v.ReadInConfig(); err != nil { |
| 24 | + return nil, err |
| 25 | + } |
| 26 | + |
| 27 | + var config configFile |
| 28 | + if err := v.Unmarshal(&config); err != nil { |
| 29 | + return nil, fmt.Errorf("failed to parse config: %w", err) |
| 30 | + } |
| 31 | + |
| 32 | + return &config, nil |
| 33 | +} |
| 34 | + |
| 35 | +// ProcessConfig merges configuration from three sources in order of precedence: |
| 36 | +// 1. programmatic configuration (highest precedence) |
| 37 | +// 2. configuration file |
| 38 | +// 3. environment variables (lowest precedence) |
| 39 | +func ProcessConfig(programmaticConfig config) *config { |
| 40 | + fileConfig, err := LoadConfig() |
| 41 | + if err != nil && !os.IsNotExist(err) { |
| 42 | + panic(err) |
| 43 | + } |
| 44 | + |
| 45 | + dbosConfig := &config{} |
| 46 | + |
| 47 | + // Start with environment variables (lowest precedence) |
| 48 | + if dbURL := os.Getenv("DBOS_DATABASE_URL"); dbURL != "" { |
| 49 | + dbosConfig.databaseURL = dbURL |
| 50 | + } |
| 51 | + |
| 52 | + // Override with file configuration if available |
| 53 | + if fileConfig != nil { |
| 54 | + if fileConfig.DatabaseURL != "" { |
| 55 | + dbosConfig.databaseURL = fileConfig.DatabaseURL |
| 56 | + } |
| 57 | + if fileConfig.Name != "" { |
| 58 | + dbosConfig.appName = fileConfig.Name |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + // Override with programmatic configuration (highest precedence) |
| 63 | + if len(programmaticConfig.databaseURL) > 0 { |
| 64 | + dbosConfig.databaseURL = programmaticConfig.databaseURL |
| 65 | + } |
| 66 | + if len(programmaticConfig.appName) > 0 { |
| 67 | + dbosConfig.appName = programmaticConfig.appName |
| 68 | + } |
| 69 | + // Copy over parameters that can only be set programmatically |
| 70 | + dbosConfig.logger = programmaticConfig.logger |
| 71 | + dbosConfig.adminServer = programmaticConfig.adminServer |
| 72 | + |
| 73 | + // Load defaults |
| 74 | + if len(dbosConfig.databaseURL) == 0 { |
| 75 | + fmt.Println("DBOS_DATABASE_URL not set, using default: postgres://postgres:${PGPASSWORD}@localhost:5432/dbos?sslmode=disable") |
| 76 | + password := url.QueryEscape(os.Getenv("PGPASSWORD")) |
| 77 | + dbosConfig.databaseURL = fmt.Sprintf("postgres://postgres:%s@localhost:5432/dbos?sslmode=disable", password) |
| 78 | + } |
| 79 | + return dbosConfig |
| 80 | +} |
0 commit comments