forked from mtusi2026/mtusi2026lab6
Prepare verified laboratory 6 implementation and evidence
This commit is contained in:
@@ -0,0 +1,225 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"backend/internal/adapter/imagefile"
|
||||
"backend/internal/adapter/queue"
|
||||
"backend/internal/adapter/repository/postgres"
|
||||
"backend/internal/adapter/storage"
|
||||
"backend/internal/adapter/telemetry"
|
||||
"backend/internal/application/usecase"
|
||||
"backend/internal/config"
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
replay := flag.String("replay", "", "replay failed attachment UUID")
|
||||
advance := flag.String("advance", "", "new version for ready/failed attachment UUID")
|
||||
fault := flag.String("fault", "", "test-only crash point: after_original/after_objects/after_commit")
|
||||
flag.Parse()
|
||||
cfg, e := config.Load()
|
||||
must(e)
|
||||
observability, e := telemetry.Setup(context.Background(), "messenger-worker")
|
||||
must(e)
|
||||
defer func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
observability.Shutdown(ctx)
|
||||
}()
|
||||
dsn, e := config.ReadSecret(cfg.DatabaseURLFile)
|
||||
must(e)
|
||||
pc, e := pgxpool.ParseConfig(dsn)
|
||||
must(e)
|
||||
pc.MaxConns = 2
|
||||
pc.ConnConfig.Tracer = telemetry.DBTracer{}
|
||||
pc.ConnConfig.ConnectTimeout = time.Second
|
||||
pc.ConnConfig.RuntimeParams["statement_timeout"] = "2000"
|
||||
pc.ConnConfig.RuntimeParams["lock_timeout"] = "1000"
|
||||
pool, e := pgxpool.NewWithConfig(context.Background(), pc)
|
||||
must(e)
|
||||
defer pool.Close()
|
||||
repo := postgres.New(pool, nil)
|
||||
must(observability.Gauges(func(ctx context.Context) (map[string]float64, error) {
|
||||
m, e := repo.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
|
||||
}))
|
||||
if *replay != "" || *advance != "" {
|
||||
s := *replay
|
||||
if s == "" {
|
||||
s = *advance
|
||||
}
|
||||
id, e := uuid.Parse(s)
|
||||
must(e)
|
||||
var ok bool
|
||||
if *replay != "" {
|
||||
ok, e = repo.ReplayJob(context.Background(), id)
|
||||
} else {
|
||||
ok, e = repo.AdvancePipeline(context.Background(), id)
|
||||
}
|
||||
must(e)
|
||||
fmt.Printf("{\"changed\":%v}\n", ok)
|
||||
return
|
||||
}
|
||||
s3path := os.Getenv("S3_CONFIG_FILE")
|
||||
if s3path == "" {
|
||||
s3path = "/run/secrets/s3_credentials"
|
||||
}
|
||||
s3cfg, e := storage.ReadConfig(s3path)
|
||||
must(e)
|
||||
objects, e := storage.FromConfig(s3cfg)
|
||||
must(e)
|
||||
url, e := config.ReadSecret(cfg.CacheURLFile)
|
||||
must(e)
|
||||
opts, e := redis.ParseURL(url)
|
||||
must(e)
|
||||
opts.MaxRetries = 0
|
||||
opts.DialTimeout = time.Second
|
||||
opts.ReadTimeout = 2 * time.Second
|
||||
opts.WriteTimeout = time.Second
|
||||
client := redis.NewClient(opts)
|
||||
defer func() { _ = client.Close() }()
|
||||
attempts := 5
|
||||
if s := os.Getenv("WORKER_MAX_ATTEMPTS"); s != "" {
|
||||
attempts, e = strconv.Atoi(s)
|
||||
must(e)
|
||||
}
|
||||
if attempts < 1 || attempts > 10 {
|
||||
must(fmt.Errorf("attempts out of bounds"))
|
||||
}
|
||||
pipeline := usecase.NewPipeline(repo, telemetry.Objects{Objects: objects}, imagefile.NewTransformer(), int32(attempts))
|
||||
pipeline.OnResult = observability.JobResult
|
||||
if *fault != "" {
|
||||
switch *fault {
|
||||
case "after_original", "after_objects", "after_commit":
|
||||
default:
|
||||
must(fmt.Errorf("invalid fault point"))
|
||||
}
|
||||
pipeline.Fault = func(point string) error {
|
||||
if point == *fault {
|
||||
os.Exit(88)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
broker := queue.New(client, repo, uuid.NewString())
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
logError := func(error) { fmt.Fprintln(os.Stderr, "{\"event\":\"pipeline_dependency_error\"}") }
|
||||
cleanupDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(cleanupDone)
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
cleanup, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
e := pipeline.Cleanup(cleanup)
|
||||
cancel()
|
||||
if e != nil {
|
||||
logError(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
done := make(chan struct{})
|
||||
go func() { defer close(done); broker.RunPublisher(ctx, logError) }()
|
||||
broker.RunWorker(ctx, observability.Worker(pipeline.Process), logError)
|
||||
stop()
|
||||
<-done
|
||||
<-cleanupDone
|
||||
}
|
||||
func must(e error) {
|
||||
if e != nil {
|
||||
fmt.Fprintln(os.Stderr, "worker initialization/operation failed")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user