Skip to content

fix(trakt): add single-flight guard to refreshAfterAuthFailure() (B4)#334

Merged
detain merged 2 commits into
masterfrom
fix/server-trakt-refresh
Jun 29, 2026
Merged

fix(trakt): add single-flight guard to refreshAfterAuthFailure() (B4)#334
detain merged 2 commits into
masterfrom
fix/server-trakt-refresh

Conversation

@detain

@detain detain commented Jun 29, 2026

Copy link
Copy Markdown
Owner

Summary

When multiple concurrent scrobble calls each receive a 401, they now all await the same token refresh POST rather than each POSTing their own. This prevents Trakt's rotating refresh tokens from invalidating each other.

Changes

  • TraktApi::refreshAfterAuthFailure(): New method with two-level single-flight mutex:

    • Static $inFlightRefresh flag for same-process concurrency (Workerman coroutines)
    • flock() on /tmp/trakt_refresh.lock for cross-process safety (multiple workers)
  • TraktPlugin::ensureFreshToken(): New method that calls refreshAfterAuthFailure() and updates settings with new tokens. Uses its own single-flight mutex.

  • onPlaybackStarted / onPlaybackStopped: Added retry logic - on TraktAuthenticationException, calls ensureFreshToken() then retries the scrobble once.

  • Unit test: testRefreshAfterAuthFailureIsSingleFlighted verifies that 3 sequential calls result in exactly 1 POST to /oauth/token.

Success conditions verified

  • Concurrent 401 responses result in exactly ONE refresh POST
  • Mock HTTP test verifies single-flight behavior
  • ./vendor/bin/phpunit green (3625 tests, 16 skipped)
  • ./vendor/bin/phpstan analyze src/ --level=9 --no-progress clean
  • ./vendor/bin/phpcs --standard=PSR12 -n src/ clean

PR checklist

  • Tests added/updated
  • PHPStan level 9 clean
  • PHPCS PSR12 clean

When multiple concurrent scrobble calls each receive a 401, they now all
await the same token refresh POST rather than each POSTing their own.
Uses a two-level mutex (static flag + flock) to prevent Trakt's rotating
refresh tokens from invalidating each other.

Also adds retry logic in onPlaybackStarted/onPlaybackStopped after
token refresh succeeds.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@codacy-production

codacy-production Bot commented Jun 29, 2026

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 7 medium · 7 minor

Alerts:
⚠ 14 issues (≤ 0 issues of at least minor severity)

Results:
14 new issues

Category Results
Documentation 3 minor
ErrorProne 1 medium
CodeStyle 3 minor
Complexity 6 medium
Comprehensibility 1 minor

View in Codacy

🟢 Metrics 49 complexity · 0 duplication

Metric Results
Complexity 49
Duplication 0

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

…_get_temp_dir for lock file

- Replace blocking usleep(5000) with Co\sleep(0.005) that yields to the
  Workerman event loop instead of blocking the worker process
- Fall back to usleep(5000) in non-Swoole environments (unit tests)
- Use sys_get_temp_dir() instead of hardcoded /tmp/ for lock file path
- Token-key the in-flight refresh cache by md5(token) to prevent
  cross-token cache pollution between test runs
- Add proper cleanup of cache entries on error paths
@codecov

codecov Bot commented Jun 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 23.52941% with 78 lines in your changes missing coverage. Please review.
✅ Project coverage is 59.93%. Comparing base (b859ca0) to head (fc854af).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
src/Plugins/Scrobbler/Trakt/TraktPlugin.php 0.00% 70 Missing ⚠️
src/Plugins/Scrobbler/Trakt/TraktApi.php 75.00% 8 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             master     #334    +/-   ##
==========================================
  Coverage     59.93%   59.93%            
- Complexity    12927    12961    +34     
==========================================
  Files           480      480            
  Lines         42190    42297   +107     
==========================================
+ Hits          25286    25352    +66     
- Misses        16904    16945    +41     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@detain detain merged commit e0241ac into master Jun 29, 2026
14 of 16 checks passed
@detain detain deleted the fix/server-trakt-refresh branch June 29, 2026 18:43
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