Avinashnalla7 commited on
Commit
2fc7c46
·
1 Parent(s): 667075f

fix: make /api/pdf serve from SFTP with timeout

Browse files
Files changed (1) hide show
  1. backend/api.py +21 -8
backend/api.py CHANGED
@@ -2,6 +2,8 @@ from __future__ import annotations
2
 
3
  import json
4
  import os
 
 
5
  from pathlib import Path
6
  from typing import Any, Dict
7
 
@@ -104,14 +106,25 @@ def root() -> Dict[str, str]:
104
 
105
  @app.get("/api/pdf/{pdf_id}")
106
  def get_pdf(pdf_id: str):
107
- # Read PDF bytes from SFTP: /inserio/pdfs/{pdf_id}.pdf
108
- rel = f"pdfs/{pdf_id}.pdf"
109
- try:
110
- data = download_bytes(rel)
111
- except FileNotFoundError:
112
- raise HTTPException(status_code=404, detail="pdf not found")
113
- except Exception as e:
114
- raise HTTPException(status_code=500, detail=f"sftp read failed: {e}")
 
 
 
 
 
 
 
 
 
 
 
115
 
116
  # Stream bytes back to UI
117
  resp = PlainTextResponse(content=data)
 
2
 
3
  import json
4
  import os
5
+ import concurrent.futures
6
+
7
  from pathlib import Path
8
  from typing import Any, Dict
9
 
 
106
 
107
  @app.get("/api/pdf/{pdf_id}")
108
  def get_pdf(pdf_id: str):
109
+ # Read from SFTP path: /inserio/pdfs/<pdf_id>.pdf (SFTP_ROOT handles /inserio)
110
+ name = pdf_id
111
+ if not name.lower().endswith(".pdf"):
112
+ remote_path = f"pdfs/{name}.pdf"
113
+ else:
114
+ remote_path = f"pdfs/{name}"
115
+
116
+ # Hard timeout so requests never hang
117
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as ex:
118
+ fut = ex.submit(download_bytes, remote_path)
119
+ try:
120
+ data = fut.result(timeout=10)
121
+ except concurrent.futures.TimeoutError:
122
+ from fastapi import HTTPException
123
+ raise HTTPException(status_code=504, detail="SFTP timeout reading PDF")
124
+
125
+ # Return raw bytes
126
+ from fastapi.responses import Response
127
+ return Response(content=data, media_type="application/pdf")
128
 
129
  # Stream bytes back to UI
130
  resp = PlainTextResponse(content=data)