Skip to content

Commit 360ec46

Browse files
committed
Refactor cache middleware and enhance health page error handling
- Updated the CacheMiddleware to remove placeholder files on non-200 responses and exceptions, allowing for retries instead of overwriting with error states. - Introduced a new helper function `has_error` in the health page to check for errors in API results. - Enhanced the health page to display error messages when fetching data for largest perp positions, most levered positions, largest spot borrows, and most levered spot borrows, improving user feedback during data retrieval.
1 parent f15ca3a commit 360ec46

File tree

2 files changed

+25
-9
lines changed

2 files changed

+25
-9
lines changed

backend/middleware/cache_middleware.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -392,9 +392,13 @@ async def _fetch_and_cache(
392392
logger.warning(
393393
f"Failed to fetch data for {request.url.path}. Status code: {response.status_code}"
394394
)
395-
# Overwrite placeholder with error state or remove? Let's overwrite.
396-
with open(cache_file, "w") as f:
397-
json.dump({"content": ERROR_PLACEHOLDER, "status_code": response.status_code, "headers": {}}, f)
395+
# On failure, remove the placeholder to allow retries
396+
if os.path.exists(cache_file):
397+
try:
398+
os.remove(cache_file)
399+
logger.info(f"Removed placeholder file due to non-200 response: {cache_file}")
400+
except OSError as e:
401+
logger.error(f"Failed to remove placeholder file {cache_file} after non-200 response: {e}")
398402

399403
# Run cleanup AFTER successfully writing new cache or error placeholder
400404
self.cleanup_old_cache_files()
@@ -403,12 +407,13 @@ async def _fetch_and_cache(
403407
logger.error(
404408
f"Error in background task for {request.url.path} under key {cache_key}: {str(e)}"
405409
)
406-
# Attempt to overwrite placeholder with error state
407-
try:
408-
with open(cache_file, "w") as f:
409-
json.dump({"content": ERROR_PLACEHOLDER, "status_code": 500, "headers": {}}, f)
410-
except Exception as write_e:
411-
logger.error(f"Failed to write error placeholder for {cache_file}: {write_e}")
410+
# On failure, remove the placeholder to allow retries
411+
if os.path.exists(cache_file):
412+
try:
413+
os.remove(cache_file)
414+
logger.info(f"Removed placeholder file due to exception: {cache_file}")
415+
except OSError as remove_e:
416+
logger.error(f"Failed to remove placeholder file {cache_file} after exception: {remove_e}")
412417
import traceback
413418
traceback.print_exc()
414419
finally:

src/page/health.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ def is_processing(result):
1212
"""Checks if the API result indicates backend processing."""
1313
return isinstance(result, dict) and result.get("result") == "processing"
1414

15+
def has_error(result):
16+
"""Checks if the API result indicates an error."""
17+
return isinstance(result, dict) and "error" in result
1518

1619
def _get_perp_market_symbol_display(market_index):
1720
"""Safely get the display string for a perp market index."""
@@ -190,6 +193,8 @@ def health_page():
190193

191194
if is_processing(largest_perp_positions):
192195
is_still_processing = True
196+
elif has_error(largest_perp_positions):
197+
st.error(f"Error fetching largest perp positions: {largest_perp_positions.get('error', 'Unknown error')}")
193198
else:
194199
# Convert to DataFrame and add pagination
195200
df = pd.DataFrame(largest_perp_positions)
@@ -236,6 +241,8 @@ def health_page():
236241

237242
if is_processing(most_levered_positions):
238243
is_still_processing = True
244+
elif has_error(most_levered_positions):
245+
st.error(f"Error fetching most levered perp positions: {most_levered_positions.get('error', 'Unknown error')}")
239246
else:
240247
# Format market index in most_levered_positions too
241248
most_levered_df = pd.DataFrame(most_levered_positions)
@@ -310,6 +317,8 @@ def health_page():
310317

311318
if is_processing(largest_spot_borrows):
312319
is_still_processing = True
320+
elif has_error(largest_spot_borrows):
321+
st.error(f"Error fetching largest spot borrows: {largest_spot_borrows.get('error', 'Unknown error')}")
313322
else:
314323
# Convert to dataframe and add market symbols
315324
spot_df = pd.DataFrame(largest_spot_borrows)
@@ -356,6 +365,8 @@ def health_page():
356365
)
357366
if is_processing(most_levered_borrows):
358367
is_still_processing = True
368+
elif has_error(most_levered_borrows):
369+
st.error(f"Error fetching most levered spot borrows: {most_levered_borrows.get('error', 'Unknown error')}")
359370
else:
360371
# Convert to dataframe and add market symbols
361372
levered_spot_df = pd.DataFrame(most_levered_borrows)

0 commit comments

Comments
 (0)