feat(worker): lab5 add exponential backoff retries and permanent error classification

This commit is contained in:
Голиков Maximillian Антон
2026-11-10 15:28:20 +03:00
parent 8fb191fc78
commit 996e305ea4
3 changed files with 91 additions and 25 deletions
+1 -1
View File
@@ -58,7 +58,7 @@ func main() {
}
defer ch.Close()
// Prefetch: сколько сообщений worker берет разом (защита от перегрузки)
// Сколько сообщений worker берет разом (защита от перегрузки)
ch.Qos(2, 0, false)
q, err := ch.QueueDeclare("attachments.process", true, false, false, false, nil)
+10
View File
@@ -0,0 +1,10 @@
package domain
const (
JobErrorDecodeFailed = "decode_failed"
JobErrorTooLarge = "too_large"
JobErrorUnsupportedFormat = "unsupported_format"
JobErrorStorage = "storage_error"
JobErrorInternal = "internal_error"
JobErrorRetryExhausted = "retry_exhausted"
)
+80 -24
View File
@@ -3,9 +3,11 @@ package worker
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"time"
"high-loud-apps-labs/internal/domain"
@@ -13,18 +15,30 @@ import (
)
type Pipeline struct {
jobs domain.AttachmentJobRepository
store domain.ObjectStorage
variants domain.AttachmentVariantRepository
lease time.Duration
jobs domain.AttachmentJobRepository
store domain.ObjectStorage
variants domain.AttachmentVariantRepository
failedJobs domain.FailedJobRepository
outbox domain.OutboxRepository
lease time.Duration
maxRetries int
}
func NewPipeline(jobs domain.AttachmentJobRepository, store domain.ObjectStorage, variants domain.AttachmentVariantRepository) *Pipeline {
func NewPipeline(
jobs domain.AttachmentJobRepository,
store domain.ObjectStorage,
variants domain.AttachmentVariantRepository,
failedJobs domain.FailedJobRepository,
outbox domain.OutboxRepository,
) *Pipeline {
return &Pipeline{
jobs: jobs,
store: store,
variants: variants,
lease: 5 * time.Minute,
jobs: jobs,
store: store,
variants: variants,
failedJobs: failedJobs,
outbox: outbox,
lease: 5 * time.Minute,
maxRetries: 5,
}
}
@@ -47,41 +61,35 @@ func (p *Pipeline) Process(ctx context.Context, attachmentID string) error {
// 2. Скачиваем оригинал из staging
rc, _, _, err := p.store.Get(jobCtx, a.StagingKey)
if err != nil {
_ = p.jobs.FailJob(context.Background(), a.ID, "storage_error")
return fmt.Errorf("скачивание staging: %w", err)
return p.handleFailure(a, fmt.Errorf("скачивание staging: %w", err), false)
}
defer rc.Close()
buf, err := io.ReadAll(rc)
if err != nil {
_ = p.jobs.FailJob(context.Background(), a.ID, "storage_error")
return fmt.Errorf("чтение staging: %w", err)
return p.handleFailure(a, fmt.Errorf("чтение staging: %w", err), false)
}
// 3. Генерируем все варианты (Thumbnail, Crop, Optimized)
log.Printf("worker: генерация вариантов для %s", a.ID)
thumbMeta, thumbData, err := imaging.Thumbnail(a.ID, buf)
if err != nil {
_ = p.jobs.FailJob(context.Background(), a.ID, "decode_failed")
return fmt.Errorf("генерация thumbnail: %w", err)
return p.handleFailure(a, fmt.Errorf("генерация thumbnail: %w", err), true)
}
cropMeta, cropData, err := imaging.Crop(a.ID, buf)
if err != nil {
_ = p.jobs.FailJob(context.Background(), a.ID, "decode_failed")
return fmt.Errorf("генерация crop: %w", err)
return p.handleFailure(a, fmt.Errorf("генерация crop: %w", err), true)
}
webpMeta, webpData, err := imaging.Optimized(a.ID, buf)
if err != nil {
_ = p.jobs.FailJob(context.Background(), a.ID, "decode_failed")
return fmt.Errorf("генерация webp: %w", err)
return p.handleFailure(a, fmt.Errorf("генерация webp: %w", err), true)
}
// 4. Сохраняем оригинал в финальный prefix (chats/...)
if err := p.store.Put(jobCtx, a.ObjectKey, bytes.NewReader(buf), int64(len(buf)), a.ContentType); err != nil {
_ = p.jobs.FailJob(context.Background(), a.ID, "storage_error")
return fmt.Errorf("загрузка оригинала: %w", err)
return p.handleFailure(a, fmt.Errorf("загрузка оригинала: %w", err), false)
}
// 5. Загружаем все сгенерированные варианты в S3
@@ -102,8 +110,7 @@ func (p *Pipeline) Process(ctx context.Context, attachmentID string) error {
}
if err := p.store.Put(jobCtx, key, bytes.NewReader(data), v.SizeBytes, v.ContentType); err != nil {
_ = p.jobs.FailJob(context.Background(), a.ID, "storage_error")
return fmt.Errorf("загрузка варианта %s: %w", v.Name, err)
return p.handleFailure(a, fmt.Errorf("загрузка варианта %s: %w", v.Name, err), false)
}
v.ObjectKey = key
}
@@ -111,7 +118,7 @@ func (p *Pipeline) Process(ctx context.Context, attachmentID string) error {
// 6. Фиксируем результат в БД (переводим в ready)
ok, err := p.jobs.CompleteJob(jobCtx, a.ID, a.PipelineVersion, variants)
if err != nil {
return fmt.Errorf("фиксация в БД: %w", err)
return p.handleFailure(a, fmt.Errorf("фиксация в БД: %w", err), false)
}
if !ok {
log.Printf("worker: версия устарела или статус изменился, пропускаем %s", a.ID)
@@ -121,3 +128,52 @@ func (p *Pipeline) Process(ctx context.Context, attachmentID string) error {
log.Printf("worker: успешно завершено %s", a.ID)
return nil
}
func (p *Pipeline) handleFailure(a *domain.Attachment, err error, isPermanent bool) error {
// Если исчерпаны попытки или ошибка постоянная (например, битый файл)
if isPermanent || a.Attempts >= p.maxRetries {
reason := domain.JobErrorInternal
if a.Attempts >= p.maxRetries {
reason = domain.JobErrorRetryExhausted
} else if isPermanent {
reason = domain.JobErrorDecodeFailed
}
log.Printf("worker: финальная ошибка для %s (попытка %d): %v", a.ID, a.Attempts, err)
// Используем context.Background(), чтобы запись в БД прошла даже при истекшем jobCtx
_ = p.jobs.FailJob(context.Background(), a.ID, reason)
_ = p.failedJobs.Record(context.Background(), &domain.FailedJob{
AttachmentID: a.ID,
ReasonCode: reason,
Attempts: a.Attempts,
})
return nil
}
// Временная ошибка - делаем Retry с backoff
log.Printf("worker: временная ошибка для %s, попытка %d: %v", a.ID, a.Attempts, err)
// Экспоненциальный backoff: 2^attempts секунд + случайный jitter (0-1000 мс)
backoff := time.Duration(1<<uint(a.Attempts)) * time.Second
jitter := time.Duration(rand.Intn(1000)) * time.Millisecond
nextAt := time.Now().UTC().Add(backoff + jitter)
_ = p.jobs.ScheduleRetry(context.Background(), a.ID, nextAt, "")
// Кладем в Outbox отложенное сообщение
payload, _ := json.Marshal(domain.JobMessage{
AttachmentID: a.ID,
PipelineVersion: a.PipelineVersion,
Attempt: a.Attempts + 1,
})
_ = p.outbox.EnqueueDirect(context.Background(), &domain.OutboxEntry{
AggregateType: domain.OutboxAggregateAttachment,
AggregateID: a.ID,
EventType: domain.OutboxEventProcess,
Payload: payload,
CreatedAt: nextAt,
})
return nil
}