Class: PinterestTokenRefreshWorker

Inherits:
Object
  • Object
show all
Includes:
Sidekiq::Job
Defined in:
app/workers/pinterest_token_refresh_worker.rb

Overview

Proactively refreshes the system-level Pinterest OAuth token before it expires.

Pinterest access tokens last 30 days. This worker runs daily and refreshes
the token once it is within REFRESH_WINDOW of expiry — well ahead of the
deadline, so PinterestCampaignSyncWorker never sees a stale token.

Each refresh also reissues the 60-day "continuous" refresh token, so the
credential renews itself indefinitely with no manual intervention (the gap
that caused AppSignal #5228 / #5225 under the old manual dev-portal token).

Constant Summary collapse

REFRESH_WINDOW =

Refresh once the 30-day access token has 10 days or less remaining.

10.days

Instance Method Summary collapse

Instance Method Details

#performObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'app/workers/pinterest_token_refresh_worker.rb', line 22

def perform
  # Advisory lock guards against concurrent refreshes (scheduler overlap,
  # Sidekiq retry, manual enqueue). Pinterest reissues the refresh token on
  # every refresh, so two overlapping runs would invalidate each other.
  # timeout_seconds: 0 — if another run holds the lock, skip; it has it covered.
  OauthCredential.with_advisory_lock('pinterest_token_refresh', timeout_seconds: 0) do
    credentials = OauthCredential
                  .where(provider: Pinterest::OauthService::PROVIDER)
                  .expiring_within(REFRESH_WINDOW)

    if credentials.none?
      Rails.logger.info('[PinterestTokenRefreshWorker] No Pinterest token expiring soon — nothing to refresh')
      next
    end

    Rails.logger.info("[PinterestTokenRefreshWorker] Refreshing #{credentials.count} Pinterest token(s)")
    credentials.find_each { |cred| refresh_credential(cred) }
  end
end