Files
mtusi2026lab5/backend/internal/worker/pipeline.go
T

180 lines
5.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package worker
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"time"
"high-loud-apps-labs/internal/domain"
"high-loud-apps-labs/internal/imaging"
)
type Pipeline struct {
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,
failedJobs domain.FailedJobRepository,
outbox domain.OutboxRepository,
) *Pipeline {
return &Pipeline{
jobs: jobs,
store: store,
variants: variants,
failedJobs: failedJobs,
outbox: outbox,
lease: 5 * time.Minute,
maxRetries: 5,
}
}
func (p *Pipeline) Process(ctx context.Context, attachmentID string, pipelineVersion int) error {
log.Printf("worker: начало обработки %s (версия пайплайна %d)", attachmentID, pipelineVersion)
jobCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// 1. Забираем задачу с проверкой версии
a, err := p.jobs.ClaimForProcessing(jobCtx, attachmentID, pipelineVersion, p.lease)
if err != nil {
return fmt.Errorf("захват задачи: %w", err)
}
if a == nil {
log.Printf("worker: задача %s уже взята, выполнена или версия устарела", attachmentID)
return nil // no-op
}
// 2. Скачиваем оригинал из staging
rc, _, _, err := p.store.Get(jobCtx, a.StagingKey)
if err != nil {
return p.handleFailure(a, fmt.Errorf("скачивание staging: %w", err), false)
}
defer rc.Close()
buf, err := io.ReadAll(rc)
if err != nil {
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 {
return p.handleFailure(a, fmt.Errorf("генерация thumbnail: %w", err), true)
}
cropMeta, cropData, err := imaging.Crop(a.ID, buf)
if err != nil {
return p.handleFailure(a, fmt.Errorf("генерация crop: %w", err), true)
}
webpMeta, webpData, err := imaging.Optimized(a.ID, buf)
if err != nil {
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 {
return p.handleFailure(a, fmt.Errorf("загрузка оригинала: %w", err), false)
}
// 5. Загружаем все сгенерированные варианты в S3
variants := []domain.AttachmentVariant{*thumbMeta, *cropMeta, *webpMeta}
for i := range variants {
v := &variants[i]
key := fmt.Sprintf("%s/%s", a.ObjectKey, v.Name)
var data []byte
switch v.Name {
case domain.VariantThumbnail:
data = thumbData
case domain.VariantCrop:
data = cropData
case domain.VariantOptimized:
data = webpData
}
if err := p.store.Put(jobCtx, key, bytes.NewReader(data), v.SizeBytes, v.ContentType); err != nil {
return p.handleFailure(a, fmt.Errorf("загрузка варианта %s: %w", v.Name, err), false)
}
v.ObjectKey = key
}
// 6. Фиксируем результат в БД (переводим в ready)
ok, err := p.jobs.CompleteJob(jobCtx, a.ID, a.PipelineVersion, variants)
if err != nil {
return p.handleFailure(a, fmt.Errorf("фиксация в БД: %w", err), false)
}
if !ok {
log.Printf("worker: версия устарела или статус изменился, пропускаем %s", a.ID)
return nil
}
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
}