MultiExec.php 13 KB

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