Skip to content

Conversation

leynos
Copy link
Owner

@leynos leynos commented Jul 27, 2025

Summary

  • document thread safety and single-use semantics for ready_tx
  • warn if readiness signal can't be sent
  • add catch_and_log_unwind helper and use it in worker_task
  • simplify PanicWorld using a PanicServer helper

Testing

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

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

Summary by Sourcery

Improve server readiness signaling by clarifying semantics, warning on send failures, and centralizing panic handling; refactor tests accordingly

Enhancements:

  • Document thread safety and single-use semantics for the ready_tx readiness channel
  • Log a warning if the readiness signal fails to send
  • Extract catch_and_log_unwind helper to centralize panic handling in worker tasks
  • Refactor PanicWorld tests by introducing a PanicServer helper and streamlining shutdown

Documentation:

  • Add documentation comments for ready_tx field and ready_signal method

Tests:

  • Simplify PanicWorld test setup and teardown using the new PanicServer helper

Copy link
Contributor

coderabbitai bot commented Jul 27, 2025

Summary by CodeRabbit

  • New Features

    • Improved server readiness signalling with enhanced error handling and documentation.
    • Added a new test to verify server behaviour when readiness signals are dropped.
  • Refactor

    • Simplified and modularised panic resilience test infrastructure for easier server management and shutdown.
    • Centralised server lifecycle logic in a dedicated structure, improving code clarity and maintainability.
  • Bug Fixes

    • Ensured that dropping the readiness receiver logs a warning but does not prevent the server from accepting connections.

Walkthrough

Extend WireframeServer with an optional readiness notification channel and enhance documentation regarding its usage. Refactor panic handling in connection worker tasks for clearer logic and improved error reporting. Add a test for readiness receiver drop scenarios and restructure panic resilience tests by introducing a PanicServer helper to encapsulate server lifecycle management.

Changes

File(s) Change Summary
src/server.rs Add ready_tx field to WireframeServer, update ready_signal docs, handle readiness send errors, refactor panic handling in worker tasks.
tests/server.rs Add async test readiness_receiver_dropped to verify server behaviour when readiness receiver is dropped.
tests/world.rs Refactor panic resilience tests: introduce PanicServer struct, centralise shutdown in Drop, simplify PanicWorld.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test
    participant Server as WireframeServer
    participant Client as TCP Client

    Test->>Server: Create with oneshot::Sender for readiness
    Test->>Server: Drop oneshot::Receiver (simulate send failure)
    Server->>Test: Attempt to send readiness signal (fails, logs warning)
    Test->>Server: Connect TCP client
    Client->>Server: Establish connection
    Server->>Client: Accept connection (despite readiness signal failure)
Loading
sequenceDiagram
    participant PanicWorld as PanicWorld
    participant PanicServer as PanicServer
    participant Server as WireframeServer
    participant Client as TCP Client

    PanicWorld->>PanicServer: spawn()
    PanicServer->>Server: Start with panic-inducing callback
    PanicServer->>Server: Await readiness
    Client->>Server: Attempt connection (triggers panic)
    Server->>PanicServer: Panic handled, error logged
    PanicWorld->>PanicServer: Drop (shutdown)
    PanicServer->>Server: Send shutdown, await task completion
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Possibly related PRs

  • Add WireframeServer skeleton #6: Introduces the initial WireframeServer struct and core async server logic, which is directly extended and refined in this PR.

Poem

A signal sent, but no one there—
The server shrugs, still takes the dare.
Panics caught and warnings logged,
Connection flows remain unclogged.
With helpers new and tests refined,
The code grows strong, robustly lined!
🚦💡


📜 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 2c6eff2 and f8707e3.

📒 Files selected for processing (3)
  • src/server.rs (4 hunks)
  • tests/server.rs (1 hunks)
  • tests/world.rs (3 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:

  • tests/server.rs
  • src/server.rs
  • tests/world.rs
🧬 Code Graph Analysis (3)
tests/server.rs (3)
tests/preamble.rs (5)
  • tokio (131-131)
  • tokio (132-132)
  • oneshot (73-73)
  • factory (38-40)
  • WireframeServer (56-58)
src/server.rs (6)
  • factory (526-528)
  • new (96-112)
  • server (594-594)
  • server (852-852)
  • WireframeServer (550-550)
  • WireframeServer (694-696)
tests/world.rs (1)
  • spawn (20-52)
src/server.rs (1)
src/app.rs (1)
  • process_stream (554-580)
tests/world.rs (1)
tests/steps/panic_steps.rs (1)
  • connect (15-15)
🔇 Additional comments (6)
src/server.rs (4)

61-73: Excellent documentation for the readiness signaling field.

The documentation clearly explains the thread safety guarantees, single-use semantics, and practical implications. This helps users understand why they need to provide a fresh sender for each server run.


210-212: Clear method documentation reinforcing single-use semantics.

The documentation correctly emphasises that a fresh sender is needed for each server run, maintaining consistency with the field documentation.


342-347: Robust error handling for readiness signal failures.

The implementation correctly logs a warning when the readiness receiver is dropped, allowing the server to continue operating normally. This prevents silent failures whilst maintaining server availability.


409-421: Clean panic handling implementation with good error context.

The refactored panic handling correctly captures and logs connection task panics with peer address context. The simplified message extraction using copied() and chained or_else() is more readable than the previous implementation.

tests/world.rs (2)

12-53: Excellent modularisation of server lifecycle management.

The PanicServer struct cleanly encapsulates server state and startup logic. The use of readiness signaling ensures the server is fully operational before returning, preventing race conditions in tests.


72-105: Clean refactoring leveraging the new PanicServer abstraction.

The simplified PanicWorld implementation delegates server management to PanicServer, making the code more maintainable. The addition of yield_now after dropping the server ensures proper task scheduling.

✨ 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/address-code-review-comments

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

sourcery-ai bot commented Jul 27, 2025

Reviewer's Guide

This PR enhances server readiness signaling by clarifying ready_tx thread-safety and single-use behavior, warning on failed signals, introducing a generic panic-catching helper for worker tasks, and refactoring the PanicWorld test scaffold into a reusable PanicServer abstraction.

Sequence diagram for server readiness signaling and warning

sequenceDiagram
    participant Server
    participant ReadyReceiver as oneshot::Receiver
    participant Logger as tracing
    Server->>ReadyReceiver: tx.send(())
    alt send fails (receiver dropped)
        Server->>Logger: warn("Failed to send readiness signal: receiver dropped")
    end
Loading

Sequence diagram for worker task panic handling with catch_and_log_unwind

sequenceDiagram
    participant WorkerTask
    participant catch_and_log_unwind
    participant Logger as tracing
    WorkerTask->>catch_and_log_unwind: spawn(process_stream, peer_addr)
    alt panic occurs
        catch_and_log_unwind->>Logger: error("connection task panicked", panic_msg, peer_addr)
    end
Loading

File-Level Changes

Change Details Files
Document and clarify thread-safety and single-use semantics of the readiness channel
  • Add doc comments on ready_tx field describing Send and single-use limitations
  • Update ready_signal docs to emphasize consumption of the sender per run
src/server.rs
Warn when readiness signal cannot be sent
  • Combine Option check and send call in run method
  • Emit a warning if tx.send() fails because receiver was dropped
src/server.rs
Extract and apply a generic panic-catching helper for connection tasks
  • Add catch_and_log_unwind async helper to centralize panic catching and logging
  • Refactor worker_task to replace inline unwind logic with the new helper
src/server.rs
Refactor PanicWorld tests into a reusable PanicServer abstraction
  • Introduce PanicServer struct with spawn method and Drop-based shutdown
  • Simplify PanicWorld to wrap an Option and delegate lifecycle
  • Update start, connect, and shutdown methods to use the new abstraction
tests/world.rs

Tips and commands

Interacting with Sourcery

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

Customizing Your Experience

Access your dashboard to:

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

Getting Help

Copy link
Contributor

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

  • Using futures::executor::block_on inside PanicServer’s Drop can deadlock if dropped within an async context—consider refactoring to await the handle in async or use JoinHandle::abort/await instead of blocking in Drop.
  • The if let Some(tx) = self.ready_tx && tx.send(()).is_err() pattern requires Rust 1.65+ for let‐chains; please ensure your CI toolchain supports this or revert to a nested if‐let for broader compatibility.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Using futures::executor::block_on inside PanicServer’s Drop can deadlock if dropped within an async context—consider refactoring to await the handle in async or use JoinHandle::abort/await instead of blocking in Drop.
- The `if let Some(tx) = self.ready_tx && tx.send(()).is_err()` pattern requires Rust 1.65+ for let‐chains; please ensure your CI toolchain supports this or revert to a nested if‐let for broader compatibility.

## Individual Comments

### Comment 1
<location> `tests/world.rs:55` </location>
<code_context>
     }
+}
+
+impl Drop for PanicServer {
+    fn drop(&mut self) {
+        if let Some(tx) = self.shutdown.take() {
+            let _ = tx.send(());
+        }
+        let _ = futures::executor::block_on(&mut self.handle);
+    }
+}
</code_context>

<issue_to_address>
Potential for panics or hangs in Drop implementation of PanicServer.

Using block_on in Drop may cause tests to hang or panic if the server task does not complete. Adding a timeout or handling panics can help prevent indefinite hangs and make failures clearer.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
impl Drop for PanicServer {
    fn drop(&mut self) {
        if let Some(tx) = self.shutdown.take() {
            let _ = tx.send(());
        }
        let _ = futures::executor::block_on(&mut self.handle);
    }
}
=======
impl Drop for PanicServer {
    fn drop(&mut self) {
        use std::time::Duration;
        use futures::FutureExt;

        if let Some(tx) = self.shutdown.take() {
            let _ = tx.send(());
        }
        // Set a timeout for the server task to finish
        let timeout = Duration::from_secs(5);
        let handle_fut = (&mut self.handle).timeout(timeout);
        match futures::executor::block_on(handle_fut) {
            Ok(Ok(_)) => {} // Server task finished successfully
            Ok(Err(e)) => {
                eprintln!("PanicServer task panicked: {:?}", e);
            }
            Err(_) => {
                eprintln!("PanicServer task did not shut down within timeout");
            }
        }
    }
}
>>>>>>> REPLACE

</suggested_fix>

### Comment 2
<location> `tests/world.rs:75` </location>
<code_context>
+    ///
+    /// # Panics
+    /// Panics if binding the server fails or the server task fails.
+    pub async fn start_panic_server(&mut self) { self.server.replace(PanicServer::spawn().await); }

     /// Connect to the running server once.
</code_context>

<issue_to_address>
No test coverage for server readiness signaling failure.

Please add a test that drops the receiver before the server signals readiness to ensure the warning path is exercised and the server behaves as expected.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
pub struct PanicWorld {
    server: Option<PanicServer>,
    attempts: usize,
}
=======
pub struct PanicWorld {
    server: Option<PanicServer>,
    attempts: usize,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use tokio::sync::Mutex;
    use tokio::time::{timeout, Duration};

    /// Test that dropping the readiness receiver before the server signals readiness
    /// triggers the warning path and the server behaves as expected.
    #[tokio::test]
    async fn test_server_readiness_receiver_dropped() {
        // Setup a custom PanicServer that exposes the readiness sender
        struct TestPanicServer {
            addr: std::net::SocketAddr,
            // Optionally store the join handle if needed
        }

        impl TestPanicServer {
            async fn spawn_with_readiness_sender() -> (Self, tokio::sync::oneshot::Sender<()>) {
                use tokio::net::TcpListener;
                use tokio::sync::oneshot;

                let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind failed");
                let addr = listener.local_addr().unwrap();
                let (tx, rx) = oneshot::channel::<()>();

                // Drop the receiver immediately to simulate the failure
                drop(rx);

                // Spawn the server task, which will try to send on tx
                tokio::spawn(async move {
                    // Simulate server startup delay
                    tokio::time::sleep(Duration::from_millis(100)).await;
                    // This send will fail, triggering the warning path
                    let _ = tx.send(());
                    // Keep the server alive for a short time
                    let _ = listener.accept().await;
                });

                (Self { addr }, tx)
            }
        }

        // Spawn the test server with readiness sender
        let (server, _tx) = TestPanicServer::spawn_with_readiness_sender().await;

        // Try to connect to the server after a short delay to ensure it's running
        tokio::time::sleep(Duration::from_millis(200)).await;
        let stream_result = TcpStream::connect(server.addr).await;

        // The server should still accept connections even though readiness signaling failed
        assert!(stream_result.is_ok(), "Server did not accept connection after readiness receiver dropped");
    }
}
>>>>>>> REPLACE

</suggested_fix>

### Comment 3
<location> `src/server.rs:342` </location>
<code_context>
         let listener = self.listener.expect("`bind` must be called before `run`");
-        if let Some(tx) = self.ready_tx {
-            let _ = tx.send(());
+        if let Some(tx) = self.ready_tx
+            && tx.send(()).is_err()
+        {
</code_context>

<issue_to_address>
Consider simplifying the readiness signal handling and inlining the panic handler to reduce boilerplate and improve readability.

```suggestion
RunWithShutdown::run_with_shutdown – simplify readiness signal and panic‐catcher

1. Replace the chained `if let … &&` with a straightforward two‐step match on `Option`  
   and avoid moving `self.ready_tx` by calling `take()`.  

   ```rust
   // before
   if let Some(tx) = self.ready_tx
       && tx.send(()).is_err()
   {
       tracing::warn!("Failed to send readiness signal: receiver dropped");
   }

   // after
   if let Some(tx) = self.ready_tx.take() {
       if tx.send(()).is_err() {
           tracing::warn!("Failed to send readiness signal: receiver dropped");
       }
   }
   ```

2. Inline the panic‐handler into `worker_task` (only used once) and drop the free fn.  
   This collapses boilerplate and keeps error‐context nearby:  

   ```rust
   // Remove the `catch_and_log_unwind` helper entirely, and in worker_task:
   t.spawn(async move {
       use futures::FutureExt;
       let fut = std::panic::AssertUnwindSafe(
           process_stream(stream, factory, success, failure),
       )
       .catch_unwind();

       if let Err(panic) = fut.await {
           let panic_msg = panic
               .downcast_ref::<&str>().map(|s| *s)
               .or_else(|| panic.downcast_ref::<String>().map(String::as_str))
               .unwrap_or("<non‐string panic>");
           tracing::error!(panic = %panic_msg, ?peer_addr, "connection task panicked");
       }
   });
   ```

Both changes keep the same functionality but reduce nested logic, free‐function boilerplate, and improve local readability.
</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.

@leynos
Copy link
Owner Author

leynos commented Jul 27, 2025

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jul 27, 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.

@leynos leynos merged commit 1214f73 into main Jul 27, 2025
5 checks passed
@leynos leynos deleted the codex/address-code-review-comments branch July 27, 2025 13:30
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