Skip to content

fix: added cron to schedule task and split the notification to be its…#41

Merged
carhartlewis merged 2 commits into
mainfrom
lewis/notifications
Feb 11, 2025
Merged

fix: added cron to schedule task and split the notification to be its…#41
carhartlewis merged 2 commits into
mainfrom
lewis/notifications

Conversation

@carhartlewis
Copy link
Copy Markdown
Contributor

@carhartlewis carhartlewis commented Feb 11, 2025

… own task, using batchTrigger

Summary by CodeRabbit

  • New Features

    • Introduced a new function for sending risk task notifications, improving the notification process for task owners.
    • Implemented an hourly scheduled task to automatically identify and send notifications for risk tasks due within the upcoming week.
  • Chores

    • Removed the legacy risk task notification process in favor of the updated system.

@vercel
Copy link
Copy Markdown

vercel Bot commented Feb 11, 2025

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

Name Status Preview Comments Updated (UTC)
app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 11, 2025 4:22pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
web ⬜️ Skipped (Inspect) Feb 11, 2025 4:22pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Feb 11, 2025

Walkthrough

This pull request refactors the risk task notifications system. It introduces a new function, sendRiskTaskNotification, to send individual notifications and a scheduled task, sendRiskTaskSchedule, that runs hourly to trigger notifications for pending risk tasks. In doing so, it removes the previously used notification file (risk-task-notifications.ts), consolidating and organizing the notification logic into the new implementations.

Changes

File Path Change Summary
apps/app/src/jobs/.../risk-task-notification.ts Introduced the sendRiskTaskNotification function using the schemaTask from @trigger.dev/sdk/v3 to extract task details, update the DB, and trigger notifications.
apps/app/src/jobs/.../risk-task-notifications.ts Deleted the file that contained the old scheduled notification logic for risk mitigation tasks.
apps/app/src/jobs/.../risk-task-schedule.ts Added the sendRiskTaskSchedule scheduled task (cron: hourly) to query pending risk tasks and batch trigger notifications using the new notification function.

Possibly related PRs

Poem

I'm a bunny on the hop, delight in every line,
New functions and schedules make the risk tasks shine.
With each tick of the clock, notifications swiftly fly,
Database updates and triggers—oh my, oh my!
I hop through the code with joy and flair,
Celebrating smooth changes with a jubilant hare!
🐇✨


📜 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 e9f51a6 and 180a720.

📒 Files selected for processing (1)
  • apps/app/src/jobs/tasks/notifications/risk-task-schedule.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/app/src/jobs/tasks/notifications/risk-task-schedule.ts

🪧 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. (Beta)
  • @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
Copy Markdown

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

🧹 Nitpick comments (4)
apps/app/src/jobs/tasks/notifications/risk-task-notification.ts (1)

22-53: Consider enhancing error handling and logging.

While the basic error handling is in place, consider these improvements:

  1. Log the specific task ID in error messages for better debugging
  2. Consider retrying the database update on transient errors
  3. Add error type checking for more specific error handling

Apply this diff to enhance error handling:

   run: async (payload) => {
     const { task } = payload;
 
     try {
       const owner = task.owner;
 
       const timeUntilDue = task.dueDate ? formatDistance(task.dueDate, new Date(), { addSuffix: true }) : "soon";
 
-      await db.riskMitigationTask.update({
-        where: { id: task.id },
-        data: { notifiedAt: new Date() },
-      });
+      try {
+        await db.riskMitigationTask.update({
+          where: { id: task.id },
+          data: { notifiedAt: new Date() },
+        });
+      } catch (dbError) {
+        logger.error(`Database error updating task ${task.id}: ${dbError}`);
+        throw dbError;
+      }
 
       await trigger({
         name: TriggerEvents.TaskReminderInApp,
         user: {
           subscriberId: `${owner.organizationId}_${owner.id}`,
           email: owner.email,
           fullName: owner.email,
           organizationId: owner.organizationId,
         },
         payload: {
           description: `${task.title} is due ${timeUntilDue}`,
           recordId: `/risk/${task.riskId}/tasks/${task.id}`,
           type: NotificationTypes.Task,
         },
       });
     } catch (error) {
-      logger.error(`Error sending risk task notification: ${error}`);
+      logger.error(`Error processing task ${task.id}: ${error}`);
+      if (error instanceof Error) {
+        logger.error(`Stack trace: ${error.stack}`);
+      }
+      throw error; // Re-throw to trigger retry mechanism
     }
   },
apps/app/src/jobs/tasks/notifications/risk-task-schedule.ts (3)

5-8: Consider adjusting cron schedule for optimal performance.

The hourly cron schedule (0 * * * *) might be too frequent for this task. Consider running it less frequently (e.g., every 4 hours) to reduce database load, unless there's a specific requirement for hourly notifications.

-  cron: "0 * * * *",
+  cron: "0 */4 * * *", // Runs every 4 hours

9-14: Use date-fns for consistent date handling.

Since date-fns is already a dependency (used in risk-task-notification.ts), consider using it here for consistent date manipulation across the codebase.

+import { addWeeks } from "date-fns";
+
 export const sendRiskTaskSchedule = schedules.task({
   id: "risk-task-schedule",
   cron: "0 * * * *",
   run: async () => {
     const now = new Date();
-    const upcomingThreshold = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
+    const upcomingThreshold = addWeeks(now, 1);

39-54: Enhance type safety in filter predicate.

The type predicate in the filter function could be improved for better type safety and readability.

-    const triggerPayloads = tasks
-      .filter((task): task is (typeof task & {
-        owner: { id: string; email: string; organizationId: string }
-      }) => Boolean(task.owner?.email && task.owner.organizationId))
+    interface ValidTask extends typeof tasks[number] {
+      owner: {
+        id: string;
+        email: string;
+        organizationId: string;
+      };
+    }
+
+    const isValidTask = (task: typeof tasks[number]): task is ValidTask => {
+      return Boolean(
+        task.owner?.id &&
+        task.owner?.email &&
+        task.owner?.organizationId
+      );
+    };
+
+    const triggerPayloads = tasks
+      .filter(isValidTask)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8185ae1 and e9f51a6.

📒 Files selected for processing (3)
  • apps/app/src/jobs/tasks/notifications/risk-task-notification.ts (1 hunks)
  • apps/app/src/jobs/tasks/notifications/risk-task-notifications.ts (0 hunks)
  • apps/app/src/jobs/tasks/notifications/risk-task-schedule.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/app/src/jobs/tasks/notifications/risk-task-notifications.ts
🔇 Additional comments (1)
apps/app/src/jobs/tasks/notifications/risk-task-notification.ts (1)

7-21: LGTM! Well-structured schema definition.

The schema is well-defined using Zod, with clear validation for all required fields.

Comment on lines +55 to +68
if (triggerPayloads.length > 0) {
await sendRiskTaskNotification.batchTrigger(
triggerPayloads,
);

logger.info(`Triggered ${triggerPayloads.length} task notifications`);
}

return {
success: true,
totalTasks: tasks.length,
triggeredTasks: triggerPayloads.length,
};
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for batch trigger operation.

The batch trigger operation should include error handling to ensure failures are properly logged and handled.

     if (triggerPayloads.length > 0) {
+      try {
         await sendRiskTaskNotification.batchTrigger(
           triggerPayloads,
         );
 
         logger.info(`Triggered ${triggerPayloads.length} task notifications`);
+      } catch (error) {
+        logger.error(`Failed to trigger batch notifications: ${error}`);
+        return {
+          success: false,
+          totalTasks: tasks.length,
+          triggeredTasks: 0,
+          error: error instanceof Error ? error.message : String(error),
+        };
+      }
     }
 
     return {
       success: true,
       totalTasks: tasks.length,
       triggeredTasks: triggerPayloads.length,
     };
📝 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
if (triggerPayloads.length > 0) {
await sendRiskTaskNotification.batchTrigger(
triggerPayloads,
);
logger.info(`Triggered ${triggerPayloads.length} task notifications`);
}
return {
success: true,
totalTasks: tasks.length,
triggeredTasks: triggerPayloads.length,
};
}
if (triggerPayloads.length > 0) {
try {
await sendRiskTaskNotification.batchTrigger(
triggerPayloads,
);
logger.info(`Triggered ${triggerPayloads.length} task notifications`);
} catch (error) {
logger.error(`Failed to trigger batch notifications: ${error}`);
return {
success: false,
totalTasks: tasks.length,
triggeredTasks: 0,
error: error instanceof Error ? error.message : String(error),
};
}
}
return {
success: true,
totalTasks: tasks.length,
triggeredTasks: triggerPayloads.length,
};
}

Comment on lines +16 to +38
const tasks = await db.riskMitigationTask.findMany({
where: {
dueDate: { gte: now, lte: upcomingThreshold },
status: { in: ["open", "pending"] },
notifiedAt: null,
},
select: {
id: true,
dueDate: true,
notifiedAt: true,
riskId: true,
title: true,
owner: {
select: {
id: true,
email: true,
name: true,
organizationId: true,
},
},
},
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider pagination for large result sets.

The findMany query might return a large number of tasks. Consider implementing pagination to handle the results in batches.

+    const BATCH_SIZE = 100;
+    let processedCount = 0;
+    
     const tasks = await db.riskMitigationTask.findMany({
       where: {
         dueDate: { gte: now, lte: upcomingThreshold },
         status: { in: ["open", "pending"] },
         notifiedAt: null,
       },
+      take: BATCH_SIZE,
       select: {
         id: true,
         dueDate: true,
         notifiedAt: true,
         riskId: true,
         title: true,
         owner: {
           select: {
             id: true,
             email: true,
             name: true,
             organizationId: true,
           },
         },
       },
     });
+    processedCount = tasks.length;
+    
+    logger.info(`Processing ${processedCount} tasks in this batch`);
📝 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
const tasks = await db.riskMitigationTask.findMany({
where: {
dueDate: { gte: now, lte: upcomingThreshold },
status: { in: ["open", "pending"] },
notifiedAt: null,
},
select: {
id: true,
dueDate: true,
notifiedAt: true,
riskId: true,
title: true,
owner: {
select: {
id: true,
email: true,
name: true,
organizationId: true,
},
},
},
});
const BATCH_SIZE = 100;
let processedCount = 0;
const tasks = await db.riskMitigationTask.findMany({
where: {
dueDate: { gte: now, lte: upcomingThreshold },
status: { in: ["open", "pending"] },
notifiedAt: null,
},
take: BATCH_SIZE,
select: {
id: true,
dueDate: true,
notifiedAt: true,
riskId: true,
title: true,
owner: {
select: {
id: true,
email: true,
name: true,
organizationId: true,
},
},
},
});
processedCount = tasks.length;
logger.info(`Processing ${processedCount} tasks in this batch`);

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