MultiExecContext.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 $_supportsWatch;
  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->_supportsWatch = $profile->supportsCommands(array('watch', 'unwatch'));
  53. }
  54. private function isWatchSupported() {
  55. if ($this->_supportsWatch === 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. $this->flagState(self::STATE_WATCH);
  107. return $this->_client->watch($keys);
  108. }
  109. public function multi() {
  110. if ($this->checkState(self::STATE_INITIALIZED | self::STATE_CAS)) {
  111. $this->unflagState(self::STATE_CAS);
  112. $this->_client->multi();
  113. }
  114. else {
  115. $this->initialize();
  116. }
  117. return $this;
  118. }
  119. public function unwatch() {
  120. $this->isWatchSupported();
  121. $this->unflagState(self::STATE_WATCH);
  122. $this->_client->unwatch();
  123. return $this;
  124. }
  125. public function discard() {
  126. if ($this->checkState(self::STATE_INITIALIZED)) {
  127. $command = $this->checkState(self::STATE_CAS) ? 'unwatch' : 'discard';
  128. $this->_client->$command();
  129. $this->reset();
  130. $this->flagState(self::STATE_DISCARDED);
  131. }
  132. return $this;
  133. }
  134. public function exec() {
  135. return $this->execute();
  136. }
  137. private function checkBeforeExecution($block) {
  138. if ($this->checkState(self::STATE_INSIDEBLOCK)) {
  139. throw new ClientException(
  140. "Cannot invoke 'execute' or 'exec' inside an active client transaction block"
  141. );
  142. }
  143. if ($block) {
  144. if (!is_callable($block)) {
  145. throw new \InvalidArgumentException(
  146. 'Argument passed must be a callable object'
  147. );
  148. }
  149. if (count($this->_commands) > 0) {
  150. $this->discard();
  151. throw new ClientException(
  152. 'Cannot execute a transaction block after using fluent interface'
  153. );
  154. }
  155. }
  156. if (isset($this->_options['retry']) && !isset($block)) {
  157. $this->discard();
  158. throw new \InvalidArgumentException(
  159. 'Automatic retries can be used only when a transaction block is provided'
  160. );
  161. }
  162. }
  163. public function execute($block = null) {
  164. $this->checkBeforeExecution($block);
  165. $reply = null;
  166. $returnValues = array();
  167. $attemptsLeft = isset($this->_options['retry']) ? (int)$this->_options['retry'] : 0;
  168. do {
  169. $blockException = null;
  170. if ($block !== null) {
  171. $this->flagState(self::STATE_INSIDEBLOCK);
  172. try {
  173. $block($this);
  174. }
  175. catch (CommunicationException $exception) {
  176. $blockException = $exception;
  177. }
  178. catch (ServerException $exception) {
  179. $blockException = $exception;
  180. }
  181. catch (\Exception $exception) {
  182. $blockException = $exception;
  183. $this->discard();
  184. }
  185. $this->unflagState(self::STATE_INSIDEBLOCK);
  186. if ($blockException !== null) {
  187. throw $blockException;
  188. }
  189. }
  190. if (count($this->_commands) === 0) {
  191. if ($this->checkState(self::STATE_WATCH)) {
  192. $this->discard();
  193. return;
  194. }
  195. return;
  196. }
  197. $reply = $this->_client->exec();
  198. if ($reply === null) {
  199. if ($attemptsLeft === 0) {
  200. $message = 'The current transaction has been aborted by the server';
  201. throw new AbortedMultiExecException($this, $message);
  202. }
  203. $this->reset();
  204. if (isset($this->_options['on_retry']) && is_callable($this->_options['on_retry'])) {
  205. call_user_func($this->_options['on_retry'], $this, $attemptsLeft);
  206. }
  207. continue;
  208. }
  209. break;
  210. } while ($attemptsLeft-- > 0);
  211. $execReply = $reply instanceof \Iterator ? iterator_to_array($reply) : $reply;
  212. $sizeofReplies = count($execReply);
  213. $commands = &$this->_commands;
  214. if ($sizeofReplies !== count($commands)) {
  215. $this->onProtocolError('Unexpected number of responses for a MultiExecContext');
  216. }
  217. for ($i = 0; $i < $sizeofReplies; $i++) {
  218. $returnValues[] = $commands[$i]->parseResponse($execReply[$i] instanceof \Iterator
  219. ? iterator_to_array($execReply[$i])
  220. : $execReply[$i]
  221. );
  222. unset($commands[$i]);
  223. }
  224. return $returnValues;
  225. }
  226. private function onProtocolError($message) {
  227. // Since a MULTI/EXEC block cannot be initialized over a clustered
  228. // connection, we can safely assume that Predis\Client::getConnection()
  229. // will always return an instance of Predis\Network\IConnectionSingle.
  230. Helpers::onCommunicationException(new ProtocolException(
  231. $this->_client->getConnection(), $message
  232. ));
  233. }
  234. }