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