MultiExec.php 12 KB

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