MultiExec.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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 SplQueue;
  12. use Predis\BasicClientInterface;
  13. use Predis\ClientException;
  14. use Predis\ClientInterface;
  15. use Predis\CommunicationException;
  16. use Predis\ExecutableContextInterface;
  17. use Predis\NotSupportedException;
  18. use Predis\Response;
  19. use Predis\Command\CommandInterface;
  20. use Predis\Connection\AggregatedConnectionInterface;
  21. use Predis\Protocol\ProtocolException;
  22. /**
  23. * Client-side abstraction of a Redis transaction based on MULTI / EXEC.
  24. *
  25. * @author Daniele Alessandri <suppakilla@gmail.com>
  26. */
  27. class MultiExec implements BasicClientInterface, ExecutableContextInterface
  28. {
  29. const STATE_RESET = 0; // 0b00000
  30. const STATE_INITIALIZED = 1; // 0b00001
  31. const STATE_INSIDEBLOCK = 2; // 0b00010
  32. const STATE_DISCARDED = 4; // 0b00100
  33. const STATE_CAS = 8; // 0b01000
  34. const STATE_WATCH = 16; // 0b10000
  35. private $state;
  36. private $canWatch;
  37. protected $client;
  38. protected $options;
  39. protected $commands;
  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->checkCapabilities($client);
  47. $this->options = $options ?: array();
  48. $this->client = $client;
  49. $this->reset();
  50. }
  51. /**
  52. * Sets the internal state flags.
  53. *
  54. * @param int $flags Set of flags
  55. */
  56. protected function setState($flags)
  57. {
  58. $this->state = $flags;
  59. }
  60. /**
  61. * Gets the internal state flags.
  62. *
  63. * @return int
  64. */
  65. protected function getState()
  66. {
  67. return $this->state;
  68. }
  69. /**
  70. * Sets one or more flags.
  71. *
  72. * @param int $flags Set of flags
  73. */
  74. protected function flagState($flags)
  75. {
  76. $this->state |= $flags;
  77. }
  78. /**
  79. * Resets one or more flags.
  80. *
  81. * @param int $flags Set of flags
  82. */
  83. protected function unflagState($flags)
  84. {
  85. $this->state &= ~$flags;
  86. }
  87. /**
  88. * Checks is a flag is set.
  89. *
  90. * @param int $flags Flag
  91. * @return Boolean
  92. */
  93. protected function checkState($flags)
  94. {
  95. return ($this->state & $flags) === $flags;
  96. }
  97. /**
  98. * Checks if the passed client instance satisfies the required conditions
  99. * needed to initialize the transaction object.
  100. *
  101. * @param ClientInterface $client Client instance used by the transaction object.
  102. */
  103. private function checkCapabilities(ClientInterface $client)
  104. {
  105. if ($client->getConnection() instanceof AggregatedConnectionInterface) {
  106. throw new NotSupportedException(
  107. 'Cannot initialize a MULTI/EXEC transaction when using aggregated connections'
  108. );
  109. }
  110. $profile = $client->getProfile();
  111. if ($profile->supportsCommands(array('multi', 'exec', 'discard')) === false) {
  112. throw new NotSupportedException(
  113. 'The current profile does not support MULTI, EXEC and DISCARD'
  114. );
  115. }
  116. $this->canWatch = $profile->supportsCommands(array('watch', 'unwatch'));
  117. }
  118. /**
  119. * Checks if WATCH and UNWATCH are supported by the server profile.
  120. */
  121. private function isWatchSupported()
  122. {
  123. if ($this->canWatch === false) {
  124. throw new NotSupportedException('The current profile does not support WATCH and UNWATCH');
  125. }
  126. }
  127. /**
  128. * Resets the state of a transaction.
  129. */
  130. protected function reset()
  131. {
  132. $this->setState(self::STATE_RESET);
  133. $this->commands = new SplQueue();
  134. }
  135. /**
  136. * Initializes a new transaction.
  137. */
  138. protected function initialize()
  139. {
  140. if ($this->checkState(self::STATE_INITIALIZED)) {
  141. return;
  142. }
  143. $options = $this->options;
  144. if (isset($options['cas']) && $options['cas']) {
  145. $this->flagState(self::STATE_CAS);
  146. }
  147. if (isset($options['watch'])) {
  148. $this->watch($options['watch']);
  149. }
  150. $cas = $this->checkState(self::STATE_CAS);
  151. $discarded = $this->checkState(self::STATE_DISCARDED);
  152. if (!$cas || ($cas && $discarded)) {
  153. $this->client->multi();
  154. if ($discarded) {
  155. $this->unflagState(self::STATE_CAS);
  156. }
  157. }
  158. $this->unflagState(self::STATE_DISCARDED);
  159. $this->flagState(self::STATE_INITIALIZED);
  160. }
  161. /**
  162. * Dynamically invokes a Redis command with the specified arguments.
  163. *
  164. * @param string $method Command ID.
  165. * @param array $arguments Arguments for the command.
  166. * @return mixed
  167. */
  168. public function __call($method, $arguments)
  169. {
  170. $command = $this->client->createCommand($method, $arguments);
  171. $response = $this->executeCommand($command);
  172. return $response;
  173. }
  174. /**
  175. * Executes the specified Redis command.
  176. *
  177. * @param CommandInterface $command A Redis command.
  178. * @return mixed
  179. */
  180. public function executeCommand(CommandInterface $command)
  181. {
  182. $this->initialize();
  183. $response = $this->client->executeCommand($command);
  184. if ($this->checkState(self::STATE_CAS)) {
  185. return $response;
  186. }
  187. if (!$response instanceof Response\StatusQueued) {
  188. $this->onProtocolError('The server did not respond with a QUEUED status reply');
  189. }
  190. $this->commands->enqueue($command);
  191. return $this;
  192. }
  193. /**
  194. * Executes WATCH on one or more keys.
  195. *
  196. * @param string|array $keys One or more keys.
  197. * @return mixed
  198. */
  199. public function watch($keys)
  200. {
  201. $this->isWatchSupported();
  202. if ($this->checkState(self::STATE_INITIALIZED) && !$this->checkState(self::STATE_CAS)) {
  203. throw new ClientException('WATCH after MULTI is not allowed');
  204. }
  205. $reply = $this->client->watch($keys);
  206. $this->flagState(self::STATE_WATCH);
  207. return $reply;
  208. }
  209. /**
  210. * Finalizes the transaction on the server by executing MULTI on the server.
  211. *
  212. * @return MultiExec
  213. */
  214. public function multi()
  215. {
  216. if ($this->checkState(self::STATE_INITIALIZED | self::STATE_CAS)) {
  217. $this->unflagState(self::STATE_CAS);
  218. $this->client->multi();
  219. } else {
  220. $this->initialize();
  221. }
  222. return $this;
  223. }
  224. /**
  225. * Executes UNWATCH.
  226. *
  227. * @return MultiExec
  228. */
  229. public function unwatch()
  230. {
  231. $this->isWatchSupported();
  232. $this->unflagState(self::STATE_WATCH);
  233. $this->__call('unwatch', array());
  234. return $this;
  235. }
  236. /**
  237. * Resets a transaction by UNWATCHing the keys that are being WATCHed and
  238. * DISCARDing the pending commands that have been already sent to the server.
  239. *
  240. * @return MultiExec
  241. */
  242. public function discard()
  243. {
  244. if ($this->checkState(self::STATE_INITIALIZED)) {
  245. $command = $this->checkState(self::STATE_CAS) ? 'unwatch' : 'discard';
  246. $this->client->$command();
  247. $this->reset();
  248. $this->flagState(self::STATE_DISCARDED);
  249. }
  250. return $this;
  251. }
  252. /**
  253. * Executes the whole transaction.
  254. *
  255. * @return mixed
  256. */
  257. public function exec()
  258. {
  259. return $this->execute();
  260. }
  261. /**
  262. * Checks the state of the transaction before execution.
  263. *
  264. * @param mixed $callable Callback for execution.
  265. */
  266. private function checkBeforeExecution($callable)
  267. {
  268. if ($this->checkState(self::STATE_INSIDEBLOCK)) {
  269. throw new ClientException("Cannot invoke 'execute' or 'exec' inside an active client transaction block");
  270. }
  271. if ($callable) {
  272. if (!is_callable($callable)) {
  273. throw new \InvalidArgumentException('Argument passed must be a callable object');
  274. }
  275. if (!$this->commands->isEmpty()) {
  276. $this->discard();
  277. throw new ClientException('Cannot execute a transaction block after using fluent interface');
  278. }
  279. }
  280. if (isset($this->options['retry']) && !isset($callable)) {
  281. $this->discard();
  282. throw new \InvalidArgumentException('Automatic retries can be used only when a transaction block is provided');
  283. }
  284. }
  285. /**
  286. * Handles the actual execution of the whole transaction.
  287. *
  288. * @param mixed $callable Optional callback for execution.
  289. * @return array
  290. */
  291. public function execute($callable = null)
  292. {
  293. $this->checkBeforeExecution($callable);
  294. $reply = null;
  295. $values = array();
  296. $attempts = isset($this->options['retry']) ? (int) $this->options['retry'] : 0;
  297. do {
  298. if ($callable !== null) {
  299. $this->executeTransactionBlock($callable);
  300. }
  301. if ($this->commands->isEmpty()) {
  302. if ($this->checkState(self::STATE_WATCH)) {
  303. $this->discard();
  304. }
  305. return;
  306. }
  307. $reply = $this->client->exec();
  308. if ($reply === null) {
  309. if ($attempts === 0) {
  310. $message = 'The current transaction has been aborted by the server';
  311. throw new AbortedMultiExecException($this, $message);
  312. }
  313. $this->reset();
  314. if (isset($this->options['on_retry']) && is_callable($this->options['on_retry'])) {
  315. call_user_func($this->options['on_retry'], $this, $attempts);
  316. }
  317. continue;
  318. }
  319. break;
  320. } while ($attempts-- > 0);
  321. $commands = $this->commands;
  322. $size = count($reply);
  323. if ($size !== count($commands)) {
  324. $this->onProtocolError("EXEC returned an unexpected number of replies");
  325. }
  326. $clientOpts = $this->client->getOptions();
  327. $useExceptions = isset($clientOpts->exceptions) ? $clientOpts->exceptions : true;
  328. for ($i = 0; $i < $size; $i++) {
  329. $commandReply = $reply[$i];
  330. if ($commandReply instanceof Response\ErrorInterface && $useExceptions) {
  331. $message = $commandReply->getMessage();
  332. throw new Response\ServerException($message);
  333. }
  334. $values[$i] = $commands->dequeue()->parseResponse($commandReply);
  335. }
  336. return $values;
  337. }
  338. /**
  339. * Passes the current transaction object to a callable block for execution.
  340. *
  341. * @param mixed $callable Callback.
  342. */
  343. protected function executeTransactionBlock($callable)
  344. {
  345. $blockException = null;
  346. $this->flagState(self::STATE_INSIDEBLOCK);
  347. try {
  348. call_user_func($callable, $this);
  349. } catch (CommunicationException $exception) {
  350. $blockException = $exception;
  351. } catch (Response\ServerException $exception) {
  352. $blockException = $exception;
  353. } catch (\Exception $exception) {
  354. $blockException = $exception;
  355. $this->discard();
  356. }
  357. $this->unflagState(self::STATE_INSIDEBLOCK);
  358. if ($blockException !== null) {
  359. throw $blockException;
  360. }
  361. }
  362. /**
  363. * Helper method that handles protocol errors encountered inside a transaction.
  364. *
  365. * @param string $message Error message.
  366. */
  367. private function onProtocolError($message)
  368. {
  369. // Since a MULTI/EXEC block cannot be initialized when using aggregated
  370. // connections, we can safely assume that Predis\Client::getConnection()
  371. // will always return an instance of Predis\Connection\SingleConnectionInterface.
  372. CommunicationException::handle(new ProtocolException(
  373. $this->client->getConnection(), $message
  374. ));
  375. }
  376. }