|
| 1 | +import asyncio |
| 2 | +import json |
| 3 | +import os |
| 4 | +import time |
| 5 | +import threading |
| 6 | +from typing import Optional |
| 7 | +from substrateinterface import SubstrateInterface |
| 8 | +from pathlib import Path |
| 9 | + |
| 10 | +from loggers.logging_utils import get_logger |
| 11 | + |
| 12 | +logger = get_logger(__name__) |
| 13 | + |
| 14 | +NETUID = os.getenv("NETUID", "62") |
| 15 | +SUBTENSOR_URL = os.getenv("SUBTENSOR_ADDRESS", "ws://127.0.0.1:9945") |
| 16 | +CACHE_FILE = Path("subnet_hotkeys_cache.json") |
| 17 | + |
| 18 | +class HotkeySubscriptionManager: |
| 19 | + def __init__(self): |
| 20 | + self.is_running = False |
| 21 | + self.main_loop: Optional[asyncio.AbstractEventLoop] = None |
| 22 | + |
| 23 | + async def start_subscription(self) -> None: |
| 24 | + if self.is_running: |
| 25 | + return |
| 26 | + |
| 27 | + self.is_running = True |
| 28 | + self.main_loop = asyncio.get_running_loop() |
| 29 | + logger.info("Starting hotkey subscription service") |
| 30 | + |
| 31 | + await self._update_cache() |
| 32 | + |
| 33 | + asyncio.create_task(self._subscription_loop()) |
| 34 | + |
| 35 | + async def stop_subscription(self) -> None: |
| 36 | + self.is_running = False |
| 37 | + logger.info("Stopped hotkey subscription service") |
| 38 | + |
| 39 | + async def _subscription_loop(self) -> None: |
| 40 | + retry_delay = 1.0 |
| 41 | + |
| 42 | + while self.is_running: |
| 43 | + try: |
| 44 | + await self._run_subscription() |
| 45 | + retry_delay = 1.0 # Reset on success |
| 46 | + except Exception as e: |
| 47 | + logger.error(f"Subscription failed: {e}") |
| 48 | + if retry_delay < 60: |
| 49 | + retry_delay *= 2 |
| 50 | + await asyncio.sleep(retry_delay) |
| 51 | + |
| 52 | + async def _run_subscription(self) -> None: |
| 53 | + substrate = SubstrateInterface( |
| 54 | + url=SUBTENSOR_URL, |
| 55 | + ss58_format=42, |
| 56 | + type_registry_preset="substrate-node-template" |
| 57 | + ) |
| 58 | + |
| 59 | + try: |
| 60 | + storage_key = substrate.create_storage_key("SubtensorModule", "Uids", [NETUID]) |
| 61 | + |
| 62 | + def handler(storage_key, obj, update_nr, subscription_id): |
| 63 | + if not self.is_running: |
| 64 | + return True |
| 65 | + if self.main_loop and not self.main_loop.is_closed(): |
| 66 | + asyncio.run_coroutine_threadsafe(self._update_cache(), self.main_loop) |
| 67 | + return None |
| 68 | + |
| 69 | + # Run in thread to avoid blocking |
| 70 | + def subscription_thread(): |
| 71 | + try: |
| 72 | + substrate.subscribe_storage([storage_key], handler) |
| 73 | + except Exception as e: |
| 74 | + # Filters out expected errors, such as |
| 75 | + # ERROR - Subscription error: Expecting value: line 1 column 1 (char 0) |
| 76 | + # ERROR - Subscription error: Connection closed |
| 77 | + # ERROR - Subscription error: WebSocket connection is closed |
| 78 | + if not any(x in str(e).lower() for x in ["expecting value", "json", "connection", "closed"]): |
| 79 | + logger.error(f"Subscription error: {e}") |
| 80 | + finally: |
| 81 | + try: |
| 82 | + substrate.close() |
| 83 | + except: |
| 84 | + pass |
| 85 | + |
| 86 | + thread = threading.Thread(target=subscription_thread, daemon=True) |
| 87 | + thread.start() |
| 88 | + |
| 89 | + while self.is_running and thread.is_alive(): |
| 90 | + await asyncio.sleep(1) |
| 91 | + |
| 92 | + finally: |
| 93 | + try: |
| 94 | + substrate.close() |
| 95 | + except: |
| 96 | + pass |
| 97 | + |
| 98 | + async def _update_cache(self) -> None: |
| 99 | + try: |
| 100 | + substrate = SubstrateInterface( |
| 101 | + url=SUBTENSOR_URL, |
| 102 | + ss58_format=42, |
| 103 | + type_registry_preset="substrate-node-template" |
| 104 | + ) |
| 105 | + |
| 106 | + result = substrate.query_map("SubtensorModule", "Uids", [NETUID]) |
| 107 | + hotkeys = [] |
| 108 | + |
| 109 | + for uid_data in result: |
| 110 | + try: |
| 111 | + hotkey = uid_data[0] |
| 112 | + if hasattr(hotkey, 'value'): |
| 113 | + hotkey = hotkey.value |
| 114 | + if isinstance(hotkey, bytes): |
| 115 | + hotkey = substrate.ss58_encode(hotkey) |
| 116 | + hotkeys.append(hotkey) |
| 117 | + except: |
| 118 | + continue |
| 119 | + |
| 120 | + # Atomic write |
| 121 | + temp_file = CACHE_FILE.with_suffix('.tmp') |
| 122 | + with open(temp_file, 'w') as f: |
| 123 | + json.dump({"hotkeys": hotkeys, "timestamp": time.time()}, f) |
| 124 | + temp_file.replace(CACHE_FILE) |
| 125 | + |
| 126 | + logger.info(f"Updated cache with {len(hotkeys)} hotkeys") |
| 127 | + substrate.close() |
| 128 | + |
| 129 | + except Exception as e: |
| 130 | + logger.error(f"Failed to update cache: {e}") |
| 131 | + |
| 132 | +# Global instance |
| 133 | +_manager: Optional[HotkeySubscriptionManager] = None |
| 134 | + |
| 135 | +async def start_hotkey_subscription() -> None: |
| 136 | + global _manager |
| 137 | + if _manager is None: |
| 138 | + _manager = HotkeySubscriptionManager() |
| 139 | + await _manager.start_subscription() |
| 140 | + |
| 141 | +async def stop_hotkey_subscription() -> None: |
| 142 | + global _manager |
| 143 | + if _manager: |
| 144 | + await _manager.stop_subscription() |
0 commit comments