MultiExecContext.php 12 KB

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