143 lines
3.9 KiB
Go
143 lines
3.9 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"messenger/internal/handler"
|
|
"messenger/internal/store"
|
|
)
|
|
|
|
func getEnv(key, defaultVal string) string {
|
|
if val := strings.TrimSpace(os.Getenv(key)); val != "" {
|
|
return val
|
|
}
|
|
return defaultVal
|
|
}
|
|
|
|
func getEnvInt(key string, defaultVal int) int {
|
|
if val := strings.TrimSpace(os.Getenv(key)); val != "" {
|
|
if n, err := strconv.Atoi(val); err == nil {
|
|
return n
|
|
}
|
|
}
|
|
return defaultVal
|
|
}
|
|
|
|
func resolveSecretOrEnv(fileEnvKey, directEnvKey, defaultVal string) string {
|
|
if filePath := strings.TrimSpace(os.Getenv(fileEnvKey)); filePath != "" {
|
|
if data, err := os.ReadFile(filePath); err == nil {
|
|
if trimmed := strings.TrimSpace(string(data)); trimmed != "" {
|
|
return trimmed
|
|
}
|
|
}
|
|
}
|
|
if direct := strings.TrimSpace(os.Getenv(directEnvKey)); direct != "" {
|
|
return direct
|
|
}
|
|
return defaultVal
|
|
}
|
|
|
|
func main() {
|
|
migrateOnly := flag.Bool("migrate-only", false, "Run database migrations and exit")
|
|
flag.Parse()
|
|
|
|
host := getEnv("APP_HOST", "0.0.0.0")
|
|
port := getEnv("APP_PORT", "8080")
|
|
appEnv := getEnv("APP_ENV", "lab")
|
|
sessionTTL := getEnvInt("SESSION_TTL_SECONDS", 3600)
|
|
maxConns := int32(getEnvInt("DB_MAX_CONNS", 25))
|
|
minConns := int32(getEnvInt("DB_MIN_CONNS", 4))
|
|
queryTimeoutMs := getEnvInt("DB_QUERY_TIMEOUT_MS", 5000)
|
|
cacheMode := getEnv("CACHE_MODE", "write_through_versioned")
|
|
migrationsPath := getEnv("MIGRATIONS_PATH", "migrations/001_init.sql")
|
|
|
|
dbURL := resolveSecretOrEnv("DATABASE_URL_FILE", "DATABASE_URL", "postgres://messenger:messenger_lab2_pass@localhost:5432/messenger?sslmode=disable")
|
|
cacheURL := resolveSecretOrEnv("CACHE_URL_FILE", "CACHE_URL", "redis://localhost:6379/0")
|
|
|
|
sqlBytes, err := os.ReadFile(migrationsPath)
|
|
if err != nil {
|
|
log.Fatalf("Failed to read migration file %s: %v", migrationsPath, err)
|
|
}
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
st, err := store.NewPostgresStore(ctx, store.Config{
|
|
DatabaseURL: dbURL,
|
|
CacheURL: cacheURL,
|
|
MaxConns: maxConns,
|
|
MinConns: minConns,
|
|
QueryTimeout: time.Duration(queryTimeoutMs) * time.Millisecond,
|
|
CacheMode: cacheMode,
|
|
})
|
|
if err != nil {
|
|
log.Fatalf("Failed to initialize store: %v", err)
|
|
}
|
|
defer st.Close()
|
|
|
|
// Wait for PostgreSQL to accept connections and apply migrations idempotently
|
|
var migErr error
|
|
for attempt := 1; attempt <= 30; attempt++ {
|
|
migErr = st.RunMigrations(ctx, "001_init.sql", string(sqlBytes))
|
|
if migErr == nil {
|
|
break
|
|
}
|
|
log.Printf("Waiting for PostgreSQL to apply migrations (attempt %d/30): %v", attempt, migErr)
|
|
select {
|
|
case <-ctx.Done():
|
|
log.Fatalf("Interrupted while waiting for database migrations")
|
|
case <-time.After(1 * time.Second):
|
|
}
|
|
}
|
|
if migErr != nil {
|
|
log.Fatalf("Could not apply database migrations after 30 attempts: %v", migErr)
|
|
}
|
|
|
|
if *migrateOnly {
|
|
log.Println("Migrate-only flag set; exiting 0.")
|
|
return
|
|
}
|
|
|
|
h := handler.RegisterRoutes(st, sessionTTL)
|
|
|
|
addr := fmt.Sprintf("%s:%s", host, port)
|
|
srv := &http.Server{
|
|
Addr: addr,
|
|
Handler: h,
|
|
ReadHeaderTimeout: 5 * time.Second,
|
|
ReadTimeout: 15 * time.Second,
|
|
WriteTimeout: 15 * time.Second,
|
|
IdleTimeout: 60 * time.Second,
|
|
}
|
|
|
|
go func() {
|
|
log.Printf("Starting messenger server (Lab 2) on %s (env=%s, sessionTTL=%ds, cacheMode=%s)", addr, appEnv, sessionTTL, cacheMode)
|
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
log.Fatalf("ListenAndServe error: %v", err)
|
|
}
|
|
}()
|
|
|
|
<-ctx.Done()
|
|
log.Println("Received termination signal, starting graceful shutdown...")
|
|
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
if err := srv.Shutdown(shutdownCtx); err != nil {
|
|
log.Printf("Server shutdown error: %v", err)
|
|
} else {
|
|
log.Println("Server stopped gracefully")
|
|
}
|
|
}
|