Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(user-notification): Stale deviceToken cleanup #14840

Merged
merged 20 commits into from
May 23, 2024

Conversation

rafnarnason
Copy link
Member

@rafnarnason rafnarnason commented May 16, 2024

This pull request introduces improvements to the user notification system by implementing a cleanup mechanism for stale device tokens. Key changes include:

Enhanced Error Handling: Added comprehensive error handling for various Firebase messaging errors, ensuring invalid or outdated device tokens are removed promptly.
New API Endpoint: Introduced a DELETE endpoint in the UserTokenController to facilitate the removal of invalid device tokens from the user profile service.
Service Method Addition: Added a method in the UserTokenService to delete device tokens by national ID, supporting the cleanup process.
These changes enhance the reliability of the notification system by ensuring that only valid device tokens are used, thus reducing potential errors and improving user experience.

Attach a link to issue if relevant

What

Specify what you're trying to achieve

Why

Specify why you need to achieve this

Screenshots / Gifs

Attach Screenshots / Gifs to help reviewers understand the scope of the pull request

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for push notifications to address various error scenarios.
    • Improved token management and notification sending logic.
  • Refactor

    • Restructured methods for fetching device tokens and sending notifications.
    • Updated method signature for sending notifications to include messageId.
  • Bug Fixes

    • Replaced dynamic user profile fetching with hardcoded mock user profile to improve reliability.

Copy link
Contributor

coderabbitai bot commented May 16, 2024

Note

Reviews Paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Walkthrough

The recent updates in the user notification service involve significant refactoring to enhance push notification handling. This includes improved error management, better token handling, and streamlined notification dispatch logic. Additionally, there has been a shift from dynamic user profile fetching to using hardcoded mock profiles in the notifications worker service.

Changes

File Path Change Summary
.../notificationDispatch.service.ts Refactored push notification handling by adding new methods for error handling, token management, and notification dispatch. Removed PushNotificationError class and isTokenError function. Modified sendNotification method to include messageId.
.../notificationsWorker.service.ts Commented out code for fetching user profiles based on delegation status and replaced it with hardcoded mock user profile creation.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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.

@datadog-island-is
Copy link

datadog-island-is bot commented May 16, 2024

Datadog Report

All test runs 7782c0d 🔗

6 Total Test Services: 0 Failed, 6 Passed
🔻 Test Sessions change in coverage: 1 decreased (-0.01%), 3 no change

Test Services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 4.23s 1 no change Link
application-system-api 0 0 0 111 2 3m 23.64s 1 decreased (-0.01%) Link
application-template-api-modules 0 0 0 109 0 1m 54.99s 1 no change Link
services-auth-ids-api 0 0 0 193 0 1m 43.97s N/A Link
services-user-notification 0 0 0 48 0 1m 40.78s N/A Link
services-user-profile 0 0 0 148 0 1m 31.88s N/A Link

🔻 Code Coverage Decreases vs Default Branch (1)

  • application-system-api - jest 37.69% (-0.01%) - Details

Copy link

codecov bot commented May 16, 2024

Codecov Report

Attention: Patch coverage is 6.06061% with 62 lines in your changes are missing coverage. Please review.

Project coverage is 37.02%. Comparing base (c4adeb9) to head (106eaa0).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #14840      +/-   ##
==========================================
- Coverage   37.04%   37.02%   -0.02%     
==========================================
  Files        6331     6331              
  Lines      129131   129134       +3     
  Branches    36859    36852       -7     
==========================================
- Hits        47833    47817      -16     
- Misses      81298    81317      +19     
Flag Coverage Δ
api 3.48% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files Coverage Δ
...vices/user-profile/src/app/v2/userToken.service.ts 77.77% <0.00%> (-22.23%) ⬇️
...es/user-profile/src/app/v2/userToken.controller.ts 85.71% <50.00%> (-14.29%) ⬇️
...ules/notifications/notificationDispatch.service.ts 12.50% <1.72%> (-14.17%) ⬇️

... and 12 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update c4adeb9...106eaa0. Read the comment docs.

@rafnarnason rafnarnason added the deploy-feature Deploys features to dev label May 16, 2024
Copy link
Contributor

Affected services are: api,application-system-api,services-auth-ids-api,services-user-notification,services-user-profile,

@rafnarnason rafnarnason removed the deploy-feature Deploys features to dev label May 21, 2024
@rafnarnason rafnarnason marked this pull request as ready for review May 21, 2024 14:44
@rafnarnason rafnarnason requested review from a team as code owners May 21, 2024 14:44
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

Review Details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits Files that changed from the base of the PR and between 6e95b66 and d0b2a88.
Files selected for processing (3)
  • apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (3 hunks)
  • apps/services/user-profile/src/app/v2/userToken.controller.ts (2 hunks)
  • apps/services/user-profile/src/app/v2/userToken.service.ts (1 hunks)
Additional Context Used
Path-based Instructions (3)
apps/services/user-profile/src/app/v2/userToken.service.ts (2)

Pattern apps/services/**/*: "Confirm that the code adheres to the following:

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/services/user-profile/src/app/v2/userToken.controller.ts (2)

Pattern apps/services/**/*: "Confirm that the code adheres to the following:

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (2)

Pattern apps/services/**/*: "Confirm that the code adheres to the following:

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
Additional comments not posted (3)
apps/services/user-profile/src/app/v2/userToken.service.ts (1)

21-31: The implementation of deleteUserTokenByNationalId correctly handles the deletion of user tokens based on national ID and device token. Good use of Sequelize's ORM capabilities.

apps/services/user-profile/src/app/v2/userToken.controller.ts (1)

55-71: The deleteUserDeviceToken method is well-implemented with clear documentation and auditing. It correctly handles the deletion of a user device token based on the provided national ID and device token.

apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (1)

31-49: The new methods in NotificationDispatchService are well-implemented with robust error handling and integration with external services. The logging and exception management are appropriate for the operations being performed.

Also applies to: 51-78, 80-115, 117-154, 156-171

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

Outside diff range and nitpick comments (1)
apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (1)

4-6: Consider handling more specific exceptions where possible.

Using generic exceptions like BadRequestException and InternalServerErrorException can be appropriate, but for a robust system, consider catching and handling more specific exceptions related to the operations being performed. This can aid in debugging and provide clearer error messages to the client.

Review Details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits Files that changed from the base of the PR and between d0b2a88 and fedb7d8.
Files selected for processing (1)
  • apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (3 hunks)
Additional Context Used
Path-based Instructions (1)
apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (2)

Pattern apps/services/**/*: "Confirm that the code adheres to the following:

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
Additional comments not posted (2)
apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (2)

31-48: Ensure proper handling when no tokens are found.

The early return when no tokens are found is a good practice as it prevents unnecessary processing. However, consider logging this event or notifying an admin if this scenario is unexpected or could indicate an issue.


111-112: Confirm successful notification dispatch.

Logging the success of the notification dispatch is good practice. It helps in monitoring and debugging the notification flow.

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

Review Details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits Files that changed from the base of the PR and between fedb7d8 and 83b5409.
Files selected for processing (2)
  • apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (3 hunks)
  • apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.ts (1 hunks)
Additional Context Used
Path-based Instructions (2)
apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (2)

Pattern apps/services/**/*: "Confirm that the code adheres to the following:

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.ts (2)

Pattern apps/services/**/*: "Confirm that the code adheres to the following:

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
Additional comments not posted (5)
apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (5)

31-31: Ensure proper handling when no device tokens are found.

This early return when no tokens are found is a good practice as it prevents unnecessary processing.


46-47: Consider breaking the loop on specific errors.

As previously noted, consider whether it might be appropriate to stop further processing if a certain type of error is encountered repeatedly.


76-78: Enhance error handling by providing more context.

When catching exceptions in getDeviceTokens, the rethrown InternalServerErrorException should include more context about the error to aid in debugging.


118-166: Refactor error handling to improve maintainability.

The handleSendError method contains a large switch statement to handle various error codes. Consider refactoring this into separate methods or a strategy pattern to handle different types of errors, which could improve the maintainability and readability of the code.


169-184: Ensure robust error handling when removing invalid tokens.

The method removeInvalidToken attempts to remove a token and logs the outcome, but the catch block only logs the error without rethrowing or handling it further. This might lead to silent failures where the system believes a token has been removed when it has not.

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

Review Details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits Files that changed from the base of the PR and between 83b5409 and a41109f.
Files selected for processing (2)
  • apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (3 hunks)
  • apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.ts (1 hunks)
Additional Context Used
Path-based Instructions (2)
apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (2)

Pattern apps/services/**/*: "Confirm that the code adheres to the following:

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.ts (2)

Pattern apps/services/**/*: "Confirm that the code adheres to the following:

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
Additional comments not posted (6)
apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (5)

31-31: Ensure proper handling when no device tokens are found.

This early return when no tokens are found is a good practice as it avoids unnecessary processing.


46-47: Consider breaking the loop on specific errors.

As previously noted, consider whether it might be appropriate to stop further processing if a certain type of error is encountered repeatedly.


76-78: Enhance error handling by providing more context.

As previously suggested, the rethrown InternalServerErrorException should include more context about the error to aid in debugging.


118-166: Refactor error handling to improve maintainability.

Consider refactoring this large switch statement into separate methods or a strategy pattern to handle different types of errors, which could improve the maintainability and readability of the code.


169-184: Ensure robust error handling when removing invalid tokens.

As previously suggested, consider rethrowing or handling the error further in the catch block to avoid silent failures where the system believes a token has been removed when it has not.

apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.ts (1)

371-384: Ensure mock user profile is used only for testing and not in production.

As previously noted, ensure that the use of a mock user profile is clearly documented to avoid confusion during maintenance. Consider using environment-based conditions to enable mock profiles only in non-production environments.

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

Outside diff range and nitpick comments (3)
apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (3)

31-49: Ensure comprehensive logging by adding more context to error messages.

Consider enhancing the error log in the catch block by including the nationalId to aid in debugging.


51-77: Enhance error handling by providing more context.

Consider adding the nationalId to the InternalServerErrorException message to provide more detailed debugging information.


Line range hint 80-115: Add error handling for Firebase messaging service calls.

Consider wrapping the firebase.messaging().send(message) call in a try-catch block to handle potential errors from the Firebase service.

Review Details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits Files that changed from the base of the PR and between a41109f and ab01aec.
Files selected for processing (2)
  • apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (3 hunks)
  • apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.ts
Additional Context Used
Path-based Instructions (1)
apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (2)

Pattern apps/services/**/*: "Confirm that the code adheres to the following:

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
Additional comments not posted (2)
apps/services/user-notification/src/app/modules/notifications/notificationDispatch.service.ts (2)

1-6: Imports are well-organized and adhere to NestJS best practices.


10-14: Constructor correctly implements dependency injection, adhering to NestJS best practices.

@rafnarnason
Copy link
Member Author

@coderabbitai pause

Copy link
Contributor

coderabbitai bot commented May 22, 2024

Actions Performed

Reviews paused.

Copy link
Member

@GunnlaugurG GunnlaugurG left a comment

Choose a reason for hiding this comment

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

LGTM!

@rafnarnason rafnarnason added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label May 23, 2024
@kodiakhq kodiakhq bot merged commit 9bf6804 into main May 23, 2024
40 checks passed
@kodiakhq kodiakhq bot deleted the user-notification/stale-token-cleanup branch May 23, 2024 05:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
deprecated:automerge (Disabled) Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants