Skip to content

Refactor frame module#223

Merged
leynos merged 1 commit intomainfrom
codex/refactor-and-modularize-src/-files
Jul 31, 2025
Merged

Refactor frame module#223
leynos merged 1 commit intomainfrom
codex/refactor-and-modularize-src/-files

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jul 31, 2025

Summary

  • split the frame module into submodules
  • relocate unit tests to tests.rs
  • update documentation for new module path

Testing

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

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

Summary by Sourcery

Refactor the frame module by splitting it into submodules for conversion, formatting, and processing, extract core frame encoding/decoding logic into dedicated helpers and traits, relocate unit tests to a separate file, and update documentation references accordingly.

Enhancements:

  • Split frame.rs into a modular structure with conversion, format, and processor submodules
  • Extract and implement length-prefix conversion helpers (bytes_to_u64, u64_to_bytes)
  • Define LengthFormat utilities for configurable prefix formats and endianness
  • Introduce FrameProcessor and FrameMetadata traits and provide a LengthPrefixedProcessor implementation

Documentation:

  • Update module path references in docs/roadmap.md to reflect the new frame module layout

Tests:

  • Relocate frame-related unit tests to src/frame/tests.rs
  • Add comprehensive tests for conversion functions and error cases

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jul 31, 2025

Reviewer's Guide

This PR refactors the monolithic frame module by splitting it into dedicated submodules (conversion, format, processor, tests), updates imports and documentation, and introduces new framing utilities and a length-prefixed processor implementation.

Class diagram for LengthPrefixedProcessor and related types

classDiagram
    class LengthPrefixedProcessor {
        -format: LengthFormat
        +new(format: LengthFormat) -> Self
        +decode(&self, src: &mut BytesMut) -> Result<Option<Vec<u8>>, std::io::Error>
        +encode(&self, frame: &Vec<u8>, dst: &mut BytesMut) -> Result<(), std::io::Error>
    }
    class LengthFormat {
        +bytes: usize
        +endianness: Endianness
        +new(bytes: usize, endianness: Endianness) -> Self
        +read_len(&self, bytes: &[u8]) -> io::Result<usize>
        +write_len(&self, len: usize, dst: &mut BytesMut) -> io::Result<()> 
    }
    class Endianness {
        <<enumeration>>
        Big
        Little
    }
    LengthPrefixedProcessor --> LengthFormat: has
    LengthFormat --> Endianness: uses
Loading

File-Level Changes

Change Details Files
Restructure frame module into submodules
  • Removed the original src/frame.rs
  • Added src/frame/mod.rs to re-export submodules and types
  • Moved unit tests into src/frame/tests.rs
src/frame.rs
src/frame/mod.rs
src/frame/tests.rs
Add conversion helpers for length prefix encoding
  • Defined error constants and prefix_err helper
  • Implemented checked_prefix_cast and parse_bytes
  • Provided bytes_to_u64 and u64_to_bytes functions with endianness support
src/frame/conversion.rs
Introduce LengthFormat and Endianness abstractions
  • Defined Endianness enum for byte order
  • Created LengthFormat struct with constructors and default
  • Implemented read_len and write_len using conversion helpers
src/frame/format.rs
Implement framing processor traits and length‐prefixed processor
  • Defined FrameProcessor and FrameMetadata traits
  • Added LengthPrefixedProcessor with decode and encode methods
src/frame/processor.rs
Update documentation for new module paths
  • Adjusted docs/roadmap.md to reference src/frame/mod.rs instead of src/frame.rs
docs/roadmap.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 31, 2025

Summary by CodeRabbit

  • Refactor
    • Reorganised frame handling utilities into modular components for improved clarity and maintainability.
  • New Features
    • Introduced configurable length prefix formats and endianness options for frame encoding.
    • Added new traits and processors for flexible frame encoding and decoding.
  • Bug Fixes
    • Improved error handling for unsupported or incomplete length prefixes and oversized frames.
  • Tests
    • Added comprehensive unit tests for length prefix conversions and error scenarios.
  • Documentation
    • Updated roadmap documentation to reflect new file structure.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/refactor-and-modularize-src/-files

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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.

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

### Comment 1
<location> `src/frame/conversion.rs:111` </location>
<code_context>
-        }
-    }
-
-    out[size..].fill(0);
-
-    Ok(size)
</code_context>

<issue_to_address>
Zeroing the remainder of the output buffer may be unnecessary.

Zeroing the unused portion may be redundant and could slightly affect performance. If preventing data leakage is the goal, document this or consider reducing the buffer size.
</issue_to_address>

### Comment 2
<location> `src/frame/tests.rs:67` </location>
<code_context>
-    }
-
-    #[rstest]
-    fn u64_to_bytes_large() {
-        let mut buf = [0u8; 8];
-        let err = u64_to_bytes(300, 1, Endianness::Big, &mut buf)
-            .expect_err("u64_to_bytes must fail if value exceeds 1-byte prefix");
-        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
-    }
-
</code_context>

<issue_to_address>
Missing test for negative or zero-length values.

Consider adding a test for zero-length values to verify correct handling, especially if zero-length frames are valid in your protocol.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH

use std::io;

=======
#[test]
fn u64_to_bytes_zero_length() {
    let mut buf = [0u8; 8];
    let err = u64_to_bytes(0, 0, Endianness::Big, &mut buf)
        .expect_err("u64_to_bytes must fail if length is zero");
    assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
}

use std::io;

>>>>>>> REPLACE

</suggested_fix>

### Comment 3
<location> `src/frame/conversion.rs:49` </location>
<code_context>
-/// let buf = [0x00, 0x10, 0x20, 0x30];
-/// assert_eq!(bytes_to_u64(&buf, 2, Endianness::Big).unwrap(), 0x0010);
-/// ```
-pub fn bytes_to_u64(bytes: &[u8], size: usize, endianness: Endianness) -> io::Result<u64> {
-    if !matches!(size, 1 | 2 | 4 | 8) {
-        return Err(prefix_err(PrefixErr::UnsupportedSize));
</code_context>

<issue_to_address>
Consider simplifying the encoding and decoding logic by using direct slice copying and casting, and removing unnecessary helpers and error indirection.

You can collapse most of the per‐size/endianness arms into two simple copy+cast steps and drop both the `PrefixErr`/`prefix_err` indirection and the `parse_bytes` helper entirely. For example:

```rust
pub fn bytes_to_u64(
    bytes: &[u8],
    size: usize,
    endianness: Endianness,
) -> io::Result<u64> {
    if !matches!(size, 1 | 2 | 4 | 8) {
        return Err(io::Error::new(io::ErrorKind::InvalidInput, ERR_UNSUPPORTED_PREFIX));
    }
    if bytes.len() < size {
        return Err(io::Error::new(io::ErrorKind::UnexpectedEof, ERR_INCOMPLETE_PREFIX));
    }

    let mut buf = [0u8; 8];
    match endianness {
        Endianness::Big    => buf[8 - size..].copy_from_slice(&bytes[..size]),
        Endianness::Little => buf[..size].copy_from_slice(&bytes[..size]),
    }

    let val = match endianness {
        Endianness::Big    => u64::from_be_bytes(buf),
        Endianness::Little => u64::from_le_bytes(buf),
    };
    Ok(val)
}
```

```rust
pub fn u64_to_bytes(
    len: usize,
    size: usize,
    endianness: Endianness,
    out: &mut [u8; 8],
) -> io::Result<usize> {
    if !matches!(size, 1 | 2 | 4 | 8) {
        return Err(io::Error::new(io::ErrorKind::InvalidInput, ERR_UNSUPPORTED_PREFIX));
    }

    // cast `len` into exactly the right integer type once
    let prefix_bytes = match size {
        1 => checked_prefix_cast::<u8>(len)?.to_be_bytes().to_vec(),
        2 => checked_prefix_cast::<u16>(len)?.to_be_bytes().to_vec(),
        4 => checked_prefix_cast::<u32>(len)?.to_be_bytes().to_vec(),
        8 => checked_prefix_cast::<u64>(len)?.to_be_bytes().to_vec(),
        _ => unreachable!(),
    };

    out.fill(0);
    match endianness {
        Endianness::Big    => out[8 - size..].copy_from_slice(&prefix_bytes),
        Endianness::Little => out[..size].copy_from_slice(&prefix_bytes),
    };
    Ok(size)
}
```

Steps to apply:

1. Remove the `PrefixErr` enum + `prefix_err` fn and inline `io::Error::new` calls.
2. Delete `parse_bytes` and its uses.
3. Replace both `bytes_to_u64` and `u64_to_bytes` with the above slice‐and‐cast logic.
</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/frame/conversion.rs
Comment thread src/frame/tests.rs
Comment thread src/frame/conversion.rs
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 31, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 31, 2025

✅ Actions performed

Review triggered.

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

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (5)
src/frame/conversion.rs (4)

10-25: Remove unnecessary error indirection.

The PrefixErr enum and prefix_err function add unnecessary complexity. Use io::Error::new directly with the error constants for cleaner code.


34-39: Remove the parse_bytes helper function.

This generic helper adds complexity without significant benefit. The conversion logic can be simplified by using direct slice operations and casting.


49-67: Simplify the encoding logic using direct slice copying.

Replace the complex match arms with simpler slice-and-cast logic as suggested in the past review. This will improve both performance and maintainability.


111-111: Document the purpose of zeroing unused buffer space.

If this zeroing is intentional for security (preventing data leakage), document this clearly. Otherwise, remove it to avoid unnecessary performance overhead.

src/frame/tests.rs (1)

66-71: Add test coverage for zero-length values.

Include a test case for zero-length values to verify correct error handling, as this is an important protocol edge case.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1214f73 and 5d104c4.

📒 Files selected for processing (7)
  • docs/roadmap.md (1 hunks)
  • src/frame.rs (0 hunks)
  • src/frame/conversion.rs (1 hunks)
  • src/frame/format.rs (1 hunks)
  • src/frame/mod.rs (1 hunks)
  • src/frame/processor.rs (1 hunks)
  • src/frame/tests.rs (1 hunks)
💤 Files with no reviewable changes (1)
  • src/frame.rs
🧰 Additional context used
📓 Path-based instructions (2)
**/*.md

⚙️ CodeRabbit Configuration File

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

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

Files:

  • docs/roadmap.md
**/*.rs

⚙️ CodeRabbit Configuration File

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

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

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

  • Avoid unsafe unless absolutely necessary.

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

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

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

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

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

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

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

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

  • Files must not exceed 400 lines in length

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

Files:

  • src/frame/mod.rs
  • src/frame/format.rs
  • src/frame/processor.rs
  • src/frame/conversion.rs
  • src/frame/tests.rs
🧬 Code Graph Analysis (3)
src/frame/mod.rs (2)
wireframe_testing/src/helpers.rs (1)
  • processor (22-22)
src/frame/conversion.rs (2)
  • bytes_to_u64 (49-68)
  • u64_to_bytes (78-114)
src/frame/processor.rs (1)
src/frame/format.rs (2)
  • new (28-28)
  • default (65-65)
src/frame/tests.rs (1)
src/frame/conversion.rs (2)
  • bytes_to_u64 (49-68)
  • u64_to_bytes (78-114)
🔇 Additional comments (12)
docs/roadmap.md (1)

27-27: LGTM - Documentation correctly updated to reflect modular structure.

The path reference has been properly updated to match the new modular frame structure.

src/frame/mod.rs (1)

1-12: Excellent modular organisation and clean API design.

The module structure is well-designed with proper documentation and selective re-exports that provide a cohesive interface whilst maintaining internal modularity.

src/frame/format.rs (1)

1-66: Well-designed format abstraction with excellent API ergonomics.

The module provides a clean abstraction for length prefix formats with convenient constructors, proper error handling, and sensible defaults. The const constructors and pub(crate) visibility are appropriately used.

src/frame/tests.rs (1)

1-84: Excellent test coverage with comprehensive parameterisation.

The test suite properly covers success cases, error conditions, and boundary cases using rstest effectively. The test organisation and error checking are exemplary.

src/frame/processor.rs (8)

1-1: Module documentation follows guidelines correctly.

The module documentation uses the required //! format and explains the module's purpose clearly.


8-26: FrameProcessor trait design is well-structured.

The trait properly uses associated types for Frame and Error, includes comprehensive documentation with error conditions, and follows the Send + Sync bounds for concurrent usage. Error type constraints ensure proper error propagation.


28-41: FrameMetadata trait provides clean separation of concerns.

The trait correctly separates metadata parsing from full frame decoding, which aligns with single responsibility principle. The return type (Self::Frame, usize) properly indicates both the parsed frame and bytes consumed.


44-47: LengthPrefixedProcessor struct is appropriately minimal.

The struct correctly encapsulates only the necessary LengthFormat field and derives appropriate traits (Clone, Copy, Debug) for value semantics.


49-53: Constructor follows coding guidelines.

The new function correctly uses #[must_use] attribute, is declared as const fn, and follows the single-line function guideline by omitting return.


55-57: Default implementation delegates appropriately.

The Default trait implementation correctly delegates to LengthFormat::default() through the constructor, maintaining consistency.


63-76: Decode method handles edge cases properly.

The implementation correctly:

  • Checks buffer length before reading length prefix
  • Uses checked_add to prevent integer overflow
  • Returns Ok(None) for incomplete frames (following tokio codec patterns)
  • Advances buffer position after reading length prefix
  • Converts BytesMut to Vec<u8> appropriately

The error handling uses the imported constant ERR_FRAME_TOO_LARGE for consistency.


78-84: Encode method implementation is correct.

The method properly:

  • Reserves buffer capacity upfront for efficiency
  • Delegates length prefix writing to the format
  • Extends buffer with frame bytes
  • Uses appropriate error propagation with ? operator

The implementation follows good practices for buffer management.

Comment thread src/frame/tests.rs
@leynos leynos merged commit f2c2e56 into main Jul 31, 2025
5 checks passed
@leynos leynos deleted the codex/refactor-and-modularize-src/-files branch July 31, 2025 19:16
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