diff --git a/CHANGELOG.md b/CHANGELOG.md index 96b483db..554b13d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,13 @@ - Added support for `ZMOVE`, `BZMOVE`, `ZMOVEMEMBER` commands (#1762) ### Fixed -- Fixed transactions retrying commands on a new connection after `WATCH` or `MULTI`, where they ran outside of the transaction (#1756) -- Fixed transactions built with the fluent interface leaving the connection in `MULTI` after Redis rejected a queued command; the transaction now throws `AbortedMultiExecException` until `discard()` is called (#1755) +- Fixed transactions running commands outside of the transaction after a lost connection (#1756, #1758) +- Fixed fluent transactions leaving the connection in `MULTI` after a queued command was rejected (#1755) +- Fixed fluent cluster transactions committing other commands after a cross-slot error (#1758) +- Fixed a `TypeError` on protocol errors in transactions with replication or cluster (#1758) +- Fixed a `TypeError` when retrying a transaction after a failed connect (#1758) +- Fixed transactions reused after `exec()` running commands outside of `MULTI` and failing on `discard()` (#1758) +- Fixed transactions leaving the connection in `MULTI` when Redis before 6.0.6 rejected `EXEC` (#1758) - Fixed Relay connections closed by the server throwing on `disconnect()` or failing the next command (#1761) - Fixed a failed TLS handshake throwing the error handler's exception instead of `StreamInitException`, which skipped retries (#1768) diff --git a/src/Transaction/MultiExec.php b/src/Transaction/MultiExec.php index bdb7db48..54dc111c 100644 --- a/src/Transaction/MultiExec.php +++ b/src/Transaction/MultiExec.php @@ -18,7 +18,7 @@ use Predis\ClientException; use Predis\ClientInterface; use Predis\Command\CommandInterface; use Predis\CommunicationException; -use Predis\Connection\Cluster\ClusterInterface; +use Predis\Connection\AggregateConnectionInterface; use Predis\NotSupportedException; use Predis\Protocol\ProtocolException; use Predis\Response\Error; @@ -242,14 +242,14 @@ class MultiExec implements ClientContextInterface } elseif ($response instanceof Relay) { $this->commands->enqueue($command); } elseif ($response instanceof ErrorResponseInterface) { - if (!$this->state->isExecuting() && !$this->isClusterTransaction()) { + if (!$this->state->isExecuting() && !$this->state->isCAS()) { $this->abortQueuedTransaction(); $this->state->flag(MultiExecState::ABORTED); } throw new AbortedMultiExecException($this, $response->getMessage()); } else { - $this->onProtocolError('The server did not return a +QUEUED status response.'); + $this->onProtocolError('The server did not return a +QUEUED status response.', $command); } return $this; @@ -319,11 +319,9 @@ class MultiExec implements ClientContextInterface $this->state->unflag(MultiExecState::WATCH); - // MULTI has been sent: at once without CAS, by multi() in CAS mode. UNWATCH is then queued with the other commands. if ($this->state->isInitialized() && !$this->state->isCAS()) { $this->__call('UNWATCH', []); } else { - // The strategy also stops keeping the transaction on its connection. $this->connectionStrategy->unwatch(); } @@ -341,14 +339,22 @@ class MultiExec implements ClientContextInterface $this->state->unflag(MultiExecState::ABORTED); if ($this->state->isInitialized()) { - if ($this->state->isCAS()) { - $this->connectionStrategy->unwatch(); - } else { - $this->connectionStrategy->discard(); + try { + if ($this->state->isCAS()) { + $this->connectionStrategy->unwatch(); + } else { + $this->connectionStrategy->discard(); + } + } finally { + $this->reset(); + $this->state->flag(MultiExecState::DISCARDED); + } + } elseif ($this->state->isWatching()) { + try { + $this->connectionStrategy->unwatch(); + } finally { + $this->reset(); } - - $this->reset(); - $this->state->flag(MultiExecState::DISCARDED); } return $this; @@ -432,7 +438,16 @@ class MultiExec implements ClientContextInterface return; } - $execResponse = $this->connectionStrategy->executeTransaction(); + try { + $execResponse = $this->connectionStrategy->executeTransaction(); + } catch (ServerException $exception) { + $this->reset(); + + throw $exception; + } + + $commands = $this->commands; + $this->reset(); // The additional `false` check is needed for Relay, // let's hope it won't break anything @@ -443,8 +458,6 @@ class MultiExec implements ClientContextInterface ); } - $this->reset(); - continue; } @@ -452,12 +465,11 @@ class MultiExec implements ClientContextInterface } while ($attempts-- > 0); $response = []; - $commands = $this->commands; $size = count($execResponse); $protocolVersion = $this->client->getConnection()->getParameters()->protocol; if ($size !== count($commands)) { - $this->onProtocolError('EXEC returned an unexpected number of response items.'); + $this->onProtocolError('EXEC returned an unexpected number of response items.', $commands->bottom()); } for ($i = 0; $i < $size; ++$i) { @@ -518,34 +530,18 @@ class MultiExec implements ClientContextInterface } /** - * Discards the transaction. When DISCARD fails, the connection is closed - * so that it cannot stay in MULTI. + * Discards the transaction, keeping the error that aborted it rather than + * one from DISCARD. When DISCARD fails, the connection strategy closes the + * connection, so that it cannot stay in MULTI. */ private function abortQueuedTransaction(): void { - if ($this->isClusterTransaction()) { - $this->discard(); - - return; - } - try { $this->discard(); } catch (Throwable $exception) { - $this->client->getConnection()->disconnect(); - $this->reset(); } } - /** - * Cluster transactions send MULTI only from execute(), so their errors - * before that come from the client and nothing is queued on a node. - */ - private function isClusterTransaction(): bool - { - return $this->client->getConnection() instanceof ClusterInterface; - } - /** * Prevents commands queued after a failed one from running as a new * transaction, unless discard() is called first. @@ -564,15 +560,17 @@ class MultiExec implements ClientContextInterface /** * Helper method for protocol errors encountered inside the transaction. * - * @param string $message Error message. + * @param string $message Error message. + * @param CommandInterface $command Command sent to the connection holding the transaction. */ - private function onProtocolError($message) + private function onProtocolError($message, CommandInterface $command) { - // Since a MULTI/EXEC block cannot be initialized when using aggregate - // connections we can safely assume that Predis\Client::getConnection() - // will return a Predis\Connection\NodeConnectionInterface instance. - CommunicationException::handle(new ProtocolException( - $this->client->getConnection(), $message - )); + $connection = $this->client->getConnection(); + + if ($connection instanceof AggregateConnectionInterface) { + $connection = $connection->getConnectionByCommand($command); + } + + CommunicationException::handle(new ProtocolException($connection, $message)); } } diff --git a/src/Transaction/MultiExecState.php b/src/Transaction/MultiExecState.php index fd2d6819..b7c2dd32 100644 --- a/src/Transaction/MultiExecState.php +++ b/src/Transaction/MultiExecState.php @@ -22,7 +22,7 @@ class MultiExecState public const DISCARDED = 4; // 0b00100 public const CAS = 8; // 0b01000 public const WATCH = 16; // 0b10000 - public const ABORTED = 32; // 0b100000 + public const ABORTED = 32; // 0b100000 private $flags; diff --git a/src/Transaction/Strategy/NonClusterConnectionStrategy.php b/src/Transaction/Strategy/NonClusterConnectionStrategy.php index 4fcae69d..004b338e 100644 --- a/src/Transaction/Strategy/NonClusterConnectionStrategy.php +++ b/src/Transaction/Strategy/NonClusterConnectionStrategy.php @@ -23,10 +23,9 @@ use Predis\Connection\ConnectionException; use Predis\Connection\NodeConnectionInterface; use Predis\Connection\RelayConnection; use Predis\Connection\Replication\ReplicationInterface; -use Predis\Connection\Resource\Exception\StreamInitException; use Predis\Response\ErrorInterface; use Predis\Response\ServerException; -use Predis\TimeoutException; +use Predis\Response\Status; use Predis\Transaction\MultiExecState; use Predis\Transaction\Response\BypassTransactionResponse; use Throwable; @@ -47,9 +46,10 @@ abstract class NonClusterConnectionStrategy implements StrategyInterface protected $state; /** - * Physical connection holding the transaction and its WATCH state. Commands - * are not retried once it is set: on another connection they would run - * outside of the transaction. + * Node connection holding the transaction from WATCH or MULTI until EXEC, + * DISCARD or UNWATCH. Commands are not retried while it is set, since they + * would run outside of the transaction on another connection. Once it is + * lost, commands fail until discard() or unwatch(). * * @var NodeConnectionInterface|null */ @@ -86,14 +86,27 @@ abstract class NonClusterConnectionStrategy implements StrategyInterface } /** + * Closes the connection when EXEC fails with any error but EXECABORT, + * since Redis before 6.0.6 can reject EXEC with BUSY, LOADING or + * MASTERDOWN and keep MULTI open. + * * {@inheritDoc} */ public function executeTransaction() { + $connection = $this->nodeConnection ?: $this->connection; + try { return $this->executeBypassingTransaction(new EXEC())->getResponse(); + } catch (ServerException $exception) { + if (strpos($exception->getMessage(), 'EXECABORT') !== 0 && !$connection instanceof RelayConnection) { + $connection->disconnect(); + $this->nodeConnection = null; + } + + throw $exception; } finally { - $this->releaseNode(); + $this->releaseConnection(); } } @@ -102,8 +115,7 @@ abstract class NonClusterConnectionStrategy implements StrategyInterface */ public function multi() { - $multi = new MULTI(); - $response = $this->executeBypassingTransaction($multi)->getResponse(); + $response = $this->executeBypassingTransaction(new MULTI())->getResponse(); $this->holdConnection(); return $response; @@ -123,26 +135,50 @@ abstract class NonClusterConnectionStrategy implements StrategyInterface } /** + * A lost connection has nothing left to unwatch: closing it dropped the + * watched keys on the server. + * * {@inheritDoc} * @throws Throwable */ public function unwatch() { - // Retrying UNWATCH is harmless: a new connection watches nothing. - $this->releaseNode(); + if ($this->isConnectionLost()) { + $this->nodeConnection = null; + + return new Status('OK'); + } + + $this->nodeConnection = null; return $this->send(new UNWATCH()); } /** + * Ends the transaction even when DISCARD fails, closing the connection so + * that it cannot stay in MULTI. A lost connection has nothing left to + * discard: closing it ended the transaction on the server. + * * {@inheritDoc} */ public function discard() { + if ($this->isConnectionLost()) { + $this->nodeConnection = null; + + return new Status('OK'); + } + + $connection = $this->nodeConnection ?: $this->connection; + try { return $this->executeBypassingTransaction(new DISCARD())->getResponse(); + } catch (ServerException $exception) { + $connection->disconnect(); + + throw $exception; } finally { - $this->releaseNode(); + $this->nodeConnection = null; } } @@ -191,21 +227,14 @@ abstract class NonClusterConnectionStrategy implements StrategyInterface private function send(CommandInterface $command) { if ($connection = $this->nodeConnection) { - // A connection that is no longer open would reconnect and run the command outside the transaction. if (!$connection->isConnected()) { - $this->releaseNode(); - throw new ConnectionException($connection, 'The connection holding the transaction was lost.'); } try { return $connection->executeCommand($command); - } catch (CommunicationException|StreamInitException $exception) { - $this->releaseNode(); - - if ($exception instanceof CommunicationException) { - $this->onFailCallback($exception); - } + } catch (CommunicationException $exception) { + $connection->disconnect(); throw $exception; } @@ -216,8 +245,10 @@ abstract class NonClusterConnectionStrategy implements StrategyInterface return $retry->callWithRetry( function () use ($command) { return $this->connection->executeCommand($command); - }, function (CommunicationException $e) { - $this->onFailCallback($e); + }, function (Throwable $e) { + if ($e instanceof CommunicationException) { + $e->getConnection()->disconnect(); + } } ); } @@ -234,42 +265,19 @@ abstract class NonClusterConnectionStrategy implements StrategyInterface } } - private function releaseNode(): void + /** + * Stops holding the connection once it has replied to EXEC. A lost + * connection stays held until discard() or unwatch(). + */ + private function releaseConnection(): void { - $this->nodeConnection = null; + if (!$this->isConnectionLost()) { + $this->nodeConnection = null; + } } - /** - * Handle communication exception. - * - * @param CommunicationException $e - * @return void - */ - private function onFailCallback(CommunicationException $e) + private function isConnectionLost(): bool { - $connection = $e->getConnection(); - - if ($connection instanceof NodeConnectionInterface) { - $connection->disconnect(); - - return; - } - - if ($e instanceof ConnectionException) { - $nodeConnection = $e->getConnection(); - - if ($nodeConnection) { - $nodeConnection->disconnect(); - $this->connection->remove($nodeConnection); - } - } - - if ($e instanceof TimeoutException) { - $nodeConnection = $e->getConnection(); - - if ($nodeConnection) { - $nodeConnection->disconnect(); - } - } + return $this->nodeConnection && !$this->nodeConnection->isConnected(); } } diff --git a/tests/Predis/Transaction/MultiExecTest.php b/tests/Predis/Transaction/MultiExecTest.php index 7f4b3811..fb5aad68 100644 --- a/tests/Predis/Transaction/MultiExecTest.php +++ b/tests/Predis/Transaction/MultiExecTest.php @@ -13,6 +13,7 @@ namespace Predis\Transaction; use Exception; +use InvalidArgumentException; use PHPUnit\Framework\MockObject\MockObject; use Predis\Client; use Predis\ClientException; @@ -27,7 +28,10 @@ use Predis\Connection\ConnectionException; use Predis\Connection\FactoryInterface; use Predis\Connection\NodeConnectionInterface; use Predis\Connection\Parameters; +use Predis\Connection\Replication\ReplicationInterface; use Predis\Connection\StreamConnection; +use Predis\PredisException; +use Predis\Protocol\ProtocolException; use Predis\Response; use Predis\Retry\Retry; use Predis\Retry\Strategy\ExponentialBackoff; @@ -261,6 +265,58 @@ class MultiExecTest extends PredisTestCase $this->assertSame(['MULTI', 'SET', 'GET', 'DISCARD'], self::commandsToIDs($commands)); } + /** + * @group disconnected + */ + public function testCheckAndSetTransactionSendsUnwatchOnDiscard(): void + { + $commands = $cas = []; + + $callback = $this->getExecuteCallback(null, $commands, $cas); + $tx = $this->getMockedTransaction($callback, ['cas' => true, 'watch' => 'foo']); + + $responses = $tx->execute(static function ($tx) { + $tx->get('foo'); + $tx->discard(); + }); + + $this->assertNull($responses); + $this->assertSame([], self::commandsToIDs($commands)); + $this->assertSame(['WATCH', 'GET', 'UNWATCH'], self::commandsToIDs($cas)); + } + + /** + * @group disconnected + */ + public function testThrowsExceptionOnNonCallableArgument(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The argument must be a callable object.'); + + $this->getMockedTransaction($this->getExecuteCallback())->execute('not a callable'); + } + + /** + * @group disconnected + */ + public function testParsesExecRepliesWithResp3(): void + { + $connection = $this->getMockBuilder(NodeConnectionInterface::class)->getMock(); + $connection + ->method('executeCommand') + ->willReturnCallback($this->getExecuteCallback([[['member', 1.0]]])); + $connection + ->method('getParameters') + ->willReturn(new Parameters(['protocol' => 3])); + $connection + ->method('isConnected') + ->willReturn(true); + + $tx = new MultiExec(new Client($connection)); + + $this->assertSame([[['member' => 1.0]]], $tx->zpopmin('key')->execute()); + } + /** * @group disconnected */ @@ -677,10 +733,16 @@ class MultiExecTest extends PredisTestCase /** * @group disconnected */ - public function testQueueErrorWithFluentInterfaceDiscardsTransaction(): void + public function testQueueErrorWithFluentInterfaceAbortsTransactionUntilDiscard(): void { + $sent = []; $commands = []; - $tx = $this->getMockedTransaction($this->getQueueErrorCallback($commands)); + $callback = $this->getQueueErrorCallback($commands, ['foo']); + $tx = $this->getMockedTransaction(static function (CommandInterface $command) use ($callback, &$sent) { + $sent[] = $command->getId(); + + return $callback($command); + }); try { $tx->set('foo', 'bar')->executeCommand(new RawCommand('SET', ['foo']))->execute(); @@ -689,25 +751,11 @@ class MultiExecTest extends PredisTestCase $this->assertSame("ERR wrong number of arguments for 'set' command", $exception->getMessage()); } - $this->assertSame(['MULTI', 'SET', 'SET', 'DISCARD'], self::commandsToIDs($commands)); - } - - /** - * @group disconnected - */ - public function testFluentTransactionAbortedByQueueErrorCannotBeReused(): void - { - $commands = []; - $tx = $this->getMockedTransaction($this->getQueueErrorCallback($commands, ['foo'])); - - try { - $tx->set('foo', 'bar')->executeCommand(new RawCommand('SET', ['foo'])); - } catch (AbortedMultiExecException $exception) { - // NOOP - } + $this->assertSame($tx, $tx->unwatch()); foreach ([ static function (MultiExec $tx) { $tx->set('foo', 'baz'); }, + static function (MultiExec $tx) { $tx->watch('foo'); }, static function (MultiExec $tx) { $tx->execute(); }, ] as $reuse) { try { @@ -718,113 +766,19 @@ class MultiExecTest extends PredisTestCase } } - $this->assertSame(['MULTI', 'SET', 'SET', 'DISCARD'], self::commandsToIDs($commands)); - - $this->assertSame(['foo'], $tx->discard()->echo('foo')->execute()); - $this->assertSame( - ['MULTI', 'SET', 'SET', 'DISCARD', 'MULTI', 'ECHO', 'EXEC'], - self::commandsToIDs($commands) - ); - } - - /** - * @group disconnected - */ - public function testQueueErrorWithFluentInterfaceClosesConnectionWhenDiscardFails(): void - { - $connection = $this->getMockedConnection(static function (CommandInterface $command) { - switch ($command->getId()) { - case 'MULTI': - return new Response\Status('OK'); - case 'DISCARD': - return new Response\Error('NOPERM simulated DISCARD failure'); - case 'SET': - return new Response\Error("ERR wrong number of arguments for 'set' command"); - default: - return new Response\Status('QUEUED'); - } - }); - $connection - ->expects($this->once()) - ->method('disconnect'); - - $tx = new MultiExec(new Client($connection)); - - try { - $tx->executeCommand(new RawCommand('SET', ['foo'])); - $this->fail('Expected the transaction to abort.'); - } catch (AbortedMultiExecException $exception) { - $this->assertSame("ERR wrong number of arguments for 'set' command", $exception->getMessage()); - } - } - - /** - * @group disconnected - */ - public function testUnwatchAfterQueueErrorKeepsTheTransactionAborted(): void - { - $commands = []; - $tx = $this->getMockedTransaction($this->getQueueErrorCallback($commands, ['foo'])); - - try { - $tx->set('foo', 'bar')->executeCommand(new RawCommand('SET', ['foo'])); - $this->fail('Expected the transaction to abort.'); - } catch (AbortedMultiExecException $exception) { - $this->assertSame($tx, $tx->unwatch()); - } - - try { - $tx->set('foo', 'baz'); - $this->fail('Expected the aborted transaction to stay aborted.'); - } catch (AbortedMultiExecException $exception) { - $this->assertStringStartsWith('The transaction has already been aborted', $exception->getMessage()); - } - - $this->assertSame(['MULTI', 'SET', 'SET', 'DISCARD'], self::commandsToIDs($commands)); - - $this->assertSame(['foo'], $tx->discard()->echo('foo')->execute()); - $this->assertSame( - ['MULTI', 'SET', 'SET', 'DISCARD', 'MULTI', 'ECHO', 'EXEC'], - self::commandsToIDs($commands) - ); - } - - /** - * @group disconnected - */ - public function testWatchAfterQueueErrorIsNotSent(): void - { - $sent = []; - $callback = $this->getQueueErrorCallback(); - $tx = $this->getMockedTransaction(static function (CommandInterface $command) use ($callback, &$sent) { - $sent[] = $command->getId(); - - return $callback($command); - }); - - try { - $tx->set('foo', 'bar')->executeCommand(new RawCommand('SET', ['foo'])); - } catch (AbortedMultiExecException $exception) { - // NOOP - } - - try { - $tx->watch('foo'); - $this->fail('Expected the aborted transaction to stay aborted.'); - } catch (AbortedMultiExecException $exception) { - $this->assertStringStartsWith('The transaction has already been aborted', $exception->getMessage()); - } - $this->assertSame(['MULTI', 'SET', 'SET', 'DISCARD'], $sent); + + $this->assertSame(['foo'], $tx->discard()->echo('foo')->execute()); + $this->assertSame(['MULTI', 'SET', 'SET', 'DISCARD', 'MULTI', 'ECHO', 'EXEC'], $sent); } /** * @group disconnected */ - public function testClusterSlotErrorWithFluentInterfaceKeepsQueuedCommands(): void + public function testClusterSlotErrorWithFluentInterfaceAbortsTransaction(): void { $commands = []; - $tx = $this->getMockedClusterTransaction($this->getExecuteCallback(['OK', 'OK'], $commands)); + $tx = $this->getMockedClusterTransaction($this->getExecuteCallback(['OK'], $commands)); $tx->set('{a}foo', 'bar'); try { @@ -834,8 +788,459 @@ class MultiExecTest extends PredisTestCase $this->assertStringContainsString('same hash slot', $exception->getMessage()); } - $this->assertEquals(['OK', 'OK'], $tx->set('{a}baz', 'qux')->execute()); - $this->assertSame(['MULTI', 'SET', 'SET', 'EXEC'], self::commandsToIDs($commands)); + try { + $tx->set('{a}baz', 'qux')->execute(); + $this->fail('Expected the aborted transaction to stay aborted.'); + } catch (AbortedMultiExecException $exception) { + $this->assertStringStartsWith('The transaction has already been aborted', $exception->getMessage()); + } + + $this->assertEquals(['OK'], $tx->discard()->set('{a}baz', 'qux')->execute()); + $this->assertSame(['MULTI', 'SET', 'EXEC'], self::commandsToIDs($commands)); + } + + /** + * @group disconnected + */ + public function testClusterSlotErrorBeforeMultiWithFluentInterfaceDoesNotAbortTransaction(): void + { + $commands = []; + $cas = []; + $tx = $this->getMockedClusterTransaction( + $this->getExecuteCallback(['OK'], $commands, $cas), + ['cas' => true, 'watch' => '{a}foo'] + ); + $tx->get('{a}foo'); + + try { + $tx->get('{b}foo'); + $this->fail('Expected the command to be rejected.'); + } catch (AbortedMultiExecException $exception) { + $this->assertStringContainsString('same hash slot', $exception->getMessage()); + } + + $this->assertEquals(['OK'], $tx->multi()->set('{a}foo', 'bar')->execute()); + $this->assertSame(['WATCH', 'GET'], self::commandsToIDs($cas)); + $this->assertSame(['MULTI', 'SET', 'EXEC'], self::commandsToIDs($commands)); + } + + /** + * @group disconnected + * @dataProvider completedTransactions + */ + public function testExecEndsTheTransaction($exec, ?string $error, bool $discard): void + { + $sent = []; + $connection = $this->getMockedConnection(static function (CommandInterface $command) use ($exec, &$sent) { + $sent[] = $command->getId(); + + switch ($command->getId()) { + case 'SET': + return new Response\Status('QUEUED'); + case 'EXEC': + return $exec; + default: + return new Response\Status('OK'); + } + }); + $connection + ->expects($this->never()) + ->method('disconnect'); + + $tx = new MultiExec(new Client($connection), ['watch' => 'foo']); + + try { + $tx->set('foo', 'bar')->execute(); + $this->assertNull($error); + } catch (PredisException $exception) { + $this->assertSame($error, $exception->getMessage()); + } + + if ($discard) { + $this->assertNull($tx->discard()->execute()); + } + + $this->assertSame(['WATCH', 'MULTI', 'SET', 'EXEC'], $sent); + + $tx->set('foo', 'baz'); + $this->assertSame(['WATCH', 'MULTI', 'SET', 'EXEC', 'WATCH', 'MULTI', 'SET'], $sent); + } + + public function completedTransactions(): array + { + $outcomes = [ + 'EXEC succeeded' => [ + [new Response\Status('OK')], + null, + ], + 'EXEC reported a failed command' => [ + [new Response\Error('ERR value is not an integer or out of range')], + 'ERR value is not an integer or out of range', + ], + 'EXEC aborted by a watched key' => [ + null, + 'The current transaction has been aborted by the server.', + ], + 'EXEC rejected' => [ + new Response\Error('EXECABORT Transaction discarded because of previous errors.'), + 'EXECABORT Transaction discarded because of previous errors.', + ], + ]; + + $cases = []; + + foreach ($outcomes as $outcome => $arguments) { + $cases["$outcome, then discard() and reuse"] = array_merge($arguments, [true]); + $cases["$outcome, then reuse"] = array_merge($arguments, [false]); + } + + return $cases; + } + + /** + * @group disconnected + */ + public function testExecOnALostConnectionFailsUntilDiscard(): void + { + $sent = []; + $connected = true; + $connection = $this->getMockBuilder(NodeConnectionInterface::class)->getMock(); + $connection + ->method('executeCommand') + ->willReturnCallback(static function (CommandInterface $command) use (&$sent, &$connected, $connection) { + $connected = true; + $sent[] = $command->getId(); + + switch ($command->getId()) { + case 'SET': + return new Response\Status('QUEUED'); + case 'EXEC': + if ($sent === ['MULTI', 'SET', 'EXEC']) { + throw new ConnectionException($connection, 'Connection lost'); + } + + return [new Response\Status('OK')]; + default: + return new Response\Status('OK'); + } + }); + $connection + ->expects($this->once()) + ->method('disconnect') + ->willReturnCallback(static function () use (&$connected) { + $connected = false; + }); + $connection + ->method('isConnected') + ->willReturnCallback(static function () use (&$connected) { + return $connected; + }); + $connection + ->method('getParameters') + ->willReturn(new Parameters(['protocol' => 2])); + + $tx = new MultiExec(new Client($connection)); + + try { + $tx->set('foo', 'bar')->execute(); + $this->fail('Expected the transaction to fail.'); + } catch (ConnectionException $exception) { + $this->assertSame('Connection lost', $exception->getMessage()); + } + + try { + $tx->set('foo', 'baz'); + $this->fail('Expected the transaction to fail on its lost connection.'); + } catch (ConnectionException $exception) { + $this->assertSame('The connection holding the transaction was lost.', $exception->getMessage()); + } + + $this->assertEquals(['OK'], $tx->discard()->set('foo', 'baz')->execute()); + $this->assertSame(['MULTI', 'SET', 'EXEC', 'MULTI', 'SET', 'EXEC'], $sent); + } + + /** + * @group disconnected + * @dataProvider transactionFailures + */ + public function testDiscardAfterAFailureMakesTheTransactionUsableAgain( + array $options, + callable $respond, + string $message, + array $expected + ): void { + $sent = []; + $connected = true; + $connection = $this->getMockBuilder(NodeConnectionInterface::class)->getMock(); + $connection + ->method('executeCommand') + ->willReturnCallback(static function (CommandInterface $command) use (&$sent, &$connected, $connection, $respond) { + $connected = true; + $sent[] = $command->getId(); + + if (null !== $response = $respond($command, $sent, $connection)) { + return $response; + } + + switch ($command->getId()) { + case 'SET': + return new Response\Status('QUEUED'); + case 'EXEC': + return [new Response\Status('OK')]; + default: + return new Response\Status('OK'); + } + }); + $connection + ->expects($this->once()) + ->method('disconnect') + ->willReturnCallback(static function () use (&$connected) { + $connected = false; + }); + $connection + ->method('isConnected') + ->willReturnCallback(static function () use (&$connected) { + return $connected; + }); + $connection + ->method('getParameters') + ->willReturn(new Parameters(['protocol' => 2])); + + $tx = new MultiExec(new Client($connection), $options); + + try { + $tx->executeCommand(new RawCommand('SET', ['foo'])); + $this->fail('Expected the transaction to fail.'); + } catch (PredisException $exception) { + $this->assertSame($message, $exception->getMessage()); + } + + $this->assertEquals(['OK'], $tx->discard()->set('foo', 'bar')->execute()); + $this->assertSame($expected, $sent); + } + + public function transactionFailures(): array + { + $queueError = static function (CommandInterface $command) { + if ($command->getId() === 'SET' && count($command->getArguments()) === 1) { + return new Response\Error("ERR wrong number of arguments for 'set' command"); + } + + return null; + }; + + return [ + 'DISCARD rejected after a queue error' => [ + [], + static function (CommandInterface $command) use ($queueError) { + if ($command->getId() === 'DISCARD') { + return new Response\Error('NOPERM simulated DISCARD failure'); + } + + return $queueError($command); + }, + "ERR wrong number of arguments for 'set' command", + ['MULTI', 'SET', 'DISCARD', 'MULTI', 'SET', 'EXEC'], + ], + 'connection lost on DISCARD after a queue error' => [ + [], + static function (CommandInterface $command, array $sent, NodeConnectionInterface $connection) use ($queueError) { + if ($command->getId() === 'DISCARD') { + throw new ConnectionException($connection, 'Connection lost'); + } + + return $queueError($command); + }, + "ERR wrong number of arguments for 'set' command", + ['MULTI', 'SET', 'DISCARD', 'MULTI', 'SET', 'EXEC'], + ], + 'connection lost between WATCH and MULTI' => [ + ['watch' => 'foo'], + static function (CommandInterface $command, array $sent, NodeConnectionInterface $connection) { + if ($sent === ['WATCH', 'MULTI']) { + throw new ConnectionException($connection, 'Connection lost'); + } + + return null; + }, + 'Connection lost', + ['WATCH', 'MULTI', 'WATCH', 'MULTI', 'SET', 'EXEC'], + ], + ]; + } + + /** + * @group disconnected + * @dataProvider protocolErrors + */ + public function testProtocolErrorIsReportedOnTheConnectionHoldingTheTransaction( + string $type, + Response\Status $reply, + string $message + ): void { + $node = $this->getMockedConnection(static function (CommandInterface $command) use ($reply) { + switch ($command->getId()) { + case 'MULTI': + return new Response\Status('OK'); + case 'EXEC': + return []; + default: + return $reply; + } + }); + $node + ->expects($this->once()) + ->method('disconnect'); + + switch ($type) { + case 'replication': + $connection = $this->getMockBuilder(ReplicationInterface::class)->getMock(); + $connection + ->method('getCurrent') + ->willReturn($node); + break; + case 'cluster': + $connection = $this->getMockBuilder(ClusterInterface::class)->getMock(); + $connection + ->method('getClusterStrategy') + ->willReturn(new RedisStrategy()); + break; + default: + $connection = $node; + } + + if ($connection !== $node) { + $connection + ->method('getConnectionByCommand') + ->willReturn($node); + $connection + ->method('getParameters') + ->willReturn(new Parameters(['protocol' => 2])); + $connection + ->method('executeCommand') + ->willReturnCallback(static function (CommandInterface $command) use ($node) { + return $node->executeCommand($command); + }); + } + + try { + (new MultiExec(new Client($connection)))->set('foo', 'bar')->execute(); + $this->fail('Expected a protocol error.'); + } catch (ProtocolException $exception) { + $this->assertSame($message, $exception->getMessage()); + $this->assertSame($node, $exception->getConnection()); + } + } + + public function protocolErrors(): array + { + $notQueued = 'The server did not return a +QUEUED status response.'; + $execCount = 'EXEC returned an unexpected number of response items.'; + + return [ + 'unexpected reply on a node' => ['node', new Response\Status('OK'), $notQueued], + 'unexpected reply on replication' => ['replication', new Response\Status('OK'), $notQueued], + 'EXEC reply count on a node' => ['node', new Response\Status('QUEUED'), $execCount], + 'EXEC reply count on replication' => ['replication', new Response\Status('QUEUED'), $execCount], + 'EXEC reply count on cluster' => ['cluster', new Response\Status('QUEUED'), $execCount], + ]; + } + + /** + * @group disconnected + */ + public function testDiscardInCasModeSucceedsWhileTheServerIsDownAfterALostConnection(): void + { + $sent = []; + $connected = true; + $down = false; + $connection = $this->getMockBuilder(NodeConnectionInterface::class)->getMock(); + $connection + ->method('executeCommand') + ->willReturnCallback(static function (CommandInterface $command) use (&$sent, &$connected, &$down, $connection) { + if ($down) { + throw new ConnectionException($connection, 'Connection refused'); + } + + $connected = true; + $sent[] = $command->getId(); + + if ($command->getId() === 'GET') { + $down = true; + + throw new ConnectionException($connection, 'Connection lost'); + } + + return new Response\Status('OK'); + }); + $connection + ->method('disconnect') + ->willReturnCallback(static function () use (&$connected) { + $connected = false; + }); + $connection + ->method('isConnected') + ->willReturnCallback(static function () use (&$connected) { + return $connected; + }); + $connection + ->method('getParameters') + ->willReturn(new Parameters(['protocol' => 2])); + + $tx = new MultiExec(new Client($connection), ['watch' => 'foo', 'cas' => true]); + + try { + $tx->get('foo'); + $this->fail('Expected the connection to be lost.'); + } catch (ConnectionException $exception) { + $this->assertSame('Connection lost', $exception->getMessage()); + } + + $this->assertSame($tx, $tx->discard()); + $this->assertSame(['WATCH', 'GET'], $sent); + } + + /** + * @group disconnected + */ + public function testRejectedExecOnReplicationClosesTheNodeHoldingTheTransaction(): void + { + $node = $this->getMockedConnection(static function (CommandInterface $command) { + switch ($command->getId()) { + case 'SET': + return new Response\Status('QUEUED'); + case 'EXEC': + return new Response\Error('BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.'); + default: + return new Response\Status('OK'); + } + }); + $node + ->expects($this->once()) + ->method('disconnect'); + + $replication = $this->getMockBuilder(ReplicationInterface::class)->getMock(); + $replication + ->method('getCurrent') + ->willReturn($node); + $replication + ->method('getParameters') + ->willReturn(new Parameters(['protocol' => 2])); + $replication + ->method('executeCommand') + ->willReturnCallback(static function (CommandInterface $command) use ($node) { + return $node->executeCommand($command); + }); + $replication + ->expects($this->never()) + ->method('disconnect'); + + try { + (new MultiExec(new Client($replication)))->set('foo', 'bar')->execute(); + $this->fail('Expected EXEC to be rejected.'); + } catch (Response\ServerException $exception) { + $this->assertStringStartsWith('BUSY ', $exception->getMessage()); + } } /** @@ -1365,7 +1770,7 @@ class MultiExecTest extends PredisTestCase /** * @group connected * @group cluster - * @dataProvider clusterTransactionPersistence + * @dataProvider connectionPersistence * @requiresRedisVersion >= 3.0.0 */ public function testClusterQueueErrorLeavesConnectionUsable(bool $persistent): void @@ -1396,7 +1801,7 @@ class MultiExecTest extends PredisTestCase $redis->disconnect(); } - public function clusterTransactionPersistence(): array + public function connectionPersistence(): array { return [[false], [true]]; } @@ -1404,7 +1809,7 @@ class MultiExecTest extends PredisTestCase /** * @group connected * @group cluster - * @dataProvider clusterTransactionPersistence + * @dataProvider connectionPersistence * @requiresRedisVersion >= 3.0.0 */ public function testClusterFailedDiscardClosesThePhysicalSocket(bool $persistent): void @@ -1552,7 +1957,7 @@ class MultiExecTest extends PredisTestCase /** * @group connected * @group relay-incompatible - * @dataProvider clusterTransactionPersistence + * @dataProvider connectionPersistence */ public function testIntegrationQueueErrorWithFluentInterfaceLeavesConnectionUsable(bool $persistent): void { @@ -1577,6 +1982,30 @@ class MultiExecTest extends PredisTestCase } } + /** + * @group connected + */ + public function testIntegrationDiscardAfterExecLeavesConnectionUsable(): void + { + $client = $this->createClient(); + $client->set('foo', 'bar'); + $tx = $client->transaction(); + + try { + $tx->set('baz', 'qux')->incr('foo')->execute(); + $this->fail('Expected EXEC to report the failed command.'); + } catch (Response\ServerException $exception) { + $this->assertStringStartsWith('ERR value is not an integer', $exception->getMessage()); + } + + $this->assertNull($tx->discard()->execute()); + $this->assertTrue($client->getConnection()->isConnected()); + $this->assertSame('qux', $client->get('baz')); + + $this->assertEquals(['OK'], $tx->set('baz', 'quux')->execute()); + $this->assertSame('quux', $client->get('baz')); + } + /** * @group connected * @group relay-incompatible @@ -1632,11 +2061,11 @@ class MultiExecTest extends PredisTestCase * @group relay-incompatible * @requiresRedisVersion >= 5.0.0 */ - public function testIntegrationLostConnectionAfterWatchIsNotRetried(): void + public function testIntegrationLostConnectionAfterWatchFailsUntilDiscard(): void { $client = $this->createClient(['retry' => new Retry(new NoBackoff(), 3)]); - $this->assertLostConnectionAfterWatchIsNotRetried($client, $this->createClient(null, null, false)); + $this->assertLostConnectionAfterWatchFailsUntilDiscard($client, $this->createClient(null, null, false)); } /** @@ -1659,12 +2088,12 @@ class MultiExecTest extends PredisTestCase * @group relay-incompatible * @requiresRedisVersion >= 7.0.0 */ - public function testSentinelLostConnectionAfterWatchIsNotRetried(): void + public function testSentinelLostConnectionAfterWatchFailsUntilDiscard(): void { $client = $this->createClient(); $admin = new Client($client->getConnection()->getMaster()->getParameters()); - $this->assertLostConnectionAfterWatchIsNotRetried($client, $admin); + $this->assertLostConnectionAfterWatchFailsUntilDiscard($client, $admin); } /** @@ -1692,27 +2121,35 @@ class MultiExecTest extends PredisTestCase /** * Drops the connection of $client between WATCH and MULTI, after another - * client changed the watched key. + * client changed the watched key, and keeps using the transaction after + * catching the error. */ - private function assertLostConnectionAfterWatchIsNotRetried(Client $client, Client $admin): void + private function assertLostConnectionAfterWatchFailsUntilDiscard(Client $client, Client $admin): void { $client->set('foo', 'original'); $id = $client->client('ID'); + $tx = $client->transaction(['cas' => true, 'watch' => 'foo']); + $value = $tx->get('foo'); + $admin->set('foo', 'changed'); + $admin->client('KILL', 'ID', $id); + try { - $client->transaction(['cas' => true, 'watch' => 'foo'], static function (MultiExec $tx) use ($admin, $id) { - $value = $tx->get('foo'); - $admin->set('foo', 'changed'); - $admin->client('KILL', 'ID', $id); - $tx->multi(); - $tx->set('foo', "$value, then the transaction"); - }); - $this->fail('Expected the transaction to fail.'); + $tx->multi(); + $this->fail('Expected the lost connection to reach the caller.'); } catch (CommunicationException $exception) { // NOOP } + try { + $tx->set('foo', "$value, then the transaction")->execute(); + $this->fail('Expected the transaction to fail on its lost connection.'); + } catch (ConnectionException $exception) { + $this->assertSame('The connection holding the transaction was lost.', $exception->getMessage()); + } + $this->assertSame('changed', $admin->get('foo')); + $this->assertSame([1], $tx->discard()->incr('counter')->execute()); } /** @@ -1781,6 +2218,7 @@ class MultiExecTest extends PredisTestCase } $this->assertInstanceOf(Response\ServerException::class, $exception); + $this->assertTrue($client1->getConnection()->isConnected()); $this->assertSame('client2', $client1->get('sentinel')); } diff --git a/tests/Predis/Transaction/Strategy/NodeConnectionStrategyTest.php b/tests/Predis/Transaction/Strategy/NodeConnectionStrategyTest.php index 05d389da..b010d3ec 100644 --- a/tests/Predis/Transaction/Strategy/NodeConnectionStrategyTest.php +++ b/tests/Predis/Transaction/Strategy/NodeConnectionStrategyTest.php @@ -19,7 +19,10 @@ use Predis\Command\Redis\SET; use Predis\Connection\ConnectionException; use Predis\Connection\NodeConnectionInterface; use Predis\Connection\Parameters; +use Predis\Connection\RelayConnection; use Predis\Connection\Resource\Exception\StreamInitException; +use Predis\Response\Error; +use Predis\Response\ServerException; use Predis\Retry\Retry; use Predis\Retry\Strategy\ExponentialBackoff; use Predis\TimeoutException; @@ -133,86 +136,6 @@ class NodeConnectionStrategyTest extends TestCase $this->assertEquals('OK', $strategy->unwatch()); } - /** - * @return void - */ - public function testCommandsAfterMultiAreNotRetried(): void - { - $sent = []; - $this->mockConnection - ->expects($this->exactly(2)) - ->method('executeCommand') - ->willReturnCallback(function (CommandInterface $command) use (&$sent) { - $sent[] = $command->getId(); - - if ($command->getId() === 'MULTI') { - return 'OK'; - } - - throw new ConnectionException($this->mockConnection, 'Connection lost'); - }); - - $this->mockConnection - ->expects($this->any()) - ->method('getParameters') - ->willReturn(new Parameters(['retry' => new Retry(new ExponentialBackoff(1, 10), 3)])); - - $this->mockConnection - ->expects($this->once()) - ->method('disconnect'); - - $strategy = new NodeConnectionStrategy($this->mockConnection, new MultiExecState()); - $this->assertTrue($strategy->initializeTransaction()); - - try { - $strategy->executeCommand(new SET()); - $this->fail('Expected the connection error to reach the caller.'); - } catch (ConnectionException $exception) { - $this->assertSame(['MULTI', 'SET'], $sent); - } - } - - /** - * @return void - */ - public function testCommandsAfterWatchAreNotRetried(): void - { - $sent = []; - $this->mockConnection - ->expects($this->exactly(2)) - ->method('executeCommand') - ->willReturnCallback(function (CommandInterface $command) use (&$sent) { - $sent[] = $command->getId(); - - if ($command->getId() === 'WATCH') { - return 'OK'; - } - - throw new TimeoutException($this->mockConnection); - }); - - $this->mockConnection - ->expects($this->any()) - ->method('getParameters') - ->willReturn(new Parameters(['retry' => new Retry(new ExponentialBackoff(1, 10), 3)])); - - $this->mockConnection - ->expects($this->once()) - ->method('disconnect'); - - $state = new MultiExecState(); - $state->flag(MultiExecState::CAS); - $strategy = new NodeConnectionStrategy($this->mockConnection, $state); - $strategy->watch(['foo']); - - try { - $strategy->executeCommand(new GET()); - $this->fail('Expected the connection error to reach the caller.'); - } catch (TimeoutException $exception) { - $this->assertSame(['WATCH', 'GET'], $sent); - } - } - /** * @return void */ @@ -242,6 +165,35 @@ class NodeConnectionStrategyTest extends TestCase $this->assertTrue($strategy->initializeTransaction()); } + /** + * @return void + */ + public function testMultiIsRetriedAfterAFailedConnect(): void + { + $failed = false; + $this->mockConnection + ->expects($this->exactly(2)) + ->method('executeCommand') + ->willReturnCallback(function () use (&$failed) { + if (!$failed) { + $failed = true; + + throw new StreamInitException('Connection refused'); + } + + return 'OK'; + }); + + $this->mockConnection + ->expects($this->any()) + ->method('getParameters') + ->willReturn(new Parameters(['retry' => new Retry(new ExponentialBackoff(1, 10), 3)])); + + $strategy = new NodeConnectionStrategy($this->mockConnection, new MultiExecState()); + + $this->assertTrue($strategy->initializeTransaction()); + } + /** * @dataProvider transactionEnds * @return void @@ -281,13 +233,6 @@ class NodeConnectionStrategyTest extends TestCase case 'UNWATCH': $strategy->unwatch(); break; - case 'connection error': - try { - $strategy->executeCommand(new SET()); - } catch (ConnectionException $exception) { - // NOOP - } - break; } $failMulti = true; @@ -300,14 +245,13 @@ class NodeConnectionStrategyTest extends TestCase return [ 'DISCARD' => ['DISCARD'], 'UNWATCH' => ['UNWATCH'], - 'connection error' => ['connection error'], ]; } /** * @return void */ - public function testCommandsAfterWatchFailWhenTheConnectionIsNoLongerOpen(): void + public function testCommandsAfterWatchFailUntilUnwatchOnceTheConnectionIsLost(): void { $sent = []; $this->mockConnection @@ -316,60 +260,20 @@ class NodeConnectionStrategyTest extends TestCase ->willReturnCallback(function (CommandInterface $command) use (&$sent) { $sent[] = $command->getId(); - return 'OK'; - }); - - $this->mockConnection - ->expects($this->any()) - ->method('getParameters') - ->willReturn(new Parameters(['retry' => new Retry(new ExponentialBackoff(1, 10), 3)])); - - $state = new MultiExecState(); - $state->flag(MultiExecState::CAS); - $strategy = new NodeConnectionStrategy($this->mockConnection, $state); - $strategy->watch(['foo']); - - // e.g. after MultiExec::onProtocolError() disconnected it - $this->connected = false; - - try { - $strategy->executeCommand(new GET()); - $this->fail('Expected the lost connection to reach the caller.'); - } catch (ConnectionException $exception) { - $this->assertSame(['WATCH'], $sent); - } - - // The transaction no longer holds the connection, so commands go through retries again. - $this->connected = true; - $this->assertSame('OK', $strategy->executeCommand(new GET())->getResponse()); - $this->assertSame('OK', $strategy->executeCommand(new GET())->getResponse()); - $this->assertSame(['WATCH', 'GET', 'GET'], $sent); - } - - /** - * @return void - */ - public function testAFailedReconnectReleasesTheConnection(): void - { - $calls = 0; - $this->mockConnection - ->expects($this->exactly(4)) - ->method('executeCommand') - ->willReturnCallback(function (CommandInterface $command) use (&$calls) { - ++$calls; - - if ($calls === 2) { - throw new StreamInitException('Connection refused'); - } - - // Only a released connection retries this one. - if ($calls === 3) { + if ($sent === ['WATCH', 'GET']) { throw new TimeoutException($this->mockConnection); } return 'OK'; }); + $this->mockConnection + ->expects($this->once()) + ->method('disconnect') + ->willReturnCallback(function () { + $this->connected = false; + }); + $this->mockConnection ->expects($this->any()) ->method('getParameters') @@ -382,10 +286,249 @@ class NodeConnectionStrategyTest extends TestCase try { $strategy->executeCommand(new GET()); - $this->fail('Expected the stream error to reach the caller.'); - } catch (StreamInitException $exception) { + $this->fail('Expected the connection error to reach the caller.'); + } catch (TimeoutException $exception) { + // NOOP } + try { + $strategy->executeCommand(new GET()); + $this->fail('Expected the lost connection to reach the caller.'); + } catch (ConnectionException $exception) { + $this->assertSame('The connection holding the transaction was lost.', $exception->getMessage()); + } + + $this->assertSame(['WATCH', 'GET'], $sent); + + $this->assertEquals('OK', $strategy->unwatch()); + $this->assertSame('OK', $strategy->executeCommand(new GET())->getResponse()); + $this->assertSame(['WATCH', 'GET', 'GET'], $sent); + } + + /** + * @return void + */ + public function testDiscardEndsATransactionWhoseConnectionWasLost(): void + { + $sent = []; + $this->mockConnection + ->expects($this->exactly(3)) + ->method('executeCommand') + ->willReturnCallback(function (CommandInterface $command) use (&$sent) { + $sent[] = $command->getId(); + + if ($command->getId() === 'SET') { + throw new ConnectionException($this->mockConnection, 'Connection lost'); + } + + return 'OK'; + }); + + $this->mockConnection + ->expects($this->once()) + ->method('disconnect') + ->willReturnCallback(function () { + $this->connected = false; + }); + + $this->mockConnection + ->expects($this->any()) + ->method('getParameters') + ->willReturn(new Parameters(['retry' => new Retry(new ExponentialBackoff(1, 10), 3)])); + + $strategy = new NodeConnectionStrategy($this->mockConnection, new MultiExecState()); + $strategy->initializeTransaction(); + + try { + $strategy->executeCommand(new SET()); + $this->fail('Expected the connection error to reach the caller.'); + } catch (ConnectionException $exception) { + // NOOP + } + + try { + $strategy->executeTransaction(); + $this->fail('Expected EXEC to fail on the lost connection.'); + } catch (ConnectionException $exception) { + $this->assertSame('The connection holding the transaction was lost.', $exception->getMessage()); + } + + $this->assertEquals('OK', $strategy->discard()); + $this->assertSame(['MULTI', 'SET'], $sent); + + $this->assertTrue($strategy->initializeTransaction()); + $this->assertSame(['MULTI', 'SET', 'MULTI'], $sent); + } + + /** + * @return void + */ + public function testServerExceptionFromNodeConnectionIsRethrown(): void + { + $this->mockConnection + ->method('executeCommand') + ->willReturnCallback(static function (CommandInterface $command) { + if ($command->getId() === 'EXEC') { + throw new ServerException('ERR RELAY_ERR_REDIS simulated'); + } + + return 'OK'; + }); + + $this->mockConnection + ->expects($this->any()) + ->method('getParameters') + ->willReturn(new Parameters()); + + $strategy = new NodeConnectionStrategy($this->mockConnection, new MultiExecState()); + $strategy->initializeTransaction(); + + $this->expectException(ServerException::class); + $this->expectExceptionMessage('ERR RELAY_ERR_REDIS simulated'); + + $strategy->executeTransaction(); + } + + /** + * @dataProvider rejectedExecReplies + * @return void + */ + public function testRejectedExecClosesTheConnectionUnlessTheTransactionWasDiscarded(string $error, bool $closed): void + { + $this->mockConnection + ->method('executeCommand') + ->willReturnCallback(static function (CommandInterface $command) use ($error) { + return $command->getId() === 'EXEC' ? new Error($error) : 'OK'; + }); + + $this->mockConnection + ->expects($closed ? $this->once() : $this->never()) + ->method('disconnect') + ->willReturnCallback(function () { + $this->connected = false; + }); + + $this->mockConnection + ->expects($this->any()) + ->method('getParameters') + ->willReturn(new Parameters()); + + $strategy = new NodeConnectionStrategy($this->mockConnection, new MultiExecState()); + $strategy->initializeTransaction(); + + try { + $strategy->executeTransaction(); + $this->fail('Expected EXEC to fail.'); + } catch (ServerException $exception) { + $this->assertSame($error, $exception->getMessage()); + } + + $this->assertTrue($strategy->initializeTransaction()); + } + + public function rejectedExecReplies(): array + { + return [ + 'transaction discarded' => [ + 'EXECABORT Transaction discarded because of previous errors.', + false, + ], + 'EXEC rejected while MULTI stays open' => [ + 'BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.', + true, + ], + ]; + } + + /** + * @requires extension relay + * @return void + */ + public function testExecAbortedByWatchKeepsTheRelayConnection(): void + { + $relay = $this->getMockBuilder(RelayConnection::class)->disableOriginalConstructor()->getMock(); + $relay + ->method('executeCommand') + ->willReturnCallback(static function (CommandInterface $command) { + return $command->getId() === 'EXEC' + ? new Error('Transaction failed (RELAY_ERR_REDIS; commands.c:16733)') + : 'OK'; + }); + $relay + ->method('isConnected') + ->willReturn(true); + $relay + ->expects($this->never()) + ->method('disconnect'); + $relay + ->method('getParameters') + ->willReturn(new Parameters()); + + $state = new MultiExecState(); + $state->flag(MultiExecState::CAS); + $strategy = new NodeConnectionStrategy($relay, $state); + $strategy->watch(['foo']); + $strategy->multi(); + + try { + $strategy->executeTransaction(); + $this->fail('Expected Relay to report the aborted transaction as an error.'); + } catch (ServerException $exception) { + $this->assertStringStartsWith('Transaction failed (RELAY_ERR_REDIS', $exception->getMessage()); + } + + $this->assertTrue($strategy->initializeTransaction()); + } + + /** + * @requires extension relay + * @dataProvider relayServerErrors + * @return void + */ + public function testServerExceptionFromRelay(string $failing, string $message, bool $aborted): void + { + $relay = $this->getMockBuilder(RelayConnection::class)->disableOriginalConstructor()->getMock(); + $relay + ->method('executeCommand') + ->willReturnCallback(static function (CommandInterface $command) use ($failing, $message) { + if ($command->getId() === $failing) { + throw new ServerException($message); + } + + return 'OK'; + }); + $relay + ->method('isConnected') + ->willReturn(true); + $relay + ->method('getParameters') + ->willReturn(new Parameters()); + + $state = new MultiExecState(); + $state->flag(MultiExecState::CAS); + $strategy = new NodeConnectionStrategy($relay, $state); + $strategy->watch(['foo']); + $strategy->multi(); + + if ($aborted) { + $this->assertNull($strategy->executeTransaction()); + + return; + } + + $this->expectException(ServerException::class); + $this->expectExceptionMessage($message); + + $failing === 'EXEC' ? $strategy->executeTransaction() : $strategy->executeCommand(new GET()); + } + + public function relayServerErrors(): array + { + return [ + 'aborted EXEC' => ['EXEC', 'ERR RELAY_ERR_REDIS simulated', true], + 'other EXEC error' => ['EXEC', 'ERR simulated', false], + 'error on another command' => ['GET', 'ERR RELAY_ERR_REDIS simulated', false], + ]; } }