package service import ( "context" "highload/internal/repository" "highload/internal/storage" "strings" "time" ) type AttachmentCleanupOptions struct { GracePeriod time.Duration DryRun bool ListTimeout time.Duration } type AttachmentCleanupService struct { repo repository.AttachmentRepository objects storage.ObjectCleanup options *AttachmentCleanupOptions } type OrphanReport struct { Pages int `json:"s3_pages"` Objects int `json:"objects_scanned"` Checked int `json:"checked_in_db"` Busy int `json:"busy"` Candidates int `json:"orphan_candidates"` Deleted int `json:"objects_deleted"` } func NewAttachmentCleanupService(repo repository.AttachmentRepository, objects storage.ObjectCleanup, options *AttachmentCleanupOptions) *AttachmentCleanupService { return &AttachmentCleanupService{repo: repo, objects: objects, options: options} } func (s *AttachmentCleanupService) RunOnce(ctx context.Context) error { _, err := s.ScanOrphans(ctx) return err } func (s *AttachmentCleanupService) ScanOrphans(ctx context.Context) (OrphanReport, error) { var report OrphanReport cutoff := time.Now().Add(-s.options.GracePeriod) var token *string for { if err := ctx.Err(); err != nil { return report, err } listCtx, cancel := context.WithTimeout(ctx, s.options.ListTimeout) objects, nextToken, err := s.objects.ListPage(listCtx, token, attachmentObjectPrefix) cancel() if err != nil { return report, err } report.Pages++ for _, obj := range objects { report.Objects++ if !strings.HasPrefix(obj.Key, attachmentObjectPrefix) || obj.LastModified.IsZero() || !obj.LastModified.Before(cutoff) { continue } acquired, err := s.repo.WithObjectKeyLock(ctx, obj.Key, func(txCtx context.Context, txRepo repository.AttachmentTx) error { exists, err := txRepo.ExistsByObjectKey(txCtx, obj.Key) if err != nil { return err } report.Checked++ if exists { return nil } report.Candidates++ if s.options.DryRun { return nil } if err := s.objects.Delete(txCtx, obj.Key); err != nil { return err } report.Deleted++ return nil }) if err != nil { return report, err } if !acquired { report.Busy++ } } if nextToken == nil { return report, ctx.Err() } token = nextToken } }