Skip to content

Commit

Permalink
fix(connector): [ECP-113] rate limit request for woo commerce (#23)
Browse files Browse the repository at this point in the history
* fix(connector): [ECP-113] rate limit request for woocommerce

* fix(connector): syntax for woo_commerce

---------

Co-authored-by: alexis.hermanns <alexis.hermanns@pcp-065>
  • Loading branch information
alherlengow and alexis.hermanns authored Oct 14, 2024
1 parent 5e8ea8a commit 67de112
Showing 1 changed file with 79 additions and 0 deletions.
79 changes: 79 additions & 0 deletions includes/class-lengow-connector.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ class Lengow_Connector {
const CODE_404 = 404;
const CODE_500 = 500;
const CODE_504 = 504;
const REQUEST_LIMIT = 500;


/**
* @var array success HTTP codes for request.
Expand Down Expand Up @@ -429,11 +431,88 @@ private function call( $api, $args, $type, $format, $body, $log_output ) {
* @throws Lengow_Exception
*/
private function call_action( $api, $args, $type, $format, $body, $log_output ) {
$this->rate_limiting_requests($api);
$result = $this->make_request( $type, $api, $args, $this->token, $body, $log_output );

return $this->format( $result, $format );
}

/**
* Rate limiting for Lengow API
*/
private function rate_limiting_requests(string $api): void
{

switch($api) {
case self::API_ORDER:
$wait = $this->get_wait_limit_order_requests();
break;
case self::API_ORDER_ACTION:
$wait = $this->get_wait_limit_action_requests();
break;
case self::API_ORDER_MOI:
$wait = $this->get_wait_limit_order_requests();
break;
default:
$wait = null;
break;
}

if (!is_null($wait) && $wait > 0) {
Lengow_Main::log(
Lengow_Log::CODE_CONNECTOR,
Lengow_Main::set_log_message('API call blocked due to rate limiting - wait %1 seconds', [$wait])
);
sleep($wait);
}
}

/**
* Limit the number of order requests
*/
private function get_wait_limit_order_requests(): ?int
{
static $nb_request = 0;
static $time_start = null;
if (is_null($time_start)) {
$time_start = time();
}
$nb_request++;
if ($nb_request >= self::REQUEST_LIMIT) {
$time_diff = time() - $time_start;
$nb_request = 0;
$time_start = time();
if ($time_diff < 60) {
return (60 - $time_diff);
}
}

return null;
}

/**
* Limit the number of action requests
*/
private function get_wait_limit_action_requests(): ?int
{
static $nb_request = 0;
static $time_start = null;
if (is_null($time_start)) {
$time_start = time();
}
$nb_request++;
if ($nb_request >= self::REQUEST_LIMIT) {
$time_diff = time() - $time_start;
$nb_request = 0;
$time_start = time();
if ($time_diff < 60) {
return (60 - $time_diff);
}
}

return null;
}

/**
* Get authorization token from Middleware.
*
Expand Down

0 comments on commit 67de112

Please sign in to comment.