ExponentialBackoff::handleTimeout()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 2
Metric Value
cc 4
eloc 10
nc 4
nop 0
dl 0
loc 16
rs 9.9332
c 3
b 0
f 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Fns\GetMessage\TimeoutStrategies;
5
6
use Exception;
7
use Fns\Contracts\RequestsManager;
8
use Fns\Contracts\TimeoutStrategyHandler;
9
10
class ExponentialBackoff implements TimeoutStrategyHandler
11
{
12
    /**
13
     * @var RequestsManager
14
     */
15
    private $manager;
16
17
    /**
18
     * Start integer value in microseconds
19
     * @var int
20
     */
21
    private $expMinDelayMicroSeconds = 500000;
22
23
    /**
24
     * Max integer value in microseconds
25
     * @var int
26
     */
27
    private $expMaxDelayMicroSeconds;
28
29
    private $expFactor = 2.71828;
30
    private $expJitter = 0.1;
31
32
    public function __construct(RequestsManager $manager, $maxDelay = 60000000)
33
    {
34
        $this->manager = $manager;
35
        $this->expMaxDelayMicroSeconds = $maxDelay;
36
    }
37
38
    public function handleTimeout()
39
    {
40
        $delay = $this->expMinDelayMicroSeconds;
41
42
        while (true) {
43
            $this->manager->executeRequest();
44
            if ($this->manager->isProcessFinished()) {
45
                break;
46
            }
47
48
            usleep((int)$delay);
49
            $delay = $delay * $this->expFactor;
50
            if ((int)$delay > $this->expMaxDelayMicroSeconds) {
51
                throw new Exception('Timeout on server side expired');
52
            }
53
            $delay += cumnormdist($delay * $this->expJitter);
54
        }
55
    }
56
}
57