From a7f9c9e1491fdae86b4e286c6b7c27ea1099756f Mon Sep 17 00:00:00 2001 From: Nick Daugherty Date: Tue, 16 Oct 2018 08:39:15 -0600 Subject: [PATCH] Cache future timestamps for a short time Instead of sending nocache headers, which has implications for cache servers like Varnish that do hit-for-pass, set a short TTL so the content can be served from cache, but expires when the timestamp becomes valid. --- liveblog.php | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/liveblog.php b/liveblog.php index a66396edb..04d42633e 100644 --- a/liveblog.php +++ b/liveblog.php @@ -53,6 +53,7 @@ final class WPCOM_Liveblog { public static $post_id = null; private static $entry_query = null; private static $do_not_cache_response = false; + private static $cache_control_max_age = null; private static $custom_template_path = null; public static $is_rest_api_call = false; @@ -428,9 +429,11 @@ public static function get_entries_by_time( $start_timestamp, $end_timestamp ) { $latest_timestamp = null; $entries_for_json = array(); - // Do not cache if it's too soon - if ( $end_timestamp > time() ) { - self::$do_not_cache_response = true; + $now = time(); + + // If end timestamp is in future, set a cache TTL until it's not + if ( $end_timestamp > $now ) { + self::$cache_control_max_age = $end_timestamp - $now; } if ( empty( self::$entry_query ) ) { @@ -1662,6 +1665,9 @@ public static function protect_liveblog_meta_key( $protected, $meta_key ) { public static function prevent_caching_if_needed() { if ( self::$do_not_cache_response ) { nocache_headers(); + } else if ( self::$cache_control_max_age ) { + header( 'Cache-control: max-age=' . self::$cache_control_max_age ); + header( 'Expires: ' . gmdate( 'D, d M Y H:i:s \G\M\T', time() + self::$cache_control_max_age ) ); } }