droboticflow/cmd/api/main.go

140 lines
4.1 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"droboticflow/internal/ai"
"droboticflow/internal/api"
"droboticflow/internal/config"
"droboticflow/internal/retry"
"droboticflow/internal/store"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func connectMongo(ctx context.Context, mongoURI string, attempts int, delay time.Duration) (*mongo.Client, error) {
return retry.Do(ctx, attempts, delay, "mongodb connection", func(ctx context.Context, _ int) (*mongo.Client, error) {
client, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoURI))
if err != nil {
return nil, err
}
if err := client.Ping(ctx, nil); err != nil {
_ = client.Disconnect(ctx)
return nil, err
}
return client, nil
})
}
func spaHandler(apiHandler http.Handler, distDir string) http.Handler {
fileServer := http.FileServer(http.Dir(distDir))
indexPath := filepath.Join(distDir, "index.html")
serveIndex := func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Cache-Control", "no-store")
writer.Header().Set("Pragma", "no-cache")
writer.Header().Set("Expires", "0")
http.ServeFile(writer, request, indexPath)
}
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
if strings.HasPrefix(request.URL.Path, "/api/") || strings.HasPrefix(request.URL.Path, "/worker-api/") {
apiHandler.ServeHTTP(writer, request)
return
}
if request.URL.Path == "/" {
serveIndex(writer, request)
return
}
targetPath := filepath.Join(distDir, filepath.Clean(request.URL.Path))
if _, err := os.Stat(targetPath); err == nil {
if strings.HasPrefix(request.URL.Path, "/assets/") {
writer.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
}
fileServer.ServeHTTP(writer, request)
return
}
if strings.HasPrefix(request.URL.Path, "/assets/") {
writer.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0")
http.NotFound(writer, request)
return
}
serveIndex(writer, request)
})
}
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
cfg, err := config.LoadValidated()
if err != nil {
fmt.Printf("[api] invalid configuration: %v\n", err)
os.Exit(1)
}
client, err := connectMongo(ctx, cfg.MongoURI, cfg.MongoConnectRetries, time.Duration(cfg.MongoConnectRetryDelayMS)*time.Millisecond)
if err != nil {
fmt.Printf("[api] failed to connect mongo: %v\n", err)
os.Exit(1)
}
defer func() {
_ = client.Disconnect(context.Background())
}()
dataStore := store.NewMongoStore(client.Database(cfg.MongoDB))
if err := dataStore.RunMigrations(ctx); err != nil {
fmt.Printf("[api] failed to run mongo migrations: %v\n", err)
os.Exit(1)
}
if err := dataStore.EnsureIndexes(ctx); err != nil {
fmt.Printf("[api] failed to ensure mongo indexes: %v\n", err)
os.Exit(1)
}
if _, err := dataStore.EnsureDefaultOrganization(ctx); err != nil {
fmt.Printf("[api] failed to ensure default organization: %v\n", err)
os.Exit(1)
}
aiService := ai.NewService(cfg.AIAPIBaseURL, cfg.AIAPIKey, cfg.AIModel)
handler := spaHandler(api.NewHandlerWithConfig(dataStore, aiService, cfg), cfg.DistDir)
server := &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%d", cfg.Port),
Handler: handler,
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 2 * time.Minute,
IdleTimeout: 2 * time.Minute,
}
fmt.Printf("[api] listening on http://0.0.0.0:%d\n", cfg.Port)
serverErrors := make(chan error, 1)
go func() {
serverErrors <- server.ListenAndServe()
}()
select {
case err := <-serverErrors:
if err != nil && !errors.Is(err, http.ErrServerClosed) {
fmt.Printf("[api] failed to start: %v\n", err)
os.Exit(1)
}
case <-ctx.Done():
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
fmt.Println("[api] shutting down")
if err := server.Shutdown(shutdownCtx); err != nil {
fmt.Printf("[api] graceful shutdown failed: %v\n", err)
_ = server.Close()
os.Exit(1)
}
}
}