summaryrefslogtreecommitdiff
path: root/includes/HashRing.php
blob: 930f8c0aa156d02ee7d6778349ef7a81e9d1eb5c (plain)
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
135
136
137
138
139
140
141
142
<?php
/**
 * Convenience class for weighted consistent hash rings.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @author Aaron Schulz
 */

/**
 * Convenience class for weighted consistent hash rings
 *
 * @since 1.22
 */
class HashRing {
	/** @var Array (location => weight) */
	protected $sourceMap = array();
	/** @var Array (location => (start, end)) */
	protected $ring = array();

	const RING_SIZE = 268435456; // 2^28

	/**
	 * @param array $map (location => weight)
	 */
	public function __construct( array $map ) {
		$map = array_filter( $map, function( $w ) { return $w > 0; } );
		if ( !count( $map ) ) {
			throw new MWException( "Ring is empty or all weights are zero." );
		}
		$this->sourceMap = $map;
		// Sort the locations based on the hash of their names
		$hashes = array();
		foreach ( $map as $location => $weight ) {
			$hashes[$location] = sha1( $location );
		}
		uksort( $map, function ( $a, $b ) use ( $hashes ) {
			return strcmp( $hashes[$a], $hashes[$b] );
		} );
		// Fit the map to weight-proportionate one with a space of size RING_SIZE
		$sum = array_sum( $map );
		$standardMap = array();
		foreach ( $map as $location => $weight ) {
			$standardMap[$location] = (int)floor( $weight / $sum * self::RING_SIZE );
		}
		// Build a ring of RING_SIZE spots, with each location at a spot in location hash order
		$index = 0;
		foreach ( $standardMap as $location => $weight ) {
			// Location covers half-closed interval [$index,$index + $weight)
			$this->ring[$location] = array( $index, $index + $weight );
			$index += $weight;
		}
		// Make sure the last location covers what is left
		end( $this->ring );
		$this->ring[key( $this->ring )][1] = self::RING_SIZE;
	}

	/**
	 * Get the location of an item on the ring
	 *
	 * @param string $item
	 * @return string Location
	 */
	public function getLocation( $item ) {
		$locations = $this->getLocations( $item, 1 );
		return $locations[0];
	}

	/**
	 * Get the location of an item on the ring, as well as the next clockwise locations
	 *
	 * @param string $item
	 * @param integer $limit Maximum number of locations to return
	 * @return array List of locations
	 */
	public function getLocations( $item, $limit ) {
		$locations = array();
		$primaryLocation = null;
		$spot = hexdec( substr( sha1( $item ), 0, 7 ) ); // first 28 bits
		foreach ( $this->ring as $location => $range ) {
			if ( count( $locations ) >= $limit ) {
				break;
			}
			// The $primaryLocation is the location the item spot is in.
			// After that is reached, keep appending the next locations.
			if ( ( $range[0] <= $spot && $spot < $range[1] ) || $primaryLocation !== null ) {
				if ( $primaryLocation === null ) {
					$primaryLocation = $location;
				}
				$locations[] = $location;
			}
		}
		// If more locations are requested, wrap-around and keep adding them
		reset( $this->ring );
		while ( count( $locations ) < $limit ) {
			list( $location, ) = each( $this->ring );
			if ( $location === $primaryLocation ) {
				break; // don't go in circles
			}
			$locations[] = $location;
		}
		return $locations;
	}

	/**
	 * Get the map of locations to weight (ignores 0-weight items)
	 *
	 * @return array
	 */
	public function getLocationWeights() {
		return $this->sourceMap;
	}

	/**
	 * Get a new hash ring with a location removed from the ring
	 *
	 * @param string $location
	 * @return HashRing|bool Returns false if no non-zero weighted spots are left
	 */
	public function newWithoutLocation( $location ) {
		$map = $this->sourceMap;
		unset( $map[$location] );
		if ( count( $map ) ) {
			return new self( $map );
		}
		return false;
	}
}