Skip to content

[Serializer] [WIP] Add cache warmer for normalizer cache #39853

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\CacheWarmer;

use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Serializer\Cache\CacheNormalizationProviderInterface;
use Symfony\Component\Serializer\Normalizer\Chooser\CacheNormalizerChooser;
use Symfony\Component\Serializer\Normalizer\Chooser\NormalizerChooser;
use Symfony\Component\Serializer\Normalizer\Chooser\NormalizerChooserInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class SerializerNormalizerChooserCacheWarmer extends AbstractPhpFileCacheWarmer
{
private $normalizers;
private $normalizationProviders;
private $decoratedNormalizerChooser;

public function __construct(array $normalizers, array $normalizationProviders, string $phpArrayFile, NormalizerChooserInterface $decoratedNormalizerChooser)
{
parent::__construct($phpArrayFile);
$this->normalizers = $normalizers;
$this->normalizationProviders = $normalizationProviders;
$this->decoratedNormalizerChooser = $decoratedNormalizerChooser;
}

protected function doWarmUp(string $cacheDir, ArrayAdapter $arrayAdapter)
{
$normalizerChooser = new CacheNormalizerChooser($this->decoratedNormalizerChooser, $arrayAdapter);

foreach ($this->normalizationProviders as $normalizationProvider) {
if (!$normalizationProvider instanceof CacheNormalizationProviderInterface) {
continue;
}

foreach ($normalizationProvider->provide() as $normalizationContext) {
$format = $normalizationContext[0];
$data = $normalizationContext[1];
$context = $normalizationContext[2] ?? [];

$normalizerChooser->chooseNormalizer($this->normalizers, $data, $format, $context);
$normalizerChooser->chooseDenormalizer($this->normalizers, $data, get_class($data), $format, $context);
}
}

return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\PriorityTaggedServiceTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class SerializerNormalizationCachePass implements CompilerPassInterface
{
use PriorityTaggedServiceTrait;

private $cacheWarmerService;
private $normalizerTag;
private $cacheNormalizationProviderTag;

public function __construct(string $cacheWarmerService = 'serializer.normalizer_chooser.cache_warmer', string $normalizerTag = 'serializer.normalizer', string $cacheNormalizationProviderTag = 'serializer.normalizer_chooser.cache.provider')
{
$this->cacheWarmerService = $cacheWarmerService;
$this->normalizerTag = $normalizerTag;
$this->cacheNormalizationProviderTag = $cacheNormalizationProviderTag;
}

public function process(ContainerBuilder $container)
{
$cacheWarmer = $container->getDefinition($this->cacheWarmerService);
$normalizers = $this->findAndSortTaggedServices($this->normalizerTag, $container);
$providers = $this->findAndSortTaggedServices($this->cacheNormalizationProviderTag, $container);
$cacheWarmer->setArgument(0, $normalizers);
$cacheWarmer->setArgument(1, $providers);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@
use Symfony\Component\Routing\Loader\AnnotationFileLoader;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Serializer\Cache\CacheNormalizationProviderInterface;
use Symfony\Component\Serializer\Encoder\DecoderInterface;
use Symfony\Component\Serializer\Encoder\EncoderInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
Expand Down Expand Up @@ -525,6 +526,8 @@ public function load(array $configs, ContainerBuilder $container)
->addTag('mime.mime_type_guesser');
$container->registerForAutoconfiguration(LoggerAwareInterface::class)
->addMethodCall('setLogger', [new Reference('logger')]);
$container->registerForAutoconfiguration(CacheNormalizationProviderInterface::class)
->addTag('serializer.normalizer_chooser.cache.provider');

if (!$container->getParameter('kernel.debug')) {
// remove tagged iterator argument for resource checkers
Expand Down
2 changes: 2 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\LoggingTranslatorPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ProfilerPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\RemoveUnusedSessionMarshallingHandlerPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\SerializerNormalizationCachePass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\SessionPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\TestServiceContainerRealRefPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\TestServiceContainerWeakRefPass;
Expand Down Expand Up @@ -140,6 +141,7 @@ public function build(ContainerBuilder $container)
$this->addCompilerPassIfExists($container, TranslationDumperPass::class);
$container->addCompilerPass(new FragmentRendererPass());
$this->addCompilerPassIfExists($container, SerializerPass::class);
$this->addCompilerPassIfExists($container, SerializerNormalizationCachePass::class);
$this->addCompilerPassIfExists($container, PropertyInfoPass::class);
$container->addCompilerPass(new DataCollectorTranslatorPass());
$container->addCompilerPass(new ControllerArgumentValueResolverPass());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Psr\Cache\CacheItemPoolInterface;
use Symfony\Bundle\FrameworkBundle\CacheWarmer\SerializerCacheWarmer;
use Symfony\Bundle\FrameworkBundle\CacheWarmer\SerializerNormalizerChooserCacheWarmer;
use Symfony\Component\Cache\Adapter\PhpArrayAdapter;
use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer;
use Symfony\Component\ErrorHandler\ErrorRenderer\SerializerErrorRenderer;
Expand All @@ -32,6 +33,9 @@
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\Chooser\CacheNormalizerChooser;
use Symfony\Component\Serializer\Normalizer\Chooser\NormalizerChooser;
use Symfony\Component\Serializer\Normalizer\Chooser\NormalizerChooserInterface;
use Symfony\Component\Serializer\Normalizer\ConstraintViolationListNormalizer;
use Symfony\Component\Serializer\Normalizer\DataUriNormalizer;
use Symfony\Component\Serializer\Normalizer\DateIntervalNormalizer;
Expand All @@ -52,13 +56,15 @@

return static function (ContainerConfigurator $container) {
$container->parameters()
->set('serializer.mapping.cache.file', '%kernel.cache_dir%/serialization.php')
->set('serializer.mapping.cache.file', '%kernel.cache_dir%/serialization.mapping.php')
->set('serializer.normalizer_chooser.cache.file', '%kernel.cache_dir%/serialization.normalization.php')
;

$container->services()
->set('serializer', Serializer::class)
->public()
->args([[], []])
->call('setNormalizerChooser', [service('serializer.normalizer_chooser')])
->tag('container.private', ['package' => 'symfony/framework-bundle', 'version' => '5.2'])

->alias(SerializerInterface::class, 'serializer')
Expand Down Expand Up @@ -143,6 +149,12 @@
->set('serializer.denormalizer.array', ArrayDenormalizer::class)
->tag('serializer.normalizer', ['priority' => -990])

// Normalizer chooser
->set('serializer.normalizer_chooser', NormalizerChooser::class)
->args([service('serializer'), service('serializer')])

->alias(NormalizerChooserInterface::class, 'serializer.normalizer_chooser')

// Loader
->set('serializer.mapping.chain_loader', LoaderChain::class)
->args([[]])
Expand All @@ -169,6 +181,26 @@
service('serializer.mapping.cache.symfony'),
])

->set('serializer.normalizer_chooser.cache_warmer', SerializerNormalizerChooserCacheWarmer::class)
->args([
[],
abstract_arg('The normalization providers'),
param('serializer.normalizer_chooser.cache.file'),
service('serializer.normalizer_chooser.cache.inner'),
])
->tag('kernel.cache_warmer')

->set('serializer.normalizer_chooser.cache.symfony', CacheItemPoolInterface::class)
->factory([PhpArrayAdapter::class, 'create'])
->args([param('serializer.normalizer_chooser.cache.file'), service('cache.serializer')])

->set('serializer.normalizer_chooser.cache', CacheNormalizerChooser::class)
->decorate('serializer.normalizer_chooser')
->args([
service('serializer.normalizer_chooser.cache.inner'),
service('serializer.normalizer_chooser.cache.symfony')
])

// Encoders
->set('serializer.encoder.xml', XmlEncoder::class)
->tag('serializer.encoder')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\Tests\CacheWarmer;

use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\CacheWarmer\SerializerNormalizerChooserCacheWarmer;
use Symfony\Component\Cache\Adapter\NullAdapter;
use Symfony\Component\Cache\Adapter\PhpArrayAdapter;
use Symfony\Component\Serializer\Cache\CacheNormalizationProviderInterface;
use Symfony\Component\Serializer\Normalizer\Chooser\NormalizerChooserInterface;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

class SerializerNormalizerChooserCacheWarmerTest extends TestCase
{
public function testWarmUp()
{
$file = sys_get_temp_dir().'/serializer.normalization.php';
@unlink($file);

$provider1 = $this->createMock(CacheNormalizationProviderInterface::class);
$provider1->method('provide')->willReturnCallback(function () {
yield ['json', new \stdClass()];
yield ['xml', new \stdClass(), ['foo' => 'bar']];
yield ['xml', new \DateTime()];
});

$provider2 = $this->createMock(CacheNormalizationProviderInterface::class);
$provider2->method('provide')->willReturnCallback(function () {
yield ['yaml', new \stdClass()];
yield ['json', new \DateTime()];
});

$dateTimeNormalizer = new DateTimeNormalizer();
$objectNormalizer = new ObjectNormalizer();

$decoratedNormalizerChooser = $this->createMock(NormalizerChooserInterface::class);
$decoratedNormalizerChooser->method('chooseNormalizer')->willReturn();
$decoratedNormalizerChooser->method('chooseDenormalizer')->willReturn();

$cacheWarmer = new SerializerNormalizerChooserCacheWarmer(
[$dateTimeNormalizer, $objectNormalizer],
[$provider1, $provider2],
$file
);

$cacheWarmer->warmUp(\dirname($file));
$this->assertFileExists($file);

$arrayPool = new PhpArrayAdapter($file, new NullAdapter());
$compiledContext = hash('md5', json_encode(['foo' => 'bar']));

foreach (['normalizer', 'denormalizer'] as $action) {
$this->assertSame(1, $arrayPool->getItem("{$action}_json_stdClass")->get());
$this->assertSame(1, $arrayPool->getItem("{$action}_xml_stdClass_$compiledContext")->get());
$this->assertSame(0, $arrayPool->getItem("{$action}_xml_DateTime")->get());
$this->assertSame(1, $arrayPool->getItem("{$action}_yaml_stdClass")->get());
$this->assertSame(0, $arrayPool->getItem("{$action}_json_DateTime")->get());
}
}
}
4 changes: 2 additions & 2 deletions src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
"symfony/security-bundle": "^5.1",
"symfony/security-csrf": "^4.4|^5.0",
"symfony/security-http": "^4.4|^5.0",
"symfony/serializer": "^5.2",
"symfony/serializer": "^5.3",
"symfony/stopwatch": "^4.4|^5.0",
"symfony/string": "^5.0",
"symfony/translation": "^5.0",
Expand Down Expand Up @@ -85,7 +85,7 @@
"symfony/mime": "<4.4",
"symfony/property-info": "<4.4",
"symfony/property-access": "<5.2",
"symfony/serializer": "<5.2",
"symfony/serializer": "<5.3",
"symfony/stopwatch": "<4.4",
"symfony/translation": "<5.0",
"symfony/twig-bridge": "<4.4",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\Cache;

interface CacheNormalizationProviderInterface
{
public function provide(): \Generator;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\Normalizer\Chooser;

use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class CacheNormalizerChooser implements NormalizerChooserInterface
{
private $decorated;
private $cacheItemPool;
private $loadedNormalizers;
private $loadedDenormalizers;

public function __construct(NormalizerChooserInterface $decorated, CacheItemPoolInterface $cacheItemPool)
{
$this->decorated = $decorated;
$this->cacheItemPool = $cacheItemPool;
}

public function chooseNormalizer(array $normalizers, $data, ?string $format = null, array $context = []): ?NormalizerInterface
{
$type = \is_object($data) ? \get_class($data) : 'native-'.\gettype($data);
$type = str_replace('\\', '-', $type);
$key = $this->generateKey(true, $type, $format, $context);

if (isset($this->loadedNormalizers[$key])) {
return $this->loadedNormalizers[$key];
}

$item = $this->cacheItemPool->getItem($key);

if ($item->isHit()) {
return $this->loadedNormalizers[$key] = $normalizers[$item->get()];
}

$normalizer = $this->loadedNormalizers[$key] = $this->decorated->chooseNormalizer($normalizers, $data, $format, $context);
$this->cacheItemPool->save($item->set(array_search($normalizer, $normalizers)));

return $normalizer;
}

public function chooseDenormalizer(array $denormalizers, $data, string $class, ?string $format = null, array $context = []): ?DenormalizerInterface
{
$type = str_replace('\\', '-', $class);
$key = $this->generateKey(false, $type, $format, $context);

if (isset($this->loadedDenormalizers[$key])) {
return $this->loadedDenormalizers[$key];
}

$item = $this->cacheItemPool->getItem($key);

if ($item->isHit()) {
return $this->loadedDenormalizers[$key] = $denormalizers[$item->get()];
}

$denormalizer = $this->loadedDenormalizers[$key] = $this->decorated->chooseDenormalizer($denormalizers, $data, $class, $format, $context);
$this->cacheItemPool->save($item->set(array_search($denormalizer, $denormalizers)));

return $denormalizer;
}

private function generateKey(bool $normalize, string $type, ?string $format, array $context = []): string
{
$compiledFormat = null !== $format ? '_'.$format : '';
$compiledContext = count($context) ? '_'.hash('md5', json_encode($context)) : '';

return sprintf('%s%s_%s%s', $normalize ? 'normalizer' : 'denormalizer', $compiledFormat, $type, $compiledContext);
}
}
Loading