package attachment_test import ( "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "os" "os/exec" "path/filepath" "sort" "strings" "sync" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "messenger/internal/attachment" "messenger/internal/testenv" ) func TestReconcileBlobKey(t *testing.T) { hash, _ := hex.DecodeString("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") if got := attachment.BlobKey(hash); got != "blobs/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" { t.Fatalf("blob key: %q", got) } } // Only object storage is doubled: SQL, transactions, FKs and advisory locks are real. type reconcileBlobs struct { mu sync.Mutex objects map[string]attachment.Object bodies map[string][]byte statErr, deleteErr, openErr error listed func(string) stating func(string) opening func(string) io.ReadCloser writes, readBytes int limits []int } func newReconcileBlobs() *reconcileBlobs { return &reconcileBlobs{objects: make(map[string]attachment.Object), bodies: make(map[string][]byte)} } func (b *reconcileBlobs) add(key string, body []byte, modified time.Time) { b.mu.Lock() defer b.mu.Unlock() b.objects[key] = attachment.Object{Key: key, Size: int64(len(body)), Modified: modified} b.bodies[key] = bytes.Clone(body) } func (b *reconcileBlobs) has(key string) bool { b.mu.Lock() defer b.mu.Unlock() _, ok := b.objects[key] return ok } func (b *reconcileBlobs) Put(_ context.Context, key string, r io.Reader, size int64, _ string) error { body, err := io.ReadAll(io.LimitReader(r, size+1)) if err != nil { return err } if int64(len(body)) != size { return io.ErrUnexpectedEOF } b.add(key, body, time.Now()) b.mu.Lock() b.writes++ b.mu.Unlock() return nil } func (b *reconcileBlobs) Copy(_ context.Context, source, dest string) error { b.mu.Lock() body, ok := b.bodies[source] b.mu.Unlock() if !ok { return attachment.ErrObjectMissing } b.add(dest, body, time.Now()) b.mu.Lock() b.writes++ b.mu.Unlock() return nil } func (b *reconcileBlobs) Open(_ context.Context, key string) (io.ReadCloser, error) { if b.openErr != nil { return nil, b.openErr } if b.opening != nil { return b.opening(key), nil } b.mu.Lock() defer b.mu.Unlock() body, ok := b.bodies[key] if !ok { return nil, attachment.ErrObjectMissing } return io.NopCloser(bytes.NewReader(body)), nil } func (b *reconcileBlobs) Stat(_ context.Context, key string) (attachment.Object, error) { if b.stating != nil { b.stating(key) } b.mu.Lock() defer b.mu.Unlock() if b.statErr != nil { return attachment.Object{}, b.statErr } obj, ok := b.objects[key] if !ok { return attachment.Object{}, fmt.Errorf("head: %w", attachment.ErrObjectMissing) } return obj, nil } func (b *reconcileBlobs) Delete(_ context.Context, key string) error { b.mu.Lock() defer b.mu.Unlock() if b.deleteErr != nil { return b.deleteErr } delete(b.objects, key) delete(b.bodies, key) b.writes++ return nil } func (b *reconcileBlobs) List(_ context.Context, prefix, after string, limit int) ([]attachment.Object, error) { b.mu.Lock() b.limits = append(b.limits, limit) if limit < 1 || limit > 500 { b.mu.Unlock() return nil, errors.New("unbounded page") } var page []attachment.Object for key, obj := range b.objects { if strings.HasPrefix(key, prefix) && key > after { page = append(page, obj) } } sort.Slice(page, func(i, j int) bool { return page[i].Key < page[j].Key }) if len(page) > limit { page = page[:limit] } b.mu.Unlock() if b.listed != nil { b.listed(prefix) } return page, nil } type reconcileFixture struct { t *testing.T db *pgxpool.Pool b *reconcileBlobs user, chat, message uuid.UUID } func reconcileSetup(t *testing.T, db *testenv.DB) *reconcileFixture { t.Helper() db.Reset(t) f := &reconcileFixture{t: t, db: db.Pool, b: newReconcileBlobs(), user: uuid.New(), chat: uuid.New(), message: uuid.New()} f.exec(`INSERT INTO users(id,username,display_name,password_hash,created_at) VALUES($1,'reconcile','Reconcile','unused',now())`, f.user) f.exec(`INSERT INTO chats(id,title,created_at) VALUES($1,'reconcile',now())`, f.chat) f.exec(`INSERT INTO messages(chat_id,id,sender_id,text,created_at) VALUES($1,$2,$3,'preserve',now())`, f.chat, f.message, f.user) return f } func (f *reconcileFixture) exec(sql string, args ...any) { f.t.Helper() if _, err := f.db.Exec(context.Background(), sql, args...); err != nil { f.t.Fatal(err) } } func (f *reconcileFixture) file(body, status string, age time.Duration, referenced, present bool) []byte { f.t.Helper() hash := sha256.Sum256([]byte(body)) f.exec(`INSERT INTO files(hash,size_bytes,mime_type,status,created_at) VALUES($1,$2,'image/png',$3,$4)`, hash[:], len(body), status, time.Now().Add(-age)) if referenced { id := uuid.New() f.exec(`INSERT INTO attachments(id,chat_id,owner_id,filename,file_hash,created_at) VALUES($1,$2,$3,'image.png',$4,now())`, id, f.chat, f.user, hash[:]) f.exec(`INSERT INTO message_attachments(chat_id,message_id,attachment_id,ordinal) VALUES($1,$2,$3,(SELECT count(*) FROM message_attachments WHERE chat_id=$1 AND message_id=$2))`, f.chat, f.message, id) } if present { f.b.add(attachment.BlobKey(hash[:]), []byte(body), time.Now().Add(-age)) } return hash[:] } func (f *reconcileFixture) status(hash []byte) string { f.t.Helper() var s string err := f.db.QueryRow(context.Background(), `SELECT status FROM files WHERE hash=$1`, hash).Scan(&s) if errors.Is(err, pgx.ErrNoRows) { return "" } if err != nil { f.t.Fatal(err) } return s } func (f *reconcileFixture) run(apply, deep bool) (attachment.Stats, []attachment.Finding, error) { f.t.Helper() r, err := attachment.NewReconciler(f.db, f.b, 0) if err != nil { f.t.Fatal(err) } var found []attachment.Finding options := attachment.ReconcileOptions{Apply: apply, Deep: deep} stats, err := r.Run(context.Background(), options, func(v attachment.Finding) { found = append(found, v) }) return stats, found, err } func TestReconciler(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() db, err := testenv.StartPostgres(ctx) if err != nil { t.Fatal(err) } defer db.Close() t.Run("healthy apply does not block publication", func(t *testing.T) { f := reconcileSetup(t, db) hash := f.file("healthy", "ready", 2*time.Hour, true, true) tx, err := db.Pool.Begin(ctx) if err != nil { t.Fatal(err) } defer tx.Rollback(ctx) if err := attachment.LockHash(ctx, tx, hash); err != nil { t.Fatal(err) } r, err := attachment.NewReconciler(f.db, f.b, time.Hour) if err != nil { t.Fatal(err) } scanCtx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() stats, err := r.Run(scanCtx, attachment.ReconcileOptions{Apply: true, Deep: true}, nil) if err != nil || stats.Findings != 0 || stats.Repaired != 0 { t.Fatalf("healthy inspection waited for publication: %+v %v", stats, err) } }) t.Run("constructor validates and defaults grace", func(t *testing.T) { f := reconcileSetup(t, db) for _, grace := range []time.Duration{-time.Second, time.Minute} { if _, err := attachment.NewReconciler(f.db, f.b, grace); err == nil { t.Fatalf("accepted grace %v", grace) } } if _, err := attachment.NewReconciler(nil, f.b, 0); err == nil { t.Fatal("accepted nil DB") } if _, err := attachment.NewReconciler(f.db, nil, 0); err == nil { t.Fatal("accepted nil blobs") } if _, err := attachment.NewReconciler(f.db, f.b, 2*time.Minute); err != nil { t.Fatal(err) } fresh := f.file("half hour", "ready", 30*time.Minute, false, true) stats, _, err := f.run(true, false) if err != nil || stats.Repaired != 0 || f.status(fresh) != "ready" { t.Fatalf("default grace: %+v %v", stats, err) } }) t.Run("dry run then apply then repeat preserves fresh referenced and message links", func(t *testing.T) { f := reconcileSetup(t, db) old := 2 * time.Hour pending := f.file("pending", "pending", old, false, true) unused := f.file("unused", "ready", old, false, true) used := f.file("used", "ready", old, true, true) fresh := f.file("fresh", "pending", time.Minute, false, true) missing := f.file("missing", "ready", old, true, false) f.b.add("staging/old", []byte("old"), time.Now().Add(-old)) f.b.add("staging/fresh", []byte("new"), time.Now()) orphan := sha256.Sum256([]byte("orphan")) orphanKey := attachment.BlobKey(orphan[:]) f.b.add(orphanKey, []byte("orphan"), time.Now().Add(-old)) stats, findings, err := f.run(false, false) if err != nil || stats.Repaired != 0 || stats.Findings != 5 || len(findings) != 5 { t.Fatalf("dry: %+v %v %+v", stats, err, findings) } if f.b.writes != 0 || f.status(pending) != "pending" || f.status(missing) != "ready" { t.Fatal("dry run mutated storage") } for _, finding := range findings { if finding.Applied { t.Fatal("dry finding marked applied") } } stats, findings, err = f.run(true, false) if err != nil || stats.Repaired != 5 { t.Fatalf("apply: %+v %v %+v", stats, err, findings) } if f.status(pending) != "" || f.status(unused) != "" || f.status(missing) != "failed" { t.Fatal("metadata repair incorrect") } if f.b.has(orphanKey) || f.b.has("staging/old") || !f.b.has("staging/fresh") || !f.b.has(attachment.BlobKey(used)) || !f.b.has(attachment.BlobKey(fresh)) { t.Fatal("incorrect object collection") } var links int if err := f.db.QueryRow(ctx, `SELECT count(*) FROM message_attachments`).Scan(&links); err != nil || links != 2 { t.Fatalf("message links lost: %d %v", links, err) } stats, _, err = f.run(true, false) if err != nil || stats.Repaired != 0 { t.Fatalf("repeat: %+v %v", stats, err) } }) t.Run("outage is not missing and failed delete keeps row", func(t *testing.T) { f := reconcileSetup(t, db) used := f.file("used", "ready", 2*time.Hour, true, true) outage := errors.New("injected S3 outage") f.b.statErr = outage stats, _, err := f.run(true, false) if !errors.Is(err, outage) || stats.Repaired != 0 || f.status(used) != "ready" { t.Fatalf("outage: %+v %v", stats, err) } f.b.statErr = nil unused := f.file("unused", "pending", 2*time.Hour, false, true) f.b.deleteErr = outage _, _, err = f.run(true, false) if !errors.Is(err, outage) || f.status(unused) != "pending" { t.Fatalf("delete failure: %v", err) } }) t.Run("deep reports corruption and never revives failed without verification", func(t *testing.T) { f := reconcileSetup(t, db) hash := f.file("good", "ready", 2*time.Hour, true, true) f.b.add(attachment.BlobKey(hash), []byte("evil"), time.Now().Add(-2*time.Hour)) stats, found, err := f.run(true, true) if err != nil || stats.Findings != 1 || stats.Repaired != 0 || len(found) != 1 || found[0].Kind != "hash_mismatch" || f.status(hash) != "ready" || !f.b.has(attachment.BlobKey(hash)) { t.Fatalf("deep: %+v %v %+v", stats, err, found) } f.exec(`UPDATE files SET status='failed' WHERE hash=$1`, hash) stats, _, err = f.run(true, false) if err != nil || stats.Repaired != 0 || f.status(hash) != "failed" { t.Fatal("shallow revived failed file") } stats, _, err = f.run(true, true) if err != nil || stats.Repaired != 0 || f.status(hash) != "failed" { t.Fatal("corrupt file revived") } }) t.Run("wrong size reports only and fresh missing stays ready", func(t *testing.T) { f := reconcileSetup(t, db) hash := f.file("sized", "ready", 2*time.Hour, true, true) f.b.add(attachment.BlobKey(hash), []byte("longer body"), time.Now().Add(-2*time.Hour)) fresh := f.file("new missing", "ready", time.Minute, true, false) stats, found, err := f.run(true, false) if err != nil || stats.Repaired != 0 || stats.Findings != 1 || found[0].Kind != "size_mismatch" || f.status(fresh) != "ready" { t.Fatalf("size/fresh: %+v %v %+v", stats, err, found) } }) t.Run("orphan rechecks current object age", func(t *testing.T) { f := reconcileSetup(t, db) hash := sha256.Sum256([]byte("orphan")) key := attachment.BlobKey(hash[:]) f.b.add(key, []byte("orphan"), time.Now().Add(-2*time.Hour)) f.b.listed = func(prefix string) { if prefix == "blobs/" { f.b.add(key, []byte("republished"), time.Now()) } } stats, _, err := f.run(true, false) if err != nil || stats.Repaired != 0 || !f.b.has(key) { t.Fatalf("fresh replacement deleted: %+v %v", stats, err) } }) t.Run("row rechecks references after taking lock", func(t *testing.T) { f := reconcileSetup(t, db) hash := f.file("race refs", "ready", 2*time.Hour, false, true) tx, err := f.db.Begin(ctx) if err != nil { t.Fatal(err) } defer tx.Rollback(ctx) if err = attachment.LockHash(ctx, tx, hash); err != nil { t.Fatal(err) } done := make(chan error, 1) go func() { r, _ := attachment.NewReconciler(f.db, f.b, 0) _, err := r.Run(ctx, attachment.ReconcileOptions{Apply: true}, nil) done <- err }() waitReconcileLock(t, ctx, f.db) _, err = tx.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,file_hash,created_at) VALUES($1,$2,$3,'race.png',$4,now())`, uuid.New(), f.chat, f.user, hash) if err != nil { t.Fatal(err) } if err = tx.Commit(ctx); err != nil { t.Fatal(err) } if err = <-done; err != nil { t.Fatal(err) } if f.status(hash) != "ready" || !f.b.has(attachment.BlobKey(hash)) { t.Fatal("new reference collected") } }) t.Run("concurrent upload lock prevents orphan collection", func(t *testing.T) { f := reconcileSetup(t, db) hash := sha256.Sum256([]byte("publishing")) key := attachment.BlobKey(hash[:]) f.b.add(key, []byte("publishing"), time.Now().Add(-2*time.Hour)) tx, err := f.db.Begin(ctx) if err != nil { t.Fatal(err) } defer tx.Rollback(ctx) if err = attachment.LockHash(ctx, tx, hash[:]); err != nil { t.Fatal(err) } done := make(chan error, 1) go func() { r, _ := attachment.NewReconciler(f.db, f.b, 0) _, err := r.Run(ctx, attachment.ReconcileOptions{Apply: true}, nil) done <- err }() waitReconcileLock(t, ctx, f.db) if _, err = tx.Exec(ctx, `INSERT INTO files(hash,size_bytes,mime_type,status) VALUES($1,10,'image/png','ready')`, hash[:]); err != nil { t.Fatal(err) } if err = tx.Commit(ctx); err != nil { t.Fatal(err) } if err = <-done; err != nil { t.Fatal(err) } if !f.b.has(key) || f.status(hash[:]) != "ready" { t.Fatal("published blob collected") } }) t.Run("signed big endian lock key matches publisher", func(t *testing.T) { f := reconcileSetup(t, db) hash := make([]byte, 32) for i := 0; i < 8; i++ { hash[i] = 255 } hash[7] = 254 tx, err := f.db.Begin(ctx) if err != nil { t.Fatal(err) } defer tx.Rollback(ctx) if err = attachment.LockHash(ctx, tx, hash); err != nil { t.Fatal(err) } other, err := f.db.Begin(ctx) if err != nil { t.Fatal(err) } defer other.Rollback(ctx) var acquired bool if err = other.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(-2::bigint)`).Scan(&acquired); err != nil || acquired { t.Fatalf("lock mismatch: %v %v", acquired, err) } }) t.Run("keyset pages tolerate deletes and report costs", func(t *testing.T) { f := reconcileSetup(t, db) for i := 0; i < 1003; i++ { f.b.add(fmt.Sprintf("staging/%04d", i), []byte("x"), time.Now().Add(-2*time.Hour)) } f.exec(`INSERT INTO files(hash,size_bytes,mime_type,status,created_at) SELECT decode(lpad(to_hex(i),64,'0'),'hex'),1,'image/png','pending',now()-interval '2 hour' FROM generate_series(1,1003) AS i`) stats, _, err := f.run(true, false) if err != nil || stats.ScannedFiles != 1003 || stats.ScannedObjects != 1003 || stats.Repaired != 2006 { t.Fatalf("pages: %+v %v", stats, err) } var n int if err := f.db.QueryRow(ctx, `SELECT count(*) FROM files`).Scan(&n); err != nil || n != 0 { t.Fatalf("skipped rows: %d %v", n, err) } if len(f.b.limits) < 4 || stats.SQLQueries == 0 || stats.S3Calls == 0 { t.Fatalf("missing paging/costs: %+v", stats) } raw, err := json.Marshal(stats) if err != nil { t.Fatal(err) } for _, key := range []string{"elapsed_ms", "sql_queries", "s3_calls", "scanned_files", "scanned_objects", "findings", "repaired"} { if !bytes.Contains(raw, []byte(`"`+key+`":`)) { t.Fatalf("missing JSON key %s: %s", key, raw) } } }) t.Run("old blob existence checks are batched by page", func(t *testing.T) { f := reconcileSetup(t, db) f.exec(`INSERT INTO files(hash,size_bytes,mime_type,status,created_at) SELECT decode(lpad(to_hex(i),64,'0'),'hex'),1,'image/png','ready',now()-interval '2 hour' FROM generate_series(1,1003) AS i`) f.exec(`INSERT INTO attachments(id,chat_id,owner_id,filename,file_hash,created_at) SELECT gen_random_uuid(),$1,$2,'batch.png',hash,now() FROM files`, f.chat, f.user) for i := 1; i <= 1003; i++ { f.b.add(fmt.Sprintf("blobs/%064x", i), []byte("x"), time.Now().Add(-2*time.Hour)) } stats, _, err := f.run(false, false) if err != nil || stats.SQLQueries > 8 || stats.SQLQueries == 0 || stats.ScannedFiles != 1003 || stats.Findings != 0 { t.Fatalf("per-object SQL lookup: %+v %v", stats, err) } }) } func waitReconcileLock(t *testing.T, ctx context.Context, db *pgxpool.Pool) { t.Helper() deadline := time.NewTimer(5 * time.Second) defer deadline.Stop() tick := time.NewTicker(10 * time.Millisecond) defer tick.Stop() for { var waiting bool if err := db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM pg_locks WHERE locktype='advisory' AND NOT granted)`).Scan(&waiting); err != nil { t.Fatal(err) } if waiting { return } select { case <-deadline.C: t.Fatal("reconciler did not wait on publisher advisory lock") case <-tick.C: } } } type reconcileEndless struct { read int64 closed bool } func (r *reconcileEndless) Read(p []byte) (int, error) { for i := range p { p[i] = 'x' } r.read += int64(len(p)) return len(p), nil } func (r *reconcileEndless) Close() error { r.closed = true; return nil } func TestReconcilerFailureBoundaries(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() db, err := testenv.StartPostgres(ctx) if err != nil { t.Fatal(err) } defer db.Close() t.Run("slow object call survives pool idle transaction timeout", func(t *testing.T) { f := reconcileSetup(t, db) hash := f.file("slow object", "pending", 2*time.Hour, false, true) cfg := f.db.Config() cfg.ConnConfig.RuntimeParams["idle_in_transaction_session_timeout"] = "100ms" pool, err := pgxpool.NewWithConfig(ctx, cfg) if err != nil { t.Fatal(err) } defer pool.Close() f.db = pool f.b.stating = func(string) { time.Sleep(250 * time.Millisecond) } stats, _, err := f.run(true, false) if err != nil || stats.Repaired != 1 || f.status(hash) != "" { t.Fatalf("slow S3 transaction rolled back: %+v %v", stats, err) } }) t.Run("fresh object with old unused metadata is preserved", func(t *testing.T) { f := reconcileSetup(t, db) hash := f.file("republished", "pending", 2*time.Hour, false, true) f.b.add(attachment.BlobKey(hash), []byte("republished"), time.Now()) stats, _, err := f.run(true, false) if err != nil || stats.Repaired != 0 || f.status(hash) != "pending" || !f.b.has(attachment.BlobKey(hash)) { t.Fatalf("fresh blob lost: %+v %v", stats, err) } }) t.Run("deep read stops at size plus one and closes body", func(t *testing.T) { f := reconcileSetup(t, db) hash := f.file("good", "ready", 2*time.Hour, true, true) body := &reconcileEndless{} f.b.opening = func(string) io.ReadCloser { return body } stats, found, err := f.run(true, true) if err != nil || body.read != 5 || !body.closed || stats.Repaired != 0 || len(found) != 1 || found[0].Kind != "hash_mismatch" || f.status(hash) != "ready" { t.Fatalf("unbounded deep read: read=%d closed=%v %+v %v", body.read, body.closed, stats, err) } }) t.Run("deep GET outage preserves referenced state", func(t *testing.T) { f := reconcileSetup(t, db) hash := f.file("good", "ready", 2*time.Hour, true, true) outage := errors.New("injected GET outage") f.b.openErr = outage stats, _, err := f.run(true, true) if !errors.Is(err, outage) || stats.Repaired != 0 || f.status(hash) != "ready" { t.Fatalf("GET outage: %+v %v", stats, err) } }) t.Run("valid failed object remains stable even deep", func(t *testing.T) { f := reconcileSetup(t, db) hash := f.file("good", "failed", 2*time.Hour, true, true) for _, deep := range []bool{false, true} { stats, found, err := f.run(true, deep) if err != nil || stats.Repaired != 0 || len(found) != 1 || found[0].Kind != "failed_present" || f.status(hash) != "failed" { t.Fatalf("failed state unstable: %+v %v %+v", stats, err, found) } } }) t.Run("dry run works with a read only PostgreSQL session", func(t *testing.T) { f := reconcileSetup(t, db) hash := f.file("missing", "ready", 2*time.Hour, true, false) cfg := f.db.Config() cfg.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on" readOnly, err := pgxpool.NewWithConfig(ctx, cfg) if err != nil { t.Fatal(err) } defer readOnly.Close() r, err := attachment.NewReconciler(readOnly, f.b, 0) if err != nil { t.Fatal(err) } stats, err := r.Run(ctx, attachment.ReconcileOptions{Deep: true}, nil) if err != nil || stats.Findings != 1 || stats.Repaired != 0 || f.status(hash) != "ready" { t.Fatalf("read only dry run: %+v %v", stats, err) } }) t.Run("failed SQL commit after blob deletion is retryable", func(t *testing.T) { f := reconcileSetup(t, db) hash := f.file("unused", "pending", 2*time.Hour, false, true) f.exec(`CREATE FUNCTION reconcile_reject_delete() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected commit failure'; END $$`) f.exec(`CREATE CONSTRAINT TRIGGER reconcile_reject_delete AFTER DELETE ON files DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reconcile_reject_delete()`) t.Cleanup(func() { f.exec(`DROP TRIGGER IF EXISTS reconcile_reject_delete ON files`) f.exec(`DROP FUNCTION IF EXISTS reconcile_reject_delete()`) }) stats, _, err := f.run(true, false) if err == nil || stats.Repaired != 0 || f.status(hash) != "pending" || f.b.has(attachment.BlobKey(hash)) { t.Fatalf("failed commit: %+v %v", stats, err) } f.exec(`DROP TRIGGER reconcile_reject_delete ON files`) stats, _, err = f.run(true, false) if err != nil || stats.Repaired != 1 || f.status(hash) != "" { t.Fatalf("retry: %+v %v", stats, err) } }) } func TestReconcilerS3(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) defer cancel() db, err := testenv.StartPostgres(ctx) if err != nil { t.Fatal(err) } defer db.Close() s3, err := testenv.StartS3(ctx) if err != nil { t.Fatal(err) } defer s3.Close() f := reconcileSetup(t, db) hash := f.file("good", "ready", 2*time.Hour, true, false) missing := f.file("missing", "ready", 2*time.Hour, true, false) key := attachment.BlobKey(hash) if err = s3.Store.Put(ctx, key, strings.NewReader("evil"), 4, "image/png"); err != nil { t.Fatal(err) } if err = s3.Store.Put(ctx, "staging/fresh", strings.NewReader("x"), 1, "image/png"); err != nil { t.Fatal(err) } r, err := attachment.NewReconciler(f.db, s3.Store, 0) if err != nil { t.Fatal(err) } // Exercise the command with file-based configuration and the real listing // identity. Its default must remain read-only, including missing metadata. secretDir := t.TempDir() cliEnv := os.Environ() for name, value := range map[string]string{ "DATABASE_URL_FILE": db.DSN, "S3_ACCESS_KEY_ID_FILE": s3.AccessKey, "S3_SECRET_ACCESS_KEY_FILE": s3.SecretKey, } { path := filepath.Join(secretDir, name) if err := os.WriteFile(path, []byte(value), 0600); err != nil { t.Fatal(err) } cliEnv = append(cliEnv, name+"="+path) } cliEnv = append(cliEnv, "S3_ENDPOINT="+s3.Endpoint, "S3_REGION="+s3.Region, "S3_BUCKET="+s3.Bucket) cmd := exec.CommandContext(ctx, "go", "run", "../../cmd/reconcile", "--deep") cmd.Env = cliEnv var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr if err := cmd.Run(); err != nil { t.Fatalf("CLI dry run: %v: %s", err, stderr.String()) } decoder := json.NewDecoder(&stdout) var cliStats attachment.Stats for i := 0; i < 2; i++ { var finding attachment.Finding if err := decoder.Decode(&finding); err != nil || finding.Applied || finding.Kind == "" || finding.Key == "" || finding.Action == "" { t.Fatalf("CLI finding: %+v %v", finding, err) } } if err := decoder.Decode(&cliStats); err != nil || cliStats.Findings != 2 || cliStats.Repaired != 0 || f.status(missing) != "ready" { t.Fatalf("CLI mutated by default: %+v %v", cliStats, err) } var found []attachment.Finding stats, err := r.Run(ctx, attachment.ReconcileOptions{Deep: true}, func(v attachment.Finding) { found = append(found, v) }) if err != nil || stats.Repaired != 0 || stats.Findings != 2 || f.status(missing) != "ready" { t.Fatalf("S3 dry: %+v %v %+v", stats, err, found) } stats, err = r.Run(ctx, attachment.ReconcileOptions{Apply: true, Deep: true}, nil) if err != nil || stats.Repaired != 1 || f.status(missing) != "failed" || f.status(hash) != "ready" { t.Fatalf("S3 apply: %+v %v", stats, err) } if _, err = s3.Store.Stat(ctx, key); err != nil { t.Fatal("referenced corrupt object deleted", err) } if _, err = s3.Store.Stat(ctx, "staging/fresh"); err != nil { t.Fatal("fresh staging deleted", err) } stats, err = r.Run(ctx, attachment.ReconcileOptions{Apply: true, Deep: true}, nil) if err != nil || stats.Repaired != 0 { t.Fatalf("S3 repeat: %+v %v", stats, err) } } func TestReconcileLockRejectsMalformedHash(t *testing.T) { if err := attachment.LockHash(context.Background(), nil, []byte("bad")); err == nil { t.Fatal("malformed hash accepted") } } func TestGCRespectsJobSourcesAndVersionedOutputs(t *testing.T) { ctx := context.Background() db, err := testenv.StartPostgres(ctx) if err != nil { t.Fatal(err) } defer db.Close() f := reconcileSetup(t, db) hash := f.file("job input", "pending", 48*time.Hour, true, false) var id uuid.UUID if err := db.Pool.QueryRow(ctx, `SELECT id FROM attachments WHERE file_hash=$1`, hash).Scan(&id); err != nil { t.Fatal(err) } stage := "staging/" + id.String() output := "variants/" + id.String() + "/1/thumbnail/" + strings.Repeat("0", 64) old := time.Now().Add(-48 * time.Hour) f.b.add(stage, []byte("job input"), old) f.b.add(output, []byte("partial"), old) f.exec(`INSERT INTO attachment_jobs(attachment_id,source_key) VALUES ($1,$2)`, id, stage) for _, apply := range []bool{false, true} { stats, _, err := f.run(apply, false) if err != nil || stats.Findings != 0 || !f.b.has(stage) || !f.b.has(output) { t.Fatalf("active job lost: %+v %v", stats, err) } } f.exec(`UPDATE attachment_jobs SET state='failed', error_code='retry_exhausted',updated_at=now()`) stats, _, err := f.run(true, false) if err != nil || stats.Repaired != 1 || !f.b.has(stage) || f.b.has(output) { t.Fatalf("failed retention: %+v %v", stats, err) } f.exec(`UPDATE attachment_jobs SET updated_at=now()-interval '3 hours'`) stats, _, err = f.run(true, false) if err != nil || stats.Repaired != 0 || !f.b.has(stage) { t.Fatalf("default failed retention: %+v %v", stats, err) } r, err := attachment.NewReconcilerWithRetention(db.Pool, f.b, time.Hour, 2*time.Hour) if err != nil { t.Fatal(err) } stats, err = r.Run(ctx, attachment.ReconcileOptions{Apply: true}, nil) if err != nil || stats.Repaired != 1 || f.b.has(stage) { t.Fatalf("expired source: %+v %v", stats, err) } }