|
1 | 1 | """ Main module for the FastAPI application. """ |
2 | 2 |
|
| 3 | +import asyncio |
3 | 4 | import os |
| 5 | +import shutil |
| 6 | +import time |
| 7 | +from contextlib import asynccontextmanager |
4 | 8 |
|
5 | 9 | from api_analytics.fastapi import Analytics |
6 | 10 | from dotenv import load_dotenv |
|
12 | 16 | from slowapi.errors import RateLimitExceeded |
13 | 17 | from starlette.middleware.trustedhost import TrustedHostMiddleware |
14 | 18 |
|
| 19 | +from config import DELETE_REPO_AFTER, TMP_BASE_PATH |
15 | 20 | from routers import download, dynamic, index |
16 | 21 | from server_utils import limiter |
17 | 22 |
|
18 | 23 | # Load environment variables from .env file |
19 | 24 | load_dotenv() |
20 | 25 |
|
21 | | -# Initialize the FastAPI application |
22 | | -app = FastAPI() |
| 26 | + |
| 27 | +async def remove_old_repositories(): |
| 28 | + """ |
| 29 | + Background task that runs periodically to clean up old repository directories. |
| 30 | +
|
| 31 | + This task: |
| 32 | + - Scans the TMP_BASE_PATH directory every 60 seconds |
| 33 | + - Removes directories older than DELETE_REPO_AFTER seconds |
| 34 | + - Before deletion, logs repository URLs to history.txt if a matching .txt file exists |
| 35 | + - Handles errors gracefully if deletion fails |
| 36 | +
|
| 37 | + The repository URL is extracted from the first .txt file in each directory, |
| 38 | + assuming the filename format: "owner-repository.txt" |
| 39 | + """ |
| 40 | + while True: |
| 41 | + try: |
| 42 | + if not os.path.exists(TMP_BASE_PATH): |
| 43 | + await asyncio.sleep(60) |
| 44 | + continue |
| 45 | + |
| 46 | + current_time = time.time() |
| 47 | + |
| 48 | + for folder in os.listdir(TMP_BASE_PATH): |
| 49 | + folder_path = os.path.join(TMP_BASE_PATH, folder) |
| 50 | + |
| 51 | + # Skip if folder is not old enough |
| 52 | + if current_time - os.path.getctime(folder_path) <= DELETE_REPO_AFTER: |
| 53 | + continue |
| 54 | + |
| 55 | + # Try to log repository URL before deletion |
| 56 | + try: |
| 57 | + txt_files = [f for f in os.listdir(folder_path) if f.endswith(".txt")] |
| 58 | + if txt_files: |
| 59 | + filename = txt_files[0].replace(".txt", "") |
| 60 | + if "-" in filename: |
| 61 | + owner, repo = filename.split("-", 1) |
| 62 | + repo_url = f"https://github.com/{owner}/{repo}" |
| 63 | + with open("history.txt", "a") as history: |
| 64 | + history.write(f"{repo_url}\n") |
| 65 | + except Exception as e: |
| 66 | + print(f"Error logging repository URL for {folder_path}: {str(e)}") |
| 67 | + |
| 68 | + # Delete the folder |
| 69 | + try: |
| 70 | + shutil.rmtree(folder_path) |
| 71 | + except Exception as e: |
| 72 | + print(f"Error deleting {folder_path}: {str(e)}") |
| 73 | + |
| 74 | + except Exception as e: |
| 75 | + print(f"Error in remove_old_repositories: {str(e)}") |
| 76 | + |
| 77 | + await asyncio.sleep(60) |
| 78 | + |
| 79 | + |
| 80 | +@asynccontextmanager |
| 81 | +async def lifespan(app: FastAPI): |
| 82 | + """ |
| 83 | + Lifecycle manager for the FastAPI application. |
| 84 | + Handles startup and shutdown events. |
| 85 | + """ |
| 86 | + task = asyncio.create_task(remove_old_repositories()) |
| 87 | + |
| 88 | + yield |
| 89 | + # Cancel the background task on shutdown |
| 90 | + task.cancel() |
| 91 | + try: |
| 92 | + await task |
| 93 | + except asyncio.CancelledError: |
| 94 | + pass |
| 95 | + |
| 96 | + |
| 97 | +# Initialize the FastAPI application with lifespan |
| 98 | +app = FastAPI(lifespan=lifespan) |
23 | 99 | app.state.limiter = limiter |
24 | 100 |
|
25 | 101 |
|
|
0 commit comments