Skip to content

Add channel-backed MultiPacket response#349

Merged
leynos merged 7 commits intomainfrom
codex/implement-response-multipacket-variant
Sep 5, 2025
Merged

Add channel-backed MultiPacket response#349
leynos merged 7 commits intomainfrom
codex/implement-response-multipacket-variant

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Sep 4, 2025

Summary

  • extend Response with MultiPacket variant backed by a channel
  • exercise multi-packet responses with unit and cucumber tests
  • document channel-based responses and mark roadmap item complete

Testing

  • make fmt
  • make lint
  • make test
  • make markdownlint
  • make nixie

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

Summary by Sourcery

Introduce a channel-backed multi-packet response variant to the core Response type and fully integrate it across code, documentation, and tests.

New Features:

  • Add Response::MultiPacket variant using tokio mpsc channels for streaming frames

Enhancements:

  • Extend Debug impl and internal logic to support the new MultiPacket variant
  • Mark the MultiPacket roadmap item as completed and adjust related enumeration numbering

Documentation:

  • Document the MultiPacket variant in code comments and design guides with usage examples and lifecycle details
  • Update design and roadmap markdown to include the new channel-based response

Tests:

  • Add unit tests covering channel-backed response scenarios and resource management
  • Add cucumber BDD world, step definitions, and feature tests for multi-packet responses

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Sep 4, 2025

Reviewer's Guide

This PR extends the core Response enum with a channel-backed MultiPacket variant using a tokio mpsc receiver, updates debugging and documentation for the new variant, and verifies its behavior through unit and Cucumber tests.

Flow diagram for MultiPacket response lifecycle

flowchart TD
    A["Handler creates mpsc::channel (Sender, Receiver)"] --> B["Frames sent via Sender"]
    B --> C["Receiver yields frames in send order"]
    C --> D["Sender dropped after sending all frames"]
    D --> E["Receiver returns None, signaling end of stream"]
Loading

File-Level Changes

Change Details Files
Introduce a MultiPacket response variant backed by a Tokio mpsc channel receiver
  • Added MultiPacket variant to Response enum with doc comments explaining usage, lifecycle, and examples
  • Updated Debug impl to surface MultiPacket as "MultiPacket(..)"
  • Marked MultiPacket roadmap item complete
src/response.rs
docs/multi-packet-and-streaming-responses-design.md
docs/roadmap.md
Implement support structures and world for BDD tests
  • Created MultiPacketWorld in tests/world.rs for channel draining and message verification
  • Extended cucumber runner to include MultiPacketWorld
  • Added multi_packet_steps and multi_packet.feature for BDD scenarios
tests/world.rs
tests/cucumber.rs
tests/steps/multi_packet_steps.rs
tests/features/multi_packet.feature
Add unit tests validating MultiPacket behavior under various channel conditions
  • Test that messages are yielded in order
  • Test empty channel yields no messages
  • Test early sender drop stops further messages
  • Test handling of channel capacity with concurrent send task
tests/multi_packet.rs
Adjust documentation and numbering in auxiliary design docs
  • Updated rust-binary-router-library-design section numbering
  • Fixed numbering in mocking-network-outages-in-rust.md
docs/rust-binary-router-library-design.md
docs/mocking-network-outages-in-rust.md

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

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Sep 4, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Summary by CodeRabbit

  • New Features

    • Introduces multi‑packet streaming responses, allowing messages to be delivered sequentially with natural back‑pressure, while keeping the simple single‑frame path unchanged.
  • Documentation

    • Added design guidance for multi‑packet/streaming responses and updated the roadmap to reflect completion.
    • Minor heading and numbering clean-ups in related documents.
  • Tests

    • Added unit and BDD tests covering ordered delivery, empty streams, sender drop, and channel capacity scenarios to ensure robust multi‑packet behaviour.

Walkthrough

Add a Response::MultiPacket(tokio::sync::mpsc::Receiver<F>) variant, update Debug and docs, and add unit and BDD tests (world, steps, feature, cucumber wiring) that validate ordered delivery, empty streams and channel capacity behaviour.

Changes

Cohort / File(s) Summary of change
Core API
src/response.rs
Add Response::MultiPacket(mpsc::Receiver<F>); import tokio::sync::mpsc; extend Debug to include MultiPacket(..); add in-code documentation describing channel-based multi-packet delivery and lifecycle.
Documentation
docs/multi-packet-and-streaming-responses-design.md, docs/roadmap.md
Document the MultiPacket variant and channel semantics; mark roadmap item as completed; preserve single-frame path guidance.
Cucumber test harness
tests/cucumber.rs, tests/features/multi_packet.feature, tests/steps/mod.rs, tests/steps/multi_packet_steps.rs, tests/world.rs
Add MultiPacketWorld, feature scenarios, step definitions, and wire the world into the test runner; implement process/process_empty and verify/verify_empty flows using an mpsc channel.
Unit tests
tests/multi_packet.rs
Add async tests verifying Response::MultiPacket yields messages in order, handles empty sender, respects channel capacity/back-pressure and ordering across sender drops.
Minor docs formatting
docs/mocking-network-outages-in-rust.md, docs/rust-binary-router-library-design.md
Apply small heading/numbering formatting fixes with no behavioural changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant Handler
  participant Tx as "mpsc::Sender<F>"
  participant Rx as "mpsc::Receiver<F>"
  participant Consumer as "Runtime / Drainer"

  Client->>Handler: Send request
  Handler->>Tx: Create channel (tx, rx)
  Handler-->>Client: Return Response::MultiPacket(rx)
  Note over Handler,Tx: Handler sends frames via tx and drops/closes tx when done

  loop while rx yields frames
    Tx-->>Rx: send(frame)
    Rx-->>Consumer: recv() -> frame
    Consumer->>Consumer: Process frame
  end

  Rx-->>Consumer: None (channel closed)
  Consumer->>Client: Finalise response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

Packets march in tidy queue, ➡️
From tiny pipes of mpsc brew,
Frames drip-drip until they’re through,
Stream or channel—both will do,
Tests applaud in ordered hue,
Roadmap ticks a box or two. ✅

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/implement-response-multipacket-variant

🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

codescene-delta-analysis[bot]

This comment was marked as outdated.

sourcery-ai[bot]

This comment was marked as resolved.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (7)
src/response.rs (2)

74-76: Add From<mpsc::Receiver<F>> for ergonomics.

Enable rx.into() like other From impls to keep the API consistent.

 impl<F, E> From<Vec<F>> for Response<F, E> {
     fn from(v: Vec<F>) -> Self { Response::Vec(v) }
 }
+
+impl<F, E> From<mpsc::Receiver<F>> for Response<F, E> {
+    fn from(rx: mpsc::Receiver<F>) -> Self { Response::MultiPacket(rx) }
+}

1-31: Extend examples to include MultiPacket and annotate code fences.

Add a MultiPacket example and specify the language on fenced blocks for better docs rendering.

-//! ```
+//! ```rust
 //! use futures::{StreamExt, stream};
 //! use wireframe::Response;
@@
 //! let empty: Response<Frame, Error> = Response::Empty;
 //! ```
+//!
+//! ```rust,no_run
+//! # type Frame = u8;
+//! use wireframe::Response;
+//! let (_tx, rx) = tokio::sync::mpsc::channel::<Frame>(4);
+//! let multi: Response<Frame, ()> = Response::MultiPacket(rx);
+//! ```
docs/multi-packet-and-streaming-responses-design.md (2)

131-137: Align error conversion with implementation (from_io vs From<std::io::Error>).

The design doc shows an impl From<std::io::Error> for WireframeError<E>, but the code exposes WireframeError::from_io. Update the doc for consistency, or implement the From trait in code.

-// Implement `From<std::io::Error>` for ergonomics.
-impl<E> From<std::io::Error> for WireframeError<E> {
-    fn from(e: std::io::Error) -> Self {
-        WireframeError::Io(e)
-    }
-}
+impl<E> WireframeError<E> {
+    /// Convert an I/O error into a `WireframeError`.
+    pub fn from_io(e: std::io::Error) -> Self {
+        WireframeError::Io(e)
+    }
+}

245-256: Use the mandated markdownlint directive form.

Replace the block-wide MD013 disable with disable-next-line as required, and duplicate it for each long table line.

-<!-- markdownlint-disable MD013 -->
+<!-- markdownlint-disable-next-line MD013 -->

Replicate the directive before the header and each row that exceeds 80 columns.

tests/cucumber.rs (2)

3-7: Update module docs to list the new suite

Document the fourth suite to keep docs in sync with code.

 //! Orchestrates three distinct test suites:
-//! - `PanicWorld`: Tests server resilience during connection panics
-//! - `CorrelationWorld`: Tests correlation ID propagation in multi-frame responses
-//! - `StreamEndWorld`: Verifies end-of-stream signalling
+//! Orchestrates four distinct test suites:
+//! - `PanicWorld`: Tests server resilience during connection panics
+//! - `CorrelationWorld`: Tests correlation ID propagation in multi-frame responses
+//! - `StreamEndWorld`: Verifies end-of-stream signalling
+//! - `MultiPacketWorld`: Verifies ordered delivery from channel-backed multi-packet responses

10-15: Extend the example list with the new feature

Keep the doc example block exhaustive.

 //! ```text
 //! tests/features/connection_panic.feature    -> PanicWorld context
 //! tests/features/correlation_id.feature      -> CorrelationWorld context
 //! tests/features/stream_end.feature          -> StreamEndWorld context
+//! tests/features/multi_packet.feature        -> MultiPacketWorld context
 //! ```
tests/world.rs (1)

1-5: Fix module-level doc drift

Broaden the module doc; it no longer describes only panic tests.

-//! Test world state for Cucumber panic resilience tests.
+//! Test worlds for Cucumber integration suites:
+//! - Panic resilience during connection setup
+//! - Correlation ID propagation across frames
+//! - End-of-stream signalling
+//! - Multi-packet channel-backed responses (ordered delivery)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

💡 Knowledge Base configuration:

  • Jira integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between bb5eff1 and 47cbb8a.

📒 Files selected for processing (9)
  • docs/multi-packet-and-streaming-responses-design.md (2 hunks)
  • docs/roadmap.md (1 hunks)
  • src/response.rs (4 hunks)
  • tests/cucumber.rs (1 hunks)
  • tests/features/multi_packet.feature (1 hunks)
  • tests/multi_packet.rs (1 hunks)
  • tests/steps/mod.rs (1 hunks)
  • tests/steps/multi_packet_steps.rs (1 hunks)
  • tests/world.rs (4 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/*.rs: Use precise names; boolean names should start with is/has/should
Use en-GB-oxendict spelling and grammar in comments
Function documentation must include clear examples; test documentation should omit redundant examples
Keep code files ≤ 400 lines; split long switch/dispatch logic by feature; move large test data to external files
Disallow Clippy warnings
Fix warnings emitted during tests in code rather than silencing them
Extract helper functions for long functions; adhere to separation of concerns and CQRS
Group related parameters into meaningful structs when functions have many parameters
Consider using Arc for large error returns to reduce data size
Each Rust module must begin with a module-level //! comment describing purpose and utility
Document public APIs with Rustdoc /// comments to enable cargo doc generation
Prefer immutable data; avoid unnecessary mut
Handle errors with Result instead of panicking where feasible
Avoid unsafe code unless necessary and document any usage clearly
Place function attributes after doc comments
Do not use return in single-line functions
Use predicate functions for conditional criteria with more than two branches
Do not silence lints except as a last resort
Lint suppressions must be tightly scoped and include a clear reason
Prefer #[expect(..)] over #[allow(..)] for lints
Prefer .expect() over .unwrap()
Use concat!() to combine long string literals rather than escaping newlines
Prefer single-line function bodies where appropriate (e.g., pub fn new(id: u64) -> Self { Self(id) })
Prefer semantic error enums deriving std::error::Error via thiserror for inspectable conditions

Files:

  • tests/multi_packet.rs
  • tests/steps/mod.rs
  • tests/steps/multi_packet_steps.rs
  • tests/cucumber.rs
  • src/response.rs
  • tests/world.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.
  • Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.

  • 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.
  • Environment access (env::set_var and env::remove_var) are always unsafe in Rust 2024 and MUST be marked as such

    • For testing of functionality depending upon environment variables, dependency injection and the mockable crate are the preferred option.
    • If mockable cannot be used, env mutations in tests ...

Files:

  • tests/multi_packet.rs
  • tests/steps/mod.rs
  • tests/steps/multi_packet_steps.rs
  • tests/cucumber.rs
  • src/response.rs
  • tests/world.rs
{src,tests}/**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

Write unit and behavioural tests for new functionality

Files:

  • tests/multi_packet.rs
  • tests/steps/mod.rs
  • tests/steps/multi_packet_steps.rs
  • tests/cucumber.rs
  • src/response.rs
  • tests/world.rs
tests/**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

tests/**/*.rs: Use rstest fixtures for shared setup
Replace duplicated tests with #[rstest(...)] parameterised cases
Prefer mockall for mocks/stubs

Files:

  • tests/multi_packet.rs
  • tests/steps/mod.rs
  • tests/steps/multi_packet_steps.rs
  • tests/cucumber.rs
  • tests/world.rs
docs/**/*.md

📄 CodeRabbit inference engine (docs/documentation-style-guide.md)

docs/**/*.md: Use British English based on the Oxford English Dictionary (en-oxendict) for documentation text.
The word "outwith" is acceptable in documentation.
Keep US spelling when used in an API, for example color.
Use the Oxford comma in documentation text.
Treat company names as collective nouns in documentation (e.g., "Lille Industries are expanding").
Write headings in sentence case in documentation.
Use Markdown headings (#, ##, ###, etc.) in order without skipping levels.
Follow markdownlint recommendations for Markdown files.
Provide code blocks and lists using standard Markdown syntax.
Always provide a language identifier for fenced code blocks; use plaintext for non-code text.
Use - as the first level bullet and renumber lists when items change.
Prefer inline links using [text](url) or angle brackets around the URL; avoid reference-style links like [foo][bar].
Ensure blank lines before and after bulleted lists and fenced blocks in Markdown.
Ensure tables have a delimiter line below the header row in Markdown.
Expand any uncommon acronym on first use, for example, Continuous Integration (CI).
Wrap paragraphs at 80 columns in documentation.
Wrap code at 120 columns in documentation.
Do not wrap tables in documentation.
Use sequentially numbered footnotes referenced with [^1] and place definitions at the end of the file.
Where it adds clarity, include Mermaid diagrams in documentation.
When embedding figures, use ![alt text](path/to/image) and provide concise alt text describing the content.
Add a brief description before each Mermaid diagram in documentation for screen readers.

Document examples showing how to deprecate old message versions gracefully

docs/**/*.md: Use docs/ markdown as the source of truth for requirements and decisions
Proactively update docs/ when requirements, dependencies, or architecture change
Documentation must use en-GB-oxendict spelling and grammar (LICENSE name exempt)

When long lines are warranted in ...

Files:

  • docs/multi-packet-and-streaming-responses-design.md
  • docs/roadmap.md
**/*.md

📄 CodeRabbit inference engine (AGENTS.md)

**/*.md: Markdown paragraphs and bullet points must be wrapped at 80 columns
Markdown code blocks must be wrapped at 120 columns
Do not wrap tables and headings in Markdown
Use dashes (-) for list bullets in Markdown
Use GitHub-flavoured Markdown footnotes ([^1])

Files:

  • docs/multi-packet-and-streaming-responses-design.md
  • docs/roadmap.md

⚙️ CodeRabbit configuration file

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

  • Use en-GB-oxendict (-ize / -our) spelling and grammar
  • 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:

  • docs/multi-packet-and-streaming-responses-design.md
  • docs/roadmap.md
docs/**

📄 CodeRabbit inference engine (docs/wireframe-1-0-detailed-development-roadmap.md)

docs/**: Document async-stream as the canonical way to create streams imperatively
Write comprehensive user guides for Duplex Messaging & Pushes, Streaming Responses, and Message Fragmentation with runnable examples

Files:

  • docs/multi-packet-and-streaming-responses-design.md
  • docs/roadmap.md
🔇 Additional comments (8)
docs/roadmap.md (1)

197-199: Align type with implementation: spell out the receiver type generically.

Use the fully qualified type to match src/response.rs and docs/design for clarity.

-  - [x] Introduce a `Response::MultiPacket` variant that contains a channel
-    `Receiver<Message>`.
+  - [x] Introduce a `Response::MultiPacket` variant that contains a channel
+    `tokio::sync::mpsc::Receiver<F>`.
⛔ Skipped due to learnings
Learnt from: CR
PR: leynos/wireframe#0
File: docs/roadmap.md:0-0
Timestamp: 2025-08-17T16:48:14.261Z
Learning: Applies to docs/src/response.rs : Introduce Response::MultiPacket with a channel Receiver<Message>
docs/multi-packet-and-streaming-responses-design.md (1)

92-99: Confirm API text matches code (generic F, Receiver fully qualified).

Keep the MultiPacket(tokio::sync::mpsc::Receiver<F>) spelling in this section aligned with src/response.rs.

tests/steps/mod.rs (1)

7-7: LGTM: wire up multi-packet cucumber steps.

The step module inclusion is correct and scoped. No issues.

tests/features/multi_packet.feature (1)

1-4: LGTM: Scenario reads clearly and maps 1:1 to steps

Keep the steps minimal and declarative as you’ve done.

tests/cucumber.rs (1)

24-24: LGTM: Wire the world and run the suite

Imports and execution order look correct.

Also applies to: 31-31

tests/steps/multi_packet_steps.rs (1)

1-10: LGTM: Step definitions are lean and idiomatic

Keep step bodies thin and delegate to world helpers.

Run the script to ensure the steps module registers these step defs.

#!/bin/bash
# Verify tests/steps/mod.rs declares `mod multi_packet_steps;`
rg -nP '^\s*mod\s+multi_packet_steps\s*;' tests/steps/mod.rs -C1
tests/world.rs (2)

256-259: LGTM: Verify ordered delivery

Assertion expresses the contract crisply.


227-260: Verify docs and roadmap entries for the new Response::MultiPacket

Ensure public docs and roadmap reflect the new variant per repo guidelines.

#!/bin/bash
# Check docs mention `Response::MultiPacket` and channel semantics
rg -n 'Response::MultiPacket' docs -C2 || true
rg -nP 'multi-?packet|channel-?based responses' docs -C2 || true

# Check roadmap updated
rg -nP 'roadmap|Multi-?packet' docs -C2 || true

Comment thread src/response.rs
Comment thread src/response.rs
Comment thread tests/features/multi_packet.feature
Comment thread tests/multi_packet.rs
Comment thread tests/world.rs Outdated
Comment thread tests/world.rs Outdated
Comment thread tests/world.rs Outdated
Comment thread tests/world.rs Outdated
codescene-delta-analysis[bot]

This comment was marked as outdated.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/features/multi_packet.feature (1)

9-9: Terminate file with a trailing newline

Keep POSIX-friendly formatting and quieter diffs.

♻️ Duplicate comments (2)
tests/features/multi_packet.feature (1)

1-4: Add a feature tag for targeted runs

Enable selective execution of this suite.

Apply this diff:

+@multi_packet
 Feature: Multi-packet responses
   Scenario: messages from a multi-packet response are delivered sequentially
     When a multi-packet response emits messages
     Then all messages are received in order
tests/multi_packet.rs (1)

58-79: Exercise back-pressure with parameterised cases

Add rstest to cover varying capacities and message counts to stress FIFO and channel fullness.

Apply this diff after existing tests:

+#[rstest::rstest]
+#[case(1, 8)]
+#[case(2, 32)]
+#[case(4, 64)]
+#[tokio::test]
+async fn multi_packet_ordering_under_pressure(#[case] cap: usize, #[case] n: u8) {
+    let (tx, rx) = mpsc::channel(cap);
+    let send = tokio::spawn(async move {
+        for i in 0..n {
+            tx.send(TestMsg(i)).await.expect("send");
+        }
+        // drop sender by exiting task
+    });
+    let mut out = Vec::new();
+    let mut rx = if let Response::MultiPacket(r) = Response::MultiPacket(rx) { r } else { unreachable!() };
+    while let Some(m) = rx.recv().await { out.push(m); }
+    send.await.expect("join");
+    assert_eq!(out, (0..n).map(TestMsg).collect::<Vec<_>>());
+}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

💡 Knowledge Base configuration:

  • Jira integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 47cbb8a and a52617e.

📒 Files selected for processing (5)
  • src/response.rs (4 hunks)
  • tests/features/multi_packet.feature (1 hunks)
  • tests/multi_packet.rs (1 hunks)
  • tests/steps/multi_packet_steps.rs (1 hunks)
  • tests/world.rs (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/*.rs: Use precise names; boolean names should start with is/has/should
Use en-GB-oxendict spelling and grammar in comments
Function documentation must include clear examples; test documentation should omit redundant examples
Keep code files ≤ 400 lines; split long switch/dispatch logic by feature; move large test data to external files
Disallow Clippy warnings
Fix warnings emitted during tests in code rather than silencing them
Extract helper functions for long functions; adhere to separation of concerns and CQRS
Group related parameters into meaningful structs when functions have many parameters
Consider using Arc for large error returns to reduce data size
Each Rust module must begin with a module-level //! comment describing purpose and utility
Document public APIs with Rustdoc /// comments to enable cargo doc generation
Prefer immutable data; avoid unnecessary mut
Handle errors with Result instead of panicking where feasible
Avoid unsafe code unless necessary and document any usage clearly
Place function attributes after doc comments
Do not use return in single-line functions
Use predicate functions for conditional criteria with more than two branches
Do not silence lints except as a last resort
Lint suppressions must be tightly scoped and include a clear reason
Prefer #[expect(..)] over #[allow(..)] for lints
Prefer .expect() over .unwrap()
Use concat!() to combine long string literals rather than escaping newlines
Prefer single-line function bodies where appropriate (e.g., pub fn new(id: u64) -> Self { Self(id) })
Prefer semantic error enums deriving std::error::Error via thiserror for inspectable conditions

Files:

  • tests/multi_packet.rs
  • tests/steps/multi_packet_steps.rs
  • src/response.rs
  • tests/world.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.
  • Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.

  • 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.
  • Environment access (env::set_var and env::remove_var) are always unsafe in Rust 2024 and MUST be marked as such

    • For testing of functionality depending upon environment variables, dependency injection and the mockable crate are the preferred option.
    • If mockable cannot be used, env mutations in tests ...

Files:

  • tests/multi_packet.rs
  • tests/steps/multi_packet_steps.rs
  • src/response.rs
  • tests/world.rs
{src,tests}/**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

Write unit and behavioural tests for new functionality

Files:

  • tests/multi_packet.rs
  • tests/steps/multi_packet_steps.rs
  • src/response.rs
  • tests/world.rs
tests/**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

tests/**/*.rs: Use rstest fixtures for shared setup
Replace duplicated tests with #[rstest(...)] parameterised cases
Prefer mockall for mocks/stubs

Files:

  • tests/multi_packet.rs
  • tests/steps/multi_packet_steps.rs
  • tests/world.rs
🪛 GitHub Check: build-test
tests/world.rs

[failure] 241-241:
used underscore-prefixed binding

🪛 GitHub Actions: CI
tests/world.rs

[error] 241-241: Command 'cargo clippy --all-targets --all-features -- -D warnings' failed. Clippy error: 'used underscore-prefixed binding' at tests/world.rs:241:14.

🔇 Additional comments (6)
src/response.rs (3)

94-103: LGTM: Debug impl includes MultiPacket

Debug output remains stable and non-invasive by eliding inner state.


106-112: LGTM: idiomatic one-liners for From impls

Follow the style guide (no return in single-line functions).

Also applies to: 110-112


35-36: Remove suggestion to abstract Tokio dependency
Crate is explicitly built on Tokio I/O and runtime (README.md:14 “Transport adapter built on Tokio I/O”; 33 “runs the Tokio event loop”), so exposing tokio::sync::mpsc::Receiver in the public API aligns with documented intent.

Likely an incorrect or invalid review comment.

tests/multi_packet.rs (1)

9-25: LGTM: basic yield and drain path is correct

Validate that all sent messages are received and order is preserved.

tests/steps/multi_packet_steps.rs (1)

1-16: LGTM: step wiring matches feature scenarios

Step names and sync/async boundaries are correct; module docs use en-GB spelling.

tests/world.rs (1)

164-168: LGTM: verify() docs now correctly describe correlation-ID validation

Keep this focused on CID semantics.

Comment thread src/response.rs
Comment thread src/response.rs Outdated
Comment thread tests/world.rs Outdated
Comment thread tests/world.rs Outdated
Comment thread tests/world.rs Outdated
codescene-delta-analysis[bot]

This comment was marked as outdated.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
docs/rust-binary-router-library-design.md (2)

666-672: Fix broken code block and misplaced MD013 directive.

Close the code fence correctly, remove the HTML comment from inside the Rust snippet, and break the long chained call rather than disabling MD013 mid-snippet.

Apply:

-  Router::new()
-    .message_guarded(
-         MessageType::GenericCommand,
-         <!-- markdownlint-disable-next-line MD013 -->
-         | msg_header: &CommandHeader | msg_header.sub_type == CommandSubType::Special, handle_special_command ).message(MessageType::GenericCommand, handle_generic_command) // Fallback ``` |
+  Router::new()
+      .message_guarded(
+          MessageType::GenericCommand,
+          |hdr: &CommandHeader| hdr.sub_type == CommandSubType::Special,
+          handle_special_command,
+      )
+      .message(MessageType::GenericCommand, handle_generic_command);

1636-1642: Add missing footnote definitions in docs/rust-binary-router-library-design.md
Definitions currently cover only [^1]–[^6], yet the document references footnotes beyond [^6] (e.g. [^9–^14], [^19:known], [^23:A], …, [^270:]). Add definitions for each referenced footnote at the end of the file or renumber all footnotes sequentially so every reference has a matching definition.

♻️ Duplicate comments (4)
tests/multi_packet.rs (1)

58-79: Exercise back‑pressure with parameterised cases.

Add rstest cases varying capacity and message count; interleave small sleeps in sender to stress ordering.

Apply (append to file):

+#[rstest::rstest]
+#[case(1, 32u8)]
+#[case(4, 64u8)]
+#[tokio::test]
+async fn multi_packet_ordering_under_pressure(#[case] cap: usize, #[case] n: u8) {
+    let (tx, rx) = mpsc::channel(cap);
+    tokio::spawn(async move {
+        for i in 0..n {
+            tx.send(TestMsg(i)).await.expect("send");
+            if i % 7 == 0 { tokio::task::yield_now().await; }
+        }
+    });
+    let received = if let Response::MultiPacket(rx) = Response::MultiPacket(rx) {
+        drain_all(rx).await
+    } else { unreachable!() };
+    assert_eq!(received, (0..n).map(TestMsg).collect::<Vec<_>>());
+}
tests/world.rs (3)

221-233: Defend against state bleed across steps.

Clear messages at entry to make steps idempotent.

Apply:

     pub async fn process(&mut self) {
+        self.messages.clear();
         let (tx, ch_rx) = tokio::sync::mpsc::channel(4);

239-248: Defend against state bleed in process_empty.

Clear messages before draining.

Apply:

     pub async fn process_empty(&mut self) {
+        self.messages.clear();
         let (tx, ch_rx) = tokio::sync::mpsc::channel(4);

235-241: Fix inaccurate panic docs for empty path.

No sends occur; adjust summary and Panics section.

Apply:

-    /// Send no messages through the channel and record them.
-    ///
-    /// # Panics
-    /// Panics if sending to the channel fails.
+    /// Record zero messages from a closed channel.
+    ///
+    /// # Panics
+    /// This function does not panic.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

💡 Knowledge Base configuration:

  • Jira integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a52617e and 13b5b1a.

📒 Files selected for processing (4)
  • docs/mocking-network-outages-in-rust.md (1 hunks)
  • docs/rust-binary-router-library-design.md (3 hunks)
  • tests/multi_packet.rs (1 hunks)
  • tests/world.rs (2 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
docs/**/*.md

📄 CodeRabbit inference engine (docs/documentation-style-guide.md)

docs/**/*.md: Use British English based on the Oxford English Dictionary (en-oxendict) for documentation text.
The word "outwith" is acceptable in documentation.
Keep US spelling when used in an API, for example color.
Use the Oxford comma in documentation text.
Treat company names as collective nouns in documentation (e.g., "Lille Industries are expanding").
Write headings in sentence case in documentation.
Use Markdown headings (#, ##, ###, etc.) in order without skipping levels.
Follow markdownlint recommendations for Markdown files.
Provide code blocks and lists using standard Markdown syntax.
Always provide a language identifier for fenced code blocks; use plaintext for non-code text.
Use - as the first level bullet and renumber lists when items change.
Prefer inline links using [text](url) or angle brackets around the URL; avoid reference-style links like [foo][bar].
Ensure blank lines before and after bulleted lists and fenced blocks in Markdown.
Ensure tables have a delimiter line below the header row in Markdown.
Expand any uncommon acronym on first use, for example, Continuous Integration (CI).
Wrap paragraphs at 80 columns in documentation.
Wrap code at 120 columns in documentation.
Do not wrap tables in documentation.
Use sequentially numbered footnotes referenced with [^1] and place definitions at the end of the file.
Where it adds clarity, include Mermaid diagrams in documentation.
When embedding figures, use ![alt text](path/to/image) and provide concise alt text describing the content.
Add a brief description before each Mermaid diagram in documentation for screen readers.

Document examples showing how to deprecate old message versions gracefully

docs/**/*.md: Use docs/ markdown as the source of truth for requirements and decisions
Proactively update docs/ when requirements, dependencies, or architecture change
Documentation must use en-GB-oxendict spelling and grammar (LICENSE name exempt)

When long lines are warranted in ...

Files:

  • docs/mocking-network-outages-in-rust.md
  • docs/rust-binary-router-library-design.md
**/*.md

📄 CodeRabbit inference engine (AGENTS.md)

**/*.md: Markdown paragraphs and bullet points must be wrapped at 80 columns
Markdown code blocks must be wrapped at 120 columns
Do not wrap tables and headings in Markdown
Use dashes (-) for list bullets in Markdown
Use GitHub-flavoured Markdown footnotes ([^1])

Files:

  • docs/mocking-network-outages-in-rust.md
  • docs/rust-binary-router-library-design.md

⚙️ CodeRabbit configuration file

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

  • Use en-GB-oxendict (-ize / -our) spelling and grammar
  • 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:

  • docs/mocking-network-outages-in-rust.md
  • docs/rust-binary-router-library-design.md
docs/**

📄 CodeRabbit inference engine (docs/wireframe-1-0-detailed-development-roadmap.md)

docs/**: Document async-stream as the canonical way to create streams imperatively
Write comprehensive user guides for Duplex Messaging & Pushes, Streaming Responses, and Message Fragmentation with runnable examples

Files:

  • docs/mocking-network-outages-in-rust.md
  • docs/rust-binary-router-library-design.md
**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/*.rs: Use precise names; boolean names should start with is/has/should
Use en-GB-oxendict spelling and grammar in comments
Function documentation must include clear examples; test documentation should omit redundant examples
Keep code files ≤ 400 lines; split long switch/dispatch logic by feature; move large test data to external files
Disallow Clippy warnings
Fix warnings emitted during tests in code rather than silencing them
Extract helper functions for long functions; adhere to separation of concerns and CQRS
Group related parameters into meaningful structs when functions have many parameters
Consider using Arc for large error returns to reduce data size
Each Rust module must begin with a module-level //! comment describing purpose and utility
Document public APIs with Rustdoc /// comments to enable cargo doc generation
Prefer immutable data; avoid unnecessary mut
Handle errors with Result instead of panicking where feasible
Avoid unsafe code unless necessary and document any usage clearly
Place function attributes after doc comments
Do not use return in single-line functions
Use predicate functions for conditional criteria with more than two branches
Do not silence lints except as a last resort
Lint suppressions must be tightly scoped and include a clear reason
Prefer #[expect(..)] over #[allow(..)] for lints
Prefer .expect() over .unwrap()
Use concat!() to combine long string literals rather than escaping newlines
Prefer single-line function bodies where appropriate (e.g., pub fn new(id: u64) -> Self { Self(id) })
Prefer semantic error enums deriving std::error::Error via thiserror for inspectable conditions

Files:

  • tests/multi_packet.rs
  • tests/world.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.
  • Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.

  • 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.
  • Environment access (env::set_var and env::remove_var) are always unsafe in Rust 2024 and MUST be marked as such

    • For testing of functionality depending upon environment variables, dependency injection and the mockable crate are the preferred option.
    • If mockable cannot be used, env mutations in tests ...

Files:

  • tests/multi_packet.rs
  • tests/world.rs
{src,tests}/**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

Write unit and behavioural tests for new functionality

Files:

  • tests/multi_packet.rs
  • tests/world.rs
tests/**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

tests/**/*.rs: Use rstest fixtures for shared setup
Replace duplicated tests with #[rstest(...)] parameterised cases
Prefer mockall for mocks/stubs

Files:

  • tests/multi_packet.rs
  • tests/world.rs
🔍 Remote MCP

Additional Context for Reviewing PR #349

  • The pull request introduces its changes on the branch codex/implement-response-multipacket-variant, which is active and was last updated on September 5, 2025 (github.com).
  • As of that update, the feature branch contains 250 commits, compared to 235 commits on main, meaning it is 15 commits ahead of the default branch. Reviewers should ensure the branch is rebased or merged cleanly against the latest main to avoid any integration conflicts (github.com).
🔇 Additional comments (3)
docs/mocking-network-outages-in-rust.md (1)

56-57: Keep numbered list sequencing consistent.

The renumbered shutdown-signal item aligns with markdownlint and the docs guidelines. No further action.

tests/world.rs (2)

164-168: LGTM: focused verification docs.

The updated docstring precisely states the correlation‑ID check and panic behaviour.


1-4: Update module‑level docs to reflect all worlds.

Document correlation IDs, stream end, and multi‑packet worlds per docs guidelines (en‑GB, ≤80 cols).

Apply:

-//! Test world state for Cucumber panic resilience tests.
-//!
-//! Provides shared state management for behavioural tests verifying
-//! server resilience against connection task panics.
+//! Test worlds for Cucumber suites:
+//! - Panic resilience during connection setup
+//! - Correlation ID propagation across frames
+//! - End‑of‑stream signalling
+//! - Channel‑backed multi‑packet responses (ordered delivery)

Run:

Comment thread tests/multi_packet.rs Outdated
Comment thread tests/multi_packet.rs
codescene-delta-analysis[bot]

This comment was marked as outdated.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/world.rs (1)

1-4: Update module-level docs to reflect all worlds.

Document Panic, Correlation, StreamEnd, and MultiPacket worlds per guidelines.

Apply:

-//! Test world state for Cucumber panic resilience tests.
-//!
-//! Provides shared state management for behavioural tests verifying
-//! server resilience against connection task panics.
+//! Cucumber test worlds for integration suites:
+//! - Panic resilience during connection setup
+//! - Correlation ID propagation across frames
+//! - End-of-stream signalling
+//! - Multi-packet channel-backed responses (ordered delivery)
♻️ Duplicate comments (1)
tests/multi_packet.rs (1)

64-84: Parameterise to exercise back-pressure and larger sequences.

Add rstest-powered cases to cover multiple capacities and message counts and insert light delays to interleave.

Append:

+use tokio::time::{sleep, Duration};
+use rstest::rstest;
+
+#[rstest]
+#[case(1, 32u8)]
+#[case(2, 64u8)]
+#[case(4, 8u8)]
+#[tokio::test]
+async fn multi_packet_ordering_under_pressure(#[case] cap: usize, #[case] n: u8) {
+    let (tx, rx) = mpsc::channel(cap);
+    let sender = tokio::spawn(async move {
+        for i in 0..n {
+            tx.send(TestMsg(i)).await.expect("send");
+            if i % 3 == 0 { sleep(Duration::from_millis(1)).await; }
+        }
+    });
+    let received = drain_all(unwrap_rx(Response::MultiPacket(rx))).await;
+    sender.await.expect("join");
+    assert_eq!(received, (0..n).map(TestMsg).collect::<Vec<_>>());
+}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

💡 Knowledge Base configuration:

  • Jira integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 13b5b1a and cf7a40f.

📒 Files selected for processing (2)
  • tests/multi_packet.rs (1 hunks)
  • tests/world.rs (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/*.rs: Use precise names; boolean names should start with is/has/should
Use en-GB-oxendict spelling and grammar in comments
Function documentation must include clear examples; test documentation should omit redundant examples
Keep code files ≤ 400 lines; split long switch/dispatch logic by feature; move large test data to external files
Disallow Clippy warnings
Fix warnings emitted during tests in code rather than silencing them
Extract helper functions for long functions; adhere to separation of concerns and CQRS
Group related parameters into meaningful structs when functions have many parameters
Consider using Arc for large error returns to reduce data size
Each Rust module must begin with a module-level //! comment describing purpose and utility
Document public APIs with Rustdoc /// comments to enable cargo doc generation
Prefer immutable data; avoid unnecessary mut
Handle errors with Result instead of panicking where feasible
Avoid unsafe code unless necessary and document any usage clearly
Place function attributes after doc comments
Do not use return in single-line functions
Use predicate functions for conditional criteria with more than two branches
Do not silence lints except as a last resort
Lint suppressions must be tightly scoped and include a clear reason
Prefer #[expect(..)] over #[allow(..)] for lints
Prefer .expect() over .unwrap()
Use concat!() to combine long string literals rather than escaping newlines
Prefer single-line function bodies where appropriate (e.g., pub fn new(id: u64) -> Self { Self(id) })
Prefer semantic error enums deriving std::error::Error via thiserror for inspectable conditions

Files:

  • tests/multi_packet.rs
  • tests/world.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.
  • Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.

  • 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.
  • Environment access (env::set_var and env::remove_var) are always unsafe in Rust 2024 and MUST be marked as such

    • For testing of functionality depending upon environment variables, dependency injection and the mockable crate are the preferred option.
    • If mockable cannot be used, env mutations in tests ...

Files:

  • tests/multi_packet.rs
  • tests/world.rs
{src,tests}/**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

Write unit and behavioural tests for new functionality

Files:

  • tests/multi_packet.rs
  • tests/world.rs
tests/**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

tests/**/*.rs: Use rstest fixtures for shared setup
Replace duplicated tests with #[rstest(...)] parameterised cases
Prefer mockall for mocks/stubs

Files:

  • tests/multi_packet.rs
  • tests/world.rs
🔍 Remote MCP

Additional Context for Reviewing PR #349

  • The pull request introduces its changes on the branch codex/implement-response-multipacket-variant, which is active and was last updated on September 5, 2025 (github.com).
  • As of that update, the feature branch contains 250 commits, compared to 235 commits on main, meaning it is 15 commits ahead of the default branch. Reviewers should ensure the branch is rebased or merged cleanly against the latest main to avoid any integration conflicts (github.com).
⏰ Context from checks skipped due to timeout of 120000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-test
🔇 Additional comments (2)
tests/multi_packet.rs (1)

6-7: Derives are tight and appropriate.

Keep as-is; no unused traits derived.

tests/world.rs (1)

164-168: Doc correction reads well.

Accurately scopes CorrelationWorld verification to correlation IDs.

Comment thread tests/multi_packet.rs
Comment thread tests/world.rs
Comment thread tests/world.rs Outdated
Comment thread tests/world.rs
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Sep 5, 2025

@coderabbitai pause

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Sep 5, 2025

✅ Actions performed

Reviews paused.

codescene-delta-analysis[bot]

This comment was marked as outdated.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Sep 5, 2025

@coderabbitai pause

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Sep 5, 2025

✅ Actions performed

Reviews paused.

codescene-delta-analysis[bot]

This comment was marked as outdated.

Repository owner deleted a comment from coderabbitai Bot Sep 5, 2025
Repository owner deleted a comment from chatgpt-codex-connector Bot Sep 5, 2025
Repository owner deleted a comment from coderabbitai Bot Sep 5, 2025
Repository owner deleted a comment from chatgpt-codex-connector Bot Sep 5, 2025
Repository owner deleted a comment from coderabbitai Bot Sep 5, 2025
Repository owner deleted a comment from chatgpt-codex-connector Bot Sep 5, 2025
Repository owner deleted a comment from coderabbitai Bot Sep 5, 2025
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Sep 5, 2025

@sourcery-ai review

@leynos leynos merged commit 2f95cc0 into main Sep 5, 2025
5 checks passed
@leynos leynos deleted the codex/implement-response-multipacket-variant branch September 5, 2025 18:44
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 there - I've reviewed your changes and found some issues that need to be addressed.

  • Consider providing a unified Stream interface for MultiPacket responses (for example, implementing Stream for Response or adding an into_stream helper) so downstream code can consume frames without manual pattern matches and channel plumbing.
  • There’s duplicated drain-and-verify logic in the unit tests and Cucumber World steps—extract a shared helper to reduce boilerplate when testing MultiPacket message sequences.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider providing a unified Stream interface for MultiPacket responses (for example, implementing `Stream` for `Response` or adding an `into_stream` helper) so downstream code can consume frames without manual pattern matches and channel plumbing.
- There’s duplicated drain-and-verify logic in the unit tests and Cucumber `World` steps—extract a shared helper to reduce boilerplate when testing MultiPacket message sequences.

## Individual Comments

### Comment 1
<location> `tests/multi_packet.rs:64` </location>
<code_context>
+    assert_eq!(received, vec![TestMsg(1)]);
+}
+
+/// Handles more messages than the channel capacity allows.
+#[tokio::test]
+async fn multi_packet_handles_channel_capacity() {
+    let (tx, rx) = mpsc::channel(2);
+    let send_task = tokio::spawn(async move {
</code_context>

<issue_to_address>
Consider adding a test for channel send failures.

Add a test where the sender tries to send after the receiver is dropped, confirming that the send fails as expected.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
    assert_eq!(received, vec![TestMsg(1)]);
}
=======
    assert_eq!(received, vec![TestMsg(1)]);
}

/// Test that sending fails after the receiver is dropped.
#[tokio::test]
async fn multi_packet_send_fails_after_receiver_dropped() {
    let (tx, rx) = mpsc::channel::<TestMsg>(2);
    drop(rx); // Drop the receiver
    let result = tx.send(TestMsg(42)).await;
    assert!(result.is_err(), "Send should fail when receiver is dropped");
}
>>>>>>> REPLACE

</suggested_fix>

### Comment 2
<location> `src/response.rs:91` </location>
<code_context>
+    ///     }
+    /// }
+    /// ```
+    MultiPacket(mpsc::Receiver<F>),
     /// A response with no frames.
     Empty,
</code_context>

<issue_to_address>
Consider deprecating the MultiPacket variant and consolidating channel outputs into the Stream variant with a From<Receiver<F>> implementation.

```markdown
It looks like `MultiPacket` is just a special‐case of your existing `Stream` variant, which means you can consolidate channel outputs into `Response::Stream`.  You can then deprecate `MultiPacket` (keeping it around for backwards‐compat) and provide a `From<mpsc::Receiver<F>>` impl that automatically wraps the receiver into a boxed stream.  This removes the extra branch from day‐to‐day use and avoids duplicating the docs/lifecycle rules.

1. Mark `MultiPacket` as deprecated and simplify its doc to a one‐liner:
```rust
pub enum Response<F, E = ()> {
    Single(F),
    Vec(Vec<F>),
    Stream(FrameStream<F, E>),

    #[deprecated(
        note = "use `Response::Stream` (with `From<Receiver<F>>`) instead; \
                this will be removed in a future release"
    )]
    /// Deprecated alias for `Stream` of a `tokio::sync::mpsc::Receiver`.
    MultiPacket(tokio::sync::mpsc::Receiver<F>),

    Empty,
}
```

2. Add an `impl From<Receiver<F>> for Response<F, E>` so users can just do:
   `Response::from(rx)` and get a boxed stream under the hood:
```rust
use futures::{StreamExt, stream::Map};
use tokio::sync::mpsc;
use wireframe::{Response, WireframeError};

impl<F, E> From<mpsc::Receiver<F>> for Response<F, E> {
    fn from(rx: mpsc::Receiver<F>) -> Self {
        // map each `F` into `Ok(F)` and box the stream
        let s = rx.map(|frame| Ok::<F, WireframeError<E>>(frame));
        Response::Stream(Box::pin(s) as FrameStream<F, E>)
    }
}
```

3. Adjust your examples to use `Response::Stream(Box::pin(rx.map(Ok)))` or simply `Response::from(rx)`.

With this:
- All channel‐based fly‐away frames go through the single `Stream` variant.
- You collapse two almost‐identical branches into one.
- You avoid re‐writing all the lifecycle docs twice (just document channels as a use‐case in `FrameStream`).
- You naturally deprecate `MultiPacket` without breaking existing callers.
```
</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 tests/multi_packet.rs
Comment thread src/response.rs
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