Реализовать уровень 3: очередь RabbitMQ и обработку изображений

Добавить устойчивый приём с ответом 202, durable jobs, dispatcher с publisher confirms и отдельный worker с ручным ACK. Формировать thumbnail, ограничить retry и защитить результат от повторной доставки. Добавить проверки очереди и адаптировать клиент к асинхронным состояниям.
This commit is contained in:
Dima
2026-11-04 19:32:01 +03:00
parent 9dfb3e5fc4
commit 495ad58cb7
27 changed files with 834 additions and 30 deletions
+147
View File
@@ -0,0 +1,147 @@
package repositories
import (
"context"
"encoding/json"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"time"
)
type Variant struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
SHA256 string `json:"sha256"`
}
type Job struct {
SchemaVersion int `json:"schema_version"`
ID string `json:"job_id"`
Type string `json:"type"`
AttachmentID string `json:"attachment_id"`
PipelineVersion int `json:"pipeline_version"`
Attempt int `json:"attempt"`
CreatedAt time.Time `json:"created_at"`
}
// QueuedJobs is also the recovery source when publish/confirm is uncertain.
// Re-publication is intentional: a durable intent is never removed by publish.
func (s *AttachmentStore) QueuedJobs(ctx context.Context) ([]Job, error) {
rows, err := s.db.Query(ctx, `SELECT j.id,j.attachment_id,j.pipeline_version,j.attempts+1,j.created_at FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.status IN ('queued','processing') AND j.next_attempt_at<=now() AND (j.lease_until IS NULL OR j.lease_until<now()) AND (j.published_at IS NULL OR j.published_at<now()-interval '30 seconds') ORDER BY j.created_at LIMIT 100`)
if err != nil {
return nil, err
}
defer rows.Close()
jobs := []Job{}
for rows.Next() {
j := Job{SchemaVersion: 1, Type: "attachment.process.v1"}
if err = rows.Scan(&j.ID, &j.AttachmentID, &j.PipelineVersion, &j.Attempt, &j.CreatedAt); err != nil {
return nil, err
}
j.CreatedAt = j.CreatedAt.UTC()
jobs = append(jobs, j)
}
return jobs, rows.Err()
}
func (s *AttachmentStore) MarkPublished(ctx context.Context, id string) error {
_, err := s.db.Exec(ctx, `UPDATE attachment_jobs SET published_at=now() WHERE id=$1`, id)
return err
}
// Claim holds a PostgreSQL row lock across object effects. Concurrent deliveries
// skip the lock. A process crash releases it; the persisted lease bounds recovery.
func (s *AttachmentStore) ProcessJob(ctx context.Context, j Job, maxAttempts int, process func(Attachment, string) ([]Variant, string, error)) error {
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())
var staging string
var attempts, version int
var a Attachment
err = tx.QueryRow(ctx, `SELECT a.id,a.object_key,a.content_type,a.size_bytes,a.sha256,a.status,j.staging_key,j.attempts,j.pipeline_version FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.id=$1 AND j.attachment_id=$2 FOR UPDATE OF j,a SKIP LOCKED`, j.ID, j.AttachmentID).Scan(&a.ID, &a.ObjectKey, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.Status, &staging, &attempts, &version)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
if a.Status == "ready" || a.Status == "failed" || version != j.PipelineVersion {
return nil
}
var due bool
if err = tx.QueryRow(ctx, `SELECT next_attempt_at<=now() FROM attachment_jobs WHERE id=$1`, j.ID).Scan(&due); err != nil {
return err
}
if !due {
return nil
}
// Attempts include interrupted executions: StartAttempt commits the counter.
if attempts > maxAttempts {
_, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=now() WHERE id=$1`, a.ID)
} else {
variants, code, workErr := process(a, staging)
if workErr == nil {
data, e := json.Marshal(variants)
if e != nil {
return e
}
_, err = tx.Exec(ctx, `UPDATE attachments SET status='ready',variants=$2,error_code=NULL,updated_at=now() WHERE id=$1`, a.ID, data)
} else if code != "" || attempts >= maxAttempts {
if code == "" {
code = "retry_exhausted"
}
_, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code=$2,updated_at=now() WHERE id=$1`, a.ID, code)
} else {
_, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=$1`, a.ID)
}
}
if err != nil {
return err
}
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET lease_until=NULL,published_at=NULL,next_attempt_at=now()+interval '2 seconds' WHERE id=$1`, j.ID)
if err != nil {
return err
}
return tx.Commit(ctx)
}
// StartAttempt publishes processing before the long transaction starts; expired
// leases are recoverable from PostgreSQL even if the broker delivery is pending.
func (s *AttachmentStore) StartAttempt(ctx context.Context, j Job, timeout time.Duration) (bool, error) {
tx, err := s.db.Begin(ctx)
if err != nil {
return false, err
}
defer tx.Rollback(context.Background())
var id string
err = tx.QueryRow(ctx, `UPDATE attachment_jobs j SET attempts=attempts+1,lease_until=now()+$2*interval '1 second' FROM attachments a WHERE j.id=$1 AND a.id=j.attachment_id AND a.status IN ('queued','processing') AND (j.lease_until IS NULL OR j.lease_until<now()) AND j.next_attempt_at<=now() RETURNING j.attachment_id`, j.ID, timeout.Seconds()+10).Scan(&id)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, err
}
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='processing',updated_at=now() WHERE id=$1`, id); err != nil {
return false, err
}
return true, tx.Commit(ctx)
}
func enqueueJob(ctx context.Context, tx pgx.Tx, a Attachment, staging string) error {
_, err := tx.Exec(ctx, `UPDATE attachments SET status='queued' WHERE id=$1`, a.ID)
if err != nil {
return err
}
_, err = tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,staging_key) VALUES($1,$2,$3)`, uuid.NewString(), a.ID, staging)
return err
}
func (s *AttachmentStore) JobTerminal(ctx context.Context, id string) (bool, error) {
var done bool
err := s.db.QueryRow(ctx, `SELECT a.status IN ('ready','failed') FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.id=$1`, id).Scan(&done)
return done, err
}