MultiExecContext.php 12 KB

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