package media import ( "context" "fmt" "time" ) // ObjectInfo describes an immutable object without its contents. type ObjectInfo struct { // Key is the server-assigned private coordinate. Key string // ModifiedAt determines eligibility for a grace-protected scan. ModifiedAt time.Time } // OrphanMetadata checks all reservations, not only published files. type OrphanMetadata interface { // HasObject reports whether any state references the key. HasObject(context.Context, string) (bool, error) } // OrphanObjects supports resumable listing and single-object cleanup. type OrphanObjects interface { // List returns a bounded lexicographic page after the given key. List(context.Context, string) ([]ObjectInfo, error) // Remove deletes an explicitly identified unreferenced key. Remove(context.Context, string) error } // OrphanResult reports one page of a safe S3-to-database reconciliation. type OrphanResult struct { // Scanned counts objects examined. Scanned int `json:"scanned"` // Orphans counts old objects with no metadata reservation. Orphans int `json:"orphans"` // Removed counts applied removals. Removed int `json:"removed"` // Next resumes the lexicographic scan. Next string `json:"next"` } // ReconcileOrphans protects fresh and referenced objects, and defaults to dry-run at the CLI. func ReconcileOrphans(ctx context.Context, metadata OrphanMetadata, objects OrphanObjects, after string, grace time.Duration, apply bool) (OrphanResult, error) { var result OrphanResult if grace < time.Hour { return result, fmt.Errorf("reconciliation grace must be at least one hour") } entries, err := objects.List(ctx, after) if err != nil { return result, err } cutoff := time.Now().UTC().Add(-grace) for _, entry := range entries { result.Scanned++ result.Next = entry.Key if entry.ModifiedAt.IsZero() || entry.ModifiedAt.After(cutoff) { continue } referenced, err := metadata.HasObject(ctx, entry.Key) if err != nil { return result, err } if referenced { continue } result.Orphans++ if apply { if err := objects.Remove(ctx, entry.Key); err != nil { return result, err } result.Removed++ } } return result, nil }