Files
mtusi2026lab5/app/cmd/worker/replay.go
T

43 lines
1.4 KiB
Go

package main
import (
"context"
"fmt"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
func replay(ctx context.Context, p *pgxpool.Pool, s objectstore.Store, id string) error {
if _, err := uuid.Parse(id); err != nil {
return fmt.Errorf("invalid attachment id")
}
tx, err := p.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
var status, key string
if err = tx.QueryRow(ctx, `SELECT status,object_key FROM attachments WHERE id=$1 FOR UPDATE`, id).Scan(&status, &key); err != nil {
return err
}
if status != "failed" {
return fmt.Errorf("replay requires failed state; ready is never reset")
}
body, _, err := s.Get(ctx, key)
if err != nil {
return fmt.Errorf("staging unavailable")
}
body.Close()
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',attempts=0,processing_started_at=NULL,error_code=NULL,lease_until=NULL,next_attempt_at=now(),updated_at=now() WHERE id=$1`, id); err != nil {
return err
}
if _, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(attachment_id) VALUES($1) ON CONFLICT(attachment_id) DO UPDATE SET next_publish_at=now()`, id); err != nil {
return err
}
if _, err = tx.Exec(ctx, `INSERT INTO attachment_replays(attachment_id) VALUES($1)`, id); err != nil {
return err
}
return tx.Commit(ctx)
}