b3906596be4d524d4db3d0f2a8206a03056c6e05
[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 $asyncReplication = false;
36 /** @var array[] */
37 protected $asyncWrites = array();
38
39 /**
40 * $params include:
41 * - caches: This should have a numbered array of cache parameter
42 * structures, in the style required by $wgObjectCaches. See
43 * the documentation of $wgObjectCaches for more detail.
44 * BagOStuff objects can also be used as values.
45 * The first cache is the primary one, being the first to
46 * be read in the fallback chain. Writes happen to all stores
47 * in the order they are defined. However, lock()/unlock() calls
48 * only use the primary store.
49 * - replication: Either 'sync' or 'async'. This controls whether writes to
50 * secondary stores are deferred when possible. Async writes
51 * require the HHVM register_postsend_function() function.
52 * Async writes can increase the chance of some race conditions
53 * or cause keys to expire seconds later than expected. It is
54 * safe to use for modules when cached values: are immutable,
55 * invalidation uses logical TTLs, invalidation uses etag/timestamp
56 * validation against the DB, or merge() is used to handle races.
57 *
58 * @param array $params
59 * @throws InvalidArgumentException
60 */
61 public function __construct( $params ) {
62 parent::__construct( $params );
63
64 if ( !isset( $params['caches'] ) ) {
65 throw new InvalidArgumentException( __METHOD__ . ': "caches" parameter required' );
66 }
67
68 $this->caches = array();
69 foreach ( $params['caches'] as $cacheInfo ) {
70 $this->caches[] = ( $cacheInfo instanceof BagOStuff )
71 ? $cacheInfo
72 : ObjectCache::newFromParams( $cacheInfo );
73 }
74
75 if ( isset( $params['replication'] ) && $params['replication'] === 'async' ) {
76 $this->asyncReplication = true;
77 }
78 }
79
80 /**
81 * @param bool $debug
82 */
83 public function setDebug( $debug ) {
84 $this->doWrite( 'setDebug', $debug );
85 }
86
87 public function get( $key, &$casToken = null, $flags = 0 ) {
88 foreach ( $this->caches as $cache ) {
89 $value = $cache->get( $key, $casToken, $flags );
90 if ( $value !== false ) {
91 return $value;
92 }
93 }
94 return false;
95 }
96
97 /**
98 * @param string $key
99 * @param mixed $value
100 * @param int $exptime
101 * @return bool
102 */
103 public function set( $key, $value, $exptime = 0 ) {
104 return $this->doWrite( 'set', $key, $value, $exptime );
105 }
106
107 /**
108 * @param string $key
109 * @return bool
110 */
111 public function delete( $key ) {
112 return $this->doWrite( 'delete', $key );
113 }
114
115 /**
116 * @param string $key
117 * @param mixed $value
118 * @param int $exptime
119 * @return bool
120 */
121 public function add( $key, $value, $exptime = 0 ) {
122 return $this->doWrite( 'add', $key, $value, $exptime );
123 }
124
125 /**
126 * @param string $key
127 * @param int $value
128 * @return bool|null
129 */
130 public function incr( $key, $value = 1 ) {
131 return $this->doWrite( 'incr', $key, $value );
132 }
133
134 /**
135 * @param string $key
136 * @param int $value
137 * @return bool
138 */
139 public function decr( $key, $value = 1 ) {
140 return $this->doWrite( 'decr', $key, $value );
141 }
142
143 /**
144 * @param string $key
145 * @param int $timeout
146 * @param int $expiry
147 * @param string $rclass
148 * @return bool
149 */
150 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
151 // Lock only the first cache, to avoid deadlocks
152 if ( isset( $this->caches[0] ) ) {
153 return $this->caches[0]->lock( $key, $timeout, $expiry, $rclass );
154 } else {
155 return true;
156 }
157 }
158
159 /**
160 * @param string $key
161 * @return bool
162 */
163 public function unlock( $key ) {
164 if ( isset( $this->caches[0] ) ) {
165 return $this->caches[0]->unlock( $key );
166 } else {
167 return true;
168 }
169 }
170
171 /**
172 * @param string $key
173 * @param callable $callback Callback method to be executed
174 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
175 * @param int $attempts The amount of times to attempt a merge in case of failure
176 * @return bool Success
177 */
178 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
179 return $this->doWrite( 'merge', $key, $callback, $exptime );
180 }
181
182 public function getLastError() {
183 return isset( $this->caches[0] ) ? $this->caches[0]->getLastError() : self::ERR_NONE;
184 }
185
186 public function clearLastError() {
187 if ( isset( $this->caches[0] ) ) {
188 $this->caches[0]->clearLastError();
189 }
190 }
191
192 /**
193 * @param string $method
194 * @return bool
195 */
196 protected function doWrite( $method /*, ... */ ) {
197 $ret = true;
198 $args = func_get_args();
199 array_shift( $args );
200
201 foreach ( $this->caches as $i => $cache ) {
202 if ( $i == 0 || !$this->asyncReplication ) {
203 // First store or in sync mode: write now and get result
204 if ( !call_user_func_array( array( $cache, $method ), $args ) ) {
205 $ret = false;
206 }
207 } else {
208 // Secondary write in async mode: do not block this HTTP request
209 $logger = $this->logger;
210 DeferredUpdates::addCallableUpdate(
211 function() use ( $cache, $method, $args, $logger ) {
212 if ( !call_user_func_array( array( $cache, $method ), $args ) ) {
213 $logger->warning( "Async $method op failed" );
214 }
215 }
216 );
217 }
218 }
219
220 return $ret;
221 }
222
223 /**
224 * Delete objects expiring before a certain date.
225 *
226 * Succeed if any of the child caches succeed.
227 * @param string $date
228 * @param bool|callable $progressCallback
229 * @return bool
230 */
231 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
232 $ret = false;
233 foreach ( $this->caches as $cache ) {
234 if ( $cache->deleteObjectsExpiringBefore( $date, $progressCallback ) ) {
235 $ret = true;
236 }
237 }
238
239 return $ret;
240 }
241 }