MultiExecContext.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.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 Predis\Transaction;
  11. use SplQueue;
  12. use Predis\BasicClientInterface;
  13. use Predis\ClientException;
  14. use Predis\ClientInterface;
  15. use Predis\CommunicationException;
  16. use Predis\ExecutableContextInterface;
  17. use Predis\NotSupportedException;
  18. use Predis\ResponseErrorInterface;
  19. use Predis\ResponseQueued;
  20. use Predis\ServerException;
  21. use Predis\Command\CommandInterface;
  22. use Predis\Connection\AggregatedConnectionInterface;
  23. use Predis\Protocol\ProtocolException;
  24. /**
  25. * Client-side abstraction of a Redis transaction based on MULTI / EXEC.
  26. *
  27. * @author Daniele Alessandri <suppakilla@gmail.com>
  28. */
  29. class MultiExecContext implements BasicClientInterface, ExecutableContextInterface
  30. {
  31. const STATE_RESET = 0; // 0b00000
  32. const STATE_INITIALIZED = 1; // 0b00001
  33. const STATE_INSIDEBLOCK = 2; // 0b00010
  34. const STATE_DISCARDED = 4; // 0b00100
  35. const STATE_CAS = 8; // 0b01000
  36. const STATE_WATCH = 16; // 0b10000
  37. private $state;
  38. private $canWatch;
  39. protected $client;
  40. protected $options;
  41. protected $commands;
  42. /**
  43. * @param ClientInterface $client Client instance used by the context.
  44. * @param array $options Options for the context initialization.
  45. */
  46. public function __construct(ClientInterface $client, Array $options = null)
  47. {
  48. $this->checkCapabilities($client);
  49. $this->options = $options ?: array();
  50. $this->client = $client;
  51. $this->reset();
  52. }
  53. /**
  54. * Sets the internal state flags.
  55. *
  56. * @param int $flags Set of flags
  57. */
  58. protected function setState($flags)
  59. {
  60. $this->state = $flags;
  61. }
  62. /**
  63. * Gets the internal state flags.
  64. *
  65. * @return int
  66. */
  67. protected function getState()
  68. {
  69. return $this->state;
  70. }
  71. /**
  72. * Sets one or more flags.
  73. *
  74. * @param int $flags Set of flags
  75. */
  76. protected function flagState($flags)
  77. {
  78. $this->state |= $flags;
  79. }
  80. /**
  81. * Resets one or more flags.
  82. *
  83. * @param int $flags Set of flags
  84. */
  85. protected function unflagState($flags)
  86. {
  87. $this->state &= ~$flags;
  88. }
  89. /**
  90. * Checks is a flag is set.
  91. *
  92. * @param int $flags Flag
  93. * @return bool
  94. */
  95. protected function checkState($flags)
  96. {
  97. return ($this->state & $flags) === $flags;
  98. }
  99. /**
  100. * Checks if the passed client instance satisfies the required conditions
  101. * needed to initialize a transaction context.
  102. *
  103. * @param ClientInterface $client Client instance used by the context.
  104. */
  105. private function checkCapabilities(ClientInterface $client)
  106. {
  107. if ($client->getConnection() instanceof AggregatedConnectionInterface) {
  108. throw new NotSupportedException('Cannot initialize a MULTI/EXEC context when using aggregated connections');
  109. }
  110. $profile = $client->getProfile();
  111. if ($profile->supportsCommands(array('MULTI', 'EXEC', 'DISCARD')) === false) {
  112. throw new NotSupportedException('The current profile does not support MULTI, EXEC and DISCARD');
  113. }
  114. $this->canWatch = $profile->supportsCommands(array('WATCH', 'UNWATCH'));
  115. }
  116. /**
  117. * Checks if WATCH and UNWATCH are supported by the server profile.
  118. */
  119. private function isWatchSupported()
  120. {
  121. if ($this->canWatch === false) {
  122. throw new NotSupportedException('The current profile does not support WATCH and UNWATCH');
  123. }
  124. }
  125. /**
  126. * Resets the state of a transaction.
  127. */
  128. protected function reset()
  129. {
  130. $this->setState(self::STATE_RESET);
  131. $this->commands = new SplQueue();
  132. }
  133. /**
  134. * Initializes a new transaction.
  135. */
  136. protected function initialize()
  137. {
  138. if ($this->checkState(self::STATE_INITIALIZED)) {
  139. return;
  140. }
  141. $options = $this->options;
  142. if (isset($options['cas']) && $options['cas']) {
  143. $this->flagState(self::STATE_CAS);
  144. }
  145. if (isset($options['watch'])) {
  146. $this->watch($options['watch']);
  147. }
  148. $cas = $this->checkState(self::STATE_CAS);
  149. $discarded = $this->checkState(self::STATE_DISCARDED);
  150. if (!$cas || ($cas && $discarded)) {
  151. $this->client->multi();
  152. if ($discarded) {
  153. $this->unflagState(self::STATE_CAS);
  154. }
  155. }
  156. $this->unflagState(self::STATE_DISCARDED);
  157. $this->flagState(self::STATE_INITIALIZED);
  158. }
  159. /**
  160. * Dynamically invokes a Redis command with the specified arguments.
  161. *
  162. * @param string $method Command ID.
  163. * @param array $arguments Arguments for the command.
  164. * @return mixed
  165. */
  166. public function __call($method, $arguments)
  167. {
  168. $command = $this->client->createCommand($method, $arguments);
  169. $response = $this->executeCommand($command);
  170. return $response;
  171. }
  172. /**
  173. * Executes the specified Redis command.
  174. *
  175. * @param CommandInterface $command Command instance.
  176. * @return $this|mixed
  177. */
  178. public function executeCommand(CommandInterface $command)
  179. {
  180. $this->initialize();
  181. if ($this->checkState(self::STATE_CAS)) {
  182. return $this->client->executeCommand($command);
  183. }
  184. $response = $this->client->getConnection()->executeCommand($command);
  185. if ($response instanceof ResponseQueued) {
  186. $this->commands->enqueue($command);
  187. } elseif ($response instanceof ResponseErrorInterface) {
  188. throw new AbortedMultiExecException($this, $response->getMessage());
  189. } else {
  190. $this->onProtocolError('The server did not return a +QUEUED status response.');
  191. }
  192. return $this;
  193. }
  194. /**
  195. * Executes WATCH on one or more keys.
  196. *
  197. * @param string|array $keys One or more keys.
  198. * @return mixed
  199. */
  200. public function watch($keys)
  201. {
  202. $this->isWatchSupported();
  203. if ($this->checkState(self::STATE_INITIALIZED) && !$this->checkState(self::STATE_CAS)) {
  204. throw new ClientException('WATCH after MULTI is not allowed');
  205. }
  206. $reply = $this->client->watch($keys);
  207. $this->flagState(self::STATE_WATCH);
  208. return $reply;
  209. }
  210. /**
  211. * Finalizes the transaction on the server by executing MULTI on the server.
  212. *
  213. * @return MultiExecContext
  214. */
  215. public function multi()
  216. {
  217. if ($this->checkState(self::STATE_INITIALIZED | self::STATE_CAS)) {
  218. $this->unflagState(self::STATE_CAS);
  219. $this->client->multi();
  220. } else {
  221. $this->initialize();
  222. }
  223. return $this;
  224. }
  225. /**
  226. * Executes UNWATCH.
  227. *
  228. * @return MultiExecContext
  229. */
  230. public function unwatch()
  231. {
  232. $this->isWatchSupported();
  233. $this->unflagState(self::STATE_WATCH);
  234. $this->__call('unwatch', array());
  235. return $this;
  236. }
  237. /**
  238. * Resets a transaction by UNWATCHing the keys that are being WATCHed and
  239. * DISCARDing the pending commands that have been already sent to the server.
  240. *
  241. * @return MultiExecContext
  242. */
  243. public function discard()
  244. {
  245. if ($this->checkState(self::STATE_INITIALIZED)) {
  246. $command = $this->checkState(self::STATE_CAS) ? 'unwatch' : 'discard';
  247. $this->client->$command();
  248. $this->reset();
  249. $this->flagState(self::STATE_DISCARDED);
  250. }
  251. return $this;
  252. }
  253. /**
  254. * Executes the whole transaction.
  255. *
  256. * @return mixed
  257. */
  258. public function exec()
  259. {
  260. return $this->execute();
  261. }
  262. /**
  263. * Checks the state of the transaction before execution.
  264. *
  265. * @param mixed $callable Callback for execution.
  266. */
  267. private function checkBeforeExecution($callable)
  268. {
  269. if ($this->checkState(self::STATE_INSIDEBLOCK)) {
  270. throw new ClientException("Cannot invoke 'execute' or 'exec' inside an active client transaction block");
  271. }
  272. if ($callable) {
  273. if (!is_callable($callable)) {
  274. throw new \InvalidArgumentException('Argument passed must be a callable object');
  275. }
  276. if (!$this->commands->isEmpty()) {
  277. $this->discard();
  278. throw new ClientException('Cannot execute a transaction block after using fluent interface');
  279. }
  280. }
  281. if (isset($this->options['retry']) && !isset($callable)) {
  282. $this->discard();
  283. throw new \InvalidArgumentException('Automatic retries can be used only when a transaction block is provided');
  284. }
  285. }
  286. /**
  287. * Handles the actual execution of the whole transaction.
  288. *
  289. * @param mixed $callable Optional callback for execution.
  290. * @return array
  291. */
  292. public function execute($callable = null)
  293. {
  294. $this->checkBeforeExecution($callable);
  295. $reply = null;
  296. $values = array();
  297. $attempts = isset($this->options['retry']) ? (int) $this->options['retry'] : 0;
  298. do {
  299. if ($callable !== null) {
  300. $this->executeTransactionBlock($callable);
  301. }
  302. if ($this->commands->isEmpty()) {
  303. if ($this->checkState(self::STATE_WATCH)) {
  304. $this->discard();
  305. }
  306. return null;
  307. }
  308. $reply = $this->client->exec();
  309. if ($reply === null) {
  310. if ($attempts === 0) {
  311. $message = 'The current transaction has been aborted by the server';
  312. throw new AbortedMultiExecException($this, $message);
  313. }
  314. $this->reset();
  315. if (isset($this->options['on_retry']) && is_callable($this->options['on_retry'])) {
  316. call_user_func($this->options['on_retry'], $this, $attempts);
  317. }
  318. continue;
  319. }
  320. break;
  321. } while ($attempts-- > 0);
  322. $exec = $reply instanceof \Iterator ? iterator_to_array($reply) : $reply;
  323. $commands = $this->commands;
  324. $size = count($exec);
  325. if ($size !== count($commands)) {
  326. $this->onProtocolError("EXEC returned an unexpected number of replies");
  327. }
  328. $clientOpts = $this->client->getOptions();
  329. $useExceptions = isset($clientOpts->exceptions) ? $clientOpts->exceptions : true;
  330. for ($i = 0; $i < $size; $i++) {
  331. $commandReply = $exec[$i];
  332. if ($commandReply instanceof ResponseErrorInterface && $useExceptions) {
  333. $message = $commandReply->getMessage();
  334. throw new ServerException($message);
  335. }
  336. if ($commandReply instanceof \Iterator) {
  337. $commandReply = iterator_to_array($commandReply);
  338. }
  339. $values[$i] = $commands->dequeue()->parseResponse($commandReply);
  340. }
  341. return $values;
  342. }
  343. /**
  344. * Passes the current transaction context to a callable block for execution.
  345. *
  346. * @param mixed $callable Callback.
  347. */
  348. protected function executeTransactionBlock($callable)
  349. {
  350. $blockException = null;
  351. $this->flagState(self::STATE_INSIDEBLOCK);
  352. try {
  353. call_user_func($callable, $this);
  354. } catch (CommunicationException $exception) {
  355. $blockException = $exception;
  356. } catch (ServerException $exception) {
  357. $blockException = $exception;
  358. } catch (\Exception $exception) {
  359. $blockException = $exception;
  360. $this->discard();
  361. }
  362. $this->unflagState(self::STATE_INSIDEBLOCK);
  363. if ($blockException !== null) {
  364. throw $blockException;
  365. }
  366. }
  367. /**
  368. * Helper method that handles protocol errors encountered inside a transaction.
  369. *
  370. * @param string $message Error message.
  371. */
  372. private function onProtocolError($message)
  373. {
  374. // Since a MULTI/EXEC block cannot be initialized when using aggregated
  375. // connections, we can safely assume that Predis\Client::getConnection()
  376. // will always return an instance of Predis\Connection\SingleConnectionInterface.
  377. CommunicationException::handle(new ProtocolException(
  378. $this->client->getConnection(), $message
  379. ));
  380. }
  381. }