-
Notifications
You must be signed in to change notification settings - Fork 198
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
* Fix #273 -- Use consistent hashing for PubSub * Update pubsub.py * Add missing import * Refactor hash function into utils module and add test * Run black
- Loading branch information
Showing
4 changed files
with
43 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
import binascii | ||
|
||
|
||
def _consistent_hash(value, ring_size): | ||
""" | ||
Maps the value to a node value between 0 and 4095 | ||
using CRC, then down to one of the ring nodes. | ||
""" | ||
if ring_size == 1: | ||
# Avoid the overhead of hashing and modulo when it is unnecessary. | ||
return 0 | ||
|
||
if isinstance(value, str): | ||
value = value.encode("utf8") | ||
bigval = binascii.crc32(value) & 0xFFF | ||
ring_divisor = 4096 / float(ring_size) | ||
return int(bigval / ring_divisor) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import pytest | ||
|
||
from channels_redis.utils import _consistent_hash | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"value,ring_size,expected", | ||
[ | ||
("key_one", 1, 0), | ||
("key_two", 1, 0), | ||
("key_one", 2, 1), | ||
("key_two", 2, 0), | ||
("key_one", 10, 6), | ||
("key_two", 10, 4), | ||
(b"key_one", 10, 6), | ||
(b"key_two", 10, 4), | ||
], | ||
) | ||
def test_consistent_hash_result(value, ring_size, expected): | ||
assert _consistent_hash(value, ring_size) == expected |