forked from mtusi2026/mtusi2026lab5
87 lines
1.8 KiB
Go
87 lines
1.8 KiB
Go
package worker
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"mtusi2026-messenger/internal/db"
|
|
s3store "mtusi2026-messenger/internal/s3"
|
|
)
|
|
|
|
var (
|
|
errAttachmentNotReplayable = errors.New("attachment is not replayable: expected failed with staging and no existing variants")
|
|
errMissingPipelineJob = errors.New("attachment has no pipeline job")
|
|
errReplayNotUpdated = errors.New("attachment replay did not update one row")
|
|
)
|
|
|
|
type txBeginner interface {
|
|
Begin(ctx context.Context) (pgx.Tx, error)
|
|
}
|
|
|
|
func Replay(
|
|
ctx context.Context,
|
|
pool txBeginner,
|
|
storage *s3store.Client,
|
|
id uuid.UUID,
|
|
operator, reason string,
|
|
) error {
|
|
tx, err := pool.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
|
|
q := db.New(tx)
|
|
row, err := q.LockFailedAttachmentForReplay(ctx, id)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return errAttachmentNotReplayable
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if row.JobID == nil {
|
|
return errMissingPipelineJob
|
|
}
|
|
|
|
if err := verify(ctx, storage, *row.StagingKey, row.SizeBytes, row.Sha256); err != nil {
|
|
return fmt.Errorf("verify replay source: %w", err)
|
|
}
|
|
|
|
n, err := q.ReplayAttachmentJob(ctx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if n != 1 {
|
|
return errReplayNotUpdated
|
|
}
|
|
|
|
if err := q.CreateAttachmentReplay(ctx, db.CreateAttachmentReplayParams{
|
|
AttachmentID: id,
|
|
Attempt: row.Attempts + 1,
|
|
PreviousErrorCode: row.ErrorCode,
|
|
Operator: operator,
|
|
Reason: reason,
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
|
|
if _, err := q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
|
AttachmentID: id,
|
|
Attempt: row.Attempts + 1,
|
|
AvailableAt: time.Now(),
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|