Skip to content

Fixed async error - #136

Merged
raphael-frank merged 1 commit into
mainfrom
bug/async-letter-mail-send
Jul 18, 2026
Merged

Fixed async error#136
raphael-frank merged 1 commit into
mainfrom
bug/async-letter-mail-send

Conversation

@f-s-h

@f-s-h f-s-h commented Jul 18, 2026

Copy link
Copy Markdown
Collaborator

Changed mail sending to async to fix that false errors are shown when emails are sent.

Summary by CodeRabbit

  • New Features

    • Email delivery now runs asynchronously, helping letter processing continue without waiting for each message to finish.
    • Added configurable background processing for outgoing mail.
  • Bug Fixes

    • Email delivery failures no longer interrupt letter processing.
    • Failed deliveries are recorded for monitoring and troubleshooting.
  • Chores

    • Updated project ignore rules for local development files.

@f-s-h
f-s-h requested a review from raphael-frank July 18, 2026 10:26
@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Spring letter delivery now uses an asynchronously configured MailDispatcher for HTML email sending. LetterService no longer performs synchronous mail delivery or propagates delivery exceptions, and tests validate failure metrics. An IDE metadata directory is also added to .gitignore.

Changes

Asynchronous letter mail delivery

Layer / File(s) Summary
Enable asynchronous execution
services/spring-letter/src/main/java/tum/devoops/letterservice/LetterServiceApplication.java, services/spring-letter/src/main/java/tum/devoops/letterservice/config/AsyncConfig.java
Spring async execution is enabled with a ThreadPoolTaskExecutor configured for mail dispatch tasks.
Delegate and dispatch email asynchronously
services/spring-letter/src/main/java/tum/devoops/letterservice/service/MailDispatcher.java, services/spring-letter/src/main/java/tum/devoops/letterservice/service/LetterService.java
LetterService delegates delivery to MailDispatcher, which sends UTF-8 HTML messages and records success or failure counters while handling messaging exceptions.
Update delivery tests
services/spring-letter/src/test/java/tum/devoops/letterservice/service/LetterServiceTest.java
Tests construct LetterService with MailDispatcher and verify failed delivery does not propagate an exception while incrementing the failure counter.

Repository ignore configuration

Layer / File(s) Summary
Ignore IDE metadata
.gitignore
Adds services/py-genai-helper/.idea/ to ignored paths.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant LetterService
  participant MailDispatcher
  participant JavaMailSender
  participant MeterRegistry
  LetterService->>MailDispatcher: sendAsync(to, subject, html)
  MailDispatcher->>JavaMailSender: Create and send HTML message
  JavaMailSender-->>MailDispatcher: Send result
  MailDispatcher->>MeterRegistry: Increment success or failure counter
Loading

Possibly related PRs

Suggested labels: enhancement, server

Suggested reviewers: raphael-frank

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title is vague and does not clearly describe the mail-sending async refactor in this PR. Rename it to something specific like 'Make letter sending asynchronous' or 'Move mail dispatch to async executor'.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bug/async-letter-mail-send

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

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 (1)
services/spring-letter/src/main/java/tum/devoops/letterservice/config/AsyncConfig.java (1)

16-22: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Prevent dropped emails on application shutdown.

Since this executor handles a queue of background mail tasks, any tasks left in the queue when the application shuts down will be immediately discarded by default.

Consider setting setWaitForTasksToCompleteOnShutdown(true) to ensure that queued emails are sent before the application exits.

♻️ Proposed refactor
         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
         executor.setCorePoolSize(2);
         executor.setMaxPoolSize(10);
         executor.setQueueCapacity(500);
         executor.setThreadNamePrefix("mail-dispatch-");
+        executor.setWaitForTasksToCompleteOnShutdown(true);
+        executor.setAwaitTerminationSeconds(60);
         executor.initialize();
         return executor;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@services/spring-letter/src/main/java/tum/devoops/letterservice/config/AsyncConfig.java`
around lines 16 - 22, Update the ThreadPoolTaskExecutor configuration in
AsyncConfig to call setWaitForTasksToCompleteOnShutdown(true) before
initialize(), ensuring queued mail tasks finish during application shutdown.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@services/spring-letter/src/main/java/tum/devoops/letterservice/service/MailDispatcher.java`:
- Around line 42-45: Update the exception handling in MailDispatcher’s
mail-sending flow to catch Spring MailException, or a broader Exception, so
runtime delivery failures from mailSender.send(message) increment the failure
counter and are logged through the existing LOG.error call. Preserve the current
failure metric and logging behavior for MessagingException as well.

---

Nitpick comments:
In
`@services/spring-letter/src/main/java/tum/devoops/letterservice/config/AsyncConfig.java`:
- Around line 16-22: Update the ThreadPoolTaskExecutor configuration in
AsyncConfig to call setWaitForTasksToCompleteOnShutdown(true) before
initialize(), ensuring queued mail tasks finish during application shutdown.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 30941703-8e55-42d2-81f7-463c5f446ecb

📥 Commits

Reviewing files that changed from the base of the PR and between 8e069a9 and 70b3803.

📒 Files selected for processing (6)
  • .gitignore
  • services/spring-letter/src/main/java/tum/devoops/letterservice/LetterServiceApplication.java
  • services/spring-letter/src/main/java/tum/devoops/letterservice/config/AsyncConfig.java
  • services/spring-letter/src/main/java/tum/devoops/letterservice/service/LetterService.java
  • services/spring-letter/src/main/java/tum/devoops/letterservice/service/MailDispatcher.java
  • services/spring-letter/src/test/java/tum/devoops/letterservice/service/LetterServiceTest.java

Comment on lines +42 to +45
} catch (MessagingException e) {
meterRegistry.counter("letters_sent_total", "status", "failure").increment();
LOG.error("Failed to send mail to {}", to, e);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Catch Spring's MailException to properly track sending failures.

mailSender.send(message) throws Spring's MailException (an unchecked RuntimeException), not the checked MessagingException (which is only thrown by MimeMessageHelper setup methods). By only catching MessagingException, actual delivery failures (like connection refused or SMTP timeouts) will bypass this catch block. This will cause the failure metric to be missed, and the exception will be swallowed by Spring's async executor.

Catch Exception (or add a catch block for MailException) to ensure all delivery failures are correctly logged and metered.

🐛 Proposed fix
-        } catch (MessagingException e) {
+        } catch (Exception e) {
             meterRegistry.counter("letters_sent_total", "status", "failure").increment();
             LOG.error("Failed to send mail to {}", to, e);
         }
📝 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
} catch (MessagingException e) {
meterRegistry.counter("letters_sent_total", "status", "failure").increment();
LOG.error("Failed to send mail to {}", to, e);
}
} catch (Exception e) {
meterRegistry.counter("letters_sent_total", "status", "failure").increment();
LOG.error("Failed to send mail to {}", to, e);
}
🧰 Tools
🪛 PMD (7.26.0)

[Low] 44-44: InvalidLogMessageFormat (Error Prone): Too many arguments, expected 1 argument but found 2

(InvalidLogMessageFormat (Error Prone))

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@services/spring-letter/src/main/java/tum/devoops/letterservice/service/MailDispatcher.java`
around lines 42 - 45, Update the exception handling in MailDispatcher’s
mail-sending flow to catch Spring MailException, or a broader Exception, so
runtime delivery failures from mailSender.send(message) increment the failure
counter and are logged through the existing LOG.error call. Preserve the current
failure metric and logging behavior for MessagingException as well.

@raphael-frank raphael-frank left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

lgtm

@raphael-frank
raphael-frank merged commit 5ec7e54 into main Jul 18, 2026
18 checks passed
@raphael-frank
raphael-frank deleted the bug/async-letter-mail-send branch July 19, 2026 06:29
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