package reconcile import ( "context" "fmt" "sort" "time" "mtusi2026lab7/internal/adapter/objectstore" "mtusi2026lab7/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 }