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

Inform Admin incase of server issue. #1524

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

jasneetsingh6114
Copy link

@jasneetsingh6114 jasneetsingh6114 commented Jan 7, 2025

Describe your changes

Created toast notifications that will alert the admin whenever there is a server issue and would inform admin too when there would be proper functioning of the server.

Issue number

1482: https://github.com/bluewave-labs/checkmate/issues/assigned/jasneetsingh6114

Please ensure all items are checked off before requesting a review:

  • [ Done] I deployed the application locally.
  • [ Done] I have performed a self-review and testing of my code.
  • [ Done] I have included the issue # in the PR.
  • [Done ] I have labelled the PR correctly.
  • [ Done] The issue I am working on is assigned to me.
  • [ I didn't hard-coded any values] I didn't use any hardcoded values (otherwise it will not scale, and will make it difficult to maintain consistency across the application).
  • [Done ] I made sure font sizes, color choices etc are all referenced from the theme.
  • [Done ] My PR is granular and targeted to one specific feature.
  • [Done] I took a screenshot and attached to this PR if there is a UI change.
    Screenshot 2025-01-06 203810
    Screenshot 2025-01-06 205058

Copy link

coderabbitai bot commented Jan 7, 2025

Walkthrough

The changes to the NetworkService.js file focus on improving error handling and user feedback mechanisms. The modifications introduce new properties to track user status, error states, and toast notification timing. A new handleError method has been implemented to process API error responses, with specific handling for authentication and server errors. The addition of a debounceToast method helps manage the frequency of toast notifications, preventing overwhelming user experiences.

Changes

File Change Summary
Client/src/Utils/NetworkService.js - Added new properties: lastToastTimestamp, errorOccurred, user, isAdmin
- Implemented handleError(error) method for comprehensive error processing
- Created debounceToast() method to control notification frequency
- Enhanced Axios response interceptor with improved error handling

Sequence Diagram

sequenceDiagram
    participant Client
    participant NetworkService
    participant API
    participant Store
    participant ToastNotification

    Client->>NetworkService: Make API Request
    NetworkService->>API: Send Request
    alt API Response
        API-->>NetworkService: Successful Response
        alt Previous Error Existed
            NetworkService->>ToastNotification: Show Success Toast
            NetworkService->>Store: Reset Error State
        end
    else API Error
        API-->>NetworkService: Error Response
        NetworkService->>NetworkService: handleError()
        alt Authentication Error
            NetworkService->>Store: Clear Auth State
            NetworkService->>Client: Redirect to Login
        else Server Error
            NetworkService->>ToastNotification: Show Error Toast
        end
    end
Loading

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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

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

Copy link

@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 (2)
Client/src/Utils/NetworkService.js (2)

14-17: Don't let 'this.user' and 'this.isAdmin' miss their chance to update

Just like seizing the moment, ensure this.user and this.isAdmin are updated within the store subscription to keep the user's status current. This will prevent any stale user information from lingering in your service.


50-62: Don't let unknown errors make your knees weak

If error.response is undefined, possibly due to network issues or unexpected errors, consider handling these cases. Adding an else clause to manage such scenarios will make your error handling more robust.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 624ea50 and 4398010.

📒 Files selected for processing (1)
  • Client/src/Utils/NetworkService.js (3 hunks)
🔇 Additional comments (2)
Client/src/Utils/NetworkService.js (2)

32-37: When the server recovers, you capture the opportunity

Great job notifying admins when the server is back up and running smoothly after issues. This ensures they're promptly informed when things return to normal.


64-70: Keeping the toast notifications in rhythm

Your debounce implementation prevents overwhelming the admin with too many notifications. It's a smooth way to manage toast frequency and keep the interface clean.

Copy link

@llamapreview llamapreview bot left a comment

Choose a reason for hiding this comment

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

Auto Pull Request Review from LlamaPReview

1. Overview

1.1 PR Summary

  • Business value and requirements alignment: The PR introduces toast notifications to alert the admin about server issues and proper functioning, improving server monitoring and response time.
  • Key components modified: Client/src/Utils/NetworkService.js
  • Impact assessment: The PR impacts the user interface (UI) and the network service layer, which handles API requests and responses. It introduces a debounce mechanism to prevent excessive toast notifications and handles errors differently based on the admin's role.
  • System dependencies and integration impacts: The PR interacts with react-toastify, axios, authSlice, and uptimeMonitorsSlice. It also depends on the admin's role and permissions for displaying notifications.

1.2 Architecture Changes

  • System design modifications: None
  • Component interactions: The PR introduces new interactions between the network service layer and the toast notification component. It also modifies the error handling logic in the network service layer.
  • Integration points: The PR integrates with the existing UI, network service layer, and authentication/authorization mechanisms.

2. Detailed Technical Analysis

2.1 Code Logic Deep-Dive

Core Logic Changes

  • Client/src/Utils/NetworkService.js - handleError function

    • Submitted PR Code:
      handleError(error) {
        if (error.response) {
          const status = error.response.status;
          if (status === 401) {
            this.dispatch(clearAuthState());
            this.dispatch(clearUptimeMonitorState());
            this.navigate("/login");
          } else if (this.isAdmin && status >= 500) {
            this.debounceToast("Checkmate server is not running or has issues. Please check.", "error");
            this.errorOccurred = true;
          }
        }
      }
    • Analysis:
      • The current logic handles 401 errors and 500 errors for admin users. However, it does not handle other error status codes or network errors. It also does not consider the case where the admin is not logged in or does not have the required permissions.
      • Edge cases and error handling: The current implementation does not handle other error status codes or network errors. It also does not consider the case where the admin is not logged in or does not have the required permissions.
      • Cross-component impact: Changes in error handling might affect other components that rely on the network service layer for error handling.
      • Business logic considerations: The current logic assumes that a 500 status indicates a server issue. However, it might not cover all server issues or might be triggered by client-side errors.
    • LlamaPReview Suggested Improvements:
      handleError(error) {
        if (error.response) {
          const status = error.response.status;
          if (status === 401) {
            this.dispatch(clearAuthState());
            this.dispatch(clearUptimeMonitorState());
            this.navigate("/login");
          } else if (this.isAdmin && (status >= 500 || status === 0)) { // Include status code 0 for network errors
            this.debounceToast("Checkmate server is not running or has issues. Please check.", "error");
            this.errorOccurred = true;
          }
        } else if (error.request) { // Handle network errors
          this.debounceToast("Checkmate server is not responding. Please check your network connection.", "error");
        } else {
          console.error("An error occurred:", error.message);
        }
      }
    • Improvement rationale:
      • Technical benefits: The improved logic handles network errors and other error status codes, providing more comprehensive error handling.
      • Business value: More comprehensive error handling ensures that the admin is notified of a wider range of server issues, enabling quicker resolution.
      • Risk assessment: The improved logic reduces the risk of missed server issues and improves the overall system's reliability.
  • Client/src/Utils/NetworkService.js - debounceToast function

    • Submitted PR Code:
      debounceToast(message, type, debounceDuration = 5000) {
        const now = Date.now();
        if (now - this.lastToastTimestamp > debounceDuration) {
          this.lastToastTimestamp = now;
          type === "success" ? toast.success(message) : toast.error(message);
        }
      }
    • Analysis:
      • The current debounce logic prevents excessive toast notifications by only displaying a new notification if a certain duration has passed since the last notification. However, it does not consider the case where the admin closes the notification before the debounce duration has passed.
      • Edge cases and error handling: The current implementation does not handle the case where the admin closes the notification before the debounce duration has passed, potentially leading to excessive notifications.
      • Cross-component impact: Changes in the debounce logic might affect other components that rely on toast notifications for displaying messages.
      • Business logic considerations: The current logic assumes that the debounce duration is sufficient for the admin to read and act upon the notification. However, it might not be optimal for all use cases.
    • LlamaPReview Suggested Improvements:
      debounceToast(message, type, debounceDuration = 5000) {
        const now = Date.now();
        if (now - this.lastToastTimestamp > debounceDuration) {
          this.lastToastTimestamp = now;
          const toastId = toast[type](message, {
            autoClose: debounceDuration,
            onClose: () => {
              this.lastToastTimestamp = 0; // Reset the timestamp when the toast is closed
            },
          });
        }
      }
    • Improvement rationale:
      • Technical benefits: The improved logic resets the debounce timestamp when the admin closes the notification, preventing excessive notifications even if the admin closes the notification before the debounce duration has passed.
      • Business value: More robust debounce logic ensures that the admin is not overwhelmed with excessive notifications, improving the overall user experience.
      • Risk assessment: The improved logic reduces the risk of notification spam and improves the overall system's usability.

2.2 Implementation Quality

  • Code organization and structure: The PR maintains a clear and organized structure, with the new functions (handleError and debounceToast) added to the NetworkService class.
  • Design patterns usage: The PR uses the observer pattern for subscribing to store changes and the debounce pattern for preventing excessive toast notifications.
  • Error handling approach: The PR introduces more comprehensive error handling, covering a wider range of error status codes and network errors.
  • Resource management: The PR does not introduce any new resources that need to be managed.

3. Critical Findings

3.1 Potential Issues

  • 🔴 Critical Issues

    • Issue description: The current handleError function does not handle other error status codes or network errors, potentially leading to missed server issues or unexpected behavior.
    • Impact: Missed server issues might lead to delayed resolution and increased downtime. Unexpected behavior might cause confusion or frustration for the admin user.
    • Recommendation: Implement the suggested improvements to handle other error status codes and network errors, as outlined in the "Code Logic Deep-Dive" section.
  • 🟡 Warnings

    • Warning description: The current debounce logic does not reset the debounce timestamp when the admin closes the notification, potentially leading to excessive notifications if the admin closes the notification before the debounce duration has passed.
    • Potential risks: Excessive notifications might overwhelm the admin, leading to notification fatigue or missed critical alerts.
    • Suggested improvements: Implement the suggested improvements to reset the debounce timestamp when the admin closes the notification, as outlined in the "Code Logic Deep-Dive" section.

3.2 Code Quality Concerns

  • Maintainability aspects: The PR maintains good maintainability, with clear and concise code that is easy to understand and modify.
  • Readability issues: The PR does not introduce any readability issues, with clear variable and function names and consistent formatting.
  • Performance bottlenecks: The PR does not introduce any performance bottlenecks, with efficient debounce logic and minimal overhead.

4. Security Assessment

  • Authentication/Authorization impacts: The PR introduces new error handling logic that checks the admin's role before displaying error notifications. This change ensures that only authorized users receive sensitive server issue notifications.
  • Data handling concerns: The PR does not introduce any new data handling concerns, with the existing data handling mechanisms remaining unchanged.
  • Input validation: The PR does not introduce any new input validation concerns, with the existing input validation mechanisms remaining unchanged.
  • Security best practices: The PR adheres to security best practices, with proper authentication and authorization checks and secure data handling mechanisms.
  • Potential security risks: The PR does not introduce any new potential security risks, with the existing security mechanisms remaining unchanged.
  • Mitigation strategies: The PR introduces new error handling logic that checks the admin's role before displaying error notifications, mitigating the risk of unauthorized access to sensitive server issue notifications.
  • Security testing requirements: Conduct security testing to ensure that the new error handling logic is secure and cannot be bypassed by unauthorized users.

5. Testing Strategy

5.1 Test Coverage

  • Unit test analysis: Write unit tests to cover the new handleError and debounceToast functions, ensuring they behave as expected under various scenarios.
  • Integration test requirements: Conduct integration testing to ensure the new notifications work correctly with the existing UI and network service layer. Test the new error handling logic to ensure it covers all relevant edge cases and behaves as expected.

5.2 Test Recommendations

Suggested Test Cases

// Test handleError function
test('handleError should handle 401 errors correctly', () => {
  // Arrange
  const networkService = new NetworkService(store, dispatch, navigate);
  const error = { response: { status: 401 } };

  // Act
  networkService.handleError(error);

  // Assert
  expect(dispatch).toHaveBeenCalledWith(clearAuthState());
  expect(dispatch).toHaveBeenCalledWith(clearUptimeMonitorState());
  expect(navigate).toHaveBeenCalledWith("/login");
});

test('handleError should handle 500 errors for admin users correctly', () => {
  // Arrange
  const networkService = new NetworkService({ getState: () => ({ auth: { user: { role: ['admin'] } } }) }, dispatch, navigate);
  const error = { response: { status: 500 } };

  // Act
  networkService.handleError(error);

  // Assert
  expect(networkService.debounceToast).toHaveBeenCalledWith("Checkmate server is not running or has issues. Please check.", "error");
  expect(networkService.errorOccurred).toBe(true);
});

// Test debounceToast function
test('debounceToast should prevent excessive notifications', () => {
  // Arrange
  const networkService = new NetworkService(store, dispatch, navigate);
  const debounceDuration = 5000;
  const now = Date.now();
  networkService.lastToastTimestamp = now - debounceDuration - 1; // Set lastToastTimestamp to just before the debounce duration

  // Act
  networkService.debounceToast("Test message", "success");

  // Assert
  expect(networkService.lastToastTimestamp).toBe(now); // lastToastTimestamp should be updated to the current timestamp
  expect(toast.success).toHaveBeenCalledWith("Test message", { autoClose: debounceDuration, onClose: expect.any(Function) });
});
  • Coverage improvements: Ensure that the new functions are covered by unit tests and that the new error handling logic is covered by integration tests.
  • Performance testing needs: Conduct performance testing to ensure that the new debounce logic and error handling logic can handle high traffic and edge cases without introducing performance bottlenecks.

6. Documentation & Maintenance

  • Documentation updates needed: Update the documentation to reflect the new error handling logic and debounce mechanism.
  • Long-term maintenance considerations: Ensure that the new error handling logic and debounce mechanism are properly documented and tested, making it easier for future maintainers to understand and modify the code.
  • Technical debt and monitoring requirements: Monitor the new error handling logic and debounce mechanism to ensure they continue to behave as expected and do not introduce new technical debt.

7. Deployment & Operations

  • Deployment impact and strategy: The PR does not introduce any new deployment considerations, with the existing deployment strategy remaining unchanged.
  • Key operational considerations: The PR introduces new error handling logic and a debounce mechanism, which should be monitored to ensure they continue to behave as expected and do not introduce new operational issues.

8. Summary & Recommendations

8.1 Key Action Items

  1. Implement suggested improvements for the handleError function to handle other error status codes and network errors, as outlined in the "Code Logic Deep-Dive" section.
  2. Implement suggested improvements for the debounceToast function to reset the debounce timestamp when the admin closes the notification, as outlined in the "Code Logic Deep-Dive" section.
  3. Write unit tests to cover the new handleError and debounceToast functions, ensuring they behave as expected under various scenarios.
  4. Conduct integration testing to ensure the new notifications work correctly with the existing UI and network service layer. Test the new error handling logic to ensure it covers all relevant edge cases and behaves as expected.
  5. Update the documentation to reflect the new error handling logic and debounce mechanism.
  6. Monitor the new error handling logic and debounce mechanism to ensure they continue to behave as expected and do not introduce new technical debt or operational issues.

8.2 Future Considerations

  • Technical evolution path: As the system evolves, consider introducing more granular error handling and notification mechanisms to provide more detailed information to the admin user.
  • Business capability evolution: As the business capabilities evolve, consider introducing new notification channels or notification preferences to provide more flexible and personalized notification experiences.
  • System integration impacts: As the system integrates with new components or services, consider introducing new error handling logic or notification mechanisms to ensure seamless integration and proper notification.

💡 Help Shape LlamaPReview
How's this review format working for you? Vote in our Github Discussion Polls to help us improve your review experience!

@gorkem-bwl
Copy link
Contributor

Out of curiosity are those the toast messages same as the ones in components folder?

@jasneetsingh6114
Copy link
Author

I see the configuration of toast in file(https://github.com/bluewave-labs/checkmate/blob/develop/Client/src/Utils/toastUtils.jsx) which is commonly used under components. Presently, I haven't used exactly those same toast but if you want me I can update the code with using those particular toast.

@gorkem-bwl
Copy link
Contributor

I see the configuration of toast in file(https://github.com/bluewave-labs/checkmate/blob/develop/Client/src/Utils/toastUtils.jsx) which is commonly used under components. Presently, I haven't used exactly those same toast but if you want me I can update the code with using those particular toast.

Yes. If there is a same functionality under components, there is no need to reinvent the wheel.

@ajhollid
Copy link
Collaborator

ajhollid commented Jan 7, 2025

Thanks for the submission @jasneetsingh6114, I'll have a look at it as soon as I can!

@ajhollid
Copy link
Collaborator

ajhollid commented Jan 7, 2025

@jasneetsingh6114 I had a brief look and I think you can safely remove all the admin checks and just display the toast for all users.

All users should be aware the server isn't responding

Copy link
Collaborator

@ajhollid ajhollid left a comment

Choose a reason for hiding this comment

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

@jasneetsingh6114 as mentioned earlier the admin check is not necessary for this functionality, it can be removed.

The logic for checking if the server is responding or not is not quite correct either.

All that needs to be done in this PR is the following:

if (error.response) {
   // current response error implementation
} else if (error.request) {
    // Show a toast informing the user the server didn't respond
}

That's all that is needed here, this should be like a 5 line PR.

Simple is often best :smile: 

this.lastToastTimestamp = 0;
this.errorOccurred = false;
this.user = this.store.getState().auth?.user;
this.isAdmin = (this.user?.role?.includes("admin") ?? false) || (this.user?.role?.includes("superadmin") ?? false);
Copy link
Collaborator

Choose a reason for hiding this comment

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

No need to do admin checks, the network error toast shoudl be shown to all users

class NetworkService {
constructor(store, dispatch, navigate) {
this.store = store;
this.dispatch = dispatch;
this.navigate = navigate;
let baseURL = BASE_URL;
this.lastToastTimestamp = 0;
this.errorOccurred = false;
Copy link
Collaborator

Choose a reason for hiding this comment

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

We don't need to worry about informing the user if the server goes back up, if it's up they will know

if (now - this.lastToastTimestamp > debounceDuration) {
this.lastToastTimestamp = now;
type === "success" ? toast.success(message) : toast.error(message);
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why do you need to debounce the toast? This doesn't seem necessary?

(response) => {
if (this.isAdmin && this.errorOccurred && response.status >= 200 && response.status < 300) {
this.debounceToast("Checkmate server is running properly.", "success");
this.errorOccurred = false;// Reset error flag if a successful response is received after errors
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

I appreciate the idea here, but I believe it is unnecessary complexity. If the server responds then the user is arleady aware it is functioning properly. This can be removed

this.navigate("/login");
} else if (this.isAdmin && status >= 500) {
this.debounceToast("Checkmate server is not running or has issues. Please check.", "error");
this.errorOccurred = true;
Copy link
Collaborator

Choose a reason for hiding this comment

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

This won't work if the server doesn't respond at all, which is the issue at hand.

If there is no response, erorr.response will be undefined and the user will not be notfied.

We should be checking for error.request, which is the property that will be defined in the event of a request error.

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.

3 participants