API принимает 202 после durable staging и TX intent (job+outbox); отдельные relay и worker публикуют/обрабатывают задания с publisher confirm, lease, retry/backoff, DLQ и replay. Добавлены версии pipeline, варианты thumbnail/crop/optimized, presign в verified staging, status-aware sweeper и admission control.
1835 lines
46 KiB
Go
1835 lines
46 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
|
|
"mtusi-messenger/internal/domain"
|
|
)
|
|
|
|
// PipelineRepository owns the durable job/outbox/variant state. Queries that
|
|
// need CAS semantics, FOR UPDATE SKIP LOCKED or multi-table transactions live
|
|
// here as explicit SQL instead of being spread across the service layer.
|
|
type PipelineRepository struct {
|
|
store *Store
|
|
}
|
|
|
|
const attachmentReturning = `id, chat_id, owner_id, filename, content_type, size_bytes,
|
|
sha256, status, error_code, object_key, COALESCE(staging_key, ''), pipeline_version,
|
|
created_at, updated_at, ready_at, failed_at`
|
|
|
|
const jobReturning = `job_id, attachment_id, pipeline_version, source_key, attempt,
|
|
max_attempts, status, available_at, lease_owner, lease_expires_at, last_error_code,
|
|
replay_count, created_at, updated_at, completed_at`
|
|
|
|
type rowScanner interface {
|
|
Scan(dest ...any) error
|
|
}
|
|
|
|
func scanAttachmentRow(row rowScanner) (domain.Attachment, error) {
|
|
var (
|
|
attachment domain.Attachment
|
|
status string
|
|
errCode pgtype.Text
|
|
readyAt pgtype.Timestamptz
|
|
failedAt pgtype.Timestamptz
|
|
)
|
|
|
|
err := row.Scan(
|
|
&attachment.ID,
|
|
&attachment.ChatID,
|
|
&attachment.OwnerID,
|
|
&attachment.Filename,
|
|
&attachment.ContentType,
|
|
&attachment.SizeBytes,
|
|
&attachment.SHA256,
|
|
&status,
|
|
&errCode,
|
|
&attachment.ObjectKey,
|
|
&attachment.StagingKey,
|
|
&attachment.PipelineVersion,
|
|
&attachment.CreatedAt,
|
|
&attachment.UpdatedAt,
|
|
&readyAt,
|
|
&failedAt,
|
|
)
|
|
if err != nil {
|
|
return domain.Attachment{}, err
|
|
}
|
|
|
|
attachment.Status = domain.AttachmentStatus(status)
|
|
if errCode.Valid {
|
|
code := errCode.String
|
|
attachment.ErrorCode = &code
|
|
}
|
|
if readyAt.Valid {
|
|
value := readyAt.Time.UTC()
|
|
attachment.ReadyAt = &value
|
|
}
|
|
if failedAt.Valid {
|
|
value := failedAt.Time.UTC()
|
|
attachment.FailedAt = &value
|
|
}
|
|
|
|
return attachment, nil
|
|
}
|
|
|
|
func scanJobRow(row rowScanner) (domain.Job, error) {
|
|
var (
|
|
job domain.Job
|
|
status string
|
|
owner pgtype.Text
|
|
leaseEnds pgtype.Timestamptz
|
|
errCode pgtype.Text
|
|
completed pgtype.Timestamptz
|
|
)
|
|
|
|
err := row.Scan(
|
|
&job.ID,
|
|
&job.AttachmentID,
|
|
&job.PipelineVersion,
|
|
&job.SourceKey,
|
|
&job.Attempt,
|
|
&job.MaxAttempts,
|
|
&status,
|
|
&job.AvailableAt,
|
|
&owner,
|
|
&leaseEnds,
|
|
&errCode,
|
|
&job.ReplayCount,
|
|
&job.CreatedAt,
|
|
&job.UpdatedAt,
|
|
&completed,
|
|
)
|
|
if err != nil {
|
|
return domain.Job{}, err
|
|
}
|
|
|
|
job.Status = domain.JobStatus(status)
|
|
if owner.Valid {
|
|
job.LeaseOwner = owner.String
|
|
}
|
|
if leaseEnds.Valid {
|
|
value := leaseEnds.Time.UTC()
|
|
job.LeaseExpiresAt = &value
|
|
}
|
|
if errCode.Valid {
|
|
code := errCode.String
|
|
job.LastErrorCode = &code
|
|
}
|
|
if completed.Valid {
|
|
value := completed.Time.UTC()
|
|
job.CompletedAt = &value
|
|
}
|
|
|
|
return job, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) withTx(ctx context.Context, fn func(pgx.Tx) error) error {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
tx, err := r.store.pool.BeginTx(ctx, pgx.TxOptions{})
|
|
if err != nil {
|
|
return fmt.Errorf("begin transaction: %w", err)
|
|
}
|
|
|
|
defer func() { _ = tx.Rollback(ctx) }()
|
|
|
|
if err := fn(tx); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return fmt.Errorf("commit transaction: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// IsChatMember mirrors the existing repository port used by the service.
|
|
func (r *PipelineRepository) IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
var member bool
|
|
|
|
err := r.store.pool.QueryRow(ctx, `
|
|
SELECT EXISTS (
|
|
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2
|
|
)`, chatID, userID).Scan(&member)
|
|
if err != nil {
|
|
return false, fmt.Errorf("check chat membership: %w", mapError(err))
|
|
}
|
|
|
|
return member, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) GetForMember(
|
|
ctx context.Context,
|
|
userID, id uuid.UUID,
|
|
) (domain.Attachment, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
row := r.store.pool.QueryRow(ctx, `
|
|
SELECT `+attachmentReturning+`
|
|
FROM attachments a
|
|
WHERE a.id = $1
|
|
AND EXISTS (
|
|
SELECT 1 FROM chat_members cm
|
|
WHERE cm.chat_id = a.chat_id AND cm.user_id = $2
|
|
)`, id, userID)
|
|
|
|
attachment, err := scanAttachmentRow(row)
|
|
if err != nil {
|
|
return domain.Attachment{}, fmt.Errorf("get attachment for member: %w", mapError(err))
|
|
}
|
|
|
|
return attachment, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) GetForOwner(
|
|
ctx context.Context,
|
|
ownerID, id uuid.UUID,
|
|
) (domain.Attachment, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
row := r.store.pool.QueryRow(ctx, `
|
|
SELECT `+attachmentReturning+`
|
|
FROM attachments a
|
|
WHERE a.id = $1 AND a.owner_id = $2`, id, ownerID)
|
|
|
|
attachment, err := scanAttachmentRow(row)
|
|
if err != nil {
|
|
return domain.Attachment{}, fmt.Errorf("get attachment for owner: %w", mapError(err))
|
|
}
|
|
|
|
return attachment, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) ListStates(
|
|
ctx context.Context,
|
|
chatID uuid.UUID,
|
|
ids []uuid.UUID,
|
|
) ([]domain.AttachmentState, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
rows, err := r.store.pool.Query(ctx, `
|
|
SELECT id, status
|
|
FROM attachments
|
|
WHERE chat_id = $1 AND id = ANY($2::uuid[])`, chatID, ids)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list attachment states: %w", mapError(err))
|
|
}
|
|
defer rows.Close()
|
|
|
|
states := make([]domain.AttachmentState, 0, len(ids))
|
|
|
|
for rows.Next() {
|
|
var (
|
|
state domain.AttachmentState
|
|
status string
|
|
)
|
|
if err := rows.Scan(&state.ID, &status); err != nil {
|
|
return nil, fmt.Errorf("scan attachment state: %w", mapError(err))
|
|
}
|
|
state.Status = domain.AttachmentStatus(status)
|
|
states = append(states, state)
|
|
}
|
|
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("list attachment states: %w", mapError(err))
|
|
}
|
|
|
|
return states, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) ListVariants(
|
|
ctx context.Context,
|
|
attachmentID uuid.UUID,
|
|
pipelineVersion int,
|
|
) ([]domain.Variant, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
rows, err := r.store.pool.Query(ctx, `
|
|
SELECT name, content_type, size_bytes, width, height, sha256, object_key
|
|
FROM attachment_variants
|
|
WHERE attachment_id = $1 AND pipeline_version = $2
|
|
ORDER BY name`, attachmentID, pipelineVersion)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list variants: %w", mapError(err))
|
|
}
|
|
defer rows.Close()
|
|
|
|
variants := make([]domain.Variant, 0, 3)
|
|
|
|
for rows.Next() {
|
|
var (
|
|
variant domain.Variant
|
|
name string
|
|
)
|
|
if err := rows.Scan(
|
|
&name, &variant.ContentType, &variant.SizeBytes,
|
|
&variant.Width, &variant.Height, &variant.SHA256, &variant.ObjectKey,
|
|
); err != nil {
|
|
return nil, fmt.Errorf("scan variant: %w", mapError(err))
|
|
}
|
|
variant.Name = domain.VariantName(name)
|
|
variants = append(variants, variant)
|
|
}
|
|
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("list variants: %w", mapError(err))
|
|
}
|
|
|
|
return variants, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) GetVariant(
|
|
ctx context.Context,
|
|
attachmentID uuid.UUID,
|
|
pipelineVersion int,
|
|
name domain.VariantName,
|
|
) (domain.Variant, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
var variant domain.Variant
|
|
|
|
err := r.store.pool.QueryRow(ctx, `
|
|
SELECT name, content_type, size_bytes, width, height, sha256, object_key
|
|
FROM attachment_variants
|
|
WHERE attachment_id = $1 AND pipeline_version = $2 AND name = $3`,
|
|
attachmentID, pipelineVersion, string(name)).Scan(
|
|
&variant.Name, &variant.ContentType, &variant.SizeBytes,
|
|
&variant.Width, &variant.Height, &variant.SHA256, &variant.ObjectKey,
|
|
)
|
|
if err != nil {
|
|
return domain.Variant{}, fmt.Errorf("get variant: %w", mapError(err))
|
|
}
|
|
|
|
return variant, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) Admission(
|
|
ctx context.Context,
|
|
ownerID uuid.UUID,
|
|
) (userPending, totalPending int, stagedBytes int64, err error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
err = r.store.pool.QueryRow(ctx, `
|
|
SELECT
|
|
count(*) FILTER (WHERE a.owner_id = $1)::int,
|
|
count(*)::int,
|
|
COALESCE(sum(a.size_bytes), 0)::bigint
|
|
FROM attachment_jobs j
|
|
JOIN attachments a ON a.id = j.attachment_id
|
|
WHERE j.status IN ('queued', 'processing')`, ownerID).Scan(
|
|
&userPending, &totalPending, &stagedBytes,
|
|
)
|
|
if err != nil {
|
|
return 0, 0, 0, fmt.Errorf("admission counts: %w", mapError(err))
|
|
}
|
|
|
|
return userPending, totalPending, stagedBytes, nil
|
|
}
|
|
|
|
func insertOutboxTx(
|
|
ctx context.Context,
|
|
tx pgx.Tx,
|
|
job domain.Job,
|
|
attempt int,
|
|
kind string,
|
|
availableAt time.Time,
|
|
) error {
|
|
payload, err := domain.NewJobMessage(domain.Job{
|
|
ID: job.ID,
|
|
AttachmentID: job.AttachmentID,
|
|
PipelineVersion: job.PipelineVersion,
|
|
Attempt: attempt,
|
|
CreatedAt: job.CreatedAt,
|
|
}).MarshalPayload()
|
|
if err != nil {
|
|
return fmt.Errorf("marshal job message: %w", err)
|
|
}
|
|
|
|
_, err = tx.Exec(ctx, `
|
|
INSERT INTO outbox_messages (job_id, attempt, kind, routing_key, payload, available_at)
|
|
VALUES ($1, $2, $3, $4, $5::jsonb, $6)`,
|
|
job.ID, attempt, kind, defaultRoutingKey, string(payload), availableAt)
|
|
if err != nil {
|
|
return fmt.Errorf("insert outbox: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func insertEventTx(ctx context.Context, tx pgx.Tx, jobID uuid.UUID, event string, attempt int, detail string) error {
|
|
_, err := tx.Exec(ctx, `
|
|
INSERT INTO attachment_job_events (job_id, event, attempt, detail)
|
|
VALUES ($1, $2, $3, NULLIF($4, '')::jsonb)`, jobID, event, attempt, detail)
|
|
if err != nil {
|
|
return fmt.Errorf("insert job event: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
const defaultRoutingKey = "attachment.process.v1"
|
|
|
|
// CreateQueued persists the attachment, its job and the outbox intent in one
|
|
// transaction. The caller has already written the durable staging object.
|
|
func (r *PipelineRepository) CreateQueued(
|
|
ctx context.Context,
|
|
draft domain.AttachmentDraft,
|
|
job domain.Job,
|
|
) (domain.Attachment, error) {
|
|
var created domain.Attachment
|
|
|
|
err := r.withTx(ctx, func(tx pgx.Tx) error {
|
|
row := tx.QueryRow(ctx, `
|
|
INSERT INTO attachments (
|
|
id, chat_id, owner_id, object_key, filename, content_type,
|
|
size_bytes, sha256, status, pipeline_version, staging_key
|
|
)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'queued', $9, $10)
|
|
RETURNING `+attachmentReturning,
|
|
draft.ID, draft.ChatID, draft.OwnerID, draft.ObjectKey, draft.Filename,
|
|
draft.ContentType, draft.SizeBytes, draft.SHA256, draft.PipelineVersion,
|
|
draft.StagingKey,
|
|
)
|
|
|
|
attachment, err := scanAttachmentRow(row)
|
|
if err != nil {
|
|
return fmt.Errorf("create attachment: %w", mapError(err))
|
|
}
|
|
|
|
_, err = tx.Exec(ctx, `
|
|
INSERT INTO attachment_jobs (
|
|
job_id, attachment_id, pipeline_version, source_key,
|
|
attempt, max_attempts, status, available_at
|
|
)
|
|
VALUES ($1, $2, $3, $4, 1, $5, 'queued', now())`,
|
|
job.ID, draft.ID, job.PipelineVersion, job.SourceKey, job.MaxAttempts)
|
|
if err != nil {
|
|
return fmt.Errorf("create job: %w", mapError(err))
|
|
}
|
|
|
|
if err := insertEventTx(ctx, tx, job.ID, domain.EventEnqueued, 1, ""); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := insertOutboxTx(
|
|
ctx, tx, job, 1, "initial", time.Now().UTC(),
|
|
); err != nil {
|
|
return err
|
|
}
|
|
|
|
created = attachment
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return domain.Attachment{}, err
|
|
}
|
|
|
|
return created, nil
|
|
}
|
|
|
|
// CompletePresign moves a verified presign object into the queue.
|
|
func (r *PipelineRepository) CompletePresign(
|
|
ctx context.Context,
|
|
ownerID, attachmentID uuid.UUID,
|
|
verifiedKey, finalKey string,
|
|
pipelineVersion, maxAttempts int,
|
|
jobID uuid.UUID,
|
|
) (domain.Attachment, error) {
|
|
var completed domain.Attachment
|
|
|
|
err := r.withTx(ctx, func(tx pgx.Tx) error {
|
|
row := tx.QueryRow(ctx, `
|
|
UPDATE attachments
|
|
SET status = 'queued',
|
|
staging_key = $3,
|
|
object_key = $4,
|
|
pipeline_version = $5,
|
|
error_code = NULL,
|
|
failed_at = NULL,
|
|
updated_at = now()
|
|
WHERE id = $1 AND owner_id = $2 AND status = 'pending'
|
|
RETURNING `+attachmentReturning,
|
|
attachmentID, ownerID, verifiedKey, finalKey, pipelineVersion,
|
|
)
|
|
|
|
attachment, err := scanAttachmentRow(row)
|
|
if err != nil {
|
|
if errors.Is(mapError(err), domain.ErrNotFound) {
|
|
return fmt.Errorf("%w: attachment is not pending", domain.ErrConflict)
|
|
}
|
|
|
|
return fmt.Errorf("queue presigned attachment: %w", mapError(err))
|
|
}
|
|
|
|
job := domain.Job{
|
|
ID: jobID,
|
|
AttachmentID: attachmentID,
|
|
PipelineVersion: pipelineVersion,
|
|
SourceKey: verifiedKey,
|
|
Attempt: 1,
|
|
MaxAttempts: maxAttempts,
|
|
CreatedAt: time.Now().UTC(),
|
|
}
|
|
|
|
_, err = tx.Exec(ctx, `
|
|
INSERT INTO attachment_jobs (
|
|
job_id, attachment_id, pipeline_version, source_key,
|
|
attempt, max_attempts, status, available_at
|
|
)
|
|
VALUES ($1, $2, $3, $4, 1, $5, 'queued', now())`,
|
|
job.ID, job.AttachmentID, job.PipelineVersion, job.SourceKey, job.MaxAttempts)
|
|
if err != nil {
|
|
return fmt.Errorf("create presign job: %w", mapError(err))
|
|
}
|
|
|
|
if err := insertEventTx(ctx, tx, job.ID, domain.EventEnqueued, 1, ""); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := insertOutboxTx(
|
|
ctx, tx, job, 1, "initial", time.Now().UTC(),
|
|
); err != nil {
|
|
return err
|
|
}
|
|
|
|
completed = attachment
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return domain.Attachment{}, err
|
|
}
|
|
|
|
return completed, nil
|
|
}
|
|
|
|
// ClaimJob atomically turns one delivery into the active processing attempt.
|
|
// The returned outcome is authoritative; the worker never guesses from message
|
|
// fields alone.
|
|
func (r *PipelineRepository) ClaimJob(
|
|
ctx context.Context,
|
|
message domain.JobMessage,
|
|
leaseOwner string,
|
|
leaseTTL time.Duration,
|
|
) (domain.ClaimResult, error) {
|
|
var result domain.ClaimResult
|
|
|
|
err := r.withTx(ctx, func(tx pgx.Tx) error {
|
|
jobRow := tx.QueryRow(ctx, `
|
|
SELECT `+jobReturning+`
|
|
FROM attachment_jobs
|
|
WHERE job_id = $1
|
|
FOR UPDATE`, message.JobID)
|
|
|
|
job, err := scanJobRow(jobRow)
|
|
if err != nil {
|
|
if errors.Is(mapError(err), domain.ErrNotFound) {
|
|
result = domain.ClaimResult{Outcome: domain.ClaimJobNotFound}
|
|
|
|
return nil
|
|
}
|
|
|
|
return fmt.Errorf("load job: %w", mapError(err))
|
|
}
|
|
|
|
result.Job = job
|
|
|
|
attachmentRow := tx.QueryRow(ctx, `
|
|
SELECT `+attachmentReturning+`
|
|
FROM attachments
|
|
WHERE id = $1
|
|
FOR UPDATE`, job.AttachmentID)
|
|
|
|
attachment, err := scanAttachmentRow(attachmentRow)
|
|
if err != nil {
|
|
return fmt.Errorf("load job attachment: %w", mapError(err))
|
|
}
|
|
|
|
result.Attachment = attachment
|
|
|
|
switch {
|
|
case job.PipelineVersion < attachment.PipelineVersion:
|
|
result.Outcome = domain.ClaimVersionStale
|
|
|
|
return nil
|
|
case job.Status == domain.JobReady:
|
|
result.Outcome = domain.ClaimAlreadyReady
|
|
|
|
return nil
|
|
case job.Status == domain.JobFailed:
|
|
result.Outcome = domain.ClaimAlreadyFailed
|
|
|
|
return nil
|
|
case job.Status == domain.JobSuperseded:
|
|
result.Outcome = domain.ClaimSuperseded
|
|
|
|
return nil
|
|
case message.Attempt < job.Attempt:
|
|
result.Outcome = domain.ClaimStaleAttempt
|
|
|
|
return nil
|
|
case message.Attempt > job.Attempt:
|
|
result.Outcome = domain.ClaimFutureAttempt
|
|
|
|
return nil
|
|
case job.Status == domain.JobProcessing:
|
|
// A live lease owns the effect; an expired one is requeued by the
|
|
// reaper, not by a duplicate delivery.
|
|
result.Outcome = domain.ClaimBusyLease
|
|
|
|
return nil
|
|
case job.Status != domain.JobQueued:
|
|
result.Outcome = domain.ClaimJobNotFound
|
|
|
|
return nil
|
|
}
|
|
|
|
tag, err := tx.Exec(ctx, `
|
|
UPDATE attachment_jobs
|
|
SET status = 'processing',
|
|
lease_owner = $2,
|
|
lease_expires_at = now() + $3::interval,
|
|
updated_at = now()
|
|
WHERE job_id = $1 AND status = 'queued' AND attempt = $4
|
|
AND available_at <= now()`,
|
|
job.ID, leaseOwner, intervalString(leaseTTL), message.Attempt)
|
|
if err != nil {
|
|
return fmt.Errorf("claim job: %w", mapError(err))
|
|
}
|
|
|
|
if tag.RowsAffected() == 0 {
|
|
result.Outcome = domain.ClaimNotDue
|
|
|
|
return nil
|
|
}
|
|
|
|
if job.PipelineVersion == attachment.PipelineVersion && attachment.Status == domain.AttachmentQueued {
|
|
_, err = tx.Exec(ctx, `
|
|
UPDATE attachments
|
|
SET status = 'processing', updated_at = now()
|
|
WHERE id = $1 AND status = 'queued' AND pipeline_version = $2`,
|
|
attachment.ID, job.PipelineVersion)
|
|
if err != nil {
|
|
return fmt.Errorf("mark attachment processing: %w", mapError(err))
|
|
}
|
|
|
|
attachment.Status = domain.AttachmentProcessing
|
|
result.Attachment = attachment
|
|
}
|
|
|
|
if err := insertEventTx(ctx, tx, job.ID, domain.EventClaimed, message.Attempt, ""); err != nil {
|
|
return err
|
|
}
|
|
|
|
job.Status = domain.JobProcessing
|
|
job.LeaseOwner = leaseOwner
|
|
expires := time.Now().Add(leaseTTL).UTC()
|
|
job.LeaseExpiresAt = &expires
|
|
result.Job = job
|
|
result.Outcome = domain.ClaimAcquired
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return domain.ClaimResult{}, err
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
func intervalString(d time.Duration) string {
|
|
return fmt.Sprintf("%d milliseconds", d.Milliseconds())
|
|
}
|
|
|
|
func (r *PipelineRepository) Heartbeat(
|
|
ctx context.Context,
|
|
jobID uuid.UUID,
|
|
attempt int,
|
|
leaseOwner string,
|
|
leaseTTL time.Duration,
|
|
) (bool, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
tag, err := r.store.pool.Exec(ctx, `
|
|
UPDATE attachment_jobs
|
|
SET lease_expires_at = now() + $4::interval, updated_at = now()
|
|
WHERE job_id = $1 AND attempt = $2 AND lease_owner = $3
|
|
AND status = 'processing' AND lease_expires_at > now()`,
|
|
jobID, attempt, leaseOwner, intervalString(leaseTTL))
|
|
if err != nil {
|
|
return false, fmt.Errorf("heartbeat: %w", mapError(err))
|
|
}
|
|
|
|
return tag.RowsAffected() == 1, nil
|
|
}
|
|
|
|
// CompleteJob inserts the effect rows and publishes the result atomically.
|
|
// A newer serving pipeline version is never downgraded.
|
|
func (r *PipelineRepository) CompleteJob(
|
|
ctx context.Context,
|
|
jobID uuid.UUID,
|
|
attempt int,
|
|
leaseOwner string,
|
|
variants []domain.Variant,
|
|
) (bool, error) {
|
|
completed := false
|
|
|
|
err := r.withTx(ctx, func(tx pgx.Tx) error {
|
|
job, attachment, err := lockJobAndAttachment(ctx, tx, jobID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if job.Status != domain.JobProcessing || job.Attempt != attempt || job.LeaseOwner != leaseOwner {
|
|
return nil
|
|
}
|
|
|
|
if job.PipelineVersion < attachment.PipelineVersion {
|
|
if _, err := tx.Exec(ctx, `
|
|
UPDATE attachment_jobs
|
|
SET status = 'superseded', updated_at = now(), completed_at = now()
|
|
WHERE job_id = $1`, job.ID); err != nil {
|
|
return fmt.Errorf("supersede stale job: %w", mapError(err))
|
|
}
|
|
|
|
if err := insertEventTx(ctx, tx, job.ID, domain.EventSuperseded, attempt, ""); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
for _, variant := range variants {
|
|
tag, err := tx.Exec(ctx, `
|
|
INSERT INTO attachment_variants (
|
|
attachment_id, pipeline_version, name, content_type,
|
|
size_bytes, width, height, sha256, object_key
|
|
)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
|
ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING`,
|
|
job.AttachmentID, job.PipelineVersion, string(variant.Name),
|
|
variant.ContentType, variant.SizeBytes, variant.Width, variant.Height,
|
|
variant.SHA256, variant.ObjectKey)
|
|
if err != nil {
|
|
return fmt.Errorf("insert variant: %w", mapError(err))
|
|
}
|
|
|
|
if tag.RowsAffected() == 0 {
|
|
existing, err := getVariantTx(ctx, tx, job.AttachmentID, job.PipelineVersion, variant.Name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if existing.ContentType != variant.ContentType ||
|
|
existing.SizeBytes != variant.SizeBytes ||
|
|
existing.Width != variant.Width ||
|
|
existing.Height != variant.Height ||
|
|
existing.SHA256 != variant.SHA256 ||
|
|
existing.ObjectKey != variant.ObjectKey {
|
|
return fmt.Errorf("%w: variant %s already has different bytes", domain.ErrConflict, variant.Name)
|
|
}
|
|
}
|
|
}
|
|
|
|
if job.PipelineVersion > attachment.PipelineVersion {
|
|
// Reprocess completed: atomically switch the published version.
|
|
_, err = tx.Exec(ctx, `
|
|
UPDATE attachments
|
|
SET pipeline_version = $2,
|
|
status = 'ready',
|
|
error_code = NULL,
|
|
ready_at = now(),
|
|
failed_at = NULL,
|
|
updated_at = now()
|
|
WHERE id = $1`, attachment.ID, job.PipelineVersion)
|
|
} else {
|
|
_, err = tx.Exec(ctx, `
|
|
UPDATE attachments
|
|
SET status = 'ready',
|
|
error_code = NULL,
|
|
ready_at = now(),
|
|
failed_at = NULL,
|
|
updated_at = now()
|
|
WHERE id = $1`, attachment.ID)
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("mark attachment ready: %w", mapError(err))
|
|
}
|
|
|
|
_, err = tx.Exec(ctx, `
|
|
UPDATE attachment_jobs
|
|
SET status = 'ready',
|
|
lease_owner = NULL,
|
|
lease_expires_at = NULL,
|
|
last_error_code = NULL,
|
|
completed_at = now(),
|
|
updated_at = now()
|
|
WHERE job_id = $1`, job.ID)
|
|
if err != nil {
|
|
return fmt.Errorf("mark job ready: %w", mapError(err))
|
|
}
|
|
|
|
if err := insertEventTx(ctx, tx, job.ID, domain.EventReady, attempt, ""); err != nil {
|
|
return err
|
|
}
|
|
|
|
completed = true
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
return completed, nil
|
|
}
|
|
|
|
func lockJobAndAttachment(
|
|
ctx context.Context,
|
|
tx pgx.Tx,
|
|
jobID uuid.UUID,
|
|
) (domain.Job, domain.Attachment, error) {
|
|
jobRow := tx.QueryRow(ctx, `
|
|
SELECT `+jobReturning+`
|
|
FROM attachment_jobs WHERE job_id = $1 FOR UPDATE`, jobID)
|
|
|
|
job, err := scanJobRow(jobRow)
|
|
if err != nil {
|
|
return domain.Job{}, domain.Attachment{}, fmt.Errorf("load job: %w", mapError(err))
|
|
}
|
|
|
|
attachmentRow := tx.QueryRow(ctx, `
|
|
SELECT `+attachmentReturning+`
|
|
FROM attachments WHERE id = $1 FOR UPDATE`, job.AttachmentID)
|
|
|
|
attachment, err := scanAttachmentRow(attachmentRow)
|
|
if err != nil {
|
|
return domain.Job{}, domain.Attachment{}, fmt.Errorf("load attachment: %w", mapError(err))
|
|
}
|
|
|
|
return job, attachment, nil
|
|
}
|
|
|
|
func getVariantTx(
|
|
ctx context.Context,
|
|
tx pgx.Tx,
|
|
attachmentID uuid.UUID,
|
|
pipelineVersion int,
|
|
name domain.VariantName,
|
|
) (domain.Variant, error) {
|
|
var variant domain.Variant
|
|
|
|
err := tx.QueryRow(ctx, `
|
|
SELECT name, content_type, size_bytes, width, height, sha256, object_key
|
|
FROM attachment_variants
|
|
WHERE attachment_id = $1 AND pipeline_version = $2 AND name = $3`,
|
|
attachmentID, pipelineVersion, string(name)).Scan(
|
|
&variant.Name, &variant.ContentType, &variant.SizeBytes,
|
|
&variant.Width, &variant.Height, &variant.SHA256, &variant.ObjectKey,
|
|
)
|
|
if err != nil {
|
|
return domain.Variant{}, fmt.Errorf("load variant: %w", mapError(err))
|
|
}
|
|
|
|
return variant, nil
|
|
}
|
|
|
|
// RetryJob schedules the next managed attempt. sameAttempt is used by graceful
|
|
// shutdown: infrastructure restarts must not consume the processing budget.
|
|
func (r *PipelineRepository) RetryJob(
|
|
ctx context.Context,
|
|
jobID uuid.UUID,
|
|
attempt int,
|
|
leaseOwner string,
|
|
errorCode string,
|
|
nextAvailable time.Time,
|
|
sameAttempt bool,
|
|
kind string,
|
|
) (failed bool, err error) {
|
|
err = r.withTx(ctx, func(tx pgx.Tx) error {
|
|
job, attachment, err := lockJobAndAttachment(ctx, tx, jobID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if job.Status != domain.JobProcessing || job.Attempt != attempt || job.LeaseOwner != leaseOwner {
|
|
return nil
|
|
}
|
|
|
|
if !sameAttempt && job.Attempt >= job.MaxAttempts {
|
|
failed = true
|
|
|
|
return failJobTx(ctx, tx, job, attachment, "retry_exhausted", false)
|
|
}
|
|
|
|
nextAttempt := job.Attempt
|
|
if !sameAttempt {
|
|
nextAttempt++
|
|
}
|
|
|
|
_, err = tx.Exec(ctx, `
|
|
UPDATE attachment_jobs
|
|
SET status = 'queued',
|
|
attempt = $2,
|
|
available_at = $3,
|
|
lease_owner = NULL,
|
|
lease_expires_at = NULL,
|
|
last_error_code = $4,
|
|
updated_at = now()
|
|
WHERE job_id = $1`,
|
|
job.ID, nextAttempt, nextAvailable, errorCode)
|
|
if err != nil {
|
|
return fmt.Errorf("schedule retry: %w", mapError(err))
|
|
}
|
|
|
|
if job.PipelineVersion == attachment.PipelineVersion &&
|
|
(attachment.Status == domain.AttachmentProcessing || attachment.Status == domain.AttachmentQueued) {
|
|
_, err = tx.Exec(ctx, `
|
|
UPDATE attachments
|
|
SET status = 'queued', updated_at = now()
|
|
WHERE id = $1 AND pipeline_version = $2`,
|
|
attachment.ID, job.PipelineVersion)
|
|
if err != nil {
|
|
return fmt.Errorf("requeue attachment: %w", mapError(err))
|
|
}
|
|
}
|
|
|
|
if err := insertEventTx(ctx, tx, job.ID, domain.EventRetried, nextAttempt, `{"error_code":"`+errorCode+`"}`); err != nil {
|
|
return err
|
|
}
|
|
|
|
job.Attempt = nextAttempt
|
|
|
|
if err := insertOutboxTx(ctx, tx, job, nextAttempt, kind, nextAvailable); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
return failed, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) FailJob(
|
|
ctx context.Context,
|
|
jobID uuid.UUID,
|
|
attempt int,
|
|
leaseOwner string,
|
|
errorCode string,
|
|
) (bool, error) {
|
|
failed := false
|
|
|
|
err := r.withTx(ctx, func(tx pgx.Tx) error {
|
|
job, attachment, err := lockJobAndAttachment(ctx, tx, jobID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if job.Status != domain.JobProcessing || job.Attempt != attempt || job.LeaseOwner != leaseOwner {
|
|
return nil
|
|
}
|
|
|
|
if err := failJobTx(ctx, tx, job, attachment, errorCode, false); err != nil {
|
|
return err
|
|
}
|
|
|
|
failed = true
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
return failed, nil
|
|
}
|
|
|
|
func failJobTx(
|
|
ctx context.Context,
|
|
tx pgx.Tx,
|
|
job domain.Job,
|
|
attachment domain.Attachment,
|
|
errorCode string,
|
|
leaseExpired bool,
|
|
) error {
|
|
_, err := tx.Exec(ctx, `
|
|
UPDATE attachment_jobs
|
|
SET status = 'failed',
|
|
lease_owner = NULL,
|
|
lease_expires_at = NULL,
|
|
last_error_code = $2,
|
|
completed_at = now(),
|
|
updated_at = now()
|
|
WHERE job_id = $1`, job.ID, errorCode)
|
|
if err != nil {
|
|
return fmt.Errorf("mark job failed: %w", mapError(err))
|
|
}
|
|
|
|
if job.PipelineVersion == attachment.PipelineVersion {
|
|
_, err = tx.Exec(ctx, `
|
|
UPDATE attachments
|
|
SET status = 'failed',
|
|
error_code = $2,
|
|
failed_at = now(),
|
|
updated_at = now()
|
|
WHERE id = $1`, attachment.ID, errorCode)
|
|
if err != nil {
|
|
return fmt.Errorf("mark attachment failed: %w", mapError(err))
|
|
}
|
|
}
|
|
|
|
detail := `{"error_code":"` + errorCode + `"}`
|
|
|
|
if leaseExpired {
|
|
if err := insertEventTx(ctx, tx, job.ID, domain.EventLeaseExpired, job.Attempt, detail); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
return insertEventTx(ctx, tx, job.ID, domain.EventFailed, job.Attempt, detail)
|
|
}
|
|
|
|
// ReapExpiredLeases requeues dead workers and terminates attempts that already
|
|
// exhausted their budget. The second branch is what makes retry bounded.
|
|
func (r *PipelineRepository) ReapExpiredLeases(
|
|
ctx context.Context,
|
|
limit int,
|
|
) (int, error) {
|
|
reaped := 0
|
|
|
|
err := r.withTx(ctx, func(tx pgx.Tx) error {
|
|
rows, err := tx.Query(ctx, `
|
|
SELECT `+jobReturning+`
|
|
FROM attachment_jobs
|
|
WHERE status = 'processing' AND lease_expires_at < now()
|
|
ORDER BY lease_expires_at
|
|
LIMIT $1
|
|
FOR UPDATE SKIP LOCKED`, limit)
|
|
if err != nil {
|
|
return fmt.Errorf("select expired leases: %w", mapError(err))
|
|
}
|
|
|
|
jobs := make([]domain.Job, 0, limit)
|
|
|
|
for rows.Next() {
|
|
job, err := scanJobRow(rows)
|
|
if err != nil {
|
|
rows.Close()
|
|
|
|
return fmt.Errorf("scan expired lease: %w", mapError(err))
|
|
}
|
|
jobs = append(jobs, job)
|
|
}
|
|
|
|
if err := rows.Err(); err != nil {
|
|
rows.Close()
|
|
|
|
return fmt.Errorf("list expired leases: %w", mapError(err))
|
|
}
|
|
rows.Close()
|
|
|
|
for _, job := range jobs {
|
|
attachmentRow := tx.QueryRow(ctx, `
|
|
SELECT `+attachmentReturning+`
|
|
FROM attachments WHERE id = $1 FOR UPDATE`, job.AttachmentID)
|
|
|
|
attachment, err := scanAttachmentRow(attachmentRow)
|
|
if err != nil {
|
|
return fmt.Errorf("load lease attachment: %w", mapError(err))
|
|
}
|
|
|
|
if job.Attempt >= job.MaxAttempts {
|
|
if err := failJobTx(ctx, tx, job, attachment, "retry_exhausted", true); err != nil {
|
|
return err
|
|
}
|
|
reaped++
|
|
|
|
continue
|
|
}
|
|
|
|
nextAttempt := job.Attempt + 1
|
|
|
|
_, err = tx.Exec(ctx, `
|
|
UPDATE attachment_jobs
|
|
SET status = 'queued',
|
|
attempt = $2,
|
|
available_at = now(),
|
|
lease_owner = NULL,
|
|
lease_expires_at = NULL,
|
|
last_error_code = 'lease_expired',
|
|
updated_at = now()
|
|
WHERE job_id = $1`, job.ID, nextAttempt)
|
|
if err != nil {
|
|
return fmt.Errorf("reap lease: %w", mapError(err))
|
|
}
|
|
|
|
if job.PipelineVersion == attachment.PipelineVersion &&
|
|
(attachment.Status == domain.AttachmentProcessing || attachment.Status == domain.AttachmentQueued) {
|
|
_, err = tx.Exec(ctx, `
|
|
UPDATE attachments
|
|
SET status = 'queued', updated_at = now()
|
|
WHERE id = $1 AND pipeline_version = $2`,
|
|
attachment.ID, job.PipelineVersion)
|
|
if err != nil {
|
|
return fmt.Errorf("requeue reaped attachment: %w", mapError(err))
|
|
}
|
|
}
|
|
|
|
if err := insertEventTx(ctx, tx, job.ID, domain.EventLeaseExpired, job.Attempt, ""); err != nil {
|
|
return err
|
|
}
|
|
|
|
job.Attempt = nextAttempt
|
|
job.AvailableAt = time.Now().UTC()
|
|
|
|
if err := insertOutboxTx(
|
|
ctx, tx, job, nextAttempt, "lease_expired", time.Now().UTC(),
|
|
); err != nil {
|
|
return err
|
|
}
|
|
|
|
reaped++
|
|
}
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
return reaped, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) ClaimOutbox(
|
|
ctx context.Context,
|
|
owner string,
|
|
claimTTL time.Duration,
|
|
limit int,
|
|
) ([]domain.OutboxMessage, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
rows, err := r.store.pool.Query(ctx, `
|
|
WITH due AS (
|
|
SELECT o.id
|
|
FROM outbox_messages o
|
|
WHERE o.published_at IS NULL
|
|
AND o.available_at <= now()
|
|
AND (o.claimed_until IS NULL OR o.claimed_until < now())
|
|
AND NOT EXISTS (
|
|
SELECT 1 FROM outbox_messages p
|
|
WHERE p.job_id = o.job_id
|
|
AND p.published_at IS NULL
|
|
AND p.id < o.id
|
|
)
|
|
ORDER BY o.available_at, o.id
|
|
LIMIT $1
|
|
FOR UPDATE SKIP LOCKED
|
|
)
|
|
UPDATE outbox_messages o
|
|
SET claimed_by = $2,
|
|
claimed_until = now() + $3::interval
|
|
FROM due
|
|
WHERE o.id = due.id
|
|
RETURNING o.id, o.job_id, o.attempt, o.kind, o.routing_key, o.payload,
|
|
o.available_at, o.published_at, COALESCE(o.claimed_by, ''),
|
|
o.claimed_until, o.publish_attempts, o.last_error, o.created_at`,
|
|
limit, owner, intervalString(claimTTL))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("claim outbox: %w", mapError(err))
|
|
}
|
|
defer rows.Close()
|
|
|
|
messages := make([]domain.OutboxMessage, 0, limit)
|
|
|
|
for rows.Next() {
|
|
var (
|
|
message domain.OutboxMessage
|
|
claimEnd pgtype.Timestamptz
|
|
errCode pgtype.Text
|
|
pubAt pgtype.Timestamptz
|
|
)
|
|
|
|
if err := rows.Scan(
|
|
&message.ID, &message.JobID, &message.Attempt, &message.Kind,
|
|
&message.RoutingKey, &message.Payload, &message.AvailableAt, &pubAt,
|
|
&message.ClaimedBy, &claimEnd, &message.PublishAttempts, &errCode,
|
|
&message.CreatedAt,
|
|
); err != nil {
|
|
return nil, fmt.Errorf("scan outbox: %w", mapError(err))
|
|
}
|
|
|
|
if pubAt.Valid {
|
|
value := pubAt.Time.UTC()
|
|
message.PublishedAt = &value
|
|
}
|
|
if claimEnd.Valid {
|
|
value := claimEnd.Time.UTC()
|
|
message.ClaimedUntil = &value
|
|
}
|
|
if errCode.Valid {
|
|
value := errCode.String
|
|
message.LastError = &value
|
|
}
|
|
|
|
messages = append(messages, message)
|
|
}
|
|
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("claim outbox: %w", mapError(err))
|
|
}
|
|
|
|
return messages, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) MarkPublished(ctx context.Context, ids []int64) error {
|
|
if len(ids) == 0 {
|
|
return nil
|
|
}
|
|
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
_, err := r.store.pool.Exec(ctx, `
|
|
UPDATE outbox_messages
|
|
SET published_at = now(),
|
|
claimed_by = NULL,
|
|
claimed_until = NULL
|
|
WHERE id = ANY($1::bigint[])`, ids)
|
|
if err != nil {
|
|
return fmt.Errorf("mark outbox published: %w", mapError(err))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (r *PipelineRepository) ReleaseOutbox(ctx context.Context, id int64, reason string) error {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
_, err := r.store.pool.Exec(ctx, `
|
|
UPDATE outbox_messages
|
|
SET claimed_by = NULL,
|
|
claimed_until = NULL,
|
|
publish_attempts = publish_attempts + 1,
|
|
last_error = $2,
|
|
available_at = now() + interval '5 seconds'
|
|
WHERE id = $1`, id, reason)
|
|
if err != nil {
|
|
return fmt.Errorf("release outbox: %w", mapError(err))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (r *PipelineRepository) ReapOutboxClaims(ctx context.Context) error {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
_, err := r.store.pool.Exec(ctx, `
|
|
UPDATE outbox_messages
|
|
SET claimed_by = NULL, claimed_until = NULL
|
|
WHERE published_at IS NULL AND claimed_until < now()`)
|
|
if err != nil {
|
|
return fmt.Errorf("reap outbox claims: %w", mapError(err))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (r *PipelineRepository) PruneOutbox(ctx context.Context, retention time.Duration) error {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
_, err := r.store.pool.Exec(ctx, `
|
|
DELETE FROM outbox_messages
|
|
WHERE published_at IS NOT NULL AND published_at < now() - $1::interval`,
|
|
intervalString(retention))
|
|
if err != nil {
|
|
return fmt.Errorf("prune outbox: %w", mapError(err))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (r *PipelineRepository) OldestUnpublished(ctx context.Context) (time.Time, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
var oldest pgtype.Timestamptz
|
|
|
|
err := r.store.pool.QueryRow(ctx, `
|
|
SELECT min(created_at) FROM outbox_messages WHERE published_at IS NULL`).Scan(&oldest)
|
|
if err != nil {
|
|
return time.Time{}, fmt.Errorf("oldest unpublished: %w", mapError(err))
|
|
}
|
|
|
|
if !oldest.Valid {
|
|
return time.Time{}, nil
|
|
}
|
|
|
|
return oldest.Time.UTC(), nil
|
|
}
|
|
|
|
// Reprocess enqueues a new pipeline version without publishing it until the
|
|
// worker commits all variants. The serving version is switched atomically by
|
|
// CompleteJob.
|
|
func (r *PipelineRepository) Reprocess(
|
|
ctx context.Context,
|
|
attachmentID uuid.UUID,
|
|
targetVersion, maxAttempts int,
|
|
jobID uuid.UUID,
|
|
) (domain.Job, error) {
|
|
var created domain.Job
|
|
|
|
err := r.withTx(ctx, func(tx pgx.Tx) error {
|
|
attachmentRow := tx.QueryRow(ctx, `
|
|
SELECT `+attachmentReturning+`
|
|
FROM attachments WHERE id = $1 FOR UPDATE`, attachmentID)
|
|
|
|
attachment, err := scanAttachmentRow(attachmentRow)
|
|
if err != nil {
|
|
return fmt.Errorf("load reprocess attachment: %w", mapError(err))
|
|
}
|
|
|
|
if targetVersion <= attachment.PipelineVersion {
|
|
return fmt.Errorf("%w: target pipeline version must be newer", domain.ErrConflict)
|
|
}
|
|
|
|
sourceKey := attachment.StagingKey
|
|
if sourceKey == "" {
|
|
sourceKey = attachment.ObjectKey
|
|
}
|
|
if sourceKey == "" {
|
|
return fmt.Errorf("%w: attachment has no source object", domain.ErrConflict)
|
|
}
|
|
|
|
_, err = tx.Exec(ctx, `
|
|
UPDATE attachment_jobs
|
|
SET status = 'superseded', updated_at = now(), completed_at = now()
|
|
WHERE attachment_id = $1 AND status IN ('queued', 'processing')
|
|
AND pipeline_version < $2`, attachmentID, targetVersion)
|
|
if err != nil {
|
|
return fmt.Errorf("supersede old jobs: %w", mapError(err))
|
|
}
|
|
|
|
if attachment.Status != domain.AttachmentReady {
|
|
_, err = tx.Exec(ctx, `
|
|
UPDATE attachments
|
|
SET status = 'queued', error_code = NULL, failed_at = NULL, updated_at = now()
|
|
WHERE id = $1 AND status <> 'ready'`, attachmentID)
|
|
if err != nil {
|
|
return fmt.Errorf("mark reprocess attachment queued: %w", mapError(err))
|
|
}
|
|
}
|
|
|
|
job := domain.Job{
|
|
ID: jobID,
|
|
AttachmentID: attachmentID,
|
|
PipelineVersion: targetVersion,
|
|
SourceKey: sourceKey,
|
|
Attempt: 1,
|
|
MaxAttempts: maxAttempts,
|
|
CreatedAt: time.Now().UTC(),
|
|
}
|
|
|
|
_, err = tx.Exec(ctx, `
|
|
INSERT INTO attachment_jobs (
|
|
job_id, attachment_id, pipeline_version, source_key,
|
|
attempt, max_attempts, status, available_at
|
|
)
|
|
VALUES ($1, $2, $3, $4, 1, $5, 'queued', now())`,
|
|
job.ID, job.AttachmentID, job.PipelineVersion, job.SourceKey, job.MaxAttempts)
|
|
if err != nil {
|
|
return fmt.Errorf("create reprocess job: %w", mapError(err))
|
|
}
|
|
|
|
if err := insertEventTx(ctx, tx, job.ID, domain.EventReprocessed, 1, ""); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := insertOutboxTx(
|
|
ctx, tx, job, 1, "reprocess", time.Now().UTC(),
|
|
); err != nil {
|
|
return err
|
|
}
|
|
|
|
created = job
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return domain.Job{}, err
|
|
}
|
|
|
|
return created, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) ReplayJob(
|
|
ctx context.Context,
|
|
jobID uuid.UUID,
|
|
extraAttempts int,
|
|
) (domain.Job, error) {
|
|
var replayed domain.Job
|
|
|
|
err := r.withTx(ctx, func(tx pgx.Tx) error {
|
|
job, attachment, err := lockJobAndAttachment(ctx, tx, jobID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if job.Status != domain.JobFailed {
|
|
return fmt.Errorf("%w: only failed jobs can be replayed", domain.ErrConflict)
|
|
}
|
|
|
|
if job.PipelineVersion < attachment.PipelineVersion {
|
|
return fmt.Errorf("%w: job is superseded by a newer pipeline version", domain.ErrConflict)
|
|
}
|
|
|
|
nextAttempt := job.Attempt + 1
|
|
|
|
_, err = tx.Exec(ctx, `
|
|
UPDATE attachment_jobs
|
|
SET status = 'queued',
|
|
attempt = $2,
|
|
max_attempts = $2::int + $3::int - 1,
|
|
available_at = now(),
|
|
lease_owner = NULL,
|
|
lease_expires_at = NULL,
|
|
last_error_code = NULL,
|
|
replay_count = replay_count + 1,
|
|
completed_at = NULL,
|
|
updated_at = now()
|
|
WHERE job_id = $1`, job.ID, nextAttempt, extraAttempts)
|
|
if err != nil {
|
|
return fmt.Errorf("replay job: %w", mapError(err))
|
|
}
|
|
|
|
if job.PipelineVersion == attachment.PipelineVersion {
|
|
_, err = tx.Exec(ctx, `
|
|
UPDATE attachments
|
|
SET status = 'queued', error_code = NULL, failed_at = NULL, updated_at = now()
|
|
WHERE id = $1 AND pipeline_version = $2`,
|
|
attachment.ID, job.PipelineVersion)
|
|
if err != nil {
|
|
return fmt.Errorf("replay attachment: %w", mapError(err))
|
|
}
|
|
}
|
|
|
|
if err := insertEventTx(ctx, tx, job.ID, domain.EventReplayed, nextAttempt, ""); err != nil {
|
|
return err
|
|
}
|
|
|
|
job.Attempt = nextAttempt
|
|
job.MaxAttempts = nextAttempt + extraAttempts - 1
|
|
|
|
if err := insertOutboxTx(
|
|
ctx, tx, job, nextAttempt, "replay", time.Now().UTC(),
|
|
); err != nil {
|
|
return err
|
|
}
|
|
|
|
replayed = job
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return domain.Job{}, err
|
|
}
|
|
|
|
return replayed, nil
|
|
}
|
|
|
|
// Duplicate inserts another publication of the current job attempt. It exists
|
|
// only for deterministic duplicate-delivery evidence.
|
|
func (r *PipelineRepository) Duplicate(ctx context.Context, attachmentID uuid.UUID) (domain.OutboxMessage, error) {
|
|
var created domain.OutboxMessage
|
|
|
|
err := r.withTx(ctx, func(tx pgx.Tx) error {
|
|
jobRow := tx.QueryRow(ctx, `
|
|
SELECT `+jobReturning+`
|
|
FROM attachment_jobs
|
|
WHERE attachment_id = $1
|
|
ORDER BY pipeline_version DESC
|
|
LIMIT 1`, attachmentID)
|
|
|
|
job, err := scanJobRow(jobRow)
|
|
if err != nil {
|
|
return fmt.Errorf("load duplicate job: %w", mapError(err))
|
|
}
|
|
|
|
if err := insertOutboxTx(
|
|
ctx, tx, job, job.Attempt, "duplicate", time.Now().UTC(),
|
|
); err != nil {
|
|
return err
|
|
}
|
|
|
|
created = domain.OutboxMessage{
|
|
JobID: job.ID,
|
|
Attempt: job.Attempt,
|
|
Kind: "duplicate",
|
|
RoutingKey: defaultRoutingKey,
|
|
}
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return domain.OutboxMessage{}, err
|
|
}
|
|
|
|
return created, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) ListFailedJobs(
|
|
ctx context.Context,
|
|
limit int,
|
|
) ([]domain.Job, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
rows, err := r.store.pool.Query(ctx, `
|
|
SELECT `+jobReturning+`
|
|
FROM attachment_jobs
|
|
WHERE status = 'failed'
|
|
ORDER BY updated_at DESC
|
|
LIMIT $1`, limit)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list failed jobs: %w", mapError(err))
|
|
}
|
|
defer rows.Close()
|
|
|
|
jobs := make([]domain.Job, 0, limit)
|
|
|
|
for rows.Next() {
|
|
job, err := scanJobRow(rows)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("scan failed job: %w", mapError(err))
|
|
}
|
|
jobs = append(jobs, job)
|
|
}
|
|
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("list failed jobs: %w", mapError(err))
|
|
}
|
|
|
|
return jobs, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) GetJob(ctx context.Context, jobID uuid.UUID) (domain.Job, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
row := r.store.pool.QueryRow(ctx, `
|
|
SELECT `+jobReturning+` FROM attachment_jobs WHERE job_id = $1`, jobID)
|
|
|
|
job, err := scanJobRow(row)
|
|
if err != nil {
|
|
return domain.Job{}, fmt.Errorf("get job: %w", mapError(err))
|
|
}
|
|
|
|
return job, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) GetJobByAttachment(
|
|
ctx context.Context,
|
|
attachmentID uuid.UUID,
|
|
pipelineVersion int,
|
|
) (domain.Job, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
row := r.store.pool.QueryRow(ctx, `
|
|
SELECT `+jobReturning+`
|
|
FROM attachment_jobs
|
|
WHERE attachment_id = $1 AND pipeline_version = $2`,
|
|
attachmentID, pipelineVersion)
|
|
|
|
job, err := scanJobRow(row)
|
|
if err != nil {
|
|
return domain.Job{}, fmt.Errorf("get job by attachment: %w", mapError(err))
|
|
}
|
|
|
|
return job, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) GetForID(ctx context.Context, id uuid.UUID) (domain.Attachment, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
row := r.store.pool.QueryRow(ctx, `
|
|
SELECT `+attachmentReturning+` FROM attachments a WHERE a.id = $1`, id)
|
|
|
|
attachment, err := scanAttachmentRow(row)
|
|
if err != nil {
|
|
return domain.Attachment{}, fmt.Errorf("get attachment: %w", mapError(err))
|
|
}
|
|
|
|
return attachment, nil
|
|
}
|
|
|
|
// MarkStagingDeleted clears the staging projection after the worker removed
|
|
// the object (or the sweeper verified it is gone).
|
|
func (r *PipelineRepository) MarkStagingDeleted(
|
|
ctx context.Context,
|
|
attachmentID uuid.UUID,
|
|
stagingKey string,
|
|
) error {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
_, err := r.store.pool.Exec(ctx, `
|
|
UPDATE attachments
|
|
SET staging_key = NULL, updated_at = now()
|
|
WHERE id = $1 AND staging_key = $2`, attachmentID, stagingKey)
|
|
if err != nil {
|
|
return fmt.Errorf("clear staging key: %w", mapError(err))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// ListReferencedKeys returns object keys that must never be collected:
|
|
// originals, variants, and staging of active jobs.
|
|
func (r *PipelineRepository) ListReferencedKeys(
|
|
ctx context.Context,
|
|
afterKey string,
|
|
limit int,
|
|
) ([]string, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
rows, err := r.store.pool.Query(ctx, `
|
|
SELECT key FROM (
|
|
SELECT object_key AS key FROM attachments
|
|
UNION
|
|
SELECT object_key AS key FROM attachment_variants
|
|
UNION
|
|
SELECT staging_key AS key FROM attachments
|
|
WHERE staging_key IS NOT NULL AND status IN ('queued', 'processing')
|
|
) referenced
|
|
WHERE key > $1
|
|
ORDER BY key
|
|
LIMIT $2`, afterKey, limit)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list referenced keys: %w", mapError(err))
|
|
}
|
|
defer rows.Close()
|
|
|
|
keys := make([]string, 0, limit)
|
|
|
|
for rows.Next() {
|
|
var key string
|
|
if err := rows.Scan(&key); err != nil {
|
|
return nil, fmt.Errorf("scan referenced key: %w", mapError(err))
|
|
}
|
|
keys = append(keys, key)
|
|
}
|
|
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("list referenced keys: %w", mapError(err))
|
|
}
|
|
|
|
return keys, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) ListStaleStaging(
|
|
ctx context.Context,
|
|
readyBefore, failedBefore time.Time,
|
|
limit int,
|
|
) ([]domain.StaleStaging, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
rows, err := r.store.pool.Query(ctx, `
|
|
SELECT id, staging_key, status
|
|
FROM attachments
|
|
WHERE staging_key IS NOT NULL
|
|
AND (
|
|
(status = 'ready' AND updated_at < $1) OR
|
|
(status = 'failed' AND updated_at < $2)
|
|
)
|
|
ORDER BY updated_at
|
|
LIMIT $3`, readyBefore, failedBefore, limit)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list stale staging: %w", mapError(err))
|
|
}
|
|
defer rows.Close()
|
|
|
|
stale := make([]domain.StaleStaging, 0, limit)
|
|
|
|
for rows.Next() {
|
|
var (
|
|
row domain.StaleStaging
|
|
status string
|
|
)
|
|
if err := rows.Scan(&row.AttachmentID, &row.StagingKey, &status); err != nil {
|
|
return nil, fmt.Errorf("scan stale staging: %w", mapError(err))
|
|
}
|
|
row.Status = domain.AttachmentStatus(status)
|
|
stale = append(stale, row)
|
|
}
|
|
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("list stale staging: %w", mapError(err))
|
|
}
|
|
|
|
return stale, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) ListPendingPresign(
|
|
ctx context.Context,
|
|
createdBefore time.Time,
|
|
limit int,
|
|
) ([]domain.Attachment, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
rows, err := r.store.pool.Query(ctx, `
|
|
SELECT `+attachmentReturning+`
|
|
FROM attachments a
|
|
WHERE status = 'pending' AND created_at < $1
|
|
ORDER BY created_at
|
|
LIMIT $2`, createdBefore, limit)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list pending presign: %w", mapError(err))
|
|
}
|
|
defer rows.Close()
|
|
|
|
pending := make([]domain.Attachment, 0, limit)
|
|
|
|
for rows.Next() {
|
|
attachment, err := scanAttachmentRow(rows)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("scan pending presign: %w", mapError(err))
|
|
}
|
|
pending = append(pending, attachment)
|
|
}
|
|
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("list pending presign: %w", mapError(err))
|
|
}
|
|
|
|
return pending, nil
|
|
}
|
|
|
|
func (r *PipelineRepository) DeletePending(ctx context.Context, id uuid.UUID) error {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
_, err := r.store.pool.Exec(ctx, `
|
|
DELETE FROM attachments WHERE id = $1 AND status = 'pending'`, id)
|
|
if err != nil {
|
|
return fmt.Errorf("delete pending attachment: %w", mapError(err))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (r *PipelineRepository) InsertRawOutbox(
|
|
ctx context.Context,
|
|
jobID uuid.UUID,
|
|
attempt int,
|
|
kind string,
|
|
payload []byte,
|
|
availableAt time.Time,
|
|
) error {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
_, err := r.store.pool.Exec(ctx, `
|
|
INSERT INTO outbox_messages (job_id, attempt, kind, routing_key, payload, available_at)
|
|
VALUES ($1, $2, $3, $4, $5::jsonb, $6)`,
|
|
jobID, attempt, kind, defaultRoutingKey, string(payload), availableAt)
|
|
if err != nil {
|
|
return fmt.Errorf("insert raw outbox: %w", mapError(err))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// CreatePresign stores the internal pending row before a direct upload. It is
|
|
// never exposed by the API.
|
|
func (r *PipelineRepository) CreatePresign(
|
|
ctx context.Context,
|
|
draft domain.AttachmentDraft,
|
|
) (domain.Attachment, error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
row := r.store.pool.QueryRow(ctx, `
|
|
INSERT INTO attachments (
|
|
id, chat_id, owner_id, object_key, filename, content_type,
|
|
size_bytes, sha256, status, pipeline_version, staging_key
|
|
)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending', $9, $10)
|
|
RETURNING `+attachmentReturning,
|
|
draft.ID, draft.ChatID, draft.OwnerID, draft.ObjectKey, draft.Filename,
|
|
draft.ContentType, draft.SizeBytes, draft.SHA256,
|
|
draft.PipelineVersion, draft.StagingKey,
|
|
)
|
|
|
|
attachment, err := scanAttachmentRow(row)
|
|
if err != nil {
|
|
return domain.Attachment{}, fmt.Errorf("create presign attachment: %w", mapError(err))
|
|
}
|
|
|
|
return attachment, nil
|
|
}
|
|
|
|
// DuplicateJob publishes another copy of a specific job attempt. It is used by
|
|
// the fault-injection evidence to simulate duplicate delivery of an old version.
|
|
func (r *PipelineRepository) DuplicateJob(ctx context.Context, jobID uuid.UUID) (domain.OutboxMessage, error) {
|
|
var created domain.OutboxMessage
|
|
|
|
err := r.withTx(ctx, func(tx pgx.Tx) error {
|
|
jobRow := tx.QueryRow(ctx, `
|
|
SELECT `+jobReturning+` FROM attachment_jobs WHERE job_id = $1`, jobID)
|
|
|
|
job, err := scanJobRow(jobRow)
|
|
if err != nil {
|
|
return fmt.Errorf("load duplicate job: %w", mapError(err))
|
|
}
|
|
|
|
if err := insertOutboxTx(
|
|
ctx, tx, job, job.Attempt, "duplicate", time.Now().UTC(),
|
|
); err != nil {
|
|
return err
|
|
}
|
|
|
|
created = domain.OutboxMessage{
|
|
JobID: job.ID, Attempt: job.Attempt, Kind: "duplicate", RoutingKey: defaultRoutingKey,
|
|
}
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return domain.OutboxMessage{}, err
|
|
}
|
|
|
|
return created, nil
|
|
}
|