forked from mtusi2026/mtusi2026lab5
feat(lab5): durable async attachment pipeline through grade 4
- RabbitMQ quorum queue, persistent messages and publisher confirms - S3 staging plus PostgreSQL attachments/jobs outbox transaction - worker variants (thumbnail, crop, optimized WebP), DB lease and lease sweeper - jittered retry, permanent failures, explicit replay and admission cap - deterministic crash hooks, resilience script and evidence for grade 4 - async-aware custom tests, oversized pixel case, docs and changelog
This commit is contained in:
@@ -3,6 +3,7 @@ package store
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
@@ -12,10 +13,11 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// CreatePendingAttachment records the intent to store an object before the S3
|
||||
// PUT happens. Committing this row first is what makes the reconciler able to
|
||||
// distinguish "never uploaded" from "uploaded but process died".
|
||||
func (s *Store) CreatePendingAttachment(ctx context.Context, att model.Attachment) error {
|
||||
// CreateQueuedAttachment is the durability boundary of the upload endpoint.
|
||||
// The attachment snapshot and the outbox job commit together, so there is no
|
||||
// observable state in which the API promised work but PostgreSQL lost the
|
||||
// intent. Publication to RabbitMQ happens later and may be retried safely.
|
||||
func (s *Store) CreateQueuedAttachment(ctx context.Context, att model.Attachment, job model.JobRecord) error {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
@@ -23,58 +25,74 @@ func (s *Store) CreatePendingAttachment(ctx context.Context, att model.Attachmen
|
||||
if err != nil {
|
||||
return common.BadRequest("invalid sha256")
|
||||
}
|
||||
if att.PipelineVersion < 1 {
|
||||
att.PipelineVersion = 1
|
||||
}
|
||||
variants, err := json.Marshal([]model.Variant{})
|
||||
if err != nil {
|
||||
return common.Internal()
|
||||
}
|
||||
|
||||
_, err = s.pool.Exec(ctx, `
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return dbError(err)
|
||||
}
|
||||
defer rollback(tx)
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO attachments
|
||||
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, error_code, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending', NULL, $9, $9)`,
|
||||
object_key, staging_key, pipeline_version, variants, status, error_code,
|
||||
created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, 'queued', NULL, $12, $12)`,
|
||||
att.ID, att.ChatID, att.OwnerID, att.Filename, att.ContentType, att.SizeBytes,
|
||||
hash, att.ObjectKey, time.Time(att.CreatedAt))
|
||||
return dbError(err)
|
||||
}
|
||||
|
||||
// MarkAttachmentReady publishes metadata only after the object bytes are known
|
||||
// to be in S3. A 201 is therefore a promise about both stores.
|
||||
func (s *Store) MarkAttachmentReady(ctx context.Context, id uuid.UUID) (time.Time, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
updatedAt := time.Now().UTC()
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', updated_at = $2
|
||||
WHERE id = $1 AND status = 'pending'`, id, updatedAt)
|
||||
hash, att.ObjectKey, att.StagingKey, att.PipelineVersion, variants, time.Time(att.CreatedAt))
|
||||
if err != nil {
|
||||
return time.Time{}, dbError(err)
|
||||
return dbError(err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return time.Time{}, common.Conflict("attachment is not pending")
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO attachment_jobs
|
||||
(job_id, attachment_id, type, pipeline_version, attempt, max_attempts,
|
||||
status, error_code, available_at, published_at, lease_until,
|
||||
processing_started_at, finished_at, replay_count, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, 0, $5, 'queued', NULL, $6, NULL, NULL,
|
||||
NULL, NULL, 0, $6, $6)`,
|
||||
job.JobID, att.ID, model.JobTypeAttachmentProcessV1, att.PipelineVersion,
|
||||
job.MaxAttempts, time.Time(att.CreatedAt))
|
||||
if err != nil {
|
||||
return dbError(err)
|
||||
}
|
||||
return updatedAt, nil
|
||||
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return dbError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeletePendingAttachment removes a row only while it is still pending. The
|
||||
// status guard is the safety property: if an upload completed concurrently, the
|
||||
// compensation or reconciler pass must not delete a ready attachment.
|
||||
func (s *Store) DeletePendingAttachment(ctx context.Context, id uuid.UUID) error {
|
||||
// CountPendingJobs is an admission control signal, not a queue size proof.
|
||||
// Two API replicas may observe slightly stale counts, but the durable cap is
|
||||
// still useful: it stops an overload from growing staging and PostgreSQL
|
||||
// without limit. Rejections are 503 because the client may retry later.
|
||||
func (s *Store) CountPendingJobs(ctx context.Context) (int, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`DELETE FROM attachments WHERE id = $1 AND status = 'pending'`, id)
|
||||
return dbError(err)
|
||||
var count int
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT count(*) FROM attachment_jobs
|
||||
WHERE status IN ('queued', 'processing')`).Scan(&count)
|
||||
if err != nil {
|
||||
return 0, dbError(err)
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetAttachmentForUser(ctx context.Context, userID, attachmentID uuid.UUID) (model.Attachment, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
att, err := scanAttachment(s.pool.QueryRow(ctx, `
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
|
||||
a.size_bytes, a.sha256, a.status, a.error_code,
|
||||
a.created_at, a.updated_at, a.object_key
|
||||
FROM attachments a
|
||||
att, err := scanAttachment(s.pool.QueryRow(ctx, attachmentSelect+`
|
||||
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = $2
|
||||
WHERE a.id = $1`, attachmentID, userID))
|
||||
if err != nil {
|
||||
@@ -83,20 +101,76 @@ func (s *Store) GetAttachmentForUser(ctx context.Context, userID, attachmentID u
|
||||
return att, nil
|
||||
}
|
||||
|
||||
// ListStalePendingAttachments is the entry point for crash recovery. cutoff is
|
||||
// an instant, not a duration: rows created before it are eligible. The caller
|
||||
// computes it as now - grace so the boundary can be tuned and tested.
|
||||
func (s *Store) ListStalePendingAttachments(ctx context.Context, cutoff time.Time, limit int) ([]model.Attachment, error) {
|
||||
// GetAttachment is the worker's trusted read. The worker never accepts bucket
|
||||
// keys or filenames from the broker message.
|
||||
func (s *Store) GetAttachment(ctx context.Context, attachmentID uuid.UUID) (model.Attachment, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
|
||||
a.size_bytes, a.sha256, a.status, a.error_code,
|
||||
a.created_at, a.updated_at, a.object_key
|
||||
FROM attachments a
|
||||
WHERE a.status = 'pending' AND a.created_at < $1
|
||||
ORDER BY a.created_at
|
||||
att, err := scanAttachment(s.pool.QueryRow(ctx, attachmentSelect+` WHERE a.id = $1`, attachmentID))
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
return att, nil
|
||||
}
|
||||
|
||||
const attachmentSelect = `
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
|
||||
a.size_bytes, a.sha256, a.status, a.error_code,
|
||||
a.created_at, a.updated_at, a.object_key, COALESCE(a.staging_key, ''),
|
||||
a.pipeline_version, a.variants
|
||||
FROM attachments a`
|
||||
|
||||
func scanAttachment(row rowScanner) (model.Attachment, error) {
|
||||
var (
|
||||
att model.Attachment
|
||||
hash []byte
|
||||
errCode *string
|
||||
createdAt time.Time
|
||||
updatedAt time.Time
|
||||
variants []byte
|
||||
)
|
||||
|
||||
if err := row.Scan(
|
||||
&att.ID, &att.ChatID, &att.OwnerID, &att.Filename, &att.ContentType,
|
||||
&att.SizeBytes, &hash, &att.Status, &errCode,
|
||||
&createdAt, &updatedAt, &att.ObjectKey, &att.StagingKey,
|
||||
&att.PipelineVersion, &variants,
|
||||
); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, common.NotFound("attachment not found")
|
||||
}
|
||||
return model.Attachment{}, dbError(err)
|
||||
}
|
||||
|
||||
att.SHA256 = hex.EncodeToString(hash)
|
||||
att.ErrorCode = errCode
|
||||
att.CreatedAt = common.RFCFormTime(createdAt.UTC())
|
||||
att.UpdatedAt = common.RFCFormTime(updatedAt.UTC())
|
||||
att.Variants = []model.Variant{}
|
||||
if len(variants) > 0 {
|
||||
if err := json.Unmarshal(variants, &att.Variants); err != nil {
|
||||
return model.Attachment{}, dbError(err)
|
||||
}
|
||||
}
|
||||
if att.Variants == nil {
|
||||
att.Variants = []model.Variant{}
|
||||
}
|
||||
return att, nil
|
||||
}
|
||||
|
||||
// ListStaleStagingAttachments returns terminal attachments whose staging copy
|
||||
// may be removed. The grace period is applied to updated_at so a just-finished
|
||||
// job is never cleaned while its commit is still settling.
|
||||
func (s *Store) ListStaleStagingAttachments(ctx context.Context, cutoff time.Time, limit int) ([]model.Attachment, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := s.pool.Query(ctx, attachmentSelect+`
|
||||
WHERE a.status IN ('ready', 'failed')
|
||||
AND a.updated_at < $1
|
||||
AND a.staging_key IS NOT NULL
|
||||
ORDER BY a.updated_at
|
||||
LIMIT $2`, cutoff, limit)
|
||||
if err != nil {
|
||||
return nil, dbError(err)
|
||||
@@ -107,7 +181,7 @@ func (s *Store) ListStalePendingAttachments(ctx context.Context, cutoff time.Tim
|
||||
for rows.Next() {
|
||||
att, scanErr := scanAttachment(rows)
|
||||
if scanErr != nil {
|
||||
return nil, dbError(scanErr)
|
||||
return nil, scanErr
|
||||
}
|
||||
result = append(result, att)
|
||||
}
|
||||
@@ -117,11 +191,24 @@ func (s *Store) ListStalePendingAttachments(ctx context.Context, cutoff time.Tim
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListAttachmentObjectKeys(ctx context.Context) (map[string]struct{}, error) {
|
||||
func (s *Store) ClearStagingKey(ctx context.Context, attachmentID uuid.UUID) error {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := s.pool.Query(ctx, `SELECT object_key FROM attachments`)
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`UPDATE attachments SET staging_key = NULL WHERE id = $1`, attachmentID)
|
||||
return dbError(err)
|
||||
}
|
||||
|
||||
// ListStorageKeys returns every object the database still owns. It includes
|
||||
// variant keys derived from the original key; the reconciler must never delete
|
||||
// a thumbnail that has no separate row.
|
||||
func (s *Store) ListStorageKeys(ctx context.Context) (map[string]struct{}, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT object_key, COALESCE(staging_key, ''), variants FROM attachments`)
|
||||
if err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
@@ -129,11 +216,25 @@ func (s *Store) ListAttachmentObjectKeys(ctx context.Context) (map[string]struct
|
||||
|
||||
keys := make(map[string]struct{})
|
||||
for rows.Next() {
|
||||
var key string
|
||||
if err = rows.Scan(&key); err != nil {
|
||||
var (
|
||||
objectKey string
|
||||
staging string
|
||||
variants []byte
|
||||
)
|
||||
if err = rows.Scan(&objectKey, &staging, &variants); err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
keys[key] = struct{}{}
|
||||
keys[objectKey] = struct{}{}
|
||||
if staging != "" {
|
||||
keys[staging] = struct{}{}
|
||||
}
|
||||
var list []model.Variant
|
||||
if err = json.Unmarshal(variants, &list); err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
for _, variant := range list {
|
||||
keys[VariantObjectKey(objectKey, variant.Name)] = struct{}{}
|
||||
}
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, dbError(err)
|
||||
@@ -141,30 +242,9 @@ func (s *Store) ListAttachmentObjectKeys(ctx context.Context) (map[string]struct
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func scanAttachment(row rowScanner) (model.Attachment, error) {
|
||||
var (
|
||||
att model.Attachment
|
||||
hash []byte
|
||||
errCode *string
|
||||
createdAt time.Time
|
||||
updatedAt time.Time
|
||||
)
|
||||
|
||||
if err := row.Scan(
|
||||
&att.ID, &att.ChatID, &att.OwnerID, &att.Filename, &att.ContentType,
|
||||
&att.SizeBytes, &hash, &att.Status, &errCode,
|
||||
&createdAt, &updatedAt, &att.ObjectKey,
|
||||
); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, common.NotFound("attachment not found")
|
||||
}
|
||||
return model.Attachment{}, dbError(err)
|
||||
}
|
||||
|
||||
att.SHA256 = hex.EncodeToString(hash)
|
||||
att.ErrorCode = errCode
|
||||
att.Variants = []model.Variant{}
|
||||
att.CreatedAt = common.RFCFormTime(createdAt.UTC())
|
||||
att.UpdatedAt = common.RFCFormTime(updatedAt.UTC())
|
||||
return att, nil
|
||||
// VariantObjectKey is the one place that names variant objects. Keeping it
|
||||
// deterministic makes a retried job overwrite the same keys instead of
|
||||
// creating a second variant set.
|
||||
func VariantObjectKey(originalKey, variant string) string {
|
||||
return originalKey + "/" + variant
|
||||
}
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// ClaimResult tells the consumer whether this delivery owns the work.
|
||||
type ClaimResult struct {
|
||||
Job model.JobRecord
|
||||
Attachment model.Attachment
|
||||
// Terminal means the logical work is already ready/failed. Ack it.
|
||||
Terminal bool
|
||||
// Busy means another attempt owns an active lease, or a retry is not due.
|
||||
// The publisher/lease sweeper will make the job visible again.
|
||||
Busy bool
|
||||
}
|
||||
|
||||
// ClaimJob acquires or renews the logical job lease in one transaction.
|
||||
// A broker redelivery of the same job_id therefore cannot become two workers
|
||||
// writing results at the same time.
|
||||
func (s *Store) ClaimJob(ctx context.Context, jobID uuid.UUID, lease time.Duration) (ClaimResult, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return ClaimResult{}, dbError(err)
|
||||
}
|
||||
defer rollback(tx)
|
||||
|
||||
job, err := scanJob(tx.QueryRow(ctx, `
|
||||
SELECT job_id, attachment_id, type, pipeline_version, attempt, max_attempts,
|
||||
status, error_code, created_at, available_at, published_at,
|
||||
lease_until, processing_started_at, finished_at, replay_count
|
||||
FROM attachment_jobs WHERE job_id = $1 FOR UPDATE`, jobID))
|
||||
if err != nil {
|
||||
return ClaimResult{}, err
|
||||
}
|
||||
|
||||
att, err := scanAttachment(tx.QueryRow(ctx, attachmentSelect+` WHERE a.id = $1 FOR UPDATE`, job.AttachmentID))
|
||||
if err != nil {
|
||||
return ClaimResult{}, err
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
if job.Status == model.JobStatusReady || job.Status == model.JobStatusFailed || att.Status == "ready" {
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return ClaimResult{}, dbError(err)
|
||||
}
|
||||
return ClaimResult{Job: job, Attachment: att, Terminal: true}, nil
|
||||
}
|
||||
if att.Status == "failed" {
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return ClaimResult{}, dbError(err)
|
||||
}
|
||||
return ClaimResult{Job: job, Attachment: att, Terminal: true}, nil
|
||||
}
|
||||
if job.Status == model.JobStatusProcessing && job.LeaseUntil != nil && job.LeaseUntil.After(now) {
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return ClaimResult{}, dbError(err)
|
||||
}
|
||||
return ClaimResult{Job: job, Attachment: att, Busy: true}, nil
|
||||
}
|
||||
if job.Status == model.JobStatusQueued && job.AvailableAt.After(now) {
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return ClaimResult{}, dbError(err)
|
||||
}
|
||||
return ClaimResult{Job: job, Attachment: att, Busy: true}, nil
|
||||
}
|
||||
|
||||
if job.Attempt >= job.MaxAttempts {
|
||||
_, failErr := tx.Exec(ctx, `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'failed', error_code = 'retry_exhausted',
|
||||
finished_at = $2, lease_until = NULL, updated_at = $2
|
||||
WHERE job_id = $1`, jobID, now)
|
||||
if failErr != nil {
|
||||
return ClaimResult{}, dbError(failErr)
|
||||
}
|
||||
_, failErr = tx.Exec(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'failed', error_code = 'retry_exhausted', updated_at = $2
|
||||
WHERE id = $1 AND status <> 'ready'`, job.AttachmentID, now)
|
||||
if failErr != nil {
|
||||
return ClaimResult{}, dbError(failErr)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return ClaimResult{}, dbError(err)
|
||||
}
|
||||
return ClaimResult{Job: job, Attachment: att, Terminal: true}, nil
|
||||
}
|
||||
|
||||
attempt := job.Attempt + 1
|
||||
leaseUntil := now.Add(lease)
|
||||
_, err = tx.Exec(ctx, `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'processing', attempt = $2, error_code = NULL,
|
||||
lease_until = $3, processing_started_at = COALESCE(processing_started_at, $4),
|
||||
published_at = COALESCE(published_at, $4), updated_at = $4
|
||||
WHERE job_id = $1`, jobID, attempt, leaseUntil, now)
|
||||
if err != nil {
|
||||
return ClaimResult{}, dbError(err)
|
||||
}
|
||||
_, err = tx.Exec(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'processing', error_code = NULL, updated_at = $2
|
||||
WHERE id = $1 AND status IN ('queued', 'processing')`, job.AttachmentID, now)
|
||||
if err != nil {
|
||||
return ClaimResult{}, dbError(err)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return ClaimResult{}, dbError(err)
|
||||
}
|
||||
|
||||
job.Attempt = attempt
|
||||
job.Status = model.JobStatusProcessing
|
||||
job.ErrorCode = nil
|
||||
job.LeaseUntil = &leaseUntil
|
||||
if job.ProcessingStartedAt == nil {
|
||||
job.ProcessingStartedAt = &now
|
||||
}
|
||||
att.Status = "processing"
|
||||
att.ErrorCode = nil
|
||||
att.UpdatedAt = common.RFCFormTime(now)
|
||||
return ClaimResult{Job: job, Attachment: att}, nil
|
||||
}
|
||||
|
||||
// CompleteJob commits the ready snapshot only for the attempt/version that
|
||||
// still owns the lease. An older duplicate can therefore never roll a newer
|
||||
// result back or overwrite it.
|
||||
func (s *Store) CompleteJob(ctx context.Context, jobID uuid.UUID, attempt int, variants []model.Variant) (bool, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
if variants == nil {
|
||||
variants = []model.Variant{}
|
||||
}
|
||||
encoded, err := json.Marshal(variants)
|
||||
if err != nil {
|
||||
return false, common.Internal()
|
||||
}
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, dbError(err)
|
||||
}
|
||||
defer rollback(tx)
|
||||
|
||||
var attachmentID uuid.UUID
|
||||
var pipelineVersion int
|
||||
var status string
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT attachment_id, pipeline_version, status
|
||||
FROM attachment_jobs WHERE job_id = $1 FOR UPDATE`, jobID).
|
||||
Scan(&attachmentID, &pipelineVersion, &status)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, common.NotFound("job not found")
|
||||
}
|
||||
if err != nil {
|
||||
return false, dbError(err)
|
||||
}
|
||||
if status != model.JobStatusProcessing {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
att, err := scanAttachment(tx.QueryRow(ctx, attachmentSelect+` WHERE a.id = $1 FOR UPDATE`, attachmentID))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if att.PipelineVersion != pipelineVersion || att.Status == "ready" || att.Status == "failed" {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
tag, err := tx.Exec(ctx, `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'ready', error_code = NULL, finished_at = $3,
|
||||
lease_until = NULL, updated_at = $3
|
||||
WHERE job_id = $1 AND attempt = $2 AND status = 'processing'`,
|
||||
jobID, attempt, now)
|
||||
if err != nil {
|
||||
return false, dbError(err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', variants = $2, error_code = NULL,
|
||||
ready_at = $3, updated_at = $3
|
||||
WHERE id = $1 AND pipeline_version = $4 AND status IN ('queued', 'processing')`,
|
||||
attachmentID, encoded, now, pipelineVersion)
|
||||
if err != nil {
|
||||
return false, dbError(err)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return false, dbError(err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// ScheduleRetry keeps the job in the durable outbox with a jittered delay.
|
||||
// The caller acks the broker only after this commit, so the retry intent is
|
||||
// never lost between "try later" and ack.
|
||||
func (s *Store) ScheduleRetry(ctx context.Context, jobID uuid.UUID, attempt int, code string, delay time.Duration) (bool, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, dbError(err)
|
||||
}
|
||||
defer rollback(tx)
|
||||
|
||||
now := time.Now().UTC()
|
||||
tag, err := tx.Exec(ctx, `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'queued', error_code = $3, available_at = $4,
|
||||
published_at = NULL, lease_until = NULL, updated_at = $5
|
||||
WHERE job_id = $1 AND status = 'processing' AND attempt = $2`,
|
||||
jobID, attempt, code, now.Add(delay), now)
|
||||
if err != nil {
|
||||
return false, dbError(err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'queued', error_code = NULL, updated_at = $2
|
||||
WHERE id = (SELECT attachment_id FROM attachment_jobs WHERE job_id = $1)
|
||||
AND status <> 'ready'`, jobID, now)
|
||||
if err != nil {
|
||||
return false, dbError(err)
|
||||
}
|
||||
return true, dbError(tx.Commit(ctx))
|
||||
}
|
||||
|
||||
// FailJob records a terminal reason. It is idempotent: a later stale attempt
|
||||
// that no longer matches the current attempt is ignored.
|
||||
func (s *Store) FailJob(ctx context.Context, jobID uuid.UUID, attempt int, code string) error {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return dbError(err)
|
||||
}
|
||||
defer rollback(tx)
|
||||
|
||||
now := time.Now().UTC()
|
||||
tag, err := tx.Exec(ctx, `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'failed', error_code = $3, finished_at = $4,
|
||||
lease_until = NULL, updated_at = $4
|
||||
WHERE job_id = $1 AND status = 'processing' AND attempt = $2`,
|
||||
jobID, attempt, code, now)
|
||||
if err != nil {
|
||||
return dbError(err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'failed', error_code = $2, updated_at = $3
|
||||
WHERE id = (SELECT attachment_id FROM attachment_jobs WHERE job_id = $1)
|
||||
AND status <> 'ready'`, jobID, code, now)
|
||||
if err != nil {
|
||||
return dbError(err)
|
||||
}
|
||||
return dbError(tx.Commit(ctx))
|
||||
}
|
||||
|
||||
// RecoverExpiredLeases is the stuck-processing guard. A dead worker leaves a
|
||||
// processing row whose lease expires; the sweeper requeues it or marks it
|
||||
// retry_exhausted. It never touches ready work.
|
||||
func (s *Store) RecoverExpiredLeases(ctx context.Context) (int, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
WITH expired AS (
|
||||
UPDATE attachment_jobs j
|
||||
SET status = CASE WHEN j.attempt >= j.max_attempts THEN 'failed' ELSE 'queued' END,
|
||||
error_code = CASE WHEN j.attempt >= j.max_attempts THEN 'retry_exhausted' ELSE NULL END,
|
||||
available_at = now(),
|
||||
published_at = NULL,
|
||||
lease_until = NULL,
|
||||
finished_at = CASE WHEN j.attempt >= j.max_attempts THEN now() ELSE NULL END,
|
||||
updated_at = now()
|
||||
WHERE j.status = 'processing'
|
||||
AND j.lease_until IS NOT NULL
|
||||
AND j.lease_until < now()
|
||||
RETURNING j.attachment_id, j.status, j.error_code
|
||||
)
|
||||
UPDATE attachments a
|
||||
SET status = CASE WHEN e.status = 'failed' THEN 'failed' ELSE 'queued' END,
|
||||
error_code = CASE WHEN e.status = 'failed' THEN e.error_code ELSE NULL END,
|
||||
updated_at = now()
|
||||
FROM expired e
|
||||
WHERE a.id = e.attachment_id AND a.status <> 'ready'`)
|
||||
if err != nil {
|
||||
return 0, dbError(err)
|
||||
}
|
||||
return int(tag.RowsAffected()), nil
|
||||
}
|
||||
|
||||
// ListPublishableJobs is the outbox read side. It intentionally does not lock
|
||||
// rows: two API replicas may publish the same message, and the idempotent
|
||||
// claim/effect makes that duplicate harmless.
|
||||
func (s *Store) ListPublishableJobs(ctx context.Context, limit int) ([]model.JobRecord, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT job_id, attachment_id, type, pipeline_version, attempt, max_attempts,
|
||||
status, error_code, created_at, available_at, published_at,
|
||||
lease_until, processing_started_at, finished_at, replay_count
|
||||
FROM attachment_jobs
|
||||
WHERE published_at IS NULL AND status = 'queued' AND available_at <= now()
|
||||
ORDER BY available_at, created_at
|
||||
LIMIT $1`, limit)
|
||||
if err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var jobs []model.JobRecord
|
||||
for rows.Next() {
|
||||
job, scanErr := scanJob(rows)
|
||||
if scanErr != nil {
|
||||
return nil, scanErr
|
||||
}
|
||||
jobs = append(jobs, job)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
return jobs, nil
|
||||
}
|
||||
|
||||
// MarkJobPublished uses status+attempt as a compare-and-set. If a worker has
|
||||
// already claimed the job, or a retry has superseded this publish, the update
|
||||
// is a no-op and the outbox will publish the current intent later.
|
||||
func (s *Store) MarkJobPublished(ctx context.Context, jobID uuid.UUID, attempt int, at time.Time) error {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE attachment_jobs
|
||||
SET published_at = $3, updated_at = $3
|
||||
WHERE job_id = $1 AND attempt = $2 AND status = 'queued' AND published_at IS NULL`,
|
||||
jobID, attempt, at.UTC())
|
||||
return dbError(err)
|
||||
}
|
||||
|
||||
// ReplayFailed is the explicit operator action. The status guard means a
|
||||
// second click, or a replay after success, cannot duplicate a ready effect.
|
||||
func (s *Store) ReplayFailed(ctx context.Context, attachmentID uuid.UUID) (bool, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, dbError(err)
|
||||
}
|
||||
defer rollback(tx)
|
||||
|
||||
now := time.Now().UTC()
|
||||
tag, err := tx.Exec(ctx, `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'queued', attempt = 0, error_code = NULL,
|
||||
available_at = $2, published_at = NULL, lease_until = NULL,
|
||||
processing_started_at = NULL, finished_at = NULL,
|
||||
replay_count = replay_count + 1, last_replay_at = $2, updated_at = $2
|
||||
WHERE attachment_id = $1 AND status = 'failed'
|
||||
AND EXISTS (SELECT 1 FROM attachments
|
||||
WHERE id = $1 AND status = 'failed')`,
|
||||
attachmentID, now)
|
||||
if err != nil {
|
||||
return false, dbError(err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'queued', error_code = NULL, updated_at = $2
|
||||
WHERE id = $1 AND status = 'failed'`, attachmentID, now)
|
||||
if err != nil {
|
||||
return false, dbError(err)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return false, dbError(err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func scanJob(row rowScanner) (model.JobRecord, error) {
|
||||
var (
|
||||
job model.JobRecord
|
||||
created time.Time
|
||||
errCode *string
|
||||
)
|
||||
if err := row.Scan(
|
||||
&job.JobID, &job.AttachmentID, &job.Type, &job.PipelineVersion,
|
||||
&job.Attempt, &job.MaxAttempts, &job.Status, &errCode, &created,
|
||||
&job.AvailableAt, &job.PublishedAt, &job.LeaseUntil,
|
||||
&job.ProcessingStartedAt, &job.FinishedAt, &job.ReplayCount,
|
||||
); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.JobRecord{}, common.NotFound("job not found")
|
||||
}
|
||||
return model.JobRecord{}, dbError(err)
|
||||
}
|
||||
job.SchemaVersion = 1
|
||||
job.CreatedAt = common.RFCFormTime(created.UTC())
|
||||
job.ErrorCode = errCode
|
||||
return job, nil
|
||||
}
|
||||
@@ -78,9 +78,11 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, t
|
||||
return model.Message{}, dbError(scanErr)
|
||||
}
|
||||
found++
|
||||
if status != "ready" {
|
||||
// Lab5: a queued/processing attachment is already linked to its
|
||||
// chat and may be sent. Only a terminal failed one is refused.
|
||||
if status == "failed" {
|
||||
rows.Close()
|
||||
return model.Message{}, common.Conflict("attachment is not ready")
|
||||
return model.Message{}, common.Conflict("attachment failed processing")
|
||||
}
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user