Skip to content

Conversation

leynos
Copy link
Owner

@leynos leynos commented Aug 10, 2025

Summary

  • trim and clarify preamble handler documentation
  • mark ServerError as non-exhaustive
  • reuse existing PhantomData when rebinding

Testing

  • make lint
  • make test

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

Summary by Sourcery

Clarify preamble handler documentation, mark the ServerError enum as non-exhaustive, reuse existing PhantomData in server bindings, and adjust preamble handler error logging format.

Enhancements:

  • Reuse existing PhantomData for server bindings instead of creating a new one
  • Change preamble handler error logging specifier to use % for error display
  • Mark ServerError enum as non-exhaustive for future extensibility

Documentation:

  • Refine PreambleHandler doc comment to explain it’s a PreambleSuccessHandler wrapped in Arc
  • Add reference to PreambleHandler alias in preamble config documentation

Copy link
Contributor

sourcery-ai bot commented Aug 10, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

This PR refines how preamble handlers are documented and wired by preserving existing PhantomData in binding builders, improving error logging formatting for failed preamble handlers, and marking the server error enum as non-exhaustive.

File-Level Changes

Change Details Files
Reuse existing PhantomData when rebinding
  • Preserve self._preamble instead of instantiating a new PhantomData
  • Apply change in both Bound and Pending builder methods
src/server/config/binding.rs
Improve tracing error formatting for preamble handler
  • Switch error formatting in tracing::error from debug (?e) to display (%e)
src/server/connection.rs
Clarify preamble handler documentation
  • Reword type alias doc to indicate Arc-wrapped handler
  • Add reference to PreambleHandler alias in config preamble docs
src/server/mod.rs
src/server/config/preamble.rs
Mark ServerError enum as non-exhaustive
  • Add #[non_exhaustive] attribute to ServerError
src/server/error.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

Copy link
Contributor

coderabbitai bot commented Aug 10, 2025

Note

Other AI code review bot(s) detected

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

Warning

Rate limit exceeded

@leynos has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 17 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 1b1a36f and 8c21bf1.

📒 Files selected for processing (2)
  • CHANGELOG.md (1 hunks)
  • src/server/connection.rs (1 hunks)

Summary by CodeRabbit

  • New Features

    • None.
  • Refactor

    • Improved connection error logging with clearer messages for preamble handling outcomes.
  • Documentation

    • Clarified handler type alias descriptions and builder callback docs.
    • Updated changelog: noted that the server error type is now non-exhaustive and removed an outdated deprecation note.
  • Chores

    • Removed unused import and streamlined internal initialisation to preserve existing state.
  • Tests

    • None.

Walkthrough

Preserve the existing _preamble field when binding listeners, remove an unused PhantomData import, improve preamble error log formatting, mark ServerError as #[non_exhaustive], and clarify documentation for preamble handler types and builder callbacks.

Changes

Cohort / File(s) Change Summary
WireframeServer Binding & Imports
src/server/config/binding.rs
Remove unused core::marker::PhantomData import; use self._preamble instead of PhantomData::default() in bind_listener.
Preamble Handler Documentation
src/server/config/preamble.rs
Add cross-reference to crate::server::PreambleHandler in on_preamble_decode_success doc comment.
Error Logging Format
src/server/connection.rs
Log preamble handler errors with both display (%e) and debug (?e) fields while retaining peer address.
ServerError Enum Annotation
src/server/error.rs
Add #[non_exhaustive] attribute to the ServerError enum.
PreambleHandler Type Doc
src/server/mod.rs
Update doc comment for pub type PreambleHandler<T> to describe it as [PreambleSuccessHandler] wrapped in Arc.
Changelog
CHANGELOG.md
Remove deprecation note for SharedState::new; add entry noting ServerError is now #[non_exhaustive].

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant PreambleHandler

    Client->>Server: Connect and send preamble
    Server->>PreambleHandler: Decode preamble and invoke callback
    alt Preamble decode success
        PreambleHandler-->>Server: Success result
        Server-->>Client: Proceed with connection
    else Preamble decode error
        PreambleHandler-->>Server: Error (returned)
        Server-->>Server: Log error with display and debug fields
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

Poem

Preserve the preamble, keep its thread,
Docs point the way, so no one’s misled.
Errors now logged with both face and file,
Enum keeps space for growth and style.
PhantomData gone — tidy the spread. 🚀

✨ 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/update-preamblehandler-documentation

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Status, Documentation and Community

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

Copy link
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/server/connection.rs:67` </location>
<code_context>
                 && let Err(e) = handler(&preamble, &mut stream).await
             {
-                tracing::error!(error = ?e, ?peer_addr, "preamble handler error");
+                tracing::error!(error = %e, ?peer_addr, "preamble handler error");
             }
             let stream = RewindStream::new(leftover, stream);
</code_context>

<issue_to_address>
Switching from ?e to %e in tracing may affect error formatting.

Switching to %e uses Display formatting for errors. Please verify that this provides the necessary detail and is appropriate for your error type.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
                tracing::error!(error = %e, ?peer_addr, "preamble handler error");
=======
                tracing::error!(
                    error_display = %e,
                    error_debug = ?e,
                    ?peer_addr,
                    "preamble handler error"
                );
>>>>>>> REPLACE

</suggested_fix>

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
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 071fdfd and 7cc11be.

📒 Files selected for processing (5)
  • src/server/config/binding.rs (2 hunks)
  • src/server/config/preamble.rs (1 hunks)
  • src/server/connection.rs (1 hunks)
  • src/server/error.rs (1 hunks)
  • src/server/mod.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Function documentation must include clear examples demonstrating the usage and outcome of the function. Test documentation should omit examples where the example serves only to reiterate the test logic.
No single code file may be longer than 400 lines. Long switch statements or dispatch tables should be broken up by feature and constituents colocated with targets. Large blocks of test data should be moved to external data files.
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.
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.
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.
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().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer semantic error enums. Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status....

Files:

  • src/server/config/preamble.rs
  • src/server/error.rs
  • src/server/connection.rs
  • src/server/mod.rs
  • src/server/config/binding.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/server/config/preamble.rs
  • src/server/error.rs
  • src/server/connection.rs
  • src/server/mod.rs
  • src/server/config/binding.rs
🧬 Code Graph Analysis (1)
src/server/connection.rs (1)
src/extractor.rs (1)
  • peer_addr (362-362)
🔍 MCP Research (1 server)

Deepwiki:

  • The _preamble field in WireframeServer is a PhantomData<T> marker used to associate the server with a specific preamble type T. This field does not store data but enforces type safety related to preamble handling. The change in the PR to reuse the existing _preamble field instead of resetting it to a new PhantomData instance preserves the original type marker, aligning with the design that this field is a type-level marker rather than a data container. (Wiki page "WireframeServer")

  • The bind method in WireframeServer is responsible for binding the server to a socket address and creating a TcpListener, but it does not directly handle the _preamble field or its callbacks. Preamble handling occurs later during connection processing in the process_stream function, where the preamble is decoded and success or failure callbacks are invoked. The _preamble field and related callbacks are part of the server's state carried through the builder chain. (Wiki page "WireframeServer")

  • The process_stream function in WireframeServer's worker tasks reads the preamble from the TCP stream using read_preamble::<_, T>(&mut stream). On successful decode, it calls the success callback with the preamble and stream; on failure, it calls the failure callback and drops the connection. Leftover bytes from preamble decoding are wrapped in a RewindStream for further processing by the application. (Wiki page "WireframeServer")

🔇 Additional comments (5)
src/server/config/preamble.rs (1)

58-58: Tighten cross-reference to the ready-to-use alias.

Keep this link to PreambleHandler; it improves discoverability for users of the builder API.

src/server/connection.rs (1)

67-67: Use Display (%) for error logging.

Prefer % here for human-readable logs. This aligns the log output with user-facing error messages.

src/server/mod.rs (1)

59-59: Clarify the alias documentation.

Keep the updated doc: “[PreambleSuccessHandler] wrapped in Arc.” It is precise and reduces ambiguity about the trait object.

src/server/config/binding.rs (2)

94-95: Reuse the existing _preamble typestate marker.

Retain self._preamble instead of instantiating a new PhantomData. This preserves the type marker and complies with the typestate design.


179-180: Preserve _preamble during rebinds.

Keep passing through self._preamble on rebind. This correctly carries the preamble type across bindings.

Repository owner deleted a comment from sourcery-ai bot Aug 10, 2025
Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Greptile Summary

This PR makes targeted improvements to the Wireframe server's API design and documentation quality. The changes focus on three main areas: enhanced type documentation, defensive API design, and minor code optimizations.

The preamble handler documentation has been refined to provide clearer guidance for developers. The PreambleHandler type alias documentation now succinctly explains that it's simply a PreambleSuccessHandler wrapped in Arc, eliminating unnecessary verbosity. Additionally, the preamble configuration documentation now includes a helpful reference to the PreambleHandler alias, making the API more discoverable for users who might prefer the ready-to-use type over implementing the trait directly.

A key architectural change involves marking the ServerError enum as #[non_exhaustive]. This is a forward-thinking API design decision that allows future error variants to be added without breaking downstream code that pattern matches on the enum. The change is properly documented in the changelog with clear guidance for users.

The PR also includes a micro-optimization in the server binding logic where existing PhantomData instances are reused instead of creating new ones during server rebinding operations. Since the preamble type remains unchanged during rebinding, reusing the existing phantom data marker is both semantically correct and slightly more efficient.

These changes integrate well with the existing Wireframe architecture, maintaining the library's focus on type safety while improving maintainability and user experience.

Important Files Changed

Files Changed
Filename Score Overview
src/server/error.rs 5/5 Added #[non_exhaustive] attribute to ServerError enum for future extensibility
src/server/config/preamble.rs 5/5 Enhanced documentation with PreambleHandler reference and reused existing PhantomData
CHANGELOG.md 5/5 Documented the ServerError non-exhaustive change with user guidance
src/server/mod.rs 5/5 Simplified PreambleHandler documentation for better clarity
src/server/config/binding.rs 5/5 Reused existing PhantomData instances during server rebinding operations

Confidence score: 5/5

  • This PR is safe to merge with minimal risk as it contains well-designed improvements and defensive coding practices
  • Score reflects thoughtful API design changes, clear documentation improvements, and proper handling of the breaking change through changelog documentation
  • No files require special attention as all changes are straightforward and follow Rust best practices

5 files reviewed, no comments

Edit Code Review Bot Settings | Greptile

@leynos
Copy link
Owner Author

leynos commented Aug 13, 2025

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Aug 13, 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
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

♻️ Duplicate comments (1)
src/server/connection.rs (1)

67-72: Log both Display and Debug forms of the error.

Keep this. It provides concise human-readable context and the detailed debug form for diagnostics. This aligns with the earlier suggestion.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7cc11be and 1b1a36f.

📒 Files selected for processing (2)
  • CHANGELOG.md (1 hunks)
  • src/server/connection.rs (1 hunks)
🧰 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
  • 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:

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

  • Use rstest fixtures for shared setup and to avoid repetition between tests.

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

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

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

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

  • Files must not exceed 400 lines in length

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

Files:

  • src/server/connection.rs
🧬 Code Graph Analysis (1)
src/server/connection.rs (1)
src/extractor.rs (1)
  • peer_addr (362-362)
🔍 Additional research (Context7)

Summary of relevant context discovered for reviewing PR #300:

  • The repo's docs/wiki include extensive, up-to-date design and implementation details for WireframeServer, ConnectionActor, preamble handling, ProtocolHooks/PreambleHandler, push queues, error handling, and observability — all areas touched by this PR. These pages confirm the semantics of preamble callbacks, how RewindStream/leftover bytes are handled, connection logging/tracing, and ServerError usage patterns (affects non-exhaustive change).,

  • The library identifier resolution succeeded for the repository (context7 listing output). Useful for locating code/docs in Context7 if deeper doc fetches are needed.

  • Items directly relevant to the PR:

    • Preamble: docs show on_preamble_decode_success is the documented hook and that handlers commonly use a PreambleHandler / ProtocolHooks to register PushHandle etc.; updating docs to reference crate::server::PreambleHandler aligns with existing patterns.
    • Bind/listener logic & PhantomData: server bind/rebind behavior and WireframeServer factory/worker patterns are documented (preserving existing _preamble vs replacing is consistent with keeping connection-specific state).
    • Connection logging: connection and preamble error logging is instrumented via tracing; changing log field formats to include both display and debug forms fits existing tracing usage.
    • ServerError design: docs describe error classification (Io vs Protocol); marking ServerError #[non_exhaustive] is compatible with the stated goal of allowing future variants.
    • Tests/CI: repo uses make lint/test and CI workflows; PR claim that make lint / make test passed is consistent with repo policies.

If you want, I can:

  • Fetch the exact source diffs or files referenced (binding.rs, preamble.rs, connection.rs, error.rs, mod.rs, CHANGELOG.md) for line-by-line review.
  • Run a focused search for tests referencing ServerError matches or preamble handler docs to confirm downstream impacts.

Tool calls used:,,

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

2 files reviewed, no comments

Edit Code Review Bot Settings | Greptile

@leynos leynos merged commit 7347409 into main Aug 13, 2025
5 checks passed
@leynos leynos deleted the codex/update-preamblehandler-documentation branch August 13, 2025 19:01
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