MultiExecContext.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. <?php
  2. namespace Predis\Transaction;
  3. use Predis\Client;
  4. use Predis\Helpers;
  5. use Predis\ResponseQueued;
  6. use Predis\ClientException;
  7. use Predis\ServerException;
  8. use Predis\CommunicationException;
  9. use Predis\Protocol\ProtocolException;
  10. class MultiExecContext {
  11. const STATE_RESET = 0x00000;
  12. const STATE_INITIALIZED = 0x00001;
  13. const STATE_INSIDEBLOCK = 0x00010;
  14. const STATE_DISCARDED = 0x00100;
  15. const STATE_CAS = 0x01000;
  16. const STATE_WATCH = 0x10000;
  17. private $_client;
  18. private $_options;
  19. private $_state;
  20. private $_canWatch;
  21. private $_commands;
  22. public function __construct(Client $client, Array $options = null) {
  23. $this->checkCapabilities($client);
  24. $this->_options = $options ?: array();
  25. $this->_client = $client;
  26. $this->reset();
  27. }
  28. protected function setState($flags) {
  29. $this->_state = $flags;
  30. }
  31. protected function flagState($flags) {
  32. $this->_state |= $flags;
  33. }
  34. protected function unflagState($flags) {
  35. $this->_state &= ~$flags;
  36. }
  37. protected function checkState($flags) {
  38. return ($this->_state & $flags) === $flags;
  39. }
  40. private function checkCapabilities(Client $client) {
  41. if (Helpers::isCluster($client->getConnection())) {
  42. throw new ClientException(
  43. 'Cannot initialize a MULTI/EXEC context over a cluster of connections'
  44. );
  45. }
  46. $profile = $client->getProfile();
  47. if ($profile->supportsCommands(array('multi', 'exec', 'discard')) === false) {
  48. throw new ClientException(
  49. 'The current profile does not support MULTI, EXEC and DISCARD commands'
  50. );
  51. }
  52. $this->_canWatch = $profile->supportsCommands(array('watch', 'unwatch'));
  53. }
  54. private function isWatchSupported() {
  55. if ($this->_canWatch === false) {
  56. throw new ClientException(
  57. 'The current profile does not support WATCH and UNWATCH commands'
  58. );
  59. }
  60. }
  61. private function reset() {
  62. $this->setState(self::STATE_RESET);
  63. $this->_commands = array();
  64. }
  65. private function initialize() {
  66. if ($this->checkState(self::STATE_INITIALIZED)) {
  67. return;
  68. }
  69. $options = $this->_options;
  70. if (isset($options['cas']) && $options['cas']) {
  71. $this->flagState(self::STATE_CAS);
  72. }
  73. if (isset($options['watch'])) {
  74. $this->watch($options['watch']);
  75. }
  76. $cas = $this->checkState(self::STATE_CAS);
  77. $discarded = $this->checkState(self::STATE_DISCARDED);
  78. if (!$cas || ($cas && $discarded)) {
  79. $this->_client->multi();
  80. if ($discarded) {
  81. $this->unflagState(self::STATE_CAS);
  82. }
  83. }
  84. $this->unflagState(self::STATE_DISCARDED);
  85. $this->flagState(self::STATE_INITIALIZED);
  86. }
  87. public function __call($method, $arguments) {
  88. $this->initialize();
  89. $client = $this->_client;
  90. if ($this->checkState(self::STATE_CAS)) {
  91. return call_user_func_array(array($client, $method), $arguments);
  92. }
  93. $command = $client->createCommand($method, $arguments);
  94. $response = $client->executeCommand($command);
  95. if (!$response instanceof ResponseQueued) {
  96. $this->onProtocolError('The server did not respond with a QUEUED status reply');
  97. }
  98. $this->_commands[] = $command;
  99. return $this;
  100. }
  101. public function watch($keys) {
  102. $this->isWatchSupported();
  103. if ($this->checkState(self::STATE_INITIALIZED) && !$this->checkState(self::STATE_CAS)) {
  104. throw new ClientException('WATCH inside MULTI is not allowed');
  105. }
  106. $watchReply = $this->_client->watch($keys);
  107. $this->flagState(self::STATE_WATCH);
  108. return $watchReply;
  109. }
  110. public function multi() {
  111. if ($this->checkState(self::STATE_INITIALIZED | self::STATE_CAS)) {
  112. $this->unflagState(self::STATE_CAS);
  113. $this->_client->multi();
  114. }
  115. else {
  116. $this->initialize();
  117. }
  118. return $this;
  119. }
  120. public function unwatch() {
  121. $this->isWatchSupported();
  122. $this->unflagState(self::STATE_WATCH);
  123. $this->_client->unwatch();
  124. return $this;
  125. }
  126. public function discard() {
  127. if ($this->checkState(self::STATE_INITIALIZED)) {
  128. $command = $this->checkState(self::STATE_CAS) ? 'unwatch' : 'discard';
  129. $this->_client->$command();
  130. $this->reset();
  131. $this->flagState(self::STATE_DISCARDED);
  132. }
  133. return $this;
  134. }
  135. public function exec() {
  136. return $this->execute();
  137. }
  138. private function checkBeforeExecution($block) {
  139. if ($this->checkState(self::STATE_INSIDEBLOCK)) {
  140. throw new ClientException(
  141. "Cannot invoke 'execute' or 'exec' inside an active client transaction block"
  142. );
  143. }
  144. if ($block) {
  145. if (!is_callable($block)) {
  146. throw new \InvalidArgumentException(
  147. 'Argument passed must be a callable object'
  148. );
  149. }
  150. if (count($this->_commands) > 0) {
  151. $this->discard();
  152. throw new ClientException(
  153. 'Cannot execute a transaction block after using fluent interface'
  154. );
  155. }
  156. }
  157. if (isset($this->_options['retry']) && !isset($block)) {
  158. $this->discard();
  159. throw new \InvalidArgumentException(
  160. 'Automatic retries can be used only when a transaction block is provided'
  161. );
  162. }
  163. }
  164. public function execute($block = null) {
  165. $this->checkBeforeExecution($block);
  166. $reply = null;
  167. $returnValues = array();
  168. $attemptsLeft = isset($this->_options['retry']) ? (int)$this->_options['retry'] : 0;
  169. do {
  170. if ($block !== null) {
  171. $this->executeTransactionBlock($block);
  172. }
  173. if (count($this->_commands) === 0) {
  174. if ($this->checkState(self::STATE_WATCH)) {
  175. $this->discard();
  176. }
  177. return;
  178. }
  179. $reply = $this->_client->exec();
  180. if ($reply === null) {
  181. if ($attemptsLeft === 0) {
  182. $message = 'The current transaction has been aborted by the server';
  183. throw new AbortedMultiExecException($this, $message);
  184. }
  185. $this->reset();
  186. if (isset($this->_options['on_retry']) && is_callable($this->_options['on_retry'])) {
  187. call_user_func($this->_options['on_retry'], $this, $attemptsLeft);
  188. }
  189. continue;
  190. }
  191. break;
  192. } while ($attemptsLeft-- > 0);
  193. $execReply = $reply instanceof \Iterator ? iterator_to_array($reply) : $reply;
  194. $sizeofReplies = count($execReply);
  195. $commands = $this->_commands;
  196. if ($sizeofReplies !== count($commands)) {
  197. $this->onProtocolError('Unexpected number of responses for a MultiExecContext');
  198. }
  199. for ($i = 0; $i < $sizeofReplies; $i++) {
  200. $commandReply = $execReply[$i];
  201. if ($commandReply instanceof \Iterator) {
  202. $commandReply = iterator_to_array($commandReply);
  203. }
  204. $returnValues[$i] = $commands[$i]->parseResponse($commandReply);
  205. unset($commands[$i]);
  206. }
  207. return $returnValues;
  208. }
  209. private function executeTransactionBlock($block) {
  210. $blockException = null;
  211. $this->flagState(self::STATE_INSIDEBLOCK);
  212. try {
  213. $block($this);
  214. }
  215. catch (CommunicationException $exception) {
  216. $blockException = $exception;
  217. }
  218. catch (ServerException $exception) {
  219. $blockException = $exception;
  220. }
  221. catch (\Exception $exception) {
  222. $blockException = $exception;
  223. $this->discard();
  224. }
  225. $this->unflagState(self::STATE_INSIDEBLOCK);
  226. if ($blockException !== null) {
  227. throw $blockException;
  228. }
  229. }
  230. private function onProtocolError($message) {
  231. // Since a MULTI/EXEC block cannot be initialized over a clustered
  232. // connection, we can safely assume that Predis\Client::getConnection()
  233. // will always return an instance of Predis\Network\IConnectionSingle.
  234. Helpers::onCommunicationException(new ProtocolException(
  235. $this->_client->getConnection(), $message
  236. ));
  237. }
  238. }