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 function React\Promise\reject; |
13
|
|
|
use ResourcePool\Allocation; |
14
|
|
|
use ResourcePool\Pool; |
15
|
|
|
use function React\Promise\resolve; |
16
|
|
|
use Throwable; |
17
|
|
|
|
18
|
|
|
class PoolMiddleware implements MiddlewareInterface |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var Allocation[] |
22
|
|
|
*/ |
23
|
|
|
private $allocations; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param RequestInterface $request |
27
|
|
|
* @param array $options |
28
|
|
|
* @return CancellablePromiseInterface |
29
|
|
|
* |
30
|
|
|
* @First() |
31
|
|
|
*/ |
32
|
3 |
|
public function pre( |
33
|
|
|
RequestInterface $request, |
34
|
|
|
string $transactionId, |
35
|
|
|
array $options = [] |
36
|
|
|
): CancellablePromiseInterface { |
37
|
3 |
|
if (!isset($options[self::class][Options::POOL])) { |
38
|
1 |
|
return resolve($request); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** @var Pool $pool */ |
42
|
2 |
|
$pool = $options[self::class][Options::POOL]; |
43
|
2 |
|
return $pool->allocateOne()->then(function (Allocation $allocation) use ($request, $transactionId) { |
44
|
2 |
|
$this->allocations[$transactionId] = $allocation; |
45
|
2 |
|
return resolve($request); |
46
|
2 |
|
}); |
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->allocations[$transactionId] instanceof Allocation) { |
62
|
|
|
$this->allocations[$transactionId]->releaseOne(); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return resolve($response); |
66
|
|
|
} |
67
|
|
|
|
68
|
1 |
|
public function error( |
69
|
|
|
Throwable $throwable, |
70
|
|
|
string $transactionId, |
71
|
|
|
array $options = [] |
72
|
|
|
): CancellablePromiseInterface { |
73
|
1 |
|
if ($this->allocations[$transactionId] instanceof Allocation) { |
74
|
1 |
|
$this->allocations[$transactionId]->releaseOne(); |
75
|
|
|
} |
76
|
|
|
|
77
|
1 |
|
return reject($throwable); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|