MCPcopy Index your code
hub / github.com/Permify/permify / assignPartitionWithLoad

Method assignPartitionWithLoad

pkg/consistent/consistent.go:178–220  ·  view source on GitHub ↗

assignPartitionWithLoad distributes a partition to a member based on the load factor. It ensures that no member exceeds the calculated average load while distributing partitions. If the distribution fails due to insufficient capacity, it panics with an error message.

(
	partitionID, startIndex int,
	partitionAssignments map[int]*Member,
	memberLoads map[string]float64,
)

Source from the content-addressed store, hash-verified

176// It ensures that no member exceeds the calculated average load while distributing partitions.
177// If the distribution fails due to insufficient capacity, it panics with an error message.
178func (c *Consistent) assignPartitionWithLoad(
179 partitionID, startIndex int,
180 partitionAssignments map[int]*Member,
181 memberLoads map[string]float64,
182) {
183 // Calculate the average load to determine the maximum load a member can handle.
184 averageLoad := c.calculateAverageLoad()
185 var attempts int
186
187 // Iterate to find a suitable member for the partition.
188 for {
189 attempts++
190
191 // If the loop exceeds the number of members, it indicates that the partition
192 // cannot be distributed with the current configuration.
193 if attempts >= len(c.sortedSet) {
194 panic("not enough capacity to distribute partitions: consider decreasing the partition count, increasing the member count, or increasing the load factor")
195 }
196
197 // Get the current hash value from the sorted set.
198 currentHash := c.sortedSet[startIndex]
199
200 // Retrieve the member associated with the hash value.
201 currentMember := *c.ring[currentHash]
202
203 // Check the current load of the member.
204 currentLoad := memberLoads[currentMember.String()]
205
206 // If the member's load is within the acceptable range, assign the partition.
207 if currentLoad+1 <= averageLoad {
208 partitionAssignments[partitionID] = &currentMember
209 memberLoads[currentMember.String()]++
210 return
211 }
212
213 // Move to the next member in the sorted set.
214 startIndex++
215 if startIndex >= len(c.sortedSet) {
216 // Loop back to the beginning of the sorted set if we reach the end.
217 startIndex = 0
218 }
219 }
220}
221
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.

Callers 1

distributePartitionsMethod · 0.95

Calls 2

calculateAverageLoadMethod · 0.95
StringMethod · 0.65

Tested by

no test coverage detected