Skip to content

Commit 89375c1

Browse files
authored
Merge pull request #255 from DevanshuNEU/chore/cleanup-dotenv-headers-emojis
chore: consolidate load_dotenv, remove decorative headers, fix emojis (OPE-86, OPE-74)
2 parents c667760 + 00faee5 commit 89375c1

19 files changed

Lines changed: 37 additions & 167 deletions

backend/config/api.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,11 @@
55
Example: "v1" -> "v2" will change /api/v1/* to /api/v2/*
66
"""
77

8-
# =============================================================================
98
# API VERSION CONFIGURATION
10-
# =============================================================================
119

1210
API_VERSION = "v1"
1311

14-
# =============================================================================
1512
# DERIVED PREFIXES (auto-calculated from version)
16-
# =============================================================================
1713

1814
# Current versioned API prefix: /api/v1
1915
API_PREFIX = f"/api/{API_VERSION}"
@@ -22,9 +18,7 @@
2218
# Routes here will be deprecated but still functional
2319
LEGACY_API_PREFIX = "/api"
2420

25-
# =============================================================================
2621
# DEPRECATION SETTINGS
27-
# =============================================================================
2822

2923
# When True, legacy routes (/api/*) will include deprecation warning headers
3024
LEGACY_DEPRECATION_ENABLED = True
@@ -33,9 +27,7 @@
3327
DEPRECATION_HEADER = "X-API-Deprecated"
3428
DEPRECATION_MESSAGE = f"This endpoint is deprecated. Please use {API_PREFIX} instead."
3529

36-
# =============================================================================
3730
# HELPER FUNCTIONS
38-
# =============================================================================
3931

4032
def get_versioned_prefix() -> str:
4133
"""Get the current versioned API prefix."""

backend/dependencies.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,6 @@
33
All route modules import from here to avoid circular imports.
44
"""
55
from fastapi import HTTPException, Depends
6-
from dotenv import load_dotenv
7-
8-
# Load env vars first
9-
load_dotenv()
106

117
from services.indexer_optimized import OptimizedCodeIndexer
128
from services.repo_manager import RepositoryManager

backend/main.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22
CodeIntel Backend API
33
FastAPI backend for codebase intelligence
44
"""
5+
# Load env vars once, before any service reads them
6+
from dotenv import load_dotenv
7+
load_dotenv()
8+
59
from contextlib import asynccontextmanager
610
from fastapi import FastAPI, Request
711
from fastapi.middleware.cors import CORSMiddleware
@@ -51,8 +55,7 @@ async def lifespan(app: FastAPI):
5155
)
5256

5357

54-
# ===== MIDDLEWARE =====
55-
58+
# MIDDLEWARE
5659
class RequestSizeLimitMiddleware(BaseHTTPMiddleware):
5760
"""Limit request body size to prevent abuse."""
5861
MAX_REQUEST_SIZE = 10 * 1024 * 1024 # 10MB
@@ -81,7 +84,7 @@ async def dispatch(self, request: Request, call_next):
8184
)
8285

8386

84-
# ===== ROUTERS =====
87+
# ROUTERS
8588
# All API routes are prefixed with API_PREFIX (e.g., /api/v1)
8689
# Route files define their sub-path (e.g., /auth, /repos)
8790
# Final paths: /api/v1/auth, /api/v1/repos, etc.
@@ -104,8 +107,7 @@ async def dispatch(self, request: Request, call_next):
104107
app.add_api_websocket_route(f"{API_PREFIX}/ws/repos/{{repo_id}}/indexing", websocket_repo_indexing)
105108

106109

107-
# ===== ERROR HANDLERS =====
108-
110+
# ERROR HANDLERS
109111
@app.exception_handler(RequestValidationError)
110112
async def validation_exception_handler(request: Request, exc: RequestValidationError):
111113
"""Handle validation errors with clear messages."""

backend/middleware/auth.py

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,7 @@ async def demo_search(auth: AuthContext = Depends(public_auth)):
2929
from fastapi.security.http import HTTPAuthorizationCredentials
3030

3131

32-
# ---------------------------------------------------------------------------
3332
# Auth Context - unified return type for all auth methods
34-
# ---------------------------------------------------------------------------
3533

3634
@dataclass
3735
class AuthContext:
@@ -52,17 +50,13 @@ def identifier(self) -> str:
5250
return self.user_id or self.api_key_name or "anonymous"
5351

5452

55-
# ---------------------------------------------------------------------------
5653
# Bearer token scheme (auto_error=False allows optional auth)
57-
# ---------------------------------------------------------------------------
5854

5955
_bearer = HTTPBearer(auto_error=False)
6056
_bearer_required = HTTPBearer(auto_error=True)
6157

6258

63-
# ---------------------------------------------------------------------------
6459
# Core validation functions
65-
# ---------------------------------------------------------------------------
6660

6761
def _validate_jwt(token: str) -> Optional[AuthContext]:
6862
"""Validate Supabase JWT token"""
@@ -143,9 +137,7 @@ def _authenticate(token: str) -> AuthContext:
143137
)
144138

145139

146-
# ---------------------------------------------------------------------------
147140
# FastAPI Dependencies - use these in your routes
148-
# ---------------------------------------------------------------------------
149141

150142
async def require_auth(
151143
credentials: HTTPAuthorizationCredentials = Depends(_bearer_required)
@@ -177,9 +169,7 @@ async def public_auth(
177169
return AuthContext(is_public=True)
178170

179171

180-
# ---------------------------------------------------------------------------
181172
# Legacy functions - kept for backwards compatibility
182-
# ---------------------------------------------------------------------------
183173

184174
async def get_current_user(
185175
credentials: HTTPAuthorizationCredentials = Depends(_bearer_required)

backend/routes/playground.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -785,9 +785,7 @@ async def validate_github_repo(request: ValidateRepoRequest, req: Request):
785785
return result
786786

787787

788-
# =============================================================================
789788
# Anonymous Indexing Endpoint (#125)
790-
# =============================================================================
791789

792790
@router.post("/index", status_code=202)
793791
async def start_anonymous_indexing(
@@ -1030,9 +1028,7 @@ async def start_anonymous_indexing(
10301028
return response_data
10311029

10321030

1033-
# =============================================================================
10341031
# GET /playground/index/{job_id} - Check indexing job status (#126)
1035-
# =============================================================================
10361032

10371033
@router.get(
10381034
"/index/{job_id}",

backend/services/cache.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,9 @@
77
import hashlib
88
from typing import Optional, List, Dict
99
import os
10-
from dotenv import load_dotenv
1110

1211
from services.observability import logger, metrics
1312

14-
load_dotenv()
15-
1613
# Configuration
1714
REDIS_URL = os.getenv("REDIS_URL") # Railway/Cloud Redis URL
1815
REDIS_HOST = os.getenv("REDIS_HOST", "localhost")

backend/services/dependency_analyzer.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -399,8 +399,7 @@ def _find_test_files(self, file_path: str, nodes: List[Dict]) -> List[str]:
399399
return test_files
400400

401401

402-
# ===== SUPABASE CACHING =====
403-
402+
# SUPABASE CACHING
404403
def save_to_cache(self, repo_id: str, graph_data: Dict):
405404
"""Save dependency graph to Supabase for caching"""
406405
from services.supabase_service import get_supabase_service

backend/services/indexer_optimized.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727

2828
# Utils
2929
import hashlib
30-
from dotenv import load_dotenv
3130
import time
3231

3332
# Search enhancement
@@ -39,8 +38,6 @@
3938
# Observability
4039
from services.observability import logger, trace_operation, track_time, capture_exception, add_breadcrumb, metrics
4140

42-
load_dotenv()
43-
4441
# Configuration
4542
# Note: If using existing Pinecone index, match the dimension (1536 for small, 3072 for large)
4643
EMBEDDING_MODEL = os.getenv("EMBEDDING_MODEL", "text-embedding-3-small")

backend/services/observability.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,7 @@ async def index_repo(repo_id: str):
3030
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO" if IS_PRODUCTION else "DEBUG")
3131

3232

33-
# =============================================================================
3433
# STRUCTURED LOGGER
35-
# =============================================================================
3634

3735
class StructuredLogger:
3836
"""
@@ -112,9 +110,7 @@ def critical(self, message: str, **kwargs):
112110
logger = StructuredLogger()
113111

114112

115-
# =============================================================================
116113
# SENTRY INTEGRATION HELPERS
117-
# =============================================================================
118114

119115
def set_operation_context(operation: str, **kwargs):
120116
"""
@@ -191,9 +187,7 @@ def capture_message(message: str, level: str = "info", **context):
191187
pass
192188

193189

194-
# =============================================================================
195190
# PERFORMANCE TRACKING
196-
# =============================================================================
197191

198192
@contextmanager
199193
def track_time(operation: str, **tags):
@@ -307,9 +301,7 @@ def sync_wrapper(*args, **kwargs):
307301
return decorator
308302

309303

310-
# =============================================================================
311304
# SIMPLE METRICS (in-memory counters)
312-
# =============================================================================
313305

314306
class Metrics:
315307
"""

backend/services/playground_limiter.py

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,7 @@
2525
from services.sentry import capture_exception
2626

2727

28-
# =============================================================================
2928
# DATA CLASSES
30-
# =============================================================================
3129

3230
@dataclass
3331
class PlaygroundLimitResult:
@@ -134,9 +132,7 @@ def _truncate_id(session_id: str) -> str:
134132
return session_id
135133

136134

137-
# =============================================================================
138135
# MAIN CLASS
139-
# =============================================================================
140136

141137
class PlaygroundLimiter:
142138
"""
@@ -161,9 +157,7 @@ class PlaygroundLimiter:
161157
has_repo = limiter.has_indexed_repo(session_token)
162158
"""
163159

164-
# -------------------------------------------------------------------------
165160
# Configuration
166-
# -------------------------------------------------------------------------
167161

168162
# Rate limits
169163
SESSION_LIMIT_PER_DAY = 50 # Per device (generous for conversion)
@@ -198,9 +192,7 @@ def __init__(self, redis_client=None):
198192
"""
199193
self.redis = redis_client
200194

201-
# -------------------------------------------------------------------------
202195
# Session Data Methods (#127)
203-
# -------------------------------------------------------------------------
204196

205197
def get_session_data(self, session_token: Optional[str]) -> SessionData:
206198
"""
@@ -449,9 +441,7 @@ def create_session(self, session_token: str) -> bool:
449441
capture_exception(e, operation="create_session")
450442
return False
451443

452-
# -------------------------------------------------------------------------
453444
# Rate Limiting Methods (existing, updated for hash storage)
454-
# -------------------------------------------------------------------------
455445

456446
def check_limit(
457447
self,
@@ -657,9 +647,7 @@ def _check_ip_limit(self, client_ip: str, record: bool) -> Tuple[bool, int]:
657647
logger.error("IP limit check failed", error=str(e))
658648
return True, self.IP_LIMIT_PER_DAY # Fail open
659649

660-
# -------------------------------------------------------------------------
661650
# Helper Methods
662-
# -------------------------------------------------------------------------
663651

664652
def _get_midnight_utc(self) -> datetime:
665653
"""Get next midnight UTC for reset time."""
@@ -788,9 +776,7 @@ def get_usage_stats(self) -> dict:
788776
return {"error": str(e), "redis_available": False}
789777

790778

791-
# =============================================================================
792779
# SINGLETON
793-
# =============================================================================
794780

795781
_playground_limiter: Optional[PlaygroundLimiter] = None
796782

0 commit comments

Comments
 (0)