-
Notifications
You must be signed in to change notification settings - Fork 0
/
Psr18Wrapper.php
62 lines (52 loc) · 1.94 KB
/
Psr18Wrapper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
declare(strict_types = 1);
namespace Interrupt;
use Exception;
use Interrupt\Contracts\FailureDetectorInterface;
use Interrupt\Contracts\CircuitBreakerInterface;
use Interrupt\Contracts\ServiceNameResolverInterface;
use Interrupt\Exceptions\ServiceUnavailableException;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\RequestInterface;
class Psr18Wrapper implements ClientInterface {
protected ClientInterface $client;
protected ServiceNameResolverInterface $serviceNameResolver;
protected CircuitBreakerInterface $circuitBreaker;
protected FailureDetectorInterface $failureDetector;
public function __construct(
ClientInterface $client,
ServiceNameResolverInterface $serviceNameResolver,
CircuitBreakerInterface $circuitBreaker,
FailureDetectorInterface $failureDetector
) {
$this->client = $client;
$this->serviceNameResolver = $serviceNameResolver;
$this->circuitBreaker = $circuitBreaker;
$this->failureDetector = $failureDetector;
}
/**
* @throws \Interrupt\Exceptions\ServiceUnavailableException
*/
public function sendRequest(RequestInterface $request): ResponseInterface {
$serviceName = $this->serviceNameResolver->handle($request);
if ($this->circuitBreaker->isAvailable($serviceName) === false) {
throw new ServiceUnavailableException("Service \"{$serviceName}\" is currently unavailable");
}
try {
$response = $this->client->sendRequest($request);
if ($this->failureDetector->isFailure($response) === true) {
$this->circuitBreaker->failed($serviceName);
return $response;
}
$this->circuitBreaker->successful($serviceName);
return $response;
} catch (Exception $exception) {
if ($exception instanceof ClientExceptionInterface) {
$this->circuitBreaker->failed($serviceName);
}
throw $exception;
}
}
}