Repository navigation
Expand file tree
/
Copy pathRoundRobinTransport.php
More file actions
76 lines (61 loc) · 2.13 KB
/
Copy pathRoundRobinTransport.php
File metadata and controls
76 lines (61 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
declare(strict_types=1);
namespace SchedulerBundle\Transport;
use Closure;
use SchedulerBundle\Exception\TransportException;
use SchedulerBundle\Transport\Configuration\ConfigurationInterface;
use SplObjectStorage;
use Symfony\Component\Stopwatch\Stopwatch;
use Throwable;
/**
* @author Guillaume Loulier <contact@guillaumeloulier.fr>
*/
final class RoundRobinTransport extends AbstractCompoundTransport
{
/**
* @var SplObjectStorage<object, mixed>
*/
private SplObjectStorage $sleepingTransports;
public function __construct(
TransportRegistryInterface $registry,
ConfigurationInterface $configuration
) {
$this->sleepingTransports = new SplObjectStorage();
parent::__construct($registry, $configuration);
}
/**
* {@inheritdoc}
*/
protected function execute(Closure $func)
{
if (0 === $this->registry->count()) {
throw new TransportException('No transport found');
}
while ($this->sleepingTransports->count() !== $this->registry->count()) {
foreach ($this->registry as $transport) {
if ($this->sleepingTransports->contains($transport)) {
continue;
}
$stopWatch = new Stopwatch();
try {
$stopWatch->start('quantum');
return $func($transport);
} catch (Throwable) {
$this->sleepingTransports->attach($transport);
continue;
} finally {
$this->storeSleepingTransports($stopWatch, $transport);
}
}
}
throw new TransportException('All the transports failed to execute the requested action');
}
private function storeSleepingTransports(Stopwatch $stopWatch, TransportInterface $transport): void
{
$event = $stopWatch->stop('quantum');
$duration = $event->getDuration() / 1000;
if ($duration > ($this->registry->count() * $this->configuration->get('quantum'))) {
$this->sleepingTransports->attach($transport);
}
}
}