Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Allow changing readPreference for MongoDB lock store
  • Loading branch information
notrix committed Jul 9, 2025
commit 9097063f952332c3766f16859d3056c42aa44438
16 changes: 13 additions & 3 deletions src/Symfony/Component/Lock/Store/MongoDbStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use MongoDB\Driver\Exception\BulkWriteException;
use MongoDB\Driver\Manager;
use MongoDB\Driver\Query;
use MongoDB\Driver\ReadPreference;
use MongoDB\Exception\DriverRuntimeException;
use MongoDB\Exception\InvalidArgumentException as MongoInvalidArgumentException;
use MongoDB\Exception\UnsupportedException;
Expand Down Expand Up @@ -108,21 +109,26 @@ public function __construct(Collection|Database|Client|Manager|string $mongo, ar
'collection' => null,
'uriOptions' => [],
'driverOptions' => [],
'readPreference' => null,
], $options);

$this->initialTtl = $initialTtl;

if ($mongo instanceof Collection) {
$this->manager = $mongo->getManager();
$this->options['database'] ??= $mongo->getDatabaseName();
$this->options['collection'] ??= $mongo->getCollectionName();
$this->manager = $mongo->getManager();
$this->options['readPreference'] ??= $mongo->getReadPreference();
} elseif ($mongo instanceof Database) {
$this->options['database'] ??= $mongo->getDatabaseName();
$this->manager = $mongo->getManager();
$this->options['database'] ??= $mongo->getDatabaseName();
$this->options['readPreference'] ??= $this->manager->getReadPreference();
} elseif ($mongo instanceof Client) {
$this->manager = $mongo->getManager();
$this->options['readPreference'] ??= $this->manager->getReadPreference();
} elseif ($mongo instanceof Manager) {
$this->manager = $mongo;
$this->options['readPreference'] ??= $this->manager->getReadPreference();
} else {
$this->uri = $this->skimUri($mongo);
}
Expand All @@ -142,6 +148,10 @@ public function __construct(Collection|Database|Client|Manager|string $mongo, ar
if ($this->initialTtl <= 0) {
throw new InvalidTtlException(sprintf('"%s()" expects a strictly positive TTL, got "%d".', __METHOD__, $this->initialTtl));
}

if (!empty($this->options['readPreference']) && !$this->options['readPreference'] instanceof ReadPreference) {
throw new InvalidArgumentException(sprintf('"%s()" expects a MongoDB\Driver\ReadPreference instance, got "%s".', __METHOD__, get_debug_type($this->options['readPreference'])));
}
}

/**
Expand Down Expand Up @@ -303,7 +313,7 @@ public function exists(Key $key): bool
'limit' => 1,
'projection' => ['_id' => 1],
]
));
), array_filter(['readPreference' => $this->options['readPreference']]));

return [] !== $cursor->toArray();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use MongoDB\Collection;
use MongoDB\Driver\Manager;
use MongoDB\Driver\ReadPreference;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Lock\Store\MongoDbStore;
use Symfony\Component\Lock\Store\StoreFactory;
Expand All @@ -38,6 +39,9 @@ public function testCreateMongoDbCollectionStore()
$collection->expects($this->once())
->method('getDatabaseName')
->willReturn('test');
$collection->expects($this->once())
->method('getReadPreference')
->willReturn(new ReadPreference('primary'));

$store = StoreFactory::createStore($collection);

Expand Down
55 changes: 53 additions & 2 deletions src/Symfony/Component/Lock/Tests/Store/MongoDbStoreTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use MongoDB\Driver\Command;
use MongoDB\Driver\Exception\ConnectionTimeoutException;
use MongoDB\Driver\Manager;
use MongoDB\Driver\ReadPreference;
use Symfony\Component\Lock\Exception\InvalidArgumentException;
use Symfony\Component\Lock\Key;
use Symfony\Component\Lock\PersistingStoreInterface;
Expand Down Expand Up @@ -46,9 +47,9 @@ public static function setUpBeforeClass(): void
}
}

private static function getMongoManager(): Manager
private static function getMongoManager(array $uriOptions = []): Manager
{
return new Manager('mongodb://'.getenv('MONGODB_HOST'));
return new Manager('mongodb://'.getenv('MONGODB_HOST'), $uriOptions);
}

protected function getClockDelay(): int
Expand Down Expand Up @@ -103,6 +104,53 @@ public static function provideConstructorArgs()
yield ['mongodb://localhost/', ['database' => 'test', 'collection' => 'lock']];
}

public function testReadPreferenceWithManagerOnSecondary()
{
$mongo = self::getMongoManager(['readPreference' => 'secondary']);

$store = new MongoDbStore(
$mongo,
['database' => 'test', 'collection' => 'lock', 'readPreference' => new ReadPreference('primary')]
);

// Use reflection to access the private options property
$reflection = new \ReflectionObject($store);
$optionsProperty = $reflection->getProperty('options');
$options = $optionsProperty->getValue($store);

// Assert that the readPreference is set to primary
$this->assertInstanceOf(ReadPreference::class, $options['readPreference']);
$this->assertEquals('primary', $options['readPreference']->getModeString());
}

public function testReadPreferenceWithCollectionOnNearest()
{
$collection = $this->createMock(Collection::class);
$collection->expects($this->once())
->method('getManager')
->willReturn(self::getMongoManager(['readPreference' => 'primary']));
$collection->expects($this->once())
->method('getDatabaseName')
->willReturn('test');
$collection->expects($this->once())
->method('getCollectionName')
->willReturn('lock');
$collection->expects($this->once())
->method('getReadPreference')
->willReturn(new ReadPreference('nearest'));

$store = new MongoDbStore($collection, []);

// Use reflection to access the private options property
$reflection = new \ReflectionObject($store);
$optionsProperty = $reflection->getProperty('options');
$options = $optionsProperty->getValue($store);

// Assert that the readPreference is set to primary
$this->assertInstanceOf(ReadPreference::class, $options['readPreference']);
$this->assertEquals('nearest', $options['readPreference']->getModeString());
}

public function testConstructWithClient()
{
$client = $this->createMock(Client::class);
Expand Down Expand Up @@ -138,6 +186,9 @@ public function testConstructWithCollection()
$collection->expects($this->once())
->method('getCollectionName')
->willReturn('lock');
$collection->expects($this->once())
->method('getReadPreference')
->willReturn(new ReadPreference('primary'));

$this->testConstructionMethods($collection, []);
}
Expand Down
3 changes: 3 additions & 0 deletions src/Symfony/Component/Lock/Tests/Store/stubs/mongodb.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace MongoDB;

use MongoDB\Driver\Manager;
use MongoDB\Driver\ReadPreference;

/*
* Stubs for the mongodb/mongodb library version ~1.16
Expand Down Expand Up @@ -40,5 +41,7 @@ abstract public function getManager(): Manager;
abstract public function getCollectionName(): string;

abstract public function getDatabaseName(): string;

abstract public function getReadPreference(): ReadPreference;
}
}
Loading