Skip to content

Refactor connection event handling#240

Merged
leynos merged 2 commits intomainfrom
codex/refactor-next_event-method-in-connection.rs
Aug 1, 2025
Merged

Refactor connection event handling#240
leynos merged 2 commits intomainfrom
codex/refactor-next_event-method-in-connection.rs

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Aug 1, 2025

Summary

  • split each select! branch of next_event into helper functions for shutdown, queue and stream polling
  • call these helpers within next_event to clarify intent

Testing

  • make fmt
  • make lint
  • make test

https://chatgpt.com/codex/tasks/task_e_688bf5b7b90083229683553b9138e8a1

Summary by Sourcery

Refactor the connection event loop by extracting each select! branch into dedicated async helper methods.

Enhancements:

  • Extract shutdown waiting into a handle_shutdown helper method.
  • Move high- and low-priority queue polling into handle_high and handle_low helper methods.
  • Extract response stream polling into a poll_response_stream helper method.
  • Simplify next_event by invoking the new helper methods in its select! branches instead of inline logic.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 1, 2025

Summary by CodeRabbit

  • Refactor
    • Improved internal event handling logic for more maintainable and reusable code. No changes to user-facing behaviour.
  • Documentation
    • Reformatted documentation and README files for better readability. No changes to content or instructions.

Walkthrough

Refactor the next_event method in ConnectionActor by extracting each tokio::select! branch into dedicated private async helper functions. Move the logic for shutdown, high and low priority message polling, and response stream polling into handle_shutdown, handle_high, handle_low, and handle_response_stream methods, preserving the original event handling flow and prioritisation.

Changes

Cohort / File(s) Change Summary
ConnectionActor Event Handling Refactor
src/connection.rs
Extract each tokio::select! branch in next_event into private async helper functions: handle_shutdown, handle_high, handle_low, and handle_response_stream. Add a generic async helper handle_event for polling optional mutable references. Preserve event flow and prioritisation.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ConnectionActor
    participant HighRx
    participant LowRx
    participant ResponseStream
    participant ShutdownToken

    Client->>ConnectionActor: Call next_event()
    alt Shutdown requested
        ConnectionActor->>ShutdownToken: Await cancellation
        ShutdownToken-->>ConnectionActor: Cancelled
        ConnectionActor-->>Client: Event::Shutdown
    else High priority message
        ConnectionActor->>HighRx: Poll for message
        HighRx-->>ConnectionActor: Message or None
        ConnectionActor-->>Client: Event::High
    else Low priority message
        ConnectionActor->>LowRx: Poll for message
        LowRx-->>ConnectionActor: Message or None
        ConnectionActor-->>Client: Event::Low
    else Response stream
        ConnectionActor->>ResponseStream: Poll for response
        ResponseStream-->>ConnectionActor: Response or None
        ConnectionActor-->>Client: Event::Response
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Possibly related PRs

Poem

Four helpers now stand in the code’s bright light,
Each polling an event, each handling it right.
No more tangled branches, just functions so neat—
The connection’s new rhythm is orderly, sweet.
With shutdown and messages, all in their place,
Refactoring brings a tidier pace!
🦀✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 533e9d1 and 703b3da.

📒 Files selected for processing (3)
  • AGENTS.md (4 hunks)
  • README.md (1 hunks)
  • src/connection.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.md

⚙️ CodeRabbit Configuration File

**/*.md: * Avoid 2nd person or 1st person pronouns ("I", "you", "we")

  • Use en-GB-oxendict (-ize / -our) spelling and grammar
  • Paragraphs and bullets must be wrapped to 80 columns, except where a long URL would prevent this (in which case, silence MD013 for that line)
  • Code blocks should be wrapped to 120 columns.
  • Headings must not be wrapped.
  • Documents must start with a level 1 heading
  • Headings must correctly increase or decrease by no more than one level at a time
  • Use GitHub-flavoured Markdown style for footnotes and endnotes.
  • Numbered footnotes must be numbered by order of appearance in the document.

Files:

  • AGENTS.md
  • README.md
**/*.rs

⚙️ CodeRabbit Configuration File

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.

Files:

  • src/connection.rs
🧠 Learnings (4)
📚 Learning: applies to **/*.md : documentation must use en-gb-oxendict spelling and grammar (with the exception ...
Learnt from: CR
PR: leynos/rstest-bdd#0
File: AGENTS.md:0-0
Timestamp: 2025-07-22T06:27:02.647Z
Learning: Applies to **/*.md : Documentation must use en-GB-oxendict spelling and grammar (with the exception of "license" which is to be left unchanged for community consistency).

Applied to files:

  • AGENTS.md
📚 Learning: applies to **/*.md : documentation must use en-gb-oxendict spelling and grammar. (exception: the nam...
Learnt from: CR
PR: leynos/comenq#0
File: AGENTS.md:0-0
Timestamp: 2025-07-27T00:57:05.353Z
Learning: Applies to **/*.md : Documentation must use en-GB-oxendict spelling and grammar. (EXCEPTION: the naming of the "LICENSE" file, which is to be left unchanged for community consistency.)

Applied to files:

  • AGENTS.md
📚 Learning: applies to docs/**/*.md : documentation must use en-gb-oxendict spelling and grammar (with the excep...
Learnt from: CR
PR: leynos/ddlint#0
File: AGENTS.md:0-0
Timestamp: 2025-07-18T18:35:14.639Z
Learning: Applies to docs/**/*.md : Documentation must use en-GB-oxendict spelling and grammar (with the exception of "license" which is to be left unchanged for community consistency).

Applied to files:

  • AGENTS.md
📚 Learning: applies to **/*.md : documentation must use en-gb-oxendict spelling and grammar, except for the nami...
Learnt from: CR
PR: leynos/femtologging#0
File: AGENTS.md:0-0
Timestamp: 2025-07-28T19:14:46.188Z
Learning: Applies to **/*.md : Documentation must use en-GB-oxendict spelling and grammar, except for the naming of the "LICENSE" file.

Applied to files:

  • AGENTS.md
🪛 LanguageTool
AGENTS.md

[locale-violation] ~47-~47: LICENSE must be spelled with a “c” when used as a noun in British English. Use “licence”.
Context: ...grammar. (EXCEPTION: the naming of the "LICENSE" file, which is to be left unchanged ...

(LICENCE_LICENSE_NOUN_SINGULAR)


[uncategorized] ~161-~161: Possible missing comma found.
Context: ...(>=) version requirements is strictly forbidden as they introduce unacceptable risk a...

(AI_HYDRA_LEO_MISSING_COMMA)

README.md

[grammar] ~87-~87: Please add a punctuation mark at the end of paragraph.
Context: ...a binary protocol server. See the [full example](docs/rust-binary-router-library-design...

(PUNCTUATION_PARAGRAPH_END)

🔇 Additional comments (10)
README.md (1)

85-89: Well-formatted line wrapping improves readability.

The sentence reformatting enhances readability whilst maintaining the original content and meaning.

AGENTS.md (5)

12-13: Proper line wrapping enhances readability.

The reformatted text maintains clarity whilst adhering to the 80-column wrapping guideline.


28-35: Clear formatting supports documentation standards.

The line breaks and formatting improvements make the documentation guidelines more readable whilst preserving all content.


47-48: Consistent formatting across documentation.

The line wrapping maintains the established 80-column standard for documentation.


158-162: Well-structured dependency management guidance.

The formatting improvements make the critical dependency requirements more readable and scannable.


169-170: Clear error handling guidance formatting.

The line breaks improve readability of the error handling recommendations.

src/connection.rs (4)

255-261: Clean refactor enhances code clarity.

The extraction of select! branches into dedicated helper functions successfully clarifies the intent of next_event whilst maintaining the biased priority ordering. The refactor achieves the stated PR objective of replacing inline logic with focused helper methods.


267-271: Well-focused shutdown handler.

The handle_shutdown function encapsulates shutdown logic clearly with appropriate documentation.


273-286: Excellent generic helper eliminates duplication.

The handle_event function provides a clean abstraction for the common polling pattern used by the queue and stream handlers. This addresses previous concerns about code duplication amongst the helper functions.


288-301: Consistent helper functions follow single responsibility.

The queue and stream handlers (handle_high, handle_low, handle_response_stream) appropriately leverage the generic handle_event helper whilst maintaining clear, focused responsibilities. The naming convention remains consistent across all helpers.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/refactor-next_event-method-in-connection.rs

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests 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 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.

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Aug 1, 2025

Reviewer's Guide

Extracts each branch of the tokio::select! in next_event into its own async helper, simplifying the control flow for shutdown, high/low queue polling, and response stream handling.

Flow diagram for event handling in next_event after refactor

flowchart TD
    A[next_event] --> B{tokio::select!}
    B -->|Shutdown| C[handle_shutdown]
    B -->|High queue| D[handle_high]
    B -->|Low queue| E[handle_low]
    B -->|Response stream| F[poll_response_stream]
    B -->|Else| G[Event::Idle]
    C --> H[Event::Shutdown]
    D --> I[Event::High]
    E --> J[Event::Low]
    F --> K[Event::Response]
Loading

File-Level Changes

Change Details Files
Replace inline select! branches with handler calls in next_event
  • Invoke handle_shutdown(token) instead of inline wait_shutdown branch
  • Invoke handle_high(rx) instead of inline high-priority queue poll
  • Invoke handle_low(rx) instead of inline low-priority queue poll
  • Invoke poll_response_stream(stream) instead of inline response poll
src/connection.rs
Add async helper functions for each event source
  • Define handle_shutdown to await cancellation and emit Shutdown
  • Define handle_high to poll the high-priority queue
  • Define handle_low to poll the low-priority queue
  • Define poll_response_stream to poll the response stream
src/connection.rs

Possibly linked issues

  • #0: PR extracts tokio::select! branches into helper functions, directly addressing the issue's refactor.

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

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey @leynos - I've reviewed your changes and found some issues that need to be addressed.

  • Consider renaming poll_response_stream to handle_response for consistency with the handle_* naming scheme.
  • You could extract a single generic helper to poll optional queues/streams and map the result to an Event, reducing the duplication between handle_high and handle_low.
  • These small async helpers introduce extra state machines; consider marking them #[inline] or converting them into synchronous poll functions to reduce overhead inside the select! macro.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider renaming poll_response_stream to handle_response for consistency with the handle_* naming scheme.
- You could extract a single generic helper to poll optional queues/streams and map the result to an Event, reducing the duplication between handle_high and handle_low.
- These small async helpers introduce extra state machines; consider marking them #[inline] or converting them into synchronous poll functions to reduce overhead inside the select! macro.

## Individual Comments

### Comment 1
<location> `src/connection.rs:267` </location>
<code_context>
         }
     }

+    /// Await cancellation and emit a shutdown event.
+    async fn handle_shutdown(token: CancellationToken) -> Event<F, E> {
+        Self::wait_shutdown(token).await;
</code_context>

<issue_to_address>
Consider inlining the poll calls or using a macro instead of adding four small async wrapper functions.

```rust
// Instead of 4 tiny async wrappers, inline the poll calls or use a small macro.
// Option A: Inline closures (closest to pre-refactor):
async fn next_event(&mut self, state: &ActorState) -> Event<F, E> {
    let high_avail = self.high_rx.is_some();
    let low_avail  = self.low_rx.is_some();
    let resp_avail = self.response.is_some() && !state.is_shutting_down();

    tokio::select! {
        biased;

        // shutdown
        () = Self::wait_shutdown(self.shutdown.clone()), if state.is_active() => {
            Event::Shutdown
        }

        // high priority queue
        res = Self::poll_optional(self.high_rx.as_mut(), Self::recv_push), if high_avail => {
            Event::High(res)
        }

        // low priority queue
        res = Self::poll_optional(self.low_rx.as_mut(), Self::recv_push), if low_avail => {
            Event::Low(res)
        }

        // response stream
        res = Self::poll_optional(self.response.as_mut(), |s| s.next()), if resp_avail => {
            Event::Response(res)
        }

        else => Event::Idle,
    }
}

// Option B: Use a tiny macro to collapse repetition
macro_rules! poll_branch {
    ($guard:expr, $rx:expr, $recv:expr, $cons:ident) => {
        res = Self::poll_optional($rx, $recv), if $guard => {
            Event::$cons(res)
        }
    }
}

async fn next_event(&mut self, state: &ActorState) -> Event<F, E> {
    let high_avail = self.high_rx.is_some();
    let low_avail  = self.low_rx.is_some();
    let resp_avail = self.response.is_some() && !state.is_shutting_down();

    tokio::select! {
        biased;

        () = Self::wait_shutdown(self.shutdown.clone()), if state.is_active() => {
            Event::Shutdown
        }

        poll_branch!(high_avail, self.high_rx.as_mut(), Self::recv_push, High);
        poll_branch!(low_avail,  self.low_rx.as_mut(), Self::recv_push, Low);
        poll_branch!(resp_avail, self.response.as_mut(), |s| s.next(), Response);

        else => Event::Idle,
    }
}

// Then remove `handle_shutdown`, `handle_high`, `handle_low`, and `poll_response_stream`.
```
</issue_to_address>

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.

Comment thread src/connection.rs
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 1, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 1, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
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: 2

♻️ Duplicate comments (1)
src/connection.rs (1)

255-262: Inline the trivial async wrappers to avoid needless Future allocations

handle_shutdown, handle_high, handle_low, and poll_response_stream wrap a single call each. Creating four separate async fns spawns four additional state-machines and allocates four extra Futures per tokio::select! iteration. Inline the calls (or use a tiny macro/closure) to keep the hot path lean and the codebase smaller.

- event = Self::handle_high(self.high_rx.as_mut()), if high_available => { event }
+ event = Self::poll_optional(self.high_rx.as_mut(), Self::recv_push), if high_available => {
+     Event::High(event)
+ }

Repeat for the remaining three branches.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6583724 and 533e9d1.

📒 Files selected for processing (1)
  • src/connection.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

⚙️ CodeRabbit Configuration File

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.

Files:

  • src/connection.rs

Comment thread src/connection.rs
Comment thread src/connection.rs Outdated
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 1, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 1, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 1, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 1, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@leynos leynos merged commit 569db7f into main Aug 1, 2025
5 checks passed
@leynos leynos deleted the codex/refactor-next_event-method-in-connection.rs branch August 1, 2025 17:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant