Update rule + flow hdfs new

This commit is contained in:
2026-09-23 11:36:34 +07:00
parent c79ea9f05f
commit 0e15bc89a8
10 changed files with 159 additions and 35 deletions

View File

@@ -26,6 +26,7 @@ class ProcessRequest(BaseModel):
file_path: str = Field(min_length=1, max_length=2048)
file_type: str = "application/pdf"
callback_url: str | None = None
dag_run_id: str | None = Field(default=None, min_length=1, max_length=250)
batch_id: str | None = Field(default=None, max_length=128)
@@ -71,7 +72,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
def public_job(job: dict) -> dict:
result = {key: job[key] for key in (
"id", "request_id", "batch_id", "status", "file_path", "filename", "source_kind",
"id", "request_id", "dag_run_id", "batch_id", "status", "file_path", "filename", "source_kind",
"total_pages", "completed_pages", "failed_pages", "error",
"callback_state", "callback_error", "created_at", "updated_at")}
result["result_available"] = job["result_json"] is not None
@@ -100,6 +101,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
file: UploadFile = File(...),
request_id: UUID | None = Form(default=None),
callback_url: str | None = Form(default=None),
dag_run_id: str | None = Form(default=None, min_length=1, max_length=250),
batch_id: str | None = Form(default=None, max_length=128)):
"""Nhận thẳng file PDF qua multipart/form-data và trả job_id ngay."""
filename = Path(file.filename or "").name
@@ -127,7 +129,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
try:
job, created = store.create_job(str(request_id or uuid4()), str(stored), callback_url,
batch_id, settings.max_queued_jobs, filename, "upload")
batch_id, settings.max_queued_jobs, filename, "upload", dag_run_id)
except ValueError as exc:
discard_upload(stored)
raise HTTPException(status_code=409, detail=str(exc)) from exc
@@ -146,7 +148,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
try:
job, created = store.create_job(str(request.request_id), request.file_path,
request.callback_url, request.batch_id,
settings.max_queued_jobs)
settings.max_queued_jobs, dag_run_id=request.dag_run_id)
except ValueError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
except OverflowError as exc:

View File

@@ -8,6 +8,7 @@ class Settings:
data_dir: Path = Path(os.getenv("IDP_DATA_DIR", "./data")).resolve()
storage: str = os.getenv("IDP_STORAGE", "local") # local, hdfs, or hdfs_cli
hdfs_url: str = os.getenv("IDP_HDFS_URL", "http://namenode:9870")
hdfs_native_uri: str = os.getenv("IDP_HDFS_NATIVE_URI", "")
api_key: str = os.getenv("IDP_API_KEY", "")
callback_hosts: str = os.getenv("IDP_CALLBACK_HOSTS", "")
ocr_url: str = os.getenv("IDP_OCR_URL", "http://localhost:9222/v1/chat/completions")

View File

@@ -30,7 +30,7 @@ class Store:
db.executescript("""
CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE,
file_path TEXT NOT NULL, callback_url TEXT, batch_id TEXT,
file_path TEXT NOT NULL, callback_url TEXT, batch_id TEXT, dag_run_id TEXT,
filename TEXT, source_kind TEXT NOT NULL DEFAULT 'path',
status TEXT NOT NULL, created_at REAL NOT NULL, updated_at REAL NOT NULL,
total_pages INTEGER NOT NULL DEFAULT 0,
@@ -63,6 +63,8 @@ class Store:
db.execute("ALTER TABLE jobs ADD COLUMN filename TEXT")
if "source_kind" not in columns:
db.execute("ALTER TABLE jobs ADD COLUMN source_kind TEXT NOT NULL DEFAULT 'path'")
if "dag_run_id" not in columns:
db.execute("ALTER TABLE jobs ADD COLUMN dag_run_id TEXT")
@contextmanager
def tx(self):
@@ -83,24 +85,25 @@ class Store:
def create_job(self, request_id: str, file_path: str, callback_url: str | None,
batch_id: str | None, max_queued: int, filename: str | None = None,
source_kind: str = "path"):
source_kind: str = "path", dag_run_id: str | None = None):
now = time.time()
filename = filename or Path(file_path).name
with self.tx() as db:
prior = db.execute("SELECT * FROM jobs WHERE request_id=?", (request_id,)).fetchone()
if prior:
if (prior["file_path"], prior["callback_url"], prior["batch_id"],
prior["filename"]) != (file_path, callback_url, batch_id, filename):
prior["filename"], prior["dag_run_id"]) != (file_path, callback_url, batch_id,
filename, dag_run_id):
raise ValueError("request_id already exists with different inputs")
return self.as_dict(prior), False
queued = db.execute("SELECT count(*) FROM jobs WHERE status IN ('queued','preparing','processing','finalizing')").fetchone()[0]
if queued >= max_queued:
raise OverflowError("Job queue is full")
job_id = "job_" + uuid4().hex
db.execute("""INSERT INTO jobs(id,request_id,file_path,callback_url,batch_id,filename,
db.execute("""INSERT INTO jobs(id,request_id,file_path,callback_url,batch_id,dag_run_id,filename,
source_kind,status,created_at,updated_at)
VALUES(?,?,?,?,?,?,?,'queued',?,?)""",
(job_id, request_id, file_path, callback_url, batch_id, filename,
VALUES(?,?,?,?,?,?,?,?,'queued',?,?)""",
(job_id, request_id, file_path, callback_url, batch_id, dag_run_id, filename,
source_kind, now, now))
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (job_id,)).fetchone()), True

View File

@@ -10,9 +10,12 @@ class StorageError(Exception):
pass
def _hdfs(*args: str) -> None:
def _hdfs(settings: Settings, *args: str) -> None:
command = ["hdfs", "dfs"]
if settings.hdfs_native_uri:
command.extend(["-fs", settings.hdfs_native_uri])
try:
subprocess.run(["hdfs", "dfs", *args], check=True, capture_output=True, text=True, timeout=600)
subprocess.run([*command, *args], check=True, capture_output=True, text=True, timeout=600)
except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
detail = getattr(exc, "stderr", None) or str(exc)
raise StorageError(f"HDFS operation failed: {detail[:500]}") from exc
@@ -26,7 +29,7 @@ def fetch_pdf(settings: Settings, source: str, destination: Path) -> None:
from .webhdfs import download_pdf
download_pdf(settings.hdfs_url, source, temporary, settings.max_pdf_bytes)
elif settings.storage == "hdfs_cli":
_hdfs("-get", source, str(temporary))
_hdfs(settings, "-get", source, str(temporary))
elif settings.storage == "local":
source_path = Path(source).resolve()
if not source_path.is_file():

View File

@@ -1,5 +1,6 @@
"""Run separately from the API: python -m idp_service.worker."""
import hashlib
import base64
import json
import logging
import shutil
@@ -16,7 +17,7 @@ from .config import Settings
from .db import Store
from .decrypt import prepare_pdf
from .dla import build_outline
from .ocr import InvalidOutput, infer_page
from .ocr import InvalidOutput, infer_page, render_page
from .storage import fetch_pdf
@@ -122,7 +123,8 @@ class Worker:
result_json = json.dumps(bundle, ensure_ascii=False, separators=(",", ":"))
has_failures = any(p["status"] == "failed" for p in pages)
if self.store.finalized(job_id, job["finalize_attempts"], result_json, has_failures):
shutil.rmtree(self.job_dir(job_id), ignore_errors=True)
if not job["callback_url"]:
shutil.rmtree(self.job_dir(job_id), ignore_errors=True)
self.cleanup_source(job)
log.info("Finalized %s for callback", job_id)
except Exception as exc:
@@ -131,12 +133,28 @@ class Worker:
def callback(self, job: dict):
try:
canonical = json.loads(job["result_json"]) if job["result_json"] else None
extraction = None
if canonical is not None:
source = self.job_dir(job["id"]) / "source.pdf"
extraction = {"pages": []}
for page_no in range(1, canonical["source"]["page_count"] + 1):
image, _, _ = render_page(source, page_no)
extraction["pages"].append({
"page_no": page_no,
"media_type": "image/png",
"data_base64": base64.b64encode(image).decode("ascii"),
})
payload = {
"request_id": job["request_id"], "job_id": job["id"],
"batch_id": job["batch_id"],
"status": "done" if job["status"] == "completed" else job["status"],
"output": json.loads(job["result_json"]) if job["result_json"] else None,
"error": job["error"],
"dag_run_id": job["dag_run_id"] or job["id"],
"conf": {
"request_id": job["request_id"], "job_id": job["id"],
"status": "done" if job["status"] == "completed" else job["status"],
"output": {
"extraction": extraction,
"canonical": canonical,
},
},
}
request = Request(job["callback_url"], data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json",
@@ -145,10 +163,13 @@ class Worker:
if not 200 <= response.status < 300:
raise RuntimeError(f"Callback HTTP {response.status}")
self.store.callback_done(job["id"], job["callback_attempts"])
shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True)
except Exception as exc:
log.warning("Callback failed for %s: %s", job["id"], exc)
self.store.callback_failed(job["id"], job["callback_attempts"],
str(exc), self.settings.max_callback_attempts)
if job["callback_attempts"] >= self.settings.max_callback_attempts:
shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True)
def coordinator_once(self) -> bool:
did_work = False