|
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
|
5 |
|
public function __construct(string $failuresCounterPrefix = "cb_failures") |
|
14
|
|
|
{ |
|
15
|
5 |
|
$this->failuresCounterPrefix = $failuresCounterPrefix; |
|
16
|
5 |
|
} |
|
17
|
|
|
|
|
18
|
2 |
|
public function incrementFailures(string $serviceName) |
|
19
|
|
|
{ |
|
20
|
2 |
|
apcu_inc($this->counterKeyForService($serviceName)); |
|
21
|
2 |
|
} |
|
22
|
|
|
|
|
23
|
2 |
|
public function decrementFailures(string $serviceName) |
|
24
|
|
|
{ |
|
25
|
2 |
|
$counterKey = $this->counterKeyForService($serviceName); |
|
26
|
2 |
|
$newValue = apcu_dec($counterKey); |
|
27
|
|
|
|
|
28
|
2 |
|
if ($newValue < 0) { |
|
29
|
1 |
|
apcu_store($counterKey, 0); |
|
30
|
|
|
} |
|
31
|
2 |
|
} |
|
32
|
|
|
|
|
33
|
1 |
|
public function numberOfFailures(string $serviceName): int |
|
34
|
|
|
{ |
|
35
|
1 |
|
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
|
1 |
|
public function getStrategyData(AvailabilityStrategy $strategy, string $key): string |
|
44
|
|
|
{ |
|
45
|
1 |
|
return apcu_fetch($this->keyForStrategyData($strategy, $key)); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
4 |
|
private function counterKeyForService(string $serviceName): string |
|
49
|
|
|
{ |
|
50
|
4 |
|
return sprintf("%s.%s", $this->failuresCounterPrefix, $serviceName); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
1 |
|
private function keyForStrategyData(AvailabilityStrategy $strategy, string $key): string |
|
54
|
|
|
{ |
|
55
|
1 |
|
return sprintf("%s.%s", $strategy->getId(), $key); |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
|