From fe1631a222ecfda01f30b6ba7e87392148ef4c88 Mon Sep 17 00:00:00 2001 From: Richard van Laak Date: Mon, 5 Oct 2026 14:20:12 +0200 Subject: [PATCH 1/2] Add a store_on_create setting generating the variations of a media on creation Generating variations lazily suits a local filesystem, where checking that a file exists is cheap. On a bucket each check is a request, and variations served without the MediaController (through a CDN or pre-signed URLs) are never generated when missing. With cache.store_on_create enabled, a listener converts all the applicable variations when a media is created or moved, forcing the conversion as no variation can be stored at that path yet. --- CHANGELOG.md | 1 + config/services.php | 13 ++++ doc/getting-started/configuration.rst | 1 + doc/misc-features/url-generation.rst | 29 ++++++++ .../Listener/StoreVariationsEventListener.php | 46 +++++++++++++ src/JoliMediaBundle.php | 5 ++ src/Storage/CacheStorage.php | 11 +++ tests/src/BaseTestCase.php | 2 + .../StoreVariationsEventListenerTest.php | 68 +++++++++++++++++++ 9 files changed, 176 insertions(+) create mode 100644 src/Event/Listener/StoreVariationsEventListener.php create mode 100644 tests/src/Event/Listener/StoreVariationsEventListenerTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index bb17c3ab..73d68787 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,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 - improvement - The existence of a variation file is cached once it is known to be stored, so that rendering a variation, or signing its temporary URL, no longer reaches the storage backend on every call - 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 - see the [URL generation documentation](doc/misc-features/url-generation.rst) - feature - The `srcset` generation moved out of the Twig components into a `SrcsetBuilder` service, so that it can be used from anywhere - an API Platform normalizer, a JSON endpoint, or your own templating - along with a `joli_media_srcset` Twig filter and the `Srcset` / `SrcsetCandidate` models - see the [srcset generation documentation](doc/misc-features/srcset.rst) - feature - The `joli:Img` component now builds the `srcset` of a variation configured with several `pixel_ratios` out of its name alone, instead of requiring the derivated variations to be listed by hand - set its new `autoSrcset` attribute to `false` to opt out. Within a `joli:Picture` component, the WebP alternative `source` tag carries the matching `srcset` - see the [Twig components documentation](doc/misc-features/twig-components.rst) - feature - The pixel dimensions of a variation which has not been generated yet are now computed from the variation definition, instead of being left out: the `srcset` carries its width descriptors, and the `img` and `source` tags their `width` and `height`, even on a cold cache - see the [srcset generation documentation](doc/misc-features/srcset.rst) diff --git a/config/services.php b/config/services.php index 19f233a5..8960aae3 100644 --- a/config/services.php +++ b/config/services.php @@ -16,6 +16,7 @@ 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; @@ -224,6 +225,18 @@ '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', + ]) // library ->set('joli_media.library_container', LibraryContainer::class) diff --git a/doc/getting-started/configuration.rst b/doc/getting-started/configuration.rst index 891c9c34..11a6e592 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>`_. - ``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 0880c7e9..0778711f 100644 --- a/doc/misc-features/url-generation.rst +++ b/doc/misc-features/url-generation.rst @@ -92,6 +92,35 @@ 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 synchronously, without checking whether they already exist: creating a media takes longer, but does not send any existence check to the storage backend; +- 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. + Twig extension -------------- diff --git a/src/Event/Listener/StoreVariationsEventListener.php b/src/Event/Listener/StoreVariationsEventListener.php new file mode 100644 index 00000000..0639cfec --- /dev/null +++ b/src/Event/Listener/StoreVariationsEventListener.php @@ -0,0 +1,46 @@ +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; + } + + // 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..30d9ee5e 100644 --- a/src/JoliMediaBundle.php +++ b/src/JoliMediaBundle.php @@ -328,6 +328,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 +1304,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/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/Event/Listener/StoreVariationsEventListenerTest.php b/tests/src/Event/Listener/StoreVariationsEventListenerTest.php new file mode 100644 index 00000000..13b0ccc2 --- /dev/null +++ b/tests/src/Event/Listener/StoreVariationsEventListenerTest.php @@ -0,0 +1,68 @@ +converter); + $this->eventDispatcher->addListener(MediaEvents::POST_CREATE_MEDIA, $listener->onMediaPostCreate(...)); + $this->eventDispatcher->addListener(MediaEvents::POST_MOVE_MEDIA, $listener->onMediaPostMove(...)); + } + + public function testVariationsAreNotStoredOnCreateByDefault(): void + { + $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->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->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->originalStorage->createMedia('document.txt', 'not an image'); + + self::assertTrue($this->originalStorage->has('document.txt')); + self::assertFalse($this->cacheStorage->has('document.txt', $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 () => $this->variation]), + ); + } +} From e048158d9254bab285450c24c0235c9409023114 Mon Sep 17 00:00:00 2001 From: Richard van Laak Date: Mon, 5 Oct 2026 14:55:03 +0200 Subject: [PATCH 2/2] Generate the variations stored on creation through Messenger when a bus is configured The store_on_create_message_bus setting names the bus to dispatch a StoreVariations message to, instead of generating the variations synchronously; routing the message to an asynchronous transport moves the generation to a worker. A setting that names no Messenger bus fails the container compilation. --- CHANGELOG.md | 2 +- composer.json | 4 +- config/services.php | 6 ++ doc/getting-started/configuration.rst | 2 +- doc/misc-features/url-generation.rst | 35 +++++++++- .../Compiler/MessageBusPass.php | 47 +++++++++++++ .../Listener/StoreVariationsEventListener.php | 13 +++- src/JoliMediaBundle.php | 12 ++++ src/Message/StoreVariations.php | 16 +++++ src/Message/StoreVariationsHandler.php | 24 +++++++ .../MessageBusPassTest.php | 64 ++++++++++++++++++ .../StoreVariationsEventListenerTest.php | 66 ++++++++++++++++--- 12 files changed, 275 insertions(+), 16 deletions(-) create mode 100644 src/DependencyInjection/Compiler/MessageBusPass.php create mode 100644 src/Message/StoreVariations.php create mode 100644 src/Message/StoreVariationsHandler.php create mode 100644 tests/src/DependencyInjection/MessageBusPassTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 73d68787..0d52d1bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,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 - improvement - The existence of a variation file is cached once it is known to be stored, so that rendering a variation, or signing its temporary URL, no longer reaches the storage backend on every call - 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 - see the [URL generation documentation](doc/misc-features/url-generation.rst) +- 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) - feature - The `srcset` generation moved out of the Twig components into a `SrcsetBuilder` service, so that it can be used from anywhere - an API Platform normalizer, a JSON endpoint, or your own templating - along with a `joli_media_srcset` Twig filter and the `Srcset` / `SrcsetCandidate` models - see the [srcset generation documentation](doc/misc-features/srcset.rst) - feature - The `joli:Img` component now builds the `srcset` of a variation configured with several `pixel_ratios` out of its name alone, instead of requiring the derivated variations to be listed by hand - set its new `autoSrcset` attribute to `false` to opt out. Within a `joli:Picture` component, the WebP alternative `source` tag carries the matching `srcset` - see the [Twig components documentation](doc/misc-features/twig-components.rst) - feature - The pixel dimensions of a variation which has not been generated yet are now computed from the variation definition, instead of being left out: the `srcset` carries its width descriptors, and the `img` and `source` tags their `width` and `height`, even on a cold cache - see the [srcset generation documentation](doc/misc-features/srcset.rst) 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 8960aae3..4bffbcea 100644 --- a/config/services.php +++ b/config/services.php @@ -23,6 +23,7 @@ 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; @@ -237,6 +238,11 @@ '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 11a6e592..45ba2e97 100644 --- a/doc/getting-started/configuration.rst +++ b/doc/getting-started/configuration.rst @@ -39,7 +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>`_. + - ``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 0778711f..d936961f 100644 --- a/doc/misc-features/url-generation.rst +++ b/doc/misc-features/url-generation.rst @@ -116,11 +116,42 @@ 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 synchronously, without checking whether they already exist: creating a media takes longer, but does not send any existence check to the storage backend; -- 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 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 index 0639cfec..e441df84 100644 --- a/src/Event/Listener/StoreVariationsEventListener.php +++ b/src/Event/Listener/StoreVariationsEventListener.php @@ -5,17 +5,22 @@ use JoliCode\MediaBundle\Conversion\Converter; use JoliCode\MediaBundle\Event\PostCreateMediaEvent; use JoliCode\MediaBundle\Event\PostMoveMediaEvent; +use JoliCode\MediaBundle\Message\StoreVariations; use JoliCode\MediaBundle\Model\Media; use JoliCode\MediaBundle\Storage\OriginalStorage; +use Symfony\Component\Messenger\MessageBusInterface; /** * Generates and stores all the variations of a media when it is created or - * moved, in the libraries where the cache.store_on_create setting is enabled. + * moved, in the libraries where the cache.store_on_create setting is enabled: + * synchronously, or through a Messenger bus when the store_on_create_message_bus + * setting names one. */ readonly class StoreVariationsEventListener { public function __construct( private Converter $converter, + private ?MessageBusInterface $messageBus = null, ) { } @@ -37,6 +42,12 @@ private function store(OriginalStorage $originalStorage, Media|string $media): v 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 diff --git a/src/JoliMediaBundle.php b/src/JoliMediaBundle.php index 30d9ee5e..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 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/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 index 13b0ccc2..bbf20304 100644 --- a/tests/src/Event/Listener/StoreVariationsEventListenerTest.php +++ b/tests/src/Event/Listener/StoreVariationsEventListenerTest.php @@ -5,21 +5,19 @@ use JoliCode\MediaBundle\Event\Listener\StoreVariationsEventListener; use JoliCode\MediaBundle\Event\MediaEvents; use JoliCode\MediaBundle\Library\Library; +use JoliCode\MediaBundle\Message\StoreVariations; +use JoliCode\MediaBundle\Message\StoreVariationsHandler; use JoliCode\MediaBundle\Tests\BaseTestCase; +use JoliCode\MediaBundle\Variation\Variation; +use Symfony\Component\Messenger\Envelope; +use Symfony\Component\Messenger\MessageBusInterface; class StoreVariationsEventListenerTest extends BaseTestCase { - protected function setUp(): void - { - parent::setUp(); - - $listener = new StoreVariationsEventListener($this->converter); - $this->eventDispatcher->addListener(MediaEvents::POST_CREATE_MEDIA, $listener->onMediaPostCreate(...)); - $this->eventDispatcher->addListener(MediaEvents::POST_MOVE_MEDIA, $listener->onMediaPostMove(...)); - } - public function testVariationsAreNotStoredOnCreateByDefault(): void { + $this->listen(); + $this->originalStorage->createMedia('test.png', self::getFixtureBinaryContent(self::PNG_FIXTURE_PATH)); self::assertFalse($this->cacheStorage->has('test.png', $this->variation)); @@ -28,6 +26,7 @@ public function testVariationsAreNotStoredOnCreateByDefault(): void public function testVariationsAreStoredOnCreate(): void { $this->enableStoreOnCreate(); + $this->listen(); $this->originalStorage->createMedia('test.png', self::getFixtureBinaryContent(self::PNG_FIXTURE_PATH)); @@ -37,6 +36,7 @@ public function testVariationsAreStoredOnCreate(): void 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'); @@ -48,6 +48,7 @@ public function testVariationsAreStoredAtTheNewPathOnMove(): void public function testAMediaThatCannotBeProcessedIsCreatedWithoutVariations(): void { $this->enableStoreOnCreate(); + $this->listen(); $this->originalStorage->createMedia('document.txt', 'not an image'); @@ -55,6 +56,44 @@ public function testAMediaThatCannotBeProcessedIsCreatedWithoutVariations(): voi 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); @@ -62,7 +101,14 @@ private function enableStoreOnCreate(): void 'default', $this->originalStorage, $this->cacheStorage, - $this->createVariationContainer($this->cacheStorage, ['thumbnail' => fn () => $this->variation]), + $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(...)); + } }