Skip to content

implement rate limit handling #185

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
25 changes: 24 additions & 1 deletion src/ClientFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,18 @@

namespace JoliCode\Slack;

use Http\Client\Common\Exception\ClientErrorException;
use Http\Client\Common\Plugin\ErrorPlugin;
use Http\Client\Common\Plugin\HeaderAppendPlugin;
use Http\Client\Common\Plugin\RetryPlugin;
use Http\Client\Common\PluginClient;
use Http\Client\Exception\HttpException;
use Http\Discovery\Psr17FactoryDiscovery;
use Http\Discovery\Psr18ClientDiscovery;
use JoliCode\Slack\HttpPlugin\AddSlackPathAndHostPlugin;
use JoliCode\Slack\HttpPlugin\SlackErrorPlugin;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Client\ClientInterface;

class ClientFactory
Expand All @@ -34,12 +39,30 @@ public static function create(string $token, ?ClientInterface $httpClient = null
// Decorates the HTTP client with some plugins
$uri = Psr17FactoryDiscovery::findUriFactory()->createUri('https://slack.com/api');
$pluginClient = new PluginClient($httpClient, [
new ErrorPlugin(),
new SlackErrorPlugin(),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we sure this plugin can stay here? Do you have an example of rate limiting response from Slack?

new AddSlackPathAndHostPlugin($uri),
new HeaderAppendPlugin([
'Authorization' => 'Bearer ' . $token,
]),
new RetryPlugin([
'retries' => 3,
'exception_decider' => function (RequestInterface $request, ClientExceptionInterface $e) {
// retry only server errors and rate limits
return !$e instanceof HttpException || ($e->getCode() === 429 || ($e->getCode() >= 500 && $e->getCode() < 600));
},
'exception_delay' => function (RequestInterface $request, ClientExceptionInterface $e, int $retries): int {
if ($e instanceof ClientErrorException) {
$response = $e->getResponse();
if ($response->hasHeader('Retry-After')) {
$retryAfter = (int) $response->getHeaderLine('retry-after');
return $retryAfter * 1000000;
}
}

return RetryPlugin::defaultExceptionDelay($request, $e, $retries);
},
]),
new ErrorPlugin(),
]);

// Instantiate our client extending the one generated by Jane
Expand Down
Loading