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