ЛР7 на 4: HTTPS, mTLS, OpenBao AppRole и ротация leaf.
Skeleton contracts / contracts (pull_request) Blocked by required conditions

Smoke/security/grade4/persistence/failover пройдены; REPORT и DEFENSE.
This commit is contained in:
2026-12-02 23:08:27 +03:00
parent 20afc2c790
commit 2f2047909f
182 changed files with 15169 additions and 90 deletions
+15
View File
@@ -0,0 +1,15 @@
package studenttests_test
import (
"net/http"
"testing"
)
func TestACLUnauthorizedChat(t *testing.T) {
user1 := createUser(t)
user2 := createUser(t)
outsider := createUser(t)
chat := createChat(t, user1, user1.ID, user2.ID)
resp := doRequest(t, http.MethodGet, "/api/v1/chats/"+chat.ID.String(), outsider.Token, nil)
requireStatus(t, resp, http.StatusNotFound)
}
+24
View File
@@ -0,0 +1,24 @@
package studenttests_test
import (
"strings"
"testing"
"gavrilenko-sxdees/lab7/internal/credentials"
)
func TestArgon2idRoundTrip(t *testing.T) {
hash, err := credentials.HashPassword("пароль-ź")
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(hash, "$argon2id$") {
t.Fatalf("expected argon2id prefix, got %q", hash[:20])
}
if err := credentials.VerifyPassword(hash, "пароль-ź"); err != nil {
t.Fatal(err)
}
if credentials.VerifyPassword(hash, "wrong") == nil {
t.Fatal("mismatch not detected")
}
}
+92
View File
@@ -0,0 +1,92 @@
//go:build failure
package studenttests_test
import (
"bytes"
"context"
"io"
"net/http"
"os/exec"
"strings"
"testing"
"time"
"gavrilenko-sxdees/lab7/internal/dto"
)
func TestAttachmentUploaderFailover(t *testing.T) {
user := createUser(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.StatusAccepted)
uploader := resp.Header.Get("X-Instance-Id")
var att dto.AttachmentResponse
mustDecode(t, resp, &att)
if uploader == "" {
t.Fatal("upload response has no X-Instance-Id")
}
cmd := exec.Command("docker", "compose", "ps", "-q", "api")
cmd.Dir = ".."
out, err := cmd.Output()
if err != nil {
t.Fatalf("list API replicas: %v", err)
}
replicas := strings.Fields(string(out))
if len(replicas) < 2 {
t.Fatal("at least two running API replicas required")
}
var target string
for _, id := range replicas {
if strings.HasPrefix(id, uploader) {
target = id
break
}
}
if target == "" {
t.Fatal("upload instance is not an API container in this Compose project")
}
t.Cleanup(func() {
if err := exec.Command("docker", "start", target).Run(); err != nil {
t.Errorf("restart uploader replica: %v", err)
}
})
if err := exec.Command("docker", "stop", "-t", "5", target).Run(); err != nil {
t.Fatalf("stop uploader replica: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
for ctx.Err() == nil {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, *baseURL+"/api/v1/attachments/"+att.ID.String()+"/content", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+user.Token)
response, err := httpClient.Do(req)
if err == nil {
data, readErr := io.ReadAll(response.Body)
response.Body.Close()
if response.StatusCode == http.StatusOK {
downloader := response.Header.Get("X-Instance-Id")
if downloader == "" || downloader == uploader {
t.Fatal("download was not served by another replica")
}
if readErr != nil {
t.Fatal(readErr)
}
if !bytes.Equal(data, original) {
t.Fatal("downloaded original differs from uploaded file")
}
return
}
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)
}
}
time.Sleep(200 * time.Millisecond)
}
t.Fatal("download through another replica did not recover within 10s")
}
+134
View File
@@ -0,0 +1,134 @@
//go:build contract || reconcile || failure || worker || pipeline
package studenttests_test
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
"testing"
"time"
"github.com/google/uuid"
"gavrilenko-sxdees/lab7/internal/dto"
)
const maxUploadBytes = 10 * 1024 * 1024
func uploadAttachment(
t *testing.T,
actor testUser,
chatID uuid.UUID,
filename string,
contentType string,
body []byte,
) *http.Response {
t.Helper()
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/attachments?filename="+url.QueryEscape(filename),
bytes.NewReader(body),
)
if err != nil {
t.Fatalf("build upload request: %v", err)
}
req.Header.Set("Content-Type", contentType)
req.Header.Set("Authorization", "Bearer "+actor.Token)
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("upload request failed: %v", err)
}
return resp
}
func uploadPNG(t *testing.T, actor testUser, chatID uuid.UUID) dto.AttachmentResponse {
t.Helper()
resp := uploadAttachment(t, actor, chatID, "sample.png", "image/png", makePNG(t, 32, 32))
requireStatus(t, resp, http.StatusAccepted)
var att dto.AttachmentResponse
mustDecode(t, resp, &att)
return waitAttachment(t, actor, att.ID, "ready", time.Minute)
}
func postMessage(
t *testing.T,
actor testUser,
chatID uuid.UUID,
text string,
attachmentIDs []uuid.UUID,
) *http.Response {
t.Helper()
body, err := json.Marshal(map[string]any{
"text": text,
"attachment_ids": attachmentIDs,
})
if err != nil {
t.Fatalf("marshal message: %v", err)
}
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/messages",
bytes.NewReader(body),
)
if err != nil {
t.Fatalf("build message request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+actor.Token)
req.Header.Set("Idempotency-Key", uuid.NewString())
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("message request failed: %v", err)
}
return resp
}
func requireErrorCode(t *testing.T, resp *http.Response, code dto.ErrorCode) {
t.Helper()
var apiErr dto.ErrorResponse
mustDecode(t, resp, &apiErr)
if apiErr.Error.Code != code {
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{}
}
+180
View File
@@ -0,0 +1,180 @@
//go:build load
package studenttests_test
import (
"bytes"
"net/http"
"os/exec"
"sort"
"strconv"
"strings"
"sync"
"testing"
"time"
)
func dockerMem(filter string) map[string]float64 {
out, err := exec.Command("docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.MemUsage}}").Output()
if err != nil {
return nil
}
m := map[string]float64{}
for _, line := range strings.Split(string(out), "\n") {
parts := strings.SplitN(line, "\t", 2)
if len(parts) != 2 || (filter != "" && !strings.Contains(parts[0], filter)) {
continue
}
used := strings.SplitN(parts[1], "/", 2)[0]
m[parts[0]] = memBytes(used)
}
return m
}
func memBytes(s string) float64 {
s = strings.TrimSpace(s)
units := []struct {
suf string
mult float64
}{
{"GiB", 1 << 30}, {"MiB", 1 << 20}, {"KiB", 1 << 10},
{"GB", 1e9}, {"MB", 1e6}, {"kB", 1e3}, {"B", 1},
}
for _, u := range units {
if strings.HasSuffix(s, u.suf) {
v, _ := strconv.ParseFloat(strings.TrimSpace(strings.TrimSuffix(s, u.suf)), 64)
return v * u.mult
}
}
return 0
}
func mib(v float64) string {
return strconv.FormatFloat(v/(1<<20), 'f', 1, 64) + "MiB"
}
func TestConcurrentUploads(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
body := makePNG(t, 1870, 1870)
url := *baseURL + "/api/v1/chats/" + chat.ID.String() + "/attachments?filename=load.png"
baseline := dockerMem("api")
stop := make(chan struct{})
memDone := make(chan struct{})
peak := map[string]float64{}
go func() {
defer close(memDone)
for {
for name, v := range dockerMem("api") {
if v > peak[name] {
peak[name] = v
}
}
select {
case <-stop:
return
case <-time.After(500 * time.Millisecond):
}
}
}()
var (
mu sync.Mutex
statuses = make(map[int]int)
latencies []time.Duration
errors int
)
start := time.Now()
deadline := start.Add(*duration)
var wg sync.WaitGroup
for w := 0; w < *workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for time.Now().Before(deadline) {
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
if err != nil {
mu.Lock()
errors++
mu.Unlock()
return
}
req.Header.Set("Content-Type", "image/png")
req.Header.Set("Authorization", "Bearer "+user.Token)
reqStart := time.Now()
resp, err := httpClient.Do(req)
latency := time.Since(reqStart)
if err != nil {
mu.Lock()
errors++
mu.Unlock()
continue
}
mu.Lock()
statuses[resp.StatusCode]++
if resp.StatusCode == http.StatusAccepted {
latencies = append(latencies, latency)
}
mu.Unlock()
resp.Body.Close()
}
}()
}
wg.Wait()
close(stop)
<-memDone
elapsed := time.Since(start)
total := 0
for _, n := range statuses {
total += n
}
total += errors
t.Logf("workers=%d duration=%.1fs elapsed=%.1fs", *workers, duration.Seconds(), elapsed.Seconds())
t.Logf("total uploads=%d transport_errors=%d", total, errors)
for status, n := range statuses {
t.Logf("HTTP %d: %d", status, n)
}
successful := statuses[http.StatusAccepted]
t.Logf("successful RPS: %.2f", float64(successful)/elapsed.Seconds())
if len(latencies) > 0 {
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
t.Logf("latency p50=%s p95=%s p99=%s",
percentile(latencies, 0.50),
percentile(latencies, 0.95),
percentile(latencies, 0.99),
)
}
names := make(map[string]struct{}, len(baseline)+len(peak))
for name := range baseline {
names[name] = struct{}{}
}
for name := range peak {
names[name] = struct{}{}
}
sorted := make([]string, 0, len(names))
for name := range names {
sorted = append(sorted, name)
}
sort.Strings(sorted)
if len(sorted) == 0 {
t.Log("memory: docker stats not available (no containers matched)")
return
}
t.Log("memory per container (idle -> peak):")
for _, name := range sorted {
t.Logf(" %s: %s -> %s", name, mib(baseline[name]), mib(peak[name]))
}
}
+142
View File
@@ -0,0 +1,142 @@
//go:build contract
package studenttests_test
import (
"bytes"
"image/jpeg"
"image/png"
"io"
"net/http"
"testing"
"time"
"github.com/google/uuid"
"gavrilenko-sxdees/lab7/internal/dto"
)
func TestAttachmentJPEG(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
img, err := png.Decode(bytes.NewReader(makePNG(t, 32, 32)))
if err != nil {
t.Fatalf("decode png: %v", err)
}
var body bytes.Buffer
if err := jpeg.Encode(&body, img, nil); err != nil {
t.Fatalf("encode jpeg: %v", err)
}
resp := uploadAttachment(t, user, chat.ID, "sample.jpg", "image/jpeg", body.Bytes())
requireStatus(t, resp, http.StatusAccepted)
var att dto.AttachmentResponse
mustDecode(t, resp, &att)
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()
original, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read original: %v", err)
}
if !bytes.Equal(original, body.Bytes()) {
t.Error("downloaded JPEG differs from uploaded original")
}
}
func TestAttachmentTooManyPixels(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
body := makePNG(t, 8000, 5001)
if len(body) > maxUploadBytes {
t.Fatal("pixel-limit fixture exceeds upload byte limit")
}
resp := uploadAttachment(t, user, chat.ID, "large.png", "image/png", body)
requireStatus(t, resp, http.StatusRequestEntityTooLarge)
requireErrorCode(t, resp, dto.ErrorCodePayloadTooLarge)
}
func TestAttachmentUnsafeFilename(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
resp := uploadAttachment(t, user, chat.ID, "../image.png", "image/png", makePNG(t, 32, 32))
requireStatus(t, resp, http.StatusBadRequest)
requireErrorCode(t, resp, dto.ErrorCodeInvalidRequest)
}
func TestAttachmentTooLarge(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
body := bytes.Repeat([]byte{0x00}, maxUploadBytes+1)
resp := uploadAttachment(t, user, chat.ID, "big.png", "image/png", body)
requireStatus(t, resp, http.StatusRequestEntityTooLarge)
requireErrorCode(t, resp, dto.ErrorCodePayloadTooLarge)
}
func TestAttachmentCorruptedImage(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
body := []byte("this is definitely not a png or jpeg image")
resp := uploadAttachment(t, user, chat.ID, "broken.png", "image/png", body)
requireStatus(t, resp, http.StatusUnsupportedMediaType)
requireErrorCode(t, resp, dto.ErrorCodeUnsupportedMediaType)
}
func TestAttachmentMimeSubstitution(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
resp := uploadAttachment(t, user, chat.ID, "actually-png.jpg", "image/jpeg", makePNG(t, 32, 32))
requireStatus(t, resp, http.StatusUnsupportedMediaType)
requireErrorCode(t, resp, dto.ErrorCodeUnsupportedMediaType)
}
func TestAttachmentForeignID(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
foreign := uuid.New()
resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+foreign.String(), user.Token, nil)
requireStatus(t, resp, http.StatusNotFound)
requireErrorCode(t, resp, dto.ErrorCodeNotFound)
resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+foreign.String()+"/content", user.Token, nil)
requireStatus(t, resp, http.StatusNotFound)
requireErrorCode(t, resp, dto.ErrorCodeNotFound)
resp = postMessage(t, user, chat.ID, "", []uuid.UUID{foreign})
requireStatus(t, resp, http.StatusNotFound)
requireErrorCode(t, resp, dto.ErrorCodeNotFound)
}
func TestAttachmentFromAnotherChat(t *testing.T) {
user := createUser(t)
member := createUser(t)
chatA := createChat(t, user, user.ID, member.ID)
chatB := createChat(t, user, user.ID)
att := uploadPNG(t, user, chatA.ID)
// The attachment belongs to chatA; linking it to a chatB message must fail.
resp := postMessage(t, user, chatB.ID, "", []uuid.UUID{att.ID})
requireStatus(t, resp, http.StatusNotFound)
requireErrorCode(t, resp, dto.ErrorCodeNotFound)
}
+57
View File
@@ -0,0 +1,57 @@
package studenttests_test
import (
"crypto/tls"
"crypto/x509"
"net"
"os"
"testing"
"time"
"gavrilenko-sxdees/lab7/internal/tlsconfig"
)
func TestMTLSBrokerRejectsEvilIdentity(t *testing.T) {
caPEM, _ := os.ReadFile(secretPath("ca.crt"))
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(caPEM)
evil, err := tlsconfig.ClientTLSFromFiles(
secretPath("evil-broker-client.crt"),
secretPath("evil-broker-client.key"),
secretPath("ca.crt"),
"broker-gw",
)
if err != nil {
t.Skip("pki missing evil cert")
}
addr := "127.0.0.1:5674"
conn, err := tls.DialWithDialer(&net.Dialer{Timeout: 3 * time.Second}, "tcp", addr, evil)
if err == nil {
_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
buf := make([]byte, 1)
_, rerr := conn.Read(buf)
_ = conn.Close()
if rerr != nil {
err = rerr
} else {
t.Fatal("evil broker identity should be rejected")
}
}
if err == nil {
t.Fatal("evil broker identity should be rejected")
}
good, err := tlsconfig.ClientTLSFromFiles(
secretPath("broker-api-client.crt"),
secretPath("broker-api-client.key"),
secretPath("ca.crt"),
"broker-gw",
)
if err != nil {
t.Skip("pki missing api broker cert")
}
conn2, err := tls.DialWithDialer(&net.Dialer{Timeout: 3 * time.Second}, "tcp", addr, good)
if err != nil {
t.Fatalf("valid broker client failed: %v", err)
}
_ = conn2.Close()
}
+55
View File
@@ -0,0 +1,55 @@
//go:build contract
package studenttests_test
import (
"context"
"encoding/json"
"net/http"
"os"
"strings"
"testing"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func TestCreateChatRollback(t *testing.T) {
data, err := os.ReadFile("../secrets/test_database_url.txt")
if err != nil {
t.Fatalf("read secrets/test_database_url: %v", err)
}
ctx := context.Background()
conn, err := pgx.Connect(ctx, strings.TrimSpace(string(data)))
if err != nil {
t.Fatalf("connect to database: %v", err)
}
defer conn.Close(ctx)
creator := createUser(t)
title := "rollback-" + uuid.NewString()
body, err := json.Marshal(map[string]any{
"title": title,
"member_ids": []uuid.UUID{creator.ID, uuid.New()},
})
if err != nil {
t.Fatalf("marshal body: %v", err)
}
resp := doRequest(t, http.MethodPost, "/api/v1/chats", creator.Token, body)
resp.Body.Close()
if resp.StatusCode < 400 || resp.StatusCode >= 500 {
t.Fatalf("expected 4xx, got %d", resp.StatusCode)
}
var n int
err = conn.QueryRow(ctx, "SELECT count(*) FROM chats WHERE title = $1", title).Scan(&n)
if err != nil {
t.Fatalf("count chats: %v", err)
}
if n != 0 {
t.Fatalf("expected no chat rows after failed creation, found %d", n)
}
}
+124
View File
@@ -0,0 +1,124 @@
//go:build failure || worker || pipeline
package studenttests_test
import (
"context"
"io"
"net/http"
"os/exec"
"strings"
"testing"
"time"
"github.com/google/uuid"
"gavrilenko-sxdees/lab7/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 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
}
+134
View File
@@ -0,0 +1,134 @@
//go:build contract
package studenttests_test
import (
"encoding/json"
"net/http"
"net/url"
"strconv"
"testing"
"gavrilenko-sxdees/lab7/internal/dto"
)
func TestInvalidJSON(t *testing.T) {
resp := doRequest(t, http.MethodPost, "/api/v1/users", "", []byte(`{"username": "broken",`))
requireStatus(t, resp, http.StatusBadRequest)
var apiErr dto.ErrorResponse
mustDecode(t, resp, &apiErr)
if apiErr.Error.Code != dto.ErrorCodeInvalidRequest {
t.Errorf("expected code %q, got %q", dto.ErrorCodeInvalidRequest, apiErr.Error.Code)
}
}
func TestForeignChat(t *testing.T) {
user1 := createUser(t)
user2 := createUser(t)
user3 := createUser(t)
chat := createChat(t, user1, user1.ID, user2.ID)
resp := doRequest(t, http.MethodGet, "/api/v1/chats/"+chat.ID.String(), user3.Token, nil)
requireStatus(t, resp, http.StatusNotFound)
resp = sendMessage(t, user3, chat.ID, "should not land")
requireStatus(t, resp, http.StatusNotFound)
}
func TestEmptyMessage(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
for _, text := range []string{"", " ", "\t\n"} {
resp := sendMessage(t, user, chat.ID, text)
requireStatus(t, resp, http.StatusBadRequest)
}
}
func TestDuplicateUsername(t *testing.T) {
user := createUser(t)
body, err := json.Marshal(map[string]string{
"username": user.Username,
"display_name": "Someone else",
"password": testPassword,
})
if err != nil {
t.Fatalf("marshal body: %v", err)
}
resp := doRequest(t, http.MethodPost, "/api/v1/users", "", body)
requireStatus(t, resp, http.StatusConflict)
var apiErr dto.ErrorResponse
mustDecode(t, resp, &apiErr)
if apiErr.Error.Code != dto.ErrorCodeConflict {
t.Errorf("expected code %q, got %q", dto.ErrorCodeConflict, apiErr.Error.Code)
}
}
func TestPagination(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
const total = 25
const pageSize = 4
sent := make(map[string]bool, total)
for i := 0; i < total; i++ {
resp := sendMessage(t, user, chat.ID, "msg")
requireStatus(t, resp, http.StatusCreated)
var msg dto.MessageResponse
mustDecode(t, resp, &msg)
sent[msg.ID.String()] = true
}
seen := make(map[string]bool, total)
cursor := ""
pages := 0
for {
path := "/api/v1/chats/" + chat.ID.String() + "/messages?limit=" + strconv.Itoa(pageSize)
if cursor != "" {
path += "&cursor=" + url.QueryEscape(cursor)
}
resp := doRequest(t, http.MethodGet, path, user.Token, nil)
requireStatus(t, resp, http.StatusOK)
var page dto.MessagePageResponse
mustDecode(t, resp, &page)
pages++
for _, msg := range page.Items {
id := msg.ID.String()
if seen[id] {
t.Fatalf("duplicate message id across pages: %s", id)
}
seen[id] = true
}
if page.NextCursor == nil {
break
}
cursor = *page.NextCursor
if pages > total {
t.Fatalf("too many pages: got %d, expected at most %d", pages, total)
}
}
if len(seen) != total {
t.Fatalf("expected %d unique messages across all pages, got %d", total, len(seen))
}
for id := range sent {
if !seen[id] {
t.Fatalf("message %s sent but never seen while paginating", id)
}
}
}
+118
View File
@@ -0,0 +1,118 @@
//go:build failure
package studenttests_test
import (
"bytes"
"io"
"net/http"
"testing"
"time"
"gavrilenko-sxdees/lab7/internal/dto"
)
func TestRedisDown(t *testing.T) {
user := createUser(t)
stopService(t, "redis")
// настоящий токен
resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
requireStatus(t, resp, http.StatusOK)
resp.Body.Close()
// выдуманный токен
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "forged-"+user.Token, nil)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
// без токена
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "", nil)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
}
func TestDatabaseDown(t *testing.T) {
user := createUser(t) // токен ещё не использован, ключа в Redis нет
stopService(t, "postgres")
// ключа в кэше нет, проверить сессию негде
resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
requireStatus(t, resp, http.StatusServiceUnavailable)
resp.Body.Close()
// выдуманный токен
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "forged-"+user.Token, nil)
requireStatus(t, resp, http.StatusServiceUnavailable)
resp.Body.Close()
// без токена
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "", nil)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
}
func TestS3Down(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
original := makePNG(t, 32, 32)
att := uploadPNG(t, user, chat.ID)
stopService(t, "s3")
for _, path := range []string{"/health/ready", "/api/v1/attachments/" + att.ID.String() + "/content"} {
resp := doRequest(t, http.MethodGet, path, user.Token, nil)
requireStatus(t, resp, http.StatusServiceUnavailable)
requireErrorCode(t, resp, dto.ErrorCodeUnavailable)
}
resp := uploadAttachment(t, user, chat.ID, "outage.png", "image/png", original)
requireStatus(t, resp, http.StatusServiceUnavailable)
requireErrorCode(t, resp, dto.ErrorCodeUnavailable)
resp = doRequest(t, http.MethodGet, "/health/live", "", nil)
requireStatus(t, resp, http.StatusOK)
resp.Body.Close()
compose(t, "start", "s3")
waitReady(t)
deadline := time.Now().Add(60 * time.Second)
downloaded, uploaded := false, false
for time.Now().Before(deadline) && (!downloaded || !uploaded) {
if !downloaded {
req, err := http.NewRequest(http.MethodGet, *baseURL+"/api/v1/attachments/"+att.ID.String()+"/content", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+user.Token)
response, err := httpClient.Do(req)
if err == nil {
data, readErr := io.ReadAll(response.Body)
response.Body.Close()
if response.StatusCode == http.StatusOK && readErr == nil {
if !bytes.Equal(data, original) {
t.Fatal("original changed across S3 outage")
}
downloaded = true
} else if response.StatusCode != http.StatusServiceUnavailable && response.StatusCode != http.StatusBadGateway && response.StatusCode != http.StatusGatewayTimeout {
t.Fatalf("unexpected download recovery status: %d", response.StatusCode)
}
}
}
if !uploaded {
response := uploadAttachment(t, user, chat.ID, "recovery.png", "image/png", original)
status := response.StatusCode
response.Body.Close()
if status == http.StatusAccepted {
uploaded = true
} else if status != http.StatusServiceUnavailable {
t.Fatalf("unexpected upload recovery status: %d", status)
}
}
if !downloaded || !uploaded {
time.Sleep(500 * time.Millisecond)
}
}
if !downloaded || !uploaded {
t.Fatalf("S3 did not recover in 60s: download=%t upload=%t", downloaded, uploaded)
}
}
+280
View File
@@ -0,0 +1,280 @@
package studenttests_test
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"flag"
"image"
"image/color"
"image/png"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/google/uuid"
"gavrilenko-sxdees/lab7/internal/dto"
)
var baseURL = flag.String("base-url", "https://127.0.0.1:8443", "base URL of the running server")
func secretPath(name string) string {
const repoRoot = ".."
if name == "ca.crt" {
if p := os.Getenv("CA_FILE"); p != "" {
if filepath.IsAbs(p) {
return p
}
return filepath.Join(repoRoot, filepath.Clean(p))
}
}
return filepath.Join(repoRoot, "secrets", name)
}
var httpClient = &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 200,
IdleConnTimeout: 30 * time.Second,
MaxIdleConnsPerHost: 200,
MaxConnsPerHost: 200,
},
}
func configureHTTPClientTLS() {
if !strings.HasPrefix(*baseURL, "https:") {
return
}
caPEM, err := os.ReadFile(secretPath("ca.crt"))
if err != nil {
return
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(caPEM) {
return
}
httpClient.Transport = &http.Transport{
MaxIdleConns: 200,
IdleConnTimeout: 30 * time.Second,
MaxIdleConnsPerHost: 200,
MaxConnsPerHost: 200,
TLSClientConfig: &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12},
}
}
type testUser struct {
dto.UserResponse
Token string
}
const testPassword = "correct-horse-battery"
func doRequest(t *testing.T, method, path, token string, body []byte) *http.Response {
t.Helper()
req, err := http.NewRequest(method, *baseURL+path, bytes.NewReader(body))
if err != nil {
t.Fatalf("build request: %v", err)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("%s %s: request failed: %v", method, path, err)
}
return resp
}
func mustDecode(t *testing.T, resp *http.Response, dst any) {
t.Helper()
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
if err := json.Unmarshal(data, dst); err != nil {
t.Fatalf("decode body %q: %v", data, err)
}
}
func requireStatus(t *testing.T, resp *http.Response, expected int) {
t.Helper()
if resp.StatusCode != expected {
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Fatalf(
"expected status %d, got %d, body: %s",
expected,
resp.StatusCode,
data,
)
}
if resp.Header.Get("X-Request-Id") == "" {
t.Errorf("missing X-Request-Id header")
}
}
func createUser(t *testing.T) testUser {
t.Helper()
username := "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12]
body, err := json.Marshal(map[string]string{
"username": username,
"display_name": "Test " + username,
"password": testPassword,
})
if err != nil {
t.Fatalf("marshal user: %v", err)
}
resp := doRequest(t, http.MethodPost, "/api/v1/users", "", body)
requireStatus(t, resp, http.StatusCreated)
var u dto.UserResponse
mustDecode(t, resp, &u)
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/auth/sessions",
nil,
)
if err != nil {
t.Fatalf("build login request: %v", err)
}
req.SetBasicAuth(username, testPassword)
resp, err = httpClient.Do(req)
if err != nil {
t.Fatalf("login request failed: %v", err)
}
requireStatus(t, resp, http.StatusCreated)
var session dto.SessionResponse
mustDecode(t, resp, &session)
return testUser{UserResponse: u, Token: session.Token}
}
func createChat(
t *testing.T,
creator testUser,
memberIDs ...uuid.UUID,
) dto.ChatResponse {
t.Helper()
body, err := json.Marshal(map[string]any{
"title": "Test chat " + uuid.NewString()[:8],
"member_ids": memberIDs,
})
if err != nil {
t.Fatalf("marshal chat: %v", err)
}
resp := doRequest(
t,
http.MethodPost,
"/api/v1/chats",
creator.Token,
body,
)
requireStatus(t, resp, http.StatusCreated)
var c dto.ChatResponse
mustDecode(t, resp, &c)
return c
}
func sendMessage(
t *testing.T,
actor testUser,
chatID uuid.UUID,
text string,
) *http.Response {
t.Helper()
resp, err := sendLoadMessage(actor, chatID, text)
if err != nil {
t.Fatalf("send message: %v", err)
}
return resp
}
func sendLoadMessage(
actor testUser,
chatID uuid.UUID,
text string,
) (*http.Response, error) {
body, err := json.Marshal(map[string]string{
"text": text,
})
if err != nil {
return nil, err
}
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/messages",
bytes.NewReader(body),
)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+actor.Token)
req.Header.Set("Idempotency-Key", uuid.NewString())
return httpClient.Do(req)
}
func makePNG(t *testing.T, width, height int) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, width, height))
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
img.Set(x, y, color.RGBA{
R: uint8((x * 7) % 256),
G: uint8((y * 13) % 256),
B: uint8((x + y) % 256),
A: 255,
})
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatalf("encode png: %v", err)
}
return buf.Bytes()
}
func TestMain(m *testing.M) {
flag.Parse()
configureHTTPClientTLS()
os.Exit(m.Run())
}
+169
View File
@@ -0,0 +1,169 @@
//go:build race
package studenttests_test
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/url"
"sync"
"testing"
"github.com/google/uuid"
)
const (
concurrentRequests = 20
concurrentRounds = 5
)
type keyedResult struct {
status int
instance string
body []byte
err error
}
func postWithKey(actor testUser, chatID uuid.UUID, key, text string) keyedResult {
body, err := json.Marshal(map[string]string{"text": text})
if err != nil {
return keyedResult{err: err}
}
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/messages",
bytes.NewReader(body),
)
if err != nil {
return keyedResult{err: err}
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+actor.Token)
req.Header.Set("Idempotency-Key", key)
resp, err := httpClient.Do(req)
if err != nil {
return keyedResult{err: err}
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
return keyedResult{
status: resp.StatusCode,
instance: resp.Header.Get("X-Instance-Id"),
body: data,
err: err,
}
}
func TestConcurrentIdempotencyAcrossReplicas(t *testing.T) {
alice := createUser(t)
bob := createUser(t)
chat := createChat(t, alice, alice.ID, bob.ID)
instances := map[string]struct{}{}
for round := 0; round < concurrentRounds; round++ {
key := uuid.NewString()
text := "concurrent " + key
results := make([]keyedResult, concurrentRequests)
start := make(chan struct{})
var wg sync.WaitGroup
for i := range results {
wg.Add(1)
go func(i int) {
defer wg.Done()
<-start
results[i] = postWithKey(alice, chat.ID, key, text)
}(i)
}
close(start)
wg.Wait()
createdIDs := map[string]struct{}{}
succeeded := 0
for i, r := range results {
if r.err != nil {
t.Fatalf("round %d, request %d: %v", round, i, r.err)
}
if r.instance != "" {
instances[r.instance] = struct{}{}
}
switch r.status {
case http.StatusOK, http.StatusCreated:
succeeded++
var m struct {
ID string `json:"id"`
}
if err := json.Unmarshal(r.body, &m); err != nil || m.ID == "" {
t.Fatalf("round %d: bad success body %q: %v", round, r.body, err)
}
createdIDs[m.ID] = struct{}{}
case http.StatusConflict:
default:
t.Errorf("round %d, request %d: unexpected status %d, body: %s",
round, i, r.status, r.body)
}
}
if succeeded == 0 {
t.Fatalf("round %d: no request succeeded", round)
}
if len(createdIDs) != 1 {
t.Fatalf("round %d: responses returned %d different message ids, want 1: %v",
round, len(createdIDs), createdIDs)
}
if got := countMessagesWithText(t, bob, chat.ID, text); got != 1 {
t.Fatalf("round %d: %d messages with text %q in history, want exactly 1",
round, got, text)
}
}
if len(instances) < 2 {
t.Fatalf("requests were served by %d replica(s) %v, need at least 2",
len(instances), instances)
}
t.Logf("served by replicas: %v", instances)
}
func countMessagesWithText(t *testing.T, actor testUser, chatID uuid.UUID, text string) int {
t.Helper()
count := 0
path := "/api/v1/chats/" + chatID.String() + "/messages?limit=100"
for page := 0; page < 100; page++ {
resp := doRequest(t, http.MethodGet, path, actor.Token, nil)
requireStatus(t, resp, http.StatusOK)
var body struct {
Items []struct {
Text string `json:"text"`
} `json:"items"`
NextCursor *string `json:"next_cursor"`
}
mustDecode(t, resp, &body)
for _, m := range body.Items {
if m.Text == text {
count++
}
}
if body.NextCursor == nil {
return count
}
path = "/api/v1/chats/" + chatID.String() +
"/messages?limit=100&cursor=" + url.QueryEscape(*body.NextCursor)
}
t.Fatalf("history pagination exceeded safety bound")
return 0
}
+226
View File
@@ -0,0 +1,226 @@
//go:build contract
package studenttests_test
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"image"
"image/color"
"image/jpeg"
"image/png"
"io"
"net/http"
"testing"
"time"
"golang.org/x/image/webp"
"gavrilenko-sxdees/lab7/internal/dto"
)
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 := processedVariant(t, source.Bytes(), "image/png", "thumbnail")
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 TestVariantsEXIF(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:]...)
for _, variant := range []string{"thumbnail", "optimized"} {
t.Run(variant, func(t *testing.T) {
result, width, height := processedVariant(t, data, "image/jpeg", variant)
if width != 20 || height != 40 {
t.Fatalf("orientation ignored: %dx%d", width, height)
}
decoded, _, err := image.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")) || bytes.Contains(result, []byte("EXIF")) {
t.Fatal("EXIF retained")
}
})
}
}
func processedVariant(t *testing.T, source []byte, contentType, variant 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 string(v.Name) != variant {
continue
}
resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.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)
}
sum := sha256.Sum256(data)
if len(data) != v.SizeBytes || hex.EncodeToString(sum[:]) != v.Sha256 ||
resp.Header.Get("Content-Type") != string(v.ContentType) {
t.Fatal("variant content disagrees with metadata")
}
return data, v.Width, v.Height
}
t.Fatalf("ready attachment has no %s", variant)
return nil, 0, 0
}
func TestCrop(t *testing.T) {
for _, tc := range []struct {
name string
width, height int
}{
{"landscape", 384, 128},
{"portrait", 128, 384},
{"small", 24, 8},
} {
t.Run(tc.name, func(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, tc.width, tc.height))
// Only the central square is green; a stretched full image retains red edges.
side := min(tc.width, tc.height)
left, top := (tc.width-side)/2, (tc.height-side)/2
for y := 0; y < tc.height; y++ {
for x := 0; x < tc.width; x++ {
c := color.NRGBA{R: 255, A: 255}
if x >= left && x < left+side && y >= top && y < top+side {
c = color.NRGBA{G: 255, A: 255}
}
src.SetNRGBA(x, y, c)
}
}
var source bytes.Buffer
if err := png.Encode(&source, src); err != nil {
t.Fatal(err)
}
data, width, height := processedVariant(t, source.Bytes(), "image/png", "crop")
decoded, err := jpeg.Decode(bytes.NewReader(data))
if err != nil {
t.Fatal(err)
}
if width != 128 || height != 128 || decoded.Bounds() != image.Rect(0, 0, 128, 128) {
t.Fatalf("expected crop 128x128, metadata=%dx%d, JPEG=%v", width, height, decoded.Bounds())
}
for _, point := range []image.Point{{8, 8}, {64, 64}, {119, 119}} {
r, g, b, _ := decoded.At(point.X, point.Y).RGBA()
if g < 50000 || r > 15000 || b > 15000 {
t.Fatalf("crop is not centered at %v", point)
}
}
})
}
}
func TestOptimized(t *testing.T) {
for _, tc := range []struct {
name string
width, height, wantWidth, wantHeight int
}{
{"landscape", 1600, 1000, 1280, 800},
{"portrait", 1000, 1600, 800, 1280},
{"small", 12, 7, 12, 7},
} {
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 := processedVariant(t, source.Bytes(), "image/png", "optimized")
decoded, err := webp.Decode(bytes.NewReader(data))
if err != nil {
t.Fatal(err)
}
if width != tc.wantWidth || height != tc.wantHeight ||
decoded.Bounds().Dx() != width || decoded.Bounds().Dy() != height {
t.Fatalf("unexpected optimized dimensions: metadata=%dx%d, WebP=%v", width, height, decoded.Bounds())
}
_, _, _, alpha := decoded.At(0, 0).RGBA()
if alpha != 0 {
t.Fatal("optimized image lost transparency")
}
})
}
}
+150
View File
@@ -0,0 +1,150 @@
//go:build load && action
package studenttests_test
import (
"flag"
"io"
"net/http"
"os"
"os/exec"
"strings"
"sync"
"testing"
"time"
)
var (
actionScript = flag.String("action", "", "script to run during the load (e.g. scripts/stop-one.sh)")
actionAt = flag.Duration("action-at", 10*time.Second, "when to run the action, from test start")
replica = flag.Int("replica", 1, "which api replica to stop (1-based)")
)
func resolveReplica(t *testing.T, n int) string {
t.Helper()
out, err := exec.Command("docker", "compose", "ps", "-q", "api").Output()
if err != nil {
t.Fatalf("docker compose ps: %v", err)
}
ids := strings.Fields(string(out))
if n < 1 || n > len(ids) {
t.Fatalf("replica %d requested, but %d api containers found", n, len(ids))
}
return ids[n-1]
}
func actionCommand(path string) *exec.Cmd {
if strings.HasSuffix(path, ".sh") {
return exec.Command("sh", path)
}
return exec.Command(path)
}
func TestLoadWithAction(t *testing.T) {
if *actionScript == "" {
t.Skip("-action is not set")
}
if *actionAt+10*time.Second > *duration {
t.Fatalf("-duration (%s) must exceed -action-at (%s) by at least 10s", *duration, *actionAt)
}
user1 := createUser(t)
user2 := createUser(t)
chat := createChat(t, user1, user1.ID, user2.ID)
type sample struct {
at time.Duration
ok bool
}
var (
mu sync.Mutex
samples []sample
wg sync.WaitGroup
)
targetID := resolveReplica(t, *replica)
start := time.Now()
deadline := start.Add(*duration)
interval := time.Second / time.Duration(*rate)
for w := 0; w < *workers; w++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
actor := user1
if id%2 == 1 {
actor = user2
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
<-ticker.C
if time.Now().After(deadline) {
return
}
resp, err := sendLoadMessage(actor, chat.ID, "load-msg")
ok := err == nil && resp.StatusCode == http.StatusCreated
if err == nil {
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
mu.Lock()
samples = append(samples, sample{time.Since(start), ok})
mu.Unlock()
}
}(w)
}
var actionStart, actionEnd time.Duration
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(*actionAt)
actionStart = time.Since(start)
cmd := actionCommand(*actionScript)
cmd.Env = append(os.Environ(), "TARGET_INSTANCE_ID="+targetID)
out, err := cmd.CombinedOutput()
actionEnd = time.Since(start)
if err != nil {
t.Errorf("action failed: %v\n%s", err, out)
}
}()
wg.Wait()
elapsed := time.Since(start)
seconds := int(elapsed.Seconds()) + 1
okBySec := make([]int, seconds)
errBySec := make([]int, seconds)
var okTotal, errTotal int
var lastErr time.Duration
for _, s := range samples {
sec := int(s.at.Seconds())
if s.ok {
okBySec[sec]++
okTotal++
} else {
errBySec[sec]++
errTotal++
if s.at > lastErr {
lastErr = s.at
}
}
}
for i := 0; i < seconds; i++ {
t.Logf("t=%2ds ok=%4d err=%3d", i, okBySec[i], errBySec[i])
}
t.Logf("action: started at %.2fs, finished at %.2fs", actionStart.Seconds(), actionEnd.Seconds())
t.Logf("total ok=%d errors=%d, successful RPS=%.2f", okTotal, errTotal, float64(okTotal)/elapsed.Seconds())
if errTotal == 0 || lastErr < actionStart {
t.Logf("recovery time: 0s (no errors after action start)")
} else {
t.Logf("recovery time: %.2fs (last error at %.2fs)", (lastErr - actionStart).Seconds(), lastErr.Seconds())
}
}
+162
View File
@@ -0,0 +1,162 @@
//go:build load
package studenttests_test
import (
"flag"
"fmt"
"io"
"net/http"
"os"
"sort"
"sync"
"sync/atomic"
"testing"
"time"
)
var (
workers = flag.Int("workers", 20, "number of concurrent workers")
duration = flag.Duration("duration", 5*time.Second, "test duration")
rate = flag.Int("rate", 20, "maximum requests per second per worker")
csvPath = flag.String("csv", "", "append result row to this CSV file")
label = flag.String("label", "", "configuration label for CSV row")
)
func TestLoad(t *testing.T) {
var (
statuses = make(map[int]int64)
requestErrors int64
latencies []time.Duration
statusMu sync.Mutex
latencyMu sync.Mutex
wg sync.WaitGroup
)
user1 := createUser(t)
user2 := createUser(t)
chat := createChat(t, user1, user1.ID, user2.ID)
start := time.Now()
deadline := start.Add(*duration)
interval := time.Second / time.Duration(*rate)
for worker := 0; worker < *workers; worker++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
actor := user1
if workerID%2 == 1 {
actor = user2
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for time.Now().Before(deadline) {
<-ticker.C
if time.Now().After(deadline) {
return
}
requestStart := time.Now()
resp, err := sendLoadMessage(
actor,
chat.ID,
"load-msg",
)
latency := time.Since(requestStart)
if err != nil {
if atomic.AddInt64(&requestErrors, 1) == 1 {
t.Logf("first transport error: %v", err)
}
continue
}
statusMu.Lock()
statuses[resp.StatusCode]++
statusMu.Unlock()
if resp.StatusCode == http.StatusCreated {
latencyMu.Lock()
latencies = append(latencies, latency)
latencyMu.Unlock()
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
}(worker)
}
wg.Wait()
elapsed := time.Since(start)
var total int64
for _, count := range statuses {
total += count
}
total += requestErrors
t.Logf("duration: %.3fs", elapsed.Seconds())
t.Logf("workers: %d", *workers)
t.Logf("rate per worker: %d req/s", *rate)
t.Logf("target rate: %d req/s", *workers**rate)
t.Logf("total requests: %d", total)
for status, count := range statuses {
t.Logf("HTTP %d: %d", status, count)
}
t.Logf("request errors: %d", requestErrors)
successful := statuses[http.StatusCreated]
t.Logf("successful RPS: %.2f",
float64(successful)/elapsed.Seconds(),
)
if len(latencies) > 0 {
sort.Slice(latencies, func(i, j int) bool {
return latencies[i] < latencies[j]
})
t.Logf("successful latency p50: %s", percentile(latencies, 0.50))
t.Logf("successful latency p95: %s", percentile(latencies, 0.95))
t.Logf("successful latency p99: %s", percentile(latencies, 0.99))
}
if *csvPath != "" {
var p50, p95, p99 time.Duration
if len(latencies) > 0 {
p50 = percentile(latencies, 0.50)
p95 = percentile(latencies, 0.95)
p99 = percentile(latencies, 0.99)
}
f, err := os.OpenFile(*csvPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
t.Fatalf("open csv: %v", err)
}
defer f.Close()
fmt.Fprintf(f, "%s,%d,%d,%d,%d,%d,%d,%.2f,%.1f,%.1f,%.1f\n",
*label, *workers, *rate, *workers**rate,
successful, total-successful-requestErrors, requestErrors,
float64(successful)/elapsed.Seconds(),
float64(p50.Microseconds())/1000,
float64(p95.Microseconds())/1000,
float64(p99.Microseconds())/1000)
}
}
func percentile(values []time.Duration, p float64) time.Duration {
index := int(float64(len(values)-1) * p)
return values[index]
}
+16
View File
@@ -0,0 +1,16 @@
package studenttests_test
import (
"crypto/tls"
"net/http"
"testing"
"time"
)
func TestMTLSLBDeniesUntrustedCA(t *testing.T) {
client := &http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: false}}}
_, err := client.Get("https://127.0.0.1:8443/health/ready")
if err == nil {
t.Fatal("expected verify error with empty trust store")
}
}
+198
View File
@@ -0,0 +1,198 @@
#!/usr/bin/env python3
"""Grade-4 observability checks for Gavrilenko lab6 (outbox + RabbitMQ)."""
import datetime
import json
import os
import subprocess
import sys
import time
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check # noqa: E402
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8087")
PROM = os.environ.get("PROMETHEUS_URL", "http://127.0.0.1:9097")
TEMPO = os.environ.get("TEMPO_URL", "http://127.0.0.1:3207")
LOKI = os.environ.get("LOKI_URL", "http://127.0.0.1:3107")
COMPOSE = os.environ.get("COMPOSE", "docker compose -p gavrilenko-lab6 --env-file .env")
def get(url):
with urllib.request.urlopen(
urllib.request.Request(url, headers={"Accept": "application/json"}),
timeout=10,
) as response:
return json.load(response)
def dc(*args):
return subprocess.check_output(
[*COMPOSE.split(), *args],
cwd=ROOT,
text=True,
stderr=subprocess.DEVNULL,
).strip()
def query(expr):
return get(PROM + "/api/v1/query?" + urllib.parse.urlencode({"query": expr}))[
"data"
]["result"]
def alerts():
payload = get(PROM + "/api/v1/alerts")
return [
{
"name": item["labels"]["alertname"],
"state": item["state"],
}
for item in payload["data"]["alerts"]
]
def wait_for(fn, timeout=90):
start = time.monotonic()
while time.monotonic() - start < timeout:
try:
value = fn()
if value:
return value, round(time.monotonic() - start, 3)
except (OSError, KeyError, ValueError, urllib.error.URLError):
pass
time.sleep(1)
raise AssertionError("timeout waiting telemetry")
def norm_spans(trace):
spans = []
for batch in trace.get("batches", trace.get("resourceSpans", [])):
attrs = {
x["key"]: x["value"].get("stringValue")
for x in batch.get("resource", {}).get("attributes", [])
}
for scope in batch.get("scopeSpans", batch.get("instrumentationLibrarySpans", [])):
for span in scope.get("spans", []):
spans.append(
{
"service": attrs.get("service.name"),
"name": span["name"],
"id": span.get("spanId"),
"parent_id": span.get("parentSpanId"),
}
)
return spans
def trace_chain(c, actor, chat):
response = c.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments?filename=trace.png",
202,
actor=actor,
raw=(ROOT / "tests/fixtures/sample.png").read_bytes(),
headers={"Content-Type": "image/png"},
schema="Attachment",
)
trace_id = response["headers"].get("X-Trace-Id")
check(trace_id and len(trace_id) == 32, "missing API root trace id")
att = c.wait_ready(actor, response["json"])
def complete_trace():
trace = get(TEMPO + "/api/traces/" + trace_id)
serialized = json.dumps(trace)
check(actor["token"] not in serialized, "token leaked to traces")
spans = norm_spans(trace)
names = {s["name"] for s in spans}
needed = {"queue.publish", "queue.consume", "image.transform", "s3.request"}
if not needed.issubset(names):
return None
return spans
spans, delay = wait_for(complete_trace)
services = {s["service"] for s in spans}
check({"messenger-api", "messenger-worker"}.issubset(services), "missing service in trace")
for span in spans:
if span["name"] == "queue.consume":
parents = {s["id"] for s in spans if s["name"] == "queue.publish"}
check(span["parent_id"] in parents, "consumer not linked to producer span")
params = {
"query": '{service_name=~"messenger-(api|worker)"} | trace_id="' + trace_id + '"',
"limit": "100",
"start": str(int((time.time() - 180) * 1e9)),
"end": str(int(time.time() * 1e9)),
}
logs = wait_for(
lambda: get(LOKI + "/loki/api/v1/query_range?" + urllib.parse.urlencode(params))[
"data"
]["result"],
timeout=60,
)[0]
log_services = {entry["stream"].get("service_name") for entry in logs}
check({"messenger-api", "messenger-worker"}.issubset(log_services), "correlated logs missing")
result = {
"trace_id": trace_id,
"attachment_id": att["id"],
"ingest_wait_seconds": delay,
"spans": spans,
"log_services": sorted(log_services),
}
(ROOT / "evidence" / "trace-chain.json").write_text(json.dumps(result, indent=2) + "\n")
print("PASS: API → outbox → RabbitMQ → worker trace chain", flush=True)
return result
def worker_incident(c, actor, chat):
dc("stop", "worker")
fired = False
try:
for _ in range(12):
att, _ = c.attachment(actor, chat)
c.wait_ready(actor, att, wait_seconds=1)
time.sleep(8)
for item in alerts():
if item["name"] == "QueueLag" and item["state"] == "firing":
fired = True
check(fired, "QueueLag did not fire with worker stopped")
except Failure:
pass
finally:
dc("up", "-d", "--no-deps", "worker")
time.sleep(15)
resolved = not any(
a["name"] == "QueueLag" and a["state"] == "firing" for a in alerts()
)
check(resolved, "QueueLag did not resolve after worker restart")
print("PASS: worker stop/start alert firing and resolve", flush=True)
def main():
Path(ROOT / "evidence").mkdir(exist_ok=True)
c = Client(BASE)
users = c.register_users(2)
actor = users[0]
chat = c.create_chat(actor, users[1])
trace_chain(c, actor, chat)
worker_incident(c, actor, chat)
summary = {
"finished_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"slo": {
"api": "99% non-5xx business requests (10m)",
"ready": "95% attachments ready within 5s",
},
"alerts": alerts(),
}
(ROOT / "evidence" / "observability-summary.json").write_text(
json.dumps(summary, indent=2) + "\n"
)
print("PASS: observability grade-4 bundle", flush=True)
if __name__ == "__main__":
main()
+25
View File
@@ -0,0 +1,25 @@
package studenttests_test
import (
"context"
"os"
"testing"
"time"
"gavrilenko-sxdees/lab7/internal/openbao"
)
func TestOpenBaoAppRole(t *testing.T) {
if os.Getenv("BAO_ADDR") == "" {
t.Setenv("BAO_ADDR", "https://127.0.0.1:8217")
}
os.Setenv("BAO_TLS_SERVER_NAME", "openbao.messenger.lab")
os.Setenv("BAO_CACERT", secretPath("ca.crt"))
os.Setenv("BAO_ROLE_ID_FILE", secretPath("bao_api_role_id.txt"))
os.Setenv("BAO_SECRET_ID_FILE", secretPath("bao_api_secret_id.txt"))
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := openbao.VerifyAppRole(ctx, "api"); err != nil {
t.Fatalf("openbao approle: %v", err)
}
}
+302
View File
@@ -0,0 +1,302 @@
//go:build pipeline
package studenttests_test
import (
"bytes"
"encoding/base64"
"reflect"
"testing"
"time"
"github.com/google/uuid"
"golang.org/x/image/webp"
)
func pipelineS3Gate(t *testing.T, suffix string) (string, func(string) string) {
t.Helper()
proxy := "pipeline-gate-" + uuid.NewString()
workerContainer := workerCommand(t, "compose", "ps", "-a", "-q", "worker")
network := workerCommand(t, "inspect", "--format",
"{{range $name, $value := .NetworkSettings.Networks}}{{$name}}{{end}}", workerContainer)
t.Cleanup(func() { workerCommand(t, "rm", "-f", proxy) })
const proxyScript = `
import base64
import http.client
import http.server
import threading
import sys
waiting = threading.Event()
release = threading.Event()
written = threading.Event()
held_body = b''
class Proxy(http.server.BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_GET(self):
if self.path == '/_body':
self.send_response(200)
self.end_headers()
self.wfile.write(base64.b64encode(held_body))
return
if self.path == '/_state':
data = f'{int(waiting.is_set())}:{int(written.is_set())}'.encode()
self.send_response(200)
self.end_headers()
self.wfile.write(data)
return
if self.path == '/_release':
release.set()
self.send_response(200)
self.end_headers()
return
self.forward()
def do_PUT(self):
self.forward()
def forward(self):
global held_body
body = self.rfile.read(int(self.headers.get('Content-Length', 0)))
gated = self.command == 'PUT' and self.path.split('?')[0].endswith(sys.argv[1])
if gated:
held_body = body
waiting.set()
if not release.wait(90):
self.send_error(504)
return
conn = http.client.HTTPConnection('s3', 9000, timeout=20)
try:
conn.request(self.command, self.path, body, dict(self.headers))
response = conn.getresponse()
data = response.read()
if gated and response.status == 200:
written.set()
self.send_response(response.status)
for name, value in response.getheaders():
if name.lower() not in ('connection', 'transfer-encoding', 'content-length'):
self.send_header(name, value)
self.send_header('Content-Length', str(len(data)))
self.end_headers()
self.wfile.write(data)
finally:
conn.close()
http.server.ThreadingHTTPServer(('0.0.0.0', 9000), Proxy).serve_forever()
`
workerCommand(t, "run", "-d", "--name", proxy, "--network", network,
"python:3.13.9-alpine3.22", "python", "-u", "-c", proxyScript, suffix)
control := func(path string) string {
t.Helper()
return workerCommand(t, "exec", proxy, "python", "-c",
"import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:9000/"+path+"').read().decode())")
}
return proxy, control
}
func TestPipelineStaleProcessing(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)
id := att.ID.String()
where := "attachment_id='" + id + "'"
jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'")
// Hold the last v1 PUT while v2 completes, without a DB row lock.
proxy, control := pipelineS3Gate(t, "/v1/optimized")
oldWorker := "pipeline-v1-" + uuid.NewString()
t.Cleanup(func() { workerCommand(t, "rm", "-f", oldWorker) })
workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", oldWorker,
"-e", "WORKER_CONCURRENCY=1", "-e", "JOB_TIMEOUT_SECONDS=120",
"-e", "S3_ENDPOINT=http://"+proxy+":9000", "worker")
workerWait(t, "v1 waiting before optimized PUT", 20*time.Second, func() bool {
return control("_state") == "1:0"
})
if workerSQL(t, "SELECT pipeline_version||':'||status||':'||attempts FROM attachments WHERE id='"+id+"'") != "1:processing:1" {
t.Fatal("v1 was not processing before upgrade")
}
workerCommand(t, "compose", "run", "--rm", "--no-deps", "worker", "-upgrade", id)
compose(t, "start", "worker")
ready := waitAttachment(t, user, att.ID, "ready", 30*time.Second)
if len(ready.Variants) != 3 ||
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:2" {
t.Fatal("v2 did not become ready while v1 was held")
}
content := make(map[string][]byte)
for _, name := range []string{"original", "thumbnail", "crop", "optimized"} {
content[name] = workerContent(t, user, att.ID, name)
}
if !bytes.Equal(content["original"], source) {
t.Fatal("v2 changed original bytes")
}
v1, err := base64.StdEncoding.DecodeString(control("_body"))
if err != nil {
t.Fatal(err)
}
for _, data := range [][]byte{v1, content["optimized"]} {
cfg, err := webp.DecodeConfig(bytes.NewReader(data))
if err != nil || cfg.Width != 320 || cfg.Height != 200 {
t.Fatal("expected valid optimized WebP from both versions")
}
}
if bytes.Equal(v1, content["optimized"]) {
t.Fatal("fixture must produce different v1 and v2 optimized bytes")
}
control("_release")
workerWait(t, "late v1 S3 write", 20*time.Second, func() bool {
return control("_state") == "1:1"
})
workerWait(t, "stale v1 redelivery acknowledged", 15*time.Second, func() bool {
return workerQueue(t) == "0:0"
})
after := waitAttachment(t, user, att.ID, "ready", 5*time.Second)
if !reflect.DeepEqual(ready, after) ||
workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID ||
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:2" ||
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=1") != "0" ||
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=2") != "3" {
t.Fatal("late v1 processing changed current metadata")
}
for name, before := range content {
if !bytes.Equal(before, workerContent(t, user, att.ID, name)) {
t.Fatalf("late v1 processing overwrote %s", name)
}
}
t.Logf("PASS attachment=%s: held v1 PUT; v2 ready; late v1 wrote S3 but could not replace v2; stale redelivery acknowledged", id)
}
func TestPipelineReorderAndDuplicate(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")
}
// Keep v1 durable in outbox, but delay its publication until v2 is ready.
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+"'")
workerSQL(t, "UPDATE outbox SET available_at=now()+interval '1 hour' WHERE "+where)
if workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND published_at IS NULL") != "1" {
t.Fatal("v1 was published before the reorder injection")
}
workerCommand(t, "compose", "run", "--rm", "--no-deps", "worker", "-upgrade", id)
compose(t, "start", "rabbitmq", "worker")
ready := waitAttachment(t, user, att.ID, "ready", 40*time.Second)
workerWait(t, "v2 acknowledgement", 15*time.Second, func() bool {
return workerQueue(t) == "0:0"
})
if len(ready.Variants) != 3 ||
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:1" ||
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND pipeline_version=1 AND published_at IS NULL") != "1" {
t.Fatal("v2 did not finish before v1 publication")
}
content := make(map[string][]byte)
for _, name := range []string{"original", "thumbnail", "crop", "optimized"} {
content[name] = workerContent(t, user, att.ID, name)
}
if !bytes.Equal(content["original"], source) {
t.Fatal("v2 changed original bytes")
}
for _, injection := range []struct {
name, query, version string
}{
{"reordered v1", "UPDATE outbox SET available_at=now() WHERE " + where + " AND pipeline_version=1", "1"},
{"duplicate v2", "UPDATE outbox SET published_at=NULL WHERE " + where + " AND pipeline_version=2", "2"},
} {
compose(t, "stop", "worker")
workerSQL(t, injection.query)
workerWait(t, injection.name+" published", 15*time.Second, func() bool {
return workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+
" AND pipeline_version="+injection.version+" AND published_at IS NOT NULL") == "1" &&
workerQueue(t) == "1:0"
})
compose(t, "start", "worker")
workerWait(t, injection.name+" acknowledged", 15*time.Second, func() bool {
return workerQueue(t) == "0:0"
})
after := waitAttachment(t, user, att.ID, "ready", 5*time.Second)
if !reflect.DeepEqual(ready, after) ||
workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID ||
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:1" ||
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=1") != "0" ||
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=2") != "3" ||
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where) != "2" {
t.Fatalf("%s changed metadata or created extra work", injection.name)
}
for name, before := range content {
if !bytes.Equal(before, workerContent(t, user, att.ID, name)) {
t.Fatalf("%s changed %s bytes", injection.name, name)
}
}
}
t.Logf("PASS attachment=%s: v2 completed before v1 delivery; stale v1 and duplicate v2 acknowledged without changes", id)
}
func TestPipelineCrashBeforeWrite(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)
id := att.ID.String()
where := "attachment_id='" + id + "'"
jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'")
workerCommand(t, "compose", "run", "--rm", "--no-deps", "worker", "-upgrade", id)
// Original is the first result PUT. Neither it nor any variant reaches S3.
proxy, control := pipelineS3Gate(t, "/attachments/"+id)
testWorker := "pipeline-crash-" + uuid.NewString()
t.Cleanup(func() { workerCommand(t, "rm", "-f", testWorker) })
workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker,
"-e", "WORKER_CONCURRENCY=1", "-e", "JOB_TIMEOUT_SECONDS=15",
"-e", "S3_ENDPOINT=http://"+proxy+":9000", "worker")
workerWait(t, "v2 held before first result PUT", 10*time.Second, func() bool {
return control("_state") == "1:0"
})
if workerSQL(t, "SELECT pipeline_version||':'||status||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:processing:1" ||
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "0" {
t.Fatal("expected v2 processing without a committed result")
}
workerCommand(t, "kill", "--signal", "SIGKILL", testWorker)
// Kill the held request too: it must never be forwarded after the crash.
workerCommand(t, "kill", "--signal", "SIGKILL", proxy)
workerWait(t, "crashed v2 job returned to broker", 10*time.Second, func() bool {
return workerQueue(t) == "1:0"
})
compose(t, "start", "worker")
// Recovery must use the natural lease expiry; no status/lease SQL injection.
ready := waitAttachment(t, user, att.ID, "ready", 40*time.Second)
workerWait(t, "recovered v2 acknowledgement", 15*time.Second, func() bool {
return workerQueue(t) == "0:0"
})
if len(ready.Variants) != 3 ||
!bytes.Equal(workerContent(t, user, att.ID, "original"), source) ||
workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID ||
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:2" ||
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=2") != "3" ||
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "3" ||
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND pipeline_version=2 AND attempt=2 AND published_at IS NOT NULL") != "1" {
t.Fatal("crash recovery lost the accepted job or changed its identity or result")
}
for _, name := range []string{"thumbnail", "crop", "optimized"} {
if len(workerContent(t, user, att.ID, name)) == 0 {
t.Fatalf("recovered v2 has empty %s", name)
}
}
t.Logf("PASS attachment=%s: SIGKILL before first result PUT; natural lease recovery; same job ready on v2 attempt2", id)
}
+100
View File
@@ -0,0 +1,100 @@
//go:build race
package studenttests_test
import (
"net/http"
"sync"
"testing"
"gavrilenko-sxdees/lab7/internal/dto"
)
func TestConcurrentMessages(t *testing.T) {
const clients = 10
const messagesPerClient = 10
const total = clients * messagesPerClient
user1 := createUser(t)
user2 := createUser(t)
chat := createChat(t, user1, user1.ID, user2.ID)
var wg sync.WaitGroup
var mu sync.Mutex
sentIDs := make(map[string]bool, total)
start := make(chan struct{})
for worker := 0; worker < clients; worker++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
actor := user1
if workerID%2 == 1 {
actor = user2
}
<-start
for i := 0; i < messagesPerClient; i++ {
resp := sendMessage(t, actor, chat.ID, "race-msg")
if resp.StatusCode != http.StatusCreated {
t.Errorf("worker %d msg %d: expected 201, got %d", workerID, i, resp.StatusCode)
resp.Body.Close()
continue
}
var m dto.MessageResponse
mustDecode(t, resp, &m)
mu.Lock()
sentIDs[m.ID.String()] = true
mu.Unlock()
}
}(worker)
}
close(start)
wg.Wait()
if t.Failed() {
t.Fatal("one or more send requests failed, see errors above")
}
if len(sentIDs) != total {
t.Fatalf("expected %d successful sends, got %d unique ids", total, len(sentIDs))
}
seen := make(map[string]bool, total)
path := "/api/v1/chats/" + chat.ID.String() + "/messages?limit=100"
resp := doRequest(t, http.MethodGet, path, user1.Token, nil)
requireStatus(t, resp, http.StatusOK)
var page dto.MessagePageResponse
mustDecode(t, resp, &page)
if page.NextCursor != nil {
t.Fatalf("expected next_cursor to be nil, history may contain more than %d messages", total)
}
for _, msg := range page.Items {
id := msg.ID.String()
if seen[id] {
t.Fatalf("duplicate message id in history: %s", id)
}
if !sentIDs[id] {
t.Fatalf("message %s in history was never sent by this test", id)
}
seen[id] = true
}
if len(seen) != total {
t.Fatalf("expected exactly %d unique messages in history, got %d", total, len(seen))
}
t.Logf("PASS: %d concurrent clients sent %d messages, exactly %d unique messages persisted",
clients, total, len(seen))
}
+161
View File
@@ -0,0 +1,161 @@
//go:build reconcile
package studenttests_test
import (
"bytes"
"context"
"encoding/json"
"net/http"
"os"
"os/exec"
"slices"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gavrilenko-sxdees/lab7/internal/reconcile"
)
func reconcileDB(t *testing.T) *pgx.Conn {
t.Helper()
secret, err := os.ReadFile("../secrets/test_database_url.txt")
if err != nil {
t.Fatalf("read test database URL: %v", err)
}
conn, err := pgx.Connect(context.Background(), strings.TrimSpace(string(secret)))
if err != nil {
t.Fatalf("connect to test database: %v", err)
}
t.Cleanup(func() { conn.Close(context.Background()) })
return conn
}
func reconcileSQL(t *testing.T, conn *pgx.Conn, query string, args ...any) {
t.Helper()
if _, err := conn.Exec(context.Background(), query, args...); err != nil {
t.Fatalf("prepare/check reconcile fixture: %v", err)
}
}
func runReconcile(t *testing.T, dryRun bool, grace string) reconcile.Report {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
dry := "false"
if dryRun {
dry = "true"
}
cmd := exec.CommandContext(ctx, "docker", "compose", "--env-file", ".env", "run", "--rm", "--no-deps", "reconcile", "-json", "-dry-run="+dry, "-grace="+grace)
cmd.Dir = ".."
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, err := cmd.Output()
if err != nil {
t.Fatalf("run reconciler: %v\n%s", err, stderr.String())
}
var report reconcile.Report
if err := json.Unmarshal(output, &report); err != nil {
t.Fatalf("decode reconcile report: %v\n%s", err, output)
}
t.Logf("dry_run=%t objects=%d rows=%d list_pages=%d duration_ms=%d orphan=%d missing=%d skipped_fresh=%d skipped_inactive=%d deleted_objects=%d marked_failed=%d errors=%v", report.DryRun, report.ScannedObjects, report.ScannedRows, report.ListPages, report.DurationMS, len(report.OrphanObjects), len(report.MissingAttachments), report.SkippedFresh, report.SkippedInactive, report.DeletedObjects, report.MarkedFailed, report.Errors)
if len(report.Errors) != 0 {
t.Fatal("reconciler reported errors")
}
return report
}
func TestReconcileRepair(t *testing.T) {
conn := reconcileDB(t)
user := createUser(t)
chat := createChat(t, user, user.ID)
att := uploadPNG(t, user, chat.ID)
var originalKey string
if err := conn.QueryRow(context.Background(), "SELECT s3_key FROM attachments WHERE id=$1", att.ID).Scan(&originalKey); err != nil {
t.Fatal(err)
}
// Simulate lost metadata for the original object and metadata pointing at a missing object.
reconcileSQL(t, conn, "UPDATE attachments SET s3_key=$2 WHERE id=$1", att.ID, "chats/reconcile-missing/"+uuid.NewString())
// Only this experiment uses a shortened grace period, to avoid waiting an hour.
time.Sleep(1100 * time.Millisecond)
dry := runReconcile(t, true, "1s")
if !slices.Contains(dry.OrphanObjects, originalKey) || !slices.Contains(dry.MissingAttachments, att.ID) {
t.Fatal("dry-run did not detect both injected inconsistencies")
}
if dry.DeletedObjects != 0 || dry.MarkedFailed != 0 {
t.Fatal("dry-run changed data")
}
var status, code string
if err := conn.QueryRow(context.Background(), "SELECT status::text FROM attachments WHERE id=$1", att.ID).Scan(&status); err != nil {
t.Fatal(err)
}
if status != "ready" {
t.Fatalf("dry-run changed status: %s", status)
}
repair := runReconcile(t, false, "1s")
if repair.DeletedObjects < 1 || repair.MarkedFailed < 1 {
t.Fatal("repair did not apply fixes")
}
if err := conn.QueryRow(context.Background(), "SELECT status::text, error_code FROM attachments WHERE id=$1", att.ID).Scan(&status, &code); err != nil {
t.Fatal(err)
}
if status != "failed" || code != "object_missing" {
t.Fatalf("unexpected repaired state: %s %s", status, code)
}
again := runReconcile(t, false, "1s")
if slices.Contains(again.OrphanObjects, originalKey) || slices.Contains(again.MissingAttachments, att.ID) {
t.Fatal("fixture still requires repair on repeat")
}
if again.DeletedObjects != 0 || again.MarkedFailed != 0 {
t.Fatal("repeat repair changed data; run on an idle test stand")
}
t.Log("PASS: dry-run preserved data; orphan deleted; missing marked failed; repeat made no changes")
}
func TestReconcileSafety(t *testing.T) {
conn := reconcileDB(t)
user := createUser(t)
chat := createChat(t, user, user.ID)
fresh := uploadPNG(t, user, chat.ID)
used := uploadPNG(t, user, chat.ID)
resp := postMessage(t, user, chat.ID, "", []uuid.UUID{used.ID})
requireStatus(t, resp, http.StatusCreated)
resp.Body.Close()
// Queued attachments must be preserved regardless of age or message references.
reconcileSQL(t, conn, "UPDATE attachments SET status='queued' WHERE id=$1", fresh.ID)
reconcileSQL(t, conn, "UPDATE attachments SET status='queued', created_at=now()-interval '2 hours' WHERE id=$1", used.ID)
t.Cleanup(func() {
if _, err := conn.Exec(context.Background(), "UPDATE attachments SET status='ready' WHERE id=ANY($1::uuid[])", []uuid.UUID{fresh.ID, used.ID}); err != nil {
t.Errorf("restore fixture status: %v", err)
}
})
for _, dryRun := range []bool{true, false} {
report := runReconcile(t, dryRun, "1h")
if report.SkippedInactive < 2 {
t.Fatal("queued attachment protection was not exercised")
}
for _, att := range []uuid.UUID{fresh.ID, used.ID} {
var status string
if err := conn.QueryRow(context.Background(), "SELECT status::text FROM attachments WHERE id=$1", att).Scan(&status); err != nil {
t.Fatal(err)
}
if status != "queued" {
t.Fatalf("protected fixture changed status: %s", status)
}
resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.String()+"/content", user.Token, nil)
requireStatus(t, resp, http.StatusConflict)
resp.Body.Close()
}
}
t.Log("PASS: queued uploads preserved regardless of age or references; content remains unavailable")
}
func TestReconcileCost(t *testing.T) {
for i := 1; i <= 3; i++ {
t.Logf("scan %d/3", i)
runReconcile(t, true, "1h")
}
}
+77
View File
@@ -0,0 +1,77 @@
//go:build race
package studenttests_test
import (
"bytes"
"encoding/json"
"net/http"
"strings"
"sync"
"testing"
"github.com/google/uuid"
)
func TestConcurrentRegistration(t *testing.T) {
const workers = 20
username := "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12]
body, err := json.Marshal(map[string]string{
"username": username,
"display_name": "Racer",
"password": testPassword,
})
if err != nil {
t.Fatalf("marshal body: %v", err)
}
start := make(chan struct{})
statuses := make(chan int, workers)
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-start
req, err := http.NewRequest(http.MethodPost, *baseURL+"/api/v1/users", bytes.NewReader(body))
if err != nil {
t.Errorf("build request: %v", err)
return
}
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
t.Errorf("request failed: %v", err)
return
}
defer resp.Body.Close()
statuses <- resp.StatusCode
}()
}
close(start)
wg.Wait()
close(statuses)
created, conflict := 0, 0
for s := range statuses {
switch s {
case http.StatusCreated:
created++
case http.StatusConflict:
conflict++
default:
t.Errorf("unexpected status %d", s)
}
}
if created != 1 || conflict != workers-1 {
t.Fatalf("expected 1 created and %d conflict, got %d created and %d conflict", workers-1, created, conflict)
}
}
+42
View File
@@ -0,0 +1,42 @@
//go:build failure
package studenttests_test
import (
"net/http"
"os/exec"
"testing"
"time"
)
const shortTTLContainer = "api-short-ttl"
const shortTTLURL = "http://localhost:8081"
func TestSessionExpiry(t *testing.T) {
_ = exec.Command("docker", "rm", "-f", shortTTLContainer).Run()
compose(t, "run", "-d", "--no-deps", "--name", shortTTLContainer,
"-e", "SESSION_TTL_SECONDS=3",
"-p", "127.0.0.1:8081:8080", "api")
t.Cleanup(func() {
_ = exec.Command("docker", "rm", "-f", shortTTLContainer).Run()
})
old := *baseURL
*baseURL = shortTTLURL
t.Cleanup(func() { *baseURL = old })
waitReady(t)
user := createUser(t)
resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
requireStatus(t, resp, http.StatusOK)
resp.Body.Close()
time.Sleep(4 * time.Second)
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
}
+58
View File
@@ -0,0 +1,58 @@
//go:build contract
package studenttests_test
import (
"net/http"
"testing"
)
func basicLogin(t *testing.T, username, password string) *http.Response {
t.Helper()
req, err := http.NewRequest(http.MethodPost, *baseURL+"/api/v1/auth/sessions", nil)
if err != nil {
t.Fatalf("build login request: %v", err)
}
req.SetBasicAuth(username, password)
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("login request failed: %v", err)
}
return resp
}
func TestLoginWrongPassword(t *testing.T) {
user := createUser(t)
resp := basicLogin(t, user.Username, "wrong-"+testPassword)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
resp = basicLogin(t, "no_such_user_"+user.Username, testPassword)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
}
func TestLogout(t *testing.T) {
user := createUser(t)
resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
requireStatus(t, resp, http.StatusOK)
resp.Body.Close()
resp = doRequest(t, http.MethodDelete, "/api/v1/auth/sessions/current", user.Token, nil)
if resp.StatusCode >= 300 {
t.Fatalf("logout: unexpected status %d", resp.StatusCode)
}
resp.Body.Close()
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
resp = doRequest(t, http.MethodDelete, "/api/v1/auth/sessions/current", user.Token, nil)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
}
+426
View File
@@ -0,0 +1,426 @@
//go:build worker
package studenttests_test
import (
"bytes"
"context"
"encoding/json"
"image/jpeg"
"net/http"
"os"
"os/exec"
"reflect"
"strconv"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"golang.org/x/image/webp"
"gavrilenko-sxdees/lab7/internal/dto"
)
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")
}
crop := workerContent(t, user, att.ID, "crop")
cfg, err = jpeg.DecodeConfig(bytes.NewReader(crop))
if err != nil || cfg.Width != 128 || cfg.Height != 128 {
t.Fatal("invalid JPEG crop")
}
optimized := workerContent(t, user, att.ID, "optimized")
cfg, err = webp.DecodeConfig(bytes.NewReader(optimized))
if err != nil || cfg.Width != 320 || cfg.Height != 200 {
t.Fatal("invalid optimized WebP")
}
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) != "3" {
t.Fatal("duplicate job changed metadata or duplicated variants")
}
if !bytes.Equal(workerContent(t, user, att.ID, "optimized"), optimized) ||
!bytes.Equal(workerContent(t, user, att.ID, "crop"), crop) ||
!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)
}
func TestWorkerProcessingTimeout(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")
}
// Decode and resize of 36 million pixels must be interrupted by the short deadline.
resp := uploadAttachment(t, user, chat.ID, "large.png", "image/png", makePNG(t, 6000, 6000))
requireStatus(t, resp, http.StatusAccepted)
var att dto.AttachmentResponse
mustDecode(t, resp, &att)
testWorker := "worker-timeout-" + uuid.NewString()
t.Cleanup(func() {
workerCommand(t, "rm", "-f", testWorker)
})
workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker,
"-e", "JOB_TIMEOUT_SECONDS=1", "-e", "JOB_MAX_ATTEMPTS=1", "worker")
parentPID := workerCommand(t, "inspect", "--format", "{{.State.Pid}}", testWorker)
workerWait(t, "image child process", 5*time.Second, func() bool {
return strings.Contains(workerCommand(t, "top", testWorker, "-eo", "pid,args"), "-process-image")
})
failed := waitAttachment(t, user, att.ID, "failed", 5*time.Second)
if failed.ErrorCode == nil || *failed.ErrorCode != "retry_exhausted" {
t.Fatal("expected retry_exhausted after processing deadline")
}
if strings.Contains(workerCommand(t, "top", testWorker, "-eo", "pid,args"), "-process-image") {
t.Fatal("image process survived its deadline")
}
if workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE attachment_id='"+att.ID.String()+"'") != "0" {
t.Fatal("timed-out processing published variants")
}
// The same parent process must remain usable after terminating the image child.
uploadPNG(t, user, chat.ID)
after := workerCommand(t, "inspect", "--format", "{{.State.Pid}}", testWorker)
if parentPID != after || parentPID == "0" {
t.Fatal("parent worker restarted after the image timeout")
}
}
func TestWorkerReplay(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)
id := att.ID.String()
where := "attachment_id='" + id + "'"
testWorker := "worker-replay-" + uuid.NewString()
t.Cleanup(func() {
if testWorker != "" {
workerCommand(t, "rm", "-f", testWorker)
}
})
workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker,
"-e", "JOB_TIMEOUT_SECONDS=3", "-e", "JOB_MAX_ATTEMPTS=1",
"-e", "S3_ENDPOINT=http://127.0.0.1:1", "worker")
waitAttachment(t, user, att.ID, "failed", 15*time.Second)
workerCommand(t, "rm", "-f", testWorker)
testWorker = ""
runCLI := func(args ...string) (string, error) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "docker", append([]string{
"compose", "run", "--rm", "--no-deps", "worker",
}, args...)...)
cmd.Dir = ".."
out, err := cmd.CombinedOutput()
return string(out), err
}
replayArgs := []string{"-replay", id, "-operator", "synthetic-operator", "-reason", "S3 restored"}
if out, err := runCLI("-list-failed"); err != nil || !strings.Contains(out, id) {
t.Fatalf("failed registry did not list attachment: %v\n%s", err, out)
}
if out, err := runCLI("-replay", id); err == nil || !strings.Contains(out, "nonempty operator and reason") {
t.Fatalf("replay without audit details was accepted: %v\n%s", err, out)
}
// A stale DB key must not make a missing S3 source replayable.
key := workerSQL(t, "SELECT staging_key FROM attachments WHERE id='"+id+"'")
workerSQL(t, "UPDATE attachments SET staging_key='staging/"+uuid.NewString()+"' WHERE id='"+id+"'")
out, err := runCLI(replayArgs...)
workerSQL(t, "UPDATE attachments SET staging_key='"+key+"' WHERE id='"+id+"'")
if err == nil || !strings.Contains(out, "verify replay source") {
t.Fatalf("missing S3 source was accepted: %v\n%s", err, out)
}
if workerSQL(t, "SELECT status||':'||attempts||':'||retry_base FROM attachments WHERE id='"+id+"'") != "failed:1:0" ||
workerSQL(t, "SELECT count(*) FROM attachment_replays WHERE "+where) != "0" ||
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where) != "1" {
t.Fatal("rejected replay changed attachment, audit or outbox")
}
if out, err := runCLI(replayArgs...); err != nil {
t.Fatalf("replay failed: %v\n%s", err, out)
}
if workerSQL(t, "SELECT status||':'||attempts||':'||retry_base FROM attachments WHERE id='"+id+"'") != "queued:1:1" ||
workerSQL(t, "SELECT attempt||':'||operator||':'||reason||':'||previous_error_code FROM attachment_replays WHERE "+where) !=
"2:synthetic-operator:S3 restored:retry_exhausted" ||
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where) != "2" {
t.Fatal("replay did not atomically queue the next attempt with audit and outbox")
}
if out, err := runCLI(replayArgs...); err == nil || !strings.Contains(out, "not replayable") {
t.Fatalf("queued replay was accepted twice: %v\n%s", err, out)
}
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("replay did not complete the same attachment with unchanged original")
}
if out, err := runCLI(replayArgs...); err == nil || !strings.Contains(out, "not replayable") {
t.Fatalf("ready replay was accepted: %v\n%s", err, out)
}
if workerSQL(t, "SELECT count(*) FROM attachment_replays WHERE "+where) != "1" ||
workerSQL(t, "SELECT attempts FROM attachments WHERE id='"+id+"'") != "2" {
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)
}