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\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. }
  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. }
  353. catch (CommunicationException $exception) {
  354. $blockException = $exception;
  355. }
  356. catch (ServerException $exception) {
  357. $blockException = $exception;
  358. }
  359. catch (\Exception $exception) {
  360. $blockException = $exception;
  361. $this->discard();
  362. }
  363. $this->unflagState(self::STATE_INSIDEBLOCK);
  364. if ($blockException !== null) {
  365. throw $blockException;
  366. }
  367. }
  368. /**
  369. * Helper method that handles protocol errors encountered inside a transaction.
  370. *
  371. * @param string $message Error message.
  372. */
  373. private function onProtocolError($message)
  374. {
  375. // Since a MULTI/EXEC block cannot be initialized when using aggregated
  376. // connections, we can safely assume that Predis\Client::getConnection()
  377. // will always return an instance of Predis\Connection\SingleConnectionInterface.
  378. Helpers::onCommunicationException(new ProtocolException(
  379. $this->client->getConnection(), $message
  380. ));
  381. }
  382. }