Initial commit

This commit is contained in:
2026-09-21 21:06:49 +07:00
commit 261233564c
20 changed files with 2146 additions and 0 deletions

101
idp_service/api.py Normal file
View File

@@ -0,0 +1,101 @@
"""HTTP API. Start with: uvicorn idp_service.api:app --host 0.0.0.0 --port 8080"""
import hmac
from urllib.parse import urlparse
from uuid import UUID
import json
from fastapi import Depends, FastAPI, Header, HTTPException, Response, status
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from .config import Settings
from .db import Store
class ProcessRequest(BaseModel):
request_id: UUID
file_path: str = Field(min_length=1, max_length=2048)
file_type: str = "application/pdf"
callback_url: str | None = None
batch_id: str | None = Field(default=None, max_length=128)
def create_app(settings: Settings | None = None) -> FastAPI:
settings = settings or Settings()
store = Store(settings.db_path)
app = FastAPI(title="IDP Parsing Service", version="0.1.0")
def authorize(x_api_key: str | None = Header(default=None)):
if settings.api_key and not hmac.compare_digest(x_api_key or "", settings.api_key):
raise HTTPException(status_code=401, detail="Invalid API key")
def public_job(job: dict) -> dict:
result = {key: job[key] for key in (
"id", "request_id", "batch_id", "status", "file_path", "total_pages",
"completed_pages", "failed_pages", "error",
"callback_state", "callback_error", "created_at", "updated_at")}
result["result_available"] = job["result_json"] is not None
return result
@app.get("/healthz")
def healthz():
return {"status": "ok"}
@app.get("/readyz")
def readyz():
try:
with store.connect() as db:
db.execute("SELECT 1").fetchone()
except Exception as exc:
raise HTTPException(status_code=503, detail="Job store unavailable") from exc
return {"status": "ready"}
@app.post("/process", status_code=status.HTTP_202_ACCEPTED, dependencies=[Depends(authorize)])
@app.post("/jobs", status_code=status.HTTP_202_ACCEPTED, dependencies=[Depends(authorize)])
def submit(request: ProcessRequest, response: Response):
if request.file_type != "application/pdf" or not request.file_path.lower().endswith(".pdf"):
raise HTTPException(status_code=422, detail="Only PDF input is supported")
if request.callback_url:
parsed = urlparse(request.callback_url)
allowed = {host.strip() for host in settings.callback_hosts.split(",") if host.strip()}
if parsed.scheme not in ("http", "https") or not parsed.hostname or (allowed and parsed.hostname not in allowed):
raise HTTPException(status_code=422, detail="Callback URL or host is not allowed")
try:
job, created = store.create_job(str(request.request_id), request.file_path,
request.callback_url, request.batch_id,
settings.max_queued_jobs)
except ValueError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
except OverflowError as exc:
raise HTTPException(status_code=429, detail=str(exc)) from exc
if not created:
response.headers["X-Idempotent-Replay"] = "true"
return {"request_id": job["request_id"], "job_id": job["id"], "status": job["status"]}
@app.get("/jobs/{job_id}", dependencies=[Depends(authorize)])
def job_status(job_id: str):
job = store.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
return public_job(job)
@app.get("/jobs/{job_id}/pages", dependencies=[Depends(authorize)])
def page_status(job_id: str):
if not store.get_job(job_id):
raise HTTPException(status_code=404, detail="Job not found")
return {"job_id": job_id, "pages": store.get_pages(job_id)}
@app.get("/jobs/{job_id}/result", dependencies=[Depends(authorize)])
def job_result(job_id: str):
job = store.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
if not job["result_json"]:
raise HTTPException(status_code=409, detail="Result is not ready")
return JSONResponse(content=json.loads(job["result_json"]))
return app
app = create_app()