forked from mtusi2026/mtusi2026lab4
239 lines
7.5 KiB
Go
239 lines
7.5 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"strconv"
|
|
"syscall"
|
|
"time"
|
|
|
|
"mtusi2026lab4-fork/src/internal/handler"
|
|
"mtusi2026lab4-fork/src/internal/session"
|
|
"mtusi2026lab4-fork/src/internal/storage"
|
|
"mtusi2026lab4-fork/src/internal/store"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/go-chi/chi/v5/middleware"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
// instanceID — уникальный идентификатор реплики.
|
|
// Источник — hostname контейнера Docker, поэтому две реплики всегда дают разные значения.
|
|
var instanceID = func() string {
|
|
if v := os.Getenv("INSTANCE_ID"); v != "" {
|
|
return v
|
|
}
|
|
if h, err := os.Hostname(); err == nil && h != "" {
|
|
return h
|
|
}
|
|
return "unknown"
|
|
}()
|
|
|
|
func RequestIDMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
requestID := uuid.New().String()
|
|
w.Header().Set("X-Request-Id", requestID)
|
|
ctx := context.WithValue(r.Context(), handler.RequestIDKey, requestID)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
// InstanceIDMiddleware добавляет X-Instance-Id во все ответы.
|
|
func InstanceIDMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("X-Instance-Id", instanceID)
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func main() {
|
|
dbURL := os.Getenv("DATABASE_URL")
|
|
if dbURL == "" {
|
|
dbURL = "postgres://lab4:lab4@postgres:5432/lab4?sslmode=disable&timezone=UTC"
|
|
}
|
|
|
|
log.Printf("INFO: [%s] connecting to PostgreSQL...", instanceID)
|
|
pgStore, err := store.NewPostgres(dbURL)
|
|
if err != nil {
|
|
log.Fatalf("ERROR: [%s] failed to connect to database: %v", instanceID, err)
|
|
}
|
|
defer pgStore.Close()
|
|
log.Printf("INFO: [%s] PostgreSQL connected, migrations applied", instanceID)
|
|
|
|
redisURL := os.Getenv("REDIS_URL")
|
|
if redisURL == "" {
|
|
redisURL = "redis://redis:6379/0"
|
|
}
|
|
|
|
sessionTTL := 24 * time.Hour
|
|
if s := os.Getenv("SESSION_TTL_SECONDS"); s != "" {
|
|
if secs, err := strconv.Atoi(s); err == nil && secs > 0 {
|
|
sessionTTL = time.Duration(secs) * time.Second
|
|
}
|
|
}
|
|
|
|
log.Printf("INFO: [%s] connecting to Redis (TTL=%v)...", instanceID, sessionTTL)
|
|
redisStore, err := session.NewRedisStore(redisURL, sessionTTL)
|
|
if err != nil {
|
|
log.Fatalf("ERROR: [%s] failed to connect to Redis: %v", instanceID, err)
|
|
}
|
|
defer redisStore.Close()
|
|
log.Printf("INFO: [%s] Redis connected", instanceID)
|
|
|
|
s3Cfg := storage.ConfigFromEnv()
|
|
log.Printf("INFO: [%s] connecting to S3 endpoint=%s bucket=%s...", instanceID, s3Cfg.Endpoint, s3Cfg.Bucket)
|
|
s3Client, err := storage.NewClient(s3Cfg)
|
|
if err != nil {
|
|
log.Fatalf("ERROR: [%s] failed to connect to S3: %v", instanceID, err)
|
|
}
|
|
log.Printf("INFO: [%s] S3 connected", instanceID)
|
|
|
|
h := handler.New(pgStore, redisStore, s3Client, sessionTTL)
|
|
|
|
reconcilerCtx, reconcilerCancel := context.WithCancel(context.Background())
|
|
defer reconcilerCancel()
|
|
|
|
go runAttachmentReconciler(reconcilerCtx, pgStore, s3Client, s3Cfg.Grace)
|
|
|
|
r := chi.NewRouter()
|
|
r.Use(InstanceIDMiddleware)
|
|
r.Use(RequestIDMiddleware)
|
|
r.Use(middleware.RealIP)
|
|
r.Use(middleware.Recoverer)
|
|
r.Use(func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
next.ServeHTTP(w, r)
|
|
rid, _ := r.Context().Value(handler.RequestIDKey).(string)
|
|
log.Printf("INFO: [%s] %s %s %v [request_id=%s]", instanceID, r.Method, r.URL.Path, time.Since(start), rid)
|
|
})
|
|
})
|
|
|
|
r.Get("/health/live", h.HealthLive)
|
|
r.Get("/health/ready", h.HealthReady)
|
|
|
|
r.Route("/api/v1", func(r chi.Router) {
|
|
r.Post("/users", h.CreateUser)
|
|
r.Post("/auth/sessions", h.CreateSession)
|
|
|
|
r.Group(func(r chi.Router) {
|
|
r.Use(h.BearerAuthMiddleware)
|
|
|
|
r.Delete("/auth/sessions/current", h.DeleteSession)
|
|
r.Get("/users/me", h.GetMe)
|
|
|
|
r.Get("/chats", h.ListChats)
|
|
r.Post("/chats", h.CreateChat)
|
|
r.Get("/chats/{chat_id}", h.GetChat)
|
|
|
|
r.Post("/chats/{chat_id}/messages", h.SendMessage)
|
|
r.Get("/chats/{chat_id}/messages", h.GetMessages)
|
|
|
|
// Лабораторная 4: вложения.
|
|
r.Post("/chats/{chat_id}/attachments", h.UploadAttachment)
|
|
r.Get("/attachments/{attachment_id}", h.GetAttachment)
|
|
r.Get("/attachments/{attachment_id}/content", h.DownloadAttachment)
|
|
})
|
|
})
|
|
|
|
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
|
|
rid, _ := r.Context().Value(handler.RequestIDKey).(string)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusNotFound)
|
|
_, _ = w.Write([]byte(`{"error":{"code":"not_found","message":"Not Found","request_id":"` + rid + `"}}`))
|
|
})
|
|
|
|
port := os.Getenv("PORT")
|
|
if port == "" {
|
|
port = "8080"
|
|
}
|
|
|
|
srv := &http.Server{
|
|
Addr: "0.0.0.0:" + port,
|
|
Handler: r,
|
|
ReadHeaderTimeout: 10 * time.Second,
|
|
// Для лабы 4 нужны загрузки до 10 MiB, поэтому read/write timeout увеличены.
|
|
ReadTimeout: 60 * time.Second,
|
|
WriteTimeout: 60 * time.Second,
|
|
IdleTimeout: 120 * time.Second,
|
|
}
|
|
|
|
go func() {
|
|
log.Printf("INFO: [%s] server starting on port %s", instanceID, port)
|
|
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
log.Fatalf("ERROR: [%s] server failed: %v", instanceID, err)
|
|
}
|
|
}()
|
|
|
|
quit := make(chan os.Signal, 1)
|
|
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
|
<-quit
|
|
|
|
log.Printf("INFO: [%s] shutting down...", instanceID)
|
|
|
|
// Останавливаем reconciler, чтобы он не работал во время shutdown.
|
|
reconcilerCancel()
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
|
|
defer cancel()
|
|
|
|
srv.SetKeepAlivesEnabled(false)
|
|
if err := srv.Shutdown(ctx); err != nil {
|
|
log.Fatalf("ERROR: [%s] forced shutdown: %v", instanceID, err)
|
|
}
|
|
|
|
log.Printf("INFO: [%s] exited properly", instanceID)
|
|
}
|
|
|
|
// runAttachmentReconciler чистит зависшие uploading-вложения.
|
|
//
|
|
// Это нужно для уровня 4: если процесс умер между S3 PUT и PostgreSQL UPDATE,
|
|
// в S3 может остаться объект, а в БД — строка status='uploading'.
|
|
// Reconciler спустя grace period помечает такие записи failed, удаляет объект
|
|
// из S3 и затем удаляет строку метаданных.
|
|
func runAttachmentReconciler(ctx context.Context, st store.Store, cl *storage.Client, grace time.Duration) {
|
|
ticker := time.NewTicker(30 * time.Second)
|
|
defer ticker.Stop()
|
|
|
|
log.Printf("INFO: [%s] attachment reconciler started, grace=%v", instanceID, grace)
|
|
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
log.Printf("INFO: [%s] attachment reconciler stopped", instanceID)
|
|
return
|
|
case <-ticker.C:
|
|
cutoff := time.Now().Add(-grace)
|
|
|
|
items, err := st.ClaimStaleUploading(ctx, cutoff)
|
|
if err != nil {
|
|
log.Printf("ERROR: [%s] reconciler claim stale uploading: %v", instanceID, err)
|
|
continue
|
|
}
|
|
|
|
if len(items) == 0 {
|
|
continue
|
|
}
|
|
|
|
log.Printf("INFO: [%s] reconciler found %d stale uploading attachments", instanceID, len(items))
|
|
|
|
for _, a := range items {
|
|
if err := cl.DeleteObject(ctx, a.ObjectKey); err != nil {
|
|
log.Printf("ERROR: [%s] reconciler delete object %s: %v", instanceID, a.ObjectKey, err)
|
|
continue
|
|
}
|
|
|
|
if err := st.DeleteFailedStaleAttachment(ctx, a.ID); err != nil {
|
|
log.Printf("ERROR: [%s] reconciler delete stale attachment row %s: %v", instanceID, a.ID, err)
|
|
continue
|
|
}
|
|
|
|
log.Printf("INFO: [%s] reconciler cleaned stale attachment %s object=%s", instanceID, a.ID, a.ObjectKey)
|
|
}
|
|
}
|
|
}
|
|
}
|