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
|
package main
import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"aigw/internal/adminapi"
"aigw/internal/auth"
"aigw/internal/billing"
"aigw/internal/catalog"
"aigw/internal/config"
"aigw/internal/controlplane"
"aigw/internal/httpapi"
"aigw/internal/limits"
"aigw/internal/mailer"
"aigw/internal/provider"
"aigw/internal/routing"
"aigw/internal/telemetry"
"github.com/go-webauthn/webauthn/webauthn"
)
func main() {
configPath := flag.String("config", "config.json", "path to the gateway configuration")
flag.Parse()
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
cfg, err := config.Load(*configPath)
if err != nil {
logger.Error("configuration_failed", "error", err)
os.Exit(1)
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
if err := run(ctx, cfg, logger); err != nil {
logger.Error("gateway_stopped", "error", err)
os.Exit(1)
}
}
func run(ctx context.Context, cfg config.Config, logger *slog.Logger) error {
metrics := &telemetry.Metrics{}
usageSink := telemetry.NewAsyncUsageLogger(logger, metrics, cfg.Observability.UsageBuffer)
defer func() {
closeContext, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := usageSink.Close(closeContext); err != nil {
logger.Warn("usage_sink_close_failed", "error", err)
}
}()
var authenticator *auth.StaticAuthenticator
var modelCatalog *catalog.Catalog
var store *controlplane.Store
var manager *controlplane.Manager
var managerCancel context.CancelFunc
var managerDone chan struct{}
var requestLimiter *limits.Limiter
var webAuthn *webauthn.WebAuthn
if cfg.ControlPlane.Enabled {
var err error
store, err = controlplane.NewStore(ctx, controlplane.Options{
DatabaseURL: cfg.ControlPlane.DatabaseURL, RedisURL: cfg.ControlPlane.RedisURL,
CredentialKey: cfg.ControlPlane.CredentialKey, RedisChannel: cfg.ControlPlane.RedisChannel,
VersionCacheKey: cfg.ControlPlane.SnapshotCacheKey,
})
if err != nil {
return err
}
defer store.Close()
if cfg.ControlPlane.AutoMigrate {
if err := store.Migrate(ctx); err != nil {
return err
}
}
authenticator = auth.NewDynamic(nil, cfg.Auth.AllowAnonymous)
modelCatalog = catalog.NewModels(nil)
requestLimiter = limits.New(cfg.ControlPlane.RedisURL, "aigw:limits", cfg.Billing.DefaultMaxOutputTokens, logger)
defer requestLimiter.Close()
manager = controlplane.NewManager(store, modelCatalog, authenticator, logger,
time.Duration(cfg.ControlPlane.ReloadIntervalSeconds)*time.Second, requestLimiter)
if _, err := manager.Reload(ctx); err != nil {
return fmt.Errorf("load initial control-plane snapshot: %w", err)
}
managerContext, cancel := context.WithCancel(ctx)
managerCancel = cancel
managerDone = make(chan struct{})
go func() {
defer close(managerDone)
manager.Run(managerContext)
}()
defer func() {
managerCancel()
select {
case <-managerDone:
case <-time.After(3 * time.Second):
logger.Warn("control_plane_shutdown_timed_out")
}
}()
} else {
var err error
authenticator, err = auth.NewStatic(os.Getenv(cfg.Auth.KeysEnv), cfg.Auth.AllowAnonymous)
if err != nil {
return err
}
modelCatalog = catalog.New(cfg)
}
if cfg.Admin.Enabled && cfg.Admin.WebAuthn.Enabled {
configured, err := webauthn.New(&webauthn.Config{
RPDisplayName: cfg.Admin.WebAuthn.RPDisplayName,
RPID: cfg.Admin.WebAuthn.RPID,
RPOrigins: cfg.Admin.WebAuthn.Origins,
EncodeUserIDAsString: true,
Timeouts: webauthn.TimeoutsConfig{
Login: webauthn.TimeoutConfig{Enforce: true},
Registration: webauthn.TimeoutConfig{Enforce: true},
},
})
if err != nil {
return fmt.Errorf("configure WebAuthn: %w", err)
}
webAuthn = configured
}
if cfg.Admin.Enabled && cfg.Admin.Mail.Enabled {
sender, err := mailer.NewSender(mailer.SMTPConfig{
Address: cfg.Admin.Mail.SMTPAddress, Username: cfg.Admin.Mail.SMTPUsername,
Password: cfg.Admin.Mail.SMTPPassword, FromName: cfg.Admin.Mail.FromName,
FromAddress: cfg.Admin.Mail.FromAddress, TLSMode: cfg.Admin.Mail.TLSMode,
})
if err != nil {
return fmt.Errorf("configure SMTP: %w", err)
}
go mailer.NewWorker(store, sender, logger).Run(ctx)
}
var billingService *billing.Service
if cfg.Billing.Enabled {
var err error
billingService, err = billing.New(ctx, billing.Options{
DatabaseURL: cfg.ControlPlane.DatabaseURL, Currency: cfg.Billing.Currency,
DefaultMaxOutputTokens: cfg.Billing.DefaultMaxOutputTokens,
MinTopUpMinor: cfg.Billing.MinTopUpMinor, MaxTopUpMinor: cfg.Billing.MaxTopUpMinor,
StripeEnabled: cfg.Billing.Stripe.Enabled, StripeAPIKey: cfg.Billing.Stripe.APIKey,
StripeWebhookSecret: cfg.Billing.Stripe.WebhookSecret,
StripeSuccessURL: cfg.Billing.Stripe.SuccessURL, StripeCancelURL: cfg.Billing.Stripe.CancelURL,
})
if err != nil {
return err
}
defer billingService.Close()
}
var billingMeter billing.Meter
if billingService != nil {
billingMeter = billingService
}
inferenceAPI := httpapi.New(httpapi.Options{
Authenticator: authenticator,
Catalog: modelCatalog,
Router: routing.New(modelCatalog),
Forwarder: provider.New(cfg.UpstreamHTTP, metrics),
UsageSink: usageSink,
BillingMeter: billingMeter,
Limiter: requestLimiter,
UsageRecorder: store,
Metrics: metrics,
Logger: logger,
MaxBodyBytes: cfg.Server.MaxBodyBytes,
ExposeMetrics: cfg.Observability.ExposeMetrics,
})
root := http.NewServeMux()
root.Handle("/", inferenceAPI.Handler())
if cfg.Admin.Enabled {
adminHandler := adminapi.New(adminapi.Options{
Store: store, Manager: manager, Billing: billingService, Token: cfg.Admin.Token,
Logger: logger, Prefix: cfg.Admin.BasePath, RegistrationEnabled: cfg.Admin.RegistrationEnabled,
SessionTTL: time.Duration(cfg.Admin.SessionTTLHours) * time.Hour, Currency: cfg.Billing.Currency,
PublicURL: cfg.Admin.PublicURL, WebAuthn: webAuthn, MailEnabled: cfg.Admin.Mail.Enabled,
}).Handler()
root.Handle(cfg.Admin.BasePath, adminHandler)
root.Handle(cfg.Admin.BasePath+"/", adminHandler)
}
if billingService != nil && billingService.StripeEnabled() {
root.Handle("/billing/stripe/webhook", billingService.WebhookHandler())
}
server := &http.Server{
Addr: cfg.Server.Address, Handler: root,
ReadHeaderTimeout: cfg.Server.ReadHeaderTimeout(),
IdleTimeout: cfg.Server.IdleTimeout(),
}
errCh := make(chan error, 1)
go func() {
logger.Info("gateway_listening", "address", cfg.Server.Address, "control_plane", cfg.ControlPlane.Enabled,
"billing", cfg.Billing.Enabled, "stripe", cfg.Billing.Stripe.Enabled)
errCh <- server.ListenAndServe()
}()
select {
case <-ctx.Done():
shutdownContext, cancel := context.WithTimeout(context.Background(), cfg.Server.ShutdownTimeout())
defer cancel()
if err := server.Shutdown(shutdownContext); err != nil {
return fmt.Errorf("shutdown HTTP server: %w", err)
}
return nil
case err := <-errCh:
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return fmt.Errorf("serve HTTP: %w", err)
}
}
|