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

more optimisations/refactoring for the readings job #3608

Merged
merged 1 commit into from
Oct 9, 2024

Conversation

Baalmart
Copy link
Contributor

@Baalmart Baalmart commented Oct 9, 2024

  • more optimisations/refactoring for the readings job

Summary by CodeRabbit

  • New Features

    • Improved efficiency in data processing with concurrent updates.
    • Enhanced error handling during data fetching and batch processing.
  • Bug Fixes

    • Refined error logging to manage duplicate key errors effectively.
  • Refactor

    • Streamlined logic for updating entity statuses and fetching data.

Copy link
Contributor

coderabbitai bot commented Oct 9, 2024

📝 Walkthrough

Walkthrough

The changes in the pull request focus on the v3-store-readings-job.js file, where several functions have been modified to enhance the handling of entity statuses and data fetching. Key modifications include the removal of the isEntityActive function, with its logic integrated into updateEntityStatus. The update process has been streamlined using findOneAndUpdate, and the handling of update promises in processDocument has been improved to allow concurrent processing. Additionally, the fetchAllData function now uses a hasMoreData flag for better control flow, and error handling throughout the functions has been refined.

Changes

File Path Change Summary
src/device-registry/bin/jobs/v3-store-readings-job.js - Removed isEntityActive function; integrated logic into updateEntityStatus.
- Updated updateEntityStatus to use findOneAndUpdate.
- Modified processDocument to handle update promises concurrently.
- Adjusted fetchAllData to use a hasMoreData flag; improved error handling.
- Enhanced error handling in fetchAndStoreDataIntoReadingsModel during batch processing.

Possibly related PRs

🎉 In the realm of code where logic flows,
Functions dance, and efficiency grows.
With updates swift and errors tamed,
The reading job's now finely framed.
So here's to changes, bold and bright,
In the world of code, we take flight! 🚀


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.

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 Oct 9, 2024

Codecov Report

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

Project coverage is 27.05%. Comparing base (a15161c) to head (1f30eb0).
Report is 4 commits behind head on staging.

Files with missing lines Patch % Lines
.../device-registry/bin/jobs/v3-store-readings-job.js 0.00% 22 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           staging    #3608   +/-   ##
========================================
  Coverage    27.04%   27.05%           
========================================
  Files          146      146           
  Lines        21346    21345    -1     
  Branches       273      273           
========================================
  Hits          5774     5774           
+ Misses       15572    15571    -1     
Files with missing lines Coverage Δ
.../device-registry/bin/jobs/v3-store-readings-job.js 19.23% <0.00%> (+0.18%) ⬆️

Copy link
Contributor

github-actions bot commented Oct 9, 2024

Device registry changes in this PR available for preview here

@Baalmart Baalmart merged commit 335b6ff into staging Oct 9, 2024
49 of 50 checks passed
@Baalmart Baalmart deleted the en1-network-status branch October 9, 2024 23:45
@Baalmart Baalmart mentioned this pull request Oct 9, 2024
2 tasks
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 (2)
src/device-registry/bin/jobs/v3-store-readings-job.js (2)

46-49: Consider adding unit tests for updateEntityStatus

To ensure the reliability of the updateEntityStatus function, it's beneficial to add unit tests covering various scenarios, such as when the entity is found or not found, and verifying the correct calculation of isOnline.

Would you like assistance in creating unit tests for this function?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 46-46: src/device-registry/bin/jobs/v3-store-readings-job.js#L46
Added line #L46 was not covered by tests


159-159: Consider adding tests for error handling in fetchAllData

To improve code reliability, consider adding unit tests that simulate errors during data fetching to ensure the error handling logic works as expected.

Can I assist in creating tests for these error scenarios?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 159-159: src/device-registry/bin/jobs/v3-store-readings-job.js#L159
Added line #L159 was not covered by tests

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between fb807c1 and 1f30eb0.

📒 Files selected for processing (1)
  • src/device-registry/bin/jobs/v3-store-readings-job.js (3 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
src/device-registry/bin/jobs/v3-store-readings-job.js

[warning] 33-33: src/device-registry/bin/jobs/v3-store-readings-job.js#L33
Added line #L33 was not covered by tests


[warning] 36-36: src/device-registry/bin/jobs/v3-store-readings-job.js#L36
Added line #L36 was not covered by tests


[warning] 46-46: src/device-registry/bin/jobs/v3-store-readings-job.js#L46
Added line #L46 was not covered by tests


[warning] 51-51: src/device-registry/bin/jobs/v3-store-readings-job.js#L51
Added line #L51 was not covered by tests


[warning] 100-100: src/device-registry/bin/jobs/v3-store-readings-job.js#L100
Added line #L100 was not covered by tests


[warning] 103-104: src/device-registry/bin/jobs/v3-store-readings-job.js#L103-L104
Added lines #L103 - L104 were not covered by tests


[warning] 106-106: src/device-registry/bin/jobs/v3-store-readings-job.js#L106
Added line #L106 was not covered by tests


[warning] 121-121: src/device-registry/bin/jobs/v3-store-readings-job.js#L121
Added line #L121 was not covered by tests


[warning] 123-124: src/device-registry/bin/jobs/v3-store-readings-job.js#L123-L124
Added lines #L123 - L124 were not covered by tests


[warning] 127-128: src/device-registry/bin/jobs/v3-store-readings-job.js#L127-L128
Added lines #L127 - L128 were not covered by tests


[warning] 134-134: src/device-registry/bin/jobs/v3-store-readings-job.js#L134
Added line #L134 was not covered by tests


[warning] 140-140: src/device-registry/bin/jobs/v3-store-readings-job.js#L140
Added line #L140 was not covered by tests


[warning] 142-142: src/device-registry/bin/jobs/v3-store-readings-job.js#L142
Added line #L142 was not covered by tests


[warning] 145-145: src/device-registry/bin/jobs/v3-store-readings-job.js#L145
Added line #L145 was not covered by tests


[warning] 150-151: src/device-registry/bin/jobs/v3-store-readings-job.js#L150-L151
Added lines #L150 - L151 were not covered by tests


[warning] 153-153: src/device-registry/bin/jobs/v3-store-readings-job.js#L153
Added line #L153 was not covered by tests


[warning] 157-157: src/device-registry/bin/jobs/v3-store-readings-job.js#L157
Added line #L157 was not covered by tests


[warning] 159-159: src/device-registry/bin/jobs/v3-store-readings-job.js#L159
Added line #L159 was not covered by tests

🔇 Additional comments (5)
src/device-registry/bin/jobs/v3-store-readings-job.js (5)

33-44: Implementation of updateEntityStatus function looks good

The updated updateEntityStatus function efficiently calculates the isOnline status based on the time difference between currentTime and the provided time. The use of findOneAndUpdate streamlines the update process and improves code readability.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 33-33: src/device-registry/bin/jobs/v3-store-readings-job.js#L33
Added line #L33 was not covered by tests


[warning] 36-36: src/device-registry/bin/jobs/v3-store-readings-job.js#L36
Added line #L36 was not covered by tests


100-102: Efficient upsert operation for readings

Using updateOne with { upsert: true } in updating readings ensures that documents are either updated or created as needed, which is an efficient approach for maintaining the readings collection.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 100-100: src/device-registry/bin/jobs/v3-store-readings-job.js#L100
Added line #L100 was not covered by tests


103-107: Enhance error handling in processDocument

While the error is logged when Promise.all(updatePromises) fails, consider implementing additional error handling or retries for transient errors to make the processing more robust.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 103-104: src/device-registry/bin/jobs/v3-store-readings-job.js#L103-L104
Added lines #L103 - L104 were not covered by tests


[warning] 106-106: src/device-registry/bin/jobs/v3-store-readings-job.js#L106
Added line #L106 was not covered by tests


121-123: Improved control flow with hasMoreData flag

Replacing the infinite while (true) loop with while (hasMoreData) enhances the readability and control flow of the fetchAllData function, making the termination condition explicit.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 121-121: src/device-registry/bin/jobs/v3-store-readings-job.js#L121
Added line #L121 was not covered by tests


145-155: Efficient data accumulation in fetchAllData

The logic for accumulating data from the database queries is well-implemented, ensuring that all retrieved entities are captured for further processing.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 145-145: src/device-registry/bin/jobs/v3-store-readings-job.js#L145
Added line #L145 was not covered by tests


[warning] 150-151: src/device-registry/bin/jobs/v3-store-readings-job.js#L150-L151
Added lines #L150 - L151 were not covered by tests


[warning] 153-153: src/device-registry/bin/jobs/v3-store-readings-job.js#L153
Added line #L153 was not covered by tests

Comment on lines +158 to +159
} catch (error) {
logger.error(`Error fetching data: ${error.message}`);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent potential infinite loop on data fetch errors

If an error occurs during data fetching, hasMoreData remains true, which could lead to an infinite loop. To prevent this, consider setting hasMoreData = false in the catch block to ensure the loop terminates appropriately.

Apply this diff to address the issue:

} catch (error) {
  logger.error(`Error fetching data: ${error.message}`);
+ hasMoreData = false;
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (error) {
logger.error(`Error fetching data: ${error.message}`);
} catch (error) {
logger.error(`Error fetching data: ${error.message}`);
hasMoreData = false;
}
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 159-159: src/device-registry/bin/jobs/v3-store-readings-job.js#L159
Added line #L159 was not covered by tests

Comment on lines +103 to +107
try {
await Promise.all(updatePromises);
} catch (error) {
logger.error(`🐛🐛 Error processing document: ${error.message}`);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid swallowing errors silently

In the processDocument function, errors caught within the inner try-catch block are logged but not rethrown or handled further. This might cause the batch processing to continue despite critical failures. Consider handling the errors appropriately, possibly by rethrowing them to be caught in the outer scope.

Apply this diff to rethrow the error:

try {
  await Promise.all(updatePromises);
} catch (error) {
  logger.error(`🐛🐛 Error processing document: ${error.message}`);
+ throw error;
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
await Promise.all(updatePromises);
} catch (error) {
logger.error(`🐛🐛 Error processing document: ${error.message}`);
}
try {
await Promise.all(updatePromises);
} catch (error) {
logger.error(`🐛🐛 Error processing document: ${error.message}`);
throw error;
}
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 103-104: src/device-registry/bin/jobs/v3-store-readings-job.js#L103-L104
Added lines #L103 - L104 were not covered by tests


[warning] 106-106: src/device-registry/bin/jobs/v3-store-readings-job.js#L106
Added line #L106 was not covered by tests

Comment on lines +129 to +143
...filter,
limit: pageSize,
skip: page * pageSize,
});

// Check if the response is successful and contains data
if (
!response.success ||
!response.data ||
response.data.length === 0 ||
response.data[0].data.length === 0
) {
break; // Exit loop if no more data
}
if (
!response.success ||
!response.data ||
response.data.length === 0 ||
response.data[0].data.length === 0
) {
hasMoreData = false;
} else {
allData.push(...response.data[0].data);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Validate response structure when fetching events

In the EventModel data fetching logic, verify that response.data[0].data exists before accessing it to prevent potential runtime errors. Adding defensive checks will enhance the robustness of the code.

Apply this diff to add a validation check:

if (
  !response.success ||
  !response.data ||
  response.data.length === 0 ||
- response.data[0].data.length === 0
+ !response.data[0].data ||
+ response.data[0].data.length === 0
) {
  hasMoreData = false;
} else {
  allData.push(...response.data[0].data);
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
...filter,
limit: pageSize,
skip: page * pageSize,
});
// Check if the response is successful and contains data
if (
!response.success ||
!response.data ||
response.data.length === 0 ||
response.data[0].data.length === 0
) {
break; // Exit loop if no more data
}
if (
!response.success ||
!response.data ||
response.data.length === 0 ||
response.data[0].data.length === 0
) {
hasMoreData = false;
} else {
allData.push(...response.data[0].data);
}
...filter,
limit: pageSize,
skip: page * pageSize,
});
if (
!response.success ||
!response.data ||
response.data.length === 0 ||
!response.data[0].data ||
response.data[0].data.length === 0
) {
hasMoreData = false;
} else {
allData.push(...response.data[0].data);
}
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 134-134: src/device-registry/bin/jobs/v3-store-readings-job.js#L134
Added line #L134 was not covered by tests


[warning] 140-140: src/device-registry/bin/jobs/v3-store-readings-job.js#L140
Added line #L140 was not covered by tests


[warning] 142-142: src/device-registry/bin/jobs/v3-store-readings-job.js#L142
Added line #L142 was not covered by tests

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