MultiExecContext.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 MultiExecContext 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 context.
  42. * @param array $options Options for the context initialization.
  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 a transaction context.
  100. *
  101. * @param ClientInterface $client Client instance used by the context.
  102. */
  103. private function checkCapabilities(ClientInterface $client)
  104. {
  105. if ($client->getConnection() instanceof AggregatedConnectionInterface) {
  106. throw new NotSupportedException('Cannot initialize a MULTI/EXEC context when using aggregated connections');
  107. }
  108. $profile = $client->getProfile();
  109. if ($profile->supportsCommands(array('multi', 'exec', 'discard')) === false) {
  110. throw new NotSupportedException('The current profile does not support MULTI, EXEC and DISCARD');
  111. }
  112. $this->canWatch = $profile->supportsCommands(array('watch', 'unwatch'));
  113. }
  114. /**
  115. * Checks if WATCH and UNWATCH are supported by the server profile.
  116. */
  117. private function isWatchSupported()
  118. {
  119. if ($this->canWatch === false) {
  120. throw new NotSupportedException('The current profile does not support WATCH and UNWATCH');
  121. }
  122. }
  123. /**
  124. * Resets the state of a transaction.
  125. */
  126. protected function reset()
  127. {
  128. $this->setState(self::STATE_RESET);
  129. $this->commands = new SplQueue();
  130. }
  131. /**
  132. * Initializes a new transaction.
  133. */
  134. protected function initialize()
  135. {
  136. if ($this->checkState(self::STATE_INITIALIZED)) {
  137. return;
  138. }
  139. $options = $this->options;
  140. if (isset($options['cas']) && $options['cas']) {
  141. $this->flagState(self::STATE_CAS);
  142. }
  143. if (isset($options['watch'])) {
  144. $this->watch($options['watch']);
  145. }
  146. $cas = $this->checkState(self::STATE_CAS);
  147. $discarded = $this->checkState(self::STATE_DISCARDED);
  148. if (!$cas || ($cas && $discarded)) {
  149. $this->client->multi();
  150. if ($discarded) {
  151. $this->unflagState(self::STATE_CAS);
  152. }
  153. }
  154. $this->unflagState(self::STATE_DISCARDED);
  155. $this->flagState(self::STATE_INITIALIZED);
  156. }
  157. /**
  158. * Dynamically invokes a Redis command with the specified arguments.
  159. *
  160. * @param string $method Command ID.
  161. * @param array $arguments Arguments for the command.
  162. * @return mixed
  163. */
  164. public function __call($method, $arguments)
  165. {
  166. $command = $this->client->createCommand($method, $arguments);
  167. $response = $this->executeCommand($command);
  168. return $response;
  169. }
  170. /**
  171. * Executes the specified Redis command.
  172. *
  173. * @param CommandInterface $command A Redis command.
  174. * @return mixed
  175. */
  176. public function executeCommand(CommandInterface $command)
  177. {
  178. $this->initialize();
  179. $response = $this->client->executeCommand($command);
  180. if ($this->checkState(self::STATE_CAS)) {
  181. return $response;
  182. }
  183. if (!$response instanceof Response\StatusQueued) {
  184. $this->onProtocolError('The server did not respond with a QUEUED status reply');
  185. }
  186. $this->commands->enqueue($command);
  187. return $this;
  188. }
  189. /**
  190. * Executes WATCH on one or more keys.
  191. *
  192. * @param string|array $keys One or more keys.
  193. * @return mixed
  194. */
  195. public function watch($keys)
  196. {
  197. $this->isWatchSupported();
  198. if ($this->checkState(self::STATE_INITIALIZED) && !$this->checkState(self::STATE_CAS)) {
  199. throw new ClientException('WATCH after MULTI is not allowed');
  200. }
  201. $reply = $this->client->watch($keys);
  202. $this->flagState(self::STATE_WATCH);
  203. return $reply;
  204. }
  205. /**
  206. * Finalizes the transaction on the server by executing MULTI on the server.
  207. *
  208. * @return MultiExecContext
  209. */
  210. public function multi()
  211. {
  212. if ($this->checkState(self::STATE_INITIALIZED | self::STATE_CAS)) {
  213. $this->unflagState(self::STATE_CAS);
  214. $this->client->multi();
  215. } else {
  216. $this->initialize();
  217. }
  218. return $this;
  219. }
  220. /**
  221. * Executes UNWATCH.
  222. *
  223. * @return MultiExecContext
  224. */
  225. public function unwatch()
  226. {
  227. $this->isWatchSupported();
  228. $this->unflagState(self::STATE_WATCH);
  229. $this->__call('unwatch', array());
  230. return $this;
  231. }
  232. /**
  233. * Resets a transaction by UNWATCHing the keys that are being WATCHed and
  234. * DISCARDing the pending commands that have been already sent to the server.
  235. *
  236. * @return MultiExecContext
  237. */
  238. public function discard()
  239. {
  240. if ($this->checkState(self::STATE_INITIALIZED)) {
  241. $command = $this->checkState(self::STATE_CAS) ? 'unwatch' : 'discard';
  242. $this->client->$command();
  243. $this->reset();
  244. $this->flagState(self::STATE_DISCARDED);
  245. }
  246. return $this;
  247. }
  248. /**
  249. * Executes the whole transaction.
  250. *
  251. * @return mixed
  252. */
  253. public function exec()
  254. {
  255. return $this->execute();
  256. }
  257. /**
  258. * Checks the state of the transaction before execution.
  259. *
  260. * @param mixed $callable Callback for execution.
  261. */
  262. private function checkBeforeExecution($callable)
  263. {
  264. if ($this->checkState(self::STATE_INSIDEBLOCK)) {
  265. throw new ClientException("Cannot invoke 'execute' or 'exec' inside an active client transaction block");
  266. }
  267. if ($callable) {
  268. if (!is_callable($callable)) {
  269. throw new \InvalidArgumentException('Argument passed must be a callable object');
  270. }
  271. if (!$this->commands->isEmpty()) {
  272. $this->discard();
  273. throw new ClientException('Cannot execute a transaction block after using fluent interface');
  274. }
  275. }
  276. if (isset($this->options['retry']) && !isset($callable)) {
  277. $this->discard();
  278. throw new \InvalidArgumentException('Automatic retries can be used only when a transaction block is provided');
  279. }
  280. }
  281. /**
  282. * Handles the actual execution of the whole transaction.
  283. *
  284. * @param mixed $callable Optional callback for execution.
  285. * @return array
  286. */
  287. public function execute($callable = null)
  288. {
  289. $this->checkBeforeExecution($callable);
  290. $reply = null;
  291. $values = array();
  292. $attempts = isset($this->options['retry']) ? (int) $this->options['retry'] : 0;
  293. do {
  294. if ($callable !== null) {
  295. $this->executeTransactionBlock($callable);
  296. }
  297. if ($this->commands->isEmpty()) {
  298. if ($this->checkState(self::STATE_WATCH)) {
  299. $this->discard();
  300. }
  301. return;
  302. }
  303. $reply = $this->client->exec();
  304. if ($reply === null) {
  305. if ($attempts === 0) {
  306. $message = 'The current transaction has been aborted by the server';
  307. throw new AbortedMultiExecException($this, $message);
  308. }
  309. $this->reset();
  310. if (isset($this->options['on_retry']) && is_callable($this->options['on_retry'])) {
  311. call_user_func($this->options['on_retry'], $this, $attempts);
  312. }
  313. continue;
  314. }
  315. break;
  316. } while ($attempts-- > 0);
  317. $commands = $this->commands;
  318. $size = count($reply);
  319. if ($size !== count($commands)) {
  320. $this->onProtocolError("EXEC returned an unexpected number of replies");
  321. }
  322. $clientOpts = $this->client->getOptions();
  323. $useExceptions = isset($clientOpts->exceptions) ? $clientOpts->exceptions : true;
  324. for ($i = 0; $i < $size; $i++) {
  325. $commandReply = $reply[$i];
  326. if ($commandReply instanceof Response\ErrorInterface && $useExceptions) {
  327. $message = $commandReply->getMessage();
  328. throw new Response\ServerException($message);
  329. }
  330. $values[$i] = $commands->dequeue()->parseResponse($commandReply);
  331. }
  332. return $values;
  333. }
  334. /**
  335. * Passes the current transaction context to a callable block for execution.
  336. *
  337. * @param mixed $callable Callback.
  338. */
  339. protected function executeTransactionBlock($callable)
  340. {
  341. $blockException = null;
  342. $this->flagState(self::STATE_INSIDEBLOCK);
  343. try {
  344. call_user_func($callable, $this);
  345. } catch (CommunicationException $exception) {
  346. $blockException = $exception;
  347. } catch (Response\ServerException $exception) {
  348. $blockException = $exception;
  349. } catch (\Exception $exception) {
  350. $blockException = $exception;
  351. $this->discard();
  352. }
  353. $this->unflagState(self::STATE_INSIDEBLOCK);
  354. if ($blockException !== null) {
  355. throw $blockException;
  356. }
  357. }
  358. /**
  359. * Helper method that handles protocol errors encountered inside a transaction.
  360. *
  361. * @param string $message Error message.
  362. */
  363. private function onProtocolError($message)
  364. {
  365. // Since a MULTI/EXEC block cannot be initialized when using aggregated
  366. // connections, we can safely assume that Predis\Client::getConnection()
  367. // will always return an instance of Predis\Connection\SingleConnectionInterface.
  368. CommunicationException::handle(new ProtocolException(
  369. $this->client->getConnection(), $message
  370. ));
  371. }
  372. }