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