From 22c876f63c8f59bab69a5867ef8495c1795b599e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=93=D0=BE=D0=BB=D0=B8=D0=BA=D0=BE=D0=B2=20Maximillian?= =?UTF-8?q?=20=D0=90=D0=BD=D1=82=D0=BE=D0=BD?= Date: Mon, 9 Nov 2026 12:39:59 +0300 Subject: [PATCH] feat(worker): lab5 implement thumbnail generation and complete job logic --- backend/internal/imaging/thumbnail.go | 2 + .../internal/storage/postgres/attachments.go | 40 ++++++++++++++----- backend/internal/worker/pipeline.go | 3 +- 3 files changed, 34 insertions(+), 11 deletions(-) diff --git a/backend/internal/imaging/thumbnail.go b/backend/internal/imaging/thumbnail.go index db08daa6..a36028f6 100644 --- a/backend/internal/imaging/thumbnail.go +++ b/backend/internal/imaging/thumbnail.go @@ -9,6 +9,7 @@ import ( _ "image/png" "high-loud-apps-labs/internal/domain" + "time" "github.com/disintegration/imaging" ) @@ -37,6 +38,7 @@ func Thumbnail(attachmentID string, imgData []byte) (*domain.AttachmentVariant, Width: thumb.Bounds().Dx(), Height: thumb.Bounds().Dy(), SHA256: sha[:], + CreatedAt: time.Now().UTC(), } return v, data, nil } diff --git a/backend/internal/storage/postgres/attachments.go b/backend/internal/storage/postgres/attachments.go index d6fe3274..42ec3b22 100644 --- a/backend/internal/storage/postgres/attachments.go +++ b/backend/internal/storage/postgres/attachments.go @@ -2,16 +2,15 @@ package postgres import ( "context" + "log" + "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "high-loud-apps-labs/internal/domain" - "time" ) -// pending -> ready (успешный upload) -// pending -> failed (отказ upload или reconciler) type AttachmentRepo struct { pool *pgxpool.Pool } @@ -88,10 +87,31 @@ func (r *AttachmentRepo) GetByID(ctx context.Context, id string) (*domain.Attach return nil, notFound(err, "attachment", id) } a.Status = domain.AttachmentStatus(status) + + rows, err := r.pool.Query(ctx, ` + SELECT name, object_key, content_type, size_bytes, width, height, sha256, created_at + FROM attachment_variants + WHERE attachment_id = $1::uuid + ORDER BY name + `, id) + if err != nil { + log.Printf("GetByID: ошибка запроса variants: %v", err) + } else { + defer rows.Close() + for rows.Next() { + var v domain.AttachmentVariant + v.AttachmentID = id + if err := rows.Scan(&v.Name, &v.ObjectKey, &v.ContentType, &v.SizeBytes, &v.Width, &v.Height, &v.SHA256, &v.CreatedAt); err != nil { + log.Printf("GetByID: ошибка Scan variant: %v", err) + } else { + a.Variants = append(a.Variants, v) + } + } + } + return a, nil } -// MarkReady переводит pending -> ready. Идемпотентна. func (r *AttachmentRepo) MarkReady(ctx context.Context, id string) error { const q = ` UPDATE attachments @@ -114,7 +134,7 @@ func (r *AttachmentRepo) MarkReady(ctx context.Context, id string) error { } switch domain.AttachmentStatus(status) { case domain.AttachmentStatusReady: - return nil // idempotent no-op + return nil case domain.AttachmentStatusFailed: return &domain.ConflictError{Reason: "нельзя перевести failed-вложение в ready"} default: @@ -122,7 +142,6 @@ func (r *AttachmentRepo) MarkReady(ctx context.Context, id string) error { } } -// MarkFailed переводит pending -> failed. Идемпотентна. func (r *AttachmentRepo) MarkFailed(ctx context.Context, id, errorCode string) error { if errorCode == "" { return &domain.ValidationError{Field: "error_code", Message: "не может быть пустым"} @@ -222,13 +241,13 @@ func (r *AttachmentRepo) ClaimForProcessing(ctx context.Context, id string, leas UPDATE attachments SET status = 'processing', locked_until = now() + $2, updated_at = now() WHERE id = $1::uuid AND status = 'queued' - RETURNING id, chat_id, staging_key, pipeline_version + RETURNING id, chat_id, staging_key, pipeline_version, object_key, content_type ` var a domain.Attachment - err := r.pool.QueryRow(ctx, q, id, lease).Scan(&a.ID, &a.ChatID, &a.StagingKey, &a.PipelineVersion) + err := r.pool.QueryRow(ctx, q, id, lease).Scan(&a.ID, &a.ChatID, &a.StagingKey, &a.PipelineVersion, &a.ObjectKey, &a.ContentType) if err != nil { if err == pgx.ErrNoRows { - return nil, nil // Задача уже взята или выполнена + return nil, nil } return nil, mapError(err) } @@ -258,7 +277,10 @@ func (r *AttachmentRepo) CompleteJob(ctx context.Context, id string, pipelineVer variantRepo := NewAttachmentVariantRepo(r.pool) for _, v := range variants { if err := variantRepo.Upsert(ctx, &pgxTx{tx: tx}, &v); err != nil { + log.Printf("CompleteJob: ошибка Upsert %s: %v", v.Name, err) return false, err + } else { + log.Printf("CompleteJob: успешно добавлен вариант %s", v.Name) } } diff --git a/backend/internal/worker/pipeline.go b/backend/internal/worker/pipeline.go index a13a4f2b..3dc5b137 100644 --- a/backend/internal/worker/pipeline.go +++ b/backend/internal/worker/pipeline.go @@ -63,8 +63,7 @@ func (p *Pipeline) Process(ctx context.Context, attachmentID string) error { } // 4. Сохраняем оригинал в финальный prefix (chats/...) - // Внимание: a.ObjectKey уже содержит "chats/{chat_id}/{id}", заданный в API - if err := p.store.Put(ctx, a.ObjectKey, bytes.NewReader(buf), int64(len(buf)), "image/jpeg"); err != nil { + if err := p.store.Put(ctx, a.ObjectKey, bytes.NewReader(buf), int64(len(buf)), a.ContentType); err != nil { _ = p.jobs.FailJob(ctx, a.ID, "storage_error") return fmt.Errorf("загрузка оригинала: %w", err) }