MultiExecContext.php 12 KB

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