Skip to content

[WIP] Explore basic error rate limiting #4313

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: develop
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions includes/class-wc-stripe-api.php
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,10 @@ public static function retrieve( $api ) {

WC_Stripe_Logger::log( "{$api}" );

if ( self::has_api_error_limit( $api, 'GET' ) ) {
return new WP_Error( 'stripe_error', __( 'We are seeing repeated problems calling Stripe and are rate limiting the client', 'woocommerce-gateway-stripe' ) );
}

$response = wp_safe_remote_get(
self::ENDPOINT . $api,
[
Expand All @@ -277,12 +281,63 @@ public static function retrieve( $api ) {

if ( is_wp_error( $response ) || empty( $response['body'] ) ) {
WC_Stripe_Logger::log( 'Error Response: ' . print_r( $response, true ) );
wp_cache_incr( self::get_api_error_cache_key( $api, 'GET' ), 1, 'woocommerce_stripe' );

return new WP_Error( 'stripe_error', __( 'There was a problem connecting to the Stripe API endpoint.', 'woocommerce-gateway-stripe' ) );
}

return json_decode( $response['body'] );
}

/**
* Bump the API error limit.
*
* @param string $api
* @param string $method
*/
protected static function bump_api_error_limit( $api, $method ) {
wp_cache_incr( self::get_api_error_cache_key( $api, $method ), 1, 'woocommerce_stripe' );
}

/**
* Check if the API error limit has been reached.
*
* @param string $api
* @param string $method
* @return bool
*/
protected static function has_api_error_limit( $api, $method ) {
$cache_key = self::get_api_error_cache_key( $api, $method );

$recent_failure_count = wp_cache_get( $cache_key, 'woocommerce_stripe' );
if ( false === $recent_failure_count ) {
$recent_failure_count = 0;
}

if ( $recent_failure_count >= 15 ) {
return true;
}

return false;
}

/**
* Get the cache key for API error tracking/counting.
*
* @param string $api
* @param string $method
* @return string
*/
protected static function get_api_error_cache_key( $api, $method ) {
$mode = WC_Stripe_Mode::is_test() ? 'test' : 'live';

$now = time();
// Use 30 second buckets
$cache_bucket = $now - ( $now % 30 );

return "wc_stripe_api_error_track_{$mode}_{$method}_{$api}_{$cache_bucket}";
}

/**
* Send the request to Stripe's API with level 3 data generated
* from the order. If the request fails due to an error related
Expand Down
Loading