diff --git a/compose.yaml b/compose.yaml index 1e16037..33c1e3c 100644 --- a/compose.yaml +++ b/compose.yaml @@ -165,6 +165,7 @@ services: command: - "server" - "-dir=/data" + - "-volume.max=10" - "-s3" - "-s3.port=9000" - "-s3.iam=false" diff --git a/student-tests/worker_test.go b/student-tests/worker_test.go index 4faad7c..5e41431 100644 --- a/student-tests/worker_test.go +++ b/student-tests/worker_test.go @@ -9,6 +9,7 @@ import ( "image/jpeg" "io" "net/http" + "os" "os/exec" "reflect" "strconv" @@ -17,6 +18,7 @@ import ( "time" "github.com/google/uuid" + "github.com/jackc/pgx/v5" "golang.org/x/image/webp" "mtusi2026-messenger/internal/dto" @@ -356,3 +358,140 @@ func TestWorkerReplay(t *testing.T) { t.Fatal("duplicate replay changed audit or attempt counter") } } + +func TestWorkerOutboxRecovery(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + stopService(t, "worker") + if workerQueue(t) != "0:0" { + t.Fatal("run on an idle stand with an empty attachment queue") + } + + stopService(t, "rabbitmq") + att, source := workerUpload(t, user, chat.ID) + id := att.ID.String() + where := "attachment_id='" + id + "'" + jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") + if workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND attempt=1 AND published_at IS NULL") != "1" { + t.Fatal("upload 202 did not persist an unpublished intent") + } + + t.Cleanup(func() { + compose(t, "start", "api") + waitReady(t) + }) + compose(t, "kill", "-s", "SIGKILL", "api") + if workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND attempt=1 AND published_at IS NULL") != "1" { + t.Fatal("committed intent lost after API crash") + } + + compose(t, "start", "api") + waitReady(t) + waitAttachment(t, user, att.ID, "queued", 15*time.Second) + compose(t, "up", "-d", "--no-deps", "--wait", "--wait-timeout", "30", "rabbitmq") + workerWait(t, "outbox publication after API crash", 15*time.Second, func() bool { + return workerSQL(t, "SELECT published_at IS NOT NULL FROM outbox WHERE "+where) == "t" + }) + if workerQueue(t) != "1:0" { + t.Fatal("recovered intent was not delivered to broker") + } + + compose(t, "start", "worker") + ready := waitAttachment(t, user, att.ID, "ready", 30*time.Second) + if len(ready.Variants) != 3 || !bytes.Equal(workerContent(t, user, att.ID, "original"), source) { + t.Fatal("recovered attachment has incomplete variants or changed original") + } + workerWait(t, "recovered job acknowledgement", 15*time.Second, func() bool { + return workerQueue(t) == "0:0" + }) + if workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID || + workerSQL(t, "SELECT attempts FROM attachments WHERE id='"+id+"'") != "1" || + workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where) != "1" { + t.Fatal("recovery replaced the job or created another attempt") + } + + t.Logf("PASS attachment=%s: commit, API SIGKILL before publication, automatic outbox recovery, same job ready", id) +} + +func TestWorkerLeaseRecovery(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + secret, err := os.ReadFile("../secrets/test_database_url.txt") + if err != nil { + t.Fatal("read test database URL") + } + conn, err := pgx.Connect(ctx, strings.TrimSpace(string(secret))) + if err != nil { + t.Fatal("connect to test database") + } + t.Cleanup(func() { conn.Close(context.Background()) }) + + user := createUser(t) + chat := createChat(t, user, user.ID) + stopService(t, "worker") + if workerQueue(t) != "0:0" { + t.Fatal("run on an idle stand with an empty attachment queue") + } + att, source := workerUpload(t, user, chat.ID) + id := att.ID.String() + where := "attachment_id='" + id + "'" + jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") + + testWorker := "worker-lease-" + uuid.NewString() + t.Cleanup(func() { workerCommand(t, "rm", "-f", testWorker) }) + tx, err := conn.Begin(ctx) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { tx.Rollback(context.Background()) }) + // S3 writes finish before variant metadata is inserted. Block that INSERT + // to kill the worker before the result COMMIT and broker acknowledgement. + if _, err := tx.Exec(ctx, "LOCK TABLE attachment_variants IN SHARE MODE"); err != nil { + t.Fatal(err) + } + workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker, + "-e", "JOB_TIMEOUT_SECONDS=15", "worker") + workerWait(t, "variant INSERT blocked after S3 writes", 10*time.Second, func() bool { + var blocked bool + if _, err := conn.Exec(ctx, "SELECT pg_stat_clear_snapshot()"); err != nil { + t.Fatal(err) + } + err := conn.QueryRow(ctx, `SELECT EXISTS ( + SELECT 1 FROM pg_stat_activity + WHERE $1::int = ANY(pg_blocking_pids(pid)) + AND query LIKE '%INSERT INTO attachment_variants%' + )`, int32(conn.PgConn().PID())).Scan(&blocked) + if err != nil { + t.Fatal(err) + } + return blocked + }) + workerCommand(t, "kill", "--signal", "SIGKILL", testWorker) + if err := tx.Rollback(ctx); err != nil { + t.Fatal(err) + } + if workerSQL(t, "SELECT status||':'||attempts FROM attachments WHERE id='"+id+"'") != "processing:1" || + workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "0" { + t.Fatal("crashed worker committed a result") + } + workerWait(t, "unacknowledged job returned to broker", 10*time.Second, func() bool { + return workerQueue(t) == "1:0" + }) + + // Leave lease_until unchanged: recovery must wait for its natural expiry. + compose(t, "start", "worker") + ready := waitAttachment(t, user, att.ID, "ready", 40*time.Second) + if len(ready.Variants) != 3 || !bytes.Equal(workerContent(t, user, att.ID, "original"), source) { + t.Fatal("lease recovery lost variants or changed original") + } + workerWait(t, "recovered job acknowledgement", 15*time.Second, func() bool { + return workerQueue(t) == "0:0" + }) + if workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID || + workerSQL(t, "SELECT attempts FROM attachments WHERE id='"+id+"'") != "2" || + workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "3" || + workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND attempt=2 AND published_at IS NOT NULL") != "1" { + t.Fatal("lease recovery replaced the job, duplicated variants or skipped retry publication") + } + t.Logf("PASS attachment=%s: SIGKILL after S3 writes, expired lease recovered, same job ready on attempt 2", id) +}