Skip to content

Extract config tests into dedicated module#278

Merged
leynos merged 6 commits intomainfrom
codex/extract-test-module-from-config.rs
Aug 6, 2025
Merged

Extract config tests into dedicated module#278
leynos merged 6 commits intomainfrom
codex/extract-test-module-from-config.rs

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Aug 6, 2025

Summary

  • split server config tests into src/server/config/tests.rs to keep implementation concise
  • expose tests via #[cfg(test)] module

Testing

  • make fmt
  • make lint
  • make test

closes #274


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

Summary by Sourcery

Extract server configuration builder API into a dedicated config module, simplify WireframeServer state handling, and relocate configuration tests.

Enhancements:

  • Remove the Bound state generic and consolidate the listener field directly on WireframeServer
  • Implement configuration methods (new, with_preamble, workers, callbacks, bind) in src/server/config module
  • Add Rustdoc examples to server runtime methods for run and run_with_shutdown

Documentation:

  • Add Rustdoc comments and usage examples for WireframeServer methods

Tests:

  • Relocate and expand server configuration tests into src/server/config/tests.rs covering worker settings, binding behavior, and callback registration

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Aug 6, 2025

Reviewer's Guide

This PR refactors the server configuration API by extracting its tests into a dedicated module behind cfg(test), restructures the config builder into its own module (removing type-level bound states), and enhances the WireframeServer runtime methods with improved documentation and example usage.

File-Level Changes

Change Details Files
Restructure server configuration API into a dedicated module and simplify listener state
  • Introduce src/server/config/mod.rs containing builder impls for WireframeServer
  • Remove Unbound/Bound state generics in server/mod.rs and replace with Option
  • Update bind_server signature in test_util to match new WireframeServer type
src/server/config/mod.rs
src/server/mod.rs
src/server/test_util.rs
Extract server config tests into a separate tests module under cfg(test)
  • Create src/server/config/tests.rs with full test suite covering builder and behavior
  • Add #[cfg(test)] mod tests declaration in config/mod.rs
  • Remove inline or legacy tests from previous config implementation
src/server/config/mod.rs
src/server/config/tests.rs
Enhance WireframeServer runtime methods with examples and simplify implementation
  • Remove Bound type from impl signature of Runtime methods
  • Add doc tests for run and run_with_shutdown methods
  • Unwrap listener Option and inline error for unbound listener
src/server/runtime.rs

Assessment against linked issues

Issue Objective Addressed Explanation
#274 Reduce the length of src/server/config.rs to comply with the 400-line limit coding guideline.
#274 Extract the large test module from src/server/config.rs into a dedicated module or file.

Possibly linked issues


Tips and commands

Interacting with Sourcery

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

Customizing Your Experience

Access your dashboard to:

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

Getting Help

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 6, 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.

Summary by CodeRabbit

  • Refactor

    • Simplified the server configuration interface for easier and more flexible setup.
    • Removed internal state marker types and replaced them with a more straightforward binding mechanism.
    • Streamlined the server structure by embedding listener management directly.
  • New Features

    • Introduced a builder-style API for server configuration, including worker count, preamble handling, and readiness signalling.
    • Added comprehensive documentation and usage examples for server methods.
  • Tests

    • Added extensive tests covering server initialisation, configuration, binding, callback registration, and method chaining.
  • Chores

    • Improved code clarity by removing obsolete or redundant code.

Walkthrough

Remove the original src/server/config.rs file, splitting its logic into a new modular structure. Add src/server/config/mod.rs to house the configuration and binding logic for WireframeServer, and move all tests into a dedicated src/server/config/tests.rs file. Maintain all previous functionality and test coverage with this reorganisation.

Changes

Cohort / File(s) Change Summary
Remove monolithic config.rs
src/server/config.rs
Delete the original config file, including all implementation and tests for WireframeServer configuration and binding.
Add modular config implementation
src/server/config/mod.rs
Introduce a new module for WireframeServer configuration, splitting logic into generic, typestate-tracked builder methods.
Add dedicated config tests
src/server/config/tests.rs
Move all tests from the original config file to a separate test module, preserving and expanding test coverage.
Modify server core struct
src/server/mod.rs
Remove Unbound and Bound state types; simplify WireframeServer by removing state parameter and adding optional listener field.
Update runtime server logic
src/server/runtime.rs
Remove Bound state usage; add explicit check for listener presence in run_with_shutdown.
Update test utility
src/server/test_util.rs
Remove Bound type parameter from bind_server function signature and imports.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant WireframeServer
    participant OS
    participant Tokio

    User->>WireframeServer: new(factory)
    User->>WireframeServer: workers(count)
    User->>WireframeServer: with_preamble(P)
    User->>WireframeServer: on_preamble_decode_success(handler)
    User->>WireframeServer: on_preamble_decode_failure(handler)
    User->>WireframeServer: ready_signal(tx)
    User->>WireframeServer: bind(addr)
    WireframeServer->>OS: create StdTcpListener
    WireframeServer->>Tokio: convert to Tokio TcpListener
    WireframeServer->>WireframeServer: update listener field
    User->>WireframeServer: local_addr()
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Decompose src/server/config.rs to comply with 400-line limit (#274)
Extract test module from src/server/config.rs (#274)
Maintain all existing configuration and binding logic in new structure (#274)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes detected.

Possibly related PRs

Poem

Split the config, neat and keen,
No more lines in a single scene!
Tests now live in their own domain,
Builder patterns rise again.
Code is tidy, structure bright—
Wireframe’s future looking right!
🎉🦀


📜 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 f793c95 and 7ffae35.

📒 Files selected for processing (6)
  • src/server/config.rs (0 hunks)
  • src/server/config/mod.rs (1 hunks)
  • src/server/config/tests.rs (1 hunks)
  • src/server/mod.rs (2 hunks)
  • src/server/runtime.rs (4 hunks)
  • src/server/test_util.rs (2 hunks)
💤 Files with no reviewable changes (1)
  • src/server/config.rs
🧰 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/test_util.rs
  • src/server/config/tests.rs
  • src/server/runtime.rs
  • src/server/mod.rs
  • src/server/config/mod.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/test_util.rs
  • src/server/config/tests.rs
  • src/server/runtime.rs
  • src/server/mod.rs
  • src/server/config/mod.rs
🧬 Code Graph Analysis (1)
src/server/config/mod.rs (3)
tests/preamble.rs (1)
  • oneshot (71-71)
src/server/test_util.rs (2)
  • WireframeServer (44-44)
  • factory (18-20)
src/server/config/tests.rs (2)
  • WireframeServer (60-60)
  • WireframeServer (135-137)
🔇 Additional comments (5)
src/server/test_util.rs (1)

8-8: Changes correctly reflect the simplified server state management.

The removal of the Bound import and simplification of the return type align perfectly with the elimination of the state marker pattern from WireframeServer.

Also applies to: 31-31

src/server/mod.rs (1)

36-62: Excellent simplification of the server state management.

The replacement of the generic state parameter with an optional listener field eliminates unnecessary type-level complexity whilst maintaining all functionality. This architectural improvement makes the code more maintainable and easier to understand.

src/server/runtime.rs (2)

25-25: Implementation correctly handles the simplified server structure.

The removal of the Bound type parameter and direct access to the optional listener field with appropriate error handling maintains the same runtime behaviour whilst reducing complexity.

Also applies to: 100-104


34-46: Documentation examples enhance usability.

The added examples for run and run_with_shutdown methods clearly demonstrate usage patterns and comply with the coding guidelines requirement for function documentation examples.

Also applies to: 61-85

src/server/config/mod.rs (1)

1-261: Well-structured configuration module with excellent documentation.

The module successfully:

  • Implements a clean builder-style API
  • Provides comprehensive documentation with examples for all public functions
  • Maintains file length well under the 400-line limit
  • Follows all coding guidelines for Rust modules
✨ 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/extract-test-module-from-config.rs

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

Support

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

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

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

Choose a reason for hiding this comment

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

Gates Failed
Enforce advisory code health rules (1 file with Code Duplication)

Gates Passed
5 Quality Gates Passed

See analysis details in CodeScene

Reason for failure
Enforce advisory code health rules Violations Code Health Impact
tests.rs 1 advisory rule 10.00 → 9.39 Suppress

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

Comment thread src/server/config/tests.rs Outdated
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

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

Blocking issues:

  • Use of #[allow(clippy::too_many_arguments)] is forbidden; use a narrowly scoped #[expect(...)] with a reason instead. (link)
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `src/server/config/mod.rs:20` </location>
<code_context>
-use super::{Bound, PreambleCallback, PreambleErrorCallback, Unbound, WireframeServer};
-use crate::{app::WireframeApp, preamble::Preamble};
-
-impl<F> WireframeServer<F, (), Unbound>
-where
-    F: Fn() -> WireframeApp + Send + Sync + Clone + 'static,
</code_context>

<issue_to_address>
Consider replacing the Unbound/Bound state generics with an Option<Arc<TcpListener>> field to unify the server implementation.

Here’s a sketch of how you can collapse the two‐state generic (“Unbound” vs “Bound”) into one struct with an `Option<Arc<TcpListener>>`.  That lets you:

  * remove both the `impl<…Unbound>` and `impl<…Bound>` blocks  
  * have one unified `bind` / `bind_listener` / `local_addr` implementation  
  * keep *exactly* the same public API and behavior

```rust
pub struct WireframeServer<F, P> {
    factory: F,
    workers: usize,
    on_preamble_success: Option<PreambleCallback<P>>,
    on_preamble_failure: Option<PreambleErrorCallback>,
    ready_tx: Option<oneshot::Sender<()>>,
    listener: Option<Arc<TcpListener>>,
    _preamble: PhantomData<P>,
}

impl<F, P> WireframeServer<F, P>
where
    F: Fn() -> WireframeApp + Send + Sync + Clone + 'static,
    P: Preamble,
{
    /// Returns the bound address, or `None` if not yet bound.
    #[must_use]
    pub fn local_addr(&self) -> Option<SocketAddr> {
        self.listener
            .as_ref()
            .and_then(|l| l.local_addr().ok())
    }

    /// Bind to a fresh address.
    pub fn bind(mut self, addr: SocketAddr) -> io::Result<Self> {
        let std = StdTcpListener::bind(addr)?;
        self.bind_listener(std)
    }

    /// Bind to an existing `StdTcpListener`.
    pub fn bind_listener(mut self, mut std: StdTcpListener) -> io::Result<Self> {
        std.set_nonblocking(true)?;
        let tokio = TcpListener::from_std(std)?;
        self.listener = Some(Arc::new(tokio));
        Ok(self)
    }

    // ... keep your `new`, `with_preamble`, `workers`, callbacks, ready_signal, etc.
}
```

Steps to apply:

1. Add `listener: Option<Arc<TcpListener>>` to the struct and drop the `state: Unbound/Bound` generic.  
2. Collapse both `impl<…, Unbound>` and `impl<…, Bound>` blocks into the single `impl<F, P> …` above.  
3. Move your existing `bind_std_listener` logic into the unified `bind_listener(...)` method.  

This preserves *all* your callbacks, worker‐count logic, and type‐parameters, but removes the two‐state boilerplate completely.
</issue_to_address>

### Comment 2
<location> `src/server/config/mod.rs:199` </location>
<code_context>
+    }
+}
+
+#[allow(clippy::too_many_arguments)]
+fn bind_std_listener<F, T>(
+    factory: F,
</code_context>

<issue_to_address>
Use of `#[allow(clippy::too_many_arguments)]` is forbidden; use a narrowly scoped `#[expect(...)]` with a reason instead.

The review instructions explicitly forbid the use of `#[allow]` for lints. Please replace this with a narrowly scoped `#[expect(clippy::too_many_arguments, reason = "...")]` and provide a justification. Blanket or group suppression is not permitted.
</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/server/config/mod.rs Outdated
Comment thread src/server/config/mod.rs Outdated
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 17

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9945d14 and e62cf66.

📒 Files selected for processing (3)
  • src/server/config.rs (0 hunks)
  • src/server/config/mod.rs (1 hunks)
  • src/server/config/tests.rs (1 hunks)
💤 Files with no reviewable changes (1)
  • src/server/config.rs
🧰 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/tests.rs
  • src/server/config/mod.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/tests.rs
  • src/server/config/mod.rs
🔇 Additional comments (1)
src/server/config/tests.rs (1)

41-49: Well-structured edge case testing!

Good coverage of worker configuration including the zero-worker edge case that should default to 1.

Comment thread src/server/config/mod.rs
Comment thread src/server/config/mod.rs Outdated
Comment thread src/server/config/mod.rs Outdated
Comment thread src/server/config/mod.rs
Comment thread src/server/config/mod.rs
Comment thread src/server/config/tests.rs Outdated
Comment thread src/server/config/tests.rs Outdated
Comment thread src/server/config/tests.rs Outdated
Comment thread src/server/config/tests.rs Outdated
Comment thread src/server/config/tests.rs Outdated
Comment thread src/server/config/tests.rs Outdated
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (10)
src/server/config/tests.rs (3)

1-1: Expand the module documentation to explain test coverage scope.

The module documentation is too brief. Add details about what aspects of server configuration are being tested and the testing strategy employed.

-//! Tests for server configuration utilities.
+//! Tests for server configuration utilities.
+//! 
+//! This module provides comprehensive test coverage for the `WireframeServer` configuration,
+//! including worker count settings, binding behaviour, preamble handling, callback registration,
+//! and method chaining. Tests use `rstest` fixtures for shared setup and parameterised cases.

22-25: Remove duplication of the default worker count logic.

This duplicates the logic from WireframeServer::new. If the implementation changes, tests could pass incorrectly due to parallel changes in both places. Test against the actual behaviour instead.


30-30: Split the compound assertion for clearer test failures.

Compound assertions make debugging test failures harder. Split into separate assertions.

-    assert!(server.worker_count() >= 1 && server.local_addr().is_none());
+    assert!(server.worker_count() >= 1);
+    assert!(server.local_addr().is_none());
src/server/config/mod.rs (7)

29-33: Add usage example to function documentation.

Function documentation must include clear examples demonstrating usage and outcome.

     /// Create a new `WireframeServer` from the given application factory.
     ///
     /// The worker count defaults to the number of available CPU cores (or 1 if this cannot be
     /// determined). The TCP listener is unset; call [`bind`](Self::bind) before running the
     /// server.
+    /// 
+    /// # Example
+    /// 
+    /// ```
+    /// use wireframe::server::WireframeServer;
+    /// 
+    /// let server = WireframeServer::new(|| MyApp::new());
+    /// assert!(server.worker_count() >= 1);
+    /// ```

53-55: Add usage example to function documentation.

     /// Converts the server to use a custom preamble type for incoming connections.
     ///
     /// Calling this method drops any previously configured preamble decode callbacks.
+    /// 
+    /// # Example
+    /// 
+    /// ```
+    /// use wireframe::server::WireframeServer;
+    /// 
+    /// let server = WireframeServer::new(|| MyApp::new())
+    ///     .with_preamble::<MyPreamble>();
+    /// ```

78-78: Add usage example to function documentation.

     /// Set the number of worker tasks to spawn for the server.
+    /// 
+    /// # Example
+    /// 
+    /// ```
+    /// let server = WireframeServer::new(|| MyApp::new())
+    ///     .workers(4);
+    /// assert_eq!(server.worker_count(), 4);
+    /// ```

85-85: Add usage example to function documentation.

     /// Register a callback invoked when the connection preamble decodes successfully.
+    /// 
+    /// # Example
+    /// 
+    /// ```
+    /// let server = server.on_preamble_decode_success(|preamble, stream| {
+    ///     Box::pin(async move {
+    ///         println!("Preamble decoded: {:?}", preamble);
+    ///         Ok(())
+    ///     })
+    /// });
+    /// ```

98-98: Add usage example to function documentation.

     /// Register a callback invoked when the connection preamble fails to decode.
+    /// 
+    /// # Example
+    /// 
+    /// ```
+    /// let server = server.on_preamble_decode_failure(|error| {
+    ///     eprintln!("Preamble decode failed: {}", error);
+    /// });
+    /// ```

108-108: Add usage example to function documentation.

     /// Configure a channel used to signal when the server is ready to accept connections.
+    /// 
+    /// # Example
+    /// 
+    /// ```
+    /// let (tx, rx) = tokio::sync::oneshot::channel();
+    /// let server = server.ready_signal(tx);
+    /// // Server will send on tx when ready
+    /// ```

156-159: Add usage example to function documentation.

     /// Bind the server to the given address and create a listener.
     ///
     /// # Errors
     /// Returns an `io::Error` if binding or configuring the listener fails.
+    /// 
+    /// # Example
+    /// 
+    /// ```
+    /// use std::net::SocketAddr;
+    /// 
+    /// let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
+    /// let server = server.bind(addr)?;
+    /// ```
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e62cf66 and 2e99b07.

📒 Files selected for processing (2)
  • src/server/config/mod.rs (1 hunks)
  • src/server/config/tests.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/tests.rs
  • src/server/config/mod.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/tests.rs
  • src/server/config/mod.rs
🧬 Code Graph Analysis (1)
src/server/config/tests.rs (2)
src/server/test_util.rs (3)
  • bind_server (31-38)
  • free_port (23-29)
  • server_with_preamble (40-45)
src/server/config/mod.rs (7)
  • new (35-46)
  • worker_count (118-118)
  • local_addr (154-154)
  • local_addr (184-184)
  • workers (80-83)
  • bind (160-163)
  • bind (190-193)
🔇 Additional comments (4)
src/server/config/tests.rs (2)

41-49: Well-structured test with good edge case coverage.

The test properly validates worker configuration including the edge case of zero workers being clamped to 1.


176-182: Excellent edge case testing for worker count boundaries.

The test properly validates behaviour at the extreme boundaries of the worker count range.

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

1-6: Good module documentation with clear explanation of design patterns.

The documentation properly explains the module's purpose, builder pattern usage, and compile-time state tracking with phantom types.


124-144: Well-structured delegation to binding helper.

Good separation of concerns with the helper method extracting fields and delegating to the standalone binding function.

Comment thread src/server/config/tests.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

♻️ Duplicate comments (5)
src/server/config/mod.rs (5)

97-102: Add usage example to function documentation.

Function documentation must include clear examples demonstrating usage and outcome as per the coding guidelines.

    /// Set the number of worker tasks to spawn for the server.
+   ///
+   /// # Examples
+   ///
+   /// ```
+   /// use wireframe::{app::WireframeApp, server::WireframeServer};
+   ///
+   /// let server = WireframeServer::new(|| WireframeApp::default())
+   ///     .workers(4);
+   /// assert_eq!(server.worker_count(), 4);
+   /// ```
    #[must_use]

104-115: Add usage example to function documentation.

Function documentation must include clear examples as per the coding guidelines.

    /// Register a callback invoked when the connection preamble decodes successfully.
+   ///
+   /// # Examples
+   ///
+   /// ```
+   /// use wireframe::{app::WireframeApp, server::WireframeServer};
+   ///
+   /// let server = WireframeServer::new(|| WireframeApp::default())
+   ///     .on_preamble_decode_success(|preamble, stream| {
+   ///         Box::pin(async move {
+   ///             println!("Preamble decoded: {:?}", preamble);
+   ///             Ok(())
+   ///         })
+   ///     });
+   /// ```
    #[must_use]

117-125: Add usage example to function documentation.

Function documentation must include clear examples as per the coding guidelines.

    /// Register a callback invoked when the connection preamble fails to decode.
+   ///
+   /// # Examples
+   ///
+   /// ```
+   /// use wireframe::{app::WireframeApp, server::WireframeServer};
+   ///
+   /// let server = WireframeServer::new(|| WireframeApp::default())
+   ///     .on_preamble_decode_failure(|error| {
+   ///         eprintln!("Preamble decode failed: {}", error);
+   ///     });
+   /// ```
    #[must_use]

127-132: Add usage example to function documentation.

Function documentation must include clear examples as per the coding guidelines.

    /// Configure a channel used to signal when the server is ready to accept connections.
+   ///
+   /// # Examples
+   ///
+   /// ```
+   /// use tokio::sync::oneshot;
+   /// use wireframe::{app::WireframeApp, server::WireframeServer};
+   ///
+   /// let (tx, rx) = oneshot::channel();
+   /// let server = WireframeServer::new(|| WireframeApp::default())
+   ///     .ready_signal(tx);
+   /// // Server will send on tx when ready
+   /// ```
    #[must_use]

145-152: Add usage example to function documentation.

Function documentation must include clear examples as per the coding guidelines.

    /// Bind to a fresh address.
    ///
    /// # Errors
    /// Returns an `io::Error` if binding or configuring the listener fails.
+   ///
+   /// # Examples
+   ///
+   /// ```
+   /// use std::net::SocketAddr;
+   /// use wireframe::{app::WireframeApp, server::WireframeServer};
+   ///
+   /// # fn main() -> std::io::Result<()> {
+   /// let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
+   /// let server = WireframeServer::new(|| WireframeApp::default())
+   ///     .bind(addr)?;
+   /// # Ok(())
+   /// # }
+   /// ```
    pub fn bind(self, addr: SocketAddr) -> io::Result<Self> {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a61c122 and 357e777.

📒 Files selected for processing (4)
  • src/server/config/mod.rs (1 hunks)
  • src/server/mod.rs (2 hunks)
  • src/server/runtime.rs (2 hunks)
  • src/server/test_util.rs (2 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/test_util.rs
  • src/server/mod.rs
  • src/server/runtime.rs
  • src/server/config/mod.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/test_util.rs
  • src/server/mod.rs
  • src/server/runtime.rs
  • src/server/config/mod.rs
🧬 Code Graph Analysis (1)
src/server/config/mod.rs (3)
tests/preamble.rs (1)
  • oneshot (71-71)
src/server/test_util.rs (2)
  • WireframeServer (44-44)
  • factory (18-20)
src/server/config/tests.rs (2)
  • WireframeServer (57-57)
  • WireframeServer (158-160)
🔇 Additional comments (6)
src/server/test_util.rs (1)

8-8: LGTM! Correctly reflects the simplified WireframeServer type.

The removal of the Bound import and simplification of the return type aligns perfectly with the broader refactoring that eliminates the state type parameter.

Also applies to: 31-31

src/server/mod.rs (1)

36-36: Excellent simplification of the server architecture.

The removal of the state type parameter and replacement with Option<Arc<TcpListener>> eliminates unnecessary complexity whilst maintaining the same functionality. This addresses the previous review suggestion perfectly.

Also applies to: 60-60

src/server/runtime.rs (1)

25-25: Runtime correctly adapted to the simplified server structure.

The removal of the Bound wrapper and addition of explicit error handling for unbound listeners maintains the same behaviour whilst working with the simplified WireframeServer struct.

Also applies to: 59-63

src/server/config/mod.rs (3)

1-6: Module documentation appropriately describes the simplified design.

The documentation correctly explains the fluent builder pattern and optional listener approach, which is clearer than the previous state machine design.


29-55: Well-documented constructor with sensible defaults.

The new function correctly initialises all fields and provides a clear usage example as required by the coding guidelines.


63-95: Correct preamble type conversion with proper callback reset.

The function appropriately resets preamble callbacks when changing types and includes the required usage example.

Comment thread src/server/config/mod.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

♻️ Duplicate comments (4)
src/server/config/mod.rs (4)

139-144: Add missing documentation example.

Function documentation must include clear examples as per the coding guidelines.

     /// Configure a channel used to signal when the server is ready to accept connections.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use tokio::sync::oneshot;
+    /// use wireframe::{app::WireframeApp, server::WireframeServer};
+    ///
+    /// let (tx, rx) = oneshot::channel();
+    /// let server = WireframeServer::new(|| WireframeApp::default())
+    ///     .ready_signal(tx);
+    /// // Server will send on tx when ready
+    /// ```

166-175: Add missing documentation example.

Function documentation must include clear examples as per the coding guidelines.

     /// Bind to an existing `StdTcpListener`.
     ///
     /// # Errors
     /// Returns an `io::Error` if configuring the listener fails.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::net::TcpListener;
+    /// use wireframe::{app::WireframeApp, server::WireframeServer};
+    ///
+    /// # fn main() -> std::io::Result<()> {
+    /// let std_listener = TcpListener::bind("127.0.0.1:8080")?;
+    /// let server = WireframeServer::new(|| WireframeApp::default())
+    ///     .bind_listener(std_listener)?;
+    /// # Ok(())
+    /// # }
+    /// ```

97-106: Fix malformed documentation and add missing example.

The documentation comment is incorrectly formatted and lacks the required usage example.

-/// Set the number of worker tasks to spawn for the server.
-    /// 
-    /// # Example
-    /// 
-    ///
+    /// Set the number of worker tasks to spawn for the server.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use wireframe::{app::WireframeApp, server::WireframeServer};
+    ///
+    /// let server = WireframeServer::new(|| WireframeApp::default())
+    ///     .workers(4);
+    /// assert_eq!(server.worker_count(), 4);
+    /// ```

125-137: Fix malformed documentation and add missing example.

The documentation comment is incorrectly formatted and lacks the required usage example.

-/// Register a callback invoked when the connection preamble fails to decode.
-     ///
-     /// # Example
-     ///
-     ///
+    /// Register a callback invoked when the connection preamble fails to decode.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use wireframe::{app::WireframeApp, server::WireframeServer};
+    ///
+    /// let server = server.on_preamble_decode_failure(|error| {
+    ///     eprintln!("Preamble decode failed: {}", error);
+    /// });
+    /// ```
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 357e777 and f793c95.

📒 Files selected for processing (1)
  • src/server/config/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/mod.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/mod.rs
🔇 Additional comments (5)
src/server/config/mod.rs (5)

1-7: LGTM! Module documentation meets requirements.

The module documentation properly explains the purpose, builder pattern, and key functionality with appropriate detail as required by the coding guidelines.


8-23: LGTM! Clean imports and test module declaration.

The imports are well-organised and the conditional test module inclusion follows proper conventions.


29-55: LGTM! Constructor implementation with proper defaults.

The new method correctly initialises the server with sensible defaults, using available_parallelism() with a fallback to 1. The documentation example demonstrates proper usage.


63-95: LGTM! Type conversion method properly resets callbacks.

The with_preamble method correctly creates a new instance with the target preamble type whilst resetting preamble-related callbacks to prevent type mismatches. The documentation example is comprehensive.


146-155: LGTM! Simple accessor methods are well-implemented.

Both worker_count and local_addr methods are correctly implemented with appropriate attributes and error handling.

Comment thread src/server/config/mod.rs Outdated
Comment thread src/server/config/mod.rs
@leynos leynos force-pushed the codex/extract-test-module-from-config.rs branch from f793c95 to 357e777 Compare August 6, 2025 18:28
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 6, 2025

Caution

An unexpected error occurred while opening a pull request: Reference does not exist - https://docs.github.com/rest/git/refs#update-a-reference

leynos and others added 6 commits August 6, 2025 19:52
Documents all public builder methods and runtime entrypoints with runnable doctests covering typical usage patterns. Enables consumers to see practical configuration examples without needing external samples.
Extracts repeated default worker count calculation into a dedicated helper
Simplifies callback registration tests by removing unnecessary network setup
Streamlines assertion logic and removes a redundant test for callback resets
Updates variable naming for consistency and drops unused imports
@leynos leynos force-pushed the codex/extract-test-module-from-config.rs branch from 357e777 to 7ffae35 Compare August 6, 2025 19:16
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 6, 2025

@sourcery-ai review

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey @leynos - I've reviewed your changes - here's some feedback:

  • The removal of the Bound/Unbound typestate makes binding errors arise at runtime; consider restoring typestate to enforce binding at compile time.
  • The error returned when running an unbound server ('listener not bound') is generic; consider using a more descriptive error or a custom error type.
  • src/server/config/mod.rs is quite large now; splitting it into smaller submodules (e.g., binding, preamble) could improve readability and maintainability.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The removal of the Bound/Unbound typestate makes binding errors arise at runtime; consider restoring typestate to enforce binding at compile time.
- The error returned when running an unbound server ('listener not bound') is generic; consider using a more descriptive error or a custom error type.
- src/server/config/mod.rs is quite large now; splitting it into smaller submodules (e.g., binding, preamble) could improve readability and maintainability.

## Individual Comments

### Comment 1
<location> `src/server/config/mod.rs:97` </location>
<code_context>
-    F: Fn() -> WireframeApp + Send + Sync + Clone + 'static,
-    T: Preamble,
-{
-    /// Set the number of worker tasks to spawn for the server.
-    #[must_use]
-    pub fn workers(mut self, count: usize) -> Self {
</code_context>

<issue_to_address>
Consider replacing the repetitive setter and callback methods with builder macros to reduce boilerplate.

You can collapse all those repetitive setters into either a derived‐builder (via the derive_builder crate) or a tiny macro. Here’s an example of the macro approach which preserves your signatures but cuts ~200 LOC of boilerplate:

```rust
// at top of file
macro_rules! builder_setter {
    ($(#[$meta:meta])* $fn:ident, $field:ident, $ty:ty) => {
        $(#[$meta])*
        #[must_use]
        pub fn $fn(mut self, val: $ty) -> Self {
            self.$field = val;
            self
        }
    };
}
macro_rules! builder_callback {
    ($fn:ident, $field:ident, $bound:ty) => {
        #[must_use]
        pub fn $fn<H>(mut self, handler: H) -> Self
        where H: $bound {
            self.$field = Some(Arc::new(handler));
            self
        }
    };
}
```

Then inside your `impl<F,T> WireframeServer<F,T> { … }` you replace the manual methods with calls to those macros:

```rust
impl<F, T> WireframeServer<F, T>
where
    F: Fn() -> WireframeApp + Send + Sync + Clone + 'static,
    T: Preamble,
{
    builder_setter!(
        /// Set number of worker tasks (min 1).
        workers, workers, usize
    );

    builder_setter!(
        /// Configure a channel to signal readiness.
        ready_signal, ready_tx, oneshot::Sender<()>
    );

    builder_callback!(
        /// Callback for preamble decode success.
        on_preamble_decode_success,
        on_preamble_success,
        for<'a> Fn(&'a T, &'a mut tokio::net::TcpStream) -> BoxFuture<'a, io::Result<()>> + Send + Sync + 'static
    );

    builder_callback!(
        /// Callback for preamble decode failure.
        on_preamble_decode_failure,
        on_preamble_failure,
        Fn(&DecodeError) + Send + Sync + 'static
    );

    // keep new(), with_preamble(), worker_count(), bind()/bind_listener(), etc.
}
```

This preserves all functionality, keeps your docs, and collapses the repeated `mut self`/`self` plumbing into two small macros.
</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/server/config/mod.rs
@leynos leynos merged commit e890d53 into main Aug 6, 2025
5 checks passed
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.

File length violation: src/server/config.rs exceeds 400-line limit

1 participant