Completed
Pull Request — master (#37)
by Eugene
05:31
created

RetryMiddleware::constant()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 2
nc 1
nop 2
crap 6
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 4
    private function __construct(\Closure $getDelay)
27
    {
28 4
        $this->getDelay = $getDelay;
29 4
    }
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
    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
            return $retries > $maxRetries ? null : $uStep * $retries;
49
        });
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 4
    public function process(Request $request, Handler $handler) : Response
60
    {
61 4
        $retries = 0;
62
63
        do {
64
            try {
65 4
                return $handler->handle($request);
66 4
            } catch (\Throwable $e) {
67 4
                if (null === $delay = ($this->getDelay)(++$retries)) {
68 2
                    break;
69
                }
70 4
                \usleep($delay);
71
            }
72 4
        } while (true);
73
74 2
        throw $e;
75
    }
76
}
77