Files
mtusi2026lab7/internal/adapter/postgres/attachment_jobs.go
T
2026-11-22 23:33:11 +03:00

907 lines
31 KiB
Go

package postgres
import (
"context"
"errors"
"fmt"
"time"
"mtusi2026lab7/internal/domain"
"github.com/jackc/pgx/v5"
)
const attachmentJobColumns = `
schema_version, job_id::text, job_type, attachment_id::text,
pipeline_version, attempt, max_attempts, status, error_code,
available_at, lease_until, leased_by, replay_count, created_at, updated_at,
COALESCE(traceparent, ''), COALESCE(tracestate, '')
`
type scanner interface {
Scan(dest ...any) error
}
func scanAttachmentJob(row scanner, job *domain.AttachmentJob) error {
return row.Scan(
&job.SchemaVersion,
&job.JobID,
&job.Type,
&job.AttachmentID,
&job.PipelineVersion,
&job.Attempt,
&job.MaxAttempts,
&job.Status,
&job.ErrorCode,
&job.AvailableAt,
&job.LeaseUntil,
&job.LeasedBy,
&job.ReplayCount,
&job.CreatedAt,
&job.UpdatedAt,
&job.TraceParent,
&job.TraceState,
)
}
func (s *PostgreSQLStore) CreateQueuedAttachment(ctx context.Context, attachment domain.Attachment, job domain.AttachmentJob) (domain.Attachment, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(queryContext)
if err != nil {
return domain.Attachment{}, fmt.Errorf("begin queued attachment transaction: %w", err)
}
defer func() { _ = tx.Rollback(queryContext) }()
err = tx.QueryRow(queryContext, `
INSERT INTO attachments (
id, chat_id, owner_id, object_key, staging_key, filename, content_type,
size_bytes, sha256, width, height, pipeline_version, status, error_code,
created_at, updated_at
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,decode($9,'hex'),$10,$11,$12,$13,NULL,$14,$15)
RETURNING created_at, updated_at
`, attachment.ID, attachment.ChatID, attachment.OwnerID, attachment.ObjectKey,
attachment.StagingKey, attachment.Filename, attachment.ContentType, attachment.SizeBytes,
attachment.SHA256, attachment.Width, attachment.Height, attachment.PipelineVersion,
attachment.Status, attachment.CreatedAt, attachment.UpdatedAt,
).Scan(&attachment.CreatedAt, &attachment.UpdatedAt)
if err != nil {
return domain.Attachment{}, fmt.Errorf("insert queued attachment: %w", err)
}
if job.AvailableAt.IsZero() {
job.AvailableAt = job.CreatedAt
}
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_jobs (
job_id, attachment_id, schema_version, job_type, pipeline_version,
attempt, max_attempts, status, available_at, created_at, updated_at,
traceparent, tracestate
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
`, job.JobID, job.AttachmentID, job.SchemaVersion, job.Type, job.PipelineVersion,
job.Attempt, job.MaxAttempts, job.Status, job.AvailableAt, job.CreatedAt, job.UpdatedAt,
job.TraceParent, job.TraceState)
if err != nil {
return domain.Attachment{}, fmt.Errorf("insert attachment job: %w", err)
}
if err = tx.Commit(queryContext); err != nil {
return domain.Attachment{}, fmt.Errorf("commit queued attachment: %w", err)
}
attachment.Variants = make([]domain.AttachmentVariant, 0)
return attachment, nil
}
func (s *PostgreSQLStore) ListUnpublishedAttachmentJobs(ctx context.Context, limit int) ([]domain.AttachmentJob, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
rows, err := s.pool.Query(queryContext, `
SELECT `+attachmentJobColumns+`
FROM attachment_jobs
WHERE status = 'queued' AND published_at IS NULL
AND available_at <= CURRENT_TIMESTAMP
ORDER BY available_at, created_at, job_id
LIMIT $1
`, limit)
if err != nil {
return nil, fmt.Errorf("list unpublished attachment jobs: %w", err)
}
defer rows.Close()
jobs := make([]domain.AttachmentJob, 0)
for rows.Next() {
var job domain.AttachmentJob
if err = scanAttachmentJob(rows, &job); err != nil {
return nil, fmt.Errorf("scan unpublished attachment job: %w", err)
}
jobs = append(jobs, job)
}
return jobs, rows.Err()
}
func (s *PostgreSQLStore) MarkAttachmentJobPublished(ctx context.Context, jobID string, attempt int, publishedAt time.Time) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
_, err := s.pool.Exec(queryContext, `
UPDATE attachment_jobs SET published_at = $3, updated_at = $3
WHERE job_id = $1 AND attempt = $2 AND status = 'queued'
`, jobID, attempt, publishedAt)
if err != nil {
return fmt.Errorf("mark attachment job published: %w", err)
}
return nil
}
func (s *PostgreSQLStore) ClaimAttachmentJob(
ctx context.Context,
message domain.AttachmentJobMessage,
workerID string,
leaseUntil time.Time,
) (domain.AttachmentJob, bool, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(queryContext)
if err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("begin claim attachment job: %w", err)
}
defer func() { _ = tx.Rollback(queryContext) }()
var job domain.AttachmentJob
err = scanAttachmentJob(tx.QueryRow(queryContext, `
UPDATE attachment_jobs
SET status = 'processing', lease_until = $5, leased_by = $6,
updated_at = CURRENT_TIMESTAMP
WHERE job_id = $1 AND attachment_id = $2 AND pipeline_version = $3
AND attempt = $4 AND status = 'queued'
AND available_at <= CURRENT_TIMESTAMP
AND EXISTS (
SELECT 1 FROM attachments a
WHERE a.id = attachment_jobs.attachment_id
AND a.pipeline_version = attachment_jobs.pipeline_version
AND a.status = 'queued'
)
RETURNING `+attachmentJobColumns+`
`, message.JobID, message.AttachmentID, message.PipelineVersion, message.Attempt,
leaseUntil, workerID), &job)
if errors.Is(err, pgx.ErrNoRows) {
var status domain.AttachmentJobStatus
var attachmentStatus domain.AttachmentStatus
var attempt, activeVersion, jobVersion int
lookupErr := tx.QueryRow(queryContext, `
SELECT j.status, j.attempt, a.status, a.pipeline_version, j.pipeline_version
FROM attachment_jobs j
JOIN attachments a ON a.id=j.attachment_id
WHERE j.job_id=$1
FOR UPDATE OF a,j
`, message.JobID).Scan(
&status,
&attempt,
&attachmentStatus,
&activeVersion,
&jobVersion,
)
if errors.Is(lookupErr, pgx.ErrNoRows) {
return domain.AttachmentJob{}, false, ErrNotFound
}
if lookupErr != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("inspect unclaimed attachment job: %w", lookupErr)
}
err = nil
switch {
case status == domain.AttachmentJobQueued &&
activeVersion == jobVersion &&
attachmentStatus == domain.AttachmentStatusReady:
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='succeeded', error_code=NULL, published_at=COALESCE(published_at,CURRENT_TIMESTAMP),
lease_until=NULL, leased_by=NULL, updated_at=CURRENT_TIMESTAMP
WHERE job_id=$1
`, message.JobID)
status = domain.AttachmentJobSucceeded
case status == domain.AttachmentJobQueued && activeVersion != jobVersion:
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='superseded', error_code='superseded_pipeline',
lease_until=NULL, leased_by=NULL, updated_at=CURRENT_TIMESTAMP
WHERE job_id=$1
`, message.JobID)
status = domain.AttachmentJobSuperseded
}
if err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("normalize unclaimed attachment job: %w", err)
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("commit unclaimed attachment job: %w", err)
}
return domain.AttachmentJob{JobID: message.JobID, Status: status, Attempt: attempt}, false, nil
}
if err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("claim attachment job: %w", err)
}
_, err = tx.Exec(queryContext, `
UPDATE attachments SET status = 'processing', updated_at = CURRENT_TIMESTAMP
WHERE id = $1 AND pipeline_version = $2 AND status = 'queued'
`, message.AttachmentID, message.PipelineVersion)
if err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("mark attachment processing: %w", err)
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("commit claimed attachment job: %w", err)
}
return job, true, nil
}
func (s *PostgreSQLStore) GetAttachmentForProcessing(ctx context.Context, attachmentID string) (domain.Attachment, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var attachment domain.Attachment
var digest []byte
var stagingKey *string
err := s.pool.QueryRow(queryContext, `
SELECT id::text, chat_id::text, owner_id::text, object_key, staging_key,
filename, content_type, size_bytes, sha256, width, height,
pipeline_version, status, error_code, created_at, updated_at
FROM attachments WHERE id = $1
`, attachmentID).Scan(&attachment.ID, &attachment.ChatID, &attachment.OwnerID,
&attachment.ObjectKey, &stagingKey, &attachment.Filename,
&attachment.ContentType, &attachment.SizeBytes, &digest, &attachment.Width,
&attachment.Height, &attachment.PipelineVersion, &attachment.Status,
&attachment.ErrorCode, &attachment.CreatedAt, &attachment.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return domain.Attachment{}, ErrNotFound
}
if err != nil {
return domain.Attachment{}, fmt.Errorf("get attachment for processing: %w", err)
}
attachment.SHA256 = fmt.Sprintf("%x", digest)
if stagingKey != nil {
attachment.StagingKey = *stagingKey
}
return attachment, nil
}
func (s *PostgreSQLStore) CompleteAttachmentJob(
ctx context.Context,
job domain.AttachmentJob,
variants []domain.AttachmentVariant,
updatedAt time.Time,
) (bool, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(queryContext)
if err != nil {
return false, fmt.Errorf("begin complete attachment job: %w", err)
}
defer func() { _ = tx.Rollback(queryContext) }()
var attachmentStatus domain.AttachmentStatus
var pipelineVersion int
var jobStatus domain.AttachmentJobStatus
err = tx.QueryRow(queryContext, `
SELECT a.status, a.pipeline_version, j.status
FROM attachments a
JOIN attachment_jobs j ON j.attachment_id = a.id
WHERE a.id = $1 AND j.job_id = $2
FOR UPDATE OF a, j
`, job.AttachmentID, job.JobID).Scan(&attachmentStatus, &pipelineVersion, &jobStatus)
if err != nil {
return false, fmt.Errorf("lock attachment completion: %w", err)
}
if pipelineVersion != job.PipelineVersion || jobStatus == domain.AttachmentJobSuperseded {
if jobStatus != domain.AttachmentJobSuperseded {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='superseded', error_code='superseded_pipeline',
lease_until=NULL, leased_by=NULL, updated_at=$2
WHERE job_id=$1
`, job.JobID, updatedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
VALUES ($1, 'superseded', $2, 'superseded', $3, 'superseded_pipeline', $4)
`, job.JobID, jobStatus, job.Attempt, updatedAt)
}
if err != nil {
return false, fmt.Errorf("supersede stale pipeline completion: %w", err)
}
}
if err = tx.Commit(queryContext); err != nil {
return false, fmt.Errorf("commit stale pipeline completion: %w", err)
}
return false, nil
}
if attachmentStatus == domain.AttachmentStatusReady || jobStatus == domain.AttachmentJobSucceeded {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='succeeded', error_code=NULL, lease_until=NULL, leased_by=NULL, updated_at=$2
WHERE job_id=$1
`, job.JobID, updatedAt)
if err != nil {
return false, fmt.Errorf("normalize completed job: %w", err)
}
if err = tx.Commit(queryContext); err != nil {
return false, err
}
return true, nil
}
if len(variants) != 3 {
return false, fmt.Errorf("complete attachment requires three variants: %w", ErrConflict)
}
for _, variant := range variants {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_variants (
attachment_id, pipeline_version, name, object_key, content_type,
size_bytes, width, height, sha256, created_at
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,decode($9,'hex'),$10)
ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET
object_key = EXCLUDED.object_key, content_type = EXCLUDED.content_type,
size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width,
height = EXCLUDED.height, sha256 = EXCLUDED.sha256
`, job.AttachmentID, job.PipelineVersion, variant.Name, variant.ObjectKey,
variant.ContentType, variant.SizeBytes, variant.Width, variant.Height,
variant.SHA256, updatedAt)
if err != nil {
return false, fmt.Errorf("upsert attachment variant %s: %w", variant.Name, err)
}
}
tag, err := tx.Exec(queryContext, `
UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = $3
WHERE id = $1 AND pipeline_version = $2 AND status IN ('queued','processing')
`, job.AttachmentID, job.PipelineVersion, updatedAt)
if err != nil {
return false, fmt.Errorf("mark attachment ready: %w", err)
}
if tag.RowsAffected() != 1 {
return false, fmt.Errorf("active pipeline changed during completion: %w", ErrConflict)
}
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status = 'succeeded', error_code = NULL, lease_until = NULL,
leased_by = NULL, updated_at = $2
WHERE job_id = $1
`, job.JobID, updatedAt)
if err != nil {
return false, fmt.Errorf("mark attachment job succeeded: %w", err)
}
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, created_at)
VALUES ($1, 'completed', $2, 'succeeded', $3, $4)
`, job.JobID, jobStatus, job.Attempt, updatedAt)
if err != nil {
return false, fmt.Errorf("record attachment completion: %w", err)
}
if err = tx.Commit(queryContext); err != nil {
return false, fmt.Errorf("commit completed attachment job: %w", err)
}
return true, nil
}
func (s *PostgreSQLStore) RetryAttachmentJob(
ctx context.Context,
jobID string,
errorCode string,
availableAt time.Time,
updatedAt time.Time,
eventType string,
) (domain.AttachmentJob, bool, error) {
if eventType != "retry_scheduled" && eventType != "lease_recovered" {
return domain.AttachmentJob{}, false, fmt.Errorf("unsupported retry event type")
}
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(queryContext)
if err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("begin retry attachment job: %w", err)
}
defer func() { _ = tx.Rollback(queryContext) }()
var job domain.AttachmentJob
err = scanAttachmentJob(tx.QueryRow(queryContext, `
SELECT `+attachmentJobColumns+`
FROM attachment_jobs WHERE job_id = $1 FOR UPDATE
`, jobID), &job)
if err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("lock attachment job for retry: %w", err)
}
var attachmentStatus domain.AttachmentStatus
var activePipelineVersion int
if err = tx.QueryRow(queryContext,
`SELECT status, pipeline_version FROM attachments WHERE id = $1 FOR UPDATE`,
job.AttachmentID,
).Scan(&attachmentStatus, &activePipelineVersion); err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("lock attachment for retry: %w", err)
}
if activePipelineVersion != job.PipelineVersion || job.Status == domain.AttachmentJobSuperseded {
previousStatus := job.Status
if job.Status != domain.AttachmentJobSuperseded {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='superseded', error_code='superseded_pipeline',
lease_until=NULL, leased_by=NULL, updated_at=$2
WHERE job_id=$1
`, jobID, updatedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
VALUES ($1, 'superseded', $2, 'superseded', $3, 'superseded_pipeline', $4)
`, jobID, previousStatus, job.Attempt, updatedAt)
}
}
if err != nil {
return domain.AttachmentJob{}, false, err
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, false, err
}
job.Status = domain.AttachmentJobSuperseded
job.ErrorCode = stringPointer("superseded_pipeline")
job.LeaseUntil = nil
job.LeasedBy = nil
return job, true, nil
}
if attachmentStatus == domain.AttachmentStatusReady || job.Status == domain.AttachmentJobSucceeded {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='succeeded', error_code=NULL, lease_until=NULL, leased_by=NULL, updated_at=$2
WHERE job_id=$1
`, jobID, updatedAt)
if err != nil {
return domain.AttachmentJob{}, false, err
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, false, err
}
job.Status = domain.AttachmentJobSucceeded
return job, true, nil
}
if job.Status != domain.AttachmentJobProcessing {
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, false, err
}
return job, job.Status == domain.AttachmentJobFailed || job.Status == domain.AttachmentJobSuperseded, nil
}
if job.Attempt >= job.MaxAttempts {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='failed', error_code=$2, lease_until=NULL, leased_by=NULL, updated_at=$3
WHERE job_id=$1
`, jobID, errorCode, updatedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
UPDATE attachments
SET status='failed', error_code='retry_exhausted', updated_at=$3
WHERE id=$1 AND pipeline_version=$2 AND status <> 'ready'
`, job.AttachmentID, job.PipelineVersion, updatedAt)
}
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
VALUES ($1, 'permanent_failure', 'processing', 'failed', $2, $3, $4)
`, jobID, job.Attempt, errorCode, updatedAt)
}
if err != nil {
return domain.AttachmentJob{}, false, err
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, false, err
}
job.Status = domain.AttachmentJobFailed
job.ErrorCode = &errorCode
job.LeaseUntil = nil
job.LeasedBy = nil
return job, true, nil
}
job.Attempt++
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET attempt=$2, status='queued', error_code=$3, available_at=$4,
published_at=NULL, lease_until=NULL, leased_by=NULL, updated_at=$5
WHERE job_id=$1
`, jobID, job.Attempt, errorCode, availableAt, updatedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
UPDATE attachments
SET status='queued', error_code=NULL, updated_at=$3
WHERE id=$1 AND pipeline_version=$2 AND status <> 'ready'
`, job.AttachmentID, job.PipelineVersion, updatedAt)
}
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
VALUES ($1, $2, 'processing', 'queued', $3, $4, $5)
`, jobID, eventType, job.Attempt, errorCode, updatedAt)
}
if err != nil {
return domain.AttachmentJob{}, false, err
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, false, err
}
job.Status = domain.AttachmentJobQueued
job.ErrorCode = &errorCode
job.AvailableAt = availableAt
job.LeaseUntil = nil
job.LeasedBy = nil
job.UpdatedAt = updatedAt
return job, false, nil
}
func (s *PostgreSQLStore) FailAttachmentJob(ctx context.Context, jobID, errorCode string, updatedAt time.Time) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(queryContext)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(queryContext) }()
var attachmentID string
var attachmentStatus domain.AttachmentStatus
var activePipelineVersion, jobPipelineVersion, attempt int
var jobStatus domain.AttachmentJobStatus
err = tx.QueryRow(queryContext, `
SELECT a.id::text, a.status, a.pipeline_version, j.pipeline_version, j.status, j.attempt
FROM attachment_jobs j
JOIN attachments a ON a.id=j.attachment_id
WHERE j.job_id=$1 FOR UPDATE OF a,j
`, jobID).Scan(
&attachmentID,
&attachmentStatus,
&activePipelineVersion,
&jobPipelineVersion,
&jobStatus,
&attempt,
)
if err != nil {
return err
}
if activePipelineVersion != jobPipelineVersion || jobStatus == domain.AttachmentJobSuperseded {
if jobStatus != domain.AttachmentJobSuperseded {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='superseded', error_code='superseded_pipeline',
lease_until=NULL, leased_by=NULL, updated_at=$2
WHERE job_id=$1
`, jobID, updatedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
VALUES ($1, 'superseded', $2, 'superseded', $3, 'superseded_pipeline', $4)
`, jobID, jobStatus, attempt, updatedAt)
}
}
if err != nil {
return err
}
return tx.Commit(queryContext)
}
if attachmentStatus == domain.AttachmentStatusReady || jobStatus == domain.AttachmentJobSucceeded {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='succeeded', error_code=NULL, lease_until=NULL, leased_by=NULL, updated_at=$2
WHERE job_id=$1
`, jobID, updatedAt)
} else {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='failed', error_code=$2, lease_until=NULL, leased_by=NULL, updated_at=$3
WHERE job_id=$1
`, jobID, errorCode, updatedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
UPDATE attachments
SET status='failed', error_code=$3, updated_at=$4
WHERE id=$1 AND pipeline_version=$2
`, attachmentID, jobPipelineVersion, errorCode, updatedAt)
}
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
VALUES ($1, 'permanent_failure', $2, 'failed', $3, $4, $5)
`, jobID, jobStatus, attempt, errorCode, updatedAt)
}
}
if err != nil {
return err
}
return tx.Commit(queryContext)
}
func (s *PostgreSQLStore) ListExpiredAttachmentJobs(ctx context.Context, now time.Time, limit int) ([]domain.AttachmentJob, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
rows, err := s.pool.Query(queryContext, `
SELECT `+attachmentJobColumns+`
FROM attachment_jobs
WHERE status='processing' AND lease_until <= $1
ORDER BY lease_until, job_id
LIMIT $2
`, now, limit)
if err != nil {
return nil, fmt.Errorf("list expired attachment jobs: %w", err)
}
defer rows.Close()
jobs := make([]domain.AttachmentJob, 0)
for rows.Next() {
var job domain.AttachmentJob
if err = scanAttachmentJob(rows, &job); err != nil {
return nil, fmt.Errorf("scan expired attachment job: %w", err)
}
jobs = append(jobs, job)
}
return jobs, rows.Err()
}
func (s *PostgreSQLStore) ReplayFailedAttachmentJob(ctx context.Context, jobID string, replayedAt time.Time) (domain.AttachmentJob, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(queryContext)
if err != nil {
return domain.AttachmentJob{}, fmt.Errorf("begin attachment replay: %w", err)
}
defer func() { _ = tx.Rollback(queryContext) }()
var job domain.AttachmentJob
err = scanAttachmentJob(tx.QueryRow(queryContext, `
SELECT `+attachmentJobColumns+`
FROM attachment_jobs WHERE job_id=$1 FOR UPDATE
`, jobID), &job)
if errors.Is(err, pgx.ErrNoRows) {
return domain.AttachmentJob{}, ErrNotFound
}
if err != nil {
return domain.AttachmentJob{}, fmt.Errorf("lock failed job for replay: %w", err)
}
var attachmentStatus domain.AttachmentStatus
var activePipelineVersion int
var stagingKey *string
if err = tx.QueryRow(queryContext, `
SELECT status, staging_key, pipeline_version FROM attachments WHERE id=$1 FOR UPDATE
`, job.AttachmentID).Scan(&attachmentStatus, &stagingKey, &activePipelineVersion); err != nil {
return domain.AttachmentJob{}, err
}
if job.Status != domain.AttachmentJobFailed ||
attachmentStatus != domain.AttachmentStatusFailed ||
activePipelineVersion != job.PipelineVersion {
return domain.AttachmentJob{}, fmt.Errorf("only the active failed pipeline can be replayed: %w", ErrConflict)
}
if stagingKey == nil || *stagingKey == "" {
return domain.AttachmentJob{}, fmt.Errorf("failed job staging is no longer retained: %w", ErrConflict)
}
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET attempt=1, status='queued', error_code=NULL, available_at=$2,
published_at=NULL, lease_until=NULL, leased_by=NULL,
replay_count=replay_count+1, updated_at=$2
WHERE job_id=$1
`, jobID, replayedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
UPDATE attachments SET status='queued', error_code=NULL, updated_at=$2 WHERE id=$1
`, job.AttachmentID, replayedAt)
}
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, created_at)
VALUES ($1, 'operator_replay', 'failed', 'queued', 1, $2)
`, jobID, replayedAt)
}
if err != nil {
return domain.AttachmentJob{}, fmt.Errorf("replay failed job: %w", err)
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, fmt.Errorf("commit attachment replay: %w", err)
}
job.Attempt = 1
job.Status = domain.AttachmentJobQueued
job.ErrorCode = nil
job.AvailableAt = replayedAt
job.ReplayCount++
job.UpdatedAt = replayedAt
return job, nil
}
func (s *PostgreSQLStore) ListFailedAttachmentJobs(ctx context.Context, limit int) ([]domain.AttachmentJob, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
rows, err := s.pool.Query(queryContext, `
SELECT `+attachmentJobColumns+`
FROM attachment_jobs
WHERE status='failed'
ORDER BY updated_at, job_id
LIMIT $1
`, limit)
if err != nil {
return nil, fmt.Errorf("list failed attachment jobs: %w", err)
}
defer rows.Close()
jobs := make([]domain.AttachmentJob, 0)
for rows.Next() {
var job domain.AttachmentJob
if err = scanAttachmentJob(rows, &job); err != nil {
return nil, err
}
jobs = append(jobs, job)
}
return jobs, rows.Err()
}
func (s *PostgreSQLStore) LookupAttachmentByStagingKey(
ctx context.Context,
stagingKey string,
) (string, domain.AttachmentStatus, time.Time, bool, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var attachmentID string
var status domain.AttachmentStatus
var updatedAt time.Time
err := s.pool.QueryRow(queryContext, `
SELECT id::text, status, updated_at FROM attachments WHERE staging_key=$1
`, stagingKey).Scan(&attachmentID, &status, &updatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return "", "", time.Time{}, false, nil
}
if err != nil {
return "", "", time.Time{}, false, err
}
return attachmentID, status, updatedAt, true, nil
}
func (s *PostgreSQLStore) ClearAttachmentStagingKey(ctx context.Context, attachmentID, stagingKey string) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
_, err := s.pool.Exec(queryContext, `
UPDATE attachments SET staging_key=NULL
WHERE id=$1 AND staging_key=$2 AND status IN ('ready','failed')
`, attachmentID, stagingKey)
if err != nil {
return fmt.Errorf("clear attachment staging key: %w", err)
}
return nil
}
func (s *PostgreSQLStore) ListReadyStagingKeys(
ctx context.Context,
limit int,
) (map[string]string, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
rows, err := s.pool.Query(queryContext, `
SELECT staging_key, id::text
FROM attachments
WHERE status='ready' AND staging_key IS NOT NULL
ORDER BY updated_at, id
LIMIT $1
`, limit)
if err != nil {
return nil, fmt.Errorf("list ready staging keys: %w", err)
}
defer rows.Close()
keys := make(map[string]string)
for rows.Next() {
var key, attachmentID string
if err = rows.Scan(&key, &attachmentID); err != nil {
return nil, fmt.Errorf("scan ready staging key: %w", err)
}
keys[key] = attachmentID
}
return keys, rows.Err()
}
func stringPointer(value string) *string { return &value }
func (s *PostgreSQLStore) GetAttachmentJob(ctx context.Context, jobID string) (domain.AttachmentJob, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var job domain.AttachmentJob
err := scanAttachmentJob(s.pool.QueryRow(queryContext, `
SELECT `+attachmentJobColumns+`
FROM attachment_jobs WHERE job_id=$1
`, jobID), &job)
if errors.Is(err, pgx.ErrNoRows) {
return domain.AttachmentJob{}, ErrNotFound
}
if err != nil {
return domain.AttachmentJob{}, fmt.Errorf("get attachment job: %w", err)
}
return job, nil
}
func (s *PostgreSQLStore) UpgradeAttachmentPipeline(
ctx context.Context,
attachmentID string,
targetVersion int,
stagingKey string,
job domain.AttachmentJob,
upgradedAt time.Time,
) (domain.AttachmentJob, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(queryContext)
if err != nil {
return domain.AttachmentJob{}, fmt.Errorf("begin pipeline upgrade: %w", err)
}
defer func() { _ = tx.Rollback(queryContext) }()
var status domain.AttachmentStatus
var currentVersion int
err = tx.QueryRow(queryContext, `
SELECT status, pipeline_version
FROM attachments WHERE id=$1 FOR UPDATE
`, attachmentID).Scan(&status, &currentVersion)
if errors.Is(err, pgx.ErrNoRows) {
return domain.AttachmentJob{}, ErrNotFound
}
if err != nil {
return domain.AttachmentJob{}, fmt.Errorf("lock attachment for pipeline upgrade: %w", err)
}
if targetVersion != currentVersion+1 ||
(status != domain.AttachmentStatusReady && status != domain.AttachmentStatusProcessing) {
return domain.AttachmentJob{}, fmt.Errorf("pipeline upgrade requires ready/processing current version and next target version: %w", ErrConflict)
}
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
SELECT job_id, 'superseded', status, 'superseded', attempt, 'superseded_pipeline', $3
FROM attachment_jobs
WHERE attachment_id=$1 AND pipeline_version < $2
AND status IN ('queued','processing')
`, attachmentID, targetVersion, upgradedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='superseded', error_code='superseded_pipeline',
lease_until=NULL, leased_by=NULL, updated_at=$3
WHERE attachment_id=$1 AND pipeline_version < $2
AND status IN ('queued','processing')
`, attachmentID, targetVersion, upgradedAt)
}
if err == nil {
_, err = tx.Exec(queryContext, `
UPDATE attachments
SET pipeline_version=$2, staging_key=$3, status='queued',
error_code=NULL, updated_at=$4
WHERE id=$1
`, attachmentID, targetVersion, stagingKey, upgradedAt)
}
if job.AvailableAt.IsZero() {
job.AvailableAt = upgradedAt
}
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_jobs (
job_id, attachment_id, schema_version, job_type, pipeline_version,
attempt, max_attempts, status, available_at, created_at, updated_at,
traceparent, tracestate
) VALUES ($1,$2,$3,$4,$5,$6,$7,'queued',$8,$9,$10,$11,$12)
`, job.JobID, attachmentID, job.SchemaVersion, job.Type, targetVersion,
job.Attempt, job.MaxAttempts, job.AvailableAt, job.CreatedAt, job.UpdatedAt,
job.TraceParent, job.TraceState)
}
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, created_at)
VALUES ($1, 'version_upgrade', 'queued', 'queued', $2, $3)
`, job.JobID, job.Attempt, upgradedAt)
}
if err != nil {
return domain.AttachmentJob{}, fmt.Errorf("apply pipeline upgrade: %w", err)
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, fmt.Errorf("commit pipeline upgrade: %w", err)
}
job.Status = domain.AttachmentJobQueued
job.PipelineVersion = targetVersion
job.AvailableAt = upgradedAt
job.UpdatedAt = upgradedAt
return job, nil
}