Skip to content

Fix decoder example to propagate errors#192

Merged
leynos merged 6 commits intomainfrom
codex/update-decoder-example-to-handle-errors
Jul 7, 2025
Merged

Fix decoder example to propagate errors#192
leynos merged 6 commits intomainfrom
codex/update-decoder-example-to-handle-errors

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jul 6, 2025

Summary

  • illustrate error propagation when reading the frame length
  • document this behaviour in the decoder code example

Testing

  • mdformat-all
  • make fmt
  • make lint
  • make test

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

Summary by Sourcery

Revise the length-prefixed framing example to propagate IO errors on invalid or oversized frames in both decode and encode paths and document this behavior.

Enhancements:

  • Add error handling for invalid input and oversized frames in both decode and encode implementations

Documentation:

  • Update the decoder example in documentation to illustrate and document error propagation when reading the frame length

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jul 6, 2025

Reviewer's Guide

This PR updates the length-prefixed framing example in the documentation to properly propagate I/O errors in both decoding and encoding, replaces panicking calls with error logic to avoid unexpected crashes, and revises the example heading and formatting to emphasize this behavior.

File-Level Changes

Change Details Files
Revise example heading and formatting to highlight error propagation
  • Updated heading text to mention io::Error return on invalid or oversized frames
  • Adjusted list numbering and indentation for consistency
  • Refined code block fencing and comments for clarity
docs/rust-binary-router-library-design.md
Enhance decode to propagate errors and avoid panics
  • Removed ReadBytesExt import and expect(...) call
  • Replaced read_u32 with Buf::get_u32 for length prefix extraction
  • Added maximum frame length check returning Err(io::Error) on oversized inputs
  • Adjusted buffer reservation and length checks before consuming frame
docs/rust-binary-router-library-design.md
Add frame size validation in encode
  • Inserted check to return Err(io::Error) when payload exceeds MAX_FRAME_LEN
  • Retained reserve, put_u32, and put_slice calls for valid frames
docs/rust-binary-router-library-design.md

Possibly linked issues


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 6, 2025

Summary by CodeRabbit

  • Documentation
    • Improved the example for a length-prefixed frame processor, clarifying error handling and simplifying code for better readability.
    • Expanded explanations on how invalid or oversized frames are managed.
    • Enhanced formatting and updated code samples for greater clarity.

Summary by CodeRabbit

  • Documentation
    • Improved the example for a length-prefixed frame processor, clarifying error handling and updating code formatting for better readability. Enhanced comments and descriptions to emphasise error propagation and frame size checks. No changes to the public API.

Walkthrough

The update revises the example of a length-prefixed frame processor in the documentation, focusing on improved error handling by replacing .expect() with the ? operator in the decode method, and applies formatting and clarity enhancements throughout the code and explanatory comments. No public API changes are introduced.

Changes

File(s) Change Summary
docs/rust-binary-router-library-design.md Improved error handling in the decode method, added frame size check in encode, reformatted code and comments, clarified documentation.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant Codec as LengthPrefixedCodec
    participant Buffer as BytesMut

    App->>Codec: decode(buffer)
    Codec->>Buffer: read length prefix with error propagation (?)
    Codec->>Buffer: check if enough bytes for frame
    Codec-->>App: return frame or Ok(None) on incomplete data
    App->>Codec: encode(frame, buffer)
    Codec->>Buffer: check frame size <= MAX_FRAME_LEN
    Codec->>Buffer: write length prefix and frame bytes
Loading

Possibly related issues

Possibly related PRs

Poem

In the docs a codec lay,
With error handling gone astray.
Now with ? it’s safe and neat,
No more panics in defeat!
Framing bytes with gentle care,
Rabbits code with savoir-faire.
🐇✨

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/update-decoder-example-to-handle-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!


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.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 6, 2025

@coderabbitai resume

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 6, 2025

✅ Actions performed

Reviews resumed.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 07b716f and ee23219.

📒 Files selected for processing (1)
  • docs/rust-binary-router-library-design.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.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/rust-binary-router-library-design.md

Comment thread docs/rust-binary-router-library-design.md
Comment thread docs/rust-binary-router-library-design.md Outdated
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 6, 2025

@sourcery-ai review

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 - here's some feedback:

  • Consider using the Buf trait’s get_u32 method directly on BytesMut instead of creating a new Cursor for efficiency.
  • The example now enforces a max frame size on encode—update the surrounding docs to mention error propagation on the encoding side as well.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider using the `Buf` trait’s get_u32 method directly on `BytesMut` instead of creating a new `Cursor` for efficiency.
- The example now enforces a max frame size on encode—update the surrounding docs to mention error propagation on the encoding side as well.

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.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ee23219 and dcdce6b.

📒 Files selected for processing (1)
  • docs/rust-binary-router-library-design.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/rust-binary-router-library-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/rust-binary-router-library-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/rust-binary-router-library-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/rust-binary-router-library-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/rust-binary-router-library-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/rust-binary-router-library-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/rust-binary-router-library-design.md
⏰ Context from checks skipped due to timeout of 240000ms (1)
  • GitHub Check: build-test
🔇 Additional comments (2)
docs/rust-binary-router-library-design.md (2)

1141-1146: Error-propagation change compiles cleanly – good fix

Replacing expect with ? and introducing Cursor resolves the compile-time
type mismatch flagged in the earlier review, and correctly propagates I/O
errors to the caller. Implementation looks sound.


1164-1168: Oversize-frame guard added – previous concern resolved

The encode path now mirrors the decode limit check, preventing peers from
forcing unbounded allocations. This addresses the earlier “frame too large”
comment perfectly.

Comment on lines +1178 to +1179
(Note: "wireframe" would abstract the direct use of `Encoder`/`Decoder` behind
its own `FrameProcessor` trait or provide helpers.)
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)

Line length exceeds documentation guidelines

docs/**/*.md must wrap prose at 80 columns, but the note starting with
“Note: "wireframe" would abstract…” runs far longer. Please re-wrap or let
mdformat-all handle it so CI markdown-lint passes.

🤖 Prompt for AI Agents
In docs/rust-binary-router-library-design.md around lines 1178 to 1179, the note
about "wireframe" exceeds the 80-column line length limit for documentation.
Reformat the text to wrap lines at or below 80 characters, either manually or by
running the mdformat-all tool, to ensure it complies with markdown linting
rules.

Comment thread docs/rust-binary-router-library-design.md 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: 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 dcdce6b and 347e9a9.

📒 Files selected for processing (1)
  • docs/rust-binary-router-library-design.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/rust-binary-router-library-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/rust-binary-router-library-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/rust-binary-router-library-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/rust-binary-router-library-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/rust-binary-router-library-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/rust-binary-router-library-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/rust-binary-router-library-design.md
⏰ Context from checks skipped due to timeout of 240000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-test
🔇 Additional comments (1)
docs/rust-binary-router-library-design.md (1)

1162-1167: Oversize-frame guard in encode looks spot-on

Nice addition—this mirrors the check already present in decode, prevents unbounded allocations, and resolves the earlier review note.

Comment on lines +1123 to 1126
1. **Frame Processor Implementation** (Simple length-prefixed framing using
`tokio-util`; invalid input or oversized frames return `io::Error` from both
decode and encode):

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)

Wrap prose at 80 columns to satisfy documentation linting

The bullet text introducing the codec example runs far beyond the 80-column limit mandated for docs/**/*.md. This will fail markdownlint/CI.

🤖 Prompt for AI Agents
In docs/rust-binary-router-library-design.md around lines 1123 to 1126, the
bullet point text exceeds the 80-column limit required by markdownlint. Reformat
the text by wrapping the prose so that no line exceeds 80 characters, ensuring
it meets the documentation linting standards without altering the content.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 7, 2025

@sourcery-ai review

Copy link
Copy Markdown

@SourceryAI SourceryAI left a comment

Choose a reason for hiding this comment

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

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

Blocking issues:

  • Advance the buffer by 4 bytes to consume the length prefix before splitting out the frame payload. (link)

General comments:

  • The decode example currently consumes the 4-byte length prefix via get_u32() before checking if the full payload is available, so on a partial frame you lose the header—consider peeking the length without advancing (or only advancing after verifying src.len() >= 4 + length).
  • The numbered list in the docs now has two ‘1.’ entries (for framing and server setup), so renumber the sections to maintain a proper sequence.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The `decode` example currently consumes the 4-byte length prefix via `get_u32()` before checking if the full payload is available, so on a partial frame you lose the header—consider peeking the length without advancing (or only advancing after verifying `src.len() >= 4 + length`).
- The numbered list in the docs now has two ‘1.’ entries (for framing and server setup), so renumber the sections to maintain a proper sequence.

## Individual Comments

### Comment 1
<location> `docs/rust-binary-router-library-design.md:1158` </location>
<code_context>
+        }

-          src.advance(4); // Consume length prefix
-          Ok(Some(src.split_to(length)))
-      }
-  }
</code_context>

<issue_to_address>
Advance the buffer by 4 bytes to consume the length prefix before splitting out the frame payload.

Currently, you split out the payload without first advancing past the 4-byte length prefix, so the returned BytesMut will include the length prefix. You should call src.advance(4) before split_to(length).
</issue_to_address>

Hi @leynos! 👋

Thanks for trying out Sourcery by commenting with @sourcery-ai review! 🚀

Install the sourcery-ai bot to get automatic code reviews on every pull request ✨

Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Ok(Some(src.split_to(length)))
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (review_instructions): Advance the buffer by 4 bytes to consume the length prefix before splitting out the frame payload.

Currently, you split out the payload without first advancing past the 4-byte length prefix, so the returned BytesMut will include the length prefix. You should call src.advance(4) before split_to(length).

Review instructions:

Path patterns: **/*

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

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

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

Blocking issues:

  • Do not use get_u32() here as it advances the buffer before checking if enough data is present, which can corrupt the buffer state. (link)
  • Check for src.len() < 4 + length, not just < length, to ensure the full frame (including prefix) is present. (link)
  • Advance the buffer by 4 bytes to consume the length prefix before splitting the payload. (link)
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `docs/rust-binary-router-library-design.md:1144` </location>
<code_context>
-          let length = (&src[..4])
-              .read_u32::<BigEndian>()
-              .expect("slice length checked") as usize;
+        let length = src.get_u32() as usize;

-          if length > MAX_FRAME_LEN {
</code_context>

<issue_to_address>
Do not use get_u32() here as it advances the buffer before checking if enough data is present, which can corrupt the buffer state.

You should first check that src.len() >= 4, then use something like src[..4] to read the length without advancing the buffer. Only advance the buffer after confirming the full frame is present. This prevents buffer corruption if the frame is incomplete.
</issue_to_address>

### Comment 2
<location> `docs/rust-binary-router-library-design.md:1150` </location>
<code_context>
-              src.reserve(4 + length - src.len());
-              return Ok(None); // Not enough data for full frame
-          }
+        if src.len() < length {
+            src.reserve(length - src.len());
+            return Ok(None); // Not enough data for full frame
</code_context>

<issue_to_address>
Check for src.len() < 4 + length, not just < length, to ensure the full frame (including prefix) is present.

The check should be if src.len() < 4 + length, since the length prefix is part of the buffer. Otherwise, you may attempt to split or advance the buffer incorrectly, leading to panics or data loss.
</issue_to_address>

### Comment 3
<location> `docs/rust-binary-router-library-design.md:1158` </location>
<code_context>
+        }

-          src.advance(4); // Consume length prefix
-          Ok(Some(src.split_to(length)))
-      }
-  }
</code_context>

<issue_to_address>
Advance the buffer by 4 bytes to consume the length prefix before splitting the payload.

You must call src.advance(4) before src.split_to(length) to remove the length prefix from the buffer. Otherwise, the returned frame will include the length prefix, which is incorrect.
</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.

let length = (&src[..4])
.read_u32::<BigEndian>()
.expect("slice length checked") as usize;
let length = src.get_u32() as usize;
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 use get_u32() here as it advances the buffer before checking if enough data is present, which can corrupt the buffer state.

You should first check that src.len() >= 4, then use something like src[..4] to read the length without advancing the buffer. Only advance the buffer after confirming the full frame is present. This prevents buffer corruption if the frame is incomplete.

Review instructions:

Path patterns: **/*

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

src.reserve(4 + length - src.len());
return Ok(None); // Not enough data for full frame
}
if src.len() < length {
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): Check for src.len() < 4 + length, not just < length, to ensure the full frame (including prefix) is present.

The check should be if src.len() < 4 + length, since the length prefix is part of the buffer. Otherwise, you may attempt to split or advance the buffer incorrectly, leading to panics or data loss.

Review instructions:

Path patterns: **/*

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

Ok(Some(src.split_to(length)))
}
}

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): Advance the buffer by 4 bytes to consume the length prefix before splitting the payload.

You must call src.advance(4) before src.split_to(length) to remove the length prefix from the buffer. Otherwise, the returned frame will include the length prefix, which is incorrect.

Review instructions:

Path patterns: **/*

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

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 347e9a9 and 597302a.

📒 Files selected for processing (1)
  • docs/rust-binary-router-library-design.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/rust-binary-router-library-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/rust-binary-router-library-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/rust-binary-router-library-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/rust-binary-router-library-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/rust-binary-router-library-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/rust-binary-router-library-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/rust-binary-router-library-design.md
🔇 Additional comments (1)
docs/rust-binary-router-library-design.md (1)

1123-1125: Re-run mdformat-all; this bullet still looks > 80 chars in CI.

The documentation guidelines insist that prose in docs/**/*.md is wrapped at
80 columns. Please run mdformat-all (or wrap manually) so markdownlint does
not fail on these three lines.

Comment on lines +1128 to +1174
// Crate: my_frame_processor.rs
use bytes::{BytesMut, Buf, BufMut};
use tokio_util::codec::{Decoder, Encoder};
use byteorder::{BigEndian, ByteOrder};
use std::io;

const MAX_FRAME_LEN: usize = 16 * 1024 * 1024; // 16 MiB upper limit
const MAX_FRAME_LEN: usize = 16 * 1024 * 1024; // 16 MiB upper limit

pub struct LengthPrefixedCodec;
pub struct LengthPrefixedCodec;

impl Decoder for LengthPrefixedCodec {
type Item = BytesMut; // Raw frame payload
type Error = io::Error;
impl Decoder for LengthPrefixedCodec {
type Item = BytesMut; // Raw frame payload
type Error = io::Error;

fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
if src.len() < 4 { return Ok(None); } // Not enough data for length prefix
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
if src.len() < 4 { return Ok(None); } // Not enough data for length prefix

let length = u32::from_be_bytes(
src[..4].try_into().expect("slice length checked"),
) as usize;
let length = BigEndian::read_u32(&src[..4]) as usize;

if length > MAX_FRAME_LEN {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "frame too large"));
}
if length > MAX_FRAME_LEN {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "frame too large"));
}

if src.len() < 4 + length {
src.reserve(4 + length - src.len());
return Ok(None); // Not enough data for full frame
}
if src.len() < 4 + length {
src.reserve(4 + length - src.len());
return Ok(None); // Not enough data for full frame
}
src.advance(4); // Consume length prefix
Ok(Some(src.split_to(length)))
}
}

src.advance(4); // Consume length prefix
Ok(Some(src.split_to(length)))
}
}
impl<T: AsRef<[u8]>> Encoder<T> for LengthPrefixedCodec {
type Error = io::Error;

impl<T: AsRef<[u8]>> Encoder<T> for LengthPrefixedCodec {
type Error = io::Error;

fn encode(&mut self, item: T, dst: &mut BytesMut) -> Result<(), Self::Error> {
let data = item.as_ref();
let length = u32::try_from(data.len()).map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidInput,
"payload exceeds 4 GiB limit",
)
})?;
dst.reserve(4 + data.len());
dst.put_u32(length);
dst.put_slice(data);
Ok(())
fn encode(&mut self, item: T, dst: &mut BytesMut) -> Result<(), Self::Error> {
let data = item.as_ref();
if data.len() > MAX_FRAME_LEN {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "frame too large"));
}
}
```

(Note: "wireframe" would abstract the direct use of `Encoder`/`Decoder` behind
its own `FrameProcessor` trait or provide helpers.)
dst.reserve(4 + data.len());
dst.put_u32(data.len() as u32);
dst.put_slice(data);
Ok(())
}
}
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)

Introduce a LEN_PREFIX constant for clarity & easier maintenance.

The literal 4 appears several times and couples the logic tightly to a
32-bit length prefix. Replacing the magic number with a named constant improves
readability and makes it trivial to swap in a different prefix width later.

@@
-        if src.len() < 4 { return Ok(None); } // Not enough data for length prefix
+        const LEN_PREFIX: usize = 4;
+        if src.len() < LEN_PREFIX {
+            return Ok(None); // Not enough data for length prefix
+        }
@@
-        if src.len() < 4 + length {
+        if src.len() < LEN_PREFIX + length {
             src.reserve(LEN_PREFIX + length - src.len());
             return Ok(None); // Not enough data for full frame
         }
-        src.advance(4); // Consume length prefix
+        src.advance(LEN_PREFIX); // Consume length prefix
@@
-        dst.reserve(4 + data.len());
-        dst.put_u32(data.len() as u32);
+        dst.reserve(LEN_PREFIX + data.len());
+        dst.put_u32(data.len() as u32);

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

🤖 Prompt for AI Agents
In docs/rust-binary-router-library-design.md between lines 1128 and 1174,
replace all occurrences of the literal 4, which represents the length prefix
size, with a new constant named LEN_PREFIX. Define LEN_PREFIX as 4 at the top of
the file to improve code clarity and maintainability. Update all length prefix
related calculations and buffer operations to use LEN_PREFIX instead of the
hardcoded 4.

@leynos leynos merged commit 3644bcf into main Jul 7, 2025
5 checks passed
@leynos leynos deleted the codex/update-decoder-example-to-handle-errors branch July 7, 2025 19:20
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.

2 participants