Fix post deletion, moderation races and cache leftovers
- PostService.delete did not remove favorites (FK without cascade -> 500 once a post was favorited) or chat links; owner, admin and nightly cleanup now share PostDeletionService, which deletes MinIO files only after commit. The nightly job also removes the images of expired posts. - Moderation reads a snapshot in a short transaction, calls AI outside of it and applies the verdict only if the post is still in MODERATION and unchanged, so an edit made during a check can no longer go live unmoderated. Storage/AI outages keep the post in MODERATION instead of rejecting it. - Posts without a category broke PostMapper with an NPE; title/phone/reward and address are checked against column sizes; a long address no longer overflows posts.city; Nominatim outages fall back to the address instead of 503. - Favorites list hides posts that are back in moderation or rejected. - Statistics counters use atomic UPDATEs instead of read-modify-write. - Removed MapCacheService: its version key was bumped but never read. - hibernate.default_batch_fetch_size=50 removes N+1 on images/users; show-sql is off by default. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
import com.krylov.refound.entity.Image;
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.repository.ChatRepository;
|
||||
import com.krylov.refound.repository.FavoriteRepository;
|
||||
import com.krylov.refound.repository.PostRepository;
|
||||
import com.krylov.refound.service.redis.PostCacheService;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
/**
|
||||
* Удаление объявлений — одно для владельца, администратора и ночной чистки.
|
||||
*
|
||||
* <p>На posts ссылаются favorites (внешний ключ без ON DELETE CASCADE) и chats.post_id
|
||||
* (без внешнего ключа). Раньше пользовательское удаление не чистило избранное и падало
|
||||
* с 500, если пост кто-то добавил в избранное.
|
||||
*
|
||||
* <p>Файлы в MinIO удаляются только после коммита: если транзакция откатится,
|
||||
* объявление останется с целыми картинками, а не со ссылками на удалённые файлы.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class PostDeletionService {
|
||||
|
||||
private final PostRepository postRepository;
|
||||
private final FavoriteRepository favoriteRepository;
|
||||
private final ChatRepository chatRepository;
|
||||
private final FileStorageService fileStorageService;
|
||||
private final PostCacheService postCacheService;
|
||||
|
||||
@Transactional
|
||||
public void delete(List<Post> posts) {
|
||||
if (posts.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<String> fileKeys = posts.stream()
|
||||
.flatMap(post -> post.getImages().stream())
|
||||
.map(Image::getUrl)
|
||||
.toList();
|
||||
List<Long> postIds = posts.stream().map(Post::getId).toList();
|
||||
|
||||
favoriteRepository.deleteByPostIn(posts);
|
||||
// Переписка остаётся, просто без ссылки на объявление
|
||||
chatRepository.clearPostReferences(postIds);
|
||||
postRepository.deleteAll(posts);
|
||||
|
||||
deleteFilesAfterCommit(fileKeys);
|
||||
postCacheService.invalidatePosts();
|
||||
log.info("Удалено объявлений: {}, файлов к удалению: {}", posts.size(), fileKeys.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Удаляет файлы из хранилища после коммита текущей транзакции (или сразу, если её нет).
|
||||
* Ошибки хранилища не роняют операцию: файл останется мусором, это лишь warn в логе.
|
||||
*/
|
||||
public void deleteFilesAfterCommit(Collection<String> fileKeys) {
|
||||
if (fileKeys.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<String> keys = List.copyOf(fileKeys);
|
||||
if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||
@Override
|
||||
public void afterCommit() {
|
||||
keys.forEach(PostDeletionService.this::deleteFileQuietly);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
keys.forEach(this::deleteFileQuietly);
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteFileQuietly(String objectKey) {
|
||||
try {
|
||||
fileStorageService.deleteFile(objectKey);
|
||||
} catch (Exception e) {
|
||||
log.warn("Не удалось удалить файл из хранилища: {}", objectKey, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user