Merge "rest: Return a 400 for invalid render IDs"
[mediawiki.git] / includes / libs / objectcache / RedisConnRef.php
blob489edda3a6a76dd0c92f6fa470bf774c48093279
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @file
21 namespace Wikimedia\ObjectCache;
23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\LoggerInterface;
25 use Redis;
26 use RedisException;
28 /**
29 * Wrapper class for Redis connections that automatically reuses connections (via RAII pattern)
31 * This class proxies a Redis class instance from the php-redis PECL extension.
32 * All its methods can be called the same way.
34 * @see <https://github.com/phpredis/phpredis#table-of-contents>
36 * @ingroup Cache
37 * @since 1.21
39 class RedisConnRef implements LoggerAwareInterface {
40 /** @var RedisConnectionPool */
41 protected $pool;
42 /** @var Redis */
43 protected $conn;
44 /** @var string */
45 protected $server;
46 /** @var string|null */
47 protected $lastError;
49 /**
50 * @var LoggerInterface
52 protected $logger;
54 /**
55 * No authentication errors.
57 private const AUTH_NO_ERROR = 200;
59 /**
60 * Temporary authentication error; recovered by reauthenticating.
62 private const AUTH_ERROR_TEMPORARY = 201;
64 /**
65 * Authentication error was permanent and could not be recovered.
67 private const AUTH_ERROR_PERMANENT = 202;
69 /**
70 * @param RedisConnectionPool $pool
71 * @param string $server
72 * @param Redis $conn
73 * @param LoggerInterface $logger
75 public function __construct(
76 RedisConnectionPool $pool, $server, Redis $conn, LoggerInterface $logger
77 ) {
78 $this->pool = $pool;
79 $this->server = $server;
80 $this->conn = $conn;
81 $this->logger = $logger;
84 public function setLogger( LoggerInterface $logger ) {
85 $this->logger = $logger;
88 /**
89 * @return string
90 * @since 1.23
92 public function getServer() {
93 return $this->server;
96 public function getLastError() {
97 return $this->lastError;
100 public function clearLastError() {
101 $this->lastError = null;
105 * Magic __call handler for most Redis functions.
107 * @param string $name
108 * @param array $arguments
109 * @return mixed
110 * @throws RedisException
112 public function __call( $name, $arguments ) {
113 // Work around https://github.com/nicolasff/phpredis/issues/70
114 $lname = strtolower( $name );
115 if (
116 ( $lname === 'blpop' || $lname === 'brpop' || $lname === 'brpoplpush' )
117 && count( $arguments ) > 1
119 // Get timeout off the end since it is always required and argument length can vary
120 $timeout = end( $arguments );
121 // Only give the additional one second buffer if not requesting an infinite timeout
122 $this->pool->resetTimeout( $this->conn, ( $timeout > 0 ? $timeout + 1 : $timeout ) );
125 return $this->tryCall( $name, $arguments );
129 * Do the method call in the common try catch handler.
131 * @param string $method
132 * @param array $arguments
133 * @return mixed
134 * @throws RedisException
136 private function tryCall( $method, $arguments ) {
137 $this->conn->clearLastError();
138 try {
139 $res = $this->conn->$method( ...$arguments );
140 $authError = $this->checkAuthentication();
141 if ( $authError === self::AUTH_ERROR_TEMPORARY ) {
142 $res = $this->conn->$method( ...$arguments );
144 if ( $authError === self::AUTH_ERROR_PERMANENT ) {
145 throw new RedisException( "Failure reauthenticating to Redis." );
147 return $res;
148 } finally {
149 $this->postCallCleanup();
154 * Key Scan
155 * Handle this explicitly due to needing the iterator passed by reference.
156 * See: https://github.com/phpredis/phpredis#scan
158 * @param int &$iterator
159 * @param string|null $pattern
160 * @param int|null $count
161 * @return array
163 public function scan( &$iterator, $pattern = null, $count = null ) {
164 return $this->tryCall( 'scan', [ &$iterator, $pattern, $count ] );
168 * Set Scan
169 * Handle this explicitly due to needing the iterator passed by reference.
170 * See: https://github.com/phpredis/phpredis#sScan
172 * @param string $key
173 * @param int &$iterator
174 * @param string|null $pattern
175 * @param int|null $count
176 * @return array
178 public function sScan( $key, &$iterator, $pattern = null, $count = null ) {
179 return $this->tryCall( 'sScan', [ $key, &$iterator, $pattern, $count ] );
183 * Hash Scan
184 * Handle this explicitly due to needing the iterator passed by reference.
185 * See: https://github.com/phpredis/phpredis#hScan
187 * @param string $key
188 * @param int &$iterator
189 * @param string|null $pattern
190 * @param int|null $count
191 * @return array
193 public function hScan( $key, &$iterator, $pattern = null, $count = null ) {
194 return $this->tryCall( 'hScan', [ $key, &$iterator, $pattern, $count ] );
198 * Sorted Set Scan
199 * Handle this explicitly due to needing the iterator passed by reference.
200 * See: https://github.com/phpredis/phpredis#hScan
202 * @param string $key
203 * @param int &$iterator
204 * @param string|null $pattern
205 * @param int|null $count
206 * @return array
208 public function zScan( $key, &$iterator, $pattern = null, $count = null ) {
209 return $this->tryCall( 'zScan', [ $key, &$iterator, $pattern, $count ] );
213 * Handle authentication errors and automatically reauthenticate.
215 * @return int self::AUTH_NO_ERROR, self::AUTH_ERROR_TEMPORARY, or self::AUTH_ERROR_PERMANENT
217 private function checkAuthentication() {
218 $lastError = $this->conn->getLastError();
219 if ( $lastError && preg_match( '/^ERR operation not permitted\b/', $lastError ) ) {
220 if ( !$this->pool->reauthenticateConnection( $this->server, $this->conn ) ) {
221 return self::AUTH_ERROR_PERMANENT;
223 $this->conn->clearLastError();
224 $this->logger->info(
225 "Used automatic re-authentication for Redis.",
226 [ 'redis_server' => $this->server ]
228 return self::AUTH_ERROR_TEMPORARY;
230 return self::AUTH_NO_ERROR;
234 * Post Redis call cleanup.
236 * @return void
238 private function postCallCleanup() {
239 $this->lastError = $this->conn->getLastError() ?: $this->lastError;
241 // Restore original timeout in the case of blocking calls.
242 $this->pool->resetTimeout( $this->conn );
246 * @param string $script
247 * @param array $params
248 * @param int $numKeys
249 * @return mixed
250 * @throws RedisException
252 public function luaEval( $script, array $params, $numKeys ) {
253 $sha1 = sha1( $script ); // 40 char hex
254 $conn = $this->conn; // convenience
255 $server = $this->server; // convenience
257 // Try to run the server-side cached copy of the script
258 $conn->clearLastError();
259 $res = $conn->evalSha( $sha1, $params, $numKeys );
260 // If we got a permission error reply that means that (a) we are not in
261 // multi()/pipeline() and (b) some connection problem likely occurred. If
262 // the password the client gave was just wrong, an exception should have
263 // been thrown back in getConnection() previously.
264 $lastError = $conn->getLastError();
265 if ( $lastError && preg_match( '/^ERR operation not permitted\b/', $lastError ) ) {
266 $this->pool->reauthenticateConnection( $server, $conn );
267 $conn->clearLastError();
268 $res = $conn->eval( $script, $params, $numKeys );
269 $this->logger->info(
270 "Used automatic re-authentication for Lua script '$sha1'.",
271 [ 'redis_server' => $server ]
274 // If the script is not in cache, use eval() to retry and cache it
275 $lastError = $conn->getLastError();
276 if ( $lastError && preg_match( '/^NOSCRIPT/', $lastError ) ) {
277 $conn->clearLastError();
278 $res = $conn->eval( $script, $params, $numKeys );
279 $this->logger->info(
280 "Used eval() for Lua script '$sha1'.",
281 [ 'redis_server' => $server ]
285 $lastError = $conn->getLastError();
286 if ( $lastError ) { // script bug?
287 $this->logger->error(
288 'Lua script error on server "{redis_server}": {lua_error}',
290 'redis_server' => $server,
291 'lua_error' => $lastError
294 $this->lastError = $lastError;
297 return $res;
301 * @param Redis $conn
302 * @return bool
304 public function isConnIdentical( Redis $conn ) {
305 return $this->conn === $conn;
308 public function __destruct() {
309 $this->pool->freeConnection( $this->server, $this->conn );
313 /** @deprecated class alias since 1.43 */
314 class_alias( RedisConnRef::class, 'RedisConnRef' );