Skip to content

Router methods - #41

Merged
j03-dev merged 17 commits into
mainfrom
router_methods
May 23, 2025
Merged

Router methods#41
j03-dev merged 17 commits into
mainfrom
router_methods

Conversation

@j03-dev

@j03-dev j03-dev commented May 23, 2025

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Introduced thread-safe and decorator-based route registration for improved flexibility and concurrency in routing.
    • Added centralized authentication and logging logic for API endpoints, including secure password hashing and JWT handling.
    • Separated public and secured API endpoints with middleware for enhanced security and logging.
  • Refactor

    • Consolidated request handling context into a single structure for cleaner and more maintainable server code.
    • Simplified and unified route registration and middleware application across examples.
    • Renamed types and updated function signatures for clarity and consistency.
  • Chores

    • Removed redundant utility and middleware files, integrating their logic directly where needed.

@coderabbitai

coderabbitai Bot commented May 23, 2025

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

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

⌛ How to resolve this issue?

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

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

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

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

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between e178602 and 9506cd5.

📒 Files selected for processing (2)
  • README.md (3 hunks)
  • examples/htmx/main.py (2 hunks)

Walkthrough

The updates refactor authentication, password hashing, and logging in the API example by moving all related logic into main.py, removing external utility and middleware files. Routing is restructured using explicit Router instances with middleware for public and secured endpoints. The Rust backend is refactored for thread-safe routing, decorator-style registration, and consolidated request context handling.

Changes

File(s) Change Summary
examples/api/main.py Refactored to implement password hashing, JWT handling, and logging directly in-file. Introduced bcrypt-based functions, JWT middleware, logger, and explicit Router instances for public and secured routes with attached middleware. Route decorators updated to use routers.
examples/api/middlewares.py, examples/api/utils.py Deleted. Their middleware and utility functions (JWT, password hashing, logging) are now implemented directly in main.py.
examples/htmx/main.py Refactored to use explicit Router instance for route registration and static files. Route decorators updated to use the router. Cleaned up imports and simplified form validation logic.
src/handling/request_handler.rs Simplified handle_request signature to accept a single Arc<RequestContext> parameter. Updated internal destructuring and imports accordingly.
src/handling/response_handler.rs Renamed MatchitRoute to MatchRoute in imports and function signatures. No logic changes.
src/lib.rs Renamed type alias MatchitRoute to MatchRoute. Introduced RequestContext struct to bundle request handling context. Refactored server run logic to use this struct.
src/routing.rs Made Router's route storage thread-safe with Arc<RwLock<HashMap>>. Added a Decorator class for decorator-style route registration. Updated methods for thread safety and decorator support. Changed find to use new types.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API_Server
    participant JWT_Middleware
    participant Logger
    participant Router
    participant Handler

    Client->>API_Server: HTTP Request (e.g., /me)
    API_Server->>Logger: Log method, URI, timestamp
    Logger->>JWT_Middleware: (if secured route) Check Authorization header
    JWT_Middleware-->>API_Server: Set request.user_id or return UNAUTHORIZED
    API_Server->>Router: Route request
    Router->>Handler: Call endpoint handler
    Handler-->>API_Server: Return response
    API_Server-->>Client: HTTP Response
Loading

Possibly related PRs

  • use decorateur to create route #13: This PR modularizes routing and authentication by importing utilities and middleware, whereas the current PR centralizes these into main.py. Both affect routing and authentication but take opposite approaches regarding utility and middleware placement.

Poem

🐇
In the warren, code now hops,
JWTs and hashes—no more stops!
Routers guard both pub and sec,
With logs and locks, what the heck!
Rusty routes now thread-safe run,
Refactored flows—springtime fun!
Hooray for changes, everybun!

✨ Finishing Touches
  • 📝 Generate Docstrings

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Nitpick comments (4)
src/routing.rs (3)

71-93: Consider the mutability requirements for Decorator.

The Decorator struct's __call__ method requires &mut self, but the router methods that create decorators (lines 132-138) use &self. This works because the Router is cloned and its internal routes field uses Arc<RwLock> for shared mutability. However, this design might be confusing as it's not immediately clear why __call__ needs mutable access when it's only modifying shared state.

Consider making __call__ take &self instead of &mut self for clarity:

-    fn __call__(&mut self, handler: Py<PyAny>) -> PyResult<Route> {
+    fn __call__(&self, handler: Py<PyAny>) -> PyResult<Route> {

97-97: Good thread-safety implementation!

The use of Arc<RwLock<HashMap>> for the routes field enables safe concurrent access. This is a solid improvement for multi-threaded environments.

Consider monitoring for lock contention under high load scenarios, as write locks on the entire HashMap could become a bottleneck if routes are frequently modified at runtime.


124-129: Use more idiomatic iteration pattern.

Consider using the more conventional iteration pattern:

-                for ref route in routes {
+                for route in &routes {
                     self.route(route)?;
                 }
examples/api/main.py (1)

117-122: Avoid modifying validated data directly.

Instead of modifying validate_data in place, create a new user instance:

-    new_user.validate_data.update(
-        {
-            "id": str(uuid.uuid4()),
-            "password": hash_password(new_user.validate_data["password"]),
-        }
-    )
+    user_data = {
+        **new_user.validate_data,
+        "id": str(uuid.uuid4()),
+        "password": hash_password(new_user.validate_data["password"]),
+    }

Then use user_data when saving the user.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 27ad339 and 51a6888.

📒 Files selected for processing (8)
  • examples/api/main.py (4 hunks)
  • examples/api/middlewares.py (0 hunks)
  • examples/api/utils.py (0 hunks)
  • examples/htmx/main.py (2 hunks)
  • src/handling/request_handler.rs (3 hunks)
  • src/handling/response_handler.rs (2 hunks)
  • src/lib.rs (3 hunks)
  • src/routing.rs (3 hunks)
💤 Files with no reviewable changes (2)
  • examples/api/utils.py
  • examples/api/middlewares.py
🧰 Additional context used
🪛 Gitleaks (8.26.0)
examples/api/main.py

22-22: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🪛 Ruff (0.11.9)
examples/api/main.py

86-87: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)

⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: macos (macos-13, x86_64)
  • GitHub Check: linux (ubuntu-22.04, aarch64)
  • GitHub Check: windows (windows-latest, x86)
  • GitHub Check: windows (windows-latest, x64)
  • GitHub Check: linux (ubuntu-22.04, s390x)
  • GitHub Check: musllinux (ubuntu-22.04, x86)
  • GitHub Check: linux (ubuntu-22.04, armv7)
  • GitHub Check: linux (ubuntu-22.04, x86)
  • GitHub Check: musllinux (ubuntu-22.04, armv7)
  • GitHub Check: linux (ubuntu-22.04, ppc64le)
  • GitHub Check: musllinux (ubuntu-22.04, x86_64)
  • GitHub Check: musllinux (ubuntu-22.04, aarch64)
  • GitHub Check: linux (ubuntu-22.04, x86_64)
🔇 Additional comments (12)
src/handling/response_handler.rs (1)

10-10: LGTM! Type alias rename is consistent.

The rename from MatchitRoute to MatchRoute is consistent with the broader refactoring across the codebase. The change simplifies the type name while maintaining the same functionality.

Also applies to: 53-53

examples/htmx/main.py (3)

2-2: Good cleanup of unused imports.

Removing the unused get and post imports makes sense since the code now uses router-bound decorators instead.


5-6: Excellent refactoring to explicit router instance.

Creating an explicit Router instance and registering static files early improves code organization and makes the routing structure more explicit and maintainable.


9-9: Router-bound decorators improve modularity.

The change from global decorators (@get, @post) to router-bound decorators (@router.get, @router.post) is a good architectural improvement that makes routing more explicit and modular.

Also applies to: 17-17, 22-22, 34-34

src/lib.rs (4)

49-49: Type alias rename improves clarity.

The rename from MatchitRoute to MatchRoute provides a cleaner, more concise type name while maintaining the same functionality.


87-87: Consistent type usage in ProcessRequest.

The MatchRoute type is correctly used in the ProcessRequest struct, maintaining consistency with the type alias rename.


92-101: Excellent RequestContext consolidation.

The new RequestContext struct effectively consolidates multiple shared fields into a single context object. This significantly improves code maintainability by:

  • Reducing parameter passing complexity
  • Providing a clear ownership model with Arc for thread-safe sharing
  • Making the request handling context more explicit

194-202: Clean RequestContext usage in async handling.

The RequestContext is properly created, cloned, and passed through the async task spawning chain. The Arc cloning ensures thread-safe access to the shared context data across concurrent request handlers.

Also applies to: 209-209, 217-218

src/handling/request_handler.rs (3)

9-9: Good import cleanup.

Removing unused imports (Sender, Router, Cors) and updating the type import (MatchitRoute to MatchRoute) keeps the imports clean and consistent with the refactoring.

Also applies to: 18-18


31-43: Excellent function signature simplification.

The refactoring from multiple individual parameters to a single Arc<RequestContext> parameter significantly improves the function signature's maintainability. The destructuring approach provides clear access to all context fields while maintaining the same functionality.


58-58: Type cast updated consistently.

The unsafe transmute now uses the updated MatchRoute type, maintaining consistency with the type alias rename. While unsafe code should generally be avoided, this appears to be existing functionality that was just updated for the new type.

examples/api/main.py (1)

75-81: Secure password handling implementation!

Good use of bcrypt with proper salt generation and constant-time comparison. This follows security best practices for password storage.

Comment thread examples/htmx/main.py Outdated
Comment thread src/routing.rs
Comment thread src/routing.rs
Comment thread examples/api/main.py
Comment thread examples/api/main.py
Comment thread examples/api/main.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 51a6888 and e178602.

📒 Files selected for processing (1)
  • README.md (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: windows (windows-latest, x86)
  • GitHub Check: windows (windows-latest, x64)
🔇 Additional comments (5)
README.md (5)

17-17: Import updated to Router-based API
The import line now correctly brings in HttpServer, Router, Status, and Response instead of individual route decorators, aligning with the new routing module design.


19-23: Instantiate and bind routes via Router instance
Creating a Router() instance and using its .get() decorator for the root endpoint ensures thread-safe, decorator-based registration as intended.


25-28: Use parameterized path with router.get
The /hello/{name} route leverages the new placeholder syntax with the router.get decorator correctly. This matches the updated API.


45-47: Register middleware on Router instance
Moving router.middleware(auth_middleware) before route definitions aligns with the new middleware attachment approach on router instances.


72-79: Instantiate Router for application state example
Initializing a fresh Router() here keeps the examples consistent: each section demonstrates a standalone router usage pattern.

Comment thread README.md Outdated
j03-dev and others added 3 commits May 23, 2025 14:21
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@j03-dev
j03-dev merged commit faceb10 into main May 23, 2025
@j03-dev
j03-dev deleted the router_methods branch May 23, 2025 11:28
@coderabbitai coderabbitai Bot mentioned this pull request May 26, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Sep 17, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Nov 28, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Aug 19, 2026
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