|
1 | 1 | """ Utility functions for the server. """ |
2 | 2 |
|
| 3 | +import asyncio |
3 | 4 | import math |
| 5 | +import shutil |
| 6 | +import time |
| 7 | +from contextlib import asynccontextmanager |
| 8 | +from pathlib import Path |
4 | 9 |
|
5 | | -from slowapi import Limiter |
| 10 | +from fastapi import FastAPI, Request |
| 11 | +from fastapi.responses import Response |
| 12 | +from slowapi import Limiter, _rate_limit_exceeded_handler |
| 13 | +from slowapi.errors import RateLimitExceeded |
6 | 14 | from slowapi.util import get_remote_address |
7 | 15 |
|
| 16 | +from gitingest.config import TMP_BASE_PATH |
| 17 | +from server.server_config import DELETE_REPO_AFTER |
| 18 | + |
8 | 19 | # Initialize a rate limiter |
9 | 20 | limiter = Limiter(key_func=get_remote_address) |
10 | 21 |
|
11 | 22 |
|
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | + |
| 27 | +async def rate_limit_exception_handler(request: Request, exc: Exception) -> Response: |
| 28 | + """ |
| 29 | + Custom exception handler for rate-limiting errors. |
| 30 | +
|
| 31 | + Parameters |
| 32 | + ---------- |
| 33 | + request : Request |
| 34 | + The incoming HTTP request. |
| 35 | + exc : Exception |
| 36 | + The exception raised, expected to be RateLimitExceeded. |
| 37 | +
|
| 38 | + Returns |
| 39 | + ------- |
| 40 | + Response |
| 41 | + A response indicating that the rate limit has been exceeded. |
| 42 | +
|
| 43 | + Raises |
| 44 | + ------ |
| 45 | + exc |
| 46 | + If the exception is not a RateLimitExceeded error, it is re-raised. |
| 47 | + """ |
| 48 | + if isinstance(exc, RateLimitExceeded): |
| 49 | + # Delegate to the default rate limit handler |
| 50 | + return _rate_limit_exceeded_handler(request, exc) |
| 51 | + # Re-raise other exceptions |
| 52 | + raise exc |
| 53 | + |
| 54 | + |
| 55 | +@asynccontextmanager |
| 56 | +async def lifespan(_: FastAPI): |
| 57 | + """ |
| 58 | + Lifecycle manager for handling startup and shutdown events for the FastAPI application. |
| 59 | +
|
| 60 | + Parameters |
| 61 | + ---------- |
| 62 | + _ : FastAPI |
| 63 | + The FastAPI application instance (unused). |
| 64 | +
|
| 65 | + Yields |
| 66 | + ------- |
| 67 | + None |
| 68 | + Yields control back to the FastAPI application while the background task runs. |
| 69 | + """ |
| 70 | + task = asyncio.create_task(_remove_old_repositories()) |
| 71 | + |
| 72 | + yield |
| 73 | + # Cancel the background task on shutdown |
| 74 | + task.cancel() |
| 75 | + try: |
| 76 | + await task |
| 77 | + except asyncio.CancelledError: |
| 78 | + pass |
| 79 | + |
| 80 | + |
| 81 | +async def _remove_old_repositories(): |
| 82 | + """ |
| 83 | + Periodically remove old repository folders. |
| 84 | +
|
| 85 | + Background task that runs periodically to clean up old repository directories. |
| 86 | +
|
| 87 | + This task: |
| 88 | + - Scans the TMP_BASE_PATH directory every 60 seconds |
| 89 | + - Removes directories older than DELETE_REPO_AFTER seconds |
| 90 | + - Before deletion, logs repository URLs to history.txt if a matching .txt file exists |
| 91 | + - Handles errors gracefully if deletion fails |
| 92 | +
|
| 93 | + The repository URL is extracted from the first .txt file in each directory, |
| 94 | + assuming the filename format: "owner-repository.txt" |
| 95 | + """ |
| 96 | + while True: |
| 97 | + try: |
| 98 | + if not TMP_BASE_PATH.exists(): |
| 99 | + await asyncio.sleep(60) |
| 100 | + continue |
| 101 | + |
| 102 | + current_time = time.time() |
| 103 | + |
| 104 | + for folder in TMP_BASE_PATH.iterdir(): |
| 105 | + if folder.is_dir(): |
| 106 | + continue |
| 107 | + |
| 108 | + # Skip if folder is not old enough |
| 109 | + if current_time - folder.stat().st_ctime <= DELETE_REPO_AFTER: |
| 110 | + continue |
| 111 | + |
| 112 | + await _process_folder(folder) |
| 113 | + |
| 114 | + except Exception as e: |
| 115 | + print(f"Error in _remove_old_repositories: {e}") |
| 116 | + |
| 117 | + await asyncio.sleep(60) |
| 118 | + |
| 119 | + |
| 120 | +async def _process_folder(folder: Path) -> None: |
| 121 | + """ |
| 122 | + Process a single folder for deletion and logging. |
| 123 | +
|
| 124 | + Parameters |
| 125 | + ---------- |
| 126 | + folder : Path |
| 127 | + The path to the folder to be processed. |
| 128 | + """ |
| 129 | + # Try to log repository URL before deletion |
| 130 | + try: |
| 131 | + txt_files = [f for f in folder.iterdir() if f.suffix == ".txt"] |
| 132 | + |
| 133 | + # Extract owner and repository name from the filename |
| 134 | + if txt_files and "-" in (filename := txt_files[0].stem): |
| 135 | + owner, repo = filename.split("-", 1) |
| 136 | + repo_url = f"{owner}/{repo}" |
| 137 | + |
| 138 | + with open("history.txt", mode="a", encoding="utf-8") as history: |
| 139 | + history.write(f"{repo_url}\n") |
| 140 | + |
| 141 | + except Exception as e: |
| 142 | + print(f"Error logging repository URL for {folder}: {e}") |
| 143 | + |
| 144 | + # Delete the folder |
| 145 | + try: |
| 146 | + shutil.rmtree(folder) |
| 147 | + except Exception as e: |
| 148 | + print(f"Error deleting {folder}: {e}") |
| 149 | + |
| 150 | + |
12 | 151 | def log_slider_to_size(position: int) -> int: |
13 | 152 | """ |
14 | 153 | Convert a slider position to a file size in bytes using a logarithmic scale. |
|
0 commit comments