MultiExecContext.php 12 KB

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