Repository navigation
Conversation
There was a problem hiding this comment.
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.
| // Retry with exponential backoff | ||
| $data = $this->retryWithBackoff(function () use ($getMalDataCallback, $page) { | ||
| return $getMalDataCallback($this->jikan, $page); | ||
| }, $cacheKey); | ||
|
|
||
| if ($data !== null) { |
| // 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); | ||
| } |
| ], 429)->withHeaders([ | ||
| 'Retry-After' => $retryAfter, | ||
| 'X-RateLimit-Limit' => $this->perMinute, | ||
| 'X-RateLimit-Remaining' => 0, | ||
| ]); | ||
| } |
| return 1; | ||
| } |
| // 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]; | ||
| } |
| private function isMalCdnUrl(string $url): bool | ||
| { | ||
| return strpos($url, 'cdn.myanimelist.net') !== false; | ||
| } |
| 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, | ||
| ]); |
There was a problem hiding this comment.
Nope, raw curl is not ok. We use PSR-7 compatible http clients everywhere in the code. (e.g. Guzzle)
| use App\Events\SourceHeartbeatEvent; | ||
| use App\Providers\SourceHeartbeatProvider; |
| use Closure; | ||
| use Illuminate\Http\Request; | ||
| use Illuminate\Support\Facades\Cache; | ||
| use App\Http\HttpHelper; |
…dub metadata (addressed PR code review)
7c10e10 to
c1717e2
Compare
…aw curl with GuzzleHttp\Client in ImageProxyController
Problem: Parallel requests from web pages triggered Jikan's strict 3 req/sec rate limit, causing red error boxes (
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.
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).
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.
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.
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.
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.