diff --git a/plugins/woocommerce/changelog/fix-33315-stats-cache-ttl b/plugins/woocommerce/changelog/fix-33315-stats-cache-ttl new file mode 100644 index 00000000000..e81476c359f --- /dev/null +++ b/plugins/woocommerce/changelog/fix-33315-stats-cache-ttl @@ -0,0 +1,4 @@ +Significance: minor +Type: update + +Change invalidation and TTL of the analytics cache for better cache resilience diff --git a/plugins/woocommerce/src/Admin/API/Reports/Cache.php b/plugins/woocommerce/src/Admin/API/Reports/Cache.php index 7bea6059458..83a052fc254 100644 --- a/plugins/woocommerce/src/Admin/API/Reports/Cache.php +++ b/plugins/woocommerce/src/Admin/API/Reports/Cache.php @@ -22,18 +22,32 @@ class Cache { * Invalidate cache. */ public static function invalidate() { - \WC_Cache_Helper::get_transient_version( self::VERSION_OPTION, true ); + self::get_version( true ); } /** * Get cache version number. * + * This is based on WC_Cache_Helper::get_transient_version, but rounds the Unix timestamp to the nearest + * increment to rate-limit cache invalidations. + * + * @param bool $refresh True to generate a new value. + * * @return string */ - public static function get_version() { - $version = \WC_Cache_Helper::get_transient_version( self::VERSION_OPTION ); + public static function get_version( $refresh = false ) { + $transient_name = self::VERSION_OPTION . '-transient-version'; + $transient_value = get_transient( $transient_name ); - return $version; + if ( false === $transient_value || true === $refresh ) { + // Round to the nearest $minutes increment. + $minutes = 10; + $transient_value = (string) round( time() / ( MINUTE_IN_SECONDS * $minutes ) ) * ( MINUTE_IN_SECONDS * $minutes ); + + set_transient( $transient_name, $transient_value ); + } + + return $transient_value; } /** @@ -70,7 +84,7 @@ class Cache { 'value' => $value, ); - $result = set_transient( $key, $transient_value, WEEK_IN_SECONDS ); + $result = set_transient( $key, $transient_value, HOUR_IN_SECONDS ); return $result; } diff --git a/plugins/woocommerce/src/Admin/API/Reports/DataStore.php b/plugins/woocommerce/src/Admin/API/Reports/DataStore.php index 09df3f95c9d..e13a082f407 100644 --- a/plugins/woocommerce/src/Admin/API/Reports/DataStore.php +++ b/plugins/woocommerce/src/Admin/API/Reports/DataStore.php @@ -221,6 +221,7 @@ class DataStore extends SqlQuery { if ( true === $this->debug_cache ) { $this->debug_cache_data['should_use_cache'] = $this->should_use_cache(); $this->debug_cache_data['force_cache_refresh'] = $this->force_cache_refresh; + $this->debug_cache_data['cache_version'] = Cache::get_version(); $this->debug_cache_data['cache_hit'] = false; }