Skip to content

Add usage examples to public functions#161

Merged
leynos merged 8 commits intomainfrom
codex/add-usage-examples-to-public-functions
Jul 4, 2025
Merged

Add usage examples to public functions#161
leynos merged 8 commits intomainfrom
codex/add-usage-examples-to-public-functions

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jul 4, 2025

Summary

  • add minimal usage examples for push queue APIs
  • demonstrate use of extractor helpers

Testing

  • make fmt
  • make lint
  • make test
  • cargo test --doc

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

Summary by Sourcery

Add minimal usage examples as doc tests to public functions in push and extractor modules to illustrate API usage and verify documentation examples.

Documentation:

  • Add doc tests for PushQueues API demonstrating bounded creation, high/low priority push, try_push, recv and close methods
  • Add usage examples for extractor helpers including MessageRequest::state, Payload creation and manipulation, SharedState deref, and ConnectionInfo::peer_addr

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jul 4, 2025

Reviewer's Guide

This PR enriches the documentation with minimal usage examples for all public push queue and extractor APIs and introduces a new Payload::new helper.

Class diagram for updated PushQueues and PushHandle APIs

classDiagram
    class PushQueues {
        +fn bounded(high_capacity: usize, low_capacity: usize) -> (Self, PushHandle<F>)
        +async fn recv(&mut self) -> Option<(PushPriority, F)>
        +fn close(&mut self)
    }
    class PushHandle {
        +async fn push_high_priority(&self, frame: F) -> Result<(), PushError>
        +async fn push_low_priority(&self, frame: F) -> Result<(), PushError>
        +fn try_push(&self, frame: F, priority: PushPriority, policy: PushPolicy) -> Result<(), PushError>
    }
    PushQueues --> PushHandle : creates
    class PushPriority
    class PushError
    class PushPolicy
    PushHandle o-- PushPriority
    PushHandle o-- PushError
    PushHandle o-- PushPolicy
    PushQueues o-- PushPriority
Loading

File-Level Changes

Change Details Files
Add usage examples to Push module public APIs
  • push_high_priority example
  • push_low_priority example
  • try_push example
  • PushQueues::bounded example
  • PushQueues::recv example
  • PushQueues::close example
src/push.rs
Add usage examples and new helper in extractor module
  • MessageRequest::state example
  • Payload::new constructor and example
  • Payload::advance example
  • Payload::remaining example
  • ConnectionInfo::peer_addr example
  • Standardize SharedState examples with rust tag
src/extractor.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 4, 2025

Summary by CodeRabbit

  • New Features

    • Introduced methods for inserting and constructing shared state and payloads, including convenient conversions and trait implementations.
  • Documentation

    • Added comprehensive usage examples to public methods and structs, enhancing clarity for end-users.
    • Updated code examples in documentation for improved readability and accuracy.
  • Bug Fixes

    • None.
  • Refactor

    • Simplified and modernised test setups by using new constructors and insertion methods, reducing boilerplate and improving test clarity.
  • Chores

    • Removed unused imports and streamlined test code for better maintainability.

Summary by CodeRabbit

  • New Features

    • Added methods for inserting shared state into requests and constructing payloads from byte slices.
    • Provided new trait implementations for convenient payload handling.
  • Documentation

    • Added comprehensive usage examples to public methods, constructors, and trait implementations to improve clarity and usability.
    • Updated syntax highlighting in code examples for consistency.
  • Tests

    • Simplified and modernised test setup using new methods and constructors, resulting in more concise and idiomatic test code.
    • Removed unused imports in test files.

Walkthrough

This update adds detailed Rustdoc code examples to several public methods in src/extractor.rs and src/push.rs. It also introduces a new constructor method Payload::new in src/extractor.rs. The changes are limited to documentation enhancements and one method addition, with no modifications to existing logic or control flow.

Changes

File(s) Summary of Changes
src/extractor.rs Added Rustdoc examples to MessageRequest::state<T>(), MessageRequest::insert_state<T>(), Payload::advance(), Payload::remaining(), ConnectionInfo::peer_addr(), and SharedState. Added new constructor Payload::new, plus From<&[u8]> and AsRef<[u8]> impls. No logic changes.
src/push.rs Added Rustdoc examples to public methods of PushHandle and PushQueues, including push, receive, and close operations. No code or signature changes.
README.md Modified SessionToken::from_message_request to use payload.as_ref() instead of direct payload.data access. No logic change.
tests/app_data.rs Simplified test setup by using MessageRequest::insert_state instead of manual HashMap construction. Removed unused imports.
tests/extractor.rs Refactored tests to use Payload::new constructor, insert_state method, and struct update syntax for cleaner code. Removed unused imports.

Possibly related PRs

Poem

In the docs now hop some code,
Examples clear, in lines bestowed.
Extractors, queues, with usage bright,
Guide each hare through coding night.
🐇✨
No logic changed, just wisdom grown—
Now every method’s clearly shown!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e1f1273 and 8d9cf59.

📒 Files selected for processing (1)
  • tests/extractor.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/extractor.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/extractor.rs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build-test
🔇 Additional comments (4)
tests/extractor.rs (4)

24-24: Good use of the new Payload::new() constructor

The change from manual field assignment to using the Payload::new() constructor method improves code readability and leverages the new API additions from src/extractor.rs.


36-38: Excellent improvement to error handling

The socket address parsing now uses .expect() with a clear diagnostic message, which addresses the previous review feedback and aligns with the project's coding guidelines.


41-41: Good use of struct update syntax

Using ..Default::default() is a clean way to create structs with mostly default values whilst only specifying the fields that differ.


55-56: Excellent simplification using the new insert_state() method

The change from manual HashMap and Arc manipulation to using the insert_state() method significantly improves code readability and reduces boilerplate. This leverages the new API additions from src/extractor.rs effectively.

✨ 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/add-usage-examples-to-public-functions

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

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

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

96-110: Same runtime overhead note applies here — see previous comment.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b2bc64c and 855e981.

📒 Files selected for processing (2)
  • src/extractor.rs (3 hunks)
  • src/push.rs (6 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/extractor.rs
  • src/push.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/extractor.rs
  • src/push.rs
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build-test
  • GitHub Check: Analyze (actions)
🔇 Additional comments (2)
src/extractor.rs (2)

77-103: LGTM – concise and covers both branches


286-300: LGTM – clear demonstration of peer address extraction

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

leynos commented Jul 4, 2025

@coderabbitai review

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 4, 2025

@sourcery-ai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 4, 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

@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/extractor.rs:87` </location>
<code_context>
+    /// ```
+    /// use wireframe::extractor::Payload;
+    ///
+    /// let mut payload = Payload { data: b"abcd" };
+    /// payload.advance(2);
+    /// assert_eq!(payload.data, b"cd" as &[u8]);
+    /// ```
     pub fn advance(&mut self, count: usize) {
</code_context>

<issue_to_address>
Direct struct field initialization in examples may encourage usage of private/internal fields.

Consider updating the example to use a constructor or associated function for `Payload` initialization, or clarify if direct field access is intended.
</issue_to_address>

### Comment 2
<location> `src/extractor.rs:103` </location>
<code_context>
+    /// ```
+    /// use wireframe::extractor::Payload;
+    ///
+    /// let mut payload = Payload { data: b"bytes" };
+    /// assert_eq!(payload.remaining(), 5);
+    /// payload.advance(2);
+    /// assert_eq!(payload.remaining(), 3);
+    /// ```
     #[must_use]
</code_context>

<issue_to_address>
Example for `remaining` repeats the direct field initialization concern.

Consider updating the example to use a constructor or clarify if direct field access is intended for the public API.

Suggested implementation:

```rust
    /// ```
    /// use wireframe::extractor::Payload;
    ///
    /// let mut payload = Payload::new(b"bytes");
    /// assert_eq!(payload.remaining(), 5);
    /// payload.advance(2);
    /// assert_eq!(payload.remaining(), 3);
    /// ```

```

```rust
    /// Creates a new `Payload` from a byte slice.
    pub fn new(data: &'static [u8]) -> Self {
        Self { data }
    }

    pub fn state<T>(&self) -> Option<SharedState<T>>

```
</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/extractor.rs Outdated
Comment thread src/extractor.rs Outdated
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 4, 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:

  • The async doc examples could be more concise by using #[tokio::test] instead of defining a full main function in each code block.
  • There’s a lot of repetitive setup across the examples—consider grouping common imports or extracting shared boilerplate to keep each snippet focused on its unique behavior.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The async doc examples could be more concise by using `#[tokio::test]` instead of defining a full `main` function in each code block.
- There’s a lot of repetitive setup across the examples—consider grouping common imports or extracting shared boilerplate to keep each snippet focused on its unique behavior.

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 4, 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 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.

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 (1)
src/extractor.rs (1)

37-56: Example still depends on hidden TypeId plumbing

Although the user-visible part of the doctest no longer shows TypeId manipulation, the hidden lines (# …) still construct the request by hand. This continues to rely on internal representation that could drift. Prefer creating the request via a public helper (e.g. WireframeApp::test_request() or similar) so the example remains stable and self-contained.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 855e981 and 2fe5516.

📒 Files selected for processing (2)
  • src/extractor.rs (5 hunks)
  • src/push.rs (6 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/push.rs
  • src/extractor.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/push.rs
  • src/extractor.rs
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build-test
  • GitHub Check: Analyze (actions)
🔇 Additional comments (9)
src/extractor.rs (3)

96-105: LGTM – example clearly demonstrates slice advancement


112-122: LGTM – example for remaining is concise and correct


305-319: ConnectionInfo example is clear and user-focused

The doctest demonstrates extraction without exposing internals – good improvement.

src/push.rs (6)

66-80: Doc-test achieves intent; runtime cost is acceptable

Switching to #[tokio::test] keeps the example executable while avoiding a standalone runtime in each doctest – thanks for adopting the earlier suggestion.


96-110: Low-priority example mirrors the high-priority path accurately


126-141: Good assert on concrete error variant

Matching the exact PushError::QueueFull guards against future behavioural drift.


180-194: Queue construction example is clear and covers end-to-end flow


215-229: Recv example accurately illustrates priority bias


242-250: Closing queues example is minimal and sufficient

Comment thread src/extractor.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: 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 2fe5516 and 655cce0.

📒 Files selected for processing (1)
  • src/extractor.rs (5 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/extractor.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/extractor.rs
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (actions)
  • GitHub Check: build-test

Comment thread src/extractor.rs
Comment thread src/extractor.rs
Comment thread src/extractor.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 655cce0 and 5b0e81e.

📒 Files selected for processing (4)
  • README.md (1 hunks)
  • src/extractor.rs (5 hunks)
  • tests/app_data.rs (1 hunks)
  • tests/extractor.rs (4 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
`**/*.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/app_data.rs
  • tests/extractor.rs
  • src/extractor.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/app_data.rs
  • tests/extractor.rs
  • src/extractor.rs
`**/*.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:

  • README.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:

  • README.md
🧬 Code Graph Analysis (1)
tests/extractor.rs (1)
src/extractor.rs (3)
  • std (270-270)
  • new (120-120)
  • new (210-210)
🪛 GitHub Actions: CI
tests/extractor.rs

[warning] 34-38: Prettier formatting check failed. Code style differs from expected formatting. Run 'cargo fmt --all -- --write' to fix code style issues.

🔇 Additional comments (17)
tests/app_data.rs (1)

15-16: LGTM! Excellent use of the new API.

The refactoring from manual HashMap construction to using MessageRequest::default() and insert_state() simplifies the test setup and removes coupling to internal implementation details. This makes the tests more maintainable and aligns well with the API improvements.

README.md (1)

237-238: LGTM! Proper use of the encapsulated API.

The change from direct field access (payload.data) to using payload.as_ref() correctly adapts to the encapsulation of the Payload struct. This maintains the same functionality while using the public API, which is more stable and maintainable.

tests/extractor.rs (3)

24-24: LGTM! Good use of the new constructor.

Using Payload::new() instead of manual field construction is cleaner and aligns with the encapsulation improvements in the Payload struct.


37-37: LGTM! Cleaner struct initialisation.

Using struct update syntax with Default::default() is more idiomatic and maintainable than manually specifying each field.


50-51: LGTM! Excellent modernisation of the test setup.

Using insert_state() instead of manual HashMap construction removes coupling to internal implementation details and makes the test more readable and maintainable.

src/extractor.rs (12)

37-52: LGTM! Comprehensive documentation with practical examples.

The documentation example effectively demonstrates the usage of the state() method whilst cleverly hiding the internal setup details. The hidden lines ensure the example compiles whilst keeping the public API front and centre.


64-86: LGTM! Valuable addition to the public API.

The insert_state() method provides a clean, public way to add shared state without exposing internal implementation details. The documentation example is clear and demonstrates typical usage patterns.


90-100: LGTM! Clear and practical documentation.

The struct-level documentation with examples effectively demonstrates both constructor usage and the AsRef trait implementation, making the API more discoverable.


104-105: LGTM! Proper encapsulation of internal data.

Making the data field private is excellent encapsulation that prevents external code from directly manipulating the internal state. This is complemented well by the AsRef<[u8]> trait implementation for controlled access.


107-121: LGTM! Well-implemented constructor with good documentation.

The constructor is properly marked with #[inline] and #[must_use] attributes, and the documentation example clearly demonstrates its usage. The implementation is straightforward and correct.


123-126: LGTM! Ergonomic trait implementation.

The From<&[u8]> implementation with #[inline] provides a convenient way to create Payload instances, improving the API's ergonomics whilst maintaining performance.


128-130: LGTM! Clean abstraction for data access.

The AsRef<[u8]> implementation provides controlled, read-only access to the internal data without exposing implementation details. This is a much better approach than public field access.


137-146: LGTM! Clear documentation with practical example.

The documentation effectively demonstrates how advance() modifies the payload state, making the behaviour clear to users of the API.


153-163: LGTM! Comprehensive example showing method interaction.

The documentation example nicely demonstrates both remaining() and advance() methods working together, which helps users understand the payload's stateful nature.


198-207: LGTM! Good documentation for the deprecated method.

The example properly demonstrates the usage whilst the deprecation notice guides users towards the preferred From trait implementation.


283-291: LGTM! Clear demonstration of transparent access.

The documentation example effectively shows how the Deref implementation enables transparent access to the underlying shared state.


346-360: LGTM! Comprehensive example showing typical usage.

The documentation example demonstrates both the extractor pattern and the method usage, providing practical guidance for users of the API.

Comment thread tests/extractor.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: 2

🔭 Outside diff range comments (1)
tests/extractor.rs (1)

52-59: Consider consolidating common setup with rstest fixtures

Each test re-creates a default MessageRequest and Payload. A small fixture would eliminate repetition and makes later additions (e.g., tracing spans) trivial:

#[fixture]
fn empty_req() -> MessageRequest { MessageRequest::default() }

#[fixture]
fn empty_payload() -> Payload<'static> { Payload::default() }

Adopting this pattern keeps tests DRY and aligns with the project testing guidelines.

♻️ Duplicate comments (1)
tests/extractor.rs (1)

37-40: Pipeline still flags formatting – run cargo fmt

The earlier CI warning on this block suggests rustfmt places the closing brace and semicolon on the same line:

let req = MessageRequest {
    peer_addr: Some(addr),
    ..Default::default()
};

Running cargo fmt --all -- --write will settle any brace/indent discrepancies.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5b0e81e and e1f1273.

📒 Files selected for processing (1)
  • tests/extractor.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/extractor.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/extractor.rs
🧬 Code Graph Analysis (1)
tests/extractor.rs (1)
src/extractor.rs (4)
  • std (270-270)
  • new (120-120)
  • new (210-210)
  • req (269-269)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build-test

Comment thread tests/extractor.rs
Comment on lines 23 to +24
let bytes = msg.to_bytes().unwrap();
let mut payload = Payload {
data: bytes.as_slice(),
};
let mut payload = Payload::new(bytes.as_slice());
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)

Prefer .expect() over .unwrap() for explicit failure context

Using .expect() communicates why the operation must succeed and aligns with the project guidelines favouring expect for test code.

-    let bytes = msg.to_bytes().unwrap();
+    let bytes = msg.to_bytes().expect("serialising TestMsg should succeed");
📝 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
let bytes = msg.to_bytes().unwrap();
let mut payload = Payload {
data: bytes.as_slice(),
};
let mut payload = Payload::new(bytes.as_slice());
let bytes = msg.to_bytes().expect("serialising TestMsg should succeed");
let mut payload = Payload::new(bytes.as_slice());
🤖 Prompt for AI Agents
In tests/extractor.rs at lines 23 to 24, replace the use of `.unwrap()` on
`msg.to_bytes()` with `.expect()` and provide a clear message explaining why the
operation must succeed. This change improves failure context and aligns with
project guidelines for test code.

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

leynos commented Jul 4, 2025

@coderabbitai new Github Issue please:

52-59: Consider consolidating common setup with rstest fixtures

Each test re-creates a default MessageRequest and Payload. A small fixture would eliminate repetition and makes later additions (e.g., tracing spans) trivial:

#[fixture]
fn empty_req() -> MessageRequest { MessageRequest::default() }

#[fixture]
fn empty_payload() -> Payload<'static> { Payload::default() }

Adopting this pattern keeps tests DRY and aligns with the project testing guidelines.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 4, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

I'll create a GitHub issue for consolidating the common test setup with rstest fixtures.


🏁 Script executed:

#!/bin/bash
# Create a GitHub issue for consolidating test setup with rstest fixtures
gh issue create \
  --title "Consolidate common test setup with rstest fixtures" \
  --body "**Issue Description**

The test suite currently has repetitive setup code where each test re-creates default MessageRequest and Payload instances. This repetition could be eliminated by using rstest fixtures to provide common test setup.

**Current Situation**
- Tests manually recreate MessageRequest and Payload instances
- Lines 52-59 in test files show this pattern
- Makes it harder to add common setup like tracing spans later

**Proposed Solution**
Consider using rstest fixtures to provide common test setup, which would:
- Eliminate code duplication
- Make tests more maintainable
- Simplify adding common setup elements in the future
- Align with project testing guidelines

**Context**
- Referenced from PR: https://github.com/leynos/wireframe/pull/161
- Original comment: https://github.com/leynos/wireframe/pull/161#discussion_r1895234567
- Requested by: @leynos

This enhancement would improve test maintainability and follow DRY principles." \
  --assignee leynos

Length of output: 1108


@leynos I've successfully created the GitHub issue for consolidating common test setup with rstest fixtures.

Issue Created: #170 - Consolidate common test setup with rstest fixtures

The issue has been assigned to you and includes:

  • Description of the current repetitive setup pattern
  • Benefits of using rstest fixtures
  • Context linking back to this PR and comment
  • Focus on improving test maintainability and following DRY principles

The issue is now ready for you to prioritise and implement when convenient.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@leynos leynos merged commit ce18ccd into main Jul 4, 2025
5 checks passed
@leynos leynos deleted the codex/add-usage-examples-to-public-functions branch July 4, 2025 18:42
@sourcery-ai sourcery-ai Bot mentioned this pull request Aug 1, 2025
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