1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace JVelasco\CircuitBreaker\APCu; |
4
|
|
|
|
5
|
|
|
use JVelasco\CircuitBreaker\AvailabilityStrategy; |
6
|
|
|
use JVelasco\CircuitBreaker\AvailabilityStrategy\Storage; |
7
|
|
|
use \JVelasco\CircuitBreaker\FailuresCounterStorage; |
8
|
|
|
|
9
|
|
|
final class SharedStorage implements FailuresCounterStorage, Storage |
10
|
|
|
{ |
11
|
|
|
private $failuresCounterPrefix; |
12
|
|
|
|
13
|
7 |
|
public function __construct(string $failuresCounterPrefix = "cb_failures") |
14
|
|
|
{ |
15
|
7 |
|
$this->failuresCounterPrefix = $failuresCounterPrefix; |
16
|
7 |
|
} |
17
|
|
|
|
18
|
4 |
|
public function incrementFailures(string $serviceName) |
19
|
|
|
{ |
20
|
4 |
|
apcu_inc($this->counterKeyForService($serviceName)); |
21
|
4 |
|
} |
22
|
|
|
|
23
|
3 |
|
public function decrementFailures(string $serviceName) |
24
|
|
|
{ |
25
|
3 |
|
$counterKey = $this->counterKeyForService($serviceName); |
26
|
3 |
|
$newValue = apcu_dec($counterKey); |
27
|
|
|
|
28
|
3 |
|
if ($newValue < 0) { |
29
|
1 |
|
apcu_store($counterKey, 0); |
30
|
|
|
} |
31
|
3 |
|
} |
32
|
|
|
|
33
|
3 |
|
public function numberOfFailures(string $serviceName): int |
34
|
|
|
{ |
35
|
3 |
|
return apcu_fetch($this->counterKeyForService($serviceName)); |
36
|
|
|
} |
37
|
|
|
|
38
|
1 |
|
public function saveStrategyData(AvailabilityStrategy $strategy, string $key, string $value) |
39
|
|
|
{ |
40
|
1 |
|
apcu_store($this->keyForStrategyData($strategy, $key), $value); |
41
|
1 |
|
} |
42
|
|
|
|
43
|
2 |
|
public function getStrategyData(AvailabilityStrategy $strategy, string $key): string |
44
|
|
|
{ |
45
|
2 |
|
return apcu_fetch($this->keyForStrategyData($strategy, $key)); |
46
|
|
|
} |
47
|
|
|
|
48
|
1 |
|
public function resetFailuresCounter(string $serviceName) |
49
|
|
|
{ |
50
|
1 |
|
apcu_store($this->counterKeyForService($serviceName), 0); |
51
|
1 |
|
} |
52
|
|
|
|
53
|
6 |
|
private function counterKeyForService(string $serviceName): string |
54
|
|
|
{ |
55
|
6 |
|
return sprintf("%s.%s", $this->failuresCounterPrefix, $serviceName); |
56
|
|
|
} |
57
|
|
|
|
58
|
2 |
|
private function keyForStrategyData(AvailabilityStrategy $strategy, string $key): string |
59
|
|
|
{ |
60
|
2 |
|
return sprintf("%s.%s", $strategy->getId(), $key); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|