Skip to content

Commit c7ca1c6

Browse files
committed
Optimise ShardAwarePortGenerator
Make ShardAwarePortGenerator iterate only over matching ports.
1 parent ffc6392 commit c7ca1c6

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

cassandra/connection.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -672,13 +672,21 @@ def __init__(self, start_port: int, end_port: int):
672672
self.start_port = start_port
673673
self.end_port = end_port
674674

675+
@staticmethod
676+
def _align(value: int, total_shards: int):
677+
shift = value % total_shards
678+
if shift == 0:
679+
return value
680+
return value + total_shards - shift
681+
675682
def generate(self, shard_id: int, total_shards: int):
676-
start = random.randrange(self.start_port, self.end_port)
677-
available_ports = itertools.chain(range(start, self.end_port), range(self.start_port, start))
683+
start = self._align(random.randrange(self.start_port, self.end_port), total_shards) + shard_id
684+
beginning = self._align(self.start_port, total_shards) + shard_id
685+
available_ports = itertools.chain(range(start, self.end_port, total_shards),
686+
range(beginning, start, total_shards))
678687

679688
for port in available_ports:
680-
if port % total_shards == shard_id:
681-
yield port
689+
yield port
682690

683691

684692
DefaultShardAwarePortGenerator = ShardAwarePortGenerator(DEFAULT_LOCAL_PORT_LOW, DEFAULT_LOCAL_PORT_HIGH)

0 commit comments

Comments
 (0)