forked from mtusi2026/mtusi2026lab6
265 lines
8.1 KiB
Go
265 lines
8.1 KiB
Go
package jobs
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"math/rand/v2"
|
|
"time"
|
|
|
|
"mtusi2026/internal/idgen"
|
|
"mtusi2026/internal/model"
|
|
"mtusi2026/internal/telemetry"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/trace"
|
|
)
|
|
|
|
const JobType = "attachment.process.v1"
|
|
|
|
type Job struct {
|
|
SchemaVersion int `json:"schema_version"`
|
|
ID string `json:"job_id"`
|
|
Type string `json:"type"`
|
|
AttachmentID string `json:"attachment_id"`
|
|
PipelineVersion int `json:"pipeline_version"`
|
|
Attempt int `json:"attempt"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
}
|
|
|
|
type Repo struct {
|
|
Pool *pgxpool.Pool
|
|
MaxAttempts int
|
|
Lease time.Duration
|
|
}
|
|
type Work struct {
|
|
Job
|
|
Token, StagingKey, ObjectKey, SHA256, ContentType string
|
|
Size int64
|
|
}
|
|
|
|
func Enqueue(ctx context.Context, tx pgx.Tx, attachmentID string) error {
|
|
id := idgen.GenerateUUIDv4()
|
|
carrier := telemetry.Inject(ctx)
|
|
_, err := tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,created_at,traceparent,tracestate)
|
|
VALUES($1,$2,clock_timestamp(),NULLIF($3,''),NULLIF($4,''))`, id, attachmentID, carrier.Get("traceparent"), carrier.Get("tracestate"))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(job_id,attempt) VALUES($1,1)`, id)
|
|
return err
|
|
}
|
|
|
|
func (r Repo) Claim(ctx context.Context, j Job) (*Work, error) {
|
|
tx, err := r.Pool.Begin(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
w := &Work{Job: j, Token: idgen.GenerateUUIDv4()}
|
|
err = tx.QueryRow(ctx, `UPDATE attachment_jobs SET status='processing',attempt=attempt+1,
|
|
lease_token=$3,lease_until=now()+$4::interval,updated_at=now()
|
|
WHERE id=$1 AND attachment_id=$2 AND pipeline_version=$5 AND status='queued'
|
|
AND next_attempt_at<=now() AND attempt=$6-1
|
|
RETURNING attempt,created_at`, j.ID, j.AttachmentID, w.Token, r.Lease.String(), j.PipelineVersion, j.Attempt).Scan(&w.Attempt, &w.CreatedAt)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
err = tx.QueryRow(ctx, `UPDATE attachments SET status='processing',updated_at=now()
|
|
WHERE id=$1 RETURNING staging_key,object_key,sha256,content_type,size_bytes`, j.AttachmentID).
|
|
Scan(&w.StagingKey, &w.ObjectKey, &w.SHA256, &w.ContentType, &w.Size)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err = tx.Commit(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
return w, nil
|
|
}
|
|
|
|
func (r Repo) Complete(ctx context.Context, w *Work, variants []model.Variant) (_ bool, err error) {
|
|
ctx, span := telemetry.Tracer.Start(ctx, "db.job.complete",
|
|
trace.WithAttributes(attribute.String("db.system.name", "postgresql")))
|
|
defer func() { telemetry.Finish(span, err) }()
|
|
tx, err := r.Pool.Begin(ctx)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
tag, err := tx.Exec(ctx, `UPDATE attachment_jobs SET status='ready',error_code=NULL,
|
|
lease_token=NULL,lease_until=NULL,updated_at=now() WHERE id=$1 AND status='processing'
|
|
AND lease_token=$2 AND lease_until>now()`, w.ID, w.Token)
|
|
if err != nil || tag.RowsAffected() == 0 {
|
|
return false, err
|
|
}
|
|
b, err := json.Marshal(variants)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
_, err = tx.Exec(ctx, `UPDATE attachments SET status='ready',variants=$2,error_code=NULL,updated_at=now() WHERE id=$1`, w.AttachmentID, b)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return true, tx.Commit(ctx)
|
|
}
|
|
|
|
func RetryDelay(attempt int) time.Duration {
|
|
base := time.Second
|
|
for i := 1; i < attempt && base < 60*time.Second; i++ {
|
|
base *= 2
|
|
}
|
|
if base > 60*time.Second {
|
|
base = 60 * time.Second
|
|
}
|
|
return base/2 + time.Duration(rand.Int64N(int64(base/2)+1))
|
|
}
|
|
|
|
func (r Repo) Fail(ctx context.Context, w *Work, code string, permanent bool) error {
|
|
tx, err := r.Pool.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
var attempt, replayBase int
|
|
err = tx.QueryRow(ctx, `SELECT attempt FROM attachment_jobs WHERE id=$1 AND status='processing'
|
|
AND lease_token=$2 FOR UPDATE`, w.ID, w.Token).Scan(&attempt)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err = tx.QueryRow(ctx, `SELECT COALESCE(max(previous_attempt),0) FROM job_replays WHERE job_id=$1`, w.ID).Scan(&replayBase); err != nil {
|
|
return err
|
|
}
|
|
state := "queued"
|
|
if permanent || attempt-replayBase >= r.MaxAttempts {
|
|
state = "failed"
|
|
if !permanent {
|
|
code = "retry_exhausted"
|
|
}
|
|
}
|
|
delay := RetryDelay(attempt)
|
|
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET status=$2,error_code=$3,lease_until=NULL,lease_token=NULL,
|
|
next_attempt_at=now()+$4::interval,updated_at=now() WHERE id=$1`, w.ID, state, code, delay.String())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = tx.Exec(ctx, `UPDATE attachments SET status=$2,error_code=$3,updated_at=now() WHERE id=$1`, w.AttachmentID, state, code)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if state == "queued" {
|
|
_, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(job_id,attempt,available_at)
|
|
SELECT id,attempt+1,next_attempt_at FROM attachment_jobs WHERE id=$1`, w.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return tx.Commit(ctx)
|
|
}
|
|
|
|
func (r Repo) Recover(ctx context.Context) error {
|
|
rows, err := r.Pool.Query(ctx, `SELECT id,attachment_id,lease_token FROM attachment_jobs
|
|
WHERE status='processing' AND lease_until<now() LIMIT 100`)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var ws []Work
|
|
for rows.Next() {
|
|
var w Work
|
|
if err = rows.Scan(&w.ID, &w.AttachmentID, &w.Token); err != nil {
|
|
rows.Close()
|
|
return err
|
|
}
|
|
ws = append(ws, w)
|
|
}
|
|
rows.Close()
|
|
if err = rows.Err(); err != nil {
|
|
return err
|
|
}
|
|
for i := range ws {
|
|
if err = r.Fail(ctx, &ws[i], "lease_expired", false); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r Repo) Replay(ctx context.Context, id, reason string) error {
|
|
if !idgen.IsValidUUID(id) || len(reason) < 1 || len(reason) > 200 {
|
|
return errors.New("provide job UUID and reason (1..200 bytes)")
|
|
}
|
|
tx, err := r.Pool.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
var attempt int
|
|
var aid string
|
|
err = tx.QueryRow(ctx, `SELECT attempt,attachment_id FROM attachment_jobs WHERE id=$1 AND status='failed' FOR UPDATE`, id).Scan(&attempt, &aid)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return errors.New("replay allowed only for failed jobs; ready is never replayed")
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var staging *string
|
|
if err = tx.QueryRow(ctx, `SELECT staging_key FROM attachments WHERE id=$1 FOR UPDATE`, aid).Scan(&staging); err != nil {
|
|
return err
|
|
}
|
|
if staging == nil {
|
|
return errors.New("staging retention expired; original must be uploaded again")
|
|
}
|
|
_, err = tx.Exec(ctx, `INSERT INTO job_replays(job_id,reason,previous_attempt) VALUES($1,$2,$3)`, id, reason, attempt)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET status='queued',error_code=NULL,next_attempt_at=now(),updated_at=now() WHERE id=$1`, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=$1`, aid)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(job_id,attempt) VALUES($1,$2)`, id, attempt+1)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit(ctx)
|
|
}
|
|
|
|
func VariantKey(original, name string) string { return original + "/v1/" + name }
|
|
|
|
func (r Repo) Failed(ctx context.Context) ([]map[string]any, error) {
|
|
rows, err := r.Pool.Query(ctx, `SELECT id,attachment_id,attempt,error_code FROM attachment_jobs WHERE status='failed' ORDER BY updated_at`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
result := []map[string]any{}
|
|
for rows.Next() {
|
|
var id, aid, code string
|
|
var n int
|
|
if err = rows.Scan(&id, &aid, &n, &code); err != nil {
|
|
return nil, err
|
|
}
|
|
result = append(result, map[string]any{"job_id": id, "attachment_id": aid, "attempt": n, "error_code": code})
|
|
}
|
|
return result, rows.Err()
|
|
}
|
|
|
|
func (j Job) Validate() error {
|
|
if j.SchemaVersion != 1 || j.Type != JobType || j.PipelineVersion != 1 || j.Attempt < 1 || !idgen.IsValidUUID(j.ID) || !idgen.IsValidUUID(j.AttachmentID) || j.CreatedAt.IsZero() {
|
|
return fmt.Errorf("invalid job envelope")
|
|
}
|
|
return nil
|
|
}
|