-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNotificationService.java
More file actions
144 lines (121 loc) · 6.36 KB
/
NotificationService.java
File metadata and controls
144 lines (121 loc) · 6.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package com.example.RealMatch.notification.application.service;
import java.util.Set;
import java.util.UUID;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.example.RealMatch.global.exception.CustomException;
import com.example.RealMatch.notification.application.dto.CreateNotificationCommand;
import com.example.RealMatch.notification.domain.entity.Notification;
import com.example.RealMatch.notification.domain.entity.NotificationDelivery;
import com.example.RealMatch.notification.domain.entity.NotificationOutbox;
import com.example.RealMatch.notification.domain.entity.enums.DeliveryStatus;
import com.example.RealMatch.notification.domain.entity.enums.NotificationKind;
import com.example.RealMatch.notification.domain.repository.NotificationDeliveryRepository;
import com.example.RealMatch.notification.domain.repository.NotificationOutboxRepository;
import com.example.RealMatch.notification.domain.repository.NotificationRepository;
import com.example.RealMatch.notification.exception.NotificationErrorCode;
import com.example.RealMatch.notification.infrastructure.redis.NotificationUnreadCountCache;
import com.example.RealMatch.user.domain.entity.enums.NotificationChannel;
import lombok.RequiredArgsConstructor;
/**
* 알림 생성 서비스 (Outbox 패턴).
* Notification + Delivery(PENDING) + Outbox(PENDING)를 한 트랜잭션에 원자적 저장.
* MQ 발행은 이 서비스에서 금지 — OutboxPublisher가 별도로 처리.
*/
@Service
@RequiredArgsConstructor
@Transactional
public class NotificationService {
private static final Logger LOG = LoggerFactory.getLogger(NotificationService.class);
private final NotificationRepository notificationRepository;
private final NotificationDeliveryRepository notificationDeliveryRepository;
private final NotificationOutboxRepository notificationOutboxRepository;
private final NotificationChannelResolver channelResolver;
private final NotificationUnreadCountCache unreadCountCache;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Notification create(CreateNotificationCommand command) {
Notification notification = Notification.builder()
.userId(command.getUserId())
.kind(command.getKind())
.title(command.getTitle())
.body(command.getBody())
.referenceType(command.getReferenceType())
.referenceId(command.getReferenceId())
.campaignId(command.getCampaignId())
.proposalId(command.getProposalId())
.build();
Notification savedNotification = notificationRepository.save(notification);
unreadCountCache.invalidate(command.getUserId());
createPendingDeliveriesWithOutbox(
savedNotification.getId(),
command.getKind(),
command.getEventId(),
command.getUserId());
return savedNotification;
}
private void createPendingDeliveriesWithOutbox(UUID notificationId, NotificationKind kind,
String eventId, Long receiverId) {
Set<NotificationChannel> channels = channelResolver.resolveChannels(kind);
for (NotificationChannel channel : channels) {
String idempotencyKey = generateIdempotencyKey(eventId, kind, receiverId, channel);
try {
// Delivery(PENDING) 생성
NotificationDelivery delivery = NotificationDelivery.builder()
.notificationId(notificationId)
.channel(channel)
.status(DeliveryStatus.PENDING)
.idempotencyKey(idempotencyKey)
.build();
NotificationDelivery savedDelivery = notificationDeliveryRepository.save(delivery);
// Outbox(PENDING) 생성 — 같은 TX
NotificationOutbox outbox = NotificationOutbox.builder()
.deliveryId(savedDelivery.getId())
.notificationId(notificationId)
.channel(channel)
.build();
notificationOutboxRepository.save(outbox);
LOG.debug("[Notification] Created delivery + outbox. idempotencyKey={}, channel={}",
idempotencyKey, channel);
} catch (DataIntegrityViolationException e) {
if (e.getCause() instanceof ConstraintViolationException) {
LOG.debug("[Notification] Delivery already exists (idempotent). idempotencyKey={}, channel={}",
idempotencyKey, channel);
} else {
throw e;
}
}
}
}
private String generateIdempotencyKey(String eventId, NotificationKind kind,
Long receiverId, NotificationChannel channel) {
return String.format("%s:%s:%d:%s", eventId, kind, receiverId, channel);
}
public void markAsRead(Long userId, UUID notificationId) {
Notification notification = findNotificationForUser(userId, notificationId);
notification.markAsRead();
unreadCountCache.invalidate(userId);
}
public int markAllAsRead(Long userId) {
int count = notificationRepository.markAllAsRead(userId);
unreadCountCache.invalidate(userId);
return count;
}
public void softDelete(Long userId, UUID notificationId) {
Notification notification = findNotificationForUser(userId, notificationId);
notification.softDelete();
unreadCountCache.invalidate(userId);
}
private Notification findNotificationForUser(Long userId, UUID notificationId) {
Notification notification = notificationRepository.findById(notificationId)
.orElseThrow(() -> new CustomException(NotificationErrorCode.NOTIFICATION_NOT_FOUND));
if (!notification.getUserId().equals(userId)) {
throw new CustomException(NotificationErrorCode.NOTIFICATION_FORBIDDEN);
}
return notification;
}
}