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

Open to executor #5678

Merged
merged 1 commit into from
Feb 28, 2025
Merged

Open to executor #5678

merged 1 commit into from
Feb 28, 2025

Conversation

mdegat01
Copy link
Contributor

@mdegat01 mdegat01 commented Feb 26, 2025

Proposed change

All calls to native open and pathlib.Path.open moved to executor.

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New feature (which adds functionality to the supervisor)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue:
  • Link to documentation pull request:
  • Link to cli pull request:
  • Link to client library pull request:

Checklist

  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass
  • There is no commented out code in this PR.
  • I have followed the development checklist
  • The code has been formatted using Ruff (ruff format supervisor tests)
  • Tests have been added to verify that the new code works.

If API endpoints or add-on configuration are added/changed:

Summary by CodeRabbit

  • Refactor
    • Enhanced asynchronous processing for file operations and profile validations, reducing blocking and improving overall system responsiveness.
    • Improved mount and unmount procedures by isolating key logic into dedicated asynchronous functions.
  • Documentation
    • Expanded in-code documentation to clarify asynchronous execution requirements.
  • Tests
    • Updated test assertions to verify service calls in a more order-agnostic manner.

@mdegat01 mdegat01 added the refactor A code change that neither fixes a bug nor adds a feature label Feb 26, 2025
@mdegat01 mdegat01 marked this pull request as ready for review February 27, 2025 19:38
Copy link
Contributor

coderabbitai bot commented Feb 27, 2025

📝 Walkthrough

Walkthrough

This pull request refactors several file and process operations across multiple modules to improve asynchronous behavior. Synchronous file I/O has been replaced by asynchronous execution via self.sys_run_in_executor in API asset reading, AppArmor profile validation, mount operations, and RAUCB file download. Additionally, multiple docstrings have been updated to indicate that these functions must run in an executor. A test file has also been adjusted for unordered comparison of expected calls.

Changes

File(s) Change Summary
supervisor/api/store.py Added _read_static_file to asynchronously read static files; updated API endpoints (icon, logo, changelog, documentation) to delegate file access to executor.
supervisor/host/apparmor.py Modified load_profile in AppArmorControl to call validate_profile asynchronously via executor for non-blocking validation.
supervisor/mounts/mount.py Refactored mount (in both Mount and CIFSMount classes) by extracting inner functions (ensure_empty_folder, write_credentials) and executing them via executor; updated unmount to await asynchronous file unlinking.
supervisor/os/manager.py Updated _download_raucb to open, write, and close files asynchronously using self.sys_run_in_executor, moving file operations from a synchronous context to a non-blocking one.
supervisor/store/data.py Expanded the docstring for _read_git_repository to note that it "Must be run in executor."
supervisor/store/repository.py Updated the validate and update methods to run validation asynchronously (using executor); enhanced the docstring of validate to include an executor requirement.
supervisor/utils/apparmor.py Added "Must be run in executor." note to the docstrings of get_profile_name, validate_profile, and adjust_profile.
supervisor/utils/common.py Updated docstrings for find_one_filetype, read_json_or_yaml_file, and write_json_or_yaml_file to indicate that they must be executed within an executor context.
supervisor/utils/yaml.py Modified docstrings of read_yaml_file and write_yaml_file by adding "Must be run in executor." (Functionality remains unchanged.)
tests/mounts/test_manager.py Replaced strict equality assertions with an unordered comparison using unorderable_list_difference; added an import for this helper function to accommodate potential variations in call order during mount operations.

Sequence Diagram(s)

sequenceDiagram
    participant Client as API Client
    participant API as API Endpoint
    participant Executor as Executor
    Client->>API: Request asset (icon/logo/changelog/docs)
    API->>Executor: Call _read_static_file(path)
    Executor-->>API: Return file content
    API-->>Client: Deliver asset data
Loading
sequenceDiagram
    participant Request as Profile Load Request
    participant AppArmor as AppArmorControl.load_profile
    participant Executor as Executor
    Request->>AppArmor: Initiate profile load (profile name, file)
    AppArmor->>Executor: Invoke validate_profile asynchronously
    Executor-->>AppArmor: Return validation result
    AppArmor-->>Request: Return profile load result (or error)
Loading
sequenceDiagram
    participant Caller as Mount Operation Caller
    participant Mount as Mount/CIFSMount
    participant Executor as Executor
    Caller->>Mount: Initiate mount()
    Mount->>Executor: Run inner function (ensure_empty_folder/write_credentials)
    Executor-->>Mount: Return function result
    Mount-->>Caller: Complete mount operation
Loading
sequenceDiagram
    participant RepoCaller as Repository Update Caller
    participant Repository as Repository.update
    participant Executor as Executor
    RepoCaller->>Repository: Trigger update()
    Repository->>Executor: Execute validate() asynchronously
    Executor-->>Repository: Return validation outcome
    Repository-->>RepoCaller: Update result delivered
Loading

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 151d4bd and 17d8743.

📒 Files selected for processing (10)
  • supervisor/api/store.py (6 hunks)
  • supervisor/host/apparmor.py (1 hunks)
  • supervisor/mounts/mount.py (2 hunks)
  • supervisor/os/manager.py (1 hunks)
  • supervisor/store/data.py (1 hunks)
  • supervisor/store/repository.py (2 hunks)
  • supervisor/utils/apparmor.py (2 hunks)
  • supervisor/utils/common.py (2 hunks)
  • supervisor/utils/yaml.py (2 hunks)
  • tests/mounts/test_manager.py (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • supervisor/utils/yaml.py
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Build armv7 supervisor
  • GitHub Check: Build armhf supervisor
  • GitHub Check: Build aarch64 supervisor
  • GitHub Check: Run tests Python 3.13.2
🔇 Additional comments (21)
supervisor/store/data.py (1)

77-80: Appropriate docstring addition

Adding the note "Must be run in executor" to the docstring clearly indicates this function performs operations that would block the event loop (file I/O operations) and needs to be executed in a separate thread. This aligns with how it's being used in the codebase at line 141.

supervisor/api/store.py (5)

72-79: Good encapsulation of synchronous file I/O operation

The new helper function nicely centralizes the synchronous file I/O operation that needs to be run in an executor. The docstring clearly indicates its execution requirement.


246-246: Properly uses executor for file I/O operations

Converting the direct file read to an executor-wrapped operation prevents blocking the event loop, improving overall system responsiveness.


255-255: Properly uses executor for file I/O operations

Good conversion from synchronous to asynchronous execution for reading the logo file.


269-269: Properly uses executor for file I/O operations

Correct implementation of asynchronous file reading for the changelog.


283-285: Properly uses executor for file I/O operations

The multi-line formatting of this executor call maintains good readability for longer parameter values.

supervisor/utils/common.py (3)

22-25: Helpful docstring addition

The added note "Must be run in executor" provides clear guidance to developers about how this function should be called, preventing potential event loop blocking.


33-36: Helpful docstring addition

Good documentation update indicating this file I/O function must be run in an executor context.


47-50: Helpful docstring addition

Proper documentation indicating file writing operations must be run in an executor context.

supervisor/host/apparmor.py (1)

74-76: Good conversion to asynchronous execution

Converting the synchronous validate_profile call to run in an executor is an important improvement to prevent blocking the event loop. This change maintains the same error handling logic while making the operation non-blocking.

supervisor/utils/apparmor.py (3)

15-18: Docstring update confirms executor requirement

The addition of "Must be run in executor" is consistent with the PR's objective to move file I/O operations into executor contexts for better asynchronous behavior.


48-51: Docstring update confirms executor requirement

This docstring update properly documents that this function performs file I/O operations and must be run within an executor to prevent blocking the event loop.


58-61: Docstring update confirms executor requirement

The docstring update consistently documents that this file I/O operation must be run in an executor, which aligns with the rest of the codebase changes.

supervisor/os/manager.py (1)

219-229: Good refactoring of file I/O to use executor

The changes properly refactor synchronous file operations to run in an executor, which prevents blocking the event loop. The addition of a finally block ensures the file is properly closed, which is a good practice.

-                # Download RAUCB file
-                with raucb.open("wb") as ota_file:
-                    while True:
-                        chunk = await request.content.read(1_048_576)
-                        if not chunk:
-                            break
-                        ota_file.write(chunk)
+                # Download RAUCB file
+                ota_file = await self.sys_run_in_executor(raucb.open, "wb")
+                try:
+                    while True:
+                        chunk = await request.content.read(1_048_576)
+                        if not chunk:
+                            break
+                        await self.sys_run_in_executor(ota_file.write, chunk)
+                finally:
+                    await self.sys_run_in_executor(ota_file.close)
tests/mounts/test_manager.py (2)

6-6: New import for test assertion

Adding the unorderable_list_difference import supports the updated test assertion logic.


115-154: Improved test assertion for unordered comparisons

Good change to use unorderable_list_difference instead of direct equality comparison. This makes the test more robust against changes in the order of calls while still ensuring all expected calls are present.

The test now accommodates variations in call order which might occur due to asynchronous execution, while maintaining the same validation rigor.

supervisor/store/repository.py (2)

77-80: Docstring update confirms executor requirement

This docstring update properly documents that the validation function must be run within an executor context, which is important for readers of the code to understand.


110-110: Function execution wrapped in executor

The change from direct method call to executor-wrapped call ensures the validation function runs in a non-blocking manner, consistent with the updated docstring.

-        if not self.validate():
+        if not await self.sys_run_in_executor(self.validate):
supervisor/mounts/mount.py (3)

282-299: Good refactoring to use executor for file operations.

This change moves directory operations (checking existence, creating directories, validating it's a directory, and checking if it's empty) into an executor using sys_run_in_executor. This is an improvement as it prevents blocking file I/O operations from running directly in the async context.


496-505: Well-structured credential file handling.

Moving the credential file operations to an executor is a good practice. The code also properly sets secure permissions (0o600) when creating the credentials file, ensuring only the owner can read/write the sensitive information.


511-511: Good change to use executor for file deletion.

Using sys_run_in_executor for unlinking the credentials file ensures that this potentially blocking I/O operation doesn't block the async context.

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
  • @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 or @coderabbitai title 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.

@mdegat01 mdegat01 mentioned this pull request Feb 28, 2025
14 tasks
Copy link
Member

@agners agners left a comment

Choose a reason for hiding this comment

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

LGTM

@agners agners merged commit 2274de9 into main Feb 28, 2025
20 checks passed
@agners agners deleted the open-to-executor branch February 28, 2025 08:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
cla-signed refactor A code change that neither fixes a bug nor adds a feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants