MultiExec.php 12 KB

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