8000 [RFC] Introduce a RateLimiter component by wouterj · Pull Request #37546 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[RFC] Introduce a RateLimiter component #37546

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

Merged
merged 1 commit into from
Sep 16, 2020
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Notifier\Notifier;
use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;
use Symfony\Component\RateLimiter\TokenBucketLimiter;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Validator\Validation;
Expand Down Expand Up @@ -134,6 +135,7 @@ public function getConfigTreeBuilder()
$this->addMailerSection($rootNode);
$this->addSecretsSection($rootNode);
$this->addNotifierSection($rootNode);
$this->addRateLimiterSection($rootNode);

return $treeBuilder;
}
Expand Down Expand Up @@ -1707,4 +1709,50 @@ private function addNotifierSection(ArrayNodeDefinition $rootNode)
->end()
;
}

private function addRateLimiterSection(ArrayNodeDefinition $rootNode)
{
$rootNode
->children()
->arrayNode('rate_limiter')
->info('Rate limiter configuration')
->{!class_exists(FullStack::class) && class_exists(TokenBucketLimiter::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->fixXmlConfig('limiter')
->beforeNormalization()
->ifTrue(function ($v) { return \is_array($v) && !isset($v['limiters']) && !isset($v['limiter']); })
->then(function (array $v) {
$newV = [
'enabled' => $v['enabled'],
];
unset($v['enabled']);

$newV['limiters'] = $v;

return $newV;
})
->end()
->children()
->arrayNode('limiters')
->useAttributeAsKey('name')
->arrayPrototype()
->children()
->scalarNode('lock')->defaultValue('lock.factory')->end()
->scalarNode('storage')->defaultValue('cache.app')->end()
->scalarNode('strategy')->isRequired()->end()
->integerNode('limit')->isRequired()->end()
->scalarNode('interval')->end()
->arrayNode('rate')
->children()
->scalarNode('interval')->isRequired()->end()
->integerNode('amount')->defaultValue(1)->end()
->end()
->end()
->end()
->end()
->end()
->end()
->end()
->end()
;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,9 @@
use Symfony\Component\PropertyInfo\PropertyReadInfoExtractorInterface;
use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
use Symfony\Component\PropertyInfo\PropertyWriteInfoExtractorInterface;
use Symfony\Component\RateLimiter\Limiter;
use Symfony\Component\RateLimiter\LimiterInterface;
use Symfony\Component\RateLimiter\Storage\CacheStorage;
use Symfony\Component\Routing\Loader\AnnotationDirectoryLoader;
use Symfony\Component\Routing\Loader\AnnotationFileLoader;
use Symfony\Component\Security\Core\Security;
Expand Down Expand Up @@ -173,6 +176,7 @@ class FrameworkExtension extends Extension
private $mailerConfigEnabled = false;
private $httpClientConfigEnabled = false;
private $notifierConfigEnabled = false;
private $lockConfigEnabled = false;

/**
* Responds to the app.config configuration parameter.
Expand Down Expand Up @@ -405,10 +409,18 @@ public function load(array $configs, ContainerBuilder $container)
$this->registerPropertyInfoConfiguration($container, $loader);
}

if ($this->isConfigEnabled($container, $config['lock'])) {
if ($this->lockConfigEnabled = $this->isConfigEnabled($container, $config['lock'])) {
$this->registerLockConfiguration($config['lock'], $container, $loader);
}

if ($this->isConfigEnabled($container, $config['rate_limiter'])) {
if (!interface_exists(LimiterInterface::class)) {
throw new LogicException('Rate limiter support cannot be enabled as the RateLimiter component is not installed. Try running "composer require symfony/rate-limiter".');
}

$this->registerRateLimiterConfiguration($config['rate_limiter'], $container, $loader);
}

if ($this->isConfigEnabled($container, $config['web_link'])) {
if (!class_exists(HttpHeaderSerializer::class)) {
throw new LogicException('WebLink support cannot be enabled as the WebLink component is not installed. Try running "composer require symfony/weblink".');
Expand Down Expand Up @@ -2170,6 +2182,48 @@ private function registerNotifierConfiguration(array $config, ContainerBuilder $
}
}

private function registerRateLimiterConfiguration(array $config, ContainerBuilder $container, PhpFileLoader $loader)
{
if (!$this->lockConfigEnabled) {
throw new LogicException('Rate limiter support cannot be enabled without enabling the Lock component.');
}

$loader->load('rate_limiter.php');

$locks = [];
$storages = [];
foreach ($config['limiters'] as $name => $limiterConfig) {
$limiter = $container->setDefinition($limiterId = 'limiter.'.$name, new ChildDefinition('limiter'));

if (!isset($locks[$limiterConfig['lock']])) {
$locks[$limiterConfig['lock']] = new Reference($limiterConfig['lock']);
}
$limiter->addArgument($locks[$limiterConfig['lock']]);
unset($limiterConfig['lock']);

if (!isset($storages[$limiterConfig['storage']])) {
$storageId = $limiterConfig['storage'];
// cache pools are configured by the FrameworkBundle, so they
// exists in the scoped ContainerBuilder provided to this method
if ($container->has($storageId)) {
if ($container->findDefinition($storageId)->hasTag('cache.pool')) {
$container->register('limiter.storage.'.$storageId, CacheStorage::class)->addArgument(new Reference($storageId));
$storageId = 'limiter.storage.'.$storageId;
}
}

$storages[$limiterConfig['storage']] = new Reference($storageId);
}
$limiter->replaceArgument(1, $storages[$limiterConfig['storage']]);
unset($limiterConfig['storage']);

$limiterConfig['id'] = $name;
$limiter->replaceArgument(0, $limiterConfig);

$container->registerAliasForArgument($limiterId, Limiter::class, $name.'.limiter');
}
}

private function resolveTrustedHeaders(array $headers): int
{
$trustedHeaders = 0;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Component\RateLimiter\Limiter;

return static function (ContainerConfigurator $container) {
$container->services()
->set('limiter', Limiter::class)
->abstract()
->args([
abstract_arg('config'),
abstract_arg('storage'),
])
;
};
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
<xsd:element name="http-client" type="http_client" minOccurs="0" maxOccurs="1" />
<xsd:element name="mailer" type="mailer" minOccurs="0" maxOccurs="1" />
<xsd:element name="http-cache" type="http_cache" minOccurs="0" maxOccurs="1" />
<xsd:element name="rate-limiter" type="rate_limiter" minOccurs="0" maxOccurs="1" />
</xsd:choice>

<xsd:attribute name="http-method-override" type="xsd:boolean" />
Expand Down Expand Up @@ -634,4 +635,30 @@
<xsd:enumeration value="full" />
</xsd:restriction>
</xsd:simpleType>

<xsd:complexType name="rate_limiter">
<xsd:sequence>
<xsd:element name="limiter" type="rate_limiter_limiter" minOccurs="0" maxOccurs="unbounded" />
</xsd:sequence>
<xsd:attribute name="enabled" type="xsd:boolean" />
<xsd:attribute name="max-host-connections" type="xsd:integer" />
<xsd:attribute name="mock-response-factory" type="xsd:string" />
</xsd:complexType>

<xsd:complexType name="rate_limiter_limiter">
<xsd:sequence>
<xsd:element name="rate" type="rate_limiter_rate" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="lock" type="xsd:string" />
<xsd:attribute name="storage" type="xsd:string" />
<xsd:attribute name="strategy" type="xsd:string" />
<xsd:attribute name="limit" type="xsd:int" />
<xsd:attribute name="interval" type="xsd:string" />
</xsd:complexType>

<xsd:complexType name="rate_limiter_rate">
<xsd:attribute name="interval" type="xsd:string" />
<xsd:attribute name="amount" type="xsd:int" />
</xsd:complexType>
</xsd:schema>
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,10 @@ class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphor
'debug' => '%kernel.debug%',
'private_headers' => [],
],
'rate_limiter' => [
'enabled' => false,
'limiters' => [],
],
];
}
}
7 changes: 4 additions & 3 deletions src/Symfony/Component/Lock/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ CHANGELOG

* `MongoDbStore` does not implement `BlockingStoreInterface` anymore, typehint against `PersistingStoreInterface` instead.
* added support for shared locks
* added `NoLock`

5.1.0
-----
Expand All @@ -25,10 +26,10 @@ CHANGELOG
* added InvalidTtlException
* deprecated `StoreInterface` in favor of `BlockingStoreInterface` and `PersistingStoreInterface`
* `Factory` is deprecated, use `LockFactory` instead
* `StoreFactory::createStore` allows PDO and Zookeeper DSN.
* deprecated services `lock.store.flock`, `lock.store.semaphore`, `lock.store.memcached.abstract` and `lock.store.redis.abstract`,
* `StoreFactory::createStore` allows PDO and Zookeeper DSN.
* deprecated services `lock.store.flock`, `lock.store.semaphore`, `lock.store.memcached.abstract` and `lock.store.redis.abstract`,
use `StoreFactory::createStore` instead.

4.2.0
-----

Expand Down
51 changes: 51 additions & 0 deletions src/Symfony/Component/Lock/NoLock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Lock;

/**
* A non locking lock.
*
* This can be used to disable locking in classes
* requiring a lock.
*
* @author Wouter de Jong <wouter@wouterj.nl>
*/
final class NoLock implements LockInterface
{
public function acquire(bool $blocking = false): bool
{
return true;
}

public function refresh(float $ttl = null)
{
}

public function isAcquired(): bool
{
return true;
}

public function release()
{
}

public function isExpired(): bool
{
return false;
}

public function getRemainingLifetime(): ?float
{
return null;
}
}
4 changes: 4 additions & 0 deletions src/Symfony/Component/RateLimiter/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
3 changes: 3 additions & 0 deletions src/Symfony/Component/RateLimiter/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
composer.lock
phpunit.xml
vendor/
7 changes: 7 additions & 0 deletions src/Symfony/Component/RateLimiter/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

5.2.0
-----

* added the component
47 changes: 47 additions & 0 deletions src/Symfony/Component/RateLimiter/CompoundLimiter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\RateLimiter;

/**
* @author Wouter de Jong <wouter@wouterj.nl>
*
* @experimental in 5.2
*/
final class CompoundLimiter implements LimiterInterface
{
private $limiters;

/**
* @param LimiterInterface[] $limiters
*/
public function __construct(array $limiters)
{
$this->limiters = $limiters;
}

public function consume(int $tokens = 1): bool
{
$allow = true;
foreach ($this->limiters as $limiter) {
$allow = $limiter->consume($tokens) && $allow;
}

return $allow;
}

public function reset(): void
{
foreach ($this->limiters as $limiter) {
$limiter->reset();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\RateLimiter\Exception;

/**
* @author Wouter de Jong <wouter@wouterj.nl>
*
* @experimental in 5.2
*/
class MaxWaitDurationExceededException extends \RuntimeException
{
}
Loading
0