mirror of
https://github.com/predis/predis.git
synced 2026-11-26 21:53:10 +00:00
8e34223fb9
* Do not follow -ASK on the first command of a cluster transaction A cluster transaction is held on the node the slots map associates with its slot, but its first command went through the cluster like any other one. While a slot was being migrated, an -ASK reply to WATCH (or to the first command in CAS mode) was followed to the node importing the slot, and only then was the connection pinned from the slots map, which -ASK does not update. WATCH was left on the importing node while MULTI, the queued commands and EXEC ran on the source node with nothing watched, so the transaction committed even though the watched key had changed. When the transaction failed after that WATCH, the cleanup was sent to the source node and the WATCH on the importing node was never released, so its dirty flag aborted a later, unrelated transaction sent over the pooled connection. The first command is now sent through RedisCluster::executeCommandOnSlotOwner(), which retries and follows -MOVED and -READONLY like executeCommand() but returns -ASK replies. The transaction then fails with a ServerException carrying the -ASK reply, as later CAS commands already did, without touching the importing node. Retrying once the migration has finished reaches the new owner. An -ASK reply to a queued command still aborts the transaction, as before. The README no longer claims that the first command is redirected like any other command, and describes how an -ASK reply fails a transaction. * Add the cluster ASK fix to the changelog
3370 lines
113 KiB
PHP
3370 lines
113 KiB
PHP
<?php
|
|
|
|
/*
|
|
* This file is part of the Predis package.
|
|
*
|
|
* (c) 2009-2020 Daniele Alessandri
|
|
* (c) 2021-2026 Till Krüss
|
|
*
|
|
* For the full copyright and license information, please view the LICENSE
|
|
* file that was distributed with this source code.
|
|
*/
|
|
|
|
namespace Predis\Transaction;
|
|
|
|
use Exception;
|
|
use InvalidArgumentException;
|
|
use PHPUnit\Framework\MockObject\MockObject;
|
|
use Predis\Client;
|
|
use Predis\ClientException;
|
|
use Predis\ClientInterface;
|
|
use Predis\Cluster\RedisStrategy;
|
|
use Predis\Command\CommandInterface;
|
|
use Predis\Command\RawCommand;
|
|
use Predis\CommunicationException;
|
|
use Predis\Connection\Cluster\ClusterInterface;
|
|
use Predis\Connection\Cluster\RedisCluster;
|
|
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;
|
|
use Predis\Retry\Strategy\NoBackoff;
|
|
use Predis\TimeoutException;
|
|
use Predis\Transaction\Exception\TransactionException;
|
|
use PredisTestCase;
|
|
use RuntimeException;
|
|
use Throwable;
|
|
use TypeError;
|
|
|
|
/**
|
|
* @group realm-transaction
|
|
*/
|
|
class MultiExecTest extends PredisTestCase
|
|
{
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testThrowsExceptionOnUnsupportedMultiExecInCommandFactory(): void
|
|
{
|
|
$this->expectException('Predis\NotSupportedException');
|
|
$this->expectExceptionMessage('MULTI, EXEC and DISCARD are not supported by the current command factory.');
|
|
|
|
$commands = $this->getMockBuilder('Predis\Command\FactoryInterface')->getMock();
|
|
$commands
|
|
->expects($this->once())
|
|
->method('supports')
|
|
->with('MULTI', 'EXEC', 'DISCARD')
|
|
->willReturn(false);
|
|
|
|
$connection = $this->getMockBuilder('Predis\Connection\NodeConnectionInterface')->getMock();
|
|
$client = new Client($connection, ['commands' => $commands]);
|
|
|
|
new MultiExec($client);
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testThrowsExceptionOnUnsupportedWatchInCommandFactory(): void
|
|
{
|
|
$this->expectException('Predis\NotSupportedException');
|
|
$this->expectExceptionMessage('WATCH is not supported by the current command factory.');
|
|
|
|
$commands = $this->getMockBuilder('Predis\Command\FactoryInterface')->getMock();
|
|
$commands
|
|
->expects($this->exactly(2))
|
|
->method('supports')
|
|
->withConsecutive(
|
|
['MULTI', 'EXEC', 'DISCARD'],
|
|
['WATCH']
|
|
)
|
|
->willReturnOnConsecutiveCalls(
|
|
true,
|
|
false
|
|
);
|
|
|
|
$connection = $this->getMockBuilder('Predis\Connection\NodeConnectionInterface')->getMock();
|
|
$client = new Client($connection, ['commands' => $commands]);
|
|
|
|
$tx = new MultiExec($client, ['options' => 'cas']);
|
|
$tx->watch('foo');
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testThrowsExceptionOnUnsupportedUnwatchInCommandFactory(): void
|
|
{
|
|
$this->expectException('Predis\NotSupportedException');
|
|
$this->expectExceptionMessage('UNWATCH is not supported by the current command factory.');
|
|
|
|
$commands = $this->getMockBuilder('Predis\Command\FactoryInterface')->getMock();
|
|
|
|
$commands = $this->getMockBuilder('Predis\Command\FactoryInterface')->getMock();
|
|
$commands
|
|
->expects($this->exactly(2))
|
|
->method('supports')
|
|
->withConsecutive(
|
|
['MULTI', 'EXEC', 'DISCARD'],
|
|
['UNWATCH']
|
|
)
|
|
->willReturnOnConsecutiveCalls(
|
|
true,
|
|
false
|
|
);
|
|
|
|
$connection = $this->getMockBuilder('Predis\Connection\NodeConnectionInterface')->getMock();
|
|
$client = new Client($connection, ['commands' => $commands]);
|
|
|
|
$tx = new MultiExec($client, ['options' => 'cas']);
|
|
|
|
$tx->unwatch('foo');
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testExecutionWithFluentInterface(): void
|
|
{
|
|
$commands = [];
|
|
$expected = ['one', 'two', 'three'];
|
|
|
|
$callback = $this->getExecuteCallback($expected, $commands);
|
|
$tx = $this->getMockedTransaction($callback);
|
|
|
|
$this->assertSame($expected, $tx->echo('one')->echo('two')->echo('three')->execute());
|
|
$this->assertSame(['MULTI', 'ECHO', 'ECHO', 'ECHO', 'EXEC'], self::commandsToIDs($commands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testExecutionWithCallable(): void
|
|
{
|
|
$commands = [];
|
|
$expected = ['one', 'two', 'three'];
|
|
|
|
$callback = $this->getExecuteCallback($expected, $commands);
|
|
$tx = $this->getMockedTransaction($callback);
|
|
|
|
$responses = $tx->execute(static function ($tx) {
|
|
$tx->echo('one');
|
|
$tx->echo('two');
|
|
$tx->echo('three');
|
|
});
|
|
|
|
$this->assertSame($expected, $responses);
|
|
$this->assertSame(['MULTI', 'ECHO', 'ECHO', 'ECHO', 'EXEC'], self::commandsToIDs($commands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testCannotMixExecutionWithFluentInterfaceAndCallable(): void
|
|
{
|
|
$commands = [];
|
|
|
|
$callback = $this->getExecuteCallback(null, $commands);
|
|
$tx = $this->getMockedTransaction($callback);
|
|
|
|
$exception = null;
|
|
|
|
try {
|
|
$tx->echo('foo')->execute(static function ($tx) {
|
|
$tx->echo('bar');
|
|
});
|
|
} catch (Exception $ex) {
|
|
$exception = $ex;
|
|
}
|
|
|
|
$this->assertInstanceOf('Predis\ClientException', $exception);
|
|
$this->assertSame(['MULTI', 'ECHO', 'DISCARD'], self::commandsToIDs($commands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testEmptyTransactionDoesNotSendMultiExecCommands(): void
|
|
{
|
|
$commands = [];
|
|
|
|
$callback = $this->getExecuteCallback(null, $commands);
|
|
$tx = $this->getMockedTransaction($callback);
|
|
|
|
$responses = $tx->execute(static function ($tx) {
|
|
// NOOP
|
|
});
|
|
|
|
$this->assertNull($responses);
|
|
$this->assertSame([], self::commandsToIDs($commands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testThrowsExceptionOnExecInsideTransactionBlock(): void
|
|
{
|
|
$this->expectException('Predis\ClientException');
|
|
$this->expectExceptionMessage('Cannot invoke "execute" or "exec" inside an active transaction context');
|
|
|
|
$commands = [];
|
|
|
|
$callback = $this->getExecuteCallback(null, $commands);
|
|
$tx = $this->getMockedTransaction($callback);
|
|
|
|
$responses = $tx->execute(static function ($tx) {
|
|
$tx->exec();
|
|
});
|
|
|
|
$this->assertNull($responses);
|
|
$this->assertSame([], self::commandsToIDs($commands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testEmptyTransactionIgnoresDiscard(): void
|
|
{
|
|
$commands = [];
|
|
|
|
$callback = $this->getExecuteCallback(null, $commands);
|
|
$tx = $this->getMockedTransaction($callback);
|
|
|
|
$responses = $tx->execute(static function ($tx) {
|
|
$tx->discard();
|
|
});
|
|
|
|
$this->assertNull($responses);
|
|
$this->assertSame([], self::commandsToIDs($commands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testTransactionWithCommandsSendsDiscard(): void
|
|
{
|
|
$commands = [];
|
|
|
|
$callback = $this->getExecuteCallback(null, $commands);
|
|
$tx = $this->getMockedTransaction($callback);
|
|
|
|
$responses = $tx->execute(static function ($tx) {
|
|
$tx->set('foo', 'bar');
|
|
$tx->get('foo');
|
|
$tx->discard();
|
|
});
|
|
|
|
$this->assertNull($responses);
|
|
$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
|
|
*/
|
|
public function testSendMultiOnCommandsFollowingDiscard(): void
|
|
{
|
|
$commands = [];
|
|
$expected = ['after DISCARD'];
|
|
|
|
$callback = $this->getExecuteCallback($expected, $commands);
|
|
$tx = $this->getMockedTransaction($callback);
|
|
|
|
$responses = $tx->execute(static function ($tx) {
|
|
$tx->echo('before DISCARD');
|
|
$tx->discard();
|
|
$tx->echo('after DISCARD');
|
|
});
|
|
|
|
$this->assertSame($responses, $expected);
|
|
$this->assertSame(['MULTI', 'ECHO', 'DISCARD', 'MULTI', 'ECHO', 'EXEC'], self::commandsToIDs($commands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testThrowsExceptionOnWatchInsideMulti(): void
|
|
{
|
|
$this->expectException('Predis\ClientException');
|
|
|
|
$callback = $this->getExecuteCallback();
|
|
$tx = $this->getMockedTransaction($callback);
|
|
|
|
$tx->echo('foobar')->watch('foo')->execute();
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testUnwatchInsideMulti(): void
|
|
{
|
|
$commands = [];
|
|
$expected = ['foobar', true];
|
|
|
|
$callback = $this->getExecuteCallback($expected, $commands);
|
|
$tx = $this->getMockedTransaction($callback);
|
|
|
|
$responses = $tx->echo('foobar')->unwatch('foo')->execute();
|
|
|
|
$this->assertSame($responses, $expected);
|
|
$this->assertSame(['MULTI', 'ECHO', 'UNWATCH', 'EXEC'], self::commandsToIDs($commands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testUnwatchReleasesTheConnectionOfTheTransaction(): void
|
|
{
|
|
$sent = [];
|
|
$connection = $this->getMockBuilder(NodeConnectionInterface::class)->getMock();
|
|
$connection
|
|
->method('executeCommand')
|
|
->willReturnCallback(static function (CommandInterface $command) use (&$sent, $connection) {
|
|
$sent[] = $command->getId();
|
|
|
|
// The first GET after UNWATCH loses the connection; a retry must follow.
|
|
if ($sent === ['WATCH', 'GET', 'UNWATCH', 'GET']) {
|
|
throw new ConnectionException($connection, 'Connection lost');
|
|
}
|
|
|
|
return $command->getId() === 'GET' ? 'bar' : new Response\Status('OK');
|
|
});
|
|
$connection
|
|
->method('getParameters')
|
|
->willReturn(new Parameters(['protocol' => 2, 'retry' => new Retry(new ExponentialBackoff(1, 10), 3)]));
|
|
$connection
|
|
->method('isConnected')
|
|
->willReturn(true);
|
|
|
|
$tx = new MultiExec(new Client($connection), ['cas' => true]);
|
|
$tx->watch('foo');
|
|
// A read before UNWATCH initializes the transaction in CAS mode, without sending MULTI.
|
|
$this->assertSame('bar', $tx->get('foo'));
|
|
$tx->unwatch();
|
|
|
|
$this->assertSame('bar', $tx->get('foo'));
|
|
$this->assertSame(['WATCH', 'GET', 'UNWATCH', 'GET', 'GET'], $sent);
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testAutomaticWatchInOptions(): void
|
|
{
|
|
$txCommands = $casCommands = [];
|
|
$expected = ['bar', 'piyo'];
|
|
$options = ['watch' => ['foo', 'hoge']];
|
|
|
|
$callback = $this->getExecuteCallback($expected, $txCommands, $casCommands);
|
|
$tx = $this->getMockedTransaction($callback, $options);
|
|
|
|
$responses = $tx->execute(static function ($tx) {
|
|
$tx->get('foo');
|
|
$tx->get('hoge');
|
|
});
|
|
|
|
$this->assertSame($responses, $expected);
|
|
$this->assertSame(['WATCH'], self::commandsToIDs($casCommands));
|
|
$this->assertSame(['foo', 'hoge'], $casCommands[0]->getArguments());
|
|
$this->assertSame(['MULTI', 'GET', 'GET', 'EXEC'], self::commandsToIDs($txCommands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testCheckAndSetWithFluentInterface(): void
|
|
{
|
|
$txCommands = $casCommands = [];
|
|
$expected = ['bar', 'piyo'];
|
|
$options = ['cas' => true, 'watch' => ['foo', 'hoge']];
|
|
|
|
$callback = $this->getExecuteCallback($expected, $txCommands, $casCommands);
|
|
$tx = $this->getMockedTransaction($callback, $options);
|
|
|
|
$tx->watch('foobar');
|
|
$this->assertSame('DUMMY_RESPONSE', $tx->get('foo'));
|
|
$this->assertSame('DUMMY_RESPONSE', $tx->get('hoge'));
|
|
|
|
$responses = $tx
|
|
->multi()
|
|
->get('foo')
|
|
->get('hoge')
|
|
->execute();
|
|
|
|
$this->assertSame($responses, $expected);
|
|
$this->assertSame(['WATCH', 'WATCH', 'GET', 'GET'], self::commandsToIDs($casCommands));
|
|
$this->assertSame(['MULTI', 'GET', 'GET', 'EXEC'], self::commandsToIDs($txCommands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testCheckAndSetWithBlock(): void
|
|
{
|
|
$txCommands = $casCommands = [];
|
|
$expected = ['bar', 'piyo'];
|
|
$options = ['cas' => true, 'watch' => ['foo', 'hoge']];
|
|
|
|
$callback = $this->getExecuteCallback($expected, $txCommands, $casCommands);
|
|
$tx = $this->getMockedTransaction($callback, $options);
|
|
|
|
$test = $this;
|
|
$responses = $tx->execute(static function ($tx) use ($test) {
|
|
$tx->watch('foobar');
|
|
|
|
$response1 = $tx->get('foo');
|
|
$response2 = $tx->get('hoge');
|
|
|
|
$test->assertSame('DUMMY_RESPONSE', $response1);
|
|
$test->assertSame('DUMMY_RESPONSE', $response2);
|
|
|
|
$tx->multi();
|
|
|
|
$tx->get('foo');
|
|
$tx->get('hoge');
|
|
});
|
|
|
|
$this->assertSame($responses, $expected);
|
|
$this->assertSame(['WATCH', 'WATCH', 'GET', 'GET'], self::commandsToIDs($casCommands));
|
|
$this->assertSame(['MULTI', 'GET', 'GET', 'EXEC'], self::commandsToIDs($txCommands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testEmptyExplicitTransactionIsDiscarded(): void
|
|
{
|
|
$commands = [];
|
|
$tx = $this->getMockedTransaction($this->getExecuteCallback([], $commands));
|
|
|
|
$tx->execute(static function ($tx) {
|
|
$tx->multi();
|
|
});
|
|
|
|
$this->assertSame(['MULTI', 'DISCARD'], self::commandsToIDs($commands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testCallbackPhpErrorDiscardsTransaction(): void
|
|
{
|
|
$commands = [];
|
|
$tx = $this->getMockedTransaction($this->getExecuteCallback([], $commands));
|
|
|
|
try {
|
|
$tx->execute(static function ($tx) {
|
|
$tx->set('foo', 'bar');
|
|
|
|
throw new TypeError('Invalid callback argument');
|
|
});
|
|
$this->fail('Expected the callback error to be rethrown.');
|
|
} catch (TypeError $exception) {
|
|
$this->assertSame('Invalid callback argument', $exception->getMessage());
|
|
}
|
|
|
|
$this->assertSame(['MULTI', 'SET', 'DISCARD'], self::commandsToIDs($commands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testCheckAndSetWithEmptyBlock(): void
|
|
{
|
|
$txCommands = $casCommands = [];
|
|
$options = ['cas' => true];
|
|
|
|
$callback = $this->getExecuteCallback([], $txCommands, $casCommands);
|
|
$tx = $this->getMockedTransaction($callback, $options);
|
|
|
|
$tx->execute(static function ($tx) {
|
|
$tx->multi();
|
|
});
|
|
|
|
$this->assertSame([], self::commandsToIDs($casCommands));
|
|
$this->assertSame(['MULTI', 'DISCARD'], self::commandsToIDs($txCommands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testCheckAndSetWithoutExec(): void
|
|
{
|
|
$txCommands = $casCommands = [];
|
|
$options = ['cas' => true];
|
|
|
|
$callback = $this->getExecuteCallback([], $txCommands, $casCommands);
|
|
$tx = $this->getMockedTransaction($callback, $options);
|
|
|
|
$tx->execute(static function ($tx) {
|
|
$tx->get('foo');
|
|
$tx->set('hoge', 'piyo');
|
|
});
|
|
|
|
$this->assertSame(['GET', 'SET'], self::commandsToIDs($casCommands));
|
|
$this->assertSame([], self::commandsToIDs($txCommands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testThrowsExceptionOnAutomaticRetriesWithFluentInterface(): void
|
|
{
|
|
$this->expectException('Predis\ClientException');
|
|
$this->expectExceptionMessage('Automatic retries are supported only when a callable block is provided');
|
|
|
|
$options = ['retry' => 1];
|
|
|
|
$callback = $this->getExecuteCallback();
|
|
$tx = $this->getMockedTransaction($callback, $options);
|
|
|
|
$tx->echo('message')->execute();
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testAutomaticRetryOnServerSideTransactionAbort(): void
|
|
{
|
|
$casCommands = $txCommands = [];
|
|
$expected = ['bar'];
|
|
$options = ['watch' => ['foo', 'bar'], 'retry' => ($attempts = 2) + 1];
|
|
|
|
$signal = $this->getMockBuilder('stdClass')
|
|
->addMethods(['__invoke'])
|
|
->getMock();
|
|
$signal
|
|
->expects($this->exactly($attempts))
|
|
->method('__invoke');
|
|
|
|
$callback = $this->getExecuteCallback($expected, $txCommands, $casCommands);
|
|
$tx = $this->getMockedTransaction($callback, $options);
|
|
|
|
$responses = $tx->execute(static function (MultiExec $tx) use ($signal, &$attempts) {
|
|
$tx->get('foo');
|
|
|
|
if ($attempts > 0) {
|
|
$attempts--;
|
|
$signal();
|
|
|
|
$tx->echo('!!ABORT!!');
|
|
}
|
|
});
|
|
|
|
$this->assertSame($responses, $expected);
|
|
$this->assertSame(['WATCH'], self::commandsToIDs($casCommands));
|
|
$this->assertSame(['foo', 'bar'], $casCommands[0]->getArguments());
|
|
$this->assertSame(['MULTI', 'GET', 'EXEC'], self::commandsToIDs($txCommands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testThrowsExceptionOnServerSideTransactionAbort(): void
|
|
{
|
|
$this->expectException('Predis\Transaction\AbortedMultiExecException');
|
|
|
|
$callback = $this->getExecuteCallback();
|
|
$tx = $this->getMockedTransaction($callback);
|
|
|
|
$tx->execute(static function ($tx) {
|
|
$tx->echo('!!ABORT!!');
|
|
});
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testHandlesStandardExceptionsInBlock(): void
|
|
{
|
|
$commands = [];
|
|
$expected = ['foobar', true];
|
|
|
|
$callback = $this->getExecuteCallback($expected, $commands);
|
|
$tx = $this->getMockedTransaction($callback);
|
|
|
|
$responses = null;
|
|
|
|
try {
|
|
$responses = $tx->execute(static function (MultiExec $tx) {
|
|
$tx->set('foo', 'bar');
|
|
$tx->get('foo');
|
|
|
|
throw new RuntimeException('TEST');
|
|
});
|
|
} catch (Exception $ex) {
|
|
// NOOP
|
|
}
|
|
|
|
$this->assertNull($responses);
|
|
$this->assertIsArray($expected);
|
|
$this->assertSame(['MULTI', 'SET', 'GET', 'DISCARD'], self::commandsToIDs($commands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testHandlesServerExceptionsInBlock(): void
|
|
{
|
|
$commands = [];
|
|
$expected = ['foobar', true];
|
|
|
|
$callback = $this->getExecuteCallback($expected, $commands);
|
|
$tx = $this->getMockedTransaction($callback);
|
|
|
|
$responses = null;
|
|
|
|
try {
|
|
$responses = $tx->execute(static function (MultiExec $tx) {
|
|
$tx->set('foo', 'bar');
|
|
$tx->echo('ERR Invalid operation');
|
|
$tx->get('foo');
|
|
});
|
|
} catch (Response\ServerException $ex) {
|
|
$tx->discard();
|
|
}
|
|
|
|
$this->assertNull($responses);
|
|
$this->assertSame(['MULTI', 'SET', 'ECHO', 'DISCARD'], self::commandsToIDs($commands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testProperlyDiscardsTransactionAfterServerExceptionInBlock(): void
|
|
{
|
|
$connection = $this->getMockedConnection(static function (CommandInterface $command) {
|
|
switch ($command->getId()) {
|
|
case 'MULTI':
|
|
return true;
|
|
|
|
case 'ECHO':
|
|
return new Response\Error('ERR simulated failure on ECHO');
|
|
|
|
case 'EXEC':
|
|
return new Response\Error('EXECABORT Transaction discarded because of previous errors.');
|
|
|
|
default:
|
|
return new Response\Status('QUEUED');
|
|
}
|
|
});
|
|
|
|
$client = new Client($connection);
|
|
|
|
// First attempt
|
|
$tx = new MultiExec($client);
|
|
|
|
try {
|
|
$tx->multi()->set('foo', 'bar')->echo('simulated failure')->exec();
|
|
} catch (Exception $exception) {
|
|
$this->assertInstanceOf('Predis\Transaction\AbortedMultiExecException', $exception);
|
|
$this->assertSame('ERR simulated failure on ECHO', $exception->getMessage());
|
|
}
|
|
|
|
// Second attempt
|
|
$tx = new MultiExec($client);
|
|
|
|
try {
|
|
$tx->multi()->set('foo', 'bar')->echo('simulated failure')->exec();
|
|
} catch (Exception $exception) {
|
|
$this->assertInstanceOf('Predis\Transaction\AbortedMultiExecException', $exception);
|
|
$this->assertSame('ERR simulated failure on ECHO', $exception->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testQueueErrorWithFluentInterfaceAbortsTransactionUntilDiscard(): void
|
|
{
|
|
$sent = [];
|
|
$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();
|
|
$this->fail('Expected the transaction to abort.');
|
|
} catch (AbortedMultiExecException $exception) {
|
|
$this->assertSame("ERR wrong number of arguments for 'set' command", $exception->getMessage());
|
|
}
|
|
|
|
$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 {
|
|
$reuse($tx);
|
|
$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 testClusterSlotErrorWithFluentInterfaceAbortsTransaction(): void
|
|
{
|
|
$commands = [];
|
|
$tx = $this->getMockedClusterTransaction($this->getExecuteCallback(['OK'], $commands));
|
|
$tx->set('{a}foo', 'bar');
|
|
|
|
try {
|
|
$tx->set('{b}foo', 'bar');
|
|
$this->fail('Expected the transaction to abort.');
|
|
} catch (AbortedMultiExecException $exception) {
|
|
$this->assertStringContainsString('same hash slot', $exception->getMessage());
|
|
}
|
|
|
|
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 testClusterSlotErrorCaughtInsideBlockAbortsExec(): void
|
|
{
|
|
$commands = [];
|
|
$tx = $this->getMockedClusterTransaction($this->getExecuteCallback(['OK'], $commands));
|
|
|
|
try {
|
|
$tx->execute(static function (MultiExec $tx) {
|
|
$tx->set('{a}foo', 'bar');
|
|
|
|
try {
|
|
$tx->set('{b}foo', 'bar');
|
|
} catch (AbortedMultiExecException $exception) {
|
|
// NOOP
|
|
}
|
|
});
|
|
$this->fail('Expected EXEC to fail after the rejected command.');
|
|
} catch (Response\ServerException $exception) {
|
|
$this->assertSame('EXECABORT Transaction discarded because of previous errors.', $exception->getMessage());
|
|
}
|
|
|
|
$this->assertSame([], $commands);
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testClusterSlotErrorCaughtBeforeMultiDoesNotAbortExec(): void
|
|
{
|
|
$commands = [];
|
|
$cas = [];
|
|
$tx = $this->getMockedClusterTransaction(
|
|
$this->getExecuteCallback(['OK'], $commands, $cas),
|
|
['cas' => true, 'watch' => '{a}foo']
|
|
);
|
|
|
|
$response = $tx->execute(static function (MultiExec $tx) {
|
|
$tx->get('{a}foo');
|
|
|
|
try {
|
|
$tx->get('{b}foo');
|
|
} catch (AbortedMultiExecException $exception) {
|
|
// NOOP
|
|
}
|
|
|
|
$tx->multi();
|
|
$tx->set('{a}foo', 'bar');
|
|
});
|
|
|
|
$this->assertSame(['OK'], $response);
|
|
$this->assertSame(['WATCH', 'GET'], self::commandsToIDs($cas));
|
|
$this->assertSame(['MULTI', 'SET', 'EXEC'], self::commandsToIDs($commands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testClusterExecReportsALostConnectionBeforeARejectedCommand(): void
|
|
{
|
|
$node = $this->getMockBuilder(NodeConnectionInterface::class)->getMock();
|
|
$callback = $this->getExecuteCallback(['OK']);
|
|
$gets = 0;
|
|
$tx = $this->getMockedClusterTransaction(
|
|
static function (CommandInterface $command) use ($callback, $node, &$gets) {
|
|
if ($command->getId() === 'GET' && ++$gets === 2) {
|
|
throw new ConnectionException($node, 'Connection lost');
|
|
}
|
|
|
|
return $callback($command);
|
|
},
|
|
['cas' => true, 'watch' => '{a}foo']
|
|
);
|
|
|
|
try {
|
|
$tx->execute(static function (MultiExec $tx) {
|
|
$tx->get('{a}foo');
|
|
|
|
try {
|
|
$tx->get('{a}foo');
|
|
} catch (CommunicationException $exception) {
|
|
// NOOP
|
|
}
|
|
|
|
$tx->multi();
|
|
$tx->set('{a}foo', 'bar');
|
|
|
|
try {
|
|
$tx->set('{b}foo', 'bar');
|
|
} catch (AbortedMultiExecException $exception) {
|
|
// NOOP
|
|
}
|
|
});
|
|
$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->assertTrue($tx->discard()->watch('{a}foo'));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testClusterServerErrorCaughtBeforeMultiKeepsTheWatch(): void
|
|
{
|
|
$commands = [];
|
|
$cas = [];
|
|
$tx = $this->getMockedClusterTransaction(
|
|
$this->getWrongTypeCallback($this->getExecuteCallback(['OK'], $commands, $cas)),
|
|
['cas' => true, 'watch' => '{a}foo']
|
|
);
|
|
|
|
$response = $tx->execute(function (MultiExec $tx) {
|
|
$tx->get('{a}foo');
|
|
|
|
try {
|
|
$tx->get('{a}hash');
|
|
$this->fail('Expected the server error to be thrown.');
|
|
} catch (Response\ServerException $exception) {
|
|
$this->assertStringStartsWith('WRONGTYPE', $exception->getMessage());
|
|
}
|
|
|
|
$tx->multi();
|
|
$tx->set('{a}foo', 'bar');
|
|
});
|
|
|
|
$this->assertSame(['OK'], $response);
|
|
$this->assertSame(['WATCH', 'GET', 'GET'], self::commandsToIDs($cas));
|
|
$this->assertSame(['MULTI', 'SET', 'EXEC'], self::commandsToIDs($commands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
* @dataProvider clusterOrSingleNode
|
|
*/
|
|
public function testServerErrorEscapingTheBlockUnwatchesTheKeys(bool $cluster): void
|
|
{
|
|
$commands = [];
|
|
$cas = [];
|
|
$callback = $this->getWrongTypeCallback($this->getExecuteCallback([], $commands, $cas));
|
|
$options = ['cas' => true, 'watch' => '{a}foo'];
|
|
$tx = $cluster
|
|
? $this->getMockedClusterTransaction($callback, $options)
|
|
: $this->getMockedTransaction($callback, $options);
|
|
|
|
try {
|
|
$tx->execute(static function (MultiExec $tx) {
|
|
$tx->get('{a}foo');
|
|
$tx->get('{a}hash');
|
|
});
|
|
$this->fail('Expected the server error to be thrown.');
|
|
} catch (Response\ServerException $exception) {
|
|
$this->assertStringStartsWith('WRONGTYPE', $exception->getMessage());
|
|
}
|
|
|
|
$this->assertSame(['WATCH', 'GET', 'GET', 'UNWATCH'], self::commandsToIDs($cas));
|
|
$this->assertSame([], $commands);
|
|
}
|
|
|
|
public function clusterOrSingleNode(): array
|
|
{
|
|
return [
|
|
'single node' => [false],
|
|
'cluster' => [true],
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @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 callsAfterARejectedMulti
|
|
*/
|
|
public function testRejectedMultiLeavesTheTransactionInCheckAndSetMode(callable $call, $expected, array $commands): void
|
|
{
|
|
$sent = [];
|
|
$callback = $this->getExecuteCallback(['OK']);
|
|
$connection = $this->getMockedConnection(static function (CommandInterface $command) use ($callback, &$sent) {
|
|
$sent[] = $command->getId();
|
|
|
|
if ($sent === ['WATCH', 'GET', 'MULTI']) {
|
|
return new Response\Error("NOPERM User test has no permissions to run the 'multi' command");
|
|
}
|
|
|
|
return $callback($command);
|
|
});
|
|
$connection
|
|
->expects($this->never())
|
|
->method('disconnect');
|
|
|
|
$tx = new MultiExec(new Client($connection), ['cas' => true, 'watch' => 'foo']);
|
|
$this->assertSame('DUMMY_RESPONSE', $tx->get('foo'));
|
|
|
|
try {
|
|
$tx->multi();
|
|
$this->fail('Expected MULTI to be rejected.');
|
|
} catch (Response\ServerException $exception) {
|
|
$this->assertStringStartsWith('NOPERM', $exception->getMessage());
|
|
}
|
|
|
|
$this->assertSame($expected, $call($tx));
|
|
$this->assertSame(array_merge(['WATCH', 'GET', 'MULTI'], $commands), $sent);
|
|
}
|
|
|
|
public function callsAfterARejectedMulti(): array
|
|
{
|
|
return [
|
|
'discard()' => [
|
|
static function (MultiExec $tx) { return $tx->discard()->execute(); },
|
|
null,
|
|
['UNWATCH'],
|
|
],
|
|
'unwatch()' => [
|
|
static function (MultiExec $tx) { return $tx->unwatch()->execute(); },
|
|
null,
|
|
['UNWATCH'],
|
|
],
|
|
'execute()' => [
|
|
static function (MultiExec $tx) { return $tx->execute(); },
|
|
null,
|
|
['UNWATCH'],
|
|
],
|
|
'a command' => [
|
|
static function (MultiExec $tx) { return $tx->get('foo'); },
|
|
'DUMMY_RESPONSE',
|
|
['GET'],
|
|
],
|
|
'multi() again' => [
|
|
static function (MultiExec $tx) { return $tx->multi()->set('foo', 'bar')->execute(); },
|
|
['OK'],
|
|
['MULTI', 'SET', 'EXEC'],
|
|
],
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testCheckAndSetMultiOnALostConnectionFailsUntilUnwatch(): 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 'GET':
|
|
return 'bar';
|
|
case 'MULTI':
|
|
if ($sent === ['WATCH', 'GET', 'MULTI']) {
|
|
throw new ConnectionException($connection, 'Connection lost');
|
|
}
|
|
|
|
return new Response\Status('OK');
|
|
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), ['cas' => true, 'watch' => 'foo']);
|
|
$this->assertSame('bar', $tx->get('foo'));
|
|
|
|
try {
|
|
$tx->multi();
|
|
$this->fail('Expected the transaction to fail.');
|
|
} catch (ConnectionException $exception) {
|
|
$this->assertSame('Connection lost', $exception->getMessage());
|
|
}
|
|
|
|
try {
|
|
$tx->get('foo');
|
|
$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->unwatch()->multi()->set('foo', 'bar')->execute());
|
|
$this->assertSame(['WATCH', 'GET', 'MULTI', 'MULTI', 'SET', 'EXEC'], $sent);
|
|
}
|
|
|
|
/**
|
|
* @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());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
* @dataProvider discardOnTheWayOut
|
|
*/
|
|
public function testFailedDiscardClosesConnectionAndKeepsTheOriginalError(
|
|
callable $run,
|
|
string $exception,
|
|
string $message
|
|
): 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');
|
|
default:
|
|
return new Response\Status('QUEUED');
|
|
}
|
|
});
|
|
$connection
|
|
->expects($this->once())
|
|
->method('disconnect');
|
|
|
|
$this->expectException($exception);
|
|
$this->expectExceptionMessage($message);
|
|
|
|
$run(new Client($connection));
|
|
}
|
|
|
|
public function discardOnTheWayOut(): array
|
|
{
|
|
return [
|
|
'exception in block' => [
|
|
static function (Client $client) {
|
|
$client->transaction(static function (MultiExec $tx) {
|
|
$tx->set('foo', 'bar');
|
|
|
|
throw new RuntimeException('block failed');
|
|
});
|
|
},
|
|
RuntimeException::class,
|
|
'block failed',
|
|
],
|
|
'block after fluent interface' => [
|
|
static function (Client $client) {
|
|
$tx = new MultiExec($client);
|
|
$tx->set('foo', 'bar')->execute(static function () {});
|
|
},
|
|
ClientException::class,
|
|
'Cannot execute a transaction block after using fluent interface.',
|
|
],
|
|
'retry without block' => [
|
|
static function (Client $client) {
|
|
$tx = new MultiExec($client, ['retry' => 1]);
|
|
$tx->set('foo', 'bar')->execute();
|
|
},
|
|
ClientException::class,
|
|
'Automatic retries are supported only when a callable block is provided.',
|
|
],
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testExceptionsOptionTakesPrecedenceOverClientOptionsWhenFalse(): void
|
|
{
|
|
$expected = ['before', new Response\Error('ERR simulated error'), 'after'];
|
|
|
|
$connection = $this->getMockedConnection(static function (CommandInterface $command) use ($expected) {
|
|
switch ($command->getId()) {
|
|
case 'MULTI':
|
|
return true;
|
|
|
|
case 'EXEC':
|
|
return $expected;
|
|
|
|
default:
|
|
return new Response\Status('QUEUED');
|
|
}
|
|
});
|
|
|
|
$client = new Client($connection, ['exceptions' => true]);
|
|
$tx = new MultiExec($client, ['exceptions' => false]);
|
|
|
|
$result = $tx
|
|
->multi()
|
|
->echo('before')
|
|
->echo('ERROR PLEASE!')
|
|
->echo('after')
|
|
->exec();
|
|
|
|
$this->assertSame($expected, $result);
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testExceptionsOptionTakesPrecedenceOverClientOptionsWhenTrue(): void
|
|
{
|
|
$this->expectException('Predis\Response\ServerException');
|
|
$this->expectExceptionMessage('ERR simulated error');
|
|
|
|
$expected = ['before', new Response\Error('ERR simulated error'), 'after'];
|
|
|
|
$connection = $this->getMockedConnection(static function (CommandInterface $command) use ($expected) {
|
|
switch ($command->getId()) {
|
|
case 'MULTI':
|
|
return true;
|
|
|
|
case 'EXEC':
|
|
return $expected;
|
|
|
|
default:
|
|
return new Response\Status('QUEUED');
|
|
}
|
|
});
|
|
|
|
$client = new Client($connection, ['exceptions' => false]);
|
|
$tx = new MultiExec($client, ['exceptions' => true]);
|
|
|
|
$tx->multi()->echo('before')->echo('ERROR PLEASE!')->echo('after')->exec();
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testExceptionsOptionDoesNotAffectTransactionControlCommands(): void
|
|
{
|
|
$this->expectException('Predis\Response\ServerException');
|
|
$this->expectExceptionMessage('ERR simulated failure on EXEC');
|
|
|
|
$connection = $this->getMockedConnection(static function (CommandInterface $command) {
|
|
switch ($command->getId()) {
|
|
case 'MULTI':
|
|
return true;
|
|
|
|
case 'EXEC':
|
|
return new Response\Error('ERR simulated failure on EXEC');
|
|
|
|
default:
|
|
return new Response\Status('QUEUED');
|
|
}
|
|
});
|
|
|
|
$client = new Client($connection, ['exceptions' => false]);
|
|
$tx = new MultiExec($client);
|
|
|
|
$tx->multi()->echo('test')->exec();
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
* @throws Exception
|
|
*/
|
|
public function testRetryReplicationPipelineOnRetryableErrors(): void
|
|
{
|
|
$parameters = new Parameters([
|
|
'retry' => new Retry(new ExponentialBackoff(1000, 10000), 3),
|
|
'role' => 'master',
|
|
]);
|
|
|
|
$mockConnection = $this->getMockConnection();
|
|
|
|
$mockConnection
|
|
->expects($this->any())
|
|
->method('getParameters')
|
|
->willReturn($parameters);
|
|
|
|
$mockConnection
|
|
->expects($this->atLeast(3))
|
|
->method('disconnect')
|
|
->withAnyParameters();
|
|
|
|
$mockConnection
|
|
->method('isConnected')
|
|
->willReturn(true);
|
|
|
|
$mockConnection
|
|
->expects($this->exactly(8))
|
|
->method('executeCommand')
|
|
->withAnyParameters()
|
|
->willReturnOnConsecutiveCalls(
|
|
$this->throwException(new TimeoutException($mockConnection)),
|
|
$this->throwException(new TimeoutException($mockConnection)),
|
|
$this->throwException(new TimeoutException($mockConnection)),
|
|
new Response\Status('OK'),
|
|
new Response\Status('QUEUED'),
|
|
new Response\Status('QUEUED'),
|
|
new Response\Status('QUEUED'),
|
|
['OK', 'OK', 'OK']
|
|
);
|
|
|
|
$tx = new MultiExec(new Client($mockConnection));
|
|
|
|
$responses = $tx->execute(static function (MultiExec $tx) {
|
|
$tx->set('key', 'value');
|
|
$tx->set('key', 'value');
|
|
$tx->set('key', 'value');
|
|
});
|
|
|
|
$this->assertEquals(['OK', 'OK', 'OK'], $responses);
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testClusterCheckAndSetSendsMultiOnceAfterReads(): void
|
|
{
|
|
$txCommands = $casCommands = [];
|
|
$expected = ['bar', 'piyo'];
|
|
$options = ['cas' => true, 'watch' => ['{cas}foo', '{cas}hoge']];
|
|
|
|
$callback = $this->getExecuteCallback($expected, $txCommands, $casCommands);
|
|
$tx = $this->getMockedClusterTransaction($callback, $options);
|
|
|
|
$test = $this;
|
|
$responses = $tx->execute(static function ($tx) use ($test) {
|
|
$test->assertSame('DUMMY_RESPONSE', $tx->get('{cas}foo'));
|
|
|
|
$tx->multi();
|
|
|
|
$tx->get('{cas}foo');
|
|
$tx->get('{cas}hoge');
|
|
});
|
|
|
|
$this->assertSame($responses, $expected);
|
|
$this->assertSame(['WATCH', 'GET'], self::commandsToIDs($casCommands));
|
|
$this->assertSame(['MULTI', 'GET', 'GET', 'EXEC'], self::commandsToIDs($txCommands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
* @dataProvider blockExceptions
|
|
*/
|
|
public function testClusterCheckAndSetNeverLeavesMultiOpenWhenBlockThrows(Throwable $exception): void
|
|
{
|
|
$txCommands = $casCommands = [];
|
|
$options = ['cas' => true, 'watch' => '{cas}foo'];
|
|
|
|
$callback = $this->getExecuteCallback([], $txCommands, $casCommands);
|
|
$tx = $this->getMockedClusterTransaction($callback, $options);
|
|
$caught = null;
|
|
|
|
try {
|
|
$tx->execute(static function ($tx) use ($exception) {
|
|
$tx->get('{cas}foo');
|
|
$tx->multi();
|
|
$tx->set('{cas}foo', 'bar');
|
|
|
|
throw $exception;
|
|
});
|
|
} catch (Throwable $caught) {
|
|
// NOOP
|
|
}
|
|
|
|
$this->assertSame($exception, $caught);
|
|
$this->assertSame(['WATCH', 'GET'], array_slice(self::commandsToIDs($casCommands), 0, 2));
|
|
$this->assertSame([], self::commandsToIDs($txCommands));
|
|
}
|
|
|
|
public function blockExceptions(): array
|
|
{
|
|
return [
|
|
'PHP error' => [new TypeError('Invalid callback argument')],
|
|
'server error' => [new Response\ServerException('ERR simulated failure')],
|
|
'connection error' => [new ConnectionException(new StreamConnection(new Parameters()), 'Connection lost')],
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testClusterAutomaticRetryOnServerSideTransactionAbort(): void
|
|
{
|
|
$casCommands = $txCommands = [];
|
|
$expected = ['bar'];
|
|
$options = ['watch' => ['{cas}foo', '{cas}bar'], 'retry' => ($attempts = 2) + 1];
|
|
|
|
$callback = $this->getExecuteCallback($expected, $txCommands, $casCommands);
|
|
$tx = $this->getMockedClusterTransaction($callback, $options);
|
|
|
|
$responses = $tx->execute(static function (MultiExec $tx) use (&$attempts) {
|
|
$tx->get('{cas}foo');
|
|
|
|
if ($attempts > 0) {
|
|
$attempts--;
|
|
|
|
$tx->echo('!!ABORT!!');
|
|
}
|
|
});
|
|
|
|
$this->assertSame($responses, $expected);
|
|
$this->assertSame(0, $attempts);
|
|
$this->assertSame(['WATCH'], self::commandsToIDs($casCommands));
|
|
$this->assertSame(['MULTI', 'GET', 'EXEC'], self::commandsToIDs($txCommands));
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
* @dataProvider clusterServerErrors
|
|
*/
|
|
public function testClusterServerErrorIsReportedWithItsMessageWithoutRetrying(
|
|
string $stage,
|
|
string $error,
|
|
string $exceptionClass,
|
|
array $sent
|
|
): void {
|
|
$commands = [];
|
|
$calls = 0;
|
|
$tx = $this->getMockedClusterTransaction(
|
|
static function (CommandInterface $command) use (&$stage, $error, &$commands) {
|
|
$commands[] = $id = $command->getId();
|
|
|
|
if ($id === $stage) {
|
|
return new Response\Error($error);
|
|
}
|
|
|
|
switch ($id) {
|
|
case 'MULTI':
|
|
case 'DISCARD':
|
|
case 'UNWATCH':
|
|
return new Response\Status('OK');
|
|
case 'EXEC':
|
|
return ['bar'];
|
|
default:
|
|
return new Response\Status('QUEUED');
|
|
}
|
|
},
|
|
['retry' => 2]
|
|
);
|
|
$block = static function (MultiExec $tx) use (&$calls) {
|
|
$calls++;
|
|
$tx->get('{a}foo');
|
|
};
|
|
|
|
try {
|
|
$tx->execute($block);
|
|
$this->fail('Expected the server error to reach the caller.');
|
|
} catch (PredisException $exception) {
|
|
$this->assertInstanceOf($exceptionClass, $exception);
|
|
$this->assertSame($error, $exception->getMessage());
|
|
}
|
|
|
|
$this->assertSame(1, $calls);
|
|
$this->assertSame($sent, $commands);
|
|
|
|
// The transaction is reset and can be used again.
|
|
$stage = 'none';
|
|
$commands = [];
|
|
$this->assertSame(['bar'], $tx->execute($block));
|
|
$this->assertSame(['bar'], $tx->discard()->execute($block));
|
|
$this->assertSame(['MULTI', 'GET', 'EXEC', 'MULTI', 'GET', 'EXEC'], $commands);
|
|
}
|
|
|
|
public function clusterServerErrors(): array
|
|
{
|
|
$queued = ['MULTI', 'GET', 'DISCARD'];
|
|
$exec = ['MULTI', 'GET', 'EXEC', 'UNWATCH'];
|
|
|
|
return [
|
|
'queued command, wrong arity' => ['GET', "ERR wrong number of arguments for 'get' command", AbortedMultiExecException::class, $queued],
|
|
'queued command, cross-slot' => ['GET', "CROSSSLOT Keys in request don't hash to the same slot", AbortedMultiExecException::class, $queued],
|
|
'queued command, out of memory' => ['GET', "OOM command not allowed when used memory > 'maxmemory'.", AbortedMultiExecException::class, $queued],
|
|
'queued command, busy script' => ['GET', 'BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.', AbortedMultiExecException::class, $queued],
|
|
'EXEC, aborted by OOM' => ['EXEC', "EXECABORT Transaction discarded because of: OOM command not allowed when used memory > 'maxmemory'.", Response\ServerException::class, $exec],
|
|
'EXEC, cross-slot' => ['EXEC', "CROSSSLOT Keys in request don't hash to the same slot", Response\ServerException::class, $exec],
|
|
'MULTI denied' => ['MULTI', "NOPERM User default has no permissions to run the 'multi' command", Response\ServerException::class, ['MULTI', 'UNWATCH']],
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testClusterFluentTransactionReportsRejectedCommandAndCanBeReused(): void
|
|
{
|
|
$reject = true;
|
|
$tx = $this->getMockedClusterTransaction(static function (CommandInterface $command) use (&$reject) {
|
|
switch ($command->getId()) {
|
|
case 'MULTI':
|
|
case 'DISCARD':
|
|
return new Response\Status('OK');
|
|
case 'EXEC':
|
|
return ['bar'];
|
|
case 'SET':
|
|
return $reject ? new Response\Error("OOM command not allowed when used memory > 'maxmemory'.") : new Response\Status('QUEUED');
|
|
default:
|
|
return new Response\Status('QUEUED');
|
|
}
|
|
});
|
|
|
|
try {
|
|
$tx->get('{a}foo')->set('{a}foo', 'bar')->execute();
|
|
$this->fail('Expected the rejected command to abort the transaction.');
|
|
} catch (AbortedMultiExecException $exception) {
|
|
$this->assertSame("OOM command not allowed when used memory > 'maxmemory'.", $exception->getMessage());
|
|
$this->assertSame($tx, $exception->getTransaction());
|
|
}
|
|
|
|
$reject = false;
|
|
$this->assertSame(['bar'], $tx->get('{a}foo')->execute());
|
|
$this->assertSame(['bar'], $tx->discard()->get('{a}foo')->execute());
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testClusterRetryReachesTheNodeTheSlotWasMovedTo(): void
|
|
{
|
|
$seedCommands = $targetCommands = [];
|
|
$slot = (new RedisStrategy())->getSlotByKey('foo');
|
|
|
|
$seed = $this->getMockConnection('tcp://127.0.0.1:6379');
|
|
$seed
|
|
->method('executeCommand')
|
|
->willReturnCallback(static function (CommandInterface $command) use (&$seedCommands, $slot) {
|
|
$seedCommands[] = $id = $command->getId();
|
|
|
|
return $id === 'GET'
|
|
? new Response\Error("MOVED $slot 127.0.0.1:6380")
|
|
: new Response\Status('OK');
|
|
});
|
|
|
|
$target = $this->getMockConnection('tcp://127.0.0.1:6380');
|
|
$target
|
|
->method('executeCommand')
|
|
->willReturnCallback(static function (CommandInterface $command) use (&$targetCommands) {
|
|
$targetCommands[] = $id = $command->getId();
|
|
|
|
switch ($id) {
|
|
case 'CLUSTER':
|
|
return [[0, 16383, ['127.0.0.1', 6380]]];
|
|
|
|
case 'MULTI':
|
|
return new Response\Status('OK');
|
|
|
|
case 'EXEC':
|
|
return ['bar'];
|
|
|
|
default:
|
|
return new Response\Status('QUEUED');
|
|
}
|
|
});
|
|
|
|
$factory = $this->getMockBuilder(FactoryInterface::class)->getMock();
|
|
$factory
|
|
->expects($this->once())
|
|
->method('create')
|
|
->with(['host' => '127.0.0.1', 'port' => '6380', 'database' => null])
|
|
->willReturn($target);
|
|
|
|
$cluster = new RedisCluster($factory, new Parameters(['protocol' => 2]));
|
|
$cluster->add($seed);
|
|
|
|
$tx = new MultiExec(new Client($cluster), ['retry' => 1]);
|
|
|
|
$responses = $tx->execute(static function (MultiExec $tx) {
|
|
$tx->get('foo');
|
|
});
|
|
|
|
$this->assertSame(['bar'], $responses);
|
|
$this->assertSame(['MULTI', 'GET', 'DISCARD'], $seedCommands);
|
|
$this->assertSame(['CLUSTER', 'MULTI', 'GET', 'EXEC'], $targetCommands);
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testClusterFollowsRedirectionOfTheFirstCommand(): void
|
|
{
|
|
$seedCommands = $targetCommands = [];
|
|
$slot = (new RedisStrategy())->getSlotByKey('foo');
|
|
|
|
$seed = $this->getMockConnection('tcp://127.0.0.1:6379');
|
|
$seed
|
|
->method('executeCommand')
|
|
->willReturnCallback(static function (CommandInterface $command) use (&$seedCommands, $slot) {
|
|
$seedCommands[] = $command->getId();
|
|
|
|
return new Response\Error("MOVED $slot 127.0.0.1:6380");
|
|
});
|
|
|
|
$target = $this->getMockConnection('tcp://127.0.0.1:6380');
|
|
$target
|
|
->method('executeCommand')
|
|
->willReturnCallback($this->getClusterNodeCallback($targetCommands));
|
|
|
|
$factory = $this->getMockBuilder(FactoryInterface::class)->getMock();
|
|
$factory
|
|
->expects($this->once())
|
|
->method('create')
|
|
->with(['host' => '127.0.0.1', 'port' => '6380', 'database' => null])
|
|
->willReturn($target);
|
|
|
|
$cluster = new RedisCluster($factory, new Parameters(['protocol' => 2]));
|
|
$cluster->add($seed);
|
|
|
|
$tx = new MultiExec(new Client($cluster), ['watch' => 'foo']);
|
|
|
|
$responses = $tx->execute(static function (MultiExec $tx) {
|
|
$tx->get('foo');
|
|
});
|
|
|
|
$this->assertSame(['bar'], $responses);
|
|
$this->assertSame(['WATCH'], $seedCommands);
|
|
$this->assertSame(['CLUSTER', 'WATCH', 'MULTI', 'GET', 'EXEC'], $targetCommands);
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testClusterDoesNotFollowAskRedirectionOfTheFirstCommand(): void
|
|
{
|
|
$sourceCommands = $targetCommands = [];
|
|
$slot = (new RedisStrategy())->getSlotByKey('foo');
|
|
|
|
// The source still serves the slot, but the watched key was migrated.
|
|
$source = $this->getMockConnection('tcp://127.0.0.1:6379?slots=0-16383');
|
|
$source
|
|
->method('executeCommand')
|
|
->willReturnCallback(static function (CommandInterface $command) use (&$sourceCommands, $slot) {
|
|
$sourceCommands[] = $id = $command->getId();
|
|
|
|
switch ($id) {
|
|
case 'WATCH':
|
|
return new Response\Error("ASK $slot 127.0.0.1:6380");
|
|
|
|
case 'EXEC':
|
|
return ['OK'];
|
|
|
|
case 'SET':
|
|
return new Response\Status('QUEUED');
|
|
|
|
default:
|
|
return new Response\Status('OK');
|
|
}
|
|
});
|
|
|
|
$target = $this->getMockConnection('tcp://127.0.0.1:6380');
|
|
$target
|
|
->method('executeCommand')
|
|
->willReturnCallback($this->getClusterNodeCallback($targetCommands));
|
|
|
|
$factory = $this->getMockBuilder(FactoryInterface::class)->getMock();
|
|
$factory->expects($this->never())->method('create');
|
|
|
|
$cluster = new RedisCluster($factory, new Parameters(['protocol' => 2]));
|
|
$cluster->add($source);
|
|
$cluster->add($target);
|
|
|
|
$tx = new MultiExec(new Client($cluster), ['watch' => 'foo']);
|
|
|
|
try {
|
|
$tx->execute(static function (MultiExec $tx) {
|
|
$tx->set('foo', 'bar');
|
|
});
|
|
$this->fail('Expected the -ASK response to WATCH to fail the transaction.');
|
|
} catch (Response\ServerException $exception) {
|
|
$this->assertSame("ASK $slot 127.0.0.1:6380", $exception->getMessage());
|
|
}
|
|
|
|
// Neither WATCH nor the transaction run on the node importing the slot.
|
|
$this->assertSame(['WATCH', 'UNWATCH'], $sourceCommands);
|
|
$this->assertSame([], $targetCommands);
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testClusterRetriesTheFirstCommandOnConnectionFailure(): void
|
|
{
|
|
$deadCommands = $aliveCommands = [];
|
|
|
|
$dead = $this->getMockConnection('tcp://127.0.0.1:6379?slots=0-16383');
|
|
$dead
|
|
->method('executeCommand')
|
|
->willReturnCallback(static function (CommandInterface $command) use (&$deadCommands, &$dead) {
|
|
$deadCommands[] = $command->getId();
|
|
|
|
throw new ConnectionException($dead, 'Connection lost');
|
|
});
|
|
|
|
$alive = $this->getMockConnection('tcp://127.0.0.1:6380');
|
|
$alive
|
|
->method('executeCommand')
|
|
->willReturnCallback($this->getClusterNodeCallback($aliveCommands));
|
|
|
|
$cluster = new RedisCluster(
|
|
$this->getMockBuilder(FactoryInterface::class)->getMock(),
|
|
new Parameters(['protocol' => 2])
|
|
);
|
|
$cluster->add($dead);
|
|
$cluster->add($alive);
|
|
|
|
$tx = new MultiExec(new Client($cluster));
|
|
|
|
$responses = $tx->execute(static function (MultiExec $tx) {
|
|
$tx->get('foo');
|
|
});
|
|
|
|
$this->assertSame(['bar'], $responses);
|
|
$this->assertSame(['MULTI'], $deadCommands);
|
|
$this->assertSame(['CLUSTER', 'MULTI', 'GET', 'EXEC'], $aliveCommands);
|
|
}
|
|
|
|
/**
|
|
* @group disconnected
|
|
*/
|
|
public function testClusterTransactionReachesAnotherNodeAfterTheFirstOneDied(): void
|
|
{
|
|
$deadCommands = $aliveCommands = [];
|
|
|
|
$dead = $this->getMockConnection('tcp://127.0.0.1:6379?slots=0-16383');
|
|
$dead
|
|
->method('executeCommand')
|
|
->willReturnCallback(static function (CommandInterface $command) use (&$deadCommands, &$dead) {
|
|
$deadCommands[] = $id = $command->getId();
|
|
|
|
if ($id === 'GET') {
|
|
throw new ConnectionException($dead, 'Connection lost');
|
|
}
|
|
|
|
return new Response\Status('OK');
|
|
});
|
|
|
|
$alive = $this->getMockConnection('tcp://127.0.0.1:6380');
|
|
$alive
|
|
->method('executeCommand')
|
|
->willReturnCallback($this->getClusterNodeCallback($aliveCommands));
|
|
|
|
$cluster = new RedisCluster(
|
|
$this->getMockBuilder(FactoryInterface::class)->getMock(),
|
|
new Parameters(['protocol' => 2])
|
|
);
|
|
$cluster->add($dead);
|
|
$cluster->add($alive);
|
|
|
|
$client = new Client($cluster);
|
|
$block = static function (MultiExec $tx) {
|
|
$tx->get('foo');
|
|
};
|
|
|
|
try {
|
|
(new MultiExec($client))->execute($block);
|
|
$this->fail('Expected the connection failure to abort the transaction.');
|
|
} catch (ConnectionException $exception) {
|
|
$this->assertSame('Connection lost', $exception->getMessage());
|
|
}
|
|
|
|
// The commands of the aborted transaction are not sent anywhere else.
|
|
$this->assertSame(['MULTI', 'GET'], $deadCommands);
|
|
$this->assertSame(['CLUSTER'], $aliveCommands);
|
|
|
|
$this->assertSame(['bar'], (new MultiExec($client))->execute($block));
|
|
$this->assertSame(['MULTI', 'GET'], $deadCommands);
|
|
$this->assertSame(['CLUSTER', 'MULTI', 'GET', 'EXEC'], $aliveCommands);
|
|
}
|
|
|
|
/**
|
|
* Returns a callback emulating the only node of a cluster that is able to
|
|
* complete a transaction, keeping track of the commands it receives.
|
|
*
|
|
* @param array $commands Reference to an array storing the IDs of the commands
|
|
*
|
|
* @return callable
|
|
*/
|
|
protected function getClusterNodeCallback(array &$commands): callable
|
|
{
|
|
return static function (CommandInterface $command) use (&$commands) {
|
|
$commands[] = $id = $command->getId();
|
|
|
|
switch ($id) {
|
|
case 'CLUSTER':
|
|
return [[0, 16383, ['127.0.0.1', 6380]]];
|
|
|
|
case 'WATCH':
|
|
case 'MULTI':
|
|
return new Response\Status('OK');
|
|
|
|
case 'EXEC':
|
|
return ['bar'];
|
|
|
|
default:
|
|
return new Response\Status('QUEUED');
|
|
}
|
|
};
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @dataProvider connectionPersistence
|
|
* @requiresRedisVersion >= 3.0.0
|
|
*/
|
|
public function testClusterQueueErrorLeavesConnectionUsable(bool $persistent): void
|
|
{
|
|
$options = ['parameters' => ['persistent' => $persistent]];
|
|
$redis = $this->createClient(null, $options);
|
|
$key = '{abort}value';
|
|
$missing = '{abort}missing';
|
|
$redis->set($key, 'original');
|
|
$redis->del($missing);
|
|
|
|
try {
|
|
$redis->transaction(static function (MultiExec $tx) use ($key) {
|
|
$tx->set($key, 'queued');
|
|
$tx->executeCommand(new RawCommand('SET', [$key]));
|
|
});
|
|
$this->fail('Expected the transaction to abort.');
|
|
} catch (AbortedMultiExecException $exception) {
|
|
$this->assertSame('original', $redis->get($key));
|
|
}
|
|
|
|
$this->assertNull($redis->get($missing));
|
|
$this->assertEquals('OK', $redis->set($key, 'after-abort'));
|
|
|
|
$nextClient = $this->createClient(null, $options, false);
|
|
$this->assertSame('after-abort', $nextClient->get($key));
|
|
$this->assertNull($nextClient->get($missing));
|
|
$redis->disconnect();
|
|
}
|
|
|
|
public function connectionPersistence(): array
|
|
{
|
|
return [[false], [true]];
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @requiresRedisVersion >= 3.0.0
|
|
*/
|
|
public function testClusterServerErrorReachesTheCallerWithoutRetrying(): void
|
|
{
|
|
$redis = $this->getClient();
|
|
$key = '{p1}value';
|
|
$redis->set($key, 'original');
|
|
$calls = 0;
|
|
|
|
try {
|
|
$redis->transaction(['retry' => 2], static function (MultiExec $tx) use ($key, &$calls) {
|
|
$calls++;
|
|
$tx->set($key, 'queued');
|
|
$tx->mget($key, '{p1-other}value');
|
|
});
|
|
$this->fail('Expected the cross-slot command to abort the transaction.');
|
|
} catch (AbortedMultiExecException $exception) {
|
|
$this->assertStringStartsWith('CROSSSLOT', $exception->getMessage());
|
|
}
|
|
|
|
$this->assertSame(1, $calls);
|
|
$this->assertSame('original', $redis->get($key));
|
|
$this->assertEquals(['OK'], $redis->transaction(static function (MultiExec $tx) use ($key) {
|
|
$tx->set($key, 'after');
|
|
}));
|
|
$this->assertSame('after', $redis->get($key));
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @requiresRedisVersion >= 3.0.0
|
|
*/
|
|
public function testClusterWatchConflictIsStillRetried(): void
|
|
{
|
|
$redis = $this->getClient();
|
|
$other = $this->getClient();
|
|
$key = '{p1}watched';
|
|
$redis->set($key, 'original');
|
|
$calls = 0;
|
|
|
|
$responses = $redis->transaction(['watch' => $key, 'cas' => true, 'retry' => 1], static function (MultiExec $tx) use ($key, $other, &$calls) {
|
|
$tx->get($key);
|
|
|
|
if (++$calls === 1) {
|
|
$other->set($key, 'changed');
|
|
}
|
|
|
|
$tx->multi();
|
|
$tx->set($key, 'committed');
|
|
});
|
|
|
|
$this->assertEquals(['OK'], $responses);
|
|
$this->assertSame(2, $calls);
|
|
$this->assertSame('committed', $redis->get($key));
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @requiresRedisVersion >= 3.0.0
|
|
*/
|
|
public function testClusterSlotErrorCaughtInsideBlockCommitsNothing(): void
|
|
{
|
|
$redis = $this->getClient();
|
|
|
|
try {
|
|
$redis->transaction(static function (MultiExec $tx) {
|
|
$tx->set('{a}foo', 'bar');
|
|
|
|
try {
|
|
$tx->set('{b}foo', 'bar');
|
|
} catch (AbortedMultiExecException $exception) {
|
|
// NOOP
|
|
}
|
|
});
|
|
$this->fail('Expected EXEC to fail after the rejected command.');
|
|
} catch (Response\ServerException $exception) {
|
|
$this->assertStringStartsWith('EXECABORT', $exception->getMessage());
|
|
}
|
|
|
|
$this->assertNull($redis->get('{a}foo'));
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @group relay-incompatible
|
|
* @requiresRedisVersion >= 5.0.0
|
|
*/
|
|
public function testClusterLostConnectionAfterWatchFailsUntilDiscard(): void
|
|
{
|
|
// Nodes found after the lost one is reported get only these parameters.
|
|
$redis = $this->createClient(null, [
|
|
'parameters' => ['password' => getenv('REDIS_PASSWORD') ?: constant('REDIS_PASSWORD')],
|
|
]);
|
|
$key = '{cas}foo';
|
|
$redis->set($key, 'original');
|
|
$node = $redis->getConnection()->getConnectionByCommand($redis->createCommand('GET', [$key]));
|
|
$admin = new Client($node->getParameters());
|
|
$id = $node->executeCommand($redis->createCommand('CLIENT', ['ID']));
|
|
|
|
$tx = $redis->transaction(['cas' => true, 'watch' => $key]);
|
|
$value = $tx->get($key);
|
|
$admin->set($key, 'changed');
|
|
$admin->client('KILL', 'ID', $id);
|
|
|
|
try {
|
|
$tx->get($key);
|
|
$this->fail('Expected the lost connection to reach the caller.');
|
|
} catch (CommunicationException $exception) {
|
|
// NOOP
|
|
}
|
|
|
|
try {
|
|
$tx->multi()->set($key, "$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($key));
|
|
$this->assertSame([1], $tx->discard()->incr('{cas}counter')->execute());
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @dataProvider connectionPersistence
|
|
* @requiresRedisVersion >= 3.0.0
|
|
*/
|
|
public function testClusterFailedDiscardClosesThePhysicalSocket(bool $persistent): void
|
|
{
|
|
$connection = new class(new Parameters()) extends StreamConnection {
|
|
public function executeCommand(CommandInterface $command)
|
|
{
|
|
if ($command->getId() === 'DISCARD') {
|
|
return new Response\Error('NOPERM simulated DISCARD failure');
|
|
}
|
|
|
|
return parent::executeCommand($command);
|
|
}
|
|
};
|
|
$redis = $this->createClient(null, [
|
|
'connections' => ['tcp' => get_class($connection)],
|
|
'parameters' => ['persistent' => $persistent],
|
|
]);
|
|
$key = '{failed-discard}value';
|
|
$redis->set($key, 'original');
|
|
$command = $redis->createCommand('GET', [$key]);
|
|
$node = $redis->getConnection()->getConnectionByCommand($command);
|
|
$originalClientId = $node->executeCommand(new RawCommand('CLIENT', ['ID']));
|
|
|
|
try {
|
|
$redis->transaction(static function (MultiExec $tx) use ($key) {
|
|
$tx->set($key, 'queued');
|
|
$tx->executeCommand(new RawCommand('SET', [$key]));
|
|
});
|
|
$this->fail('Expected the transaction to abort.');
|
|
} catch (AbortedMultiExecException $exception) {
|
|
$this->assertFalse($node->isConnected());
|
|
}
|
|
|
|
$this->assertSame('original', $redis->get($key));
|
|
$this->assertNotSame($originalClientId, $node->executeCommand(new RawCommand('CLIENT', ['ID'])));
|
|
$this->assertNull($redis->get('{failed-discard}missing'));
|
|
$this->assertEquals('OK', $redis->set($key, 'after-abort'));
|
|
$this->assertSame('after-abort', $redis->get($key));
|
|
$redis->disconnect();
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @requiresRedisVersion >= 3.0.0
|
|
*/
|
|
public function testClusterIntegrationServerErrorCaughtBeforeMultiKeepsTheWatch(): void
|
|
{
|
|
$redis = $this->getClient();
|
|
$key = '{cas}foo';
|
|
$hash = '{cas}hash';
|
|
$redis->set($key, 'original');
|
|
$redis->hset($hash, 'field', 'value');
|
|
$node = $redis->getConnection()->getConnectionByCommand($redis->createCommand('GET', [$key]));
|
|
$other = new Client($node->getParameters());
|
|
|
|
try {
|
|
$redis->transaction(['cas' => true, 'watch' => $key], function (MultiExec $tx) use ($key, $hash, $other) {
|
|
try {
|
|
$tx->get($hash);
|
|
$this->fail('Expected the server error to be thrown.');
|
|
} catch (Response\ServerException $exception) {
|
|
$this->assertStringStartsWith('WRONGTYPE', $exception->getMessage());
|
|
}
|
|
|
|
$other->set($key, 'changed');
|
|
$tx->multi();
|
|
$tx->set($key, 'overwritten');
|
|
});
|
|
$this->fail('Expected EXEC to fail after the change to the watched key.');
|
|
} catch (AbortedMultiExecException $exception) {
|
|
$this->assertSame('The current transaction has been aborted by the server.', $exception->getMessage());
|
|
}
|
|
|
|
$this->assertSame('changed', $redis->get($key));
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @requiresRedisVersion >= 3.0.0
|
|
*/
|
|
public function testClusterIntegrationServerErrorEscapingTheBlockUnwatchesTheKeys(): void
|
|
{
|
|
$redis = $this->getClient();
|
|
$key = '{cas}foo';
|
|
$hash = '{cas}hash';
|
|
$redis->hset($hash, 'field', 'value');
|
|
$node = $redis->getConnection()->getConnectionByCommand($redis->createCommand('GET', [$key]));
|
|
$other = new Client($node->getParameters());
|
|
|
|
try {
|
|
$redis->transaction(['cas' => true, 'watch' => $key], static function (MultiExec $tx) use ($hash) {
|
|
$tx->get($hash);
|
|
});
|
|
$this->fail('Expected the server error to be thrown.');
|
|
} catch (Response\ServerException $exception) {
|
|
$this->assertStringStartsWith('WRONGTYPE', $exception->getMessage());
|
|
}
|
|
|
|
$other->set($key, 'changed');
|
|
|
|
$this->assertEquals(['OK'], $redis->transaction()->set('{cas}bar', 'baz')->execute());
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @requiresRedisVersion >= 3.0.0
|
|
*/
|
|
public function testClusterCasReadsValueBeforeMulti(): void
|
|
{
|
|
$redis = $this->getClient();
|
|
$key = '{cas}counter';
|
|
$redis->set($key, '7');
|
|
|
|
$response = $redis->transaction(['cas' => true, 'watch' => $key], function (MultiExec $tx) use ($key) {
|
|
$current = $tx->get($key);
|
|
$this->assertSame('7', $current);
|
|
$tx->multi();
|
|
$tx->set($key, (string) ((int) $current + 1));
|
|
});
|
|
|
|
$this->assertEquals(['OK'], $response);
|
|
$this->assertSame('8', $redis->get($key));
|
|
$this->assertNull($redis->get('{cas}missing'));
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @dataProvider blockExceptions
|
|
* @requiresRedisVersion >= 3.0.0
|
|
*/
|
|
public function testClusterCasBlockExceptionLeavesConnectionUsable(Throwable $exception): void
|
|
{
|
|
$redis = $this->getClient();
|
|
$key = '{cas}counter';
|
|
$redis->set($key, '7');
|
|
$caught = null;
|
|
|
|
try {
|
|
$redis->transaction(['cas' => true, 'watch' => $key], static function (MultiExec $tx) use ($key, $exception) {
|
|
$tx->multi();
|
|
$tx->set($key, 'queued');
|
|
|
|
throw $exception;
|
|
});
|
|
} catch (Throwable $caught) {
|
|
// NOOP
|
|
}
|
|
|
|
$this->assertSame($exception, $caught);
|
|
$this->assertSame('7', $redis->get($key));
|
|
$this->assertNull($redis->get('{cas}missing'));
|
|
$this->assertEquals('OK', $redis->set($key, 'after-error'));
|
|
$this->assertSame('after-error', $redis->get($key));
|
|
}
|
|
|
|
// ******************************************************************** //
|
|
// ---- INTEGRATION TESTS --------------------------------------------- //
|
|
// ******************************************************************** //
|
|
|
|
/**
|
|
* @group connected
|
|
*/
|
|
public function testIntegrationHandlesStandardExceptionsInBlock(): void
|
|
{
|
|
$client = $this->getClient();
|
|
$exception = null;
|
|
|
|
try {
|
|
$client->transaction(static function (MultiExec $tx) {
|
|
$tx->set('foo', 'bar');
|
|
throw new RuntimeException('TEST');
|
|
});
|
|
} catch (Exception $ex) {
|
|
$exception = $ex;
|
|
}
|
|
|
|
$this->assertInstanceOf('RuntimeException', $exception);
|
|
$this->assertSame(0, $client->exists('foo'));
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
*/
|
|
public function testIntegrationThrowsExceptionOnRedisErrorInBlock(): void
|
|
{
|
|
$client = $this->getClient();
|
|
$exception = null;
|
|
$value = (string) rand();
|
|
|
|
try {
|
|
$client->transaction(static function (MultiExec $tx) use ($value) {
|
|
$tx->set('foo', 'bar');
|
|
$tx->lpush('foo', 'bar');
|
|
$tx->set('foo', $value);
|
|
});
|
|
} catch (Response\ServerException $ex) {
|
|
$exception = $ex;
|
|
}
|
|
|
|
$this->assertInstanceOf('Predis\Response\ErrorInterface', $exception);
|
|
$this->assertSame($value, $client->get('foo'));
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group relay-incompatible
|
|
* @dataProvider connectionPersistence
|
|
*/
|
|
public function testIntegrationQueueErrorWithFluentInterfaceLeavesConnectionUsable(bool $persistent): void
|
|
{
|
|
$client = $this->createClient(['persistent' => $persistent]);
|
|
$client->set('foo', 'original');
|
|
|
|
try {
|
|
try {
|
|
$client->transaction()->set('foo', 'queued')->executeCommand(new RawCommand('SET', ['foo']))->execute();
|
|
$this->fail('Expected the transaction to abort.');
|
|
} catch (AbortedMultiExecException $exception) {
|
|
$this->assertStringStartsWith('ERR wrong number of arguments', $exception->getMessage());
|
|
}
|
|
|
|
$this->assertSame('original', $client->get('foo'));
|
|
$this->assertEquals('OK', $client->set('foo', 'after-abort'));
|
|
|
|
$nextClient = $this->createClient(['persistent' => $persistent], null, false);
|
|
$this->assertSame('after-abort', $nextClient->get('foo'));
|
|
} finally {
|
|
$client->disconnect();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @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
|
|
* @requiresRedisVersion >= 6.0.0
|
|
*/
|
|
public function testIntegrationDiscardAfterRejectedMultiLeavesConnectionUsable(): void
|
|
{
|
|
$admin = $this->createClient();
|
|
$admin->acl->setUser('predis-multi-denied', 'reset', 'on', '>secret', '~*', '+@all', '-multi');
|
|
|
|
try {
|
|
$client = $this->createClient(['username' => 'predis-multi-denied', 'password' => 'secret'], null, false);
|
|
$client->set('foo', 'bar');
|
|
$id = $client->client('ID');
|
|
|
|
$tx = $client->transaction(['cas' => true, 'watch' => 'foo']);
|
|
$this->assertSame('bar', $tx->get('foo'));
|
|
|
|
try {
|
|
$tx->multi();
|
|
$this->fail('Expected MULTI to be rejected.');
|
|
} catch (Response\ServerException $exception) {
|
|
$this->assertStringStartsWith('NOPERM', $exception->getMessage());
|
|
}
|
|
|
|
$tx->discard();
|
|
|
|
// A WATCH left on the connection would abort the next transaction.
|
|
$admin->set('foo', 'baz');
|
|
$admin->acl->setUser('predis-multi-denied', '+multi');
|
|
|
|
$this->assertSame([1], $client->transaction()->incr('counter')->execute());
|
|
$this->assertSame($id, $client->client('ID'));
|
|
} finally {
|
|
$admin->acl->delUser('predis-multi-denied');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group relay-incompatible
|
|
*/
|
|
public function testIntegrationReturnsErrorObjectOnRedisErrorInBlock(): void
|
|
{
|
|
$client = $this->getClient([], ['exceptions' => false]);
|
|
|
|
$responses = $client->transaction(static function (MultiExec $tx) {
|
|
$tx->set('foo', 'bar');
|
|
$tx->lpush('foo', 'bar');
|
|
$tx->echo('foobar');
|
|
});
|
|
|
|
$this->assertInstanceOf('Predis\Response\Status', $responses[0]);
|
|
$this->assertInstanceOf('Predis\Response\Error', $responses[1]);
|
|
$this->assertSame('foobar', $responses[2]);
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group ext-relay
|
|
*/
|
|
public function testIntegrationReturnsErrorObjectOnRedisErrorInBlockWhenUsingRelay(): void
|
|
{
|
|
$client = $this->getClient([], ['exceptions' => false]);
|
|
|
|
$responses = $client->transaction(static function (MultiExec $tx) {
|
|
$tx->set('foo', 'bar');
|
|
$tx->lpush('foo', 'bar');
|
|
$tx->echo('foobar');
|
|
});
|
|
|
|
$this->assertSame('OK', $responses[0]);
|
|
$this->assertInstanceOf('Predis\Response\Error', $responses[1]);
|
|
$this->assertSame('foobar', $responses[2]);
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group relay-incompatible
|
|
* @requiresRedisVersion >= 5.0.0
|
|
*/
|
|
public function testIntegrationLostConnectionInsideBlockIsNotRetried(): void
|
|
{
|
|
$client = $this->createClient(['retry' => new Retry(new NoBackoff(), 3)]);
|
|
|
|
$this->assertLostConnectionInsideBlockIsNotRetried($client, $this->createClient(null, null, false));
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group relay-incompatible
|
|
* @requiresRedisVersion >= 5.0.0
|
|
*/
|
|
public function testIntegrationLostConnectionAfterWatchFailsUntilDiscard(): void
|
|
{
|
|
$client = $this->createClient(['retry' => new Retry(new NoBackoff(), 3)]);
|
|
|
|
$this->assertLostConnectionAfterWatchFailsUntilDiscard($client, $this->createClient(null, null, false));
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group sentinel
|
|
* @group relay-incompatible
|
|
* @requiresRedisVersion >= 7.0.0
|
|
*/
|
|
public function testSentinelLostConnectionInsideBlockIsNotRetried(): void
|
|
{
|
|
$client = $this->createClient();
|
|
$admin = new Client($client->getConnection()->getMaster()->getParameters());
|
|
|
|
$this->assertLostConnectionInsideBlockIsNotRetried($client, $admin);
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group sentinel
|
|
* @group relay-incompatible
|
|
* @requiresRedisVersion >= 7.0.0
|
|
*/
|
|
public function testSentinelLostConnectionAfterWatchFailsUntilDiscard(): void
|
|
{
|
|
$client = $this->createClient();
|
|
$admin = new Client($client->getConnection()->getMaster()->getParameters());
|
|
|
|
$this->assertLostConnectionAfterWatchFailsUntilDiscard($client, $admin);
|
|
}
|
|
|
|
/**
|
|
* Drops the connection of $client in the middle of a transaction block.
|
|
*/
|
|
private function assertLostConnectionInsideBlockIsNotRetried(Client $client, Client $admin): void
|
|
{
|
|
$id = $client->client('ID');
|
|
|
|
try {
|
|
$client->transaction(static function (MultiExec $tx) use ($admin, $id) {
|
|
$tx->set('foo', 'bar');
|
|
$admin->client('KILL', 'ID', $id);
|
|
$tx->incr('counter');
|
|
});
|
|
$this->fail('Expected the transaction to fail.');
|
|
} catch (CommunicationException $exception) {
|
|
// NOOP
|
|
}
|
|
|
|
$this->assertNull($admin->get('foo'));
|
|
$this->assertNull($admin->get('counter'));
|
|
$this->assertSame([1], $client->transaction()->incr('counter')->execute());
|
|
}
|
|
|
|
/**
|
|
* Drops the connection of $client between WATCH and MULTI, after another
|
|
* client changed the watched key, and keeps using the transaction after
|
|
* catching the error.
|
|
*/
|
|
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 {
|
|
$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());
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @requiresRedisVersion >= 2.0.0
|
|
*/
|
|
public function testIntegrationSendMultiOnCommandsAfterDiscard(): void
|
|
{
|
|
$client = $this->getClient();
|
|
|
|
$responses = $client->transaction(static function (MultiExec $tx) {
|
|
$tx->set('foo', 'bar');
|
|
$tx->discard();
|
|
$tx->set('hoge', 'piyo');
|
|
});
|
|
|
|
$this->assertCount(1, $responses);
|
|
$this->assertSame(0, $client->exists('foo'));
|
|
$this->assertSame(1, $client->exists('hoge'));
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @requiresRedisVersion >= 2.2.0
|
|
*/
|
|
public function testIntegrationServerErrorEscapingTheBlockUnwatchesTheKeys(): void
|
|
{
|
|
$redis = $this->getClient();
|
|
$other = $this->getClient();
|
|
$redis->hset('hash', 'field', 'value');
|
|
|
|
try {
|
|
$redis->transaction(['cas' => true, 'watch' => 'foo'], static function (MultiExec $tx) {
|
|
$tx->get('hash');
|
|
});
|
|
$this->fail('Expected the server error to be thrown.');
|
|
} catch (Response\ServerException $exception) {
|
|
$this->assertStringStartsWith('WRONGTYPE', $exception->getMessage());
|
|
}
|
|
|
|
$other->set('foo', 'changed');
|
|
|
|
$this->assertEquals(['OK'], $redis->transaction()->set('bar', 'baz')->execute());
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @requiresRedisVersion >= 2.2.0
|
|
*/
|
|
public function testIntegrationWritesOnWatchedKeysAbortTransaction(): void
|
|
{
|
|
$exception = null;
|
|
$client1 = $this->getClient();
|
|
$client2 = $this->getClient();
|
|
|
|
try {
|
|
$client1->transaction(['watch' => 'sentinel'], static function ($tx) use ($client2) {
|
|
$tx->set('sentinel', 'client1');
|
|
$tx->get('sentinel');
|
|
$client2->set('sentinel', 'client2');
|
|
});
|
|
} catch (AbortedMultiExecException $ex) {
|
|
$exception = $ex;
|
|
}
|
|
|
|
$this->assertInstanceOf('Predis\Transaction\AbortedMultiExecException', $exception);
|
|
$this->assertSame('client2', $client1->get('sentinel'));
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @requiresRedisVersion >= 2.2.0
|
|
*/
|
|
public function testIntegrationRetriesTransactionAbortedByWatch(): void
|
|
{
|
|
$client1 = $this->getClient();
|
|
$client2 = $this->getClient();
|
|
$attempts = 0;
|
|
$options = ['watch' => 'sentinel', 'cas' => true, 'retry' => 1];
|
|
|
|
$responses = $client1->transaction($options, static function ($tx) use ($client2, &$attempts) {
|
|
$tx->get('sentinel');
|
|
|
|
if (++$attempts === 1) {
|
|
$client2->set('sentinel', 'client2');
|
|
}
|
|
|
|
$tx->multi();
|
|
$tx->set('sentinel', 'client1');
|
|
});
|
|
|
|
$this->assertSame(2, $attempts);
|
|
$this->assertEquals(['OK'], $responses);
|
|
$this->assertSame('client1', $client2->get('sentinel'));
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @requiresRedisVersion >= 2.2.0
|
|
*/
|
|
public function testIntegrationCheckAndSetWithDiscardAndRetry(): void
|
|
{
|
|
$client = $this->getClient();
|
|
|
|
$client->set('foo', 'bar');
|
|
$options = ['watch' => 'foo', 'cas' => true];
|
|
|
|
$responses = $client->transaction($options, static function ($tx) {
|
|
$tx->watch('foobar');
|
|
$foo = $tx->get('foo');
|
|
|
|
$tx->multi();
|
|
$tx->set('foobar', $foo);
|
|
$tx->discard();
|
|
$tx->mget('foo', 'foobar');
|
|
});
|
|
|
|
$this->assertIsArray($responses);
|
|
$this->assertSame([['bar', null]], $responses);
|
|
|
|
$hijack = true;
|
|
$client2 = $this->getClient();
|
|
$client->set('foo', 'bar');
|
|
|
|
$options = ['watch' => 'foo', 'cas' => true, 'retry' => 1];
|
|
$responses = $client->transaction($options, static function ($tx) use ($client2, &$hijack) {
|
|
$foo = $tx->get('foo');
|
|
$tx->multi();
|
|
|
|
$tx->set('foobar', $foo);
|
|
$tx->discard();
|
|
|
|
if ($hijack) {
|
|
$hijack = false;
|
|
$client2->set('foo', 'hijacked!');
|
|
}
|
|
|
|
$tx->mget('foo', 'foobar');
|
|
});
|
|
|
|
$this->assertIsArray($responses);
|
|
$this->assertSame([['hijacked!', null]], $responses);
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @return void
|
|
* @requiresRedisVersion >= 3.0.0
|
|
*/
|
|
public function testExecutesTransactionAgainstCluster(): void
|
|
{
|
|
$redis = $this->getClient();
|
|
|
|
$response = $redis->transaction(static function (MultiExec $tx) {
|
|
$tx->set('{foo}foo', 'value');
|
|
$tx->set('{foo}bar', 'value');
|
|
$tx->set('{foo}baz', 'value');
|
|
});
|
|
|
|
$this->assertEquals(['OK', 'OK', 'OK'], $response);
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @return void
|
|
* @requiresRedisVersion >= 3.0.0
|
|
*/
|
|
public function testThrowsExceptionOnDifferentHashSlots(): void
|
|
{
|
|
$redis = $this->getClient();
|
|
|
|
$this->expectException(AbortedMultiExecException::class);
|
|
$this->expectExceptionMessage(
|
|
'To be able to execute a transaction against cluster, all commands should operate on the same hash slot'
|
|
);
|
|
|
|
$redis->transaction(static function (MultiExec $tx) {
|
|
$tx->set('foo_bar_baz', 'value');
|
|
$tx->set('{foo}bar', 'value');
|
|
$tx->set('{foo}baz', 'value');
|
|
});
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @return void
|
|
* @requiresRedisVersion >= 3.0.0
|
|
*/
|
|
public function testExecutesCASTransactionAgainstCluster(): void
|
|
{
|
|
$redis = $this->getClient();
|
|
$options = ['cas' => true, 'watch' => ['{foo}foo', '{foo}bar', '{foo}baz']];
|
|
|
|
$response = $redis->transaction($options, static function (MultiExec $tx) {
|
|
$tx->multi();
|
|
$tx->set('{foo}foo', 'value');
|
|
$tx->set('{foo}bar', 'value');
|
|
$tx->set('{foo}baz', 'value');
|
|
});
|
|
|
|
$this->assertEquals(['OK', 'OK', 'OK'], $response);
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @return void
|
|
* @requiresRedisVersion >= 3.0.0
|
|
*/
|
|
public function testUNWATCHCurrentlyWATCHedKeys(): void
|
|
{
|
|
$redis = $this->getClient();
|
|
$options = ['cas' => true, 'watch' => ['{foo}foo', '{foo}bar', '{foo}baz']];
|
|
|
|
$response = $redis->transaction($options, static function (MultiExec $tx) {
|
|
$tx->multi();
|
|
$tx->set('{foo}foo', 'value');
|
|
$tx->set('{foo}bar', 'value');
|
|
$tx->set('{foo}baz', 'value');
|
|
$tx->unwatch();
|
|
});
|
|
|
|
$this->assertEquals(['OK', 'OK', 'OK', 'OK'], $response);
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @return void
|
|
* @requiresRedisVersion >= 3.0.0
|
|
*/
|
|
public function testThrowsExceptionOnWATCHedKeysPointsToDifferentSlots(): void
|
|
{
|
|
$redis = $this->getClient();
|
|
$options = ['cas' => true, 'watch' => ['foo_bar_baz', '{foo}bar', '{foo}baz']];
|
|
|
|
$this->expectException(TransactionException::class);
|
|
$this->expectExceptionMessage('WATCHed keys should point to the same hash slot');
|
|
|
|
$redis->transaction($options, static function (MultiExec $tx) {
|
|
$tx->multi();
|
|
$tx->set('{foo}foo', 'value');
|
|
$tx->set('{foo}bar', 'value');
|
|
$tx->set('{foo}baz', 'value');
|
|
});
|
|
}
|
|
|
|
/**
|
|
* @group connected
|
|
* @group cluster
|
|
* @return void
|
|
* @requiresRedisVersion >= 3.0.0
|
|
*/
|
|
public function testThrowsExceptionOnTransactionContextPointsToDifferentSlots(): void
|
|
{
|
|
$redis = $this->getClient();
|
|
$options = ['cas' => true, 'watch' => ['{foo}foo', '{foo}bar', '{foo}baz']];
|
|
|
|
$this->expectException(AbortedMultiExecException::class);
|
|
$this->expectExceptionMessage(
|
|
'To be able to execute a transaction against cluster, all commands should operate on the same hash slot'
|
|
);
|
|
|
|
$redis->transaction($options, static function (MultiExec $tx) {
|
|
$tx->multi();
|
|
$tx->set('{foo}foo', 'value');
|
|
$tx->set('{foo}bar', 'value');
|
|
$tx->set('foo_bar_baz', 'value');
|
|
});
|
|
}
|
|
|
|
// ******************************************************************** //
|
|
// ---- HELPER METHODS ------------------------------------------------ //
|
|
// ******************************************************************** //
|
|
|
|
/**
|
|
* Returns a mocked instance of Predis\Connection\NodeConnectionInterface
|
|
* using the specified callback to return values from executeCommand().
|
|
*
|
|
* @param callable $executeCallback
|
|
*
|
|
* @return NodeConnectionInterface|MockObject
|
|
*/
|
|
protected function getMockedConnection(callable $executeCallback)
|
|
{
|
|
$connection = $this->getMockBuilder('Predis\Connection\NodeConnectionInterface')->getMock();
|
|
$connection
|
|
->expects($this->any())
|
|
->method('executeCommand')
|
|
->willReturnCallback($executeCallback);
|
|
|
|
$connection
|
|
->method('getParameters')
|
|
->willReturn(new Parameters(['protocol' => 2]));
|
|
|
|
$connection
|
|
->method('isConnected')
|
|
->willReturn(true);
|
|
|
|
return $connection;
|
|
}
|
|
|
|
/**
|
|
* Returns a mocked instance of Predis\Transaction\MultiExec using
|
|
* the specified callback to return values from the executeCommand method
|
|
* of the underlying connection.
|
|
*
|
|
* @param callable $executeCallback
|
|
* @param array $txOpts
|
|
* @param array $clientOpts
|
|
*
|
|
* @return MultiExec
|
|
*/
|
|
protected function getMockedTransaction($executeCallback, $txOpts = null, $clientOpts = null): MultiExec
|
|
{
|
|
$connection = $this->getMockedConnection($executeCallback);
|
|
|
|
$connection
|
|
->method('getParameters')
|
|
->willReturn(new Parameters(['protocol' => 2]));
|
|
|
|
$client = new Client($connection, $clientOpts ?: []);
|
|
$transaction = new MultiExec($client, $txOpts ?: []);
|
|
|
|
return $transaction;
|
|
}
|
|
|
|
/**
|
|
* Returns an instance of Predis\Transaction\MultiExec running against a
|
|
* mocked cluster, using the specified callback to return values from the
|
|
* executeCommand method of the node connection holding the transaction.
|
|
*
|
|
* @param callable $executeCallback
|
|
* @param array $txOpts
|
|
*
|
|
* @return MultiExec
|
|
*/
|
|
protected function getMockedClusterTransaction($executeCallback, $txOpts = null): MultiExec
|
|
{
|
|
$cluster = $this->getMockBuilder(ClusterInterface::class)->getMock();
|
|
$cluster
|
|
->method('getClusterStrategy')
|
|
->willReturn(new RedisStrategy());
|
|
$connection = $this->getMockedConnection($executeCallback);
|
|
|
|
$cluster
|
|
->method('getConnectionByCommand')
|
|
->willReturn($connection);
|
|
$cluster
|
|
->method('getParameters')
|
|
->willReturn(new Parameters(['protocol' => 2]));
|
|
$cluster
|
|
->method('executeCommand')
|
|
->willReturnCallback(static function (CommandInterface $command) use ($connection) {
|
|
return $connection->executeCommand($command);
|
|
});
|
|
|
|
return new MultiExec(new Client($cluster), $txOpts ?: []);
|
|
}
|
|
|
|
/**
|
|
* Returns a callback emulating a server-side MULTI/EXEC context.
|
|
*
|
|
* @param ?array $expected List of expected responses
|
|
* @param ?array $commands Reference to an array storing the whole flow of commands
|
|
* @param ?array $cas Reference to an array storing CAS operations performed by the transaction
|
|
*
|
|
* @return callable
|
|
*/
|
|
protected function getExecuteCallback(
|
|
?array $expected = [],
|
|
?array &$commands = [],
|
|
?array &$cas = []
|
|
): callable {
|
|
$multi = $watch = $abort = false;
|
|
|
|
return static function (CommandInterface $command) use (&$expected, &$commands, &$cas, &$multi, &$watch, &$abort) {
|
|
$cmd = $command->getId();
|
|
|
|
if ($multi || $cmd === 'MULTI') {
|
|
$commands[] = $command;
|
|
} else {
|
|
$cas[] = $command;
|
|
}
|
|
|
|
switch ($cmd) {
|
|
case 'WATCH':
|
|
if ($multi) {
|
|
return new Response\Error("ERR $cmd inside MULTI is not allowed");
|
|
}
|
|
|
|
return $watch = true;
|
|
|
|
case 'MULTI':
|
|
if ($multi) {
|
|
return new Response\Error('ERR MULTI calls can not be nested');
|
|
}
|
|
|
|
return $multi = true;
|
|
|
|
case 'EXEC':
|
|
if (!$multi) {
|
|
return new Response\Error("ERR $cmd without MULTI");
|
|
}
|
|
|
|
$watch = $multi = false;
|
|
|
|
if ($abort) {
|
|
$commands = $cas = [];
|
|
$abort = false;
|
|
|
|
return;
|
|
}
|
|
|
|
return $expected;
|
|
|
|
case 'DISCARD':
|
|
if (!$multi) {
|
|
return new Response\Error("ERR $cmd without MULTI");
|
|
}
|
|
|
|
$watch = $multi = false;
|
|
|
|
return true;
|
|
|
|
case 'ECHO':
|
|
@[$trigger] = $command->getArguments();
|
|
if (strpos($trigger, 'ERR ') === 0) {
|
|
throw new Response\ServerException($trigger);
|
|
}
|
|
|
|
if ($trigger === '!!ABORT!!' && $multi) {
|
|
$abort = true;
|
|
}
|
|
|
|
return new Response\Status('QUEUED');
|
|
|
|
case 'UNWATCH':
|
|
$watch = false;
|
|
// no break
|
|
|
|
default:
|
|
return $multi ? new Response\Status('QUEUED') : 'DUMMY_RESPONSE';
|
|
}
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Returns a callback emulating a server-side MULTI/EXEC context that
|
|
* rejects SET with a single argument while queueing it.
|
|
*
|
|
* @param ?array $commands Reference to an array storing the whole flow of commands
|
|
* @param ?array $expected List of expected responses
|
|
*
|
|
* @return callable
|
|
*/
|
|
protected function getQueueErrorCallback(?array &$commands = [], ?array $expected = null): callable
|
|
{
|
|
$callback = $this->getExecuteCallback($expected, $commands);
|
|
|
|
return static function (CommandInterface $command) use ($callback) {
|
|
$response = $callback($command);
|
|
|
|
if ($command->getId() === 'SET' && count($command->getArguments()) === 1) {
|
|
return new Response\Error("ERR wrong number of arguments for 'set' command");
|
|
}
|
|
|
|
return $response;
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Wraps a callback emulating a server-side MULTI/EXEC context, so that GET
|
|
* on a key named "hash" fails with WRONGTYPE.
|
|
*
|
|
* @param callable $callback
|
|
*
|
|
* @return callable
|
|
*/
|
|
protected function getWrongTypeCallback(callable $callback): callable
|
|
{
|
|
return static function (CommandInterface $command) use ($callback) {
|
|
$response = $callback($command);
|
|
$arguments = $command->getArguments();
|
|
|
|
if ($command->getId() === 'GET' && substr($arguments[0], -4) === 'hash') {
|
|
return new Response\Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
}
|
|
|
|
return $response;
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Converts an array of command instances to an array of command IDs.
|
|
*
|
|
* @param CommandInterface[] $commands List of commands instances
|
|
*
|
|
* @return array
|
|
*/
|
|
protected static function commandsToIDs(array $commands): array
|
|
{
|
|
return array_map(static function ($cmd) { return $cmd->getId(); }, $commands);
|
|
}
|
|
|
|
/**
|
|
* Returns a client instance connected to the specified Redis
|
|
* server instance to perform integration tests.
|
|
*
|
|
* @param array $parameters Additional connection parameters
|
|
* @param array $options Additional client options
|
|
*
|
|
* @return ClientInterface
|
|
*/
|
|
protected function getClient(array $parameters = [], array $options = []): ClientInterface
|
|
{
|
|
return $this->createClient($parameters, $options);
|
|
}
|
|
}
|