forked from mtusi2026/mtusi2026lab6
lab6
This commit is contained in:
@@ -0,0 +1,215 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/imageproc"
|
||||
"mtusi-messenger/internal/logger"
|
||||
"mtusi-messenger/internal/storage/postgres"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "load config:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
log := logger.New(logger.WithLevel(cfg.SlogLevel()), logger.WithFormat(logger.FormatConsole))
|
||||
slog.SetDefault(log)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
store, err := postgres.New(ctx, cfg.Postgres, time.Duration(cfg.Idempotency.TTLSeconds)*time.Second)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "connect database:", err)
|
||||
cancel()
|
||||
os.Exit(1) //nolint:gocritic // main exits after DB setup failure
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
repo := store.Pipeline()
|
||||
|
||||
switch os.Args[1] {
|
||||
case "failed":
|
||||
runFailed(ctx, repo)
|
||||
case "replay":
|
||||
runReplay(ctx, repo, cfg)
|
||||
case "reprocess":
|
||||
runReprocess(ctx, repo, cfg)
|
||||
case "duplicate":
|
||||
runDuplicate(ctx, repo)
|
||||
case "inspect":
|
||||
runInspect(ctx, repo)
|
||||
default:
|
||||
usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
func usage() {
|
||||
fmt.Fprintln(os.Stderr, `usage: jobctl <command> [flags]
|
||||
|
||||
failed -limit N
|
||||
replay -job JOB_ID [-attempts N]
|
||||
reprocess -attachment ATTACHMENT_ID -pipeline N
|
||||
duplicate -attachment ATTACHMENT_ID | -job JOB_ID
|
||||
inspect -attachment ATTACHMENT_ID`)
|
||||
}
|
||||
|
||||
func runFailed(ctx context.Context, repo *postgres.PipelineRepository) {
|
||||
flags := flag.NewFlagSet("failed", flag.ExitOnError)
|
||||
limit := flags.Int("limit", 50, "maximum jobs")
|
||||
_ = flags.Parse(os.Args[2:])
|
||||
|
||||
jobs, err := repo.ListFailedJobs(ctx, *limit)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
}
|
||||
|
||||
printJSON(jobs)
|
||||
}
|
||||
|
||||
func runReplay(ctx context.Context, repo *postgres.PipelineRepository, cfg config.Config) {
|
||||
flags := flag.NewFlagSet("replay", flag.ExitOnError)
|
||||
jobID := flags.String("job", "", "job id")
|
||||
attempts := flags.Int("attempts", cfg.Processing.MaxAttempts, "additional attempts")
|
||||
_ = flags.Parse(os.Args[2:])
|
||||
|
||||
id, err := uuid.Parse(*jobID)
|
||||
if err != nil {
|
||||
fail(fmt.Errorf("invalid job id: %w", err))
|
||||
}
|
||||
|
||||
job, err := repo.ReplayJob(ctx, id, *attempts)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
}
|
||||
|
||||
printJSON(job)
|
||||
}
|
||||
|
||||
func runReprocess(ctx context.Context, repo *postgres.PipelineRepository, cfg config.Config) {
|
||||
flags := flag.NewFlagSet("reprocess", flag.ExitOnError)
|
||||
attachmentID := flags.String("attachment", "", "attachment id")
|
||||
version := flags.Int("pipeline", 2, "target pipeline version")
|
||||
_ = flags.Parse(os.Args[2:])
|
||||
|
||||
if _, ok := imageproc.Pipeline(*version); !ok {
|
||||
fail(fmt.Errorf("unsupported pipeline version %d", *version))
|
||||
}
|
||||
|
||||
id, err := uuid.Parse(*attachmentID)
|
||||
if err != nil {
|
||||
fail(fmt.Errorf("invalid attachment id: %w", err))
|
||||
}
|
||||
|
||||
jobID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
fail(err)
|
||||
}
|
||||
|
||||
job, err := repo.Reprocess(ctx, id, *version, cfg.Processing.MaxAttempts, jobID)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
}
|
||||
|
||||
printJSON(job)
|
||||
}
|
||||
|
||||
func runDuplicate(ctx context.Context, repo *postgres.PipelineRepository) {
|
||||
flags := flag.NewFlagSet("duplicate", flag.ExitOnError)
|
||||
attachmentID := flags.String("attachment", "", "attachment id")
|
||||
jobID := flags.String("job", "", "specific job id (old pipeline version)")
|
||||
_ = flags.Parse(os.Args[2:])
|
||||
|
||||
if *jobID != "" {
|
||||
id, err := uuid.Parse(*jobID)
|
||||
if err != nil {
|
||||
fail(fmt.Errorf("invalid job id: %w", err))
|
||||
}
|
||||
|
||||
message, err := repo.DuplicateJob(ctx, id)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
}
|
||||
|
||||
printJSON(message)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
id, err := uuid.Parse(*attachmentID)
|
||||
if err != nil {
|
||||
fail(fmt.Errorf("attachment or job id is required: %w", err))
|
||||
}
|
||||
|
||||
message, err := repo.Duplicate(ctx, id)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
}
|
||||
|
||||
printJSON(message)
|
||||
}
|
||||
|
||||
func runInspect(ctx context.Context, repo *postgres.PipelineRepository) {
|
||||
flags := flag.NewFlagSet("inspect", flag.ExitOnError)
|
||||
attachmentID := flags.String("attachment", "", "attachment id")
|
||||
_ = flags.Parse(os.Args[2:])
|
||||
|
||||
id, err := uuid.Parse(*attachmentID)
|
||||
if err != nil {
|
||||
fail(fmt.Errorf("invalid attachment id: %w", err))
|
||||
}
|
||||
|
||||
attachment, err := repo.GetForID(ctx, id)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
}
|
||||
|
||||
variants, err := repo.ListVariants(ctx, id, attachment.PipelineVersion)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
}
|
||||
|
||||
var jobOutput any
|
||||
|
||||
job, jobErr := repo.GetJobByAttachment(ctx, id, attachment.PipelineVersion)
|
||||
if jobErr == nil {
|
||||
jobOutput = job
|
||||
}
|
||||
|
||||
printJSON(map[string]any{
|
||||
"attachment": attachment,
|
||||
"variants": variants,
|
||||
"job": jobOutput,
|
||||
})
|
||||
}
|
||||
|
||||
func printJSON(value any) {
|
||||
encoder := json.NewEncoder(os.Stdout)
|
||||
encoder.SetIndent("", " ")
|
||||
if err := encoder.Encode(value); err != nil {
|
||||
fail(err)
|
||||
}
|
||||
}
|
||||
|
||||
func fail(err error) {
|
||||
fmt.Fprintln(os.Stderr, "error:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/health"
|
||||
"mtusi-messenger/internal/logger"
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
"mtusi-messenger/internal/platform/objectstore"
|
||||
"mtusi-messenger/internal/platform/token"
|
||||
"mtusi-messenger/internal/service/attachment"
|
||||
"mtusi-messenger/internal/service/chat"
|
||||
"mtusi-messenger/internal/service/message"
|
||||
"mtusi-messenger/internal/service/session"
|
||||
"mtusi-messenger/internal/service/user"
|
||||
"mtusi-messenger/internal/storage/postgres"
|
||||
storageredis "mtusi-messenger/internal/storage/redis"
|
||||
"mtusi-messenger/internal/telemetry"
|
||||
"mtusi-messenger/internal/transport/rest"
|
||||
)
|
||||
|
||||
var version = "dev"
|
||||
|
||||
func main() {
|
||||
log := logger.New()
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Error("load config", slog.Any("error", err))
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
log = logger.New(
|
||||
logger.WithLevel(cfg.SlogLevel()),
|
||||
logger.WithFormat(cfg.LoggerFormat()),
|
||||
)
|
||||
|
||||
shutdown, telemetryErr := telemetry.Setup(context.Background(), "messenger-api", version)
|
||||
if telemetryErr != nil {
|
||||
log.Warn("telemetry setup failed; continuing without OTLP", slog.Any("error", telemetryErr))
|
||||
shutdown = func(context.Context) error { return nil }
|
||||
}
|
||||
log = telemetry.WrapLogger(log, "messenger-api", cfg.SlogLevel())
|
||||
slog.SetDefault(log)
|
||||
|
||||
if err := run(cfg, log); err != nil {
|
||||
log.Error("shutdown with error", slog.Any("error", err))
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
_ = shutdown(shutdownCtx)
|
||||
cancel()
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := shutdown(shutdownCtx); err != nil {
|
||||
log.Warn("telemetry shutdown failed", slog.Any("error", err))
|
||||
}
|
||||
}
|
||||
|
||||
func run(cfg config.Config, log *slog.Logger) error {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
store, err := postgres.New(ctx, cfg.Postgres, time.Duration(cfg.Idempotency.TTLSeconds)*time.Second, postgres.WithQueryTracer(telemetry.NewPGXTracer()))
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect database: %w", err)
|
||||
}
|
||||
|
||||
defer store.Close()
|
||||
|
||||
if err := telemetry.RegisterDBPool(store.PoolStats); err != nil {
|
||||
log.Warn("register db pool metrics", slog.Any("error", err))
|
||||
}
|
||||
if err := telemetry.RegisterProcessMetrics(); err != nil {
|
||||
log.Warn("register process metrics", slog.Any("error", err))
|
||||
}
|
||||
|
||||
objectStoreConcrete, err := objectstore.New(objectstore.Config{
|
||||
Endpoint: cfg.S3.Endpoint,
|
||||
PublicEndpoint: cfg.S3.PublicEndpoint,
|
||||
Region: cfg.S3.Region,
|
||||
Bucket: cfg.S3.Bucket,
|
||||
AccessKeyID: cfg.S3.AccessKeyID,
|
||||
SecretAccessKey: cfg.S3.SecretAccessKey,
|
||||
UsePathStyle: cfg.S3.UsePathStyle,
|
||||
Timeout: cfg.S3.Timeout,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect object store: %w", err)
|
||||
}
|
||||
|
||||
objectStore := telemetry.WrapStore(objectStoreConcrete)
|
||||
|
||||
pipelineRepository := store.Pipeline()
|
||||
attachmentService := attachment.NewService(
|
||||
pipelineRepository,
|
||||
objectStore,
|
||||
attachment.Config{
|
||||
MaxUploadBytes: cfg.S3.MaxUploadBytes,
|
||||
MaxImagePixels: cfg.S3.MaxImagePixels,
|
||||
PresignTTL: cfg.S3.PresignTTL,
|
||||
PipelineVersion: cfg.Processing.PipelineVersion,
|
||||
MaxAttempts: cfg.Processing.MaxAttempts,
|
||||
MaxPendingPerUser: cfg.Admission.MaxPendingPerUser,
|
||||
MaxPending: cfg.Admission.MaxPending,
|
||||
MaxStagedBytes: cfg.Admission.MaxStagedBytes,
|
||||
MaxConcurrent: cfg.Admission.MaxConcurrent,
|
||||
},
|
||||
log,
|
||||
)
|
||||
|
||||
sweeper := attachment.NewSweeper(
|
||||
pipelineRepository,
|
||||
objectStore,
|
||||
store,
|
||||
cfg.S3.SweepGrace,
|
||||
cfg.Staging.OrphanGrace,
|
||||
cfg.Staging.FailedRetention,
|
||||
cfg.S3.SweepInterval,
|
||||
log,
|
||||
)
|
||||
|
||||
sweepCtx, stopSweeper := context.WithCancel(context.Background())
|
||||
var sweepWait sync.WaitGroup
|
||||
|
||||
sweepWait.Add(1)
|
||||
|
||||
go func() {
|
||||
defer sweepWait.Done()
|
||||
|
||||
sweeper.Run(sweepCtx)
|
||||
}()
|
||||
|
||||
defer func() {
|
||||
stopSweeper()
|
||||
sweepWait.Wait()
|
||||
}()
|
||||
|
||||
redisCache, err := connectRedis(cfg.Redis)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() { _ = redisCache.Close() }()
|
||||
|
||||
sessionRepo := session.Repository(store.Sessions())
|
||||
chatRepo := chat.Repository(store.Chats())
|
||||
|
||||
pingers := []health.Pinger{store}
|
||||
|
||||
if cfg.Redis.Enabled {
|
||||
if cfg.Cache.Enabled {
|
||||
distributed, err := cache.NewDistributed(redisCache, cache.DistributedConfig{
|
||||
LockTTL: cfg.Cache.LockTTL,
|
||||
WaitTimeout: cfg.Cache.LockWaitTimeout,
|
||||
}, log)
|
||||
if err != nil {
|
||||
return fmt.Errorf("build distributed cache: %w", err)
|
||||
}
|
||||
|
||||
chatRepo = storageredis.NewChatRepository(
|
||||
store.Chats(),
|
||||
distributed,
|
||||
cfg.Cache.ChatListTTL,
|
||||
log,
|
||||
)
|
||||
}
|
||||
|
||||
log.Info("redis cache enabled", slog.String("host", cfg.Redis.Host), slog.Int("port", cfg.Redis.Port))
|
||||
}
|
||||
|
||||
ttl := time.Duration(cfg.Session.TTLSeconds) * time.Second
|
||||
sessionService := session.NewService(sessionRepo, token.New(), ttl)
|
||||
|
||||
router, err := rest.NewRouter(
|
||||
rest.NewHandler(
|
||||
user.NewService(store.Users()),
|
||||
chat.NewService(chatRepo),
|
||||
message.NewService(store.Messages(), pipelineRepository),
|
||||
attachmentService,
|
||||
health.New(pingers...),
|
||||
sessionService,
|
||||
),
|
||||
rest.NewSecurityHandler(sessionService),
|
||||
rest.NewExtensions(attachmentService, sessionService, log),
|
||||
log,
|
||||
cfg.Server.MaxBodyBytes,
|
||||
cfg.S3.MaxUploadBytes,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("build router: %w", err)
|
||||
}
|
||||
|
||||
server := &http.Server{
|
||||
Addr: cfg.Addr(),
|
||||
Handler: router,
|
||||
ReadHeaderTimeout: cfg.Server.ReadHeaderTimeout,
|
||||
ReadTimeout: cfg.Server.ReadTimeout,
|
||||
}
|
||||
|
||||
errc := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
log.Info("server started", slog.String("addr", cfg.Addr()))
|
||||
|
||||
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
errc <- err
|
||||
}
|
||||
|
||||
close(errc)
|
||||
}()
|
||||
|
||||
select {
|
||||
case err, ok := <-errc:
|
||||
if ok && err != nil {
|
||||
return fmt.Errorf("listen: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
log.Info("shutdown signal received", slog.Duration("timeout", cfg.Server.ShutdownTimeout))
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.Server.ShutdownTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
return fmt.Errorf("shutdown: %w", err)
|
||||
}
|
||||
|
||||
log.Info("server stopped")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func connectRedis(cfg config.Redis) (cache.LockStore, error) {
|
||||
if !cfg.Enabled {
|
||||
return cache.NoOpCache{}, nil
|
||||
}
|
||||
|
||||
client, err := cache.NewRedis(cache.RedisConfig{
|
||||
Host: cfg.Host,
|
||||
Port: cfg.Port,
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
MaxRetries: cfg.MaxRetries,
|
||||
DialTimeout: cfg.DialTimeout,
|
||||
ReadTimeout: cfg.ReadTimeout,
|
||||
WriteTimeout: cfg.WriteTimeout,
|
||||
PoolSize: cfg.PoolSize,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect redis: %w", err)
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"github.com/pressly/goose/v3"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/logger"
|
||||
"mtusi-messenger/internal/storage/postgres/migrations"
|
||||
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log := logger.New()
|
||||
|
||||
if err := run(os.Args[1:]); err != nil {
|
||||
log.Error("migrate failed", slog.Any("error", err))
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(args []string) error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return fmt.Errorf("load config: %w", err)
|
||||
}
|
||||
|
||||
slog.SetDefault(logger.New(
|
||||
logger.WithLevel(cfg.SlogLevel()),
|
||||
logger.WithFormat(cfg.LoggerFormat()),
|
||||
))
|
||||
|
||||
command := "up"
|
||||
if len(args) > 0 {
|
||||
command = args[0]
|
||||
}
|
||||
|
||||
db, err := sql.Open("pgx", cfg.Postgres.DSN())
|
||||
if err != nil {
|
||||
return fmt.Errorf("open database: %w", err)
|
||||
}
|
||||
|
||||
defer func() { _ = db.Close() }()
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(context.Background(), cfg.Postgres.ConnectTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := db.PingContext(pingCtx); err != nil {
|
||||
return fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
|
||||
goose.SetBaseFS(migrations.FS)
|
||||
|
||||
if err := goose.SetDialect("postgres"); err != nil {
|
||||
return fmt.Errorf("set dialect: %w", err)
|
||||
}
|
||||
|
||||
if err := goCommand(db, command); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func goCommand(db *sql.DB, command string) error {
|
||||
switch command {
|
||||
case "up":
|
||||
return goose.Up(db, ".")
|
||||
case "up-by-one":
|
||||
return goose.UpByOne(db, ".")
|
||||
case "down":
|
||||
return goose.Down(db, ".")
|
||||
case "status":
|
||||
return goose.Status(db, ".")
|
||||
case "version":
|
||||
return goose.Version(db, ".")
|
||||
case "redo":
|
||||
return goose.Redo(db, ".")
|
||||
default:
|
||||
return errors.New("unknown command: " + command + " (up, up-by-one, down, status, version, redo)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/broker"
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/logger"
|
||||
"mtusi-messenger/internal/outbox"
|
||||
"mtusi-messenger/internal/storage/postgres"
|
||||
"mtusi-messenger/internal/telemetry"
|
||||
)
|
||||
|
||||
const maxUnpublishedAge = 10 * time.Minute
|
||||
|
||||
var version = "dev"
|
||||
|
||||
func main() {
|
||||
log := logger.New()
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Error("load config", slog.Any("error", err))
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
log = logger.New(
|
||||
logger.WithLevel(cfg.SlogLevel()),
|
||||
logger.WithFormat(cfg.LoggerFormat()),
|
||||
)
|
||||
|
||||
shutdown, telemetryErr := telemetry.Setup(context.Background(), "messenger-relay", version)
|
||||
if telemetryErr != nil {
|
||||
log.Warn("telemetry setup failed; continuing without OTLP", slog.Any("error", telemetryErr))
|
||||
shutdown = func(context.Context) error { return nil }
|
||||
}
|
||||
log = telemetry.WrapLogger(log, "messenger-relay", cfg.SlogLevel())
|
||||
slog.SetDefault(log)
|
||||
|
||||
if err := run(cfg, log); err != nil {
|
||||
log.Error("shutdown with error", slog.Any("error", err))
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
_ = shutdown(shutdownCtx)
|
||||
cancel()
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := shutdown(shutdownCtx); err != nil {
|
||||
log.Warn("telemetry shutdown failed", slog.Any("error", err))
|
||||
}
|
||||
}
|
||||
|
||||
type publisher struct {
|
||||
cfg broker.Config
|
||||
log *slog.Logger
|
||||
mu sync.Mutex
|
||||
conn *broker.Client
|
||||
}
|
||||
|
||||
func (p *publisher) client() (*broker.Client, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if p.conn != nil && p.conn.Connected() {
|
||||
return p.conn, nil
|
||||
}
|
||||
|
||||
if p.conn != nil {
|
||||
_ = p.conn.Close()
|
||||
p.conn = nil
|
||||
}
|
||||
|
||||
conn, err := broker.Dial(p.cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
p.conn = conn
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (p *publisher) PublishConfirmed(
|
||||
ctx context.Context,
|
||||
routingKey string,
|
||||
message domain.JobMessage,
|
||||
) error {
|
||||
conn, err := p.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := conn.PublishConfirmed(ctx, routingKey, message); err != nil {
|
||||
p.mu.Lock()
|
||||
if p.conn == conn {
|
||||
_ = p.conn.Close()
|
||||
p.conn = nil
|
||||
}
|
||||
p.mu.Unlock()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *publisher) Connect() error {
|
||||
_, err := p.client()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *publisher) Connected() bool {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
return p.conn != nil && p.conn.Connected()
|
||||
}
|
||||
|
||||
func (p *publisher) Close() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if p.conn != nil {
|
||||
_ = p.conn.Close()
|
||||
p.conn = nil
|
||||
}
|
||||
}
|
||||
|
||||
func brokerConfig(cfg config.Config) broker.Config {
|
||||
return broker.Config{
|
||||
URL: cfg.Broker.URL,
|
||||
Exchange: cfg.Broker.Exchange,
|
||||
DLX: cfg.Broker.DLX,
|
||||
Queue: cfg.Broker.Queue,
|
||||
DLQ: cfg.Broker.DLQ,
|
||||
ConnectTimeout: cfg.Broker.ConnectTimeout,
|
||||
ConfirmTimeout: cfg.Broker.ConfirmTimeout,
|
||||
Heartbeat: cfg.Broker.Heartbeat,
|
||||
Prefetch: cfg.Broker.Prefetch,
|
||||
}
|
||||
}
|
||||
|
||||
func run(cfg config.Config, log *slog.Logger) error {
|
||||
if cfg.Broker.URL == "" {
|
||||
return errors.New("BROKER_URL is required for relay")
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
store, err := postgres.New(ctx, cfg.Postgres, time.Duration(cfg.Idempotency.TTLSeconds)*time.Second, postgres.WithQueryTracer(telemetry.NewPGXTracer()))
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect database: %w", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
if err := telemetry.RegisterDBPool(store.PoolStats); err != nil {
|
||||
log.Warn("register db pool metrics", slog.Any("error", err))
|
||||
}
|
||||
if err := telemetry.RegisterProcessMetrics(); err != nil {
|
||||
log.Warn("register process metrics", slog.Any("error", err))
|
||||
}
|
||||
|
||||
pub := &publisher{cfg: brokerConfig(cfg), log: log}
|
||||
defer pub.Close()
|
||||
|
||||
if err := pub.Connect(); err != nil {
|
||||
log.Warn("broker is not reachable yet; relay will retry", slog.Any("error", err))
|
||||
}
|
||||
|
||||
relay := outbox.New(store.Pipeline(), pub, outbox.Config{
|
||||
Owner: "relay-" + cfg.Broker.Queue,
|
||||
PollInterval: cfg.Outbox.PollInterval,
|
||||
ClaimTTL: cfg.Outbox.ClaimTTL,
|
||||
Batch: cfg.Outbox.Batch,
|
||||
ReaperInterval: cfg.Outbox.ReaperInterval,
|
||||
ReconcileAfter: cfg.Outbox.ReconcileAfter,
|
||||
Retention: cfg.Outbox.Retention,
|
||||
}, log)
|
||||
|
||||
if err := telemetry.RegisterRelayMetrics(store.Pipeline().OldestActiveJobAge, relay.Health, func(ctx context.Context) (int64, error) {
|
||||
return store.Pipeline().CountOverdueJobs(ctx, 30*time.Second)
|
||||
}); err != nil {
|
||||
log.Warn("register relay metrics", slog.Any("error", err))
|
||||
}
|
||||
|
||||
relayCtx, cancelRelay := context.WithCancel(ctx)
|
||||
defer cancelRelay()
|
||||
|
||||
relayDone := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
defer close(relayDone)
|
||||
|
||||
relay.Run(relayCtx)
|
||||
}()
|
||||
|
||||
server := healthServer(cfg.Relay.HealthAddr, store, pub, relay, log)
|
||||
|
||||
go func() {
|
||||
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Error("health server failed", slog.Any("error", err))
|
||||
}
|
||||
}()
|
||||
|
||||
<-ctx.Done()
|
||||
cancelRelay()
|
||||
<-relayDone
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
return server.Shutdown(shutdownCtx)
|
||||
}
|
||||
|
||||
func healthServer(
|
||||
addr string,
|
||||
store *postgres.Store,
|
||||
pub *publisher,
|
||||
relay *outbox.Relay,
|
||||
_ *slog.Logger,
|
||||
) *http.Server {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
mux.HandleFunc("/health/live", func(w http.ResponseWriter, _ *http.Request) {
|
||||
writeHealth(w, http.StatusOK, map[string]any{"status": "ok"})
|
||||
})
|
||||
|
||||
mux.HandleFunc("/health/ready", func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := store.Ping(ctx); err != nil {
|
||||
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !pub.Connected() {
|
||||
if err := pub.Connect(); err != nil {
|
||||
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
oldest, err := relay.Health(ctx)
|
||||
if err != nil {
|
||||
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if oldest > maxUnpublishedAge {
|
||||
writeHealth(w, http.StatusServiceUnavailable, map[string]any{
|
||||
"status": "unavailable",
|
||||
"outbox_oldest_seconds": int(oldest.Seconds()),
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
writeHealth(w, http.StatusOK, map[string]any{
|
||||
"status": "ok",
|
||||
"outbox_oldest_seconds": int(oldest.Seconds()),
|
||||
})
|
||||
})
|
||||
|
||||
return &http.Server{
|
||||
Addr: addr,
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func writeHealth(w http.ResponseWriter, status int, body map[string]any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
// Command s3init bootstraps the private attachment bucket. It is idempotent:
|
||||
// it runs before the API on every compose up, verifies the bucket and the
|
||||
// application identity, and exits successfully when everything is in place.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/smithy-go"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const bootstrapTimeout = 120 * time.Second
|
||||
|
||||
type settings struct {
|
||||
Endpoint string
|
||||
Region string
|
||||
Bucket string
|
||||
AdminAccessKey string
|
||||
AdminSecretKey string
|
||||
AppAccessKey string
|
||||
AppSecretKey string
|
||||
}
|
||||
|
||||
func main() {
|
||||
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||
|
||||
if err := run(log); err != nil {
|
||||
log.Error("s3 bootstrap failed", slog.Any("error", err))
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(log *slog.Logger) error {
|
||||
cfg, err := loadSettings()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), bootstrapTimeout)
|
||||
defer cancel()
|
||||
|
||||
admin := newClient(cfg, cfg.AdminAccessKey, cfg.AdminSecretKey)
|
||||
app := newClient(cfg, cfg.AppAccessKey, cfg.AppSecretKey)
|
||||
|
||||
if err := waitForBucket(ctx, admin, cfg.Bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := probeAppIdentity(ctx, app, cfg.Bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := probeForbiddenPrefix(ctx, app, cfg.Bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Info("s3 bucket ready",
|
||||
slog.String("endpoint", cfg.Endpoint),
|
||||
slog.String("bucket", cfg.Bucket),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadSettings() (settings, error) {
|
||||
cfg := settings{
|
||||
Endpoint: strings.TrimSpace(os.Getenv("S3_ENDPOINT")),
|
||||
Region: strings.TrimSpace(os.Getenv("S3_REGION")),
|
||||
Bucket: strings.TrimSpace(os.Getenv("S3_BUCKET")),
|
||||
AdminAccessKey: strings.TrimSpace(os.Getenv("S3_ADMIN_ACCESS_KEY")),
|
||||
AdminSecretKey: strings.TrimSpace(os.Getenv("S3_ADMIN_SECRET_ACCESS_KEY")),
|
||||
AppAccessKey: strings.TrimSpace(os.Getenv("S3_ACCESS_KEY_ID")),
|
||||
AppSecretKey: strings.TrimSpace(os.Getenv("S3_SECRET_ACCESS_KEY")),
|
||||
}
|
||||
|
||||
switch {
|
||||
case cfg.Endpoint == "":
|
||||
return settings{}, errors.New("S3_ENDPOINT is required")
|
||||
case cfg.Region == "":
|
||||
return settings{}, errors.New("S3_REGION is required")
|
||||
case cfg.Bucket == "":
|
||||
return settings{}, errors.New("S3_BUCKET is required")
|
||||
case cfg.AdminAccessKey == "" || cfg.AdminSecretKey == "":
|
||||
return settings{}, errors.New("S3_ADMIN_ACCESS_KEY and S3_ADMIN_SECRET_ACCESS_KEY are required")
|
||||
case cfg.AppAccessKey == "" || cfg.AppSecretKey == "":
|
||||
return settings{}, errors.New("S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY are required")
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func newClient(cfg settings, accessKey, secretKey string) *s3.Client {
|
||||
return s3.New(s3.Options{
|
||||
Region: cfg.Region,
|
||||
BaseEndpoint: aws.String(cfg.Endpoint),
|
||||
UsePathStyle: true,
|
||||
Credentials: credentials.NewStaticCredentialsProvider(accessKey, secretKey, ""),
|
||||
})
|
||||
}
|
||||
|
||||
func waitForBucket(ctx context.Context, client *s3.Client, bucket string) error {
|
||||
for {
|
||||
_, err := client.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: aws.String(bucket)})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if !isNotFound(err) {
|
||||
return fmt.Errorf("head bucket: %w", err)
|
||||
}
|
||||
|
||||
if _, err := client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(bucket)}); err == nil {
|
||||
return nil
|
||||
} else if isBucketExists(err) {
|
||||
return nil
|
||||
} else if !isNotFound(err) {
|
||||
return fmt.Errorf("create bucket: %w", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return fmt.Errorf("wait for object store: %w", ctx.Err())
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func probeAppIdentity(ctx context.Context, client *s3.Client, bucket string) error {
|
||||
key := "staging/.bootstrap/" + uuid.NewString()
|
||||
|
||||
if _, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Body: bytes.NewReader([]byte("ok")),
|
||||
ContentLength: aws.Int64(2),
|
||||
ContentType: aws.String("text/plain"),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("application identity cannot write: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_, _ = client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
}()
|
||||
|
||||
if _, err := client.HeadObject(ctx, &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("application identity cannot read: %w", err)
|
||||
}
|
||||
|
||||
if _, err := client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(bucket),
|
||||
Prefix: aws.String("staging/"),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("application identity cannot list: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func probeForbiddenPrefix(ctx context.Context, client *s3.Client, bucket string) error {
|
||||
key := "forbidden/" + uuid.NewString()
|
||||
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Body: bytes.NewReader([]byte("must not be stored")),
|
||||
})
|
||||
if err == nil {
|
||||
_, _ = client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
|
||||
return errors.New("application identity can write outside the allowed prefixes; check infra/s3/s3.json")
|
||||
}
|
||||
|
||||
var apiErr smithy.APIError
|
||||
if !errors.As(err, &apiErr) || apiErr.ErrorCode() != "AccessDenied" {
|
||||
return fmt.Errorf("forbidden-prefix probe returned an unexpected error: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func isNotFound(err error) bool {
|
||||
var apiErr smithy.APIError
|
||||
if errors.As(err, &apiErr) {
|
||||
switch apiErr.ErrorCode() {
|
||||
case "NotFound", "NoSuchBucket", "NoSuchKey":
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func isBucketExists(err error) bool {
|
||||
var apiErr smithy.APIError
|
||||
if errors.As(err, &apiErr) {
|
||||
switch apiErr.ErrorCode() {
|
||||
case "BucketAlreadyExists", "BucketAlreadyOwnedByYou":
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/broker"
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/logger"
|
||||
"mtusi-messenger/internal/platform/objectstore"
|
||||
"mtusi-messenger/internal/storage/postgres"
|
||||
"mtusi-messenger/internal/telemetry"
|
||||
"mtusi-messenger/internal/worker"
|
||||
)
|
||||
|
||||
var version = "dev"
|
||||
|
||||
func main() {
|
||||
log := logger.New()
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Error("load config", slog.Any("error", err))
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
log = logger.New(
|
||||
logger.WithLevel(cfg.SlogLevel()),
|
||||
logger.WithFormat(cfg.LoggerFormat()),
|
||||
)
|
||||
|
||||
shutdown, telemetryErr := telemetry.Setup(context.Background(), "messenger-worker", version)
|
||||
if telemetryErr != nil {
|
||||
log.Warn("telemetry setup failed; continuing without OTLP", slog.Any("error", telemetryErr))
|
||||
shutdown = func(context.Context) error { return nil }
|
||||
}
|
||||
log = telemetry.WrapLogger(log, "messenger-worker", cfg.SlogLevel())
|
||||
slog.SetDefault(log)
|
||||
|
||||
if err := run(cfg, log); err != nil {
|
||||
log.Error("shutdown with error", slog.Any("error", err))
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
_ = shutdown(shutdownCtx)
|
||||
cancel()
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := shutdown(shutdownCtx); err != nil {
|
||||
log.Warn("telemetry shutdown failed", slog.Any("error", err))
|
||||
}
|
||||
}
|
||||
|
||||
func run(cfg config.Config, log *slog.Logger) error {
|
||||
if cfg.Broker.URL == "" {
|
||||
return errors.New("BROKER_URL is required for worker")
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
store, err := postgres.New(ctx, cfg.Postgres, time.Duration(cfg.Idempotency.TTLSeconds)*time.Second, postgres.WithQueryTracer(telemetry.NewPGXTracer()))
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect database: %w", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
if err := telemetry.RegisterDBPool(store.PoolStats); err != nil {
|
||||
log.Warn("register db pool metrics", slog.Any("error", err))
|
||||
}
|
||||
if err := telemetry.RegisterProcessMetrics(); err != nil {
|
||||
log.Warn("register process metrics", slog.Any("error", err))
|
||||
}
|
||||
|
||||
objectStoreConcrete, err := objectstore.New(objectstore.Config{
|
||||
Endpoint: cfg.S3.Endpoint,
|
||||
PublicEndpoint: cfg.S3.PublicEndpoint,
|
||||
Region: cfg.S3.Region,
|
||||
Bucket: cfg.S3.Bucket,
|
||||
AccessKeyID: cfg.S3.AccessKeyID,
|
||||
SecretAccessKey: cfg.S3.SecretAccessKey,
|
||||
UsePathStyle: cfg.S3.UsePathStyle,
|
||||
Timeout: cfg.S3.Timeout,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect object store: %w", err)
|
||||
}
|
||||
|
||||
objectStore := telemetry.WrapStore(objectStoreConcrete)
|
||||
|
||||
workerInstance := worker.New(store.Pipeline(), objectStore, worker.Config{
|
||||
Concurrency: cfg.Worker.Concurrency,
|
||||
LeaseTTL: cfg.Processing.LeaseTTL,
|
||||
Heartbeat: cfg.Processing.Heartbeat,
|
||||
JobTimeout: cfg.Processing.JobTimeout,
|
||||
RetryBase: cfg.Processing.RetryBase,
|
||||
RetryCap: cfg.Processing.RetryCap,
|
||||
MaxUploadBytes: cfg.S3.MaxUploadBytes,
|
||||
MaxImagePixels: cfg.S3.MaxImagePixels,
|
||||
}, log)
|
||||
|
||||
if err := telemetry.RegisterWorkerMetrics(workerInstance.Busy, int64(cfg.Worker.Concurrency)); err != nil {
|
||||
log.Warn("register worker metrics", slog.Any("error", err))
|
||||
}
|
||||
|
||||
server := healthServer(cfg.Worker.HealthAddr, store, objectStore, workerInstance)
|
||||
|
||||
var serverWait sync.WaitGroup
|
||||
serverWait.Add(1)
|
||||
|
||||
go func() {
|
||||
defer serverWait.Done()
|
||||
|
||||
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Error("health server failed", slog.Any("error", err))
|
||||
}
|
||||
}()
|
||||
|
||||
runCtx, cancelRun := context.WithCancel(ctx)
|
||||
defer cancelRun()
|
||||
|
||||
consumerDone := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
defer close(consumerDone)
|
||||
|
||||
consumeWithReconnect(runCtx, cfg, workerInstance, log)
|
||||
}()
|
||||
|
||||
<-ctx.Done()
|
||||
cancelRun()
|
||||
<-consumerDone
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.Worker.ShutdownTimeout)
|
||||
defer cancel()
|
||||
|
||||
_ = server.Shutdown(shutdownCtx)
|
||||
serverWait.Wait()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func consumeWithReconnect(
|
||||
ctx context.Context,
|
||||
cfg config.Config,
|
||||
workerInstance *worker.Worker,
|
||||
log *slog.Logger,
|
||||
) {
|
||||
for ctx.Err() == nil {
|
||||
client, err := broker.Dial(brokerConfig(cfg))
|
||||
if err != nil {
|
||||
log.WarnContext(ctx, "broker dial failed, retrying", slog.Any("error", err))
|
||||
|
||||
if !sleepCtx(ctx, 2*time.Second) {
|
||||
return
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
err = workerInstance.Run(ctx, client)
|
||||
_ = client.Close()
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
log.WarnContext(ctx, "consumer stopped, reconnecting", slog.Any("error", err))
|
||||
}
|
||||
|
||||
if !sleepCtx(ctx, 2*time.Second) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sleepCtx(ctx context.Context, d time.Duration) bool {
|
||||
timer := time.NewTimer(d)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-timer.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func brokerConfig(cfg config.Config) broker.Config {
|
||||
return broker.Config{
|
||||
URL: cfg.Broker.URL,
|
||||
Exchange: cfg.Broker.Exchange,
|
||||
DLX: cfg.Broker.DLX,
|
||||
Queue: cfg.Broker.Queue,
|
||||
DLQ: cfg.Broker.DLQ,
|
||||
ConnectTimeout: cfg.Broker.ConnectTimeout,
|
||||
ConfirmTimeout: cfg.Broker.ConfirmTimeout,
|
||||
Heartbeat: cfg.Broker.Heartbeat,
|
||||
Prefetch: cfg.Worker.Prefetch,
|
||||
}
|
||||
}
|
||||
|
||||
func healthServer(
|
||||
addr string,
|
||||
store *postgres.Store,
|
||||
objectStore objectstore.Store,
|
||||
workerInstance *worker.Worker,
|
||||
) *http.Server {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
mux.HandleFunc("/health/live", func(w http.ResponseWriter, _ *http.Request) {
|
||||
writeHealth(w, http.StatusOK, map[string]any{"status": "ok"})
|
||||
})
|
||||
|
||||
mux.HandleFunc("/health/ready", func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := store.Ping(ctx); err != nil {
|
||||
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err := objectStore.Ping(ctx); err != nil {
|
||||
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
running, connected := workerInstance.Ready()
|
||||
if !running || !connected {
|
||||
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
writeHealth(w, http.StatusOK, map[string]any{"status": "ok"})
|
||||
})
|
||||
|
||||
return &http.Server{
|
||||
Addr: addr,
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func writeHealth(w http.ResponseWriter, status int, body map[string]any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
}
|
||||
Reference in New Issue
Block a user