import hashlib
import bisect
import uuid
class HashRing:
"""
Implements Consistent Hashing.
Maps keys to specific nodes (shards) on a logical ring.
"""
def __init__(self, virtual_nodes=100):
self.virtual_nodes = virtual_nodes
self.ring = dict() # Maps hash_value -> Node Name
self.sorted_keys = [] # Sorted list of hash values for binary search
def _hash(self, key):
"""
Generates a hash value for a key using MD5.
Returns an integer representation.
"""
return int(hashlib.md5(key.encode('utf-8')).hexdigest(), 16)
def add_node(self, node):
"""
Adds a physical node (shard) to the ring with V virtual nodes.
"""
for i in range(self.virtual_nodes):
virtual_node_key = f"{node}-{i}"
hash_val = self._hash(virtual_node_key)
self.ring[hash_val] = node
bisect.insort(self.sorted_keys, hash_val)
print(f"[Cluster] Node '{node}' added with {self.virtual_nodes} virtual replicas.")
def remove_node(self, node):
"""
Removes a physical node and all its virtual nodes from the ring.
"""
keys_to_remove = []
for i in range(self.virtual_nodes):
virtual_node_key = f"{node}-{i}"
hash_val = self._hash(virtual_node_key)
keys_to_remove.append(hash_val)
for h in keys_to_remove:
del self.ring[h]
self.sorted_keys.remove(h)
print(f"[Cluster] Node '{node}' removed.")
def get_node(self, key):
"""
Given a data key (e.g., UserID), returns which shard owns it.
It finds the first node hash >= key hash (clockwise traversal).
"""
if not self.ring:
return None
hash_val = self._hash(key)
# Find the first node hash that is greater than or equal to the key hash
idx = bisect.bisect_left(self.sorted_keys, hash_val)
# Wrap around to the first node if we passed the largest hash
if idx == len(self.sorted_keys):
idx = 0
return self.ring[self.sorted_keys[idx]]
class Shard:
"""
Represents a single database instance (a shard).
In a real app, this would be a connection to MySQL, Postgres, or MongoDB.
"""
def __init__(self, name):
self.name = name
self.data = {}
def write(self, key, value):
self.data[key] = value
def read(self, key):
return self.data.get(key, None)
def count(self):
return len(self.data)
class ShardedDatabase:
"""
The Controller. It abstracts the sharding logic from the user.
"""
def __init__(self):
self.ring = HashRing(virtual_nodes=150) # 150 virtual nodes per physical node
self.shards = {} # Map name -> Shard Object
def add_shard(self, name):
shard = Shard(name)
self.shards[name] = shard
self.ring.add_node(name)
def write(self, key, value):
node_name = self.ring.get_node(key)
if node_name:
print(f"Writing '{key}' to Shard: {node_name}")
self.shards[node_name].write(key, value)
else:
print("Error: No active shards.")
def read(self, key):
node_name = self.ring.get_node(key)
if node_name:
print(f"Reading '{key}' from Shard: {node_name}")
return self.shards[node_name].read(key)
return None
def stats(self):
print("\n--- Database Stats ---")
for name, shard in self.shards.items():
print(f"Shard [{name}]: {shard.count()} records")
print("---------------------\n")
# ==========================================
# Demonstration
# ==========================================
if __name__ == "__main__":
# 1. Initialize the cluster with 3 shards
db = ShardedDatabase()
db.add_shard("Shard-A")
db.add_shard("Shard-B")
db.add_shard("Shard-C")
# 2. Write some data (Simulating Users)
# We use UUIDs to simulate random unique user IDs
user_ids = [str(uuid.uuid4()) for _ in range(10)]
print("\n>>> WRITING DATA PHASE 1 <<<")
for i, uid in enumerate(user_ids):
db.write(uid, {"username": f"user_{i}", "score": i * 10})
db.stats()
# 3. Demonstrate Scalability (Adding a new node)
# Because we use Consistent Hashing, most keys stay on the same shard.
# Only a portion of keys from ONE neighbor will move to the new shard.
print(">>> SCALING: ADDING Shard-D <<<")
db.add_shard("Shard-D")
# Note: In a real system, you would now need a "rebalancing" script
# that iterates over existing data and moves it if the hash mapping changed.
# For this demo, we will simply write NEW data to see it landing on D.
new_user = str(uuid.uuid4())
db.write(new_user, {"username": "new_guy", "score": 100})
# 4. Verify Reading
print("\n>>> READING DATA <<<")
check_id = user_ids[0]
data = db.read(check_id)
print(f"Retrieved data: {data}")