Files
nahodka-back/src/main/java/com/krylov/refound/service/OrphanFileCleanupService.java
SlimusMinus 4ff61d8eda 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>
2026-10-20 01:42:39 +03:00

121 lines
5.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
}
}