RedisTrait.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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\Traits;
  11. use Predis\Command\Redis\UNLINK;
  12. use Predis\Connection\Aggregate\ClusterInterface;
  13. use Predis\Connection\Aggregate\RedisCluster;
  14. use Predis\Connection\Aggregate\ReplicationInterface;
  15. use Predis\Response\ErrorInterface;
  16. use Predis\Response\Status;
  17. use Symfony\Component\Cache\Exception\CacheException;
  18. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  19. use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
  20. use Symfony\Component\Cache\Marshaller\MarshallerInterface;
  21. /**
  22. * @author Aurimas Niekis <aurimas@niekis.lt>
  23. * @author Nicolas Grekas <p@tchwork.com>
  24. *
  25. * @internal
  26. */
  27. trait RedisTrait
  28. {
  29. private static $defaultConnectionOptions = [
  30. 'class' => null,
  31. 'persistent' => 0,
  32. 'persistent_id' => null,
  33. 'timeout' => 30,
  34. 'read_timeout' => 0,
  35. 'retry_interval' => 0,
  36. 'tcp_keepalive' => 0,
  37. 'lazy' => null,
  38. 'redis_cluster' => false,
  39. 'redis_sentinel' => null,
  40. 'dbindex' => 0,
  41. 'failover' => 'none',
  42. 'ssl' => null, // see https://php.net/context.ssl
  43. ];
  44. private $redis;
  45. private $marshaller;
  46. /**
  47. * @param \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $redis
  48. */
  49. private function init($redis, string $namespace, int $defaultLifetime, ?MarshallerInterface $marshaller)
  50. {
  51. parent::__construct($namespace, $defaultLifetime);
  52. if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace, $match)) {
  53. throw new InvalidArgumentException(sprintf('RedisAdapter namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
  54. }
  55. if (!$redis instanceof \Redis && !$redis instanceof \RedisArray && !$redis instanceof \RedisCluster && !$redis instanceof \Predis\ClientInterface && !$redis instanceof RedisProxy && !$redis instanceof RedisClusterProxy) {
  56. throw new InvalidArgumentException(sprintf('"%s()" expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\ClientInterface, "%s" given.', __METHOD__, get_debug_type($redis)));
  57. }
  58. if ($redis instanceof \Predis\ClientInterface && $redis->getOptions()->exceptions) {
  59. $options = clone $redis->getOptions();
  60. \Closure::bind(function () { $this->options['exceptions'] = false; }, $options, $options)();
  61. $redis = new $redis($redis->getConnection(), $options);
  62. }
  63. $this->redis = $redis;
  64. $this->marshaller = $marshaller ?? new DefaultMarshaller();
  65. }
  66. /**
  67. * Creates a Redis connection using a DSN configuration.
  68. *
  69. * Example DSN:
  70. * - redis://localhost
  71. * - redis://example.com:1234
  72. * - redis://secret@example.com/13
  73. * - redis:///var/run/redis.sock
  74. * - redis://secret@/var/run/redis.sock/13
  75. *
  76. * @param array $options See self::$defaultConnectionOptions
  77. *
  78. * @return \Redis|\RedisArray|\RedisCluster|RedisClusterProxy|RedisProxy|\Predis\ClientInterface According to the "class" option
  79. *
  80. * @throws InvalidArgumentException when the DSN is invalid
  81. */
  82. public static function createConnection(string $dsn, array $options = [])
  83. {
  84. if (str_starts_with($dsn, 'redis:')) {
  85. $scheme = 'redis';
  86. } elseif (str_starts_with($dsn, 'rediss:')) {
  87. $scheme = 'rediss';
  88. } else {
  89. throw new InvalidArgumentException('Invalid Redis DSN: it does not start with "redis[s]:".');
  90. }
  91. if (!\extension_loaded('redis') && !class_exists(\Predis\Client::class)) {
  92. throw new CacheException('Cannot find the "redis" extension nor the "predis/predis" package.');
  93. }
  94. $params = preg_replace_callback('#^'.$scheme.':(//)?(?:(?:[^:@]*+:)?([^@]*+)@)?#', function ($m) use (&$auth) {
  95. if (isset($m[2])) {
  96. $auth = rawurldecode($m[2]);
  97. if ('' === $auth) {
  98. $auth = null;
  99. }
  100. }
  101. return 'file:'.($m[1] ?? '');
  102. }, $dsn);
  103. if (false === $params = parse_url($params)) {
  104. throw new InvalidArgumentException('Invalid Redis DSN.');
  105. }
  106. $query = $hosts = [];
  107. $tls = 'rediss' === $scheme;
  108. $tcpScheme = $tls ? 'tls' : 'tcp';
  109. if (isset($params['query'])) {
  110. parse_str($params['query'], $query);
  111. if (isset($query['host'])) {
  112. if (!\is_array($hosts = $query['host'])) {
  113. throw new InvalidArgumentException('Invalid Redis DSN: query parameter "host" must be an array.');
  114. }
  115. foreach ($hosts as $host => $parameters) {
  116. if (\is_string($parameters)) {
  117. parse_str($parameters, $parameters);
  118. }
  119. if (false === $i = strrpos($host, ':')) {
  120. $hosts[$host] = ['scheme' => $tcpScheme, 'host' => $host, 'port' => 6379] + $parameters;
  121. } elseif ($port = (int) substr($host, 1 + $i)) {
  122. $hosts[$host] = ['scheme' => $tcpScheme, 'host' => substr($host, 0, $i), 'port' => $port] + $parameters;
  123. } else {
  124. $hosts[$host] = ['scheme' => 'unix', 'path' => substr($host, 0, $i)] + $parameters;
  125. }
  126. }
  127. $hosts = array_values($hosts);
  128. }
  129. }
  130. if (isset($params['host']) || isset($params['path'])) {
  131. if (!isset($params['dbindex']) && isset($params['path'])) {
  132. if (preg_match('#/(\d+)?$#', $params['path'], $m)) {
  133. $params['dbindex'] = $m[1] ?? '0';
  134. $params['path'] = substr($params['path'], 0, -\strlen($m[0]));
  135. } elseif (isset($params['host'])) {
  136. throw new InvalidArgumentException('Invalid Redis DSN: query parameter "dbindex" must be a number.');
  137. }
  138. }
  139. if (isset($params['host'])) {
  140. array_unshift($hosts, ['scheme' => $tcpScheme, 'host' => $params['host'], 'port' => $params['port'] ?? 6379]);
  141. } else {
  142. array_unshift($hosts, ['scheme' => 'unix', 'path' => $params['path']]);
  143. }
  144. }
  145. if (!$hosts) {
  146. throw new InvalidArgumentException('Invalid Redis DSN: missing host.');
  147. }
  148. $params += $query + $options + self::$defaultConnectionOptions;
  149. if (isset($params['redis_sentinel']) && !class_exists(\Predis\Client::class) && !class_exists(\RedisSentinel::class)) {
  150. throw new CacheException('Redis Sentinel support requires the "predis/predis" package or the "redis" extension v5.2 or higher.');
  151. }
  152. if (isset($params['lazy'])) {
  153. $params['lazy'] = filter_var($params['lazy'], \FILTER_VALIDATE_BOOLEAN);
  154. }
  155. $params['redis_cluster'] = filter_var($params['redis_cluster'], \FILTER_VALIDATE_BOOLEAN);
  156. if ($params['redis_cluster'] && isset($params['redis_sentinel'])) {
  157. throw new InvalidArgumentException('Cannot use both "redis_cluster" and "redis_sentinel" at the same time.');
  158. }
  159. if (null === $params['class'] && \extension_loaded('redis')) {
  160. $class = $params['redis_cluster'] ? \RedisCluster::class : (1 < \count($hosts) && !isset($params['redis_sentinel']) ? \RedisArray::class : \Redis::class);
  161. } else {
  162. $class = $params['class'] ?? \Predis\Client::class;
  163. if (isset($params['redis_sentinel']) && !is_a($class, \Predis\Client::class, true) && !class_exists(\RedisSentinel::class)) {
  164. throw new CacheException(sprintf('Cannot use Redis Sentinel: class "%s" does not extend "Predis\Client" and ext-redis >= 5.2 not found.', $class));
  165. }
  166. }
  167. if (is_a($class, \Redis::class, true)) {
  168. $connect = $params['persistent'] || $params['persistent_id'] ? 'pconnect' : 'connect';
  169. $redis = new $class();
  170. $initializer = static function ($redis) use ($connect, $params, $auth, $hosts, $tls) {
  171. $hostIndex = 0;
  172. do {
  173. $host = $hosts[$hostIndex]['host'] ?? $hosts[$hostIndex]['path'];
  174. $port = $hosts[$hostIndex]['port'] ?? 0;
  175. $passAuth = \defined('Redis::OPT_NULL_MULTIBULK_AS_NULL') && isset($params['auth']);
  176. $address = false;
  177. if (isset($hosts[$hostIndex]['host']) && $tls) {
  178. $host = 'tls://'.$host;
  179. }
  180. if (!isset($params['redis_sentinel'])) {
  181. break;
  182. }
  183. if (version_compare(phpversion('redis'), '6.0.0', '>=')) {
  184. $options = [
  185. 'host' => $host,
  186. 'port' => $port,
  187. 'connectTimeout' => $params['timeout'],
  188. 'persistent' => $params['persistent_id'],
  189. 'retryInterval' => $params['retry_interval'],
  190. 'readTimeout' => $params['read_timeout'],
  191. ];
  192. if ($passAuth) {
  193. $options['auth'] = $params['auth'];
  194. }
  195. $sentinel = new \RedisSentinel($options);
  196. } else {
  197. $extra = $passAuth ? [$params['auth']] : [];
  198. $sentinel = new \RedisSentinel($host, $port, $params['timeout'], (string) $params['persistent_id'], $params['retry_interval'], $params['read_timeout'], ...$extra);
  199. }
  200. try {
  201. if ($address = $sentinel->getMasterAddrByName($params['redis_sentinel'])) {
  202. [$host, $port] = $address;
  203. }
  204. } catch (\RedisException $e) {
  205. }
  206. } while (++$hostIndex < \count($hosts) && !$address);
  207. if (isset($params['redis_sentinel']) && !$address) {
  208. throw new InvalidArgumentException(sprintf('Failed to retrieve master information from sentinel "%s".', $params['redis_sentinel']));
  209. }
  210. try {
  211. $extra = [
  212. 'stream' => $params['ssl'] ?? null,
  213. ];
  214. $booleanStreamOptions = [
  215. 'allow_self_signed',
  216. 'capture_peer_cert',
  217. 'capture_peer_cert_chain',
  218. 'disable_compression',
  219. 'SNI_enabled',
  220. 'verify_peer',
  221. 'verify_peer_name',
  222. ];
  223. foreach ($extra['stream'] ?? [] as $streamOption => $value) {
  224. if (\in_array($streamOption, $booleanStreamOptions, true) && \is_string($value)) {
  225. $extra['stream'][$streamOption] = filter_var($value, \FILTER_VALIDATE_BOOL);
  226. }
  227. }
  228. if (isset($params['auth'])) {
  229. $extra['auth'] = $params['auth'];
  230. }
  231. @$redis->{$connect}($host, $port, $params['timeout'], (string) $params['persistent_id'], $params['retry_interval'], $params['read_timeout'], ...\defined('Redis::SCAN_PREFIX') ? [$extra] : []);
  232. set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
  233. try {
  234. $isConnected = $redis->isConnected();
  235. } finally {
  236. restore_error_handler();
  237. }
  238. if (!$isConnected) {
  239. $error = preg_match('/^Redis::p?connect\(\): (.*)/', $error ?? $redis->getLastError() ?? '', $error) ? sprintf(' (%s)', $error[1]) : '';
  240. throw new InvalidArgumentException('Redis connection failed: '.$error.'.');
  241. }
  242. if ((null !== $auth && !$redis->auth($auth))
  243. || ($params['dbindex'] && !$redis->select($params['dbindex']))
  244. ) {
  245. $e = preg_replace('/^ERR /', '', $redis->getLastError());
  246. throw new InvalidArgumentException('Redis connection failed: '.$e.'.');
  247. }
  248. if (0 < $params['tcp_keepalive'] && \defined('Redis::OPT_TCP_KEEPALIVE')) {
  249. $redis->setOption(\Redis::OPT_TCP_KEEPALIVE, $params['tcp_keepalive']);
  250. }
  251. } catch (\RedisException $e) {
  252. throw new InvalidArgumentException('Redis connection failed: '.$e->getMessage());
  253. }
  254. return true;
  255. };
  256. if ($params['lazy']) {
  257. $redis = new RedisProxy($redis, $initializer);
  258. } else {
  259. $initializer($redis);
  260. }
  261. } elseif (is_a($class, \RedisArray::class, true)) {
  262. foreach ($hosts as $i => $host) {
  263. switch ($host['scheme']) {
  264. case 'tcp': $hosts[$i] = $host['host'].':'.$host['port']; break;
  265. case 'tls': $hosts[$i] = 'tls://'.$host['host'].':'.$host['port']; break;
  266. default: $hosts[$i] = $host['path'];
  267. }
  268. }
  269. $params['lazy_connect'] = $params['lazy'] ?? true;
  270. $params['connect_timeout'] = $params['timeout'];
  271. try {
  272. $redis = new $class($hosts, $params);
  273. } catch (\RedisClusterException $e) {
  274. throw new InvalidArgumentException('Redis connection failed: '.$e->getMessage());
  275. }
  276. if (0 < $params['tcp_keepalive'] && \defined('Redis::OPT_TCP_KEEPALIVE')) {
  277. $redis->setOption(\Redis::OPT_TCP_KEEPALIVE, $params['tcp_keepalive']);
  278. }
  279. } elseif (is_a($class, \RedisCluster::class, true)) {
  280. $initializer = static function () use ($class, $params, $hosts) {
  281. foreach ($hosts as $i => $host) {
  282. switch ($host['scheme']) {
  283. case 'tcp': $hosts[$i] = $host['host'].':'.$host['port']; break;
  284. case 'tls': $hosts[$i] = 'tls://'.$host['host'].':'.$host['port']; break;
  285. default: $hosts[$i] = $host['path'];
  286. }
  287. }
  288. try {
  289. $redis = new $class(null, $hosts, $params['timeout'], $params['read_timeout'], (bool) $params['persistent'], $params['auth'] ?? '', ...\defined('Redis::SCAN_PREFIX') ? [$params['ssl'] ?? null] : []);
  290. } catch (\RedisClusterException $e) {
  291. throw new InvalidArgumentException('Redis connection failed: '.$e->getMessage());
  292. }
  293. if (0 < $params['tcp_keepalive'] && \defined('Redis::OPT_TCP_KEEPALIVE')) {
  294. $redis->setOption(\Redis::OPT_TCP_KEEPALIVE, $params['tcp_keepalive']);
  295. }
  296. switch ($params['failover']) {
  297. case 'error': $redis->setOption(\RedisCluster::OPT_SLAVE_FAILOVER, \RedisCluster::FAILOVER_ERROR); break;
  298. case 'distribute': $redis->setOption(\RedisCluster::OPT_SLAVE_FAILOVER, \RedisCluster::FAILOVER_DISTRIBUTE); break;
  299. case 'slaves': $redis->setOption(\RedisCluster::OPT_SLAVE_FAILOVER, \RedisCluster::FAILOVER_DISTRIBUTE_SLAVES); break;
  300. }
  301. return $redis;
  302. };
  303. $redis = $params['lazy'] ? new RedisClusterProxy($initializer) : $initializer();
  304. } elseif (is_a($class, \Predis\ClientInterface::class, true)) {
  305. if ($params['redis_cluster']) {
  306. $params['cluster'] = 'redis';
  307. } elseif (isset($params['redis_sentinel'])) {
  308. $params['replication'] = 'sentinel';
  309. $params['service'] = $params['redis_sentinel'];
  310. }
  311. $params += ['parameters' => []];
  312. $params['parameters'] += [
  313. 'persistent' => $params['persistent'],
  314. 'timeout' => $params['timeout'],
  315. 'read_write_timeout' => $params['read_timeout'],
  316. 'tcp_nodelay' => true,
  317. ];
  318. if ($params['dbindex']) {
  319. $params['parameters']['database'] = $params['dbindex'];
  320. }
  321. if (null !== $auth) {
  322. $params['parameters']['password'] = $auth;
  323. }
  324. if (isset($params['ssl'])) {
  325. foreach ($hosts as $i => $host) {
  326. if (!isset($host['ssl'])) {
  327. $hosts[$i]['ssl'] = $params['ssl'];
  328. }
  329. }
  330. }
  331. if (1 === \count($hosts) && !($params['redis_cluster'] || $params['redis_sentinel'])) {
  332. $hosts = $hosts[0];
  333. } elseif (\in_array($params['failover'], ['slaves', 'distribute'], true) && !isset($params['replication'])) {
  334. $params['replication'] = true;
  335. $hosts[0] += ['alias' => 'master'];
  336. }
  337. $params['exceptions'] = false;
  338. $redis = new $class($hosts, array_diff_key($params, self::$defaultConnectionOptions));
  339. if (isset($params['redis_sentinel'])) {
  340. $redis->getConnection()->setSentinelTimeout($params['timeout']);
  341. }
  342. } elseif (class_exists($class, false)) {
  343. throw new InvalidArgumentException(sprintf('"%s" is not a subclass of "Redis", "RedisArray", "RedisCluster" nor "Predis\ClientInterface".', $class));
  344. } else {
  345. throw new InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
  346. }
  347. return $redis;
  348. }
  349. /**
  350. * {@inheritdoc}
  351. */
  352. protected function doFetch(array $ids)
  353. {
  354. if (!$ids) {
  355. return [];
  356. }
  357. $result = [];
  358. if ($this->redis instanceof \Predis\ClientInterface && $this->redis->getConnection() instanceof ClusterInterface) {
  359. $values = $this->pipeline(function () use ($ids) {
  360. foreach ($ids as $id) {
  361. yield 'get' => [$id];
  362. }
  363. });
  364. } else {
  365. $values = $this->redis->mget($ids);
  366. if (!\is_array($values) || \count($values) !== \count($ids)) {
  367. return [];
  368. }
  369. $values = array_combine($ids, $values);
  370. }
  371. foreach ($values as $id => $v) {
  372. if ($v) {
  373. $result[$id] = $this->marshaller->unmarshall($v);
  374. }
  375. }
  376. return $result;
  377. }
  378. /**
  379. * {@inheritdoc}
  380. */
  381. protected function doHave(string $id)
  382. {
  383. return (bool) $this->redis->exists($id);
  384. }
  385. /**
  386. * {@inheritdoc}
  387. */
  388. protected function doClear(string $namespace)
  389. {
  390. if ($this->redis instanceof \Predis\ClientInterface) {
  391. $prefix = $this->redis->getOptions()->prefix ? $this->redis->getOptions()->prefix->getPrefix() : '';
  392. $prefixLen = \strlen($prefix ?? '');
  393. }
  394. $cleared = true;
  395. $hosts = $this->getHosts();
  396. $host = reset($hosts);
  397. if ($host instanceof \Predis\Client && $host->getConnection() instanceof ReplicationInterface) {
  398. // Predis supports info command only on the master in replication environments
  399. $hosts = [$host->getClientFor('master')];
  400. }
  401. foreach ($hosts as $host) {
  402. if (!isset($namespace[0])) {
  403. $cleared = $host->flushDb() && $cleared;
  404. continue;
  405. }
  406. $info = $host->info('Server');
  407. $info = !$info instanceof ErrorInterface ? $info['Server'] ?? $info : ['redis_version' => '2.0'];
  408. if (!$host instanceof \Predis\ClientInterface) {
  409. $prefix = \defined('Redis::SCAN_PREFIX') && (\Redis::SCAN_PREFIX & $host->getOption(\Redis::OPT_SCAN)) ? '' : $host->getOption(\Redis::OPT_PREFIX);
  410. $prefixLen = \strlen($host->getOption(\Redis::OPT_PREFIX) ?? '');
  411. }
  412. $pattern = $prefix.$namespace.'*';
  413. if (!version_compare($info['redis_version'], '2.8', '>=')) {
  414. // As documented in Redis documentation (http://redis.io/commands/keys) using KEYS
  415. // can hang your server when it is executed against large databases (millions of items).
  416. // Whenever you hit this scale, you should really consider upgrading to Redis 2.8 or above.
  417. $unlink = version_compare($info['redis_version'], '4.0', '>=') ? 'UNLINK' : 'DEL';
  418. $args = $this->redis instanceof \Predis\ClientInterface ? [0, $pattern] : [[$pattern], 0];
  419. $cleared = $host->eval("local keys=redis.call('KEYS',ARGV[1]) for i=1,#keys,5000 do redis.call('$unlink',unpack(keys,i,math.min(i+4999,#keys))) end return 1", $args[0], $args[1]) && $cleared;
  420. continue;
  421. }
  422. $cursor = null;
  423. do {
  424. $keys = $host instanceof \Predis\ClientInterface ? $host->scan($cursor, 'MATCH', $pattern, 'COUNT', 1000) : $host->scan($cursor, $pattern, 1000);
  425. if (isset($keys[1]) && \is_array($keys[1])) {
  426. $cursor = $keys[0];
  427. $keys = $keys[1];
  428. }
  429. if ($keys) {
  430. if ($prefixLen) {
  431. foreach ($keys as $i => $key) {
  432. $keys[$i] = substr($key, $prefixLen);
  433. }
  434. }
  435. $this->doDelete($keys);
  436. }
  437. } while ($cursor = (int) $cursor);
  438. }
  439. return $cleared;
  440. }
  441. /**
  442. * {@inheritdoc}
  443. */
  444. protected function doDelete(array $ids)
  445. {
  446. if (!$ids) {
  447. return true;
  448. }
  449. if ($this->redis instanceof \Predis\ClientInterface && $this->redis->getConnection() instanceof ClusterInterface) {
  450. static $del;
  451. $del = $del ?? (class_exists(UNLINK::class) ? 'unlink' : 'del');
  452. $this->pipeline(function () use ($ids, $del) {
  453. foreach ($ids as $id) {
  454. yield $del => [$id];
  455. }
  456. })->rewind();
  457. } else {
  458. static $unlink = true;
  459. if ($unlink) {
  460. try {
  461. $unlink = false !== $this->redis->unlink($ids);
  462. } catch (\Throwable $e) {
  463. $unlink = false;
  464. }
  465. }
  466. if (!$unlink) {
  467. $this->redis->del($ids);
  468. }
  469. }
  470. return true;
  471. }
  472. /**
  473. * {@inheritdoc}
  474. */
  475. protected function doSave(array $values, int $lifetime)
  476. {
  477. if (!$values = $this->marshaller->marshall($values, $failed)) {
  478. return $failed;
  479. }
  480. $results = $this->pipeline(function () use ($values, $lifetime) {
  481. foreach ($values as $id => $value) {
  482. if (0 >= $lifetime) {
  483. yield 'set' => [$id, $value];
  484. } else {
  485. yield 'setEx' => [$id, $lifetime, $value];
  486. }
  487. }
  488. });
  489. foreach ($results as $id => $result) {
  490. if (true !== $result && (!$result instanceof Status || Status::get('OK') !== $result)) {
  491. $failed[] = $id;
  492. }
  493. }
  494. return $failed;
  495. }
  496. private function pipeline(\Closure $generator, ?object $redis = null): \Generator
  497. {
  498. $ids = [];
  499. $redis = $redis ?? $this->redis;
  500. if ($redis instanceof RedisClusterProxy || $redis instanceof \RedisCluster || ($redis instanceof \Predis\ClientInterface && $redis->getConnection() instanceof RedisCluster)) {
  501. // phpredis & predis don't support pipelining with RedisCluster
  502. // see https://github.com/phpredis/phpredis/blob/develop/cluster.markdown#pipelining
  503. // see https://github.com/nrk/predis/issues/267#issuecomment-123781423
  504. $results = [];
  505. foreach ($generator() as $command => $args) {
  506. $results[] = $redis->{$command}(...$args);
  507. $ids[] = 'eval' === $command ? ($redis instanceof \Predis\ClientInterface ? $args[2] : $args[1][0]) : $args[0];
  508. }
  509. } elseif ($redis instanceof \Predis\ClientInterface) {
  510. $results = $redis->pipeline(static function ($redis) use ($generator, &$ids) {
  511. foreach ($generator() as $command => $args) {
  512. $redis->{$command}(...$args);
  513. $ids[] = 'eval' === $command ? $args[2] : $args[0];
  514. }
  515. });
  516. } elseif ($redis instanceof \RedisArray) {
  517. $connections = $results = $ids = [];
  518. foreach ($generator() as $command => $args) {
  519. $id = 'eval' === $command ? $args[1][0] : $args[0];
  520. if (!isset($connections[$h = $redis->_target($id)])) {
  521. $connections[$h] = [$redis->_instance($h), -1];
  522. $connections[$h][0]->multi(\Redis::PIPELINE);
  523. }
  524. $connections[$h][0]->{$command}(...$args);
  525. $results[] = [$h, ++$connections[$h][1]];
  526. $ids[] = $id;
  527. }
  528. foreach ($connections as $h => $c) {
  529. $connections[$h] = $c[0]->exec();
  530. }
  531. foreach ($results as $k => [$h, $c]) {
  532. $results[$k] = $connections[$h][$c];
  533. }
  534. } else {
  535. $redis->multi(\Redis::PIPELINE);
  536. foreach ($generator() as $command => $args) {
  537. $redis->{$command}(...$args);
  538. $ids[] = 'eval' === $command ? $args[1][0] : $args[0];
  539. }
  540. $results = $redis->exec();
  541. }
  542. if (!$redis instanceof \Predis\ClientInterface && 'eval' === $command && $redis->getLastError()) {
  543. $e = new \RedisException($redis->getLastError());
  544. $results = array_map(function ($v) use ($e) { return false === $v ? $e : $v; }, (array) $results);
  545. }
  546. if (\is_bool($results)) {
  547. return;
  548. }
  549. foreach ($ids as $k => $id) {
  550. yield $id => $results[$k];
  551. }
  552. }
  553. private function getHosts(): array
  554. {
  555. $hosts = [$this->redis];
  556. if ($this->redis instanceof \Predis\ClientInterface) {
  557. $connection = $this->redis->getConnection();
  558. if ($connection instanceof ClusterInterface && $connection instanceof \Traversable) {
  559. $hosts = [];
  560. foreach ($connection as $c) {
  561. $hosts[] = new \Predis\Client($c);
  562. }
  563. }
  564. } elseif ($this->redis instanceof \RedisArray) {
  565. $hosts = [];
  566. foreach ($this->redis->_hosts() as $host) {
  567. $hosts[] = $this->redis->_instance($host);
  568. }
  569. } elseif ($this->redis instanceof RedisClusterProxy || $this->redis instanceof \RedisCluster) {
  570. $hosts = [];
  571. foreach ($this->redis->_masters() as $host) {
  572. $hosts[] = new RedisClusterNodeProxy($host, $this->redis);
  573. }
  574. }
  575. return $hosts;
  576. }
  577. }