|
| 1 | +package org.devkor.apu.saerok_server.domain.community.application; |
| 2 | + |
| 3 | +import lombok.RequiredArgsConstructor; |
| 4 | +import lombok.extern.slf4j.Slf4j; |
| 5 | +import org.devkor.apu.saerok_server.domain.collection.core.entity.UserBirdCollection; |
| 6 | +import org.devkor.apu.saerok_server.domain.community.core.entity.PopularCollection; |
| 7 | +import org.devkor.apu.saerok_server.domain.community.core.repository.PopularCollectionRepository; |
| 8 | +import org.devkor.apu.saerok_server.domain.community.core.repository.TrendingCollectionRepository; |
| 9 | +import org.devkor.apu.saerok_server.domain.community.core.repository.dto.TrendingCollectionCandidate; |
| 10 | +import org.springframework.stereotype.Service; |
| 11 | +import org.springframework.transaction.annotation.Transactional; |
| 12 | + |
| 13 | +import java.time.Duration; |
| 14 | +import java.time.OffsetDateTime; |
| 15 | +import java.time.ZoneId; |
| 16 | +import java.util.*; |
| 17 | +import java.util.stream.IntStream; |
| 18 | + |
| 19 | +@Slf4j |
| 20 | +@Service |
| 21 | +@Transactional |
| 22 | +@RequiredArgsConstructor |
| 23 | +public class PopularCollectionBatchService { |
| 24 | + |
| 25 | + private static final ZoneId KST = ZoneId.of("Asia/Seoul"); |
| 26 | + |
| 27 | + private static final double POPULARITY_LIKE_WEIGHT = 1.0; |
| 28 | + private static final double POPULARITY_COMMENT_WEIGHT = 1.2; |
| 29 | + private static final double FRESHNESS_LIKE_RATIO = 0.7; |
| 30 | + private static final double FRESHNESS_COMMENT_RATIO = 0.3; |
| 31 | + private static final double LAST_ACTIVITY_WINDOW_DAYS = 7.0; |
| 32 | + private static final double HALF_LIFE_DAYS = 3.0; |
| 33 | + private static final int CANDIDATE_DAYS = 120; |
| 34 | + private static final int POPULAR_LIMIT = 5; |
| 35 | + |
| 36 | + private final PopularCollectionRepository popularCollectionRepository; |
| 37 | + private final TrendingCollectionRepository trendingCollectionRepository; |
| 38 | + private final jakarta.persistence.EntityManager em; |
| 39 | + |
| 40 | + public void refreshPopularCollections() { |
| 41 | + OffsetDateTime now = OffsetDateTime.now(KST); |
| 42 | + log.info("[popular] refreshing popular collections at {}", now); |
| 43 | + |
| 44 | + List<TrendingCollectionCandidate> candidates = trendingCollectionRepository |
| 45 | + .findRecentPublicCollections(now.minusDays(CANDIDATE_DAYS)); |
| 46 | + if (candidates.isEmpty()) { |
| 47 | + popularCollectionRepository.deleteAll(); |
| 48 | + log.info("[popular] no candidates found; table truncated"); |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + List<Long> candidateIds = candidates.stream() |
| 53 | + .map(TrendingCollectionCandidate::collectionId) |
| 54 | + .toList(); |
| 55 | + |
| 56 | + Map<Long, List<OffsetDateTime>> likeCreatedAts = trendingCollectionRepository |
| 57 | + .findLikeCreatedAtByCollectionIds(candidateIds); |
| 58 | + Map<Long, Map<Long, OffsetDateTime>> lastCommentAtByUser = trendingCollectionRepository |
| 59 | + .findLastCommentAtByCollectionIds(candidateIds); |
| 60 | + |
| 61 | + List<PopularCandidateSnapshot> ranked = candidates.stream() |
| 62 | + .map(candidate -> buildSnapshot(candidate, now, likeCreatedAts, lastCommentAtByUser)) |
| 63 | + .filter(Objects::nonNull) |
| 64 | + .sorted(Comparator.comparingDouble(PopularCandidateSnapshot::trendingScore).reversed() |
| 65 | + .thenComparing(snapshot -> snapshot.collection().getId())) |
| 66 | + .limit(POPULAR_LIMIT) |
| 67 | + .toList(); |
| 68 | + |
| 69 | + List<PopularCandidateSnapshot> shuffled = new ArrayList<>(ranked); |
| 70 | + Collections.shuffle(shuffled); |
| 71 | + |
| 72 | + List<PopularCollection> rankedAndShuffled = IntStream.range(0, shuffled.size()) |
| 73 | + .mapToObj(idx -> toPopularCollection(shuffled.get(idx), now, idx)) |
| 74 | + .toList(); |
| 75 | + |
| 76 | + popularCollectionRepository.deleteAll(); |
| 77 | + popularCollectionRepository.saveAll(rankedAndShuffled); |
| 78 | + |
| 79 | + log.info("[popular] refreshed {} rows", rankedAndShuffled.size()); |
| 80 | + } |
| 81 | + |
| 82 | + private PopularCandidateSnapshot buildSnapshot( |
| 83 | + TrendingCollectionCandidate candidate, |
| 84 | + OffsetDateTime now, |
| 85 | + Map<Long, List<OffsetDateTime>> likeCreatedAts, |
| 86 | + Map<Long, Map<Long, OffsetDateTime>> lastCommentAtByUser |
| 87 | + ) { |
| 88 | + List<OffsetDateTime> likes = likeCreatedAts.getOrDefault(candidate.collectionId(), List.of()); |
| 89 | + Map<Long, OffsetDateTime> commentsByUser = lastCommentAtByUser.getOrDefault(candidate.collectionId(), Map.of()); |
| 90 | + |
| 91 | + long likeCount = likes.size(); |
| 92 | + long commentUserCount = commentsByUser.size(); |
| 93 | + if (likeCount == 0 && commentUserCount == 0) { |
| 94 | + return null; |
| 95 | + } |
| 96 | + |
| 97 | + double popularityScore = POPULARITY_LIKE_WEIGHT * Math.log(1 + likeCount) |
| 98 | + + POPULARITY_COMMENT_WEIGHT * Math.log(1 + commentUserCount); |
| 99 | + |
| 100 | + double decayedLikes = likes.stream() |
| 101 | + .mapToDouble(ts -> decay(ts, now)) |
| 102 | + .sum(); |
| 103 | + double decayedCommentUsers = commentsByUser.values().stream() |
| 104 | + .mapToDouble(ts -> decay(ts, now)) |
| 105 | + .sum(); |
| 106 | + |
| 107 | + double freshnessCore = FRESHNESS_LIKE_RATIO * decayedLikes |
| 108 | + + FRESHNESS_COMMENT_RATIO * decayedCommentUsers; |
| 109 | + |
| 110 | + OffsetDateTime lastCommentAt = commentsByUser.values().stream() |
| 111 | + .max(Comparator.naturalOrder()) |
| 112 | + .orElse(null); |
| 113 | + double lastActivityBonus = 0.0; |
| 114 | + if (lastCommentAt != null) { |
| 115 | + double ageDays = daysBetween(lastCommentAt, now); |
| 116 | + lastActivityBonus = Math.max(0.0, 1 - ageDays / LAST_ACTIVITY_WINDOW_DAYS); |
| 117 | + } |
| 118 | + |
| 119 | + double freshnessScore = freshnessCore * (0.7 + 0.3 * lastActivityBonus); |
| 120 | + double trendingScore = popularityScore * freshnessScore; |
| 121 | + if (trendingScore <= 0) { |
| 122 | + return null; |
| 123 | + } |
| 124 | + |
| 125 | + UserBirdCollection ref = em.getReference(UserBirdCollection.class, candidate.collectionId()); |
| 126 | + return new PopularCandidateSnapshot(ref, popularityScore, freshnessScore, trendingScore); |
| 127 | + } |
| 128 | + |
| 129 | + private double decay(OffsetDateTime eventTime, OffsetDateTime now) { |
| 130 | + double ageDays = daysBetween(eventTime, now); |
| 131 | + return Math.pow(0.5, ageDays / HALF_LIFE_DAYS); |
| 132 | + } |
| 133 | + |
| 134 | + private double daysBetween(OffsetDateTime earlier, OffsetDateTime later) { |
| 135 | + double seconds = Duration.between(earlier, later).getSeconds(); |
| 136 | + double days = seconds / 86_400d; |
| 137 | + return Math.max(0d, days); |
| 138 | + } |
| 139 | + |
| 140 | + private PopularCollection toPopularCollection(PopularCandidateSnapshot snapshot, OffsetDateTime calculatedAt, int displayOrder) { |
| 141 | + return new PopularCollection( |
| 142 | + snapshot.collection(), |
| 143 | + snapshot.popularityScore(), |
| 144 | + snapshot.freshnessScore(), |
| 145 | + snapshot.trendingScore(), |
| 146 | + calculatedAt, |
| 147 | + displayOrder |
| 148 | + ); |
| 149 | + } |
| 150 | + |
| 151 | + private record PopularCandidateSnapshot( |
| 152 | + UserBirdCollection collection, |
| 153 | + double popularityScore, |
| 154 | + double freshnessScore, |
| 155 | + double trendingScore |
| 156 | + ) { |
| 157 | + } |
| 158 | +} |
0 commit comments