Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
Expand Down Expand Up @@ -315,8 +316,8 @@ public void withdraw(String tokenHeader) {
jwtService.deleteRefreshToken(userId);
}

@Transactional
// 소셜 로그인 연결 해제
// 외부 연동 실패가 영구탈퇴의 내부 데이터 정리 트랜잭션까지 rollback시키지 않도록 분리한다.
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void revoke(Long userId) {
// 현재 트랜잭션 안에서 유저를 다시 조회 (영속화)
User user = userRepository.findById(userId)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.hrr.backend.domain.fcm.dto;

/** FCM에는 token만 전달하고, 내부 ID는 실패한 대상 추적에만 사용한다. */
public record FcmTokenTargetDto(
Long fcmTokenId,
Long userId,
String token
) {
@Override
public String toString() {
return "FcmTokenTargetDto[fcmTokenId=" + fcmTokenId
+ ", userId=" + userId
+ ", token=[REDACTED]]";
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.hrr.backend.domain.fcm.repository;

import com.hrr.backend.domain.fcm.entity.FcmToken;
import com.hrr.backend.domain.fcm.dto.FcmTokenTargetDto;
import com.hrr.backend.domain.user.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
Expand All @@ -22,12 +23,13 @@ public interface FcmTokenRepository extends JpaRepository<FcmToken, Long> {
@Query("SELECT t.token FROM FcmToken t WHERE t.user = :user AND t.isActive = true")
List<String> findAllActiveTokensByUser(@Param("user") User user);

// 여러 유저의 활성화된 FCM 토큰 목록을 한 번에 조회 (벌크 발송용, N+1 방지)
@Query("SELECT t.token FROM FcmToken t WHERE t.user IN :users AND t.isActive = true")
List<String> findAllActiveTokensByUsers(@Param("users") List<User> users);
// 응답 순서와 사용자/토큰 레코드를 연결할 수 있도록 내부 ID도 함께 조회한다.
@Query("SELECT new com.hrr.backend.domain.fcm.dto.FcmTokenTargetDto(t.id, t.user.id, t.token) " +
"FROM FcmToken t WHERE t.user IN :users AND t.isActive = true")
List<FcmTokenTargetDto> findAllActiveTokenTargetsByUsers(@Param("users") List<User> users);

// 특정 토큰을 가진 모든 유저의 레코드를 한 번에 비활성화 (중복 토큰 대응)
@Modifying(clearAutomatically = true)
@Query("UPDATE FcmToken t SET t.isActive = false WHERE t.token = :token")
void deactivateAllByToken(@Param("token") String token);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.hrr.backend.domain.fcm.service;

import com.google.firebase.messaging.*;
import com.hrr.backend.domain.fcm.dto.FcmTokenTargetDto;
import com.hrr.backend.domain.fcm.repository.FcmTokenRepository;
import com.hrr.backend.domain.notification.entity.NotificationDelivery;
import com.hrr.backend.domain.notification.entity.NotificationEvent;
Expand All @@ -17,6 +18,7 @@
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
Expand Down Expand Up @@ -91,29 +93,32 @@ public void sendPushForDeliveries(List<NotificationDelivery> deliveries, Notific
}

// 활성 토큰을 IN절로 한 번에 조회
List<String> allTokens = fcmTokenRepository.findAllActiveTokensByUsers(eligibleReceivers);
List<FcmTokenTargetDto> allTargets = fcmTokenRepository.findAllActiveTokenTargetsByUsers(eligibleReceivers);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FCM 토큰 조회 시 FcmTokenTargetDto를 사용하도록 변경하여 실패 응답에서 fcmTokenId, userId 기준으로 추적할 수 있도록 수정된 부분 확인했습니닷


if (allTokens.isEmpty()) {
if (allTargets.isEmpty()) {
log.debug("[sendPushForDeliveries] 활성 FCM token이 없어 발송을 건너뜁니다. receiverCount={}",
eligibleReceivers.size());
return;
}

// FCM 500개 제한에 맞춰 배치 분할 후 벌크 전송
List<List<String>> batches = partitionTokens(allTokens, FCM_MULTICAST_LIMIT);
List<List<FcmTokenTargetDto>> batches = partitionTargets(allTargets, FCM_MULTICAST_LIMIT);
int failedBatchCount = 0;
FirebaseMessagingException firstFailure = null;
for (List<String> batch : batches) {
FirebaseMessagingException failure = sendMulticast(batch, event);
List<String> failedIncidentIds = new ArrayList<>();
Map<String, Integer> failureBreakdown = new LinkedHashMap<>();
for (List<FcmTokenTargetDto> batch : batches) {
BatchSendFailure failure = sendMulticast(batch, event);
if (failure != null) {
failedBatchCount++;
if (firstFailure == null) firstFailure = failure;
failedIncidentIds.add(failure.incidentId());
failureBreakdown.merge(failure.failureKey(), 1, Integer::sum);
}
}
if (failedBatchCount > 0) {
log.error("[sendPushForDeliveries] FCM bulk 발송 batch 총 {}건 중 {}건을 실패했습니다. typeName={}, category={}, targetType={}, targetId={}",
batches.size(), failedBatchCount, event.getType().getTypeName(), event.getCategory(),
event.getTargetType(), event.getTargetId(), firstFailure);
log.error("[sendPushForDeliveries] FCM bulk 발송 batch 실패가 누적되었습니다. incidentIds={}, batchCount={}, failureCount={}, breakdown={}, typeName={}, category={}",
failedIncidentIds, batches.size(), failedBatchCount,
failureBreakdown,
event.getType().getTypeName(), event.getCategory());
}
}

Expand All @@ -138,16 +143,18 @@ private boolean isCategoryEnabled(NotificationSetting setting, NotificationCateg
};
}

/** 토큰 리스트를 maxSize 단위로 분할 (FCM 500개 제한 대응) */
private List<List<String>> partitionTokens(List<String> tokens, int maxSize) {
List<List<String>> partitions = new ArrayList<>();
for (int i = 0; i < tokens.size(); i += maxSize) {
partitions.add(tokens.subList(i, Math.min(i + maxSize, tokens.size())));
/** 응답 순서와 내부 ID 매핑을 유지한 채 FCM 제한 단위로 분할한다. */
private List<List<FcmTokenTargetDto>> partitionTargets(List<FcmTokenTargetDto> targets, int maxSize) {
List<List<FcmTokenTargetDto>> partitions = new ArrayList<>();
for (int i = 0; i < targets.size(); i += maxSize) {
partitions.add(targets.subList(i, Math.min(i + maxSize, targets.size())));
}
return partitions;
}

private FirebaseMessagingException sendMulticast(List<String> tokens, NotificationEvent event) {
private BatchSendFailure sendMulticast(List<FcmTokenTargetDto> targets, NotificationEvent event) {
List<String> tokens = targets.stream().map(FcmTokenTargetDto::token).toList();

// iOS APNs 설정 추가
ApnsConfig apnsConfig = ApnsConfig.builder()
.setAps(Aps.builder()
Expand Down Expand Up @@ -184,15 +191,26 @@ private FirebaseMessagingException sendMulticast(List<String> tokens, Notificati
try {
BatchResponse response = FirebaseMessaging.getInstance().sendEachForMulticast(message);

fcmTokenDeactivationService.handleFailedTokens(tokens, response);
fcmTokenDeactivationService.handleFailedTokens(targets, response);
log.info("[sendMulticast] FCM bulk 발송을 완료했습니다. tokenCount={}, successCount={}, failedCount={}",
tokens.size(), response.getSuccessCount(), response.getFailureCount());
return null;

} catch (FirebaseMessagingException e) {
log.warn("[sendMulticast] FCM bulk 발송 batch 처리에 실패했습니다. tokenCount={}, exception={}",
tokens.size(), e.getClass().getSimpleName());
return e;
String incidentId = UUID.randomUUID().toString();
String messagingCode = e.getMessagingErrorCode() != null ? e.getMessagingErrorCode().name() : "UNKNOWN";
String platformCode = e.getErrorCode() != null ? e.getErrorCode().name() : "UNKNOWN";
String httpStatus = e.getHttpResponse() != null
? Integer.toString(e.getHttpResponse().getStatusCode())
: "UNKNOWN";
log.warn("[sendMulticast] FCM bulk 발송 batch 처리에 실패했습니다. incidentId={}, tokenCount={}, messagingCode={}, platformCode={}, httpStatus={}, exceptionType={}",
incidentId, tokens.size(), messagingCode, platformCode, httpStatus,
e.getClass().getSimpleName());
String failureKey = "messaging=" + messagingCode + ",platform=" + platformCode + ",http=" + httpStatus;
return new BatchSendFailure(incidentId, failureKey);
}
}

private record BatchSendFailure(String incidentId, String failureKey) {
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package com.hrr.backend.domain.fcm.service;

import com.google.firebase.messaging.BatchResponse;
import com.hrr.backend.domain.fcm.dto.FcmTokenTargetDto;
import java.util.List;

public interface FcmTokenDeactivationService {
/**
* FCM 발송 결과에서 실패한 토큰들이 유효하지 않은 경우 비활성화 처리
*/
void handleFailedTokens(List<String> tokens, BatchResponse response);
}
void handleFailedTokens(List<FcmTokenTargetDto> targets, BatchResponse response);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@
import com.google.firebase.messaging.FirebaseMessagingException;
import com.google.firebase.messaging.MessagingErrorCode;
import com.google.firebase.messaging.SendResponse;
import com.hrr.backend.domain.fcm.dto.FcmTokenTargetDto;
import com.hrr.backend.domain.fcm.repository.FcmTokenRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
Expand All @@ -21,66 +25,70 @@ public class FcmTokenDeactivationServiceImpl implements FcmTokenDeactivationServ
private final FcmTokenRepository fcmTokenRepository;

@Override
@Transactional(propagation = Propagation.REQUIRES_NEW) // 별도의 독립적인 트랜잭션 보장
public void handleFailedTokens(List<String> tokens, BatchResponse response) {
List<SendResponse> responses = response.getResponses();
// 실패 토큰 갱신이 알림 생성 트랜잭션과 서로 영향을 주지 않도록 분리한다.
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void handleFailedTokens(List<FcmTokenTargetDto> targets, BatchResponse response) {
String incidentId = UUID.randomUUID().toString();
List<SendResponse> responses = response != null ? response.getResponses() : null;

// 토큰 리스트와 응답 리스트의 크기 정합성 체크
if (tokens == null || responses == null || tokens.size() != responses.size()) {
log.error("[handleFailedTokens] FCM token 목록과 응답 목록의 크기가 일치하지 않습니다. tokenCount={}, responseCount={}",
tokens != null ? tokens.size() : "null",
// 응답 인덱스로 내부 대상을 찾으므로 두 목록의 크기가 반드시 같아야 한다.
if (targets == null || responses == null || targets.size() != responses.size()) {
log.error("[handleFailedTokens] FCM 대상 목록과 응답 목록의 크기가 일치하지 않습니다. incidentId={}, targetCount={}, responseCount={}",
incidentId,
targets != null ? targets.size() : "null",
responses != null ? responses.size() : "null");
return;
}

int actionableFailureCount = 0;
FirebaseMessagingException firstFailure = null;
Map<String, Integer> failureBreakdown = new LinkedHashMap<>();
for (int i = 0; i < responses.size(); i++) {
SendResponse sendResponse = responses.get(i);

if (!sendResponse.isSuccessful()) {
String token = tokens.get(i);
FcmTokenTargetDto target = targets.get(i);

// NPE 방지
FirebaseMessagingException exception = sendResponse.getException();
if (exception == null) {
log.warn("[handleFailedTokens] FCM 실패 응답에 예외 정보가 없습니다. responseIndex={}", i);
String failureKey = "messaging=UNKNOWN,platform=UNKNOWN,http=UNKNOWN";
log.warn("[handleFailedTokens] FCM 실패 응답에 예외 정보가 없습니다. incidentId={}, responseIndex={}, fcmTokenId={}, userId={}, action=RETAIN",
incidentId, i, target.fcmTokenId(), target.userId());
actionableFailureCount++;
failureBreakdown.merge(failureKey, 1, Integer::sum);
continue; // 원인 파악이 불가능하므로 건너뜀
}

MessagingErrorCode errorCode = exception.getMessagingErrorCode();
String messagingCode = errorCode != null ? errorCode.name() : "UNKNOWN";
String platformCode = exception.getErrorCode() != null ? exception.getErrorCode().name() : "UNKNOWN";
String httpStatus = exception.getHttpResponse() != null
? Integer.toString(exception.getHttpResponse().getStatusCode())
: "UNKNOWN";
String failureKey = "messaging=" + messagingCode + ",platform=" + platformCode + ",http=" + httpStatus;

if (errorCode == MessagingErrorCode.UNREGISTERED ||
errorCode == MessagingErrorCode.SENDER_ID_MISMATCH) {

// 토큰 자체가 무효한 경우 비활성화 수행
fcmTokenRepository.deactivateAllByToken(token);
log.info("[handleFailedTokens] 유효하지 않은 FCM token을 비활성화했습니다. errorCode={}, responseIndex={}",
errorCode, i);
} else if (errorCode == MessagingErrorCode.INVALID_ARGUMENT) {
// 페이로드 오류 등은 로그만 남기고 토큰은 유지
log.warn("[handleFailedTokens] FCM payload가 유효하지 않습니다. errorCode={}, responseIndex={}",
errorCode, i);
actionableFailureCount++;
if (firstFailure == null) firstFailure = exception;
fcmTokenRepository.deactivateAllByToken(target.token());
log.warn("[handleFailedTokens] 유효하지 않은 FCM token을 비활성화했습니다. incidentId={}, messagingCode={}, platformCode={}, httpStatus={}, responseIndex={}, fcmTokenId={}, userId={}",
incidentId, messagingCode, platformCode, httpStatus, i,
target.fcmTokenId(), target.userId());
} else {
// 기타 일시적 오류 등
log.warn("[handleFailedTokens] FCM 발송에 실패했지만 token을 유지합니다. errorCode={}, exception={}",
errorCode, exception.getClass().getSimpleName());
// 페이로드 오류, 일시적 오류 및 분류되지 않은 오류는 진단 정보를 남기고 토큰을 유지한다.
// 내부 ID는 서버 WARN에만 남기고 Discord로 전송되는 집계 ERROR에서는 제외한다.
log.warn("[handleFailedTokens] FCM 발송에 실패했지만 token을 유지합니다. incidentId={}, messagingCode={}, platformCode={}, httpStatus={}, responseIndex={}, fcmTokenId={}, userId={}, exceptionType={}, action=RETAIN",
incidentId, messagingCode, platformCode, httpStatus, i,
target.fcmTokenId(), target.userId(), exception.getClass().getSimpleName());
actionableFailureCount++;
if (firstFailure == null) firstFailure = exception;
failureBreakdown.merge(failureKey, 1, Integer::sum);
}
}
}
if (actionableFailureCount > 0) {
if (firstFailure != null) {
log.error("[handleFailedTokens] FCM 응답에서 조치가 필요한 실패가 누적되었습니다. failureCount={}, responseCount={}",
actionableFailureCount, responses.size(), firstFailure);
} else {
log.error("[handleFailedTokens] FCM 응답에서 원인을 확인할 수 없는 실패가 누적되었습니다. failureCount={}, responseCount={}",
actionableFailureCount, responses.size());
}
log.error("[handleFailedTokens] FCM 응답에서 조치가 필요한 실패가 누적되었습니다. incidentId={}, failureCount={}, responseCount={}, breakdown={}",
incidentId, actionableFailureCount, responses.size(), failureBreakdown);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import com.hrr.backend.domain.verification.repository.VerificationRepository;
import com.hrr.backend.global.common.enums.ChallengeDays;
import com.hrr.backend.global.response.SliceResponseDto;
import com.hrr.backend.global.logging.SafeExceptionSummary;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -81,7 +82,6 @@ public void checkAndEarnFlawlessRoundPoints(Round endedRound) {
// 종료된 라운드에 속한 모든 RoundRecord 조회 (JOINED/DROPPED 대상)
List<RoundRecord> records = roundRecordRepository.findAllByRoundIdWithUserAndChallenge(endedRound.getId());
int failCount = 0;
Exception firstFailure = null;

for (RoundRecord record : records) {
try {
Expand All @@ -104,16 +104,15 @@ public void checkAndEarnFlawlessRoundPoints(Round endedRound) {

awardPoint(user, PointType.FLAWLESS_ROUND, challenge, endedRound, null, null);
} catch (Exception e) {
log.warn("[checkAndEarnFlawlessRoundPoints] 무결석 완주 포인트 지급에 실패했습니다. roundRecordId={}",
record.getId(), e);
log.warn("[checkAndEarnFlawlessRoundPoints] 무결석 완주 포인트 지급에 실패했습니다. roundRecordId={}, failure={}",
record.getId(), SafeExceptionSummary.summarize(e));
failCount++;
if (firstFailure == null) firstFailure = e;
}
}

if (failCount > 0) {
log.error("[checkAndEarnFlawlessRoundPoints] 포인트 지급 대상 총 {}건 중 {}건을 실패했습니다. roundId={}",
records.size(), failCount, endedRound.getId(), firstFailure);
log.error("[checkAndEarnFlawlessRoundPoints] 무결석 완주 포인트 지급 실패가 누적되었습니다. targetCount={}, failureCount={}",
records.size(), failCount);
}
}

Expand Down
Loading