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

Refactor RQId / RQIdManager #8306

Merged
merged 2 commits into from
Aug 15, 2024
Merged

Refactor RQId / RQIdManager #8306

merged 2 commits into from
Aug 15, 2024

Conversation

SpecLad
Copy link
Contributor

@SpecLad SpecLad commented Aug 14, 2024

Motivation and context

  • Merge these into one class. These classes clearly deal with the same concept, so it doesn't make sense to divide the logic into two classes.

  • Turn build into an instance method (render). That way, the validation logic can be reused between it and the RQId constructor. Adjust the fields so that the first three fields can be specified as positional arguments.

  • Make the class frozen (I don't see a compelling case to mutate it).

  • Change string fields into corresponding enums. This reduces the amount of hardcoded string literals everywhere. Note that I had to move the enums into the models module to avoid a circular import.

  • Rename resource to target, because that's the name of the enum and the corresponding field in the API.

How has this been tested?

Unit tests.

Checklist

  • I submit my changes into the develop branch
  • [ ] I have created a changelog fragment
  • [ ] I have updated the documentation accordingly
  • [ ] I have added tests to cover my changes
  • [ ] I have linked related issues (see GitHub docs)
  • [ ] I have increased versions of npm packages if it is necessary
    (cvat-canvas,
    cvat-core,
    cvat-data and
    cvat-ui)

License

  • I submit my code changes under the same MIT License that covers the project.
    Feel free to contact the maintainers if that's a concern.

Summary by CodeRabbit

  • New Features

    • Enhanced request ID generation for importing projects, tasks, and data annotations, providing improved clarity and structure.
    • Introduced new classes for request handling: RequestStatus, RequestAction, RequestTarget, and RequestSubresource.
  • Improvements

    • Transitioned from string-based to enumerated types for request identifiers, enhancing type safety and maintainability.
    • Refactored request ID creation to streamline the process, promoting better encapsulation and readability across the application.
  • Bug Fixes

    • Updated error handling and logging for request IDs to better reflect the new structure.
  • Documentation

    • Adjustments made to method signatures and request handling to improve clarity and consistency in code usage.

Copy link
Contributor

coderabbitai bot commented Aug 14, 2024

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The recent changes in the CVAT application significantly enhance the management of request identifiers by introducing new classes and refactoring existing code. This update replaces the previous approach of using string-based identifiers with a more structured object-oriented design, utilizing enumerations for actions and targets. These improvements promote type safety, clarity, and maintainability across various modules involved in data import and export operations.

Changes

Files Change Summary
cvat/apps/engine/background_operations.py, cvat/apps/engine/backup.py, cvat/apps/engine/mixins.py, cvat/apps/engine/task.py, cvat/apps/engine/views.py Refactored request ID handling by replacing RQIdManager with the new RQId class, enhancing clarity and maintainability through structured object-oriented design.
cvat/apps/engine/models.py Introduced new classes (RequestStatus, RequestAction, RequestTarget, RequestSubresource) using Django's TextChoices, improving request status and action management.
cvat/apps/engine/serializers.py Removed local definitions of request-related classes, now referencing them from the models module, enhancing organization and maintainability.
cvat/apps/engine/permissions.py Modified permission logic to replace parsed_rq_id.resource with parsed_rq_id.target, refining how resource identifiers are handled.
cvat/apps/engine/rq_job_handler.py Updated RQId class to utilize enumerated types for fields, introduced immutability, and improved parsing and rendering methods, enhancing type safety and clarity.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant RequestHandler
    participant RQId
    participant Database

    User->>RequestHandler: Initiate request (Import/Export)
    RequestHandler->>RQId: Create request ID (Action, Target)
    RQId-->>RequestHandler: Return request ID
    RequestHandler->>Database: Process Import/Export with ID
    Database-->>RequestHandler: Return result
    RequestHandler-->>User: Send response
Loading

🐇 In the code where requests do play,
A rabbit hops in a bright new way!
With types and enums dancing in line,
Clarity reigns, oh how divine!
No more strings that cause us grief,
Just structured joy, like a carrot leaf! 🥕


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

Outside diff range, codebase verification and nitpick comments (1)
cvat/apps/engine/rq_job_handler.py (1)

Line range hint 93-135: Improve error handling in parse method.

The parse method could benefit from more specific error messages to aid debugging and user understanding.

except ValueError as ex:
    raise ValueError(f"Invalid RQ ID format: {rq_id!r}. Error: {str(ex)}") from ex
except Exception as ex:
    raise ValueError(f"An unexpected error occurred while parsing RQ ID: {rq_id!r}. Error: {str(ex)}") from ex
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 8d0095f and b1cc426.

Files selected for processing (9)
  • cvat/apps/engine/background_operations.py (3 hunks)
  • cvat/apps/engine/backup.py (3 hunks)
  • cvat/apps/engine/mixins.py (4 hunks)
  • cvat/apps/engine/models.py (2 hunks)
  • cvat/apps/engine/permissions.py (2 hunks)
  • cvat/apps/engine/rq_job_handler.py (3 hunks)
  • cvat/apps/engine/serializers.py (5 hunks)
  • cvat/apps/engine/task.py (2 hunks)
  • cvat/apps/engine/views.py (21 hunks)
Additional comments not posted (28)
cvat/apps/engine/rq_job_handler.py (3)

35-35: Marking RQId as immutable is a good practice.

The use of @attrs.frozen() ensures that instances of RQId are immutable, which is beneficial for maintaining data integrity.


37-58: Use of enumerations improves type safety.

Replacing string types with enumerations for action, target, and subresource enhances type safety and reduces the risk of errors due to invalid values.


61-63: Ensure consistent validation logic.

The __attrs_post_init__ method enforces validation logic for action and target. Ensure that similar validation is applied elsewhere if needed.

cvat/apps/engine/mixins.py (2)

278-281: Use of RQId enhances clarity and maintainability.

The refactoring to use RQId for request identifiers improves the structure and clarity of the code.


Line range hint 479-498: Renaming to rq_id_factory improves semantic clarity.

The renaming of rq_id_template to rq_id_factory better reflects its purpose and enhances code readability.

cvat/apps/engine/background_operations.py (2)

347-355: Use of RQId improves type safety and clarity.

The transition to using RQId for request identifiers enhances type safety and reduces the likelihood of errors.


586-592: Use of RQId enhances consistency and maintainability.

The adoption of RQId for request identifiers aligns with the refactoring goals and improves the consistency of the codebase.

cvat/apps/engine/models.py (4)

1199-1204: Good use of Django's TextChoices.

The RequestStatus class clearly defines the possible statuses for a request, enhancing readability and maintainability.


1206-1209: Well-defined action choices.

The RequestAction class uses TextChoices to define actions, which improves type safety and reduces the use of hardcoded strings.


1211-1214: Clear target definitions with TextChoices.

The RequestTarget class effectively uses TextChoices to specify request targets, aligning with best practices for clarity and maintainability.


1216-1219: Structured subresource definitions.

The RequestSubresource class provides a structured way to handle subresources, which promotes consistency and reduces errors.

cvat/apps/engine/backup.py (3)

42-46: Improved import statements with new enumerations.

The import of RQId and related enumerations (RequestAction, RequestTarget, RequestSubresource) enhances code clarity and reduces the risk of errors associated with hardcoded strings.


1018-1021: Refactored request ID generation in import_project.

The use of the RQId class to generate request IDs is a clear improvement. It encapsulates the parameters and uses the .render() method to produce the final ID, promoting a more structured approach.


1044-1047: Refactored request ID generation in import_task.

Similar to import_project, the import_task function now uses the RQId class for generating request IDs. This change enhances maintainability and aligns with the refactored design.

cvat/apps/engine/permissions.py (2)

1230-1230: Consistent use of target instead of resource.

The change from parsed_rq_id.resource to parsed_rq_id.target is consistent with the refactor. Ensure this change is applied throughout the file.

Also applies to: 1239-1239


1244-1244: Error message update aligns with refactor.

The error message now correctly references target, maintaining consistency with the refactor.

cvat/apps/engine/task.py (2)

30-30: LGTM! Imports for RequestAction and RequestTarget.

The addition of RequestAction and RequestTarget imports aligns with the refactoring goals to use enums for better clarity and maintainability.


53-53: LGTM! Improved request ID generation.

The change to generate the request ID using the RQId constructor with RequestAction.CREATE and RequestTarget.TASK enhances clarity and maintainability.

Additionally, ensure that this new usage of RQId is consistent across the codebase.

Verification successful

Consistent Usage of RQId Constructor Across Codebase

The RQId constructor is consistently used with enums (RequestAction and RequestTarget) across multiple files, confirming the refactoring's alignment with the codebase's design goals.

  • Files with consistent usage:
    • cvat/apps/engine/rq_job_handler.py
    • cvat/apps/engine/task.py
    • cvat/apps/engine/backup.py
    • cvat/apps/engine/mixins.py
    • cvat/apps/engine/views.py
    • cvat/apps/engine/background_operations.py
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the `RQId` constructor across the codebase to ensure consistency.

# Test: Search for the `RQId` constructor usage. Expect: Consistent usage with enums.
rg --type python -A 5 $'RQId('

Length of output: 92


Script:

#!/bin/bash
# Description: Verify the usage of the `RQId` constructor across the codebase to ensure consistency.

# Test: Search for the `RQId` constructor usage. Expect: Consistent usage with enums.
rg --type python -A 5 'RQId('

Length of output: 92


Script:

#!/bin/bash
# Description: Verify the usage of the `RQId` constructor across the codebase to ensure consistency.

# Test: Search for the `RQId` constructor usage. Expect: Consistent usage with enums.
rg --type python -A 5 'RQId\('

Length of output: 63


Script:

#!/bin/bash
# Description: Verify the usage of the `RQId` constructor across the codebase to ensure consistency.

# Test: Search for the `RQId` constructor usage. Expect: Consistent usage with enums.
rg --type py -A 5 'RQId\('

Length of output: 3591

cvat/apps/engine/serializers.py (3)

2206-2206: Use of centralized choice field is approved.

The change to use models.RequestTarget.choices improves maintainability by centralizing choice definitions.


2234-2234: Centralized choice field usage is approved.

The update to use models.RequestStatus.choices enhances consistency and maintainability by centralizing choice definitions.


2302-2305: Use of enumerations for actions and subresources is approved.

Replacing string literals with models.RequestAction.IMPORT and models.RequestSubresource.BACKUP enhances type safety and maintainability.

cvat/apps/engine/views.py (7)

283-284: Transition to IMPORT_RQ_ID_FACTORY is approved.

The use of functools.partial for IMPORT_RQ_ID_FACTORY enhances flexibility and readability by allowing dynamic request ID generation.


861-862: Transition to IMPORT_RQ_ID_FACTORY is approved.

The use of functools.partial for IMPORT_RQ_ID_FACTORY in TaskViewSet enhances flexibility and readability, similar to the change in ProjectViewSet.


1731-1732: Transition to IMPORT_RQ_ID_FACTORY is approved.

The use of functools.partial for IMPORT_RQ_ID_FACTORY in JobViewSet aligns with the changes in other viewsets, enhancing flexibility and readability.


Line range hint 3029-3043: Use of rq_id_factory enhances modularity.

The transition to using rq_id_factory for generating rq_id improves the modularity and reusability of the code.


Line range hint 3145-3157: Use of rq_id_factory enhances modularity.

The transition to using rq_id_factory for generating rq_id in _import_project_dataset improves the modularity and reusability of the code, consistent with changes in _import_annotations.


3326-3328: Consistent use of RQId.parse is approved.

The use of RQId.parse for parsing rq_id ensures consistency with the refactored RQId class, aligning with the refactoring objectives.


3363-3365: Consistent use of RQId.parse is approved.

The use of RQId.parse for parsing rq_id in _get_rq_job_by_id ensures consistency with the refactored RQId class, similar to _get_rq_jobs_from_queue.

Comment on lines +71 to +100
def render(
self,
) -> str:
if "import" == action:
return f"{action}:{resource}-{identifier}-{subresource}"
elif "export" == action:
if anno_format is None:
common_prefix = f"{self.action}:{self.target}-{self.identifier}"

if RequestAction.IMPORT == self.action:
return f"{common_prefix}-{self.subresource}"
elif RequestAction.EXPORT == self.action:
if self.format is None:
return (
f"{action}:{resource}-{identifier}-{subresource}-by-{user_id}"
f"{common_prefix}-{self.subresource}-by-{self.user_id}"
)
format_to_be_used_in_urls = anno_format.replace(" ", "_").replace(".", "@")
return f"{action}:{resource}-{identifier}-{subresource}-in-{format_to_be_used_in_urls}-format-by-{user_id}"
elif "create" == action:
assert "task" == resource
return f"{action}:{resource}-{identifier}"

format_to_be_used_in_urls = self.format.replace(" ", "_").replace(".", "@")
return f"{common_prefix}-{self.subresource}-in-{format_to_be_used_in_urls}-format-by-{self.user_id}"
elif RequestAction.CREATE == self.action:
return common_prefix
else:
raise ValueError(f"Unsupported action {action!r} was found")
assert False, f"Unsupported action {self.action!r} was found"
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor render method for clarity and maintainability.

The render method is well-structured but could benefit from further refactoring to reduce complexity and improve readability.

def render(self) -> str:
    common_prefix = f"{self.action}:{self.target}-{self.identifier}"
    if self.action == RequestAction.IMPORT:
        return f"{common_prefix}-{self.subresource}"
    if self.action == RequestAction.EXPORT:
        format_str = f"-in-{self.format.replace(' ', '_').replace('.', '@')}-format" if self.format else ""
        return f"{common_prefix}-{self.subresource}{format_str}-by-{self.user_id}"
    if self.action == RequestAction.CREATE:
        return common_prefix
    raise AssertionError(f"Unsupported action {self.action!r} was found")

@SpecLad
Copy link
Contributor Author

SpecLad commented Aug 15, 2024

@Marishka17 Mind taking a look?

Copy link
Contributor

@Marishka17 Marishka17 left a comment

Choose a reason for hiding this comment

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

LGTM

)

def __attrs_post_init__(self) -> None:
if self.action == RequestAction.CREATE and self.target != RequestTarget.TASK:
Copy link
Contributor

Choose a reason for hiding this comment

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

there are also a few more cases to be handled:

Suggested change
if self.action == RequestAction.CREATE and self.target != RequestTarget.TASK:
if (
self.action == RequestAction.CREATE
and self.target != RequestTarget.TASK
or self.action == RequestAction.IMPORT
and (
self.target != RequestTarget.PROJECT
and self.subresource == RequestSubresource.DATASET
or self.target == RequestTarget.PROJECT
and self.subresource == RequestSubresource.ANNOTATIONS
)
or self.action in (RequestAction.EXPORT, RequestAction.IMPORT)
and self.target == RequestTarget.JOB
and self.subresource == RequestSubresource.BACKUP
):

Copy link
Contributor Author

@SpecLad SpecLad Aug 15, 2024

Choose a reason for hiding this comment

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

I decided to redo this function entirely. My original check was adapted from an assert in RQIdManager.build, but on second thought, I don't think it's really needed, because it's not RQId's responsibility to decide which actions can be applied to which resources.

OTOH, it is its responsibility to make sure that the ID can be rendered to a string that can then be parsed back to the same ID. So I added checks that make sure certain fields are present/absent, depending on the action.

* Merge these into one class. These classes clearly deal with the same
  concept, so it doesn't make sense to divide the logic into two classes.

* Turn `build` into an instance method (`render`). That way, the validation
  logic can be reused between it and the `RQId` constructor. Adjust the
  fields so that the first three fields can be specified as positional
  arguments.

* Make the class frozen (I don't see a compelling case to mutate it).

* Change string fields into corresponding enums. This reduces the amount
  of hardcoded string literals everywhere. Note that I had to move the
  enums into the `models` module to avoid a circular import.

* Rename `resource` to `target`, because that's the name of the enum
  and the corresponding field in the API.
`RQId` wants an integer, but `pk` is a string.
Copy link

sonarcloud bot commented Aug 15, 2024

@SpecLad SpecLad merged commit ac9ff33 into cvat-ai:develop Aug 15, 2024
33 checks passed
@SpecLad SpecLad deleted the rq-id-refactor branch August 15, 2024 17:31
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