Skip to content

Commit

Permalink
Apply stale-while-revalidate also for responses without a validator
Browse files Browse the repository at this point in the history
  • Loading branch information
mpdude committed Sep 8, 2020
1 parent c49a693 commit 9913c15
Showing 1 changed file with 24 additions and 13 deletions.
37 changes: 24 additions & 13 deletions src/CacheMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,25 +153,36 @@ function (ResponseInterface $response) use ($request) {
return new FulfilledPromise(
$cacheEntry->getResponse()->withHeader(self::HEADER_CACHE_INFO, self::HEADER_CACHE_HIT)
);
} elseif ($staleResponse
|| ($maxStaleCache !== null && $cacheEntry->getStaleAge() <= $maxStaleCache)
) {
// Staled cache!
} elseif ($staleResponse || ($maxStaleCache !== null && $cacheEntry->getStaleAge() <= $maxStaleCache)) {
/*
* Client is willing to accept a response that has exceeded its freshness lifetime,
* possibly by not more than $maxStaleCache (https://tools.ietf.org/html/rfc7234#section-5.2.1.2).
*
* Return the cached, stale response.
*/
return new FulfilledPromise(
$cacheEntry->getResponse()->withHeader(self::HEADER_CACHE_INFO, self::HEADER_CACHE_HIT)
);
} elseif ($cacheEntry->staleWhileValidate() && ($maxStaleCache === null || $cacheEntry->getStaleAge() <= $maxStaleCache)) {
/*
* The cached response indicated that it may be served stale while background revalidation (or fetch)
* occurs, and the client did not limit maximum staleness. (https://tools.ietf.org/html/rfc5861#section-3)
*
* Return the cached, stale response; initiate deferred revalidation/re-fetch.
*/
static::addReValidationRequest(
static::getRequestWithReValidationHeader($request, $cacheEntry),
$this->cacheStorage,
$cacheEntry
);

return new FulfilledPromise(
$cacheEntry->getResponse()
->withHeader(self::HEADER_CACHE_INFO, self::HEADER_CACHE_STALE)
);
} elseif ($cacheEntry->hasValidationInformation() && !$onlyFromCache) {
// Re-validation header
$request = static::getRequestWithReValidationHeader($request, $cacheEntry);

if ($cacheEntry->staleWhileValidate()) {
static::addReValidationRequest($request, $this->cacheStorage, $cacheEntry);

return new FulfilledPromise(
$cacheEntry->getResponse()
->withHeader(self::HEADER_CACHE_INFO, self::HEADER_CACHE_STALE)
);
}
}
} else {
$cacheEntry = null;
Expand Down

0 comments on commit 9913c15

Please sign in to comment.