chore: get files from lab6

This commit is contained in:
Голиков Maximillian Антон
2026-11-24 22:32:11 +03:00
parent 20afc2c790
commit 9b88c6f0bd
118 changed files with 9682 additions and 0 deletions
+65
View File
@@ -0,0 +1,65 @@
package worker
import (
"context"
"log/slog"
"time"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
"high-loud-apps-labs/internal/domain"
"high-loud-apps-labs/internal/telemetry"
)
type jobMetrics struct {
processed metric.Int64Counter
duration metric.Float64Histogram
ready metric.Float64Histogram
}
func newJobMetrics() jobMetrics {
meter := telemetry.Meter("worker.pipeline")
processed, err := meter.Int64Counter("jobs_processed_total")
if err != nil {
panic(err)
}
unit := metric.WithUnit("s")
duration, err := meter.Float64Histogram("job_processing_duration_seconds", unit,
metric.WithExplicitBucketBoundaries(.01, .05, .1, .25, .5, 1, 2, 5, 10, 30, 60))
if err != nil {
panic(err)
}
ready, err := meter.Float64Histogram("end_to_end_ready_seconds", unit,
metric.WithExplicitBucketBoundaries(.1, .5, 1, 2, 5, 10, 30, 60, 120, 300, 900, 3600))
if err != nil {
panic(err)
}
return jobMetrics{processed: processed, duration: duration, ready: ready}
}
func (m jobMetrics) recordAttempt(ctx context.Context, start time.Time, outcome string) {
attrs := metric.WithAttributes(attribute.String("job.type", domain.OutboxEventProcess), attribute.String("outcome", outcome))
m.duration.Record(ctx, time.Since(start).Seconds(), attrs)
m.processed.Add(ctx, 1, attrs)
span := trace.SpanFromContext(ctx)
span.SetAttributes(attribute.String("job.outcome", outcome))
level := slog.LevelInfo
switch outcome {
case "failed", "error", "retry":
level = slog.LevelWarn
span.SetStatus(codes.Error, outcome)
}
slog.Log(ctx, level, "Попытка обработки завершена", "event", "job.processed", "outcome", outcome)
}
func (m jobMetrics) recordReady(ctx context.Context, createdAt time.Time) {
if createdAt.IsZero() {
return
}
m.ready.Record(ctx, max(0, time.Since(createdAt).Seconds()),
metric.WithAttributes(attribute.String("job.type", domain.OutboxEventProcess)))
}
+228
View File
@@ -0,0 +1,228 @@
package worker
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"time"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"high-loud-apps-labs/internal/domain"
"high-loud-apps-labs/internal/imaging"
"high-loud-apps-labs/internal/telemetry"
)
type Pipeline struct {
jobs domain.AttachmentJobRepository
store domain.ObjectStorage
variants domain.AttachmentVariantRepository
failedJobs domain.FailedJobRepository
outbox domain.OutboxRepository
lease time.Duration
maxRetries int
metrics jobMetrics
}
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,
metrics: newJobMetrics(),
}
}
func (p *Pipeline) Process(ctx context.Context, attachmentID string, pipelineVersion int) error {
start := time.Now()
outcome := "error"
defer func() { p.metrics.recordAttempt(ctx, start, outcome) }()
log.Printf("worker: начало обработки %s (версия пайплайна %d)", attachmentID, pipelineVersion)
jobCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
tracer := telemetry.Tracer("worker.pipeline")
// 1. Забираем задачу с проверкой версии
claimCtx, claimSpan := tracer.Start(jobCtx, "job.claim")
a, err := p.jobs.ClaimForProcessing(claimCtx, attachmentID, pipelineVersion, p.lease)
endPipelineSpan(claimSpan, err)
if err != nil {
return fmt.Errorf("захват задачи: %w", err)
}
if a == nil {
outcome = "skipped"
log.Printf("worker: задача %s уже взята, выполнена или версия устарела", attachmentID)
return nil // no-op
}
fail := func(err error, permanent bool) error {
outcome = p.handleFailure(context.WithoutCancel(ctx), a, err, permanent)
return nil
}
// 2. Скачиваем оригинал из staging
getCtx, getSpan := tracer.Start(jobCtx, "job.s3.get")
rc, _, _, err := p.store.Get(getCtx, a.StagingKey)
if err != nil {
endPipelineSpan(getSpan, err)
return fail(fmt.Errorf("скачивание staging: %w", err), false)
}
defer rc.Close()
buf, err := io.ReadAll(rc)
endPipelineSpan(getSpan, err)
if err != nil {
return fail(fmt.Errorf("чтение staging: %w", err), false)
}
// 3. Генерируем все варианты (Thumbnail, Crop, Optimized)
log.Printf("worker: генерация вариантов для %s", a.ID)
_, imageSpan := tracer.Start(jobCtx, "job.image.process")
thumbMeta, thumbData, err := imaging.Thumbnail(a.ID, buf)
if err != nil {
endPipelineSpan(imageSpan, err)
return fail(fmt.Errorf("генерация thumbnail: %w", err), true)
}
cropMeta, cropData, err := imaging.Crop(a.ID, buf)
if err != nil {
endPipelineSpan(imageSpan, err)
return fail(fmt.Errorf("генерация crop: %w", err), true)
}
webpMeta, webpData, err := imaging.Optimized(a.ID, buf)
endPipelineSpan(imageSpan, err)
if err != nil {
return fail(fmt.Errorf("генерация webp: %w", err), true)
}
// 4. Сохраняем оригинал в финальный prefix (chats/...)
putCtx, putSpan := tracer.Start(jobCtx, "job.s3.put")
if err := p.store.Put(putCtx, a.ObjectKey, bytes.NewReader(buf), int64(len(buf)), a.ContentType); err != nil {
endPipelineSpan(putSpan, err)
return fail(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(putCtx, key, bytes.NewReader(data), v.SizeBytes, v.ContentType); err != nil {
endPipelineSpan(putSpan, err)
return fail(fmt.Errorf("загрузка варианта %s: %w", v.Name, err), false)
}
v.ObjectKey = key
}
putSpan.End()
// 6. Фиксируем результат в БД (переводим в ready)
completeCtx, completeSpan := tracer.Start(jobCtx, "job.db.complete")
ok, err := p.jobs.CompleteJob(completeCtx, a.ID, a.PipelineVersion, variants)
endPipelineSpan(completeSpan, err)
if err != nil {
return fail(fmt.Errorf("фиксация в БД: %w", err), false)
}
if !ok {
outcome = "skipped"
log.Printf("worker: версия устарела или статус изменился, пропускаем %s", a.ID)
return nil
}
outcome = "ready"
p.metrics.recordReady(ctx, a.CreatedAt)
log.Printf("worker: успешно завершено %s", a.ID)
return nil
}
func endPipelineSpan(span trace.Span, err error) {
if err != nil {
span.SetStatus(codes.Error, "операция завершилась ошибкой")
}
span.End()
}
func (p *Pipeline) handleFailure(ctx context.Context, a *domain.Attachment, err error, isPermanent bool) string {
// Если исчерпаны попытки или ошибка постоянная (например, битый файл)
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
updateErr := p.jobs.FailJob(context.Background(), a.ID, reason)
recordErr := p.failedJobs.Record(context.Background(), &domain.FailedJob{
AttachmentID: a.ID,
ReasonCode: reason,
Attempts: a.Attempts,
})
if updateErr != nil || recordErr != nil {
return "error"
}
return "failed"
}
// Временная ошибка - делаем 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)
scheduleErr := p.jobs.ScheduleRetry(ctx, a.ID, nextAt, "")
// Кладем в Outbox отложенное сообщение
payload, _ := json.Marshal(domain.JobMessage{
AttachmentID: a.ID,
PipelineVersion: a.PipelineVersion,
Attempt: a.Attempts + 1,
})
enqueueErr := p.outbox.EnqueueDirect(ctx, &domain.OutboxEntry{
AggregateType: domain.OutboxAggregateAttachment,
AggregateID: a.ID,
EventType: domain.OutboxEventProcess,
Payload: payload,
CreatedAt: nextAt,
})
if scheduleErr != nil || enqueueErr != nil {
return "error"
}
return "retry"
}