Skip to content

Conversation

@wannevancamp
Copy link
Member

@wannevancamp wannevancamp commented May 28, 2025

Clean up mail archive entries via a console command, enabling crontab monitoring with tools like Oh Dear.

Summary by CodeRabbit

  • New Features

    • Added a command-line command to manually trigger cleanup of old mail archive entries.
    • Introduced automated cleanup of mail archive entries and associated files based on configurable retention settings.
  • Refactor

    • Updated cleanup process to run asynchronously via message dispatching, improving performance and reliability.

@coderabbitai
Copy link

coderabbitai bot commented May 28, 2025

Warning

Rate limit exceeded

@wannevancamp has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 7 minutes and 22 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 352f821 and a78fc6e.

📒 Files selected for processing (3)
  • src/Command/CleanupCommand.php (1 hunks)
  • src/Messenger/CleanupHandler.php (1 hunks)
  • src/Messenger/CleanupMessage.php (1 hunks)

Walkthrough

A new asynchronous cleanup mechanism for mail archive entries is introduced. The changes add a Symfony console command, a Messenger message and handler, and refactor the scheduled cleanup task to dispatch the cleanup as a message instead of executing it synchronously. The actual cleanup logic is now handled by the new message handler.

Changes

File(s) Change Summary
src/Command/CleanupCommand.php Added a Symfony console command to dispatch mail archive cleanup via the message bus.
src/Messenger/CleanupHandler.php Introduced a Messenger message handler to perform mail archive cleanup and EML file deletion.
src/Messenger/CleanupMessage.php Added an empty Messenger message class for triggering cleanup asynchronously.
src/Task/CleanupTaskHandler.php Refactored: now dispatches a cleanup message instead of performing cleanup directly; dependencies updated.
src/Task/CleanupTask.php Added a clarifying comment to the default interval return value.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ConsoleCommand as CleanupCommand
    participant MessageBus
    participant Handler as CleanupHandler
    participant Database
    participant FileManager as EmlFileManager

    User->>ConsoleCommand: Execute 'frosh:mail-archive:cleanup'
    ConsoleCommand->>MessageBus: Dispatch CleanupMessage
    MessageBus->>Handler: Deliver CleanupMessage
    Handler->>Database: Query for old mail archive entries
    Handler->>FileManager: Delete associated EML files
    Handler->>Database: Delete old mail archive records
Loading
sequenceDiagram
    participant ScheduledTask
    participant TaskHandler as CleanupTaskHandler
    participant MessageBus
    participant Handler as CleanupHandler

    ScheduledTask->>TaskHandler: Trigger run()
    TaskHandler->>MessageBus: Dispatch CleanupMessage
    MessageBus->>Handler: Deliver CleanupMessage
    Handler->>...: (Performs cleanup as above)
Loading

Poem

In the warren, we sweep and we clean,
With messages sent, our code is serene.
Old mails hop away, their files now gone,
Tasks and commands, all working as one.
Asynchronous bunnies, efficient and bright—
Our archive now sparkles, pure delight!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai 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

Documentation and Community

  • 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

@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: 3

🧹 Nitpick comments (3)
src/Command/CleanupCommand.php (1)

24-33: Consider clarifying the asynchronous nature of the cleanup.

The command returns success immediately after dispatching the message, which is correct for async processing. However, consider updating the output messages to clarify that the cleanup will be processed asynchronously.

-        $output->writeln('Dispatching mail archive cleanup...');
+        $output->writeln('Dispatching mail archive cleanup (will be processed asynchronously)...');
        
         $this->messageBus->dispatch(new CleanupMessage());
         
-        $output->writeln('Cleanup message dispatched successfully.');
+        $output->writeln('Cleanup message dispatched successfully. Processing will continue in the background.');
src/Messenger/CleanupHandler.php (2)

47-51: Consider batch processing for large datasets.

Loading all records at once with fetchAllAssociative() could consume significant memory for large datasets. Consider implementing batch processing for better memory efficiency.

-        $result = $query->executeQuery()->fetchAllAssociative();
-        
-        if (\count($result) === 0) {
-            return;
-        }
+        $batchSize = 1000;
+        $offset = 0;
+        
+        do {
+            $batchQuery = clone $query;
+            $batchQuery->setFirstResult($offset);
+            $batchQuery->setMaxResults($batchSize);
+            
+            $result = $batchQuery->executeQuery()->fetchAllAssociative();
+            
+            if (\count($result) === 0) {
+                break;
+            }
+            
+            // Process batch...
+            
+            $offset += $batchSize;
+        } while (\count($result) === $batchSize);

53-59: Consider logging file deletion failures.

The current implementation silently continues if EML file deletion fails. Consider adding logging to track cleanup issues for monitoring purposes.

+use Psr\Log\LoggerInterface;

 public function __construct(
     private readonly SystemConfigService $configService,
     private readonly Connection $connection,
     private readonly EmlFileManager $emlFileManager,
+    private readonly LoggerInterface $logger,
 ) {
 }

 foreach ($result as $item) {
     if (empty($item['eml_path']) || !\is_string($item['eml_path'])) {
         continue;
     }

-    $this->emlFileManager->deleteEmlFile($item['eml_path']);
+    try {
+        $this->emlFileManager->deleteEmlFile($item['eml_path']);
+    } catch (\Throwable $e) {
+        $this->logger->warning('Failed to delete EML file during cleanup', [
+            'file_path' => $item['eml_path'],
+            'error' => $e->getMessage()
+        ]);
+    }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 543e844 and 00c3301.

📒 Files selected for processing (5)
  • src/Command/CleanupCommand.php (1 hunks)
  • src/Messenger/CleanupHandler.php (1 hunks)
  • src/Messenger/CleanupMessage.php (1 hunks)
  • src/Task/CleanupTask.php (1 hunks)
  • src/Task/CleanupTaskHandler.php (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/Command/CleanupCommand.php (1)
src/Messenger/CleanupMessage.php (1)
  • CleanupMessage (9-12)
src/Messenger/CleanupHandler.php (2)
src/Services/EmlFileManager.php (2)
  • EmlFileManager (12-93)
  • deleteEmlFile (85-92)
src/Messenger/CleanupMessage.php (1)
  • CleanupMessage (9-12)
🔇 Additional comments (4)
src/Task/CleanupTask.php (1)

20-20: LGTM! Good clarification.

The comment clearly explains that 86400 represents 1 day in seconds, improving code readability.

src/Messenger/CleanupMessage.php (1)

9-12: LGTM! Follows Symfony Messenger best practices.

The empty message class is a valid pattern when no data needs to be passed between the dispatcher and handler.

src/Task/CleanupTaskHandler.php (2)

7-12: Clean refactoring to use message-driven architecture!

The imports are appropriate for the new asynchronous cleanup approach. This separation of concerns will make the system more maintainable and testable.


20-25: Constructor properly simplified.

The dependency injection is correctly implemented, replacing the previous direct dependencies with the message bus interface.

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.

1 participant