added spatie/laravel-rate-limited-job-middleware to composer

This commit is contained in:
2021-02-06 17:22:09 +00:00
parent df510b8680
commit e8649811f2
19 changed files with 876 additions and 7 deletions

View File

@@ -17,6 +17,7 @@
"laravel/ui": "^2.0",
"laravelcollective/html": "^6.0",
"predis/predis": "^1.1",
"spatie/laravel-rate-limited-job-middleware": "^1.5",
"twbs/bootstrap": "^4.5"
},
"require-dev": {

62
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "def63b69a9e4d54db5c28bafdf491100",
"content-hash": "ea02a28c4e0e5b626127a2be8c62c3d9",
"packages": [
{
"name": "brick/math",
@@ -2585,6 +2585,66 @@
],
"time": "2020-08-18T17:17:46+00:00"
},
{
"name": "spatie/laravel-rate-limited-job-middleware",
"version": "1.5.0",
"source": {
"type": "git",
"url": "https://github.com/spatie/laravel-rate-limited-job-middleware.git",
"reference": "7b72592e0d823e2948c413f5e661de0fd3431db5"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/spatie/laravel-rate-limited-job-middleware/zipball/7b72592e0d823e2948c413f5e661de0fd3431db5",
"reference": "7b72592e0d823e2948c413f5e661de0fd3431db5",
"shasum": ""
},
"require": {
"illuminate/redis": "^6.0|^7.0|^8.0",
"php": "^7.3|^8.0"
},
"require-dev": {
"mockery/mockery": "^1.4",
"orchestra/testbench": "^4.0|^5.0|^6.0",
"phpunit/phpunit": "^8.2|^9.0",
"symfony/var-dumper": "^4.3|^5.0"
},
"type": "library",
"autoload": {
"psr-4": {
"Spatie\\RateLimitedMiddleware\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Freek Van der Herten",
"email": "freek@spatie.be",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"description": "A middleware that can rate limit jobs",
"homepage": "https://github.com/spatie/laravel-rate-limited-job-middleware",
"keywords": [
"laravel-rate-limited-job-middleware",
"spatie"
],
"support": {
"issues": "https://github.com/spatie/laravel-rate-limited-job-middleware/issues",
"source": "https://github.com/spatie/laravel-rate-limited-job-middleware/tree/1.5.0"
},
"funding": [
{
"url": "https://www.patreon.com/spatie",
"type": "patreon"
}
],
"time": "2020-11-27T09:36:55+00:00"
},
{
"name": "spomky-labs/base64url",
"version": "v2.0.4",

View File

@@ -29,7 +29,7 @@ private static $installed = array (
'aliases' =>
array (
),
'reference' => 'f11360e5e8490dfa475f7ba449245d5eae66c5be',
'reference' => 'df510b86806490c95eaa14064e89e5968cc541e0',
'name' => 'laravel/laravel',
),
'versions' =>
@@ -463,7 +463,7 @@ private static $installed = array (
'aliases' =>
array (
),
'reference' => 'f11360e5e8490dfa475f7ba449245d5eae66c5be',
'reference' => 'df510b86806490c95eaa14064e89e5968cc541e0',
),
'laravel/socialite' =>
array (
@@ -928,6 +928,15 @@ private static $installed = array (
),
'reference' => '99732be0ddb3361e16ad77b68ba41efc8e979019',
),
'spatie/laravel-rate-limited-job-middleware' =>
array (
'pretty_version' => '1.5.0',
'version' => '1.5.0.0',
'aliases' =>
array (
),
'reference' => '7b72592e0d823e2948c413f5e661de0fd3431db5',
),
'spomky-labs/base64url' =>
array (
'pretty_version' => 'v2.0.4',

View File

@@ -17,6 +17,10 @@ return array(
'App\\Console\\Commands\\Files\\UpdateItemCompositionFromSDECommand' => $baseDir . '/app/Console/Commands/Files/UpdateItemCompositionFromSDECommand.php',
'App\\Console\\Commands\\Finances\\HoldingFinancesCommand' => $baseDir . '/app/Console/Commands/Finances/HoldingFinancesCommand.php',
'App\\Console\\Commands\\Finances\\SovBillsCommand' => $baseDir . '/app/Console/Commands/Finances/SovBillsCommand.php',
'App\\Console\\Commands\\MiningTaxes\\MiningTaxesInvoices' => $baseDir . '/app/Console/Commands/MiningTaxes/MiningTaxesInvoices.php',
'App\\Console\\Commands\\MiningTaxes\\MiningTaxesLedgers' => $baseDir . '/app/Console/Commands/MiningTaxes/MiningTaxesLedgers.php',
'App\\Console\\Commands\\MiningTaxes\\MiningTaxesObservers' => $baseDir . '/app/Console/Commands/MiningTaxes/MiningTaxesObservers.php',
'App\\Console\\Commands\\MiningTaxes\\MiningTaxesPayments' => $baseDir . '/app/Console/Commands/MiningTaxes/MiningTaxesPayments.php',
'App\\Console\\Commands\\Moons\\MoonsUpdateCommand' => $baseDir . '/app/Console/Commands/Moons/MoonsUpdateCommand.php',
'App\\Console\\Commands\\RentalMoons\\AllianceRentalMoonInvoiceCreationCommand' => $baseDir . '/app/Console/Commands/RentalMoons/AllianceRentalMoonInvoiceCreationCommand.php',
'App\\Console\\Commands\\RentalMoons\\AllianceRentalMoonUpdatePricingCommand' => $baseDir . '/app/Console/Commands/RentalMoons/AllianceRentalMoonUpdatePricingCommand.php',
@@ -4141,6 +4145,7 @@ return array(
'SebastianBergmann\\Type\\VoidType' => $vendorDir . '/sebastian/type/src/VoidType.php',
'SebastianBergmann\\Version' => $vendorDir . '/sebastian/version/src/Version.php',
'SolarSystemSeeder' => $baseDir . '/database/seeds/SolarSystemSeeder.php',
'Spatie\\RateLimitedMiddleware\\RateLimited' => $vendorDir . '/spatie/laravel-rate-limited-job-middleware/src/RateLimited.php',
'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
'Symfony\\Component\\Console\\Application' => $vendorDir . '/symfony/console/Application.php',
'Symfony\\Component\\Console\\Color' => $vendorDir . '/symfony/console/Color.php',

View File

@@ -38,6 +38,7 @@ return array(
'Symfony\\Component\\ErrorHandler\\' => array($vendorDir . '/symfony/error-handler'),
'Symfony\\Component\\CssSelector\\' => array($vendorDir . '/symfony/css-selector'),
'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
'Spatie\\RateLimitedMiddleware\\' => array($vendorDir . '/spatie/laravel-rate-limited-job-middleware/src'),
'Seat\\Eseye\\' => array($vendorDir . '/eveseat/eseye/src'),
'Ramsey\\Uuid\\' => array($vendorDir . '/ramsey/uuid/src'),
'Ramsey\\Collection\\' => array($vendorDir . '/ramsey/collection/src'),

View File

@@ -84,6 +84,7 @@ class ComposerStaticInitc3f953f8a7291d41a76e1664339777c9
'Symfony\\Component\\ErrorHandler\\' => 31,
'Symfony\\Component\\CssSelector\\' => 30,
'Symfony\\Component\\Console\\' => 26,
'Spatie\\RateLimitedMiddleware\\' => 29,
'Seat\\Eseye\\' => 11,
),
'R' =>
@@ -317,6 +318,10 @@ class ComposerStaticInitc3f953f8a7291d41a76e1664339777c9
array (
0 => __DIR__ . '/..' . '/symfony/console',
),
'Spatie\\RateLimitedMiddleware\\' =>
array (
0 => __DIR__ . '/..' . '/spatie/laravel-rate-limited-job-middleware/src',
),
'Seat\\Eseye\\' =>
array (
0 => __DIR__ . '/..' . '/eveseat/eseye/src',
@@ -547,6 +552,10 @@ class ComposerStaticInitc3f953f8a7291d41a76e1664339777c9
'App\\Console\\Commands\\Files\\UpdateItemCompositionFromSDECommand' => __DIR__ . '/../..' . '/app/Console/Commands/Files/UpdateItemCompositionFromSDECommand.php',
'App\\Console\\Commands\\Finances\\HoldingFinancesCommand' => __DIR__ . '/../..' . '/app/Console/Commands/Finances/HoldingFinancesCommand.php',
'App\\Console\\Commands\\Finances\\SovBillsCommand' => __DIR__ . '/../..' . '/app/Console/Commands/Finances/SovBillsCommand.php',
'App\\Console\\Commands\\MiningTaxes\\MiningTaxesInvoices' => __DIR__ . '/../..' . '/app/Console/Commands/MiningTaxes/MiningTaxesInvoices.php',
'App\\Console\\Commands\\MiningTaxes\\MiningTaxesLedgers' => __DIR__ . '/../..' . '/app/Console/Commands/MiningTaxes/MiningTaxesLedgers.php',
'App\\Console\\Commands\\MiningTaxes\\MiningTaxesObservers' => __DIR__ . '/../..' . '/app/Console/Commands/MiningTaxes/MiningTaxesObservers.php',
'App\\Console\\Commands\\MiningTaxes\\MiningTaxesPayments' => __DIR__ . '/../..' . '/app/Console/Commands/MiningTaxes/MiningTaxesPayments.php',
'App\\Console\\Commands\\Moons\\MoonsUpdateCommand' => __DIR__ . '/../..' . '/app/Console/Commands/Moons/MoonsUpdateCommand.php',
'App\\Console\\Commands\\RentalMoons\\AllianceRentalMoonInvoiceCreationCommand' => __DIR__ . '/../..' . '/app/Console/Commands/RentalMoons/AllianceRentalMoonInvoiceCreationCommand.php',
'App\\Console\\Commands\\RentalMoons\\AllianceRentalMoonUpdatePricingCommand' => __DIR__ . '/../..' . '/app/Console/Commands/RentalMoons/AllianceRentalMoonUpdatePricingCommand.php',
@@ -4671,6 +4680,7 @@ class ComposerStaticInitc3f953f8a7291d41a76e1664339777c9
'SebastianBergmann\\Type\\VoidType' => __DIR__ . '/..' . '/sebastian/type/src/VoidType.php',
'SebastianBergmann\\Version' => __DIR__ . '/..' . '/sebastian/version/src/Version.php',
'SolarSystemSeeder' => __DIR__ . '/../..' . '/database/seeds/SolarSystemSeeder.php',
'Spatie\\RateLimitedMiddleware\\RateLimited' => __DIR__ . '/..' . '/spatie/laravel-rate-limited-job-middleware/src/RateLimited.php',
'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
'Symfony\\Component\\Console\\Application' => __DIR__ . '/..' . '/symfony/console/Application.php',
'Symfony\\Component\\Console\\Color' => __DIR__ . '/..' . '/symfony/console/Color.php',

View File

@@ -4512,6 +4512,69 @@
"homepage": "https://github.com/sebastianbergmann/version",
"install-path": "../sebastian/version"
},
{
"name": "spatie/laravel-rate-limited-job-middleware",
"version": "1.5.0",
"version_normalized": "1.5.0.0",
"source": {
"type": "git",
"url": "https://github.com/spatie/laravel-rate-limited-job-middleware.git",
"reference": "7b72592e0d823e2948c413f5e661de0fd3431db5"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/spatie/laravel-rate-limited-job-middleware/zipball/7b72592e0d823e2948c413f5e661de0fd3431db5",
"reference": "7b72592e0d823e2948c413f5e661de0fd3431db5",
"shasum": ""
},
"require": {
"illuminate/redis": "^6.0|^7.0|^8.0",
"php": "^7.3|^8.0"
},
"require-dev": {
"mockery/mockery": "^1.4",
"orchestra/testbench": "^4.0|^5.0|^6.0",
"phpunit/phpunit": "^8.2|^9.0",
"symfony/var-dumper": "^4.3|^5.0"
},
"time": "2020-11-27T09:36:55+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Spatie\\RateLimitedMiddleware\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Freek Van der Herten",
"email": "freek@spatie.be",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"description": "A middleware that can rate limit jobs",
"homepage": "https://github.com/spatie/laravel-rate-limited-job-middleware",
"keywords": [
"laravel-rate-limited-job-middleware",
"spatie"
],
"support": {
"issues": "https://github.com/spatie/laravel-rate-limited-job-middleware/issues",
"source": "https://github.com/spatie/laravel-rate-limited-job-middleware/tree/1.5.0"
},
"funding": [
{
"url": "https://www.patreon.com/spatie",
"type": "patreon"
}
],
"install-path": "../spatie/laravel-rate-limited-job-middleware"
},
{
"name": "spomky-labs/base64url",
"version": "v2.0.4",

View File

@@ -6,7 +6,7 @@
'aliases' =>
array (
),
'reference' => 'f11360e5e8490dfa475f7ba449245d5eae66c5be',
'reference' => 'df510b86806490c95eaa14064e89e5968cc541e0',
'name' => 'laravel/laravel',
),
'versions' =>
@@ -440,7 +440,7 @@
'aliases' =>
array (
),
'reference' => 'f11360e5e8490dfa475f7ba449245d5eae66c5be',
'reference' => 'df510b86806490c95eaa14064e89e5968cc541e0',
),
'laravel/socialite' =>
array (
@@ -905,6 +905,15 @@
),
'reference' => '99732be0ddb3361e16ad77b68ba41efc8e979019',
),
'spatie/laravel-rate-limited-job-middleware' =>
array (
'pretty_version' => '1.5.0',
'version' => '1.5.0.0',
'aliases' =>
array (
),
'reference' => '7b72592e0d823e2948c413f5e661de0fd3431db5',
),
'spomky-labs/base64url' =>
array (
'pretty_version' => 'v2.0.4',

View File

@@ -4,8 +4,8 @@
$issues = array();
if (!(PHP_VERSION_ID >= 70205)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 7.2.5". You are running ' . PHP_VERSION . '.';
if (!(PHP_VERSION_ID >= 70300)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 7.3.0". You are running ' . PHP_VERSION . '.';
}
if ($issues) {

View File

@@ -0,0 +1,55 @@
# Contributing
Contributions are **welcome** and will be fully **credited**.
Please read and understand the contribution guide before creating an issue or pull request.
## Etiquette
This project is open source, and as such, the maintainers give their free time to build and maintain the source code
held within. They make the code freely available in the hope that it will be of use to other developers. It would be
extremely unfair for them to suffer abuse or anger for their hard work.
Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the
world that developers are civilized and selfless people.
It's the duty of the maintainer to ensure that all submissions to the project are of sufficient
quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used.
## Viability
When requesting or submitting new features, first consider whether it might be useful to others. Open
source projects are used by many developers, who may have entirely different needs to your own. Think about
whether or not your feature is likely to be used by other users of the project.
## Procedure
Before filing an issue:
- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident.
- Check to make sure your feature suggestion isn't already present within the project.
- Check the pull requests tab to ensure that the bug doesn't have a fix in progress.
- Check the pull requests tab to ensure that the feature isn't already in progress.
Before submitting a pull request:
- Check the codebase to ensure that your feature doesn't already exist.
- Check the pull requests to ensure that another person hasn't already submitted the feature or fix.
## Requirements
If the project maintainer has any additional requirements, you will find them listed here.
- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer).
- **Add tests!** - Your patch won't be accepted if it doesn't have tests.
- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
- **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option.
- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.
**Happy coding**!

View File

@@ -0,0 +1 @@
patreon: spatie

View File

@@ -0,0 +1,29 @@
name: Check & fix styling
on: [push]
jobs:
style:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Fix style
uses: docker://oskarstark/php-cs-fixer-ga
with:
args: --config=.php_cs --allow-risky=yes
- name: Extract branch name
shell: bash
run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})"
id: extract_branch
- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@v4.4.1
with:
commit_message: Fix styling
branch: ${{ steps.extract_branch.outputs.branch }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -0,0 +1,50 @@
name: run-tests
on: [push, pull_request]
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
os: [ubuntu-latest]
php: [8.0, 7.4, 7.3]
laravel: [8.*, 7.*]
dependency-version: [prefer-lowest, prefer-stable]
include:
- laravel: 8.*
testbench: 6.*
- laravel: 7.*
testbench: 5.*
name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} - ${{ matrix.os }}
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick
coverage: none
- name: Start Redis
uses: supercharge/redis-github-action@1.1.0
with:
redis-version: 5
- name: Install dependencies
run: |
composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update
composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest
- name: Setup Problem Matches
run: |
echo "::add-matcher::${{ runner.tool_cache }}/php.json"
echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
- name: Execute tests
run: vendor/bin/phpunit

View File

@@ -0,0 +1,38 @@
<?php
$finder = Symfony\Component\Finder\Finder::create()
->notPath('bootstrap/*')
->notPath('storage/*')
->notPath('storage/*')
->notPath('resources/view/mail/*')
->in([
__DIR__ . '/src',
__DIR__ . '/tests',
])
->name('*.php')
->notName('*.blade.php')
->ignoreDotFiles(true)
->ignoreVCS(true);
return PhpCsFixer\Config::create()
->setRules([
'@PSR2' => true,
'array_syntax' => ['syntax' => 'short'],
'ordered_imports' => ['sortAlgorithm' => 'alpha'],
'no_unused_imports' => true,
'not_operator_with_successor_space' => true,
'trailing_comma_in_multiline_array' => true,
'phpdoc_scalar' => true,
'unary_operator_spaces' => true,
'binary_operator_spaces' => true,
'blank_line_before_statement' => [
'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'],
],
'phpdoc_single_line_var_spacing' => true,
'phpdoc_var_without_name' => true,
'method_argument_space' => [
'on_multiline' => 'ensure_fully_multiline',
'keep_multiple_spaces_after_comma' => true,
]
])
->setFinder($finder);

View File

@@ -0,0 +1,35 @@
# Changelog
All notable changes to `laravel-rate-limited-job-middleware` will be documented in this file
## 1.5.0 - 2020-11-27
- add support for PHP 8
## 1.4.1 - 2020-09-08
- add support for Laravel 8
## 1.4.0 - 2020-05-29
- add feature exponential back-off to release logic (#18)
## 1.3.0 - 2020-03-02
- add support for Laravel 7
## 1.2.0 - 2019-10-17
- add `releaseAfterRandomSeconds`
## 1.1.1 - 2019-10-14
- renamed parameter method `releaseAfterMinutes` (#13)
## 1.1.0 - 2019-10-14
- add release duration callback (#12)
## 1.0.0 - 2019-10-04
- initial release

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Spatie bvba <info@spatie.be>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,264 @@
# A job middleware to rate limit jobs
[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/laravel-rate-limited-job-middleware.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-rate-limited-job-middleware)
![run-tests](https://github.com/spatie/laravel-rate-limited-job-middleware/workflows/run-tests/badge.svg)
[![Total Downloads](https://img.shields.io/packagist/dt/spatie/laravel-rate-limited-job-middleware.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-rate-limited-job-middleware)
This package contains a [job middleware](https://laravel.com/docs/master/queues#job-middleware) that can rate limit jobs in Laravel apps.
## Support us
[<img src="https://github-ads.s3.eu-central-1.amazonaws.com/laravel-rate-limited-job-middleware.jpg?t=1" width="419px" />](https://spatie.be/github-ad-click/laravel-rate-limited-job-middleware)
We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).
## Installation
You can install the package via composer:
```bash
composer require spatie/laravel-rate-limited-job-middleware
```
This package requires Redis to be set up in your Laravel app.
## Usage
By default, the middleware will only allow 5 jobs to be executed per second. Any jobs that are not allowed will be released for 5 seconds.
To apply the middleware just add the `Spatie\RateLimitedMiddleware\RateLimited` to the middlewares of your job.
```php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Spatie\RateLimitedMiddleware\RateLimited;
class TestJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable;
public function handle()
{
// your job logic
}
public function middleware()
{
return [new RateLimited()];
}
}
```
### Configuring attempts
When using rate limiting, the number of attempts of your job may be hard to predict. Instead of using a fixed number of attempts, it's better to use [time based attempts](https://laravel.com/docs/master/queues#time-based-attempts).
You can add this to your job class:
```php
/*
* Determine the time at which the job should timeout.
*
*/
public function retryUntil() : \DateTime
{
return now()->addDay();
}
```
### Customizing the behaviour
You can customize all the behaviour. Here's an example where the middleware allows a maximum of 30 jobs to performed in a timespan off 60 seconds. Jobs that are not allowed will be released for 90 seconds.
```php
// in your job
public function middleware()
{
$rateLimitedMiddleware = (new RateLimited())
->allow(30)
->everySeconds(60)
->releaseAfterSeconds(90);
return [$rateLimitedMiddleware];
}
```
### Implementing Exponential Backoff
Often remote services such as APIs have rate limits or otherwise respond with a server error. Under these circumstances it makes sense to increment our delay before trying again. You can replace `releaseAfter` methods with `releaseAfterBackoff($this->attempts()` to use the default Rate Limiter interval of 5 seconds. Otherwise, you may chain the `releaseAfter` calls to adjust the backoff interval.
#### Example: `releaseAfterOneMinute()`
```php
// in your job
/**
* Attempt 1: Release after 60 seconds
* Attempt 2: Release after 180 seconds
* Attempt 3: Release after 420 seconds
* Attempt 4: Release after 900 seconds
*/
public function middleware()
{
$rateLimitedMiddleware = (new RateLimited())
->allow(30)
->everySeconds(60)
->releaseAfterOneMinute()
->releaseAfterBackoff($this->attempts());
return [$rateLimitedMiddleware];
}
```
#### Example: `releaseAfterSeconds()`
```php
// in your job
/**
* Attempt 1: Release after 5 seconds
* Attempt 2: Release after 15 seconds
* Attempt 3: Release after 35 seconds
* Attempt 4: Release after 75 seconds
*/
public function middleware()
{
$rateLimitedMiddleware = (new RateLimited())
->allow(30)
->everySeconds(60)
->releaseAfterSeconds(5)
->releaseAfterBackoff($this->attempts());
return [$rateLimitedMiddleware];
}
```
#### Example: Customize Backoff Rate
`releaseAfterBackoff()` accepts the rate multiplier as the second argument. By default, the multiplier is 2.
Below is an example of setting the rate to 3. You'll notice that as the attempts grow, the difference between a rate of 2 vs. a rate of 3 becomes significantly greater.
```php
// in your job
/**
* Attempt 1: Release after 5 seconds
* Attempt 2: Release after 20 seconds
* Attempt 3: Release after 65 seconds
* Attempt 4: Release after 200 seconds
*/
public function middleware()
{
$rateLimitedMiddleware = (new RateLimited())
->allow(30)
->everySeconds(60)
->releaseAfterBackoff($this->attempts(), 3);
return [$rateLimitedMiddleware];
}
```
### Customizing Redis
By default, the middleware will use the default Redis connection.
The default key that will be used in redis will be the name of the class that created the instance of the middleware. In most cases this will be name of job in which the middleware is applied. If this is not what you expect, you can use the `key` method to customize it.
Here's an example where a custom connection and custom key is used.
```php
// in your job
public function middleware()
{
$rateLimitedMiddleware = (new RateLimited())
->connection('my-custom-connection')
->key('my-custom-key');
return [$rateLimitedMiddleware];
}
```
### Conditionally applying the middleware
If you want to conditionally apply the middleware you can use the `enabled` method. If accepts a boolean that determines if the middleware should rate limit your job or not.
You can also pass a `Closure` to `enabled`. If it evaluates to a truthy value the middleware will be enable.
Here's a silly example where the rate limiting is only activated in January.
```php
// in your job
public function middleware()
{
$shouldRateLimitJobs = Carbon::now()->month === 1;
$rateLimitedMiddleware = (new RateLimited())
->enabled($shouldRateLimitJobs);
return [$rateLimitedMiddleware];
}
```
### Available methods.
These methods are available to be called on the middleware. Their names should be self-explanatory.
- `allow(int $allowedNumberOfJobsInTimeSpan)`
- `everySecond(int $timespanInSeconds = 1)`
- `everySeconds(int $timespanInSeconds)`
- `everyMinute(int $timespanInMinutes = 1)`
- `everyMinutes(int $timespanInMinutes)`
- `releaseAfterOneSecond()`
- `releaseAfterSeconds(int $releaseInSeconds)`
- `releaseAfterOneMinute()`
- `releaseAfterMinutes(int $releaseInMinutes)`
- `releaseAfterRandomSeconds(int $min = 1, int $max = 10)`
### Testing
``` bash
composer test
```
### Changelog
Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.
## Contributing
Please see [CONTRIBUTING](CONTRIBUTING.md) for details.
### Security
If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker.
## Postcardware
You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.
Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.
We publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).
## Credits
- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)
This code is heavily based on [the rate limiting example](https://laravel.com/docs/master/queues#job-middleware) found in the Laravel docs.
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

View File

@@ -0,0 +1,48 @@
{
"name": "spatie/laravel-rate-limited-job-middleware",
"description": "A middleware that can rate limit jobs",
"keywords": [
"spatie",
"laravel-rate-limited-job-middleware"
],
"homepage": "https://github.com/spatie/laravel-rate-limited-job-middleware",
"license": "MIT",
"authors": [
{
"name": "Freek Van der Herten",
"email": "freek@spatie.be",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"require": {
"php": "^7.3|^8.0",
"illuminate/redis": "^6.0|^7.0|^8.0"
},
"require-dev": {
"orchestra/testbench": "^4.0|^5.0|^6.0",
"phpunit/phpunit": "^8.2|^9.0",
"symfony/var-dumper": "^4.3|^5.0",
"mockery/mockery": "^1.4"
},
"autoload": {
"psr-4": {
"Spatie\\RateLimitedMiddleware\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Spatie\\RateLimitedMiddleware\\Tests\\": "tests"
}
},
"scripts": {
"test": "vendor/bin/phpunit",
"test-coverage": "vendor/bin/phpunit --coverage-html coverage"
},
"config": {
"sort-packages": true
},
"minimum-stability": "dev",
"prefer-stable": true
}

View File

@@ -0,0 +1,170 @@
<?php
namespace Spatie\RateLimitedMiddleware;
use Closure;
use Illuminate\Support\Facades\Redis;
class RateLimited
{
/** @var bool|\Closure */
protected $enabled = true;
/** @var string */
protected $connectionName = '';
/** @var string */
protected $key;
/** @var int */
protected $timeSpanInSeconds = 1;
/** @var int */
protected $allowedNumberOfJobsInTimeSpan = 5;
/** @var int */
protected $releaseInSeconds = 5;
/** @var array */
protected $releaseRandomSeconds = null;
public function __construct()
{
$calledByClass = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['class'];
$this->key($calledByClass);
}
/**
* @param bool|\Closure $enabled
*
* @return $this
*/
public function enabled($enabled = true)
{
$this->enabled = $enabled;
return $this;
}
public function connectionName(string $connectionName)
{
$this->connectionName = $connectionName;
return $this;
}
public function key(string $key)
{
$this->key = $key;
return $this;
}
public function timespanInSeconds(int $timespanInSeconds)
{
$this->timeSpanInSeconds = $timespanInSeconds;
return $this;
}
public function allow(int $allowedNumberOfJobsInTimeSpan)
{
$this->allowedNumberOfJobsInTimeSpan = $allowedNumberOfJobsInTimeSpan;
return $this;
}
public function everySecond(int $timespanInSeconds = 1)
{
$this->timeSpanInSeconds = $timespanInSeconds;
return $this;
}
public function everySeconds(int $timespanInSeconds)
{
return $this->everySecond($timespanInSeconds);
}
public function everyMinute(int $timespanInMinutes = 1)
{
return $this->everySecond($timespanInMinutes * 60);
}
public function everyMinutes(int $timespanInMinutes)
{
return $this->everySecond($timespanInMinutes * 60);
}
public function releaseAfterOneSecond()
{
return $this->releaseAfterSeconds(1);
}
public function releaseAfterSeconds(int $releaseInSeconds)
{
$this->releaseInSeconds = $releaseInSeconds;
return $this;
}
public function releaseAfterOneMinute()
{
return $this->releaseAfterMinutes(1);
}
public function releaseAfterMinutes(int $releaseInMinutes)
{
return $this->releaseAfterSeconds($releaseInMinutes * 60);
}
public function releaseAfterRandomSeconds(int $min = 1, int $max = 10)
{
$this->releaseRandomSeconds = [$min, $max];
return $this;
}
public function releaseAfterBackoff(int $attemptedCount, int $backoffRate = 2)
{
$releaseAfterSeconds = 0;
$interval = $this->releaseInSeconds;
for ($attempt = 0; $attempt <= $attemptedCount; $attempt++) {
$releaseAfterSeconds += $interval * pow($backoffRate, $attempt);
}
return $this->releaseAfterSeconds($releaseAfterSeconds);
}
protected function releaseDuration(): int
{
if (! is_null($this->releaseRandomSeconds)) {
return random_int(...$this->releaseRandomSeconds);
}
return $this->releaseInSeconds;
}
public function handle($job, $next)
{
if ($this->enabled instanceof Closure) {
$this->enabled = (bool) $this->enabled();
}
if (! $this->enabled) {
return $next($job);
}
Redis::connection($this->connectionName)
->throttle($this->key)
->block(0)
->allow($this->allowedNumberOfJobsInTimeSpan)
->every($this->timeSpanInSeconds)
->then(function () use ($job, $next) {
$next($job);
}, function () use ($job) {
$job->release($this->releaseDuration());
});
}
}