GithubHelp home page GithubHelp logo

hamburgscleanest / laravel-guzzle-throttle Goto Github PK

View Code? Open in Web Editor NEW
76.0 3.0 9.0 364 KB

A Laravel wrapper for https://github.com/hamburgscleanest/guzzle-advanced-throttle.

License: MIT License

PHP 100.00%
guzzle throttle api laravel laravel-5-package rate-limiting rate-limiter rate-limit request-handler cache-responses

laravel-guzzle-throttle's Introduction

hamburgscleanest/laravel-guzzle-throttle

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

A Laravel (>= 8.0) wrapper for Guzzle Advanced Throttle.

Install

Via Composer

composer require hamburgscleanest/laravel-guzzle-throttle

Automatic Package Discovery

Everything is automatically registered for you.


Configuration

Publish the config to get the example configuration.

php artisan vendor:publish

Example configuration

20 requests every 1 seconds

100 requests every 2 minutes


    return [
        'cache' => [
            // Name of the configured driver in the Laravel cache config file / Also needs to be set when "no-cache" is set! Because it's used for the internal timers
            'driver'   => 'default',
            // Cache strategy: no-cache, cache, force-cache
            'strategy' => 'cache',
            // TTL in minutes
            'ttl'      => 900,
            // When this is set to false, empty responses won't be cached.
            'allow_empty' => true
        ],
        'rules' => [
            // host (including scheme)
            'https://www.google.com' => [
                [
                    // maximum number of requests in the given interval
                    'max_requests'     => 20,
                    // interval in seconds till the limit is reset
                    'request_interval' => 1
                ],
                [
                // maximum number of requests in the given interval
                'max_requests'     => 100,
                // interval in seconds till the limit is reset
                'request_interval' => 120
                ]
            ]
        ]
    ];

Usage

To use the pre-configured client, you have to instantiate your client like this:

// returns an instance of GuzzleHttp\Client
$client = LaravelGuzzleThrottle::client(['base_uri' => 'https://www.google.com']);

After that, you can use all of the usual GuzzleHttp\Client methods, e.g.

$client->get('/test'));

Add other middlewares

You can still add other middlewares to the stack, too.
Define your stack as usual and then pass it to the throttled client:

$stack = HandlerStack::create(new CurlHandler());
$stack->push(some_other_middleware);

$client = LaravelGuzzleThrottle::client(['base_uri' => 'https://www.google.com', 'handler' => $stack]);

The client will 'automatically' add every other middleware to the top of the stack.


Caching


Beforehand

Responses with an error status code 4xx or 5xx are not cached (even with force-cache enabled)! Note: Also, 3xx redirect codes are not cached.


Supported drivers

The following drivers are officially supported: File, Redis and Memcached.

The configuration for the drivers can be seen in the middleware repository.


Options

Without caching - no-cache

Just throttle the requests and don't cache them. When the limit is exceeded, a 429 - Too Many Requests exception is thrown.


With caching (default) - cache

Use cached responses when your defined rate limit is exceeded. The middleware tries to fall back to a cached response before throwing a 429 - Too Many Requests exception.


With forced caching - force-cache

Always uses the cached responses when available to spare your rate limits. It only sends the request when it is not cached. If there is no cached response and the request limits are exceeded, it falls back to throwing a 429 - Too Many Requests exception.


Wildcards

If you want to define the same rules for multiple different hosts, you can use wildcards. A possible use case can be subdomains:

$rules = new RequestLimitRuleset([
        'https://www.{subdomain}.mysite.com' => [
            [
                'max_requests'     => 50,
                'request_interval' => 2
            ]
        ]
    ]);

This host matches https://www.en.mysite.com, https://www.de.mysite.com, https://www.fr.mysite.com, etc.


Further details

If you want to know more about the possible configurations, head over to the middleware repository: Guzzle Advanced Throttle.


Changes

Please see CHANGELOG for more information on what has changed recently.

Testing

composer test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

If you discover any security-related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

laravel-guzzle-throttle's People

Contributors

dependabot-preview[bot] avatar dependabot[bot] avatar remipou avatar timopruesse avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

laravel-guzzle-throttle's Issues

Locked to PHP version >= 7.1.0

Packages is locked toPHP version >= 7.1.0

Currently cannot install this package on PHP 7.0.23

Provide a detailed description of the change or addition you are proposing.

Make it clear if the issue is a bug, an enhancement or just a question.

Context

Me because i want to support >= 7.0

How can it benefit other users?

Others who who also want to support >= won't be able to use this package.

Possible implementation

Is there any specific reason why this is locked to >= 7.1.0, if none, then maybe lower to 7.0

Your environment

Include as many relevant details about the environment you experienced the bug in and how to reproduce it.

  • Version used: PHP 7.0.23:
  • Operating system and version: Ubuntu 16

Can't pass headers

Describe the bug
I was trying to add throttle to a Http request using headers, but it looks like the standard methods are not recognized.

To Reproduce
This is my code

/**
     * Generate API Http client request
     *
     * @param string $host   The API host
     * @param string $url    The API URL
     * @param array  $params The API query URL arguments
     * @return PromiseInterface|Response
     */
    public function get(string $host, string $url, array $params)
    {
        $scheme = str_starts_with('https://', $host) ? $host : 'https://' . $host;
        $relativeUrl = str_replace($scheme, '', $url);
        $client = LaravelGuzzleThrottle::client(['base_uri' => $scheme]);

        return $client
            ->acceptJson()
            ->withHeaders(
                [
                    'x-rapidapi-host' => $host,
                    'x-rapidapi-key' => $this->key,
                ]
            )
            ->timeout(20)->retry(1, 100, function ($exception)
            {
                // retry once after a 20 seconds cURL timeout, delayed by 100ms
                return $exception instanceof ConnectException;

            })
            ->get($relativeUrl, $params);
    }

Is there any way to use other mathods than get ?

Thx.

Remove support Laravel 5.5 in documents

Remove support Laravel 5.5 in documents

Detailed description

In composer.json file:

"require": {
    "php": ">=7.1.0",
    "hamburgscleanest/guzzle-advanced-throttle": "1.*",
    "illuminate/support": "5.6.*"
  },

This package required "illuminate/support": "5.6.*", it only available in Laravel 5.6.*
But in this package's README, it have configure for Laravel < 5.5

I think you should update README

funnel

Hey, nice work. I made something similar recently. My throttle is fine, but I've got issues with funnel. It works fine in homestead but not in my vapor deploy. Something about "All keys do not map to the same slot" from redis cluster. Have you taken a crack at funnel?

Update Documentation

Hi,

First of all thanks for this great package! Works perfectly :)
Not so much of an issue, but a few remarks regarding the documentation:

  • The examples use the GuzzleThrottle class, however since this is the Laravel wrapper it maybe better to show/use the LaravelGuzzleThrottle class in the examples.
  • When you have published the configuration, it maybe necessary to do a php artisan config:clear if the config is cached. Without this, you will encounter errors from this package. I got a 'Please provide a cache driver' error, even though it was set correctly. Maybe a good idea to mention this in the documentation :)

Cheers! Sacha

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.