MediaWiki  master
MemcachedBagOStuff.php
Go to the documentation of this file.
1 <?php
30  function __construct( array $params ) {
31  parent::__construct( $params );
32 
33  $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_BE; // unreliable
34  $this->segmentationSize = $params['maxPreferedKeySize'] ?? 917504; // < 1MiB
35  }
36 
45  public function makeKeyInternal( $keyspace, $args ) {
46  // Memcached keys have a maximum length of 255 characters. From that,
47  // subtract the number of characters we need for the keyspace and for
48  // the separator character needed for each argument. To handle some
49  // custom prefixes used by thing like WANObjectCache, limit to 205.
50  $charsLeft = 205 - strlen( $keyspace ) - count( $args );
51 
52  foreach ( $args as &$arg ) {
53  $arg = strtr( $arg, ' ', '_' );
54 
55  // Make sure %, #, and non-ASCII chars are escaped
56  $arg = preg_replace_callback(
57  '/[^\x21-\x22\x24\x26-\x39\x3b-\x7e]+/',
58  function ( $m ) {
59  return rawurlencode( $m[0] );
60  },
61  $arg
62  );
63 
64  // 33 = 32 characters for the MD5 + 1 for the '#' prefix.
65  if ( $charsLeft > 33 && strlen( $arg ) > $charsLeft ) {
66  $arg = '#' . md5( $arg );
67  }
68 
69  $charsLeft -= strlen( $arg );
70  }
71 
72  if ( $charsLeft < 0 ) {
73  return $keyspace . ':BagOStuff-long-key:##' . md5( implode( ':', $args ) );
74  }
75 
76  return $keyspace . ':' . implode( ':', $args );
77  }
78 
87  public function validateKeyEncoding( $key ) {
88  if ( preg_match( '/[^\x21-\x7e]+/', $key ) ) {
89  throw new Exception( "Key contains invalid characters: $key" );
90  }
91  return $key;
92  }
93 
98  protected function fixExpiry( $exptime ) {
99  if ( $exptime < 0 ) {
100  // The PECL driver does not seem to like negative relative values
101  $expiresAt = $this->getCurrentTime() + $exptime;
102  } elseif ( $this->isRelativeExpiration( $exptime ) ) {
103  // TTLs higher than 30 days will be detected as absolute TTLs
104  // (UNIX timestamps), and will result in the cache entry being
105  // discarded immediately because the expiry is in the past.
106  // Clamp expires >30d at 30d, unless they're >=1e9 in which
107  // case they are likely to really be absolute (1e9 = 2011-09-09)
108  $expiresAt = min( $exptime, self::TTL_MONTH );
109  } else {
110  $expiresAt = $exptime;
111  }
112 
113  return (int)$expiresAt;
114  }
115 }
getCurrentTime()
Definition: BagOStuff.php:523
validateKeyEncoding( $key)
Ensure that a key is safe to use (contains no control characters and no characters above the ASCII ra...
if( $line===false) $args
Definition: cdb.php:64
__construct(array $params)
Storage medium specific cache for storing items (e.g.
makeKeyInternal( $keyspace, $args)
Construct a cache key.
Base class for memcached clients.