distributePartitions evenly distributes partitions among members while respecting the load factor. It ensures that partitions are assigned to members based on consistent hashing and load constraints.
()
| 222 | // distributePartitions evenly distributes partitions among members while respecting the load factor. |
| 223 | // It ensures that partitions are assigned to members based on consistent hashing and load constraints. |
| 224 | func (c *Consistent) distributePartitions() { |
| 225 | // Initialize maps to track the load for each member and partition assignments. |
| 226 | memberLoads := make(map[string]float64) |
| 227 | partitionAssignments := make(map[int]*Member) |
| 228 | |
| 229 | // Create a buffer for converting partition IDs into byte slices for hashing. |
| 230 | partitionKeyBuffer := make([]byte, 8) |
| 231 | |
| 232 | // Iterate over all partition IDs to distribute them among members. |
| 233 | for partitionID := uint64(0); partitionID < c.partitionCount; partitionID++ { |
| 234 | // Convert the partition ID into a byte slice for hashing. |
| 235 | binary.LittleEndian.PutUint64(partitionKeyBuffer, partitionID) |
| 236 | |
| 237 | // Generate a hash key for the partition using the configured hasher. |
| 238 | hashKey := c.hasher(partitionKeyBuffer) |
| 239 | |
| 240 | // Find the index of the member in the sorted set where the hash key should be placed. |
| 241 | index := sort.Search(len(c.sortedSet), func(i int) bool { |
| 242 | return c.sortedSet[i] >= hashKey |
| 243 | }) |
| 244 | |
| 245 | // If the index is beyond the end of the sorted set, wrap around to the beginning. |
| 246 | if index >= len(c.sortedSet) { |
| 247 | index = 0 |
| 248 | } |
| 249 | |
| 250 | // Assign the partition to a member, ensuring the load factor is respected. |
| 251 | c.assignPartitionWithLoad(int(partitionID), index, partitionAssignments, memberLoads) |
| 252 | } |
| 253 | |
| 254 | // Update the Consistent instance with the new partition assignments and member loads. |
| 255 | c.partitions = partitionAssignments |
| 256 | c.loads = memberLoads |
| 257 | } |
| 258 | |
| 259 | // addMemberToRing adds a member to the consistent hash ring and updates the sorted set of hashes. |
| 260 | func (c *Consistent) addMemberToRing(member Member) { |
no test coverage detected