Skip to content
This repository has been archived by the owner on Nov 10, 2023. It is now read-only.

Commit

Permalink
Merge pull request #11 from bluehost/fix/too-many-retries
Browse files Browse the repository at this point in the history
Prevent sites from making too many API requests
  • Loading branch information
wpscholar authored Aug 23, 2022
2 parents 03f5a43 + 60183f3 commit 7e23128
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions includes/Customer.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ class Customer {
*/
private const TRANSIENT = 'bh_cdata';

/**
* Retry throttle.
*
* @var string
*/
private const THROTTLE = 'bh_cdata_pause';

/**
* Provided option.
*
Expand All @@ -31,6 +38,13 @@ class Customer {
*/
private const PROVIDED_MOLE = 'bh_cdata_mole';

/**
* The number of failed connection attempts.
*
* @var integer
*/
private const RETRY_COUNT = 'bh_cdata_retry_count';

/**
* Prepare customer data
*
Expand Down Expand Up @@ -123,13 +137,23 @@ public static function connect( $path ) {
return $provided;
}

if ( self::is_throttled() ) {
return;
}

// refresh token if needed
AccessToken::maybe_refresh_token();

// construct request
$token = AccessToken::get_token();
$user_id = AccessToken::get_user();
$domain = SiteMeta::get_domain();

if ( empty( $token ) || empty( $user_id ) || empty( $domain ) ) {
self::throttle();
return;
}

$api_endpoint = 'https://my.bluehost.com/api/users/'.$user_id.'/usersite/'.$domain;
$args = array( 'headers' => array( 'X-SiteAPI-Token' => $token ) );
$url = $api_endpoint . $path;
Expand All @@ -138,13 +162,59 @@ public static function connect( $path ) {

// exit on errors
if ( is_wp_error( $response ) || wp_remote_retrieve_response_code( $response ) != 200 ) {
self::throttle();
return;
}

self::clear_throttle();
return json_decode( wp_remote_retrieve_body( $response ) );
}


/**
* Checks if a request should be throttled.
*
* @return bool
*/
public static function is_throttled() {
$throttle = Transient::get( self::THROTTLE );
$retry_count = (int) \get_option( self::RETRY_COUNT, 0 );

if ( false !== $throttle || $retry_count >= 10 ) {
return true;
}

return false;
}

/**
* Updates the throttle when there is a failure.
*/
public static function throttle() {
$retry_count = (int) \get_option( self::RETRY_COUNT, 0 ) + 1;

if ( $retry_count <= 5 ) {
$timeout = MINUTE_IN_SECONDS * $retry_count;
} elseif ( $retry_count < 10 ) {
$timeout = HOUR_IN_SECONDS * $retry_count;
} else {
$timeout = WEEK_IN_SECONDS;
$retry_count = 0;
}

Transient::set( self::THROTTLE, 1, $timeout );
\update_option( self::RETRY_COUNT, $retry_count );
}


/**
* Clears the retry count option.
*/
public static function clear_throttle() {
\delete_option( self::RETRY_COUNT );
}


/**
* Connect to the hosting info (guapi) endpoint and format response into hiive friendly data
*
Expand Down

0 comments on commit 7e23128

Please sign in to comment.