/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.pulsar.broker.service;

import java.util.Collections;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.pulsar.broker.service.BrokerServiceException.ConsumerAssignException;
import org.apache.pulsar.common.util.Murmur3_32Hash;

/**
 * This is a consumer selector based fixed hash range.
 *
 * The implementation uses consistent hashing to evenly split, the
 * number of keys assigned to each consumer.
 */
public class ConsistentHashingStickyKeyConsumerSelector implements StickyKeyConsumerSelector {

    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();

    // Consistent-Hash ring
    private final NavigableMap<Integer, Consumer> hashRing;

    private final int numberOfPoints;

    public ConsistentHashingStickyKeyConsumerSelector(int numberOfPoints) {
        this.hashRing = new TreeMap<>();
        this.numberOfPoints = numberOfPoints;
    }

    @Override
    public void addConsumer(Consumer consumer) throws ConsumerAssignException {
        rwLock.writeLock().lock();
        try {
            // Insert multiple points on the hash ring for every consumer
            // The points are deterministically added based on the hash of the consumer name
            for (int i = 0; i < numberOfPoints; i++) {
                String key = consumer.consumerName() + i;
                int hash = Murmur3_32Hash.getInstance().makeHash(key.getBytes());
                hashRing.put(hash, consumer);
            }
        } finally {
            rwLock.writeLock().unlock();
        }
    }

    @Override
    public void removeConsumer(Consumer consumer) {
        rwLock.writeLock().lock();
        try {
            // Remove all the points that were added for this consumer
            for (int i = 0; i < numberOfPoints; i++) {
                String key = consumer.consumerName() + i;
                int hash = Murmur3_32Hash.getInstance().makeHash(key.getBytes());
                hashRing.remove(hash, consumer);
            }
        } finally {
            rwLock.writeLock().unlock();
        }
    }

    @Override
    public Consumer select(byte[] stickyKey) {
        int hash = Murmur3_32Hash.getInstance().makeHash(stickyKey);

        rwLock.readLock().lock();
        try {
            if (hashRing.isEmpty()) {
                return null;
            }

            Map.Entry<Integer, Consumer> ceilingEntry = hashRing.ceilingEntry(hash);
            if (ceilingEntry != null) {
                return ceilingEntry.getValue();
            } else {
                return hashRing.firstEntry().getValue();
            }
        } finally {
            rwLock.readLock().unlock();
        }
    }

    Map<Integer, Consumer> getRangeConsumer() {
        return Collections.unmodifiableMap(hashRing);
    }
}

@@ -856,29 +856,263 @@
 ort 
-java.util.Collections
+com.google.common.collect.Lists;%0Aimport org.apache.pulsar.broker.service.BrokerServiceException.ConsumerAssignException;%0Aimport org.apache.pulsar.common.util.Murmur3_32Hash;%0A%0Aimport java.util.Collections;%0Aimport java.util.Comparator;%0Aimport java.util.List
 ;%0Aim
@@ -1300,150 +1300,8 @@
 k;%0A%0A
-import org.apache.pulsar.broker.service.BrokerServiceException.ConsumerAssignException;%0Aimport org.apache.pulsar.common.util.Murmur3_32Hash;%0A%0A
 /**%0A
@@ -1702,32 +1702,37 @@
 bleMap%3CInteger, 
+List%3C
 Consumer%3E hashRi
@@ -1724,16 +1724,17 @@
 onsumer%3E
+%3E
  hashRin
@@ -2480,26 +2480,459 @@
 ing.
+com
 put
+e
 (hash, 
-consumer
+(k, v) -%3E %7B%0A                    if (v == null) %7B%0A                        return Lists.newArrayList(consumer);%0A                    %7D else %7B%0A                        if (!v.contains(consumer)) %7B%0A                            v.add(consumer);%0A                            v.sort(Comparator.comparing(Consumer::consumerName, String::compareTo));%0A                        %7D%0A                        return v;%0A                    %7D%0A                %7D
 );%0A 
@@ -3432,21 +3432,22 @@
 ing.
-remov
+comput
 e(hash, 
 cons
@@ -3442,24 +3442,402 @@
 e(hash, 
-consumer
+(k, v) -%3E %7B%0A                    if (v == null) %7B%0A                        return null;%0A                    %7D else %7B%0A                        v.removeIf(c -%3E c.consumerName().equals(consumer.consumerName()));%0A                        if (v.isEmpty()) %7B%0A                            v = null;%0A                        %7D%0A                        return v;%0A                    %7D%0A                %7D
 );%0A     
@@ -4180,24 +4180,65 @@
          %7D%0A%0A
+            List%3CConsumer%3E consumerList;%0A
             
@@ -4248,32 +4248,37 @@
 .Entry%3CInteger, 
+List%3C
 Consumer%3E ceilin
@@ -4270,16 +4270,17 @@
 onsumer%3E
+%3E
  ceiling
@@ -4372,22 +4372,31 @@
         
-return
+consumerList = 
  ceiling
@@ -4450,22 +4450,30 @@
         
-return
+consumerList =
  hashRin
@@ -4504,32 +4504,98 @@
 );%0A            %7D
+%0A%0A            return consumerList.get(hash %25 consumerList.size());
 %0A        %7D final
@@ -4673,16 +4673,21 @@
 nteger, 
+List%3C
 Consumer
@@ -4687,16 +4687,17 @@
 onsumer%3E
+%3E
  getRang

Handle hash collision in ConsistentHashingStickyKeyConsumerSelector (#8396)