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