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\Client;
  12. use Predis\Helpers;
  13. use Predis\ResponseQueued;
  14. use Predis\ClientException;
  15. use Predis\ServerException;
  16. use Predis\CommunicationException;
  17. use Predis\Protocol\ProtocolException;
  18. /**
  19. * Client-side abstraction of a Redis transaction based on MULTI / EXEC.
  20. *
  21. * @author Daniele Alessandri <suppakilla@gmail.com>
  22. */
  23. class MultiExecContext
  24. {
  25. const STATE_RESET = 0x00000;
  26. const STATE_INITIALIZED = 0x00001;
  27. const STATE_INSIDEBLOCK = 0x00010;
  28. const STATE_DISCARDED = 0x00100;
  29. const STATE_CAS = 0x01000;
  30. const STATE_WATCH = 0x10000;
  31. private $state;
  32. private $canWatch;
  33. protected $client;
  34. protected $options;
  35. protected $commands;
  36. /**
  37. * @param Client Client instance used by the context.
  38. * @param array Options for the context initialization.
  39. */
  40. public function __construct(Client $client, Array $options = null)
  41. {
  42. $this->checkCapabilities($client);
  43. $this->options = $options ?: array();
  44. $this->client = $client;
  45. $this->reset();
  46. }
  47. /**
  48. * Sets the internal state flags.
  49. *
  50. * @param int $flags Set of flags
  51. */
  52. protected function setState($flags)
  53. {
  54. $this->state = $flags;
  55. }
  56. /**
  57. * Gets the internal state flags.
  58. *
  59. * @return int
  60. */
  61. protected function getState()
  62. {
  63. return $this->state;
  64. }
  65. /**
  66. * Sets one or more flags.
  67. *
  68. * @param int $flags Set of flags
  69. */
  70. protected function flagState($flags)
  71. {
  72. $this->state |= $flags;
  73. }
  74. /**
  75. * Resets one or more flags.
  76. *
  77. * @param int $flags Set of flags
  78. */
  79. protected function unflagState($flags)
  80. {
  81. $this->state &= ~$flags;
  82. }
  83. /**
  84. * Checks is a flag is set.
  85. *
  86. * @param int $flags Flag
  87. * @return Boolean
  88. */
  89. protected function checkState($flags)
  90. {
  91. return ($this->state & $flags) === $flags;
  92. }
  93. /**
  94. * Checks if the passed client instance satisfies the required conditions
  95. * needed to initialize a transaction context.
  96. *
  97. * @param Client Client instance used by the context.
  98. */
  99. private function checkCapabilities(Client $client)
  100. {
  101. if (Helpers::isCluster($client->getConnection())) {
  102. throw new ClientException(
  103. 'Cannot initialize a MULTI/EXEC context over a cluster of connections'
  104. );
  105. }
  106. $profile = $client->getProfile();
  107. if ($profile->supportsCommands(array('multi', 'exec', 'discard')) === false) {
  108. throw new ClientException(
  109. 'The current profile does not support MULTI, EXEC and DISCARD'
  110. );
  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 ClientException(
  121. 'The current profile does not support WATCH and UNWATCH'
  122. );
  123. }
  124. }
  125. /**
  126. * Resets the state of a transaction.
  127. */
  128. protected function reset()
  129. {
  130. $this->setState(self::STATE_RESET);
  131. $this->commands = array();
  132. }
  133. /**
  134. * Initializes a new transaction.
  135. */
  136. protected function initialize()
  137. {
  138. if ($this->checkState(self::STATE_INITIALIZED)) {
  139. return;
  140. }
  141. $options = $this->options;
  142. if (isset($options['cas']) && $options['cas']) {
  143. $this->flagState(self::STATE_CAS);
  144. }
  145. if (isset($options['watch'])) {
  146. $this->watch($options['watch']);
  147. }
  148. $cas = $this->checkState(self::STATE_CAS);
  149. $discarded = $this->checkState(self::STATE_DISCARDED);
  150. if (!$cas || ($cas && $discarded)) {
  151. $this->client->multi();
  152. if ($discarded) {
  153. $this->unflagState(self::STATE_CAS);
  154. }
  155. }
  156. $this->unflagState(self::STATE_DISCARDED);
  157. $this->flagState(self::STATE_INITIALIZED);
  158. }
  159. /**
  160. * Dinamically invokes a Redis command with the specified arguments.
  161. *
  162. * @param string $method Command ID.
  163. * @param array $arguments Arguments for the command.
  164. * @return MultiExecContext
  165. */
  166. public function __call($method, $arguments)
  167. {
  168. $this->initialize();
  169. $client = $this->client;
  170. if ($this->checkState(self::STATE_CAS)) {
  171. return call_user_func_array(array($client, $method), $arguments);
  172. }
  173. $command = $client->createCommand($method, $arguments);
  174. $response = $client->executeCommand($command);
  175. if (!$response instanceof ResponseQueued) {
  176. $this->onProtocolError('The server did not respond with a QUEUED status reply');
  177. }
  178. $this->commands[] = $command;
  179. return $this;
  180. }
  181. /**
  182. * Executes WATCH on one or more keys.
  183. *
  184. * @param string|array $keys One or more keys.
  185. * @return mixed
  186. */
  187. public function watch($keys)
  188. {
  189. $this->isWatchSupported();
  190. if ($this->checkState(self::STATE_INITIALIZED) && !$this->checkState(self::STATE_CAS)) {
  191. throw new ClientException('WATCH after MULTI is not allowed');
  192. }
  193. $watchReply = $this->client->watch($keys);
  194. $this->flagState(self::STATE_WATCH);
  195. return $watchReply;
  196. }
  197. /**
  198. * Finalizes the transaction on the server by executing MULTI on the server.
  199. *
  200. * @return MultiExecContext
  201. */
  202. public function multi()
  203. {
  204. if ($this->checkState(self::STATE_INITIALIZED | self::STATE_CAS)) {
  205. $this->unflagState(self::STATE_CAS);
  206. $this->client->multi();
  207. }
  208. else {
  209. $this->initialize();
  210. }
  211. return $this;
  212. }
  213. /**
  214. * Executes UNWATCH.
  215. *
  216. * @return MultiExecContext
  217. */
  218. public function unwatch()
  219. {
  220. $this->isWatchSupported();
  221. $this->unflagState(self::STATE_WATCH);
  222. $this->client->unwatch();
  223. return $this;
  224. }
  225. /**
  226. * Resets a transaction by UNWATCHing the keys that are being WATCHed and
  227. * DISCARDing the pending commands that have been already sent to the server.
  228. *
  229. * @return MultiExecContext
  230. */
  231. public function discard()
  232. {
  233. if ($this->checkState(self::STATE_INITIALIZED)) {
  234. $command = $this->checkState(self::STATE_CAS) ? 'unwatch' : 'discard';
  235. $this->client->$command();
  236. $this->reset();
  237. $this->flagState(self::STATE_DISCARDED);
  238. }
  239. return $this;
  240. }
  241. /**
  242. * Executes the whole transaction.
  243. *
  244. * @return mixed
  245. */
  246. public function exec()
  247. {
  248. return $this->execute();
  249. }
  250. /**
  251. * Checks the state of the transaction before execution.
  252. *
  253. * @param mixed $callable Callback for execution.
  254. */
  255. private function checkBeforeExecution($callable)
  256. {
  257. if ($this->checkState(self::STATE_INSIDEBLOCK)) {
  258. throw new ClientException(
  259. "Cannot invoke 'execute' or 'exec' inside an active client transaction block"
  260. );
  261. }
  262. if ($callable) {
  263. if (!is_callable($callable)) {
  264. throw new \InvalidArgumentException(
  265. 'Argument passed must be a callable object'
  266. );
  267. }
  268. if (count($this->commands) > 0) {
  269. $this->discard();
  270. throw new ClientException(
  271. 'Cannot execute a transaction block after using fluent interface'
  272. );
  273. }
  274. }
  275. if (isset($this->options['retry']) && !isset($callable)) {
  276. $this->discard();
  277. throw new \InvalidArgumentException(
  278. 'Automatic retries can be used only when a transaction block is provided'
  279. );
  280. }
  281. }
  282. /**
  283. * Handles the actual execution of the whole transaction.
  284. *
  285. * @param mixed $callable 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. $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\Network\IConnectionSingle.
  371. Helpers::onCommunicationException(new ProtocolException(
  372. $this->client->getConnection(), $message
  373. ));
  374. }
  375. }