package com.krylov.refound.service; import com.krylov.refound.config.MinioProperties; import com.krylov.refound.repository.ImageRepository; import com.krylov.refound.repository.UserRepository; import java.time.Duration; import java.time.Instant; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; import lombok.extern.slf4j.Slf4j; import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; import software.amazon.awssdk.services.s3.model.S3Object; /** * Ночная чистка «сирот» в бакете картинок: файлов, на которые не ссылаются ни * images.url, ни users.avatar_url. Они появляются, когда фото загружено через * POST /api/v1/files и не прикреплено к объявлению, или когда запрос упал между * загрузкой и сохранением. * *

Удаляются только файлы старше {@code storage.orphan-cleanup.min-age} * (по умолчанию сутки) — свежая загрузка может ещё ждать сохранения формы. За * прогон удаляется не больше {@code max-deletes} файлов. Бакет версионируемый: * удалённое ещё 30 дней можно восстановить (StorageStructureService). */ @Slf4j @Service public class OrphanFileCleanupService { private final S3Client s3Client; private final MinioProperties properties; private final ImageRepository imageRepository; private final UserRepository userRepository; private final FileStorageService fileStorageService; private final boolean enabled; private final Duration minAge; private final int maxDeletes; public OrphanFileCleanupService(S3Client s3Client, MinioProperties properties, ImageRepository imageRepository, UserRepository userRepository, FileStorageService fileStorageService, @Value("${storage.orphan-cleanup.enabled:true}") boolean enabled, @Value("${storage.orphan-cleanup.min-age:PT24H}") Duration minAge, @Value("${storage.orphan-cleanup.max-deletes:5000}") int maxDeletes) { this.s3Client = s3Client; this.properties = properties; this.imageRepository = imageRepository; this.userRepository = userRepository; this.fileStorageService = fileStorageService; this.enabled = enabled; this.minAge = minAge; this.maxDeletes = maxDeletes; } @Scheduled(cron = "${storage.orphan-cleanup.cron:0 30 3 * * *}") @SchedulerLock(name = "cleanupOrphanFiles", lockAtMostFor = "PT1H", lockAtLeastFor = "PT1M") public void cleanupOrphanFiles() { if (!enabled) { return; } // Ссылки читаются до листинга: файл, прикреплённый во время прогона, моложе minAge Set referenced = referencedKeys(); Instant olderThan = Instant.now().minus(minAge); int deleted = 0; int scanned = 0; ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(properties.bucket()).build(); for (S3Object object : s3Client.listObjectsV2Paginator(request).contents()) { scanned++; if (object.lastModified() == null || object.lastModified().isAfter(olderThan) || referenced.contains(object.key())) { continue; } if (deleted >= maxDeletes) { log.warn("Чистка файлов: достигнут предел {} удалений за прогон, остальное — в следующий раз", maxDeletes); break; } try { fileStorageService.deleteFile(object.key()); deleted++; } catch (RuntimeException e) { log.warn("Чистка файлов: не удалось удалить {}: {}", object.key(), e.getMessage()); } } log.info("Чистка файлов-сирот: просмотрено {}, удалено {}", scanned, deleted); } /** * Ключи, на которые ссылается БД. Значения приводятся к ключу объекта: в старых * записях может лежать полный URL или путь вида /bucket/key — такие файлы тоже * считаются используемыми. */ Set referencedKeys() { Set keys = new HashSet<>(); Stream.concat(imageRepository.findAllUrls().stream(), userRepository.findAllAvatarUrls().stream()) .map(this::toKey) .forEach(keys::add); return keys; } String toKey(String value) { String key = value; int query = key.indexOf('?'); if (query >= 0) { key = key.substring(0, query); } String bucketPart = "/" + properties.bucket() + "/"; int bucketIndex = key.indexOf(bucketPart); if (bucketIndex >= 0) { key = key.substring(bucketIndex + bucketPart.length()); } else if (key.startsWith("/api/v1/files/")) { key = key.substring("/api/v1/files/".length()); } return key.startsWith("/") ? key.substring(1) : key; } }