lab5: асинхронная очередь, worker и идемпотентный pipeline
API принимает 202 после durable staging и TX intent (job+outbox); отдельные relay и worker публикуют/обрабатывают задания с publisher confirm, lease, retry/backoff, DLQ и replay. Добавлены версии pipeline, варианты thumbnail/crop/optimized, presign в verified staging, status-aware sweeper и admission control.
This commit is contained in:
@@ -0,0 +1,261 @@
|
||||
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,
|
||||
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", "database": err.Error()})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !pub.Connected() {
|
||||
if err := pub.Connect(); err != nil {
|
||||
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable", "broker": err.Error()})
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
oldest, err := relay.Health(ctx)
|
||||
if err != nil {
|
||||
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable", "outbox": err.Error()})
|
||||
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user