MultiExec.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 $method 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 mixed
  161. */
  162. public function executeCommand(CommandInterface $command)
  163. {
  164. $this->initialize();
  165. $response = $this->client->executeCommand($command);
  166. if ($this->state->isCAS()) {
  167. return $response;
  168. }
  169. if ($response != 'QUEUED' && !$response instanceof StatusResponse) {
  170. $this->onProtocolError('The server did not return a +QUEUED status response.');
  171. }
  172. $this->commands->enqueue($command);
  173. return $this;
  174. }
  175. /**
  176. * Executes WATCH against one or more keys.
  177. *
  178. * @param string|array $keys One or more keys.
  179. * @return mixed
  180. */
  181. public function watch($keys)
  182. {
  183. if (!$this->client->getProfile()->supportsCommand('WATCH')) {
  184. throw new NotSupportedException('WATCH is not supported by the current profile.');
  185. }
  186. if ($this->state->isWatchAllowed()) {
  187. throw new ClientException('Sending WATCH after MULTI is not allowed.');
  188. }
  189. $response = $this->call('watch', array($keys));
  190. $this->state->flag(MultiExecState::WATCH);
  191. return $response;
  192. }
  193. /**
  194. * Finalizes the transaction by executing MULTI on the server.
  195. *
  196. * @return MultiExec
  197. */
  198. public function multi()
  199. {
  200. if ($this->state->check(MultiExecState::INITIALIZED | MultiExecState::CAS)) {
  201. $this->state->unflag(MultiExecState::CAS);
  202. $this->call('multi');
  203. } else {
  204. $this->initialize();
  205. }
  206. return $this;
  207. }
  208. /**
  209. * Executes UNWATCH.
  210. *
  211. * @return MultiExec
  212. */
  213. public function unwatch()
  214. {
  215. if (!$this->client->getProfile()->supportsCommand('WATCH')) {
  216. throw new NotSupportedException('UNWATCH is not supported by the current profile.');
  217. }
  218. $this->state->unflag(MultiExecState::WATCH);
  219. $this->__call('unwatch', array());
  220. return $this;
  221. }
  222. /**
  223. * Resets the transaction by UNWATCH-ing the keys that are being WATCHed and
  224. * DISCARD-ing pending commands that have been already sent to the server.
  225. *
  226. * @return MultiExec
  227. */
  228. public function discard()
  229. {
  230. if ($this->state->isInitialized()) {
  231. $this->call($this->state->isCAS() ? 'unwatch' : 'discard');
  232. $this->reset();
  233. $this->state->flag(MultiExecState::DISCARDED);
  234. }
  235. return $this;
  236. }
  237. /**
  238. * Executes the whole transaction.
  239. *
  240. * @return mixed
  241. */
  242. public function exec()
  243. {
  244. return $this->execute();
  245. }
  246. /**
  247. * Checks the state of the transaction before execution.
  248. *
  249. * @param mixed $callable Callback for execution.
  250. */
  251. private function checkBeforeExecution($callable)
  252. {
  253. if ($this->state->isExecuting()) {
  254. throw new ClientException(
  255. 'Cannot invoke "execute" or "exec" inside an active transaction context.'
  256. );
  257. }
  258. if ($callable) {
  259. if (!is_callable($callable)) {
  260. throw new InvalidArgumentException('The argument must be a callable object.');
  261. }
  262. if (!$this->commands->isEmpty()) {
  263. $this->discard();
  264. throw new ClientException(
  265. 'Cannot execute a transaction block after using fluent interface.'
  266. );
  267. }
  268. } elseif ($this->attempts) {
  269. $this->discard();
  270. throw new ClientException(
  271. 'Automatic retries are supported only when a callable block is provided.'
  272. );
  273. }
  274. }
  275. /**
  276. * Handles the actual execution of the whole transaction.
  277. *
  278. * @param mixed $callable Optional callback for execution.
  279. * @return array
  280. */
  281. public function execute($callable = null)
  282. {
  283. $this->checkBeforeExecution($callable);
  284. $execResponse = null;
  285. $attempts = $this->attempts;
  286. do {
  287. if ($callable) {
  288. $this->executeTransactionBlock($callable);
  289. }
  290. if ($this->commands->isEmpty()) {
  291. if ($this->state->isWatching()) {
  292. $this->discard();
  293. }
  294. return;
  295. }
  296. $execResponse = $this->call('exec');
  297. if ($execResponse === null) {
  298. if ($attempts === 0) {
  299. throw new AbortedMultiExecException(
  300. $this, 'The current transaction has been aborted by the server.'
  301. );
  302. }
  303. $this->reset();
  304. continue;
  305. }
  306. break;
  307. } while ($attempts-- > 0);
  308. $response = array();
  309. $commands = $this->commands;
  310. $size = count($execResponse);
  311. if ($size !== count($commands)) {
  312. $this->onProtocolError('EXEC returned an unexpected number of response items.');
  313. }
  314. for ($i = 0; $i < $size; $i++) {
  315. $cmdResponse = $execResponse[$i];
  316. if ($cmdResponse instanceof ErrorResponseInterface && $this->exceptions) {
  317. throw new ServerException($cmdResponse->getMessage());
  318. }
  319. $response[$i] = $commands->dequeue()->parseResponse($cmdResponse);
  320. }
  321. return $response;
  322. }
  323. /**
  324. * Passes the current transaction object to a callable block for execution.
  325. *
  326. * @param mixed $callable Callback.
  327. */
  328. protected function executeTransactionBlock($callable)
  329. {
  330. $exception = null;
  331. $this->state->flag(MultiExecState::INSIDEBLOCK);
  332. try {
  333. call_user_func($callable, $this);
  334. } catch (CommunicationException $exception) {
  335. // NOOP
  336. } catch (ServerException $exception) {
  337. // NOOP
  338. } catch (Exception $exception) {
  339. $this->discard();
  340. }
  341. $this->state->unflag(MultiExecState::INSIDEBLOCK);
  342. if ($exception) {
  343. throw $exception;
  344. }
  345. }
  346. /**
  347. * Helper method for protocol errors encountered inside the transaction.
  348. *
  349. * @param string $message Error message.
  350. */
  351. private function onProtocolError($message)
  352. {
  353. // Since a MULTI/EXEC block cannot be initialized when using aggregate
  354. // connections we can safely assume that Predis\Client::getConnection()
  355. // will return a Predis\Connection\SingleConnectionInterface instance.
  356. CommunicationException::handle(new ProtocolException(
  357. $this->client->getConnection(), $message
  358. ));
  359. }
  360. }