phpsymfonysymfony-messenger

Symfony 6.4 Messenger problem with #[AsMessageHandler(fromTransport: 'sync')]


I have configured my project with Symfony 6.4 and Messenger. I have create 2 transports (sync and async) on an event bus. When I dispatch a message, this message goes on the 2 transports that's what I want. On the handler I have add the fromTransport attribute to define when the handler run. Normally the message must handle only when the transport is sync but it runs on async too...

I don't if i have made an error on my config or if it's a bug, I have open an issue https://github.com/symfony/symfony/issues/54543

messenger.yaml

messenger:
    reset_on_message: true
    buses:
        bus.event:
            default_middleware:
                enabled: true
                allow_no_handlers: true
    failure_transport: failed

    transports:
        async:
            dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
            options:
                queue_name: async
            retry_strategy:
                max_retries: 3
                delay: 60000
                multiplier: 2
                max_delay: 0
            serializer: messenger.transport.symfony_serializer

        failed: 'doctrine://default?queue_name=failed'

        sync: 'sync://'

    routing:
        App\Message\Event\MessageEventInterface: [async, sync]
when@test:
    framework:
        messenger:
            transports:
                async: 'in-memory://'

services.yaml

    App\MessageHandler\Event\:
    resource: '../src/MessageHandler/Event'
    autoconfigure: false
    tags: [ { name: messenger.message_handler, bus: bus.event } ]

my handler

    <?php

declare(strict_types=1);

namespace App\MessageHandler\Event\Test;

use App\Message\Event\Agent\AgentTestedEvent;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'bus.event', fromTransport: 'sync')]
class TestAgentTested extends TestAgentMessageHandlerAbstract
{

    public function __construct(private readonly LoggerInterface $logger)
    {
    }

    public function __invoke(AgentTestedEvent $testedEvent): void
    {

        $this->logger->error('test lance ' . $testedEvent->getAgentUuid());
    }
}

Solution

  • In your service configuration, you tag message handlers manually.

    This is unnecessary when you have autoconfigure enabled (you don't) and use AsMessageHandler attribute in handlers.

    With autoconfigure disabled (like in your service configuration) attributes do not have the effect, therefore only the tags you specified in the service configuration are used to configure message handlers. In other words, your handlers are not configured with the fromTransport option.

    I would remove tags in the service configuration, enable autoconfigure and try again:

    App\MessageHandler\Event\:
    resource: '../src/MessageHandler/Event'
    autoconfigure: true