Реализовать lab4: вложения S3/MinIO, уровень 4 и трек 2 reconciler.
Метаданные в PostgreSQL, байты в приватном bucket; sync upload 201 ready; компенсация orphan и cmd/reconcile с dry-run/apply и grace period.
This commit is contained in:
@@ -0,0 +1,221 @@
|
||||
// Reconciler lab4 (трек 5 / согласованность двух хранилищ).
|
||||
//
|
||||
// Сверяет PostgreSQL (attachments) и приватный S3-bucket (префикс originals/).
|
||||
// По умолчанию dry-run: только отчёт. Флаг -apply выполняет безопасные правки.
|
||||
//
|
||||
// Классы расхождений:
|
||||
//
|
||||
// orphan — объект в S3 без строки в БД. После grace period удаляется (-apply).
|
||||
// missing — строка в БД без объекта. Если на вложение нет ссылок из сообщений
|
||||
// и строка старше grace — удаляется. Ссылаемые (в сообщениях) только
|
||||
// логируются: удалять их нельзя, файл уже «в истории».
|
||||
//
|
||||
// Свежие объекты/строки (моложе grace) не трогаются: гонка «PUT прошёл, INSERT ещё нет»
|
||||
// не должна приводить к удалению чужой успешной загрузки.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab4/internal/auth"
|
||||
"mtusi2026lab4/internal/blob"
|
||||
"mtusi2026lab4/internal/config"
|
||||
"mtusi2026lab4/internal/store"
|
||||
)
|
||||
|
||||
func main() {
|
||||
apply := flag.Bool("apply", false, "apply safe fixes (default: dry-run)")
|
||||
graceSec := flag.Int64("grace-seconds", -1, "override S3_RECONCILE_GRACE_SECONDS (-1 = from env)")
|
||||
pageSize := flag.Int("page-size", 200, "DB page size for attachment refs")
|
||||
flag.Parse()
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Fatalf("config: %v", err)
|
||||
}
|
||||
grace := cfg.ReconcileGrace
|
||||
if *graceSec >= 0 {
|
||||
grace = time.Duration(*graceSec) * time.Second
|
||||
}
|
||||
s3cfg, err := config.LoadS3()
|
||||
if err != nil {
|
||||
log.Fatalf("s3 config: %v", err)
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
hasher, err := auth.NewHasher()
|
||||
if err != nil {
|
||||
log.Fatalf("hasher: %v", err)
|
||||
}
|
||||
st, err := store.Open(ctx, cfg.DatabaseURL, hasher, cfg.MaxConns)
|
||||
if err != nil {
|
||||
log.Fatalf("postgres: %v", err)
|
||||
}
|
||||
defer st.Close()
|
||||
|
||||
bl, err := blob.New(blob.Config{
|
||||
Endpoint: s3cfg.Endpoint,
|
||||
UseSSL: s3cfg.UseSSL,
|
||||
Region: s3cfg.Region,
|
||||
Bucket: s3cfg.Bucket,
|
||||
AccessKey: s3cfg.AccessKey,
|
||||
SecretKey: s3cfg.SecretKey,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("s3: %v", err)
|
||||
}
|
||||
if err := bl.Ping(ctx); err != nil {
|
||||
log.Fatalf("s3 ping: %v", err)
|
||||
}
|
||||
|
||||
mode := "dry-run"
|
||||
if *apply {
|
||||
mode = "apply"
|
||||
}
|
||||
log.Printf("reconcile start mode=%s grace=%s bucket=%s page=%d", mode, grace, s3cfg.Bucket, *pageSize)
|
||||
|
||||
started := time.Now()
|
||||
rep, err := run(ctx, st, bl, grace, *pageSize, *apply)
|
||||
if err != nil {
|
||||
log.Fatalf("reconcile: %v", err)
|
||||
}
|
||||
elapsed := time.Since(started)
|
||||
|
||||
fmt.Printf("reconcile_report mode=%s elapsed_ms=%d\n", mode, elapsed.Milliseconds())
|
||||
fmt.Printf("s3_objects=%d db_rows=%d\n", rep.S3Objects, rep.DBRows)
|
||||
fmt.Printf("orphans_found=%d orphans_deleted=%d orphans_skipped_fresh=%d\n",
|
||||
rep.OrphansFound, rep.OrphansDeleted, rep.OrphansSkippedFresh)
|
||||
fmt.Printf("missing_found=%d missing_deleted=%d missing_referenced=%d missing_skipped_fresh=%d\n",
|
||||
rep.MissingFound, rep.MissingDeleted, rep.MissingReferenced, rep.MissingSkippedFresh)
|
||||
for _, line := range rep.Details {
|
||||
fmt.Println(line)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
type report struct {
|
||||
S3Objects int
|
||||
DBRows int
|
||||
OrphansFound int
|
||||
OrphansDeleted int
|
||||
OrphansSkippedFresh int
|
||||
MissingFound int
|
||||
MissingDeleted int
|
||||
MissingReferenced int
|
||||
MissingSkippedFresh int
|
||||
Details []string
|
||||
}
|
||||
|
||||
func run(ctx context.Context, st *store.Store, bl *blob.Client, grace time.Duration, pageSize int, apply bool) (*report, error) {
|
||||
if pageSize < 1 || pageSize > 1000 {
|
||||
pageSize = 200
|
||||
}
|
||||
rep := &report{}
|
||||
cutoff := time.Now().UTC().Add(-grace)
|
||||
|
||||
objs, err := bl.ListKeys(ctx, blob.KeyPrefix)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list s3: %w", err)
|
||||
}
|
||||
rep.S3Objects = len(objs)
|
||||
byKey := make(map[string]blob.ObjectInfo, len(objs))
|
||||
for _, o := range objs {
|
||||
byKey[o.Key] = o
|
||||
}
|
||||
|
||||
dbKeys := make(map[string]store.AttachmentRef)
|
||||
var after uuid.UUID
|
||||
for {
|
||||
page, err := st.ListAttachmentRefs(ctx, after, pageSize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list db: %w", err)
|
||||
}
|
||||
if len(page) == 0 {
|
||||
break
|
||||
}
|
||||
for _, r := range page {
|
||||
dbKeys[r.ObjectKey] = r
|
||||
rep.DBRows++
|
||||
after = r.ID
|
||||
}
|
||||
if len(page) < pageSize {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// orphan: S3 без строки
|
||||
for key, o := range byKey {
|
||||
if _, ok := dbKeys[key]; ok {
|
||||
continue
|
||||
}
|
||||
rep.OrphansFound++
|
||||
if o.LastModified.After(cutoff) {
|
||||
rep.OrphansSkippedFresh++
|
||||
rep.Details = append(rep.Details, fmt.Sprintf("orphan_skip_fresh key=%s age<%s", key, grace))
|
||||
continue
|
||||
}
|
||||
// Повторная проверка: загрузка могла успеть записать строку после ListKeys.
|
||||
exists, err := st.AttachmentKeyExists(ctx, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if exists {
|
||||
rep.Details = append(rep.Details, fmt.Sprintf("orphan_race_gone key=%s", key))
|
||||
continue
|
||||
}
|
||||
if apply {
|
||||
if err := bl.Delete(ctx, key); err != nil {
|
||||
return nil, fmt.Errorf("delete orphan %s: %w", key, err)
|
||||
}
|
||||
rep.OrphansDeleted++
|
||||
rep.Details = append(rep.Details, fmt.Sprintf("orphan_deleted key=%s size=%d", key, o.Size))
|
||||
} else {
|
||||
rep.Details = append(rep.Details, fmt.Sprintf("orphan_would_delete key=%s size=%d", key, o.Size))
|
||||
}
|
||||
}
|
||||
|
||||
// missing: строка без объекта
|
||||
for key, ref := range dbKeys {
|
||||
if _, ok := byKey[key]; ok {
|
||||
continue
|
||||
}
|
||||
rep.MissingFound++
|
||||
if ref.CreatedAt.After(cutoff) {
|
||||
rep.MissingSkippedFresh++
|
||||
rep.Details = append(rep.Details, fmt.Sprintf("missing_skip_fresh id=%s key=%s", ref.ID, key))
|
||||
continue
|
||||
}
|
||||
if ref.Referenced {
|
||||
rep.MissingReferenced++
|
||||
rep.Details = append(rep.Details, fmt.Sprintf("missing_referenced id=%s key=%s (kept)", ref.ID, key))
|
||||
continue
|
||||
}
|
||||
if apply {
|
||||
ok, err := st.DeleteUnreferencedAttachment(ctx, ref.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("delete missing meta %s: %w", ref.ID, err)
|
||||
}
|
||||
if ok {
|
||||
rep.MissingDeleted++
|
||||
rep.Details = append(rep.Details, fmt.Sprintf("missing_deleted id=%s key=%s", ref.ID, key))
|
||||
} else {
|
||||
rep.MissingReferenced++
|
||||
rep.Details = append(rep.Details, fmt.Sprintf("missing_race_referenced id=%s key=%s", ref.ID, key))
|
||||
}
|
||||
} else {
|
||||
rep.Details = append(rep.Details, fmt.Sprintf("missing_would_delete id=%s key=%s", ref.ID, key))
|
||||
}
|
||||
}
|
||||
return rep, nil
|
||||
}
|
||||
Reference in New Issue
Block a user