MultiExec.php 12 KB

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