diff --git a/config/shipengine.php b/config/shipengine.php index f5cd9d0..3864227 100644 --- a/config/shipengine.php +++ b/config/shipengine.php @@ -27,6 +27,7 @@ 'base' => env('SHIP_ENGINE_ENDPOINT', 'https://api.shipengine.com/'), ], 'request_limit_per_minute' => env('SHIP_ENGINE_REQUEST_LIMIT_PER_MINUTE', 200), + 'use_local_rate_limit' => env('SHIP_ENGINE_USE_LOCAL_RATE_LIMIT', false), 'retries' => env('SHIP_ENGINE_RETRIES', 1), 'response' => [ 'as_object' => env('SHIP_ENGINE_RESPONSE_AS_OBJECT', false), diff --git a/src/ShipEngineClient.php b/src/ShipEngineClient.php index 66dea6a..563464b 100644 --- a/src/ShipEngineClient.php +++ b/src/ShipEngineClient.php @@ -296,19 +296,21 @@ private static function responseIsRateLimit(array $response) : bool private static function incrementRequestCount(ShipEngineConfig $config) : void { - $lock = tap(Cache::lock('shipengine.api-request.lock', 10))->block(10); + if ($config->useLocalRateLimit) { + $lock = tap(Cache::lock('shipengine.api-request.lock', 10))->block(10); - try { - $count = Cache::get('shipengine.api-request.count', 0); - $nextExpire = now()->seconds(0)->addMinute(); + try { + $count = Cache::get('shipengine.api-request.count', 0); + $nextExpire = now()->seconds(0)->addMinute(); - if ($count > $config->requestLimitPerMinute) { - throw new RateLimitExceededException(retryAfter: new DateInterval('PT1S'), message: 'Internal config API rate limit of ' . $config->requestLimitPerMinute . ' exceeded.'); - } + if ($count > $config->requestLimitPerMinute) { + throw new RateLimitExceededException(retryAfter: new DateInterval('PT1S'), message: 'Internal config API rate limit of ' . $config->requestLimitPerMinute . ' exceeded.'); + } - Cache::put('shipengine.api-request.count', $count + 1, $nextExpire); - } finally { - $lock->release(); + Cache::put('shipengine.api-request.count', $count + 1, $nextExpire); + } finally { + $lock->release(); + } } } } diff --git a/src/ShipEngineConfig.php b/src/ShipEngineConfig.php index 2dde0ec..496c8a9 100644 --- a/src/ShipEngineConfig.php +++ b/src/ShipEngineConfig.php @@ -21,6 +21,8 @@ final class ShipEngineConfig implements \JsonSerializable, Arrayable public bool $asObject = false; + public bool $useLocalRateLimit = false; + public DateInterval $timeout; public DateInterval $timeoutTotal; @@ -60,6 +62,7 @@ public function __construct(array $config = []) $assert->isTimeoutValid($timeout_total_value); $this->timeoutTotal = $timeout_total_value; + $this->useLocalRateLimit = boolval($config['use_local_rate_limit'] ?? config('shipengine.use_local_rate_limit', false)); $this->asObject = boolval($config['asObject'] ?? config('shipengine.response.as_object', false)); $this->baseUrl = $config['baseUrl'] ?? self::getBaseUri();