- getFeed: add id DESC as tie-breaker so posts with equal createdAt are not duplicated or lost between pages - moderation: AI verdict false now sets REJECTED instead of ACTIVE - nightly cleanup: invalidate feed and map caches after deleting posts Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
99 lines
4.1 KiB
Java
99 lines
4.1 KiB
Java
package com.krylov.refound.service;
|
||
|
||
import com.krylov.refound.entity.Post;
|
||
import com.krylov.refound.enums.PostStatus;
|
||
import com.krylov.refound.repository.FavoriteRepository;
|
||
import com.krylov.refound.repository.PostRepository;
|
||
import com.krylov.refound.service.redis.MapCacheService;
|
||
import com.krylov.refound.service.redis.PostCacheService;
|
||
import java.time.LocalDateTime;
|
||
import java.util.List;
|
||
import lombok.RequiredArgsConstructor;
|
||
import lombok.extern.slf4j.Slf4j;
|
||
import org.springframework.scheduling.annotation.Scheduled;
|
||
import org.springframework.stereotype.Service;
|
||
import org.springframework.transaction.annotation.Transactional;
|
||
|
||
@Slf4j
|
||
@Service
|
||
@RequiredArgsConstructor
|
||
public class SchedulerService {
|
||
|
||
private final PostRepository postRepository;
|
||
private final FavoriteRepository favoriteRepository;
|
||
private final PostModerationExecutorService postModerationExecutorService;
|
||
private final PostCacheService postCacheService;
|
||
private final MapCacheService mapCacheService;
|
||
|
||
/**
|
||
* Runs every day at 00:01 to delete:
|
||
* 1. Posts with CLOSED status
|
||
* 2. Posts older than 6 months
|
||
*/
|
||
@Scheduled(cron = "0 1 0 * * ?")
|
||
@Transactional
|
||
public void deleteExpiredPosts() {
|
||
log.info("Starting scheduled cleanup of expired posts...");
|
||
|
||
LocalDateTime sixMonthsAgo = LocalDateTime.now().minusMonths(6);
|
||
|
||
// Find and delete posts with CLOSED status
|
||
List<Post> closedPosts = postRepository.findByStatus(PostStatus.CLOSED);
|
||
if (!closedPosts.isEmpty()) {
|
||
// Delete favorites first to avoid foreign key constraint violation
|
||
favoriteRepository.deleteByPostIn(closedPosts);
|
||
log.info("Deleted {} favorites for CLOSED posts", closedPosts.size());
|
||
|
||
postRepository.deleteAll(closedPosts);
|
||
log.info("Deleted {} posts with CLOSED status", closedPosts.size());
|
||
}
|
||
|
||
// Find and delete posts older than 6 months
|
||
List<Post> oldPosts = postRepository.findByCreatedAtBefore(sixMonthsAgo);
|
||
if (!oldPosts.isEmpty()) {
|
||
// Delete favorites first to avoid foreign key constraint violation
|
||
favoriteRepository.deleteByPostIn(oldPosts);
|
||
log.info("Deleted {} favorites for old posts", oldPosts.size());
|
||
|
||
postRepository.deleteAll(oldPosts);
|
||
log.info("Deleted {} posts older than 6 months", oldPosts.size());
|
||
}
|
||
|
||
if (!closedPosts.isEmpty() || !oldPosts.isEmpty()) {
|
||
// Иначе удалённые посты висят в ленте и на карте до TTL кэша
|
||
postCacheService.invalidatePosts();
|
||
mapCacheService.clearMapMarkersCache();
|
||
}
|
||
|
||
log.info("Scheduled cleanup completed successfully");
|
||
}
|
||
|
||
/**
|
||
* Каждые 60 секунд забирает посты, ожидающие модерации, и прогоняет их через
|
||
* ContentModerationFacade. Изображения к этому моменту уже лежат в MinIO
|
||
* (залиты синхронно в PostService.create/update) — оригинальные MultipartFile
|
||
* из запроса уже недоступны (Tomcat удаляет temp-файл сразу после завершения
|
||
* запроса), поэтому скачиваем их заново и оборачиваем в ByteArrayMultipartFile,
|
||
* чтобы не менять сигнатуру ContentModerationFacade.
|
||
*
|
||
* Сама обработка одного поста вынесена в отдельный бин PostModerationExecutor —
|
||
* вызов через него идёт через Spring-прокси, поэтому @Transactional на
|
||
* moderateOne реально применяется (self-invocation внутри этого класса привёл бы
|
||
* к тому, что транзакция не открывалась бы вовсе).
|
||
*/
|
||
@Scheduled(fixedDelay = 60_000)
|
||
public void moderatePendingPosts() {
|
||
List<Long> pending = postRepository.findIdsByStatus(PostStatus.MODERATION);
|
||
if (pending.isEmpty()) {
|
||
return;
|
||
}
|
||
|
||
log.info("На модерации {} постов.", pending.size());
|
||
for (Long postId : pending) {
|
||
postModerationExecutorService.moderateOne(postId);
|
||
}
|
||
}
|
||
|
||
|
||
}
|