forked from mtusi2026/mtusi2026lab5
162 lines
5.9 KiB
Go
162 lines
5.9 KiB
Go
//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"
|
|
|
|
"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 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")
|
|
}
|
|
}
|