Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
60.51% |
95 / 157 |
|
37.50% |
3 / 8 |
CRAP | |
0.00% |
0 / 1 |
| MemcachedWrapper | |
60.51% |
95 / 157 |
|
37.50% |
3 / 8 |
95.06 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
33 / 33 |
|
100.00% |
1 / 1 |
7 | |||
| recordOp | |
66.67% |
2 / 3 |
|
0.00% |
0 / 1 |
2.15 | |||
| get | |
100.00% |
27 / 27 |
|
100.00% |
1 / 1 |
6 | |||
| set | |
63.16% |
24 / 38 |
|
0.00% |
0 / 1 |
9.45 | |||
| getStats | |
0.00% |
0 / 33 |
|
0.00% |
0 / 1 |
12 | |||
| delete | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
| makeKey | |
80.00% |
4 / 5 |
|
0.00% |
0 / 1 |
2.03 | |||
| makeMemcachedKey | |
0.00% |
0 / 13 |
|
0.00% |
0 / 1 |
12 | |||
| 1 | <?php |
| 2 | /** |
| 3 | * WikiLambda memcached access wrapper |
| 4 | * |
| 5 | * @file |
| 6 | * @ingroup Extensions |
| 7 | * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt |
| 8 | * @license MIT |
| 9 | */ |
| 10 | |
| 11 | namespace MediaWiki\Extension\WikiLambda\Cache; |
| 12 | |
| 13 | use InvalidArgumentException; |
| 14 | use MediaWiki\Config\Config; |
| 15 | use MediaWiki\Extension\WikiLambda\Metrics\StoreOpsMetrics; |
| 16 | use MediaWiki\Logger\LoggerFactory; |
| 17 | use MediaWiki\MediaWikiServices; |
| 18 | use Memcached; |
| 19 | use Psr\Log\LoggerInterface; |
| 20 | use Wikimedia\ObjectCache\BagOStuff; |
| 21 | use Wikimedia\Stats\StatsFactory; |
| 22 | |
| 23 | class MemcachedWrapper implements \Wikimedia\LightweightObjectStore\ExpirationAwareness { |
| 24 | |
| 25 | private const TOMBSTONE = '__WIKILAMBDA_TOMBSTONE__'; |
| 26 | |
| 27 | /** @var array<string,array{0:Memcached|BagOStuff,1:string}> */ |
| 28 | private array $services = []; |
| 29 | |
| 30 | private string $broadcastRoute = ''; |
| 31 | |
| 32 | private LoggerInterface $logger; |
| 33 | |
| 34 | private readonly StoreOpsMetrics $metrics; |
| 35 | |
| 36 | /** |
| 37 | * This is a simple direct wrapper around Memcached that allows us to use multiple configured memcached services, |
| 38 | * with different assumptions to those that MediaWiki's BagO'Stuff (and especially WANObjectCache) make. It will |
| 39 | * check each service in order for a key, and return the first value it finds, later, but for now it only will go |
| 40 | * to the local service. When setting or deleting a key, it will set/delete it via the broadcast route. Deletion |
| 41 | * is implemented by setting a tombstone value with a short TTL instead of actually deleting the key, to prevent |
| 42 | * cache penetration while allowing the key to eventually be fully removed from the cache. |
| 43 | * |
| 44 | * @param Config $config |
| 45 | * @param ?StatsFactory $statsFactory |
| 46 | */ |
| 47 | public function __construct( private readonly Config $config, ?StatsFactory $statsFactory = null ) { |
| 48 | // Non-injected items |
| 49 | $this->logger = LoggerFactory::getInstance( 'WikiLambdaCache' ); |
| 50 | $this->metrics = new StoreOpsMetrics( 'memcached', $statsFactory ); |
| 51 | |
| 52 | $configuredCaches = $this->config->get( 'WikiLambdaObjectCaches' ); |
| 53 | |
| 54 | foreach ( $configuredCaches as $serviceName => $serviceConfig ) { |
| 55 | $prefix = $serviceConfig['prefix'] ?? "/$serviceName/"; |
| 56 | $this->logger->debug( |
| 57 | 'Constructing a cache {serviceName} with prefix {prefix}', |
| 58 | [ 'serviceName' => $serviceName, 'prefix' => $prefix ] |
| 59 | ); |
| 60 | |
| 61 | $memcached = new Memcached(); |
| 62 | // Parse the server address (host:port or UDS path) using the same logic as |
| 63 | // MemcachedPeclBagOStuff, to ensure config compatibility. |
| 64 | if ( preg_match( '/^\[(.+)\]:(\d+)$/', $serviceConfig['server'], $m ) ) { |
| 65 | // (ipv6, port) |
| 66 | $host = $m[1]; |
| 67 | $port = (int)$m[2]; |
| 68 | } elseif ( preg_match( '/^([^:]+):(\d+)$/', $serviceConfig['server'], $m ) ) { |
| 69 | // (ipv4 or domain name, port) |
| 70 | $host = $m[1]; |
| 71 | $port = (int)$m[2]; |
| 72 | } else { |
| 73 | // (socket path, no port) |
| 74 | $host = $serviceConfig['server']; |
| 75 | $port = false; |
| 76 | } |
| 77 | $memcached->addServer( $host, $port ); |
| 78 | |
| 79 | $this->services[$serviceName] = [ $memcached, $prefix ]; |
| 80 | } |
| 81 | |
| 82 | if ( count( $this->services ) === 0 ) { |
| 83 | $this->logger->info( 'No memcached services configured, falling back to MW\'s main BagOStuff' ); |
| 84 | |
| 85 | $this->services['main'] = [ MediaWikiServices::getInstance()->getMainObjectStash(), 'wikilambda:' ]; |
| 86 | $this->broadcastRoute = 'wikilambda:'; |
| 87 | return; |
| 88 | } |
| 89 | |
| 90 | $configuredBroadcast = $this->config->get( 'WikiLambdaObjectCacheBroadcast' ); |
| 91 | if ( $configuredBroadcast !== null ) { |
| 92 | $this->logger->debug( 'Setting broadcast cache route as {bcast}', [ 'bcast' => $configuredBroadcast ] ); |
| 93 | $this->broadcastRoute = $configuredBroadcast; |
| 94 | } |
| 95 | |
| 96 | if ( $this->broadcastRoute === '' ) { |
| 97 | $this->logger->warning( 'No broadcast cache route configured, falling back to first known cache' ); |
| 98 | $this->broadcastRoute = array_key_first( $this->services ); |
| 99 | } |
| 100 | |
| 101 | $this->logger->debug( 'Finished constructing {count} caches', [ 'count' => count( $this->services ) ] ); |
| 102 | } |
| 103 | |
| 104 | /** |
| 105 | * Records a store operation's outcome and latency for observability. |
| 106 | * |
| 107 | * Unlabelled calls (empty $storeLabel) are skipped. |
| 108 | * |
| 109 | * @param string $storeLabel Identifies the calling store, e.g. 'aw_fragment' |
| 110 | * @param string $op One of 'get', 'set', 'delete' |
| 111 | * @param string $outcome One of 'hit', 'miss', 'success', 'failure' |
| 112 | * @param int $startTimeNs As returned by hrtime( true ) at the start of the operation |
| 113 | */ |
| 114 | private function recordOp( string $storeLabel, string $op, string $outcome, int $startTimeNs ): void { |
| 115 | if ( $storeLabel === '' ) { |
| 116 | return; |
| 117 | } |
| 118 | $this->metrics->recordOp( $storeLabel, $op, $outcome, $startTimeNs ); |
| 119 | } |
| 120 | |
| 121 | /** |
| 122 | * Checks the local memcached service and returns the value for the given key. |
| 123 | * |
| 124 | * @param string $key The key to retrieve |
| 125 | * @param string $storeLabel Identifies the calling store, for observability (e.g. 'aw_fragment') |
| 126 | * @return mixed The value associated with the key from the DC-local memcached service, or false if the key |
| 127 | * is not found. |
| 128 | */ |
| 129 | public function get( string $key, string $storeLabel = '' ): mixed { |
| 130 | $this->logger->debug( __METHOD__ . ': cache check for {key}', [ 'key' => $key ] ); |
| 131 | $startTime = hrtime( true ); |
| 132 | |
| 133 | // Get only our DC local service. |
| 134 | $localServiceName = array_key_first( $this->services ); |
| 135 | [ $localService, $localPrefix ] = $this->services[ $localServiceName ]; |
| 136 | |
| 137 | // TODO: Consider checking the remote service(s) too. |
| 138 | |
| 139 | $targetKey = $localPrefix . $key; |
| 140 | |
| 141 | $value = $localService->get( $targetKey ); |
| 142 | if ( |
| 143 | ( $localService instanceof Memcached && $localService->getResultCode() === Memcached::RES_SUCCESS ) || |
| 144 | ( $localService instanceof BagOStuff && $value !== false ) |
| 145 | ) { |
| 146 | if ( $value === self::TOMBSTONE ) { |
| 147 | $this->logger->debug( |
| 148 | __METHOD__ . ': cache tombstone found for prefixed {key} from {service}, setting as cache miss', |
| 149 | [ 'key' => $targetKey, 'service' => $localServiceName ] |
| 150 | ); |
| 151 | $this->recordOp( $storeLabel, 'get', 'miss', $startTime ); |
| 152 | return false; |
| 153 | } |
| 154 | $this->logger->debug( |
| 155 | __METHOD__ . ': cache hit for prefixed {key} from {service}', |
| 156 | [ 'key' => $targetKey, 'service' => $localServiceName ] |
| 157 | ); |
| 158 | $this->recordOp( $storeLabel, 'get', 'hit', $startTime ); |
| 159 | return $value; |
| 160 | } |
| 161 | $this->logger->debug( |
| 162 | __METHOD__ . ': cache miss for prefixed {key} from {service}', |
| 163 | [ 'key' => $targetKey, 'service' => $localServiceName ] |
| 164 | ); |
| 165 | $this->recordOp( $storeLabel, 'get', 'miss', $startTime ); |
| 166 | return false; |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * Attempt to set the given key via the broadcast route. We use mcrouter to convey this across service(s). |
| 171 | * |
| 172 | * @param string $key The key to set |
| 173 | * @param mixed $value The value to set |
| 174 | * @param int $ttl Time to live in seconds (default 60*60*24*30 seconds = 30 days) |
| 175 | * @param string $storeLabel Identifies the calling store, for observability (e.g. 'aw_fragment') |
| 176 | * @return bool Whether the set operation succeeded |
| 177 | */ |
| 178 | public function set( string $key, mixed $value, int $ttl = self::TTL_MONTH, string $storeLabel = '' ): bool { |
| 179 | $startTime = hrtime( true ); |
| 180 | |
| 181 | if ( $this->broadcastRoute === '' ) { |
| 182 | $this->logger->warning( __METHOD__ . ': no broadcast cache configured!' ); |
| 183 | $this->recordOp( $storeLabel, 'set', 'failure', $startTime ); |
| 184 | return false; |
| 185 | } |
| 186 | |
| 187 | $localServiceName = array_keys( $this->services )[0]; |
| 188 | |
| 189 | // Note: We ignore the local prefix, as we're using the broadcast route instead. |
| 190 | $localService = $this->services[$localServiceName][0]; |
| 191 | |
| 192 | // TODO (T432217) We can demote to debug once this issue is fixed |
| 193 | $this->logger->info( |
| 194 | __METHOD__ . ': setting {memcached-key} on local server {memcached-server}' |
| 195 | . ' with broadcast cache route {route}', |
| 196 | [ |
| 197 | 'memcached-key' => $this->broadcastRoute . $key, |
| 198 | 'memcached-server' => $localServiceName, |
| 199 | 'route' => $this->broadcastRoute |
| 200 | ] |
| 201 | ); |
| 202 | |
| 203 | $success = $localService->set( $this->broadcastRoute . $key, $value, $ttl ); |
| 204 | |
| 205 | if ( !$success ) { |
| 206 | $this->logger->warning( |
| 207 | __METHOD__ . ': failed to set broadcast prefixed {memcached-key} on {memcached-server}' |
| 208 | . ' with error {error_class}: {error}', |
| 209 | [ |
| 210 | 'memcached-key' => $this->broadcastRoute . $key, |
| 211 | 'memcached-server' => $localServiceName, |
| 212 | 'error_class' => ( $localService instanceof Memcached ? $localService->getResultCode() : '?' ), |
| 213 | 'error' => ( $localService instanceof Memcached ? $localService->getResultMessage() : '?' ), |
| 214 | // TODO (T432217) Temporarily log stats in case of Memcached::set failure to diagnose the problem. |
| 215 | // We should remove this in the future, although it's not a very large object: |
| 216 | // https://www.php.net/manual/en/memcached.getstats.php |
| 217 | 'status' => ( $localService instanceof Memcached ? $this->getStats( $localService, $value ) : '?' ), |
| 218 | ] |
| 219 | ); |
| 220 | } else { |
| 221 | // TODO (T432217) We can demote to debug once this issue is fixed |
| 222 | $this->logger->info( |
| 223 | __METHOD__ . ': successfully set broadcast prefixed {memcached-key} on {memcached-server}', |
| 224 | [ |
| 225 | 'memcached-key' => $this->broadcastRoute . $key, |
| 226 | 'memcached-server' => $localServiceName |
| 227 | ] |
| 228 | ); |
| 229 | } |
| 230 | |
| 231 | $this->recordOp( $storeLabel, 'set', $success ? 'success' : 'failure', $startTime ); |
| 232 | |
| 233 | return $success; |
| 234 | } |
| 235 | |
| 236 | /** |
| 237 | * Get selected service stats to show in the MemcachedWrapper::set failure logs |
| 238 | * See: https://github.com/memcached/memcached/blob/master/doc/protocol.txt |
| 239 | * |
| 240 | * Recording the following stats: |
| 241 | * * limit_maxbytes: Number of bytes this server is allowed to use for storage |
| 242 | * * bytes: Current number of bytes used to store items |
| 243 | * * store_too_large: Number of rejected storage requests caused by attempting |
| 244 | * to write a value larget than the -I limit |
| 245 | * * store_no_memory: Number of rejected storage requests caused by exhaustion |
| 246 | * of the -m memory limit (relevant when -M is used) |
| 247 | * * max_connections: Max number of simultaneous connections |
| 248 | * * curr_connections: Number of open connections |
| 249 | * * rejected_connections: Conns rejected in maxconns_fast mode |
| 250 | * * listen_disabled_num: Number of times server has stopped accepting new |
| 251 | * connections (maxconns) |
| 252 | * * accepting_conns: Whether or not server is accepting conns |
| 253 | * * evictions: Number of valid items removed from cache to free memory for new items |
| 254 | * * cmd_set: Cumulative number of storage reqs |
| 255 | * * auth_errors: Number of failed authentications. |
| 256 | * * idle_kicks: Number of connections closed due to reaching their idle timeout. |
| 257 | * * response_obj_oom: Connections closed by lack of memory |
| 258 | * * read_buf_oom: Connections closed by lack of memory |
| 259 | * * proxy_conn_oom: Number of out of memory errors while serving proxy requests |
| 260 | * |
| 261 | * Also compiling the following information: |
| 262 | * * size_serialized and size_json: the size of the value after different serializations |
| 263 | * * serializer: Serializer used before compression |
| 264 | * * compression: Whether payload compression is enabled. |
| 265 | * * compression_type: Algorithm used for compression (zlib, zstd, fastlz) |
| 266 | * |
| 267 | * |
| 268 | * @param Memcached $localService |
| 269 | * @param mixed $value |
| 270 | * @return string |
| 271 | */ |
| 272 | private function getStats( Memcached $localService, mixed $value ): string { |
| 273 | $relevantStats = []; |
| 274 | $relevantKeys = [ |
| 275 | // Size/memory |
| 276 | 'limit_maxbytes', |
| 277 | 'bytes', |
| 278 | 'store_too_large', |
| 279 | 'store_no_memory', |
| 280 | // Server load |
| 281 | 'max_connections', |
| 282 | 'curr_connections', |
| 283 | 'rejected_connections', |
| 284 | 'listen_disabled_num', |
| 285 | 'accepting_conns', |
| 286 | // Operations |
| 287 | 'evictions', |
| 288 | 'cmd_set', |
| 289 | 'auth_errors', |
| 290 | 'idle_kicks', |
| 291 | 'response_obj_oom', |
| 292 | 'read_buf_oom', |
| 293 | 'proxy_conn_oom' |
| 294 | ]; |
| 295 | |
| 296 | // Value size diagnostics |
| 297 | $relevantStats['size_serialized'] = strlen( serialize( $value ) ); |
| 298 | $relevantStats['size_json'] = strlen( json_encode( $value ) ); |
| 299 | $relevantStats['compression_enabled'] = $localService->getOption( Memcached::OPT_COMPRESSION ); |
| 300 | $relevantStats['compression_type'] = $localService->getOption( Memcached::OPT_COMPRESSION_TYPE ); |
| 301 | $relevantStats['serializer'] = $localService->getOption( Memcached::OPT_SERIALIZER ); |
| 302 | |
| 303 | // If no stats, log status as unavailable |
| 304 | $stats = $localService->getStats(); |
| 305 | if ( !$stats ) { |
| 306 | $relevantStats['server'] = 'unavailable'; |
| 307 | return json_encode( $relevantStats ); |
| 308 | } |
| 309 | |
| 310 | // Log keys of all available memcached servers (should only be one, the local, |
| 311 | // but let's make sure that the stats being logged belong to the right service) |
| 312 | $relevantStats[ 'server' ] = array_keys( $stats ); |
| 313 | $server = array_key_first( $stats ); |
| 314 | |
| 315 | // Log only the relevant keys, if available |
| 316 | foreach ( $relevantKeys as $statKey ) { |
| 317 | $relevantStats[ $statKey ] = $stats[ $server ][ $statKey ] ?? '?'; |
| 318 | } |
| 319 | |
| 320 | return json_encode( $relevantStats ); |
| 321 | } |
| 322 | |
| 323 | /** |
| 324 | * Attempt to delete the given key via the broadcast route (setting a tombstone value) |
| 325 | * |
| 326 | * @param string $key The key to delete |
| 327 | * @param string $storeLabel Identifies the calling store, for observability (e.g. 'aw_fragment') |
| 328 | * @return bool Whether the delete operation succeeded on the broadcast cache. |
| 329 | */ |
| 330 | public function delete( string $key, string $storeLabel = '' ): bool { |
| 331 | $this->logger->debug( __METHOD__ . ': deleting {key} by setting a tombstone value', [ 'key' => $key ] ); |
| 332 | $startTime = hrtime( true ); |
| 333 | $success = $this->set( $key, self::TOMBSTONE, self::TTL_MINUTE, $storeLabel ); |
| 334 | $this->recordOp( $storeLabel, 'delete', $success ? 'success' : 'failure', $startTime ); |
| 335 | return $success; |
| 336 | } |
| 337 | |
| 338 | /** |
| 339 | * Utility method to create a cache key by concatenating parts with a colon. |
| 340 | * This is used to ensure consistent cache key formatting across the codebase. |
| 341 | * |
| 342 | * If the cache service is BagOStuff, fallback to its makeKey method to ensure |
| 343 | * that the constraints for each implementation of BagOStuff are followed. |
| 344 | * |
| 345 | * If the cache service is Memcached, implement its own logic for correct ASCII |
| 346 | * encoding and limited key size (250 characters max) |
| 347 | * |
| 348 | * @see MemcachedBagOStuff::makeKeyInternal |
| 349 | * @param string $prefix A prefix to identify the type of cache entry (e.g. 'functioncall') |
| 350 | * @param string ...$parts The parts to concatenate into a cache key |
| 351 | * @throws InvalidArgumentException If no parts are provided |
| 352 | * @return string The generated cache key |
| 353 | */ |
| 354 | public function makeKey( string $prefix, string ...$parts ): string { |
| 355 | // Get only our DC local service. |
| 356 | $localServiceName = array_key_first( $this->services ); |
| 357 | [ $localService, $localPrefix ] = $this->services[ $localServiceName ]; |
| 358 | |
| 359 | // Fallback to their own makeKey logic when the service is BagOStuff |
| 360 | // E.g. SqlBagOStuff keys have a maximum length of 250 characters |
| 361 | if ( $localService instanceof BagOStuff ) { |
| 362 | return $localService->makeKey( $prefix, ...$parts ); |
| 363 | } |
| 364 | |
| 365 | return $this->makeMemcachedKey( $prefix, ...$parts ); |
| 366 | } |
| 367 | |
| 368 | /** |
| 369 | * Utility method to create a cache key for a Memcached backed cache service. |
| 370 | * Concatenates all string parts and, if the result exceeds 205 characters |
| 371 | * (250 max, minus 45 for prefixes) hashes the parts and prepends the prefix. |
| 372 | * |
| 373 | * @param string $prefix A prefix to identify the type of cache entry (e.g. 'functioncall') |
| 374 | * @param string ...$parts The parts to concatenate into a cache key |
| 375 | * @return string The generated cache key |
| 376 | */ |
| 377 | protected function makeMemcachedKey( string $prefix, string ...$parts ): string { |
| 378 | // Keep 45 characters for prefixes (e.g. 'wikilambda:WikiLambdaClientFunctionCall') |
| 379 | $maxLength = 205; |
| 380 | |
| 381 | // Add the prefix as the last step, just in case we need to hash the parts |
| 382 | $key = ''; |
| 383 | foreach ( $parts as $part ) { |
| 384 | $part = strtr( $part ?? '', ' ', '_' ); |
| 385 | |
| 386 | // Make sure %, #, and non-ASCII chars are escaped |
| 387 | $part = preg_replace_callback( |
| 388 | '/[^\x21-\x22\x24\x26-\x39\x3b-\x7e]+/', |
| 389 | static fn ( $m ) => rawurlencode( $m[0] ), |
| 390 | $part |
| 391 | ); |
| 392 | |
| 393 | $key .= ':' . $part; |
| 394 | } |
| 395 | |
| 396 | // If the joint and encoded parts is larger than maxLength, hash it |
| 397 | if ( strlen( $key ) > $maxLength ) { |
| 398 | $key = '#' . hash( 'sha256', $key ); |
| 399 | } |
| 400 | |
| 401 | // Add the prefix; the result should not be longer than 250 characters |
| 402 | return $prefix . ':' . $key; |
| 403 | } |
| 404 | } |