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

chore(j-s): add slack lock for daily court hearing arrangements #17468

Open
wants to merge 10 commits into
base: main
Choose a base branch
from

Conversation

thorhildurt
Copy link
Member

@thorhildurt thorhildurt commented Jan 10, 2025

Betri yfirsýn fyrir fyrirtökur dagsins

What

  • Create a summary log to post in Slack for the daily court hearing arrangements

Why

  • Helps the team to plan manual deployments

Screenshots / Gifs

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

    • Added functionality to retrieve and post court hearing arrangements for a specific date.
    • Introduced new methods for handling daily hearing arrangement summaries and archiving cases.
  • Improvements

    • Enhanced case management and event tracking capabilities.
    • Improved scheduler service with more modular and robust error handling.
  • Maintenance

    • Removed unused import in limited access case controller.
    • Refactored application service methods for better code organization.

Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

Walkthrough

This pull request introduces new functionality for handling court hearing arrangements in the judicial system backend. A new method postHearingArrangements is added to the InternalCaseController, which retrieves cases with court hearing arrangements for a specific date. The InternalCaseService includes a corresponding method getCaseHearingArrangements to fetch these cases. An additional method in the EventService allows posting daily hearing arrangement events, and the scheduler's AppService is updated to incorporate this new feature into its run cycle.

Changes

File Change Summary
apps/judicial-system/backend/src/app/modules/case/internalCase.controller.ts Added postHearingArrangements method to handle POST requests for court hearing arrangements.
apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts Added getCaseHearingArrangements method to retrieve cases with hearing arrangements for a specific date.
apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts Removed unused DefendantEventType import.
apps/judicial-system/backend/src/app/modules/event/event.service.ts Added postDailyHearingArrangementEvents method to send events for daily hearing arrangements.
apps/judicial-system/scheduler/src/app/app.service.ts Added new private methods for handling case-related tasks and updated run method.
apps/judicial-system/scheduler/src/app/test/run.spec.ts Updated test cases to reflect changes in the expected behavior of fetch calls.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • unakb
  • oddsson

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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

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.

@thorhildurt thorhildurt changed the title J s/add slack log for hearing arrangements chore(j-s): add slack lock for daily court hearing arrangements Jan 10, 2025
async run() {
this.logger.info('Scheduler starting')

await this.addMessagesForIndictmentsWaitingForConfirmationToQueue()
Copy link
Member Author

Choose a reason for hiding this comment

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

Refactor: splitting previous scheduler tasks into functions

…github.com/island-is/island.is into j-s/add-slack-log-for-hearing-arrangements

# Conflicts:
#	apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts
@thorhildurt thorhildurt self-assigned this Jan 10, 2025
@thorhildurt thorhildurt marked this pull request as ready for review January 10, 2025 10:04
@thorhildurt thorhildurt requested a review from a team as a code owner January 10, 2025 10:04
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

🧹 Nitpick comments (2)
apps/judicial-system/scheduler/src/app/app.service.ts (1)

105-113: Consider parallel execution for independent tasks

The tasks appear to be independent and could be executed in parallel using Promise.all() for better performance.

Apply this diff:

   async run() {
     this.logger.info('Scheduler starting')
 
-    await this.addMessagesForIndictmentsWaitingForConfirmationToQueue()
-    await this.archiveCases()
-    await this.postDailyHearingArrangementSummary()
+    await Promise.all([
+      this.addMessagesForIndictmentsWaitingForConfirmationToQueue(),
+      this.archiveCases(),
+      this.postDailyHearingArrangementSummary(),
+    ])
 
     this.logger.info('Scheduler done')
   }
apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1)

523-544: Add input validation and consider performance optimization

The method needs input validation and could benefit from performance optimization.

  1. Add input validation:
   async getCaseHearingArrangements(date: Date): Promise<Case[]> {
+    if (!(date instanceof Date) || isNaN(date.getTime())) {
+      throw new BadRequestException('Invalid date provided')
+    }
  1. Consider adding an index on the date_type and date columns for better query performance:
CREATE INDEX idx_date_logs_type_date ON date_logs (date_type, date);
  1. Consider adding a limit to prevent excessive memory usage:
   return this.caseModel.findAll({
     include: [...],
     order: [...],
+    limit: 1000, // Adjust based on requirements
   })
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1364f19 and b4afe11.

📒 Files selected for processing (5)
  • apps/judicial-system/backend/src/app/modules/case/internalCase.controller.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts (0 hunks)
  • apps/judicial-system/backend/src/app/modules/event/event.service.ts (1 hunks)
  • apps/judicial-system/scheduler/src/app/app.service.ts (4 hunks)
💤 Files with no reviewable changes (1)
  • apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts
🧰 Additional context used
📓 Path-based instructions (4)
apps/judicial-system/backend/src/app/modules/event/event.service.ts (1)

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/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1)

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/judicial-system/backend/src/app/modules/case/internalCase.controller.ts (1)

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/judicial-system/scheduler/src/app/app.service.ts (1)

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."
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: prepare
🔇 Additional comments (3)
apps/judicial-system/scheduler/src/app/app.service.ts (2)

Line range hint 27-41: Well-structured message queue handling!

Good job extracting this functionality into a separate method with proper error handling and logging.


Line range hint 43-79: Well-implemented archiving logic!

Good implementation of retry mechanism with proper time limit and error handling.

apps/judicial-system/backend/src/app/modules/event/event.service.ts (1)

176-219: Add JSDoc documentation for better maintainability

The method would benefit from JSDoc documentation explaining its purpose, parameters, and return type.

Add documentation:

+  /**
+   * Posts a summary of daily hearing arrangements to Slack
+   * @param date The date for which to post hearing arrangements
+   * @param cases Array of cases with hearing arrangements
+   * @returns Promise<void>
+   */
   async postDailyHearingArrangementEvents(date: Date, cases: Case[]) {

Also, consider adding unit tests to verify the formatting logic and error handling.

✅ Verification successful

Add JSDoc documentation and unit tests for better maintainability

The original suggestion for adding JSDoc documentation is valid. Additionally, the verification confirms that there are no direct unit tests for the EventService, despite its important role in posting hearing arrangements. The service is only referenced in test setup modules.

  • Add the suggested JSDoc documentation
  • Create a dedicated test file (event.service.spec.ts) to cover:
    • Message formatting logic
    • Error handling
    • Empty case list handling
    • Date formatting
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for existing test coverage
fd -e spec.ts -e test.ts | grep -l "event.service"

Length of output: 50


Script:

#!/bin/bash
# Try multiple search strategies to find test files
echo "=== Searching for EventService tests ==="
rg -l "EventService" --type ts

echo -e "\n=== Searching for event.service tests ==="
rg -l "event.service" --type ts

echo -e "\n=== Looking for spec files in event module ==="
fd -e ts . src/app/modules/event

Length of output: 3898

Copy link

codecov bot commented Jan 10, 2025

Codecov Report

Attention: Patch coverage is 39.02439% with 25 lines in your changes missing coverage. Please review.

Project coverage is 35.68%. Comparing base (7e3a370) to head (27e2ecf).
Report is 20 commits behind head on main.

Files with missing lines Patch % Lines
...tem/backend/src/app/modules/event/event.service.ts 0.00% 16 Missing ⚠️
...ckend/src/app/modules/case/internalCase.service.ts 0.00% 4 Missing ⚠️
...nd/src/app/modules/case/internalCase.controller.ts 25.00% 3 Missing ⚠️
...s/judicial-system/scheduler/src/app/app.service.ts 88.23% 2 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #17468      +/-   ##
==========================================
+ Coverage   35.66%   35.68%   +0.01%     
==========================================
  Files        6941     6942       +1     
  Lines      149131   149257     +126     
  Branches    42640    42685      +45     
==========================================
+ Hits        53193    53260      +67     
- Misses      95938    95997      +59     
Flag Coverage Δ
judicial-system-backend 55.81% <4.16%> (-0.07%) ⬇️
judicial-system-scheduler 71.33% <88.23%> (+0.13%) ⬆️

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

Files with missing lines Coverage Δ
...c/app/modules/case/limitedAccessCase.controller.ts 97.50% <ø> (ø)
...s/judicial-system/scheduler/src/app/app.service.ts 95.55% <88.23%> (-4.45%) ⬇️
...nd/src/app/modules/case/internalCase.controller.ts 95.32% <25.00%> (-1.69%) ⬇️
...ckend/src/app/modules/case/internalCase.service.ts 83.29% <0.00%> (-0.80%) ⬇️
...tem/backend/src/app/modules/event/event.service.ts 24.71% <0.00%> (-5.42%) ⬇️

... and 14 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 7e3a370...27e2ecf. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Jan 10, 2025

Datadog Report

All test runs 10f66c9 🔗

2 Total Test Services: 0 Failed, 2 Passed
🔻 Test Sessions change in coverage: 1 decreased (-0.05%), 1 increased (+0.01%)

Test Services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
judicial-system-backend 0 0 0 21053 0 18m 30.87s 1 decreased (-0.05%) Link
judicial-system-scheduler 0 0 0 4 0 4.13s 1 increased (+0.01%) Link

🔻 Code Coverage Decreases vs Default Branch (1)

  • judicial-system-backend - jest 59.48% (-0.05%) - Details

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

🔭 Outside diff range comments (1)
apps/judicial-system/scheduler/src/app/test/run.spec.ts (1)

Line range hint 79-91: Improve test clarity for the new fetch call.

The test now expects 4 fetch calls instead of 3, presumably due to the new hearing arrangements functionality. However, the test description and mock responses don't clearly indicate the purpose of this additional call.

Consider:

  1. Adding a descriptive comment explaining what each fetch call is for
  2. Including mock responses for hearing arrangement data
  3. Adding assertions to verify the hearing arrangement API call
     beforeEach(async () => {
       mockFetch
+        // Mock response for hearing arrangements
+        .mockResolvedValueOnce({
+          ok: true,
+          json: () => Promise.resolve({ hearingArrangements: [] }),
+        })
+        // Mock responses for case archiving
         .mockResolvedValue({
           ok: true,
           json: () => Promise.resolve({ caseArchived: false }),
         })
         .mockResolvedValueOnce({
           ok: true,
           json: () => Promise.resolve({ caseArchived: true }),
         })
         .mockResolvedValueOnce({
           ok: true,
           json: () => Promise.resolve({ caseArchived: true }),
         })

       await givenWhenThen()
     })

-    it('should continue until done', () => {
+    it('should fetch hearing arrangements and continue archiving until done', () => {
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b4afe11 and 239f60e.

📒 Files selected for processing (1)
  • apps/judicial-system/scheduler/src/app/test/run.spec.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/scheduler/src/app/test/run.spec.ts (1)

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 (1)
apps/judicial-system/scheduler/src/app/test/run.spec.ts (1)

31-31: LGTM!

The added empty line improves code readability.

apps/judicial-system/scheduler/src/app/test/run.spec.ts Outdated Show resolved Hide resolved
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 (4)
apps/judicial-system/scheduler/src/app/app.service.ts (4)

Line range hint 27-41: Consider adding retry logic for better resilience

While the error handling logs failures, adding retry logic would improve reliability for transient failures.

Consider implementing exponential backoff:

   private addMessagesForIndictmentsWaitingForConfirmationToQueue() {
+    const maxRetries = 3;
+    const retry = async (attempt = 0): Promise<void> => {
+      try {
         return this.messageService
           .sendMessagesToQueue([
             {
               type: MessageType.NOTIFICATION_DISPATCH,
               body: {
                 type: NotificationDispatchType.INDICTMENTS_WAITING_FOR_CONFIRMATION,
               },
             },
           ])
-          .catch((reason) =>
-            // Tolerate failure, but log
-            this.logger.error('Failed to dispatch notifications', { reason }),
-          )
+      } catch (error) {
+        if (attempt < maxRetries) {
+          const delay = Math.pow(2, attempt) * 1000;
+          this.logger.warn(`Retry attempt ${attempt + 1} after ${delay}ms`, { error });
+          await new Promise(resolve => setTimeout(resolve, delay));
+          return retry(attempt + 1);
+        }
+        this.logger.error('Failed to dispatch notifications after retries', { error });
+      }
+    };
+    return retry();
   }

Line range hint 43-79: Well-implemented retry mechanism and error handling

The implementation shows good practices with:

  • Time-bounded retries
  • Proper error handling
  • Secure authorization header usage

Consider extracting the content-type header to a constant:

+const JSON_CONTENT_TYPE = 'application/json';
+
   private async archiveCases() {
     // ...
           headers: {
-            'Content-Type': 'application/json',
+            'Content-Type': JSON_CONTENT_TYPE,
             authorization: `Bearer ${this.config.backendAccessToken}`,
           },

81-103: Improve error handling and URL construction

While the timezone-insensitive date handling is intentional (as per previous discussion), there are some improvements possible:

   private async postDailyHearingArrangementSummary() {
     const today = now()
+    const url = new URL(`api/internal/cases/postHearingArrangements/${today}`, this.config.backendUrl);
     try {
       const res = await fetch(
-        `${this.config.backendUrl}/api/internal/cases/postHearingArrangements/${today}`,
+        url.toString(),
         {
           method: 'POST',
           headers: {
             'Content-Type': 'application/json',
             authorization: `Bearer ${this.config.backendAccessToken}`,
           },
         },
       )

       if (!res.ok) {
+        const errorBody = await res.text();
         throw new BadGatewayException(
-          'Unexpected error occurred while fetching cases',
+          `Unexpected error occurred while fetching cases: ${errorBody}`,
         )
       }
     } catch (error) {
+      if (error instanceof BadGatewayException) {
+        throw error;
+      }
       throw new BadGatewayException(`Failed to fetch cases: ${error.message}`)
     }
   }

105-111: Consider parallel execution for independent operations

The sequential execution is clear, but independent operations could be executed in parallel for better performance.

   async run() {
     this.logger.info('Scheduler starting')

-    await this.addMessagesForIndictmentsWaitingForConfirmationToQueue()
-    await this.archiveCases()
-    await this.postDailyHearingArrangementSummary()
+    await Promise.all([
+      this.addMessagesForIndictmentsWaitingForConfirmationToQueue(),
+      this.archiveCases(),
+      this.postDailyHearingArrangementSummary(),
+    ])

     this.logger.info('Scheduler done')
   }

Note: Only implement this if these operations are truly independent and can be executed concurrently without side effects.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 239f60e and d792494.

📒 Files selected for processing (2)
  • apps/judicial-system/scheduler/src/app/app.service.ts (4 hunks)
  • apps/judicial-system/scheduler/src/app/test/run.spec.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/judicial-system/scheduler/src/app/test/run.spec.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/scheduler/src/app/app.service.ts (1)

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."
📓 Learnings (1)
apps/judicial-system/scheduler/src/app/app.service.ts (1)
Learnt from: thorhildurt
PR: island-is/island.is#17468
File: apps/judicial-system/scheduler/src/app/app.service.ts:81-103
Timestamp: 2025-01-10T11:23:01.559Z
Learning: In the judicial system backend, court hearing arrangements and their date handling (including in `postDailyHearingArrangementSummary`) are designed to be timezone-insensitive, using native Date objects without specific timezone handling.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: prepare
🔇 Additional comments (1)
apps/judicial-system/scheduler/src/app/app.service.ts (1)

3-3: LGTM: Import follows NestJS best practices

The BadGatewayException import is appropriately added and used for error handling.

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 (3)
apps/judicial-system/scheduler/src/app/app.service.ts (3)

Line range hint 27-41: Consider adding retry logic for resilience

While the error handling is appropriate for a scheduler task, consider implementing retry logic to improve reliability, similar to the archiveCases method.

 private addMessagesForIndictmentsWaitingForConfirmationToQueue() {
+    const startTime = now()
+    const retry = async () => {
     return this.messageService
       .sendMessagesToQueue([
         {
           type: MessageType.NOTIFICATION_DISPATCH,
           body: {
             type: NotificationDispatchType.INDICTMENTS_WAITING_FOR_CONFIRMATION,
           },
         },
       ])
       .catch((reason) => {
-        // Tolerate failure, but log
-        this.logger.error('Failed to dispatch notifications', { reason }),
+        this.logger.error('Failed to dispatch notifications', { reason })
+        if (minutesBetween(startTime, now()) < this.config.timeToLiveMinutes) {
+          return retry()
+        }
       })
+    }
+    return retry()
   }

81-103: Consider enhancing error handling and retry logic

While the error handling is good, consider these improvements:

  1. Add retry logic similar to archiveCases for consistency
  2. Include more specific error details in the BadGatewayException message
   private async postDailyHearingArrangementSummary() {
     const today = now()
+    const startTime = now()
+    
+    const attemptPost = async () => {
     try {
       const res = await fetch(
         `${this.config.backendUrl}/api/internal/cases/postHearingArrangements/${today}`,
         {
           method: 'POST',
           headers: {
             'Content-Type': 'application/json',
             authorization: `Bearer ${this.config.backendAccessToken}`,
           },
         },
       )

       if (!res.ok) {
+        const errorBody = await res.text()
         throw new BadGatewayException(
-          'Unexpected error occurred while fetching cases',
+          `Unexpected error occurred while fetching cases: ${res.status} - ${errorBody}`,
         )
       }
     } catch (error) {
-      throw new BadGatewayException(`Failed to fetch cases: ${error.message}`)
+      if (minutesBetween(startTime, now()) < this.config.timeToLiveMinutes) {
+        return attemptPost()
+      }
+      throw new BadGatewayException(
+        `Failed to fetch cases after retries: ${error.message}`
+      )
     }
+    }
+    return attemptPost()
   }

105-112: Consider parallel execution for independent tasks

The run method executes tasks sequentially, which is safe but might not be optimal. Consider running independent tasks in parallel using Promise.all() if they don't have dependencies.

   async run() {
     this.logger.info('Scheduler starting')
 
-    await this.addMessagesForIndictmentsWaitingForConfirmationToQueue()
-    await this.archiveCases()
-    await this.postDailyHearingArrangementSummary()
+    await Promise.all([
+      this.addMessagesForIndictmentsWaitingForConfirmationToQueue(),
+      this.archiveCases(),
+      this.postDailyHearingArrangementSummary(),
+    ])
 
     this.logger.info('Scheduler done')
   }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d792494 and 27e2ecf.

📒 Files selected for processing (2)
  • apps/judicial-system/scheduler/src/app/app.service.ts (4 hunks)
  • apps/judicial-system/scheduler/src/app/test/run.spec.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/judicial-system/scheduler/src/app/test/run.spec.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/scheduler/src/app/app.service.ts (1)

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."
📓 Learnings (1)
apps/judicial-system/scheduler/src/app/app.service.ts (1)
Learnt from: thorhildurt
PR: island-is/island.is#17468
File: apps/judicial-system/scheduler/src/app/app.service.ts:81-103
Timestamp: 2025-01-10T11:23:01.559Z
Learning: In the judicial system backend, court hearing arrangements and their date handling (including in `postDailyHearingArrangementSummary`) are designed to be timezone-insensitive, using native Date objects without specific timezone handling.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: prepare
🔇 Additional comments (2)
apps/judicial-system/scheduler/src/app/app.service.ts (2)

3-3: LGTM: Import addition is well-placed

The BadGatewayException import is appropriately grouped with other NestJS imports and is used correctly in the error handling.


Line range hint 43-79: LGTM: Well-implemented retry mechanism

The archiveCases method implements a robust retry mechanism with proper time limiting and error handling.

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.

2 participants