Passed
Pull Request — master (#37)
by Eugene
03:10
created

RetryMiddleware::custom()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Tarantool Client package.
7
 *
8
 * (c) Eugene Leonovich <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Tarantool\Client\Middleware;
15
16
use Tarantool\Client\Handler\Handler;
17
use Tarantool\Client\Request\Request;
18
use Tarantool\Client\Response;
19
20
final class RetryMiddleware implements Middleware
21
{
22
    public const DEFAULT_MAX_RETRIES = 3;
23
24
    private $getDelay;
25
26 6
    private function __construct(\Closure $getDelay)
27
    {
28 6
        $this->getDelay = $getDelay;
29 6
    }
30
31
    public static function constant(int $maxRetries = self::DEFAULT_MAX_RETRIES, int $uInterval = 1000) : self
32
    {
33
        return new self(static function (int $retries) use ($maxRetries, $uInterval) {
34
            return $retries > $maxRetries ? null : $uInterval;
35
        });
36
    }
37
38
    public static function exponential(int $maxRetries = self::DEFAULT_MAX_RETRIES, int $uBase = 1000) : self
39
    {
40
        return new self(static function (int $retries) use ($maxRetries, $uBase) {
41
            return $retries > $maxRetries ? null : $uBase ** $retries;
42
        });
43
    }
44
45 2
    public static function linear(int $maxRetries = self::DEFAULT_MAX_RETRIES, int $uStep = 1000) : self
46
    {
47
        return new self(static function (int $retries) use ($maxRetries, $uStep) {
48 2
            return $retries > $maxRetries ? null : $uStep * $retries;
49 2
        });
50
    }
51
52 4
    public static function custom(\Closure $getDelay) : self
53
    {
54
        return new self(static function (int $retries) use ($getDelay) : ?int {
55 4
            return $getDelay($retries);
56 4
        });
57
    }
58
59 6
    public function process(Request $request, Handler $handler) : Response
60
    {
61 6
        $retries = 0;
62
63
        do {
64
            try {
65 6
                return $handler->handle($request);
66 6
            } catch (\Throwable $e) {
67 6
                if (null === $delay = ($this->getDelay)(++$retries)) {
68 2
                    break;
69
                }
70 6
                \usleep($delay);
71
            }
72 6
        } while (true);
73
74 2
        throw $e;
75
    }
76
}
77