feat: two-store reconciler with safe repair and cost measurement (grade 5, track 2)

This commit is contained in:
2026-11-20 05:01:20 +03:00
parent 1c3011bf28
commit 60e8f4474b
36 changed files with 807 additions and 212 deletions
+81 -8
View File
@@ -5,8 +5,11 @@ import (
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"sync/atomic"
"time"
"uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
@@ -17,20 +20,31 @@ import (
"messenger/internal/repository/s3"
)
type countingTransport struct {
base http.RoundTripper
count atomic.Int64
}
func (t *countingTransport) RoundTrip(request *http.Request) (*http.Response, error) {
t.count.Add(1)
return t.base.RoundTrip(request)
}
func main() {
dryRun := flag.Bool("dry-run", true, "report only, do not delete orphan objects")
dryRun := flag.Bool("dry-run", true, "report only, do not delete or repair anything")
grace := flag.Duration("grace", time.Hour, "minimum object age before it can be deleted")
prefix := flag.String("prefix", "chats/", "object key prefix to scan")
limit := flag.Int("limit", 10000, "maximum number of objects to scan")
repairMissing := flag.Bool("repair-missing", true, "delete metadata rows whose object is gone and that no message references")
flag.Parse()
if err := run(*dryRun, *grace, *prefix, *limit); err != nil {
if err := run(*dryRun, *grace, *prefix, *limit, *repairMissing); err != nil {
fmt.Fprintln(os.Stderr, "reconcile failed:", err)
os.Exit(1)
}
}
func run(dryRun bool, grace time.Duration, prefix string, limit int) error {
func run(dryRun bool, grace time.Duration, prefix string, limit int, repairMissing bool) error {
if grace < 0 {
return fmt.Errorf("grace must not be negative")
}
@@ -55,10 +69,11 @@ func run(dryRun bool, grace time.Duration, prefix string, limit int) error {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
store, err := s3.New(endpoint, region, accessKeyID, secretAccessKey, bucket)
transport := &countingTransport{base: http.DefaultTransport}
store, err := s3.NewWithTransport(endpoint, region, accessKeyID, secretAccessKey, bucket, transport)
if err != nil {
return err
}
@@ -77,8 +92,12 @@ func run(dryRun bool, grace time.Duration, prefix string, limit int) error {
if err != nil {
return err
}
referenced, err := loadReferences(ctx, pool)
if err != nil {
return err
}
orphans, missing := reconcile.Plan(toObjects(scanned), rows, prefix, time.Now(), grace)
orphans, missing := reconcile.Plan(toObjects(scanned), rows, referenced, prefix, time.Now(), grace)
if truncated {
missing = nil
}
@@ -93,16 +112,50 @@ func run(dryRun bool, grace time.Duration, prefix string, limit int) error {
Orphans: orphans,
Missing: missing,
}
dbQueries := 2
if !dryRun {
for _, orphan := range orphans {
if err := store.Delete(ctx, orphan.Key); err != nil {
report.DeleteFailures++
continue
}
report.Deleted++
report.DeletedObjects++
}
if repairMissing {
for _, item := range missing {
if item.Referenced {
report.RetainedMissing++
continue
}
id, err := uuid.Parse(item.ID)
if err != nil {
report.DeleteFailures++
continue
}
tag, err := pool.Exec(ctx, `DELETE FROM attachments WHERE id = $1`, id)
dbQueries++
if err != nil {
report.DeleteFailures++
continue
}
report.DeletedMetadata += int(tag.RowsAffected())
}
} else {
for _, item := range missing {
if item.Referenced {
report.RetainedMissing++
}
}
}
}
report.S3Requests = transport.count.Load()
report.DBQueries = dbQueries
report.DurationMS = time.Since(started).Milliseconds()
if report.DurationMS > 0 {
report.ObjectsPerSecond = float64(report.ScannedObjects) / (float64(report.DurationMS) / 1000)
}
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
@@ -110,7 +163,7 @@ func run(dryRun bool, grace time.Duration, prefix string, limit int) error {
return err
}
if report.DeleteFailures > 0 {
return fmt.Errorf("%d orphan deletions failed", report.DeleteFailures)
return fmt.Errorf("%d repair operations failed", report.DeleteFailures)
}
return nil
}
@@ -127,6 +180,26 @@ func loadMetadata(ctx context.Context, pool *pgxpool.Pool) ([]reconcile.Metadata
})
}
func loadReferences(ctx context.Context, pool *pgxpool.Pool) (map[uuid.UUID]bool, error) {
rows, err := pool.Query(ctx, `SELECT DISTINCT attachment_id FROM message_attachments`)
if err != nil {
return nil, err
}
ids, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (uuid.UUID, error) {
var id uuid.UUID
err := row.Scan(&id)
return id, err
})
if err != nil {
return nil, err
}
referenced := make(map[uuid.UUID]bool, len(ids))
for _, id := range ids {
referenced[id] = true
}
return referenced, nil
}
func toObjects(scanned []s3.ObjectInfo) []reconcile.Object {
objects := make([]reconcile.Object, len(scanned))
for i, info := range scanned {