From 9f8b1ebaf80710e5ab817fcc0622ed5f14dcf3a8 Mon Sep 17 00:00:00 2001 From: Ryan McCue Date: Tue, 18 Feb 2025 16:08:57 +0000 Subject: [PATCH] Add SWR threshold capability This will work automatically with Batcache, as it only instructs CloudFront to change its behaviour, rather than everything. --- README.md | 1 + inc/namespace.php | 25 +++++++++++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1677e49..e3535bb 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ Smartcache has a variety of filters available. These include: * `smartcache.is_old_post` - Filter whether a specific post is considered old (infrequently updated). (Default true for posts older than the old threshold.) * `smartcache.is_new_post` - Filter whether a specific post is considered new (frequently updated). (Default true if published in previous 24 hours.) * `smartcache.max-age` - Filter the maximum lifetime for the current page directly. +* `smartcache.swr_threshold` - Filter the stale-while-revalidate timeframe. (Default 30s for frequently updated content, 60s for infrequently updated content.) * `smartcache.should_cache` - Filter whether a page should be cached at all. (Only affects whether Smartcache generates a header, but may be overridden by other behaviour or by the cache itself.) * `smartcache.urls_to_invalidate_for_post` - Filter which URLs to invalidate for a given post. * `smartcache.should_invalidate` - Should we invalidate URLs for this post? (Default true, false for new content as it will expire naturally quickly.) diff --git a/inc/namespace.php b/inc/namespace.php index 7aed448..5b9b5ce 100644 --- a/inc/namespace.php +++ b/inc/namespace.php @@ -28,6 +28,16 @@ */ const LIFETIME_LONG = 1209600; +/** + * Threshold for the SWR (Stale-While-Revalidate) cache. + */ +const SWR_THRESHOLD_LONG = 60; + +/** + * Threshold for short SWR (Stale-While-Revalidate) cache. + */ +const SWR_THRESHOLD_SHORT = 30; + /** * Bootstrap function to set up the plugin. * @@ -155,11 +165,22 @@ function set_cache_ttl() : void { global $batcache; $max_age = absint( apply_filters( 'smartcache.max-age', get_default_lifetime() ) ); + $swr_time = apply_filters( 'smartcache.swr_threshold', $max_age <= 300 ? SWR_THRESHOLD_SHORT : SWR_THRESHOLD_LONG ); if ( ! $batcache || ! is_object( $batcache ) ) { - header( 'Cache-Control: s-maxage=' . $max_age . ', must-revalidate' ); + $value = sprintf( + 's-maxage=%d, stale-while-revalidate=%d, must-revalidate', + $max_age, + $swr_time + ); } else { - header( 'Cache-Control: s-maxage=' . $max_age . ', max-age=' . $batcache->max_age . ', must-revalidate' ); + $value = sprintf( + 's-maxage=%d, max-age=%d, stale-while-revalidate=%d, must-revalidate', + $max_age, + $batcache->max_age, + $swr_time + ); } + header( $value ); } /**