forked from mtusi2026/mtusi2026lab5
Реализовать уровень 4 и упорядочить структуру backend
Добавить crop и WebP, изолированную обработку с таймаутом, lease token, backoff с jitter, реестр failed, безопасный replay и очистку staging. Добавить проверки crash-окон и восстановления. Разделить запуск API, CLI-команды, фоновые процессы и инфраструктуру по пакетам.
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -114,6 +114,13 @@ func newTestFixture(t *testing.T) *testFixture {
|
||||
if _, err = db.Exec(ctx, string(ddl)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ddl, err = os.ReadFile("../repositories/migrations/000008_job_recovery.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(ctx, string(ddl)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = redisClient.Close() })
|
||||
if err := redisClient.Ping(ctx).Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
Reference in New Issue
Block a user