Symfony messenger with doctrine return "7 no connection to the server"

25 Views Asked by At

I have trouble with all my tests Symfony (7.0.4) messenger and handling messages. I have entity ID in message (in aws sqs) and handler loading entity from DB (postgres on diferent server). After process I see right processed results in database, but handler throw exception to log.

Messenger config:

framework:
    messenger:
        failure_transport: failed

        transports:
            async:
                dsn: 'https://sqs.%env(AWS_REGION)%.amazonaws.com/test-messenger.fifo?access_key=%env(AWS_ACCESS_KEY)%&secret_key=%env(AWS_URLENCODED_SECRET_KEY)%'
                retry_strategy:
                    max_retries: 0
                    multiplier: 2
            failed: 'https://sqs.%env(AWS_REGION)%.amazonaws.com/test-messenger-failed.fifo?access_key=%env(AWS_ACCESS_KEY)%&secret_key=%env(AWS_URLENCODED_SECRET_KEY)%'

        routing:
            App\Messenger\Message\NewValidCertificateForCustomDomainMessage: async

Worker config:

\[program:messenger-consume\]
command=php /var/www/bin/console messenger:consume async --memory-limit=128M -vv --time-limit=600
user=root
numprocs=4
startsecs=0
autostart=true
autorestart=true
startretries=10
stopwaitsecs=5
process_name=%(program_name)s\_%(process_num)02d

Message:

<?php

declare(strict_types=1);

namespace App\Messenger\Message;

class NewValidCertificateForCustomDomainMessage
{
    public function __construct(
        private string $accessTokenId,
    ) {
    }

    public function getAccessTokenId(): string
    {
        return $this->accessTokenId;
    }
}

Handler:

<?php

declare(strict_types=1);

namespace App\Messenger\Handler;

use App\Entity\AccessToken;
use App\Messenger\Message\NewValidCertificateForCustomDomainMessage;
use App\Service\CustomDomainService;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Uid\Uuid;

#[AsMessageHandler]
class NewValidCertificateForCustomDomainHandler
{
    private const CONTEXT = 'NewValidCertificateForCustomDomainHandler';

    public function __construct(
        private CustomDomainService $customDomainService,
        private EntityManagerInterface $entityManager,
        private LoggerInterface $logger,
    ) {
    }

    public function __invoke(NewValidCertificateForCustomDomainMessage $newValidCertificateForCustomDomainMessage): void
    {
        if ($this->entityManager->getConnection()->isConnected() === false) {
            $this->entityManager->getConnection()
                ->close();
        }

        $accessToken = $this->entityManager->getRepository(AccessToken::class)->find(
            Uuid::fromString($newValidCertificateForCustomDomainMessage->getAccessTokenId())
        );

        if (!$accessToken instanceof AccessToken) {
            $this->logger->error(
                'AccessToken not found!',
                [
                    'context' => self::CONTEXT,
                    'accessTokenId' => $newValidCertificateForCustomDomainMessage->getAccessTokenId(),
                ]
            );

            throw new \RuntimeException('AccessToken not found!');
        }

        if (!$this->customDomainService->addCustomDomainToDistribution($accessToken)) {
            throw new \RuntimeException('Failed to add custom domain to CloudFront distribution!');
        }
    }
}

After processing i see right results, but in log is exception:

{
    "message": "Error thrown while handling message {class}. Removing from transport after {retryCount} retries. Error: \"{error}\"",
    "context": {
        "class": "App\\Messenger\\Message\\NewValidCertificateForCustomDomainMessage",
        "retryCount": 0,
        "error": "Handling \"App\\Messenger\\Message\\NewValidCertificateForCustomDomainMessage\" failed: An exception occurred while executing a query: SQLSTATE[HY000]: General error: 7 no connection to the server",
        "exception": {
            "class": "Symfony\\Component\\Messenger\\Exception\\HandlerFailedException",
            "message": "Handling \"App\\Messenger\\Message\\NewValidCertificateForCustomDomainMessage\" failed: An exception occurred while executing a query: SQLSTATE[HY000]: General error: 7 no connection to the server",
            "code": 7,
            "file": "/var/www/vendor/symfony/messenger/Middleware/HandleMessageMiddleware.php:124",
            "previous": {
                "class": "Doctrine\\DBAL\\Exception\\DriverException",
                "message": "An exception occurred while executing a query: SQLSTATE[HY000]: General error: 7 no connection to the server",
                "code": 7,
                "file": "/var/www/vendor/doctrine/dbal/src/Driver/API/PostgreSQL/ExceptionConverter.php:80",
                "previous": {
                    "class": "Doctrine\\DBAL\\Driver\\PDO\\Exception",
                    "message": "SQLSTATE[HY000]: General error: 7 no connection to the server",
                    "code": 7,
                    "file": "/var/www/vendor/doctrine/dbal/src/Driver/PDO/Exception.php:28",
                    "previous": {
                        "class": "PDOException",
                        "message": "SQLSTATE[HY000]: General error: 7 no connection to the server",
                        "code": 0,
                        "file": "/var/www/vendor/doctrine/dbal/src/Driver/PDO/Statement.php:55"
                    }
                }
            }
        }
    },
    "level": 500,
    "level_name": "CRITICAL",
    "channel": "messenger",
    "datetime": "2024-03-25T00:05:02.362953+00:00",
    "extra": {}
}

...and message is resend to failed queue.

When I move logic to basic Symfony command and processing by CRON - all working properly. I try reset connection in handler (you can see it in code), but without effect.

I`m pleasure for any advice. Thank you

I try reset connection. - not working Reduce time worker to 600s. - not working Process same logic in cron command. - working

0

There are 0 best solutions below