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:
SlimusMinus
2026-10-20 01:02:12 +03:00
parent 98e6789b7e
commit 6e001fbc41
18 changed files with 397 additions and 328 deletions

View File

@@ -2,7 +2,6 @@ package com.krylov.refound.config;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.krylov.refound.dto.CachedMapMarkers;
import com.krylov.refound.dto.CachedPostPage;
import com.krylov.refound.dto.MapMarkerDto;
import java.util.List;
@@ -21,11 +20,6 @@ public class RedisConfig {
return buildTemplate(connectionFactory, objectMapper, CachedPostPage.class);
}
@Bean
public RedisTemplate<String, CachedMapMarkers> feedRedisTemplate(RedisConnectionFactory connectionFactory, ObjectMapper objectMapper) {
return buildTemplate(connectionFactory, objectMapper, CachedMapMarkers.class);
}
private static <T> RedisTemplate<String, T> buildTemplate(RedisConnectionFactory connectionFactory, ObjectMapper objectMapper, Class<T> type) {
// Своя копия: изменения веб-настроек ObjectMapper не должны ломать формат кэша,
// а неизвестные поля в старых записях не должны валить десериализацию

View File

@@ -8,6 +8,7 @@ import com.krylov.refound.exception.ApiException;
import com.krylov.refound.search.PostFeedFilter;
import com.krylov.refound.search.SearchSuggestService;
import com.krylov.refound.service.PostService;
import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -40,8 +41,8 @@ public class PostController {
private final SearchSuggestService searchSuggestService;
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public PostRequest create(@ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
log.info("create post {}", request.toString());
public PostRequest create(@Valid @ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
log.info("create post type={}, title='{}'", request.getType(), request.getTitle());
return service.create(request, images);
}

View File

@@ -1,14 +0,0 @@
package com.krylov.refound.dto;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CachedMapMarkers {
private List<MapMarkerDto> content;
}

View File

@@ -21,7 +21,8 @@ public interface PostMapper {
@Mapping(source = "user.id", target = "userId")
@Mapping(source = "user.login", target = "userEmail")
@Mapping(source = "images", target = "images", qualifiedByName = "imagesToUrls")
@Mapping(target = "category", expression = "java(post.getCategory().getDisplayName())")
// Категория необязательна: без проверки на null пост без категории ронял ленту с 500
@Mapping(target = "category", expression = "java(post.getCategory() == null ? null : post.getCategory().getDisplayName())")
@Mapping(source = "isReward", target = "reward")
@Mapping(source = "reward", target = "rewardText")
@Mapping(source = "rulesAccepted", target = "rulesAccepted", qualifiedByName = "booleanToString")

View File

@@ -1,6 +1,7 @@
package com.krylov.refound.repository;
import com.krylov.refound.entity.Chat;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
@@ -30,6 +31,6 @@ public interface ChatRepository extends JpaRepository<Chat, Long> {
* У posts нет ON DELETE CASCADE, поэтому без этого удаление падало бы с 500.
*/
@Modifying
@Query("UPDATE Chat c SET c.postId = NULL WHERE c.postId = :postId")
int clearPostReference(@Param("postId") Long postId);
@Query("UPDATE Chat c SET c.postId = NULL WHERE c.postId IN :postIds")
int clearPostReferences(@Param("postIds") Collection<Long> postIds);
}

View File

@@ -2,7 +2,18 @@ package com.krylov.refound.repository;
import com.krylov.refound.entity.Statistics;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface StatisticsRepository extends JpaRepository<Statistics, Long> {
/** Атомарный инкремент: read-modify-write в Java терял обновления при параллельных запросах. */
@Modifying
@Query("update Statistics s set s.postsCreated = s.postsCreated + 1 where s.id = :id")
int incrementCreated(@Param("id") Long id);
@Modifying
@Query("update Statistics s set s.postsFound = s.postsFound + 1 where s.id = :id")
int incrementFound(@Param("id") Long id);
}

View File

@@ -9,8 +9,8 @@ import com.krylov.refound.exception.ApiException;
import com.krylov.refound.mapper.PostMapper;
import com.krylov.refound.repository.FavoriteRepository;
import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.util.PostVisibility;
import java.util.List;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
@@ -53,30 +53,32 @@ public class FavoriteService {
return repository.findByUser(user)
.stream()
.map(Favorite::getPost)
.filter(post -> isVisibleTo(post, user))
.map(mapper::toResponse)
.toList();
}
@Transactional(readOnly = true)
public List<PostResponse> getAllFavoritesPosts() {
User user = userService.getCurrentUser();
if (user == null) {
return List.of();
}
List<Long> favoritePostIds = repository.findPostIdsByUserId(user.getId());
if (favoritePostIds.isEmpty()) {
return List.of();
}
List<Post> posts = postRepository.findAllById(favoritePostIds);
List<Long> postIds = posts.stream()
.map(Post::getId)
.toList();
return posts.stream()
return postRepository.findAllById(favoritePostIds).stream()
.filter(post -> isVisibleTo(post, user))
.map(post -> postService.toResponse(post, true))
.toList();
}
/**
* Пост из избранного мог уйти на повторную модерацию (после правки) или быть
* отклонён — такой виден только владельцу, как и в ленте.
*/
private static boolean isVisibleTo(Post post, User user) {
return PostVisibility.FEED_VISIBLE_STATUSES.contains(post.getStatus())
|| post.getUser().getId().equals(user.getId());
}
}

View File

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

View File

@@ -1,82 +1,162 @@
package com.krylov.refound.service;
import com.krylov.refound.ai.exception.AiBadRequestException;
import com.krylov.refound.ai.exception.ContentBlockedException;
import com.krylov.refound.ai.facade.ContentModerationFacade;
import com.krylov.refound.dto.DownloadedFile;
import com.krylov.refound.entity.Image;
import com.krylov.refound.entity.Post;
import com.krylov.refound.enums.PostStatus;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.service.redis.MapCacheService;
import com.krylov.refound.service.redis.PostCacheService;
import com.krylov.refound.util.ByteArrayMultipartFile;
import java.util.HashSet;
import java.util.List;
import lombok.RequiredArgsConstructor;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;
/**
* Вынесено из SchedulerService отдельным бином специально: вызов moderateOne(post)
* из цикла в том же классе был бы self-invocation и обходил бы Spring-прокси,
* из-за чего @Transactional на методе не действовал бы во время выполнения
* (post.getImages() как раз требует активной транзакции — это ленивая коллекция).
* Модерация одного поста. Вынесено из SchedulerService отдельным бином, чтобы
* транзакции работали через Spring-прокси.
*
* <p>Пост проверяется в три шага: короткая транзакция читает снимок поста
* (текст и ключи картинок), затем без транзакции скачиваются картинки и идёт
* вызов AI (с ретраями это десятки секунд — держать всё это время соединение
* с БД незачем), и в конце новая транзакция ставит статус. Статус ставится,
* только если пост всё ещё на модерации и не менялся с момента снимка: иначе
* правка, сделанная во время проверки, стала бы ACTIVE без модерации.
*/
@Component
@Slf4j
@RequiredArgsConstructor
public class PostModerationExecutorService {
private final PostRepository postRepository;
private final ContentModerationFacade contentModerationFacade;
private final FileStorageService fileStorageService;
private final PostCacheService postCacheService;
private final MapCacheService mapCacheService;
private final TransactionTemplate transactionTemplate;
public PostModerationExecutorService(PostRepository postRepository,
ContentModerationFacade contentModerationFacade, FileStorageService fileStorageService,
PostCacheService postCacheService, PlatformTransactionManager transactionManager) {
this.postRepository = postRepository;
this.contentModerationFacade = contentModerationFacade;
this.fileStorageService = fileStorageService;
this.postCacheService = postCacheService;
this.transactionTemplate = new TransactionTemplate(transactionManager);
}
/** Что именно проверяла модерация. */
record Snapshot(Long postId, String title, String description, List<String> imageKeys) {
}
@Transactional
public void moderateOne(Long postId) {
Post post = postRepository.findById(postId).orElse(null);
if (post == null) {
log.warn("Пост {} не найден на момент модерации, пропускаем", postId);
Snapshot snapshot = transactionTemplate.execute(status -> loadSnapshot(postId));
if (snapshot == null) {
log.debug("Пост {} уже не на модерации или удалён, пропускаем", postId);
return;
}
PostStatus verdict = moderate(snapshot);
if (verdict == null) {
return;
}
Boolean applied = transactionTemplate.execute(status -> applyVerdict(snapshot, verdict));
if (Boolean.TRUE.equals(applied) && verdict == PostStatus.ACTIVE) {
// Пост впервые становится виден публике — и в ленте, и на карте
postCacheService.invalidatePosts();
}
}
private Snapshot loadSnapshot(Long postId) {
Post post = postRepository.findById(postId).orElse(null);
if (post == null || post.getStatus() != PostStatus.MODERATION) {
return null;
}
return new Snapshot(post.getId(), post.getTitle(), post.getDescription(), imageKeys(post));
}
/**
* @return ACTIVE или REJECTED; null — решения нет (AI или хранилище недоступны),
* пост остаётся на модерации и проверяется при следующем запуске
*/
PostStatus moderate(Snapshot snapshot) {
Long postId = snapshot.postId();
try {
List<MultipartFile> images = post.getImages().stream()
.map(Image::getUrl)
List<MultipartFile> images = snapshot.imageKeys().stream()
.map(fileStorageService::downloadFileRaw)
.map(this::toMultipartFile)
.toList();
Boolean approved = contentModerationFacade.moderate(post.getTitle(), post.getDescription(), images);
Boolean approved = contentModerationFacade.moderate(snapshot.title(), snapshot.description(), images);
if (approved == null) {
log.warn("Пост {} не отмодерирован из-за недоступности AI, статус не меняем", post.getId());
return;
log.warn("Пост {} не отмодерирован из-за недоступности AI, статус не меняем", postId);
return null;
}
return approved ? PostStatus.ACTIVE : PostStatus.REJECTED;
if (!approved) {
postRepository.updateStatus(postId, PostStatus.REJECTED);
log.info("Пост {} отклонён модерацией.", post.getId());
return;
} catch (ContentBlockedException e) {
log.info("Пост {} отклонён модерацией: {} {}", postId, e.getReason(), e.getDetectedLabels());
return PostStatus.REJECTED;
} catch (ApiException e) {
if (e.getStatus() == HttpStatus.NOT_FOUND) {
// Картинки поста нет в хранилище — проверить его целиком уже не получится
log.warn("Пост {}: файл не найден в хранилище, отклоняем: {}", postId, e.getMessage());
return PostStatus.REJECTED;
}
postRepository.updateStatus(postId, PostStatus.ACTIVE);
log.info("Пост {} прошёл модерацию.", post.getId());
// Пост впервые становится виден публике — и в ленте, и на карте.
// Инвалидируем оба кэша, иначе одобренный пост висит до TTL (2 минуты)
postCacheService.invalidatePosts();
mapCacheService.clearMapMarkersCache();
} catch (Exception e) {
log.warn("Пост {} не прошёл модерацию: {}", post.getId(), e.getMessage());
postRepository.updateStatus(postId, PostStatus.REJECTED);
log.warn("Пост {}: хранилище недоступно, повторим позже: {}", postId, e.getMessage());
return null;
} catch (RuntimeException e) {
if (hasCause(e, AiBadRequestException.class)) {
// 4xx от AI-сервиса: контент он не принимает (формат, размер) — повтор не поможет
log.warn("Пост {}: AI-сервис отверг запрос, отклоняем: {}", postId, e.getMessage());
return PostStatus.REJECTED;
}
log.warn("Пост {} не отмодерирован, повторим позже: {}", postId, e.toString());
return null;
}
}
private Boolean applyVerdict(Snapshot snapshot, PostStatus verdict) {
Post post = postRepository.findById(snapshot.postId()).orElse(null);
if (post == null || post.getStatus() != PostStatus.MODERATION) {
log.info("Пост {} удалён или сменил статус во время модерации, вердикт {} не применяем",
snapshot.postId(), verdict);
return false;
}
if (!Objects.equals(post.getTitle(), snapshot.title())
|| !Objects.equals(post.getDescription(), snapshot.description())
|| !new HashSet<>(imageKeys(post)).equals(new HashSet<>(snapshot.imageKeys()))) {
log.info("Пост {} изменён во время модерации, проверим новую версию при следующем запуске",
snapshot.postId());
return false;
}
post.setStatus(verdict);
log.info("Пост {} {}", snapshot.postId(), verdict == PostStatus.ACTIVE ? "прошёл модерацию" : "отклонён модерацией");
return true;
}
private static List<String> imageKeys(Post post) {
return post.getImages().stream().map(Image::getUrl).toList();
}
private static boolean hasCause(Throwable e, Class<? extends Throwable> type) {
for (Throwable t = e; t != null; t = t.getCause()) {
if (type.isInstance(t)) {
return true;
}
}
return false;
}
private MultipartFile toMultipartFile(DownloadedFile file) {
return new ByteArrayMultipartFile("images", file.originalFilename(), file.contentType(), file.content());
}
}
}

View File

@@ -20,9 +20,9 @@ import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.search.PostFeedFilter;
import com.krylov.refound.search.PostSearchService;
import com.krylov.refound.search.SearchSuggestService;
import com.krylov.refound.service.redis.MapCacheService;
import com.krylov.refound.service.redis.PostCacheKeyGenerator;
import com.krylov.refound.service.redis.PostCacheService;
import com.krylov.refound.util.PostFieldLimits;
import com.krylov.refound.util.PostSpecification;
import com.krylov.refound.util.PostVisibility;
import com.krylov.refound.util.TimeZoneContext;
@@ -67,7 +67,7 @@ public class PostService {
private final ObjectMapper objectMapper;
private final PostCacheService postCacheService;
private final PostCacheKeyGenerator postCacheKeyGenerator;
private final MapCacheService mapCacheService;
private final PostDeletionService postDeletionService;
private final PostSearchService postSearchService;
private final SearchSuggestService searchSuggestService;
@@ -75,6 +75,7 @@ public class PostService {
public PostRequest create(PostRequest request, List<MultipartFile> images) {
User currentUser = userService.getCurrentUser();
PostFieldLimits.validate(request.getTitle(), request.getAddress(), request.getPhone(), request.getRewardText());
Post post = mapper.toEntity(request);
post.setCreatedAt(TimeZoneContext.now());
@@ -83,13 +84,7 @@ public class PostService {
post.setIsReward(request.getReward());
// Адрес из формы сохраняем как есть; геокодер заполняет только city/district
post.setAddress(normalizeAddress(request.getAddress()));
if (request.getLatitude() == null || request.getLongitude() == null) {
post.setCity(request.getAddress());
} else {
AddressInfo address = geocodingService.getAddress(request.getLatitude().toString(), request.getLongitude().toString());
post.setCity(address.city());
post.setDistrict(address.district());
}
resolveLocation(post, request.getLatitude(), request.getLongitude(), request.getAddress());
postRepository.save(post);
log.info("Создан пост id={} пользователем userId={}, статус={}", post.getId(), currentUser.getId(), post.getStatus());
@@ -99,7 +94,6 @@ public class PostService {
statisticsService.incrementCreated();
postCacheService.invalidatePosts();
mapCacheService.clearMapMarkersCache();
return request;
}
@@ -223,6 +217,7 @@ public class PostService {
request.setAddress(address);
request.setReward(reward);
request.setRewardText(rewardText);
PostFieldLimits.validate(title, address, phone, rewardText);
List<String> existingUrls = parseExistingImages(existingImagesJson);
@@ -248,14 +243,8 @@ public class PostService {
if (request.getLatitude() != null && request.getLongitude() != null) {
post.setLatitude(request.getLatitude());
post.setLongitude(request.getLongitude());
AddressInfo address = geocodingService.getAddress(
request.getLatitude().toString(), request.getLongitude().toString());
post.setCity(address.city());
post.setDistrict(address.district());
} else {
post.setCity(request.getAddress());
}
resolveLocation(post, request.getLatitude(), request.getLongitude(), request.getAddress());
List<String> keepUrls = existingUrls != null ? existingUrls : List.of();
@@ -270,23 +259,15 @@ public class PostService {
Post updated = postRepository.save(post);
log.info("Обновлён пост id={}: удалено изображений={}, добавлено={}, статус={}", id, toRemove.size(), uploaded, updated.getStatus());
postCacheService.invalidatePosts();
mapCacheService.clearMapMarkersCache();
log.info("redis cache invalidated in update");
return mapper.toResponse(updated);
}
@Transactional
public void delete(Long id) {
Post post = findOwnedPost(id);
// Без этого файлы останутся в MinIO мусором после удаления объявления
post.getImages().forEach(img -> deleteFileQuietly(img.getUrl()));
postRepository.delete(post);
// Вместе с постом чистит избранное, ссылки из чатов и файлы в MinIO
postDeletionService.delete(List.of(post));
log.info("Удалён пост id={}, изображений={}", id, post.getImages().size());
postCacheService.invalidatePosts();
mapCacheService.clearMapMarkersCache();
log.info("redis cache invalidated in delete");
}
@Transactional
@@ -311,8 +292,6 @@ public class PostService {
Post updated = postRepository.save(post);
log.info("Статус поста id={} изменён: {} -> {}", id, previousStatus, newStatus);
postCacheService.invalidatePosts();
mapCacheService.clearMapMarkersCache();
log.info("redis cache invalidated in update status");
return mapper.toResponse(updated);
}
@@ -409,18 +388,29 @@ public class PostService {
}
private void removeImages(Post post, List<Image> toRemove) {
toRemove.forEach(img -> deleteFileQuietly(img.getUrl()));
post.getImages().removeAll(toRemove);
postDeletionService.deleteFilesAfterCommit(toRemove.stream().map(Image::getUrl).toList());
}
private void deleteFileQuietly(String objectKey) {
try {
fileStorageService.deleteFile(objectKey);
} catch (Exception e) {
// Не блокируем основную операцию из-за мусора в хранилище — это некритично,
// но стоит завести алерт на такие warn-логи, если их станет много.
log.warn("Не удалось удалить файл из хранилища: {}", objectKey, e);
/**
* Город и район по координатам. Геокодер (Nominatim) — внешний сервис: если он
* недоступен, объявление всё равно сохраняется, а городом становится адрес из
* формы. Раньше недоступность Nominatim не давала создать объявление (503).
*/
private void resolveLocation(Post post, Double latitude, Double longitude, String address) {
if (latitude != null && longitude != null) {
try {
AddressInfo resolved = geocodingService.getAddress(latitude.toString(), longitude.toString());
if (StringUtils.hasText(resolved.city())) {
post.setCity(resolved.city());
post.setDistrict(resolved.district());
return;
}
} catch (ApiException e) {
log.warn("Геокодинг недоступен, город берём из адреса: postId={}, {}", post.getId(), e.getMessage());
}
}
post.setCity(PostFieldLimits.cityFromAddress(address));
}
public PostResponse toResponse(Post post, boolean includeUserRole) {

View File

@@ -2,12 +2,15 @@ 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.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
@@ -20,66 +23,45 @@ import org.springframework.transaction.annotation.Transactional;
public class SchedulerService {
private final PostRepository postRepository;
private final FavoriteRepository favoriteRepository;
private final PostModerationExecutorService postModerationExecutorService;
private final PostCacheService postCacheService;
private final MapCacheService mapCacheService;
private final PostDeletionService postDeletionService;
/**
* Runs every day at 00:01 to delete:
* 1. Posts with CLOSED status
* 2. Posts older than 6 months
*
* Удаление идёт через PostDeletionService: вместе с постами чистятся избранное,
* ссылки из чатов и файлы в MinIO (раньше файлы оставались мусором в бакете).
*/
@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");
LocalDateTime sixMonthsAgo = LocalDateTime.now().minusMonths(6);
List<Post> closedPosts = postRepository.findByStatus(PostStatus.CLOSED);
List<Post> oldPosts = postRepository.findByCreatedAtBefore(sixMonthsAgo);
// Закрытый пост бывает и старым — удаляем каждый один раз
Map<Long, Post> expired = Stream.concat(closedPosts.stream(), oldPosts.stream())
.collect(Collectors.toMap(Post::getId, Function.identity(), (a, b) -> a, LinkedHashMap::new));
postDeletionService.delete(new ArrayList<>(expired.values()));
log.info("Scheduled cleanup completed: closed={}, older than 6 months={}, deleted={}",
closedPosts.size(), oldPosts.size(), expired.size());
}
/**
* Каждые 60 секунд забирает посты, ожидающие модерации, и прогоняет их через
* ContentModerationFacade. Изображения к этому моменту уже лежат в MinIO
* (залиты синхронно в PostService.create/update) — оригинальные MultipartFile
* из запроса уже недоступны (Tomcat удаляет temp-файл сразу после завершения
* запроса), поэтому скачиваем их заново и оборачиваем в ByteArrayMultipartFile,
* чтобы не менять сигнатуру ContentModerationFacade.
* из запроса уже недоступны, поэтому PostModerationExecutorService скачивает их заново.
*
* Сама обработка одного поста вынесена в отдельный бин PostModerationExecutor —
* вызов через него идёт через Spring-прокси, поэтому @Transactional на
* moderateOne реально применяется (self-invocation внутри этого класса привёл бы
* к тому, что транзакция не открывалась бы вовсе).
* Сама обработка одного поста вынесена в отдельный бин: ему нужны собственные
* короткие транзакции до и после вызова AI, а self-invocation внутри этого
* класса обошёл бы Spring-прокси.
*/
@Scheduled(fixedDelay = 60_000)
public void moderatePendingPosts() {
@@ -90,9 +72,12 @@ public class SchedulerService {
log.info("На модерации {} постов.", pending.size());
for (Long postId : pending) {
postModerationExecutorService.moderateOne(postId);
try {
postModerationExecutorService.moderateOne(postId);
} catch (RuntimeException e) {
// Один сломанный пост не должен останавливать модерацию остальных
log.error("Ошибка модерации поста {}", postId, e);
}
}
}
}

View File

@@ -2,27 +2,39 @@ package com.krylov.refound.service;
import com.krylov.refound.entity.Statistics;
import com.krylov.refound.repository.StatisticsRepository;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class StatisticsService {
/** Единственная строка статистики, её создаёт changelog 009. */
private static final Long STATISTICS_ID = 1L;
private final StatisticsRepository repository;
public void incrementCreated() {
Statistics statistics = repository.findById(1L).orElseThrow();
statistics.setPostsCreated(statistics.getPostsCreated() + 1);
if (repository.incrementCreated(STATISTICS_ID) == 0) {
log.warn("Строка statistics id={} не найдена, счётчик созданных не увеличен", STATISTICS_ID);
}
}
public void incrementFound() {
Statistics statistics = repository.findById(1L).orElseThrow();
statistics.setPostsFound(statistics.getPostsFound() + 1);
if (repository.incrementFound(STATISTICS_ID) == 0) {
log.warn("Строка statistics id={} не найдена, счётчик найденных не увеличен", STATISTICS_ID);
}
}
@Transactional(readOnly = true)
public Statistics getStatistics() {
return repository.findById(1L).orElseThrow();
return repository.findById(STATISTICS_ID)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Statistics not found", HttpStatus.NOT_FOUND));
}
}

View File

@@ -12,15 +12,14 @@ import com.krylov.refound.enums.PostCategory;
import com.krylov.refound.enums.PostStatus;
import com.krylov.refound.enums.PostType;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.repository.ChatRepository;
import com.krylov.refound.repository.FavoriteRepository;
import com.krylov.refound.repository.ImageRepository;
import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.service.FileStorageService;
import com.krylov.refound.service.GeocodingService;
import com.krylov.refound.service.PostDeletionService;
import com.krylov.refound.service.StatisticsService;
import com.krylov.refound.service.redis.MapCacheService;
import com.krylov.refound.service.redis.PostCacheService;
import com.krylov.refound.util.PostFieldLimits;
import com.krylov.refound.util.PostSpecification;
import java.util.Arrays;
import java.util.EnumSet;
@@ -48,7 +47,7 @@ import org.springframework.web.multipart.MultipartFile;
* <li>нет проверки владельца — операции доступны любому ADMIN;</li>
* <li>редактирование не меняет статус: перевод в MODERATION убрал бы объявление из ленты до
* прохождения AI-модерации, а в REJECTED — скрыл бы навсегда;</li>
* <li>удаление чистит ссылки из favorites и chats, потому что каскада в БД нет;</li>
* <li>удаление идёт через {@link PostDeletionService}, как и у владельца;</li>
* <li>геокодинг при правке best-effort: недоступность Nominatim не должна блокировать
* исправление текста объявления.</li>
* </ul>
@@ -68,12 +67,10 @@ public class AdminPostService {
private final PostRepository postRepository;
private final ImageRepository imageRepository;
private final FavoriteRepository favoriteRepository;
private final ChatRepository chatRepository;
private final FileStorageService fileStorageService;
private final GeocodingService geocodingService;
private final PostCacheService postCacheService;
private final MapCacheService mapCacheService;
private final PostDeletionService postDeletionService;
private final StatisticsService statisticsService;
private final ObjectMapper objectMapper;
@@ -128,6 +125,7 @@ public class AdminPostService {
Post post = findPost(postId);
PostStatus statusBeforeEdit = post.getStatus();
PostFieldLimits.validate(title, address, phone, rewardText);
post.setType(parseTypeOrThrow(type));
post.setTitle(title);
@@ -147,7 +145,7 @@ public class AdminPostService {
post.setLongitude(longitude);
resolveLocation(post, latitude, longitude, address);
} else if (StringUtils.hasText(address)) {
post.setCity(address.trim());
post.setCity(PostFieldLimits.cityFromAddress(address));
}
syncImages(post, existingImagesJson, images);
@@ -161,17 +159,8 @@ public class AdminPostService {
@Transactional
public void deletePost(Long postId) {
Post post = findPost(postId);
for (Image image : post.getImages()) {
deleteFileQuietly(image.getUrl());
}
// На posts ссылаются favorites и chats, ON DELETE CASCADE в БД нет:
// без явной чистки удаление падало бы на внешнем ключе.
favoriteRepository.deleteByPostIn(List.of(post));
chatRepository.clearPostReference(postId);
postRepository.delete(post);
invalidateCaches();
// Чистит favorites и ссылки из chats (каскада в БД нет), файлы — после коммита
postDeletionService.delete(List.of(post));
log.info("Post {} deleted by admin", postId);
}
@@ -219,7 +208,7 @@ public class AdminPostService {
log.warn("Геокодинг недоступен, город берём из address: postId={}, {}", post.getId(), e.getMessage());
}
if (StringUtils.hasText(address)) {
post.setCity(address.trim());
post.setCity(PostFieldLimits.cityFromAddress(address));
}
}
@@ -229,10 +218,8 @@ public class AdminPostService {
List<Image> toRemove = post.getImages().stream()
.filter(image -> !keepUrls.contains(image.getUrl()))
.toList();
for (Image image : toRemove) {
deleteFileQuietly(image.getUrl());
}
post.getImages().removeAll(toRemove);
postDeletionService.deleteFilesAfterCommit(toRemove.stream().map(Image::getUrl).toList());
if (newImages == null) {
return;
@@ -263,15 +250,6 @@ public class AdminPostService {
private void invalidateCaches() {
postCacheService.invalidatePosts();
mapCacheService.clearMapMarkersCache();
}
private void deleteFileQuietly(String objectKey) {
try {
fileStorageService.deleteFile(objectKey);
} catch (Exception e) {
log.warn("Не удалось удалить файл из хранилища: {}", objectKey, e);
}
}
/** Один запрос вместо N+1 при сборке страницы объявлений. */

View File

@@ -1,22 +0,0 @@
package com.krylov.refound.service.redis;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class MapCacheKeyGenerator {
private static final String PREFIX = "maps:markers:v";
private final MapCacheService mapCacheService;
public String markersKey(String type, String category) {
// Версия читается здесь, то есть в самом начале getMapMarkers, до запроса в БД
String version = mapCacheService.currentMapVersion();
return PREFIX + version
+ ":type=" + RedisCacheKeyUtil.sha256(RedisCacheKeyUtil.normalize(type))
+ ":category=" + RedisCacheKeyUtil.sha256(RedisCacheKeyUtil.normalize(category));
}
}

View File

@@ -1,77 +0,0 @@
package com.krylov.refound.service.redis;
import com.krylov.refound.dto.CachedMapMarkers;
import java.time.Duration;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
@Service
@RequiredArgsConstructor
@Slf4j
public class MapCacheService {
// Ключ версии без TTL. Redis должен работать с maxmemory-policy volatile-lru,
// чтобы этот ключ не вытеснялся
private static final String VERSION_KEY = "maps:markers:version";
private final RedisTemplate<String, CachedMapMarkers> redisTemplate;
private final StringRedisTemplate stringRedisTemplate;
public CachedMapMarkers getMarkers(String key) {
try {
return redisTemplate.opsForValue().get(key);
} catch (Exception e) {
// Кэш best-effort: любая проблема (Redis недоступен, битый JSON) = miss
log.warn("Не удалось прочитать метки карты из Redis, key={}: {}", key, e.toString());
return null;
}
}
public void saveMarkers(String key, CachedMapMarkers value, Duration ttl) {
try {
redisTemplate.opsForValue().set(key, value, ttl);
} catch (Exception e) {
log.warn("Не удалось сохранить метки карты в Redis, key={}: {}", key, e.toString());
}
}
/** Текущая версия меток карты. Должна читаться ДО запроса в БД. */
public String currentMapVersion() {
try {
String version = stringRedisTemplate.opsForValue().get(VERSION_KEY);
return version == null ? "0" : version;
} catch (Exception e) {
log.warn("Не удалось прочитать версию map cache: {}", e.toString());
return "0";
}
}
/** Инвалидирует метки карты после коммита текущей транзакции (или сразу, если транзакции нет). */
public void clearMapMarkersCache() {
if (TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
bumpMapVersion();
}
});
} else {
bumpMapVersion();
}
}
private void bumpMapVersion() {
try {
Long version = stringRedisTemplate.opsForValue().increment(VERSION_KEY);
log.info("Map cache инвалидирован, версия={}", version);
} catch (Exception e) {
// Устаревшие записи доживут до TTL (2 минуты)
log.warn("Не удалось инвалидировать map cache: {}", e.toString());
}
}
}

View File

@@ -0,0 +1,52 @@
package com.krylov.refound.util;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
/**
* Длины текстовых полей объявления по схеме БД (changelog 002, 003, 015, 018).
* Без проверки слишком длинное значение доходило до INSERT и давало 500.
*/
public final class PostFieldLimits {
public static final int TITLE = 255;
public static final int PHONE = 255;
public static final int REWARD_TEXT = 255;
public static final int ADDRESS = 500;
public static final int CITY = 100;
private PostFieldLimits() {
}
/** Проверяет поля формы объявления; 400 VALIDATION_ERROR при нарушении. */
public static void validate(String title, String address, String phone, String rewardText) {
if (!StringUtils.hasText(title)) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Заголовок обязателен", HttpStatus.BAD_REQUEST);
}
checkLength("Заголовок", title, TITLE);
checkLength("Адрес", address, ADDRESS);
checkLength("Телефон", phone, PHONE);
checkLength("Текст вознаграждения", rewardText, REWARD_TEXT);
}
/**
* Город, когда геокодер его не дал: берётся адрес из формы, обрезанный под
* колонку city (адрес допускает 500 символов, город — 100).
*/
public static String cityFromAddress(String address) {
if (!StringUtils.hasText(address)) {
return null;
}
String city = address.trim();
return city.length() > CITY ? city.substring(0, CITY) : city;
}
private static void checkLength(String field, String value, int max) {
if (value != null && value.length() > max) {
throw new ApiException(ErrorCode.VALIDATION_ERROR,
field + " длиннее " + max + " символов", HttpStatus.BAD_REQUEST);
}
}
}

View File

@@ -19,10 +19,17 @@ spring:
# из-за чего базы расходились. Для разработки можно переопределить
# переменной окружения JPA_DDL_AUTO=update.
ddl-auto: ${JPA_DDL_AUTO:validate}
show-sql: ${JPA_SHOW_SQL:true}
show-sql: ${JPA_SHOW_SQL:false}
# Ленту и избранное собирают вне транзакции (PostResponse читает images и user лениво),
# поэтому сессия Hibernate должна жить до конца запроса. Значение по умолчанию,
# указано явно, чтобы убрать предупреждение при старте.
open-in-view: true
properties:
hibernate:
format_sql: true
# Ленивые коллекции (images) и связи (user) грузятся пачками по id,
# а не по одному запросу на пост — убирает N+1 в ленте, избранном и чистке
default_batch_fetch_size: 50
data:
redis: