Delete orphan files from the image bucket nightly
OrphanFileCleanupService (03:30, ShedLock) lists the bucket and deletes objects older than 24 hours that no images.url or users.avatar_url points to (full URLs in legacy rows are normalised to keys), at most 5000 per run. Such files appear when an upload via POST /api/v1/files is never attached or a request fails between upload and save. Deleted files stay recoverable for 30 days as noncurrent versions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -15,4 +15,8 @@ public interface ImageRepository extends JpaRepository<Image, Long> {
|
||||
/** Один запрос вместо N+1 при сборке админской страницы объявлений. */
|
||||
@Query("select i from Image i where i.post.id in :postIds order by i.id asc")
|
||||
List<Image> findByPostIdIn(@Param("postIds") Collection<Long> postIds);
|
||||
|
||||
/** Все ключи картинок объявлений — для чистки файлов-сирот. */
|
||||
@Query("select i.url from Image i where i.url is not null")
|
||||
List<String> findAllUrls();
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.krylov.refound.repository;
|
||||
|
||||
import com.krylov.refound.entity.User;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
@@ -13,4 +14,8 @@ public interface UserRepository extends JpaRepository<User, Long> {
|
||||
|
||||
@Query("SELECT u.id FROM User u WHERE u.login = :login")
|
||||
Optional<Long> findUserByLogin(@Param("login") String login);
|
||||
|
||||
/** Все ключи аватаров — для чистки файлов-сирот. */
|
||||
@Query("SELECT u.avatarUrl FROM User u WHERE u.avatarUrl IS NOT NULL")
|
||||
List<String> findAllAvatarUrls();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
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 и не прикреплено к объявлению, или когда запрос упал между
|
||||
* загрузкой и сохранением.
|
||||
*
|
||||
* <p>Удаляются только файлы старше {@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<String> 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<String> referencedKeys() {
|
||||
Set<String> 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;
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,14 @@ ai:
|
||||
delay: 500
|
||||
multiplier: 2
|
||||
|
||||
# Ночная чистка файлов без ссылок в бакете картинок (OrphanFileCleanupService)
|
||||
storage:
|
||||
orphan-cleanup:
|
||||
enabled: ${STORAGE_ORPHAN_CLEANUP_ENABLED:true}
|
||||
cron: "0 30 3 * * *"
|
||||
min-age: PT24H # моложе — не трогаем: загрузка может ещё ждать сохранения формы
|
||||
max-deletes: 5000 # предел удалений за прогон
|
||||
|
||||
# Обратное геокодирование (GeocodingService): публичный Nominatim требует
|
||||
# User-Agent с контактом и не больше 1 запроса/с; для нагрузки — свой экземпляр
|
||||
geocoding:
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
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.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
|
||||
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
|
||||
import software.amazon.awssdk.services.s3.model.S3Object;
|
||||
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;
|
||||
|
||||
class OrphanFileCleanupServiceTest {
|
||||
|
||||
@Test
|
||||
void deletesOnlyOldUnreferencedFiles() {
|
||||
S3Client s3 = mock(S3Client.class);
|
||||
Instant old = Instant.now().minus(Duration.ofDays(3));
|
||||
ListObjectsV2Response page = ListObjectsV2Response.builder().contents(
|
||||
S3Object.builder().key("used.jpg").lastModified(old).build(),
|
||||
S3Object.builder().key("avatars/legacy.jpg").lastModified(old).build(),
|
||||
S3Object.builder().key("orphan.jpg").lastModified(old).build(),
|
||||
S3Object.builder().key("fresh.jpg").lastModified(Instant.now()).build()).build();
|
||||
when(s3.listObjectsV2Paginator(any(ListObjectsV2Request.class)))
|
||||
.thenReturn(new ListObjectsV2Iterable(s3, ListObjectsV2Request.builder().build()));
|
||||
when(s3.listObjectsV2(any(ListObjectsV2Request.class))).thenReturn(page);
|
||||
|
||||
MinioProperties properties = new MinioProperties("http://minio", "refound-images", "a", "b", "us-east-1");
|
||||
ImageRepository images = mock(ImageRepository.class);
|
||||
when(images.findAllUrls()).thenReturn(List.of("used.jpg"));
|
||||
UserRepository users = mock(UserRepository.class);
|
||||
// Старая запись аватара хранит полный URL
|
||||
when(users.findAllAvatarUrls()).thenReturn(List.of("http://minio:9010/refound-images/avatars/legacy.jpg?x=1"));
|
||||
FileStorageService storage = mock(FileStorageService.class);
|
||||
|
||||
new OrphanFileCleanupService(s3, properties, images, users, storage, true, Duration.ofHours(24), 100)
|
||||
.cleanupOrphanFiles();
|
||||
|
||||
verify(storage).deleteFile("orphan.jpg");
|
||||
verify(storage, never()).deleteFile("used.jpg");
|
||||
verify(storage, never()).deleteFile("avatars/legacy.jpg");
|
||||
verify(storage, never()).deleteFile("fresh.jpg");
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledJobDoesNothing() {
|
||||
S3Client s3 = mock(S3Client.class);
|
||||
FileStorageService storage = mock(FileStorageService.class);
|
||||
|
||||
new OrphanFileCleanupService(s3, mock(MinioProperties.class), mock(ImageRepository.class),
|
||||
mock(UserRepository.class), storage, false, Duration.ofHours(24), 100).cleanupOrphanFiles();
|
||||
|
||||
verify(storage, never()).deleteFile(anyString());
|
||||
}
|
||||
}
|
||||
@@ -23,3 +23,7 @@ app:
|
||||
|
||||
rate-limit:
|
||||
enabled: false
|
||||
|
||||
storage:
|
||||
orphan-cleanup:
|
||||
enabled: false
|
||||
|
||||
Reference in New Issue
Block a user