Skip to content

feat: add catcher feature to custom status handler (#31) #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

j03-dev
Copy link
Owner

@j03-dev j03-dev commented Apr 22, 2025

Summary by CodeRabbit

  • New Features
    • Introduced support for registering custom error handlers for specific HTTP status codes, enabling tailored responses for errors such as internal server errors.
  • Bug Fixes
    • Improved error handling by allowing validation exceptions to propagate and be managed by global error catchers.
  • Refactor
    • Streamlined response handling logic for better maintainability.
  • Style
    • Minor stylistic improvements in struct construction for consistency.
  • Chores
    • Enhanced struct traits to support equality checks, hashing, and debugging.

Copy link
Contributor

coderabbitai bot commented Apr 22, 2025

Walkthrough

This update introduces a status-based error handling mechanism to the server framework. A new Catcher class is implemented in Rust and exposed to Python, allowing users to register custom Python handlers for specific HTTP status codes. The HttpServer struct is extended to maintain a mapping of status codes to these handler functions. When a response with a registered status code is generated, the corresponding catcher is invoked to modify or replace the response. The Python API is updated to support this feature, and example usage is demonstrated in the API example. Minor refactoring and trait derivations are also included.

Changes

File(s) Change Summary
src/catcher.rs Introduced new Rust module defining a Python-exposed Catcher class, allowing registration of Python handlers for HTTP status codes. Implements constructor, callable interface, and exposes a catcher function to Python.
src/lib.rs Integrated the catcher module and logic into the core library. Added status_catchers to HttpServer and ProcessRequest, a method to register catchers, and exposed the catcher function to Python. Propagated the catcher mapping through server runtime and request handling.
src/handling/request_handler.rs Updated handle_request to accept an optional status_catcher parameter, propagating it to request processing. Added Clippy lint suppression for argument count.
src/handling/response_handler.rs Refactored response handling to allow mutation. Added logic to invoke status-based catcher handlers when a matching status is present in status_catcher, replacing the response if needed.
examples/api/main.py Updated endpoint handlers to let validation errors propagate. Added a global error catcher for internal server errors using the new catcher API and registered it with the server. Updated imports accordingly.
src/status.rs Extended Status struct to derive PartialEq, Eq, Hash, and Debug traits to support hashing and equality for use as map keys.
src/routing.rs Minor refactor to use Self in Route constructor for stylistic consistency. No logic changes.
src/serializer/mod.rs Simplified return expressions in the Serializer class by removing unnecessary Ok() wrappers and redundant .into() calls.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant HttpServer
    participant Catcher
    participant PythonHandler

    Client->>HttpServer: Send HTTP request
    HttpServer->>HttpServer: Process request, generate response
    alt Response status matches registered catcher
        HttpServer->>Catcher: Invoke catcher for status
        Catcher->>PythonHandler: Call Python handler with request & response
        PythonHandler-->>Catcher: Return modified response
        Catcher-->>HttpServer: Provide new response
    end
    HttpServer->>Client: Send (possibly modified) response
Loading

Possibly related PRs

  • Big refact #8: Introduced foundational request and response handling modules; this PR directly extends those modules to support status-based catcher callbacks.

Poem

A clever new catcher hops into play,
Handling errors in a custom way.
When status codes rise,
Python handlers surprise—
Responses transformed without delay!
With Rust and Python paw in paw,
The server now catches all with awe.
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f40b06b and 1e5c5a8.

📒 Files selected for processing (1)
  • src/lib.rs (12 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/lib.rs
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: windows (windows-latest, x86)
  • GitHub Check: windows (windows-latest, x64)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

@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

🧹 Nitpick comments (4)
examples/api/main.py (1)

127-130: Consider status code consistency in error catcher

The catcher correctly intercepts internal server errors, but returns a BAD_REQUEST (400) status instead of maintaining the original INTERNAL_SERVER_ERROR (500). While this might be intentional, consider whether this status conversion is desired UX. Usually, it's better to maintain the same status code category while providing a more user-friendly error message.

@catcher(Status.INTERNAL_SERVER_ERROR)
def catch_500(req: Request, res: Response):
-    return {"error": res.body}, Status.BAD_REQUEST
+    return {"error": res.body}, Status.INTERNAL_SERVER_ERROR
src/handling/response_handler.rs (2)

41-49: Surface catcher errors instead of silently ignoring them

If the Python catcher raises or returns an invalid object, the error is swallowed and the original response is returned. This makes debugging extremely hard.

Consider:

  1. Logging the Python exception via e.print(py) or your logging façade.
  2. Returning a 500 built from Status::INTERNAL_SERVER_ERROR so that clients and tests can detect the failure path.

Even a low‑verbosity log is better than complete silence.


53-54: Check the result of response_sender.send

_ = sender.send(..) discards a potential Err, masking back‑pressure or channel‑closure problems.
Return or log the error so that upstream can react.

-let _ = process_request.response_sender.send(response).await;
+if let Err(e) = process_request.response_sender.send(response).await {
+    eprintln!("Failed to forward response: {e}");
+}
src/catcher.rs (1)

1-36: Consider adding documentation for Python users.

While the implementation is solid, adding Python-facing docstrings would improve usability for Python developers consuming this API. PyO3 supports exposing Rust doc comments as Python docstrings.

 #[derive(Clone)]
 #[pyclass]
+/// A catcher for HTTP responses with specific status codes.
+/// 
+/// Use this class to register custom handlers for specific HTTP status codes.
 pub struct Catcher {
     pub status: Status,
     pub handler: Arc<Py<PyAny>>,
 }

 #[pymethods]
 impl Catcher {
     #[new]
+    /// Create a new catcher for the given status code.
     pub fn new(status: PyRef<'_, Status>, py: Python<'_>) -> Self {
         Self {
             status: status.clone(),
             handler: Arc::new(py.None()),
         }
     }

+    /// Register a handler function for this catcher.
+    /// 
+    /// The handler should accept a response object and return a modified response.
     fn __call__(&self, handler: Py<PyAny>) -> PyResult<Self> {
         Ok(Self {
             handler: Arc::new(handler),
             ..self.clone()
         })
     }
 }

 #[pyfunction]
+/// Create a new catcher for the given status code.
+/// 
+/// This is a decorator function that can be used to register
+/// a handler for a specific status code.
 pub fn catcher(status: PyRef<'_, Status>, py: Python<'_>) -> Catcher {
     Catcher::new(status, py)
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 324979f and f40b06b.

📒 Files selected for processing (8)
  • examples/api/main.py (5 hunks)
  • src/catcher.rs (1 hunks)
  • src/handling/request_handler.rs (3 hunks)
  • src/handling/response_handler.rs (2 hunks)
  • src/lib.rs (12 hunks)
  • src/routing.rs (1 hunks)
  • src/serializer/mod.rs (1 hunks)
  • src/status.rs (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/lib.rs (1)
src/catcher.rs (2)
  • catcher (33-35)
  • new (17-22)
⏰ Context from checks skipped due to timeout of 90000ms (14)
  • GitHub Check: macos (macos-14, aarch64)
  • GitHub Check: macos (macos-13, x86_64)
  • GitHub Check: linux (ubuntu-22.04, x86)
  • GitHub Check: linux (ubuntu-22.04, aarch64)
  • GitHub Check: linux (ubuntu-22.04, s390x)
  • GitHub Check: musllinux (ubuntu-22.04, armv7)
  • GitHub Check: linux (ubuntu-22.04, x86_64)
  • GitHub Check: windows (windows-latest, x86)
  • GitHub Check: linux (ubuntu-22.04, armv7)
  • GitHub Check: windows (windows-latest, x64)
  • GitHub Check: musllinux (ubuntu-22.04, aarch64)
  • GitHub Check: musllinux (ubuntu-22.04, x86_64)
  • GitHub Check: linux (ubuntu-22.04, ppc64le)
  • GitHub Check: musllinux (ubuntu-22.04, x86)
🔇 Additional comments (12)
src/status.rs (1)

8-8: Improved trait derivations allow Status to be used as HashMap key

Adding PartialEq, Eq, Hash, and Debug derivations is essential for the new catcher feature, as it enables Status instances to be used as keys in the status catcher HashMap.

src/routing.rs (1)

21-21: LGTM: Good refactoring to use Self

Using Self instead of the explicit struct name improves code maintainability. If the struct name changes in the future, this code won't need updating.

examples/api/main.py (3)

19-19: LGTM: Added catcher import

The import is properly added to support the new error handling functionality.


66-66: Removed try-except blocks in favor of global error handling

The validation exception handling is now delegated to the global catcher instead of being handled with try-except blocks in each handler, which is a cleaner approach.

Also applies to: 86-86


144-144: LGTM: Registered catcher with server instance

The catcher is properly registered with the server using the new API.

src/serializer/mod.rs (1)

145-145: Code simplification improves readability

The refactoring removes redundant Ok() wrappers and unnecessary .into() calls, making the code more concise while maintaining the same functionality.

Also applies to: 153-153, 156-156

src/handling/request_handler.rs (1)

23-33: Thread‑safety of status_catcher must be guaranteed

status_catcher is captured by the tokio::spawn below.
That future must be Send, which in turn requires
Arc<HashMap<Status, Py<PyAny>>>: Send + Sync.

Double‑check that Py<PyAny> indeed implements both Send and Sync
for your pyo3 version; otherwise this will fail to compile (or, worse, compile
with unsafe guarantees violated).
If Sync is missing, wrap the map in an RwLock and store the handlers as
GILOnceCell<Py<PyAny>>, or use a dashmap guarded by the GIL.

This issue has bitten the router handlers before, so please verify.

src/catcher.rs (5)

1-5: Imports look appropriate.

The imports correctly include Arc for thread-safe reference counting, PyO3 for Python integration, and the internal Status type. This provides the foundation needed for the rest of the implementation.


7-12: Good struct design with appropriate attribute derivation.

The Catcher struct correctly derives Clone and is properly marked with #[pyclass] for Python exposure. Using Arc<Py<PyAny>> for the handler ensures thread-safety when sharing Python callables across async contexts.


14-22: Constructor initialization looks good.

The constructor appropriately takes a Python reference to a Status object and initializes the handler to Python's None. This matches the pattern where the actual handler would be set later via the __call__ method.


24-29: Elegant implementation of the callable pattern.

The __call__ method creates a new Catcher with the provided handler while preserving the original status. Using struct update syntax (..self.clone()) is a clean approach. The return type correctly uses PyResult to handle potential Python errors.


32-35: Good Python function export.

The standalone catcher function provides a convenient way to create a new Catcher instance from Python. This follows the common PyO3 pattern of providing a function wrapper around a struct constructor for better Python ergonomics.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant