Skip to content

Conversation

@modem
Copy link
Contributor

@modem modem commented Sep 2, 2025

If token expires while the app is running, the refresh is currently not occurring. This is due to OAUTH_TOKEN_VALID, that takes the following values:

  • none: at app start
  • true: at the 1st check if token is valid
  • true: after refreshing the token

Because of this, it fails to validate the stored token as it always relies on a static value, unless the app restarts.

This addresses plextracksync issue Taxel/PlexTraktSync#1546

@coderabbitai
Copy link

coderabbitai bot commented Sep 2, 2025

Walkthrough

Adds an internal concurrency guard (TOKEN_UNDER_REFRESH) in TokenAuth within trakt/api.py. get_token now sets and checks this flag to prevent multiple simultaneous refreshes; validate_token clears the flag after refresh checks. No public API signatures changed.

Changes

Cohort / File(s) Summary of Changes
Token refresh concurrency guard
trakt/api.py
Introduced TOKEN_UNDER_REFRESH flag on TokenAuth (initialized False). get_token() now checks and sets TOKEN_UNDER_REFRESH to guard refresh flow when config.have_refresh_token() is true. validate_token() resets TOKEN_UNDER_REFRESH to False after expiry/refresh logic. No public API signature changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client A
  actor Client B
  participant TokenAuth
  participant Config
  participant TraktOAuth as Trakt OAuth

  Client A->>TokenAuth: get_token()
  TokenAuth->>Config: have_refresh_token()?
  alt refresh token present
    TokenAuth->>TokenAuth: TOKEN_UNDER_REFRESH == False?
    alt not under refresh
      TokenAuth->>TokenAuth: set TOKEN_UNDER_REFRESH = True
      TokenAuth->>TokenAuth: validate_token()
      alt token expired/near-expiry
        TokenAuth->>TraktOAuth: refresh_token()
        TraktOAuth-->>TokenAuth: new tokens
      end
      TokenAuth->>TokenAuth: set TOKEN_UNDER_REFRESH = False
      TokenAuth->>Client A: return token
    else already under refresh
      Note right of TokenAuth: Concurrency guard prevents another refresh
      TokenAuth->>Client A: return existing token / wait outcome
    end
  else no refresh token
    TokenAuth->>Client A: return existing token
  end

  Client B->>TokenAuth: get_token() (concurrent)
  TokenAuth->>TokenAuth: sees TOKEN_UNDER_REFRESH True -> avoids duplicate refresh
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Poem

I’m a rabbit guarding keys tonight,
One refresh at a time, I keep it tight.
When tokens wobble, I won’t duplicate the race,
I set a flag, then tidy up the place.
Hop, guard, and hop — safe in my little space 🐇🔐


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f60ba73 and 719f0e3.

📒 Files selected for processing (1)
  • trakt/api.py (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • trakt/api.py
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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

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

215-231: Avoid concurrent double-refresh with a lock + double-check.

Multiple parallel requests can now hit validate_token(), race into refresh_token(), and cause duplicate refreshes or invalid_grant if the refresh token rotates. Guard the refresh path with a lock and re-check expiry inside the lock.

+import threading
@@
 class TokenAuth(AuthBase):
@@
   def __init__(self, client: HttpClient, config: AuthConfig):
     super().__init__()
     self.config = config
     self.client = client
     # OAuth token validity checked
     self.OAUTH_TOKEN_VALID = None
     self.refresh_attempts = 0
+    self._refresh_lock = threading.Lock()
@@
   def validate_token(self):
@@
-        if margin > timedelta(**self.TOKEN_REFRESH_MARGIN):
+        if margin > timedelta(**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()
+            self.logger.debug("Token expires in %s, refreshing (margin: %s)", margin, self.TOKEN_REFRESH_MARGIN)
+            # Serialize refresh to avoid duplicate refreshes under load
+            with self._refresh_lock:
+                # Double-check after acquiring the lock in case another thread already refreshed
+                current = datetime.now(tz=timezone.utc)
+                expires_at = datetime.fromtimestamp(self.config.OAUTH_EXPIRES_AT, tz=timezone.utc)
+                if (expires_at - current) <= timedelta(**self.TOKEN_REFRESH_MARGIN):
+                    self.refresh_token()

240-247: Tighten the log message (not always “expired”).

We refresh when within the margin too. Adjust wording to reduce confusion during debugging.

-        self.logger.info("OAuth token has expired, refreshing now...")
+        self.logger.info("OAuth token expired or expiring soon; refreshing now...")

169-170: Consider modest retries with backoff for transient failures.

MAX_RETRIES = 1 makes any blip a hard stop until restart. Suggest 2–3 attempts with small backoff/jitter. Happy to draft a looped implementation if desired.


180-183: Remove vestigial OAUTH_TOKEN_VALID attribute
The self.OAUTH_TOKEN_VALID flag is only assigned in trakt/api.py (lines 181, 227, 274) and never read. Remove its declaration and related assignments to eliminate dead code.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e879853 and f60ba73.

📒 Files selected for processing (1)
  • trakt/api.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
trakt/api.py (2)
trakt/core.py (1)
  • config (73-83)
trakt/config.py (1)
  • have_refresh_token (23-24)
🔇 Additional comments (1)
trakt/api.py (1)

205-209: Good fix: always validate when a refresh token exists.

This removes the stale OAUTH_TOKEN_VALID gate and ensures tokens are refreshed during runtime expiry windows. Change aligns with the linked issue and is backward-safe given have_refresh_token() also asserts OAUTH_EXPIRES_AT presence.

In case there's 2 simultaneous token refresh attempts
@glensc glensc merged commit 4e78678 into glensc:main Sep 8, 2025
8 checks passed
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