package tests import ( "context" "errors" "github.com/google/uuid" "messenger/src/backend/repositories" "testing" "time" ) func TestJobExpiredLeaseCannotPublishOrExceedAttempts(t *testing.T) { f := newTestFixture(t) user, _ := createTestUser(t, f.users, "lease_user", "Lease") chat := createTestChat(t, f.chats, "Lease", []string{user.ID}) ctx := context.Background() id := uuid.NewString() store := repositories.NewAttachmentStore(f.db) if err := store.Create(ctx, repositories.Attachment{ID: id, ChatID: chat.ID, OwnerID: user.ID, Filename: "x.png", ObjectKey: "originals/" + id, ContentType: "image/png", SizeBytes: 1, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", CreatedAt: time.Now(), UpdatedAt: time.Now()}); err != nil { t.Fatal(err) } job := repositories.Job{ID: uuid.NewString(), AttachmentID: id, PipelineVersion: 1} if _, err := f.db.Exec(ctx, `UPDATE attachments SET status='queued' WHERE id=$1;`, id); err != nil { t.Fatal(err) } if _, err := f.db.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,staging_key) VALUES($1,$2,$3)`, job.ID, id, "staging/jobs/"+id); err != nil { t.Fatal(err) } first, err := store.StartAttempt(ctx, job, time.Second, 2) if err != nil || first == "" { t.Fatal("claim", err) } if _, err = f.db.Exec(ctx, `UPDATE attachment_jobs SET lease_until=now()-interval '1 second' WHERE id=$1`, job.ID); err != nil { t.Fatal(err) } second, err := store.StartAttempt(ctx, job, time.Second, 2) if err != nil || second == "" || second == first { t.Fatal("reclaim", err) } effects := 0 callback := func(repositories.Attachment, string) ([]repositories.Variant, string, error) { effects++ return nil, "", errors.New("injected storage failure") } if err = store.ProcessJob(ctx, job, first, 2, callback); err == nil || effects != 0 { t.Fatal("stale worker performed side effect") } if err = store.ProcessJob(ctx, job, second, 2, callback); err != nil || effects != 1 { t.Fatal("new worker failed", err) } if token, err := store.StartAttempt(ctx, job, time.Second, 2); err != nil || token != "" { t.Fatal("failed job reclaimed", err) } var status string var attempts int if err = f.db.QueryRow(ctx, `SELECT a.status,j.attempts FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.id=$1`, job.ID).Scan(&status, &attempts); err != nil || status != "failed" || attempts != 2 { t.Fatalf("%s/%d %v", status, attempts, err) } } func TestRetryBackoffStaysInExponentialJitterWindow(t *testing.T) { for attempt, bounds := range map[int][2]time.Duration{1: {time.Second, 2 * time.Second}, 2: {2 * time.Second, 4 * time.Second}, 3: {4 * time.Second, 8 * time.Second}, 8: {15 * time.Second, 30 * time.Second}} { seen := map[time.Duration]bool{} for i := 0; i < 20; i++ { delay := repositories.RetryDelay(attempt) if delay < bounds[0] || delay > bounds[1] { t.Fatalf("attempt %d: %v", attempt, delay) } seen[delay] = true } if len(seen) < 2 { t.Fatal("jitter produced no variation") } } }