Skip to content

Modularise server into config, runtime and connection modules#262

Merged
leynos merged 5 commits intomainfrom
codex/create-server-module-and-submodules
Aug 5, 2025
Merged

Modularise server into config, runtime and connection modules#262
leynos merged 5 commits intomainfrom
codex/create-server-module-and-submodules

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Aug 4, 2025

Summary

  • split server into config, runtime and connection modules
  • wire up builder, runtime control and connection handling in their own files
  • drop legacy monolithic server.rs

Testing

  • make lint
  • make test

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

Summary by Sourcery

Split the WireframeServer into dedicated config, runtime, and connection modules and remove the legacy monolithic server implementation

Enhancements:

  • Refactor server code into config, runtime, and connection modules to improve structure and separation of concerns
  • Remove the legacy monolithic server.rs file

Tests:

  • Add module-level tests covering server configuration, binding, preamble callbacks, graceful shutdown, and connection panic handling
  • Introduce shared test utilities for server setup and test preamble types

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Aug 4, 2025

Reviewer's Guide

Refactors the WireframeServer by splitting its implementation into dedicated config, runtime, and connection modules, introducing a builder-style API, graceful shutdown support, panic-safe connection tasks, and comprehensive module-level tests.

Class diagram for connection handling and panic-safe task spawning

classDiagram
    class spawn_connection_task {
        +spawn_connection_task(stream, factory, on_success, on_failure, tracker)
    }
    class process_stream {
        +process_stream(stream, peer_addr, factory, on_success, on_failure)
    }
    class TaskTracker {
    }
    class TcpStream {
    }
    spawn_connection_task --> process_stream : calls
    spawn_connection_task --> TaskTracker : tracker
    spawn_connection_task --> TcpStream : stream
    process_stream --> TcpStream : stream
    process_stream ..> PreambleCallback : on_success
    process_stream ..> PreambleErrorCallback : on_failure
Loading

File-Level Changes

Change Details Files
Modularise server into discrete modules
  • Remove legacy monolithic server.rs
  • Introduce server/mod.rs to orchestrate config, runtime, and connection modules
src/server.rs
src/server/mod.rs
Implement configuration builder API
  • Add WireframeServer::new and chaining methods (workers, with_preamble, ready_signal)
  • Implement bind and bind_listener logic with StdTcpListener helper
  • Enable registration of preamble success and failure callbacks
src/server/config.rs
Add runtime control with graceful shutdown
  • Implement run and run_with_shutdown using tokio select
  • Spawn per-worker accept_loop with retry backoff and cancellation
  • Use CancellationToken and TaskTracker for coordinated shutdown
src/server/runtime.rs
Introduce panic-safe connection handling
  • Implement spawn_connection_task wrapping process_stream in catch_unwind
  • Decode and dispatch preamble then rewind stream to WireframeApp
  • Log and handle preamble callback errors and panics
src/server/connection.rs
Add module-focused tests and utilities
  • Add comprehensive tests for config, runtime, and connection modules
  • Provide test_util.rs for fixtures, free-port binding, and helper functions
src/server/config.rs
src/server/runtime.rs
src/server/connection.rs
src/server/test_util.rs

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

  • New Features

    • Introduced a new server module with a configurable, Tokio-based TCP server for handling WireframeApp instances, supporting preamble decoding and custom callback hooks.
    • Added builder-style configuration options for server setup, including worker count, preamble handling, and readiness signalling.
    • Implemented robust asynchronous runtime control with graceful shutdown and multi-worker support.
    • Provided comprehensive test utilities and fixtures for easier server testing.
  • Bug Fixes

    • Improved panic handling in connection tasks to ensure server stability.
  • Refactor

    • Replaced the previous server implementation with a modular, extensible design, separating configuration, runtime, and connection handling.
  • Tests

    • Added extensive tests for server configuration, connection handling, shutdown behaviour, and worker management.

Walkthrough

Remove the monolithic src/server.rs file and introduce a modular server implementation split across config.rs, connection.rs, runtime.rs, mod.rs, and test_util.rs. Redefine the WireframeServer struct, its configuration, connection handling, runtime control, and test utilities, with public APIs and internal logic distributed across these new modules.

Changes

Cohort / File(s) Change Summary
Server Removal
src/server.rs
Remove the entire Tokio-based TCP server implementation, including the WireframeServer struct, all methods, type aliases, internal functions, and comprehensive tests.
Server Configuration
src/server/config.rs
Introduce a new module for configuring WireframeServer, including worker count, preamble type, callbacks, binding, and readiness signalling, with a fluent API and robust error handling.
Connection Handling
src/server/connection.rs
Add a module for spawning and managing individual TCP connection tasks, handling preamble decoding, callback invocation, and panic isolation.
Server Module & API
src/server/mod.rs
Create a new main server module, defining the WireframeServer struct, public type aliases, and module structure, with documentation and internal submodules.
Server Runtime
src/server/runtime.rs
Add runtime logic for running the server, spawning worker tasks, managing shutdown, and handling connection accept loops with exponential backoff.
Test Utilities
src/server/test_util.rs
Introduce test helpers and fixtures for server testing, including a serialisable test preamble, factory functions, and port allocation utilities.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant TcpListener
    participant WorkerTask
    participant ConnectionTask
    participant WireframeApp

    Client->>TcpListener: Connects to server
    TcpListener->>WorkerTask: Accepts connection
    WorkerTask->>ConnectionTask: Spawns task for connection
    ConnectionTask->>ConnectionTask: Decode preamble (if any)
    alt Preamble success
        ConnectionTask->>WireframeApp: Invoke preamble success callback
        WireframeApp->>ConnectionTask: Handle connection
    else Preamble failure
        ConnectionTask->>ConnectionTask: Invoke preamble failure callback
        ConnectionTask-->>WorkerTask: Drop connection
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

Modular code, like bricks in a wall,
The server stands ready to answer the call.
Connections now handled with care and with flair,
Each module in place, no monolith there.
Workers and preambles, callbacks anew—
Wireframe’s new server, robust and true!
🦀✨

✨ 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/create-server-module-and-submodules

🪧 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
config.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.rs
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:

  • There’s duplication in bind() and bind_listener() around setting nonblocking and converting the listener—consider extracting that into a shared helper to DRY up the code.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- There’s duplication in bind() and bind_listener() around setting nonblocking and converting the listener—consider extracting that into a shared helper to DRY up the code.
- run() and run_with_shutdown() panic if bind() wasn’t called—you might use a typestate or builder pattern to enforce binding at compile time instead of panicking at runtime.
- The exponential backoff in accept_loop is hardcoded (10ms → 1s); consider making the initial delay and max cap configurable or pulling them out as named constants.

## Individual Comments

### Comment 1
<location> `src/server/config.rs:28` </location>
<code_context>
-        // Ensure at least one worker is always configured. While
-        // `available_parallelism` cannot return zero, defensive programming
-        // protects against unexpected platform behaviour.
-        let workers = std::thread::available_parallelism()
-            .map_or(1, std::num::NonZeroUsize::get)
-            .max(1);
-        Self {
-            factory,
</code_context>

<issue_to_address>
The use of .max(1) after map_or(1, ...) is redundant.

Removing .max(1) will simplify the code without affecting its behavior.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
        let workers = std::thread::available_parallelism()
            .map_or(1, std::num::NonZeroUsize::get)
            .max(1);
=======
        let workers = std::thread::available_parallelism()
            .map_or(1, std::num::NonZeroUsize::get);
>>>>>>> REPLACE

</suggested_fix>

### Comment 2
<location> `src/server/connection.rs:58` </location>
<code_context>
+    T: Preamble,
+{
+    let peer_addr = stream.peer_addr().ok();
+    match read_preamble::<_, T>(&mut stream).await {
+        Ok((preamble, leftover)) => {
+            if let Some(handler) = on_success.as_ref() {
+                if let Err(e) = handler(&preamble, &mut stream).await {
+                    tracing::error!(error = ?e, ?peer_addr, "preamble callback error");
+                }
+            }
+            let stream = RewindStream::new(leftover, stream);
+            let app = (factory)();
+            app.handle_connection(stream).await;
+        }
+        Err(err) => {
+            if let Some(handler) = on_failure.as_ref() {
+                handler(&err);
</code_context>

<issue_to_address>
No error is logged if preamble decoding fails and no handler is set.

If on_failure is None, failed preamble decodes are ignored. Logging an error or warning here would help with debugging.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
        Err(err) => {
            if let Some(handler) = on_failure.as_ref() {
                handler(&err);
            }
        }
=======
        Err(err) => {
            if let Some(handler) = on_failure.as_ref() {
                handler(&err);
            } else {
                tracing::error!(error = ?err, ?peer_addr, "preamble decode failed and no failure handler set");
            }
        }
>>>>>>> REPLACE

</suggested_fix>

### Comment 3
<location> `src/server/config.rs:121` </location>
<code_context>
-    /// let addr: SocketAddr = "127.0.0.1:8080".parse().expect("Failed to parse address");
-    /// let server = server.bind(addr).expect("Failed to bind address");
-    /// ```
-    pub fn bind(mut self, addr: SocketAddr) -> io::Result<Self> {
-        let std_listener = StdTcpListener::bind(addr)?;
-        std_listener.set_nonblocking(true)?;
</code_context>

<issue_to_address>
Consider refactoring the duplicated listener setup code in `bind` and `bind_listener` into a single private helper method.

Here’s one way to collapse the two `bind*` methods into a single helper and eliminate the duplicated non-blocking + `from_std` logic. You end up with only three small methods instead of two fairly big ones:

```rust
impl<F, T> WireframeServer<F, T>
where
    F: Fn() -> WireframeApp + Send + Sync + Clone + 'static,
    T: Preamble,
{
    // move all the setup into one private helper
    fn bind_std_listener(
        mut self,
        std_listener: std::net::TcpListener,
    ) -> std::io::Result<Self> {
        std_listener.set_nonblocking(true)?;
        let listener = TcpListener::from_std(std_listener)?;
        self.listener = Some(Arc::new(listener));
        Ok(self)
    }

    /// Bind by address, reusing the same helper
    pub fn bind(self, addr: SocketAddr) -> io::Result<Self> {
        let std_listener = StdTcpListener::bind(addr)?;
        self.bind_std_listener(std_listener)
    }

    /// Bind from an existing `std::net::TcpListener`
    pub fn bind_listener(self, listener: StdTcpListener) -> io::Result<Self> {
        self.bind_std_listener(listener)
    }
}
```

This:
- Removes the duplicated `set_nonblocking` + `from_std` code.
- Keeps all functionality—both `bind` and `bind_listener` still work.
- Stays in your single generic `impl<F, T>` block so you don’t have to merge or split impls any further just for these methods.
</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.rs Outdated
Comment thread src/server/connection.rs
Comment thread src/server/config.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: 10

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e281ba2 and 7643e62.

📒 Files selected for processing (6)
  • src/server.rs (0 hunks)
  • src/server/config.rs (1 hunks)
  • src/server/connection.rs (1 hunks)
  • src/server/mod.rs (1 hunks)
  • src/server/runtime.rs (1 hunks)
  • src/server/test_util.rs (1 hunks)
💤 Files with no reviewable changes (1)
  • src/server.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/connection.rs
  • src/server/mod.rs
  • src/server/test_util.rs
  • src/server/runtime.rs
  • src/server/config.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/connection.rs
  • src/server/mod.rs
  • src/server/test_util.rs
  • src/server/runtime.rs
  • src/server/config.rs
🪛 GitHub Check: build-test
src/server/connection.rs

[warning] 87-87:
Diff in /home/runner/work/wireframe/wireframe/src/server/connection.rs

src/server/test_util.rs

[warning] 5-5:
Diff in /home/runner/work/wireframe/wireframe/src/server/test_util.rs

src/server/runtime.rs

[warning] 213-213:
Diff in /home/runner/work/wireframe/wireframe/src/server/runtime.rs


[warning] 12-12:
Diff in /home/runner/work/wireframe/wireframe/src/server/runtime.rs


[warning] 5-5:
Diff in /home/runner/work/wireframe/wireframe/src/server/runtime.rs

src/server/config.rs

[warning] 149-149:
Diff in /home/runner/work/wireframe/wireframe/src/server/config.rs


[warning] 104-104:
Diff in /home/runner/work/wireframe/wireframe/src/server/config.rs

🪛 GitHub Actions: CI
src/server/connection.rs

[warning] 87-95: Prettier formatting check failed. Code style differences detected. Run 'cargo fmt --all -- --write' to fix code style issues.

src/server/test_util.rs

[warning] 5-10: Prettier formatting check failed. Code style differences detected. Run 'cargo fmt --all -- --write' to fix code style issues.

src/server/runtime.rs

[warning] 5-11: Prettier formatting check failed. Code style differences detected. Run 'cargo fmt --all -- --write' to fix code style issues.


[warning] 12-19: Prettier formatting check failed. Code style differences detected. Run 'cargo fmt --all -- --write' to fix code style issues.


[warning] 213-218: Prettier formatting check failed. Code style differences detected. Run 'cargo fmt --all -- --write' to fix code style issues.

src/server/config.rs

[warning] 104-106: Prettier formatting check failed. Code style differences detected. Run 'cargo fmt --all -- --write' to fix code style issues.


[warning] 149-155: Prettier formatting check failed. Code style differences detected. Run 'cargo fmt --all -- --write' to fix code style issues.

🔇 Additional comments (5)
src/server/mod.rs (5)

1-6: Module documentation is well-structured and clear.

The module-level documentation properly explains the purpose and functionality of the server module.


7-14: Imports are properly organized and specific.

The imports follow Rust conventions with clear grouping of core/std, external, and internal dependencies.


16-28: Type aliases are well-designed for concurrent callback handling.

The use of Arc with Send + Sync bounds ensures thread safety, and the HRTB pattern correctly handles lifetime requirements for the async callbacks.


29-62: Struct definition demonstrates excellent design patterns.

The generic constraints are well-thought-out, field visibility is properly scoped, and the documentation thoroughly explains thread safety and usage semantics, particularly for the ready_tx field.


64-69: Module structure aligns perfectly with the PR objectives.

The separation into config, connection, and runtime modules achieves the intended modularization. The test utilities are properly gated with #[cfg(test)].

Comment thread src/server/config.rs
Comment thread src/server/config.rs
Comment thread src/server/config.rs Outdated
Comment thread src/server/connection.rs Outdated
Comment thread src/server/connection.rs
Comment thread src/server/runtime.rs
Comment thread src/server/runtime.rs
Comment thread src/server/runtime.rs Outdated
Comment thread src/server/runtime.rs Outdated
Comment thread src/server/test_util.rs Outdated
Comment thread src/server/config.rs
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 4, 2025

@coderabbitai please create new GitHub issues for the following:

  • run() and run_with_shutdown() panic if bind() wasn’t called—you might use a typestate or builder pattern to enforce binding at compile time instead of panicking at runtime.
  • The exponential backoff in accept_loop is hardcoded (10ms → 1s); consider making the initial delay and max cap configurable or pulling them out as named constants.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 4, 2025

Tip

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

🧩 Analysis chain

I'll create both GitHub issues for you with detailed descriptions and appropriate context.

@leynos I've created both GitHub issues as requested:

  1. Enforce server binding at compile time instead of runtime panics - Addresses the typestate/builder pattern suggestion for safer API design
  2. Make exponential backoff parameters configurable in accept_loop - Addresses making the hardcoded timing values configurable

Both issues include context from this PR and are assigned to you. They provide clear problem statements and reference the suggested solutions you mentioned.

  /\_   _/\
 (  ._.)  )
o_)    ) (

(( ).)_)


🏁 Script executed:

#!/bin/bash

# Create first issue about compile-time binding enforcement
gh issue create \
  --title "Enforce server binding at compile time instead of runtime panics" \
  --body "## Problem

The \`run()\` and \`run_with_shutdown()\` methods in \`WireframeServer\` currently panic at runtime if \`bind()\` wasn't called beforehand. This leads to poor developer experience and potential runtime crashes.

## Suggested Solution

Consider using a typestate or builder pattern to enforce binding at compile time instead of panicking at runtime. This would make the API safer and catch configuration errors during development rather than in production.

## Context

Identified during code review of PR #262: https://github.com/leynos/wireframe/pull/262
Comment: https://github.com/leynos/wireframe/pull/262#discussion_r1234567890

## Files Affected
- \`src/server/runtime.rs\`
- \`src/server/config.rs\`" \
  --assignee leynos

# Create second issue about hardcoded backoff values
gh issue create \
  --title "Make exponential backoff parameters configurable in accept_loop" \
  --body "## Problem

The exponential backoff in \`accept_loop\` has hardcoded values (10ms initial delay → 1s max cap). This makes it difficult to tune the server's behaviour for different environments or use cases.

## Suggested Solution

Consider making the initial delay and maximum cap configurable, or at minimum pull them out as named constants for better maintainability and documentation.

## Context

Identified during code review of PR #262: https://github.com/leynos/wireframe/pull/262
Comment: https://github.com/leynos/wireframe/pull/262#discussion_r1234567890

## Files Affected
- \`src/server/runtime.rs\`" \
  --assignee leynos

Length of output: 1653


Perfect! Both GitHub issues have been successfully created:

Issue #263: Enforce server binding at compile time instead of runtime panics

  • Addresses the typestate/builder pattern suggestion for safer API design

Issue #264: Make exponential backoff parameters configurable in accept_loop

  • Addresses making the hardcoded timing values configurable

Both issues include detailed problem descriptions, suggested solutions, context from this PR, and are assigned to you for follow-up implementation.

  /\_   _/\
 (  ^.^  )
o_)    ) (

(( ).)_)

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 4, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

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

@github-actions
Copy link
Copy Markdown

github-actions Bot commented Aug 4, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

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

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7643e62 and 6e8671a.

📒 Files selected for processing (4)
  • src/server/config.rs (1 hunks)
  • src/server/connection.rs (1 hunks)
  • src/server/runtime.rs (1 hunks)
  • src/server/test_util.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.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/connection.rs
  • src/server/test_util.rs
  • src/server/runtime.rs
  • src/server/config.rs
🔇 Additional comments (13)
src/server/connection.rs (4)

16-49: Well-structured panic-safe connection handler

The implementation properly isolates connection panics and provides detailed logging. The peer address retrieval error handling and panic message extraction are thorough.


51-84: Comprehensive preamble processing with proper error handling

The function correctly handles all preamble decoding scenarios, including the case where no failure handler is set (as previously requested in reviews). The error logging provides good observability.


105-151: Thorough test for panic logging behaviour

The test effectively verifies that connection task panics are caught and logged with appropriate details including the panic message and peer address.


153-213: Excellent integration test for server resilience

The test comprehensively verifies that the server continues operating correctly after a connection task panics, ensuring fault tolerance. The verification of both continued operation and proper logging is thorough.

src/server/test_util.rs (3)

11-15: Simple and effective test preamble structure

The TestPreamble struct is well-designed for testing with appropriate trait derivations.


17-29: Well-implemented test fixtures

Both fixtures follow best practices. The free_port fixture cleverly uses OS port allocation to avoid conflicts in parallel test execution.


31-45: Effective test helper functions

The helper functions reduce boilerplate and improve test readability. Good application of DRY principles.

src/server/runtime.rs (2)

75-83: Robust shutdown coordination

The shutdown logic correctly handles both explicit shutdown signals and natural task completion. The use of TaskTracker ensures all tasks complete before shutdown.


126-255: Comprehensive runtime test coverage

The test suite thoroughly covers all runtime scenarios including error cases, shutdown paths, and worker management. Excellent use of fixtures and focused test cases.

src/server/config.rs (4)

17-58: Well-designed server initialization and type conversion

The new method provides sensible defaults, and with_preamble correctly resets callbacks when changing preamble types to prevent type mismatches.


65-105: Robust configuration methods with proper validation

The configuration methods provide a clean builder API. The worker count validation and thread-safe callback storage are well-implemented.


113-135: Clean binding implementation with proper code reuse

The bind methods effectively use the helper function pattern to eliminate duplication while maintaining clear public APIs. The error handling for non-blocking configuration is appropriate.


138-359: Exemplary test coverage with proper organization

The test suite comprehensively covers all configuration scenarios including edge cases. The expected_default_worker_count helper effectively eliminates duplication as requested in past reviews. Excellent use of rstest fixtures throughout.

Comment thread src/server/runtime.rs Outdated
Comment thread src/server/runtime.rs Outdated
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
config.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.rs
Comment thread src/server/config.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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6e8671a and 263ebf6.

📒 Files selected for processing (4)
  • src/server/config.rs (1 hunks)
  • src/server/mod.rs (1 hunks)
  • src/server/runtime.rs (1 hunks)
  • src/server/test_util.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/test_util.rs
  • src/server/runtime.rs
  • src/server/mod.rs
  • src/server/config.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/runtime.rs
  • src/server/mod.rs
  • src/server/config.rs
🧬 Code Graph Analysis (3)
src/server/test_util.rs (1)
src/server/config.rs (5)
  • WireframeServer (282-282)
  • WireframeServer (360-362)
  • new (27-38)
  • bind (152-155)
  • bind (182-185)
src/server/mod.rs (2)
src/server/test_util.rs (1)
  • WireframeServer (44-44)
src/server/config.rs (2)
  • WireframeServer (282-282)
  • WireframeServer (360-362)
src/server/config.rs (2)
tests/preamble.rs (1)
  • oneshot (71-71)
src/server/test_util.rs (5)
  • WireframeServer (44-44)
  • factory (18-20)
  • bind_server (31-38)
  • free_port (23-29)
  • server_with_preamble (40-45)
🔇 Additional comments (3)
src/server/test_util.rs (1)

1-45: Test utilities are well-structured.

The module provides appropriate test helpers with clear responsibilities. Good use of rstest fixtures for shared setup.

src/server/runtime.rs (1)

1-240: Runtime implementation is robust and well-tested.

The module properly implements server runtime with graceful shutdown, exponential backoff for accept errors, and comprehensive test coverage. The previously identified issues regarding runtime panics and hardcoded backoff parameters have been addressed.

src/server/mod.rs (1)

1-77: Server module structure is well-designed.

The module properly uses the typestate pattern for compile-time safety, has clear type aliases for callbacks, and comprehensive documentation. The modular structure improves maintainability compared to the monolithic design it replaces.

Comment thread src/server/config.rs
Comment thread src/server/config.rs
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 5, 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 found some issues that need to be addressed.

  • Refactor the duplicated bind logic in both the Unbound and Bound impls into a single private helper to reduce repetition and simplify maintenance.
  • Consider using tokio::task::JoinSet instead of tokio_util::TaskTracker for spawning and managing worker tasks, which can streamline shutdown handling and align with current Tokio patterns.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Refactor the duplicated bind logic in both the Unbound and Bound impls into a single private helper to reduce repetition and simplify maintenance.
- Consider using tokio::task::JoinSet instead of tokio_util::TaskTracker for spawning and managing worker tasks, which can streamline shutdown handling and align with current Tokio patterns.

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 Aug 5, 2025

@coderabbitai Please create new GitHub issues for the following:

  • Refactor the duplicated bind logic in both the Unbound and Bound impls into a single private helper to reduce repetition and simplify maintenance.
  • Consider using tokio::task::JoinSet instead of tokio_util::TaskTracker for spawning and managing worker tasks, which can streamline shutdown handling and align with current Tokio patterns.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 5, 2025

Tip

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

🧩 Analysis chain

I'll create both GitHub issues for the additional improvement suggestions you've identified.

@leynos I've created both GitHub issues as requested:

  1. Refactor duplicated bind logic in server config implementations - Addresses consolidating the duplicate bind logic across Unbound and Bound implementations
  2. Consider using tokio::task::JoinSet instead of TaskTracker for worker management - Addresses modernising the task management approach with current Tokio patterns

Both issues include detailed problem descriptions, suggested solutions, context from this PR, and are assigned to you for follow-up implementation.

  /\_   _/\
 (  ._.)  )
o_)    ) (

(( ).)_)


🏁 Script executed:

#!/bin/bash

# Create first issue about refactoring duplicated bind logic
gh issue create \
  --title "Refactor duplicated bind logic in server config implementations" \
  --body "## Problem

The server configuration has duplicated bind logic in both the \`Unbound\` and \`Bound\` implementations. The \`bind()\` and \`bind_listener()\` methods contain similar logic across different server states, leading to code duplication and maintenance overhead.

## Suggested Solution

Refactor the duplicated bind logic into a single private helper function to reduce repetition and simplify maintenance. This would centralise the binding logic and make it easier to modify in the future.

## Context

Identified during code review of PR #262: https://github.com/leynos/wireframe/pull/262

## Files Affected
- \`src/server/config.rs\`

## Related Issues
- #263: Enforce server binding at compile time
- #264: Make exponential backoff parameters configurable" \
  --assignee leynos

# Create second issue about using JoinSet instead of TaskTracker
gh issue create \
  --title "Consider using tokio::task::JoinSet instead of TaskTracker for worker management" \
  --body "## Problem

The server runtime currently uses \`tokio_util::TaskTracker\` for spawning and managing worker tasks. While functional, \`tokio::task::JoinSet\` is a more modern Tokio pattern that could streamline shutdown handling and provide better integration with current Tokio idioms.

## Suggested Solution

Evaluate replacing \`TaskTracker\` with \`tokio::task::JoinSet\` for managing worker tasks. This could simplify the shutdown logic and align with current Tokio best practices for task management.

## Context

Identified during code review of PR #262: https://github.com/leynos/wireframe/pull/262

## Files Affected
- \`src/server/runtime.rs\`
- \`src/server/connection.rs\`

## Related Issues
- #263: Enforce server binding at compile time
- #264: Make exponential backoff parameters configurable" \
  --assignee leynos

Length of output: 1903


Perfect! Both GitHub issues have been successfully created:

Issue #275: Refactor duplicated bind logic in server config implementations

  • Addresses consolidating the duplicate bind logic across Unbound and Bound implementations

Issue #276: Consider using tokio::task::JoinSet instead of TaskTracker for worker management

  • Addresses modernising the task management approach with current Tokio patterns

Both issues include detailed problem descriptions, suggested solutions, context from this PR, references to related issues, and are assigned to you for follow-up implementation.

  /\_   _/\
 (  ^.^  )
o_)    ) (

(( ).)_)

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