stillbox/pkg/gordio/config/config.go

103 lines
2.1 KiB
Go
Raw Normal View History

2024-07-14 13:47:48 -04:00
package config
2024-07-14 17:39:03 -04:00
import (
2024-08-04 08:55:12 -04:00
"os"
2024-10-18 15:21:42 -04:00
"sync"
"time"
2024-08-04 08:55:12 -04:00
2024-07-23 20:27:19 -04:00
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
2024-07-14 17:39:03 -04:00
)
2024-07-14 13:47:48 -04:00
type Config struct {
2024-10-18 15:21:42 -04:00
DB DB `yaml:"db"`
CORS CORS `yaml:"cors"`
Auth Auth `yaml:"auth"`
Alerting Alerting `yaml:"alerting"`
2024-10-18 15:21:42 -04:00
Log []Logger `yaml:"log"`
Listen string `yaml:"listen"`
Public bool `yaml:"public"`
RateLimit RateLimit `yaml:"rateLimit"`
2024-07-23 20:27:19 -04:00
configPath string
2024-07-14 13:47:48 -04:00
}
2024-08-04 08:55:12 -04:00
type Auth struct {
JWTSecret string `yaml:"jwtsecret"`
Domain string `yaml:"domain"`
AllowInsecure map[string]bool `yaml:"allowInsecureFor"`
}
2024-08-14 19:12:20 -04:00
type CORS struct {
AllowedOrigins []string `yaml:"allowedOrigins"`
}
2024-07-14 17:39:03 -04:00
type DB struct {
Connect string `yaml:"connect"`
}
2024-10-17 10:00:23 -04:00
type Logger struct {
2024-10-17 11:28:43 -04:00
File *string `yaml:"file"`
Level *string `yaml:"level"`
2024-10-17 10:00:23 -04:00
}
2024-10-18 15:21:42 -04:00
type RateLimit struct {
Enable bool `yaml:"enable"`
Requests int `yaml:"requests"`
Over time.Duration `yaml:"over"`
verifyError sync.Once
}
type Alerting struct {
Enable bool `yaml:"enable"`
LookbackDays uint `yaml:"lookbackDays"`
HalfLife time.Duration `yaml:"halfLife"`
Recent time.Duration `yaml:"recent"`
}
2024-10-18 15:21:42 -04:00
func (rl *RateLimit) Verify() bool {
if rl.Enable {
if rl.Requests > 0 && rl.Over > 0 {
return true
}
rl.verifyError.Do(func() {
log.Error().Int("requests", rl.Requests).Str("over", rl.Over.String()).Msg("rate limit config makes no sense, disabled")
})
}
return false
}
2024-10-17 11:28:43 -04:00
func (c *Config) PreRunE() func(*cobra.Command, []string) error {
return func(cmd *cobra.Command, args []string) error {
return c.ReadConfig()
}
}
func New(rootCommand *cobra.Command) *Config {
2024-07-23 20:27:19 -04:00
c := &Config{}
2024-10-17 11:28:43 -04:00
rootCommand.PersistentFlags().StringVarP(&c.configPath, "config", "c", "config.yaml", "configuration file")
2024-07-23 20:27:19 -04:00
return c
2024-07-14 17:39:03 -04:00
}
2024-07-23 20:27:19 -04:00
func (c *Config) ReadConfig() error {
cfgBytes, err := os.ReadFile(c.configPath)
2024-07-14 17:39:03 -04:00
if err != nil {
2024-07-23 20:27:19 -04:00
return err
2024-07-14 17:39:03 -04:00
}
err = yaml.Unmarshal(cfgBytes, c)
if err != nil {
2024-07-23 20:27:19 -04:00
return err
2024-07-14 17:39:03 -04:00
}
2024-07-23 20:27:19 -04:00
log.Info().Str("configPath", c.configPath).Msg("read gordio config")
return nil
2024-07-14 13:47:48 -04:00
}