fix: Pinterest video processing timeout — longer poll + retry (#246)

* fix: give Pinterest video processing more time and retry on timeout

A valid ~54s video pin failed after ~90s of polling while Pinterest was
still processing. Extend the poll window to ~5 minutes and treat timeout
as platform unavailable so PublishToSocialPlatform reschedules instead of
failing the post on the first attempt.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: use Laravel Sleep for Pinterest media processing polls

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: inline Pinterest video processing poll constants

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: map Pinterest media upload statuses to an enum

Use the official MediaUploadStatus values (registered, processing,
succeeded, failed) instead of comparing raw strings in the publisher.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: trim Pinterest media processing docblock

* fix: cap platform-unavailable retries and recover stuck retrying posts

Stop infinite reschedules after 6 attempts with a user-safe failure
message, keep technical detail in error_context, recover Retrying
platforms in social:recover-stuck-posts, and drop unused isTerminal().

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: remove unused failedCount in RecoverStuckPosts

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: skip final Pinterest poll sleep and localize recover timeout

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: raise publish job timeout headroom and ignore already-failed platforms

Give social publish jobs 15 minutes so Pinterest media polling fits under
the worker limit, bump Horizon/redis retry_after above that timeout, and
skip handle/failed when the platform is already Failed so delayed jobs
cannot revive posts recovered by social:recover-stuck-posts.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: restore social-publishing and ai-assistant horizon supervisors

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: harden Pinterest 401 handling, unique publish jobs, and recover JSON

Treat media-status 401 as TokenExpired, make PublishToSocialPlatform
unique per platform+attempt so retries still queue, and persist recover
error_context via Eloquent casts instead of manual json_encode.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: mass-update stuck post platforms without per-row each

Eloquent query updates already bind JSON arrays correctly here, so one
UPDATE is enough — no manual json_encode and no N model writes.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: simplify Pinterest media processing poll loop

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: simplify publish job retry and terminal status checks

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: do not finalize posts while platforms are still retrying

Co-authored-by: Cursor <cursoragent@cursor.com>

* test: cover Pinterest timeout, unique jobs, and recover edge cases

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: retry Pinterest media poll on connection errors and tighten tests

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: remove ineffective TypeError import that breaks CI

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Paulo Castellano 2026-08-06 19:49:37 -04:00 committed by GitHub
parent b4f61be6ef
commit 27287aa130
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
27 changed files with 1030 additions and 48 deletions

View file

@ -23,25 +23,33 @@ public function handle(): void
->where('status', PostStatus::Publishing)
->where('updated_at', '<=', now()->subHour())
->each(function (Post $post) use (&$count) {
// Mark stuck platforms as failed
$post->postPlatforms()
->where('enabled', true)
->whereIn('status', [PlatformStatus::Publishing, PlatformStatus::Pending])
->whereIn('status', [PlatformStatus::Publishing, PlatformStatus::Pending, PlatformStatus::Retrying])
->where('updated_at', '<=', now()->subHour())
->update([
'status' => PlatformStatus::Failed,
'error_message' => 'Publishing timed out. Please try again.',
'error_context' => json_encode([
'error_message' => __('posts.errors.publishing_timed_out'),
'error_context' => [
'category' => 'timeout',
'failed_at' => now()->toIso8601String(),
]),
],
]);
// Recalculate post status
// Delayed platform-unavailable retries keep the platform Retrying with a
// fresh updated_at — do not finalize the post while that work is still live.
$stillActive = $post->postPlatforms()
->where('enabled', true)
->whereIn('status', [PlatformStatus::Publishing, PlatformStatus::Pending, PlatformStatus::Retrying])
->exists();
if ($stillActive) {
return;
}
$enabledPlatforms = $post->postPlatforms()->where('enabled', true)->get();
$total = $enabledPlatforms->count();
$publishedCount = $enabledPlatforms->where('status', PlatformStatus::Published)->count();
$failedCount = $enabledPlatforms->where('status', PlatformStatus::Failed)->count();
if ($publishedCount === $total) {
$post->markAsPublished();

View file

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Enums\Pinterest;
/**
* Pinterest media upload lifecycle statuses from GET /v5/media/{media_id}.
*
* @see https://developers.pinterest.com/docs/api/v5/media-get/
*/
enum MediaUploadStatus: string
{
case Registered = 'registered';
case Processing = 'processing';
case Succeeded = 'succeeded';
case Failed = 'failed';
}

View file

@ -31,29 +31,42 @@
use App\Services\Social\TikTokPublisher;
use App\Services\Social\XPublisher;
use App\Services\Social\YouTubePublisher;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;
class PublishToSocialPlatform implements ShouldQueue
class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
{
use Queueable;
public int $tries = 1;
public int $timeout = 600; // 10 minutes — large video uploads need time
/** Download/upload + Pinterest poll headroom; keep Horizon/Redis timeouts above this. */
public int $timeout = 900;
public function __construct(public PostPlatform $postPlatform)
{
public int $uniqueFor = 960;
/** Max platform-unavailable reschedules (~1 hour at 10 min each). */
public const MAX_PLATFORM_UNAVAILABLE_RETRIES = 6;
public function __construct(
public PostPlatform $postPlatform,
public int $uniqueAttempt = 0,
) {
$this->onQueue($postPlatform->platform->queue());
}
public function uniqueId(): string
{
return "{$this->postPlatform->id}:{$this->uniqueAttempt}";
}
public function handle(): void
{
// Idempotency: skip if already published (prevents duplicate posts on retry)
$this->postPlatform->refresh();
if ($this->postPlatform->status === PostPlatformStatus::Published) {
if ($this->isTerminal()) {
return;
}
@ -193,30 +206,57 @@ private function refreshAccountToken(): void
private function rescheduleForRetry(PlatformUnavailableException $e): void
{
$retryCount = (int) ($this->postPlatform->error_context['retry_count'] ?? 0) + 1;
$retryCount = (int) data_get($this->postPlatform->error_context, 'retry_count', 0) + 1;
$context = [
'category' => 'platform_unavailable',
'http_status' => $e->httpStatus,
'retry_count' => $retryCount,
'detail' => $e->getMessage(),
];
if ($retryCount > self::MAX_PLATFORM_UNAVAILABLE_RETRIES) {
Log::warning('Publish retries exhausted: platform unavailable', [
'post_platform_id' => $this->postPlatform->id,
'platform' => $this->postPlatform->platform->value,
...$context,
]);
$this->postPlatform->markAsFailed(
__('posts.errors.platform_unavailable_exhausted'),
[...$context, 'failed_at' => now()->toIso8601String()],
);
return;
}
$nextAttemptAt = now()->addMinutes(10);
Log::warning('Publish rescheduled: platform unavailable', [
'post_platform_id' => $this->postPlatform->id,
'platform' => $this->postPlatform->platform->value,
'retry_count' => $retryCount,
'next_attempt_at' => $nextAttemptAt->toIso8601String(),
'error' => $e->getMessage(),
...$context,
]);
$this->postPlatform->update([
'status' => PostPlatformStatus::Retrying,
'error_message' => $e->getMessage(),
'error_message' => __('posts.errors.platform_unavailable'),
'error_context' => [
'category' => 'platform_unavailable',
'http_status' => $e->httpStatus,
'retry_count' => $retryCount,
...$context,
'last_attempt_at' => now()->toIso8601String(),
'next_attempt_at' => $nextAttemptAt->toIso8601String(),
],
]);
self::dispatch($this->postPlatform)->delay($nextAttemptAt);
self::dispatch($this->postPlatform, $retryCount)->delay($nextAttemptAt);
}
private function isTerminal(): bool
{
return in_array($this->postPlatform->status, [
PostPlatformStatus::Published,
PostPlatformStatus::Failed,
], true);
}
private function broadcastStatus(): void
@ -319,17 +359,19 @@ public function failed(?\Throwable $exception): void
$this->postPlatform->refresh();
if ($this->postPlatform->status !== PostPlatformStatus::Published) {
$this->postPlatform->markAsFailed(
$exception ? $this->safeFailureMessage($exception) : 'Unknown error',
[
'category' => 'job_failed',
'failed_at' => now()->toIso8601String(),
]
);
$this->updatePostStatus();
$this->broadcastStatus();
if ($this->isTerminal()) {
return;
}
$this->postPlatform->markAsFailed(
$exception ? $this->safeFailureMessage($exception) : 'Unknown error',
[
'category' => 'job_failed',
'failed_at' => now()->toIso8601String(),
]
);
$this->updatePostStatus();
$this->broadcastStatus();
}
private function notifyFailure(Post $post): void

View file

@ -5,17 +5,21 @@
namespace App\Services\Social;
use App\Enums\Media\Type as MediaType;
use App\Enums\Pinterest\MediaUploadStatus;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\PinterestPublishException;
use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Services\Media\MediaOptimizer;
use App\Services\Social\Concerns\HasSocialHttpClient;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Sleep;
class PinterestPublisher
{
@ -320,45 +324,69 @@ private function publishCarousel(PostPlatform $postPlatform, ?string $content):
return $this->createPin($account, $payload, 'Pinterest carousel creation failed');
}
private function waitForMediaProcessing(SocialAccount $account, string $mediaId, int $maxAttempts = 30): void
/** @throws PlatformUnavailableException|PinterestPublishException */
private function waitForMediaProcessing(SocialAccount $account, string $mediaId): void
{
$maxAttempts = 60;
$pollSeconds = 5;
$lastStatus = null;
for ($i = 0; $i < $maxAttempts; $i++) {
$response = $this->socialHttp()->withToken($account->access_token)
->get($this->baseUrl."/media/{$mediaId}");
if ($i > 0) {
Sleep::for($pollSeconds)->seconds();
}
try {
$response = $this->socialHttp()->withToken($account->access_token)
->get($this->baseUrl."/media/{$mediaId}");
} catch (ConnectionException $e) {
throw new PlatformUnavailableException(
"Pinterest media status check connection failed (media_id={$mediaId}): {$e->getMessage()}",
);
}
if ($response->failed()) {
if ($response->status() === 401) {
$this->handleApiError($response);
}
Log::warning('Pinterest media status check failed', [
'media_id' => $mediaId,
'attempt' => $i,
'attempt' => $i + 1,
'status_code' => $response->status(),
'body' => $this->redactResponseBody($response->body()),
]);
sleep(3);
continue;
}
$data = $response->json();
$status = data_get($data, 'status', 'unknown');
$lastStatus = MediaUploadStatus::tryFrom((string) data_get($data, 'status', ''));
if ($status === 'succeeded') {
if ($lastStatus === MediaUploadStatus::Succeeded) {
return;
}
if ($status === 'failed') {
if ($lastStatus === MediaUploadStatus::Failed) {
$failureCode = data_get($data, 'failure_code', 'unknown');
throw new PinterestPublishException(
userMessage: "Pinterest media processing failed: {$failureCode}",
category: ErrorCategory::ServerError,
platformErrorCode: (string) $failureCode,
rawResponse: $response->body(),
);
}
sleep(3);
}
throw new PinterestPublishException(
userMessage: "Pinterest media processing timeout after {$maxAttempts} attempts",
category: ErrorCategory::ServerError,
Log::warning('Pinterest media processing timeout', [
'media_id' => $mediaId,
'attempts' => $maxAttempts,
'last_status' => $lastStatus?->value,
'poll_seconds' => $pollSeconds,
]);
throw new PlatformUnavailableException(
"Pinterest media processing timeout after {$maxAttempts} attempts (media_id={$mediaId}, last_status=".($lastStatus?->value ?? 'unknown').')',
);
}

View file

@ -233,7 +233,7 @@
'autoScalingStrategy' => 'time',
'minProcesses' => 1,
'maxProcesses' => 3,
'timeout' => 630,
'timeout' => 930,
'maxTime' => 0,
'maxJobs' => 0,
'memory' => 256,

View file

@ -70,7 +70,7 @@
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 660),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 960),
'block_for' => null,
'after_commit' => false,
],

View file

@ -575,6 +575,9 @@
'account_disconnected' => 'الحساب الاجتماعي مفصول',
'account_inactive' => 'الحساب الاجتماعي مُعطَّل',
'account_token_expired' => 'انتهت جلسة الحساب الاجتماعي — يرجى إعادة الربط',
'platform_unavailable' => 'المنصة غير متاحة مؤقتًا. سنعيد المحاولة قريبًا.',
'platform_unavailable_exhausted' => 'ظلت المنصة غير متاحة بعد عدة محاولات. يرجى المحاولة لاحقًا.',
'publishing_timed_out' => 'انتهت مهلة النشر. يرجى المحاولة مرة أخرى.',
],
'delete' => [

View file

@ -577,6 +577,9 @@
'account_disconnected' => 'Social-Media-Konto ist getrennt',
'account_inactive' => 'Social-Media-Konto ist deaktiviert',
'account_token_expired' => 'Sitzung des Social-Media-Kontos abgelaufen – bitte erneut verbinden',
'platform_unavailable' => 'Die Plattform ist vorübergehend nicht verfügbar. Wir versuchen es in Kürze erneut.',
'platform_unavailable_exhausted' => 'Die Plattform blieb nach mehreren Versuchen nicht verfügbar. Bitte später erneut versuchen.',
'publishing_timed_out' => 'Die Veröffentlichung ist abgelaufen. Bitte erneut versuchen.',
],
'delete' => [

View file

@ -575,6 +575,9 @@
'account_disconnected' => 'Ο λογαριασμός κοινωνικού δικτύου έχει αποσυνδεθεί',
'account_inactive' => 'Ο λογαριασμός κοινωνικού δικτύου έχει απενεργοποιηθεί',
'account_token_expired' => 'Η συνεδρία του λογαριασμού κοινωνικού δικτύου έληξε — επανασυνδεθείτε',
'platform_unavailable' => 'Η πλατφόρμα είναι προσωρινά μη διαθέσιμη. Θα δοκιμάσουμε ξανά σύντομα.',
'platform_unavailable_exhausted' => 'Η πλατφόρμα παρέμεινε μη διαθέσιμη μετά από αρκετές προσπάθειες. Δοκιμάστε ξανά αργότερα.',
'publishing_timed_out' => 'Η δημοσίευση έληξε. Δοκιμάστε ξανά.',
],
'delete' => [

View file

@ -575,6 +575,9 @@
'account_disconnected' => 'Social account is disconnected',
'account_inactive' => 'Social account is deactivated',
'account_token_expired' => 'Social account session expired — please reconnect',
'platform_unavailable' => 'The platform is temporarily unavailable. We\'ll retry shortly.',
'platform_unavailable_exhausted' => 'The platform stayed unavailable after several retries. Please try again later.',
'publishing_timed_out' => 'Publishing timed out. Please try again.',
],
'delete' => [

View file

@ -575,6 +575,9 @@
'account_disconnected' => 'Cuenta social desconectada',
'account_inactive' => 'Cuenta social desactivada',
'account_token_expired' => 'Sesión de la cuenta social expirada — reconecta la cuenta',
'platform_unavailable' => 'La plataforma no está disponible temporalmente. Reintentaremos en breve.',
'platform_unavailable_exhausted' => 'La plataforma siguió sin estar disponible tras varios reintentos. Inténtalo de nuevo más tarde.',
'publishing_timed_out' => 'La publicación agotó el tiempo de espera. Inténtalo de nuevo.',
],
'delete' => [

View file

@ -575,6 +575,9 @@
'account_disconnected' => 'Le compte social est déconnecté',
'account_inactive' => 'Le compte social est désactivé',
'account_token_expired' => 'La session du compte social a expiré — veuillez reconnecter',
'platform_unavailable' => 'La plateforme est temporairement indisponible. Nouvelle tentative sous peu.',
'platform_unavailable_exhausted' => 'La plateforme est restée indisponible après plusieurs tentatives. Réessayez plus tard.',
'publishing_timed_out' => 'La publication a expiré. Veuillez réessayer.',
],
'delete' => [

View file

@ -575,6 +575,9 @@
'account_disconnected' => 'L\'account social è scollegato',
'account_inactive' => 'L\'account social è disattivato',
'account_token_expired' => 'Sessione dell\'account social scaduta — ricollegalo',
'platform_unavailable' => 'La piattaforma è temporaneamente non disponibile. Riproveremo a breve.',
'platform_unavailable_exhausted' => 'La piattaforma è rimasta non disponibile dopo diversi tentativi. Riprova più tardi.',
'publishing_timed_out' => 'Pubblicazione scaduta. Riprova.',
],
'delete' => [

View file

@ -575,6 +575,9 @@
'account_disconnected' => 'ソーシャルアカウントの接続が解除されています',
'account_inactive' => 'ソーシャルアカウントが無効化されています',
'account_token_expired' => 'ソーシャルアカウントのセッションの有効期限が切れました — 再接続してください',
'platform_unavailable' => 'プラットフォームが一時的に利用できません。まもなく再試行します。',
'platform_unavailable_exhausted' => '何度か再試行しましたがプラットフォームが利用できませんでした。後でもう一度お試しください。',
'publishing_timed_out' => '公開がタイムアウトしました。もう一度お試しください。',
],
'delete' => [

View file

@ -575,6 +575,9 @@
'account_disconnected' => '소셜 계정 연결이 해제되었습니다',
'account_inactive' => '소셜 계정이 비활성화되었습니다',
'account_token_expired' => '소셜 계정 세션이 만료되었습니다 — 재연결하세요',
'platform_unavailable' => '플랫폼을 일시적으로 사용할 수 없습니다. 곧 다시 시도합니다.',
'platform_unavailable_exhausted' => '여러 번 재시도했지만 플랫폼을 사용할 수 없었습니다. 나중에 다시 시도하세요.',
'publishing_timed_out' => '게시에 시간이 초과되었습니다. 다시 시도하세요.',
],
'delete' => [

View file

@ -575,6 +575,9 @@
'account_disconnected' => 'Social account is losgekoppeld',
'account_inactive' => 'Social account is gedeactiveerd',
'account_token_expired' => 'Sessie van social account verlopen — koppel opnieuw',
'platform_unavailable' => 'Het platform is tijdelijk niet beschikbaar. We proberen het zo opnieuw.',
'platform_unavailable_exhausted' => 'Het platform bleef na meerdere pogingen niet beschikbaar. Probeer het later opnieuw.',
'publishing_timed_out' => 'Publiceren is timed-out. Probeer het opnieuw.',
],
'delete' => [

View file

@ -575,6 +575,9 @@
'account_disconnected' => 'Konto społecznościowe jest rozłączone',
'account_inactive' => 'Konto społecznościowe jest dezaktywowane',
'account_token_expired' => 'Sesja konta społecznościowego wygasła — połącz ponownie',
'platform_unavailable' => 'Platforma jest tymczasowo niedostępna. Spróbujemy ponownie wkrótce.',
'platform_unavailable_exhausted' => 'Platforma pozostała niedostępna po kilku próbach. Spróbuj ponownie później.',
'publishing_timed_out' => 'Publikowanie przekroczyło limit czasu. Spróbuj ponownie.',
],
'delete' => [

View file

@ -575,6 +575,9 @@
'account_disconnected' => 'Conta social está desconectada',
'account_inactive' => 'Conta social está desativada',
'account_token_expired' => 'Sessão da conta social expirou — reconecte a conta',
'platform_unavailable' => 'A plataforma está temporariamente indisponível. Vamos tentar de novo em breve.',
'platform_unavailable_exhausted' => 'A plataforma continuou indisponível após várias tentativas. Tente de novo mais tarde.',
'publishing_timed_out' => 'A publicação excedeu o tempo limite. Tente novamente.',
],
'delete' => [

View file

@ -575,6 +575,9 @@
'account_disconnected' => 'Социальный аккаунт отключён',
'account_inactive' => 'Социальный аккаунт деактивирован',
'account_token_expired' => 'Сессия социального аккаунта истекла — переподключите',
'platform_unavailable' => 'Платформа временно недоступна. Мы повторим попытку вскоре.',
'platform_unavailable_exhausted' => 'Платформа оставалась недоступной после нескольких попыток. Попробуйте позже.',
'publishing_timed_out' => 'Публикация превысила время ожидания. Попробуйте снова.',
],
'delete' => [

View file

@ -577,6 +577,9 @@
'account_disconnected' => 'Sosyal hesabın bağlantısı kesildi',
'account_inactive' => 'Sosyal hesap devre dışı bırakıldı',
'account_token_expired' => 'Sosyal hesap oturumunun süresi doldu — lütfen yeniden bağlanın',
'platform_unavailable' => 'Platform geçici olarak kullanılamıyor. Kısa süre içinde yeniden deneyeceğiz.',
'platform_unavailable_exhausted' => 'Platform birkaç denemeden sonra kullanılamaz kaldı. Lütfen daha sonra tekrar deneyin.',
'publishing_timed_out' => 'Yayınlama zaman aşımına uğradı. Lütfen tekrar deneyin.',
],
'delete' => [

View file

@ -575,6 +575,9 @@
'account_disconnected' => 'Соціальний акаунт відключено',
'account_inactive' => 'Соціальний акаунт деактивовано',
'account_token_expired' => 'Сесія соціального акаунта закінчилася — перепідключіть',
'platform_unavailable' => 'Платформа тимчасово недоступна. Ми спробуємо знову незабаром.',
'platform_unavailable_exhausted' => 'Платформа залишалася недоступною після кількох спроб. Спробуйте пізніше.',
'publishing_timed_out' => 'Публікація перевищила час очікування. Спробуйте ще раз.',
],
'delete' => [

View file

@ -575,6 +575,9 @@
'account_disconnected' => '社交账号已断开连接',
'account_inactive' => '社交账号已停用',
'account_token_expired' => '社交账号会话已过期——请重新连接',
'platform_unavailable' => '平台暂时不可用。我们稍后会重试。',
'platform_unavailable_exhausted' => '多次重试后平台仍不可用。请稍后再试。',
'publishing_timed_out' => '发布超时。请重试。',
],
'delete' => [

View file

@ -5,11 +5,15 @@
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\Status as PlatformStatus;
use App\Enums\SocialAccount\Platform;
use App\Jobs\PublishToSocialPlatform;
use App\Models\Post;
use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Social\LinkedInPublisher;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Mail;
beforeEach(function () {
$this->user = User::factory()->create();
@ -42,7 +46,10 @@
$post->refresh();
expect($platform->status)->toBe(PlatformStatus::Failed);
expect($platform->error_message)->toBe('Publishing timed out. Please try again.');
expect($platform->error_message)->toBe(__('posts.errors.publishing_timed_out'));
expect($platform->error_context)->toMatchArray([
'category' => 'timeout',
]);
expect($post->status)->toBe(PostStatus::Failed);
});
@ -104,3 +111,170 @@
expect($stuckPlatform->status)->toBe(PlatformStatus::Failed);
expect($post->status)->toBe(PostStatus::PartiallyPublished);
});
test('it recovers platforms stuck in retrying for over 1 hour', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
'updated_at' => now()->subHours(2),
]);
$platform = PostPlatform::factory()->create([
'post_id' => $post->id,
'social_account_id' => $this->socialAccount->id,
'status' => PlatformStatus::Retrying,
'enabled' => true,
'error_message' => __('posts.errors.platform_unavailable'),
'updated_at' => now()->subHours(2),
]);
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
$platform->refresh();
$post->refresh();
expect($platform->status)->toBe(PlatformStatus::Failed)
->and($platform->error_message)->toBe(__('posts.errors.publishing_timed_out'))
->and($post->status)->toBe(PostStatus::Failed);
});
test('it does not finalize a post while a platform is still actively retrying', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
'updated_at' => now()->subHours(2),
]);
$platform = PostPlatform::factory()->create([
'post_id' => $post->id,
'social_account_id' => $this->socialAccount->id,
'status' => PlatformStatus::Retrying,
'enabled' => true,
'error_message' => __('posts.errors.platform_unavailable'),
'updated_at' => now()->subMinutes(5),
]);
$this->artisan('social:recover-stuck-posts')
->expectsOutput('Recovered 0 stuck posts.')
->assertSuccessful();
$platform->refresh();
$post->refresh();
expect($platform->status)->toBe(PlatformStatus::Retrying)
->and($post->status)->toBe(PostStatus::Publishing);
});
test('it does not finalize a post while a platform is still actively pending or publishing', function (PlatformStatus $status) {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
'updated_at' => now()->subHours(2),
]);
$platform = PostPlatform::factory()->create([
'post_id' => $post->id,
'social_account_id' => $this->socialAccount->id,
'status' => $status,
'enabled' => true,
'updated_at' => now()->subMinutes(5),
]);
$this->artisan('social:recover-stuck-posts')
->expectsOutput('Recovered 0 stuck posts.')
->assertSuccessful();
$platform->refresh();
$post->refresh();
expect($platform->status)->toBe($status)
->and($post->status)->toBe(PostStatus::Publishing);
})->with([
PlatformStatus::Pending,
PlatformStatus::Publishing,
]);
test('it fails stale platforms but keeps the post publishing when another platform is still retrying', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
'updated_at' => now()->subHours(2),
]);
$stalePlatform = PostPlatform::factory()->create([
'post_id' => $post->id,
'social_account_id' => $this->socialAccount->id,
'status' => PlatformStatus::Publishing,
'enabled' => true,
'updated_at' => now()->subHours(2),
]);
$activeRetry = PostPlatform::factory()->create([
'post_id' => $post->id,
'social_account_id' => SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'platform' => Platform::Pinterest,
])->id,
'status' => PlatformStatus::Retrying,
'enabled' => true,
'error_message' => __('posts.errors.platform_unavailable'),
'updated_at' => now()->subMinutes(5),
]);
$this->artisan('social:recover-stuck-posts')
->expectsOutput('Recovered 0 stuck posts.')
->assertSuccessful();
$stalePlatform->refresh();
$activeRetry->refresh();
$post->refresh();
expect($stalePlatform->status)->toBe(PlatformStatus::Failed)
->and($stalePlatform->error_message)->toBe(__('posts.errors.publishing_timed_out'))
->and($activeRetry->status)->toBe(PlatformStatus::Retrying)
->and($post->status)->toBe(PostStatus::Publishing);
});
test('delayed publish job no-ops after recover fails a stuck retrying platform', function () {
Event::fake();
Mail::fake();
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
'updated_at' => now()->subHours(2),
]);
$platform = PostPlatform::factory()->create([
'post_id' => $post->id,
'social_account_id' => $this->socialAccount->id,
'status' => PlatformStatus::Retrying,
'enabled' => true,
'error_message' => __('posts.errors.platform_unavailable'),
'updated_at' => now()->subHours(2),
]);
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
$platform->refresh();
expect($platform->status)->toBe(PlatformStatus::Failed)
->and($platform->error_message)->toBe(__('posts.errors.publishing_timed_out'));
$publisher = Mockery::mock(LinkedInPublisher::class);
$publisher->shouldNotReceive('publish');
$this->app->instance(LinkedInPublisher::class, $publisher);
(new PublishToSocialPlatform($platform))->handle();
$platform->refresh();
$post->refresh();
expect($platform->status)->toBe(PlatformStatus::Failed)
->and($platform->error_message)->toBe(__('posts.errors.publishing_timed_out'))
->and($post->status)->toBe(PostStatus::Failed);
});

View file

@ -2,6 +2,7 @@
declare(strict_types=1);
use App\Enums\Notification\Type;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
use App\Enums\PostPlatform\Status as PlatformStatus;
@ -23,12 +24,15 @@
use App\Services\Social\ConnectionVerifier;
use App\Services\Social\LinkedInPagePublisher;
use App\Services\Social\LinkedInPublisher;
use App\Services\Social\PinterestPublisher;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Sleep;
beforeEach(function () {
Mail::fake();
@ -273,10 +277,57 @@
expect($this->postPlatform->error_context['category'] ?? null)->toBe('platform_unavailable');
expect($this->postPlatform->error_context['http_status'] ?? null)->toBe(503);
expect($this->postPlatform->error_context['retry_count'] ?? null)->toBe(1);
expect($this->postPlatform->error_message)->toBe(__('posts.errors.platform_unavailable'));
expect($this->postPlatform->error_context['detail'] ?? null)->toContain('LinkedIn API returned 503');
expect($this->socialAccount->status)->toBe(AccountStatus::Connected);
Bus::assertDispatched(PublishToSocialPlatform::class, function ($job) {
return $job->postPlatform->id === $this->postPlatform->id;
return $job->postPlatform->id === $this->postPlatform->id
&& $job->uniqueAttempt === 1
&& $job->uniqueId() === "{$this->postPlatform->id}:1";
});
});
test('publish reschedules when pinterest video processing times out', function () {
Bus::fake([PublishToSocialPlatform::class]);
Event::fake();
Mail::fake();
$pinterestAccount = SocialAccount::factory()->pinterest()->create([
'workspace_id' => $this->workspace->id,
'meta' => ['default_board_id' => 'board_123'],
]);
$postPlatform = PostPlatform::factory()->pinterest()->create([
'post_id' => $this->post->id,
'social_account_id' => $pinterestAccount->id,
'platform' => Platform::Pinterest,
'content_type' => ContentType::PinterestVideoPin,
'enabled' => true,
'status' => PlatformStatus::Pending,
'meta' => ['board_id' => 'board_123'],
]);
$publisher = Mockery::mock(PinterestPublisher::class);
$publisher->shouldReceive('publish')->andThrow(
new PlatformUnavailableException(
'Pinterest media processing timeout after 60 attempts (media_id=media_abc, last_status=processing)'
)
);
$this->app->instance(PinterestPublisher::class, $publisher);
(new PublishToSocialPlatform($postPlatform))->handle();
$postPlatform->refresh();
expect($postPlatform->status)->toBe(PlatformStatus::Retrying)
->and($postPlatform->error_context['category'] ?? null)->toBe('platform_unavailable')
->and($postPlatform->error_message)->toBe(__('posts.errors.platform_unavailable'))
->and($postPlatform->error_context['detail'] ?? null)->toContain('Pinterest media processing timeout');
Bus::assertDispatched(PublishToSocialPlatform::class, function ($job) use ($postPlatform) {
return $job->postPlatform->id === $postPlatform->id
&& $job->uniqueAttempt === 1;
});
});
@ -450,9 +501,216 @@
$this->postPlatform->refresh();
expect($this->postPlatform->status)->toBe(PlatformStatus::Retrying);
expect($this->postPlatform->error_context['retry_count'] ?? null)->toBe(6);
});
test('publish hard-fails when platform unavailable retries are exhausted', function () {
Bus::fake([PublishToSocialPlatform::class]);
Event::fake();
Mail::fake();
$publisher = Mockery::mock(LinkedInPublisher::class);
$publisher->shouldReceive('publish')->andThrow(
new PlatformUnavailableException('LinkedIn 503', 503)
);
$this->app->instance(LinkedInPublisher::class, $publisher);
$this->postPlatform->update([
'error_context' => ['retry_count' => PublishToSocialPlatform::MAX_PLATFORM_UNAVAILABLE_RETRIES],
]);
(new PublishToSocialPlatform($this->postPlatform))->handle();
$this->postPlatform->refresh();
expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)
->and($this->postPlatform->error_message)->toBe(__('posts.errors.platform_unavailable_exhausted'))
->and($this->postPlatform->error_context['category'] ?? null)->toBe('platform_unavailable')
->and($this->postPlatform->error_context['retry_count'] ?? null)->toBe(PublishToSocialPlatform::MAX_PLATFORM_UNAVAILABLE_RETRIES + 1)
->and($this->postPlatform->error_context['detail'] ?? null)->toContain('LinkedIn 503');
Bus::assertNotDispatched(PublishToSocialPlatform::class);
});
test('publish skips platforms that are already failed', function () {
Event::fake();
Mail::fake();
$this->postPlatform->update([
'status' => PlatformStatus::Failed,
'error_message' => __('posts.errors.publishing_timed_out'),
]);
$publisher = Mockery::mock(LinkedInPublisher::class);
$publisher->shouldNotReceive('publish');
$this->app->instance(LinkedInPublisher::class, $publisher);
(new PublishToSocialPlatform($this->postPlatform))->handle();
$this->postPlatform->refresh();
expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)
->and($this->postPlatform->error_message)->toBe(__('posts.errors.publishing_timed_out'));
});
test('publish job timeout leaves headroom above the pinterest media poll budget', function () {
$job = new PublishToSocialPlatform($this->postPlatform);
$horizonTimeout = (int) config('horizon.defaults.social-publishing.timeout');
$retryAfter = (int) config('queue.connections.redis.retry_after');
expect($job->timeout)->toBe(900)
->and($horizonTimeout)->toBe(930)
->and($retryAfter)->toBe(960)
->and($job->uniqueFor)->toBe(960)
->and($job->timeout)->toBeLessThan($horizonTimeout)
->and($horizonTimeout)->toBeLessThan($retryAfter)
->and($job->uniqueFor)->toBeGreaterThanOrEqual($job->timeout);
});
test('publish job unique id includes the platform and attempt', function () {
$job = new PublishToSocialPlatform($this->postPlatform, 3);
expect($job)->toBeInstanceOf(ShouldBeUnique::class)
->and($job->uniqueId())->toBe("{$this->postPlatform->id}:3")
->and($job->uniqueFor)->toBe(960);
});
test('publish job unique lock drops a duplicate dispatch for the same platform attempt', function () {
Bus::fake([PublishToSocialPlatform::class]);
PublishToSocialPlatform::dispatch($this->postPlatform, 0);
PublishToSocialPlatform::dispatch($this->postPlatform, 0);
Bus::assertDispatchedTimes(PublishToSocialPlatform::class, 1);
});
test('publish job unique lock allows concurrent dispatches for different attempts', function () {
Bus::fake([PublishToSocialPlatform::class]);
PublishToSocialPlatform::dispatch($this->postPlatform, 0);
PublishToSocialPlatform::dispatch($this->postPlatform, 1);
Bus::assertDispatchedTimes(PublishToSocialPlatform::class, 2);
Bus::assertDispatched(PublishToSocialPlatform::class, fn ($job) => $job->uniqueAttempt === 0);
Bus::assertDispatched(PublishToSocialPlatform::class, fn ($job) => $job->uniqueAttempt === 1);
});
test('failed hook skips platforms that are already failed', function () {
Event::fake();
Mail::fake();
$this->postPlatform->update([
'status' => PlatformStatus::Failed,
'error_message' => __('posts.errors.publishing_timed_out'),
'error_context' => ['category' => 'timeout'],
]);
(new PublishToSocialPlatform($this->postPlatform))->failed(new TypeError('Simulated worker kill'));
$this->postPlatform->refresh();
expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)
->and($this->postPlatform->error_message)->toBe(__('posts.errors.publishing_timed_out'))
->and($this->postPlatform->error_context['category'] ?? null)->toBe('timeout');
});
test('failed hook skips platforms that are already published', function () {
Event::fake();
Mail::fake();
$this->postPlatform->update([
'status' => PlatformStatus::Published,
'platform_post_id' => 'already-published',
'error_message' => null,
]);
(new PublishToSocialPlatform($this->postPlatform))->failed(new TypeError('Simulated worker kill'));
$this->postPlatform->refresh();
expect($this->postPlatform->status)->toBe(PlatformStatus::Published)
->and($this->postPlatform->platform_post_id)->toBe('already-published')
->and($this->postPlatform->error_message)->toBeNull();
});
test('pinterest media status 401 marks the account token expired and notifies to reconnect', function () {
Event::fake();
Queue::fake();
Mail::fake();
Sleep::fake();
$pinterestAccount = SocialAccount::factory()->pinterest()->create([
'workspace_id' => $this->workspace->id,
'status' => AccountStatus::Connected,
'token_expires_at' => now()->addDays(30),
'meta' => ['default_board_id' => 'board_123'],
]);
$postPlatform = PostPlatform::factory()->pinterest()->create([
'post_id' => $this->post->id,
'social_account_id' => $pinterestAccount->id,
'platform' => Platform::Pinterest,
'content_type' => ContentType::PinterestVideoPin,
'enabled' => true,
'status' => PlatformStatus::Pending,
'meta' => ['board_id' => 'board_123'],
]);
$this->post->update([
'media' => [[
'id' => 'test-media-video',
'path' => 'media/2026-01/video.mp4',
'url' => 'https://example.com/media/2026-01/video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'video.mp4',
]],
]);
$s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';
Http::fake(function ($request) use ($s3UploadUrl) {
$url = $request->url();
if (str_contains($url, '/v5/media') && $request->method() === 'POST') {
return Http::response([
'media_id' => 'media_video_401_job',
'upload_url' => $s3UploadUrl,
'upload_parameters' => [],
], 201);
}
if ($url === $s3UploadUrl) {
return Http::response('', 204);
}
if (str_contains($url, '/v5/media/media_video_401_job')) {
return Http::response(['message' => 'Access token has expired or been revoked'], 401);
}
return Http::response('fake-video-content', 200);
});
$verifier = Mockery::mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')->once()->andThrow(new Exception('Refresh failed'));
$this->app->instance(ConnectionVerifier::class, $verifier);
(new PublishToSocialPlatform($postPlatform))->handle();
$postPlatform->refresh();
$pinterestAccount->refresh();
expect($postPlatform->status)->toBe(PlatformStatus::Failed)
->and($postPlatform->error_context['category'] ?? null)->toBe('token_expired')
->and($pinterestAccount->status)->toBe(AccountStatus::TokenExpired);
Queue::assertPushed(SendNotification::class, function ($job) use ($pinterestAccount) {
return $job->type === Type::AccountDisconnected
&& data_get($job->data, 'social_account_id') === $pinterestAccount->id
&& str_contains($job->title, 'needs to be reconnected');
});
});
test('publish to social platform updates post status when all platforms finished', function () {
Event::fake();

View file

@ -4,6 +4,8 @@
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\PinterestPublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
use App\Models\PostPlatform;
@ -12,7 +14,9 @@
use App\Models\Workspace;
use App\Services\Media\MediaOptimizer;
use App\Services\Social\PinterestPublisher;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Sleep;
beforeEach(function () {
$this->user = User::factory()->create();
@ -951,3 +955,354 @@
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(Exception::class, 'Unsupported content type');
});
test('pinterest publisher waits through pending video processing before creating the pin', function () {
Sleep::fake();
$this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);
$this->post->update([
'media' => [[
'id' => 'test-media-video',
'path' => 'media/2026-01/video.mp4',
'url' => 'https://example.com/media/2026-01/video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'video.mp4',
]],
]);
$s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';
$statusChecks = 0;
Http::fake(function ($request) use ($s3UploadUrl, &$statusChecks) {
$url = $request->url();
if (str_contains($url, '/v5/media') && $request->method() === 'POST') {
return Http::response([
'media_id' => 'media_video_pending',
'upload_url' => $s3UploadUrl,
'upload_parameters' => [],
], 201);
}
if ($url === $s3UploadUrl) {
return Http::response('', 204);
}
if (str_contains($url, '/v5/media/media_video_pending')) {
$statusChecks++;
return Http::response([
'status' => $statusChecks < 3 ? 'processing' : 'succeeded',
], 200);
}
if (str_contains($url, '/v5/pins')) {
return Http::response(['id' => 'video_pin_after_wait'], 200);
}
return Http::response('fake-video-content', 200);
});
$result = $this->publisher->publish($this->postPlatform);
expect($result['id'])->toBe('video_pin_after_wait')
->and($statusChecks)->toBe(3);
Sleep::assertSleptTimes(2);
});
test('pinterest publisher treats video processing timeout as platform unavailable for retry', function () {
Sleep::fake();
$this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);
$this->post->update([
'media' => [[
'id' => 'test-media-video',
'path' => 'media/2026-01/video.mp4',
'url' => 'https://example.com/media/2026-01/video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'video.mp4',
]],
]);
$s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';
Http::fake(function ($request) use ($s3UploadUrl) {
$url = $request->url();
if (str_contains($url, '/v5/media') && $request->method() === 'POST') {
return Http::response([
'media_id' => 'media_video_timeout',
'upload_url' => $s3UploadUrl,
'upload_parameters' => [],
], 201);
}
if ($url === $s3UploadUrl) {
return Http::response('', 204);
}
if (str_contains($url, '/v5/media/media_video_timeout')) {
return Http::response(['status' => 'processing'], 200);
}
return Http::response('fake-video-content', 200);
});
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(PlatformUnavailableException::class, 'Pinterest media processing timeout after 60 attempts');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v5/pins'));
Sleep::assertSleptTimes(59);
});
test('pinterest publisher fails hard when video processing reports failed', function () {
Sleep::fake();
$this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);
$this->post->update([
'media' => [[
'id' => 'test-media-video',
'path' => 'media/2026-01/video.mp4',
'url' => 'https://example.com/media/2026-01/video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'video.mp4',
]],
]);
$s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';
Http::fake(function ($request) use ($s3UploadUrl) {
$url = $request->url();
if (str_contains($url, '/v5/media') && $request->method() === 'POST') {
return Http::response([
'media_id' => 'media_video_failed',
'upload_url' => $s3UploadUrl,
'upload_parameters' => [],
], 201);
}
if ($url === $s3UploadUrl) {
return Http::response('', 204);
}
if (str_contains($url, '/v5/media/media_video_failed')) {
return Http::response([
'status' => 'failed',
'failure_code' => 'VIDEO_TOO_LONG',
], 200);
}
return Http::response('fake-video-content', 200);
});
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(PinterestPublishException::class, 'Pinterest media processing failed: VIDEO_TOO_LONG');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v5/pins'));
Sleep::assertNeverSlept();
});
test('pinterest publisher treats media status 401 as token expired', function () {
Sleep::fake();
$this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);
$this->post->update([
'media' => [[
'id' => 'test-media-video',
'path' => 'media/2026-01/video.mp4',
'url' => 'https://example.com/media/2026-01/video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'video.mp4',
]],
]);
$s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';
Http::fake(function ($request) use ($s3UploadUrl) {
$url = $request->url();
if (str_contains($url, '/v5/media') && $request->method() === 'POST') {
return Http::response([
'media_id' => 'media_video_401',
'upload_url' => $s3UploadUrl,
'upload_parameters' => [],
], 201);
}
if ($url === $s3UploadUrl) {
return Http::response('', 204);
}
if (str_contains($url, '/v5/media/media_video_401')) {
return Http::response(['message' => 'Access token has expired or been revoked'], 401);
}
return Http::response('fake-video-content', 200);
});
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(TokenExpiredException::class, 'Access token has expired or been revoked');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v5/pins'));
Sleep::assertNeverSlept();
});
test('pinterest publisher keeps polling through transient media status http errors', function () {
Sleep::fake();
$this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);
$this->post->update([
'media' => [[
'id' => 'test-media-video',
'path' => 'media/2026-01/video.mp4',
'url' => 'https://example.com/media/2026-01/video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'video.mp4',
]],
]);
$s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';
$statusChecks = 0;
Http::fake(function ($request) use ($s3UploadUrl, &$statusChecks) {
$url = $request->url();
if (str_contains($url, '/v5/media') && $request->method() === 'POST') {
return Http::response([
'media_id' => 'media_video_5xx',
'upload_url' => $s3UploadUrl,
'upload_parameters' => [],
], 201);
}
if ($url === $s3UploadUrl) {
return Http::response('', 204);
}
if (str_contains($url, '/v5/media/media_video_5xx')) {
$statusChecks++;
if ($statusChecks < 3) {
return Http::response(['message' => 'temporary error'], 503);
}
return Http::response(['status' => 'succeeded'], 200);
}
if (str_contains($url, '/v5/pins')) {
return Http::response(['id' => 'video_pin_after_5xx'], 200);
}
return Http::response('fake-video-content', 200);
});
$result = $this->publisher->publish($this->postPlatform);
expect($result['id'])->toBe('video_pin_after_5xx')
->and($statusChecks)->toBe(3);
Sleep::assertSleptTimes(2);
});
test('pinterest publisher treats unknown media status as still processing until timeout', function (string $status) {
Sleep::fake();
$this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);
$this->post->update([
'media' => [[
'id' => 'test-media-video',
'path' => 'media/2026-01/video.mp4',
'url' => 'https://example.com/media/2026-01/video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'video.mp4',
]],
]);
$s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';
Http::fake(function ($request) use ($s3UploadUrl, $status) {
$url = $request->url();
if (str_contains($url, '/v5/media') && $request->method() === 'POST') {
return Http::response([
'media_id' => 'media_video_unknown',
'upload_url' => $s3UploadUrl,
'upload_parameters' => [],
], 201);
}
if ($url === $s3UploadUrl) {
return Http::response('', 204);
}
if (str_contains($url, '/v5/media/media_video_unknown')) {
return Http::response(['status' => $status], 200);
}
return Http::response('fake-video-content', 200);
});
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(PlatformUnavailableException::class, 'Pinterest media processing timeout after 60 attempts');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v5/pins'));
Sleep::assertSleptTimes(59);
})->with([
'registered',
'not_a_real_status',
'',
]);
test('pinterest publisher treats media status connection errors as platform unavailable', function () {
Sleep::fake();
$this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);
$this->post->update([
'media' => [[
'id' => 'test-media-video',
'path' => 'media/2026-01/video.mp4',
'url' => 'https://example.com/media/2026-01/video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'video.mp4',
]],
]);
$s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';
Http::fake(function ($request) use ($s3UploadUrl) {
$url = $request->url();
if (str_contains($url, '/v5/media') && $request->method() === 'POST') {
return Http::response([
'media_id' => 'media_video_conn',
'upload_url' => $s3UploadUrl,
'upload_parameters' => [],
], 201);
}
if ($url === $s3UploadUrl) {
return Http::response('', 204);
}
if (str_contains($url, '/v5/media/media_video_conn')) {
throw new ConnectionException('cURL error 28: Connection timed out');
}
return Http::response('fake-video-content', 200);
});
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(PlatformUnavailableException::class, 'Pinterest media status check connection failed');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v5/pins'));
Sleep::assertNeverSlept();
});

View file

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
use App\Enums\Pinterest\MediaUploadStatus;
test('media upload status mirrors the pinterest api enum values', function () {
expect(MediaUploadStatus::cases())->toHaveCount(4)
->and(MediaUploadStatus::Registered->value)->toBe('registered')
->and(MediaUploadStatus::Processing->value)->toBe('processing')
->and(MediaUploadStatus::Succeeded->value)->toBe('succeeded')
->and(MediaUploadStatus::Failed->value)->toBe('failed');
});
test('media upload status tryFrom accepts known values and rejects unknown', function (string $value, ?MediaUploadStatus $expected) {
expect(MediaUploadStatus::tryFrom($value))->toBe($expected);
})->with([
['registered', MediaUploadStatus::Registered],
['processing', MediaUploadStatus::Processing],
['succeeded', MediaUploadStatus::Succeeded],
['failed', MediaUploadStatus::Failed],
['unknown', null],
['', null],
]);

View file

@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
test('platform unavailable and publish timeout error keys exist in every locale', function () {
$locales = collect(glob(lang_path('*')) ?: [])
->filter(fn (string $path) => is_dir($path) && is_file("{$path}/posts.php"))
->map(fn (string $path) => basename($path))
->values()
->all();
expect($locales)->not->toBeEmpty();
foreach ($locales as $locale) {
$translations = require lang_path("{$locale}/posts.php");
expect(data_get($translations, 'errors.platform_unavailable'))
->toBeString()
->not->toBeEmpty("Missing errors.platform_unavailable in {$locale}")
->and(data_get($translations, 'errors.platform_unavailable_exhausted'))
->toBeString()
->not->toBeEmpty("Missing errors.platform_unavailable_exhausted in {$locale}")
->and(data_get($translations, 'errors.publishing_timed_out'))
->toBeString()
->not->toBeEmpty("Missing errors.publishing_timed_out in {$locale}");
}
});