diff --git a/CHANGELOG.md b/CHANGELOG.md index ec8345f2..aa61950c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ - bc break - The bundle no longer forces a `public` visibility when writing media and variation files: the visibility configured on the Flysystem storage now applies. On Amazon S3, the forced visibility made every file public through a `public-read` ACL, and failed on the buckets where ACLs are disabled. Declare `visibility: public` on your Flysystem storage if you relied on the forced visibility - bc break - `league/flysystem` 3.10 or newer is now required +- feature - Add a `store_on_create` setting to the library `cache` configuration, generating and storing all the variations of a media as soon as it is created or moved, for storage backends on which generating them lazily is costly, such as buckets. Set the `store_on_create_message_bus` setting to a Messenger bus to generate them in the background - see the [URL generation documentation](doc/misc-features/url-generation.rst) - bc break - The `imagine/imagine` package is now required, instead of suggested: the default configuration needs it to output JPEG and PNG variations - bc break - The markup generated by the `joli:Img` component changed for the variations configured with several `pixel_ratios`: it now carries a `srcset` and a `sizes` attribute. Set `autoSrcset` to `false` to restore the previous markup - bc break - The markup generated by the `joli:Img` and `joli:Source` components now carries the `width` and `height` attributes of a variation which has not been generated yet, and their `srcset` keeps the candidates which have not been generated yet, or whose conversion failed: the URL is now always output, and the variation is served on the fly when requested diff --git a/composer.json b/composer.json index b44c2019..b1eeb9b6 100644 --- a/composer.json +++ b/composer.json @@ -58,6 +58,7 @@ "sylius/ui-translations": "^0.12.0", "symfony/browser-kit": "^7.0 || ^8.0", "symfony/css-selector": "^7.0 || ^8.0", + "symfony/messenger": "^7.0 || ^8.0", "symfony/monolog-bundle": "^3.10", "symfony/stopwatch": "^7.0 || ^8.0", "symfony/ux-icons": "^2.20 || ^3.0", @@ -71,7 +72,8 @@ }, "suggest": { "ext-imagick": "required by the default \"imagick\" driver of the imagine processor", - "league/flysystem-bundle": "Ease of use with FlySystem" + "league/flysystem-bundle": "Ease of use with FlySystem", + "symfony/messenger": "Generate the variations stored on creation in the background" }, "license": "MIT", "autoload": { diff --git a/config/services.php b/config/services.php index 19f233a5..4bffbcea 100644 --- a/config/services.php +++ b/config/services.php @@ -16,12 +16,14 @@ use JoliCode\MediaBundle\Event\Listener\DeleteMediaEventListener; use JoliCode\MediaBundle\Event\Listener\MoveFolderEventListener; use JoliCode\MediaBundle\Event\Listener\MoveMediaEventListener; +use JoliCode\MediaBundle\Event\Listener\StoreVariationsEventListener; use JoliCode\MediaBundle\Event\MediaEvents; use JoliCode\MediaBundle\Inspector\DataCollector; use JoliCode\MediaBundle\Inspector\ProcessingChainInspector; use JoliCode\MediaBundle\Inspector\TransformationDataHolder; use JoliCode\MediaBundle\Library\Library; use JoliCode\MediaBundle\Library\LibraryContainer; +use JoliCode\MediaBundle\Message\StoreVariationsHandler; use JoliCode\MediaBundle\PostProcessor\Gifsicle as GifsiclePostProcessor; use JoliCode\MediaBundle\PostProcessor\Jpegoptim; use JoliCode\MediaBundle\PostProcessor\Mozjpeg; @@ -224,6 +226,23 @@ 'event' => MediaEvents::POST_MOVE_MEDIA, 'method' => 'onMediaPostMove', ]) + ->set('joli_media.event_listener.store_variations', StoreVariationsEventListener::class) + ->args([ + service('joli_media.converter'), + ]) + ->tag('kernel.event_listener', [ + 'event' => MediaEvents::POST_CREATE_MEDIA, + 'method' => 'onMediaPostCreate', + ]) + ->tag('kernel.event_listener', [ + 'event' => MediaEvents::POST_MOVE_MEDIA, + 'method' => 'onMediaPostMove', + ]) + ->set('joli_media.message_handler.store_variations', StoreVariationsHandler::class) + ->args([ + service('joli_media.converter'), + ]) + ->tag('messenger.message_handler') // library ->set('joli_media.library_container', LibraryContainer::class) diff --git a/doc/getting-started/configuration.rst b/doc/getting-started/configuration.rst index 891c9c34..45ba2e97 100644 --- a/doc/getting-started/configuration.rst +++ b/doc/getting-started/configuration.rst @@ -39,6 +39,7 @@ A library is defined by a name and contains the multiple information: - the ``flysystem`` key contains the id of a Flysystem service that addresses the location where cache media are stored. - its ``url_generator``: the configuration of the way URLs should be generated for the media variations - ``must_store_when_generating_url`` is a boolean (default: ``false``) that defines whether the media variation must be generated and stored when its URL is generated. If set to ``false``, the media variation will be generated on-the-fly when accessed for the first time. This setting can be overridden for a single variation, using the ``must_store_when_generating_url`` attribute of the variation configuration - the variations that leave it to ``null`` (the default) fall back to this library-level value. Variation clones (the ``@2x`` pixel-ratio variations and the automatic WebP alternatives) inherit the value of the variation they are cloned from. + - ``store_on_create`` is a boolean (default: ``false``) that defines whether all the variations of a media are generated and stored as soon as the media is created or moved, instead of on the fly or when their URL is generated. See `Generating the variation files on creation <../misc-features/url-generation.rst#generating-the-variation-files-on-creation>`_. To generate them in the background, set the root-level ``store_on_create_message_bus`` setting to the id of a Messenger bus (default: ``null``, generating them synchronously). - ``variations`` that can be created from the original media. See the `Variation configuration <../variations/variations.rst>`_ section for more information - ``enable_auto_webp`` is a boolean (default: ``false``) that enables the automatic generation of WebP variations for the media. When enabled, the configured variations in the ``variations`` above node will be duplicated in WebP format, in addition to the original format. diff --git a/doc/misc-features/url-generation.rst b/doc/misc-features/url-generation.rst index cad04732..64e5e046 100644 --- a/doc/misc-features/url-generation.rst +++ b/doc/misc-features/url-generation.rst @@ -105,6 +105,66 @@ Pre-signed URLs are mostly useful on private buckets. The bundle writes the medi visibility: private directory_visibility: private +Generating the variation files on creation +------------------------------------------ + +Generating variation files lazily suits a local filesystem, where checking whether a file exists is cheap, and where the application serves the files itself, so that it can generate a missing one when it is requested. Neither holds on a bucket (Amazon S3, MinIO, etc.): + +- each existence check is a request to the storage backend, so a page or an API response listing many media would send one per variation; +- the variations are often served by the storage backend itself (pre-signed URLs, a CDN), without going through the application and its ``MediaController``, so a missing variation file is never generated. + +Enable the ``store_on_create`` setting of the library's ``cache`` configuration to generate and store all the variations of a media as soon as it is created: + +.. code-block:: yaml + + # config/packages/joli_media.yaml + joli_media: + libraries: + default: + cache: + flysystem: default.cache.storage + store_on_create: true + +With this setting: + +- every variation that can be applied to the media (see the `voters <../variations/variation-voters.rst>`_) is generated, including the pixel-ratio variations and the automatic WebP alternatives. A media that no processor can read (a PDF, an SVG) is stored without variations; +- the variations are generated again at the new path when a media is moved with ``OriginalStorage::move()``, as the variations of its previous path are deleted. Moving a folder does not generate them: run the ``joli:media:convert`` command afterwards; +- the variations are generated without checking whether they already exist, so that it does not send any existence check to the storage backend; +- by default, they are generated synchronously: creating a media takes longer, and a conversion failure is not swallowed - the exception is thrown from ``createMedia()`` (the original file is stored nevertheless) or from ``move()`` (the move is rolled back). + +The setting only applies to the media created or moved after it was enabled. Generate the variations of the existing media, and those of variations added later to the configuration, with the ``joli:media:convert`` command. + +Generating them in the background +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To keep the creation of a media fast, the generation can be handed over to `Symfony Messenger `_. Name the bus to dispatch it to in the ``store_on_create_message_bus`` setting: + +.. code-block:: yaml + + # config/packages/joli_media.yaml + joli_media: + store_on_create_message_bus: messenger.default_bus + +A ``JoliCode\MediaBundle\Message\StoreVariations`` message is then dispatched for each created or moved media, instead of generating its variations right away. As with any message, Messenger handles it synchronously unless it is routed to a transport - route it to an asynchronous one to generate the variations in a worker: + +.. code-block:: yaml + + # config/packages/messenger.yaml + framework: + messenger: + transports: + async: '%env(MESSENGER_TRANSPORT_DSN)%' + routing: + JoliCode\MediaBundle\Message\StoreVariations: async + +The setting is checked when the container is compiled: it fails if the Messenger component is not installed, or if the service is not a Messenger bus. + +When the variations are generated in the background: + +- they do not exist until the worker has handled the message - a URL that bypasses the ``MediaController`` (a pre-signed URL, a CDN) points at a missing file in the meantime; +- a conversion failure follows the retry strategy of the transport, instead of being thrown from ``createMedia()`` or ``move()``; +- a media deleted or moved before its message is handled is skipped - a move dispatches a message of its own for the new path. + Twig extension -------------- diff --git a/src/DependencyInjection/Compiler/MessageBusPass.php b/src/DependencyInjection/Compiler/MessageBusPass.php new file mode 100644 index 00000000..f0b3784d --- /dev/null +++ b/src/DependencyInjection/Compiler/MessageBusPass.php @@ -0,0 +1,47 @@ +hasDefinition('joli_media.event_listener.store_variations')) { + return; + } + + $arguments = $container->getDefinition('joli_media.event_listener.store_variations')->getArguments(); + $bus = $arguments['$messageBus'] ?? null; + + if (!$bus instanceof Reference) { + return; + } + + $id = (string) $bus; + + if (!interface_exists(MessageBusInterface::class)) { + throw new InvalidArgumentException(\sprintf('The "joli_media.store_on_create_message_bus" setting is "%s", but the Messenger component is not installed. Run "composer require symfony/messenger", or set the setting to null to generate the variations synchronously.', $id)); + } + + if (!$container->has($id)) { + throw new InvalidArgumentException(\sprintf('The "joli_media.store_on_create_message_bus" setting is "%s", but there is no such service. Set it to the id of a Messenger bus, such as "messenger.default_bus", or to null to generate the variations synchronously.', $id)); + } + + $class = $container->getParameterBag()->resolveValue($container->findDefinition($id)->getClass()); + + if (!\is_string($class) || !is_a($class, MessageBusInterface::class, true)) { + throw new InvalidArgumentException(\sprintf('The "joli_media.store_on_create_message_bus" setting is "%s", which is not a Messenger bus: its class does not implement %s. Set it to the id of a Messenger bus, such as "messenger.default_bus", or to null to generate the variations synchronously.', $id, MessageBusInterface::class)); + } + } +} diff --git a/src/Event/Listener/StoreVariationsEventListener.php b/src/Event/Listener/StoreVariationsEventListener.php new file mode 100644 index 00000000..e441df84 --- /dev/null +++ b/src/Event/Listener/StoreVariationsEventListener.php @@ -0,0 +1,57 @@ +store($event->originalStorage, $event->media); + } + + public function onMediaPostMove(PostMoveMediaEvent $event): void + { + $this->store($event->originalStorage, $event->to); + } + + private function store(OriginalStorage $originalStorage, Media|string $media): void + { + $library = $originalStorage->getLibrary(); + + if (!$library->getCacheStorage()->mustStoreOnCreate()) { + return; + } + + if (null !== $this->messageBus) { + $this->messageBus->dispatch(new StoreVariations($library->getName(), $media instanceof Media ? $media->getPath() : $media)); + + return; + } + + // forced: no variation is stored at this path yet - those of a + // created media are deleted beforehand, those of a moved media stay + // at its previous path - so checking would only cost a request to the + // storage backend per variation + $this->converter->convert($media, $library->getName(), force: true); + } +} diff --git a/src/JoliMediaBundle.php b/src/JoliMediaBundle.php index 445b130f..7e8e6559 100644 --- a/src/JoliMediaBundle.php +++ b/src/JoliMediaBundle.php @@ -9,6 +9,7 @@ use Imagine\Imagick\Imagine as ImagickImagine; use JoliCode\MediaBundle\DependencyInjection\Compiler\CollectorPass; use JoliCode\MediaBundle\DependencyInjection\Compiler\DoctrinePass; +use JoliCode\MediaBundle\DependencyInjection\Compiler\MessageBusPass; use JoliCode\MediaBundle\Doctrine\Type\MediaLongType; use JoliCode\MediaBundle\Doctrine\Type\MediaType; use JoliCode\MediaBundle\Doctrine\Types; @@ -71,6 +72,7 @@ public function build(ContainerBuilder $container): void $container->addCompilerPass(new CollectorPass()); $container->addCompilerPass(new DoctrinePass()); + $container->addCompilerPass(new MessageBusPass()); } public function configure(DefinitionConfigurator $definition): void @@ -85,6 +87,10 @@ public function configure(DefinitionConfigurator $definition): void ->defaultValue(60.0) ->info('Default timeout, in seconds, of the external binary processes created by the processors, pre-processors and post-processors. Use 0 to disable the timeout.') ->end() + ->scalarNode('store_on_create_message_bus') + ->defaultNull() + ->info('The id of a Messenger bus (e.g. "messenger.default_bus") to which the generation of the variations is dispatched, in the libraries where cache.store_on_create is enabled. When null, the variations are generated synchronously.') + ->end() ->append($this->addLibrariesNode()) ->append($this->addPreProcessorsNode()) ->append($this->addProcessorsNode()) @@ -119,6 +125,12 @@ public function loadExtension(array $config, ContainerConfigurator $container, C $builder->setParameter('joli_media.process_timeout', $config['process_timeout']); + if (null !== $config['store_on_create_message_bus']) { + $container->services()->get('joli_media.event_listener.store_variations') + ->arg('$messageBus', service($config['store_on_create_message_bus'])) + ; + } + $this->imagineProcessorEnabled = isset($config['processors']['imagine']) && $config['processors']['imagine']['options']['enabled']; // libraries @@ -328,6 +340,10 @@ private function addCacheStorageNode(string $name): NodeDefinition ->defaultFalse() ->info('If true, variation files will be generated, if missing, when their URL is generated.') ->end() + ->booleanNode('store_on_create') + ->defaultFalse() + ->info('If true, all the variation files of a media are generated and stored when the media is created or moved, so that they never have to be generated on the fly.') + ->end() ->arrayNode('url_generator') ->children() ->scalarNode('path') @@ -1300,6 +1316,7 @@ private function createLibraryService(ContainerConfigurator $container, Containe ->arg('$strategy', service(sprintf('.joli_media.storage.strategy.%s', $libraryConfig['cache']['url_generator']['strategy']))) ->arg('$urlPath', $libraryConfig['cache']['url_generator']['path']) ->arg('$mustStoreWhenGeneratingUrl', $libraryConfig['cache']['must_store_when_generating_url']) + ->arg('$storeOnCreate', $libraryConfig['cache']['store_on_create']) ->arg('$mediaVariationPropertyAccessor', service($mediaVariationPropertyAccessorServiceId)) ; diff --git a/src/Message/StoreVariations.php b/src/Message/StoreVariations.php new file mode 100644 index 00000000..2e29ab30 --- /dev/null +++ b/src/Message/StoreVariations.php @@ -0,0 +1,16 @@ +converter->convert($message->path, $message->libraryName, force: true); + } catch (MediaNotFoundException) { + // the media was deleted or moved before the message was handled - + // a move dispatches a message of its own for the new path + } + } +} diff --git a/src/Storage/CacheStorage.php b/src/Storage/CacheStorage.php index 74206bd1..9c03a49b 100644 --- a/src/Storage/CacheStorage.php +++ b/src/Storage/CacheStorage.php @@ -25,6 +25,7 @@ public function __construct( private readonly UrlGeneratorInterface $urlGenerator, private readonly MimeTypeGuesser $mimeTypeGuesser, private readonly MediaVariationPropertyAccessor $mediaVariationPropertyAccessor, + private readonly bool $storeOnCreate = false, ) { } @@ -250,6 +251,16 @@ public function store(MediaVariation $mediaVariation): void $this->filesystem->write($path, $mediaVariation->getBinary()->getContent()); } + /** + * Whether all the variations of a media are generated and stored when it + * is created or moved (cache.store_on_create setting), so that they exist + * without having to check for them. + */ + public function mustStoreOnCreate(): bool + { + return $this->storeOnCreate; + } + public function mustStoreWhenGeneratingUrl(MediaVariation $mediaVariation): bool { $mustStore = $mediaVariation->getVariation()->mustStoreWhenGeneratingUrl() diff --git a/tests/src/BaseTestCase.php b/tests/src/BaseTestCase.php index e29968bb..96f1a87c 100644 --- a/tests/src/BaseTestCase.php +++ b/tests/src/BaseTestCase.php @@ -252,6 +252,7 @@ protected function createCacheStorage( string $urlPath, UrlGeneratorInterface $urlGenerator, bool $mustStoreWhenGeneratingUrl = false, + bool $storeOnCreate = false, ): CacheStorage { $cache = $this->createCache(); $mimeTypeGuesser = new MimeTypeGuesser( @@ -275,6 +276,7 @@ protected function createCacheStorage( $urlGenerator, $mimeTypeGuesser, $mediaVariationPropertyAccessor, + $storeOnCreate, ); } diff --git a/tests/src/DependencyInjection/MessageBusPassTest.php b/tests/src/DependencyInjection/MessageBusPassTest.php new file mode 100644 index 00000000..f4da077d --- /dev/null +++ b/tests/src/DependencyInjection/MessageBusPassTest.php @@ -0,0 +1,64 @@ +createContainer('messenger.default_bus'); + $container->register('messenger.bus.default', MessageBus::class); + $container->setAlias('messenger.default_bus', 'messenger.bus.default'); + + (new MessageBusPass())->process($container); + + $this->addToAssertionCount(1); + } + + public function testNoBusIsAccepted(): void + { + (new MessageBusPass())->process($this->createContainer(null)); + + $this->addToAssertionCount(1); + } + + public function testAMissingServiceIsRejected(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('there is no such service'); + + (new MessageBusPass())->process($this->createContainer('messenger.default_bus')); + } + + public function testAServiceThatIsNotABusIsRejected(): void + { + $container = $this->createContainer('logger'); + $container->register('logger', NullLogger::class); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('which is not a Messenger bus'); + + (new MessageBusPass())->process($container); + } + + private function createContainer(?string $bus): ContainerBuilder + { + $container = new ContainerBuilder(); + $listener = $container->register('joli_media.event_listener.store_variations', StoreVariationsEventListener::class); + + if (null !== $bus) { + $listener->setArgument('$messageBus', new Reference($bus)); + } + + return $container; + } +} diff --git a/tests/src/Event/Listener/StoreVariationsEventListenerTest.php b/tests/src/Event/Listener/StoreVariationsEventListenerTest.php new file mode 100644 index 00000000..bbf20304 --- /dev/null +++ b/tests/src/Event/Listener/StoreVariationsEventListenerTest.php @@ -0,0 +1,114 @@ +listen(); + + $this->originalStorage->createMedia('test.png', self::getFixtureBinaryContent(self::PNG_FIXTURE_PATH)); + + self::assertFalse($this->cacheStorage->has('test.png', $this->variation)); + } + + public function testVariationsAreStoredOnCreate(): void + { + $this->enableStoreOnCreate(); + $this->listen(); + + $this->originalStorage->createMedia('test.png', self::getFixtureBinaryContent(self::PNG_FIXTURE_PATH)); + + self::assertTrue($this->cacheStorage->has('test.png', $this->variation)); + } + + public function testVariationsAreStoredAtTheNewPathOnMove(): void + { + $this->enableStoreOnCreate(); + $this->listen(); + $this->originalStorage->createMedia('test.png', self::getFixtureBinaryContent(self::PNG_FIXTURE_PATH)); + + $this->originalStorage->move('test.png', 'folder/moved.png'); + + self::assertTrue($this->cacheStorage->has('folder/moved.png', $this->variation)); + self::assertFalse($this->cacheStorage->has('test.png', $this->variation)); + } + + public function testAMediaThatCannotBeProcessedIsCreatedWithoutVariations(): void + { + $this->enableStoreOnCreate(); + $this->listen(); + + $this->originalStorage->createMedia('document.txt', 'not an image'); + + self::assertTrue($this->originalStorage->has('document.txt')); + self::assertFalse($this->cacheStorage->has('document.txt', $this->variation)); + } + + public function testTheGenerationIsDispatchedToTheMessageBus(): void + { + $bus = new class implements MessageBusInterface { + /** @var list */ + public array $messages = []; + + public function dispatch(object $message, array $stamps = []): Envelope + { + \assert($message instanceof StoreVariations); + $this->messages[] = $message; + + return new Envelope($message, $stamps); + } + }; + $this->enableStoreOnCreate(); + $this->listen($bus); + + $this->originalStorage->createMedia('test.png', self::getFixtureBinaryContent(self::PNG_FIXTURE_PATH)); + $this->originalStorage->move('test.png', 'folder/moved.png'); + + self::assertEquals([ + new StoreVariations('default', 'test.png'), + new StoreVariations('default', 'folder/moved.png'), + ], $bus->messages); + self::assertFalse($this->cacheStorage->has('folder/moved.png', $this->variation), 'The handler generates them, not the listener.'); + + (new StoreVariationsHandler($this->converter))($bus->messages[1]); + + self::assertTrue($this->cacheStorage->has('folder/moved.png', $this->variation)); + } + + public function testTheHandlerIgnoresAMediaThatIsGoneByTheTimeItIsHandled(): void + { + (new StoreVariationsHandler($this->converter))(new StoreVariations('default', 'deleted.png')); + + self::assertFalse($this->cacheStorage->has('deleted.png', $this->variation)); + } + + private function enableStoreOnCreate(): void + { + $this->cacheStorage = $this->createCacheStorage('default', $this->cacheFilesystem, '/cache', $this->urlGenerator, storeOnCreate: true); + $this->library = new Library( + 'default', + $this->originalStorage, + $this->cacheStorage, + $this->createVariationContainer($this->cacheStorage, ['thumbnail' => fn (): Variation => $this->variation]), + ); + } + + private function listen(?MessageBusInterface $messageBus = null): void + { + $listener = new StoreVariationsEventListener($this->converter, $messageBus); + $this->eventDispatcher->addListener(MediaEvents::POST_CREATE_MEDIA, $listener->onMediaPostCreate(...)); + $this->eventDispatcher->addListener(MediaEvents::POST_MOVE_MEDIA, $listener->onMediaPostMove(...)); + } +}