forked from mtusi2026/mtusi2026lab6
226 lines
7.2 KiB
Go
226 lines
7.2 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"backend/db"
|
|
"backend/internal/adapter/handler"
|
|
"backend/internal/adapter/password"
|
|
"backend/internal/adapter/repository/postgres"
|
|
"backend/internal/adapter/storage"
|
|
"backend/internal/adapter/telemetry"
|
|
"backend/internal/application/usecase"
|
|
"backend/internal/config"
|
|
"backend/pkg/logger"
|
|
"backend/pkg/server"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
func main() {
|
|
healthcheck := flag.Bool("healthcheck", false, "проверить /health/ready и выйти (для Docker HEALTHCHECK)")
|
|
migrate := flag.Bool("migrate", false, "apply migrations and exit")
|
|
bootstrapS3 := flag.Bool("bootstrap-s3", false, "initialize private bucket and application IAM credentials")
|
|
reconcile := flag.Bool("reconcile", false, "reconcile at most 100 metadata rows and 100 objects; dry-run by default")
|
|
apply := flag.Bool("apply", false, "apply safe reconciliation changes")
|
|
grace := flag.Duration("grace", 10*time.Minute, "minimum safe object age, at least 60 seconds")
|
|
after := flag.String("after", "", "metadata UUID cursor")
|
|
objectAfter := flag.String("object-after", "", "object key cursor")
|
|
flag.Parse()
|
|
|
|
cfg, err := config.Load()
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, "config:", err)
|
|
os.Exit(1)
|
|
}
|
|
if *healthcheck {
|
|
os.Exit(probe(cfg.Port))
|
|
}
|
|
|
|
log := logger.New(cfg.LogLevel)
|
|
alias := uuid.NewString()
|
|
if err = os.Setenv("INSTANCE_ALIAS", alias); err != nil {
|
|
log.Fatal().Msg("instance alias initialization failed")
|
|
}
|
|
if err = os.WriteFile("/tmp/messenger-instance-id", []byte(alias), 0600); err != nil {
|
|
log.Fatal().Msg("instance alias file unavailable")
|
|
}
|
|
observability, err := telemetry.Setup(context.Background(), "messenger-api")
|
|
if err != nil {
|
|
log.Fatal().Msg("telemetry initialization failed")
|
|
}
|
|
defer func() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
|
defer cancel()
|
|
observability.Shutdown(ctx)
|
|
}()
|
|
dsn, err := config.ReadSecret(cfg.DatabaseURLFile)
|
|
if err != nil {
|
|
log.Fatal().Msg("database secret unavailable")
|
|
}
|
|
if *migrate {
|
|
if err = db.Migrate(context.Background(), dsn); err != nil {
|
|
log.Fatal().Err(err).Msg("migration failed")
|
|
}
|
|
return
|
|
}
|
|
s3path := os.Getenv("S3_CONFIG_FILE")
|
|
if s3path == "" {
|
|
s3path = "/run/secrets/s3_credentials"
|
|
}
|
|
s3config, err := storage.ReadConfig(s3path)
|
|
if err != nil {
|
|
log.Fatal().Msg("S3 application credentials unavailable")
|
|
}
|
|
objects, err := storage.FromConfig(s3config)
|
|
if err != nil {
|
|
log.Fatal().Msg("invalid S3 endpoint")
|
|
}
|
|
if *bootstrapS3 {
|
|
root, e := storage.ReadConfig("/run/secrets/s3_root")
|
|
if e != nil {
|
|
log.Fatal().Msg("S3 bootstrap credentials unavailable")
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
if e = storage.Bootstrap(ctx, root, s3config); e != nil {
|
|
log.Fatal().Err(e).Msg("S3 bootstrap failed")
|
|
}
|
|
return
|
|
}
|
|
pc, err := pgxpool.ParseConfig(dsn)
|
|
if err != nil {
|
|
log.Fatal().Msg("invalid database configuration")
|
|
}
|
|
pc.MaxConns = cfg.MaxConns
|
|
pc.ConnConfig.Tracer = telemetry.DBTracer{}
|
|
pc.MinConns = 0
|
|
pc.ConnConfig.ConnectTimeout = time.Second
|
|
pc.ConnConfig.RuntimeParams["statement_timeout"] = "2000"
|
|
pc.ConnConfig.RuntimeParams["lock_timeout"] = "1000"
|
|
pool, err := pgxpool.NewWithConfig(context.Background(), pc)
|
|
if err != nil {
|
|
log.Fatal().Msg("database initialization failed")
|
|
}
|
|
defer pool.Close()
|
|
var cache *redis.Client
|
|
if url, e := config.ReadSecret(cfg.CacheURLFile); e == nil {
|
|
opts, e := redis.ParseURL(url)
|
|
if e != nil {
|
|
log.Fatal().Msg("invalid cache configuration")
|
|
}
|
|
opts.MaxRetries = 0
|
|
opts.DialTimeout = 80 * time.Millisecond
|
|
opts.ReadTimeout = 80 * time.Millisecond
|
|
opts.WriteTimeout = 80 * time.Millisecond
|
|
cache = redis.NewClient(opts)
|
|
defer func() { _ = cache.Close() }()
|
|
}
|
|
store := postgres.New(pool, cache)
|
|
if err = observability.Gauges(func(ctx context.Context) (map[string]float64, error) {
|
|
m, e := store.PipelineMetrics(ctx)
|
|
values := telemetry.PipelineValues(m)
|
|
values["db_pool_used"] = float64(pool.Stat().AcquiredConns())
|
|
values["db_pool_capacity"] = float64(pool.Stat().MaxConns())
|
|
return values, e
|
|
}); err != nil {
|
|
log.Fatal().Msg("telemetry gauge initialization failed")
|
|
}
|
|
if *reconcile {
|
|
cursor := uuid.Nil
|
|
if *after != "" {
|
|
cursor, err = uuid.Parse(*after)
|
|
if err != nil {
|
|
log.Fatal().Msg("invalid metadata cursor")
|
|
}
|
|
}
|
|
if len(*objectAfter) > 64 {
|
|
log.Fatal().Msg("object cursor too long")
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
report, e := usecase.NewReconciler(store, objects, time.Now).Run(ctx, cursor, *objectAfter, *grace, *apply)
|
|
if err = json.NewEncoder(os.Stdout).Encode(report); err != nil {
|
|
log.Fatal().Msg("reconciliation report write failed")
|
|
}
|
|
if e != nil {
|
|
log.Fatal().Err(e).Msg("reconciliation incomplete")
|
|
}
|
|
return
|
|
}
|
|
app := usecase.NewMessenger(store)
|
|
auth := usecase.NewAuth(store, password.New(), app, time.Duration(cfg.SessionTTLSeconds)*time.Second, time.Now)
|
|
attachments := usecase.NewAttachments(store, app, telemetry.Objects{Objects: objects})
|
|
probeDependencies := func(ctx context.Context) error {
|
|
if e := pool.Ping(ctx); e != nil {
|
|
return e
|
|
}
|
|
return objects.Ready(ctx)
|
|
}
|
|
h := handler.New(app, auth, attachments, probeDependencies, handler.Limits{
|
|
MaxBodyBytes: cfg.MaxBodyBytes,
|
|
MaxInflight: cfg.MaxInflight,
|
|
MaxQueue: cfg.MaxQueue,
|
|
QueueTimeout: cfg.QueueTimeout,
|
|
}, func() any {
|
|
return map[string]any{"pool_total": pool.Stat().TotalConns(), "pool_acquired": pool.Stat().AcquiredConns(), "pool_max": pool.Stat().MaxConns()}
|
|
}, &log)
|
|
srv := server.New(cfg.Addr(), h.Router())
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
|
defer stop()
|
|
|
|
serveErr := make(chan error, 1)
|
|
go func() { serveErr <- srv.ListenAndServe() }()
|
|
log.Info().Str("addr", cfg.Addr()).Str("env", cfg.Env).
|
|
Int("max_inflight", cfg.MaxInflight).
|
|
Int("max_queue", cfg.MaxQueue).Msg("server started")
|
|
|
|
select {
|
|
case err := <-serveErr:
|
|
log.Fatal().Err(err).Msg("server failed")
|
|
case <-ctx.Done():
|
|
}
|
|
|
|
started := time.Now()
|
|
log.Info().Dur("timeout", cfg.ShutdownTimeout).Msg("shutdown signal received, draining")
|
|
h.Drain()
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
|
defer cancel()
|
|
if err := srv.Shutdown(shutdownCtx); err != nil {
|
|
log.Error().Msg("shutdown timed out, forcing active requests closed")
|
|
if err := srv.Close(); err != nil {
|
|
log.Error().Msg("forced server close failed")
|
|
}
|
|
}
|
|
if err := <-serveErr; err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
log.Error().Err(err).Msg("server error")
|
|
}
|
|
log.Info().Dur("took", time.Since(started)).Msg("shutdown complete")
|
|
}
|
|
|
|
// probe — healthcheck без curl в образе distroless: сам бинарник ходит в
|
|
// /health/ready и возвращает код выхода для Docker.
|
|
func probe(port int) int {
|
|
client := http.Client{Timeout: 2 * time.Second}
|
|
resp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d/health/ready", port))
|
|
if err != nil {
|
|
return 1
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|