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

adding a helper function to update offline Sites #4082

Merged
merged 1 commit into from
Dec 14, 2024

Conversation

Baalmart
Copy link
Contributor

@Baalmart Baalmart commented Dec 14, 2024

Description

adding a helper function to update offline Sites

Changes Made

  • adding a helper function to update offline Sites

Testing

  • Tested locally
  • Tested against staging environment
  • Relevant tests passed: [List test names]

Affected Services

  • Which services were modified:
    • Device Registry

API Documentation Updated?

  • Yes, API documentation was updated
  • No, API documentation does not need updating

Additional Notes

adding a helper function to update offline Sites

Summary by CodeRabbit

  • New Features

    • Introduced a new functionality to update the status of offline sites based on their last active timestamp.
  • Bug Fixes

    • Improved the handling of offline devices and sites by processing updates in parallel.
  • Documentation

    • Updated export statements to include the new functionality for testing.

Copy link
Contributor

coderabbitai bot commented Dec 14, 2024

📝 Walkthrough

Walkthrough

The pull request introduces a new helper function updateOfflineSites in the store readings job, designed to update the status of offline sites based on their last active timestamp. This function is integrated into the existing fetchAndStoreDataIntoReadingsModel function, where it is executed in parallel with the updateOfflineDevices function. The modification enhances the system's ability to track and manage site statuses automatically.

Changes

File Change Summary
src/device-registry/bin/jobs/v2.1-store-readings-job.js - Added updateOfflineSites helper function
- Updated module.exports to include new function
- Modified fetchAndStoreDataIntoReadingsModel to run site and device offline updates in parallel

Sequence Diagram

sequenceDiagram
    participant Job as Store Readings Job
    participant DeviceRegistry as Device Registry
    
    Job->>DeviceRegistry: Fetch Measurements
    Job->>DeviceRegistry: Parallel Updates
    par
        Job->>DeviceRegistry: Update Offline Devices
        Job->>DeviceRegistry: Update Offline Sites
    end
    DeviceRegistry-->>Job: Status Updated
Loading

Possibly related PRs

Suggested Reviewers

  • Codebmk

Poem

In the realm of data's swift dance,
Sites and devices find their stance
Offline status, a gentle mark
Tracking silence in the digital park 🌐
Parallel updates, smooth and light
Bringing order to the system's might! 🤖

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. This feature will be included in our Pro Plan when released.


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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Dec 14, 2024

Codecov Report

Attention: Patch coverage is 0% with 4 lines in your changes missing coverage. Please review.

Project coverage is 11.81%. Comparing base (b907f64) to head (30abfb0).
Report is 17 commits behind head on staging.

Files with missing lines Patch % Lines
...evice-registry/bin/jobs/v2.1-store-readings-job.js 0.00% 4 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           staging    #4082      +/-   ##
===========================================
- Coverage    11.81%   11.81%   -0.01%     
===========================================
  Files          115      115              
  Lines        15482    15485       +3     
  Branches       319      319              
===========================================
  Hits          1829     1829              
- Misses       13653    13656       +3     
Files with missing lines Coverage Δ
...evice-registry/bin/jobs/v2.1-store-readings-job.js 18.18% <0.00%> (-0.51%) ⬇️

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 and nitpick comments (3)
src/device-registry/bin/jobs/v2.1-store-readings-job.js (3)

185-199: Good implementation, consider adding error handling and logging

The implementation is well-structured and efficient, using Set for unique values and bulk updates. However, consider adding error handling and logging for better observability.

Consider applying this enhancement:

 async function updateOfflineSites(data) {
+  try {
     const activeSiteIds = new Set(data.map((doc) => doc.site_id).filter(Boolean));
     const thresholdTime = moment()
       .subtract(INACTIVE_THRESHOLD, "milliseconds")
       .toDate();
 
-    await SiteModel("airqo").updateMany(
+    const result = await SiteModel("airqo").updateMany(
       {
         _id: { $nin: Array.from(activeSiteIds) },
         lastActive: { $lt: thresholdTime },
       },
       { isOnline: false }
     );
+    logger.info(`Updated ${result.modifiedCount} offline sites`);
+  } catch (error) {
+    logger.error(`Error updating offline sites: ${error.message}`);
+    throw error;  // Re-throw to be handled by the caller
+  }
 }

278-279: LGTM! Efficient parallel execution implementation

Good use of Promise.all for concurrent execution of offline updates. The implementation is efficient as both operations are independent.

Consider adding a more descriptive log message after successful completion:

-    logText("All data inserted successfully and offline devices updated");
+    logText("All data inserted successfully, offline devices and sites updated");

185-199: Consider architectural improvements for better maintainability

A few suggestions to enhance the implementation:

  1. Consider moving the INACTIVE_THRESHOLD to the configuration file for easier maintenance across environments.
  2. Consider implementing metrics collection for offline sites to track trends and patterns.

This would make the system more configurable and provide better insights into site health.

Example configuration structure:

// @config/constants.js
module.exports = {
  // ... existing constants
  SITE_INACTIVE_THRESHOLD: process.env.SITE_INACTIVE_THRESHOLD || 5 * 60 * 60 * 1000,
};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a570742 and 30abfb0.

📒 Files selected for processing (1)
  • src/device-registry/bin/jobs/v2.1-store-readings-job.js (3 hunks)

@@ -282,4 +298,5 @@ module.exports = {
updateEntityStatus,
isEntityActive,
updateOfflineDevices,
updateOfflineSites,
Copy link
Contributor

@coderabbitai coderabbitai bot Dec 14, 2024

Choose a reason for hiding this comment

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

💡 Codebase verification

Tests needed for the new updateOfflineSites function

The updateOfflineSites function is not covered by the existing test suite in ut_v2-store-readings-job.js. While the test file has good coverage for other functions including similar functionality in fetchAndStoreDataIntoReadingsModel, it lacks specific tests for this newly exported function.

Please add test cases for:

  • Updating sites as offline when they're not in the active set and beyond the threshold
  • Handling empty data arrays
  • Verifying the correct MongoDB query conditions are used
  • Ensuring the SiteModel update operation is called with correct parameters

The test structure should follow the existing patterns in the file, using the same testing utilities (chai, sinon) and setup/teardown approach.

🔗 Analysis chain

Verify test coverage for the new function

The new function is correctly exported for testing purposes. However, we should ensure adequate test coverage exists.

Let's verify the test coverage:


The previous attempt failed because we assumed the test directory location. Let's first understand the project structure and then look for test files that might contain our target function.


The previous search revealed the test directory structure and the function implementation. Let's specifically look for test files in the jobs directory where our function resides.


We found the relevant test file. Let's check if it contains tests for our new function and understand the test structure to verify coverage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for test files and coverage for updateOfflineSites

# Look for test files that might contain tests for this function
rg -l "updateOfflineSites" --type js test/

Length of output: 88


Script:

#!/bin/bash
# Let's first find the test directory structure
fd -t d "test" -d 3

# Then search for the function name in all JavaScript files
rg -l "updateOfflineSites" --type js

Length of output: 181


Script:

#!/bin/bash
# Let's check for tests in the device-registry directory
fd -t d "test" -d 3 "src/device-registry"

# Also search for any test files containing our function name in device-registry
rg -l "updateOfflineSites" "src/device-registry/**/*test*"
rg -l "updateOfflineSites" "src/device-registry/**/*spec*"

# Let's also see the function implementation to understand what kind of tests would be needed
rg -A 10 "function updateOfflineSites" src/device-registry/bin/jobs/v2.1-store-readings-job.js

Length of output: 1105


Script:

#!/bin/bash
# Let's check for test files in the jobs test directory specifically
fd -t f . "src/device-registry/bin/jobs/test"

# Let's also check for any test files related to store-readings-job
rg -l "store-readings" "src/device-registry/bin/jobs/test"

Length of output: 739


Script:

#!/bin/bash
# Let's check if the updateOfflineSites function is tested in the v2 store readings test file
rg -C 5 "updateOfflineSites" "src/device-registry/bin/jobs/test/ut_v2-store-readings-job.js"

# Also get the test file content to understand the test structure
cat "src/device-registry/bin/jobs/test/ut_v2-store-readings-job.js"

Length of output: 8442

Copy link
Contributor Author

Choose a reason for hiding this comment

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

please generate a new Github issue for this.

Copy link
Contributor

Choose a reason for hiding this comment

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

@Baalmart, the GitHub issue has been successfully created: #4083. Let me know if there's anything else I can assist with.

🔗 Analysis chain

@Baalmart, I've opened a GitHub issue to add tests for the updateOfflineSites function.

(_/)
(•_•)
/ 💻 Happy to help!

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Create a GitHub issue for adding tests for the updateOfflineSites function
gh issue create \
  --title "Add tests for the updateOfflineSites function" \
  --body "The \`updateOfflineSites\` function introduced in PR https://github.com/airqo-platform/AirQo-api/pull/4082 lacks test coverage.

Specific tests should be added for:

* Updating sites as offline when they're not in the active set and beyond the threshold
* Handling empty data arrays
* Verifying the correct MongoDB query conditions are used
* Ensuring the SiteModel update operation is called with correct parameters

The test structure should follow the existing patterns in the file, using the same testing utilities (chai, sinon) and setup/teardown approach.

Refer to the comment: https://github.com/airqo-platform/AirQo-api/pull/4082#discussion_r1885023407

Requester: @Baalmart" \
  --assignee Baalmart

Length of output: 843

Copy link
Contributor

Device registry changes in this PR available for preview here

@Baalmart Baalmart merged commit f271745 into staging Dec 14, 2024
51 of 52 checks passed
@Baalmart Baalmart deleted the hf-update-offline-sites branch December 14, 2024 10:51
@Baalmart Baalmart mentioned this pull request Dec 14, 2024
1 task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant