forked from mtusi2026/mtusi2026lab4
117 lines
2.4 KiB
Go
117 lines
2.4 KiB
Go
package reconcile
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"mtusi2026/internal/blobstore"
|
|
)
|
|
|
|
type Report struct {
|
|
Scanned, Young, Orphans, Deleted, Missing int
|
|
}
|
|
|
|
type cand struct{ key string }
|
|
|
|
func Run(ctx context.Context, pool *pgxpool.Pool, blobs blobstore.Store, grace time.Duration,
|
|
dryRun, checkMissing bool, logf func(string, ...any)) (Report, error) {
|
|
|
|
var rep Report
|
|
cutoff := time.Now().Add(-grace)
|
|
var batch []string
|
|
|
|
flush := func() error {
|
|
if len(batch) == 0 {
|
|
return nil
|
|
}
|
|
rows, err := pool.Query(ctx, `SELECT object_key FROM attachments WHERE object_key = ANY($1)`, batch)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
known := map[string]bool{}
|
|
for rows.Next() {
|
|
var k string
|
|
if err := rows.Scan(&k); err != nil {
|
|
rows.Close()
|
|
return err
|
|
}
|
|
known[k] = true
|
|
}
|
|
rows.Close()
|
|
if err := rows.Err(); err != nil {
|
|
return err
|
|
}
|
|
for _, k := range batch {
|
|
if known[k] {
|
|
continue
|
|
}
|
|
rep.Orphans++
|
|
if dryRun {
|
|
logf("orphan (dry-run, not deleted): %s", k)
|
|
continue
|
|
}
|
|
if err := blobs.Delete(ctx, k); err != nil {
|
|
logf("orphan delete failed: %s: %v", k, err)
|
|
continue
|
|
}
|
|
rep.Deleted++
|
|
logf("orphan deleted: %s", k)
|
|
}
|
|
batch = batch[:0]
|
|
return nil
|
|
}
|
|
|
|
err := blobs.List(ctx, "attachments/", func(key string, modified time.Time) error {
|
|
rep.Scanned++
|
|
if modified.After(cutoff) {
|
|
rep.Young++
|
|
return nil
|
|
}
|
|
batch = append(batch, key)
|
|
if len(batch) >= 500 {
|
|
return flush()
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return rep, fmt.Errorf("list: %w", err)
|
|
}
|
|
if err := flush(); err != nil {
|
|
return rep, fmt.Errorf("check db: %w", err)
|
|
}
|
|
|
|
if checkMissing {
|
|
rows, err := pool.Query(ctx,
|
|
`SELECT id, object_key FROM attachments WHERE created_at < $1 ORDER BY created_at`, cutoff)
|
|
if err != nil {
|
|
return rep, err
|
|
}
|
|
type rec struct{ id, key string }
|
|
var recs []rec
|
|
for rows.Next() {
|
|
var r rec
|
|
if err := rows.Scan(&r.id, &r.key); err != nil {
|
|
rows.Close()
|
|
return rep, err
|
|
}
|
|
recs = append(recs, r)
|
|
}
|
|
rows.Close()
|
|
for _, r := range recs {
|
|
ok, err := blobs.Exists(ctx, r.key)
|
|
if err != nil {
|
|
logf("exists check failed: %s: %v", r.key, err)
|
|
continue
|
|
}
|
|
if !ok {
|
|
rep.Missing++
|
|
logf("MISSING object for attachment id=%s key=%s (metadata kept, needs manual decision)", r.id, r.key)
|
|
}
|
|
}
|
|
}
|
|
return rep, nil
|
|
}
|