Skip to content

feat : 문제 출제 실패 시, 메일 발송 실패 로그 저장 추가#424

Merged
crocusia merged 2 commits intodevfrom
feat/420
Sep 10, 2025
Merged

feat : 문제 출제 실패 시, 메일 발송 실패 로그 저장 추가#424
crocusia merged 2 commits intodevfrom
feat/420

Conversation

@crocusia
Copy link
Member

@crocusia crocusia commented Sep 2, 2025

🔎 작업 내용

  • 별도의 트랜잭션으로 메일 발송 실패 로그를 저장하던 메서드를 Processor에 적용
  • 출제할 문제가 없어서 실패 시, caused = No quizzes available 로 저장됨

Summary by CodeRabbit

  • 버그 수정
    • 퀴즈가 없는 날 발생하던 메일 처리 예외를 명확히 처리하고 실패 상황을 기록하도록 개선했습니다. 중복 시도와 대기열 잔류를 줄여 메일 발송 흐름의 안정성을 높였습니다.
    • 에러 발생 시 처리 완료와 정리 절차를 보장하여 간헐적 지연 및 누락 가능성을 낮췄습니다.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 2, 2025

Walkthrough

MailConsumerAsyncProcessor에 MailLogBatchService 의존성이 추가되었고, QuizException 처리 시 실패 로그를 저장하도록 로직이 확장되었습니다. 예외 발생 시 mailLogBatchService.saveFailLog(...)를 호출한 뒤 기존과 같이 Redis 메시지를 ack 및 삭제하고 null을 반환합니다. 생성자 시그니처가 해당 서비스 추가로 변경되었습니다.

Changes

Cohort / File(s) Summary of Changes
Mail failure logging integration
cs25-batch/src/main/java/com/example/cs25batch/batch/component/processor/MailConsumerAsyncProcessor.java
- MailLogBatchService 필드 및 생성자 파라미터 추가
- QuizException 캐치 블록에서 mailLogBatchService.saveFailLog(...) 호출 추가
- 이후 redisClient.ackAndDel(recordId) 및 null 반환은 기존 유지

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant P as MailConsumerAsyncProcessor
    participant T as TodayQuizService
    participant M as MailLogBatchService
    participant R as RedisStreamsClient

    rect rgb(245,248,255)
    note over P: 구독 레코드 처리 시작
    P->>T: 오늘의 퀴즈 조회
    T-->>P: QuizException 발생
    end

    rect rgb(255,245,245)
    note over P,M: 변경된 예외 처리 경로
    P->>M: saveFailLog(subscription, null, now, "No quizzes available")
    P->>R: ackAndDel(recordId)
    P-->>P: return null
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested reviewers

  • HeeMang-Lee
  • wannabeing

Poem

깡총, 편지 바구니 살짝 비어도
오늘 퀴즈 없었대요—기록해 두죠.
로그 한 줄, 톡—기억은 남기고,
레디스에 인사하고 길을 비우죠.
내일은 퀴즈 가득, 토닥토닥 기대해요! 🐰✉️

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/420

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
cs25-batch/src/main/java/com/example/cs25batch/batch/component/processor/MailConsumerAsyncProcessor.java (2)

11-11: 시간 소스 하드코딩 제거(테스트 용이성/일관된 타임존): Clock 주입 권장

LocalDateTime.now() 대신 Clock을 주입받아 사용하면 테스트 및 타임존 일관성이 좋아집니다.

@@
-import java.time.LocalDateTime;
+import java.time.LocalDateTime;
+import java.time.Clock;
@@
-    private final MailLogBatchService mailLogBatchService;
+    private final MailLogBatchService mailLogBatchService;
+    private final Clock clock;
@@
-            mailLogBatchService.saveFailLog(subscription, null, LocalDateTime.now(), "No quizzes available");
+            mailLogBatchService.saveFailLog(subscription, null, LocalDateTime.now(clock), "No quizzes available");

Clock 빈이 없다면 구성에 @Bean Clock clock() { return Clock.systemDefaultZone(); } 추가를 고려해 주세요.

Also applies to: 26-26, 55-55


55-55: 원인 메시지 하드코딩 최소화

"No quizzes available" 문자열을 상수/enum(예: MailFailCause.NO_QUIZZES_AVAILABLE)로 통일하거나 QuizException의 에러 코드로부터 매핑하면 오타/다국어/집계 쿼리 시 유리합니다.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c723900 and bd04cb6.

📒 Files selected for processing (1)
  • cs25-batch/src/main/java/com/example/cs25batch/batch/component/processor/MailConsumerAsyncProcessor.java (3 hunks)
🔇 Additional comments (1)
cs25-batch/src/main/java/com/example/cs25batch/batch/component/processor/MailConsumerAsyncProcessor.java (1)

5-5: MailLogBatchService 트랜잭션 전파 및 빈 등록 확인됨
saveFailLog 메서드에 @Transactional(propagation = Propagation.REQUIRES_NEW)가 적용되어 별도 트랜잭션이 보장되며, @RequiredArgsConstructor 기반 생성자 주입을 통해 MailConsumerAsyncProcessor에서 정상 인젝션됩니다.

Comment on lines 54 to 58
//문제 출제 실패로 인한 예외 발생 시, 기존 Queue에 있는 데이터 삭제
mailLogBatchService.saveFailLog(subscription, null, LocalDateTime.now(), "No quizzes available");
redisClient.ackAndDel(recordId);
return null;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

ACK 보장: 로그 저장 실패 시에도 메시지를 반드시 ack/del 하도록 finally로 이동

현재는 saveFailLog에서 예외가 나면 ack가 호출되지 않아 동일 메시지가 재처리될 수 있습니다. ack를 finally로 옮기고, recordId null 가드 및 로깅을 추가해 주세요.

다음 패치를 제안합니다:

-        } catch(QuizException e){
-            //문제 출제 실패로 인한 예외 발생 시, 기존 Queue에 있는 데이터 삭제
-            mailLogBatchService.saveFailLog(subscription, null, LocalDateTime.now(), "No quizzes available");
-            redisClient.ackAndDel(recordId);
-            return null;
-        }
+        } catch (QuizException e) {
+            // 문제 출제 실패 시: 실패 로그 저장 후, 메시지는 항상 정리
+            try {
+                mailLogBatchService.saveFailLog(subscription, null, LocalDateTime.now(), "No quizzes available");
+            } catch (Exception logEx) {
+                log.error("Fail log persist failed. subscriptionId={}, recordId={}", subscriptionId, recordId, logEx);
+            } finally {
+                if (recordId != null) {
+                    redisClient.ackAndDel(recordId);
+                } else {
+                    log.warn("Missing recordId. subscriptionId={}", subscriptionId);
+                }
+            }
+            return null;
+        }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
//문제 출제 실패로 인한 예외 발생 시, 기존 Queue에 있는 데이터 삭제
mailLogBatchService.saveFailLog(subscription, null, LocalDateTime.now(), "No quizzes available");
redisClient.ackAndDel(recordId);
return null;
}
} catch (QuizException e) {
// 문제 출제 실패 시: 실패 로그 저장 후, 메시지는 항상 정리
try {
mailLogBatchService.saveFailLog(subscription, null, LocalDateTime.now(), "No quizzes available");
} catch (Exception logEx) {
log.error("Fail log persist failed. subscriptionId={}, recordId={}", subscriptionId, recordId, logEx);
} finally {
if (recordId != null) {
redisClient.ackAndDel(recordId);
} else {
log.warn("Missing recordId. subscriptionId={}", subscriptionId);
}
}
return null;
}
🤖 Prompt for AI Agents
In
cs25-batch/src/main/java/com/example/cs25batch/batch/component/processor/MailConsumerAsyncProcessor.java
around lines 54 to 58, the call to mailLogBatchService.saveFailLog can throw and
prevent redisClient.ackAndDel(recordId) from running, causing duplicate
reprocessing; move the ack/del into a finally block so it always runs, surround
saveFailLog with its own try/catch to log failures (including exception details)
but not rethrow, and in the finally check recordId for null before calling
redisClient.ackAndDel(recordId) and log a warning if recordId is null or ack/del
fails.

@crocusia crocusia merged commit 7292db0 into dev Sep 10, 2025
2 checks passed
@crocusia crocusia deleted the feat/420 branch September 10, 2025 02:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants