Merge "Change 1.26 to 1.27, mostly in doc comments"
[lhc/web/wiklou.git] / includes / objectcache / MultiWriteBagOStuff.php
1 <?php
2 /**
3 * Wrapper for object caching in different caches.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Cache
22 */
23
24 /**
25 * A cache class that replicates all writes to multiple child caches. Reads
26 * are implemented by reading from the caches in the order they are given in
27 * the configuration until a cache gives a positive result.
28 *
29 * @ingroup Cache
30 */
31 class MultiWriteBagOStuff extends BagOStuff {
32 /** @var BagOStuff[] */
33 protected $caches;
34 /** @var bool Use async secondary writes */
35 protected $asyncWrites = false;
36
37 /** Idiom for "write to all backends" */
38 const ALL = INF;
39
40 const UPGRADE_TTL = 3600; // TTL when a key is copied to a higher cache tier
41
42 /**
43 * $params include:
44 * - caches: This should have a numbered array of cache parameter
45 * structures, in the style required by $wgObjectCaches. See
46 * the documentation of $wgObjectCaches for more detail.
47 * BagOStuff objects can also be used as values.
48 * The first cache is the primary one, being the first to
49 * be read in the fallback chain. Writes happen to all stores
50 * in the order they are defined. However, lock()/unlock() calls
51 * only use the primary store.
52 * - replication: Either 'sync' or 'async'. This controls whether writes to
53 * secondary stores are deferred when possible. Async writes
54 * require the HHVM register_postsend_function() function.
55 * Async writes can increase the chance of some race conditions
56 * or cause keys to expire seconds later than expected. It is
57 * safe to use for modules when cached values: are immutable,
58 * invalidation uses logical TTLs, invalidation uses etag/timestamp
59 * validation against the DB, or merge() is used to handle races.
60 *
61 * @param array $params
62 * @throws InvalidArgumentException
63 */
64 public function __construct( $params ) {
65 parent::__construct( $params );
66
67 if ( empty( $params['caches'] ) || !is_array( $params['caches'] ) ) {
68 throw new InvalidArgumentException(
69 __METHOD__ . ': "caches" parameter must be an array of caches'
70 );
71 }
72
73 $this->caches = array();
74 foreach ( $params['caches'] as $cacheInfo ) {
75 $this->caches[] = ( $cacheInfo instanceof BagOStuff )
76 ? $cacheInfo
77 : ObjectCache::newFromParams( $cacheInfo );
78 }
79
80 $this->asyncWrites = isset( $params['replication'] ) && $params['replication'] === 'async';
81 }
82
83 /**
84 * @param bool $debug
85 */
86 public function setDebug( $debug ) {
87 $this->doWrite( self::ALL, 'setDebug', $debug );
88 }
89
90 protected function doGet( $key, $flags = 0 ) {
91 $misses = 0; // number backends checked
92 $value = false;
93 foreach ( $this->caches as $cache ) {
94 $value = $cache->get( $key, $flags );
95 if ( $value !== false ) {
96 break;
97 }
98 ++$misses;
99 }
100
101 if ( $value !== false
102 && $misses > 0
103 && ( $flags & self::READ_VERIFIED ) == self::READ_VERIFIED
104 ) {
105 $this->doWrite( $misses, 'set', $key, $value, self::UPGRADE_TTL );
106 }
107
108 return $value;
109 }
110
111 /**
112 * @param string $key
113 * @param mixed $value
114 * @param int $exptime
115 * @return bool
116 */
117 public function set( $key, $value, $exptime = 0 ) {
118 return $this->doWrite( self::ALL, 'set', $key, $value, $exptime );
119 }
120
121 /**
122 * @param string $key
123 * @return bool
124 */
125 public function delete( $key ) {
126 return $this->doWrite( self::ALL, 'delete', $key );
127 }
128
129 /**
130 * @param string $key
131 * @param mixed $value
132 * @param int $exptime
133 * @return bool
134 */
135 public function add( $key, $value, $exptime = 0 ) {
136 return $this->doWrite( self::ALL, 'add', $key, $value, $exptime );
137 }
138
139 /**
140 * @param string $key
141 * @param int $value
142 * @return bool|null
143 */
144 public function incr( $key, $value = 1 ) {
145 return $this->doWrite( self::ALL, 'incr', $key, $value );
146 }
147
148 /**
149 * @param string $key
150 * @param int $value
151 * @return bool
152 */
153 public function decr( $key, $value = 1 ) {
154 return $this->doWrite( self::ALL, 'decr', $key, $value );
155 }
156
157 /**
158 * @param string $key
159 * @param int $timeout
160 * @param int $expiry
161 * @param string $rclass
162 * @return bool
163 */
164 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
165 // Lock only the first cache, to avoid deadlocks
166 return $this->caches[0]->lock( $key, $timeout, $expiry, $rclass );
167 }
168
169 /**
170 * @param string $key
171 * @return bool
172 */
173 public function unlock( $key ) {
174 return $this->caches[0]->unlock( $key );
175 }
176
177 /**
178 * @param string $key
179 * @param callable $callback Callback method to be executed
180 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
181 * @param int $attempts The amount of times to attempt a merge in case of failure
182 * @return bool Success
183 */
184 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
185 return $this->doWrite( self::ALL, 'merge', $key, $callback, $exptime );
186 }
187
188 public function getLastError() {
189 return $this->caches[0]->getLastError();
190 }
191
192 public function clearLastError() {
193 $this->caches[0]->clearLastError();
194 }
195
196 /**
197 * Apply a write method to the first $count backing caches
198 *
199 * @param integer $count
200 * @param string $method
201 * @param mixed ...
202 * @return bool
203 */
204 protected function doWrite( $count, $method /*, ... */ ) {
205 $ret = true;
206 $args = array_slice( func_get_args(), 2 );
207
208 foreach ( $this->caches as $i => $cache ) {
209 if ( $i >= $count ) {
210 break; // ignore the lower tiers
211 }
212
213 if ( $i == 0 || !$this->asyncWrites ) {
214 // First store or in sync mode: write now and get result
215 if ( !call_user_func_array( array( $cache, $method ), $args ) ) {
216 $ret = false;
217 }
218 } else {
219 // Secondary write in async mode: do not block this HTTP request
220 $logger = $this->logger;
221 DeferredUpdates::addCallableUpdate(
222 function () use ( $cache, $method, $args, $logger ) {
223 if ( !call_user_func_array( array( $cache, $method ), $args ) ) {
224 $logger->warning( "Async $method op failed" );
225 }
226 }
227 );
228 }
229 }
230
231 return $ret;
232 }
233
234 /**
235 * Delete objects expiring before a certain date.
236 *
237 * Succeed if any of the child caches succeed.
238 * @param string $date
239 * @param bool|callable $progressCallback
240 * @return bool
241 */
242 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
243 $ret = false;
244 foreach ( $this->caches as $cache ) {
245 if ( $cache->deleteObjectsExpiringBefore( $date, $progressCallback ) ) {
246 $ret = true;
247 }
248 }
249
250 return $ret;
251 }
252 }