forked from mtusi2026/mtusi2026lab4
feat:lab3-catchup
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/src/api"
|
||||
"mtusi-messenger/src/config"
|
||||
"mtusi-messenger/src/domain"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg := config.Load()
|
||||
if cfg.DatabaseURL == "" {
|
||||
log.Fatal("DATABASE_URL is required (env DATABASE_URL or DATABASE_URL_FILE)")
|
||||
}
|
||||
|
||||
rootCtx, cancelRoot := context.WithCancel(context.Background())
|
||||
defer cancelRoot()
|
||||
|
||||
store, err := domain.NewStore(rootCtx, cfg.DatabaseURL)
|
||||
if err != nil {
|
||||
log.Fatalf("postgres: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
// Кэш сессий в Redis/Valkey. Если CACHE_URL не задан — работаем без кэша.
|
||||
var cache *domain.SessionCache
|
||||
if cfg.CacheURL != "" {
|
||||
cache, err = domain.NewSessionCache(rootCtx, cfg.CacheURL)
|
||||
if err != nil {
|
||||
if cfg.RedisRequired {
|
||||
log.Fatalf("redis required but unavailable: %v", err)
|
||||
}
|
||||
log.Printf("redis unavailable, continuing without session cache: %v", err)
|
||||
cache = nil
|
||||
} else {
|
||||
defer cache.Close()
|
||||
}
|
||||
} else if cfg.RedisRequired {
|
||||
log.Fatal("SESSION_STORE=redis but CACHE_URL is not configured")
|
||||
}
|
||||
|
||||
sessions := domain.NewSessionStore(store, cache, cfg.SessionTTL)
|
||||
handler := &api.Handler{Store: store, Sessions: sessions}
|
||||
router := api.NewRouter(handler, cfg.InstanceID)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
|
||||
Handler: router,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
|
||||
|
||||
go func() {
|
||||
log.Printf("messenger listening on %s (env=%s, session_ttl=%s)", srv.Addr, cfg.Env, cfg.SessionTTL)
|
||||
log.Printf("instance_id=%s", cfg.InstanceID)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Fatalf("server error: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
<-stop
|
||||
log.Println("shutting down...")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
_ = srv.Shutdown(ctx)
|
||||
log.Println("stopped")
|
||||
}
|
||||
Reference in New Issue
Block a user