lab5: очереди и асинхронная обработка изображений
Durable staging handoff, transactional outbox, at-least-once worker with lease fencing, idempotent versioned pipeline, three variants, operator tooling, contract tests and evidence. Includes the review fixes: reprocess source selection and failure settlement, replay guards, stale-job retirement, PNG structural/raster validation, migration rollback safety and audit events.
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)
|
||||
}
|
||||
+15
-7
@@ -74,23 +74,31 @@ func run(cfg config.Config, log *slog.Logger) error {
|
||||
return fmt.Errorf("connect object store: %w", err)
|
||||
}
|
||||
|
||||
attachmentRepository := store.Attachments()
|
||||
pipelineRepository := store.Pipeline()
|
||||
attachmentService := attachment.NewService(
|
||||
attachmentRepository,
|
||||
pipelineRepository,
|
||||
objectStore,
|
||||
attachment.Config{
|
||||
MaxUploadBytes: cfg.S3.MaxUploadBytes,
|
||||
MaxImagePixels: cfg.S3.MaxImagePixels,
|
||||
PresignTTL: cfg.S3.PresignTTL,
|
||||
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(
|
||||
attachmentRepository,
|
||||
pipelineRepository,
|
||||
objectStore,
|
||||
store,
|
||||
cfg.S3.SweepGrace,
|
||||
cfg.Staging.OrphanGrace,
|
||||
cfg.Staging.FailedRetention,
|
||||
cfg.S3.SweepInterval,
|
||||
log,
|
||||
)
|
||||
@@ -151,7 +159,7 @@ func run(cfg config.Config, log *slog.Logger) error {
|
||||
rest.NewHandler(
|
||||
user.NewService(store.Users()),
|
||||
chat.NewService(chatRepo),
|
||||
message.NewService(store.Messages(), attachmentRepository),
|
||||
message.NewService(store.Messages(), pipelineRepository),
|
||||
attachmentService,
|
||||
health.New(pingers...),
|
||||
sessionService,
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
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"
|
||||
)
|
||||
|
||||
const maxUnpublishedAge = 10 * time.Minute
|
||||
|
||||
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()),
|
||||
)
|
||||
slog.SetDefault(log)
|
||||
|
||||
if err := run(cfg, log); err != nil {
|
||||
log.Error("shutdown with error", slog.Any("error", err))
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect database: %w", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
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)
|
||||
|
||||
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,231 @@
|
||||
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/worker"
|
||||
)
|
||||
|
||||
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()),
|
||||
)
|
||||
slog.SetDefault(log)
|
||||
|
||||
if err := run(cfg, log); err != nil {
|
||||
log.Error("shutdown with error", slog.Any("error", err))
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect database: %w", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
objectStore, 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)
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
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