MultiExec.php 12 KB

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