summaryrefslogtreecommitdiff
path: root/internal/config/config.go
blob: 8c21c6c2435e08cfe1576dca0d85bdd37a1aad90 (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
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
package config

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/url"
	"os"
	"strings"
	"time"

	"aigw/internal/domain"
)

type Config struct {
	Server        ServerConfig        `json:"server"`
	Auth          AuthConfig          `json:"auth"`
	ControlPlane  ControlPlaneConfig  `json:"control_plane"`
	Admin         AdminConfig         `json:"admin"`
	UpstreamHTTP  UpstreamHTTPConfig  `json:"upstream_http"`
	Providers     []ProviderConfig    `json:"providers"`
	Models        []ModelConfig       `json:"models"`
	Billing       BillingConfig       `json:"billing"`
	Observability ObservabilityConfig `json:"observability"`
}

type ServerConfig struct {
	Address               string `json:"address"`
	MaxBodyBytes          int64  `json:"max_body_bytes"`
	ReadHeaderTimeoutSecs int    `json:"read_header_timeout_seconds"`
	IdleTimeoutSecs       int    `json:"idle_timeout_seconds"`
	ShutdownTimeoutSecs   int    `json:"shutdown_timeout_seconds"`
}

type AuthConfig struct {
	KeysEnv        string `json:"keys_env"`
	AllowAnonymous bool   `json:"allow_anonymous"`
}

type ControlPlaneConfig struct {
	Enabled               bool   `json:"enabled"`
	DatabaseURLEnv        string `json:"database_url_env"`
	RedisURLEnv           string `json:"redis_url_env"`
	CredentialKeyEnv      string `json:"credential_key_env"`
	RedisChannel          string `json:"redis_channel"`
	SnapshotCacheKey      string `json:"snapshot_cache_key"`
	ReloadIntervalSeconds int    `json:"reload_interval_seconds"`
	AutoMigrate           bool   `json:"auto_migrate"`
	DatabaseURL           string `json:"-"`
	RedisURL              string `json:"-"`
	CredentialKey         string `json:"-"`
}

type AdminConfig struct {
	Enabled  bool   `json:"enabled"`
	TokenEnv string `json:"token_env"`
	BasePath string `json:"base_path"`
	Token    string `json:"-"`
}

type UpstreamHTTPConfig struct {
	MaxIdleConnections        int `json:"max_idle_connections"`
	MaxIdleConnectionsPerHost int `json:"max_idle_connections_per_host"`
	IdleConnectionTimeoutSecs int `json:"idle_connection_timeout_seconds"`
	ResponseHeaderTimeoutSecs int `json:"response_header_timeout_seconds"`
}

type ProviderConfig struct {
	ID        string          `json:"id"`
	Protocol  domain.Protocol `json:"protocol"`
	BaseURL   string          `json:"base_url"`
	APIKeyEnv string          `json:"api_key_env"`
	APIKey    string          `json:"-"`
}

type ModelConfig struct {
	ID                              string        `json:"id"`
	OwnedBy                         string        `json:"owned_by"`
	InputPriceMicrosPerMillion      int64         `json:"input_price_micros_per_million"`
	OutputPriceMicrosPerMillion     int64         `json:"output_price_micros_per_million"`
	CacheReadPriceMicrosPerMillion  int64         `json:"cache_read_price_micros_per_million"`
	CacheWritePriceMicrosPerMillion int64         `json:"cache_write_price_micros_per_million"`
	Routes                          []RouteConfig `json:"routes"`
}

type RouteConfig struct {
	Provider      string `json:"provider"`
	UpstreamModel string `json:"upstream_model"`
	Priority      int    `json:"priority"`
	Weight        int    `json:"weight"`
}

type ObservabilityConfig struct {
	UsageBuffer   int  `json:"usage_buffer"`
	ExposeMetrics bool `json:"expose_metrics"`
}

type BillingConfig struct {
	Enabled                bool         `json:"enabled"`
	Currency               string       `json:"currency"`
	DefaultMaxOutputTokens int64        `json:"default_max_output_tokens"`
	MinTopUpMinor          int64        `json:"min_top_up_minor"`
	MaxTopUpMinor          int64        `json:"max_top_up_minor"`
	Stripe                 StripeConfig `json:"stripe"`
}

type StripeConfig struct {
	Enabled          bool   `json:"enabled"`
	APIKeyEnv        string `json:"api_key_env"`
	WebhookSecretEnv string `json:"webhook_secret_env"`
	SuccessURL       string `json:"success_url"`
	CancelURL        string `json:"cancel_url"`
	APIKey           string `json:"-"`
	WebhookSecret    string `json:"-"`
}

func Load(path string) (Config, error) {
	f, err := os.Open(path)
	if err != nil {
		return Config{}, fmt.Errorf("open config: %w", err)
	}
	defer f.Close()

	var cfg Config
	decoder := json.NewDecoder(f)
	decoder.DisallowUnknownFields()
	if err := decoder.Decode(&cfg); err != nil {
		return Config{}, fmt.Errorf("decode config: %w", err)
	}
	if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
		if err == nil {
			return Config{}, errors.New("decode config: multiple JSON values")
		}
		return Config{}, fmt.Errorf("decode config trailing data: %w", err)
	}

	applyDefaults(&cfg)
	if err := resolveSecrets(&cfg); err != nil {
		return Config{}, err
	}
	if err := Validate(cfg); err != nil {
		return Config{}, err
	}
	return cfg, nil
}

func applyDefaults(cfg *Config) {
	if cfg.Server.Address == "" {
		cfg.Server.Address = ":8080"
	}
	if cfg.Server.MaxBodyBytes == 0 {
		cfg.Server.MaxBodyBytes = 16 << 20
	}
	if cfg.Server.ReadHeaderTimeoutSecs == 0 {
		cfg.Server.ReadHeaderTimeoutSecs = 10
	}
	if cfg.Server.IdleTimeoutSecs == 0 {
		cfg.Server.IdleTimeoutSecs = 120
	}
	if cfg.Server.ShutdownTimeoutSecs == 0 {
		cfg.Server.ShutdownTimeoutSecs = 20
	}
	if cfg.Auth.KeysEnv == "" {
		cfg.Auth.KeysEnv = "AIGW_API_KEYS"
	}
	if cfg.ControlPlane.DatabaseURLEnv == "" {
		cfg.ControlPlane.DatabaseURLEnv = "AIGW_DATABASE_URL"
	}
	if cfg.ControlPlane.RedisURLEnv == "" {
		cfg.ControlPlane.RedisURLEnv = "AIGW_REDIS_URL"
	}
	if cfg.ControlPlane.CredentialKeyEnv == "" {
		cfg.ControlPlane.CredentialKeyEnv = "AIGW_CREDENTIAL_KEY"
	}
	if cfg.ControlPlane.RedisChannel == "" {
		cfg.ControlPlane.RedisChannel = "aigw:control:changed"
	}
	if cfg.ControlPlane.SnapshotCacheKey == "" {
		cfg.ControlPlane.SnapshotCacheKey = "aigw:control:snapshot:v1"
	}
	if cfg.ControlPlane.ReloadIntervalSeconds == 0 {
		cfg.ControlPlane.ReloadIntervalSeconds = 30
	}
	if cfg.Admin.TokenEnv == "" {
		cfg.Admin.TokenEnv = "AIGW_ADMIN_TOKEN"
	}
	if cfg.Admin.BasePath == "" {
		cfg.Admin.BasePath = "/admin"
	}
	if cfg.UpstreamHTTP.MaxIdleConnections == 0 {
		cfg.UpstreamHTTP.MaxIdleConnections = 4096
	}
	if cfg.UpstreamHTTP.MaxIdleConnectionsPerHost == 0 {
		cfg.UpstreamHTTP.MaxIdleConnectionsPerHost = 1024
	}
	if cfg.UpstreamHTTP.IdleConnectionTimeoutSecs == 0 {
		cfg.UpstreamHTTP.IdleConnectionTimeoutSecs = 90
	}
	if cfg.UpstreamHTTP.ResponseHeaderTimeoutSecs == 0 {
		cfg.UpstreamHTTP.ResponseHeaderTimeoutSecs = 60
	}
	if cfg.Observability.UsageBuffer == 0 {
		cfg.Observability.UsageBuffer = 8192
	}
	if cfg.Billing.Currency == "" {
		cfg.Billing.Currency = "usd"
	}
	if cfg.Billing.DefaultMaxOutputTokens == 0 {
		cfg.Billing.DefaultMaxOutputTokens = 4096
	}
	if cfg.Billing.MaxTopUpMinor == 0 {
		cfg.Billing.MaxTopUpMinor = 1000000
	}
	if cfg.Billing.MinTopUpMinor == 0 {
		cfg.Billing.MinTopUpMinor = 500
	}
	if cfg.Billing.Stripe.APIKeyEnv == "" {
		cfg.Billing.Stripe.APIKeyEnv = "AIGW_STRIPE_API_KEY"
	}
	if cfg.Billing.Stripe.WebhookSecretEnv == "" {
		cfg.Billing.Stripe.WebhookSecretEnv = "AIGW_STRIPE_WEBHOOK_SECRET"
	}
	for i := range cfg.Models {
		for j := range cfg.Models[i].Routes {
			if cfg.Models[i].Routes[j].Weight == 0 {
				cfg.Models[i].Routes[j].Weight = 1
			}
		}
	}
}

func resolveSecrets(cfg *Config) error {
	if cfg.ControlPlane.Enabled {
		cfg.ControlPlane.DatabaseURL = os.Getenv(cfg.ControlPlane.DatabaseURLEnv)
		cfg.ControlPlane.RedisURL = os.Getenv(cfg.ControlPlane.RedisURLEnv)
		cfg.ControlPlane.CredentialKey = os.Getenv(cfg.ControlPlane.CredentialKeyEnv)
	}
	if cfg.Admin.Enabled {
		cfg.Admin.Token = os.Getenv(cfg.Admin.TokenEnv)
	}
	if cfg.Billing.Enabled && cfg.Billing.Stripe.Enabled {
		cfg.Billing.Stripe.APIKey = os.Getenv(cfg.Billing.Stripe.APIKeyEnv)
		cfg.Billing.Stripe.WebhookSecret = os.Getenv(cfg.Billing.Stripe.WebhookSecretEnv)
	}
	for i := range cfg.Providers {
		provider := &cfg.Providers[i]
		if provider.APIKeyEnv == "" {
			continue
		}
		provider.APIKey = os.Getenv(provider.APIKeyEnv)
		if provider.APIKey == "" {
			return fmt.Errorf("provider %q: environment variable %s is empty", provider.ID, provider.APIKeyEnv)
		}
	}
	return nil
}

func Validate(cfg Config) error {
	if cfg.Server.MaxBodyBytes < 1024 {
		return errors.New("server.max_body_bytes must be at least 1024")
	}
	if cfg.Observability.UsageBuffer < 1 {
		return errors.New("observability.usage_buffer must be positive")
	}

	if cfg.ControlPlane.Enabled {
		if cfg.ControlPlane.DatabaseURL == "" {
			return fmt.Errorf("control_plane: environment variable %s is empty", cfg.ControlPlane.DatabaseURLEnv)
		}
		if cfg.ControlPlane.CredentialKey == "" {
			return fmt.Errorf("control_plane: environment variable %s is empty", cfg.ControlPlane.CredentialKeyEnv)
		}
		if cfg.ControlPlane.ReloadIntervalSeconds < 1 {
			return errors.New("control_plane.reload_interval_seconds must be positive")
		}
	}
	if cfg.Admin.Enabled {
		if !cfg.ControlPlane.Enabled {
			return errors.New("admin requires control_plane.enabled")
		}
		if cfg.Admin.Token == "" {
			return fmt.Errorf("admin: environment variable %s is empty", cfg.Admin.TokenEnv)
		}
		if !strings.HasPrefix(cfg.Admin.BasePath, "/") || cfg.Admin.BasePath == "/" {
			return errors.New("admin.base_path must start with / and cannot be /")
		}
	}
	if cfg.Billing.Enabled {
		if !cfg.ControlPlane.Enabled {
			return errors.New("billing requires control_plane.enabled")
		}
		if cfg.Auth.AllowAnonymous {
			return errors.New("billing cannot be enabled with auth.allow_anonymous")
		}
		if len(cfg.Billing.Currency) != 3 || strings.ToLower(cfg.Billing.Currency) != cfg.Billing.Currency {
			return errors.New("billing.currency must be a lowercase ISO 4217 code")
		}
		if cfg.Billing.DefaultMaxOutputTokens < 1 {
			return errors.New("billing.default_max_output_tokens must be positive")
		}
		if cfg.Billing.MinTopUpMinor < 1 || cfg.Billing.MaxTopUpMinor < cfg.Billing.MinTopUpMinor {
			return errors.New("billing top-up bounds are invalid")
		}
		if cfg.Billing.Stripe.Enabled {
			if cfg.Billing.Stripe.APIKey == "" {
				return fmt.Errorf("billing.stripe: environment variable %s is empty", cfg.Billing.Stripe.APIKeyEnv)
			}
			if cfg.Billing.Stripe.WebhookSecret == "" {
				return fmt.Errorf("billing.stripe: environment variable %s is empty", cfg.Billing.Stripe.WebhookSecretEnv)
			}
			if strings.TrimSpace(cfg.Billing.Stripe.SuccessURL) == "" || strings.TrimSpace(cfg.Billing.Stripe.CancelURL) == "" {
				return errors.New("billing.stripe.success_url and cancel_url are required")
			}
			for name, value := range map[string]string{"success_url": cfg.Billing.Stripe.SuccessURL, "cancel_url": cfg.Billing.Stripe.CancelURL} {
				parsed, err := url.Parse(value)
				if err != nil || parsed.Host == "" || (parsed.Scheme != "http" && parsed.Scheme != "https") {
					return fmt.Errorf("billing.stripe.%s must be an absolute http(s) URL", name)
				}
			}
		}
	}

	providers := make(map[string]ProviderConfig, len(cfg.Providers))
	for _, provider := range cfg.Providers {
		if provider.ID == "" {
			return errors.New("provider id is required")
		}
		if _, exists := providers[provider.ID]; exists {
			return fmt.Errorf("duplicate provider id %q", provider.ID)
		}
		if provider.Protocol != domain.ProtocolOpenAI && provider.Protocol != domain.ProtocolAnthropic {
			return fmt.Errorf("provider %q: unsupported protocol %q", provider.ID, provider.Protocol)
		}
		parsed, err := url.Parse(provider.BaseURL)
		if err != nil || parsed.Host == "" || (parsed.Scheme != "http" && parsed.Scheme != "https") {
			return fmt.Errorf("provider %q: base_url must be an absolute http(s) URL", provider.ID)
		}
		if provider.APIKeyEnv == "" {
			return fmt.Errorf("provider %q: api_key_env is required", provider.ID)
		}
		providers[provider.ID] = provider
	}
	if len(providers) == 0 && !cfg.ControlPlane.Enabled {
		return errors.New("at least one provider is required")
	}

	models := make(map[string]struct{}, len(cfg.Models))
	for _, model := range cfg.Models {
		if strings.TrimSpace(model.ID) == "" {
			return errors.New("model id is required")
		}
		if _, exists := models[model.ID]; exists {
			return fmt.Errorf("duplicate model id %q", model.ID)
		}
		models[model.ID] = struct{}{}
		if model.InputPriceMicrosPerMillion < 0 || model.OutputPriceMicrosPerMillion < 0 || model.CacheReadPriceMicrosPerMillion < 0 || model.CacheWritePriceMicrosPerMillion < 0 {
			return fmt.Errorf("model %q: prices cannot be negative", model.ID)
		}
		if len(model.Routes) == 0 {
			return fmt.Errorf("model %q: at least one route is required", model.ID)
		}
		for _, route := range model.Routes {
			if _, exists := providers[route.Provider]; !exists {
				return fmt.Errorf("model %q: unknown provider %q", model.ID, route.Provider)
			}
			if route.UpstreamModel == "" {
				return fmt.Errorf("model %q: upstream_model is required", model.ID)
			}
			if route.Priority < 0 {
				return fmt.Errorf("model %q: route priority cannot be negative", model.ID)
			}
			if route.Weight < 1 || route.Weight > 100 {
				return fmt.Errorf("model %q: route weight must be between 1 and 100", model.ID)
			}
		}
	}
	if len(models) == 0 && !cfg.ControlPlane.Enabled {
		return errors.New("at least one model is required")
	}
	return nil
}

func (c ServerConfig) ReadHeaderTimeout() time.Duration {
	return time.Duration(c.ReadHeaderTimeoutSecs) * time.Second
}

func (c ServerConfig) IdleTimeout() time.Duration {
	return time.Duration(c.IdleTimeoutSecs) * time.Second
}

func (c ServerConfig) ShutdownTimeout() time.Duration {
	return time.Duration(c.ShutdownTimeoutSecs) * time.Second
}