From eafc43793313c831573baea6f647c4663be1ca60 Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 16 Nov 2026 12:41:11 +0300 Subject: [PATCH] test(worker): add retry and persistence checks and adapt attachment tests for async processing --- student-tests/attachment_failover_test.go | 4 +- student-tests/attachment_helpers_test.go | 34 ++- student-tests/attachment_load_test.go | 4 +- student-tests/attachment_test.go | 9 +- student-tests/compose_helpers_test.go | 47 ++++ student-tests/dependency_failure_test.go | 40 +--- .../thumbnail_test.go | 53 +++-- student-tests/worker_test.go | 218 ++++++++++++++++++ student.mk | 6 +- 9 files changed, 345 insertions(+), 70 deletions(-) create mode 100644 student-tests/compose_helpers_test.go rename internal/worker/image_test.go => student-tests/thumbnail_test.go (67%) create mode 100644 student-tests/worker_test.go diff --git a/student-tests/attachment_failover_test.go b/student-tests/attachment_failover_test.go index e37e144..a6da30d 100644 --- a/student-tests/attachment_failover_test.go +++ b/student-tests/attachment_failover_test.go @@ -20,7 +20,7 @@ func TestAttachmentUploaderFailover(t *testing.T) { chat := createChat(t, user, user.ID) original := makePNG(t, 32, 32) resp := uploadAttachment(t, user, chat.ID, "failover.png", "image/png", original) - requireStatus(t, resp, http.StatusCreated) + requireStatus(t, resp, http.StatusAccepted) uploader := resp.Header.Get("X-Instance-Id") var att dto.AttachmentResponse mustDecode(t, resp, &att) @@ -82,7 +82,7 @@ func TestAttachmentUploaderFailover(t *testing.T) { } return } - if response.StatusCode != http.StatusBadGateway && response.StatusCode != http.StatusServiceUnavailable && response.StatusCode != http.StatusGatewayTimeout { + if response.StatusCode != http.StatusConflict && response.StatusCode != http.StatusBadGateway && response.StatusCode != http.StatusServiceUnavailable && response.StatusCode != http.StatusGatewayTimeout { t.Fatalf("unexpected download status: %d", response.StatusCode) } } diff --git a/student-tests/attachment_helpers_test.go b/student-tests/attachment_helpers_test.go index 3da7613..dd87cb9 100644 --- a/student-tests/attachment_helpers_test.go +++ b/student-tests/attachment_helpers_test.go @@ -1,4 +1,4 @@ -//go:build contract || reconcile || failure +//go:build contract || reconcile || failure || worker package studenttests_test @@ -8,6 +8,7 @@ import ( "net/http" "net/url" "testing" + "time" "github.com/google/uuid" @@ -49,12 +50,12 @@ func uploadPNG(t *testing.T, actor testUser, chatID uuid.UUID) dto.AttachmentRes t.Helper() resp := uploadAttachment(t, actor, chatID, "sample.png", "image/png", makePNG(t, 32, 32)) - requireStatus(t, resp, http.StatusCreated) + requireStatus(t, resp, http.StatusAccepted) var att dto.AttachmentResponse mustDecode(t, resp, &att) - return att + return waitAttachment(t, actor, att.ID, "ready", time.Minute) } func postMessage( @@ -104,3 +105,30 @@ func requireErrorCode(t *testing.T, resp *http.Response, code dto.ErrorCode) { t.Errorf("expected error code %q, got %q", code, apiErr.Error.Code) } } + +func waitAttachment( + t *testing.T, + actor testUser, + id uuid.UUID, + status string, + timeout time.Duration, +) dto.AttachmentResponse { + t.Helper() + + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+id.String(), actor.Token, nil) + requireStatus(t, resp, http.StatusOK) + var att dto.AttachmentResponse + mustDecode(t, resp, &att) + if string(att.Status) == status { + return att + } + if att.Status == "failed" { + t.Fatalf("attachment failed: %v", att.ErrorCode) + } + time.Sleep(200 * time.Millisecond) + } + t.Fatalf("attachment did not reach %s within %s", status, timeout) + return dto.AttachmentResponse{} +} diff --git a/student-tests/attachment_load_test.go b/student-tests/attachment_load_test.go index 2d8a854..903c506 100644 --- a/student-tests/attachment_load_test.go +++ b/student-tests/attachment_load_test.go @@ -118,7 +118,7 @@ func TestConcurrentUploads(t *testing.T) { mu.Lock() statuses[resp.StatusCode]++ - if resp.StatusCode == http.StatusCreated { + if resp.StatusCode == http.StatusAccepted { latencies = append(latencies, latency) } mu.Unlock() @@ -144,7 +144,7 @@ func TestConcurrentUploads(t *testing.T) { t.Logf("HTTP %d: %d", status, n) } - successful := statuses[http.StatusCreated] + successful := statuses[http.StatusAccepted] t.Logf("successful RPS: %.2f", float64(successful)/elapsed.Seconds()) if len(latencies) > 0 { diff --git a/student-tests/attachment_test.go b/student-tests/attachment_test.go index 0cdd0ad..31fb9e2 100644 --- a/student-tests/attachment_test.go +++ b/student-tests/attachment_test.go @@ -9,6 +9,7 @@ import ( "io" "net/http" "testing" + "time" "github.com/google/uuid" @@ -29,14 +30,16 @@ func TestAttachmentJPEG(t *testing.T) { } resp := uploadAttachment(t, user, chat.ID, "sample.jpg", "image/jpeg", body.Bytes()) - requireStatus(t, resp, http.StatusCreated) + requireStatus(t, resp, http.StatusAccepted) var att dto.AttachmentResponse mustDecode(t, resp, &att) - if att.Status != "ready" { - t.Fatalf("expected ready attachment, got %q", att.Status) + if att.Status != "queued" { + t.Fatalf("expected queued attachment, got %q", att.Status) } + waitAttachment(t, user, att.ID, "ready", time.Minute) + resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.ID.String()+"/content", user.Token, nil) requireStatus(t, resp, http.StatusOK) defer resp.Body.Close() diff --git a/student-tests/compose_helpers_test.go b/student-tests/compose_helpers_test.go new file mode 100644 index 0000000..a5d176d --- /dev/null +++ b/student-tests/compose_helpers_test.go @@ -0,0 +1,47 @@ +//go:build failure || worker + +package studenttests_test + +import ( + "net/http" + "os/exec" + "testing" + "time" +) + +func compose(t *testing.T, args ...string) { + t.Helper() + + cmd := exec.Command("docker", append([]string{"compose"}, args...)...) + cmd.Dir = ".." + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("docker compose %v: %v\n%s", args, err, out) + } +} + +func stopService(t *testing.T, name string) { + t.Helper() + + compose(t, "stop", name) + t.Cleanup(func() { + compose(t, "start", name) + waitReady(t) + }) +} + +func waitReady(t *testing.T) { + t.Helper() + + deadline := time.Now().Add(60 * time.Second) + for time.Now().Before(deadline) { + resp, err := httpClient.Get(*baseURL + "/health/ready") + if err == nil { + resp.Body.Close() + if resp.StatusCode == http.StatusOK { + return + } + } + time.Sleep(500 * time.Millisecond) + } + t.Fatal("service did not become ready in 60s") +} diff --git a/student-tests/dependency_failure_test.go b/student-tests/dependency_failure_test.go index 59d7ba1..ce570f9 100644 --- a/student-tests/dependency_failure_test.go +++ b/student-tests/dependency_failure_test.go @@ -6,50 +6,12 @@ import ( "bytes" "io" "net/http" - "os/exec" "testing" "time" "mtusi2026-messenger/internal/dto" ) -func compose(t *testing.T, args ...string) { - t.Helper() - - cmd := exec.Command("docker", append([]string{"compose"}, args...)...) - cmd.Dir = ".." - if out, err := cmd.CombinedOutput(); err != nil { - t.Fatalf("docker compose %v: %v\n%s", args, err, out) - } -} - -func stopService(t *testing.T, name string) { - t.Helper() - - compose(t, "stop", name) - t.Cleanup(func() { - compose(t, "start", name) - waitReady(t) - }) -} - -func waitReady(t *testing.T) { - t.Helper() - - deadline := time.Now().Add(60 * time.Second) - for time.Now().Before(deadline) { - resp, err := httpClient.Get(*baseURL + "/health/ready") - if err == nil { - resp.Body.Close() - if resp.StatusCode == http.StatusOK { - return - } - } - time.Sleep(500 * time.Millisecond) - } - t.Fatal("service did not become ready in 60s") -} - func TestRedisDown(t *testing.T) { user := createUser(t) @@ -140,7 +102,7 @@ func TestS3Down(t *testing.T) { response := uploadAttachment(t, user, chat.ID, "recovery.png", "image/png", original) status := response.StatusCode response.Body.Close() - if status == http.StatusCreated { + if status == http.StatusAccepted { uploaded = true } else if status != http.StatusServiceUnavailable { t.Fatalf("unexpected upload recovery status: %d", status) diff --git a/internal/worker/image_test.go b/student-tests/thumbnail_test.go similarity index 67% rename from internal/worker/image_test.go rename to student-tests/thumbnail_test.go index 5292733..5d5e4df 100644 --- a/internal/worker/image_test.go +++ b/student-tests/thumbnail_test.go @@ -1,4 +1,6 @@ -package worker +//go:build contract + +package studenttests_test import ( "bytes" @@ -7,7 +9,12 @@ import ( "image/color" "image/jpeg" "image/png" + "io" + "net/http" "testing" + "time" + + "mtusi2026-messenger/internal/dto" ) func TestThumbnail(t *testing.T) { @@ -24,10 +31,7 @@ func TestThumbnail(t *testing.T) { t.Fatal(err) } - data, width, height, err := thumbnail(bytes.NewReader(source.Bytes()), 40000000) - if err != nil { - t.Fatal(err) - } + data, width, height := processedThumbnail(t, source.Bytes(), "image/png") if width != tc.wantWidth || height != tc.wantHeight { t.Fatalf("got %dx%d", width, height) @@ -82,10 +86,7 @@ func TestThumbnailEXIF(t *testing.T) { 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) - } + result, width, height := processedThumbnail(t, data, "image/jpeg") if width != 20 || height != 40 { t.Fatalf("orientation ignored: %dx%d", width, height) @@ -106,17 +107,29 @@ func TestThumbnailEXIF(t *testing.T) { } } -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) - } +func processedThumbnail(t *testing.T, source []byte, contentType string) ([]byte, int, int) { + t.Helper() + user := createUser(t) + chat := createChat(t, user, user.ID) + resp := uploadAttachment(t, user, chat.ID, "image", contentType, source) + requireStatus(t, resp, http.StatusAccepted) + var att dto.AttachmentResponse + mustDecode(t, resp, &att) + att = waitAttachment(t, user, att.ID, "ready", time.Minute) + for _, v := range att.Variants { + if v.Name != "thumbnail" { + continue + } + resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.ID.String()+"/content?variant=thumbnail", user.Token, nil) + requireStatus(t, resp, http.StatusOK) + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + if 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") + return data, v.Width, v.Height } + t.Fatal("ready attachment has no thumbnail") + return nil, 0, 0 } diff --git a/student-tests/worker_test.go b/student-tests/worker_test.go new file mode 100644 index 0000000..a1d3220 --- /dev/null +++ b/student-tests/worker_test.go @@ -0,0 +1,218 @@ +//go:build worker + +package studenttests_test + +import ( + "bytes" + "context" + "encoding/json" + "image/jpeg" + "io" + "net/http" + "os/exec" + "reflect" + "strconv" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "mtusi2026-messenger/internal/dto" +) + +func workerCommand(t *testing.T, args ...string) string { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, "docker", args...) + cmd.Dir = ".." + out, err := cmd.Output() + if err != nil { + t.Fatalf("Docker command failed: %v", err) + } + return strings.TrimSpace(string(out)) +} + +func workerSQL(t *testing.T, query string) string { + t.Helper() + return workerCommand(t, "compose", "exec", "-T", "postgres", "psql", + "-U", "messenger", "-d", "messenger", "-Atqc", query) +} + +func workerWait(t *testing.T, description string, timeout time.Duration, condition func() bool) { + t.Helper() + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + if condition() { + return + } + time.Sleep(300 * time.Millisecond) + } + t.Fatalf("timeout waiting for %s", description) +} + +func workerQueue(t *testing.T) string { + t.Helper() + out := workerCommand(t, "compose", "exec", "-T", "rabbitmq", "rabbitmqctl", + "list_queues", "name", "messages_ready", "messages_unacknowledged", "--silent") + for _, line := range strings.Split(out, "\n") { + fields := strings.Fields(line) + if len(fields) == 3 && fields[0] == "attachments.process.v1" { + return fields[1] + ":" + fields[2] + } + } + t.Fatal("attachment queue missing") + return "" +} + +func workerUpload(t *testing.T, user testUser, chatID uuid.UUID) (dto.AttachmentResponse, []byte) { + t.Helper() + source := makePNG(t, 320, 200) + resp := uploadAttachment(t, user, chatID, "worker.png", "image/png", source) + requireStatus(t, resp, http.StatusAccepted) + var att dto.AttachmentResponse + mustDecode(t, resp, &att) + if att.Status != "queued" { + t.Fatalf("expected queued, got %s", att.Status) + } + return att, source +} + +func workerContent(t *testing.T, user testUser, id uuid.UUID, variant string) []byte { + t.Helper() + resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+id.String()+"/content?variant="+variant, user.Token, nil) + requireStatus(t, resp, http.StatusOK) + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + return data +} + +func TestWorkerPersistenceAndDuplicate(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") + } + att, source := workerUpload(t, user, chat.ID) + where := "attachment_id='" + att.ID.String() + "'" + resp := postMessage(t, user, chat.ID, "", []uuid.UUID{att.ID}) + requireStatus(t, resp, http.StatusCreated) + var message dto.MessageResponse + mustDecode(t, resp, &message) + resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.ID.String()+"/content", user.Token, nil) + requireStatus(t, resp, http.StatusConflict) + resp.Body.Close() + resp = sendMessage(t, user, chat.ID, "worker is stopped") + requireStatus(t, resp, http.StatusCreated) + resp.Body.Close() + workerWait(t, "confirmed publication", 15*time.Second, func() bool { + return workerSQL(t, "SELECT published_at IS NOT NULL FROM outbox WHERE "+where) == "t" + }) + stopService(t, "api") + if workerQueue(t) != "1:0" { + t.Fatal("accepted job is not pending in broker") + } + before := workerCommand(t, "compose", "ps", "-q", "rabbitmq") + compose(t, "up", "-d", "--no-deps", "--force-recreate", "rabbitmq") + after := workerCommand(t, "compose", "ps", "-q", "rabbitmq") + if before == after { + t.Fatal("broker was not recreated") + } + workerWait(t, "broker health", 30*time.Second, func() bool { + return workerCommand(t, "inspect", "--format", "{{.State.Health.Status}}", after) == "healthy" + }) + if workerQueue(t) != "1:0" { + t.Fatal("job lost after broker recreation with existing volume") + } + compose(t, "start", "api") + waitReady(t) + att = waitAttachment(t, user, att.ID, "queued", 15*time.Second) + resp = doRequest(t, http.MethodGet, "/api/v1/chats/"+chat.ID.String()+"/messages", user.Token, nil) + requireStatus(t, resp, http.StatusOK) + var page dto.MessagePageResponse + mustDecode(t, resp, &page) + found := false + for _, item := range page.Items { + if item.ID == message.ID && reflect.DeepEqual(item.AttachmentIDs, message.AttachmentIDs) { + found = true + } + } + if !found { + t.Fatal("message with attachment lost after API restart") + } + compose(t, "start", "worker") + ready := waitAttachment(t, user, att.ID, "ready", 30*time.Second) + if !bytes.Equal(workerContent(t, user, att.ID, "original"), source) { + t.Fatal("original changed") + } + thumb := workerContent(t, user, att.ID, "thumbnail") + cfg, err := jpeg.DecodeConfig(bytes.NewReader(thumb)) + if err != nil || cfg.Width != 256 || cfg.Height != 160 { + t.Fatal("invalid JPEG thumbnail") + } + // Re-publish the same intent, modeling duplicate delivery after a lost publisher confirmation. + workerSQL(t, "UPDATE outbox SET published_at=NULL WHERE "+where) + workerWait(t, "duplicate publication", 15*time.Second, func() bool { + return workerSQL(t, "SELECT published_at IS NOT NULL FROM outbox WHERE "+where) == "t" + }) + workerWait(t, "duplicate acknowledgement", 15*time.Second, func() bool { return workerQueue(t) == "0:0" }) + duplicate := waitAttachment(t, user, att.ID, "ready", 30*time.Second) + if !reflect.DeepEqual(ready, duplicate) || workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "1" { + t.Fatal("duplicate job changed metadata or duplicated variants") + } + if !bytes.Equal(workerContent(t, user, att.ID, "thumbnail"), thumb) || + !bytes.Equal(workerContent(t, user, att.ID, "original"), source) { + t.Fatal("duplicate changed content") + } + t.Logf("PASS attachment=%s: queued survives API/broker restart; ready; duplicate acknowledged with unchanged result", att.ID) +} + +func TestWorkerRetryExhausted(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + stopService(t, "worker") + att, _ := workerUpload(t, user, chat.ID) + workerID := workerCommand(t, "compose", "ps", "-a", "-q", "worker") + var env []string + if err := json.Unmarshal([]byte(workerCommand(t, "inspect", "--format", "{{json .Config.Env}}", workerID)), &env); err != nil { + t.Fatal(err) + } + maxAttempts := 5 + for _, entry := range env { + if value, ok := strings.CutPrefix(entry, "JOB_MAX_ATTEMPTS="); ok { + n, err := strconv.Atoi(value) + if err != nil || n < 1 { + t.Fatal("invalid JOB_MAX_ATTEMPTS") + } + maxAttempts = n + } + } + // A separate worker gets an unreachable S3 endpoint and a short attempt timeout. + // Keep the configured attempt count and normal backoff; leave the shared S3 running. + testWorker := "worker-retry-" + uuid.NewString() + t.Cleanup(func() { + workerCommand(t, "rm", "-f", testWorker) + }) + workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker, + "-e", "JOB_TIMEOUT_SECONDS=3", "-e", "S3_ENDPOINT=http://127.0.0.1:1", "worker") + failed := waitAttachment(t, user, att.ID, "failed", 90*time.Second) + if failed.ErrorCode == nil || *failed.ErrorCode != "retry_exhausted" { + t.Fatal("expected safe retry_exhausted error") + } + attempts := workerSQL(t, "SELECT attempts FROM attachments WHERE id='"+att.ID.String()+"'") + if attempts != strconv.Itoa(maxAttempts) { + t.Fatalf("expected %d attempts, got %s", maxAttempts, attempts) + } + resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.ID.String()+"/content", user.Token, nil) + requireStatus(t, resp, http.StatusConflict) + resp.Body.Close() + resp = postMessage(t, user, chat.ID, "", []uuid.UUID{att.ID}) + requireStatus(t, resp, http.StatusConflict) + resp.Body.Close() + t.Logf("PASS attachment=%s: %d attempts, failed/retry_exhausted, content/link rejected", att.ID, maxAttempts) +} diff --git a/student.mk b/student.mk index 6b2f745..c5c51fa 100644 --- a/student.mk +++ b/student.mk @@ -8,10 +8,11 @@ ACTION ?= stop-one.sh ACTION_AT ?= 10s DRY_RUN ?= true -.PHONY: help-go contract-go race-go load-go failure-go load-action-go reconcile reconcile-test-go +.PHONY: help-go contract-go race-go load-go failure-go load-action-go reconcile reconcile-test-go worker-go help-go: @echo "contract-go: contract tests" + @echo "worker-go: worker persistence, duplicate and bounded retry (stops shared services)" @echo "race-go: concurrency tests (-race)" @echo "load-go: load test" @echo "failure-go: dependency failure tests (stops redis/postgres/s3 containers)" @@ -42,3 +43,6 @@ reconcile: reconcile-test-go: docker compose --env-file .env build reconcile go test -count=1 -tags=reconcile ./student-tests/... -v -args -base-url=$(BASE_URL) + +worker-go: + go test -count=1 -tags=worker ./student-tests/... -v -args -base-url=$(BASE_URL)