Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply stale-while-revalidate also for responses without a validator #128

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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