Skip to content
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

fix(connector): [ECP-113] rate limit request for woo commerce #23

Merged
merged 2 commits into from
Oct 14, 2024
Merged
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
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
Loading