1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace ApiClients\Middleware\Pool; |
4
|
|
|
|
5
|
|
|
use ApiClients\Foundation\Middleware\Annotation\First; |
6
|
|
|
use ApiClients\Foundation\Middleware\Annotation\Last; |
7
|
|
|
use ApiClients\Foundation\Middleware\ErrorTrait; |
8
|
|
|
use ApiClients\Foundation\Middleware\MiddlewareInterface; |
9
|
|
|
use Psr\Http\Message\RequestInterface; |
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
11
|
|
|
use React\Promise\CancellablePromiseInterface; |
12
|
|
|
use ResourcePool\Allocation; |
13
|
|
|
use ResourcePool\Pool; |
14
|
|
|
use function React\Promise\resolve; |
15
|
|
|
|
16
|
|
|
class PoolMiddleware implements MiddlewareInterface |
17
|
|
|
{ |
18
|
|
|
use ErrorTrait; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var Allocation |
22
|
|
|
*/ |
23
|
|
|
private $allocation; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param RequestInterface $request |
27
|
|
|
* @param array $options |
28
|
|
|
* @return CancellablePromiseInterface |
29
|
|
|
* |
30
|
|
|
* @First() |
31
|
|
|
*/ |
32
|
2 |
|
public function pre( |
33
|
|
|
RequestInterface $request, |
34
|
|
|
string $transactionId, |
35
|
|
|
array $options = [] |
36
|
|
|
): CancellablePromiseInterface { |
37
|
2 |
|
if (!isset($options[self::class][Options::POOL])) { |
38
|
1 |
|
return resolve($request); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** @var Pool $pool */ |
42
|
1 |
|
$pool = $options[self::class][Options::POOL]; |
43
|
1 |
|
return $pool->allocateOne()->then(function (Allocation $allocation) use ($request) { |
44
|
1 |
|
$this->allocation = $allocation; |
45
|
1 |
|
return resolve($request); |
46
|
1 |
|
}); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param ResponseInterface $response |
51
|
|
|
* @param array $options |
52
|
|
|
* @return CancellablePromiseInterface |
53
|
|
|
* |
54
|
|
|
* @Last() |
55
|
|
|
*/ |
56
|
|
|
public function post( |
57
|
|
|
ResponseInterface $response, |
58
|
|
|
string $transactionId, |
59
|
|
|
array $options = [] |
60
|
|
|
): CancellablePromiseInterface { |
61
|
|
|
if ($this->allocation instanceof Allocation) { |
62
|
|
|
$this->allocation->releaseOne(); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return resolve($response); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|