Update method for getting Reports API cache version number (#33353)

* Changes the frequency at which the Reports API cache can be invalidated via the cache version number to be at most once every 10 minutes, instead of with every change to the store.
* Changes the TTL of Reports API cache entries so that they expire after an hour instead of after a week.

The goal of these changes is to increase the chance that a request to the Reports API for store stats will result in a cache hit, thus avoiding expensive, slow queries. The reason for lowering the TTL is so that if multiple store changes are made within the new 10-minute frequency window, the cache data will only be stale for up to an hour. With #33325 users will be able to refresh entries in the cache manually if they think something is stale.

Closes #33315
This commit is contained in:
Corey McKrill 2022-06-15 11:40:05 -07:00 committed by GitHub
parent f0b9adc7ae
commit bccc80366d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 5 deletions

View File

@ -0,0 +1,4 @@
Significance: minor
Type: update
Change invalidation and TTL of the analytics cache for better cache resilience

View File

@ -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;
}

View File

@ -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;
}