summaryrefslogtreecommitdiffstats
path: root/internal/config/config.go
blob: 87ca4eb1f58ae8a19d72639474e05af7ba5622c8 (plain)
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
package config

import (
	"fmt"
	"os"
	"strings"
	"time"

	"gopkg.in/yaml.v3"
)

// Config holds all configuration for the relay.
type Config struct {
	Server     ServerConfig     `yaml:"server"`
	Database   DatabaseConfig   `yaml:"database"`
	Auth       AuthConfig       `yaml:"auth"`
	RateLimit  RateLimitConfig  `yaml:"rate_limit"`
	Metrics    MetricsConfig    `yaml:"metrics"`
	Logging    LoggingConfig    `yaml:"logging"`
	Storage    StorageConfig    `yaml:"storage"`
}

// ServerConfig holds server configuration.
type ServerConfig struct {
	GrpcAddr     string        `yaml:"grpc_addr"`
	HttpAddr     string        `yaml:"http_addr"`
	PublicURL    string        `yaml:"public_url"`
	ReadTimeout  time.Duration `yaml:"read_timeout"`
	WriteTimeout time.Duration `yaml:"write_timeout"`
}

// DatabaseConfig holds database configuration.
type DatabaseConfig struct {
	Path           string        `yaml:"path"`
	MaxConnections int           `yaml:"max_connections"`
	MaxLifetime    time.Duration `yaml:"max_lifetime"`
}

// AuthConfig holds authentication configuration.
type AuthConfig struct {
	Enabled         bool     `yaml:"enabled"`
	Required        bool     `yaml:"required"`
	TimestampWindow int64    `yaml:"timestamp_window"`
	AllowedPubkeys  []string `yaml:"allowed_pubkeys"`
	SkipMethods     []string `yaml:"skip_methods"`
}

// RateLimitConfig holds rate limiting configuration.
type RateLimitConfig struct {
	Enabled         bool                       `yaml:"enabled"`
	DefaultRPS      float64                    `yaml:"default_rps"`
	DefaultBurst    int                        `yaml:"default_burst"`
	IPRPS           float64                    `yaml:"ip_rps"`
	IPBurst         int                        `yaml:"ip_burst"`
	Methods         map[string]MethodLimit     `yaml:"methods"`
	Users           map[string]UserLimit       `yaml:"users"`
	SkipMethods     []string                   `yaml:"skip_methods"`
	SkipUsers       []string                   `yaml:"skip_users"`
	CleanupInterval time.Duration              `yaml:"cleanup_interval"`
	MaxIdleTime     time.Duration              `yaml:"max_idle_time"`
}

// MethodLimit defines rate limits for a specific method.
type MethodLimit struct {
	RPS   float64 `yaml:"rps"`
	Burst int     `yaml:"burst"`
}

// UserLimit defines rate limits for a specific user.
type UserLimit struct {
	RPS     float64                `yaml:"rps"`
	Burst   int                    `yaml:"burst"`
	Methods map[string]MethodLimit `yaml:"methods"`
}

// MetricsConfig holds metrics configuration.
type MetricsConfig struct {
	Enabled   bool   `yaml:"enabled"`
	Addr      string `yaml:"addr"`
	Path      string `yaml:"path"`
	Namespace string `yaml:"namespace"`
	Subsystem string `yaml:"subsystem"`
}

// LoggingConfig holds logging configuration.
type LoggingConfig struct {
	Level  string `yaml:"level"`
	Format string `yaml:"format"`
	Output string `yaml:"output"`
}

// StorageConfig holds storage configuration.
type StorageConfig struct {
	AutoCompact     bool          `yaml:"auto_compact"`
	CompactInterval time.Duration `yaml:"compact_interval"`
	MaxEventAge     time.Duration `yaml:"max_event_age"`
}

// Default returns the default configuration.
func Default() *Config {
	return &Config{
		Server: ServerConfig{
			GrpcAddr:     ":50051",
			HttpAddr:     ":8080",
			ReadTimeout:  30 * time.Second,
			WriteTimeout: 30 * time.Second,
		},
		Database: DatabaseConfig{
			Path:           "relay.db",
			MaxConnections: 10,
			MaxLifetime:    1 * time.Hour,
		},
		Auth: AuthConfig{
			Enabled:         false,
			Required:        false,
			TimestampWindow: 60,
		},
		RateLimit: RateLimitConfig{
			Enabled:         false,
			DefaultRPS:      10,
			DefaultBurst:    20,
			IPRPS:           5,
			IPBurst:         10,
			CleanupInterval: 5 * time.Minute,
			MaxIdleTime:     10 * time.Minute,
		},
		Metrics: MetricsConfig{
			Enabled:   true,
			Addr:      ":9090",
			Path:      "/metrics",
			Namespace: "muxstr",
			Subsystem: "relay",
		},
		Logging: LoggingConfig{
			Level:  "info",
			Format: "json",
			Output: "stdout",
		},
		Storage: StorageConfig{
			AutoCompact:     true,
			CompactInterval: 24 * time.Hour,
			MaxEventAge:     0, // unlimited
		},
	}
}

// Load loads configuration from a YAML file and applies environment variable overrides.
func Load(filename string) (*Config, error) {
	// Start with defaults
	cfg := Default()

	// Read file if provided
	if filename != "" {
		data, err := os.ReadFile(filename)
		if err != nil {
			return nil, fmt.Errorf("failed to read config file: %w", err)
		}

		if err := yaml.Unmarshal(data, cfg); err != nil {
			return nil, fmt.Errorf("failed to parse config file: %w", err)
		}
	}

	// Apply environment variable overrides
	applyEnvOverrides(cfg)

	// Validate
	if err := cfg.Validate(); err != nil {
		return nil, fmt.Errorf("invalid configuration: %w", err)
	}

	return cfg, nil
}

// Validate validates the configuration.
func (c *Config) Validate() error {
	// Validate server addresses
	if c.Server.GrpcAddr == "" {
		return fmt.Errorf("server.grpc_addr is required")
	}
	if c.Server.HttpAddr == "" {
		return fmt.Errorf("server.http_addr is required")
	}

	// Validate database path
	if c.Database.Path == "" {
		return fmt.Errorf("database.path is required")
	}

	// Validate metrics config if enabled
	if c.Metrics.Enabled {
		if c.Metrics.Addr == "" {
			return fmt.Errorf("metrics.addr is required when metrics enabled")
		}
		if c.Metrics.Namespace == "" {
			return fmt.Errorf("metrics.namespace is required when metrics enabled")
		}
	}

	// Validate logging
	validLevels := map[string]bool{"debug": true, "info": true, "warn": true, "error": true}
	if !validLevels[c.Logging.Level] {
		return fmt.Errorf("invalid logging.level: %s (must be debug, info, warn, or error)", c.Logging.Level)
	}

	validFormats := map[string]bool{"json": true, "text": true}
	if !validFormats[c.Logging.Format] {
		return fmt.Errorf("invalid logging.format: %s (must be json or text)", c.Logging.Format)
	}

	return nil
}

// applyEnvOverrides applies environment variable overrides to the configuration.
// Environment variables follow the pattern: MUXSTR_<SECTION>_<KEY>
func applyEnvOverrides(cfg *Config) {
	// Server
	if val := os.Getenv("MUXSTR_SERVER_GRPC_ADDR"); val != "" {
		cfg.Server.GrpcAddr = val
	}
	if val := os.Getenv("MUXSTR_SERVER_HTTP_ADDR"); val != "" {
		cfg.Server.HttpAddr = val
	}
	if val := os.Getenv("MUXSTR_SERVER_PUBLIC_URL"); val != "" {
		cfg.Server.PublicURL = val
	}
	if val := os.Getenv("MUXSTR_SERVER_READ_TIMEOUT"); val != "" {
		if d, err := time.ParseDuration(val); err == nil {
			cfg.Server.ReadTimeout = d
		}
	}
	if val := os.Getenv("MUXSTR_SERVER_WRITE_TIMEOUT"); val != "" {
		if d, err := time.ParseDuration(val); err == nil {
			cfg.Server.WriteTimeout = d
		}
	}

	// Database
	if val := os.Getenv("MUXSTR_DATABASE_PATH"); val != "" {
		cfg.Database.Path = val
	}
	if val := os.Getenv("MUXSTR_DATABASE_MAX_CONNECTIONS"); val != "" {
		var n int
		if _, err := fmt.Sscanf(val, "%d", &n); err == nil {
			cfg.Database.MaxConnections = n
		}
	}

	// Auth
	if val := os.Getenv("MUXSTR_AUTH_ENABLED"); val != "" {
		cfg.Auth.Enabled = parseBool(val)
	}
	if val := os.Getenv("MUXSTR_AUTH_REQUIRED"); val != "" {
		cfg.Auth.Required = parseBool(val)
	}
	if val := os.Getenv("MUXSTR_AUTH_TIMESTAMP_WINDOW"); val != "" {
		var n int64
		if _, err := fmt.Sscanf(val, "%d", &n); err == nil {
			cfg.Auth.TimestampWindow = n
		}
	}
	if val := os.Getenv("MUXSTR_AUTH_ALLOWED_PUBKEYS"); val != "" {
		cfg.Auth.AllowedPubkeys = strings.Split(val, ",")
	}

	// Rate limit
	if val := os.Getenv("MUXSTR_RATE_LIMIT_ENABLED"); val != "" {
		cfg.RateLimit.Enabled = parseBool(val)
	}
	if val := os.Getenv("MUXSTR_RATE_LIMIT_DEFAULT_RPS"); val != "" {
		var n float64
		if _, err := fmt.Sscanf(val, "%f", &n); err == nil {
			cfg.RateLimit.DefaultRPS = n
		}
	}
	if val := os.Getenv("MUXSTR_RATE_LIMIT_DEFAULT_BURST"); val != "" {
		var n int
		if _, err := fmt.Sscanf(val, "%d", &n); err == nil {
			cfg.RateLimit.DefaultBurst = n
		}
	}

	// Metrics
	if val := os.Getenv("MUXSTR_METRICS_ENABLED"); val != "" {
		cfg.Metrics.Enabled = parseBool(val)
	}
	if val := os.Getenv("MUXSTR_METRICS_ADDR"); val != "" {
		cfg.Metrics.Addr = val
	}
	if val := os.Getenv("MUXSTR_METRICS_PATH"); val != "" {
		cfg.Metrics.Path = val
	}

	// Logging
	if val := os.Getenv("MUXSTR_LOGGING_LEVEL"); val != "" {
		cfg.Logging.Level = val
	}
	if val := os.Getenv("MUXSTR_LOGGING_FORMAT"); val != "" {
		cfg.Logging.Format = val
	}
	if val := os.Getenv("MUXSTR_LOGGING_OUTPUT"); val != "" {
		cfg.Logging.Output = val
	}
}

// parseBool parses a boolean from a string.
func parseBool(s string) bool {
	s = strings.ToLower(s)
	return s == "true" || s == "1" || s == "yes" || s == "on"
}

// Save saves the configuration to a YAML file.
func (c *Config) Save(filename string) error {
	data, err := yaml.Marshal(c)
	if err != nil {
		return fmt.Errorf("failed to marshal config: %w", err)
	}

	if err := os.WriteFile(filename, data, 0644); err != nil {
		return fmt.Errorf("failed to write config file: %w", err)
	}

	return nil
}