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

feat: only process incoming websocket packet model type once #52

Merged
merged 7 commits into from
Jun 14, 2024

Conversation

bdraco
Copy link
Member

@bdraco bdraco commented Jun 14, 2024

Description of change

only process incoming websocket packet model type once

Summary by CodeRabbit

  • New Features

    • Enhanced device processing by introducing model-specific handling in various methods.
  • Improvements

    • Streamlined device access by using model-specific keys instead of model values.
    • Improved flexibility with new methods for handling sets of model types and events.
  • Bug Fixes

    • Ensured consistent model type behavior across different methods and modules.
  • Refactor

    • Updated methods to use ModelType enums for more precise model handling and better code maintainability.

Copy link
Contributor

coderabbitai bot commented Jun 14, 2024

Walkthrough

The recent changes primarily focus on enhancing the handling of ModelType in the uiprotect module. This involves the creation of new properties and methods within the ModelType class, updating API interaction methods to use these new attributes, and refining data processing logic to accommodate these adjustments. These modifications are aimed at improving the flexibility and maintainability of the code by centralizing model type information and making it more adaptable.

Changes

File Change Summary
src/uiprotect/api.py Updated get_devices_raw and adopt_device to use model_type.devices_key instead of {model_type.value}s.
src/uiprotect/data/bootstrap.py Streamlined methods to use ModelType.bootstrap_models_types_set() and refined packet handling by incorporating model_type parameters.
src/uiprotect/data/convert.py Added model_type parameter to create_from_unifi_dict function.
src/uiprotect/data/types.py Added devices_key cached property, updated from_string, renamed bootstrap_models, and added new methods to ModelType class.
src/uiprotect/data/user.py Modified objs method to use self.model.devices_key to access devices.

Poem

🐇 In code we trust, the rabbits say,
Models crafted in a clever way.
With keys of magic, types so bright,
Protect evolves with morning light.
Devices dance in graceful glee,
Unified in harmony. 🐇


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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.

@bdraco bdraco marked this pull request as ready for review June 14, 2024 00:08
Copy link

codecov bot commented Jun 14, 2024

Codecov Report

Attention: Patch coverage is 76.92308% with 12 lines in your changes missing coverage. Please review.

Files Coverage Δ
src/uiprotect/data/convert.py 75.00% <100.00%> (+6.81%) ⬆️
src/uiprotect/data/types.py 97.94% <100.00%> (-0.14%) ⬇️
src/uiprotect/api.py 54.17% <50.00%> (ø)
src/uiprotect/data/user.py 87.41% <0.00%> (ø)
src/uiprotect/data/bootstrap.py 55.55% <61.53%> (+0.47%) ⬆️

@bdraco
Copy link
Member Author

bdraco commented Jun 14, 2024

verified it doesn't leak

2024-06-13 19:24:08.630 CRITICAL (SyncWorker_26) [homeassistant.components.profiler] Cache stats for lru_cache <function ModelType.devices_key at 0x7fd7bd5fb100> at /usr/local/lib/python3.12/site-packages/uiprotect/data/types.py: CacheInfo(hits=110, misses=11, maxsize=None, currsize=11)

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

Outside diff range and nitpick comments (1)
src/uiprotect/data/convert.py (1)

66-66: Consider adding a docstring for the new parameter model_type to enhance code documentation.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 8a6c7f2 and 5f42753.

Files selected for processing (5)
  • src/uiprotect/api.py (2 hunks)
  • src/uiprotect/data/bootstrap.py (9 hunks)
  • src/uiprotect/data/convert.py (2 hunks)
  • src/uiprotect/data/types.py (2 hunks)
  • src/uiprotect/data/user.py (1 hunks)
Additional comments not posted (7)
src/uiprotect/data/convert.py (1)

75-77: Ensure that MODEL_TO_CLASS.get(model_type) is always expected to return a valid class. Consider adding error handling if model_type is not found in the dictionary.

Verification successful

MODEL_TO_CLASS is defined with various ModelType keys mapped to corresponding classes, ensuring that most model_type values have valid mappings. However, there is still a potential risk if model_type is not found in the dictionary. The existing code does handle this scenario by raising a DataDecodeError if klass is None.

  • MODEL_TO_CLASS is defined with mappings for various ModelType values.
  • The function get_klass_from_dict raises DataDecodeError if the modelKey is unknown.
  • Similarly, create_from_unifi_dict calls get_klass_from_dict if klass is None.

This indicates that the error handling is already in place.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that all possible values of `model_type` have corresponding classes in `MODEL_TO_CLASS`.

# Test: Search for missing classes in `MODEL_TO_CLASS`.
ast-grep --lang python --pattern $'dict[str, type[ProtectModel]] MODEL_TO_CLASS {
  $$$
  $model_type: $_ {
    $$$
  }
  $$$
}' src/uiprotect/data/convert.py

Length of output: 674



Script:

#!/bin/bash
# Description: Verify that all possible values of `model_type` have corresponding classes in `MODEL_TO_CLASS`.

# Test: Search for the dictionary definition of `MODEL_TO_CLASS` and list all its key-value pairs.
ast-grep --lang python --pattern $'MODEL_TO_CLASS = {
  $$$
}' src/uiprotect/data/convert.py

Length of output: 93



Script:

#!/bin/bash
# Description: Locate the definition of `MODEL_TO_CLASS` and inspect its structure.

# Search for the `MODEL_TO_CLASS` definition in the codebase.
rg 'MODEL_TO_CLASS' --python

Length of output: 439



Script:

#!/bin/bash
# Description: Locate the definition of `MODEL_TO_CLASS` and inspect its structure.

# Search for the `MODEL_TO_CLASS` definition in Python files.
rg 'MODEL_TO_CLASS' --type py

Length of output: 254



Script:

#!/bin/bash
# Description: Display the contents of `src/uiprotect/data/convert.py` to inspect the `MODEL_TO_CLASS` dictionary.

# Display the contents of the file.
cat src/uiprotect/data/convert.py

Length of output: 2220

src/uiprotect/data/types.py (2)

112-115: The implementation of devices_key as a cached property is efficient for repeated accesses. This change aligns with the PR's goal of optimizing model type handling.


117-121: The method from_string simplifies the creation of ModelType instances from strings. Ensure that all possible strings are valid ModelType enums to avoid exceptions.

Verification successful

The strings passed to the ModelType.from_string method are values extracted from the action dictionary, specifically action["modelKey"]. Before calling ModelType.from_string, there is a check to ensure that model_key (which is action["modelKey"]) is in ModelType.values_set(). This validation ensures that only valid ModelType enums are passed to the from_string method.

  • src/uiprotect/data/bootstrap.py:
    • Line: model_key: str = action["modelKey"]
    • Validation: if model_key not in ModelType.values_set():

This confirms that the code already includes a check to ensure all possible strings are valid ModelType enums before calling the from_string method.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that all strings passed to `from_string` are valid `ModelType` enums.

# Test: Check for potential invalid enum values.
ast-grep --lang python --pattern $'ModelType.from_string($value)' src/uiprotect/data/types.py

Length of output: 94



Script:

#!/bin/bash
# Description: Verify that all strings passed to `from_string` are valid `ModelType` enums.

# Test: Check for potential invalid enum values in the entire codebase.
ast-grep --lang python --pattern $'ModelType.from_string($value)' 

Length of output: 66



Script:

#!/bin/bash
# Description: Verify the usage of `ModelType` and its `from_string` method in the entire codebase.

# Find the definition of `ModelType`.
ast-grep --lang python --pattern $'class ModelType($_) { $$$ }'

# Find all usages of `ModelType` in the codebase.
rg 'ModelType' --glob '!*.pyc' --glob '!__pycache__'

Length of output: 10442



Script:

#!/bin/bash
# Description: Extract lines containing `ModelType.from_string` in `src/uiprotect/data/bootstrap.py`.

# Extract lines with `ModelType.from_string`.
rg 'ModelType.from_string' src/uiprotect/data/bootstrap.py

Length of output: 183



Script:

#!/bin/bash
# Description: Extract context around `model_key` and `action` in `src/uiprotect/data/bootstrap.py`.

# Extract lines where `model_key` is defined or assigned.
rg 'model_key' src/uiprotect/data/bootstrap.py -A 3 -B 3

# Extract lines where `action` is defined or assigned.
rg 'action' src/uiprotect/data/bootstrap.py -A 3 -B 3

Length of output: 6403

src/uiprotect/data/bootstrap.py (2)

Line range hint 200-238: The refactoring to use ModelType.bootstrap_models_types_set() for initializing device dictionaries improves modularity and readability. Ensure that model_type.devices_key always corresponds to a valid attribute in the data dictionary to prevent runtime errors.

Verification successful

The ast-grep script successfully matched the pattern and verified the code segment. The presence of the data[key] assignment indicates that model_type.devices_key is being used correctly within the data dictionary.

  • Lines 200-217 in src/uiprotect/data/bootstrap.py show the correct usage of model_type.devices_key.

No issues were found with the usage of model_type.devices_key in the provided code.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that `model_type.devices_key` always corresponds to a valid attribute.

# Test: Check for potential attribute errors in data dictionary.
ast-grep --lang python --pattern $'for model_type in ModelType.bootstrap_models_types_set() {
  $model_type.devices_key: $_
}' src/uiprotect/data/bootstrap.py

Length of output: 672



Script:

#!/bin/bash
# Description: Verify that `model_type.devices_key` always corresponds to a valid attribute.

# Test: Check for potential attribute errors in data dictionary.
ast-grep --lang python --pattern $'for model_type in ModelType.bootstrap_models_types_set():\n    key = model_type.devices_key\n    items: dict[str, ProtectModel] = {}\n    for item in data[key]:\n        if (\n            api is not None\n            and api.ignore_unadopted\n            and not item.get("isAdopted", True)\n        ):\n            continue\n\n        ref = {"model": model_type, "id": item["id"]}\n        items[item["id"]] = item\n        data["idLookup"][item["id"]] = ref\n        if "mac" in item:\n            cleaned_mac = normalize_mac(item["mac"])\n            data["macLookup"][cleaned_mac] = ref\n    data[key] = items' src/uiprotect/data/bootstrap.py

Length of output: 2046


347-364: The handling of different model types in _process_add_packet is well-implemented. Verify that all model types in ModelType.bootstrap_models_types_set() are handled correctly in this method.

Verification successful

The _process_add_packet method correctly handles model types in ModelType.bootstrap_models_types_set(), as it includes a specific branch to process these model types. The bootstrap_models_types_set method itself returns a set of model types from ModelType.bootstrap_model_types(), ensuring that all relevant types are considered.

  • ModelType.EVENT and ModelType.NVR are explicitly handled.
  • Other model types in ModelType.bootstrap_models_types_set() are processed within the corresponding branch.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify handling of all model types in `_process_add_packet`.

# Test: Check for unhandled model types.
ast-grep --lang python --pattern $'def _process_add_packet($$$) {
  if $model_type in ModelType.bootstrap_models_types_set() {
    $$$
  }
}' src/uiprotect/data/bootstrap.py

Length of output: 519



Script:

#!/bin/bash
# Find the definition of `bootstrap_models_types_set` method in the repository.
ast-grep --lang python --pattern 'def bootstrap_models_types_set($$) { $$ }' 

# Find the usage of `bootstrap_models_types_set` in the repository to verify its handling in `_process_add_packet`.
rg 'bootstrap_models_types_set' 

Length of output: 936



Script:

#!/bin/bash
# Display the definition of `bootstrap_models_types_set` method in `src/uiprotect/data/types.py`.
rg --context 10 'def bootstrap_models_types_set' src/uiprotect/data/types.py

# Display the `_process_add_packet` method in `src/uiprotect/data/bootstrap.py` to verify the handling of model types.
rg --context 20 'def _process_add_packet' src/uiprotect/data/bootstrap.py

Length of output: 2304

src/uiprotect/api.py (2)

1149-1149: LGTM! The change from model_type.value to model_type.devices_key aligns with the PR objectives and should help optimize API requests.


1706-1706: Excellent refactor! Using model_type.devices_key in the adopt_device method enhances consistency and aligns perfectly with the PR's goal of optimizing model type handling.

src/uiprotect/data/user.py Show resolved Hide resolved
src/uiprotect/data/types.py Show resolved Hide resolved
@bdraco bdraco merged commit 57d7c10 into main Jun 14, 2024
8 checks passed
@bdraco bdraco deleted the avoid_multiple_model_converts branch June 14, 2024 00:48
@coderabbitai coderabbitai bot mentioned this pull request Dec 8, 2024
6 tasks
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.

1 participant