8000 Fix Jikan API rate limiting, timeouts, schemas, image proxy, and sub/… by mushtak7 · Pull Request #611 · jikan-me/jikan-rest · GitHub
[go: up one dir, main page]

Skip to content

Fix Jikan API rate limiting, timeouts, schemas, image proxy, and sub/… - #611

Open
mushtak7 wants to merge 2 commits into
jikan-me:masterfrom
mushtak7:fix
Open

mushtak7 wants to merge 2 commits into
jikan-me:masterfrom
mushtak7:fix

Conversation

@mushtak7
Copy link
Copy Markdown
  1. 🛑 Fixed Rate Limit Crashes (HTTP 429)
    Problem: Parallel requests from web pages triggered Jikan's strict 3 req/sec rate limit, causing red error boxes (⚠️ Failed to load catalog data).
    Fix: Added a smart request queue on the client (spaces calls by 350ms) and built a server rate limiter with clear retry timers so requests never get blocked.
  2. 🛡️ Added Upstream Overload Protection (HTTP 504 / 503 / 502)
    Problem: Server timeouts or MyAnimeList overloads crashed pages with uncaught fetch errors.
    Fix: Implemented automatic retries with exponential backoff (retries up to 3 times) and a stale-cache system (serves saved data if the live API is down).
  3. 🖼️ Fixed Broken Poster Images & srcset Errors
    Problem: Missing small_image_url properties resulted in invalid "undefined 300w" HTML strings that broke poster displays.
    Fix: Built an automatic schema normalizer that generates any missing image size variants and a safeSrcset() helper to ensure poster images always render cleanly.
  4. ☁️ Bypassed Cloudflare & MAL Downtime
    Problem: MAL maintenance or Cloudflare captchas caused Jikan endpoints to fail or return empty records.
    Fix: Added a stale-while-revalidate fallback on the server and client that serves expired cache records (up to 7 days old) instead of throwing 404 errors when MAL is unreachable.
  5. 🚫 Fixed CDN Image Hotlink & CORS Blocks
    Problem: cdn.myanimelist.net frequently blocked image referrers from custom web domains, showing broken image icons.
    Fix: Built a server-side Image Proxy (/v4/proxy/image) that strips referrers, caches images for 24 hours, and serves them with full CORS support.
  6. 🎙️ Added Sub / Dub Audio Metadata
    Problem: Jikan v4 provided no sub/dub audio origin tags for filtering.
    Fix: Created a smart licensor detection system (detecting Crunchyroll, Funimation, Viz Media, etc.) that automatically attaches audio_languages: ['ja', 'en'] and has_dub: true tags to titles.

8000
@mushtak7
mushtak7 requested a review from a team as a code owner August 10, 2026 15:05
Copilot AI lite review requested due to automatic review settings August 10, 2026 15:05
Copilot AI left a comment
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR hardens the Jikan REST API against upstream instability and client-side burst traffic by adding server-side rate limiting, stale-cache fallback, response schema normalization (images/audio metadata), and an image proxy endpoint under the v4 API.

Changes:

  • Added global rate limiting middleware and v4 response normalization middleware; introduced stale-cache fallback middleware.
  • Enhanced cached scraping with retry/backoff and circuit-breaker logic to reduce upstream load and serve cached data when possible.
  • Added a v4 image proxy endpoint and response/model schema normalization for image variants and sub/dub metadata.

Reviewed changes

Copilot reviewed 11 out of 11 changed files in this pull request and generated 9 comments.

Show a summary per file
File Description
routes/web.v4.php Adds v4 route for the image proxy endpoint.
bootstrap/app.php Registers new middleware (rate limit, stale cache, response normalizer) and wires it into v4 routes.
app/Services/DefaultCachedScraperService.php Implements retry/backoff, stale-while-revalidate behavior, and circuit breaker for scraping.
app/Providers/SourceHeartbeatProvider.php Adds helper methods for scrape eligibility and heartbeat recording.
app/Http/Middleware/StaleCacheMiddleware.php Introduces HTTP-layer stale response caching for retryable upstream failures.
app/Http/Middleware/SourceHeartbeatMonitor.php Emits heartbeat events based on response status codes.
app/Http/Middleware/ResponseNormalizerMiddleware.php Normalizes response schemas (images, titles, year, episodes/score/synopsis, audio metadata) and optionally rewrites image URLs via proxy.
app/Http/Middleware/RateLimitMiddleware.php Adds per-IP rate limiting with 429 responses and rate limit headers.
app/Http/Controllers/V4DB/ImageProxyController.php Implements server-side image proxying with caching and CORS headers.
app/Anime.php Adds image variant normalization and sub/dub metadata to the Anime model output.
.env.dist Documents new environment variables for rate limiting, stale cache TTL, and image proxy configuration.
Suppressed comments (2)

app/Services/DefaultCachedScraperService.php:115

  • If all retries are exhausted and there is no cached data, the code falls through and later aborts with a 404 via raiseNotFoundIfEmpty(). That misrepresents upstream outages (502/503/504/timeouts) as "not found"; when no stale data exists, return an upstream-unavailable error instead (e.g., 503).
            // Retry with exponential backoff
            $response = $this->retryWithBackoff(function () use ($id) {
                return $this->repository->scrape($id);
            }, $cacheKey);

app/Services/DefaultCachedScraperService.php:157

  • Same issue as find(): when scraping fails and there is no cached record, the method later returns a 404 via raiseNotFoundIfEmpty(), which hides upstream outages. If retryWithBackoff() returns null and no stale data exists, return 503 instead.
            $scraperResponse = $this->retryWithBackoff(function () use ($val) {
                return $this->repository->scrape($val);
            }, $cacheKey);

            if ($scraperResponse !== null) {

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +74 to +79
// Retry with exponential backoff
$data = $this->retryWithBackoff(function () use ($getMalDataCallback, $page) {
return $getMalDataCallback($this->jikan, $page);
}, $cacheKey);

if ($data !== null) {
Comment on lines +44 to +47
// Allow bypass if APP_KEY supplied in auth header (for internal/admin use)
if ($request->header('auth') === env('APP_KEY') && !empty(env('APP_KEY'))) {
return $next($request);
}
Comment on lines +98 to +103
], 429)->withHeaders([
'Retry-After' => $retryAfter,
'X-RateLimit-Limit' => $this->perMinute,
'X-RateLimit-Remaining' => 0,
]);
}
Comment on lines +149 to +150
return 1;
}
Comment on lines +157 to +163
// Trust X-Forwarded-For if behind a known proxy (e.g., Cloudflare, nginx)
$forwardedFor = $request->header('X-Forwarded-For');
if ($forwardedFor) {
// X-Forwarded-For can be comma-separated; the first IP is the real client
$ips = array_map('trim', explode(',', $forwardedFor));
return $ips[0];
}
Comment on lines +289 to +292
private function isMalCdnUrl(string $url): bool
{
return strpos($url, 'cdn.myanimelist.net') !== false;
}
Comment on lines +159 to +177
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 3,
CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 5,
// Strip referrer to bypass CDN hotlink protection
CURLOPT_REFERER => '',
CURLOPT_HTTPHEADER => [
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.9',
],
// Don't send referrer
CURLOPT_AUTOREFERER => false,
// Size limit
CURLOPT_MAXFILESIZE => self::MAX_IMAGE_SIZE,
]);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nope, raw curl is not ok. We use PSR-7 compatible http clients everywhere in the code. (e.g. Guzzle)

Comment on lines +6 to +7
use App\Events\SourceHeartbeatEvent;
use App\Providers\SourceHeartbeatProvider;
Comment on lines +5 to +8
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use App\Http\HttpHelper;
@mushtak7
mushtak7 force-pushed the fix branch 2 times, most recently from 7c10e10 to c1717e2 Compare August 10, 2026 16:11
…aw curl with GuzzleHttp\Client in ImageProxyController
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.

3 participants

0