forked from mtusi2026/mtusi2026lab5
Реализовать уровень 4 и упорядочить структуру backend
Добавить crop и WebP, изолированную обработку с таймаутом, lease token, backoff с jitter, реестр failed, безопасный replay и очистку staging. Добавить проверки crash-окон и восстановления. Разделить запуск API, CLI-команды, фоновые процессы и инфраструктуру по пакетам.
This commit is contained in:
@@ -2,10 +2,12 @@ package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"math/big"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -51,84 +53,142 @@ func (s *AttachmentStore) MarkPublished(ctx context.Context, id string) error {
|
||||
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 {
|
||||
// StartAttempt commits the lease and attempt before decoding. A token fences a
|
||||
// consumer that was paused between claim and processing past its lease deadline.
|
||||
func (s *AttachmentStore) StartAttempt(ctx context.Context, j Job, timeout time.Duration, maxAttempts int) (string, error) {
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var status string
|
||||
var attempts, generation int
|
||||
var available bool
|
||||
err = tx.QueryRow(ctx, `SELECT a.status,j.attempts,j.generation,j.next_attempt_at<=now() AND (j.lease_until IS NULL OR j.lease_until<now()) FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.id=$1 AND j.attachment_id=$2 AND j.pipeline_version=$3 FOR UPDATE OF j,a SKIP LOCKED`, j.ID, j.AttachmentID, j.PipelineVersion).Scan(&status, &attempts, &generation, &available)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if status == "ready" || status == "failed" || !available {
|
||||
return "", nil
|
||||
}
|
||||
// A crashed attempt remains visible in the audit trail.
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachment_job_attempts SET finished_at=clock_timestamp(),error_code='processing_timeout' WHERE job_id=$1 AND finished_at IS NULL`, j.ID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if attempts >= maxAttempts {
|
||||
if err = failJob(ctx, tx, j, "retry_exhausted", attempts); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "", tx.Commit(ctx)
|
||||
}
|
||||
token := uuid.NewString()
|
||||
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET attempts=attempts+1,lease_token=$2,lease_until=now()+$3*interval '1 second' WHERE id=$1`, j.ID, token, timeout.Seconds()+5)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='processing',updated_at=now() WHERE id=$1`, j.AttachmentID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO attachment_job_attempts(job_id,generation,attempt) VALUES($1,$2,$3)`, j.ID, generation, attempts+1); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return token, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
var ErrProcessingTimeout = errors.New("processing timeout")
|
||||
|
||||
// ProcessJob holds the row lock across deterministic object writes. The lock and
|
||||
// token check prevent overlapping/stale attempts from publishing metadata.
|
||||
func (s *AttachmentStore) ProcessJob(ctx context.Context, j Job, token string, 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 attempts, generation 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)
|
||||
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.generation FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.id=$1 AND j.attachment_id=$2 AND j.pipeline_version=$3 AND j.lease_token=$4 AND j.lease_until>now() FOR UPDATE OF j,a`, j.ID, j.AttachmentID, j.PipelineVersion, token).Scan(&a.ID, &a.ObjectKey, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.Status, &staging, &attempts, &generation)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
return errors.New("stale job lease")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.Status == "ready" || a.Status == "failed" || version != j.PipelineVersion {
|
||||
return nil
|
||||
if a.Status != "processing" {
|
||||
return errors.New("job is not processing")
|
||||
}
|
||||
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)
|
||||
variants, code, workErr := process(a, staging)
|
||||
var next *time.Time
|
||||
var auditCode *string
|
||||
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 {
|
||||
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 {
|
||||
reason := "temporary_failure"
|
||||
if errors.Is(workErr, ErrProcessingTimeout) {
|
||||
reason = "processing_timeout"
|
||||
}
|
||||
if code != "" {
|
||||
reason = code
|
||||
}
|
||||
auditCode = &reason
|
||||
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)
|
||||
err = failJob(ctx, tx, j, code, attempts)
|
||||
} else {
|
||||
due := time.Now().UTC().Add(RetryDelay(attempts))
|
||||
next = &due
|
||||
_, 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)
|
||||
_, err = tx.Exec(ctx, `UPDATE attachment_job_attempts SET finished_at=clock_timestamp(),error_code=$4,next_attempt_at=$5 WHERE job_id=$1 AND generation=$2 AND attempt=$3`, j.ID, generation, attempts, auditCode, next)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET lease_until=NULL,lease_token=NULL,published_at=NULL,next_attempt_at=COALESCE($2,now()) WHERE id=$1`, j.ID, next)
|
||||
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)
|
||||
func failJob(ctx context.Context, tx pgx.Tx, j Job, code string, attempts int) error {
|
||||
if _, err := tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code=$2,updated_at=now() WHERE id=$1`, j.AttachmentID, code); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE attachment_jobs SET lease_token=NULL,lease_until=NULL WHERE id=$1`, j.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(ctx, `INSERT INTO attachment_job_failures(job_id,error_code,attempts) VALUES($1,$2,$3) ON CONFLICT(job_id) DO UPDATE SET error_code=EXCLUDED.error_code,attempts=EXCLUDED.attempts,failed_at=clock_timestamp()`, j.ID, code, attempts)
|
||||
return err
|
||||
}
|
||||
|
||||
// Equal jitter: exponential ceiling 2,4,8,...,30 seconds; delay in [ceiling/2,ceiling).
|
||||
func RetryDelay(attempt int) time.Duration {
|
||||
ceiling := 2 * time.Second
|
||||
for i := 1; i < attempt && ceiling < 30*time.Second; i++ {
|
||||
ceiling *= 2
|
||||
}
|
||||
if ceiling > 30*time.Second {
|
||||
ceiling = 30 * time.Second
|
||||
}
|
||||
n, err := rand.Int(rand.Reader, big.NewInt(int64(ceiling/2)))
|
||||
if err != nil {
|
||||
return false, err
|
||||
return ceiling
|
||||
}
|
||||
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)
|
||||
return ceiling/2 + time.Duration(n.Int64())
|
||||
}
|
||||
|
||||
func enqueueJob(ctx context.Context, tx pgx.Tx, a Attachment, staging string) error {
|
||||
|
||||
Reference in New Issue
Block a user