feat(worker): lab5 add exponential backoff retries and permanent error classification
This commit is contained in:
@@ -58,7 +58,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
defer ch.Close()
|
defer ch.Close()
|
||||||
|
|
||||||
// Prefetch: сколько сообщений worker берет разом (защита от перегрузки)
|
// Сколько сообщений worker берет разом (защита от перегрузки)
|
||||||
ch.Qos(2, 0, false)
|
ch.Qos(2, 0, false)
|
||||||
|
|
||||||
q, err := ch.QueueDeclare("attachments.process", true, false, false, false, nil)
|
q, err := ch.QueueDeclare("attachments.process", true, false, false, false, nil)
|
||||||
|
|||||||
@@ -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"
|
||||||
|
)
|
||||||
@@ -3,9 +3,11 @@ package worker
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
|
"math/rand"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"high-loud-apps-labs/internal/domain"
|
"high-loud-apps-labs/internal/domain"
|
||||||
@@ -13,18 +15,30 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Pipeline struct {
|
type Pipeline struct {
|
||||||
jobs domain.AttachmentJobRepository
|
jobs domain.AttachmentJobRepository
|
||||||
store domain.ObjectStorage
|
store domain.ObjectStorage
|
||||||
variants domain.AttachmentVariantRepository
|
variants domain.AttachmentVariantRepository
|
||||||
lease time.Duration
|
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{
|
return &Pipeline{
|
||||||
jobs: jobs,
|
jobs: jobs,
|
||||||
store: store,
|
store: store,
|
||||||
variants: variants,
|
variants: variants,
|
||||||
lease: 5 * time.Minute,
|
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
|
// 2. Скачиваем оригинал из staging
|
||||||
rc, _, _, err := p.store.Get(jobCtx, a.StagingKey)
|
rc, _, _, err := p.store.Get(jobCtx, a.StagingKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = p.jobs.FailJob(context.Background(), a.ID, "storage_error")
|
return p.handleFailure(a, fmt.Errorf("скачивание staging: %w", err), false)
|
||||||
return fmt.Errorf("скачивание staging: %w", err)
|
|
||||||
}
|
}
|
||||||
defer rc.Close()
|
defer rc.Close()
|
||||||
|
|
||||||
buf, err := io.ReadAll(rc)
|
buf, err := io.ReadAll(rc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = p.jobs.FailJob(context.Background(), a.ID, "storage_error")
|
return p.handleFailure(a, fmt.Errorf("чтение staging: %w", err), false)
|
||||||
return fmt.Errorf("чтение staging: %w", err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Генерируем все варианты (Thumbnail, Crop, Optimized)
|
// 3. Генерируем все варианты (Thumbnail, Crop, Optimized)
|
||||||
log.Printf("worker: генерация вариантов для %s", a.ID)
|
log.Printf("worker: генерация вариантов для %s", a.ID)
|
||||||
thumbMeta, thumbData, err := imaging.Thumbnail(a.ID, buf)
|
thumbMeta, thumbData, err := imaging.Thumbnail(a.ID, buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = p.jobs.FailJob(context.Background(), a.ID, "decode_failed")
|
return p.handleFailure(a, fmt.Errorf("генерация thumbnail: %w", err), true)
|
||||||
return fmt.Errorf("генерация thumbnail: %w", err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
cropMeta, cropData, err := imaging.Crop(a.ID, buf)
|
cropMeta, cropData, err := imaging.Crop(a.ID, buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = p.jobs.FailJob(context.Background(), a.ID, "decode_failed")
|
return p.handleFailure(a, fmt.Errorf("генерация crop: %w", err), true)
|
||||||
return fmt.Errorf("генерация crop: %w", err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
webpMeta, webpData, err := imaging.Optimized(a.ID, buf)
|
webpMeta, webpData, err := imaging.Optimized(a.ID, buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = p.jobs.FailJob(context.Background(), a.ID, "decode_failed")
|
return p.handleFailure(a, fmt.Errorf("генерация webp: %w", err), true)
|
||||||
return fmt.Errorf("генерация webp: %w", err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Сохраняем оригинал в финальный prefix (chats/...)
|
// 4. Сохраняем оригинал в финальный prefix (chats/...)
|
||||||
if err := p.store.Put(jobCtx, a.ObjectKey, bytes.NewReader(buf), int64(len(buf)), a.ContentType); err != nil {
|
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 p.handleFailure(a, fmt.Errorf("загрузка оригинала: %w", err), false)
|
||||||
return fmt.Errorf("загрузка оригинала: %w", err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Загружаем все сгенерированные варианты в S3
|
// 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 {
|
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 p.handleFailure(a, fmt.Errorf("загрузка варианта %s: %w", v.Name, err), false)
|
||||||
return fmt.Errorf("загрузка варианта %s: %w", v.Name, err)
|
|
||||||
}
|
}
|
||||||
v.ObjectKey = key
|
v.ObjectKey = key
|
||||||
}
|
}
|
||||||
@@ -111,7 +118,7 @@ func (p *Pipeline) Process(ctx context.Context, attachmentID string) error {
|
|||||||
// 6. Фиксируем результат в БД (переводим в ready)
|
// 6. Фиксируем результат в БД (переводим в ready)
|
||||||
ok, err := p.jobs.CompleteJob(jobCtx, a.ID, a.PipelineVersion, variants)
|
ok, err := p.jobs.CompleteJob(jobCtx, a.ID, a.PipelineVersion, variants)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("фиксация в БД: %w", err)
|
return p.handleFailure(a, fmt.Errorf("фиксация в БД: %w", err), false)
|
||||||
}
|
}
|
||||||
if !ok {
|
if !ok {
|
||||||
log.Printf("worker: версия устарела или статус изменился, пропускаем %s", a.ID)
|
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)
|
log.Printf("worker: успешно завершено %s", a.ID)
|
||||||
return nil
|
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
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user