package postgres import ( "context" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "go.opentelemetry.io/otel/propagation" "gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto" "gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/pipeline" "gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store" ) // QueueAttachment atomically exposes queued metadata and durable outbox intent. func (s *Store) QueueAttachment(ctx context.Context, id uuid.UUID) (dto.Attachment, error) { ctx, cancel := context.WithTimeout(ctx, s.timeout) defer cancel() carrier := propagation.MapCarrier{} propagation.TraceContext{}.Inject(ctx, carrier) var result dto.Attachment err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { var err error result, err = scanAttachment(tx.QueryRow(ctx, `UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=@id AND status='uploading' RETURNING `+attachmentColumns, pgx.StrictNamedArgs{"id": id})) if err != nil { return err } _, err = tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,pipeline_version,staging_key,traceparent,tracestate) VALUES(@job,@attachment,@version,@key,@parent,@state)`, pgx.StrictNamedArgs{"job": uuid.New(), "attachment": id, "version": result.PipelineVersion, "key": result.ObjectKey, "parent": carrier["traceparent"], "state": carrier["tracestate"]}) return err }) return result, normalize(err) } // Due scans a bounded outbox page, including expired processing leases. func (s *Store) Due(ctx context.Context, limit int) ([]pipeline.Job, error) { ctx, cancel := context.WithTimeout(ctx, s.timeout) defer cancel() rows, err := s.pool.Query(ctx, `SELECT j.id,j.attachment_id,j.pipeline_version,j.attempt+1,j.created_at,j.traceparent,j.tracestate FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id AND a.pipeline_version=j.pipeline_version WHERE j.status IN ('queued','processing') AND j.next_attempt_at<=clock_timestamp() AND (j.lease_until IS NULL OR j.lease_until maxAttempts { _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET status='failed',error_code='retry_exhausted',lease_until=NULL WHERE id=@id`, pgx.StrictNamedArgs{"id": j.ID}) if err != nil { return err } _, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=clock_timestamp() WHERE id=@id`, pgx.StrictNamedArgs{"id": j.AttachmentID}) return err } _, err = tx.Exec(ctx, `UPDATE attachments SET status='processing',updated_at=clock_timestamp() WHERE id=@id`, pgx.StrictNamedArgs{"id": j.AttachmentID}) result = &lease return err }) return result, normalize(err) } // Complete publishes only the current, unexpired fenced attempt. func (s *Store) Complete(ctx context.Context, l pipeline.Lease, key string, variants []dto.Variant) (bool, error) { ctx, cancel := context.WithTimeout(ctx, s.timeout) defer cancel() if variants == nil { variants = []dto.Variant{} } published := false err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { var version int if err := tx.QueryRow(ctx, `SELECT pipeline_version FROM attachments WHERE id=@id FOR UPDATE`, pgx.StrictNamedArgs{"id": l.Job.AttachmentID}).Scan(&version); err != nil { return err } if version != l.Job.Version { return nil } tag, err := tx.Exec(ctx, `UPDATE attachment_jobs SET status='ready',lease_until=NULL,error_code=NULL,updated_at=clock_timestamp() WHERE id=@id AND lease_id=@token AND status='processing' AND lease_until>clock_timestamp()`, pgx.StrictNamedArgs{"id": l.Job.ID, "token": l.Token}) if err != nil || tag.RowsAffected() == 0 { return err } _, err = tx.Exec(ctx, `UPDATE attachments SET status='ready',object_key=@key,variants=@variants,error_code=NULL,updated_at=clock_timestamp() WHERE id=@id`, pgx.StrictNamedArgs{"key": key, "variants": variants, "id": l.Job.AttachmentID}) published = err == nil return err }) return published, normalize(err) } // Fail persists a retry deadline or terminal result before broker acknowledgement. func (s *Store) Fail(ctx context.Context, l pipeline.Lease, code string, delay time.Duration, maxAttempts int) error { ctx, cancel := context.WithTimeout(ctx, s.timeout) defer cancel() state := "queued" if code == "invalid_image" || l.Job.Attempt >= maxAttempts { state = "failed" } if state == "failed" && code != "invalid_image" { code = "retry_exhausted" } return normalize(pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { var version int if err := tx.QueryRow(ctx, `SELECT pipeline_version FROM attachments WHERE id=@id FOR UPDATE`, pgx.StrictNamedArgs{"id": l.Job.AttachmentID}).Scan(&version); err != nil { return err } if version != l.Job.Version { return nil } tag, err := tx.Exec(ctx, `UPDATE attachment_jobs SET status=@state,error_code=@code,lease_until=NULL,next_attempt_at=clock_timestamp()+@delay*interval '1 second',last_published_at=NULL,updated_at=clock_timestamp() WHERE id=@id AND lease_id=@token AND status='processing'`, pgx.StrictNamedArgs{"state": state, "code": code, "delay": delay.Seconds(), "id": l.Job.ID, "token": l.Token}) if err != nil || tag.RowsAffected() == 0 { return err } _, err = tx.Exec(ctx, `UPDATE attachments SET status=@state,error_code=CASE WHEN @state='failed' THEN @code ELSE NULL END,updated_at=clock_timestamp() WHERE id=@id`, pgx.StrictNamedArgs{"state": state, "code": code, "id": l.Job.AttachmentID}) return err })) } // Replay retries a failed logical job or explicitly creates a newer pipeline version. func (s *Store) Replay(ctx context.Context, id uuid.UUID, version int) error { ctx, cancel := context.WithTimeout(ctx, s.timeout) defer cancel() return normalize(pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { a, err := scanAttachment(tx.QueryRow(ctx, `SELECT `+attachmentColumns+` FROM attachments WHERE id=@id FOR UPDATE`, pgx.StrictNamedArgs{"id": id})) if err != nil { return err } var expired bool if err := tx.QueryRow(ctx, `SELECT staging_expired FROM attachment_jobs WHERE attachment_id=@id AND pipeline_version=@version`, pgx.StrictNamedArgs{"id": id, "version": a.PipelineVersion}).Scan(&expired); err != nil { return err } if expired { return store.ErrConflict } if version < a.PipelineVersion || version < 1 || (version == a.PipelineVersion && a.Status != "failed") { return store.ErrConflict } var job uuid.UUID if version == a.PipelineVersion { err = tx.QueryRow(ctx, `UPDATE attachment_jobs SET status='queued',attempt=0,error_code=NULL,lease_until=NULL,last_published_at=NULL,next_attempt_at=clock_timestamp() WHERE attachment_id=@id AND pipeline_version=@version RETURNING id`, pgx.StrictNamedArgs{"id": id, "version": version}).Scan(&job) } else { job = uuid.New() _, err = tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,pipeline_version,staging_key) SELECT @job,attachment_id,@version,staging_key FROM attachment_jobs WHERE attachment_id=@id AND pipeline_version=@previous`, pgx.StrictNamedArgs{"job": job, "version": version, "id": id, "previous": a.PipelineVersion}) } if err != nil { return err } _, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',pipeline_version=@version,error_code=NULL,updated_at=clock_timestamp() WHERE id=@id`, pgx.StrictNamedArgs{"version": version, "id": id}) if err != nil { return err } _, err = tx.Exec(ctx, `INSERT INTO attachment_job_audit(job_id,action) VALUES(@job,'operator_replay')`, pgx.StrictNamedArgs{"job": job}) return err })) }