1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace JVelasco\CircuitBreaker\Adapters; |
4
|
|
|
|
5
|
|
|
use JVelasco\CircuitBreaker\AvailabilityStrategy; |
6
|
|
|
use JVelasco\CircuitBreaker\AvailabilityStrategy\Storage; |
7
|
|
|
use \JVelasco\CircuitBreaker\FailuresCounterStorage; |
8
|
|
|
|
9
|
|
|
final class APCuStorage 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( |
39
|
|
|
AvailabilityStrategy $strategy, |
40
|
|
|
string $serviceName, |
41
|
|
|
string $key, |
42
|
|
|
string $value |
43
|
|
|
) { |
44
|
1 |
|
apcu_store($this->keyForStrategyData($strategy, $serviceName, $key), $value); |
45
|
1 |
|
} |
46
|
|
|
|
47
|
2 |
|
public function getStrategyData( |
48
|
|
|
AvailabilityStrategy $strategy, |
49
|
|
|
string $serviceName, |
50
|
|
|
string $key |
51
|
|
|
): string { |
52
|
2 |
|
return apcu_fetch($this->keyForStrategyData($strategy, $serviceName, $key)); |
53
|
|
|
} |
54
|
|
|
|
55
|
1 |
|
public function resetFailuresCounter(string $serviceName) |
56
|
|
|
{ |
57
|
1 |
|
apcu_store($this->counterKeyForService($serviceName), 0); |
58
|
1 |
|
} |
59
|
|
|
|
60
|
6 |
|
private function counterKeyForService(string $serviceName): string |
61
|
|
|
{ |
62
|
6 |
|
return sprintf("%s.%s", $this->failuresCounterPrefix, $serviceName); |
63
|
|
|
} |
64
|
|
|
|
65
|
2 |
|
private function keyForStrategyData( |
66
|
|
|
AvailabilityStrategy $strategy, |
67
|
|
|
string $serviceName, |
68
|
|
|
string $key |
69
|
|
|
): string { |
70
|
2 |
|
return implode(".", [$strategy->getId(), $serviceName, $key]); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|