Skip to content

🧹 [code health] Refactor handle_messages in notifications.py#137

Merged
DaTiC0 merged 1 commit into
mainfrom
refactor-notifications-handle-messages-16033057587243757832
Jun 6, 2026
Merged

🧹 [code health] Refactor handle_messages in notifications.py#137
DaTiC0 merged 1 commit into
mainfrom
refactor-notifications-handle-messages-16033057587243757832

Conversation

@DaTiC0

@DaTiC0 DaTiC0 commented Jun 6, 2026

Copy link
Copy Markdown
Owner

🎯 What: Extracted the status message handling logic from the overly long handle_messages function in notifications.py into a new _handle_status_message helper function.
💡 Why: This refactoring significantly simplifies handle_messages, making it much easier to read, understand, and maintain. The separation of concerns improves code health.
Verification: Ran existing tests in test_notifications.py and test_multi_tenant.py and confirmed they still pass, ensuring that no functionality was broken by the extraction.
Result: Improved codebase readability and maintainability without altering existing functionality.


PR created automatically by Jules for task 16033057587243757832 started by @DaTiC0

Summary by Sourcery

Enhancements:

  • Extract status message handling from handle_messages into a new _handle_status_message helper to simplify the main MQTT message handler and improve readability.

Co-authored-by: DaTiC0 <13198638+DaTiC0@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@sourcery-ai

sourcery-ai Bot commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Refactors MQTT status message handling in notifications.py by extracting the Firebase update logic into a dedicated helper, simplifying handle_messages without changing behavior.

Sequence diagram for refactored MQTT status message handling

sequenceDiagram
    participant MQTT
    participant handle_messages
    participant _handle_status_message
    participant _get_user_device_states_ref
    participant FirebaseRef

    MQTT->>handle_messages: on_message(message)
    handle_messages->>handle_messages: _decode_payload(message.payload)
    handle_messages->>handle_messages: parse topic to msg_type
    alt msg_type is status
        handle_messages->>_handle_status_message: _handle_status_message(user_id, device_id, payload)
        alt payload is dict or JSON string
            _handle_status_message->>_get_user_device_states_ref: _get_user_device_states_ref(user_id, device_id)
            _get_user_device_states_ref-->>_handle_status_message: ref
            alt ref is not None
                _handle_status_message->>FirebaseRef: update(state_updates)
            end
        else non JSON payload
            _handle_status_message->>_handle_status_message: logger.debug(...)
        end
    end
    handle_messages->>handle_messages: _append_mqtt_log(topic, payload, 'Received', user_id)
Loading

File-Level Changes

Change Details Files
Extract MQTT status/Firebase update logic from handle_messages into a dedicated helper to improve readability and reuse.
  • Introduced a new _handle_status_message(user_id, device_id, payload) helper that parses the payload into state_updates and conditionally updates Firebase device state.
  • Moved the existing JSON parsing and error handling for status payloads from handle_messages into the new helper while preserving logging behavior.
  • Replaced the inline status-handling block in handle_messages with a single call to _handle_status_message when msg_type == 'status'.
notifications.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request refactors notifications.py by extracting the Firebase device status update logic from handle_messages into a dedicated helper function _handle_status_message. Feedback was provided to ensure that state_updates is verified as a dictionary before calling ref.update(), preventing potential runtime exceptions when the JSON payload decodes to a non-dictionary value.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread notifications.py
except (ValueError, TypeError):
logger.debug("Non-JSON status payload for %s/%s; skipping Firebase update", user_id, device_id)

if state_updates is not None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

If the payload is a valid JSON but not an object (e.g., a string, number, or boolean like "true" or "123"), json.loads will succeed and return a non-dictionary value. Calling ref.update() with a non-dictionary will raise an exception. To prevent this, verify that state_updates is a dictionary before attempting to update the reference.

Suggested change
if state_updates is not None:
if isinstance(state_updates, dict):

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've left some high level feedback:

  • In _handle_status_message, consider catching more specific exceptions (e.g., Firebase/DB-related errors) instead of a bare Exception so that unexpected failures aren't silently folded into a generic log.
  • To aid debugging, you might pass the MQTT topic or original message into _handle_status_message and include it in the debug/error logs, since knowing only user_id/device_id may be insufficient when multiple topics are involved.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `_handle_status_message`, consider catching more specific exceptions (e.g., Firebase/DB-related errors) instead of a bare `Exception` so that unexpected failures aren't silently folded into a generic log.
- To aid debugging, you might pass the MQTT topic or original message into `_handle_status_message` and include it in the debug/error logs, since knowing only `user_id/device_id` may be insufficient when multiple topics are involved.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@DaTiC0 DaTiC0 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ok

@DaTiC0 DaTiC0 merged commit 67cb2c3 into main Jun 6, 2026
7 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.

1 participant