feat(worker): lab5 implement thumbnail generation and complete job logic
This commit is contained in:
@@ -9,6 +9,7 @@ import (
|
|||||||
_ "image/png"
|
_ "image/png"
|
||||||
|
|
||||||
"high-loud-apps-labs/internal/domain"
|
"high-loud-apps-labs/internal/domain"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/disintegration/imaging"
|
"github.com/disintegration/imaging"
|
||||||
)
|
)
|
||||||
@@ -37,6 +38,7 @@ func Thumbnail(attachmentID string, imgData []byte) (*domain.AttachmentVariant,
|
|||||||
Width: thumb.Bounds().Dx(),
|
Width: thumb.Bounds().Dx(),
|
||||||
Height: thumb.Bounds().Dy(),
|
Height: thumb.Bounds().Dy(),
|
||||||
SHA256: sha[:],
|
SHA256: sha[:],
|
||||||
|
CreatedAt: time.Now().UTC(),
|
||||||
}
|
}
|
||||||
return v, data, nil
|
return v, data, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,16 +2,15 @@ package postgres
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
"high-loud-apps-labs/internal/domain"
|
"high-loud-apps-labs/internal/domain"
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// pending -> ready (успешный upload)
|
|
||||||
// pending -> failed (отказ upload или reconciler)
|
|
||||||
type AttachmentRepo struct {
|
type AttachmentRepo struct {
|
||||||
pool *pgxpool.Pool
|
pool *pgxpool.Pool
|
||||||
}
|
}
|
||||||
@@ -88,10 +87,31 @@ func (r *AttachmentRepo) GetByID(ctx context.Context, id string) (*domain.Attach
|
|||||||
return nil, notFound(err, "attachment", id)
|
return nil, notFound(err, "attachment", id)
|
||||||
}
|
}
|
||||||
a.Status = domain.AttachmentStatus(status)
|
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
|
return a, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarkReady переводит pending -> ready. Идемпотентна.
|
|
||||||
func (r *AttachmentRepo) MarkReady(ctx context.Context, id string) error {
|
func (r *AttachmentRepo) MarkReady(ctx context.Context, id string) error {
|
||||||
const q = `
|
const q = `
|
||||||
UPDATE attachments
|
UPDATE attachments
|
||||||
@@ -114,7 +134,7 @@ func (r *AttachmentRepo) MarkReady(ctx context.Context, id string) error {
|
|||||||
}
|
}
|
||||||
switch domain.AttachmentStatus(status) {
|
switch domain.AttachmentStatus(status) {
|
||||||
case domain.AttachmentStatusReady:
|
case domain.AttachmentStatusReady:
|
||||||
return nil // idempotent no-op
|
return nil
|
||||||
case domain.AttachmentStatusFailed:
|
case domain.AttachmentStatusFailed:
|
||||||
return &domain.ConflictError{Reason: "нельзя перевести failed-вложение в ready"}
|
return &domain.ConflictError{Reason: "нельзя перевести failed-вложение в ready"}
|
||||||
default:
|
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 {
|
func (r *AttachmentRepo) MarkFailed(ctx context.Context, id, errorCode string) error {
|
||||||
if errorCode == "" {
|
if errorCode == "" {
|
||||||
return &domain.ValidationError{Field: "error_code", Message: "не может быть пустым"}
|
return &domain.ValidationError{Field: "error_code", Message: "не может быть пустым"}
|
||||||
@@ -222,13 +241,13 @@ func (r *AttachmentRepo) ClaimForProcessing(ctx context.Context, id string, leas
|
|||||||
UPDATE attachments
|
UPDATE attachments
|
||||||
SET status = 'processing', locked_until = now() + $2, updated_at = now()
|
SET status = 'processing', locked_until = now() + $2, updated_at = now()
|
||||||
WHERE id = $1::uuid AND status = 'queued'
|
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
|
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 != nil {
|
||||||
if err == pgx.ErrNoRows {
|
if err == pgx.ErrNoRows {
|
||||||
return nil, nil // Задача уже взята или выполнена
|
return nil, nil
|
||||||
}
|
}
|
||||||
return nil, mapError(err)
|
return nil, mapError(err)
|
||||||
}
|
}
|
||||||
@@ -258,7 +277,10 @@ func (r *AttachmentRepo) CompleteJob(ctx context.Context, id string, pipelineVer
|
|||||||
variantRepo := NewAttachmentVariantRepo(r.pool)
|
variantRepo := NewAttachmentVariantRepo(r.pool)
|
||||||
for _, v := range variants {
|
for _, v := range variants {
|
||||||
if err := variantRepo.Upsert(ctx, &pgxTx{tx: tx}, &v); err != nil {
|
if err := variantRepo.Upsert(ctx, &pgxTx{tx: tx}, &v); err != nil {
|
||||||
|
log.Printf("CompleteJob: ошибка Upsert %s: %v", v.Name, err)
|
||||||
return false, err
|
return false, err
|
||||||
|
} else {
|
||||||
|
log.Printf("CompleteJob: успешно добавлен вариант %s", v.Name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -63,8 +63,7 @@ func (p *Pipeline) Process(ctx context.Context, attachmentID string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 4. Сохраняем оригинал в финальный prefix (chats/...)
|
// 4. Сохраняем оригинал в финальный prefix (chats/...)
|
||||||
// Внимание: a.ObjectKey уже содержит "chats/{chat_id}/{id}", заданный в API
|
if err := p.store.Put(ctx, a.ObjectKey, bytes.NewReader(buf), int64(len(buf)), a.ContentType); err != nil {
|
||||||
if err := p.store.Put(ctx, a.ObjectKey, bytes.NewReader(buf), int64(len(buf)), "image/jpeg"); err != nil {
|
|
||||||
_ = p.jobs.FailJob(ctx, a.ID, "storage_error")
|
_ = p.jobs.FailJob(ctx, a.ID, "storage_error")
|
||||||
return fmt.Errorf("загрузка оригинала: %w", err)
|
return fmt.Errorf("загрузка оригинала: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user