Skip to content
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

Customization of httpx.AsyncClient behaviour #185

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

Conversation

santibreo
Copy link

@santibreo santibreo commented Jul 30, 2024

First of all, congratz for this awesome library.

I was using it for a non-public application, and I encountered issues when using it behind a proxy and also related with SSL certificates, everything related with the httpx.AsyncClient used here so I just added a new parameter with keyword arguments that is passed directly to that class (that is the reason why I do not have added any tests).

Additionally, I have solved some typing issues, but they were related to pyright and you might not want to incorporate those.

That's it. Thank you for your work 😄

Summary by CodeRabbit

  • New Features

    • Introduced a new parameter for custom asynchronous HTTP client configuration.
  • Improvements

    • Updated verify_and_process and process_login methods to require explicit values for several parameters, enhancing clarity.
    • Streamlined type handling for the convert_response parameter.
  • Tests

    • Refined the testing strategy for the login functionality by updating the setup of the fake asynchronous client.

@tomasvotava
Copy link
Owner

Thanks a lot! It looks good to me, but I feel like it's a lot of changes to do something rather simple, don't you think? It feels a little bit weird (though I understand that it's due to the client being instantiated on multiple places) that some methods should ask for a httpx client, a common user of the library should probably be a little bit shielded from that. I am seriously considering using a factory method instead, you could initialize SSOBase with a http client factory, what do you think? Am I overthinking this? 😄

@santibreo
Copy link
Author

santibreo commented Aug 19, 2024

The factory method is a better approach. I was in a rush because I wanted to finish the implementation before my holidays (which also explains the delay in the answer), and I thought that was good enough. However, I did not have the complete picture as I only use Microsoft SSO.
Would you like me to implement it, or are you working on it?

Copy link

coderabbitai bot commented Sep 6, 2024

Walkthrough

The changes enhance the fastapi_sso library by introducing a new optional parameter, get_async_client, to the constructor for custom HTTP client configuration. The method signatures for verify_and_process and process_login have been updated to remove default values for several parameters, making them mandatory. Additionally, the type for the convert_response parameter has been simplified to a boolean, improving clarity in method usage.

Changes

Files Change Summary
fastapi_sso/sso/base.py Added get_async_client parameter to the constructor. Updated verify_and_process and process_login method signatures to remove default values for several parameters and simplified the type of convert_response.
tests/test_providers.py Updated the test_process_login function to mock the get_async_client method instead of httpx.AsyncClient, improving test encapsulation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant FastAPI
    participant HttpxClient

    User->>FastAPI: Initiate Login
    FastAPI->>HttpxClient: Call process_login with parameters
    HttpxClient-->>FastAPI: Return response
    FastAPI->>User: Send login response
Loading

🐇 "Oh, what a delight, my code's now so bright!
With kwargs for clients, it's a wonderful sight!
Parameters clear, no defaults to fear,
In the land of FastAPI, I leap with good cheer!
Hopping through changes, I dance with glee,
HTTP's magic, oh, come play with me!" 🐇


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 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

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Outside diff range, codebase verification and nitpick comments (1)
fastapi_sso/sso/base.py (1)

314-318: Enhance documentation for httpx_client_kwargs

The documentation for the httpx_client_kwargs parameter is minimal across the methods where it's introduced. Given the importance of this parameter for configuring the HTTP client, detailed documentation would help developers understand how to use it effectively. It would be beneficial to include examples of common configurations, such as setting up proxies or disabling SSL verification, in the docstrings.

Also applies to: 326-330, 340-341, 351-351, 361-361, 386-386, 418-423, 432-437, 442-452, 463-464, 477-477, 497-497, 530-530

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 6c8ed47 and a85929e.

Files selected for processing (1)
  • fastapi_sso/sso/base.py (12 hunks)
Additional comments not posted (2)
fastapi_sso/sso/base.py (2)

23-40: New TypedDict HttpxClientKwargsType for HTTP client configuration

The introduction of HttpxClientKwargsType is a positive change as it provides a structured way to pass HTTP client configurations. This approach enhances type safety and makes the API more expressive and easier to use correctly. The fields cover common configurations like SSL verification, client certificates, proxy settings, and timeouts, which are essential for flexible HTTP client operations.


314-318: Verify and enhance error handling

The addition of httpx_client_kwargs allows for more flexible HTTP client configurations, which is a significant improvement. However, the error handling related to HTTP client interactions seems minimal. Given the complexity and variety of network-related errors that can occur, especially with proxies and SSL configurations, robust error handling is crucial.

It would be beneficial to add more comprehensive error handling around the HTTP client interactions to manage exceptions like httpx.HTTPError, timeouts, and other network issues. This would improve the robustness of the SSO functionality and provide clearer error messages to the users.

Also applies to: 326-330, 340-341, 351-351, 361-361, 386-386, 418-423, 432-437, 442-452, 463-464, 477-477, 497-497, 530-530

Comment on lines 314 to 318
params: Optional[Dict[str, Any]],
headers: Optional[Dict[str, Any]],
redirect_uri: Optional[str],
convert_response: Literal[True],
httpx_client_kwargs: Optional[HttpxClientKwargsType],
Copy link

Choose a reason for hiding this comment

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

Refactor suggestion: Consolidate httpx_client_kwargs handling

The httpx_client_kwargs parameter has been added across multiple methods (verify_and_process, process_login) to customize the HTTP client behavior. While this addition is beneficial, the handling of this parameter is scattered and repetitive across methods. This could be streamlined by centralizing the creation and configuration of the httpx.AsyncClient instance, possibly using a factory method or a helper function within the class. This would reduce redundancy and improve maintainability.

Consider implementing a method like get_http_client that takes httpx_client_kwargs and returns a configured httpx.AsyncClient instance. This method can then be used across all functions needing an HTTP client.

Also applies to: 326-330, 340-341, 351-351, 361-361, 386-386, 418-423, 432-437, 442-452, 463-464, 477-477, 497-497, 530-530

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a85929e and 29c1045.

Files selected for processing (2)
  • fastapi_sso/sso/base.py (9 hunks)
  • tests/test_providers.py (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • fastapi_sso/sso/base.py
Additional context used
Ruff
tests/test_providers.py

141-141: Line too long (121 > 120)

(E501)

Additional comments not posted (1)
tests/test_providers.py (1)

153-153: Good encapsulation practice in test setup.

The change to use monkeypatch.setattr on the get_async_client method of the sso object is a good practice. It improves the encapsulation and modularity of the test setup, making it easier to maintain and adapt to changes in the underlying client setup.

@@ -138,8 +138,7 @@ async def test_login_url_scope_additional(self, Provider: Type[SSOBase]):
async def test_process_login(self, Provider: Type[SSOBase], monkeypatch: pytest.MonkeyPatch):
sso = Provider("client_id", "client_secret")
FakeAsyncClient = make_fake_async_client(
returns_post=Response(url="https://localhost", json_content={"access_token": "token"}),
returns_get=Response(
returns_post=Response(url="https://localhost", json_content={"access_token": "token"}), returns_get=Response(
Copy link

Choose a reason for hiding this comment

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

Consider breaking long lines for better readability.

This line exceeds the recommended length of 120 characters, which can affect readability and maintainability. Consider breaking it into multiple lines.

Apply this diff to break the line into a more manageable length:

-returns_post=Response(url="https://localhost", json_content={"access_token": "token"}), returns_get=Response(
+returns_post=Response(url="https://localhost", json_content={"access_token": "token"}),
+returns_get=Response(
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
returns_post=Response(url="https://localhost", json_content={"access_token": "token"}), returns_get=Response(
returns_post=Response(url="https://localhost", json_content={"access_token": "token"}),
returns_get=Response(
Tools
Ruff

141-141: Line too long (121 > 120)

(E501)

@santibreo
Copy link
Author

Hello again!
I have implemented the factory method as suggested (as an additional parameter to sso.base.SSOBase.__init__) and adapted the tests. Everything seems to be working fine.

I think it's better this way and I hope @tomasvotava thinks the same way. Thank you again.

@santibreo santibreo changed the title Added httpx_client_kwargs parameter to allow customization of httpx.AsyncClient behaviour Customization of httpx.AsyncClient behaviour Sep 7, 2024
Copy link

@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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 29c1045 and 7e1e3ac.

Files selected for processing (2)
  • fastapi_sso/sso/base.py (9 hunks)
  • tests/test_providers.py (1 hunks)
Files skipped from review due to trivial changes (1)
  • tests/test_providers.py
Files skipped from review as they are similar to previous changes (1)
  • fastapi_sso/sso/base.py

Argument `get_httpx_client` incorporated to `SSOBase` to allow
customization of `httpx.AsyncClient` used to call auth provider
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.

2 participants