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

Add timeout to all requests #50

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

Add timeout to all requests #50

wants to merge 1 commit into from

Conversation

U1F984
Copy link

@U1F984 U1F984 commented Dec 11, 2024

Since the default requests timeout is infinite individual calls might hang for a very long time if something in the network breaks. See also Taxel/PlexTraktSync#2107.

Copy link

coderabbitai bot commented Dec 11, 2024

Walkthrough

The changes involve the introduction of a new constant TIMEOUT set to 30 seconds in trakt/core.py. This constant is applied to various HTTP request methods, specifically in the pin_auth, get_device_code, get_device_token, and _refresh_token functions, ensuring that requests to the Trakt API do not hang indefinitely. Additionally, print statement formatting in the get_device_code function has been standardized, but the overall code structure and logic remain unchanged.

Changes

File Change Summary
trakt/core.py Added a new constant TIMEOUT set to 30 seconds; updated session.post calls and _handle_request method to include timeout=TIMEOUT; formatted print statements in get_device_code for consistency.

Poem

In the code where rabbits play,
A timeout now keeps hangs at bay.
With thirty seconds, swift and bright,
Our requests will dance, taking flight.
Hooray for changes, neat and fine,
In the world of code, we brightly shine! 🐇✨


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>, 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. (Experiment)
  • @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: 0

🧹 Outside diff range and nitpick comments (2)
trakt/core.py (2)

75-76: Consider making the timeout configurable

While 30 seconds is a reasonable default timeout, it would be better to make this configurable to accommodate different network conditions and use cases.

Consider this implementation:

-#: Timeout in seconds for all requests
-TIMEOUT = 30
+#: Timeout in seconds for all requests (default: 30)
+TIMEOUT = int(os.getenv('PYTRAKT_TIMEOUT', '30'))

Line range hint 553-563: Enhance error handling for timeout scenarios

The current error handling doesn't specifically handle request timeouts. Consider adding explicit handling for requests.exceptions.Timeout to provide clearer feedback to users.

Here's a suggested implementation:

 def _handle_request(self, method, url, data=None):
     try:
         if method == 'get':
             response = session.request(method, url, headers=HEADERS,
                                    params=data, timeout=TIMEOUT)
         else:
             response = session.request(method, url, headers=HEADERS,
                                    data=json.dumps(data), timeout=TIMEOUT)
+    except requests.exceptions.Timeout:
+        self.logger.error('Request timed out after %s seconds: %s %s', 
+                         TIMEOUT, method, url)
+        raise errors.TraktTimeout(f"Request timed out after {TIMEOUT} seconds")
     
     self.logger.debug('RESPONSE [%s] (%s): %s', method, url, str(response))
     if response.status_code in self.error_map:
         raise self.error_map[response.status_code](response)

You'll also need to add a new exception class in errors.py:

class TraktTimeout(TraktException):
    """Request timed out"""
    http_code = 408  # Request Timeout
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 11bf3c0 and 9c7ae84.

📒 Files selected for processing (1)
  • trakt/core.py (12 hunks)
🔇 Additional comments (2)
trakt/core.py (2)

147-147: Well-implemented timeout across all request methods

The timeout parameter has been consistently applied to all HTTP requests, including authentication, device code generation, token refresh, and general API calls. This implementation effectively prevents requests from hanging indefinitely.

Also applies to: 237-237, 278-278, 421-421, 548-548, 551-551


548-551: Verify complete coverage of request timeouts

Let's verify that all HTTP requests in the codebase are routed through _handle_request and thus have the timeout applied.

✅ Verification successful

Let me gather more information to verify if all requests are properly routed through the core request handling mechanism.


Let me do one final check to understand the class structure and request routing.


All request timeouts are properly implemented

Based on the verification results:

  1. All HTTP methods (GET, POST, PUT, DELETE) are implemented as decorators that route through _handle_request
  2. The only direct session calls are for authentication-related endpoints, and they all have the timeout parameter properly set
  3. There are no other request calls that could bypass the timeout implementation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct requests.Session or requests calls that might bypass _handle_request
rg -l "requests\.(get|post|put|delete|request)" | grep -v "core\.py"

# Search for potential timeout parameter usage elsewhere
rg "timeout\s*="

Length of output: 656


Script:

#!/bin/bash
# Search for all HTTP-related method definitions and usages in core.py
ast-grep --pattern 'def _handle_request'

# Look for any direct session usage
rg "session\." -A 2

# Check for any request methods defined in the class
ast-grep --pattern 'def (get|post|put|delete|request)'

Length of output: 1438


Script:

#!/bin/bash
# Check the class structure and public methods
ast-grep --pattern 'class $_ {
  $$$
}'

# Look for any method that might be calling these requests
rg "def" -A 1 trakt/core.py

Length of output: 2772

@glensc
Copy link
Owner

glensc commented Dec 11, 2024

formatting changes and code changes must be separate commits, even better separate pull request

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