Skip to content

Commit e8d6994

Browse files
fix: restart caching loop automatically upon fail
1 parent fe289c4 commit e8d6994

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

brownie/network/middlewares/caching.py

+22-6
Original file line numberDiff line numberDiff line change
@@ -105,17 +105,21 @@ def __init__(self, w3: Web3) -> None:
105105
self.cur = Cursor(_get_data_folder().joinpath("cache.db"))
106106
self.cur.execute(f"CREATE TABLE IF NOT EXISTS {self.table_key} (method, params, result)")
107107

108-
latest = w3.eth.get_block("latest")
108+
self.lock = threading.Lock()
109+
self.event = threading.Event()
110+
self.start()
111+
112+
def start(self):
113+
latest = self.w3.eth.get_block("latest")
109114
self.last_block = latest.hash
110115
self.last_block_seen = latest.timestamp
111-
self.last_request = 0.0
116+
self.last_request = time.time()
112117
self.block_cache: OrderedDict = OrderedDict()
113-
self.block_filter = w3.eth.filter("latest")
118+
self.block_filter = self.w3.eth.filter("latest")
114119

115-
self.lock = threading.Lock()
116-
self.event = threading.Event()
117120
self.is_killed = False
118-
threading.Thread(target=self.block_filter_loop, daemon=True).start()
121+
self.loop_thread = threading.Thread(target=self.loop_exception_handler, daemon=True)
122+
self.loop_thread.start()
119123

120124
@classmethod
121125
def get_layer(cls, w3: Web3, network_type: str) -> Optional[int]:
@@ -138,6 +142,14 @@ def get_layer(cls, w3: Web3, network_type: str) -> Optional[int]:
138142
def time_since(self) -> float:
139143
return time.time() - self.last_request
140144

145+
def loop_exception_handler(self) -> None:
146+
try:
147+
self.block_filter_loop()
148+
except Exception:
149+
# catch unhandled exceptions to avoid random error messages in the console
150+
self.block_cache.clear()
151+
self.is_killed = True
152+
141153
def block_filter_loop(self) -> None:
142154
while not self.is_killed:
143155
# if the last RPC request was > 60 seconds ago, reduce the rate of updates.
@@ -215,6 +227,10 @@ def process_request(self, make_request: Callable, method: str, params: List) ->
215227
data = HexBytes(data)
216228
return {"id": "cache", "jsonrpc": "2.0", "result": data}
217229

230+
if not self.loop_thread.is_alive():
231+
# restart the block filter loop if it has crashed (usually from a ConnectionError)
232+
self.start()
233+
218234
with self.lock:
219235
self.last_request = time.time()
220236
self.event.set()

0 commit comments

Comments
 (0)