Skip to content

Implement typed protocol error handling#180

Merged
leynos merged 5 commits intomainfrom
codex/implement-typed-wireframeerror-for-protocol-errors
Jul 5, 2025
Merged

Implement typed protocol error handling#180
leynos merged 5 commits intomainfrom
codex/implement-typed-wireframeerror-for-protocol-errors

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jul 5, 2025

Summary

  • extend WireframeProtocol with handle_error for recoverable protocol errors
  • support typed errors in ProtocolHooks and ConnectionActor
  • document WireframeError usage and new trait method
  • test protocol error handling and IO error propagation

Testing

  • cargo fmt --all
  • cargo clippy --all-targets --all-features -- -D warnings
  • cargo test
  • markdownlint *.md docs/**/*.md
  • mdformat-all README.md docs/**/*.md

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

Summary by Sourcery

Implement typed protocol error handling by extending the protocol trait with an error hook, updating the hooks and actor to support a generic error type, and ensuring protocol errors are handled gracefully while I/O errors propagate.

New Features:

  • Add handle_error method to WireframeProtocol trait
  • Enable typed protocol error callbacks in ProtocolHooks and ConnectionActor

Enhancements:

  • Recover from protocol errors in ConnectionActor while propagating I/O errors
  • Generalize ProtocolHooks over an error type and invoke error hooks
  • Update default protocol_hooks and hook construction to include typed error handler

Documentation:

  • Document WireframeError usage and examples in response.rs
  • Add handle_error hook documentation and example in hooks.rs

Tests:

  • Test that protocol errors trigger the error hook without terminating the connection
  • Test that I/O errors terminate the connection and return an error

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jul 5, 2025

Reviewer's Guide

Implements typed protocol error handling by adding a handle_error hook to the WireframeProtocol trait and ProtocolHooks, updating ConnectionActor to distinguish and propagate protocol vs I/O errors, enhancing documentation for WireframeError, and extending tests accordingly.

Sequence diagram for protocol error handling in ConnectionActor

sequenceDiagram
    participant ConnectionActor
    participant ProtocolHooks
    participant WireframeProtocol
    participant Context as ConnectionContext

    ConnectionActor->>ProtocolHooks: handle_response(Some(Err(WireframeError::Protocol(e))))
    ProtocolHooks->>WireframeProtocol: handle_error(e, &mut Context)
    WireframeProtocol-->>ProtocolHooks: (custom error handling)
    ProtocolHooks->>ConnectionActor: (returns)
    ConnectionActor->>ProtocolHooks: on_command_end(&mut Context)
    ProtocolHooks-->>ConnectionActor: (returns)
    Note over ConnectionActor: Protocol error handled, actor continues
Loading

Entity relationship diagram for ProtocolHooks and WireframeProtocol

erDiagram
    WIREFRAME_PROTOCOL ||--o{ PROTOCOL_HOOKS : "implements"
    PROTOCOL_HOOKS {
        on_connection_setup Option
        before_send Option
        on_command_end Option
        handle_error Option
    }
    WIREFRAME_PROTOCOL {
        Frame
        ProtocolError
    }
Loading

Class diagram for updated protocol error handling

classDiagram
    class WireframeProtocol {
        +on_connection_setup(PushHandle<Frame>, &mut ConnectionContext)
        +before_send(&mut Frame, &mut ConnectionContext)
        +on_command_end(&mut ConnectionContext)
        +handle_error(ProtocolError, &mut ConnectionContext)
        <<trait>>
        type Frame
        type ProtocolError
    }

    class ProtocolHooks {
        +on_connection_setup: Option<OnConnectionSetupHook<F>>
        +before_send: Option<BeforeSendHook<F>>
        +on_command_end: Option<OnCommandEndHook>
        +handle_error: Option<HandleErrorHook<E>>
        +on_connection_setup(PushHandle<F>, &mut ConnectionContext)
        +before_send(&mut F, &mut ConnectionContext)
        +on_command_end(&mut ConnectionContext)
        +handle_error(E, &mut ConnectionContext)
        +from_protocol(protocol: Arc<P>)
        <<generic<F, E>>
    }

    class ConnectionActor {
        -hooks: ProtocolHooks<F, E>
        +run(&mut self, out: &mut Vec<F>) -> Result<(), WireframeError<E>>
        +handle_response(res: Option<Result<F, WireframeError<E>>>, out: &mut Vec<F>, state: &mut State) -> Result<(), WireframeError<E>>
        <<generic<F, E>>
    }

    WireframeProtocol <|.. ProtocolHooks : uses
    ProtocolHooks <|-- ConnectionActor : member

    class WireframeError {
        <<enum<E=()>>
        +Protocol(E)
        +Io(std::io::Error)
    }
Loading

File-Level Changes

Change Details Files
Extend protocol trait and hooks to support typed errors
  • Added handle_error to WireframeProtocol with default implementation and docs
  • Introduced HandleErrorHook type alias and handle_error field in ProtocolHooks
  • Generalized ProtocolHooks over frame type F and error type E (default impl, methods, from_protocol)
src/hooks.rs
Update ConnectionActor to handle typed errors
  • Parameterized hooks on error type E and updated constructors to accept ProtocolHooks<F, E>
  • Modified run/handle_response to invoke handle_error for protocol errors and mark closed, while propagating I/O errors
  • Adjusted termination logic so protocol errors don’t abort the actor
src/connection.rs
Enhance WireframeError and Response documentation for generic errors
  • Added examples showing conversion of protocol and I/O errors into WireframeError
src/response.rs
Adjust application API to use generic ProtocolHooks
  • Changed App::protocol_hooks signature to return ProtocolHooks<Vec, ()>
src/app.rs
Add and update tests for protocol and I/O error handling
  • Added tests for handle_error hook invocation and for I/O errors terminating the connection
  • Updated existing tests to explicitly specify ProtocolHooks::<u8, ()> defaults and to construct ConnectionActor with hooks
tests/connection_actor.rs

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 Jul 5, 2025

Summary by CodeRabbit

  • New Features

    • Introduced typed protocol error handling, allowing protocol-specific errors to be managed via a new error hook and callback system.
    • Enhanced documentation with examples and diagrams for protocol error handling.
  • Bug Fixes

    • Improved error differentiation so that protocol errors are handled without terminating connections, while I/O errors still close the connection.
  • Tests

    • Added and updated tests to verify protocol error handling, logging, and connection termination on I/O errors.
  • Documentation

    • Updated design documents to reflect the new typed protocol error handling and marked related roadmap items as complete.
  • Chores

    • Added the serial_test crate as a development dependency.

Summary by CodeRabbit

  • New Features

    • Added support for protocol-specific error handling via new callback hooks, allowing custom responses to protocol errors without terminating connections.
  • Bug Fixes

    • Improved error handling in connections to differentiate between protocol errors (now handled gracefully) and I/O errors (which still terminate the connection).
  • Documentation

    • Added example usage to the error type documentation for clearer guidance.
  • Tests

    • Enhanced tests to verify protocol error handling and I/O error propagation, ensuring correct behaviour of error hooks and connection termination.

Walkthrough

The changes introduce a generic error parameter to the ProtocolHooks and related types, enabling protocol-specific error handling via a new handle_error hook. The ConnectionActor now differentiates between protocol and I/O errors, invoking the error hook for protocol errors without terminating the actor. Tests are updated to verify the new error handling behaviour.

Changes

File(s) Change Summary
src/app.rs Changed WireframeApp::protocol_hooks return type to ProtocolHooks<Vec<u8>, ()>.
src/connection.rs Updated ConnectionActor and methods to use ProtocolHooks<F, E>. Enhanced error handling in handle_response.
src/hooks.rs Added handle_error to WireframeProtocol and ProtocolHooks. Extended hooks to handle protocol errors.
src/response.rs Added documentation with usage example to WireframeError.
tests/connection_actor.rs Updated and added tests for protocol and I/O error handling, using new handle_error hook.
docs/asynchronous-outbound-messaging-design.md Added section on typed protocol errors and error handling flow with diagrams.
docs/asynchronous-outbound-messaging-roadmap.md Marked "Typed WireframeError" checklist item as complete.
Cargo.toml Added serial_test crate as a dev-dependency for test serialization.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ConnectionActor
    participant ProtocolHooks
    participant Protocol

    Client->>ConnectionActor: Send/receive frames
    ConnectionActor->>ProtocolHooks: before_send / on_command_end
    ConnectionActor->>Protocol: Process frame
    Protocol-->>ConnectionActor: Result or ProtocolError
    alt ProtocolError
        ConnectionActor->>ProtocolHooks: handle_error(error, ctx)
        ProtocolHooks-->>ConnectionActor: (handled, continue)
    else IO Error
        ConnectionActor-->>Client: Return WireframeError (terminates)
    end
Loading

Possibly related PRs

Poem

A rabbit hopped through error’s maze,
Now hooks can catch what protocols raise.
No longer does a glitch mean doom—
Errors handled, plenty of room!
With tests that check each careful leap,
The code grows strong, the bugs asleep.
🐇✨

✨ 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/implement-typed-wireframeerror-for-protocol-errors

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

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 they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `src/connection.rs:368` </location>
<code_context>
                 out.push(frame);
             }
+            Some(Err(WireframeError::Protocol(e))) => {
+                self.hooks.handle_error(e, &mut self.ctx);
+                state.mark_closed();
+                self.hooks.on_command_end(&mut self.ctx);
</code_context>

<issue_to_address>
Do not consume protocol errors silently; ensure they are logged or observable for debugging.

Currently, protocol errors are passed to the `handle_error` hook and then the command is ended, but there is no guarantee that the error is logged or otherwise made observable. This could make debugging difficult if the hook is a no-op. Consider at least logging the error or providing a default observable behavior.
</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
out.push(frame);
}
Some(Err(WireframeError::Protocol(e))) => {
self.hooks.handle_error(e, &mut self.ctx);
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.

issue (review_instructions): Do not consume protocol errors silently; ensure they are logged or observable for debugging.

Currently, protocol errors are passed to the handle_error hook and then the command is ended, but there is no guarantee that the error is logged or otherwise made observable. This could make debugging difficult if the hook is a no-op. Consider at least logging the error or providing a default observable behavior.

Review instructions:

Path patterns: **/*

Instructions:
Create code-review comments for ALL issues. Avoid making general observations or non-specific feedback if at all possible.

Don't hold back. Review changes as if your life depends upon it.

Use the imperative mood when writing pull request review feedback.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fe4508f and 34c0a10.

📒 Files selected for processing (5)
  • src/app.rs (1 hunks)
  • src/connection.rs (6 hunks)
  • src/hooks.rs (4 hunks)
  • src/response.rs (1 hunks)
  • tests/connection_actor.rs (3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`**/*.rs`: Comment why, not what. Explain assumptions, edge cases, trade-offs, o...

**/*.rs: Comment why, not what. Explain assumptions, edge cases, trade-offs, or complexity. Don't echo the obvious.
Comments must use en-GB-oxendict spelling and grammar.
Function documentation must include clear examples.
Every module must begin with a module level (//!) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
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.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Prefer .expect() over .unwrap().
Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Avoid unsafe code unless absolutely necessary and document any usage clearly.

📄 Source: CodeRabbit Inference Engine (AGENTS.md)

List of files the instruction was applied to:

  • src/response.rs
  • src/app.rs
  • tests/connection_actor.rs
  • src/connection.rs
  • src/hooks.rs
`**/*.rs`: * Seek to keep the cyclomatic complexity of functions no more than 12...

**/*.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 must use en-GB-oxendict 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/

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • src/response.rs
  • src/app.rs
  • tests/connection_actor.rs
  • src/connection.rs
  • src/hooks.rs
🧬 Code Graph Analysis (2)
tests/connection_actor.rs (2)
src/connection.rs (4)
  • new (101-114)
  • new (444-453)
  • default (50-55)
  • with_hooks (118-138)
src/hooks.rs (1)
  • default (81-88)
src/connection.rs (1)
src/hooks.rs (1)
  • default (81-88)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build-test
  • GitHub Check: Analyze (actions)
🔇 Additional comments (10)
src/response.rs (1)

75-90: Documentation looks good!

The examples clearly demonstrate both protocol error conversion and I/O error creation patterns, which will help users understand how to work with the WireframeError type.

src/app.rs (1)

409-409: Type signature correctly updated.

The addition of the () error type parameter aligns with the protocol configuration on line 84 where ProtocolError = ().

tests/connection_actor.rs (3)

122-143: Test correctly validates protocol error handling.

The test properly verifies that:

  • Protocol errors invoke the handle_error callback exactly once
  • Frames before the error are still processed and output
  • The connection continues to process remaining frames

Good use of atomics to track callback invocations in the test.


145-162: New test properly verifies I/O error behaviour.

The test correctly validates that I/O errors:

  • Propagate and terminate the connection
  • Return as Err(WireframeError::Io(_))
  • Still allow frames before the error to be processed

This complements the protocol error test nicely, demonstrating the different handling paths.


224-224: Generic parameters correctly specified.

The explicit type parameters <u8, ()> are necessary for the updated ProtocolHooks type and ensure proper type inference.

Also applies to: 254-254

src/hooks.rs (2)

65-87: Struct changes follow established patterns.

The new handle_error field and its type alias follow the same conventions as the existing hooks, maintaining consistency in the codebase.


113-117: Implementation correctly integrates the error handler.

The handle_error method and its integration in from_protocol follow the established patterns for hook methods, properly managing the optional callback.

Also applies to: 139-148

src/connection.rs (3)

76-76: Type updates correctly propagate the error parameter.

The changes properly thread the error type E through the ConnectionActor and its constructors, maintaining type safety.

Also applies to: 107-113, 123-123


156-156: Documentation clearly explains error handling behaviour.

The updates effectively communicate that protocol errors are handled internally via hooks whilst I/O errors propagate to the caller.

Also applies to: 353-355


367-372: Error handling correctly implements the design.

The implementation properly:

  • Invokes the error handler for protocol errors
  • Marks the response as closed
  • Calls the command end hook for cleanup
  • Propagates I/O errors to maintain connection termination semantics

This provides a clean separation between recoverable protocol errors and fatal I/O errors.

Comment thread src/hooks.rs
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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 34c0a10 and 6d41500.

📒 Files selected for processing (3)
  • src/connection.rs (7 hunks)
  • src/hooks.rs (4 hunks)
  • tests/connection_actor.rs (4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`**/*.rs`: Comment why, not what. Explain assumptions, edge cases, trade-offs, o...

**/*.rs: Comment why, not what. Explain assumptions, edge cases, trade-offs, or complexity. Don't echo the obvious.
Comments must use en-GB-oxendict spelling and grammar.
Function documentation must include clear examples.
Every module must begin with a module level (//!) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
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.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Prefer .expect() over .unwrap().
Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Avoid unsafe code unless absolutely necessary and document any usage clearly.

📄 Source: CodeRabbit Inference Engine (AGENTS.md)

List of files the instruction was applied to:

  • tests/connection_actor.rs
  • src/hooks.rs
  • src/connection.rs
`**/*.rs`: * Seek to keep the cyclomatic complexity of functions no more than 12...

**/*.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 must use en-GB-oxendict 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/

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • tests/connection_actor.rs
  • src/hooks.rs
  • src/connection.rs
🧬 Code Graph Analysis (2)
tests/connection_actor.rs (2)
src/connection.rs (5)
  • new (102-115)
  • new (446-455)
  • default (50-55)
  • with_hooks (119-139)
  • shutdown_token (149-149)
src/hooks.rs (1)
  • default (83-90)
src/connection.rs (2)
src/response.rs (2)
  • fmt (56-63)
  • fmt (110-115)
src/hooks.rs (1)
  • default (83-90)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build-test
🔇 Additional comments (5)
tests/connection_actor.rs (3)

122-143: LGTM! Well-structured test for error handler invocation.

The test correctly verifies that protocol errors trigger the error handler exactly once and that frame processing continues up to the error point.


145-163: LGTM! Good test coverage for logging behaviour.

The test properly verifies that protocol errors generate warning logs with appropriate content.


164-181: LGTM! Comprehensive test for I/O error handling.

The test correctly verifies that I/O errors terminate the connection and are propagated to the caller.

src/hooks.rs (1)

39-53: Documentation example is clear and focused.

The example effectively demonstrates the handle_error method usage without unnecessary complexity. The past review comment appears to have been addressed.

src/connection.rs (1)

354-382: LGTM! Robust error handling implementation.

The differentiated error handling correctly:

  • Logs protocol errors as warnings (addressing the past review comment about observability)
  • Invokes the error handler for custom handling
  • Allows the actor to continue after protocol errors
  • Propagates I/O errors to terminate the connection

Comment thread tests/connection_actor.rs
Comment on lines +234 to +264
/// Handle to the global logger with exclusive access.
struct LoggerHandle {
guard: std::sync::MutexGuard<'static, Logger>,
}

impl LoggerHandle {
fn new() -> Self {
static LOGGER: OnceLock<Mutex<Logger>> = OnceLock::new();

let logger = LOGGER.get_or_init(|| Mutex::new(Logger::start()));
let guard = logger
.lock()
.expect("failed to acquire global logger lock; a previous test may still hold it");

Self { guard }
}
}

impl std::ops::Deref for LoggerHandle {
type Target = Logger;

fn deref(&self) -> &Self::Target { &self.guard }
}

impl std::ops::DerefMut for LoggerHandle {
fn deref_mut(&mut self) -> &mut Self::Target { &mut self.guard }
}

#[allow(unused_braces)]
#[fixture]
fn logger() -> LoggerHandle { LoggerHandle::new() }
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.

🧹 Nitpick (assertive)

Consider test serialisation to prevent flaky parallel test execution.

The global logger with mutex could cause test failures if tests run in parallel and one panics while holding the lock. Consider using the serial_test crate to ensure these tests run sequentially.

Add the serial_test dependency to Cargo.toml:

[dev-dependencies]
serial_test = "3.1"

Then annotate tests using the logger with #[serial]:

+use serial_test::serial;

 #[rstest]
 #[tokio::test]
+#[serial]
 async fn protocol_error_logs_warning(
🤖 Prompt for AI Agents
In tests/connection_actor.rs around lines 234 to 264, the global logger uses a
mutex which can cause flaky test failures if tests run in parallel and one
panics while holding the lock. To fix this, add the serial_test crate as a
dev-dependency in Cargo.toml with version 3.1, then annotate all tests that use
the logger with #[serial] to ensure they run sequentially and avoid concurrent
access issues.

Copy link
Copy Markdown

@codescene-delta-analysis codescene-delta-analysis Bot left a comment

Choose a reason for hiding this comment

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

Gates Passed
6 Quality Gates Passed

See analysis details in CodeScene

Quality Gate Profile: Pay Down Tech Debt
Want more control? Customize Code Health rules or catch issues early with our IDE extension and CLI tool.

Copy link
Copy Markdown

@codescene-delta-analysis codescene-delta-analysis Bot left a comment

Choose a reason for hiding this comment

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

Gates Passed
6 Quality Gates Passed

See analysis details in CodeScene

Quality Gate Profile: Pay Down Tech Debt
Want more control? Customize Code Health rules or catch issues early with our IDE extension and CLI tool.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6d41500 and a18cab1.

📒 Files selected for processing (2)
  • docs/asynchronous-outbound-messaging-design.md (1 hunks)
  • docs/asynchronous-outbound-messaging-roadmap.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
`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).

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

📄 Source: CodeRabbit Inference Engine (AGENTS.md)

List of files the instruction was applied to:

  • docs/asynchronous-outbound-messaging-roadmap.md
  • docs/asynchronous-outbound-messaging-design.md
`**/*.md`: Validate Markdown files using `markdownlint *.md **/*.md`. Run `mdfor...

**/*.md: Validate Markdown files using markdownlint *.md **/*.md.
Run mdformat-all after any documentation changes to format all Markdown files and fix table markup.
Validate Markdown Mermaid diagrams using the nixie CLI. The tool is already installed; run nixie *.md **/*.md directly instead of using npx.
Markdown paragraphs and bullet points must be wrapped at 80 columns.
Code blocks must be wrapped at 120 columns.
Tables and headings must not be wrapped.

📄 Source: CodeRabbit Inference Engine (AGENTS.md)

List of files the instruction was applied to:

  • docs/asynchronous-outbound-messaging-roadmap.md
  • docs/asynchronous-outbound-messaging-design.md
`docs/**/*.md`: Provide user guides and examples demonstrating server-initiated messaging.

docs/**/*.md: Provide user guides and examples demonstrating server-initiated messaging.

📄 Source: CodeRabbit Inference Engine (docs/asynchronous-outbound-messaging-roadmap.md)

List of files the instruction was applied to:

  • docs/asynchronous-outbound-messaging-roadmap.md
  • docs/asynchronous-outbound-messaging-design.md
`docs/**/*.md`: Conventions for writing project documentation should follow the rules outlined in the documentation style guide.

docs/**/*.md: Conventions for writing project documentation should follow the rules outlined in the documentation style guide.

📄 Source: CodeRabbit Inference Engine (docs/contents.md)

List of files the instruction was applied to:

  • docs/asynchronous-outbound-messaging-roadmap.md
  • docs/asynchronous-outbound-messaging-design.md
`docs/**/*.md`: Use British English based on the Oxford English Dictionary (en-o...

docs/**/*.md: Use British English based on the Oxford English Dictionary (en-oxendict) for documentation.
The word "outwith" is acceptable in documentation.
Keep US spelling when used in an API, for example color.
Use the Oxford comma in documentation.
Company names are treated as collective nouns (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 use fenced code blocks with a language identifier; 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 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 footnotes referenced with [^label] in documentation.
Include Mermaid diagrams in documentation where it adds clarity.
When embedding figures in documentation, use ![alt text](path/to/image) and provide concise alt text describing the content.
Add a short description before each Mermaid diagram in documentation so screen readers can understand it.

📄 Source: CodeRabbit Inference Engine (docs/documentation-style-guide.md)

List of files the instruction was applied to:

  • docs/asynchronous-outbound-messaging-roadmap.md
  • docs/asynchronous-outbound-messaging-design.md
`docs/**/*.md`: Write the official documentation for the new features. Create se...

docs/**/*.md: Write the official documentation for the new features. Create separate guides for "Duplex Messaging & Pushes", "Streaming Responses", and "Message Fragmentation". Each guide must include runnable examples and explain the relevant concepts and APIs.

📄 Source: CodeRabbit Inference Engine (docs/wireframe-1-0-detailed-development-roadmap.md)

List of files the instruction was applied to:

  • docs/asynchronous-outbound-messaging-roadmap.md
  • docs/asynchronous-outbound-messaging-design.md
`**/*.md`: * Avoid 2nd person or 1st person pronouns ("I", "you", "we") * Use en...

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

  • Use en-oxendic 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.

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • docs/asynchronous-outbound-messaging-roadmap.md
  • docs/asynchronous-outbound-messaging-design.md
🪛 LanguageTool
docs/asynchronous-outbound-messaging-design.md

[uncategorized] ~605-~605: Do not mix variants of the same word (‘serialise’ and ‘serialize’) within a single text.
Context: ...s allows the protocol implementation to serialise a domain-specific error frame before th...

(EN_WORD_COHERENCY)

⏰ Context from checks skipped due to timeout of 240000ms (1)
  • GitHub Check: build-test

Comment on lines +43 to 44
- [x] **Typed `WireframeError`** for recoverable protocol errors
([Design §5][design-errors]).
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.

🧹 Nitpick (assertive)

Enforce roadmap checkbox & line-wrap consistency

The newly-checked item mixes lowercase [x] with an earlier uppercase [X], and the bullet now exceeds the mandated 80-column wrap limit. Align the checkbox style and wrap the link on a new indented line:

- - [x] **Typed `WireframeError`** for recoverable protocol errors ([Design §5][design-errors]).
+ - [x] **Typed `WireframeError`** for recoverable protocol errors  
+   ([Design §5][design-errors]).

This keeps the bullet under 80 columns and preserves list readability.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In docs/asynchronous-outbound-messaging-roadmap.md around lines 43 to 44, the
checklist item uses a lowercase [x] instead of the uppercase [X] used earlier,
and the line exceeds the 80-column limit. Change the checkbox to uppercase [X]
for consistency and wrap the link onto a new indented line so the bullet point
stays within 80 columns, improving readability and maintaining style
consistency.

Comment thread docs/asynchronous-outbound-messaging-design.md Outdated
Comment thread docs/asynchronous-outbound-messaging-design.md Outdated
Copy link
Copy Markdown

@codescene-delta-analysis codescene-delta-analysis Bot left a comment

Choose a reason for hiding this comment

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

Gates Passed
6 Quality Gates Passed

See analysis details in CodeScene

Quality Gate Profile: Pay Down Tech Debt
Want more control? Customize Code Health rules or catch issues early with our IDE extension and CLI tool.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a18cab1 and 11d2810.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • Cargo.toml (1 hunks)
  • docs/asynchronous-outbound-messaging-design.md (1 hunks)
  • tests/connection_actor.rs (4 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
`Cargo.toml`: Use explicit version ranges in `Cargo.toml` and keep dependencies up-to-date.

Cargo.toml: Use explicit version ranges in Cargo.toml and keep dependencies up-to-date.

📄 Source: CodeRabbit Inference Engine (AGENTS.md)

List of files the instruction was applied to:

  • Cargo.toml
`**/*.rs`: Comment why, not what. Explain assumptions, edge cases, trade-offs, o...

**/*.rs: Comment why, not what. Explain assumptions, edge cases, trade-offs, or complexity. Don't echo the obvious.
Comments must use en-GB-oxendict spelling and grammar.
Function documentation must include clear examples.
Every module must begin with a module level (//!) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
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.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Prefer .expect() over .unwrap().
Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Avoid unsafe code unless absolutely necessary and document any usage clearly.

📄 Source: CodeRabbit Inference Engine (AGENTS.md)

List of files the instruction was applied to:

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

**/*.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 must use en-GB-oxendict 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/

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • tests/connection_actor.rs
`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).

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

📄 Source: CodeRabbit Inference Engine (AGENTS.md)

List of files the instruction was applied to:

  • docs/asynchronous-outbound-messaging-design.md
`**/*.md`: Validate Markdown files using `markdownlint *.md **/*.md`. Run `mdfor...

**/*.md: Validate Markdown files using markdownlint *.md **/*.md.
Run mdformat-all after any documentation changes to format all Markdown files and fix table markup.
Validate Markdown Mermaid diagrams using the nixie CLI. The tool is already installed; run nixie *.md **/*.md directly instead of using npx.
Markdown paragraphs and bullet points must be wrapped at 80 columns.
Code blocks must be wrapped at 120 columns.
Tables and headings must not be wrapped.

📄 Source: CodeRabbit Inference Engine (AGENTS.md)

List of files the instruction was applied to:

  • docs/asynchronous-outbound-messaging-design.md
`docs/**/*.md`: Provide user guides and examples demonstrating server-initiated messaging.

docs/**/*.md: Provide user guides and examples demonstrating server-initiated messaging.

📄 Source: CodeRabbit Inference Engine (docs/asynchronous-outbound-messaging-roadmap.md)

List of files the instruction was applied to:

  • docs/asynchronous-outbound-messaging-design.md
`docs/**/*.md`: Conventions for writing project documentation should follow the rules outlined in the documentation style guide.

docs/**/*.md: Conventions for writing project documentation should follow the rules outlined in the documentation style guide.

📄 Source: CodeRabbit Inference Engine (docs/contents.md)

List of files the instruction was applied to:

  • docs/asynchronous-outbound-messaging-design.md
`docs/**/*.md`: Use British English based on the Oxford English Dictionary (en-o...

docs/**/*.md: Use British English based on the Oxford English Dictionary (en-oxendict) for documentation.
The word "outwith" is acceptable in documentation.
Keep US spelling when used in an API, for example color.
Use the Oxford comma in documentation.
Company names are treated as collective nouns (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 use fenced code blocks with a language identifier; 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 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 footnotes referenced with [^label] in documentation.
Include Mermaid diagrams in documentation where it adds clarity.
When embedding figures in documentation, use ![alt text](path/to/image) and provide concise alt text describing the content.
Add a short description before each Mermaid diagram in documentation so screen readers can understand it.

📄 Source: CodeRabbit Inference Engine (docs/documentation-style-guide.md)

List of files the instruction was applied to:

  • docs/asynchronous-outbound-messaging-design.md
`docs/**/*.md`: Write the official documentation for the new features. Create se...

docs/**/*.md: Write the official documentation for the new features. Create separate guides for "Duplex Messaging & Pushes", "Streaming Responses", and "Message Fragmentation". Each guide must include runnable examples and explain the relevant concepts and APIs.

📄 Source: CodeRabbit Inference Engine (docs/wireframe-1-0-detailed-development-roadmap.md)

List of files the instruction was applied to:

  • docs/asynchronous-outbound-messaging-design.md
`**/*.md`: * Avoid 2nd person or 1st person pronouns ("I", "you", "we") * Use en...

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

  • Use en-oxendic 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.

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • docs/asynchronous-outbound-messaging-design.md
⏰ Context from checks skipped due to timeout of 240000ms (1)
  • GitHub Check: build-test
🔇 Additional comments (7)
tests/connection_actor.rs (6)

122-143: Excellent test coverage for protocol error handling.

The test effectively verifies that protocol errors invoke the error handler exactly once and that frames before the error are output whilst the connection remains active. The use of Arc<AtomicUsize> for tracking error handler invocations is a clean approach.


145-163: Good test implementation following past review guidance.

The test correctly uses the #[serial] attribute to prevent concurrent logger access issues as recommended in the past review comments. The test effectively verifies that protocol errors generate warning logs without terminating the connection.


165-182: Comprehensive verification of I/O error behaviour.

The test correctly demonstrates that I/O errors terminate the connection and return an error, in contrast to protocol errors which are handled internally. This provides clear behavioural distinction between the two error types.


236-266: Well-designed logger infrastructure with proper concurrency handling.

The LoggerHandle struct provides exclusive access to the global logger through RAII, preventing the mutex issues identified in past reviews. The use of OnceLock for lazy initialisation and clear error messaging for lock acquisition failures demonstrates good defensive programming.


280-280: Correctly updated for new generic type signature.

The addition of <u8, ()> type parameters aligns with the updated ProtocolHooks signature that now includes an error type parameter.


310-310: Correctly updated for new generic type signature.

The addition of <u8, ()> type parameters aligns with the updated ProtocolHooks signature that now includes an error type parameter.

docs/asynchronous-outbound-messaging-design.md (1)

600-668: Excellent documentation for typed protocol error handling.

The new section provides comprehensive coverage of the typed protocol error feature with clear explanations, appropriate diagrams, and good technical detail. The documentation correctly follows sentence case for headings and uses consistent OED spelling. The class and sequence diagrams effectively illustrate the error handling flow and the distinction between protocol errors (handled internally) and I/O errors (which terminate connections).

Comment thread Cargo.toml
proptest = "^1.0"
loom = "^0.7"
async-stream = "0.3"
serial_test = "3.1"
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.

🧹 Nitpick (assertive)

Use explicit version range for better dependency management.

The coding guidelines require explicit version ranges in Cargo.toml. Consider using a more specific version range instead of "3.1".

Apply this diff for better version specificity:

-serial_test = "3.1"
+serial_test = "3.1.0"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
serial_test = "3.1"
serial_test = "3.1.0"
🤖 Prompt for AI Agents
In Cargo.toml at line 25, replace the dependency version "3.1" for serial_test
with an explicit version range such as "^3.1" or ">=3.1, <4.0" to comply with
coding guidelines and improve dependency management by specifying compatible
versions more clearly.

@leynos leynos merged commit b296566 into main Jul 5, 2025
5 checks passed
@leynos leynos deleted the codex/implement-typed-wireframeerror-for-protocol-errors branch July 5, 2025 17:40
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