3 * Convenience class for weighted consistent hash rings.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Convenience class for weighted consistent hash rings
29 /** @var Array (location => weight) */
30 protected $sourceMap = [];
31 /** @var Array (location => (start, end)) */
34 /** @var HashRing|null */
36 /** @var Array (location => UNIX timestamp) */
37 protected $ejectionExpiries = [];
38 /** @var integer UNIX timestamp */
39 protected $ejectionNextExpiry = INF
;
41 const RING_SIZE
= 268435456; // 2^28
44 * @param array $map (location => weight)
46 public function __construct( array $map ) {
47 $map = array_filter( $map, function ( $w ) {
50 if ( !count( $map ) ) {
51 throw new UnexpectedValueException( "Ring is empty or all weights are zero." );
53 $this->sourceMap
= $map;
54 // Sort the locations based on the hash of their names
56 foreach ( $map as $location => $weight ) {
57 $hashes[$location] = sha1( $location );
59 uksort( $map, function ( $a, $b ) use ( $hashes ) {
60 return strcmp( $hashes[$a], $hashes[$b] );
62 // Fit the map to weight-proportionate one with a space of size RING_SIZE
63 $sum = array_sum( $map );
65 foreach ( $map as $location => $weight ) {
66 $standardMap[$location] = (int)floor( $weight / $sum * self
::RING_SIZE
);
68 // Build a ring of RING_SIZE spots, with each location at a spot in location hash order
70 foreach ( $standardMap as $location => $weight ) {
71 // Location covers half-closed interval [$index,$index + $weight)
72 $this->ring
[$location] = [ $index, $index +
$weight ];
75 // Make sure the last location covers what is left
77 $this->ring
[key( $this->ring
)][1] = self
::RING_SIZE
;
81 * Get the location of an item on the ring
84 * @return string Location
86 public function getLocation( $item ) {
87 $locations = $this->getLocations( $item, 1 );
93 * Get the location of an item on the ring, as well as the next locations
96 * @param integer $limit Maximum number of locations to return
97 * @return array List of locations
99 public function getLocations( $item, $limit ) {
101 $primaryLocation = null;
102 $spot = hexdec( substr( sha1( $item ), 0, 7 ) ); // first 28 bits
103 foreach ( $this->ring
as $location => $range ) {
104 if ( count( $locations ) >= $limit ) {
107 // The $primaryLocation is the location the item spot is in.
108 // After that is reached, keep appending the next locations.
109 if ( ( $range[0] <= $spot && $spot < $range[1] ) ||
$primaryLocation !== null ) {
110 if ( $primaryLocation === null ) {
111 $primaryLocation = $location;
113 $locations[] = $location;
116 // If more locations are requested, wrap-around and keep adding them
117 reset( $this->ring
);
118 while ( count( $locations ) < $limit ) {
119 list( $location, ) = each( $this->ring
);
120 if ( $location === $primaryLocation ) {
121 break; // don't go in circles
123 $locations[] = $location;
130 * Get the map of locations to weight (ignores 0-weight items)
134 public function getLocationWeights() {
135 return $this->sourceMap
;
139 * Get a new hash ring with a location removed from the ring
141 * @param string $location
142 * @return HashRing|bool Returns false if no non-zero weighted spots are left
144 public function newWithoutLocation( $location ) {
145 $map = $this->sourceMap
;
146 unset( $map[$location] );
148 return count( $map ) ?
new self( $map ) : false;
152 * Remove a location from the "live" hash ring
154 * @param string $location
155 * @param integer $ttl Seconds
156 * @return bool Whether some non-ejected locations are left
158 public function ejectFromLiveRing( $location, $ttl ) {
159 if ( !isset( $this->sourceMap
[$location] ) ) {
160 throw new UnexpectedValueException( "No location '$location' in the ring." );
162 $expiry = time() +
$ttl;
163 $this->liveRing
= null; // stale
164 $this->ejectionExpiries
[$location] = $expiry;
165 $this->ejectionNextExpiry
= min( $expiry, $this->ejectionNextExpiry
);
167 return ( count( $this->ejectionExpiries
) < count( $this->sourceMap
) );
171 * Get the "live" hash ring (which does not include ejected locations)
174 * @throws UnexpectedValueException
176 public function getLiveRing() {
178 if ( $this->liveRing
=== null ||
$this->ejectionNextExpiry
<= $now ) {
179 $this->ejectionExpiries
= array_filter(
180 $this->ejectionExpiries
,
181 function ( $expiry ) use ( $now ) {
182 return ( $expiry > $now );
185 if ( count( $this->ejectionExpiries
) ) {
186 $map = array_diff_key( $this->sourceMap
, $this->ejectionExpiries
);
187 $this->liveRing
= count( $map ) ?
new self( $map ) : false;
189 $this->ejectionNextExpiry
= min( $this->ejectionExpiries
);
190 } else { // common case; avoid recalculating ring
191 $this->liveRing
= clone $this;
192 $this->liveRing
->ejectionExpiries
= [];
193 $this->liveRing
->ejectionNextExpiry
= INF
;
194 $this->liveRing
->liveRing
= null;
196 $this->ejectionNextExpiry
= INF
;
199 if ( !$this->liveRing
) {
200 throw new UnexpectedValueException( "The live ring is currently empty." );
203 return $this->liveRing
;
207 * Get the location of an item on the "live" ring
209 * @param string $item
210 * @return string Location
211 * @throws UnexpectedValueException
213 public function getLiveLocation( $item ) {
214 return $this->getLiveRing()->getLocation( $item );
218 * Get the location of an item on the "live" ring, as well as the next locations
220 * @param string $item
221 * @param integer $limit Maximum number of locations to return
222 * @return array List of locations
223 * @throws UnexpectedValueException
225 public function getLiveLocations( $item, $limit ) {
226 return $this->getLiveRing()->getLocations( $item, $limit );
230 * Get the map of "live" locations to weight (ignores 0-weight items)
233 * @throws UnexpectedValueException
235 public function getLiveLocationWeights() {
236 return $this->getLiveRing()->getLocationWeights();