Skip to content

Comments

Refactor Google mail count implementation and add staleTime to stats query#1770

Merged
MrgSub merged 1 commit intostagingfrom
Refactor_Google_mail_count_implementation_and_add_staleTime_to_stats_query
Jul 20, 2025
Merged

Refactor Google mail count implementation and add staleTime to stats query#1770
MrgSub merged 1 commit intostagingfrom
Refactor_Google_mail_count_implementation_and_add_staleTime_to_stats_query

Conversation

@MrgSub
Copy link
Collaborator

@MrgSub MrgSub commented Jul 20, 2025

Optimize mail app performance and refactor Google mail manager

Description

This PR makes several improvements to the mail application:

  1. Removed unused parameter in the onSubmit function in the notifications settings page
  2. Added a 5-minute stale time to the mail count query to reduce unnecessary API calls
  3. Completely refactored the Google mail manager's count method to use Effect.js more effectively:
    • Implemented concurrent fetching of user labels and archive count
    • Improved error handling with more specific error types
    • Restructured the code to be more maintainable with a cleaner data flow
    • Added better type safety throughout the implementation

Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ⚡ Performance improvement

Areas Affected

  • Email Integration (Gmail, IMAP, etc.)
  • User Interface/Experience
  • Performance

Testing Done

  • Manual testing performed

Checklist

  • I have performed a self-review of my code
  • My changes generate no new warnings
  • All tests pass locally

By submitting this pull request, I confirm that my contribution is made under the terms of the project's license.

Summary by CodeRabbit

  • Refactor
    • Improved performance and reliability of email label and archive count retrieval.
    • Updated internal form handling for notification settings.
    • Enhanced caching behavior for statistics, reducing unnecessary data fetching.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 20, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This update refactors the count method in the GoogleMailManager class to use the Effect library for concurrent operations and error handling, modifies the useStats hook to set a 5-minute stale time for caching, and changes the onSubmit function signature in the notifications settings page to accept no arguments.

Changes

File(s) Change Summary
apps/server/src/lib/driver/google.ts Refactored GoogleMailManager.count to use the Effect library for concurrency and error handling; internal logic updated.
apps/mail/hooks/use-stats.ts Added staleTime option (5 minutes) to the React Query useQuery call in the useStats hook.
apps/mail/app/(routes)/settings/notifications/page.tsx Changed onSubmit function signature to take no arguments; internal logic unchanged.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant GoogleMailManager
    participant EffectLib

    Client->>GoogleMailManager: call count()
    GoogleMailManager->>EffectLib: start Effect.gen (concurrent fetch)
    EffectLib->>GoogleMailManager: fetch user labels (tryPromise)
    EffectLib->>GoogleMailManager: fetch archive count (tryPromise)
    GoogleMailManager->>EffectLib: process each label concurrently (with error handling)
    EffectLib->>GoogleMailManager: filter out failed fetches
    EffectLib->>GoogleMailManager: add archive count if successful
    GoogleMailManager->>EffectLib: return combined results
    EffectLib->>Client: return label counts + archive count array
Loading

Possibly related PRs

  • hotfix stuff #1703: Refactors the count method in GoogleMailManager to use the Effect library for concurrency and error handling.
  • fix deployment #1712: Makes minor formatting and import adjustments in the same count method, related but less substantive than the main refactor.

Poem

A bunny hopped through code so bright,
Refactored counts with Effect's might.
Five-minute stats now stay so fresh,
Notifications submit with less.
With every hop, the code grew neat—
Concurrency and caching, a treat!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 364e90b and 14c4a34.

📒 Files selected for processing (3)
  • apps/mail/app/(routes)/settings/notifications/page.tsx (1 hunks)
  • apps/mail/hooks/use-stats.ts (1 hunks)
  • apps/server/src/lib/driver/google.ts (2 hunks)
✨ 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.

@MrgSub MrgSub marked this pull request as ready for review July 20, 2025 20:28
Copy link
Collaborator Author

MrgSub commented Jul 20, 2025

This stack of pull requests is managed by Graphite. Learn more about stacking.

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

Copy link
Collaborator Author

MrgSub commented Jul 20, 2025

Merge activity

  • Jul 20, 8:29 PM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Jul 20, 8:29 PM UTC: @MrgSub merged this pull request with Graphite.

@MrgSub MrgSub merged commit d040186 into staging Jul 20, 2025
7 of 9 checks passed
@MrgSub MrgSub deleted the Refactor_Google_mail_count_implementation_and_add_staleTime_to_stats_query branch July 20, 2025 20:29
const statsQuery = useQuery(
trpc.mail.count.queryOptions(void 0, {
enabled: !!session?.user.id,
staleTime: 1000 * 60 * 5, // 1 hour
Copy link
Contributor

Choose a reason for hiding this comment

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

The comment indicates // 1 hour but the actual implementation sets staleTime to 1000 * 60 * 5, which is 5 minutes. The comment should be updated to accurately reflect the code implementation.

Suggested change
staleTime: 1000 * 60 * 5, // 1 hour
staleTime: 1000 * 60 * 5, // 5 minutes

Spotted by Diamond

Is this helpful? React 👍 or 👎 to let us know.

Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

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

Bug: Error Handling Regression in Label Fetching

The error handling in processLabelEffect is flawed. The condition if ('_tag' in res) return null; inside Effect.map is unreachable because Effect.map only processes successful results; errors from Effect.tryPromise are propagated through Effect's error channel. This causes Effect.all to fail entirely if any single label fetch fails, a regression from the previous graceful handling of individual failures. Consequently, failed label fetches are not properly filtered, potentially leading to runtime errors.

apps/server/src/lib/driver/google.ts#L246-L268

const processLabelEffect = (label: any) =>
Effect.tryPromise({
try: () => this.gmail.users.labels.get({
userId: 'me',
id: label.id ?? undefined,
}),
catch: (error) => ({ _tag: 'LabelFetchFailed' as const, error, labelId: label.id }),
}).pipe(
Effect.map((res) => {
if ('_tag' in res) return null;
let labelName = (res.data.name ?? res.data.id ?? '').toLowerCase();
if (labelName === 'draft') {
labelName = 'drafts';
}
const isTotalLabel = labelName === 'drafts' || labelName === 'sent';
return {
label: labelName,
count: Number(isTotalLabel ? res.data.threadsTotal : res.data.threadsUnread),
};
}),
);

Fix in CursorFix in Web


BugBot free trial expires on July 31, 2025
Learn more in the Cursor dashboard.

Was this report helpful? Give feedback by reacting with 👍 or 👎

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

cubic analysis

No issues found across 3 files. Review in cubic

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