405 lines
14 KiB
Go
405 lines
14 KiB
Go
// Package reconcile сверяет метаданные вложений (PostgreSQL) и объекты (S3).
|
||
//
|
||
// Обход — один merge-проход по двум потокам, отсортированным одинаково
|
||
// (object_key COLLATE "C" и лексикографический листинг S3), поэтому память
|
||
// O(1) от числа вложений, а стоимость — O(N) строк + ceil(N/1000) LIST-запросов.
|
||
//
|
||
// Расхождения и безопасные действия:
|
||
//
|
||
// stale_intent строка uploading старше grace (брошенная загрузка) → удалить объект, затем строку
|
||
// orphan_object объект без строки, старше grace → удалить объект (после перепроверки строки)
|
||
// missing_object строка ready без объекта → карантин: status=missing (после перепроверки Stat)
|
||
// size_mismatch строка ready, размер объекта другой → карантин: status=missing
|
||
// restored строка missing, объект снова есть и размер совпадает → status=ready
|
||
// purge_missing строка missing старше grace, ни одно сообщение не ссылается → удалить строку
|
||
// missing_variant у ready-варианта нет объекта → только отчёт (без автоисправления)
|
||
//
|
||
// С lab5 вложения в queued/processing/failed и их staging принадлежат pipeline
|
||
// (lease, retry, retention): reconciler их не трогает. Объекты без строки
|
||
// (например, частичные результаты попытки, закончившейся failed) удаляются как
|
||
// orphan после grace — так же, как в lab4.
|
||
//
|
||
// Свежие объекты и намерения (моложе grace) и вложения, на которые ссылаются
|
||
// сообщения, не удаляются никогда. Режим по умолчанию — dry-run (только отчёт).
|
||
package reconcile
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"fmt"
|
||
"runtime"
|
||
"time"
|
||
|
||
"github.com/charawein/mtusi2026lab6/internal/domain"
|
||
"github.com/charawein/mtusi2026lab6/internal/storage"
|
||
)
|
||
|
||
// Repo — нужные reconciler операции над метаданными.
|
||
type Repo interface {
|
||
StreamByKey(ctx context.Context, prefix string, fn func(*domain.Attachment) error) error
|
||
HasKey(ctx context.Context, key string) (bool, error)
|
||
DeleteStaleIntent(ctx context.Context, id string, cutoff time.Time) (bool, error)
|
||
SetStatus(ctx context.Context, id, from, to string) (bool, error)
|
||
DeleteUnreferencedMissing(ctx context.Context, id string, cutoff time.Time) (bool, error)
|
||
IsReferenced(ctx context.Context, id string) (bool, error)
|
||
}
|
||
|
||
type Options struct {
|
||
Prefix string
|
||
Grace time.Duration
|
||
Apply bool
|
||
Now time.Time // общий «сейчас» для строк и объектов (время БД)
|
||
// MaxItems ограничивает список примеров в отчёте на каждый вид расхождения.
|
||
MaxItems int
|
||
}
|
||
|
||
type Item struct {
|
||
Kind string `json:"kind"`
|
||
Key string `json:"key"`
|
||
AttachmentID string `json:"attachment_id,omitempty"`
|
||
Action string `json:"action"`
|
||
Detail string `json:"detail,omitempty"`
|
||
}
|
||
|
||
type Report struct {
|
||
DryRun bool `json:"dry_run"`
|
||
GraceSeconds float64 `json:"grace_seconds"`
|
||
Cutoff time.Time `json:"cutoff"`
|
||
DurationMS int64 `json:"duration_ms"`
|
||
RowsScanned int `json:"rows_scanned"`
|
||
ObjectsScanned int `json:"objects_scanned"`
|
||
Consistent int `json:"consistent"`
|
||
Found map[string]int `json:"found"`
|
||
Fixed map[string]int `json:"fixed"`
|
||
Skipped map[string]int `json:"skipped"`
|
||
Calls map[string]int `json:"calls"`
|
||
HeapAllocMB float64 `json:"heap_alloc_mb"`
|
||
// WaitMS — сколько merge-цикл простоял в ожидании очередного элемента каждого
|
||
// потока: показывает, кто (S3-листинг или запрос к БД) задаёт время обхода.
|
||
WaitMS map[string]int64 `json:"wait_ms"`
|
||
Errors []string `json:"errors"`
|
||
Items []Item `json:"items"`
|
||
}
|
||
|
||
type reconciler struct {
|
||
repo Repo
|
||
store storage.Store
|
||
opt Options
|
||
rep *Report
|
||
items map[string]int
|
||
}
|
||
|
||
func (r *reconciler) note(kind string, it Item) {
|
||
r.rep.Found[kind]++
|
||
if r.items[kind] < r.opt.MaxItems {
|
||
r.items[kind]++
|
||
r.rep.Items = append(r.rep.Items, it)
|
||
}
|
||
}
|
||
|
||
func (r *reconciler) fail(format string, args ...any) {
|
||
if len(r.rep.Errors) < 100 {
|
||
r.rep.Errors = append(r.rep.Errors, fmt.Sprintf(format, args...))
|
||
}
|
||
}
|
||
|
||
// Run выполняет один проход. Ошибки отдельных действий попадают в отчёт и не
|
||
// прерывают обход; ошибка листинга/запроса прерывает проход целиком.
|
||
func Run(ctx context.Context, repo Repo, store storage.Store, opt Options) (*Report, error) {
|
||
start := time.Now()
|
||
if opt.MaxItems == 0 {
|
||
opt.MaxItems = 50
|
||
}
|
||
cutoff := opt.Now.Add(-opt.Grace)
|
||
rep := &Report{
|
||
DryRun: !opt.Apply, GraceSeconds: opt.Grace.Seconds(), Cutoff: cutoff,
|
||
Found: map[string]int{}, Fixed: map[string]int{}, Skipped: map[string]int{}, Calls: map[string]int{},
|
||
Errors: []string{}, Items: []Item{}, WaitMS: map[string]int64{},
|
||
}
|
||
rc := &reconciler{repo: repo, store: store, opt: opt, rep: rep, items: map[string]int{}}
|
||
|
||
ctx, cancel := context.WithCancel(ctx)
|
||
defer cancel()
|
||
|
||
objs := make(chan storage.Object, 512)
|
||
objErr := make(chan error, 1)
|
||
go func() {
|
||
defer close(objs)
|
||
objErr <- store.List(ctx, opt.Prefix, func(o storage.Object) error {
|
||
select {
|
||
case objs <- o:
|
||
return nil
|
||
case <-ctx.Done():
|
||
return ctx.Err()
|
||
}
|
||
})
|
||
}()
|
||
rows := make(chan *domain.Attachment, 512)
|
||
rowErr := make(chan error, 1)
|
||
go func() {
|
||
defer close(rows)
|
||
rowErr <- repo.StreamByKey(ctx, opt.Prefix, func(a *domain.Attachment) error {
|
||
select {
|
||
case rows <- a:
|
||
return nil
|
||
case <-ctx.Done():
|
||
return ctx.Err()
|
||
}
|
||
})
|
||
}()
|
||
|
||
var waitS3, waitDB time.Duration
|
||
nextObj := func() (storage.Object, bool) {
|
||
t := time.Now()
|
||
o, ok := <-objs
|
||
waitS3 += time.Since(t)
|
||
return o, ok
|
||
}
|
||
nextRow := func() (*domain.Attachment, bool) {
|
||
t := time.Now()
|
||
a, ok := <-rows
|
||
waitDB += time.Since(t)
|
||
return a, ok
|
||
}
|
||
o, okO := nextObj()
|
||
a, okA := nextRow()
|
||
for okO || okA {
|
||
switch {
|
||
case okA && (!okO || a.ObjectKey < o.Key):
|
||
rep.RowsScanned++
|
||
rc.rowWithoutObject(ctx, a, cutoff)
|
||
a, okA = nextRow()
|
||
case okO && (!okA || o.Key < a.ObjectKey):
|
||
rep.ObjectsScanned++
|
||
rc.objectWithoutRow(ctx, o, cutoff)
|
||
o, okO = nextObj()
|
||
default:
|
||
rep.RowsScanned++
|
||
rep.ObjectsScanned++
|
||
rc.both(ctx, a, o, cutoff)
|
||
a, okA = nextRow()
|
||
o, okO = nextObj()
|
||
}
|
||
}
|
||
rep.WaitMS["s3_list"] = waitS3.Milliseconds()
|
||
rep.WaitMS["db_stream"] = waitDB.Milliseconds()
|
||
if err := <-objErr; err != nil {
|
||
return rep, fmt.Errorf("list objects: %w", err)
|
||
}
|
||
if err := <-rowErr; err != nil {
|
||
return rep, fmt.Errorf("stream rows: %w", err)
|
||
}
|
||
rep.Calls["s3_list_pages"] = (rep.ObjectsScanned + 999) / 1000
|
||
var ms runtime.MemStats
|
||
runtime.ReadMemStats(&ms)
|
||
rep.HeapAllocMB = float64(ms.HeapAlloc) / (1 << 20)
|
||
rep.DurationMS = time.Since(start).Milliseconds()
|
||
return rep, nil
|
||
}
|
||
|
||
func (r *reconciler) rowWithoutObject(ctx context.Context, a *domain.Attachment, cutoff time.Time) {
|
||
switch a.Status {
|
||
case "variant":
|
||
if r.objectExists(ctx, a.ObjectKey) {
|
||
r.rep.Skipped["recheck_object_present"]++
|
||
return
|
||
}
|
||
r.note("missing_variant", Item{Kind: "missing_variant", Key: a.ObjectKey, AttachmentID: a.ID, Action: "report"})
|
||
case "staging", domain.AttachmentQueued, domain.AttachmentProcessing, domain.AttachmentFailed:
|
||
r.rep.Skipped["owned_by_pipeline"]++
|
||
case domain.AttachmentUploading:
|
||
if !a.UpdatedAt.Before(cutoff) {
|
||
r.rep.Skipped["fresh_intent"]++ // загрузка может быть в процессе
|
||
return
|
||
}
|
||
r.staleIntent(ctx, a, false)
|
||
case domain.AttachmentReady:
|
||
// Листинг мог начаться раньше, чем объект записан: перепроверяем точечно.
|
||
if r.objectExists(ctx, a.ObjectKey) {
|
||
r.rep.Skipped["recheck_object_present"]++
|
||
return
|
||
}
|
||
r.quarantine(ctx, a, "missing_object", "")
|
||
case domain.AttachmentMissing:
|
||
r.purgeMissing(ctx, a, cutoff)
|
||
}
|
||
}
|
||
|
||
func (r *reconciler) objectWithoutRow(ctx context.Context, o storage.Object, cutoff time.Time) {
|
||
if !o.LastModified.Before(cutoff) {
|
||
r.rep.Skipped["fresh_object"]++
|
||
return
|
||
}
|
||
// Строка могла появиться после начала обхода — перепроверяем перед удалением.
|
||
r.rep.Calls["db_haskey"]++
|
||
has, err := r.repo.HasKey(ctx, o.Key)
|
||
if err != nil {
|
||
r.fail("haskey %s: %v", o.Key, err)
|
||
return
|
||
}
|
||
if has {
|
||
r.rep.Skipped["recheck_row_present"]++
|
||
return
|
||
}
|
||
it := Item{Kind: "orphan_object", Key: o.Key, Action: "delete_object",
|
||
Detail: fmt.Sprintf("size=%d modified=%s", o.Size, o.LastModified.UTC().Format(time.RFC3339))}
|
||
if !r.opt.Apply {
|
||
it.Action = "would_delete_object"
|
||
r.note("orphan_object", it)
|
||
return
|
||
}
|
||
r.rep.Calls["s3_delete"]++
|
||
if err := r.store.Delete(ctx, o.Key); err != nil {
|
||
r.fail("delete orphan %s: %v", o.Key, err)
|
||
return
|
||
}
|
||
r.note("orphan_object", it)
|
||
r.rep.Fixed["orphan_object"]++
|
||
}
|
||
|
||
func (r *reconciler) both(ctx context.Context, a *domain.Attachment, o storage.Object, cutoff time.Time) {
|
||
switch a.Status {
|
||
case "variant":
|
||
if o.Size != a.SizeBytes {
|
||
r.note("variant_size_mismatch", Item{Kind: "variant_size_mismatch", Key: a.ObjectKey, AttachmentID: a.ID,
|
||
Action: "report", Detail: fmt.Sprintf("db=%d s3=%d", a.SizeBytes, o.Size)})
|
||
return
|
||
}
|
||
r.rep.Consistent++
|
||
case "staging", domain.AttachmentQueued, domain.AttachmentProcessing, domain.AttachmentFailed:
|
||
r.rep.Consistent++
|
||
case domain.AttachmentUploading:
|
||
if !a.UpdatedAt.Before(cutoff) {
|
||
r.rep.Skipped["fresh_intent"]++
|
||
return
|
||
}
|
||
r.staleIntent(ctx, a, true)
|
||
case domain.AttachmentReady:
|
||
if o.Size != a.SizeBytes {
|
||
r.quarantine(ctx, a, "size_mismatch", fmt.Sprintf("db=%d s3=%d", a.SizeBytes, o.Size))
|
||
return
|
||
}
|
||
r.rep.Consistent++
|
||
case domain.AttachmentMissing:
|
||
if o.Size != a.SizeBytes {
|
||
r.purgeMissing(ctx, a, cutoff)
|
||
return
|
||
}
|
||
it := Item{Kind: "restored", Key: a.ObjectKey, AttachmentID: a.ID, Action: "set_ready"}
|
||
if !r.opt.Apply {
|
||
it.Action = "would_set_ready"
|
||
r.note("restored", it)
|
||
return
|
||
}
|
||
r.rep.Calls["db_update"]++
|
||
ok, err := r.repo.SetStatus(ctx, a.ID, domain.AttachmentMissing, domain.AttachmentReady)
|
||
if err != nil {
|
||
r.fail("restore %s: %v", a.ID, err)
|
||
return
|
||
}
|
||
r.note("restored", it)
|
||
if ok {
|
||
r.rep.Fixed["restored"]++
|
||
}
|
||
}
|
||
}
|
||
|
||
func (r *reconciler) objectExists(ctx context.Context, key string) bool {
|
||
r.rep.Calls["s3_stat"]++
|
||
_, err := r.store.Stat(ctx, key)
|
||
if err == nil {
|
||
return true
|
||
}
|
||
if !errors.Is(err, storage.ErrNotFound) {
|
||
r.fail("stat %s: %v", key, err)
|
||
return true // при ошибке хранилища ничего не трогаем
|
||
}
|
||
return false
|
||
}
|
||
|
||
func (r *reconciler) staleIntent(ctx context.Context, a *domain.Attachment, hasObject bool) {
|
||
it := Item{Kind: "stale_intent", Key: a.ObjectKey, AttachmentID: a.ID, Action: "delete_intent",
|
||
Detail: "updated_at=" + a.UpdatedAt.UTC().Format(time.RFC3339)}
|
||
if hasObject {
|
||
it.Action = "delete_object_and_intent"
|
||
}
|
||
if !r.opt.Apply {
|
||
it.Action = "would_" + it.Action
|
||
r.note("stale_intent", it)
|
||
return
|
||
}
|
||
// Сначала объект: если упадём между шагами, останется намерение без объекта,
|
||
// и следующий проход его доберёт (обратный порядок оставил бы сироту без учёта).
|
||
if hasObject {
|
||
r.rep.Calls["s3_delete"]++
|
||
if err := r.store.Delete(ctx, a.ObjectKey); err != nil {
|
||
r.fail("delete intent object %s: %v", a.ObjectKey, err)
|
||
return
|
||
}
|
||
}
|
||
r.rep.Calls["db_delete"]++
|
||
ok, err := r.repo.DeleteStaleIntent(ctx, a.ID, r.opt.Now.Add(-r.opt.Grace))
|
||
if err != nil {
|
||
r.fail("delete intent %s: %v", a.ID, err)
|
||
return
|
||
}
|
||
r.note("stale_intent", it)
|
||
if ok {
|
||
r.rep.Fixed["stale_intent"]++
|
||
}
|
||
}
|
||
|
||
func (r *reconciler) quarantine(ctx context.Context, a *domain.Attachment, kind, detail string) {
|
||
it := Item{Kind: kind, Key: a.ObjectKey, AttachmentID: a.ID, Action: "quarantine", Detail: detail}
|
||
if !r.opt.Apply {
|
||
it.Action = "would_quarantine"
|
||
r.note(kind, it)
|
||
return
|
||
}
|
||
r.rep.Calls["db_update"]++
|
||
ok, err := r.repo.SetStatus(ctx, a.ID, domain.AttachmentReady, domain.AttachmentMissing)
|
||
if err != nil {
|
||
r.fail("quarantine %s: %v", a.ID, err)
|
||
return
|
||
}
|
||
r.note(kind, it)
|
||
if ok {
|
||
r.rep.Fixed[kind]++
|
||
}
|
||
}
|
||
|
||
// purgeMissing удаляет запись карантина, только если она старше grace и на неё
|
||
// не ссылается ни одно сообщение. Используемые вложения остаются (их история цела).
|
||
func (r *reconciler) purgeMissing(ctx context.Context, a *domain.Attachment, cutoff time.Time) {
|
||
if !a.UpdatedAt.Before(cutoff) {
|
||
r.rep.Skipped["fresh_missing"]++
|
||
return
|
||
}
|
||
r.rep.Calls["db_referenced"]++
|
||
ref, err := r.repo.IsReferenced(ctx, a.ID)
|
||
if err != nil {
|
||
r.fail("referenced %s: %v", a.ID, err)
|
||
return
|
||
}
|
||
if ref {
|
||
r.rep.Skipped["referenced_missing_kept"]++
|
||
return
|
||
}
|
||
it := Item{Kind: "purge_missing", Key: a.ObjectKey, AttachmentID: a.ID, Action: "delete_row"}
|
||
if !r.opt.Apply {
|
||
it.Action = "would_delete_row"
|
||
r.note("purge_missing", it)
|
||
return
|
||
}
|
||
r.rep.Calls["db_delete"]++
|
||
ok, err := r.repo.DeleteUnreferencedMissing(ctx, a.ID, cutoff)
|
||
if err != nil {
|
||
r.fail("purge %s: %v", a.ID, err)
|
||
return
|
||
}
|
||
r.note("purge_missing", it)
|
||
if ok {
|
||
r.rep.Fixed["purge_missing"]++
|
||
}
|
||
}
|