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