Files
mtusi2026lab5/internal/outbox/relay.go
T
Vladislav Kunetskiy 01b885e846 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.
2026-10-31 14:34:24 +03:00

169 lines
4.8 KiB
Go

// Package outbox publishes the durable job intents with publisher confirms and
// reclaims abandoned relay claims and expired worker leases.
package outbox
import (
"context"
"log/slog"
"time"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/failpoint"
)
type Repository interface {
ClaimOutbox(ctx context.Context, owner string, claimTTL time.Duration, limit int) ([]domain.OutboxMessage, error)
MarkPublished(ctx context.Context, ids []int64) error
ReleaseOutbox(ctx context.Context, id int64, reason string) error
ReapOutboxClaims(ctx context.Context) error
ReapExpiredLeases(ctx context.Context, limit int) (int, error)
ReconcileQueuedJobs(ctx context.Context, olderThan time.Duration, limit int) (int, error)
PruneOutbox(ctx context.Context, retention time.Duration) error
OldestUnpublished(ctx context.Context) (time.Time, error)
}
type Publisher interface {
PublishConfirmed(ctx context.Context, routingKey string, message domain.JobMessage) error
}
type Config struct {
Owner string
PollInterval time.Duration
ClaimTTL time.Duration
Batch int
ReaperInterval time.Duration
ReconcileAfter time.Duration
Retention time.Duration
}
type Relay struct {
repo Repository
publisher Publisher
config Config
log *slog.Logger
lastPublished time.Time
lastReap time.Time
}
func New(repo Repository, publisher Publisher, config Config, log *slog.Logger) *Relay {
if log == nil {
log = slog.Default()
}
return &Relay{repo: repo, publisher: publisher, config: config, log: log}
}
func (r *Relay) Run(ctx context.Context) {
poll := time.NewTicker(r.config.PollInterval)
defer poll.Stop()
reaper := time.NewTicker(r.config.ReaperInterval)
defer reaper.Stop()
for {
select {
case <-ctx.Done():
return
case <-poll.C:
if _, err := r.RunOnce(ctx); err != nil {
r.log.WarnContext(ctx, "outbox publish cycle failed", slog.Any("error", err))
}
case <-reaper.C:
r.reap(ctx)
}
}
}
// RunOnce claims due rows, publishes each with a broker confirm and marks only
// confirmed rows. A crash between confirm and mark causes a duplicate publish,
// which the worker tolerates by CAS.
func (r *Relay) RunOnce(ctx context.Context) (int, error) {
messages, err := r.repo.ClaimOutbox(ctx, r.config.Owner, r.config.ClaimTTL, r.config.Batch)
if err != nil {
return 0, err
}
published := make([]int64, 0, len(messages))
for _, message := range messages {
job, err := domain.ParseJobMessage(message.Payload)
if err != nil {
// A malformed payload is an application bug, not a transient
// failure. Keep the row claim until it expires and log loudly; the
// operator can inspect the outbox.
r.log.ErrorContext(ctx, "outbox payload is invalid",
slog.Int64("outbox_id", message.ID),
slog.Any("error", err),
)
_ = r.repo.ReleaseOutbox(ctx, message.ID, "invalid payload")
continue
}
failpoint.Check("OUTBOX_AFTER_COMMIT", job.JobID)
if err := r.publisher.PublishConfirmed(ctx, message.RoutingKey, job); err != nil {
_ = r.repo.ReleaseOutbox(ctx, message.ID, err.Error())
continue
}
published = append(published, message.ID)
r.lastPublished = time.Now()
}
if err := r.repo.MarkPublished(ctx, published); err != nil {
return len(published), err
}
return len(published), nil
}
func (r *Relay) reap(ctx context.Context) {
if err := r.repo.ReapOutboxClaims(ctx); err != nil {
r.log.WarnContext(ctx, "outbox claim reaper failed", slog.Any("error", err))
}
reaped, err := r.repo.ReapExpiredLeases(ctx, 100)
if err != nil {
r.log.WarnContext(ctx, "lease reaper failed", slog.Any("error", err))
} else if reaped > 0 {
r.log.InfoContext(ctx, "expired job leases requeued", slog.Int("count", reaped))
}
// The broker is not the source of truth. If a delivery was dead-lettered
// or lost, the queued job has no unpublished outbox row; republish it.
if r.config.ReconcileAfter > 0 {
reconciled, err := r.repo.ReconcileQueuedJobs(ctx, r.config.ReconcileAfter, 100)
if err != nil {
r.log.WarnContext(ctx, "queued-job reconciliation failed", slog.Any("error", err))
} else if reconciled > 0 {
r.log.InfoContext(ctx, "lost queued jobs reconciled", slog.Int("count", reconciled))
}
}
if r.config.Retention > 0 {
if err := r.repo.PruneOutbox(ctx, r.config.Retention); err != nil {
r.log.WarnContext(ctx, "outbox retention failed", slog.Any("error", err))
}
}
r.lastReap = time.Now()
}
// Health returns the age of the oldest unpublished intent. A bounded age is a
// better relay readiness signal than "connected to broker".
func (r *Relay) Health(ctx context.Context) (oldest time.Duration, err error) {
oldestAt, err := r.repo.OldestUnpublished(ctx)
if err != nil {
return 0, err
}
if oldestAt.IsZero() {
return 0, nil
}
return time.Since(oldestAt), nil
}