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
20 use Psr\Log\LoggerInterface
;
21 use Psr\Log\LoggerAwareInterface
;
24 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
26 * This class simply wraps the Redis class and can be used the same way
31 class RedisConnRef
implements LoggerAwareInterface
{
32 /** @var RedisConnectionPool */
38 /** @var string|null */
42 * @var LoggerInterface
47 * No authentication errors.
49 const AUTH_NO_ERROR
= 200;
52 * Temporary authentication error; recovered by reauthenticating.
54 const AUTH_ERROR_TEMPORARY
= 201;
57 * Authentication error was permanent and could not be recovered.
59 const AUTH_ERROR_PERMANENT
= 202;
62 * @param RedisConnectionPool $pool
63 * @param string $server
65 * @param LoggerInterface $logger
67 public function __construct(
68 RedisConnectionPool
$pool, $server, Redis
$conn, LoggerInterface
$logger
71 $this->server
= $server;
73 $this->logger
= $logger;
76 public function setLogger( LoggerInterface
$logger ) {
77 $this->logger
= $logger;
84 public function getServer() {
88 public function getLastError() {
89 return $this->lastError
;
92 public function clearLastError() {
93 $this->lastError
= null;
97 * Magic __call handler for most Redis functions.
100 * @param array $arguments
102 * @throws RedisException
104 public function __call( $name, $arguments ) {
105 // Work around https://github.com/nicolasff/phpredis/issues/70
106 $lname = strtolower( $name );
108 ( $lname === 'blpop' ||
$lname === 'brpop' ||
$lname === 'brpoplpush' )
109 && count( $arguments ) > 1
111 // Get timeout off the end since it is always required and argument length can vary
112 $timeout = end( $arguments );
113 // Only give the additional one second buffer if not requesting an infinite timeout
114 $this->pool
->resetTimeout( $this->conn
, ( $timeout > 0 ?
$timeout +
1 : $timeout ) );
117 return $this->tryCall( $name, $arguments );
121 * Do the method call in the common try catch handler.
123 * @param string $method
124 * @param array $arguments
126 * @throws RedisException
128 private function tryCall( $method, $arguments ) {
129 $this->conn
->clearLastError();
131 $res = $this->conn
->$method( ...$arguments );
132 $authError = $this->checkAuthentication();
133 if ( $authError === self
::AUTH_ERROR_TEMPORARY
) {
134 $res = $this->conn
->$method( ...$arguments );
136 if ( $authError === self
::AUTH_ERROR_PERMANENT
) {
137 throw new RedisException( "Failure reauthenticating to Redis." );
140 $this->postCallCleanup();
148 * Handle this explicity due to needing the iterator passed by reference.
149 * See: https://github.com/phpredis/phpredis#scan
151 * @param int &$iterator
152 * @param string|null $pattern
153 * @param int|null $count
156 public function scan( &$iterator, $pattern = null, $count = null ) {
157 return $this->tryCall( 'scan', [ &$iterator, $pattern, $count ] );
162 * Handle this explicity due to needing the iterator passed by reference.
163 * See: https://github.com/phpredis/phpredis#sScan
166 * @param int &$iterator
167 * @param string|null $pattern
168 * @param int|null $count
171 public function sScan( $key, &$iterator, $pattern = null, $count = null ) {
172 return $this->tryCall( 'sScan', [ $key, &$iterator, $pattern, $count ] );
177 * Handle this explicity due to needing the iterator passed by reference.
178 * See: https://github.com/phpredis/phpredis#hScan
181 * @param int &$iterator
182 * @param string|null $pattern
183 * @param int|null $count
186 public function hScan( $key, &$iterator, $pattern = null, $count = null ) {
187 return $this->tryCall( 'hScan', [ $key, &$iterator, $pattern, $count ] );
192 * Handle this explicity due to needing the iterator passed by reference.
193 * See: https://github.com/phpredis/phpredis#hScan
196 * @param int &$iterator
197 * @param string|null $pattern
198 * @param int|null $count
201 public function zScan( $key, &$iterator, $pattern = null, $count = null ) {
202 return $this->tryCall( 'zScan', [ $key, &$iterator, $pattern, $count ] );
206 * Handle authentication errors and automatically reauthenticate.
208 * @return int self::AUTH_NO_ERROR, self::AUTH_ERROR_TEMPORARY, or self::AUTH_ERROR_PERMANENT
210 private function checkAuthentication() {
211 if ( preg_match( '/^ERR operation not permitted\b/', $this->conn
->getLastError() ) ) {
212 if ( !$this->pool
->reauthenticateConnection( $this->server
, $this->conn
) ) {
213 return self
::AUTH_ERROR_PERMANENT
;
215 $this->conn
->clearLastError();
217 "Used automatic re-authentication for Redis.",
218 [ 'redis_server' => $this->server
]
220 return self
::AUTH_ERROR_TEMPORARY
;
222 return self
::AUTH_NO_ERROR
;
226 * Post Redis call cleanup.
230 private function postCallCleanup() {
231 $this->lastError
= $this->conn
->getLastError() ?
: $this->lastError
;
233 // Restore original timeout in the case of blocking calls.
234 $this->pool
->resetTimeout( $this->conn
);
238 * @param string $script
239 * @param array $params
240 * @param int $numKeys
242 * @throws RedisException
244 public function luaEval( $script, array $params, $numKeys ) {
245 $sha1 = sha1( $script ); // 40 char hex
246 $conn = $this->conn
; // convenience
247 $server = $this->server
; // convenience
249 // Try to run the server-side cached copy of the script
250 $conn->clearLastError();
251 $res = $conn->evalSha( $sha1, $params, $numKeys );
252 // If we got a permission error reply that means that (a) we are not in
253 // multi()/pipeline() and (b) some connection problem likely occurred. If
254 // the password the client gave was just wrong, an exception should have
255 // been thrown back in getConnection() previously.
256 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
257 $this->pool
->reauthenticateConnection( $server, $conn );
258 $conn->clearLastError();
259 $res = $conn->eval( $script, $params, $numKeys );
261 "Used automatic re-authentication for Lua script '$sha1'.",
262 [ 'redis_server' => $server ]
265 // If the script is not in cache, use eval() to retry and cache it
266 if ( preg_match( '/^NOSCRIPT/', $conn->getLastError() ) ) {
267 $conn->clearLastError();
268 $res = $conn->eval( $script, $params, $numKeys );
270 "Used eval() for Lua script '$sha1'.",
271 [ 'redis_server' => $server ]
275 if ( $conn->getLastError() ) { // script bug?
276 $this->logger
->error(
277 'Lua script error on server "{redis_server}": {lua_error}',
279 'redis_server' => $server,
280 'lua_error' => $conn->getLastError()
285 $this->lastError
= $conn->getLastError() ?
: $this->lastError
;
294 public function isConnIdentical( Redis
$conn ) {
295 return $this->conn
=== $conn;
298 function __destruct() {
299 $this->pool
->freeConnection( $this->server
, $this->conn
);