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

Remove I/O in event loop for Home Assistant Core backup #5648

Merged
merged 2 commits into from
Feb 19, 2025

Conversation

agners
Copy link
Member

@agners agners commented Feb 19, 2025

Proposed change

The Home Assistant Core backup still contains some I/O in the event loop. Move all I/O into the 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
    • Streamlined the backup process with clearer status messages and improved error handling.
    • Enhanced the management of exclusions during backups to ensure a more consistent and reliable experience.
    • Updated method documentation for clarity.

@agners agners added the refactor A code change that neither fixes a bug nor adds a feature label Feb 19, 2025
The Home Assistant Core backup still contains some I/O in the event
loop. Move all I/O into the executor.
@agners agners force-pushed the remove-io-fron-evevnt-loop-in-ha-core-backup branch from 0d15b09 to 556de56 Compare February 19, 2025 16:23
@agners agners marked this pull request as ready for review February 19, 2025 16:24
Copy link
Contributor

coderabbitai bot commented Feb 19, 2025

📝 Walkthrough

Walkthrough

The changes update the backup method in the HomeAssistant class. The method’s docstring has been revised for clarity. The exclusion filter logic is refactored by introducing a new local function _is_excluded_by_filter, replacing the previous inline approach. The backup process now builds an exclusions list by copying a constant and conditionally appending an additional exclusion based on the exclude_database parameter. Additionally, the _write_tarfile function now accepts metadata explicitly, and the JSON file writing uses this metadata. Logging and error handling have also been streamlined.

Changes

File Changes Summary
supervisor/homeassistant/module.py - Updated backup method docstring for clarity
- Refactored exclusion logic by introducing _is_excluded_by_filter and removing the inline filter
- Builds exclusions list with optional database exclusion
- Adjusted _write_tarfile to accept metadata and updated JSON file writing
- Streamlined logging and error handling

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant HA as HomeAssistant
    participant EF as _is_excluded_by_filter
    participant WT as _write_tarfile
    participant WJ as write_json_file

    C->>HA: backup(tar_file, exclude_database)
    HA->>HA: Log backup start
    HA->>HA: Build exclusions list
    HA->>EF: Evaluate if file is excluded
    HA->>WT: Call _write_tarfile(metadata)
    WT->>WJ: Write JSON file using metadata
    HA->>HA: Log backup complete
    HA->>C: Return backup result
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 556de56 and a16ae4f.

📒 Files selected for processing (1)
  • supervisor/homeassistant/module.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • supervisor/homeassistant/module.py
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Build i386 supervisor
  • GitHub Check: Build armv7 supervisor
  • GitHub Check: Build armhf supervisor
  • GitHub Check: Build aarch64 supervisor
  • GitHub Check: Run tests Python 3.13.2

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

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

🧹 Nitpick comments (1)
supervisor/homeassistant/module.py (1)

412-449: Consider adding progress reporting for large backups.

While the current implementation effectively moves I/O out of the event loop, for large backup operations, it might be beneficial to add progress reporting.

 def _write_tarfile(metadata: dict[str, Any]) -> None:
     """Write tarfile."""
     with TemporaryDirectory(dir=self.sys_config.path_tmp) as temp:
         temp_path = Path(temp)
+        total_files = sum(1 for _ in self.sys_config.path_homeassistant.rglob('*') if _.is_file())
+        processed_files = 0
 
         # Store local configs/state
         try:
             write_json_file(temp_path.joinpath("homeassistant.json"), metadata)
         except ConfigurationFileError as err:
             raise HomeAssistantError(
                 f"Can't save meta for Home Assistant Core: {err!s}",
                 _LOGGER.error,
             ) from err
 
         try:
             with tar_file as backup:
                 # Backup metadata
                 backup.add(temp, arcname=".")
 
+                def _progress_callback(path: Path) -> None:
+                    """Report backup progress."""
+                    nonlocal processed_files
+                    processed_files += 1
+                    _LOGGER.debug("Backup progress: %d/%d files", processed_files, total_files)
 
                 # Backup data
                 atomic_contents_add(
                     backup,
                     self.sys_config.path_homeassistant,
                     file_filter=_is_excluded_by_filter,
+                    progress_callback=_progress_callback,
                     arcname="data",
                 )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 34939cf and 556de56.

📒 Files selected for processing (1)
  • supervisor/homeassistant/module.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run the Supervisor
  • GitHub Check: Run tests Python 3.13.2
🔇 Additional comments (4)
supervisor/homeassistant/module.py (4)

396-396: LGTM! Minor docstring improvement.

The docstring update from "config/ directory" to "config/directory" improves clarity.


398-411: Well-structured refactoring of exclusion filter logic.

The extraction of filter logic into _is_excluded_by_filter function improves code organization and readability. The function effectively:

  • Encapsulates the exclusion logic
  • Provides helpful debug logging
  • Uses clear variable names

412-443: Effective removal of I/O operations from event loop.

The refactoring successfully moves I/O operations into the executor by:

  1. Encapsulating tarfile operations in _write_tarfile
  2. Passing metadata explicitly instead of accessing instance state
  3. Using atomic_contents_add for safe file operations

This aligns perfectly with the PR's objective of removing I/O from the event loop.


445-451: Improved backup process flow with better error handling.

The changes enhance the backup process by:

  1. Using clear logging for start and completion
  2. Properly handling cleanup in the finally block
  3. Moving I/O operations to executor via sys_run_in_executor

This ensures the event loop remains responsive during backup operations.

@agners agners merged commit c8cc6fe into main Feb 19, 2025
20 checks passed
@agners agners deleted the remove-io-fron-evevnt-loop-in-ha-core-backup branch February 19, 2025 19:11
@github-actions github-actions bot locked and limited conversation to collaborators Feb 21, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
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