Skip to content

Conversation

@simonc56
Copy link
Collaborator

@simonc56 simonc56 commented Feb 7, 2025

Starting on March 4, 2025, a Trakt OAuth access_token will expire in 24 hours, instead of 3 months.

The current logic is to refresh the access_token if its expiration date is within next 2 days.
With current code, a 24h token would be immediately refreshed after being fetched. We do not want that.
This PR changes this delay from 2 days to 10 minutes.

Why 10 minutes ?

This is a margin to be sure the token does not expire in the middle of a critical action such as a list sync/fetch/post.
It could be any other delay, but not bigger than 24h.

Refs :

@coderabbitai
Copy link

coderabbitai bot commented Feb 7, 2025

Walkthrough

The changes modify the token validation logic in the TokenAuth class found in trakt/api.py. The validity condition was adjusted to require that tokens have more than ten minutes before expiration, rather than over two days. No changes were made to the signatures of exported or public entities.

Changes

File Change Summary
trakt/api.py Modified the validate_token method in TokenAuth to check for token expiry >10 minutes instead of >2 days.

Sequence Diagram(s)

sequenceDiagram
  participant C as Client
  participant T as TokenAuth
  C->>T: validate_token(token)
  alt Token expiry > 10 minutes
    T-->>C: Return "Token valid"
  else Token expiry ≤ 10 minutes
    T-->>C: Initiate token refresh
  end
Loading

Possibly related PRs

Poem

Hi there, I'm a bouncy rabbit, herein I cheer,
Tokens checked more often, keeping our code clear.
A hop and a skip, through validation we flow,
Short lives need refreshing, now you know!
🐇 Crunching carrots and code, let the changes glow!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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. (Beta)
  • @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.

@simonc56 simonc56 force-pushed the lower-token-expiration-delay branch from 8d81412 to 8d135af Compare February 7, 2025 17:19
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

🧹 Nitpick comments (2)
trakt/api.py (2)

217-217: LGTM! Consider making the margin configurable.

The 10-minute margin is a reasonable choice given the new 24-hour token expiration policy. However, consider making this value configurable to easily adjust it if needed.

 class TokenAuth(AuthBase):
+    # Time margin before token expiry when refresh should be triggered
+    TOKEN_REFRESH_MARGIN = timedelta(minutes=10)
+
     def validate_token(self):
         """Check if current OAuth token has not expired"""
 
         current = datetime.now(tz=timezone.utc)
         expires_at = datetime.fromtimestamp(self.config.OAUTH_EXPIRES_AT, tz=timezone.utc)
-        if expires_at - current > timedelta(minutes=10):
+        if expires_at - current > self.TOKEN_REFRESH_MARGIN:

212-220: Add comments explaining the token validation logic.

The token validation logic would benefit from additional comments explaining the margin choice and improved logging for better debugging.

     def validate_token(self):
-        """Check if current OAuth token has not expired"""
+        """Check if current OAuth token has not expired
+        
+        The token is considered valid if it expires in more than TOKEN_REFRESH_MARGIN
+        (default: 10 minutes). This margin ensures the token doesn't expire during
+        critical operations while also maximizing the token's useful lifetime.
+        """
 
         current = datetime.now(tz=timezone.utc)
         expires_at = datetime.fromtimestamp(self.config.OAUTH_EXPIRES_AT, tz=timezone.utc)
-        if expires_at - current > timedelta(minutes=10):
+        margin = expires_at - current
+        if margin > self.TOKEN_REFRESH_MARGIN:
+            self.logger.debug("Token valid for %s, exceeds margin of %s", margin, self.TOKEN_REFRESH_MARGIN)
             self.OAUTH_TOKEN_VALID = True
         else:
+            self.logger.debug("Token expires in %s, refreshing (margin: %s)", margin, self.TOKEN_REFRESH_MARGIN)
             self.refresh_token()
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 81b716b and 8d135af.

📒 Files selected for processing (1)
  • trakt/api.py (1 hunks)

@glensc glensc merged commit 6ceda9a into glensc:main Feb 13, 2025
9 checks passed
@glensc
Copy link
Owner

glensc commented Feb 13, 2025

It could be calculated automatically from the age the token will expire to account for future token changes. but too annoying to figure out what the logic would be. or maybe some AI could provide example logic?

@simonc56 simonc56 deleted the lower-token-expiration-delay branch March 31, 2025 09:50
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