Skip to content

Commit 9913c15

Browse files
committed
Apply stale-while-revalidate also for responses without a validator
1 parent c49a693 commit 9913c15

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed

src/CacheMiddleware.php

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -153,25 +153,36 @@ function (ResponseInterface $response) use ($request) {
153153
return new FulfilledPromise(
154154
$cacheEntry->getResponse()->withHeader(self::HEADER_CACHE_INFO, self::HEADER_CACHE_HIT)
155155
);
156-
} elseif ($staleResponse
157-
|| ($maxStaleCache !== null && $cacheEntry->getStaleAge() <= $maxStaleCache)
158-
) {
159-
// Staled cache!
156+
} elseif ($staleResponse || ($maxStaleCache !== null && $cacheEntry->getStaleAge() <= $maxStaleCache)) {
157+
/*
158+
* Client is willing to accept a response that has exceeded its freshness lifetime,
159+
* possibly by not more than $maxStaleCache (https://tools.ietf.org/html/rfc7234#section-5.2.1.2).
160+
*
161+
* Return the cached, stale response.
162+
*/
160163
return new FulfilledPromise(
161164
$cacheEntry->getResponse()->withHeader(self::HEADER_CACHE_INFO, self::HEADER_CACHE_HIT)
162165
);
166+
} elseif ($cacheEntry->staleWhileValidate() && ($maxStaleCache === null || $cacheEntry->getStaleAge() <= $maxStaleCache)) {
167+
/*
168+
* The cached response indicated that it may be served stale while background revalidation (or fetch)
169+
* occurs, and the client did not limit maximum staleness. (https://tools.ietf.org/html/rfc5861#section-3)
170+
*
171+
* Return the cached, stale response; initiate deferred revalidation/re-fetch.
172+
*/
173+
static::addReValidationRequest(
174+
static::getRequestWithReValidationHeader($request, $cacheEntry),
175+
$this->cacheStorage,
176+
$cacheEntry
177+
);
178+
179+
return new FulfilledPromise(
180+
$cacheEntry->getResponse()
181+
->withHeader(self::HEADER_CACHE_INFO, self::HEADER_CACHE_STALE)
182+
);
163183
} elseif ($cacheEntry->hasValidationInformation() && !$onlyFromCache) {
164184
// Re-validation header
165185
$request = static::getRequestWithReValidationHeader($request, $cacheEntry);
166-
167-
if ($cacheEntry->staleWhileValidate()) {
168-
static::addReValidationRequest($request, $this->cacheStorage, $cacheEntry);
169-
170-
return new FulfilledPromise(
171-
$cacheEntry->getResponse()
172-
->withHeader(self::HEADER_CACHE_INFO, self::HEADER_CACHE_STALE)
173-
);
174-
}
175186
}
176187
} else {
177188
$cacheEntry = null;

0 commit comments

Comments
 (0)