MultiExec.php 11 KB

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