24use UnexpectedValueException;
25use Wikimedia\ScopedCallback;
57 parent::__construct( $params );
61 'compress_threshold' => 1500,
62 'connect_timeout' => 0.5,
64 'serializer' =>
'php',
65 'use_binary_protocol' =>
false,
66 'allow_tcp_nagle_delay' => true
69 if ( $params[
'persistent'] ) {
73 $connectionPoolId = md5(
serialize( $params ) );
74 $client =
new Memcached( $connectionPoolId );
79 $this->initializeClient(
$client, $params );
85 ini_set(
'memcached.compression_threshold', $params[
'compress_threshold'] );
97 private function initializeClient( Memcached
$client, array $params ) {
98 if (
$client->getServerList() ) {
99 $this->logger->debug( __METHOD__ .
": pre-initialized client instance." );
104 $this->logger->debug( __METHOD__ .
": initializing new client instance." );
107 Memcached::OPT_NO_BLOCK =>
false,
108 Memcached::OPT_BUFFER_WRITES =>
false,
109 Memcached::OPT_NOREPLY =>
false,
111 Memcached::OPT_BINARY_PROTOCOL => $params[
'use_binary_protocol'],
113 Memcached::OPT_CONNECT_TIMEOUT => $params[
'connect_timeout'] * 1000,
114 Memcached::OPT_SEND_TIMEOUT => $params[
'timeout'],
115 Memcached::OPT_RECV_TIMEOUT => $params[
'timeout'],
116 Memcached::OPT_POLL_TIMEOUT => $params[
'timeout'] / 1000,
118 Memcached::OPT_TCP_NODELAY => !$params[
'allow_tcp_nagle_delay'],
120 Memcached::OPT_LIBKETAMA_COMPATIBLE => true
122 if ( isset( $params[
'retry_timeout'] ) ) {
123 $options[Memcached::OPT_RETRY_TIMEOUT] = $params[
'retry_timeout'];
125 if ( isset( $params[
'server_failure_limit'] ) ) {
126 $options[Memcached::OPT_SERVER_FAILURE_LIMIT] = $params[
'server_failure_limit'];
128 if ( $params[
'serializer'] ===
'php' ) {
129 $options[Memcached::OPT_SERIALIZER] = Memcached::SERIALIZER_PHP;
130 } elseif ( $params[
'serializer'] ===
'igbinary' ) {
132 if ( !Memcached::HAVE_IGBINARY ) {
133 throw new RuntimeException(
134 __CLASS__ .
': the igbinary extension is not available ' .
135 'but igbinary serialization was requested.'
138 $options[Memcached::OPT_SERIALIZER] = Memcached::SERIALIZER_IGBINARY;
141 if ( !
$client->setOptions( $options ) ) {
142 throw new RuntimeException(
143 "Invalid options: " . json_encode( $options, JSON_PRETTY_PRINT )
148 foreach ( $params[
'servers'] as $host ) {
149 if ( preg_match(
'/^\[(.+)\]:(\d+)$/', $host, $m ) ) {
150 $servers[] = [ $m[1], (int)$m[2] ];
151 } elseif ( preg_match(
'/^([^:]+):(\d+)$/', $host, $m ) ) {
152 $servers[] = [ $m[1], (int)$m[2] ];
154 $servers[] = [ $host, false ];
158 if ( !
$client->addServers( $servers ) ) {
159 throw new RuntimeException(
"Failed to inject server address list" );
172 private function noReplyScope( $flags ) {
173 if ( $flags !==
true && !( $flags & self::WRITE_BACKGROUND ) ) {
177 $client->setOption( Memcached::OPT_NOREPLY,
true );
179 return new ScopedCallback(
static function () use (
$client ) {
180 $client->setOption( Memcached::OPT_NOREPLY,
false );
184 protected function doGet( $key, $flags = 0, &$casToken =
null ) {
188 $this->
debug(
"get($key)" );
195 $flags = Memcached::GET_EXTENDED;
196 $res = $this->client->get( $routeKey,
null, $flags );
197 if ( is_array( $res ) ) {
198 $result = $res[
'value'];
199 $casToken = $res[
'cas'];
204 $result = $this->client->get( $routeKey );
210 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
211 $this->
debug(
"set($key)" );
215 $noReplyScope = $this->noReplyScope( $flags );
216 $result = $this->client->set( $routeKey, $value, $this->
fixExpiry( $exptime ) );
217 ScopedCallback::consume( $noReplyScope );
219 return ( !$result && $this->client->getResultCode() === Memcached::RES_NOTSTORED )
225 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
226 $this->
debug(
"cas($key)" );
229 $result = $this->client->cas(
239 $this->
debug(
"delete($key)" );
242 $noReplyScope = $this->noReplyScope( $flags );
243 $result = $this->client->delete( $routeKey );
244 ScopedCallback::consume( $noReplyScope );
246 return ( !$result && $this->client->getResultCode() === Memcached::RES_NOTFOUND )
252 protected function doAdd( $key, $value, $exptime = 0, $flags = 0 ) {
253 $this->
debug(
"add($key)" );
256 $noReplyScope = $this->noReplyScope( $flags );
257 $result = $this->client->add(
262 ScopedCallback::consume( $noReplyScope );
268 $this->
debug(
"incrWithInit($key)" );
271 $scope = $this->noReplyScope(
true );
272 $this->
checkResult( $key, $this->client->add( $routeKey, $init - $step, $this->fixExpiry( $exptime ) ) );
273 $this->
checkResult( $key, $this->client->increment( $routeKey, $step ) );
274 ScopedCallback::consume( $scope );
281 $this->
debug(
"incrWithInit($key)" );
284 $result = $this->client->increment( $routeKey, $step );
286 if ( $newValue ===
false && !$this->
getLastError( $watchPoint ) ) {
288 $result = $this->client->add( $routeKey, $init, $this->
fixExpiry( $exptime ) );
289 $newValue = $this->
checkResult( $key, $result ) ? $init :
false;
290 if ( $newValue ===
false && !$this->
getLastError( $watchPoint ) ) {
292 $result = $this->client->increment( $routeKey, $step );
313 static $statusByCode = [
327 if ( $result !==
false ) {
332 $code =
$client->getResultCode();
334 case Memcached::RES_SUCCESS:
336 case Memcached::RES_DATA_EXISTS:
337 case Memcached::RES_NOTSTORED:
338 case Memcached::RES_NOTFOUND:
339 $this->
debug(
"result: " . $client->getResultMessage() );
342 $msg =
$client->getResultMessage();
344 if ( $key !==
false ) {
345 $server =
$client->getServerByKey( $key );
346 $logCtx[
'memcached-server'] =
"{$server['host']}:{$server['port']}";
347 $logCtx[
'memcached-key'] = $key;
348 $msg =
"Memcached error for key \"{memcached-key}\" " .
349 "on server \"{memcached-server}\": $msg";
351 $msg =
"Memcached error: $msg";
353 $this->logger->error( $msg, $logCtx );
354 $this->
setLastError( $statusByCode[$code] ?? self::ERR_UNEXPECTED );
361 $this->
debug(
'getMulti(' . implode(
', ', $keys ) .
')' );
364 foreach ( $keys as $key ) {
371 $resByRouteKey = $this->client->getMulti( $routeKeys );
373 if ( is_array( $resByRouteKey ) ) {
375 foreach ( $resByRouteKey as $routeKey => $value ) {
384 return $res !==
false ? $res : [];
387 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
388 $this->
debug(
'setMulti(' . implode(
', ', array_keys( $data ) ) .
')' );
391 $dataByRouteKey = [];
392 foreach ( $data as $key => $value ) {
396 $noReplyScope = $this->noReplyScope( $flags );
400 $result = @$this->client->setMulti( $dataByRouteKey, $exptime );
401 ScopedCallback::consume( $noReplyScope );
407 $this->
debug(
'deleteMulti(' . implode(
', ', $keys ) .
')' );
410 foreach ( $keys as $key ) {
414 $noReplyScope = $this->noReplyScope( $flags );
415 $resultArray = $this->client->deleteMulti( $routeKeys ) ?: [];
416 ScopedCallback::consume( $noReplyScope );
419 foreach ( $resultArray as $code ) {
420 if ( !in_array( $code, [
true, Memcached::RES_NOTFOUND ],
true ) ) {
430 $this->
debug(
"touch($key)" );
435 $result = $this->client->touch( $routeKey, $this->
fixExpiry( $exptime ) );
441 if ( is_int( $value ) ) {
445 $serializer = $this->client->getOption( Memcached::OPT_SERIALIZER );
446 if ( $serializer === Memcached::SERIALIZER_PHP ) {
448 } elseif ( $serializer === Memcached::SERIALIZER_IGBINARY ) {
449 return igbinary_serialize( $value );
452 throw new UnexpectedValueException( __METHOD__ .
": got serializer '$serializer'." );
460 $serializer = $this->client->getOption( Memcached::OPT_SERIALIZER );
461 if ( $serializer === Memcached::SERIALIZER_PHP ) {
463 } elseif ( $serializer === Memcached::SERIALIZER_IGBINARY ) {
464 return igbinary_unserialize( $value );
467 throw new UnexpectedValueException( __METHOD__ .
": got serializer '$serializer'." );
472class_alias( MemcachedPeclBagOStuff::class,
'MemcachedPeclBagOStuff' );