Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
86.36% |
19 / 22 |
|
50.00% |
2 / 4 |
CRAP | |
0.00% |
0 / 1 |
CacheQueryServiceLagStore | |
86.36% |
19 / 22 |
|
50.00% |
2 / 4 |
11.31 | |
0.00% |
0 / 1 |
__construct | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
3 | |||
getLag | |
87.50% |
7 / 8 |
|
0.00% |
0 / 1 |
3.02 | |||
updateLag | |
77.78% |
7 / 9 |
|
0.00% |
0 / 1 |
4.18 | |||
makeCacheKey | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 |
1 | <?php |
2 | |
3 | namespace WikidataOrg\QueryServiceLag; |
4 | |
5 | use WANObjectCache; |
6 | |
7 | /** |
8 | * Manages retrieving and updating query service lag data in cache |
9 | */ |
10 | class CacheQueryServiceLagStore { |
11 | |
12 | private const CACHE_CLASS = 'CacheQueryServiceLagStore'; |
13 | private const CACHE_KEY_LAG = 'lag'; |
14 | |
15 | /** @var WANObjectCache */ |
16 | private $cache; |
17 | |
18 | /** @var int */ |
19 | private $ttl; |
20 | |
21 | /** |
22 | * @param WANObjectCache $cache |
23 | * @param int $ttl positive time-to-live in seconds for cached lag |
24 | */ |
25 | public function __construct( |
26 | WANObjectCache $cache, |
27 | $ttl |
28 | ) { |
29 | if ( !is_int( $ttl ) || $ttl <= 0 ) { |
30 | throw new \InvalidArgumentException( '$ttl cannot be less or equal to 0' ); |
31 | } |
32 | |
33 | $this->cache = $cache; |
34 | $this->ttl = $ttl; |
35 | } |
36 | |
37 | /** |
38 | * Retrieves lag from underlying cache medium |
39 | * |
40 | * @return array|null |
41 | */ |
42 | public function getLag() { |
43 | $lagData = $this->cache->get( $this->makeCacheKey( self::CACHE_KEY_LAG ) ); |
44 | |
45 | // No cached value |
46 | if ( $lagData === false ) { |
47 | return null; |
48 | } |
49 | |
50 | // Back compat for before server was also stored in cache |
51 | if ( strstr( $lagData, ' ' ) === false ) { |
52 | return [ 'unknown', $lagData ]; |
53 | } |
54 | |
55 | // Current storage is server and lag value separated by a space |
56 | $values = explode( ' ', $lagData ); |
57 | $values[1] = (int)$values[1]; |
58 | return $values; |
59 | } |
60 | |
61 | /** |
62 | * Updates stored lag in cache. |
63 | * |
64 | * @param string $server |
65 | * @param int $lag |
66 | */ |
67 | public function updateLag( $server, $lag ) { |
68 | if ( !is_string( $server ) ) { |
69 | throw new \InvalidArgumentException( '$server must be string.' ); |
70 | } |
71 | if ( is_int( $lag ) && $lag < 0 ) { |
72 | throw new \InvalidArgumentException( '$lag must be null or a non-negative integer.' ); |
73 | } |
74 | |
75 | $this->cache->set( |
76 | $this->makeCacheKey( self::CACHE_KEY_LAG ), |
77 | $server . ' ' . $lag, |
78 | $this->ttl |
79 | ); |
80 | } |
81 | |
82 | /** |
83 | * @param string $type |
84 | * @return string |
85 | */ |
86 | private function makeCacheKey( $type ) { |
87 | return $this->cache->makeKey( self::CACHE_CLASS, $type ); |
88 | } |
89 | |
90 | } |