MultiExecContext.php 11 KB

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