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

Update fix/clean up #4179

Merged

Conversation

NicholasTurner23
Copy link
Contributor

@NicholasTurner23 NicholasTurner23 commented Jan 8, 2025

Description

This PR allows to pick specific network devices and cleans up the field naming to match the fields returned by get_devices_by_network.

Related Issues

  • JIRA cards:
    • OPS-327

Summary by CodeRabbit

  • New Features

    • Introduced DeviceNetwork constant to categorize devices by network type
    • Enhanced device data retrieval with network-specific filtering
  • Refactor

    • Renamed Tenant to DeviceNetwork across multiple utility files
    • Updated method signatures to include network-specific parameters
    • Improved code clarity and consistency in device data handling
  • Chores

    • Updated import statements and constant usage in DAG files
    • Removed deprecated import references

Copy link
Contributor

coderabbitai bot commented Jan 8, 2025

📝 Walkthrough

Walkthrough

This pull request introduces a comprehensive update to the AirQo ETL utilities, focusing on device network categorization and data processing. The changes primarily revolve around introducing a new DeviceNetwork constant, updating method signatures across multiple files, and refactoring device data retrieval mechanisms. The modifications enhance the precision of device filtering and provide more granular control over network-specific data extraction.

Changes

File Change Summary
src/workflows/airqo_etl_utils/constants.py Added new DeviceNetwork enumeration with METONE, AIRQO, URBANBETTER, and IQAIR network types
src/workflows/airqo_etl_utils/airqo_utils.py Updated method signatures to include device_network, replaced Tenant.AIRQO with DeviceNetwork.AIRQO
src/workflows/airqo_etl_utils/airqo_api.py Modified get_maintenance_logs and get_devices_by_network methods to support network-specific parameters
src/workflows/airqo_etl_utils/airnow_utils.py Updated device data retrieval methods to use DeviceNetwork.METONE
DAG files Added DeviceNetwork imports, updated method signatures with network-specific parameters

Possibly related PRs

Suggested Labels

python, ready for review

Suggested Reviewers

  • Baalmart
  • Mnoble-19
  • Psalmz777
  • BenjaminSsempala

Poem

🌐 Networks dancing, constants bright,
Code refactored with surgical might
Devices sorted, networks clear
ETL magic drawing near!
A symphony of data's delight 🚀


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.

@Baalmart Baalmart merged commit 36d65c6 into airqo-platform:staging Jan 8, 2025
46 checks passed
@Baalmart Baalmart mentioned this pull request Jan 8, 2025
1 task
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 (3)
src/workflows/airqo_etl_utils/constants.py (1)

50-74: Well-structured DeviceNetwork enum implementation.

The implementation is clean, well-documented, and follows Python enum best practices. The error handling for invalid networks adds robustness to the code.

However, consider adding a class-level docstring that includes examples of usage to make it even more developer-friendly.

 class DeviceNetwork(Enum):
     """
     METONE -> Us embassy
     AIRQO -> Airqo
     URBANBETTER -> Urban Better
     IQAIR -> Iqair
+
+    Example usage:
+        network = DeviceNetwork.AIRQO
+        network_str = str(network)  # Returns "airqo"
     """
src/workflows/airqo_etl_utils/airqo_utils.py (2)

429-431: Consider adding error handling for invalid device networks.

The get_devices_by_network call should handle cases where an invalid device_network is provided.

Add validation before the API call:

+        if device_network and not isinstance(device_network, DeviceNetwork):
+            logger.warning(f"Invalid device_network provided: {device_network}")
+            return devices_data
         devices = airqo_api.get_devices_by_network(
             device_network=device_network, device_category=device_category
         )

905-905: Consistent use of DeviceNetwork enum.

Good use of the DeviceNetwork enum for network specification, but the string literal "airqo" is still used in the get_maintenance_logs call.

Apply this diff to maintain consistency:

         devices = airqo_api.get_devices(network=DeviceNetwork.AIRQO)
         devices_history = pd.DataFrame()
         for device in devices:
             try:
                 maintenance_logs = airqo_api.get_maintenance_logs(
-                    network="airqo",
+                    network=DeviceNetwork.AIRQO,
                     device=device.get("name", None),
                     activity_type="deployment",
                 )

Also applies to: 910-910

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 40459ac and e2d2697.

📒 Files selected for processing (7)
  • src/workflows/airqo_etl_utils/airnow_utils.py (5 hunks)
  • src/workflows/airqo_etl_utils/airqo_api.py (5 hunks)
  • src/workflows/airqo_etl_utils/airqo_utils.py (8 hunks)
  • src/workflows/airqo_etl_utils/constants.py (1 hunks)
  • src/workflows/airqo_etl_utils/data_validator.py (1 hunks)
  • src/workflows/dags/airqo_bam_measurements.py (3 hunks)
  • src/workflows/dags/airqo_measurements.py (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/workflows/airqo_etl_utils/data_validator.py
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (10)
src/workflows/dags/airqo_bam_measurements.py (2)

13-13: LGTM! Enhanced device filtering with network specification.

The addition of DeviceNetwork import and the new parameters in extract_bam_data improve the precision of device selection, aligning well with the PR objectives.

Also applies to: 34-35


94-95: LGTM! Consistent implementation in realtime DAG.

The realtime measurements DAG follows the same pattern of network specification, maintaining consistency across the codebase.

src/workflows/airqo_etl_utils/airnow_utils.py (3)

7-7: LGTM! Improved device filtering with network specification.

The implementation now correctly filters METONE devices using the new DeviceNetwork enum, enhancing the precision of device selection.

Also applies to: 71-73


128-129: Good code organization improvements.

The variable renaming from device_id to device_id_ and the relocation of pollutant_value initialization improve code readability.

Also applies to: 139-140


145-145: LGTM! Clear error handling and logging.

The error messages are descriptive and the logging implementation follows best practices, making debugging easier.

Also applies to: 156-156

src/workflows/dags/airqo_measurements.py (2)

18-18: LGTM! Consistent import structure.

The addition of DeviceNetwork import aligns with the codebase-wide refactoring approach.


572-572: LGTM! Enhanced device filtering in gaseous measurements DAG.

The addition of device_network parameter with DeviceNetwork.AIRQO maintains consistency with other DAGs while improving device selection precision.

src/workflows/airqo_etl_utils/airqo_api.py (2)

289-297: Good error handling for network fetching.

The code properly handles the case where network fetching fails, logging the error and returning an empty devices list.


29-30: Verify the impact of enabling staging environment storage.

The commented code previously prevented storing measurements in the staging environment. This change enables measurement storage in staging, which could affect system resources and data integrity.

Run this script to assess the potential impact:

✅ Verification successful

Enabling staging measurement storage is safe and beneficial

The change allows proper testing of measurement storage functionality in the staging environment while maintaining environment isolation through separate infrastructure configurations. Other staging environment protections, like preventing notifications, remain in place.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any existing measurements in staging
rg -A 3 "staging.*measurements" 

Length of output: 33


Script:

#!/bin/bash
# Search for staging environment configuration and base URL
rg "AIRQO_BASE_URL" -A 3

# Search for measurement-related code
rg "def.*measurement" -A 5

# Look for staging environment checks
rg "if.*staging" -A 3

# Find configuration files
fd -e yaml -e yml -e conf -e config -e env

Length of output: 37596

src/workflows/airqo_etl_utils/airqo_utils.py (1)

407-407: Good addition of device_network parameter.

The addition of the device_network parameter and the updated docstring improves the clarity of the function's purpose and aligns with the network-based filtering functionality.

Also applies to: 413-413

@@ -41,7 +41,7 @@ def save_events(self, measurements: List) -> None:
)

def get_maintenance_logs(
self, tenant: str, device: str, activity_type: str = None
self, network: str, device: str, activity_type: str = None
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

Parameter rename from tenant to network needs documentation update.

The parameter has been renamed from tenant to network, but the docstring still references tenant. This inconsistency could confuse future developers.

Apply this diff to update the documentation:

        """
        Retrieve devices given a tenant and device category.

        Args:
-           - tenant: An Enum that represents site ownership.
+           - network: A string that represents the device network/manufacturer.
            - device: The name of the device.
            - activity_type: Defines if the activity logged is a maintenance or deployment activity. If not supplied returns all activities for the given device.

Also applies to: 73-73

Comment on lines +244 to +251
self, device_network: str = None, device_category: DeviceCategory = None
) -> List[Dict[str, Any]]:
"""
Retrieve devices by network based on the specified device category.

Args: device_category (DeviceCategory, optional): The category of devices to retrieve. Defaults to `DeviceCategory.LOW_COST`.
Args:
network (str): This defines the network or manufacture of the device(s) to retrieve. Defaults to `None`. If not passed, devices from all networks are returned.
device_category (DeviceCategory, optional): The category of devices to retrieve. Defaults to `None`. If not passed, devices from all categories are returned.
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

Documentation improvement needed for device_network parameter.

The docstring has a mismatch between the parameter name in the signature (device_network) and the documentation (network).

Apply this diff to fix the documentation:

        """
        Retrieve devices by network based on the specified device category.

        Args:
-           network (str): This defines the network or manufacture of the device(s) to retrieve. Defaults to `None`. If not passed, devices from all networks are returned.
+           device_network (str): This defines the network or manufacturer of the device(s) to retrieve. Defaults to `None`. If not passed, devices from all networks are returned.
            device_category (DeviceCategory, optional): The category of devices to retrieve. Defaults to `None`. If not passed, devices from all categories are returned.
📝 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
self, device_network: str = None, device_category: DeviceCategory = None
) -> List[Dict[str, Any]]:
"""
Retrieve devices by network based on the specified device category.
Args: device_category (DeviceCategory, optional): The category of devices to retrieve. Defaults to `DeviceCategory.LOW_COST`.
Args:
network (str): This defines the network or manufacture of the device(s) to retrieve. Defaults to `None`. If not passed, devices from all networks are returned.
device_category (DeviceCategory, optional): The category of devices to retrieve. Defaults to `None`. If not passed, devices from all categories are returned.
self, device_network: str = None, device_category: DeviceCategory = None
) -> List[Dict[str, Any]]:
"""
Retrieve devices by network based on the specified device category.
Args:
device_network (str): This defines the network or manufacturer of the device(s) to retrieve. Defaults to `None`. If not passed, devices from all networks are returned.
device_category (DeviceCategory, optional): The category of devices to retrieve. Defaults to `None`. If not passed, devices from all categories are returned.

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