MultiExec.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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 SplQueue;
  12. use Predis\BasicClientInterface;
  13. use Predis\ClientException;
  14. use Predis\ClientInterface;
  15. use Predis\CommunicationException;
  16. use Predis\ExecutableContextInterface;
  17. use Predis\NotSupportedException;
  18. use Predis\Response;
  19. use Predis\Command\CommandInterface;
  20. use Predis\Connection\AggregatedConnectionInterface;
  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 MultiExec implements BasicClientInterface, ExecutableContextInterface
  28. {
  29. private $state;
  30. private $canWatch;
  31. protected $client;
  32. protected $options;
  33. protected $commands;
  34. /**
  35. * @param ClientInterface $client Client instance used by the transaction.
  36. * @param array $options Initialization options.
  37. */
  38. public function __construct(ClientInterface $client, array $options = null)
  39. {
  40. $this->checkCapabilities($client);
  41. $this->options = $options ?: array();
  42. $this->client = $client;
  43. $this->state = new MultiExecState();
  44. $this->reset();
  45. }
  46. /**
  47. * Checks if the passed client instance satisfies the required conditions
  48. * needed to initialize the transaction object.
  49. *
  50. * @param ClientInterface $client Client instance used by the transaction object.
  51. */
  52. private function checkCapabilities(ClientInterface $client)
  53. {
  54. if ($client->getConnection() instanceof AggregatedConnectionInterface) {
  55. throw new NotSupportedException(
  56. 'Cannot initialize a MULTI/EXEC transaction when using aggregated connections'
  57. );
  58. }
  59. $profile = $client->getProfile();
  60. if ($profile->supportsCommands(array('multi', 'exec', 'discard')) === false) {
  61. throw new NotSupportedException(
  62. 'The current profile does not support MULTI, EXEC and DISCARD'
  63. );
  64. }
  65. $this->canWatch = $profile->supportsCommands(array('watch', 'unwatch'));
  66. }
  67. /**
  68. * Checks if WATCH and UNWATCH are supported by the server profile.
  69. */
  70. private function isWatchSupported()
  71. {
  72. if ($this->canWatch === false) {
  73. throw new NotSupportedException('The current profile does not support WATCH and UNWATCH');
  74. }
  75. }
  76. /**
  77. * Resets the state of a transaction.
  78. */
  79. protected function reset()
  80. {
  81. $this->state->reset();
  82. $this->commands = new SplQueue();
  83. }
  84. /**
  85. * Initializes a new transaction.
  86. */
  87. protected function initialize()
  88. {
  89. if ($this->state->isInitialized()) {
  90. return;
  91. }
  92. $options = $this->options;
  93. if (isset($options['cas']) && $options['cas']) {
  94. $this->state->flag(MultiExecState::CAS);
  95. }
  96. if (isset($options['watch'])) {
  97. $this->watch($options['watch']);
  98. }
  99. $cas = $this->state->isCAS();
  100. $discarded = $this->state->isDiscarded();
  101. if (!$cas || ($cas && $discarded)) {
  102. $this->client->multi();
  103. if ($discarded) {
  104. $this->state->unflag(MultiExecState::CAS);
  105. }
  106. }
  107. $this->state->unflag(MultiExecState::DISCARDED);
  108. $this->state->flag(MultiExecState::INITIALIZED);
  109. }
  110. /**
  111. * Dynamically invokes a Redis command with the specified arguments.
  112. *
  113. * @param string $method Command ID.
  114. * @param array $arguments Arguments for the command.
  115. * @return mixed
  116. */
  117. public function __call($method, $arguments)
  118. {
  119. $command = $this->client->createCommand($method, $arguments);
  120. $response = $this->executeCommand($command);
  121. return $response;
  122. }
  123. /**
  124. * Executes the specified Redis command.
  125. *
  126. * @param CommandInterface $command A Redis command.
  127. * @return mixed
  128. */
  129. public function executeCommand(CommandInterface $command)
  130. {
  131. $this->initialize();
  132. $response = $this->client->executeCommand($command);
  133. if ($this->state->isCAS()) {
  134. return $response;
  135. }
  136. if (!$response instanceof Response\StatusQueued) {
  137. $this->onProtocolError('The server did not respond with a QUEUED status reply');
  138. }
  139. $this->commands->enqueue($command);
  140. return $this;
  141. }
  142. /**
  143. * Executes WATCH on one or more keys.
  144. *
  145. * @param string|array $keys One or more keys.
  146. * @return mixed
  147. */
  148. public function watch($keys)
  149. {
  150. $this->isWatchSupported();
  151. if ($this->state->isWatchAllowed()) {
  152. throw new ClientException('WATCH after MULTI is not allowed');
  153. }
  154. $reply = $this->client->watch($keys);
  155. $this->state->flag(MultiExecState::WATCH);
  156. return $reply;
  157. }
  158. /**
  159. * Finalizes the transaction on the server by executing MULTI on the server.
  160. *
  161. * @return MultiExec
  162. */
  163. public function multi()
  164. {
  165. if ($this->state->check(MultiExecState::INITIALIZED | MultiExecState::CAS)) {
  166. $this->state->unflag(MultiExecState::CAS);
  167. $this->client->multi();
  168. } else {
  169. $this->initialize();
  170. }
  171. return $this;
  172. }
  173. /**
  174. * Executes UNWATCH.
  175. *
  176. * @return MultiExec
  177. */
  178. public function unwatch()
  179. {
  180. $this->isWatchSupported();
  181. $this->state->unflag(MultiExecState::WATCH);
  182. $this->__call('unwatch', array());
  183. return $this;
  184. }
  185. /**
  186. * Resets a transaction by UNWATCHing the keys that are being WATCHed and
  187. * DISCARDing the pending commands that have been already sent to the server.
  188. *
  189. * @return MultiExec
  190. */
  191. public function discard()
  192. {
  193. if ($this->state->isInitialized()) {
  194. $command = $this->state->isCAS() ? 'unwatch' : 'discard';
  195. $this->client->$command();
  196. $this->reset();
  197. $this->state->flag(MultiExecState::DISCARDED);
  198. }
  199. return $this;
  200. }
  201. /**
  202. * Executes the whole transaction.
  203. *
  204. * @return mixed
  205. */
  206. public function exec()
  207. {
  208. return $this->execute();
  209. }
  210. /**
  211. * Checks the state of the transaction before execution.
  212. *
  213. * @param mixed $callable Callback for execution.
  214. */
  215. private function checkBeforeExecution($callable)
  216. {
  217. if ($this->state->isExecuting()) {
  218. throw new ClientException("Cannot invoke 'execute' or 'exec' inside an active client transaction block");
  219. }
  220. if ($callable) {
  221. if (!is_callable($callable)) {
  222. throw new \InvalidArgumentException('Argument passed must be a callable object');
  223. }
  224. if (!$this->commands->isEmpty()) {
  225. $this->discard();
  226. throw new ClientException('Cannot execute a transaction block after using fluent interface');
  227. }
  228. }
  229. if (isset($this->options['retry']) && !isset($callable)) {
  230. $this->discard();
  231. throw new \InvalidArgumentException('Automatic retries can be used only when a transaction block is provided');
  232. }
  233. }
  234. /**
  235. * Handles the actual execution of the whole transaction.
  236. *
  237. * @param mixed $callable Optional callback for execution.
  238. * @return array
  239. */
  240. public function execute($callable = null)
  241. {
  242. $this->checkBeforeExecution($callable);
  243. $reply = null;
  244. $values = array();
  245. $attempts = isset($this->options['retry']) ? (int) $this->options['retry'] : 0;
  246. do {
  247. if ($callable !== null) {
  248. $this->executeTransactionBlock($callable);
  249. }
  250. if ($this->commands->isEmpty()) {
  251. if ($this->state->isWatching()) {
  252. $this->discard();
  253. }
  254. return;
  255. }
  256. $reply = $this->client->exec();
  257. if ($reply === null) {
  258. if ($attempts === 0) {
  259. $message = 'The current transaction has been aborted by the server';
  260. throw new AbortedMultiExecException($this, $message);
  261. }
  262. $this->reset();
  263. if (isset($this->options['on_retry']) && is_callable($this->options['on_retry'])) {
  264. call_user_func($this->options['on_retry'], $this, $attempts);
  265. }
  266. continue;
  267. }
  268. break;
  269. } while ($attempts-- > 0);
  270. $commands = $this->commands;
  271. $size = count($reply);
  272. if ($size !== count($commands)) {
  273. $this->onProtocolError("EXEC returned an unexpected number of replies");
  274. }
  275. $clientOpts = $this->client->getOptions();
  276. $useExceptions = isset($clientOpts->exceptions) ? $clientOpts->exceptions : true;
  277. for ($i = 0; $i < $size; $i++) {
  278. $commandReply = $reply[$i];
  279. if ($commandReply instanceof Response\ErrorInterface && $useExceptions) {
  280. $message = $commandReply->getMessage();
  281. throw new Response\ServerException($message);
  282. }
  283. $values[$i] = $commands->dequeue()->parseResponse($commandReply);
  284. }
  285. return $values;
  286. }
  287. /**
  288. * Passes the current transaction object to a callable block for execution.
  289. *
  290. * @param mixed $callable Callback.
  291. */
  292. protected function executeTransactionBlock($callable)
  293. {
  294. $blockException = null;
  295. $this->state->flag(MultiExecState::INSIDEBLOCK);
  296. try {
  297. call_user_func($callable, $this);
  298. } catch (CommunicationException $exception) {
  299. $blockException = $exception;
  300. } catch (Response\ServerException $exception) {
  301. $blockException = $exception;
  302. } catch (\Exception $exception) {
  303. $blockException = $exception;
  304. $this->discard();
  305. }
  306. $this->state->unflag(MultiExecState::INSIDEBLOCK);
  307. if ($blockException !== null) {
  308. throw $blockException;
  309. }
  310. }
  311. /**
  312. * Helper method that handles protocol errors encountered inside a transaction.
  313. *
  314. * @param string $message Error message.
  315. */
  316. private function onProtocolError($message)
  317. {
  318. // Since a MULTI/EXEC block cannot be initialized when using aggregated
  319. // connections, we can safely assume that Predis\Client::getConnection()
  320. // will always return an instance of Predis\Connection\SingleConnectionInterface.
  321. CommunicationException::handle(new ProtocolException(
  322. $this->client->getConnection(), $message
  323. ));
  324. }
  325. }