Skip to content

Commit

Permalink
fix: restart caching loop automatically upon fail
Browse files Browse the repository at this point in the history
  • Loading branch information
iamdefinitelyahuman committed Feb 4, 2024
1 parent fe289c4 commit a1aa8c6
Showing 1 changed file with 20 additions and 6 deletions.
26 changes: 20 additions & 6 deletions brownie/network/middlewares/caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,17 +105,21 @@ def __init__(self, w3: Web3) -> None:
self.cur = Cursor(_get_data_folder().joinpath("cache.db"))
self.cur.execute(f"CREATE TABLE IF NOT EXISTS {self.table_key} (method, params, result)")

latest = w3.eth.get_block("latest")
self.lock = threading.Lock()
self.event = threading.Event()
self.start()

def start(self):
latest = self.w3.eth.get_block("latest")
self.last_block = latest.hash
self.last_block_seen = latest.timestamp
self.last_request = 0.0
self.last_request = time.time()
self.block_cache: OrderedDict = OrderedDict()
self.block_filter = w3.eth.filter("latest")
self.block_filter = self.w3.eth.filter("latest")

self.lock = threading.Lock()
self.event = threading.Event()
self.is_killed = False
threading.Thread(target=self.block_filter_loop, daemon=True).start()
self.loop_thread = threading.Thread(target=self.loop_exception_handler, daemon=True)
self.loop_thread.start()

@classmethod
def get_layer(cls, w3: Web3, network_type: str) -> Optional[int]:
Expand All @@ -138,6 +142,13 @@ def get_layer(cls, w3: Web3, network_type: str) -> Optional[int]:
def time_since(self) -> float:
return time.time() - self.last_request

def loop_exception_handler(self) -> None:
try:
self.block_filter_loop()
except Exception:
self.block_cache.clear()
self.is_killed = True

def block_filter_loop(self) -> None:
while not self.is_killed:
# if the last RPC request was > 60 seconds ago, reduce the rate of updates.
Expand Down Expand Up @@ -215,6 +226,9 @@ def process_request(self, make_request: Callable, method: str, params: List) ->
data = HexBytes(data)
return {"id": "cache", "jsonrpc": "2.0", "result": data}

if not self.loop_thread.is_alive():
self.start()

with self.lock:
self.last_request = time.time()
self.event.set()
Expand Down

0 comments on commit a1aa8c6

Please sign in to comment.