forked from mtusi2026/mtusi2026lab7
143 lines
5.4 KiB
Go
143 lines
5.4 KiB
Go
package repositories
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"github.com/jackc/pgx/v5"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
type FailedJob struct {
|
|
ID string `json:"job_id"`
|
|
AttachmentID string `json:"attachment_id"`
|
|
Code string `json:"error_code"`
|
|
Attempts int `json:"attempts"`
|
|
FailedAt time.Time `json:"failed_at"`
|
|
}
|
|
|
|
func (s *AttachmentStore) FailedJobs(ctx context.Context) ([]FailedJob, error) {
|
|
rows, err := s.db.Query(ctx, `SELECT j.id,j.attachment_id,f.error_code,f.attempts,f.failed_at FROM attachment_job_failures f JOIN attachment_jobs j ON j.id=f.job_id JOIN attachments a ON a.id=j.attachment_id WHERE a.status='failed' AND j.pipeline_version=a.pipeline_version AND j.superseded_at IS NULL ORDER BY f.failed_at DESC LIMIT 100`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
result := []FailedJob{}
|
|
for rows.Next() {
|
|
var j FailedJob
|
|
if err = rows.Scan(&j.ID, &j.AttachmentID, &j.Code, &j.Attempts, &j.FailedAt); err != nil {
|
|
return nil, err
|
|
}
|
|
result = append(result, j)
|
|
}
|
|
return result, rows.Err()
|
|
}
|
|
|
|
func (s *AttachmentStore) ReplayJob(ctx context.Context, id, reason string, exists func(context.Context, string) error) (bool, error) {
|
|
reason = strings.TrimSpace(reason)
|
|
if reason == "" || utf8.RuneCountInString(reason) > 200 {
|
|
return false, errors.New("replay reason must contain 1-200 characters")
|
|
}
|
|
tx, err := s.db.Begin(ctx)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
var status, key, attachment string
|
|
var deleted, obsolete bool
|
|
err = tx.QueryRow(ctx, `SELECT a.status,j.staging_key,a.id,j.staging_deleted_at IS NOT NULL,j.pipeline_version<>a.pipeline_version OR j.superseded_at IS NOT NULL FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.id=$1 FOR UPDATE OF j,a`, id).Scan(&status, &key, &attachment, &deleted, &obsolete)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if obsolete || status != "failed" {
|
|
return false, nil
|
|
}
|
|
if deleted {
|
|
return false, errors.New("staging has expired; replay unavailable")
|
|
}
|
|
if key != "staging/jobs/"+attachment && key != "originals/"+attachment {
|
|
return false, errors.New("invalid staging key")
|
|
}
|
|
if err = exists(ctx, key); err != nil {
|
|
return false, errors.New("staging unavailable; replay not scheduled")
|
|
}
|
|
if _, err = tx.Exec(ctx, `INSERT INTO attachment_job_replays(job_id,reason) VALUES($1,$2)`, id, reason); err != nil {
|
|
return false, err
|
|
}
|
|
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET attempts=0,generation=generation+1,next_attempt_at=now(),lease_until=NULL,lease_token=NULL,published_at=NULL WHERE id=$1`, id); err != nil {
|
|
return false, err
|
|
}
|
|
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=$1`, attachment); err != nil {
|
|
return false, err
|
|
}
|
|
return true, tx.Commit(ctx)
|
|
}
|
|
|
|
// Replay and cleanup lock the same rows. A ready source is removed only after
|
|
// final publication, failed sources expire after retention; queued work is safe.
|
|
func (s *AttachmentStore) CleanupJobStaging(ctx context.Context, id string, retention time.Duration, dryRun bool, remove func(context.Context, string) error) (bool, error) {
|
|
tx, err := s.db.Begin(ctx)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
var key, attachment, status string
|
|
var eligible bool
|
|
err = tx.QueryRow(ctx, `SELECT j.staging_key,a.id,a.status,j.staging_deleted_at IS NULL AND (a.status='ready' AND jsonb_array_length(a.variants)>=3 OR a.status='failed' AND j.pipeline_version=a.pipeline_version AND COALESCE(f.failed_at,a.updated_at)<now()-$2*interval '1 second') FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id LEFT JOIN attachment_job_failures f ON f.job_id=j.id WHERE j.id=$1 FOR UPDATE OF j,a SKIP LOCKED`, id, retention.Seconds()).Scan(&key, &attachment, &status, &eligible)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return false, nil
|
|
}
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if !eligible || key == "originals/"+attachment {
|
|
return false, nil
|
|
}
|
|
if key != "staging/jobs/"+attachment {
|
|
return false, errors.New("invalid staging key")
|
|
}
|
|
if dryRun {
|
|
return true, nil
|
|
}
|
|
if err = remove(ctx, key); err != nil {
|
|
return false, err
|
|
}
|
|
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET staging_deleted_at=now() WHERE id=$1`, id); err != nil {
|
|
return false, err
|
|
}
|
|
return true, tx.Commit(ctx)
|
|
}
|
|
|
|
func (s *AttachmentStore) CleanupJobs(ctx context.Context, retention time.Duration, dryRun bool, remove func(context.Context, string) error) (int, error) {
|
|
rows, err := s.db.Query(ctx, `SELECT j.id FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id LEFT JOIN attachment_job_failures f ON f.job_id=j.id WHERE j.staging_deleted_at IS NULL AND j.staging_key='staging/jobs/'||j.attachment_id::text AND (a.status='ready' AND jsonb_array_length(a.variants)>=3 OR a.status='failed' AND j.pipeline_version=a.pipeline_version AND COALESCE(f.failed_at,a.updated_at)<now()-$1*interval '1 second') ORDER BY j.created_at LIMIT 100`, retention.Seconds())
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
ids := []string{}
|
|
for rows.Next() {
|
|
var id string
|
|
if err = rows.Scan(&id); err != nil {
|
|
rows.Close()
|
|
return 0, err
|
|
}
|
|
ids = append(ids, id)
|
|
}
|
|
err = rows.Err()
|
|
rows.Close()
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
count := 0
|
|
for _, id := range ids {
|
|
done, e := s.CleanupJobStaging(ctx, id, retention, dryRun, remove)
|
|
if e != nil {
|
|
return count, e
|
|
}
|
|
if done {
|
|
count++
|
|
}
|
|
}
|
|
return count, nil
|
|
}
|