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

Hotfixes of metadata for Devices and Sites #4104

Merged
merged 4 commits into from
Dec 20, 2024
Merged

Conversation

Baalmart
Copy link
Contributor

@Baalmart Baalmart commented Dec 20, 2024

Description

Hotfixes of metadata for Devices and Sites

Changes Made

  • Automatically assign data_provider when assigning groups
  • A job to automatically update duplicate Sites after they have been identified
  • When recalling/deploying devices, ensure that the category field is never removed, accidentally

Testing

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

Affected Services

  • Which services were modified:
    • Device Registry

Endpoints Ready for Testing

  • New endpoints ready for testing:
    • Deploy Device
    • Recall Device

API Documentation Updated?

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

Summary by CodeRabbit

  • New Features

    • Introduced a scheduled job to identify and update duplicate fields in site records, running every four hours.
    • Enhanced handling of the category field in device records, ensuring data integrity and validation.
    • Improved update logic for the data_provider field in site records, streamlining the update process.
  • Bug Fixes

    • Added checks to prevent duplicates in the grids and groups fields during updates.
  • Documentation

    • Improved error handling and messaging for device lifecycle methods.

Copy link
Contributor

coderabbitai bot commented Dec 20, 2024

📝 Walkthrough

Walkthrough

This pull request introduces a comprehensive update to the device registry system, focusing on improving data integrity and management. The changes include a new scheduled job for updating duplicate site fields, modifications to device and site models to enhance validation and update processes, and the integration of a new job into the server configuration. The primary goal is to ensure data consistency and provide more robust handling of site and device records.

Changes

File Change Summary
src/device-registry/bin/jobs/update-duplicate-site-fields-job.js New job to identify and update duplicate site fields every four hours
src/device-registry/bin/server.js Added import for new duplicate site fields update job
src/device-registry/models/Device.js Enhanced category field validation, improved error handling and device creation logic
src/device-registry/models/Site.js Updated data_provider assignment logic, added duplicate checks for grids and groups

Sequence Diagram

sequenceDiagram
    participant Job as Duplicate Site Fields Job
    participant SitesModel as Sites Database
    participant UpdateProcess as Update Processor

    Job->>SitesModel: Fetch Active Sites
    SitesModel-->>Job: Return Site Records
    Job->>Job: Group Sites by Duplicate Fields
    Job->>UpdateProcess: Generate Unique Field Values
    UpdateProcess->>SitesModel: Perform Bulk Updates
    SitesModel-->>Job: Update Confirmation
    Job->>Job: Log Update Report
Loading

Possibly Related PRs

Suggested Reviewers

  • Codebmk
  • NicholasTurner23

Poem

In the realm of data, where duplicates hide,
A job emerges, with precision as its guide
Cleaning fields with algorithmic grace
Ensuring uniqueness in every database space
🤖✨ Code dancing, records realigning!

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. We would love to hear your feedback on Discord.


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 20, 2024

Codecov Report

Attention: Patch coverage is 19.78022% with 73 lines in your changes missing coverage. Please review.

Project coverage is 11.85%. Comparing base (2f4845a) to head (73bcd49).

Files with missing lines Patch % Lines
...istry/bin/jobs/update-duplicate-site-fields-job.js 23.28% 56 Missing ⚠️
src/device-registry/models/Device.js 8.33% 11 Missing ⚠️
src/device-registry/models/Site.js 0.00% 6 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           staging    #4104      +/-   ##
===========================================
+ Coverage    11.81%   11.85%   +0.04%     
===========================================
  Files          115      116       +1     
  Lines        15485    15576      +91     
  Branches       319      319              
===========================================
+ Hits          1829     1847      +18     
- Misses       13656    13729      +73     
Files with missing lines Coverage Δ
src/device-registry/models/Site.js 13.21% <0.00%> (-0.48%) ⬇️
src/device-registry/models/Device.js 13.08% <8.33%> (-0.29%) ⬇️
...istry/bin/jobs/update-duplicate-site-fields-job.js 23.28% <23.28%> (ø)

Copy link
Contributor

Device registry changes in this PR available for preview here

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 (5)
src/device-registry/bin/jobs/update-duplicate-site-fields-job.js (2)

91-104: Validate filtering for "active" sites.
The code uses { isOnline: true } to filter active sites. If your definition of “active” changes or includes additional predicates, it may be beneficial to centralize this into a helper method for consistency.


150-155: Cron scheduling feedback.
Running every 4 hours at minute 15 is generally fine. However, if the dataset grows or the job becomes more resource-intensive, you may consider adjusting frequency or implementing more fine-grained scheduling.

src/device-registry/models/Device.js (2)

273-278: Use 'undefined' assignment instead of 'delete' for performance.
Static analysis highlights the potential performance overhead of the delete operator. Consider setting the field to undefined instead, which often proves faster and safer in V8.

- if (this.category === null) {
-   delete this.category;
- } else if (
+ if (this.category === null) {
+   this.category = undefined;
+ } else if (
    !DEVICE_CONFIG.ALLOWED_CATEGORIES.includes(this.category)
🧰 Tools
🪛 Biome (1.9.4)

[error] 278-278: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


295-297: Refactor removing 'category' field on updates.
Similar to line 278, consider assigning to undefined rather than deleting to align with best practices.

- if (updateData.category === null) {
-   delete updateData.category;
- } else if (
+ if (updateData.category === null) {
+   updateData.category = undefined;
+ } else if (
    !DEVICE_CONFIG.ALLOWED_CATEGORIES.includes(updateData.category)
🧰 Tools
🪛 Biome (1.9.4)

[error] 296-296: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

src/device-registry/models/Site.js (1)

396-420: Optional chaining for improved readability.
The repeated checks for existence in lines 398, 403, 404-406, and 407 can be made more concise and safe using optional chaining (e.g., updates?.$set?.groups) if you’re comfortable with that style.

- const hasExplicitDataProvider = 
-   updates.data_provider || (updates.$set && updates.$set.data_provider);
+ const hasExplicitDataProvider =
+   updates.data_provider || updates?.$set?.data_provider;

(and similarly for other lines)

🧰 Tools
🪛 Biome (1.9.4)

[error] 398-398: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 403-403: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 404-406: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 407-407: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2f4845a and 73bcd49.

📒 Files selected for processing (4)
  • src/device-registry/bin/jobs/update-duplicate-site-fields-job.js (1 hunks)
  • src/device-registry/bin/server.js (1 hunks)
  • src/device-registry/models/Device.js (2 hunks)
  • src/device-registry/models/Site.js (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/device-registry/models/Device.js

[error] 278-278: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 296-296: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

src/device-registry/models/Site.js

[error] 398-398: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 403-403: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 404-406: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 407-407: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (4)
src/device-registry/bin/jobs/update-duplicate-site-fields-job.js (2)

58-68: Consider concurrency and validation for net-new fieldValue updates.
While building updates, ensure other concurrent jobs aren’t updating the same documents, which might cause race conditions or partial updates.


17-20: Consider more robust pattern validation.
Currently, the regex only captures "site_123" patterns. If there's a possibility of uppercase, extra dashes, or other numeric prefixes, consider expanding the pattern or adding fallback logic.

Do you need a more flexible or strict pattern? Let’s confirm by searching for additional naming patterns elsewhere in the code.

✅ Verification successful

Let me search for the actual site name patterns in the codebase to understand the naming conventions.


Let me check how the site names are generated to understand the pattern requirements better.


Current site name pattern is sufficient and correct

Based on the codebase analysis, the current regex pattern /site_(\d+)/ is actually appropriate because:

  1. Site names are systematically generated using a counter starting from "site_0"
  2. The pattern is consistently used across the codebase with lowercase "site_" prefix followed by numbers
  3. The generation is controlled through the UniqueIdentifierCounterModel, ensuring standardized naming

The current implementation correctly handles the only format that can exist in the system, making additional pattern flexibility unnecessary.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Searching for references to "extractSiteNumber" usage
rg -A 5 $'extractSiteNumber'

Length of output: 1468


Script:

#!/bin/bash
# Search for site name patterns in the codebase
rg -i "site_\d+" --type js -A 2 -B 2

# Also search for generated_name assignments or declarations
ast-grep --pattern 'generated_name = $_'

Length of output: 2326


Script:

#!/bin/bash
# Check the site name generation logic
rg -A 10 "generateName" src/device-registry/utils/create-site.js

# Also check for any site name validation
rg -i "site.*name.*validation" --type js

Length of output: 1313

src/device-registry/models/Device.js (1)

280-310: Ensure consistent error and field handling.
This logic properly enforces valid categories, default networks, and checks the AirQo constraints. Keep an eye on whether future custom categories or networks might need additional exception handling.

🧰 Tools
🪛 Biome (1.9.4)

[error] 296-296: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

src/device-registry/bin/server.js (1)

33-33: Importing the new job looks good.
This ensures that the duplicate site fields job is available and scheduled. Great job expanding your overall data integrity strategy by integrating the job with your existing environment.

@Baalmart Baalmart merged commit a3fd1cf into staging Dec 20, 2024
52 checks passed
@Baalmart Baalmart deleted the hotfixes-metadata branch December 20, 2024 07:30
@Baalmart Baalmart mentioned this pull request Dec 20, 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