lab4: вложения в S3 (MinIO), reconciler PostgreSQL↔S3, тесты и CI

This commit is contained in:
2026-11-04 20:11:33 +03:00
parent ec540a1a72
commit 77b6e5c2c7
86 changed files with 6921 additions and 2 deletions
+363
View File
@@ -0,0 +1,363 @@
// 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, ни одно сообщение не ссылается → удалить строку
//
// Свежие объекты и намерения (моложе grace) и вложения, на которые ссылаются
// сообщения, не удаляются никогда. Режим по умолчанию — dry-run (только отчёт).
package reconcile
import (
"context"
"errors"
"fmt"
"runtime"
"time"
"github.com/charawein/mtusi2026lab4/internal/domain"
"github.com/charawein/mtusi2026lab4/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"`
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{},
}
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()
}
})
}()
o, okO := <-objs
a, okA := <-rows
for okO || okA {
switch {
case okA && (!okO || a.ObjectKey < o.Key):
rep.RowsScanned++
rc.rowWithoutObject(ctx, a, cutoff)
a, okA = <-rows
case okO && (!okA || o.Key < a.ObjectKey):
rep.ObjectsScanned++
rc.objectWithoutRow(ctx, o, cutoff)
o, okO = <-objs
default:
rep.RowsScanned++
rep.ObjectsScanned++
rc.both(ctx, a, o, cutoff)
a, okA = <-rows
o, okO = <-objs
}
}
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 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 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"]++
}
}
+232
View File
@@ -0,0 +1,232 @@
package reconcile
import (
"bytes"
"context"
"io"
"sort"
"testing"
"time"
"github.com/charawein/mtusi2026lab4/internal/domain"
"github.com/charawein/mtusi2026lab4/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) 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)
}
}