Created NotifyVisitToWebhooksTest

This commit is contained in:
Alejandro Celaya 2019-12-27 20:12:13 +01:00
parent 21a3d4b66b
commit 79cd3ba912
2 changed files with 157 additions and 13 deletions

View File

@ -4,12 +4,15 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core\EventDispatcher;
use Closure;
use Doctrine\ORM\EntityManagerInterface;
use Fig\Http\Message\RequestMethodInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\RequestOptions;
use Psr\Log\LoggerInterface;
use Shlinkio\Shlink\Core\Entity\Visit;
use Shlinkio\Shlink\Core\Options\AppOptions;
use Shlinkio\Shlink\Core\Transformer\ShortUrlDataTransformer;
use Throwable;
@ -29,23 +32,31 @@ class NotifyVisitToWebHooks
private $webhooks;
/** @var ShortUrlDataTransformer */
private $transformer;
/** @var AppOptions */
private $appOptions;
public function __construct(
ClientInterface $httpClient,
EntityManagerInterface $em,
LoggerInterface $logger,
array $webhooks,
array $domainConfig
array $domainConfig,
AppOptions $appOptions
) {
$this->httpClient = $httpClient;
$this->em = $em;
$this->logger = $logger;
$this->webhooks = $webhooks;
$this->transformer = new ShortUrlDataTransformer($domainConfig);
$this->appOptions = $appOptions;
}
public function __invoke(ShortUrlLocated $shortUrlLocated): void
{
if (empty($this->webhooks)) {
return;
}
$visitId = $shortUrlLocated->visitId();
/** @var Visit|null $visit */
@ -57,27 +68,46 @@ class NotifyVisitToWebHooks
return;
}
$requestOptions = [
$requestOptions = $this->buildRequestOptions($visit);
$requestPromises = $this->performRequests($requestOptions, $visitId);
// Wait for all the promises to finish, ignoring rejections, as in those cases we only want to log the error.
settle($requestPromises)->wait();
}
private function buildRequestOptions(Visit $visit): array
{
return [
RequestOptions::TIMEOUT => 10,
RequestOptions::HEADERS => [
'User-Agent' => (string) $this->appOptions,
],
RequestOptions::JSON => [
'shortUrl' => $this->transformer->transform($visit->getShortUrl(), false),
'visit' => $visit->jsonSerialize(),
],
];
$logWebhookWarning = function (string $webhook, Throwable $e) use ($visitId): void {
$this->logger->warning('Failed to notify visit with id "{visitId}" to webhook "{webhook}". {e}', [
'visitId' => $visitId,
'webhook' => $webhook,
'e' => $e,
]);
};
}
$requestPromises = map($this->webhooks, function (string $webhook) use ($requestOptions, $logWebhookWarning) {
/**
* @param Promise[] $requestOptions
*/
private function performRequests(array $requestOptions, string $visitId): array
{
return map($this->webhooks, function (string $webhook) use ($requestOptions, $visitId) {
$promise = $this->httpClient->requestAsync(RequestMethodInterface::METHOD_POST, $webhook, $requestOptions);
return $promise->otherwise(partial_left($logWebhookWarning, $webhook));
return $promise->otherwise(
partial_left(Closure::fromCallable([$this, 'logWebhookFailure']), $webhook, $visitId)
);
});
}
// Wait for all the promises to finish, ignoring rejections, as in those cases we only want to log the error.
settle($requestPromises)->wait();
private function logWebhookFailure(string $webhook, string $visitId, Throwable $e): void
{
$this->logger->warning('Failed to notify visit with id "{visitId}" to webhook "{webhook}". {e}', [
'visitId' => $visitId,
'webhook' => $webhook,
'e' => $e,
]);
}
}

View File

@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
namespace ShlinkioTest\Shlink\Rest\EventDispatcher;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Fig\Http\Message\RequestMethodInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Promise\RejectedPromise;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\Prophecy\ObjectProphecy;
use Psr\Log\LoggerInterface;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Entity\Visit;
use Shlinkio\Shlink\Core\EventDispatcher\NotifyVisitToWebHooks;
use Shlinkio\Shlink\Core\EventDispatcher\ShortUrlLocated;
use Shlinkio\Shlink\Core\Model\Visitor;
use Shlinkio\Shlink\Core\Options\AppOptions;
use function count;
use function Functional\contains;
class NotifyVisitToWebHooksTest extends TestCase
{
/** @var ObjectProphecy */
private $httpClient;
/** @var ObjectProphecy */
private $em;
/** @var ObjectProphecy */
private $logger;
public function setUp(): void
{
$this->httpClient = $this->prophesize(ClientInterface::class);
$this->em = $this->prophesize(EntityManagerInterface::class);
$this->logger = $this->prophesize(LoggerInterface::class);
}
/** @test */
public function emptyWebhooksMakeNoFurtherActions(): void
{
$find = $this->em->find(Visit::class, '1')->willReturn(null);
$this->createListener([])(new ShortUrlLocated('1'));
$find->shouldNotHaveBeenCalled();
}
/** @test */
public function invalidVisitDoesNotPerformAnyRequest(): void
{
$find = $this->em->find(Visit::class, '1')->willReturn(null);
$requestAsync = $this->httpClient->requestAsync(
RequestMethodInterface::METHOD_POST,
Argument::type('string'),
Argument::type('array')
)->willReturn(new FulfilledPromise(''));
$logWarning = $this->logger->warning(
'Tried to notify webhooks for visit with id "{visitId}", but it does not exist.',
['visitId' => '1']
);
$this->createListener(['foo', 'bar'])(new ShortUrlLocated('1'));
$find->shouldHaveBeenCalledOnce();
$logWarning->shouldHaveBeenCalledOnce();
$requestAsync->shouldNotHaveBeenCalled();
}
/** @test */
public function expectedRequestsArePerformedToWebhooks(): void
{
$webhooks = ['foo', 'invalid', 'bar', 'baz'];
$invalidWebhooks = ['invalid', 'baz'];
$find = $this->em->find(Visit::class, '1')->willReturn(new Visit(new ShortUrl(''), Visitor::emptyInstance()));
$requestAsync = $this->httpClient->requestAsync(
RequestMethodInterface::METHOD_POST,
Argument::type('string'),
Argument::type('array')
)->will(function (array $args) use ($invalidWebhooks) {
[, $webhook] = $args;
$e = new Exception('');
return contains($invalidWebhooks, $webhook) ? new RejectedPromise($e) : new FulfilledPromise('');
});
$logWarning = $this->logger->warning(
'Failed to notify visit with id "{visitId}" to webhook "{webhook}". {e}',
Argument::type('array')
);
$this->createListener($webhooks)(new ShortUrlLocated('1'));
$find->shouldHaveBeenCalledOnce();
$requestAsync->shouldHaveBeenCalledTimes(count($webhooks));
$logWarning->shouldHaveBeenCalledTimes(count($invalidWebhooks));
}
private function createListener(array $webhooks): NotifyVisitToWebHooks
{
return new NotifyVisitToWebHooks(
$this->httpClient->reveal(),
$this->em->reveal(),
$this->logger->reveal(),
$webhooks,
[],
new AppOptions()
);
}
}