forked from php-pm/php-pm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSlavePool.php
More file actions
134 lines (114 loc) · 2.79 KB
/
SlavePool.php
File metadata and controls
134 lines (114 loc) · 2.79 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
<?php
namespace PHPPM;
use React\Socket\ConnectionInterface;
/**
* SlavePool singleton is responsible for maintaining a pool of slave instances
*/
class SlavePool
{
/** @var Slave[] */
private $slaves = [];
/**
* Add slave to pool
*
* Slave is in CREATED state
*
* @param Slave $slave
*
* @return void
*/
public function add(Slave $slave)
{
$port = $slave->getPort();
if (isset($this->slaves[$port])) {
throw new \Exception("Slave port $port already occupied.");
}
if ($slave->getPort() !== $port) {
throw new \Exception("Slave mis-assigned.");
}
$this->slaves[$port] = $slave;
}
/**
* Remove from pool
*
* @param Slave $slave
*
* @return void
*/
public function remove(Slave $slave)
{
$port = $slave->getPort();
// validate existence
$this->getByPort($port);
// remove
unset($this->slaves[$port]);
}
/**
* Get slave by port
*
* @param int $port
* @return Slave
*/
public function getByPort($port)
{
if (!isset($this->slaves[$port])) {
throw new \Exception("Slave port $port empty.");
}
return $this->slaves[$port];
}
/**
* Get slave slaves by connection
*
* @param ConnectionInterface $connection
*
* @return mixed
* @throws \Exception
*/
public function getByConnection(ConnectionInterface $connection)
{
$hash = \spl_object_hash($connection);
foreach ($this->slaves as $slave) {
if ($slave->getConnection() && $hash === \spl_object_hash($slave->getConnection())) {
return $slave;
}
}
throw new \Exception("Slave connection not registered.");
}
/**
* Get multiple slaves by status
*/
public function getByStatus($status)
{
return \array_filter($this->slaves, function ($slave) use ($status) {
return $status === Slave::ANY || $status === $slave->getStatus();
});
}
/**
* Return a human-readable summary of the slaves in the pool.
*
* @return array
*/
public function getStatusSummary()
{
$map = [
'total' => Slave::ANY,
'ready' => Slave::READY,
'busy' => Slave::BUSY,
'created' => Slave::CREATED,
'registered' => Slave::REGISTERED,
'closed' => Slave::CLOSED
];
return \array_map(function ($state) {
return \count($this->getByStatus($state));
}, $map);
}
/**
* Returns all slaves in pool
*
* @return Slave[]
*/
public function getSlaves()
{
return $this->slaves;
}
}