Skip to content

Comments

move up processing code#755

Merged
elie222 merged 1 commit intomainfrom
fix/mark-processing
Sep 7, 2025
Merged

move up processing code#755
elie222 merged 1 commit intomainfrom
fix/mark-processing

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Sep 7, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability of email event handling by preventing duplicate processing of the same message, reducing repeated actions or notifications.
  • Chores

    • Bumped app version to v2.9.1.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 7, 2025

Walkthrough

Moves the concurrency guard (markMessageAsProcessing) to the start of processHistoryItem to skip already-processing messages earlier; removes the later duplicate guard. No signature changes. Updates version.txt from v2.9.0 to v2.9.1.

Changes

Cohort / File(s) Summary
Google webhook processing
apps/web/app/api/google/webhook/process-history-item.ts
Relocated concurrency check to the beginning of processing; added early-return skip log; removed redundant later guard; overall control flow updated before type-specific handling.
Versioning
version.txt
Bumped version from v2.9.0 to v2.9.1.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Google as Google Webhook
  participant API as processHistoryItem
  participant Email as EmailProvider
  participant Mutex as markMessageAsProcessing

  Google->>API: POST history item
  API->>Email: create provider
  API->>Mutex: markMessageAsProcessing(userEmail, messageId)
  alt Message already processing
    API-->>Google: Log "Skipping. Message already being processed." and return
  else Message free
    API->>API: Handle type-specific paths (e.g., LABEL_REMOVED / LABEL_ADDED)
    API->>Email: Fetch/process message as needed
    API-->>Google: Done
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Poem

A whisk of code, a hop so spry,
We guard the queue and then we fly.
If busy, skip—no time to stew,
Version bumps to two-dot-nine-dot-two.
Ears up high, the logs are clean,
A tidy trail in fields of green. 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/mark-processing

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 and usage tips.

@vercel
Copy link

vercel bot commented Sep 7, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Sep 7, 2025 3:20pm

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.

This PR is being reviewed by Cursor Bugbot

Details

You are on the Bugbot Free tier. On this plan, Bugbot will review limited PRs each billing cycle.

To receive Bugbot reviews on all of your PRs, please upgrade to Bugbot Pro by visiting the Cursor dashboard. Your first 14 days will be free!

logger.info("Skipping. Message already being processed.", loggerOptions);
return;
}

Copy link

Choose a reason for hiding this comment

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

Bug: Processing Lock Skips Label Events

Moving the markMessageAsProcessing check before label event handling causes LABEL_REMOVED and LABEL_ADDED events to be skipped if a message is already being processed. This prevents independent learning operations and also unnecessarily calls markMessageAsProcessing, potentially leaving messages permanently locked since the lock is never released for these early-exit paths.

Fix in Cursor Fix in Web

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: 0

🧹 Nitpick comments (1)
apps/web/app/api/google/webhook/process-history-item.ts (1)

68-74: Lock timing may gate label-only events; confirm intent or adjust placement.

Acquiring the processing lock before branching on event type means LABEL_ADDED/LABEL_REMOVED paths also take a 5‑min lock, potentially delaying subsequent MESSAGE_ADDED handling for the same message. If that’s not desired, acquire the lock only for the message-processing path. Alternatively, if you want the early guard, move it before provider creation to avoid unnecessary provider instantiation when the lock is held.

Option A — lock only for non-label events (recommended if label events shouldn’t block message processing):

@@
-  const provider = await createEmailProvider({
-    emailAccountId,
-    provider: "google",
-  });
-
-  const isFree = await markMessageAsProcessing({ userEmail, messageId });
-
-  if (!isFree) {
-    logger.info("Skipping. Message already being processed.", loggerOptions);
-    return;
-  }
+  const provider = await createEmailProvider({
+    emailAccountId,
+    provider: "google",
+  });
@@
   } else if (type === HistoryEventType.LABEL_ADDED) {
     logger.info("Processing label added event for learning", loggerOptions);
     return;
   }
 
+  // Acquire processing lock only for non-label events (i.e., MESSAGE_ADDED).
+  const isFree = await markMessageAsProcessing({ userEmail, messageId });
+  if (!isFree) {
+    logger.info("Skipping. Message already being processed.", loggerOptions);
+    return;
+  }

Option B — keep early guard, but avoid creating the provider when we’ll skip anyway:

@@
-  const provider = await createEmailProvider({
-    emailAccountId,
-    provider: "google",
-  });
-
-  const isFree = await markMessageAsProcessing({ userEmail, messageId });
+  const isFree = await markMessageAsProcessing({ userEmail, messageId });
 
   if (!isFree) {
     logger.info("Skipping. Message already being processed.", loggerOptions);
     return;
   }
 
+  const provider = await createEmailProvider({
+    emailAccountId,
+    provider: "google",
+  });
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3eeb4cd and 7e755c2.

📒 Files selected for processing (2)
  • apps/web/app/api/google/webhook/process-history-item.ts (1 hunks)
  • version.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • version.txt
  • apps/web/app/api/google/webhook/process-history-item.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • version.txt
  • apps/web/app/api/google/webhook/process-history-item.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/app/api/google/webhook/process-history-item.ts
apps/web/app/**

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

NextJS app router structure with (app) directory

Files:

  • apps/web/app/api/google/webhook/process-history-item.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/app/api/google/webhook/process-history-item.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/app/api/google/webhook/process-history-item.ts
apps/web/app/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)

apps/web/app/api/**/*.{ts,js}: All API route handlers in 'apps/web/app/api/' must use authentication middleware: withAuth, withEmailAccount, or withError (with custom authentication logic).
All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.
All parameters used in API routes must be validated before use; do not use parameters from 'params' or request bodies directly in queries without validation.
Request bodies in API routes should use Zod schemas for validation.
API routes should only return necessary fields using Prisma's 'select' and must not include sensitive data in error messages.
Error messages in API routes must not reveal internal details; use generic errors and SafeError for user-facing errors.
All QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.
All cron endpoints in API routes must use hasCronSecret or hasPostCronSecret for authentication.
Do not hardcode weak or plaintext secrets in API route files; secrets must not be directly assigned as string literals.
Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Files:

  • apps/web/app/api/google/webhook/process-history-item.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/app/api/google/webhook/process-history-item.ts
🧬 Code graph analysis (1)
apps/web/app/api/google/webhook/process-history-item.ts (1)
apps/web/utils/redis/message-processing.ts (1)
  • markMessageAsProcessing (13-31)
🔇 Additional comments (1)
version.txt (1)

1-1: Patch bump looks good.

v2.9.1 aligns with a small internal behavior tweak. No concerns.

@elie222 elie222 merged commit baae770 into main Sep 7, 2025
17 checks passed
@elie222 elie222 deleted the fix/mark-processing branch September 7, 2025 15:44
@coderabbitai coderabbitai bot mentioned this pull request Oct 8, 2025
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