Use a new table for storing rate limits.

This commit is contained in:
Jeff Stieler 2021-10-15 13:07:12 -04:00
parent 8d312150fe
commit 39d3de1d41
2 changed files with 37 additions and 6 deletions

View File

@ -1039,6 +1039,13 @@ CREATE TABLE {$wpdb->prefix}wc_reserved_stock (
`timestamp` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`expires` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`order_id`, `product_id`)
) $collate;
CREATE TABLE {$wpdb->prefix}woocommerce_rate_limits (
rate_limit_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
rate_limit_key varchar(200) NOT NULL,
rate_limit_expiry BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (rate_limit_id),
UNIQUE KEY rate_limit_key (rate_limit_key($max_index_length))
) $collate;
";
@ -1074,6 +1081,7 @@ CREATE TABLE {$wpdb->prefix}wc_reserved_stock (
"{$wpdb->prefix}woocommerce_tax_rate_locations",
"{$wpdb->prefix}woocommerce_tax_rates",
"{$wpdb->prefix}wc_reserved_stock",
"{$wpdb->prefix}woocommerce_rate_limits",
);
/**

View File

@ -32,13 +32,14 @@ defined( 'ABSPATH' ) || exit;
class WC_Rate_Limiter {
/**
* Constructs Option name from action identifier.
* Constructs key name from action identifier.
* Left in for backwards compatibility.
*
* @param string $action_id Identifier of the action.
* @return string
*/
public static function storage_id( $action_id ) {
return 'woocommerce_rate_limit_' . $action_id;
return $action_id;
}
/**
@ -48,10 +49,21 @@ class WC_Rate_Limiter {
* @return bool
*/
public static function retried_too_soon( $action_id ) {
$next_try_allowed_at = get_option( self::storage_id( $action_id ) );
global $wpdb;
$next_try_allowed_at = $wpdb->get_var(
$wpdb->prepare(
"
SELECT rate_limit_expiry
FROM {$wpdb->prefix}woocommerce_rate_limits
WHERE rate_limit_key = %s
",
$action_id
)
);
// No record of action running, so action is allowed to run.
if ( false === $next_try_allowed_at ) {
if ( null === $next_try_allowed_at ) {
return false;
}
@ -72,8 +84,19 @@ class WC_Rate_Limiter {
* @return bool True if the option setting was successful, false otherwise.
*/
public static function set_rate_limit( $action_id, $delay ) {
$option_name = self::storage_id( $action_id );
global $wpdb;
$next_try_allowed_at = time() + $delay;
return update_option( $option_name, $next_try_allowed_at );
$result = $wpdb->replace(
$wpdb->prefix . 'woocommerce_rate_limits',
array(
'rate_limit_key' => $action_id,
'rate_limit_expiry' => $next_try_allowed_at,
),
array( '%s', '%d' )
);
return false !== $result;
}
}