Add daily cleanup of expired rate limits.

This commit is contained in:
Jeff Stieler 2021-10-15 13:56:55 -04:00
parent a8b4f83c9c
commit f218571fec
3 changed files with 34 additions and 2 deletions

View File

@ -528,6 +528,7 @@ class WC_Install {
wp_clear_scheduled_hook( 'woocommerce_cleanup_logs' );
wp_clear_scheduled_hook( 'woocommerce_geoip_updater' );
wp_clear_scheduled_hook( 'woocommerce_tracker_send_event' );
wp_clear_scheduled_hook( 'woocommerce_cleanup_rate_limits' );
$ve = get_option( 'gmt_offset' ) > 0 ? '-' : '+';
@ -549,6 +550,7 @@ class WC_Install {
wp_schedule_event( time() + ( 6 * HOUR_IN_SECONDS ), 'twicedaily', 'woocommerce_cleanup_sessions' );
wp_schedule_event( time() + MINUTE_IN_SECONDS, 'fifteendays', 'woocommerce_geoip_updater' );
wp_schedule_event( time() + 10, apply_filters( 'woocommerce_tracker_event_recurrence', 'daily' ), 'woocommerce_tracker_send_event' );
wp_schedule_event( time() + ( 3 * HOUR_IN_SECONDS ), 'daily', 'woocommerce_cleanup_rate_limits' );
}
/**

View File

@ -31,6 +31,11 @@ defined( 'ABSPATH' ) || exit;
*/
class WC_Rate_Limiter {
/**
* Cache group.
*/
const CACHE_GROUP = 'wc_rate_limit';
/**
* Constructs key name from action identifier.
* Left in for backwards compatibility.
@ -59,7 +64,7 @@ class WC_Rate_Limiter {
* @return bool|int
*/
protected static function get_cached( $action_id ) {
return wp_cache_get( self::get_cache_key( $action_id ), 'wc_rate_limit' );
return wp_cache_get( self::get_cache_key( $action_id ), self::CACHE_GROUP );
}
/**
@ -70,7 +75,7 @@ class WC_Rate_Limiter {
* @return bool
*/
protected static function set_cache( $action_id, $expiry ) {
return wp_cache_set( self::get_cache_key( $action_id ), $expiry, 'wc_rate_limit' );
return wp_cache_set( self::get_cache_key( $action_id ), $expiry, self::CACHE_GROUP );
}
/**
@ -138,4 +143,22 @@ class WC_Rate_Limiter {
return false !== $result;
}
/**
* Cleanup expired rate limits from the database and clear caches.
*/
public static function cleanup() {
global $wpdb;
$wpdb->query(
$wpdb->prepare(
"DELETE FROM {$wpdb->prefix}woocommerce_rate_limits WHERE rate_limit_expiry < %d",
time()
)
);
if ( class_exists( 'WC_Cache_Helper' ) ) {
WC_Cache_Helper::invalidate_cache_group( self::CACHE_GROUP );
}
}
}

View File

@ -2548,3 +2548,10 @@ function wc_cache_get_multiple( $keys, $group = '', $force = false ) {
}
return $values;
}
/**
* Cleans up rate limit data - cron callback.
*
* @since 6.0.0
*/
add_action( 'woocommerce_cleanup_rate_limits', array( 'WC_Rate_Limiter', 'cleanup' ) );