Update main.py

Add detailed logging
This commit is contained in:
Cal Corum 2025-07-16 11:40:28 -05:00
parent 386ee0cdcf
commit be64bd7114

View File

@ -80,56 +80,60 @@ async def proxy_postgrest(
request: Request, request: Request,
x_api_key: str = Header(default=None) x_api_key: str = Header(default=None)
): ):
logger.info(f'an API call was made to: /{path} with api key: {x_api_key}') log_prefix = f'{getattr(getattr(request, "client", None), "host", None)} - {datetime.now().timestamp()}'
logger.info(f'{log_prefix} - an API call was made to: /{path} with api key: {x_api_key}')
if not x_api_key: if not x_api_key:
raise HTTPException(status_code=401, detail="Unauthorized access") raise HTTPException(status_code=401, detail="Unauthorized access")
# Step 1: Check cache # Step 1: Check cache
user_info = api_key_cache.get(x_api_key) user_info = api_key_cache.get(x_api_key)
logger.info(f'cached user: {user_info}') logger.info(f'{log_prefix} - cached user: {user_info}')
if not user_info: if not user_info:
# Step 2: Cache miss → look up in DB # Step 2: Cache miss → look up in DB
logger.info(f'in prod: {PRODUCTION}') logger.info(f'{log_prefix} - in prod: {PRODUCTION}')
if PRODUCTION: if PRODUCTION:
logger.info(f'looking up user in prod db') logger.info(f'{log_prefix} - looking up user in prod db')
user_info = await fetch_user_from_db(app.state.db, x_api_key) user_info = await fetch_user_from_db(app.state.db, x_api_key)
else: else:
logger.info(f'looking up user in fake db') logger.info(f'{log_prefix} - looking up user in fake db')
user_info = fetch_user_in_dev(x_api_key) user_info = fetch_user_in_dev(x_api_key)
logger.info(f'user_info: {user_info}') logger.info(f'{log_prefix} - user_info: {user_info}')
if not user_info: if not user_info:
raise HTTPException(status_code=401, detail="Invalid or inactive API key") raise HTTPException(status_code=401, detail="Invalid or inactive API key")
logger.info(f'caching {x_api_key} for {user_info}') logger.info(f'{log_prefix} - caching {x_api_key} for {user_info}')
api_key_cache[x_api_key] = user_info # Step 3: Cache it api_key_cache[x_api_key] = user_info # Step 3: Cache it
# Step 4: Sign JWT # Step 4: Sign JWT
logger.info(f'generating jwt for postgrest') logger.info(f'{log_prefix} - generating jwt for postgrest')
token = generate_jwt(user_info["user_id"], user_info["role"]) token = generate_jwt(user_info["user_id"], user_info["role"])
# Step 5: Forward request to PostgREST # Step 5: Forward request to PostgREST
method = request.method method = request.method
body = await request.body() body = await request.body()
headers = dict(request.headers) headers = dict(request.headers)
logger.info(f'{log_prefix} - incoming headers: {headers}')
headers["Authorization"] = f"Bearer {token}" headers["Authorization"] = f"Bearer {token}"
forward_headers = { forward_headers = {
'Authorization': f'Bearer {token}', 'Authorization': f'Bearer {token}',
'Content-Type': headers.get("content-type", "application/json"), 'Content-Type': headers.get("Content-Type", headers.get("content-type", "application/json")),
'Accept': headers.get('Accept', '*/*') 'Accept': headers.get('Accept', headers.get('accept', '*/*'))
} }
# TODO: proxy is currently not honoring Accept: text/csv
# we were logging 'headers' but passing 'forward_headers'
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
logger.info(f'sending request to postgrest for {user_info}:\nMethod: {method}\nURL: {POSTGREST_URL}/{path}\nHeaders: {headers}\nBody: {body}\nParams: {request.query_params}') logger.info(f'{log_prefix} - sending request to postgrest for {user_info}:\nMethod: {method}\nURL: {POSTGREST_URL}/{path}\nHeaders: {headers}\nBody: {body}\nParams: {request.query_params}')
response = await client.request( response = await client.request(
method=method, method=method,
url=f"{POSTGREST_URL}/{path}", url=f"{POSTGREST_URL}/{path}",
headers=forward_headers, headers=headers,
content=body, content=body,
params=request.query_params params=request.query_params
) )
logger.info(f'{user_info} / Response Code: {response.status_code}') logger.info(f'{log_prefix} - {user_info} / Response Code: {response.status_code}')
if response.status_code != 200: if response.status_code != 200:
logger.warning(f'Response Content: {response.content}') logger.warning(f'{log_prefix} - Response Content: {response.content}')
return Response( return Response(
content=response.content, content=response.content,
status_code=response.status_code, status_code=response.status_code,