Merge pull request #61 from SlimusMinus/feat-closed_posts_ttl
All checks were successful
deploy-backend / deploy (push) Successful in 1m32s
All checks were successful
deploy-backend / deploy (push) Successful in 1m32s
Delete CLOSED posts only a week after closing; track closedAt
This commit is contained in:
@@ -25,6 +25,8 @@ public class PostResponse {
|
|||||||
private PostType type;
|
private PostType type;
|
||||||
private PostStatus status;
|
private PostStatus status;
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
/** Когда пост закрыт (status = CLOSED); фронт показывает дату «найдено». */
|
||||||
|
private LocalDateTime closedAt;
|
||||||
/** Логин автора. */
|
/** Логин автора. */
|
||||||
private String userLogin;
|
private String userLogin;
|
||||||
private String phone;
|
private String phone;
|
||||||
|
|||||||
@@ -58,6 +58,11 @@ public class Post {
|
|||||||
@Enumerated(EnumType.STRING)
|
@Enumerated(EnumType.STRING)
|
||||||
private PostStatus status;
|
private PostStatus status;
|
||||||
|
|
||||||
|
// Когда пост перешёл в CLOSED; по нему SchedulerService удаляет закрытые
|
||||||
|
// больше недели назад. Ведётся в setStatus — менять напрямую не нужно.
|
||||||
|
@Setter(lombok.AccessLevel.NONE)
|
||||||
|
private LocalDateTime closedAt;
|
||||||
|
|
||||||
@ManyToOne
|
@ManyToOne
|
||||||
@JsonIgnore
|
@JsonIgnore
|
||||||
private User user;
|
private User user;
|
||||||
@@ -67,4 +72,19 @@ public class Post {
|
|||||||
@OrderBy("id ASC")
|
@OrderBy("id ASC")
|
||||||
private List<Image> images = new ArrayList<>();
|
private List<Image> images = new ArrayList<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Меняет статус и ведёт closedAt: переход в CLOSED ставит время закрытия,
|
||||||
|
* уход из CLOSED (переоткрытие, правка с повторной модерацией) его сбрасывает.
|
||||||
|
* Повторный CLOSED у уже закрытого поста время не сдвигает.
|
||||||
|
*/
|
||||||
|
public void setStatus(PostStatus status) {
|
||||||
|
if (status == PostStatus.CLOSED) {
|
||||||
|
if (this.status != PostStatus.CLOSED || closedAt == null) {
|
||||||
|
closedAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
closedAt = null;
|
||||||
|
}
|
||||||
|
this.status = status;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ public interface PostRepository extends JpaRepository<Post, Long>, JpaSpecificat
|
|||||||
|
|
||||||
Page<Post> findByUserIdAndStatusIn(Long userId, Collection<PostStatus> statuses, Pageable pageable);
|
Page<Post> findByUserIdAndStatusIn(Long userId, Collection<PostStatus> statuses, Pageable pageable);
|
||||||
|
|
||||||
List<Post> findByStatus(PostStatus status);
|
List<Post> findByStatusAndClosedAtBefore(PostStatus status, LocalDateTime closedBefore);
|
||||||
|
|
||||||
List<Post> findByCreatedAtBefore(LocalDateTime date);
|
List<Post> findByCreatedAtBefore(LocalDateTime date);
|
||||||
|
|
||||||
|
|||||||
@@ -27,14 +27,17 @@ public class SchedulerService {
|
|||||||
/** Меньше lockAtMostFor задачи модерации (10 минут). */
|
/** Меньше lockAtMostFor задачи модерации (10 минут). */
|
||||||
private static final Duration MODERATION_RUN_BUDGET = Duration.ofMinutes(8);
|
private static final Duration MODERATION_RUN_BUDGET = Duration.ofMinutes(8);
|
||||||
|
|
||||||
|
/** Сколько закрытый пост остаётся в ленте, прежде чем его удалит ночная задача. */
|
||||||
|
static final Duration CLOSED_POST_TTL = Duration.ofDays(7);
|
||||||
|
|
||||||
private final PostRepository postRepository;
|
private final PostRepository postRepository;
|
||||||
private final PostModerationExecutorService postModerationExecutorService;
|
private final PostModerationExecutorService postModerationExecutorService;
|
||||||
private final PostDeletionService postDeletionService;
|
private final PostDeletionService postDeletionService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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 closed more than a week ago (by closedAt)
|
||||||
* 2. Posts older than 6 months
|
* 2. Posts older than 6 months (any status)
|
||||||
*
|
*
|
||||||
* Удаление идёт через PostDeletionService: вместе с постами чистятся избранное,
|
* Удаление идёт через PostDeletionService: вместе с постами чистятся избранное,
|
||||||
* ссылки из чатов и файлы в MinIO (раньше файлы оставались мусором в бакете).
|
* ссылки из чатов и файлы в MinIO (раньше файлы оставались мусором в бакете).
|
||||||
@@ -45,9 +48,11 @@ public class SchedulerService {
|
|||||||
public void deleteExpiredPosts() {
|
public void deleteExpiredPosts() {
|
||||||
log.info("Starting scheduled cleanup of expired posts...");
|
log.info("Starting scheduled cleanup of expired posts...");
|
||||||
|
|
||||||
LocalDateTime sixMonthsAgo = LocalDateTime.now().minusMonths(6);
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
LocalDateTime sixMonthsAgo = now.minusMonths(6);
|
||||||
|
LocalDateTime closedBefore = now.minus(CLOSED_POST_TTL);
|
||||||
|
|
||||||
List<Post> closedPosts = postRepository.findByStatus(PostStatus.CLOSED);
|
List<Post> closedPosts = postRepository.findByStatusAndClosedAtBefore(PostStatus.CLOSED, closedBefore);
|
||||||
List<Post> oldPosts = postRepository.findByCreatedAtBefore(sixMonthsAgo);
|
List<Post> oldPosts = postRepository.findByCreatedAtBefore(sixMonthsAgo);
|
||||||
|
|
||||||
// Закрытый пост бывает и старым — удаляем каждый один раз
|
// Закрытый пост бывает и старым — удаляем каждый один раз
|
||||||
@@ -55,7 +60,7 @@ public class SchedulerService {
|
|||||||
.collect(Collectors.toMap(Post::getId, Function.identity(), (a, b) -> a, LinkedHashMap::new));
|
.collect(Collectors.toMap(Post::getId, Function.identity(), (a, b) -> a, LinkedHashMap::new));
|
||||||
|
|
||||||
postDeletionService.delete(new ArrayList<>(expired.values()));
|
postDeletionService.delete(new ArrayList<>(expired.values()));
|
||||||
log.info("Scheduled cleanup completed: closed={}, older than 6 months={}, deleted={}",
|
log.info("Scheduled cleanup completed: closed more than a week ago={}, older than 6 months={}, deleted={}",
|
||||||
closedPosts.size(), oldPosts.size(), expired.size());
|
closedPosts.size(), oldPosts.size(), expired.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
databaseChangeLog:
|
||||||
|
- changeSet:
|
||||||
|
id: 022-add-closed-at-posts
|
||||||
|
author: krylov
|
||||||
|
comment: >
|
||||||
|
Время перехода поста в CLOSED. Ночная задача удаляет закрытые посты,
|
||||||
|
у которых closed_at старше недели (раньше удалялись все CLOSED сразу).
|
||||||
|
preConditions:
|
||||||
|
onFail: MARK_RAN
|
||||||
|
not:
|
||||||
|
columnExists:
|
||||||
|
tableName: posts
|
||||||
|
columnName: closed_at
|
||||||
|
changes:
|
||||||
|
- addColumn:
|
||||||
|
tableName: posts
|
||||||
|
columns:
|
||||||
|
- column: { name: closed_at, type: TIMESTAMP }
|
||||||
@@ -34,3 +34,4 @@ databaseChangeLog:
|
|||||||
- include: { file: db/changelog/search/019-posts-full-text-search.yaml }
|
- include: { file: db/changelog/search/019-posts-full-text-search.yaml }
|
||||||
- include: { file: db/changelog/search/020-search-words.yaml }
|
- include: { file: db/changelog/search/020-search-words.yaml }
|
||||||
- include: { file: db/changelog/add/021-ad-stats-indexes.yaml }
|
- include: { file: db/changelog/add/021-ad-stats-indexes.yaml }
|
||||||
|
- include: { file: db/changelog/add/022-add-closed-at-posts.yaml }
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.krylov.refound.entity;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import com.krylov.refound.enums.PostStatus;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** closedAt ведётся в Post.setStatus: по нему ночная задача удаляет закрытые посты. */
|
||||||
|
class PostClosedAtTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void closingSetsClosedAt() {
|
||||||
|
Post post = new Post();
|
||||||
|
post.setStatus(PostStatus.ACTIVE);
|
||||||
|
LocalDateTime before = LocalDateTime.now();
|
||||||
|
|
||||||
|
post.setStatus(PostStatus.CLOSED);
|
||||||
|
|
||||||
|
assertThat(post.getClosedAt()).isNotNull().isAfterOrEqualTo(before);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reopeningClearsClosedAt() {
|
||||||
|
Post post = new Post();
|
||||||
|
post.setStatus(PostStatus.CLOSED);
|
||||||
|
|
||||||
|
post.setStatus(PostStatus.ACTIVE);
|
||||||
|
|
||||||
|
assertThat(post.getClosedAt()).isNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void closingAlreadyClosedPostKeepsOriginalTime() throws InterruptedException {
|
||||||
|
Post post = new Post();
|
||||||
|
post.setStatus(PostStatus.CLOSED);
|
||||||
|
LocalDateTime firstClosedAt = post.getClosedAt();
|
||||||
|
Thread.sleep(5);
|
||||||
|
|
||||||
|
post.setStatus(PostStatus.CLOSED);
|
||||||
|
|
||||||
|
assertThat(post.getClosedAt()).isEqualTo(firstClosedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void activeAndModerationPostsHaveNoClosedAt() {
|
||||||
|
Post post = new Post();
|
||||||
|
|
||||||
|
post.setStatus(PostStatus.MODERATION);
|
||||||
|
assertThat(post.getClosedAt()).isNull();
|
||||||
|
|
||||||
|
post.setStatus(PostStatus.ACTIVE);
|
||||||
|
assertThat(post.getClosedAt()).isNull();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package com.krylov.refound.service;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.within;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import com.krylov.refound.entity.Post;
|
||||||
|
import com.krylov.refound.enums.PostStatus;
|
||||||
|
import com.krylov.refound.repository.PostRepository;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.List;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
|
||||||
|
class SchedulerServiceDeleteExpiredPostsTest {
|
||||||
|
|
||||||
|
private PostRepository postRepository;
|
||||||
|
private PostDeletionService postDeletionService;
|
||||||
|
private SchedulerService service;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
postRepository = mock(PostRepository.class);
|
||||||
|
postDeletionService = mock(PostDeletionService.class);
|
||||||
|
service = new SchedulerService(postRepository, mock(PostModerationExecutorService.class), postDeletionService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deletesOnlyPostsClosedMoreThanAWeekAgo() {
|
||||||
|
when(postRepository.findByStatusAndClosedAtBefore(any(), any())).thenReturn(List.of());
|
||||||
|
when(postRepository.findByCreatedAtBefore(any())).thenReturn(List.of());
|
||||||
|
|
||||||
|
service.deleteExpiredPosts();
|
||||||
|
|
||||||
|
ArgumentCaptor<LocalDateTime> closedBefore = ArgumentCaptor.forClass(LocalDateTime.class);
|
||||||
|
verify(postRepository).findByStatusAndClosedAtBefore(eq(PostStatus.CLOSED), closedBefore.capture());
|
||||||
|
assertThat(closedBefore.getValue()).isCloseTo(LocalDateTime.now().minusDays(7), within(1, ChronoUnit.MINUTES));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void stillDeletesPostsOlderThanSixMonths() {
|
||||||
|
when(postRepository.findByStatusAndClosedAtBefore(any(), any())).thenReturn(List.of());
|
||||||
|
when(postRepository.findByCreatedAtBefore(any())).thenReturn(List.of());
|
||||||
|
|
||||||
|
service.deleteExpiredPosts();
|
||||||
|
|
||||||
|
ArgumentCaptor<LocalDateTime> createdBefore = ArgumentCaptor.forClass(LocalDateTime.class);
|
||||||
|
verify(postRepository).findByCreatedAtBefore(createdBefore.capture());
|
||||||
|
assertThat(createdBefore.getValue()).isCloseTo(LocalDateTime.now().minusMonths(6), within(1, ChronoUnit.MINUTES));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void postThatIsBothClosedAndOldIsDeletedOnce() {
|
||||||
|
Post closedAndOld = post(1L);
|
||||||
|
Post onlyOld = post(2L);
|
||||||
|
when(postRepository.findByStatusAndClosedAtBefore(any(), any())).thenReturn(List.of(closedAndOld));
|
||||||
|
when(postRepository.findByCreatedAtBefore(any())).thenReturn(List.of(closedAndOld, onlyOld));
|
||||||
|
|
||||||
|
service.deleteExpiredPosts();
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
ArgumentCaptor<List<Post>> deleted = ArgumentCaptor.forClass(List.class);
|
||||||
|
verify(postDeletionService).delete(deleted.capture());
|
||||||
|
assertThat(deleted.getValue()).containsExactly(closedAndOld, onlyOld);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Post post(Long id) {
|
||||||
|
Post post = new Post();
|
||||||
|
post.setId(id);
|
||||||
|
return post;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user