package reconcile import ( "bytes" "context" "io" "sort" "testing" "time" "github.com/charawein/mtusi2026lab6/internal/domain" "github.com/charawein/mtusi2026lab6/internal/storage" ) type fakeStore struct{ objs map[string]storage.Object } func (f *fakeStore) Put(_ context.Context, key string, r io.Reader, size int64, _ string) error { f.objs[key] = storage.Object{Key: key, Size: size, LastModified: time.Now()} return nil } func (f *fakeStore) Get(context.Context, string) (io.ReadCloser, int64, error) { return io.NopCloser(bytes.NewReader(nil)), 0, nil } func (f *fakeStore) Stat(_ context.Context, key string) (storage.Object, error) { o, ok := f.objs[key] if !ok { return o, storage.ErrNotFound } return o, nil } func (f *fakeStore) Delete(_ context.Context, key string) error { delete(f.objs, key); return nil } func (f *fakeStore) Copy(_ context.Context, src, dst string) error { o, ok := f.objs[src] if !ok { return storage.ErrNotFound } o.Key = dst f.objs[dst] = o return nil } func (f *fakeStore) List(_ context.Context, prefix string, fn func(storage.Object) error) error { keys := make([]string, 0, len(f.objs)) for k := range f.objs { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { if err := fn(f.objs[k]); err != nil { return err } } return nil } type fakeRepo struct { rows map[string]*domain.Attachment // by id refs map[string]bool } func (f *fakeRepo) StreamByKey(_ context.Context, _ string, fn func(*domain.Attachment) error) error { list := make([]*domain.Attachment, 0, len(f.rows)) for _, a := range f.rows { c := *a list = append(list, &c) } sort.Slice(list, func(i, j int) bool { return list[i].ObjectKey < list[j].ObjectKey }) for _, a := range list { if err := fn(a); err != nil { return err } } return nil } func (f *fakeRepo) HasKey(_ context.Context, key string) (bool, error) { for _, a := range f.rows { if a.ObjectKey == key { return true, nil } } return false, nil } func (f *fakeRepo) DeleteStaleIntent(_ context.Context, id string, cutoff time.Time) (bool, error) { a, ok := f.rows[id] if !ok || a.Status != domain.AttachmentUploading || !a.UpdatedAt.Before(cutoff) { return false, nil } delete(f.rows, id) return true, nil } func (f *fakeRepo) SetStatus(_ context.Context, id, from, to string) (bool, error) { a, ok := f.rows[id] if !ok || a.Status != from { return false, nil } a.Status = to a.UpdatedAt = now return true, nil } func (f *fakeRepo) DeleteUnreferencedMissing(_ context.Context, id string, cutoff time.Time) (bool, error) { a, ok := f.rows[id] if !ok || a.Status != domain.AttachmentMissing || !a.UpdatedAt.Before(cutoff) || f.refs[id] { return false, nil } delete(f.rows, id) return true, nil } func (f *fakeRepo) IsReferenced(_ context.Context, id string) (bool, error) { return f.refs[id], nil } var now = time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC) const grace = time.Hour func old() time.Time { return now.Add(-2 * grace) } func fresh() time.Time { return now.Add(-time.Minute) } func setup() (*fakeRepo, *fakeStore) { r := &fakeRepo{rows: map[string]*domain.Attachment{}, refs: map[string]bool{}} s := &fakeStore{objs: map[string]storage.Object{}} row := func(id, status string, size int64, at time.Time) { r.rows[id] = &domain.Attachment{ID: id, ObjectKey: "a/c/" + id, Status: status, SizeBytes: size, UpdatedAt: at} } obj := func(id string, size int64, at time.Time) { s.objs["a/c/"+id] = storage.Object{Key: "a/c/" + id, Size: size, LastModified: at} } // согласованное row("ok", domain.AttachmentReady, 10, old()) obj("ok", 10, old()) // брошенная загрузка с объектом и без row("stale1", domain.AttachmentUploading, 0, old()) obj("stale1", 7, old()) row("stale2", domain.AttachmentUploading, 0, old()) // загрузка в процессе — не трогать row("inflight", domain.AttachmentUploading, 0, fresh()) obj("inflight", 5, fresh()) // сирота старая и свежая obj("orphan", 3, old()) obj("orphan-fresh", 3, fresh()) // ready без объекта: используемое и нет row("lost-used", domain.AttachmentReady, 9, old()) r.refs["lost-used"] = true row("lost-free", domain.AttachmentReady, 9, old()) // подменённый размер row("resized", domain.AttachmentReady, 10, old()) obj("resized", 11, old()) return r, s } func run(t *testing.T, r *fakeRepo, s *fakeStore, apply bool, at time.Time) *Report { t.Helper() rep, err := Run(context.Background(), r, s, Options{Prefix: "a/", Grace: grace, Apply: apply, Now: at}) if err != nil { t.Fatal(err) } if len(rep.Errors) > 0 { t.Fatalf("errors: %v", rep.Errors) } return rep } func TestDryRunChangesNothing(t *testing.T) { r, s := setup() nRows, nObjs := len(r.rows), len(s.objs) rep := run(t, r, s, false, now) if len(r.rows) != nRows || len(s.objs) != nObjs || r.rows["lost-free"].Status != domain.AttachmentReady { t.Fatal("dry-run mutated state") } want := map[string]int{"stale_intent": 2, "orphan_object": 1, "missing_object": 2, "size_mismatch": 1} for k, v := range want { if rep.Found[k] != v { t.Errorf("found[%s]=%d want %d (%v)", k, rep.Found[k], v, rep.Found) } } if len(rep.Fixed) != 0 { t.Errorf("dry-run fixed %v", rep.Fixed) } } func TestApplyFixesAndIsIdempotent(t *testing.T) { r, s := setup() run(t, r, s, true, now) for _, id := range []string{"stale1", "stale2"} { if _, ok := r.rows[id]; ok { t.Errorf("stale intent %s not removed", id) } } if _, ok := s.objs["a/c/stale1"]; ok { t.Error("stale intent object not removed") } if _, ok := s.objs["a/c/orphan"]; ok { t.Error("old orphan not removed") } // Свежие — никогда. if _, ok := s.objs["a/c/orphan-fresh"]; !ok { t.Error("fresh orphan deleted") } if _, ok := r.rows["inflight"]; !ok { t.Error("in-flight intent deleted") } if _, ok := s.objs["a/c/inflight"]; !ok { t.Error("in-flight object deleted") } for _, id := range []string{"lost-used", "lost-free", "resized"} { if r.rows[id].Status != domain.AttachmentMissing { t.Errorf("%s not quarantined", id) } } if r.rows["ok"].Status != domain.AttachmentReady { t.Error("consistent row touched") } // Повтор сразу: исправлять нечего, карантин ещё моложе grace. rep := run(t, r, s, true, now) if len(rep.Fixed) != 0 { t.Errorf("second pass fixed %v", rep.Fixed) } // Через grace: неиспользуемая запись карантина удаляется, используемая остаётся. later := now.Add(2 * grace) run(t, r, s, true, later) if _, ok := r.rows["lost-free"]; ok { t.Error("unreferenced missing row not purged") } if _, ok := r.rows["lost-used"]; !ok { t.Error("referenced missing row deleted") } if _, ok := s.objs["a/c/orphan-fresh"]; ok { t.Error("orphan not removed after grace") } } func TestRestoredObjectLeavesQuarantine(t *testing.T) { r, s := setup() run(t, r, s, true, now) // Объект вернули (например, из бэкапа) с правильным размером. s.objs["a/c/lost-used"] = storage.Object{Key: "a/c/lost-used", Size: 9, LastModified: now} rep := run(t, r, s, true, now) if rep.Fixed["restored"] != 1 || r.rows["lost-used"].Status != domain.AttachmentReady { t.Errorf("restore failed: %v %s", rep.Fixed, r.rows["lost-used"].Status) } }