:elephant: A Circuit Breaker pattern implementation for PHP applications.
:elephant: A Circuit Breaker pattern implementation for PHP applications.
Ganesha
Ganesha is PHP implementation of Circuit Breaker pattern which has multi strategies to avoid cascading failures and supports various storages to record statistics.
This is one of the Circuit Breaker implementations in PHP that is actively developed, production-ready, well-tested and well-documented. :muscle: You can easily integrate Ganesha into your existing code base, as Ganesha provides just simple interfaces and Guzzle Middleware behaves transparency.
Here is an example which shows you how Ganesha behaves when a failure occurs.
It is easily executable. All you need is Docker.
# Install Composer
$ curl -sS https://getcomposer.org/installer | php
# Run the Composer command to install the latest version of Ganesha
$ php composer.phar require ackintosh/ganeshaGanesha provides following simple interfaces. Each method receives a string (named $service in example) to identify the service. $service will be the service name of the API, the endpoint name, etc. Please remember that Ganesha detects system failure for each $service.
$ganesha->isAvailable($service);
$ganesha->success($service);
$ganesha->failure($service);…(martinfowler.com : CircuitBreaker)
Ganesha follows the states and transitions described in the article faithfully. $ganesha->isAvailable() returns true if the circuit states on Closed, otherwise it returns false.
Open the event Ganesha::EVENT_TRIPPED is triggeredClosed the event Ganesha::EVENT_CALMED_DOWN is triggered…If disabled, Ganesha keeps to record success/failure statistics, but Ganesha doesn't trip even if the failure count reached to a threshold.
// Ganesha with Count strategy(threshold `3`).
// $ganesha = Ackintosh\Ganesha\Builder::withCountStrategy() ...
// Disable
Ackintosh\Ganesha::disable();
// Although the failure is recorded to storage,
$ganesha->failure($service);
$ganesha->failure($service);
$ganesha->failure($service);
// Ganesha does not trip and Ganesha::isAvailable() returns true.
var_dump($ganesha->isAvailable($service));
// bool(true)Resets the statistics saved in a storage.
$ganesha = Ackintosh\Ganesha\Builder::withRateStrategy()
// ...
->build();
$ganesha->reset();
Ganesha has two strategies which avoids cascading failures.
…Note about "time window": The Storage Adapter implements either SlidingTimeWindow or TumblingTimeWindow. The difference of the implementation comes from constraints of the storage functionalities.
The details to help us understand visually is shown below:
(quoted from Introduction to Stream Analytics windowing functions - Microsoft Azure)
timeWindow.The details to help us understand visually is shown below:
(quoted from Introduction to Stream Analytics windowing functions - Microsoft Azure)
If you prefer the Count strategy use Builder::withCountStrategy() to build an instance.
…The APCu adapter requires the APCu extension.
$adapter = new Ackintosh\Ganesha\Storage\Adapter\Apcu();
$ganesha = Ackintosh\Ganesha\Builder::withRateStrategy()
->adapter($adapter)
// ... (omitted) ...
->build();Note: APCu is internal to each server/instance, not pooled like most Memcache and Redis setups. Each worker's circuit breaker will activate or reset individually, and failure thresholds should be set lower to compensate.
Redis adapter requires phpredis or Predis client instance. The example below is using phpredis.
$redis = new \Redis();
$redis->connect('localhost');
$adapter = new Ackintosh\Ganesha\Storage\Adapter\Redis($redis);
$ganesha = Ackintosh\Ganesha\Builder::withRateStrategy()
->adapter($adapter)
// ... (omitted) ...
->build();Memcached adapter requires memcached (NOT memcache) extension.
$memcached = new \Memcached();
$memcached->addServer('localhost', 11211);
$adapter = new Ackintosh\Ganesha\Storage\Adapter\Memcached($memcached);
$ganesha = Ackintosh\Ganesha\Builder::withRateStrategy()
->adapter($adapter)
// ... (omitted) ...
->build();MongoDB adapter requires mongodb extension.
$manager = new \MongoDB\Driver\Manager('mongodb://localhost:27017/');
$adapter = new Ackintosh\Ganesha\Storage\Adapter\MongoDB($manager, 'dbName', 'collectionName');
$ganesha = Ackintosh\Ganesha\Builder::withRateStrategy()
->adapter($adapter)
// ... (omitted) ...
->build();If you want to customize the keys to be used when storing circuit breaker information, set an instance which implements StorageKeysInterface.
class YourStorageKeys implements StorageKeysInterface
{
public function prefix()
{
return 'your_prefix_';
}
// ... (omitted) ...
}
$ganesha = Ackintosh\Ganesha\Builder::withRateStrategy()
// The keys which will stored by Ganesha to the storage you specified via `adapter`
// will be prefixed with `your_prefix_`.
->storageKeys(new YourStorageKeys())
// ... (omitted) ...
->build();If you are using Guzzle (v6 or higher), Guzzle Middleware powered by Ganesha makes it easy to integrate Circuit Breaker to your existing code base.
…$service?As documented in Usage, Ganesha detects failures for each $service. Below, We will show you how Guzzle Middleware determine $service and how we specify $service explicitly.
By default, the host name is used as $service.
// In the example above, `api.example.com` is used as `$service`.
$client->get('http://api.example.com/awesome_resource');You can also specify $service via a option passed to client, or request header. If both are specified, the option value takes precedence.
…Alternatively, you can apply your own rules by implementing a class that implements the ServiceNameExtractorInterface.
…By default, if the next handler promise is fulfilled ganesha will consider it a success, and a failure if it is rejected.
You can implement your own rules on fulfilled response by passing an implementation of FailureDetectorInterface to the middleware.
use Ackintosh\Ganesha\GuzzleMiddleware\FailureDetectorInterface;
use Psr\Http\Message\ResponseInterface;
class HttpStatusFailureDetector implements FailureDetectorInterface
{
public function isFailureResponse(ResponseInterface $response) : bool
{
return in_array($response->getStatusCode(), [503, 504], true);
}
}
// ---
$ganesha = Builder::withRateStrategy()
// ...
->build();
$middleware = new GuzzleMiddleware(
$ganesha,
// Pass the failure detector to the GuzzleMiddleware constructor.
failureDetector: new HttpStatusFailureDetector()
);PHP client generated by OpenAPI Generator is using Guzzle as HTTP client and as we mentioned as Ganesha :heart: Guzzle, Guzzle Middleware powered by Ganesha is ready. So it is easily possible to integrate Ganesha and the PHP client generated by OpenAPI Generator in a smart way as below.
// For details on how to build middleware please see https://github.com/ackintosh/ganesha#ganesha-heart-guzzle
$middleware = new GuzzleMiddleware($ganesha);
// Set the middleware to HTTP client.
$handlers = HandlerStack::create();
$handlers->push($middleware);
$client = new Client(['handler' => $handlers]);
// Just pass the HTTP client to the constructor of API class.
$api = new PetApi($client);
try {
// Ganesha is working in the shadows! The result of api call is monitored by Ganesha.
$api->getPetById(123);
} catch (RejectedException $e) {
awesomeErrorHandling($e);
}If you are using Symfony HttpClient, GaneshaHttpClient makes it easy to integrate Circuit Breaker to your existing code base.
…$service?As documented in Usage, Ganesha detects failures for each $service. Below, We will show you how GaneshaHttpClient determine $service and how we specify $service explicitly.
By default, the host name is used as $service.
// In the example above, `api.example.com` is used as `$No open issues yet, or sync has not completed.