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:
@@ -2,7 +2,6 @@ package com.krylov.refound.config;
|
|||||||
|
|
||||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.krylov.refound.dto.CachedMapMarkers;
|
|
||||||
import com.krylov.refound.dto.CachedPostPage;
|
import com.krylov.refound.dto.CachedPostPage;
|
||||||
import com.krylov.refound.dto.MapMarkerDto;
|
import com.krylov.refound.dto.MapMarkerDto;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -21,11 +20,6 @@ public class RedisConfig {
|
|||||||
return buildTemplate(connectionFactory, objectMapper, CachedPostPage.class);
|
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) {
|
private static <T> RedisTemplate<String, T> buildTemplate(RedisConnectionFactory connectionFactory, ObjectMapper objectMapper, Class<T> type) {
|
||||||
// Своя копия: изменения веб-настроек ObjectMapper не должны ломать формат кэша,
|
// Своя копия: изменения веб-настроек ObjectMapper не должны ломать формат кэша,
|
||||||
// а неизвестные поля в старых записях не должны валить десериализацию
|
// а неизвестные поля в старых записях не должны валить десериализацию
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import com.krylov.refound.exception.ApiException;
|
|||||||
import com.krylov.refound.search.PostFeedFilter;
|
import com.krylov.refound.search.PostFeedFilter;
|
||||||
import com.krylov.refound.search.SearchSuggestService;
|
import com.krylov.refound.search.SearchSuggestService;
|
||||||
import com.krylov.refound.service.PostService;
|
import com.krylov.refound.service.PostService;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
@@ -40,8 +41,8 @@ public class PostController {
|
|||||||
private final SearchSuggestService searchSuggestService;
|
private final SearchSuggestService searchSuggestService;
|
||||||
|
|
||||||
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||||
public PostRequest create(@ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
|
public PostRequest create(@Valid @ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
|
||||||
log.info("create post {}", request.toString());
|
log.info("create post type={}, title='{}'", request.getType(), request.getTitle());
|
||||||
return service.create(request, images);
|
return service.create(request, images);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
|
||||||
}
|
|
||||||
@@ -21,7 +21,8 @@ public interface PostMapper {
|
|||||||
@Mapping(source = "user.id", target = "userId")
|
@Mapping(source = "user.id", target = "userId")
|
||||||
@Mapping(source = "user.login", target = "userEmail")
|
@Mapping(source = "user.login", target = "userEmail")
|
||||||
@Mapping(source = "images", target = "images", qualifiedByName = "imagesToUrls")
|
@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 = "isReward", target = "reward")
|
||||||
@Mapping(source = "reward", target = "rewardText")
|
@Mapping(source = "reward", target = "rewardText")
|
||||||
@Mapping(source = "rulesAccepted", target = "rulesAccepted", qualifiedByName = "booleanToString")
|
@Mapping(source = "rulesAccepted", target = "rulesAccepted", qualifiedByName = "booleanToString")
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.krylov.refound.repository;
|
package com.krylov.refound.repository;
|
||||||
|
|
||||||
import com.krylov.refound.entity.Chat;
|
import com.krylov.refound.entity.Chat;
|
||||||
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
@@ -30,6 +31,6 @@ public interface ChatRepository extends JpaRepository<Chat, Long> {
|
|||||||
* У posts нет ON DELETE CASCADE, поэтому без этого удаление падало бы с 500.
|
* У posts нет ON DELETE CASCADE, поэтому без этого удаление падало бы с 500.
|
||||||
*/
|
*/
|
||||||
@Modifying
|
@Modifying
|
||||||
@Query("UPDATE Chat c SET c.postId = NULL WHERE c.postId = :postId")
|
@Query("UPDATE Chat c SET c.postId = NULL WHERE c.postId IN :postIds")
|
||||||
int clearPostReference(@Param("postId") Long postId);
|
int clearPostReferences(@Param("postIds") Collection<Long> postIds);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,18 @@ package com.krylov.refound.repository;
|
|||||||
|
|
||||||
import com.krylov.refound.entity.Statistics;
|
import com.krylov.refound.entity.Statistics;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
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> {
|
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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ import com.krylov.refound.exception.ApiException;
|
|||||||
import com.krylov.refound.mapper.PostMapper;
|
import com.krylov.refound.mapper.PostMapper;
|
||||||
import com.krylov.refound.repository.FavoriteRepository;
|
import com.krylov.refound.repository.FavoriteRepository;
|
||||||
import com.krylov.refound.repository.PostRepository;
|
import com.krylov.refound.repository.PostRepository;
|
||||||
|
import com.krylov.refound.util.PostVisibility;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -53,30 +53,32 @@ public class FavoriteService {
|
|||||||
return repository.findByUser(user)
|
return repository.findByUser(user)
|
||||||
.stream()
|
.stream()
|
||||||
.map(Favorite::getPost)
|
.map(Favorite::getPost)
|
||||||
|
.filter(post -> isVisibleTo(post, user))
|
||||||
.map(mapper::toResponse)
|
.map(mapper::toResponse)
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
public List<PostResponse> getAllFavoritesPosts() {
|
public List<PostResponse> getAllFavoritesPosts() {
|
||||||
User user = userService.getCurrentUser();
|
User user = userService.getCurrentUser();
|
||||||
if (user == null) {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
List<Long> favoritePostIds = repository.findPostIdsByUserId(user.getId());
|
List<Long> favoritePostIds = repository.findPostIdsByUserId(user.getId());
|
||||||
if (favoritePostIds.isEmpty()) {
|
if (favoritePostIds.isEmpty()) {
|
||||||
return List.of();
|
return List.of();
|
||||||
}
|
}
|
||||||
|
|
||||||
List<Post> posts = postRepository.findAllById(favoritePostIds);
|
return postRepository.findAllById(favoritePostIds).stream()
|
||||||
|
.filter(post -> isVisibleTo(post, user))
|
||||||
List<Long> postIds = posts.stream()
|
|
||||||
.map(Post::getId)
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
|
|
||||||
return posts.stream()
|
|
||||||
.map(post -> postService.toResponse(post, true))
|
.map(post -> postService.toResponse(post, true))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Пост из избранного мог уйти на повторную модерацию (после правки) или быть
|
||||||
|
* отклонён — такой виден только владельцу, как и в ленте.
|
||||||
|
*/
|
||||||
|
private static boolean isVisibleTo(Post post, User user) {
|
||||||
|
return PostVisibility.FEED_VISIBLE_STATUSES.contains(post.getStatus())
|
||||||
|
|| post.getUser().getId().equals(user.getId());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,80 +1,160 @@
|
|||||||
package com.krylov.refound.service;
|
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.ai.facade.ContentModerationFacade;
|
||||||
import com.krylov.refound.dto.DownloadedFile;
|
import com.krylov.refound.dto.DownloadedFile;
|
||||||
import com.krylov.refound.entity.Image;
|
import com.krylov.refound.entity.Image;
|
||||||
import com.krylov.refound.entity.Post;
|
import com.krylov.refound.entity.Post;
|
||||||
import com.krylov.refound.enums.PostStatus;
|
import com.krylov.refound.enums.PostStatus;
|
||||||
|
import com.krylov.refound.exception.ApiException;
|
||||||
import com.krylov.refound.repository.PostRepository;
|
import com.krylov.refound.repository.PostRepository;
|
||||||
import com.krylov.refound.service.redis.MapCacheService;
|
|
||||||
import com.krylov.refound.service.redis.PostCacheService;
|
import com.krylov.refound.service.redis.PostCacheService;
|
||||||
import com.krylov.refound.util.ByteArrayMultipartFile;
|
import com.krylov.refound.util.ByteArrayMultipartFile;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import lombok.RequiredArgsConstructor;
|
import java.util.Objects;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Component;
|
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;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Вынесено из SchedulerService отдельным бином специально: вызов moderateOne(post)
|
* Модерация одного поста. Вынесено из SchedulerService отдельным бином, чтобы
|
||||||
* из цикла в том же классе был бы self-invocation и обходил бы Spring-прокси,
|
* транзакции работали через Spring-прокси.
|
||||||
* из-за чего @Transactional на методе не действовал бы во время выполнения
|
*
|
||||||
* (post.getImages() как раз требует активной транзакции — это ленивая коллекция).
|
* <p>Пост проверяется в три шага: короткая транзакция читает снимок поста
|
||||||
|
* (текст и ключи картинок), затем без транзакции скачиваются картинки и идёт
|
||||||
|
* вызов AI (с ретраями это десятки секунд — держать всё это время соединение
|
||||||
|
* с БД незачем), и в конце новая транзакция ставит статус. Статус ставится,
|
||||||
|
* только если пост всё ещё на модерации и не менялся с момента снимка: иначе
|
||||||
|
* правка, сделанная во время проверки, стала бы ACTIVE без модерации.
|
||||||
*/
|
*/
|
||||||
@Component
|
@Component
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class PostModerationExecutorService {
|
public class PostModerationExecutorService {
|
||||||
|
|
||||||
private final PostRepository postRepository;
|
private final PostRepository postRepository;
|
||||||
private final ContentModerationFacade contentModerationFacade;
|
private final ContentModerationFacade contentModerationFacade;
|
||||||
private final FileStorageService fileStorageService;
|
private final FileStorageService fileStorageService;
|
||||||
private final PostCacheService postCacheService;
|
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) {
|
public void moderateOne(Long postId) {
|
||||||
Post post = postRepository.findById(postId).orElse(null);
|
Snapshot snapshot = transactionTemplate.execute(status -> loadSnapshot(postId));
|
||||||
if (post == null) {
|
if (snapshot == null) {
|
||||||
log.warn("Пост {} не найден на момент модерации, пропускаем", postId);
|
log.debug("Пост {} уже не на модерации или удалён, пропускаем", postId);
|
||||||
return;
|
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 {
|
try {
|
||||||
List<MultipartFile> images = post.getImages().stream()
|
List<MultipartFile> images = snapshot.imageKeys().stream()
|
||||||
.map(Image::getUrl)
|
|
||||||
.map(fileStorageService::downloadFileRaw)
|
.map(fileStorageService::downloadFileRaw)
|
||||||
.map(this::toMultipartFile)
|
.map(this::toMultipartFile)
|
||||||
.toList();
|
.toList();
|
||||||
|
|
||||||
Boolean approved = contentModerationFacade.moderate(post.getTitle(), post.getDescription(), images);
|
Boolean approved = contentModerationFacade.moderate(snapshot.title(), snapshot.description(), images);
|
||||||
|
|
||||||
if (approved == null) {
|
if (approved == null) {
|
||||||
log.warn("Пост {} не отмодерирован из-за недоступности AI, статус не меняем", post.getId());
|
log.warn("Пост {} не отмодерирован из-за недоступности AI, статус не меняем", postId);
|
||||||
return;
|
return null;
|
||||||
}
|
}
|
||||||
|
return approved ? PostStatus.ACTIVE : PostStatus.REJECTED;
|
||||||
|
|
||||||
if (!approved) {
|
} catch (ContentBlockedException e) {
|
||||||
postRepository.updateStatus(postId, PostStatus.REJECTED);
|
log.info("Пост {} отклонён модерацией: {} {}", postId, e.getReason(), e.getDetectedLabels());
|
||||||
log.info("Пост {} отклонён модерацией.", post.getId());
|
return PostStatus.REJECTED;
|
||||||
return;
|
} catch (ApiException e) {
|
||||||
|
if (e.getStatus() == HttpStatus.NOT_FOUND) {
|
||||||
|
// Картинки поста нет в хранилище — проверить его целиком уже не получится
|
||||||
|
log.warn("Пост {}: файл не найден в хранилище, отклоняем: {}", postId, e.getMessage());
|
||||||
|
return PostStatus.REJECTED;
|
||||||
}
|
}
|
||||||
|
log.warn("Пост {}: хранилище недоступно, повторим позже: {}", postId, e.getMessage());
|
||||||
postRepository.updateStatus(postId, PostStatus.ACTIVE);
|
return null;
|
||||||
log.info("Пост {} прошёл модерацию.", post.getId());
|
} catch (RuntimeException e) {
|
||||||
|
if (hasCause(e, AiBadRequestException.class)) {
|
||||||
// Пост впервые становится виден публике — и в ленте, и на карте.
|
// 4xx от AI-сервиса: контент он не принимает (формат, размер) — повтор не поможет
|
||||||
// Инвалидируем оба кэша, иначе одобренный пост висит до TTL (2 минуты)
|
log.warn("Пост {}: AI-сервис отверг запрос, отклоняем: {}", postId, e.getMessage());
|
||||||
postCacheService.invalidatePosts();
|
return PostStatus.REJECTED;
|
||||||
mapCacheService.clearMapMarkersCache();
|
}
|
||||||
|
log.warn("Пост {} не отмодерирован, повторим позже: {}", postId, e.toString());
|
||||||
} catch (Exception e) {
|
return null;
|
||||||
log.warn("Пост {} не прошёл модерацию: {}", post.getId(), e.getMessage());
|
|
||||||
postRepository.updateStatus(postId, PostStatus.REJECTED);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) {
|
private MultipartFile toMultipartFile(DownloadedFile file) {
|
||||||
return new ByteArrayMultipartFile("images", file.originalFilename(), file.contentType(), file.content());
|
return new ByteArrayMultipartFile("images", file.originalFilename(), file.contentType(), file.content());
|
||||||
|
|||||||
@@ -20,9 +20,9 @@ import com.krylov.refound.repository.PostRepository;
|
|||||||
import com.krylov.refound.search.PostFeedFilter;
|
import com.krylov.refound.search.PostFeedFilter;
|
||||||
import com.krylov.refound.search.PostSearchService;
|
import com.krylov.refound.search.PostSearchService;
|
||||||
import com.krylov.refound.search.SearchSuggestService;
|
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.PostCacheKeyGenerator;
|
||||||
import com.krylov.refound.service.redis.PostCacheService;
|
import com.krylov.refound.service.redis.PostCacheService;
|
||||||
|
import com.krylov.refound.util.PostFieldLimits;
|
||||||
import com.krylov.refound.util.PostSpecification;
|
import com.krylov.refound.util.PostSpecification;
|
||||||
import com.krylov.refound.util.PostVisibility;
|
import com.krylov.refound.util.PostVisibility;
|
||||||
import com.krylov.refound.util.TimeZoneContext;
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
@@ -67,7 +67,7 @@ public class PostService {
|
|||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
private final PostCacheService postCacheService;
|
private final PostCacheService postCacheService;
|
||||||
private final PostCacheKeyGenerator postCacheKeyGenerator;
|
private final PostCacheKeyGenerator postCacheKeyGenerator;
|
||||||
private final MapCacheService mapCacheService;
|
private final PostDeletionService postDeletionService;
|
||||||
private final PostSearchService postSearchService;
|
private final PostSearchService postSearchService;
|
||||||
private final SearchSuggestService searchSuggestService;
|
private final SearchSuggestService searchSuggestService;
|
||||||
|
|
||||||
@@ -75,6 +75,7 @@ public class PostService {
|
|||||||
public PostRequest create(PostRequest request, List<MultipartFile> images) {
|
public PostRequest create(PostRequest request, List<MultipartFile> images) {
|
||||||
|
|
||||||
User currentUser = userService.getCurrentUser();
|
User currentUser = userService.getCurrentUser();
|
||||||
|
PostFieldLimits.validate(request.getTitle(), request.getAddress(), request.getPhone(), request.getRewardText());
|
||||||
|
|
||||||
Post post = mapper.toEntity(request);
|
Post post = mapper.toEntity(request);
|
||||||
post.setCreatedAt(TimeZoneContext.now());
|
post.setCreatedAt(TimeZoneContext.now());
|
||||||
@@ -83,13 +84,7 @@ public class PostService {
|
|||||||
post.setIsReward(request.getReward());
|
post.setIsReward(request.getReward());
|
||||||
// Адрес из формы сохраняем как есть; геокодер заполняет только city/district
|
// Адрес из формы сохраняем как есть; геокодер заполняет только city/district
|
||||||
post.setAddress(normalizeAddress(request.getAddress()));
|
post.setAddress(normalizeAddress(request.getAddress()));
|
||||||
if (request.getLatitude() == null || request.getLongitude() == null) {
|
resolveLocation(post, request.getLatitude(), request.getLongitude(), request.getAddress());
|
||||||
post.setCity(request.getAddress());
|
|
||||||
} else {
|
|
||||||
AddressInfo address = geocodingService.getAddress(request.getLatitude().toString(), request.getLongitude().toString());
|
|
||||||
post.setCity(address.city());
|
|
||||||
post.setDistrict(address.district());
|
|
||||||
}
|
|
||||||
|
|
||||||
postRepository.save(post);
|
postRepository.save(post);
|
||||||
log.info("Создан пост id={} пользователем userId={}, статус={}", post.getId(), currentUser.getId(), post.getStatus());
|
log.info("Создан пост id={} пользователем userId={}, статус={}", post.getId(), currentUser.getId(), post.getStatus());
|
||||||
@@ -99,7 +94,6 @@ public class PostService {
|
|||||||
|
|
||||||
statisticsService.incrementCreated();
|
statisticsService.incrementCreated();
|
||||||
postCacheService.invalidatePosts();
|
postCacheService.invalidatePosts();
|
||||||
mapCacheService.clearMapMarkersCache();
|
|
||||||
return request;
|
return request;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,6 +217,7 @@ public class PostService {
|
|||||||
request.setAddress(address);
|
request.setAddress(address);
|
||||||
request.setReward(reward);
|
request.setReward(reward);
|
||||||
request.setRewardText(rewardText);
|
request.setRewardText(rewardText);
|
||||||
|
PostFieldLimits.validate(title, address, phone, rewardText);
|
||||||
|
|
||||||
List<String> existingUrls = parseExistingImages(existingImagesJson);
|
List<String> existingUrls = parseExistingImages(existingImagesJson);
|
||||||
|
|
||||||
@@ -248,14 +243,8 @@ public class PostService {
|
|||||||
if (request.getLatitude() != null && request.getLongitude() != null) {
|
if (request.getLatitude() != null && request.getLongitude() != null) {
|
||||||
post.setLatitude(request.getLatitude());
|
post.setLatitude(request.getLatitude());
|
||||||
post.setLongitude(request.getLongitude());
|
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();
|
List<String> keepUrls = existingUrls != null ? existingUrls : List.of();
|
||||||
|
|
||||||
@@ -270,23 +259,15 @@ public class PostService {
|
|||||||
Post updated = postRepository.save(post);
|
Post updated = postRepository.save(post);
|
||||||
log.info("Обновлён пост id={}: удалено изображений={}, добавлено={}, статус={}", id, toRemove.size(), uploaded, updated.getStatus());
|
log.info("Обновлён пост id={}: удалено изображений={}, добавлено={}, статус={}", id, toRemove.size(), uploaded, updated.getStatus());
|
||||||
postCacheService.invalidatePosts();
|
postCacheService.invalidatePosts();
|
||||||
mapCacheService.clearMapMarkersCache();
|
|
||||||
log.info("redis cache invalidated in update");
|
|
||||||
return mapper.toResponse(updated);
|
return mapper.toResponse(updated);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public void delete(Long id) {
|
public void delete(Long id) {
|
||||||
Post post = findOwnedPost(id);
|
Post post = findOwnedPost(id);
|
||||||
|
// Вместе с постом чистит избранное, ссылки из чатов и файлы в MinIO
|
||||||
// Без этого файлы останутся в MinIO мусором после удаления объявления
|
postDeletionService.delete(List.of(post));
|
||||||
post.getImages().forEach(img -> deleteFileQuietly(img.getUrl()));
|
|
||||||
|
|
||||||
postRepository.delete(post);
|
|
||||||
log.info("Удалён пост id={}, изображений={}", id, post.getImages().size());
|
log.info("Удалён пост id={}, изображений={}", id, post.getImages().size());
|
||||||
postCacheService.invalidatePosts();
|
|
||||||
mapCacheService.clearMapMarkersCache();
|
|
||||||
log.info("redis cache invalidated in delete");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
@@ -311,8 +292,6 @@ public class PostService {
|
|||||||
Post updated = postRepository.save(post);
|
Post updated = postRepository.save(post);
|
||||||
log.info("Статус поста id={} изменён: {} -> {}", id, previousStatus, newStatus);
|
log.info("Статус поста id={} изменён: {} -> {}", id, previousStatus, newStatus);
|
||||||
postCacheService.invalidatePosts();
|
postCacheService.invalidatePosts();
|
||||||
mapCacheService.clearMapMarkersCache();
|
|
||||||
log.info("redis cache invalidated in update status");
|
|
||||||
return mapper.toResponse(updated);
|
return mapper.toResponse(updated);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -409,18 +388,29 @@ public class PostService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void removeImages(Post post, List<Image> toRemove) {
|
private void removeImages(Post post, List<Image> toRemove) {
|
||||||
toRemove.forEach(img -> deleteFileQuietly(img.getUrl()));
|
|
||||||
post.getImages().removeAll(toRemove);
|
post.getImages().removeAll(toRemove);
|
||||||
|
postDeletionService.deleteFilesAfterCommit(toRemove.stream().map(Image::getUrl).toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
private void deleteFileQuietly(String objectKey) {
|
/**
|
||||||
try {
|
* Город и район по координатам. Геокодер (Nominatim) — внешний сервис: если он
|
||||||
fileStorageService.deleteFile(objectKey);
|
* недоступен, объявление всё равно сохраняется, а городом становится адрес из
|
||||||
} catch (Exception e) {
|
* формы. Раньше недоступность Nominatim не давала создать объявление (503).
|
||||||
// Не блокируем основную операцию из-за мусора в хранилище — это некритично,
|
*/
|
||||||
// но стоит завести алерт на такие warn-логи, если их станет много.
|
private void resolveLocation(Post post, Double latitude, Double longitude, String address) {
|
||||||
log.warn("Не удалось удалить файл из хранилища: {}", objectKey, e);
|
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) {
|
public PostResponse toResponse(Post post, boolean includeUserRole) {
|
||||||
|
|||||||
@@ -2,12 +2,15 @@ package com.krylov.refound.service;
|
|||||||
|
|
||||||
import com.krylov.refound.entity.Post;
|
import com.krylov.refound.entity.Post;
|
||||||
import com.krylov.refound.enums.PostStatus;
|
import com.krylov.refound.enums.PostStatus;
|
||||||
import com.krylov.refound.repository.FavoriteRepository;
|
|
||||||
import com.krylov.refound.repository.PostRepository;
|
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.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
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.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.scheduling.annotation.Scheduled;
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
@@ -20,15 +23,16 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
public class SchedulerService {
|
public class SchedulerService {
|
||||||
|
|
||||||
private final PostRepository postRepository;
|
private final PostRepository postRepository;
|
||||||
private final FavoriteRepository favoriteRepository;
|
|
||||||
private final PostModerationExecutorService postModerationExecutorService;
|
private final PostModerationExecutorService postModerationExecutorService;
|
||||||
private final PostCacheService postCacheService;
|
private final PostDeletionService postDeletionService;
|
||||||
private final MapCacheService mapCacheService;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Runs every day at 00:01 to delete:
|
* Runs every day at 00:01 to delete:
|
||||||
* 1. Posts with CLOSED status
|
* 1. Posts with CLOSED status
|
||||||
* 2. Posts older than 6 months
|
* 2. Posts older than 6 months
|
||||||
|
*
|
||||||
|
* Удаление идёт через PostDeletionService: вместе с постами чистятся избранное,
|
||||||
|
* ссылки из чатов и файлы в MinIO (раньше файлы оставались мусором в бакете).
|
||||||
*/
|
*/
|
||||||
@Scheduled(cron = "0 1 0 * * ?")
|
@Scheduled(cron = "0 1 0 * * ?")
|
||||||
@Transactional
|
@Transactional
|
||||||
@@ -37,49 +41,27 @@ public class SchedulerService {
|
|||||||
|
|
||||||
LocalDateTime sixMonthsAgo = LocalDateTime.now().minusMonths(6);
|
LocalDateTime sixMonthsAgo = LocalDateTime.now().minusMonths(6);
|
||||||
|
|
||||||
// Find and delete posts with CLOSED status
|
|
||||||
List<Post> closedPosts = postRepository.findByStatus(PostStatus.CLOSED);
|
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);
|
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());
|
Map<Long, Post> expired = Stream.concat(closedPosts.stream(), oldPosts.stream())
|
||||||
}
|
.collect(Collectors.toMap(Post::getId, Function.identity(), (a, b) -> a, LinkedHashMap::new));
|
||||||
|
|
||||||
if (!closedPosts.isEmpty() || !oldPosts.isEmpty()) {
|
postDeletionService.delete(new ArrayList<>(expired.values()));
|
||||||
// Иначе удалённые посты висят в ленте и на карте до TTL кэша
|
log.info("Scheduled cleanup completed: closed={}, older than 6 months={}, deleted={}",
|
||||||
postCacheService.invalidatePosts();
|
closedPosts.size(), oldPosts.size(), expired.size());
|
||||||
mapCacheService.clearMapMarkersCache();
|
|
||||||
}
|
|
||||||
|
|
||||||
log.info("Scheduled cleanup completed successfully");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Каждые 60 секунд забирает посты, ожидающие модерации, и прогоняет их через
|
* Каждые 60 секунд забирает посты, ожидающие модерации, и прогоняет их через
|
||||||
* ContentModerationFacade. Изображения к этому моменту уже лежат в MinIO
|
* ContentModerationFacade. Изображения к этому моменту уже лежат в MinIO
|
||||||
* (залиты синхронно в PostService.create/update) — оригинальные MultipartFile
|
* (залиты синхронно в PostService.create/update) — оригинальные MultipartFile
|
||||||
* из запроса уже недоступны (Tomcat удаляет temp-файл сразу после завершения
|
* из запроса уже недоступны, поэтому PostModerationExecutorService скачивает их заново.
|
||||||
* запроса), поэтому скачиваем их заново и оборачиваем в ByteArrayMultipartFile,
|
|
||||||
* чтобы не менять сигнатуру ContentModerationFacade.
|
|
||||||
*
|
*
|
||||||
* Сама обработка одного поста вынесена в отдельный бин PostModerationExecutor —
|
* Сама обработка одного поста вынесена в отдельный бин: ему нужны собственные
|
||||||
* вызов через него идёт через Spring-прокси, поэтому @Transactional на
|
* короткие транзакции до и после вызова AI, а self-invocation внутри этого
|
||||||
* moderateOne реально применяется (self-invocation внутри этого класса привёл бы
|
* класса обошёл бы Spring-прокси.
|
||||||
* к тому, что транзакция не открывалась бы вовсе).
|
|
||||||
*/
|
*/
|
||||||
@Scheduled(fixedDelay = 60_000)
|
@Scheduled(fixedDelay = 60_000)
|
||||||
public void moderatePendingPosts() {
|
public void moderatePendingPosts() {
|
||||||
@@ -90,9 +72,12 @@ public class SchedulerService {
|
|||||||
|
|
||||||
log.info("На модерации {} постов.", pending.size());
|
log.info("На модерации {} постов.", pending.size());
|
||||||
for (Long postId : pending) {
|
for (Long postId : pending) {
|
||||||
postModerationExecutorService.moderateOne(postId);
|
try {
|
||||||
|
postModerationExecutorService.moderateOne(postId);
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
// Один сломанный пост не должен останавливать модерацию остальных
|
||||||
|
log.error("Ошибка модерации поста {}", postId, e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,27 +2,39 @@ package com.krylov.refound.service;
|
|||||||
|
|
||||||
import com.krylov.refound.entity.Statistics;
|
import com.krylov.refound.entity.Statistics;
|
||||||
import com.krylov.refound.repository.StatisticsRepository;
|
import com.krylov.refound.repository.StatisticsRepository;
|
||||||
|
import com.krylov.refound.enums.ErrorCode;
|
||||||
|
import com.krylov.refound.exception.ApiException;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@Transactional
|
@Transactional
|
||||||
public class StatisticsService {
|
public class StatisticsService {
|
||||||
|
/** Единственная строка статистики, её создаёт changelog 009. */
|
||||||
|
private static final Long STATISTICS_ID = 1L;
|
||||||
|
|
||||||
private final StatisticsRepository repository;
|
private final StatisticsRepository repository;
|
||||||
|
|
||||||
public void incrementCreated() {
|
public void incrementCreated() {
|
||||||
Statistics statistics = repository.findById(1L).orElseThrow();
|
if (repository.incrementCreated(STATISTICS_ID) == 0) {
|
||||||
statistics.setPostsCreated(statistics.getPostsCreated() + 1);
|
log.warn("Строка statistics id={} не найдена, счётчик созданных не увеличен", STATISTICS_ID);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void incrementFound() {
|
public void incrementFound() {
|
||||||
Statistics statistics = repository.findById(1L).orElseThrow();
|
if (repository.incrementFound(STATISTICS_ID) == 0) {
|
||||||
statistics.setPostsFound(statistics.getPostsFound() + 1);
|
log.warn("Строка statistics id={} не найдена, счётчик найденных не увеличен", STATISTICS_ID);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
public Statistics getStatistics() {
|
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));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,15 +12,14 @@ import com.krylov.refound.enums.PostCategory;
|
|||||||
import com.krylov.refound.enums.PostStatus;
|
import com.krylov.refound.enums.PostStatus;
|
||||||
import com.krylov.refound.enums.PostType;
|
import com.krylov.refound.enums.PostType;
|
||||||
import com.krylov.refound.exception.ApiException;
|
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.ImageRepository;
|
||||||
import com.krylov.refound.repository.PostRepository;
|
import com.krylov.refound.repository.PostRepository;
|
||||||
import com.krylov.refound.service.FileStorageService;
|
import com.krylov.refound.service.FileStorageService;
|
||||||
import com.krylov.refound.service.GeocodingService;
|
import com.krylov.refound.service.GeocodingService;
|
||||||
|
import com.krylov.refound.service.PostDeletionService;
|
||||||
import com.krylov.refound.service.StatisticsService;
|
import com.krylov.refound.service.StatisticsService;
|
||||||
import com.krylov.refound.service.redis.MapCacheService;
|
|
||||||
import com.krylov.refound.service.redis.PostCacheService;
|
import com.krylov.refound.service.redis.PostCacheService;
|
||||||
|
import com.krylov.refound.util.PostFieldLimits;
|
||||||
import com.krylov.refound.util.PostSpecification;
|
import com.krylov.refound.util.PostSpecification;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.EnumSet;
|
import java.util.EnumSet;
|
||||||
@@ -48,7 +47,7 @@ import org.springframework.web.multipart.MultipartFile;
|
|||||||
* <li>нет проверки владельца — операции доступны любому ADMIN;</li>
|
* <li>нет проверки владельца — операции доступны любому ADMIN;</li>
|
||||||
* <li>редактирование не меняет статус: перевод в MODERATION убрал бы объявление из ленты до
|
* <li>редактирование не меняет статус: перевод в MODERATION убрал бы объявление из ленты до
|
||||||
* прохождения AI-модерации, а в REJECTED — скрыл бы навсегда;</li>
|
* прохождения AI-модерации, а в REJECTED — скрыл бы навсегда;</li>
|
||||||
* <li>удаление чистит ссылки из favorites и chats, потому что каскада в БД нет;</li>
|
* <li>удаление идёт через {@link PostDeletionService}, как и у владельца;</li>
|
||||||
* <li>геокодинг при правке best-effort: недоступность Nominatim не должна блокировать
|
* <li>геокодинг при правке best-effort: недоступность Nominatim не должна блокировать
|
||||||
* исправление текста объявления.</li>
|
* исправление текста объявления.</li>
|
||||||
* </ul>
|
* </ul>
|
||||||
@@ -68,12 +67,10 @@ public class AdminPostService {
|
|||||||
|
|
||||||
private final PostRepository postRepository;
|
private final PostRepository postRepository;
|
||||||
private final ImageRepository imageRepository;
|
private final ImageRepository imageRepository;
|
||||||
private final FavoriteRepository favoriteRepository;
|
|
||||||
private final ChatRepository chatRepository;
|
|
||||||
private final FileStorageService fileStorageService;
|
private final FileStorageService fileStorageService;
|
||||||
private final GeocodingService geocodingService;
|
private final GeocodingService geocodingService;
|
||||||
private final PostCacheService postCacheService;
|
private final PostCacheService postCacheService;
|
||||||
private final MapCacheService mapCacheService;
|
private final PostDeletionService postDeletionService;
|
||||||
private final StatisticsService statisticsService;
|
private final StatisticsService statisticsService;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
@@ -128,6 +125,7 @@ public class AdminPostService {
|
|||||||
|
|
||||||
Post post = findPost(postId);
|
Post post = findPost(postId);
|
||||||
PostStatus statusBeforeEdit = post.getStatus();
|
PostStatus statusBeforeEdit = post.getStatus();
|
||||||
|
PostFieldLimits.validate(title, address, phone, rewardText);
|
||||||
|
|
||||||
post.setType(parseTypeOrThrow(type));
|
post.setType(parseTypeOrThrow(type));
|
||||||
post.setTitle(title);
|
post.setTitle(title);
|
||||||
@@ -147,7 +145,7 @@ public class AdminPostService {
|
|||||||
post.setLongitude(longitude);
|
post.setLongitude(longitude);
|
||||||
resolveLocation(post, latitude, longitude, address);
|
resolveLocation(post, latitude, longitude, address);
|
||||||
} else if (StringUtils.hasText(address)) {
|
} else if (StringUtils.hasText(address)) {
|
||||||
post.setCity(address.trim());
|
post.setCity(PostFieldLimits.cityFromAddress(address));
|
||||||
}
|
}
|
||||||
|
|
||||||
syncImages(post, existingImagesJson, images);
|
syncImages(post, existingImagesJson, images);
|
||||||
@@ -161,17 +159,8 @@ public class AdminPostService {
|
|||||||
@Transactional
|
@Transactional
|
||||||
public void deletePost(Long postId) {
|
public void deletePost(Long postId) {
|
||||||
Post post = findPost(postId);
|
Post post = findPost(postId);
|
||||||
|
// Чистит favorites и ссылки из chats (каскада в БД нет), файлы — после коммита
|
||||||
for (Image image : post.getImages()) {
|
postDeletionService.delete(List.of(post));
|
||||||
deleteFileQuietly(image.getUrl());
|
|
||||||
}
|
|
||||||
// На posts ссылаются favorites и chats, ON DELETE CASCADE в БД нет:
|
|
||||||
// без явной чистки удаление падало бы на внешнем ключе.
|
|
||||||
favoriteRepository.deleteByPostIn(List.of(post));
|
|
||||||
chatRepository.clearPostReference(postId);
|
|
||||||
|
|
||||||
postRepository.delete(post);
|
|
||||||
invalidateCaches();
|
|
||||||
|
|
||||||
log.info("Post {} deleted by admin", postId);
|
log.info("Post {} deleted by admin", postId);
|
||||||
}
|
}
|
||||||
@@ -219,7 +208,7 @@ public class AdminPostService {
|
|||||||
log.warn("Геокодинг недоступен, город берём из address: postId={}, {}", post.getId(), e.getMessage());
|
log.warn("Геокодинг недоступен, город берём из address: postId={}, {}", post.getId(), e.getMessage());
|
||||||
}
|
}
|
||||||
if (StringUtils.hasText(address)) {
|
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()
|
List<Image> toRemove = post.getImages().stream()
|
||||||
.filter(image -> !keepUrls.contains(image.getUrl()))
|
.filter(image -> !keepUrls.contains(image.getUrl()))
|
||||||
.toList();
|
.toList();
|
||||||
for (Image image : toRemove) {
|
|
||||||
deleteFileQuietly(image.getUrl());
|
|
||||||
}
|
|
||||||
post.getImages().removeAll(toRemove);
|
post.getImages().removeAll(toRemove);
|
||||||
|
postDeletionService.deleteFilesAfterCommit(toRemove.stream().map(Image::getUrl).toList());
|
||||||
|
|
||||||
if (newImages == null) {
|
if (newImages == null) {
|
||||||
return;
|
return;
|
||||||
@@ -263,15 +250,6 @@ public class AdminPostService {
|
|||||||
|
|
||||||
private void invalidateCaches() {
|
private void invalidateCaches() {
|
||||||
postCacheService.invalidatePosts();
|
postCacheService.invalidatePosts();
|
||||||
mapCacheService.clearMapMarkersCache();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void deleteFileQuietly(String objectKey) {
|
|
||||||
try {
|
|
||||||
fileStorageService.deleteFile(objectKey);
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("Не удалось удалить файл из хранилища: {}", objectKey, e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Один запрос вместо N+1 при сборке страницы объявлений. */
|
/** Один запрос вместо N+1 при сборке страницы объявлений. */
|
||||||
|
|||||||
@@ -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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
52
src/main/java/com/krylov/refound/util/PostFieldLimits.java
Normal file
52
src/main/java/com/krylov/refound/util/PostFieldLimits.java
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,10 +19,17 @@ spring:
|
|||||||
# из-за чего базы расходились. Для разработки можно переопределить
|
# из-за чего базы расходились. Для разработки можно переопределить
|
||||||
# переменной окружения JPA_DDL_AUTO=update.
|
# переменной окружения JPA_DDL_AUTO=update.
|
||||||
ddl-auto: ${JPA_DDL_AUTO:validate}
|
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:
|
properties:
|
||||||
hibernate:
|
hibernate:
|
||||||
format_sql: true
|
format_sql: true
|
||||||
|
# Ленивые коллекции (images) и связи (user) грузятся пачками по id,
|
||||||
|
# а не по одному запросу на пост — убирает N+1 в ленте, избранном и чистке
|
||||||
|
default_batch_fetch_size: 50
|
||||||
|
|
||||||
data:
|
data:
|
||||||
redis:
|
redis:
|
||||||
|
|||||||
@@ -23,14 +23,12 @@ import com.krylov.refound.enums.PostCategory;
|
|||||||
import com.krylov.refound.enums.PostStatus;
|
import com.krylov.refound.enums.PostStatus;
|
||||||
import com.krylov.refound.enums.PostType;
|
import com.krylov.refound.enums.PostType;
|
||||||
import com.krylov.refound.exception.ApiException;
|
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.ImageRepository;
|
||||||
import com.krylov.refound.repository.PostRepository;
|
import com.krylov.refound.repository.PostRepository;
|
||||||
import com.krylov.refound.service.FileStorageService;
|
import com.krylov.refound.service.FileStorageService;
|
||||||
import com.krylov.refound.service.GeocodingService;
|
import com.krylov.refound.service.GeocodingService;
|
||||||
|
import com.krylov.refound.service.PostDeletionService;
|
||||||
import com.krylov.refound.service.StatisticsService;
|
import com.krylov.refound.service.StatisticsService;
|
||||||
import com.krylov.refound.service.redis.MapCacheService;
|
|
||||||
import com.krylov.refound.service.redis.PostCacheService;
|
import com.krylov.refound.service.redis.PostCacheService;
|
||||||
import jakarta.persistence.criteria.CriteriaBuilder;
|
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||||
import jakarta.persistence.criteria.CriteriaQuery;
|
import jakarta.persistence.criteria.CriteriaQuery;
|
||||||
@@ -63,17 +61,13 @@ class AdminPostServiceTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private ImageRepository imageRepository;
|
private ImageRepository imageRepository;
|
||||||
@Mock
|
@Mock
|
||||||
private FavoriteRepository favoriteRepository;
|
|
||||||
@Mock
|
|
||||||
private ChatRepository chatRepository;
|
|
||||||
@Mock
|
|
||||||
private FileStorageService fileStorageService;
|
private FileStorageService fileStorageService;
|
||||||
@Mock
|
@Mock
|
||||||
private GeocodingService geocodingService;
|
private GeocodingService geocodingService;
|
||||||
@Mock
|
@Mock
|
||||||
private PostCacheService postCacheService;
|
private PostCacheService postCacheService;
|
||||||
@Mock
|
@Mock
|
||||||
private MapCacheService mapCacheService;
|
private PostDeletionService postDeletionService;
|
||||||
@Mock
|
@Mock
|
||||||
private StatisticsService statisticsService;
|
private StatisticsService statisticsService;
|
||||||
|
|
||||||
@@ -244,7 +238,6 @@ class AdminPostServiceTest {
|
|||||||
assertThat(post.getCity()).isEqualTo("Москва");
|
assertThat(post.getCity()).isEqualTo("Москва");
|
||||||
assertThat(post.getIsReward()).isTrue();
|
assertThat(post.getIsReward()).isTrue();
|
||||||
verify(postCacheService).invalidatePosts();
|
verify(postCacheService).invalidatePosts();
|
||||||
verify(mapCacheService).clearMapMarkersCache();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -265,8 +258,9 @@ class AdminPostServiceTest {
|
|||||||
false, null, List.of(), "[\"images/keep.png\"]");
|
false, null, List.of(), "[\"images/keep.png\"]");
|
||||||
|
|
||||||
assertThat(post.getImages()).extracting(Image::getUrl).containsExactly("images/keep.png");
|
assertThat(post.getImages()).extracting(Image::getUrl).containsExactly("images/keep.png");
|
||||||
verify(fileStorageService).deleteFile("images/drop.png");
|
// Файл удаляется после коммита, а не посреди транзакции
|
||||||
verify(fileStorageService, never()).deleteFile("images/keep.png");
|
verify(postDeletionService).deleteFilesAfterCommit(List.of("images/drop.png"));
|
||||||
|
verify(fileStorageService, never()).deleteFile(any());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -357,38 +351,24 @@ class AdminPostServiceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void deletePost_clearsFilesFavoritesAndChatLinks() {
|
void deletePost_delegatesToPostDeletionService() {
|
||||||
Post post = post(1L, PostStatus.CLOSED);
|
Post post = post(1L, PostStatus.CLOSED);
|
||||||
Image image = new Image();
|
|
||||||
image.setUrl("images/cat.png");
|
|
||||||
image.setPost(post);
|
|
||||||
post.getImages().add(image);
|
|
||||||
|
|
||||||
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
|
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
|
||||||
|
|
||||||
service.deletePost(1L);
|
service.deletePost(1L);
|
||||||
|
|
||||||
verify(fileStorageService).deleteFile("images/cat.png");
|
verify(postDeletionService).delete(List.of(post));
|
||||||
verify(favoriteRepository).deleteByPostIn(anyList());
|
|
||||||
verify(chatRepository).clearPostReference(1L);
|
|
||||||
verify(postRepository).delete(post);
|
|
||||||
verify(postCacheService).invalidatePosts();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void deletePost_doesNotFailWhenFileStorageIsDown() {
|
void updatePost_rejectsTooLongTitle() {
|
||||||
Post post = post(1L, PostStatus.CLOSED);
|
Post post = post(1L, PostStatus.ACTIVE);
|
||||||
Image image = new Image();
|
|
||||||
image.setUrl("images/cat.png");
|
|
||||||
image.setPost(post);
|
|
||||||
post.getImages().add(image);
|
|
||||||
|
|
||||||
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
|
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
|
||||||
org.mockito.Mockito.doThrow(new RuntimeException("MinIO недоступен"))
|
|
||||||
.when(fileStorageService).deleteFile(any());
|
|
||||||
|
|
||||||
service.deletePost(1L);
|
assertThatThrownBy(() -> service.updatePost(1L, "LOSS", "к".repeat(256), null, null, null, null, null,
|
||||||
|
null, false, null, List.of(), "[]"))
|
||||||
verify(postRepository).delete(post);
|
.isInstanceOf(ApiException.class)
|
||||||
|
.satisfies(ex -> assertThat(((ApiException) ex).getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||||
|
verify(postRepository, never()).save(any(Post.class));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user