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