Files
mtusi2026lab4/cmd/server/main.go

241 lines
6.5 KiB
Go

package main
import (
"context"
"encoding/json"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"mtusi2026lab2/internal/handler"
"mtusi2026lab2/internal/middleware"
"mtusi2026lab2/internal/storage"
)
func main() {
databaseURL := os.Getenv("DATABASE_URL")
if databaseURL == "" {
log.Fatal("DATABASE_URL is required")
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
pool, err := storage.NewPostgresPool(ctx, databaseURL)
if err != nil {
log.Fatalf("PostgreSQL connection failed: %v", err)
}
defer pool.Close()
if os.Getenv("RUN_MIGRATIONS_ONLY") == "1" {
if err := storage.ApplyMigrations(ctx, pool); err != nil {
log.Fatalf("database migrations failed: %v", err)
}
log.Println("database migrations applied; exiting")
return
}
if os.Getenv("RUN_MIGRATIONS_ON_START") == "1" {
if err := storage.ApplyMigrations(ctx, pool); err != nil {
log.Fatalf("database migrations failed: %v", err)
}
log.Println("database migrations applied")
}
var cache *storage.SessionCache
redisURL := os.Getenv("REDIS_URL")
if redisURL != "" {
cache, err = storage.NewSessionCache(redisURL)
if err != nil {
log.Printf("Redis configuration error: %v", err)
} else {
defer cache.Close()
pingCtx, pingCancel := context.WithTimeout(
context.Background(), 2*time.Second,
)
pingErr := cache.Ping(pingCtx)
pingCancel()
if pingErr != nil {
log.Printf("Redis unavailable, PostgreSQL fallback: %v", pingErr)
} else {
log.Println("Redis connected")
}
}
}
authStore := storage.NewAuthStore(pool)
sessionService := storage.NewSessionService(authStore, cache)
chatStore := storage.NewChatStore(pool)
messageStore := storage.NewMessageStore(pool)
s3, err := storage.NewS3Client()
if err != nil {
log.Fatalf("S3 configuration: %v", err)
}
attachmentHandler := &handler.AttachmentHandler{Chats: chatStore, Attachments: storage.NewAttachmentStore(pool), S3: s3}
userHandler := handler.NewUserHandler(authStore)
sessionHandler := handler.NewSessionHandler(authStore, sessionService)
chatHandler := handler.NewChatHandler(chatStore)
messageHandler := handler.NewMessageHandler(chatStore, messageStore)
mux := http.NewServeMux()
mux.HandleFunc("GET /health/live", func(w http.ResponseWriter, r *http.Request) {
writeHealthOK(w)
})
mux.HandleFunc("GET /health/ready", func(w http.ResponseWriter, r *http.Request) {
pingCtx, pingCancel := context.WithTimeout(
r.Context(), 2*time.Second,
)
defer pingCancel()
if err := pool.Ping(pingCtx); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusServiceUnavailable)
_ = json.NewEncoder(w).Encode(map[string]any{
"error": map[string]string{
"code": "unavailable",
"message": "database unavailable",
"request_id": middleware.GetRequestID(r.Context()),
},
})
return
}
if err := s3.Ready(pingCtx); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(503)
_ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]string{"code": "unavailable", "message": "object storage unavailable", "request_id": middleware.GetRequestID(r.Context())}})
return
}
writeHealthOK(w)
})
// Public routes.
mux.HandleFunc("POST /api/v1/users", userHandler.Create)
mux.HandleFunc("POST /api/v1/auth/sessions", sessionHandler.Create)
// Protected routes.
auth := middleware.Auth(sessionService)
mux.Handle(
"DELETE /api/v1/auth/sessions/current",
auth(http.HandlerFunc(sessionHandler.Delete)),
)
mux.Handle(
"GET /api/v1/users/me",
auth(http.HandlerFunc(userHandler.Me)),
)
mux.Handle(
"POST /api/v1/chats",
auth(http.HandlerFunc(chatHandler.Create)),
)
mux.Handle(
"GET /api/v1/chats",
auth(http.HandlerFunc(chatHandler.List)),
)
mux.Handle(
"GET /api/v1/chats/{chat_id}",
auth(http.HandlerFunc(chatHandler.Get)),
)
mux.Handle(
"POST /api/v1/chats/{chat_id}/messages",
auth(http.HandlerFunc(messageHandler.Create)),
)
mux.Handle("POST /api/v1/chats/{chat_id}/attachments", auth(http.HandlerFunc(attachmentHandler.Upload)))
mux.Handle("GET /api/v1/attachments/{id}", auth(http.HandlerFunc(attachmentHandler.Metadata)))
mux.Handle("GET /api/v1/attachments/{id}/content", auth(http.HandlerFunc(attachmentHandler.Content)))
mux.Handle(
"GET /api/v1/chats/{chat_id}/messages",
auth(http.HandlerFunc(messageHandler.List)),
)
host := os.Getenv("APP_HOST")
if host == "" {
host = "0.0.0.0"
}
port := os.Getenv("APP_PORT")
if port == "" {
port = "8080"
}
server := &http.Server{
Addr: host + ":" + port,
Handler: middleware.RequestID(instanceHeader(databaseDeadline(mux))),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 25 * time.Second,
IdleTimeout: 60 * time.Second,
}
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(stop)
go func() {
log.Printf("server started on %s", server.Addr)
if err := server.ListenAndServe(); err != nil &&
!errors.Is(err, http.ErrServerClosed) {
log.Printf("server error: %v", err)
stop <- syscall.SIGTERM
}
}()
sig := <-stop
log.Printf("shutdown signal received: %s", sig)
shutdownCtx, shutdownCancel := context.WithTimeout(
context.Background(), 8*time.Second,
)
defer shutdownCancel()
if err := server.Shutdown(shutdownCtx); err != nil {
log.Printf("graceful shutdown failed: %v", err)
_ = server.Close()
}
log.Println("server stopped")
}
func writeHealthOK(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"ok"}`))
}
// databaseDeadline bounds every API request, including queries on already-open
// PostgreSQL connections. The handler maps context/driver errors to HTTP 503.
func databaseDeadline(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/health/live" {
next.ServeHTTP(w, r)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// instanceHeader identifies the real API process behind the load balancer.
func instanceHeader(next http.Handler) http.Handler {
id := os.Getenv("INSTANCE_ID")
if id == "" {
id = "api-unknown"
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Instance-Id", id)
next.ServeHTTP(w, r)
})
}