Skip to content

Commit

Permalink
Merge branch '4.4.x' into add-psr6-compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
IonBazan authored Oct 1, 2021
2 parents 7b77663 + deeeff0 commit 052ff4d
Show file tree
Hide file tree
Showing 13 changed files with 278 additions and 40 deletions.
76 changes: 76 additions & 0 deletions APM/StopwatchCommandLogger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

declare(strict_types=1);

namespace Doctrine\Bundle\MongoDBBundle\APM;

use Doctrine\ODM\MongoDB\APM\CommandLoggerInterface;
use MongoDB\Driver\Monitoring\CommandFailedEvent;
use MongoDB\Driver\Monitoring\CommandStartedEvent;
use MongoDB\Driver\Monitoring\CommandSucceededEvent;
use Symfony\Component\Stopwatch\Stopwatch;

use function MongoDB\Driver\Monitoring\addSubscriber;
use function MongoDB\Driver\Monitoring\removeSubscriber;
use function sprintf;

final class StopwatchCommandLogger implements CommandLoggerInterface
{
/** @var bool */
private $registered = false;

/** @var Stopwatch|null */
private $stopwatch;

public function __construct(?Stopwatch $stopwatch)
{
$this->stopwatch = $stopwatch;
}

public function register(): void
{
if ($this->stopwatch === null || $this->registered) {
return;
}

$this->registered = true;
addSubscriber($this);
}

public function unregister(): void
{
if (! $this->registered) {
return;
}

removeSubscriber($this);
$this->registered = false;
}

public function commandStarted(CommandStartedEvent $event)
{
if (! $this->stopwatch) {
return;
}

$this->stopwatch->start(sprintf('mongodb_%s', $event->getRequestId()), 'doctrine_mongodb');
}

public function commandSucceeded(CommandSucceededEvent $event)
{
if (! $this->stopwatch) {
return;
}

$this->stopwatch->stop(sprintf('mongodb_%s', $event->getRequestId()));
}

public function commandFailed(CommandFailedEvent $event)
{
if (! $this->stopwatch) {
return;
}

$this->stopwatch->stop(sprintf('mongodb_%s', $event->getRequestId()));
}
}
11 changes: 11 additions & 0 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -305,9 +305,20 @@ private function addConnectionsSection(ArrayNodeDefinition $rootNode)
->end()
->integerNode('socketTimeoutMS')->end()
->booleanNode('ssl')->end()
->booleanNode('tls')->end()
->booleanNode('tlsAllowInvalidCertificates')->end()
->booleanNode('tlsAllowInvalidHostnames')->end()
->scalarNode('tlsCAFile')->end()
->scalarNode('tlsCertificateKeyFile')->end()
->scalarNode('tlsCertificateKeyFilePassword')->end()
->booleanNode('tlsDisableCertificateRevocationCheck')->end()
->booleanNode('tlsDisableOCSPEndpointCheck')->end()
->booleanNode('tlsInsecure')->end()
->scalarNode('username')
->validate()->ifNull()->thenUnset()->end()
->end()
->booleanNode('retryReads')->end()
->booleanNode('retryWrites')->end()
->scalarNode('w')->end()
->integerNode('wTimeoutMS')->end()
// Deprecated options
Expand Down
27 changes: 23 additions & 4 deletions DependencyInjection/DoctrineMongoDBExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\MemcachedAdapter;
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\Config\Definition\BaseNode;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ChildDefinition;
Expand All @@ -36,6 +37,7 @@
use function class_implements;
use function in_array;
use function interface_exists;
use function method_exists;
use function reset;
use function sprintf;

Expand Down Expand Up @@ -241,16 +243,25 @@ protected function loadDocumentManager(array $documentManager, $defaultDM, $defa
$methods['setPersistentCollectionFactory'] = new Reference($documentManager['persistent_collection_factory']);
}

$container->getAlias('doctrine_mongodb.odm.command_logger')
->setDeprecated(...$this->buildDeprecationArgs(
'4.4',
'The service %alias_id% is deprecated and will be dropped in DoctrineMongoDBBundle 5.0. Use "doctrine_mongodb.odm.psr_command_logger" instead.'
));

// logging
if ($container->getParameterBag()->resolveValue($documentManager['logging'])) {
$logger = $container->getDefinition('doctrine_mongodb.odm.command_logger');
$logger->addTag('doctrine_mongodb.odm.command_logger');
$container->getDefinition('doctrine_mongodb.odm.psr_command_logger')
->addTag('doctrine_mongodb.odm.command_logger');
}

// profiler
if ($container->getParameterBag()->resolveValue($documentManager['profiler']['enabled'])) {
$logger = $container->getDefinition('doctrine_mongodb.odm.data_collector.command_logger');
$logger->addTag('doctrine_mongodb.odm.command_logger');
$container->getDefinition('doctrine_mongodb.odm.data_collector.command_logger')
->addTag('doctrine_mongodb.odm.command_logger');

$container->getDefinition('doctrine_mongodb.odm.stopwatch_command_logger')
->addTag('doctrine_mongodb.odm.command_logger');

$container
->getDefinition('doctrine_mongodb.odm.data_collector')
Expand Down Expand Up @@ -592,4 +603,12 @@ protected function loadCacheDriver($cacheName, $objectManagerName, array $cacheD

return $cacheDriverServiceId;
}

private function buildDeprecationArgs(string $version, string $message): array
{
// @todo Remove when support for Symfony 5.1 and older is dropped
return method_exists(BaseNode::class, 'getDeprecation')
? ['doctrine/mongodb-odm-bundle', $version, $message]
: [$message];
}
}
8 changes: 7 additions & 1 deletion Resources/config/mongodb.xml
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,13 @@
<argument type="tagged" tag="doctrine_mongodb.odm.command_logger" />
</service>

<service id="doctrine_mongodb.odm.command_logger" class="Doctrine\Bundle\MongoDBBundle\APM\PSRCommandLogger" public="false">
<service id="doctrine_mongodb.odm.stopwatch_command_logger" class="Doctrine\Bundle\MongoDBBundle\APM\StopwatchCommandLogger" public="false">
<argument type="service" id="debug.stopwatch" on-invalid="null" />
</service>

<service id="doctrine_mongodb.odm.command_logger" alias="doctrine_mongodb.odm.psr_command_logger" />

<service id="doctrine_mongodb.odm.psr_command_logger" class="Doctrine\Bundle\MongoDBBundle\APM\PSRCommandLogger" public="false">
<argument type="service" id="logger" on-invalid="null" />

<tag name="monolog.logger" channel="doctrine" />
Expand Down
11 changes: 11 additions & 0 deletions Resources/config/schema/mongodb-1.0.xsd
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,19 @@
<xsd:attribute name="readPreference" type="read-preference" />
<xsd:attribute name="replicaSet" type="xsd:string" />
<xsd:attribute name="ssl" type="xsd:boolean" />
<xsd:attribute name="tls" type="xsd:boolean" />
<xsd:attribute name="tlsAllowInvalidCertificates" type="xsd:boolean" />
<xsd:attribute name="tlsAllowInvalidHostnames" type="xsd:boolean" />
<xsd:attribute name="tlsCAFile" type="xsd:string" />
<xsd:attribute name="tlsCertificateKeyFile" type="xsd:string" />
<xsd:attribute name="tlsCertificateKeyFilePassword" type="xsd:string" />
<xsd:attribute name="tlsDisableCertificateRevocationCheck" type="xsd:boolean" />
<xsd:attribute name="tlsDisableOCSPEndpointCheck" type="xsd:boolean" />
<xsd:attribute name="tlsInsecure" type="xsd:boolean" />
<xsd:attribute name="socketTimeoutMS" type="xsd:integer" />
<xsd:attribute name="username" type="xsd:string" />
<xsd:attribute name="retryReads" type="xsd:boolean" />
<xsd:attribute name="retryWrites" type="xsd:boolean" />
<xsd:attribute name="w" type="xsd:string" />
<xsd:attribute name="wTimeoutMS" type="xsd:integer" />
<!-- deprecated options -->
Expand Down
41 changes: 25 additions & 16 deletions Resources/doc/config.rst
Original file line number Diff line number Diff line change
Expand Up @@ -576,21 +576,31 @@ Full Default Configuration
id:
server: ~
options:
authMechanism: ~
connect: ~
connectTimeoutMS: ~
db: ~
authSource: ~
journal: ~
password: ~
readPreference: ~
readPreferenceTags: ~
replicaSet: ~ # replica set name
socketTimeoutMS: ~
ssl: ~
username: ~
w: ~
wTimeoutMS: ~
authMechanism: ~
connectTimeoutMS: ~
db: ~
authSource: ~
journal: ~
password: ~
readPreference: ~
readPreferenceTags: ~
replicaSet: ~ # replica set name
socketTimeoutMS: ~
ssl: ~
tls: ~
tlsAllowInvalidCertificates: ~
tlsAllowInvalidHostnames: ~
tlsCAFile: ~
tlsCertificateKeyFile: ~
tlsCertificateKeyFilePassword: ~
tlsDisableCertificateRevocationCheck: ~
tlsDisableOCSPEndpointCheck: ~
tlsInsecure: ~
username: ~
retryReads: ~
retryWrites: ~
w: ~
wTimeoutMS: ~
driver_options:
context: ~ # stream context to use for connection
Expand Down Expand Up @@ -658,7 +668,6 @@ Full Default Configuration
<doctrine:connection id="conn1" server="mongodb://localhost">
<doctrine:options
authMechanism=""
connect=""
connectTimeoutMS=""
db=""
authSource=""
Expand Down
64 changes: 64 additions & 0 deletions Tests/APM/StopwatchCommandLoggerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

declare(strict_types=1);

namespace Doctrine\Bundle\MongoDBBundle\Tests\APM;

use Doctrine\Bundle\MongoDBBundle\APM\StopwatchCommandLogger;
use Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Form\Category;
use Doctrine\Bundle\MongoDBBundle\Tests\TestCase;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Component\Stopwatch\Stopwatch;

class StopwatchCommandLoggerTest extends TestCase
{
/** @var StopwatchCommandLogger */
private $commandLogger;
/** @var Stopwatch */
private $stopwatch;
/** @var DocumentManager */
private $dm;

protected function setUp(): void
{
$this->dm = TestCase::createTestDocumentManager();

$this->stopwatch = new Stopwatch(true);
$this->commandLogger = new StopwatchCommandLogger($this->stopwatch);
$this->commandLogger->register();

parent::setUp();
}

protected function tearDown(): void
{
$this->commandLogger->unregister();

$this->dm->getDocumentCollection(Category::class)->drop();

parent::tearDown();
}

public function testItLogsStopwatchEvents(): void
{
$category = new Category('one');

$this->dm->persist($category);
$this->dm->flush();

$this->dm->remove($category);
$this->dm->flush();

$this->dm->getRepository(Category::class)->findAll();
$events = $this->stopwatch->getSectionEvents('__root__');

self::assertCount(3, $events);

foreach ($events as $eventName => $stopwatchEvent) {
// @todo replace with assertMatchesRegularExpression() when PHP 7.2 is dropped
self::assertRegExp('/mongodb_\d+/', $eventName);
self::assertGreaterThan(0, $stopwatchEvent->getDuration());
self::assertSame('doctrine_mongodb', $stopwatchEvent->getCategory());
}
}
}
8 changes: 7 additions & 1 deletion Tests/ContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public function testLoggerConfig(bool $expected, array $config, bool $debug): vo
$this->container->setParameter('kernel.debug', $debug);
$this->extension->load([$config], $this->container);

$definition = $this->container->getDefinition('doctrine_mongodb.odm.command_logger');
$definition = $this->container->getDefinition('doctrine_mongodb.odm.psr_command_logger');
$this->assertSame($expected, $definition->hasTag('doctrine_mongodb.odm.command_logger'));

$this->container->compile();
Expand Down Expand Up @@ -98,9 +98,15 @@ public function testDataCollectorConfig(bool $expected, array $config, bool $deb
$this->container->setParameter('kernel.debug', $debug);
$this->extension->load([$config], $this->container);

$deprecatedLoggerDefinition = $this->container->getAlias('doctrine_mongodb.odm.command_logger');
$this->assertTrue($deprecatedLoggerDefinition->isDeprecated());

$loggerDefinition = $this->container->getDefinition('doctrine_mongodb.odm.data_collector.command_logger');
$this->assertSame($expected, $loggerDefinition->hasTag('doctrine_mongodb.odm.command_logger'));

$stopwatchLoggerDefinition = $this->container->getDefinition('doctrine_mongodb.odm.stopwatch_command_logger');
$this->assertSame($expected, $stopwatchLoggerDefinition->hasTag('doctrine_mongodb.odm.command_logger'));

$dataCollectorDefinition = $this->container->getDefinition('doctrine_mongodb.odm.data_collector');
$this->assertSame($expected, $dataCollectorDefinition->hasTag('data_collector'));

Expand Down
29 changes: 20 additions & 9 deletions Tests/DependencyInjection/ConfigurationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,15 +99,26 @@ public function testFullConfiguration(array $config): void
['dc' => 'west'],
[],
],
'replicaSet' => 'foo',
'slaveOkay' => true,
'socketTimeoutMS' => 1000,
'ssl' => true,
'authMechanism' => 'MONGODB-X509',
'authSource' => 'some_db',
'username' => 'username_val',
'w' => 'majority',
'wTimeoutMS' => 1000,
'replicaSet' => 'foo',
'slaveOkay' => true,
'socketTimeoutMS' => 1000,
'ssl' => true,
'tls' => true,
'tlsAllowInvalidCertificates' => false,
'tlsAllowInvalidHostnames' => false,
'tlsCAFile' => '/path/to/cert.pem',
'tlsCertificateKeyFile' => '/path/to/key.crt',
'tlsCertificateKeyFilePassword' => 'secret',
'tlsDisableCertificateRevocationCheck' => false,
'tlsDisableOCSPEndpointCheck' => false,
'tlsInsecure' => false,
'authMechanism' => 'MONGODB-X509',
'authSource' => 'some_db',
'username' => 'username_val',
'retryReads' => false,
'retryWrites' => false,
'w' => 'majority',
'wTimeoutMS' => 1000,
],
'driver_options' => ['context' => 'conn1_context_service'],
],
Expand Down
11 changes: 11 additions & 0 deletions Tests/DependencyInjection/Fixtures/config/xml/full.xml
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,19 @@
slaveOkay="true"
socketTimeoutMS="1000"
ssl="true"
tls="true"
tlsAllowInvalidCertificates="false"
tlsAllowInvalidHostnames="false"
tlsCAFile="/path/to/cert.pem"
tlsCertificateKeyFile="/path/to/key.crt"
tlsCertificateKeyFilePassword="secret"
tlsDisableCertificateRevocationCheck="false"
tlsDisableOCSPEndpointCheck="false"
tlsInsecure="false"
authMechanism="MONGODB-X509"
username="username_val"
retryReads="false"
retryWrites="false"
w="majority"
wTimeoutMS="1000"
>
Expand Down
Loading

0 comments on commit 052ff4d

Please sign in to comment.