Skip to content

🧹 Refactor handle_messages to improve code health#136

Merged
DaTiC0 merged 5 commits into
mainfrom
fix-handle-messages-nesting-12277817126972455264
Jun 8, 2026
Merged

🧹 Refactor handle_messages to improve code health#136
DaTiC0 merged 5 commits into
mainfrom
fix-handle-messages-nesting-12277817126972455264

Conversation

@DaTiC0

@DaTiC0 DaTiC0 commented Jun 6, 2026

Copy link
Copy Markdown
Owner
  • 🎯 What: The deeply nested conditional based on len(parts) >= 3 in the handle_messages function inside notifications.py was refactored.
  • 💡 Why: Adding an early return reduces nesting depth, making the code much easier to read and maintain.
  • Verification: The refactoring preserves existing functionality by ensuring the log is appended with user_id=None before the early return, which matches the previous default fall-through behavior. Tests in test_notifications.py pass.
  • Result: The handle_messages function is flatter, cleaner, and more readable without altering functionality.

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

Summary by Sourcery

Enhancements:

  • Flatten handle_messages by introducing an early return for topics with fewer than three segments and moving the main logic out of a nested conditional.

The `handle_messages` function in `notifications.py` had a deeply nested structure for checking the MQTT topic path segments. This commit adds an early return (`if len(parts) < 3`) which significantly reduces the indentation and cognitive complexity of the function while preserving the exact same behavior (including appending the log with `user_id=None` when `len(parts) < 3`). Tests pass successfully.

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 the handle_messages function in notifications.py to use an early return for invalid MQTT topics, flattening control flow while preserving logging behavior and Firebase status update logic.

Sequence diagram for updated handle_messages early return logic

sequenceDiagram
    participant MQTTBroker
    participant handle_messages
    participant FirebaseRef
    participant MqttLog

    MQTTBroker->>handle_messages: handle_messages(_client, _userdata, message)
    activate handle_messages
    handle_messages->>handle_messages: topic.split('/')
    alt [len(parts) < 3]
        handle_messages->>MqttLog: _append_mqtt_log(topic, payload, Received, user_id=None)
    else [len(parts) >= 3]
        handle_messages->>handle_messages: user_id = parts[0], device_id = parts[1], msg_type = parts[2]
        alt [msg_type == status]
            handle_messages->>handle_messages: [build state_updates]
            alt [state_updates is not None]
                handle_messages->>handle_messages: _get_user_device_states_ref(user_id, device_id)
                handle_messages->>FirebaseRef: ref.update(state_updates)
            end
        end
        handle_messages->>MqttLog: _append_mqtt_log(topic, payload, Received, user_id=user_id)
        deactivate handle_messages
    end
Loading

File-Level Changes

Change Details Files
Refactor handle_messages control flow to early-return on malformed topics while preserving logging and Firebase update behavior.
  • Replace len(parts) >= 3 nested conditional with an early return when the topic has fewer than three segments
  • Log MQTT messages with user_id=None before returning for short topics to match previous fall-through behavior
  • Derive user_id, device_id, and msg_type unconditionally after the length check, simplifying the control flow for the status-handling block
  • Keep JSON decoding guards and Firebase state update logic intact under a flatter if msg_type == 'status' branch
  • Retain final MQTT log append using the resolved user_id for well-formed topics
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

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

  • Now that the early return has simplified the control flow, consider using tuple unpacking (e.g., user_id, device_id, msg_type = parts[:3]) to avoid repeated index access and make the intent of extracting these three components from the topic clearer.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Now that the early return has simplified the control flow, consider using tuple unpacking (e.g., `user_id, device_id, msg_type = parts[:3]`) to avoid repeated index access and make the intent of extracting these three components from the topic clearer.

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.

@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 the handle_messages function in notifications.py by introducing an early exit guard clause when the topic has fewer than three parts, which flattens the nested logic. Feedback on this change highlights that MQTT payloads are typically received as bytes rather than str in Python 3; therefore, the type check should be expanded to accept both str and bytes to prevent skipping JSON decoding and failing to update Firebase.

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 Outdated

if isinstance(payload, dict):
state_updates = payload
elif isinstance(payload, str):

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.

high

In Python 3, MQTT message payloads received via libraries like paho-mqtt are typically of type bytes rather than str. Checking only isinstance(payload, str) will cause the JSON decoding step to be skipped for standard bytes payloads, preventing Firebase from being updated. Since json.loads() natively supports bytes in Python 3.6+, we should allow both str and bytes types.

Suggested change
elif isinstance(payload, str):
elif isinstance(payload, (str, bytes)):

@DaTiC0

DaTiC0 commented Jun 8, 2026

Copy link
Copy Markdown
Owner Author

@jules this PR have merge conflicts that must be resolved!

@google-labs-jules

Copy link
Copy Markdown
Contributor

@jules this PR have merge conflicts that must be resolved!

I've resolved the merge conflicts and made sure that handle_messages works correctly with the upstream changes that extracted _handle_status_message! Tests are passing.

The upstream codebase introduced `_handle_status_message` while this branch introduced an early return on `len(parts) < 3`. This commit resolves the merge conflict, incorporating both the early return and the upstream refactoring that delegates handling to `_handle_status_message`. Tests are fully functional.
@DaTiC0

DaTiC0 commented Jun 8, 2026

Copy link
Copy Markdown
Owner Author

@jules rebase from main

@google-labs-jules

Copy link
Copy Markdown
Contributor

@jules rebase from main

I've rebased the branch from main, resolving the merge conflict while preserving the early return logic. All tests are passing successfully.

google-labs-jules Bot and others added 3 commits June 8, 2026 08:51
The upstream codebase introduced `_handle_status_message` while this branch introduced an early return on `len(parts) < 3`. This commit resolves the merge conflict, incorporating both the early return and the upstream refactoring that delegates handling to `_handle_status_message`. Tests are fully functional.
The upstream codebase introduced `_handle_status_message` while this branch introduced an early return on `len(parts) < 3`. This commit resolves the merge conflict, incorporating both the early return and the upstream refactoring that delegates handling to `_handle_status_message`. Tests are fully functional.

@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 558134b into main Jun 8, 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