1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace FrancescoMalatesta\LaravelCircuitBreaker\Manager; |
4
|
|
|
|
5
|
|
|
use FrancescoMalatesta\LaravelCircuitBreaker\Events\AttemptFailed; |
6
|
|
|
use FrancescoMalatesta\LaravelCircuitBreaker\Events\ServiceFailed; |
7
|
|
|
use FrancescoMalatesta\LaravelCircuitBreaker\Events\ServiceRestored; |
8
|
|
|
use FrancescoMalatesta\LaravelCircuitBreaker\Service\ServiceOptionsResolver; |
9
|
|
|
use Illuminate\Contracts\Events\Dispatcher as EventDispatcher; |
10
|
|
|
use FrancescoMalatesta\LaravelCircuitBreaker\Store\CircuitBreakerStoreInterface; |
11
|
|
|
use Illuminate\Config\Repository as Config; |
12
|
|
|
|
13
|
|
|
class CircuitBreakerManager |
14
|
|
|
{ |
15
|
|
|
/** @var CircuitBreakerStoreInterface */ |
16
|
|
|
private $store; |
17
|
|
|
|
18
|
|
|
/** @var EventDispatcher */ |
19
|
|
|
private $dispatcher; |
20
|
|
|
|
21
|
|
|
/** @var ServiceOptionsResolver */ |
22
|
|
|
private $serviceOptionsResolver; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* CircuitBreakerManager constructor. |
26
|
|
|
* |
27
|
|
|
* @param CircuitBreakerStoreInterface $store |
28
|
|
|
* @param EventDispatcher $dispatcher |
29
|
|
|
* @param ServiceOptionsResolver $serviceOptionsResolver |
30
|
|
|
*/ |
31
|
|
|
public function __construct( |
32
|
|
|
CircuitBreakerStoreInterface $store, |
33
|
|
|
EventDispatcher $dispatcher, |
34
|
|
|
ServiceOptionsResolver $serviceOptionsResolver |
35
|
|
|
) { |
36
|
|
|
$this->store = $store; |
37
|
|
|
$this->dispatcher = $dispatcher; |
38
|
|
|
$this->serviceOptionsResolver = $serviceOptionsResolver; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function isAvailable(string $identifier) : bool |
42
|
|
|
{ |
43
|
|
|
return $this->store->isAvailable($identifier); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function reportFailure(string $identifier) : void |
47
|
|
|
{ |
48
|
|
|
$wasAvailable = $this->isAvailable($identifier); |
49
|
|
|
|
50
|
|
|
$options = $this->serviceOptionsResolver->getOptionsFor($identifier); |
51
|
|
|
|
52
|
|
|
$this->store->reportFailure( |
53
|
|
|
$identifier, |
54
|
|
|
$options->getAttemptsThreshold(), |
55
|
|
|
$options->getAttemptsTtl(), |
56
|
|
|
$options->getFailureTtl() |
57
|
|
|
); |
58
|
|
|
|
59
|
|
|
$this->dispatcher->dispatch(new AttemptFailed($identifier)); |
60
|
|
|
|
61
|
|
|
if ($wasAvailable && !$this->isAvailable($identifier)) { |
62
|
|
|
$this->dispatcher->dispatch(new ServiceFailed($identifier)); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
public function reportSuccess(string $identifier) : void |
67
|
|
|
{ |
68
|
|
|
$this->store->reportSuccess($identifier); |
69
|
|
|
$this->dispatcher->dispatch(new ServiceRestored($identifier)); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|