Skip to content

Commit

Permalink
Merge branch '7.0' into 7.1
Browse files Browse the repository at this point in the history
* 7.0:
  [Messenger] Don't drop stamps when message validation fails
  [WebProfilerBundle] Fix assignment to constant variable
  [Mailer] [Sendgrid] Use DataPart::getContentId() when DataPart::setContentId() is used.
  • Loading branch information
fabpot committed May 7, 2024
2 parents eccdbea + 4a9d377 commit 9c9d571
Show file tree
Hide file tree
Showing 11 changed files with 194 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@
}
tab.addEventListener('click', function(e) {
const activeTab = e.target || e.srcElement;
let activeTab = e.target || e.srcElement;
/* needed because when the tab contains HTML contents, user can click */
/* on any of those elements instead of their parent '<button>' element */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -245,4 +245,45 @@ public function testTagAndMetadataHeaders()
$this->assertSame('blue', $payload['personalizations'][0]['custom_args']['Color']);
$this->assertSame('12345', $payload['personalizations'][0]['custom_args']['Client-ID']);
}

public function testInlineWithCustomContentId()
{
$imagePart = (new DataPart('text-contents', 'text.txt'));
$imagePart->asInline();
$imagePart->setContentId('content-identifier@symfony');

$email = new Email();
$email->addPart($imagePart);
$envelope = new Envelope(new Address('alice@system.com'), [new Address('bob@system.com')]);

$transport = new SendgridApiTransport('ACCESS_KEY');
$method = new \ReflectionMethod(SendgridApiTransport::class, 'getPayload');
$payload = $method->invoke($transport, $email, $envelope);

$this->assertArrayHasKey('attachments', $payload);
$this->assertCount(1, $payload['attachments']);
$this->assertArrayHasKey('content_id', $payload['attachments'][0]);

$this->assertSame('content-identifier@symfony', $payload['attachments'][0]['content_id']);
}

public function testInlineWithoutCustomContentId()
{
$imagePart = (new DataPart('text-contents', 'text.txt'));
$imagePart->asInline();

$email = new Email();
$email->addPart($imagePart);
$envelope = new Envelope(new Address('alice@system.com'), [new Address('bob@system.com')]);

$transport = new SendgridApiTransport('ACCESS_KEY');
$method = new \ReflectionMethod(SendgridApiTransport::class, 'getPayload');
$payload = $method->invoke($transport, $email, $envelope);

$this->assertArrayHasKey('attachments', $payload);
$this->assertCount(1, $payload['attachments']);
$this->assertArrayHasKey('content_id', $payload['attachments'][0]);

$this->assertSame('text.txt', $payload['attachments'][0]['content_id']);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ private function getAttachments(Email $email): array
];

if ('inline' === $disposition) {
$att['content_id'] = $filename;
$att['content_id'] = $attachment->hasContentId() ? $attachment->getContentId() : $filename;
}

$attachments[] = $att;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,17 @@
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class DelayedMessageHandlingException extends RuntimeException implements WrappedExceptionsInterface
class DelayedMessageHandlingException extends RuntimeException implements WrappedExceptionsInterface, EnvelopeAwareExceptionInterface
{
use EnvelopeAwareExceptionTrait;
use WrappedExceptionsTrait;

public function __construct(
private array $exceptions,
private ?Envelope $envelope = null,
?Envelope $envelope = null,
) {
$this->envelope = $envelope;

$exceptionMessages = implode(", \n", array_map(
fn (\Throwable $e) => $e::class.': '.$e->getMessage(),
$exceptions
Expand All @@ -40,9 +43,4 @@ public function __construct(

parent::__construct($message, 0, $exceptions[array_key_first($exceptions)]);
}

public function getEnvelope(): ?Envelope
{
return $this->envelope;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?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\Messenger\Exception;

use Symfony\Component\Messenger\Envelope;

/**
* @internal
*/
interface EnvelopeAwareExceptionInterface
{
public function getEnvelope(): ?Envelope;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?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\Messenger\Exception;

use Symfony\Component\Messenger\Envelope;

/**
* @internal
*/
trait EnvelopeAwareExceptionTrait
{
private ?Envelope $envelope = null;

public function getEnvelope(): ?Envelope
{
return $this->envelope;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

use Symfony\Component\Messenger\Envelope;

class HandlerFailedException extends RuntimeException implements WrappedExceptionsInterface
class HandlerFailedException extends RuntimeException implements WrappedExceptionsInterface, EnvelopeAwareExceptionInterface
{
use WrappedExceptionsTrait;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,23 @@

namespace Symfony\Component\Messenger\Exception;

use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Validator\ConstraintViolationListInterface;

/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class ValidationFailedException extends RuntimeException
class ValidationFailedException extends RuntimeException implements EnvelopeAwareExceptionInterface
{
use EnvelopeAwareExceptionTrait;

public function __construct(
private object $violatingMessage,
private ConstraintViolationListInterface $violations,
?Envelope $envelope = null,
) {
$this->envelope = $envelope;

parent::__construct(sprintf('Message of type "%s" failed validation.', $this->violatingMessage::class));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function handle(Envelope $envelope, StackInterface $stack): Envelope

$violations = $this->validator->validate($message, null, $groups);
if (\count($violations)) {
throw new ValidationFailedException($message, $violations);
throw new ValidationFailedException($message, $violations, $envelope);
}

return $stack->next()->handle($envelope, $stack);
Expand Down
86 changes: 86 additions & 0 deletions src/Symfony/Component/Messenger/Tests/FailureIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use Symfony\Component\Messenger\EventListener\StopWorkerOnMessageLimitListener;
use Symfony\Component\Messenger\Exception\DelayedMessageHandlingException;
use Symfony\Component\Messenger\Exception\HandlerFailedException;
use Symfony\Component\Messenger\Exception\ValidationFailedException;
use Symfony\Component\Messenger\Handler\HandlerDescriptor;
use Symfony\Component\Messenger\Handler\HandlersLocator;
use Symfony\Component\Messenger\MessageBus;
Expand All @@ -32,6 +33,7 @@
use Symfony\Component\Messenger\Middleware\FailedMessageProcessingMiddleware;
use Symfony\Component\Messenger\Middleware\HandleMessageMiddleware;
use Symfony\Component\Messenger\Middleware\SendMessageMiddleware;
use Symfony\Component\Messenger\Middleware\ValidationMiddleware;
use Symfony\Component\Messenger\Retry\MultiplierRetryStrategy;
use Symfony\Component\Messenger\Stamp\BusNameStamp;
use Symfony\Component\Messenger\Stamp\DispatchAfterCurrentBusStamp;
Expand All @@ -42,6 +44,9 @@
use Symfony\Component\Messenger\Transport\Sender\SenderInterface;
use Symfony\Component\Messenger\Transport\Sender\SendersLocator;
use Symfony\Component\Messenger\Worker;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class FailureIntegrationTest extends TestCase
{
Expand Down Expand Up @@ -419,6 +424,87 @@ public function testStampsAddedByMiddlewaresDontDisappearWhenDelayedMessageFails
$this->assertCount(1, $messagesWaiting);
$this->assertSame('some.bus', $messagesWaiting[0]->last(BusNameStamp::class)?->getBusName());
}

public function testStampsAddedByMiddlewaresDontDisappearWhenValidationFails()
{
$transport1 = new DummyFailureTestSenderAndReceiver();

$transports = [
'transport1' => $transport1,
];

$locator = $this->createMock(ContainerInterface::class);
$locator->expects($this->any())
->method('has')
->willReturn(true);
$locator->expects($this->any())
->method('get')
->willReturnCallback(fn ($transportName) => $transports[$transportName]);
$senderLocator = new SendersLocator([], $locator);

$retryStrategyLocator = $this->createMock(ContainerInterface::class);
$retryStrategyLocator->expects($this->any())
->method('has')
->willReturn(true);
$retryStrategyLocator->expects($this->any())
->method('get')
->willReturn(new MultiplierRetryStrategy(1));

$violationList = new ConstraintViolationList([new ConstraintViolation('validation failed', null, [], null, null, null)]);
$validator = $this->createMock(ValidatorInterface::class);
$validator->expects($this->once())->method('validate')->willReturn($violationList);

$middlewareStack = new \ArrayIterator([
new AddBusNameStampMiddleware('some.bus'),
new ValidationMiddleware($validator),
new SendMessageMiddleware($senderLocator),
]);

$bus = new MessageBus($middlewareStack);

$transport1Handler = fn () => $bus->dispatch(new \stdClass(), [new DispatchAfterCurrentBusStamp()]);

$handlerLocator = new HandlersLocator([
DummyMessage::class => [new HandlerDescriptor($transport1Handler)],
]);

$middlewareStack->append(new HandleMessageMiddleware($handlerLocator));

$dispatcher = new EventDispatcher();

$dispatcher->addSubscriber(new SendFailedMessageForRetryListener($locator, $retryStrategyLocator));
$dispatcher->addSubscriber(new StopWorkerOnMessageLimitListener(1));

$runWorker = function (string $transportName) use ($transports, $bus, $dispatcher): ?\Throwable {
$throwable = null;
$failedListener = function (WorkerMessageFailedEvent $event) use (&$throwable) {
$throwable = $event->getThrowable();
};
$dispatcher->addListener(WorkerMessageFailedEvent::class, $failedListener);

$worker = new Worker([$transportName => $transports[$transportName]], $bus, $dispatcher);

$worker->run();

$dispatcher->removeListener(WorkerMessageFailedEvent::class, $failedListener);

return $throwable;
};

// Simulate receive from external source
$transport1->send(new Envelope(new DummyMessage('API')));

// Receive the message from "transport1"
$throwable = $runWorker('transport1');

$this->assertInstanceOf(ValidationFailedException::class, $throwable, $throwable->getMessage());

$messagesWaiting = $transport1->getMessagesWaitingToBeReceived();

// Stamps should not be dropped on message that's queued for retry
$this->assertCount(1, $messagesWaiting);
$this->assertSame('some.bus', $messagesWaiting[0]->last(BusNameStamp::class)?->getBusName());
}
}

class DummyFailureTestSenderAndReceiver implements ReceiverInterface, SenderInterface
Expand Down
5 changes: 2 additions & 3 deletions src/Symfony/Component/Messenger/Worker.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@
use Symfony\Component\Messenger\Event\WorkerRunningEvent;
use Symfony\Component\Messenger\Event\WorkerStartedEvent;
use Symfony\Component\Messenger\Event\WorkerStoppedEvent;
use Symfony\Component\Messenger\Exception\DelayedMessageHandlingException;
use Symfony\Component\Messenger\Exception\HandlerFailedException;
use Symfony\Component\Messenger\Exception\EnvelopeAwareExceptionInterface;
use Symfony\Component\Messenger\Exception\RejectRedeliveredMessageException;
use Symfony\Component\Messenger\Exception\RuntimeException;
use Symfony\Component\Messenger\Stamp\AckStamp;
Expand Down Expand Up @@ -190,7 +189,7 @@ private function ack(): bool
$receiver->reject($envelope);
}

if ($e instanceof HandlerFailedException || ($e instanceof DelayedMessageHandlingException && null !== $e->getEnvelope())) {
if ($e instanceof EnvelopeAwareExceptionInterface && null !== $e->getEnvelope()) {
$envelope = $e->getEnvelope();
}

Expand Down

0 comments on commit 9c9d571

Please sign in to comment.