Skip to content

Refactors environment MVC #19

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

Merged
merged 8 commits into from
May 6, 2024
Merged

Refactors environment MVC #19

merged 8 commits into from
May 6, 2024

Conversation

GabrielBarberini
Copy link
Collaborator

@GabrielBarberini GabrielBarberini commented Apr 28, 2024

  • adds pyproject.toml
  • runs black over project
  • refactors environment routes
  • refactors environment controllers
  • refactors environment repositories

Summary by CodeRabbit

  • New Features

    • Introduced enhanced environment management capabilities, including creating, updating, retrieving, and deleting environment settings.
    • Added logging for database connection closures to improve monitoring and troubleshooting.
  • Refactor

    • Refined the internal handling of environment objects for better performance and reliability.

Copy link
Contributor

coderabbitai bot commented Apr 28, 2024

Walkthrough

The recent updates focus on refining the EnvRepository and Repo classes. EnvRepository now uses internal properties for environment management and introduces enhanced getter and setter methods, alongside updated asynchronous operations for CRUD functionalities. In Repo, enhancements include a shift from destructor to an explicit asynchronous method for closing database connections, improving clarity and control over resource management.

Changes

Files Change Summary
.../environment.py Refactored EnvRepository with internal properties, updated CRUD methods, and error handling.
.../repo.py Introduced close_connection method with logging for better resource management.

🐇✨
A hop, a skip, a code deploy,
Changes abound, oh what joy!
Fields align, methods refine,
In the burrow of code, all is fine.
Celebrate the craft, as we define,
Each line with care, by design. 🌟
🐇💻


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.

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 a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.

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: 6

Out of diff range and nitpick comments (13)
lib/repositories/motor.py (1)

Line range hint 30-57: The create_motor and update_motor methods are correctly implemented and well-documented. However, there is an issue in the get_motor method.

- motor
+ Motor
lib/controllers/environment.py (5)

72-88: Enhance logging to include more details about the environment being created for better traceability.


105-126: Consider enhancing the logging to include more details about the environment retrieval process.


173-211: Enhance logging to include more details about the environment update process for better traceability.


215-244: Consider enhancing the logging to include more details about the environment deletion process.


247-287: Enhance logging to include more details about the simulation process for better traceability.

lib/controllers/flight.py (7)

116-117: Enhance logging to include more details about the flight creation process for better traceability.


116-117: Consider enhancing the logging to include more details about the flight retrieval process.


183-184: Enhance logging to include more details about the flight update process for better traceability.


222-223: Consider enhancing the logging to include more details about the environment update process.


262-263: Enhance logging to include more details about the rocket update process for better traceability.


304-305: Consider enhancing the logging to include more details about the flight deletion process.


340-341: Enhance logging to include more details about the simulation process for better traceability.

Comment on lines 29 to 30
def close_connection(self) -> None:
logging.info(f"[{datetime.now()}] Closing connection to database")
Copy link
Contributor

@coderabbitai coderabbitai bot Apr 28, 2024

Choose a reason for hiding this comment

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

The close_connection method attempts to use datetime.now() without importing datetime. This will raise an "undefined name 'datetime'" error.

+ import datetime

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.

Suggested change
def close_connection(self) -> None:
logging.info(f"[{datetime.now()}] Closing connection to database")
import datetime
def close_connection(self) -> None:
logging.info(f"[{datetime.now()}] Closing connection to database")

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

nice catch : d

Copy link
Contributor

Choose a reason for hiding this comment

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

@GabrielBarberini, thank you! I'm glad to be of help. If there's anything else you need, feel free to ask. 😊


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

else:
self.env_id = self.environment.__hash__()
self._env_id = hash(self._env)
Copy link
Contributor

@coderabbitai coderabbitai bot Apr 28, 2024

Choose a reason for hiding this comment

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

Consider using a more robust method for generating unique identifiers instead of hash.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

The use of hash here is to ensure unique identifiers also represent unique object data content

Copy link
Contributor

Choose a reason for hiding this comment

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

@GabrielBarberini, I understand your point about using hash to ensure that the identifiers reflect the unique data content of the objects. This approach can indeed help in maintaining a direct correlation between the object and its identifier, which is beneficial for certain use cases where data integrity is critical.

However, it's also important to consider some potential limitations of using hash functions for this purpose. Python's built-in hash function may lead to hash collisions, where different objects could end up with the same hash value, especially as the number of objects grows. Additionally, the hash values are not persistent across different sessions in Python, which might be a concern if identifiers need to remain consistent between system restarts or in distributed environments.

If these aspects are critical for your application, you might want to consider alternatives such as UUIDs, which can provide a high level of uniqueness and are consistent across sessions. Alternatively, if the hash-based approach is well-suited for your current needs, it might be beneficial to implement additional checks for collisions or to use a custom hash function designed to minimize such risks.

Let me know if you need further details on any of these points or if there's anything else I can help with!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Agreed!

For now, since we are in Beta the odds of hash colision are very low. But we do have to implement a custom hashing mechanism in the future, one that is not session-specific.

Thanks for bringing this up!

Copy link
Contributor

Choose a reason for hiding this comment

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

@GabrielBarberini, it's great to hear that you're considering these aspects for future development! Implementing a custom hashing mechanism that is consistent across sessions will definitely enhance the robustness of your application's identifier system. If you need any assistance or have questions about designing this mechanism when you start working on it, feel free to reach out. Best of luck with the ongoing Beta testing!


New Learnings Added
User: GabrielBarberini
PR: RocketPy-Team/Infinity-API#19
File: lib/repositories/environment.py:25-25
Timestamp: 2024-04-29T16:06:49.377Z
Learning: GabrielBarberini plans to implement a custom hashing mechanism in the future for the `EnvRepository` class that is not session-specific.

Note: Learnings are effective only in the context of specific code segments. To apply general coding guidelines, please configure review instructions.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

@@ -50,7 +52,9 @@ async def create_rocket(self, rocket_option: str = "Calisto") -> "InsertOneResul
else:
return InsertOneResult(acknowledged=True, inserted_id=None)

async def update_rocket(self, rocket_option: str = "Calisto") -> "Union[int, None]":
async def update_rocket(
self, rocket_option: str = "Calisto"

Choose a reason for hiding this comment

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

Self note: Need to discuss default values for all variables that get fed into the API. Mabey implement some random name generator or just keep the field an empty string "". No comments necessary now.

Copy link
Collaborator Author

@GabrielBarberini GabrielBarberini Apr 29, 2024

Choose a reason for hiding this comment

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

Agreed!

@Gui-FernandesBR and I had a discussion about default values in the past and decided to keep them to a minimum (to avoid whenever possible), but maybe for the integration between API and web-client we might have to discuss it again.

aasitvora99
aasitvora99 previously approved these changes Apr 29, 2024
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: 10

Comment on lines 50 to 58
try:
environment_to_dict = self.env.dict()
environment_to_dict["env_id"] = self.env_id
await self.collection.insert_one(environment_to_dict)
except Exception as e:
exc_str = parse_error(e)
logging.error(
f"[{datetime.now()}] repositories.environment.create_env: {exc_str}"
)
raise Exception(f"Error creating environment: {str(e)}") from e
Copy link
Contributor

@coderabbitai coderabbitai bot Apr 30, 2024

Choose a reason for hiding this comment

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

Refine exception handling to catch more specific exceptions rather than a general exception.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

In the future we might use a more specific error handling for DB connections, such as networking issues etc, but for now we are keeping it broad on purpose.

Copy link
Contributor

Choose a reason for hiding this comment

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

@GabrielBarberini, understood! Keeping the exception handling broad for now makes sense, especially as it allows for flexibility while the project's requirements are still evolving. If you decide to implement more specific error handling in the future, especially for DB connections, feel free to reach out if you need any assistance or reviews. Happy coding! 🚀

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: 5

Out of diff range and nitpick comments (1)
lib/controllers/environment.py (1)

227-227: Ensure that logging does not expose sensitive information, especially identifiers that could be used to infer system state or data.

@@ -1,2 +1,10 @@
# lib/__init__.py
import logging
Copy link
Contributor

@coderabbitai coderabbitai bot May 1, 2024

Choose a reason for hiding this comment

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

Consider removing or using the imported app from .api.app if it's not being used in this file.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I'm providing logging to the project upper level by importing it in __init__.py and then accessing the same import object from the other modules via from lib import logging

Copy link
Contributor

Choose a reason for hiding this comment

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

@GabrielBarberini, thank you for clarifying the setup of the logging configuration in lib/__init__.py. Centralizing the logging setup in this way is indeed a good practice as it ensures consistency and maintainability of logging across different modules of your application. If you encounter any issues or need further assistance with this setup, feel free to reach out. Happy coding!

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: 6

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 16009b9 and af2cfda.
Files selected for processing (2)
  • lib/repositories/environment.py (1 hunks)
  • lib/repositories/repo.py (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • lib/repositories/repo.py
Additional comments not posted (5)
lib/repositories/environment.py (5)

29-30: Getter method for env is correctly implemented.


33-34: Setter method for env is correctly implemented.


37-38: Getter method for env_id is correctly implemented.


41-42: Setter method for env_id is correctly implemented.


52-54: Ensure that self.env.dict() method exists in the Env model to prevent runtime errors.

from pymongo.results import InsertOneResult
from pymongo.results import DeleteResult
from lib import logging
from lib.repositories import parse_error
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider using a more specific import for parse_error to avoid potential namespace conflicts and improve code clarity.

Comment on lines +22 to +26
self._env = environment
if env_id:
self.env_id = env_id
self._env_id = env_id
else:
self.env_id = self.environment.__hash__()
self._env_id = str(hash(self._env))
Copy link
Contributor

Choose a reason for hiding this comment

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

The use of hash for generating _env_id when env_id is not provided is risky due to potential hash collisions and non-persistence across sessions. Consider using a more robust method like UUIDs.

Comment on lines +56 to +58
exc_str = parse_error(e)
logger.error(f"repositories.environment.create_env: {exc_str}")
raise Exception(f"Error creating environment: {str(e)}") from e
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider using more specific exceptions instead of a generic Exception to improve error clarity and maintainability.

environment_to_dict["env_id"] = self.environment.__hash__()

environment_to_dict = self.env.dict()
environment_to_dict["env_id"] = str(hash(self.env))
Copy link
Contributor

Choose a reason for hiding this comment

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

Avoid changing the env_id during an update to maintain data consistency. If a new identifier is needed, consider a separate method to handle this.

except Exception as e:
logger.error(f"repositories.environment.get_env: {str(e)}")
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider using more specific exceptions instead of a generic Exception to improve error clarity and maintainability.

except Exception as e:
logger.error(f"repositories.environment.delete_env: {str(e)}")
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider using more specific exceptions instead of a generic Exception to improve error clarity and maintainability.

@GabrielBarberini GabrielBarberini merged commit 297f6d8 into master May 6, 2024
2 of 3 checks passed
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