Files
mtusi2026lab5/student-tests/reconcile_test.go
T
2026-11-13 15:52:39 +03:00

170 lines
6.2 KiB
Go

//go:build reconcile
package studenttests_test
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"os"
"os/exec"
"slices"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"mtusi2026-messenger/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 stale=%d skipped_fresh=%d skipped_referenced=%d deleted_objects=%d deleted_rows=%d marked_failed=%d errors=%v", report.DryRun, report.ScannedObjects, report.ScannedRows, report.ListPages, report.DurationMS, len(report.OrphanObjects), len(report.MissingAttachments), len(report.StaleUploads), report.SkippedFresh, report.SkippedReferenced, report.DeletedObjects, report.DeletedRows, 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.DeletedRows != 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.DeletedRows != 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()
// Exercise both grace-period protection and protection of referenced queued uploads.
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.SkippedFresh < 1 || report.SkippedReferenced < 1 {
t.Fatal("fresh/referenced 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.StatusOK)
data, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(data, makePNG(t, 32, 32)) {
t.Fatal("protected original changed")
}
}
}
t.Log("PASS: fresh and old referenced uploads preserved, originals unchanged")
}
func TestReconcileCost(t *testing.T) {
for i := 1; i <= 3; i++ {
t.Logf("scan %d/3", i)
runReconcile(t, true, "1h")
}
}