feat(worker): process attachments with thumbnails and bounded retries
This commit is contained in:
@@ -0,0 +1,152 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
|
||||
"mtusi2026-messenger/internal/db"
|
||||
)
|
||||
|
||||
var errInvalidSource = errors.New("invalid source image")
|
||||
|
||||
func thumbnail(r io.ReadSeeker, maxPixels int) ([]byte, int, int, error) {
|
||||
cfg, format, err := image.DecodeConfig(r)
|
||||
if err != nil ||
|
||||
(format != "png" && format != "jpeg") ||
|
||||
cfg.Width <= 0 ||
|
||||
cfg.Height <= 0 ||
|
||||
cfg.Width > maxPixels/cfg.Height {
|
||||
return nil, 0, 0, errInvalidSource
|
||||
}
|
||||
|
||||
if _, err := r.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, 0, 0, err
|
||||
}
|
||||
|
||||
src, err := imaging.Decode(r, imaging.AutoOrientation(true))
|
||||
if err != nil {
|
||||
return nil, 0, 0, errInvalidSource
|
||||
}
|
||||
|
||||
width, height := src.Bounds().Dx(), src.Bounds().Dy()
|
||||
if width > 256 || height > 256 {
|
||||
if width >= height {
|
||||
height = max(1, height*256/width)
|
||||
width = 256
|
||||
} else {
|
||||
width = max(1, width*256/height)
|
||||
height = 256
|
||||
}
|
||||
|
||||
src = imaging.Resize(src, width, height, imaging.Lanczos)
|
||||
}
|
||||
|
||||
dst := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
draw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
|
||||
draw.Draw(dst, dst.Bounds(), src, src.Bounds().Min, draw.Over)
|
||||
|
||||
var out bytes.Buffer
|
||||
if err := jpeg.Encode(&out, dst, &jpeg.Options{Quality: 85}); err != nil {
|
||||
return nil, 0, 0, err
|
||||
}
|
||||
|
||||
return out.Bytes(), width, height, nil
|
||||
}
|
||||
|
||||
func (w *Worker) process(ctx context.Context, row db.Attachment) (db.CreateAttachmentVariantParams, error) {
|
||||
if row.StagingKey == nil {
|
||||
return db.CreateAttachmentVariantParams{}, errInvalidSource
|
||||
}
|
||||
|
||||
source, err := w.s3.Get(ctx, *row.StagingKey)
|
||||
if err != nil {
|
||||
return db.CreateAttachmentVariantParams{}, err
|
||||
}
|
||||
|
||||
defer source.Body.Close()
|
||||
|
||||
tmp, err := os.CreateTemp("", "attachment-job-*")
|
||||
if err != nil {
|
||||
return db.CreateAttachmentVariantParams{}, err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = tmp.Close()
|
||||
_ = os.Remove(tmp.Name())
|
||||
}()
|
||||
|
||||
hash := sha256.New()
|
||||
size, err := io.Copy(io.MultiWriter(tmp, hash), io.LimitReader(source.Body, int64(w.maxBytes)+1))
|
||||
if err != nil {
|
||||
return db.CreateAttachmentVariantParams{}, err
|
||||
}
|
||||
|
||||
if size != int64(row.SizeBytes) ||
|
||||
hex.EncodeToString(hash.Sum(nil)) != row.Sha256 {
|
||||
return db.CreateAttachmentVariantParams{}, errInvalidSource
|
||||
}
|
||||
|
||||
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
|
||||
return db.CreateAttachmentVariantParams{}, err
|
||||
}
|
||||
|
||||
select {
|
||||
case w.decodeSlot <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return db.CreateAttachmentVariantParams{}, ctx.Err()
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
<-w.decodeSlot
|
||||
return db.CreateAttachmentVariantParams{}, err
|
||||
}
|
||||
|
||||
data, width, height, err := thumbnail(tmp, w.maxPixels)
|
||||
<-w.decodeSlot
|
||||
if err != nil {
|
||||
return db.CreateAttachmentVariantParams{}, err
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return db.CreateAttachmentVariantParams{}, err
|
||||
}
|
||||
|
||||
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
|
||||
return db.CreateAttachmentVariantParams{}, err
|
||||
}
|
||||
|
||||
if err := w.s3.Put(ctx, row.S3Key, tmp, size, string(row.ContentType)); err != nil {
|
||||
return db.CreateAttachmentVariantParams{}, err
|
||||
}
|
||||
|
||||
key := "variants/" + row.ID.String() + "/v" + strconv.Itoa(row.PipelineVersion) + "/thumbnail"
|
||||
if err := w.s3.Put(ctx, key, bytes.NewReader(data), int64(len(data)), "image/jpeg"); err != nil {
|
||||
return db.CreateAttachmentVariantParams{}, err
|
||||
}
|
||||
|
||||
sum := sha256.Sum256(data)
|
||||
return db.CreateAttachmentVariantParams{
|
||||
AttachmentID: row.ID,
|
||||
PipelineVersion: row.PipelineVersion,
|
||||
Variant: db.AttachmentVariantNameThumbnail,
|
||||
S3Key: key,
|
||||
ContentType: "image/jpeg",
|
||||
SizeBytes: len(data),
|
||||
Width: width,
|
||||
Height: height,
|
||||
Sha256: hex.EncodeToString(sum[:]),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestThumbnail(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
width, height, wantWidth, wantHeight int
|
||||
}{
|
||||
{"landscape", 320, 200, 256, 160}, {"portrait", 201, 321, 160, 256},
|
||||
{"small", 12, 7, 12, 7}, {"thin", 1, 1000, 1, 256},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var source bytes.Buffer
|
||||
if err := png.Encode(&source, image.NewNRGBA(image.Rect(0, 0, tc.width, tc.height))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
data, width, height, err := thumbnail(bytes.NewReader(source.Bytes()), 40000000)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if width != tc.wantWidth || height != tc.wantHeight {
|
||||
t.Fatalf("got %dx%d", width, height)
|
||||
}
|
||||
|
||||
decoded, err := jpeg.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if decoded.Bounds().Dx() != width || decoded.Bounds().Dy() != height {
|
||||
t.Fatal("JPEG dimensions disagree")
|
||||
}
|
||||
|
||||
r, g, b, _ := decoded.At(0, 0).RGBA()
|
||||
if r < 65000 || g < 65000 || b < 65000 {
|
||||
t.Fatal("transparent source was not composited on white")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestThumbnailEXIF(t *testing.T) {
|
||||
src := image.NewRGBA(image.Rect(0, 0, 40, 20))
|
||||
|
||||
for y := 0; y < 20; y++ {
|
||||
for x := 0; x < 40; x++ {
|
||||
c := color.RGBA{255, 0, 0, 255}
|
||||
if x >= 20 {
|
||||
c = color.RGBA{0, 0, 255, 255}
|
||||
}
|
||||
|
||||
src.Set(x, y, c)
|
||||
}
|
||||
}
|
||||
|
||||
var original bytes.Buffer
|
||||
if err := jpeg.Encode(&original, src, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Little-endian TIFF, orientation=6 (90 degrees clockwise).
|
||||
exif := []byte{
|
||||
'E', 'x', 'i', 'f', 0, 0, 'I', 'I',
|
||||
42, 0, 8, 0, 0, 0, 1, 0,
|
||||
0x12, 1, 3, 0, 1, 0, 0, 0,
|
||||
6, 0, 0, 0, 0, 0, 0, 0,
|
||||
}
|
||||
segment := []byte{0xff, 0xe1, 0, 0}
|
||||
binary.BigEndian.PutUint16(segment[2:], uint16(len(exif)+2))
|
||||
data := append([]byte{}, original.Bytes()[:2]...)
|
||||
data = append(data, segment...)
|
||||
data = append(data, exif...)
|
||||
data = append(data, original.Bytes()[2:]...)
|
||||
result, width, height, err := thumbnail(bytes.NewReader(data), 40000000)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if width != 20 || height != 40 {
|
||||
t.Fatalf("orientation ignored: %dx%d", width, height)
|
||||
}
|
||||
|
||||
decoded, err := jpeg.Decode(bytes.NewReader(result))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
r, _, b, _ := decoded.At(10, 5).RGBA()
|
||||
if r <= b {
|
||||
t.Fatal("incorrect EXIF rotation")
|
||||
}
|
||||
|
||||
if bytes.Contains(result, []byte("Exif")) {
|
||||
t.Fatal("EXIF retained")
|
||||
}
|
||||
}
|
||||
|
||||
func TestThumbnailRejectsInvalidSource(t *testing.T) {
|
||||
var source bytes.Buffer
|
||||
if err := png.Encode(&source, image.NewNRGBA(image.Rect(0, 0, 100, 100))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, _, _, err := thumbnail(bytes.NewReader(source.Bytes()), 9999); err == nil {
|
||||
t.Fatal("pixel limit ignored")
|
||||
}
|
||||
|
||||
if _, _, _, err := thumbnail(bytes.NewReader(source.Bytes()[:20]), 40000000); err == nil {
|
||||
t.Fatal("truncated image accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math/rand/v2"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
|
||||
"mtusi2026-messenger/internal/config"
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/model"
|
||||
"mtusi2026-messenger/internal/rabbitmq"
|
||||
s3store "mtusi2026-messenger/internal/s3"
|
||||
)
|
||||
|
||||
var (
|
||||
errLeaseExpired = errors.New("attachment lease expired")
|
||||
errMissingThumbnail = errors.New("ready attachment has no thumbnail")
|
||||
errAttemptProcessing = errors.New("attachment attempt is still processing")
|
||||
errAttemptUnavailable = errors.New("attachment attempt is not yet available")
|
||||
errEffectChecksumMismatch = errors.New("attachment effect checksum mismatch")
|
||||
)
|
||||
|
||||
type Worker struct {
|
||||
pool *pgxpool.Pool
|
||||
q *db.Queries
|
||||
s3 *s3store.Client
|
||||
brokerURL string
|
||||
cfg config.WorkerConfig
|
||||
maxBytes, maxPixels int
|
||||
decodeSlot chan struct{}
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func New(
|
||||
pool *pgxpool.Pool,
|
||||
s3 *s3store.Client,
|
||||
brokerURL string,
|
||||
cfg config.WorkerConfig,
|
||||
maxBytes, maxPixels int,
|
||||
log *slog.Logger,
|
||||
) *Worker {
|
||||
return &Worker{
|
||||
pool: pool,
|
||||
q: db.New(pool),
|
||||
s3: s3,
|
||||
brokerURL: brokerURL,
|
||||
cfg: cfg,
|
||||
maxBytes: maxBytes,
|
||||
maxPixels: maxPixels,
|
||||
decodeSlot: make(chan struct{}, 1),
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) Run(ctx context.Context) {
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
w.recoverLoop(ctx)
|
||||
}()
|
||||
|
||||
for range w.cfg.Concurrency {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
w.consumeLoop(ctx)
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (w *Worker) consumeLoop(ctx context.Context) {
|
||||
for ctx.Err() == nil {
|
||||
client, err := rabbitmq.New(w.brokerURL)
|
||||
if err == nil {
|
||||
err = w.consume(ctx, client)
|
||||
_ = client.Close()
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
|
||||
w.log.Warn("worker consumer reconnect", "error", err)
|
||||
if !wait(ctx, 2*time.Second) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) consume(ctx context.Context, client *rabbitmq.Client) error {
|
||||
stop := context.AfterFunc(ctx, func() {
|
||||
_ = client.Close()
|
||||
})
|
||||
defer stop()
|
||||
|
||||
deliveries, err := client.Consume(ctx, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case delivery, ok := <-deliveries:
|
||||
if !ok {
|
||||
return amqp.ErrClosed
|
||||
}
|
||||
|
||||
var job model.AttachmentJob
|
||||
if json.Unmarshal(delivery.Body, &job) != nil ||
|
||||
job.SchemaVersion != 1 ||
|
||||
job.Type != "attachment.process.v1" ||
|
||||
job.JobID == uuid.Nil ||
|
||||
job.AttachmentID == uuid.Nil ||
|
||||
job.PipelineVersion != 1 ||
|
||||
job.Attempt < 1 ||
|
||||
job.CreatedAt.IsZero() {
|
||||
if err := delivery.Reject(false); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.log.Warn("invalid attachment job rejected")
|
||||
continue
|
||||
}
|
||||
|
||||
err := w.handle(ctx, job)
|
||||
if err == nil {
|
||||
if err := delivery.Ack(false); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
w.log.Warn(
|
||||
"attachment job not acknowledged",
|
||||
"job_id",
|
||||
job.JobID,
|
||||
"attempt",
|
||||
job.Attempt,
|
||||
"error",
|
||||
err,
|
||||
)
|
||||
if !wait(ctx, time.Second) {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
if err := delivery.Nack(false, true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) handle(ctx context.Context, job model.AttachmentJob) error {
|
||||
jobCtx, cancel := context.WithTimeout(ctx, w.cfg.Timeout)
|
||||
defer cancel()
|
||||
|
||||
row, err := w.q.ClaimAttachmentJob(jobCtx, db.ClaimAttachmentJobParams{
|
||||
ID: job.AttachmentID,
|
||||
JobID: job.JobID,
|
||||
PipelineVersion: job.PipelineVersion,
|
||||
Attempt: job.Attempt,
|
||||
LeaseUntil: time.Now().Add(w.cfg.Timeout),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return w.duplicate(jobCtx, job)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.log.Info("attachment processing", "job_id", job.JobID, "attachment_id", row.ID, "attempt", job.Attempt)
|
||||
variant, processErr := w.process(jobCtx, row)
|
||||
if processErr != nil {
|
||||
resultCtx, resultCancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer resultCancel()
|
||||
|
||||
return w.finishFailure(resultCtx, job, processErr)
|
||||
}
|
||||
|
||||
tx, err := w.pool.Begin(jobCtx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
q := w.q.WithTx(tx)
|
||||
_, err = q.LockAttachmentJob(jobCtx, db.LockAttachmentJobParams{
|
||||
ID: job.AttachmentID,
|
||||
JobID: job.JobID,
|
||||
PipelineVersion: job.PipelineVersion,
|
||||
Attempt: job.Attempt,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := q.CreateAttachmentVariant(jobCtx, variant); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
n, err := q.CompleteAttachmentJob(jobCtx, db.CompleteAttachmentJobParams{
|
||||
ID: row.ID,
|
||||
Attempt: job.Attempt,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if n != 1 {
|
||||
return errLeaseExpired
|
||||
}
|
||||
|
||||
if err := tx.Commit(jobCtx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.log.Info("attachment ready", "job_id", job.JobID, "attachment_id", row.ID, "attempt", job.Attempt)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Worker) duplicate(ctx context.Context, job model.AttachmentJob) error {
|
||||
row, err := w.q.GetAttachmentByID(ctx, job.AttachmentID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if row.JobID == nil || *row.JobID != job.JobID || row.PipelineVersion != job.PipelineVersion {
|
||||
return nil
|
||||
}
|
||||
|
||||
if row.Status == db.AttachmentStatusFailed {
|
||||
return nil
|
||||
}
|
||||
|
||||
if row.Status == db.AttachmentStatusReady {
|
||||
variants, err := w.q.ListAttachmentVariants(ctx, db.ListAttachmentVariantsParams{
|
||||
AttachmentID: row.ID,
|
||||
PipelineVersion: row.PipelineVersion,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := w.verify(ctx, row.S3Key, row.SizeBytes, row.Sha256); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, variant := range variants {
|
||||
if variant.Variant == db.AttachmentVariantNameThumbnail {
|
||||
return w.verify(ctx, variant.S3Key, variant.SizeBytes, variant.Sha256)
|
||||
}
|
||||
}
|
||||
|
||||
return errMissingThumbnail
|
||||
}
|
||||
|
||||
if row.Status == db.AttachmentStatusProcessing && row.Attempts == job.Attempt {
|
||||
return errAttemptProcessing
|
||||
}
|
||||
|
||||
if row.Attempts >= job.Attempt {
|
||||
return nil
|
||||
}
|
||||
|
||||
return errAttemptUnavailable
|
||||
}
|
||||
|
||||
func (w *Worker) verify(ctx context.Context, key string, size int, checksum string) error {
|
||||
object, err := w.s3.Get(ctx, key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer object.Body.Close()
|
||||
|
||||
hash := sha256.New()
|
||||
n, err := io.Copy(hash, io.LimitReader(object.Body, int64(size)+1))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if n != int64(size) || hex.EncodeToString(hash.Sum(nil)) != checksum {
|
||||
return errEffectChecksumMismatch
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Worker) finishFailure(ctx context.Context, job model.AttachmentJob, cause error) error {
|
||||
tx, err := w.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
q := w.q.WithTx(tx)
|
||||
row, err := q.LockAttachmentJob(ctx, db.LockAttachmentJobParams{
|
||||
ID: job.AttachmentID,
|
||||
JobID: job.JobID,
|
||||
PipelineVersion: job.PipelineVersion,
|
||||
Attempt: job.Attempt,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
code := "processing_failed"
|
||||
permanent := errors.Is(cause, errInvalidSource) || errors.Is(cause, s3store.ErrObjectNotFound)
|
||||
if permanent {
|
||||
code = "invalid_source"
|
||||
} else if errors.Is(cause, context.DeadlineExceeded) {
|
||||
code = "job_timeout"
|
||||
}
|
||||
|
||||
var n int64
|
||||
if permanent || row.Attempts >= w.cfg.MaxAttempts {
|
||||
if !permanent {
|
||||
code = "retry_exhausted"
|
||||
}
|
||||
|
||||
n, err = q.FailAttachmentJob(ctx, db.FailAttachmentJobParams{
|
||||
ID: row.ID,
|
||||
Attempt: job.Attempt,
|
||||
ErrorCode: code,
|
||||
})
|
||||
} else {
|
||||
n, err = q.RetryAttachmentJob(ctx, db.RetryAttachmentJobParams{
|
||||
ID: row.ID,
|
||||
Attempt: job.Attempt,
|
||||
ErrorCode: code,
|
||||
})
|
||||
if err == nil && n == 1 {
|
||||
_, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
||||
AttachmentID: row.ID,
|
||||
Attempt: row.Attempts + 1,
|
||||
AvailableAt: time.Now().Add(retryDelay(row.Attempts)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if n != 1 {
|
||||
return errLeaseExpired
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.log.Warn(
|
||||
"attachment processing failed",
|
||||
"job_id",
|
||||
job.JobID,
|
||||
"attempt",
|
||||
job.Attempt,
|
||||
"error_code",
|
||||
code,
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Worker) recoverLoop(ctx context.Context) {
|
||||
for ctx.Err() == nil {
|
||||
recovered, err := w.recoverOne(ctx)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
w.log.Warn("recover attachment lease", "error", err)
|
||||
}
|
||||
|
||||
if (err != nil || !recovered) && !wait(ctx, time.Second) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) recoverOne(ctx context.Context) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
tx, err := w.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
q := w.q.WithTx(tx)
|
||||
rows, err := q.LockExpiredAttachmentJobs(ctx, 1)
|
||||
if err != nil || len(rows) == 0 {
|
||||
return false, err
|
||||
}
|
||||
|
||||
row := rows[0]
|
||||
if row.Attempts >= w.cfg.MaxAttempts {
|
||||
_, err = q.FailExpiredAttachmentJob(ctx, row.ID)
|
||||
} else {
|
||||
_, err = q.RecoverExpiredAttachmentJob(ctx, row.ID)
|
||||
if err == nil {
|
||||
_, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
||||
AttachmentID: row.ID,
|
||||
Attempt: row.Attempts + 1,
|
||||
AvailableAt: time.Now().Add(retryDelay(row.Attempts)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
w.log.Info("attachment lease recovered", "attachment_id", row.ID, "attempt", row.Attempts)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func wait(ctx context.Context, duration time.Duration) bool {
|
||||
timer := time.NewTimer(duration)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-timer.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func retryDelay(attempt int) time.Duration {
|
||||
ceiling := time.Second * time.Duration(1<<min(max(attempt, 1), 6))
|
||||
return ceiling/2 + time.Duration(rand.Int64N(int64(ceiling/2)))
|
||||
}
|
||||
Reference in New Issue
Block a user