-
-
Notifications
You must be signed in to change notification settings - Fork 263
/
Copy pathJikanResponseHandler.php
executable file
·215 lines (174 loc) · 7.08 KB
/
JikanResponseHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
<?php
/**
* This middleware is the successor of JikanResponseLegacy; used for REST v3.3+
*
* It works by storing cache with no automated TTL handling by Redis
*
* If a request is past it's TTL, it queues an update instead of removing the cache followed by fetching a new one
* Update queues are automated.
*
* Therefore,
* - if MyAnimeList is down or rate-limits the response, stale cache is served
* - if cache expires, the client doesn't have to wait longer for the server to fetch+parse the new response
*/
namespace App\Http\Middleware;
use App\Http\HttpHelper;
use App\Jobs\UpdateCacheJob;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class JikanResponseHandler
{
private $requestUri;
private $requestUriHash;
private $requestType;
private $requestCacheExpiry = 0;
private $requestCached = false;
private $requestCacheTtl;
private $fingerprint;
private $cacheExpiryFingerprint;
private $route;
private $queueable = true;
private const NON_QUEUEABLE = [
'UserController@profile',
'UserController@history',
'UserController@friends',
'UserController@animelist',
'UserController@mangalist',
];
private const HIGH_PRIORITY_QUEUE = [
'ScheduleController@main'
];
public function handle(Request $request, Closure $next)
{
if ($request->header('auth') === env('APP_KEY')) {
return $next($request);
}
if (empty($request->segments())) {
return $next($request);
}
if (!isset($request->segments()[1])) {
return $next($request);
}
if (\in_array('meta', $request->segments())) {
return $next($request);
}
$this->requestUriHash = HttpHelper::getRequestUriHash($request);
$this->requestType = HttpHelper::requestType($request);
$this->requestCacheTtl = HttpHelper::requestCacheExpiry($this->requestType);
$this->fingerprint = "request:{$this->requestType}:{$this->requestUriHash}";
$this->cacheExpiryFingerprint = "ttl:{$this->fingerprint}";
$this->requestCached = Cache::has($this->fingerprint);
$this->route = explode('\\', $request->route()[1]['uses']);
$this->route = end($this->route);
// Check if request is in the 404 cache pool @todo: separate as middleware
if (Cache::has("request:404:{$this->requestUriHash}")) {
return response()
->json([
'status' => 404,
'type' => 'BadResponseException',
'message' => 'Resource does not exist',
'error' => Cache::get("request:404:{$this->requestUriHash}")
], 404);
}
// Queueable?
if (\in_array($this->route, self::NON_QUEUEABLE) || env('CACHE_METHOD', 'legacy') === 'legacy') {
$this->queueable = false;
}
// Cache if it doesn't exist
if (!$this->requestCached) {
$response = $next($request);
if (HttpHelper::hasError($response)) {
return $response;
}
Cache::forever($this->fingerprint, $response->original);
Cache::forever($this->cacheExpiryFingerprint, time() + $this->requestCacheTtl);
}
// If cache is expired, handle it depending on whether it's queueable
$this->requestCacheExpiry = (int) Cache::get($this->cacheExpiryFingerprint);
if ($this->requestCached && $this->requestCacheExpiry <= time() && !$this->queueable) {
$response = $next($request);
if (HttpHelper::hasError($response)) {
return $response;
}
Cache::forever($this->fingerprint, $response->original);
Cache::forever($this->cacheExpiryFingerprint, time() + $this->requestCacheTtl);
$this->requestCacheExpiry = (int) Cache::get($this->cacheExpiryFingerprint);
}
if ($this->queueable && $this->requestCacheExpiry <= time()) {
$queueFingerprint = "queue_update:{$this->fingerprint}";
$queueHighPriority = \in_array($this->route, self::HIGH_PRIORITY_QUEUE);
// Don't duplicate the queue for same request
if (!app('redis')->exists($queueFingerprint)) {
app('redis')->set($queueFingerprint, 1);
dispatch(
(new UpdateCacheJob($request))
->delay(env('QUEUE_DELAY_PER_JOB', 5))
->onQueue($queueHighPriority ? 'high' : 'low')
);
}
}
// // ETag @todo: separate as middleware
// if (
// $request->hasHeader('If-None-Match')
// && $this->cache->exists($this->fingerprint)
// && md5($this->cache->get($this->fingerprint)) === $request->header('If-None-Match')
// ) {
// return response('', 304);
// }
// Return response
$meta = $this->generateMeta($request);
$cache = Cache::get($this->fingerprint);
$cacheMutable = json_decode($cache, true);
$cacheMutable = $this->cacheMutation($cacheMutable);
return response()
->json(
array_merge($meta, $cacheMutable)
)
->setEtag(
md5($cache)
)
->withHeaders([
'X-Request-Hash' => $this->fingerprint,
'X-Request-Cached' => $this->requestCached,
'X-Request-Cache-Ttl' => (int) $this->requestCacheExpiry - time()
])
->setExpires((new \DateTime())->setTimestamp($this->requestCacheExpiry));
}
private function generateMeta(Request $request) : array
{
$version = HttpHelper::requestAPIVersion($request);
$meta = [
'request_hash' => $this->fingerprint,
'request_cached' => $this->requestCached,
'request_cache_expiry' => (int) $this->requestCacheExpiry - time()
];
switch ($version) {
case 2:
$meta = array_merge([
'DEPRECIATION_NOTICE' => 'THIS VERSION WILL BE DEPRECIATED ON JULY 01st, 2019.',
], $meta);
break;
case 4:
// remove cache data from JSON response and send as headers
unset($meta['request_cached'], $meta['request_cache_expiry']);
$meta = array_merge([
'DEVELOPMENT_NOTICE' => 'THIS VERSION IS IN TESTING. DO NOT USE FOR PRODUCTION.',
'MIGRATION' => 'https://github.com/jikan-me/jikan-rest/blob/master/MIGRATION.MD',
], $meta);
break;
}
return $meta;
}
private function cacheMutation(array $data) : array
{
if (!($this->requestType === 'anime' || $this->requestType === 'manga')) {
return $data;
}
// Fix JSON response for empty related object
if (isset($data['related']) && \count($data['related']) === 0) {
$data['related'] = new \stdClass();
}
return $data;
}
}