|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Example demonstrating how to create custom cache policies using Python hooks. |
| 4 | +
|
| 5 | +This example shows how to implement LRU and FIFO cache policies using the |
| 6 | +PythonHookCachePolicy class, which allows users to define cache behavior using |
| 7 | +pure Python functions instead of C/C++ plugins. |
| 8 | +""" |
| 9 | + |
| 10 | +import libcachesim as lcs |
| 11 | +from collections import OrderedDict, deque |
| 12 | + |
| 13 | + |
| 14 | +class LRUPolicy: |
| 15 | + """LRU (Least Recently Used) cache policy implementation.""" |
| 16 | + |
| 17 | + def __init__(self, cache_size): |
| 18 | + self.cache_size = cache_size |
| 19 | + self.access_order = OrderedDict() # obj_id -> True (for ordering) |
| 20 | + |
| 21 | + def on_hit(self, obj_id, obj_size): |
| 22 | + """Move accessed object to end (most recent).""" |
| 23 | + if obj_id in self.access_order: |
| 24 | + # Move to end (most recent) |
| 25 | + self.access_order.move_to_end(obj_id) |
| 26 | + |
| 27 | + def on_miss(self, obj_id, obj_size): |
| 28 | + """Add new object to end (most recent).""" |
| 29 | + self.access_order[obj_id] = True |
| 30 | + |
| 31 | + def evict(self, obj_id, obj_size): |
| 32 | + """Return the least recently used object ID.""" |
| 33 | + if self.access_order: |
| 34 | + # Return first item (least recent) |
| 35 | + victim_id = next(iter(self.access_order)) |
| 36 | + return victim_id |
| 37 | + raise RuntimeError("No objects to evict") |
| 38 | + |
| 39 | + def on_remove(self, obj_id): |
| 40 | + """Remove object from tracking.""" |
| 41 | + self.access_order.pop(obj_id, None) |
| 42 | + |
| 43 | + |
| 44 | +class FIFOPolicy: |
| 45 | + """FIFO (First In First Out) cache policy implementation.""" |
| 46 | + |
| 47 | + def __init__(self, cache_size): |
| 48 | + self.cache_size = cache_size |
| 49 | + self.insertion_order = deque() # obj_id queue |
| 50 | + |
| 51 | + def on_hit(self, obj_id, obj_size): |
| 52 | + """FIFO doesn't change order on hits.""" |
| 53 | + pass |
| 54 | + |
| 55 | + def on_miss(self, obj_id, obj_size): |
| 56 | + """Add new object to end of queue.""" |
| 57 | + self.insertion_order.append(obj_id) |
| 58 | + |
| 59 | + def evict(self, obj_id, obj_size): |
| 60 | + """Return the first inserted object ID.""" |
| 61 | + if self.insertion_order: |
| 62 | + victim_id = self.insertion_order.popleft() |
| 63 | + return victim_id |
| 64 | + raise RuntimeError("No objects to evict") |
| 65 | + |
| 66 | + def on_remove(self, obj_id): |
| 67 | + """Remove object from tracking.""" |
| 68 | + try: |
| 69 | + self.insertion_order.remove(obj_id) |
| 70 | + except ValueError: |
| 71 | + pass # Object not in queue |
| 72 | + |
| 73 | + |
| 74 | +def create_lru_cache(cache_size): |
| 75 | + """Create an LRU cache using Python hooks.""" |
| 76 | + cache = lcs.PythonHookCachePolicy(cache_size, "PythonLRU") |
| 77 | + |
| 78 | + def init_hook(cache_size): |
| 79 | + return LRUPolicy(cache_size) |
| 80 | + |
| 81 | + def hit_hook(policy, obj_id, obj_size): |
| 82 | + policy.on_hit(obj_id, obj_size) |
| 83 | + |
| 84 | + def miss_hook(policy, obj_id, obj_size): |
| 85 | + policy.on_miss(obj_id, obj_size) |
| 86 | + |
| 87 | + def eviction_hook(policy, obj_id, obj_size): |
| 88 | + return policy.evict(obj_id, obj_size) |
| 89 | + |
| 90 | + def remove_hook(policy, obj_id): |
| 91 | + policy.on_remove(obj_id) |
| 92 | + |
| 93 | + def free_hook(policy): |
| 94 | + # Python garbage collection handles cleanup |
| 95 | + pass |
| 96 | + |
| 97 | + cache.set_hooks(init_hook, hit_hook, miss_hook, eviction_hook, remove_hook, free_hook) |
| 98 | + return cache |
| 99 | + |
| 100 | + |
| 101 | +def create_fifo_cache(cache_size): |
| 102 | + """Create a FIFO cache using Python hooks.""" |
| 103 | + cache = lcs.PythonHookCachePolicy(cache_size, "PythonFIFO") |
| 104 | + |
| 105 | + def init_hook(cache_size): |
| 106 | + return FIFOPolicy(cache_size) |
| 107 | + |
| 108 | + def hit_hook(policy, obj_id, obj_size): |
| 109 | + policy.on_hit(obj_id, obj_size) |
| 110 | + |
| 111 | + def miss_hook(policy, obj_id, obj_size): |
| 112 | + policy.on_miss(obj_id, obj_size) |
| 113 | + |
| 114 | + def eviction_hook(policy, obj_id, obj_size): |
| 115 | + return policy.evict(obj_id, obj_size) |
| 116 | + |
| 117 | + def remove_hook(policy, obj_id): |
| 118 | + policy.on_remove(obj_id) |
| 119 | + |
| 120 | + cache.set_hooks(init_hook, hit_hook, miss_hook, eviction_hook, remove_hook) |
| 121 | + return cache |
| 122 | + |
| 123 | + |
| 124 | +def test_cache_policy(cache, name): |
| 125 | + """Test a cache policy with sample requests.""" |
| 126 | + print(f"\n=== Testing {name} Cache ===") |
| 127 | + |
| 128 | + # Test requests: obj_id, obj_size |
| 129 | + test_requests = [ |
| 130 | + (1, 100), (2, 100), (3, 100), (4, 100), (5, 100), # Fill cache |
| 131 | + (1, 100), # Hit |
| 132 | + (6, 100), # Miss, should evict something |
| 133 | + (2, 100), # Hit or miss depending on policy |
| 134 | + (7, 100), # Miss, should evict something |
| 135 | + ] |
| 136 | + |
| 137 | + hits = 0 |
| 138 | + misses = 0 |
| 139 | + |
| 140 | + for obj_id, obj_size in test_requests: |
| 141 | + req = lcs.Request() |
| 142 | + req.obj_id = obj_id |
| 143 | + req.obj_size = obj_size |
| 144 | + |
| 145 | + hit = cache.get(req) |
| 146 | + if hit: |
| 147 | + hits += 1 |
| 148 | + print(f"Request {obj_id}: HIT") |
| 149 | + else: |
| 150 | + misses += 1 |
| 151 | + print(f"Request {obj_id}: MISS") |
| 152 | + |
| 153 | + print(f"Total: {hits} hits, {misses} misses") |
| 154 | + print(f"Cache stats: {cache.n_obj} objects, {cache.occupied_byte} bytes occupied") |
| 155 | + |
| 156 | + |
| 157 | +def main(): |
| 158 | + """Main example function.""" |
| 159 | + cache_size = 400 # Bytes (can hold 4 objects of size 100 each) |
| 160 | + |
| 161 | + # Test LRU cache |
| 162 | + lru_cache = create_lru_cache(cache_size) |
| 163 | + test_cache_policy(lru_cache, "LRU") |
| 164 | + |
| 165 | + # Test FIFO cache |
| 166 | + fifo_cache = create_fifo_cache(cache_size) |
| 167 | + test_cache_policy(fifo_cache, "FIFO") |
| 168 | + |
| 169 | + print("\n=== Comparison ===") |
| 170 | + print("LRU keeps recently accessed items, evicting least recently used") |
| 171 | + print("FIFO keeps items in insertion order, evicting oldest inserted") |
| 172 | + |
| 173 | + |
| 174 | +if __name__ == "__main__": |
| 175 | + main() |
0 commit comments