Merge "Make BagOStuff::incr abstract to discourage bad implementations"
[lhc/web/wiklou.git] / includes / libs / objectcache / MemcachedBagOStuff.php
1 <?php
2 /**
3 * Base class for memcached clients.
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 * Base class for memcached clients.
26 *
27 * @ingroup Cache
28 */
29 class MemcachedBagOStuff extends BagOStuff {
30 /** @var MemcachedClient|Memcached */
31 protected $client;
32
33 function __construct( array $params ) {
34 parent::__construct( $params );
35
36 $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_BE; // unreliable
37 }
38
39 /**
40 * Fill in some defaults for missing keys in $params.
41 *
42 * @param array $params
43 * @return array
44 */
45 protected function applyDefaultParams( $params ) {
46 return $params + [
47 'compress_threshold' => 1500,
48 'connect_timeout' => 0.5,
49 'debug' => false
50 ];
51 }
52
53 protected function doGet( $key, $flags = 0 ) {
54 $casToken = null;
55
56 return $this->getWithToken( $key, $casToken, $flags );
57 }
58
59 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
60 return $this->client->get( $this->validateKeyEncoding( $key ), $casToken );
61 }
62
63 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
64 return $this->client->set( $this->validateKeyEncoding( $key ), $value,
65 $this->fixExpiry( $exptime ) );
66 }
67
68 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
69 return $this->client->cas( $casToken, $this->validateKeyEncoding( $key ),
70 $value, $this->fixExpiry( $exptime ) );
71 }
72
73 public function delete( $key, $flags = 0 ) {
74 return $this->client->delete( $this->validateKeyEncoding( $key ) );
75 }
76
77 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
78 return $this->client->add( $this->validateKeyEncoding( $key ), $value,
79 $this->fixExpiry( $exptime ) );
80 }
81
82 public function incr( $key, $value = 1 ) {
83 $n = $this->client->incr( $this->validateKeyEncoding( $key ), $value );
84
85 return ( $n !== false && $n !== null ) ? $n : false;
86 }
87
88 public function decr( $key, $value = 1 ) {
89 $n = $this->client->decr( $this->validateKeyEncoding( $key ), $value );
90
91 return ( $n !== false && $n !== null ) ? $n : false;
92 }
93
94 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
95 return $this->mergeViaCas( $key, $callback, $exptime, $attempts );
96 }
97
98 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
99 return $this->client->touch( $this->validateKeyEncoding( $key ),
100 $this->fixExpiry( $exptime ) );
101 }
102
103 /**
104 * Get the underlying client object. This is provided for debugging
105 * purposes.
106 * @return MemcachedClient|Memcached
107 */
108 public function getClient() {
109 return $this->client;
110 }
111
112 /**
113 * Construct a cache key.
114 *
115 * @since 1.27
116 * @param string $keyspace
117 * @param array $args
118 * @return string
119 */
120 public function makeKeyInternal( $keyspace, $args ) {
121 // Memcached keys have a maximum length of 255 characters. From that,
122 // subtract the number of characters we need for the keyspace and for
123 // the separator character needed for each argument. To handle some
124 // custom prefixes used by thing like WANObjectCache, limit to 205.
125 $charsLeft = 205 - strlen( $keyspace ) - count( $args );
126
127 $args = array_map(
128 function ( $arg ) use ( &$charsLeft ) {
129 $arg = strtr( $arg, ' ', '_' );
130
131 // Make sure %, #, and non-ASCII chars are escaped
132 $arg = preg_replace_callback(
133 '/[^\x21-\x22\x24\x26-\x39\x3b-\x7e]+/',
134 function ( $m ) {
135 return rawurlencode( $m[0] );
136 },
137 $arg
138 );
139
140 // 33 = 32 characters for the MD5 + 1 for the '#' prefix.
141 if ( $charsLeft > 33 && strlen( $arg ) > $charsLeft ) {
142 $arg = '#' . md5( $arg );
143 }
144
145 $charsLeft -= strlen( $arg );
146 return $arg;
147 },
148 $args
149 );
150
151 if ( $charsLeft < 0 ) {
152 return $keyspace . ':BagOStuff-long-key:##' . md5( implode( ':', $args ) );
153 }
154
155 return $keyspace . ':' . implode( ':', $args );
156 }
157
158 /**
159 * Ensure that a key is safe to use (contains no control characters and no
160 * characters above the ASCII range.)
161 *
162 * @param string $key
163 * @return string
164 * @throws Exception
165 */
166 public function validateKeyEncoding( $key ) {
167 if ( preg_match( '/[^\x21-\x7e]+/', $key ) ) {
168 throw new Exception( "Key contains invalid characters: $key" );
169 }
170 return $key;
171 }
172
173 /**
174 * TTLs higher than 30 days will be detected as absolute TTLs
175 * (UNIX timestamps), and will result in the cache entry being
176 * discarded immediately because the expiry is in the past.
177 * Clamp expires >30d at 30d, unless they're >=1e9 in which
178 * case they are likely to really be absolute (1e9 = 2011-09-09)
179 * @param int $expiry
180 * @return int
181 */
182 function fixExpiry( $expiry ) {
183 if ( $expiry > 2592000 && $expiry < 1000000000 ) {
184 $expiry = 2592000;
185 }
186 return (int)$expiry;
187 }
188
189 /**
190 * Send a debug message to the log
191 * @param string $text
192 */
193 protected function debugLog( $text ) {
194 $this->logger->debug( $text );
195 }
196 }