на оценку 5

This commit is contained in:
2026-11-10 16:21:46 +03:00
parent 276dbdad8a
commit 7110afc598
170 changed files with 21149 additions and 30 deletions
+203
View File
@@ -0,0 +1,203 @@
package reconcile
import (
"context"
"fmt"
"sort"
"time"
"mtusi2026lab5/internal/adapter/objectstore"
"mtusi2026lab5/internal/domain"
)
const (
IssueOrphanObject = "orphan_object"
IssueMissingObject = "missing_object"
IssueFailedObject = "failed_object"
IssueReferencedMissing = "referenced_missing_object"
)
type AttachmentRecord struct {
ID string
ObjectKey string
AdditionalObjectKeys []string
Status domain.AttachmentStatus
UpdatedAt time.Time
Referenced bool
}
type MetadataStore interface {
ListAttachmentInventory(ctx context.Context) ([]AttachmentRecord, error)
MarkAttachmentFailedIfUnreferenced(
ctx context.Context,
attachmentID string,
expectedStatus domain.AttachmentStatus,
updatedBefore time.Time,
errorCode string,
updatedAt time.Time,
) (bool, error)
}
type ObjectInventory interface {
List(ctx context.Context, prefix string) ([]objectstore.StoredObject, error)
Delete(ctx context.Context, key string) error
}
type Issue struct {
Kind string `json:"kind"`
AttachmentID string `json:"attachment_id,omitempty"`
ObjectKey string `json:"object_key"`
Protected bool `json:"protected,omitempty"`
Action string `json:"action"`
}
type Result struct {
DryRun bool `json:"dry_run"`
GracePeriod time.Duration `json:"-"`
GracePeriodSeconds int64 `json:"grace_period_seconds"`
ScannedAttachments int `json:"scanned_attachments"`
ScannedObjects int `json:"scanned_objects"`
Issues []Issue `json:"issues"`
DeletedObjects int `json:"deleted_objects"`
FailedAttachments int `json:"failed_attachments"`
Duration time.Duration `json:"-"`
DurationMillis int64 `json:"duration_ms"`
}
type Reconciler struct {
metadata MetadataStore
objects ObjectInventory
now func() time.Time
}
func New(metadata MetadataStore, objects ObjectInventory) (*Reconciler, error) {
if metadata == nil || objects == nil {
return nil, fmt.Errorf("metadata and object stores are required")
}
return &Reconciler{
metadata: metadata,
objects: objects,
now: func() time.Time { return time.Now().UTC() },
}, nil
}
func (r *Reconciler) Run(
ctx context.Context,
gracePeriod time.Duration,
apply bool,
) (Result, error) {
if gracePeriod <= 0 {
return Result{}, fmt.Errorf("grace period must be positive")
}
startedAt := r.now().UTC()
cutoff := startedAt.Add(-gracePeriod)
result := Result{
DryRun: !apply,
GracePeriod: gracePeriod,
GracePeriodSeconds: int64(gracePeriod / time.Second),
Issues: make([]Issue, 0),
}
attachments, err := r.metadata.ListAttachmentInventory(ctx)
if err != nil {
return Result{}, fmt.Errorf("list attachment metadata: %w", err)
}
objects, err := r.objects.List(ctx, "attachments/")
if err != nil {
return Result{}, fmt.Errorf("list attachment objects: %w", err)
}
result.ScannedAttachments = len(attachments)
result.ScannedObjects = len(objects)
attachmentsByKey := make(map[string]AttachmentRecord, len(attachments))
for _, attachment := range attachments {
attachmentsByKey[attachment.ObjectKey] = attachment
for _, objectKey := range attachment.AdditionalObjectKeys {
if objectKey != "" {
attachmentsByKey[objectKey] = attachment
}
}
}
objectsByKey := make(map[string]objectstore.StoredObject, len(objects))
for _, object := range objects {
objectsByKey[object.Key] = object
if _, exists := attachmentsByKey[object.Key]; exists {
continue
}
if object.LastModified.IsZero() || object.LastModified.After(cutoff) {
continue
}
issue := Issue{Kind: IssueOrphanObject, ObjectKey: object.Key, Action: "would_delete"}
if apply {
if err = r.objects.Delete(ctx, object.Key); err != nil {
return result, fmt.Errorf("delete orphan object %q: %w", object.Key, err)
}
issue.Action = "deleted"
result.DeletedObjects++
}
result.Issues = append(result.Issues, issue)
}
for _, attachment := range attachments {
if attachment.UpdatedAt.After(cutoff) {
continue
}
_, objectExists := objectsByKey[attachment.ObjectKey]
switch {
case attachment.Status == domain.AttachmentStatusReady && !objectExists:
issue := Issue{
Kind: IssueMissingObject,
AttachmentID: attachment.ID,
ObjectKey: attachment.ObjectKey,
Protected: attachment.Referenced,
Action: "would_mark_failed",
}
if attachment.Referenced {
issue.Kind = IssueReferencedMissing
issue.Action = "manual_repair_required"
} else if apply {
changed, markError := r.metadata.MarkAttachmentFailedIfUnreferenced(
ctx, attachment.ID, attachment.Status, cutoff,
"reconciler_missing_object", startedAt,
)
if markError != nil {
return result, fmt.Errorf("mark missing attachment %q failed: %w", attachment.ID, markError)
}
if changed {
issue.Action = "marked_failed"
result.FailedAttachments++
} else {
issue.Action = "skipped_concurrent_change"
}
}
result.Issues = append(result.Issues, issue)
case attachment.Status == domain.AttachmentStatusFailed && objectExists:
issue := Issue{
Kind: IssueFailedObject, AttachmentID: attachment.ID,
ObjectKey: attachment.ObjectKey, Protected: attachment.Referenced,
Action: "would_delete",
}
if attachment.Referenced {
issue.Action = "manual_repair_required"
} else if apply {
if err = r.objects.Delete(ctx, attachment.ObjectKey); err != nil {
return result, fmt.Errorf("delete failed attachment object %q: %w", attachment.ObjectKey, err)
}
issue.Action = "deleted"
result.DeletedObjects++
}
result.Issues = append(result.Issues, issue)
}
}
sort.Slice(result.Issues, func(i, j int) bool {
if result.Issues[i].ObjectKey == result.Issues[j].ObjectKey {
return result.Issues[i].Kind < result.Issues[j].Kind
}
return result.Issues[i].ObjectKey < result.Issues[j].ObjectKey
})
result.Duration = r.now().UTC().Sub(startedAt)
result.DurationMillis = result.Duration.Milliseconds()
return result, nil
}
+228
View File
@@ -0,0 +1,228 @@
package reconcile
import (
"context"
"errors"
"testing"
"time"
"mtusi2026lab5/internal/adapter/objectstore"
"mtusi2026lab5/internal/domain"
)
type fakeMetadataStore struct {
records []AttachmentRecord
markError error
skipMark bool
}
func (store *fakeMetadataStore) ListAttachmentInventory(
context.Context,
) ([]AttachmentRecord, error) {
return append([]AttachmentRecord(nil), store.records...), nil
}
func (store *fakeMetadataStore) MarkAttachmentFailedIfUnreferenced(
_ context.Context,
attachmentID string,
expectedStatus domain.AttachmentStatus,
updatedBefore time.Time,
errorCode string,
updatedAt time.Time,
) (bool, error) {
if store.markError != nil {
return false, store.markError
}
if store.skipMark {
return false, nil
}
for index := range store.records {
record := &store.records[index]
if record.ID != attachmentID || record.Status != expectedStatus ||
record.UpdatedAt.After(updatedBefore) || record.Referenced {
continue
}
record.Status = domain.AttachmentStatusFailed
record.UpdatedAt = updatedAt
_ = errorCode
return true, nil
}
return false, nil
}
func TestReconcilerDoesNotTouchActiveAttachments(t *testing.T) {
old := time.Now().UTC().Add(-2 * time.Hour)
metadata := &fakeMetadataStore{
records: []AttachmentRecord{
{
ID: "queued-old", ObjectKey: "attachments/queued-old",
AdditionalObjectKeys: []string{"attachments/queued-old-staging"},
Status: domain.AttachmentStatusQueued, UpdatedAt: old,
},
{
ID: "processing-old", ObjectKey: "attachments/processing-old",
Status: domain.AttachmentStatusProcessing, UpdatedAt: old,
},
},
}
objects := &fakeObjectInventory{objects: map[string]objectstore.StoredObject{
"attachments/queued-old": {Key: "attachments/queued-old", LastModified: old},
"attachments/queued-old-staging": {Key: "attachments/queued-old-staging", LastModified: old},
"attachments/processing-old": {Key: "attachments/processing-old", LastModified: old},
}}
reconciler, err := New(metadata, objects)
if err != nil {
t.Fatal(err)
}
result, err := reconciler.Run(context.Background(), time.Hour, true)
if err != nil {
t.Fatal(err)
}
if result.DeletedObjects != 0 || result.FailedAttachments != 0 {
t.Fatalf("active attachments must not be reconciled as stale: %+v", result)
}
if len(result.Issues) != 0 {
t.Fatalf("active attachments must not produce reconciliation issues: %+v", result.Issues)
}
if len(objects.objects) != 3 {
t.Fatal("reconciler deleted an object belonging to an active attachment")
}
}
type fakeObjectInventory struct {
objects map[string]objectstore.StoredObject
deleteError error
}
func (store *fakeObjectInventory) List(
context.Context,
string,
) ([]objectstore.StoredObject, error) {
objects := make([]objectstore.StoredObject, 0, len(store.objects))
for _, object := range store.objects {
objects = append(objects, object)
}
return objects, nil
}
func (store *fakeObjectInventory) Delete(_ context.Context, key string) error {
if store.deleteError != nil {
return store.deleteError
}
delete(store.objects, key)
return nil
}
func TestReconcilerDryRunApplyAndRepeat(t *testing.T) {
now := time.Now().UTC()
old := now.Add(-2 * time.Hour)
fresh := now.Add(-5 * time.Minute)
metadata := &fakeMetadataStore{records: []AttachmentRecord{
{
ID: "ready-present", ObjectKey: "attachments/ready-present",
AdditionalObjectKeys: []string{"attachments/ready-present-thumbnail"},
Status: domain.AttachmentStatusReady, UpdatedAt: old,
},
{ID: "ready-missing", ObjectKey: "attachments/ready-missing", Status: domain.AttachmentStatusReady, UpdatedAt: old},
{ID: "ready-used-missing", ObjectKey: "attachments/ready-used-missing", Status: domain.AttachmentStatusReady, UpdatedAt: old, Referenced: true},
{ID: "queued-old", ObjectKey: "attachments/queued-old", Status: domain.AttachmentStatusQueued, UpdatedAt: old},
{ID: "failed-old", ObjectKey: "attachments/failed-old", Status: domain.AttachmentStatusFailed, UpdatedAt: old},
{ID: "queued-fresh", ObjectKey: "attachments/queued-fresh", Status: domain.AttachmentStatusQueued, UpdatedAt: fresh},
}}
objects := &fakeObjectInventory{objects: map[string]objectstore.StoredObject{
"attachments/ready-present": {Key: "attachments/ready-present", LastModified: old},
"attachments/ready-present-thumbnail": {Key: "attachments/ready-present-thumbnail", LastModified: old},
"attachments/queued-old": {Key: "attachments/queued-old", LastModified: old},
"attachments/failed-old": {Key: "attachments/failed-old", LastModified: old},
"attachments/orphan-old": {Key: "attachments/orphan-old", LastModified: old},
"attachments/orphan-fresh": {Key: "attachments/orphan-fresh", LastModified: fresh},
}}
reconciler, err := New(metadata, objects)
if err != nil {
t.Fatal(err)
}
dryRun, err := reconciler.Run(context.Background(), time.Hour, false)
if err != nil {
t.Fatal(err)
}
if !dryRun.DryRun || len(dryRun.Issues) != 4 ||
dryRun.DeletedObjects != 0 || dryRun.FailedAttachments != 0 {
t.Fatalf("unexpected dry-run result: %+v", dryRun)
}
if len(objects.objects) != 6 {
t.Fatal("dry-run changed object storage")
}
for _, record := range metadata.records {
if record.ID == "ready-missing" && record.Status != domain.AttachmentStatusReady {
t.Fatal("dry-run changed metadata")
}
}
applied, err := reconciler.Run(context.Background(), time.Hour, true)
if err != nil {
t.Fatal(err)
}
if applied.DeletedObjects != 2 || applied.FailedAttachments != 1 {
t.Fatalf("unexpected apply result: %+v", applied)
}
if _, exists := objects.objects["attachments/orphan-old"]; exists {
t.Fatal("old orphan was not deleted")
}
if _, exists := objects.objects["attachments/orphan-fresh"]; !exists {
t.Fatal("fresh orphan must be protected by grace period")
}
if _, exists := objects.objects["attachments/ready-present"]; !exists {
t.Fatal("healthy object was deleted")
}
if _, exists := objects.objects["attachments/ready-present-thumbnail"]; !exists {
t.Fatal("managed variant object was deleted as an orphan")
}
if _, exists := objects.objects["attachments/queued-old"]; !exists {
t.Fatal("active queued attachment object was deleted")
}
for _, issue := range applied.Issues {
if issue.AttachmentID == "ready-used-missing" &&
(!issue.Protected || issue.Action != "manual_repair_required") {
t.Fatalf("referenced attachment was not protected: %+v", issue)
}
}
repeated, err := reconciler.Run(context.Background(), time.Hour, true)
if err != nil {
t.Fatal(err)
}
if repeated.DeletedObjects != 0 || repeated.FailedAttachments != 0 {
t.Fatalf("repeat must be mutation-idempotent: %+v", repeated)
}
if len(repeated.Issues) != 1 || !repeated.Issues[0].Protected {
t.Fatalf("repeat should retain only protected manual issue: %+v", repeated)
}
}
func TestReconcilerReportsMutationFailures(t *testing.T) {
old := time.Now().UTC().Add(-2 * time.Hour)
metadata := &fakeMetadataStore{records: []AttachmentRecord{
{ID: "missing", ObjectKey: "attachments/missing", Status: domain.AttachmentStatusReady, UpdatedAt: old},
}}
metadata.markError = errors.New("injected database failure")
objects := &fakeObjectInventory{objects: make(map[string]objectstore.StoredObject)}
reconciler, err := New(metadata, objects)
if err != nil {
t.Fatal(err)
}
if _, err = reconciler.Run(context.Background(), time.Hour, true); err == nil {
t.Fatal("injected database mutation failure was hidden")
}
metadata.records = nil
metadata.markError = nil
objects.objects["attachments/orphan"] = objectstore.StoredObject{
Key: "attachments/orphan", LastModified: old,
}
objects.deleteError = errors.New("injected object-store failure")
if _, err = reconciler.Run(context.Background(), time.Hour, true); err == nil {
t.Fatal("injected object-store mutation failure was hidden")
}
}