10use UnexpectedValueException;
11use Wikimedia\ScopedCallback;
43 parent::__construct( $params );
47 'compress_threshold' => 1500,
48 'connect_timeout' => 0.5,
50 'serializer' =>
'php',
51 'use_binary_protocol' =>
false,
52 'allow_tcp_nagle_delay' => true
55 if ( $params[
'persistent'] ) {
59 $connectionPoolId = md5(
serialize( $params ) );
60 $client =
new Memcached( $connectionPoolId );
65 $this->initializeClient(
$client, $params );
71 ini_set(
'memcached.compression_threshold', $params[
'compress_threshold'] );
83 private function initializeClient( Memcached
$client, array $params ) {
84 if (
$client->getServerList() ) {
85 $this->logger->debug( __METHOD__ .
": pre-initialized client instance." );
90 $this->logger->debug( __METHOD__ .
": initializing new client instance." );
93 Memcached::OPT_NO_BLOCK =>
false,
94 Memcached::OPT_BUFFER_WRITES =>
false,
95 Memcached::OPT_NOREPLY =>
false,
97 Memcached::OPT_BINARY_PROTOCOL => $params[
'use_binary_protocol'],
99 Memcached::OPT_CONNECT_TIMEOUT => $params[
'connect_timeout'] * 1000,
100 Memcached::OPT_SEND_TIMEOUT => $params[
'timeout'],
101 Memcached::OPT_RECV_TIMEOUT => $params[
'timeout'],
102 Memcached::OPT_POLL_TIMEOUT => $params[
'timeout'] / 1000,
104 Memcached::OPT_TCP_NODELAY => !$params[
'allow_tcp_nagle_delay'],
106 Memcached::OPT_LIBKETAMA_COMPATIBLE => true
108 if ( isset( $params[
'retry_timeout'] ) ) {
109 $options[Memcached::OPT_RETRY_TIMEOUT] = $params[
'retry_timeout'];
111 if ( isset( $params[
'server_failure_limit'] ) ) {
112 $options[Memcached::OPT_SERVER_FAILURE_LIMIT] = $params[
'server_failure_limit'];
114 if ( $params[
'serializer'] ===
'php' ) {
115 $options[Memcached::OPT_SERIALIZER] = Memcached::SERIALIZER_PHP;
116 } elseif ( $params[
'serializer'] ===
'igbinary' ) {
118 if ( !Memcached::HAVE_IGBINARY ) {
119 throw new RuntimeException(
120 __CLASS__ .
': the igbinary extension is not available ' .
121 'but igbinary serialization was requested.'
124 $options[Memcached::OPT_SERIALIZER] = Memcached::SERIALIZER_IGBINARY;
127 if ( !
$client->setOptions( $options ) ) {
128 throw new RuntimeException(
129 "Invalid options: " . json_encode( $options, JSON_PRETTY_PRINT )
134 foreach ( $params[
'servers'] as $host ) {
135 if ( preg_match(
'/^\[(.+)\]:(\d+)$/', $host, $m ) ) {
136 $servers[] = [ $m[1], (int)$m[2] ];
137 } elseif ( preg_match(
'/^([^:]+):(\d+)$/', $host, $m ) ) {
138 $servers[] = [ $m[1], (int)$m[2] ];
140 $servers[] = [ $host, false ];
144 if ( !
$client->addServers( $servers ) ) {
145 throw new RuntimeException(
"Failed to inject server address list" );
157 private function noReplyScope( $flags ): ?ScopedCallback {
162 $client->setOption( Memcached::OPT_NOREPLY,
true );
164 return new ScopedCallback(
static function () use (
$client ) {
165 $client->setOption( Memcached::OPT_NOREPLY,
false );
170 protected function doGet( $key, $flags = 0, &$casToken =
null ) {
171 $getToken = ( $casToken === self::PASS_BY_REF );
174 $this->debug(
"get($key)" );
176 $routeKey = $this->validateKeyAndPrependRoute( $key );
181 $flags = Memcached::GET_EXTENDED;
182 $res = $this->client->get( $routeKey,
null, $flags );
183 if ( is_array( $res ) ) {
184 $result = $res[
'value'];
185 $casToken = $res[
'cas'];
190 $result = $this->client->get( $routeKey );
193 return $this->checkResult( $key, $result );
197 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
198 $this->debug(
"set($key)" );
200 $routeKey = $this->validateKeyAndPrependRoute( $key );
202 $noReplyScope = $this->noReplyScope( $flags );
203 $result = $this->client->set( $routeKey, $value, $this->fixExpiry( $exptime ) );
204 ScopedCallback::consume( $noReplyScope );
206 return ( !$result && $this->client->getResultCode() === Memcached::RES_NOTSTORED )
209 : $this->checkResult( $key, $result );
213 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
214 $this->debug(
"cas($key)" );
216 $routeKey = $this->validateKeyAndPrependRoute( $key );
217 $result = $this->client->cas(
220 $value, $this->fixExpiry( $exptime )
223 return $this->checkResult( $key, $result );
228 $this->debug(
"delete($key)" );
230 $routeKey = $this->validateKeyAndPrependRoute( $key );
231 $noReplyScope = $this->noReplyScope( $flags );
232 $result = $this->client->delete( $routeKey );
233 ScopedCallback::consume( $noReplyScope );
235 return ( !$result && $this->client->getResultCode() === Memcached::RES_NOTFOUND )
238 : $this->checkResult( $key, $result );
242 protected function doAdd( $key, $value, $exptime = 0, $flags = 0 ) {
243 $this->debug(
"add($key)" );
245 $routeKey = $this->validateKeyAndPrependRoute( $key );
246 $noReplyScope = $this->noReplyScope( $flags );
247 $result = $this->client->add(
250 $this->fixExpiry( $exptime )
252 ScopedCallback::consume( $noReplyScope );
254 return $this->checkResult( $key, $result );
259 $this->debug(
"incrWithInit($key)" );
260 $routeKey = $this->validateKeyAndPrependRoute( $key );
261 $watchPoint = $this->watchErrors();
262 $scope = $this->noReplyScope(
true );
263 $this->checkResult( $key, $this->client->add( $routeKey, $init - $step, $this->fixExpiry( $exptime ) ) );
264 $this->checkResult( $key, $this->client->increment( $routeKey, $step ) );
265 ScopedCallback::consume( $scope );
266 $lastError = $this->getLastError( $watchPoint );
273 $this->debug(
"incrWithInit($key)" );
274 $routeKey = $this->validateKeyAndPrependRoute( $key );
275 $watchPoint = $this->watchErrors();
276 $result = $this->client->increment( $routeKey, $step );
277 $newValue = $this->checkResult( $key, $result );
278 if ( $newValue ===
false && !$this->getLastError( $watchPoint ) ) {
280 $result = $this->client->add( $routeKey, $init, $this->fixExpiry( $exptime ) );
281 $newValue = $this->checkResult( $key, $result ) ? $init :
false;
282 if ( $newValue ===
false && !$this->getLastError( $watchPoint ) ) {
284 $result = $this->client->increment( $routeKey, $step );
285 $newValue = $this->checkResult( $key, $result );
305 static $statusByCode = [
306 Memcached::RES_HOST_LOOKUP_FAILURE => self::ERR_UNREACHABLE,
307 Memcached::RES_SERVER_MARKED_DEAD => self::ERR_UNREACHABLE,
308 Memcached::RES_SERVER_TEMPORARILY_DISABLED => self::ERR_UNREACHABLE,
309 Memcached::RES_UNKNOWN_READ_FAILURE => self::ERR_NO_RESPONSE,
310 Memcached::RES_WRITE_FAILURE => self::ERR_NO_RESPONSE,
311 Memcached::RES_PARTIAL_READ => self::ERR_NO_RESPONSE,
314 3 => self::ERR_UNREACHABLE,
315 27 => self::ERR_UNREACHABLE,
316 6 => self::ERR_NO_RESPONSE
319 if ( $result !==
false ) {
323 $client = $this->client;
324 $code = $client->getResultCode();
326 case Memcached::RES_SUCCESS:
328 case Memcached::RES_DATA_EXISTS:
329 case Memcached::RES_NOTSTORED:
330 case Memcached::RES_NOTFOUND:
331 $this->debug(
"result: " . $client->getResultMessage() );
334 $msg = $client->getResultMessage();
336 if ( $key !==
false ) {
337 $server = $client->getServerByKey( $key );
338 $logCtx[
'memcached-server'] =
"{$server['host']}:{$server['port']}";
339 $logCtx[
'memcached-key'] = $key;
340 $msg =
"Memcached error for key \"{memcached-key}\" " .
341 "on server \"{memcached-server}\": $msg";
343 $msg =
"Memcached error: $msg";
345 $this->logger->error( $msg, $logCtx );
346 $this->setLastError( $statusByCode[$code] ?? self::ERR_UNEXPECTED );
354 $this->debug(
'getMulti(' . implode(
', ', $keys ) .
')' );
357 foreach ( $keys as $key ) {
358 $routeKeys[] = $this->validateKeyAndPrependRoute( $key );
364 $resByRouteKey = $this->client->getMulti( $routeKeys );
366 if ( is_array( $resByRouteKey ) ) {
368 foreach ( $resByRouteKey as $routeKey => $value ) {
369 $res[$this->stripRouteFromKey( $routeKey )] = $value;
375 $res = $this->checkResult(
false, $res );
377 return $res !==
false ? $res : [];
381 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
382 $this->debug(
'setMulti(' . implode(
', ', array_keys( $data ) ) .
')' );
384 $exptime = $this->fixExpiry( $exptime );
385 $dataByRouteKey = [];
386 foreach ( $data as $key => $value ) {
387 $dataByRouteKey[$this->validateKeyAndPrependRoute( $key )] = $value;
390 $noReplyScope = $this->noReplyScope( $flags );
394 $result = @$this->client->setMulti( $dataByRouteKey, $exptime );
395 ScopedCallback::consume( $noReplyScope );
397 return $this->checkResult(
false, $result );
402 $this->debug(
'deleteMulti(' . implode(
', ', $keys ) .
')' );
405 foreach ( $keys as $key ) {
406 $routeKeys[] = $this->validateKeyAndPrependRoute( $key );
409 $noReplyScope = $this->noReplyScope( $flags );
410 $resultArray = $this->client->deleteMulti( $routeKeys ) ?: [];
411 ScopedCallback::consume( $noReplyScope );
414 foreach ( $resultArray as $code ) {
415 if ( !in_array( $code, [
true, Memcached::RES_NOTFOUND ],
true ) ) {
421 return $this->checkResult(
false, $result );
426 $this->debug(
"touch($key)" );
428 $routeKey = $this->validateKeyAndPrependRoute( $key );
431 $result = $this->client->touch( $routeKey, $this->fixExpiry( $exptime ) );
433 return $this->checkResult( $key, $result );
438 if ( is_int( $value ) ) {
442 $serializer = $this->client->getOption( Memcached::OPT_SERIALIZER );
443 if ( $serializer === Memcached::SERIALIZER_PHP ) {
444 return serialize( $value );
445 } elseif ( $serializer === Memcached::SERIALIZER_IGBINARY ) {
446 return igbinary_serialize( $value );
449 throw new UnexpectedValueException( __METHOD__ .
": got serializer '$serializer'." );
454 if ( $this->isInteger( $value ) ) {
458 $serializer = $this->client->getOption( Memcached::OPT_SERIALIZER );
459 if ( $serializer === Memcached::SERIALIZER_PHP ) {
460 return unserialize( $value );
461 } elseif ( $serializer === Memcached::SERIALIZER_IGBINARY ) {
462 return igbinary_unserialize( $value );
465 throw new UnexpectedValueException( __METHOD__ .
": got serializer '$serializer'." );
470class_alias( MemcachedPeclBagOStuff::class,
'MemcachedPeclBagOStuff' );
if(!defined('MW_SETUP_CALLBACK'))