Stop Meta rate-limit errors from disconnecting Instagram/Threads tokens

TokenRefreshClient classified every non-5xx/429 refresh failure as a dead
token. Meta returns rate-limit (code 4/17) and transient (code 1/2) errors as
HTTP 4xx with type OAuthException, so a throttled proactive refresh was
disconnecting still-valid Instagram/Threads tokens — and the wider 24h/15-min
refresh cadence raised the odds of hitting it.

Classification now keys on error code 190 (the signal the publish exceptions
already use): only a genuine 190 disconnects; every other Meta 4xx is treated as
transient (PlatformUnavailable) and retried next cycle. The same over-broad
type-based check in verifyInstagram/verifyFacebook/verifyThreads is replaced
with the shared Meta\GraphError helper so verify and refresh agree.
This commit is contained in:
Paulo Castellano 2026-07-03 11:07:54 -03:00
parent 4d5ca6b274
commit 83ba72ddc6
6 changed files with 192 additions and 35 deletions

View file

@ -9,6 +9,7 @@
use App\Exceptions\TokenExpiredException;
use App\Models\SocialAccount;
use App\Services\Social\Discord\DiscordClient;
use App\Services\Social\Meta\GraphError;
use App\Services\Social\Telegram\TelegramApi;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
@ -311,10 +312,13 @@ private function refreshPinterestToken(SocialAccount $account): void
private function refreshThreadsToken(SocialAccount $account): void
{
// Threads uses long-lived tokens that can be refreshed
$response = TokenRefreshClient::for(Platform::Threads)->send(fn () => Http::get(config('trypost.platforms.threads.auth_api').'/refresh_access_token', [
'grant_type' => 'th_refresh_token',
'access_token' => $account->access_token,
]));
$response = TokenRefreshClient::for(Platform::Threads)->send(
fn () => Http::get(config('trypost.platforms.threads.auth_api').'/refresh_access_token', [
'grant_type' => 'th_refresh_token',
'access_token' => $account->access_token,
]),
GraphError::indicatesInvalidToken(...),
);
$data = $response->json();
$newToken = data_get($data, 'access_token');
@ -322,7 +326,7 @@ private function refreshThreadsToken(SocialAccount $account): void
$account->update([
'access_token' => $newToken,
'refresh_token' => $newToken,
'token_expires_at' => now()->addSeconds(data_get($data, 'expires_in', 5184000)),
'token_expires_at' => now()->addSeconds(data_get($data, 'expires_in', Platform::LONG_LIVED_TOKEN_TTL_SECONDS)),
]);
$account->refresh();
@ -330,10 +334,13 @@ private function refreshThreadsToken(SocialAccount $account): void
private function refreshInstagramToken(SocialAccount $account): void
{
$response = TokenRefreshClient::for(Platform::Instagram)->send(fn () => Http::get(config('trypost.platforms.instagram.auth_api').'/refresh_access_token', [
'grant_type' => 'ig_refresh_token',
'access_token' => $account->access_token,
]));
$response = TokenRefreshClient::for(Platform::Instagram)->send(
fn () => Http::get(config('trypost.platforms.instagram.auth_api').'/refresh_access_token', [
'grant_type' => 'ig_refresh_token',
'access_token' => $account->access_token,
]),
GraphError::indicatesInvalidToken(...),
);
$data = $response->json();
$newToken = data_get($data, 'access_token');
@ -341,7 +348,7 @@ private function refreshInstagramToken(SocialAccount $account): void
$account->update([
'access_token' => $newToken,
'refresh_token' => $newToken,
'token_expires_at' => now()->addSeconds(data_get($data, 'expires_in', 5184000)),
'token_expires_at' => now()->addSeconds(data_get($data, 'expires_in', Platform::LONG_LIVED_TOKEN_TTL_SECONDS)),
]);
$account->refresh();
@ -408,13 +415,8 @@ private function verifyInstagram(SocialAccount $account): bool
$body = $response->json() ?? [];
if (isset($body['error'])) {
$errorCode = $body['error']['code'] ?? null;
$errorType = $body['error']['type'] ?? null;
if ($errorType === 'OAuthException' || $errorCode === 190) {
throw new TokenExpiredException('Instagram access token is invalid or expired');
}
if (GraphError::indicatesInvalidToken($body)) {
throw new TokenExpiredException('Instagram access token is invalid or expired');
}
return $response->successful();
@ -429,13 +431,8 @@ private function verifyFacebook(SocialAccount $account): bool
$body = $response->json() ?? [];
if (isset($body['error'])) {
$errorCode = $body['error']['code'] ?? null;
$errorType = $body['error']['type'] ?? null;
if ($errorType === 'OAuthException' || $errorCode === 190) {
throw new TokenExpiredException('Facebook access token is invalid or expired');
}
if (GraphError::indicatesInvalidToken($body)) {
throw new TokenExpiredException('Facebook access token is invalid or expired');
}
return $response->successful();
@ -450,13 +447,8 @@ private function verifyThreads(SocialAccount $account): bool
$body = $response->json() ?? [];
if (isset($body['error'])) {
$errorCode = $body['error']['code'] ?? null;
$errorType = $body['error']['type'] ?? null;
if ($errorType === 'OAuthException' || $errorCode === 190) {
throw new TokenExpiredException('Threads access token is invalid or expired');
}
if (GraphError::indicatesInvalidToken($body)) {
throw new TokenExpiredException('Threads access token is invalid or expired');
}
return $response->successful();

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Services\Social\Meta;
/**
* Interprets Meta Graph API (Facebook / Instagram / Threads) error responses.
*
* Meta returns rate-limit and transient failures as an ordinary HTTP 4xx with
* type "OAuthException" (e.g. code 4 / 17 "too many calls", code 1 / 2
* "temporary problem"), so neither the HTTP status nor the error type can tell
* a dead token from a throttle. Only error code 190 means the access token
* itself is invalid or expired — the same signal the platform publish
* exceptions already use to decide a disconnect.
*/
class GraphError
{
/**
* Whether the given Meta Graph error body means the access token is
* genuinely invalid or expired (code 190), as opposed to a rate-limit or
* transient error that must not disconnect a still-valid token.
*
* @param array<string, mixed>|null $body
*/
public static function indicatesInvalidToken(?array $body): bool
{
return data_get($body, 'error.code') === 190;
}
}

View file

@ -16,13 +16,18 @@
* Normalizes the failure modes of an OAuth token-refresh request:
*
* - ConnectionException (timeout / DNS / refused) → PlatformUnavailableException
* - HTTP 5xx → PlatformUnavailableException
* - HTTP 4xx → TokenExpiredException
* - HTTP 5xx or 429 → PlatformUnavailableException
* - other HTTP 4xx → TokenExpiredException
*
* Providers that return rate-limit or transient errors as an ordinary 4xx
* (Meta: Instagram/Threads) can pass an `$isTokenInvalid` classifier to
* `send()`; only a genuinely dead token then disconnects, while every other
* 4xx is treated as transient (PlatformUnavailableException).
*
* Callers configure the actual HTTP call through the closure passed to
* `send()`, so platform-specific quirks (form vs JSON body, auth headers,
* basic auth, etc.) stay where they belong — in the per-platform refresh
* method — while the failure semantics are uniform across providers.
* method.
*/
class TokenRefreshClient
{
@ -35,11 +40,14 @@ public static function for(Platform $platform): self
/**
* @param Closure():Response $request
* @param (Closure(array<string, mixed>|null):bool)|null $isTokenInvalid Given the parsed
* response body, returns whether a non-5xx/429 failure means the token itself is dead.
* When it returns false, the failure is treated as transient (PlatformUnavailableException).
*
* @throws PlatformUnavailableException
* @throws TokenExpiredException
*/
public function send(Closure $request): Response
public function send(Closure $request, ?Closure $isTokenInvalid = null): Response
{
$name = $this->platform->label();
@ -62,6 +70,14 @@ public function send(Closure $request): Response
]);
$body = $response->json();
if ($isTokenInvalid !== null && ! $isTokenInvalid($body)) {
throw new PlatformUnavailableException(
"{$name} API returned {$response->status()} during token refresh",
$response->status(),
);
}
$message = data_get($body, 'error_description')
?? data_get($body, 'error.message')
?? "Failed to refresh {$name} token";

View file

@ -107,6 +107,28 @@
expect($account->fresh()->access_token)->toBe('extended-threads-token');
});
test('proactive refresh does NOT disconnect Instagram on a Meta rate-limit (400 OAuthException code 4)', function () {
$account = SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'platform' => Platform::Instagram,
'status' => Status::Connected,
'access_token' => 'valid-ig-token',
'token_expires_at' => now()->addMinutes(20),
]);
Http::fake([
config('trypost.platforms.instagram.auth_api').'/refresh_access_token*' => Http::response([
'error' => ['message' => 'Application request limit reached', 'type' => 'OAuthException', 'code' => 4],
], 400),
]);
(new RefreshSocialToken($account))->handle(app(ConnectionVerifier::class));
// A rate-limit is transient — the still-valid token must stay Connected.
expect($account->fresh()->status)->toBe(Status::Connected);
expect($account->fresh()->access_token)->toBe('valid-ig-token');
});
test('refresh job marks account as TokenExpired when refresh_token is rejected', function () {
Queue::fake();

View file

@ -561,3 +561,65 @@
expect((new ConnectionVerifier)->verify($account))->toBeFalse();
});
test('instagram refresh treats a Meta rate-limit (400 OAuthException code 4) as transient, not a dead token', function () {
Http::fake([
config('trypost.platforms.instagram.auth_api').'/refresh_access_token*' => Http::response([
'error' => ['message' => 'Application request limit reached', 'type' => 'OAuthException', 'code' => 4],
], 400),
]);
$account = SocialAccount::factory()->instagram()->create([
'token_expires_at' => now()->subHour(),
]);
expect(fn () => (new ConnectionVerifier)->refreshToken($account))
->toThrow(PlatformUnavailableException::class);
});
test('threads refresh treats a Meta rate-limit (400 OAuthException code 17) as transient, not a dead token', function () {
Http::fake([
config('trypost.platforms.threads.auth_api').'/refresh_access_token*' => Http::response([
'error' => ['message' => 'User request limit reached', 'type' => 'OAuthException', 'code' => 17],
], 400),
]);
$account = SocialAccount::factory()->threads()->create([
'token_expires_at' => now()->subHour(),
]);
expect(fn () => (new ConnectionVerifier)->refreshToken($account))
->toThrow(PlatformUnavailableException::class);
});
test('instagram refresh treats code 190 as a genuinely expired token', function () {
Http::fake([
config('trypost.platforms.instagram.auth_api').'/refresh_access_token*' => Http::response([
'error' => ['message' => 'Access token has expired', 'type' => 'OAuthException', 'code' => 190],
], 400),
]);
$account = SocialAccount::factory()->instagram()->create([
'token_expires_at' => now()->subHour(),
]);
expect(fn () => (new ConnectionVerifier)->refreshToken($account))
->toThrow(TokenExpiredException::class);
});
test('instagram verify treats a Meta rate-limit (OAuthException code 4) as still-valid, not a disconnect', function () {
Http::fake([
config('trypost.platforms.instagram.graph_api').'/me*' => Http::response([
'error' => ['message' => 'Application request limit reached', 'type' => 'OAuthException', 'code' => 4],
], 400),
]);
// Not expired, so verify hits the endpoint directly (no refresh).
$account = SocialAccount::factory()->instagram()->create([
'token_expires_at' => now()->addDays(30),
]);
// A rate-limit must NOT raise TokenExpiredException (which would disconnect);
// verify returns false and the caller leaves the account connected.
expect((new ConnectionVerifier)->verify($account))->toBeFalse();
});

View file

@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
use App\Services\Social\Meta\GraphError;
test('code 190 indicates a genuinely invalid token', function () {
expect(GraphError::indicatesInvalidToken([
'error' => ['message' => 'Access token has expired', 'type' => 'OAuthException', 'code' => 190],
]))->toBeTrue();
});
test('rate-limit codes carried as OAuthException do NOT indicate an invalid token', function () {
// Meta returns rate limits as HTTP 4xx with type OAuthException — they must
// stay transient so a throttle never disconnects a still-valid token.
expect(GraphError::indicatesInvalidToken([
'error' => ['message' => 'Application request limit reached', 'type' => 'OAuthException', 'code' => 4],
]))->toBeFalse();
expect(GraphError::indicatesInvalidToken([
'error' => ['message' => 'User request limit reached', 'type' => 'OAuthException', 'code' => 17],
]))->toBeFalse();
});
test('transient codes do NOT indicate an invalid token', function () {
expect(GraphError::indicatesInvalidToken([
'error' => ['message' => 'Service temporarily unavailable', 'code' => 2],
]))->toBeFalse();
});
test('a body with no error, or a null body, does not indicate an invalid token', function () {
expect(GraphError::indicatesInvalidToken(null))->toBeFalse();
expect(GraphError::indicatesInvalidToken([]))->toBeFalse();
expect(GraphError::indicatesInvalidToken(['data' => ['id' => '123']]))->toBeFalse();
});