Skip to content

Comments

Disable unused drafts#409

Merged
elie222 merged 3 commits intomainfrom
disable-unused-drafts
Apr 17, 2025
Merged

Disable unused drafts#409
elie222 merged 3 commits intomainfrom
disable-unused-drafts

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Apr 17, 2025

Summary by CodeRabbit

  • New Features

    • Introduced an automated daily task to disable the auto-draft feature for users who have not used their last 10 drafts, improving system maintenance and user experience.
  • Documentation

    • Updated the README to clarify cron job requirements and added details about the new daily maintenance cron job for reply tracking.
  • Chores

    • Added a new dependency to the web app for enhanced functionality.

@vercel
Copy link

vercel bot commented Apr 17, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
inbox-zero ✅ Ready (Inspect) Visit Preview Apr 17, 2025 10:36pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 17, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The updates introduce a new API route for disabling the auto-draft feature for users who have not used their last 10 drafts, including logic for querying relevant users, checking draft usage, deleting draft actions, logging, and error handling. The README is updated to clarify that the Google watch cron job is mandatory while others are optional, and it adds a new example cron job for running the disable-unused-auto-draft task daily at 3:00 AM. Additionally, the ai-fallback dependency (version 0.1.2) is added to the web application's package configuration.

Changes

File(s) Change Summary
README.md Clarified cron job requirements: Google watch is mandatory, others optional; added example cron job for disabling unused auto-draft at 3:00 AM daily.
apps/web/app/api/reply-tracker/disable-unused-auto-draft/route.ts Added new API route implementing POST handler with cron secret authorization to disable auto-draft for users inactive on drafts; includes querying, deletion, logging, error handling, and dynamic rendering. Commented-out GET handler present for local testing.
apps/web/package.json Added new dependency "ai-fallback": "0.1.2" to the project dependencies.

Sequence Diagram(s)

sequenceDiagram
    participant CronJob as Cron Job
    participant API as /api/reply-tracker/disable-unused-auto-draft
    participant DB as Database

    CronJob->>API: Scheduled POST request with cron secret
    API->>API: Authorize request (check secret)
    API->>DB: Query users with auto-draft enabled
    loop For each user
        API->>DB: Fetch last 10 drafts older than 1 day
        API->>DB: Check if any drafts were sent
        alt None sent
            API->>DB: Delete DRAFT_EMAIL actions for user
        end
    end
    API->>API: Log progress and errors
    API-->>CronJob: Return summary (users checked, disabled, errors)
Loading

Possibly related PRs

  • Disable unused drafts #409: Implements the same API route to disable unused auto-drafts and updates the README with the same cron job information, indicating direct relation.

Poem

🐇
A cron hops nightly, silent and swift,
Disabling drafts that users let drift.
With secrets in tow, it checks every case,
Cleaning the burrows, restoring the space.
A new route is born, dependencies grow—
The garden of code continues to flow!
🌱

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

apps/web/app/api/reply-tracker/disable-unused-auto-draft/route.ts

Oops! Something went wrong! :(

ESLint: 9.24.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 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 3ec6cb5 and 2ae6ed4.

📒 Files selected for processing (1)
  • apps/web/app/api/reply-tracker/disable-unused-auto-draft/route.ts (1 hunks)

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

🧹 Nitpick comments (2)
README.md (1)

214-231: JSON snippet is not strictly valid – trailing comma after the last object

Some cron providers (and JSON linters) reject trailing commas. In the block below the last object ends with a comma on line 229:

{
  "path": "/api/reply-tracker/disable-unused-auto-draft",
  "schedule": "0 3 * * *"
},

Removing the comma keeps the example copy‑paste‑able:

@@
     {
       "path": "/api/reply-tracker/disable-unused-auto-draft",
-      "schedule": "0 3 * * *"
-    }
+      "schedule": "0 3 * * *"
+    }
apps/web/app/api/reply-tracker/disable-unused-auto-draft/route.ts (1)

24-25: Timezone edge case: subDays vs. “more than 24 h ago”

subDays(new Date(), 1) creates a timestamp exactly 24 h in the past.
If the job runs close to midnight UTC, drafts created “yesterday” but only a few hours old will already be included. That may disable auto‑draft prematurely for users in later time zones.

Consider using subHours(new Date(), 24) or even making the threshold configurable (e.g. 36 h) to avoid accidental disabling.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c2148a5 and a35908c.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (3)
  • README.md (2 hunks)
  • apps/web/app/api/reply-tracker/disable-unused-auto-draft/route.ts (1 hunks)
  • apps/web/package.json (1 hunks)
🔇 Additional comments (1)
apps/web/package.json (1)

78-80: Confirm the need for the new ai‑fallback dependency and keep lock‑files in sync

The package is pinned at 0.1.2, but no references appear elsewhere in the PR. Please verify that:

  1. The new route (or other code) really imports ai-fallback; otherwise the dependency will bloat the bundle.
  2. pnpm-lock.yaml (or equivalent) is committed to avoid CI drift.

If the lib is only intended for future work, consider adding it when the code that consumes it lands.

Comment on lines +63 to +83
// Process each user
for (const user of usersWithAutoDraft) {
try {
// Find the last 10 drafts created for the user
const lastTenDrafts = await prisma.executedAction.findMany({
where: {
executedRule: {
userId: user.id,
rule: {
systemType: SystemType.TO_REPLY,
},
},
type: ActionType.DRAFT_EMAIL,
draftId: { not: null },
createdAt: { lt: oneDayAgo }, // Only check drafts older than a day
},
orderBy: {
createdAt: "desc",
},
take: MAX_DRAFTS_TO_CHECK,
select: {
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

N + 1 queries – fetch drafts in batch instead of per‑user loop

The loop issues one executedAction.findMany per user. If thousands of users have auto‑draft enabled the route will:

  • hammer the DB with many small queries,
  • hold the Lambda/function warm longer and increase cold‑start cost,
  • risk timing out for the 10 s default Vercel edge timeout (if not using background).

You can reduce round‑trips with a single query that groups by userId and aggregates the last 10 drafts per user, e.g.:

const draftsByUser = await prisma.executedAction.groupBy({
  by: ["executedRule.userId"],
  where: { /* same filters */ },
  _count: { id: true },
  _max: { createdAt: true },
  take: MAX_DRAFTS_TO_CHECK,
});

Then process the in‑memory groups.
This will scale linearly with returned rows instead of users.

@elie222 elie222 merged commit b0f6230 into main Apr 17, 2025
2 of 3 checks passed
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

♻️ Duplicate comments (2)
apps/web/app/api/reply-tracker/disable-unused-auto-draft/route.ts (2)

22-138: Comprehensive implementation with database performance concerns

The implementation is thorough with good error handling, logging, and filtering logic. However, it still contains the N+1 query pattern mentioned in previous reviews, which could cause performance issues at scale.

Consider retrieving draft usage statistics in a single aggregated query before processing individual users. Run this script to estimate the performance impact at your current scale:

#!/bin/bash
# Check user scale and potential query performance impact

# Count total users and rules to understand scale
echo "Checking system scale:"
rg -A 5 "user.findMany|usersWithAutoDraft" apps/web/ --include "*.ts"
echo ""

# Look for similar patterns in codebase that might use batch operations
echo "Finding examples of batch operations:"
rg -A 5 "groupBy|$transaction" apps/web/ --include "*.ts" | head -n 20

105-125: 🛠️ Refactor suggestion

Race condition in check-then-act pattern

The current implementation checks if drafts were used and then deletes actions in separate database operations. This creates a race condition where a user might send a draft between the check and the deletion.

Implement the transaction-based approach suggested in the previous review to ensure atomicity:

- // Check if any of the drafts were sent
- const anyDraftsSent = lastTenDrafts.some(
-   (draft) => draft.wasDraftSent === true || draft.draftSendLog,
- );
- 
- // If none of the drafts were sent, disable auto-draft
- if (!anyDraftsSent) {
-   logger.info("Disabling auto-draft for user - last 10 drafts not used", {
-     userId: user.id,
-   });
- 
-   // Delete the DRAFT_EMAIL actions from all TO_REPLY rules
-   await prisma.action.deleteMany({
-     where: {
-       rule: {
-         userId: user.id,
-         systemType: SystemType.TO_REPLY,
-       },
-       type: ActionType.DRAFT_EMAIL,
-       content: null,
-     },
-   });
- 
-   results.usersDisabled++;
- }
+ // Extract draft IDs for the verification in the transaction
+ const lastTenDraftIds = lastTenDrafts.map(draft => draft.id);
+ 
+ // Use a transaction to ensure atomicity
+ await prisma.$transaction(async (tx) => {
+   // Re-check that none of the drafts were sent (could have changed since initial check)
+   const countUnused = await tx.executedAction.count({
+     where: {
+       id: { in: lastTenDraftIds },
+       OR: [
+         { wasDraftSent: false },
+         { draftSendLog: null },
+       ],
+     },
+   });
+   
+   // If all drafts are still unused, proceed with deletion
+   if (countUnused === MAX_DRAFTS_TO_CHECK) {
+     logger.info("Disabling auto-draft for user - last 10 drafts not used", {
+       userId: user.id,
+     });
+     
+     await tx.action.deleteMany({
+       where: {
+         rule: {
+           userId: user.id,
+           systemType: SystemType.TO_REPLY,
+         },
+         type: ActionType.DRAFT_EMAIL,
+         content: null,
+       },
+     });
+     
+     results.usersDisabled++;
+   }
+ });
🧹 Nitpick comments (1)
apps/web/app/api/reply-tracker/disable-unused-auto-draft/route.ts (1)

140-151: Commented code should be removed

The commented-out GET endpoint implementation should be removed before production deployment, as it's unused and could lead to confusion.

- // For easier local testing
- // export const GET = withError(async (request) => {
- //   if (!hasCronSecret(request)) {
- //     captureException(
- //       new Error("Unauthorized request: api/auto-draft/disable-unused"),
- //     );
- //     return new Response("Unauthorized", { status: 401 });
- //   }
- 
- //   const results = await disableUnusedAutoDrafts();
- //   return NextResponse.json(results);
- // });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a35908c and 3ec6cb5.

📒 Files selected for processing (1)
  • apps/web/app/api/reply-tracker/disable-unused-auto-draft/route.ts (1 hunks)
🔇 Additional comments (2)
apps/web/app/api/reply-tracker/disable-unused-auto-draft/route.ts (2)

13-14: Good configuration for background processing

Setting dynamic to "force-dynamic" ensures fresh data on each request, and the 5-minute maxDuration gives this background task enough time to process many users without hitting timeout limits.


153-163: Appropriate POST endpoint with security measures

Good implementation using POST instead of GET for a state-changing operation. The authentication check with hasPostCronSecret ensures only authorized cron jobs can trigger this action.

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