1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace NBN\LoadBalancer; |
4
|
|
|
|
5
|
|
|
use NBN\LoadBalancer\Chooser\ChooserInterface; |
6
|
|
|
use NBN\LoadBalancer\Exception\AlreadyRegisteredHostException; |
7
|
|
|
use NBN\LoadBalancer\Exception\HostRequestException; |
8
|
|
|
use NBN\LoadBalancer\Exception\NoAvailableHostException; |
9
|
|
|
use NBN\LoadBalancer\Exception\NoRegisteredHostException; |
10
|
|
|
use NBN\LoadBalancer\Host\Host; |
11
|
|
|
use NBN\LoadBalancer\Host\HostInterface; |
12
|
|
|
use Symfony\Component\HttpFoundation\Request; |
13
|
|
|
use Symfony\Component\HttpFoundation\Response; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @author Nicolas Bastien <[email protected]> |
17
|
|
|
*/ |
18
|
|
|
class LoadBalancer implements LoadBalancerInterface |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var array|HostInterface[] |
22
|
|
|
*/ |
23
|
|
|
protected $hosts; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var ChooserInterface |
27
|
|
|
*/ |
28
|
|
|
protected $chooser; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param array|HostInterface[] $hosts |
32
|
|
|
* @param ChooserInterface $chooser |
33
|
|
|
*/ |
34
|
|
|
public function __construct(array $hosts, ChooserInterface $chooser) |
35
|
|
|
{ |
36
|
|
|
foreach ($hosts as $host) { |
37
|
|
|
$this->hosts[$host->getId()] = $host; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$this->chooser = $chooser; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param HostInterface $host |
45
|
|
|
*/ |
46
|
|
|
public function addHost(HostInterface $host) |
47
|
|
|
{ |
48
|
|
|
if (isset($this->hosts[$host->getId()])) { |
49
|
|
|
throw new AlreadyRegisteredHostException(); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$this->hosts[$host->getId()] = $host; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param string $id |
57
|
|
|
* @param string $url |
58
|
|
|
* @param array $settings |
59
|
|
|
*/ |
60
|
|
|
public function addHostByConfiguration($id, $url, $settings) |
61
|
|
|
{ |
62
|
|
|
if (isset($this->hosts[$id])) { |
63
|
|
|
throw new AlreadyRegisteredHostException(); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
$this->hosts[$id] = new Host($id, $url, $settings); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* {@inheritdoc} |
71
|
|
|
*/ |
72
|
|
|
public function handleRequest(Request $request) |
73
|
|
|
{ |
74
|
|
|
if (count($this->hosts) == 0) { |
75
|
|
|
throw new NoRegisteredHostException(); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
$host = $this->chooser->getAvailableHost($request, $this->hosts); |
79
|
|
|
if ($host === null) { |
80
|
|
|
throw new NoAvailableHostException(); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
$response = $host->handleRequest($request); |
84
|
|
|
if (!$response instanceof Response) { |
85
|
|
|
throw new HostRequestException(); |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
$response->headers->set('Handled-By', $host->getId()); |
89
|
|
|
|
90
|
|
|
return $response; |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|