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

fix(auth-admin): Move sleep logic from messgeHandler to worker service #16712

Merged
merged 18 commits into from
Nov 14, 2024

Conversation

magnearun
Copy link
Contributor

@magnearun magnearun commented Nov 4, 2024

What

Handle sleep logic in worker instead of messageHandler

Why

Better separation of concerns and
when the worker manages sleep, it doesn’t pull new messages during non-working hours, which optimizes resource usage and reduces unnecessary processing.

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

Release Notes

  • New Features

    • Introduced a configuration option for notifications to operate continuously without pauses for non-working hours.
    • Added new utility functions for time management, including checks for working hours and sleep duration calculations.
  • Improvements

    • Enhanced the WorkerService to manage operations based on working hours, allowing for better control and efficiency.
    • Updated the NotificationsWorkerService to simplify notification processing by removing time-based checks.
  • Tests

    • Added new test cases to validate the functionality of time-related utilities and ensure robust notification handling.

These updates streamline notification processing and improve overall system responsiveness.

Copy link
Contributor

coderabbitai bot commented Nov 4, 2024

Walkthrough

The pull request introduces modifications to the notification system, specifically enhancing the handling of operational hours for the worker service. A new configuration property, shouldSleepOutsideWorkingHours, is added to the queue settings, indicating whether the worker should pause operations outside of designated hours. Correspondingly, the NotificationsWorkerService class has removed time-based checks, allowing continuous processing of notifications. New utility functions and constants related to working hours have also been introduced, along with updates to the WorkerService to manage the sleeping state effectively.

Changes

File Change Summary
apps/services/user-notification/src/app/modules/notifications/notifications.module.ts Added property shouldSleepOutsideWorkingHours to queue configuration.
apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.ts Removed constants for working hours and the sleepOutsideWorkingHours method; updated run method.
libs/message-queue/src/lib/nest/types.ts Added optional property shouldSleepOutsideWorkingHours to Queue interface.
libs/message-queue/src/lib/nest/utils.spec.ts Introduced new tests for isOutsideWorkingHours and calculateSleepDurationUntilMorning functions.
libs/message-queue/src/lib/nest/utils.ts Added constants for working hours and new functions: isOutsideWorkingHours, calculateSleepDurationUntilMorning, and sleepUntilMorning.
libs/message-queue/src/lib/nest/worker.service.ts Added Sleeping status to Status enum and implemented maybeSleepOutsideWorkingHours method.

Possibly related PRs

Suggested labels

high priority

Suggested reviewers

  • unakb
  • rafnarnason

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>, 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 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.

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 Nov 4, 2024

Datadog Report

All test runs 755e45d 🔗

5 Total Test Services: 1 Failed, 4 Passed
🔻 Test Sessions change in coverage: 1 decreased (-0.55%), 1 increased (+0.11%), 6 no change

Test Services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
services-user-notification 11 0 0 40 0 1m 34.33s 1 decreased (-0.55%) Link
api 0 0 0 4 0 3.1s 1 no change Link
application-system-api 0 0 0 112 2 3m 40.75s 1 no change Link
application-template-api-modules 0 0 0 113 0 2m 38.4s 1 no change Link
message-queue 0 0 0 10 0 43.18s 1 increased (+0.11%) Link

❌ Failed Tests (11)

This report shows up to 5 failed tests.

  • NotificationsWorkerService should call company registry for companies - apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.spec.ts - Details

    Expand for error
     expect(jest.fn()).toHaveBeenCalledTimes(expected)
     
     Expected number of calls: 1
     Received number of calls: 0
    
  • NotificationsWorkerService should call national registry for persons - apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.spec.ts - Details

    Expand for error
     expect(jest.fn()).toHaveBeenCalledTimes(expected)
     
     Expected number of calls: 1
     Received number of calls: 0
    
  • NotificationsWorkerService should not send email if feature flag is turned off - apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.spec.ts - Details

    Expand for error
     expect(jest.fn()).toHaveBeenCalledTimes(expected)
     
     Expected number of calls: 1
     Received number of calls: 0
    
  • NotificationsWorkerService should not send email if user has email notifications disabled - apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.spec.ts - Details

    Expand for error
     expect(jest.fn()).toHaveBeenCalledTimes(expected)
     
     Expected number of calls: 1
     Received number of calls: 0
    
  • NotificationsWorkerService should not send email if user has no email registered - apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.spec.ts - Details

    Expand for error
     expect(jest.fn()).toHaveBeenCalledTimes(expected)
     
     Expected number of calls: 1
     Received number of calls: 0
    

🔻 Code Coverage Decreases vs Default Branch (1)

  • services-user-notification - jest 68.97% (-0.55%) - Details

Copy link

codecov bot commented Nov 4, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 36.44%. Comparing base (c788e6a) to head (535e639).
Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main   #16712   +/-   ##
=======================================
  Coverage   36.44%   36.44%           
=======================================
  Files        6852     6855    +3     
  Lines      143541   143636   +95     
  Branches    40966    40992   +26     
=======================================
+ Hits        52307    52354   +47     
- Misses      91234    91282   +48     
Flag Coverage Δ
api 3.34% <ø> (ø)
application-system-api 40.98% <ø> (ø)
application-template-api-modules 27.66% <ø> (+<0.01%) ⬆️
message-queue 68.79% <74.07%> (+0.20%) ⬆️
services-user-notification 46.91% <100.00%> (+0.08%) ⬆️

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

Files with missing lines Coverage Δ
.../app/modules/notifications/notifications.module.ts 96.29% <ø> (ø)
...notificationsWorker/notificationsWorker.service.ts 94.28% <ø> (-0.56%) ⬇️
libs/message-queue/src/lib/nest/utils.ts 100.00% <100.00%> (ø)
libs/message-queue/src/lib/nest/worker.service.ts 95.89% <100.00%> (+0.57%) ⬆️

... and 38 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 c788e6a...535e639. Read the comment docs.

Copy link
Member

@eirikurn eirikurn left a comment

Choose a reason for hiding this comment

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

Good stuff. Just minor suggestions. 👍

libs/message-queue/src/lib/nest/worker.service.ts Outdated Show resolved Hide resolved
libs/message-queue/src/lib/nest/worker.service.ts Outdated Show resolved Hide resolved
libs/message-queue/src/lib/nest/worker.service.ts Outdated Show resolved Hide resolved
@magnearun magnearun marked this pull request as ready for review November 7, 2024 10:33
@magnearun magnearun requested review from a team as code owners November 7, 2024 10:33
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: 7

🧹 Outside diff range and nitpick comments (5)
libs/message-queue/src/lib/nest/types.ts (1)

21-22: Enhance the property documentation.

The comment could be more descriptive about when and why the worker sleeps. Consider expanding it to clarify the working hours concept and its impact.

-  // if true, the worker will sleep during the night
+  // if true, the worker will pause processing during non-working hours to optimize
+  // resource usage. Working hours are typically defined as Monday-Friday, 9 AM to 5 PM
libs/message-queue/src/lib/nest/utils.ts (1)

24-31: Add documentation and handle edge cases

The time calculation is complex and would benefit from:

  1. JSDoc documentation explaining the logic
  2. Edge case handling
  3. Explicit timezone handling

Consider these improvements:

+/**
+ * Calculates the duration in milliseconds until the next working day at WORK_STARTING_HOUR
+ * 
+ * @returns number Milliseconds until next working hour
+ * @throws {Error} If the calculation results in negative duration
+ */
 export const calculateSleepDurationUntilMorning = (): number => {
   const now = new Date()
   const currentHour = now.getHours()
   const currentMinutes = now.getMinutes()
   const currentSeconds = now.getSeconds()
   const sleepHours = (24 - currentHour + WORK_STARTING_HOUR) % 24
-  return (sleepHours * 3600 - currentMinutes * 60 - currentSeconds) * 1000
+  const duration = (sleepHours * 3600 - currentMinutes * 60 - currentSeconds) * 1000
+  
+  if (duration < 0) {
+    throw new Error('Calculated sleep duration is negative')
+  }
+  
+  return duration
 }
libs/message-queue/src/lib/nest/utils.spec.ts (1)

20-28: Enhance test coverage for edge cases and documentation.

While the current tests cover basic scenarios, consider:

  1. Adding edge cases for exactly 8:00 and 22:00
  2. Testing weekend behavior if working hours differ
  3. Using consistent comment formatting (e.g., "// 7:00 AM" instead of mixing styles)
 describe('isOutsideWorkingHours', () => {
   it('returns true if the current hour is outside working hours', () => {
-    expect(isOutsideWorkingHours(new Date('2023-01-01T07:00:00'))).toBe(true) // 7 AM
-    expect(isOutsideWorkingHours(new Date('2023-01-01T23:00:00'))).toBe(true) // 11 PM
-    expect(isOutsideWorkingHours(new Date('2023-01-01T00:00:00'))).toBe(true) // Midnight
-    expect(isOutsideWorkingHours(new Date('2023-01-01T08:00:00'))).toBe(false) // 8 AM
-    expect(isOutsideWorkingHours(new Date('2023-01-01T22:00:00'))).toBe(false) // 10 PM
+    // Before working hours
+    expect(isOutsideWorkingHours(new Date('2023-01-01T07:00:00'))).toBe(true)  // 7:00 AM
+    // Start of working hours
+    expect(isOutsideWorkingHours(new Date('2023-01-01T08:00:00'))).toBe(false) // 8:00 AM
+    // During working hours
+    expect(isOutsideWorkingHours(new Date('2023-01-01T15:00:00'))).toBe(false) // 3:00 PM
+    // End of working hours
+    expect(isOutsideWorkingHours(new Date('2023-01-01T22:00:00'))).toBe(false) // 10:00 PM
+    // After working hours
+    expect(isOutsideWorkingHours(new Date('2023-01-01T23:00:00'))).toBe(true)  // 11:00 PM
+    // Midnight
+    expect(isOutsideWorkingHours(new Date('2023-01-01T00:00:00'))).toBe(true)  // 12:00 AM
+    // Weekend (if applicable)
+    expect(isOutsideWorkingHours(new Date('2023-01-07T12:00:00'))).toBe(true)  // Saturday noon
   })
 })
apps/services/user-notification/src/app/modules/notifications/notifications.module.ts (1)

39-39: Consider making the sleep configuration more flexible.

Instead of hardcoding shouldSleepOutsideWorkingHours: true, consider making it configurable through environment variables. This would allow different behavior in different environments (e.g., development vs. production).

-        shouldSleepOutsideWorkingHours: true,
+        shouldSleepOutsideWorkingHours: environment.shouldSleepOutsideWorkingHours ?? true,
libs/message-queue/src/lib/nest/worker.service.ts (1)

124-124: Review necessity of 'Sleeping' status in shutdown logic.

If the worker's status remains Running during sleep, it's unnecessary to include Status.Sleeping in the shutdown condition. Adjusting the condition improves code clarity.

Apply this diff to refine the onModuleDestroy() method:

-    if (this.status === Status.Running || this.status === Status.Sleeping) {
+    if (this.status === Status.Running) {

This change ensures that the shutdown logic triggers appropriately based on the worker's actual operational status.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between aaebdbf and a0fe2ac.

📒 Files selected for processing (6)
  • apps/services/user-notification/src/app/modules/notifications/notifications.module.ts (1 hunks)
  • apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.ts (0 hunks)
  • libs/message-queue/src/lib/nest/types.ts (1 hunks)
  • libs/message-queue/src/lib/nest/utils.spec.ts (2 hunks)
  • libs/message-queue/src/lib/nest/utils.ts (2 hunks)
  • libs/message-queue/src/lib/nest/worker.service.ts (5 hunks)
💤 Files with no reviewable changes (1)
  • apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.ts
🧰 Additional context used
📓 Path-based instructions (5)
apps/services/user-notification/src/app/modules/notifications/notifications.module.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."
libs/message-queue/src/lib/nest/types.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/message-queue/src/lib/nest/utils.spec.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/message-queue/src/lib/nest/utils.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/message-queue/src/lib/nest/worker.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (4)
libs/message-queue/src/lib/nest/types.ts (1)

21-22: Verify the property usage across the codebase.

The type definition looks good and aligns with the PR objective of moving sleep logic to the worker service. Let's verify its implementation.

✅ Verification successful

Property shouldSleepOutsideWorkingHours is correctly implemented and used

The verification confirms proper implementation:

  • Used in WorkerService to control sleep behavior during non-working hours
  • Correctly configured in notifications.module.ts with shouldSleepOutsideWorkingHours: true
  • Implementation includes appropriate logging and status management
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of shouldSleepOutsideWorkingHours property
# Expected: Should find usage in QueueModule.register and WorkerService

# Test 1: Check QueueModule.register usage
echo "Checking QueueModule.register usage:"
rg -A 5 "QueueModule\.register" 

# Test 2: Check WorkerService implementation
echo "Checking WorkerService implementation:"
rg -A 5 "shouldSleepOutsideWorkingHours"

Length of output: 3749

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

Line range hint 1-73: LGTM! Module structure follows NestJS best practices.

The module maintains proper separation of concerns with clear dependency injection patterns. The queue configuration change aligns well with moving the sleep logic to the worker service.

libs/message-queue/src/lib/nest/worker.service.ts (2)

7-7: Imports are appropriate and clear.

The addition of clamp, isOutsideWorkingHours, and sleepUntilMorning from ./utils is correct and enhances the functionality of the worker service.


23-23: Integration of 'Sleeping' status into the worker lifecycle.

Adding Sleeping to the Status enum appropriately reflects the new state when the worker is paused during non-working hours.

libs/message-queue/src/lib/nest/utils.ts Show resolved Hide resolved
libs/message-queue/src/lib/nest/utils.ts Show resolved Hide resolved
libs/message-queue/src/lib/nest/utils.ts Show resolved Hide resolved
libs/message-queue/src/lib/nest/utils.spec.ts Outdated Show resolved Hide resolved
libs/message-queue/src/lib/nest/utils.spec.ts Outdated Show resolved Hide resolved
@magnearun magnearun marked this pull request as draft November 7, 2024 16:18
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@magnearun magnearun marked this pull request as ready for review November 8, 2024 14:07
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

🧹 Outside diff range and nitpick comments (1)
libs/message-queue/src/lib/nest/utils.spec.ts (1)

23-32: Add edge case tests for working hours boundaries.

While the basic scenarios are covered, consider adding test cases for edge cases:

  • Exactly at work start time (8:00 AM)
  • One minute before work start time (7:59 AM)
  • Exactly at work end time (4:00 PM)
  • One minute after work end time (4:01 PM)
describe('isOutsideWorkingHours', () => {
  // ... existing tests ...

  it('handles work start boundary correctly', () => {
    jest.useFakeTimers({ now: new Date(2021, 1, 1, 8, 0, 0) }) // 8:00 AM
    expect(isOutsideWorkingHours()).toBe(false)

    jest.useFakeTimers({ now: new Date(2021, 1, 1, 7, 59, 0) }) // 7:59 AM
    expect(isOutsideWorkingHours()).toBe(true)
  })

  it('handles work end boundary correctly', () => {
    jest.useFakeTimers({ now: new Date(2021, 1, 1, 16, 0, 0) }) // 4:00 PM
    expect(isOutsideWorkingHours()).toBe(false)

    jest.useFakeTimers({ now: new Date(2021, 1, 1, 16, 1, 0) }) // 4:01 PM
    expect(isOutsideWorkingHours()).toBe(true)
  })
})
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a0fe2ac and 7d083c5.

📒 Files selected for processing (3)
  • apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.spec.ts (1 hunks)
  • libs/message-queue/src/lib/nest/utils.spec.ts (2 hunks)
  • libs/message-queue/src/lib/nest/worker.service.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.spec.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."
libs/message-queue/src/lib/nest/utils.spec.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/message-queue/src/lib/nest/worker.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (6)
libs/message-queue/src/lib/nest/utils.spec.ts (1)

1-5: Add test coverage for sleepUntilMorning function.

The sleepUntilMorning function is not imported or tested, which could lead to undetected issues in the worker service's sleep logic.

libs/message-queue/src/lib/nest/worker.service.ts (3)

7-7: LGTM: Clean import of sleep-related utilities.

The new imports align well with the PR's objective of moving sleep logic to the worker service.


124-124: LGTM: Proper cleanup handling for sleeping state.

The onModuleDestroy method correctly handles the new Sleeping status, ensuring proper cleanup of active jobs before stopping.


64-72: LGTM: Well-structured sleep implementation with good logging.

The method effectively encapsulates the sleep logic with appropriate logging for both sleep and wake events. However, note that this implementation is affected by the status-related issue mentioned earlier.

Let's verify the sleep configuration usage:

✅ Verification successful

Sleep implementation is well-structured with proper configuration and utility functions

The implementation is well-designed with:

  • Configuration properly defined as an optional boolean in the worker config
  • Working hours utility functions properly implemented (8 AM - 11 PM)
  • Sleep logic encapsulated with appropriate status changes and logging
  • Used in the user-notification service with shouldSleepOutsideWorkingHours: true

The original review comment's approval was correct, and the implementation is verified to be working as intended.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for shouldSleepOutsideWorkingHours configuration
rg "shouldSleepOutsideWorkingHours.*=.*true" -A 2

Length of output: 51


Script:

#!/bin/bash
# Let's search for any usage of shouldSleepOutsideWorkingHours without assuming its value
rg "shouldSleepOutsideWorkingHours" -A 2

Length of output: 936


Script:

#!/bin/bash
# Let's also check the configuration interface/type definition
ast-grep --pattern 'interface $_Config {
  $$$
  shouldSleepOutsideWorkingHours$_
  $$$
}'

Length of output: 92


Script:

#!/bin/bash
# Check for isOutsideWorkingHours and sleepUntilMorning implementations
rg "function (isOutsideWorkingHours|sleepUntilMorning)" -A 5

Length of output: 62


Script:

#!/bin/bash
# Let's check for the utility functions in a different way
rg "isOutsideWorkingHours|sleepUntilMorning" -A 3

# Also check for any imports of these functions
rg "import.*{.*(?:isOutsideWorkingHours|sleepUntilMorning).*}"

Length of output: 3146


Script:

#!/bin/bash
# Let's look at the configuration type definition with a different pattern
rg "interface.*Config" -A 10

Length of output: 44360


Script:

#!/bin/bash
# Let's check the implementation of isOutsideWorkingHours and sleepUntilMorning in utils.ts
rg -p "export const (isOutsideWorkingHours|sleepUntilMorning)" -A 10 libs/message-queue/src/lib/nest/utils.ts

Length of output: 697


Script:

#!/bin/bash
# Let's also check the WorkerConfig interface definition
rg -p "interface.*Config.*{" -A 10 libs/message-queue/src/lib/nest/types.ts

Length of output: 181


Script:

#!/bin/bash
# Let's check the Config interface with a simpler pattern
rg "interface.*Config" -A 5 libs/message-queue/src/lib/nest/types.ts

# Also check for any constants related to working hours
rg "WORK_(STARTING|ENDING)_HOUR" libs/message-queue/src/lib/nest/utils.ts

Length of output: 456

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

239-239: LGTM! Good defensive programming practice.

The addition of optional chaining (?.) is a good defensive programming practice to handle cases where recipientMessage might be undefined, preventing potential runtime errors.


Line range hint 1-673: Comprehensive test coverage with robust test cases.

The test suite demonstrates excellent coverage of the NotificationsWorkerService functionality:

  • Proper setup and teardown of test environment
  • Comprehensive mocking of dependencies
  • Clear test cases covering various scenarios including:
    • Email and push notification delivery
    • Working hours validation
    • Feature flag handling
    • User profile validation
    • Delegation logic
    • Company vs individual user handling

This aligns well with NestJS testing best practices and provides good confidence in the service's behavior.

libs/message-queue/src/lib/nest/utils.spec.ts Show resolved Hide resolved
libs/message-queue/src/lib/nest/worker.service.ts Outdated Show resolved Hide resolved
Copy link
Member

@rafnarnason rafnarnason left a comment

Choose a reason for hiding this comment

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

lgtm

@magnearun magnearun added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Nov 12, 2024
@kodiakhq kodiakhq bot merged commit 85b4042 into main Nov 14, 2024
43 checks passed
@kodiakhq kodiakhq bot deleted the fix/queue-sleep-logic branch November 14, 2024 09:48
@coderabbitai coderabbitai bot mentioned this pull request Nov 22, 2024
jonnigs pushed a commit that referenced this pull request Nov 26, 2024
#16712)

* move sleep logic from messgeHandler to worker service

* chore: nx format:write update dirty files

* small refactor

* chore: nx format:write update dirty files

* Update libs/message-queue/src/lib/nest/utils.spec.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* fix message-queue tests

* chore: nx format:write update dirty files

* move sleep check

* change placement of sleep check back

* chore: nx format:write update dirty files

---------

Co-authored-by: andes-it <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
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.

4 participants