MemcachedAdapter.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Cache\Adapter;
  11. use Symfony\Component\Cache\Exception\CacheException;
  12. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  13. use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
  14. use Symfony\Component\Cache\Marshaller\MarshallerInterface;
  15. /**
  16. * @author Rob Frawley 2nd <rmf@src.run>
  17. * @author Nicolas Grekas <p@tchwork.com>
  18. */
  19. class MemcachedAdapter extends AbstractAdapter
  20. {
  21. /**
  22. * We are replacing characters that are illegal in Memcached keys with reserved characters from
  23. * {@see \Symfony\Contracts\Cache\ItemInterface::RESERVED_CHARACTERS} that are legal in Memcached.
  24. * Note: don’t use {@see \Symfony\Component\Cache\Adapter\AbstractAdapter::NS_SEPARATOR}.
  25. */
  26. private const RESERVED_MEMCACHED = " \n\r\t\v\f\0";
  27. private const RESERVED_PSR6 = '@()\{}/';
  28. protected $maxIdLength = 250;
  29. private $marshaller;
  30. private $client;
  31. private $lazyClient;
  32. /**
  33. * Using a MemcachedAdapter with a TagAwareAdapter for storing tags is discouraged.
  34. * Using a RedisAdapter is recommended instead. If you cannot do otherwise, be aware that:
  35. * - the Memcached::OPT_BINARY_PROTOCOL must be enabled
  36. * (that's the default when using MemcachedAdapter::createConnection());
  37. * - tags eviction by Memcached's LRU algorithm will break by-tags invalidation;
  38. * your Memcached memory should be large enough to never trigger LRU.
  39. *
  40. * Using a MemcachedAdapter as a pure items store is fine.
  41. */
  42. public function __construct(\Memcached $client, string $namespace = '', int $defaultLifetime = 0, ?MarshallerInterface $marshaller = null)
  43. {
  44. if (!static::isSupported()) {
  45. throw new CacheException('Memcached '.(\PHP_VERSION_ID >= 80100 ? '> 3.1.5' : '>= 2.2.0').' is required.');
  46. }
  47. if ('Memcached' === \get_class($client)) {
  48. $opt = $client->getOption(\Memcached::OPT_SERIALIZER);
  49. if (\Memcached::SERIALIZER_PHP !== $opt && \Memcached::SERIALIZER_IGBINARY !== $opt) {
  50. throw new CacheException('MemcachedAdapter: "serializer" option must be "php" or "igbinary".');
  51. }
  52. $this->maxIdLength -= \strlen($client->getOption(\Memcached::OPT_PREFIX_KEY));
  53. $this->client = $client;
  54. } else {
  55. $this->lazyClient = $client;
  56. }
  57. parent::__construct($namespace, $defaultLifetime);
  58. $this->enableVersioning();
  59. $this->marshaller = $marshaller ?? new DefaultMarshaller();
  60. }
  61. public static function isSupported()
  62. {
  63. return \extension_loaded('memcached') && version_compare(phpversion('memcached'), \PHP_VERSION_ID >= 80100 ? '3.1.6' : '2.2.0', '>=');
  64. }
  65. /**
  66. * Creates a Memcached instance.
  67. *
  68. * By default, the binary protocol, no block, and libketama compatible options are enabled.
  69. *
  70. * Examples for servers:
  71. * - 'memcached://user:pass@localhost?weight=33'
  72. * - [['localhost', 11211, 33]]
  73. *
  74. * @param array[]|string|string[] $servers An array of servers, a DSN, or an array of DSNs
  75. *
  76. * @return \Memcached
  77. *
  78. * @throws \ErrorException When invalid options or servers are provided
  79. */
  80. public static function createConnection($servers, array $options = [])
  81. {
  82. if (\is_string($servers)) {
  83. $servers = [$servers];
  84. } elseif (!\is_array($servers)) {
  85. throw new InvalidArgumentException(sprintf('MemcachedAdapter::createClient() expects array or string as first argument, "%s" given.', get_debug_type($servers)));
  86. }
  87. if (!static::isSupported()) {
  88. throw new CacheException('Memcached '.(\PHP_VERSION_ID >= 80100 ? '> 3.1.5' : '>= 2.2.0').' is required.');
  89. }
  90. set_error_handler(function ($type, $msg, $file, $line) { throw new \ErrorException($msg, 0, $type, $file, $line); });
  91. try {
  92. $client = new \Memcached($options['persistent_id'] ?? null);
  93. $username = $options['username'] ?? null;
  94. $password = $options['password'] ?? null;
  95. // parse any DSN in $servers
  96. foreach ($servers as $i => $dsn) {
  97. if (\is_array($dsn)) {
  98. continue;
  99. }
  100. if (!str_starts_with($dsn, 'memcached:')) {
  101. throw new InvalidArgumentException('Invalid Memcached DSN: it does not start with "memcached:".');
  102. }
  103. $params = preg_replace_callback('#^memcached:(//)?(?:([^@]*+)@)?#', function ($m) use (&$username, &$password) {
  104. if (!empty($m[2])) {
  105. [$username, $password] = explode(':', $m[2], 2) + [1 => null];
  106. $username = rawurldecode($username);
  107. $password = null !== $password ? rawurldecode($password) : null;
  108. }
  109. return 'file:'.($m[1] ?? '');
  110. }, $dsn);
  111. if (false === $params = parse_url($params)) {
  112. throw new InvalidArgumentException('Invalid Memcached DSN.');
  113. }
  114. $query = $hosts = [];
  115. if (isset($params['query'])) {
  116. parse_str($params['query'], $query);
  117. if (isset($query['host'])) {
  118. if (!\is_array($hosts = $query['host'])) {
  119. throw new InvalidArgumentException('Invalid Memcached DSN: query parameter "host" must be an array.');
  120. }
  121. foreach ($hosts as $host => $weight) {
  122. if (false === $port = strrpos($host, ':')) {
  123. $hosts[$host] = [$host, 11211, (int) $weight];
  124. } else {
  125. $hosts[$host] = [substr($host, 0, $port), (int) substr($host, 1 + $port), (int) $weight];
  126. }
  127. }
  128. $hosts = array_values($hosts);
  129. unset($query['host']);
  130. }
  131. if ($hosts && !isset($params['host']) && !isset($params['path'])) {
  132. unset($servers[$i]);
  133. $servers = array_merge($servers, $hosts);
  134. continue;
  135. }
  136. }
  137. if (!isset($params['host']) && !isset($params['path'])) {
  138. throw new InvalidArgumentException('Invalid Memcached DSN: missing host or path.');
  139. }
  140. if (isset($params['path']) && preg_match('#/(\d+)$#', $params['path'], $m)) {
  141. $params['weight'] = $m[1];
  142. $params['path'] = substr($params['path'], 0, -\strlen($m[0]));
  143. }
  144. $params += [
  145. 'host' => $params['host'] ?? $params['path'],
  146. 'port' => isset($params['host']) ? 11211 : null,
  147. 'weight' => 0,
  148. ];
  149. if ($query) {
  150. $params += $query;
  151. $options = $query + $options;
  152. }
  153. $servers[$i] = [$params['host'], $params['port'], $params['weight']];
  154. if ($hosts) {
  155. $servers = array_merge($servers, $hosts);
  156. }
  157. }
  158. // set client's options
  159. unset($options['persistent_id'], $options['username'], $options['password'], $options['weight'], $options['lazy']);
  160. $options = array_change_key_case($options, \CASE_UPPER);
  161. $client->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
  162. $client->setOption(\Memcached::OPT_NO_BLOCK, true);
  163. $client->setOption(\Memcached::OPT_TCP_NODELAY, true);
  164. if (!\array_key_exists('LIBKETAMA_COMPATIBLE', $options) && !\array_key_exists(\Memcached::OPT_LIBKETAMA_COMPATIBLE, $options)) {
  165. $client->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
  166. }
  167. foreach ($options as $name => $value) {
  168. if (\is_int($name)) {
  169. continue;
  170. }
  171. if ('HASH' === $name || 'SERIALIZER' === $name || 'DISTRIBUTION' === $name) {
  172. $value = \constant('Memcached::'.$name.'_'.strtoupper($value));
  173. }
  174. unset($options[$name]);
  175. if (\defined('Memcached::OPT_'.$name)) {
  176. $options[\constant('Memcached::OPT_'.$name)] = $value;
  177. }
  178. }
  179. $client->setOptions($options + [\Memcached::OPT_SERIALIZER => \Memcached::SERIALIZER_PHP]);
  180. // set client's servers, taking care of persistent connections
  181. if (!$client->isPristine()) {
  182. $oldServers = [];
  183. foreach ($client->getServerList() as $server) {
  184. $oldServers[] = [$server['host'], $server['port']];
  185. }
  186. $newServers = [];
  187. foreach ($servers as $server) {
  188. if (1 < \count($server)) {
  189. $server = array_values($server);
  190. unset($server[2]);
  191. $server[1] = (int) $server[1];
  192. }
  193. $newServers[] = $server;
  194. }
  195. if ($oldServers !== $newServers) {
  196. $client->resetServerList();
  197. $client->addServers($servers);
  198. }
  199. } else {
  200. $client->addServers($servers);
  201. }
  202. if (null !== $username || null !== $password) {
  203. if (!method_exists($client, 'setSaslAuthData')) {
  204. trigger_error('Missing SASL support: the memcached extension must be compiled with --enable-memcached-sasl.');
  205. }
  206. $client->setSaslAuthData($username, $password);
  207. }
  208. return $client;
  209. } finally {
  210. restore_error_handler();
  211. }
  212. }
  213. /**
  214. * {@inheritdoc}
  215. */
  216. protected function doSave(array $values, int $lifetime)
  217. {
  218. if (!$values = $this->marshaller->marshall($values, $failed)) {
  219. return $failed;
  220. }
  221. if ($lifetime && $lifetime > 30 * 86400) {
  222. $lifetime += time();
  223. }
  224. $encodedValues = [];
  225. foreach ($values as $key => $value) {
  226. $encodedValues[self::encodeKey($key)] = $value;
  227. }
  228. return $this->checkResultCode($this->getClient()->setMulti($encodedValues, $lifetime)) ? $failed : false;
  229. }
  230. /**
  231. * {@inheritdoc}
  232. */
  233. protected function doFetch(array $ids)
  234. {
  235. try {
  236. $encodedIds = array_map([__CLASS__, 'encodeKey'], $ids);
  237. $encodedResult = $this->checkResultCode($this->getClient()->getMulti($encodedIds));
  238. $result = [];
  239. foreach ($encodedResult as $key => $value) {
  240. $result[self::decodeKey($key)] = $this->marshaller->unmarshall($value);
  241. }
  242. return $result;
  243. } catch (\Error $e) {
  244. throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine());
  245. }
  246. }
  247. /**
  248. * {@inheritdoc}
  249. */
  250. protected function doHave(string $id)
  251. {
  252. return false !== $this->getClient()->get(self::encodeKey($id)) || $this->checkResultCode(\Memcached::RES_SUCCESS === $this->client->getResultCode());
  253. }
  254. /**
  255. * {@inheritdoc}
  256. */
  257. protected function doDelete(array $ids)
  258. {
  259. $ok = true;
  260. $encodedIds = array_map([__CLASS__, 'encodeKey'], $ids);
  261. foreach ($this->checkResultCode($this->getClient()->deleteMulti($encodedIds)) as $result) {
  262. if (\Memcached::RES_SUCCESS !== $result && \Memcached::RES_NOTFOUND !== $result) {
  263. $ok = false;
  264. }
  265. }
  266. return $ok;
  267. }
  268. /**
  269. * {@inheritdoc}
  270. */
  271. protected function doClear(string $namespace)
  272. {
  273. return '' === $namespace && $this->getClient()->flush();
  274. }
  275. private function checkResultCode($result)
  276. {
  277. $code = $this->client->getResultCode();
  278. if (\Memcached::RES_SUCCESS === $code || \Memcached::RES_NOTFOUND === $code) {
  279. return $result;
  280. }
  281. throw new CacheException('MemcachedAdapter client error: '.strtolower($this->client->getResultMessage()));
  282. }
  283. private function getClient(): \Memcached
  284. {
  285. if ($this->client) {
  286. return $this->client;
  287. }
  288. $opt = $this->lazyClient->getOption(\Memcached::OPT_SERIALIZER);
  289. if (\Memcached::SERIALIZER_PHP !== $opt && \Memcached::SERIALIZER_IGBINARY !== $opt) {
  290. throw new CacheException('MemcachedAdapter: "serializer" option must be "php" or "igbinary".');
  291. }
  292. if ('' !== $prefix = (string) $this->lazyClient->getOption(\Memcached::OPT_PREFIX_KEY)) {
  293. throw new CacheException(sprintf('MemcachedAdapter: "prefix_key" option must be empty when using proxified connections, "%s" given.', $prefix));
  294. }
  295. return $this->client = $this->lazyClient;
  296. }
  297. private static function encodeKey(string $key): string
  298. {
  299. return strtr($key, self::RESERVED_MEMCACHED, self::RESERVED_PSR6);
  300. }
  301. private static function decodeKey(string $key): string
  302. {
  303. return strtr($key, self::RESERVED_PSR6, self::RESERVED_MEMCACHED);
  304. }
  305. }