diff --git a/.gitignore b/.gitignore index 9612942..8443b13 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,5 @@ export/ idp_parsing_service.egg-info/ build/ chandra-dla-api-v2-20260906-024126.tar -hdfs-kbr.zip \ No newline at end of file +hdfs-kbr.zip +.env \ No newline at end of file diff --git a/SERVICE.md b/SERVICE.md index dc39b2b..9a93569 100644 --- a/SERVICE.md +++ b/SERVICE.md @@ -161,6 +161,8 @@ Khi đặt `IDP_API_KEY`, mọi endpoint job cần header `X-API-Key`. | `KRB5_CONFIG` | `native-hdfs/conf/krb5.conf` | Đường dẫn cấu hình Kerberos | | `IDP_API_KEY` | rỗng | Khóa API; **bắt buộc cấu hình khi mở API ra mạng** | | `IDP_CALLBACK_HOSTS` | rỗng | Danh sách hostname callback được phép, cách nhau bằng dấu phẩy | +| `IDP_CALLBACK_BASIC_USER` | rỗng | Username Basic Auth khi worker gọi callback | +| `IDP_CALLBACK_BASIC_PASSWORD` | rỗng | Password Basic Auth khi worker gọi callback | | `IDP_OCR_URL` | `http://localhost:9222/v1/chat/completions` | API vLLM | | `IDP_OCR_MODEL` | `chandra` | Tên model | | `IDP_OCR_BACKEND` | `http` | `http` gọi model; `pdf_text` dựng bundle từ text layer, chỉ để chạy thử | @@ -169,6 +171,7 @@ Khi đặt `IDP_API_KEY`, mọi endpoint job cần header `X-API-Key`. | `IDP_KIE_MODEL` | theo `IDP_OCR_MODEL` | Tên model KIE | | `IDP_KIE_MAX_PAGES` | `5` | Số ảnh tối đa gửi một lượt KIE; quá thì lấy các trang đầu và trang cuối | | `IDP_KIE_TIMEOUT` | `300` | Timeout một lượt KIE, giây | +| `IDP_KIE_MAX_TOKENS` | `2048` | Giới hạn số token đầu ra của mỗi request KIE; độc lập với `--max-model-len` của vLLM | | `IDP_MAX_KIE_ATTEMPTS` | `3` | Số lần thử bóc trường mỗi tài liệu | | `IDP_RUN_WORKER` | `0` | `1` chạy worker ngay trong process API | | `IDP_OCR_WORKERS` | `64` | Giới hạn tổng request tới GPU, lưu bằng SQLite | @@ -250,6 +253,12 @@ Callback gửi `{ "dag_run_id": "...", "conf": { "request_id": "...", "job_id": header `Idempotency-Key: job_id`. Nếu không truyền `dag_run_id`, service dùng `job_id` làm giá trị ổn định khi retry. Callback được retry độc lập với OCR, tối đa `IDP_MAX_CALLBACK_ATTEMPTS` lần; Airflow nên xử lý callback lặp idempotently. +Nếu Airflow trả `409` vì DAG run đã tồn tại, worker gọi GET DAG run đó và chỉ +đánh dấu callback đã giao khi `dag_run_id`, `job_id` và `request_id` đều khớp. +Xung đột với job khác vẫn được ghi là lỗi callback. +Nếu Airflow yêu cầu Basic Auth, đặt cả `IDP_CALLBACK_BASIC_USER` và +`IDP_CALLBACK_BASIC_PASSWORD` trong `.env` của API/worker; worker gửi header +`Authorization: Basic ...` cùng request callback. Trạng thái `callback_state=exhausted` cho biết cần xử lý thủ công; bundle vẫn đọc được qua `GET /jobs/{job_id}/result`. diff --git a/idp_service/config.py b/idp_service/config.py index 019badf..5d23409 100644 --- a/idp_service/config.py +++ b/idp_service/config.py @@ -11,6 +11,8 @@ class Settings: 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", "") + callback_basic_user: str = os.getenv("IDP_CALLBACK_BASIC_USER", "") + callback_basic_password: str = os.getenv("IDP_CALLBACK_BASIC_PASSWORD", "") ocr_url: str = os.getenv("IDP_OCR_URL", "http://localhost:9222/v1/chat/completions") ocr_model: str = os.getenv("IDP_OCR_MODEL", "chandra") ocr_backend: str = os.getenv("IDP_OCR_BACKEND", "http") # http hoặc pdf_text @@ -19,6 +21,7 @@ class Settings: kie_model: str = os.getenv("IDP_KIE_MODEL") or os.getenv("IDP_OCR_MODEL", "chandra") kie_max_pages: int = int(os.getenv("IDP_KIE_MAX_PAGES", "5")) kie_timeout: int = int(os.getenv("IDP_KIE_TIMEOUT", "300")) + kie_max_tokens: int = int(os.getenv("IDP_KIE_MAX_TOKENS", "2048")) max_kie_attempts: int = int(os.getenv("IDP_MAX_KIE_ATTEMPTS", "3")) run_worker: bool = os.getenv("IDP_RUN_WORKER", "0").lower() in ("1", "true", "yes") ocr_workers: int = int(os.getenv("IDP_OCR_WORKERS", "64")) diff --git a/idp_service/kie.py b/idp_service/kie.py index 684b192..2fa4b1f 100644 --- a/idp_service/kie.py +++ b/idp_service/kie.py @@ -140,7 +140,7 @@ def extract_document(settings: Settings, pdf_path: Path, page_count: int) -> dic payload = { "model": settings.kie_model, "messages": [{"role": "user", "content": content}], - "max_tokens": 2048, + "max_tokens": settings.kie_max_tokens, "temperature": 0.0, "top_p": 0.1, } diff --git a/idp_service/worker.py b/idp_service/worker.py index 59fc002..d6f83ce 100644 --- a/idp_service/worker.py +++ b/idp_service/worker.py @@ -9,6 +9,8 @@ import threading import time from dataclasses import replace from pathlib import Path +from urllib.error import HTTPError +from urllib.parse import quote, urlsplit, urlunsplit from urllib.request import Request, urlopen import pymupdf @@ -35,6 +37,8 @@ class Worker: raise ValueError("OCR workers must be positive and lease must exceed OCR timeout") if settings.ocr_backend not in ("http", "pdf_text"): raise ValueError("IDP_OCR_BACKEND must be http or pdf_text") + if bool(settings.callback_basic_user) != bool(settings.callback_basic_password): + raise ValueError("Set both IDP_CALLBACK_BASIC_USER and IDP_CALLBACK_BASIC_PASSWORD") if settings.ocr_backend == "pdf_text": log.warning("IDP_OCR_BACKEND=pdf_text: bundle dựng từ text layer của PDF, không gọi model") @@ -179,12 +183,20 @@ class Worker: }, }, } + headers = {"Content-Type": "application/json", "Idempotency-Key": job["id"]} + if self.settings.callback_basic_user: + credentials = f"{self.settings.callback_basic_user}:{self.settings.callback_basic_password}" + headers["Authorization"] = "Basic " + base64.b64encode(credentials.encode("utf-8")).decode("ascii") request = Request(job["callback_url"], data=json.dumps(payload).encode("utf-8"), - headers={"Content-Type": "application/json", - "Idempotency-Key": job["id"]}, method="POST") - with urlopen(request, timeout=10) as response: - if not 200 <= response.status < 300: - raise RuntimeError(f"Callback HTTP {response.status}") + headers=headers, method="POST") + try: + with urlopen(request, timeout=10) as response: + if not 200 <= response.status < 300: + raise RuntimeError(f"Callback HTTP {response.status}") + except HTTPError as exc: + if exc.code != 409 or not self.airflow_run_matches(job["callback_url"], payload, headers): + raise + log.info("Airflow DAG run already exists for %s; callback confirmed", job["id"]) self.store.callback_done(job["id"], job["callback_attempts"]) shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True) except Exception as exc: @@ -194,6 +206,25 @@ class Worker: if job["callback_attempts"] >= self.settings.max_callback_attempts: shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True) + @staticmethod + def airflow_run_matches(callback_url: str, payload: dict, headers: dict) -> bool: + """A 409 confirms delivery only when Airflow has this same job's DAG run.""" + parsed = urlsplit(callback_url) + path = parsed.path.rstrip("/") + segments = path.split("/") + if len(segments) != 6 or segments[:4] != ["", "api", "v1", "dags"] or segments[5] != "dagRuns": + return False + run_url = urlunsplit((parsed.scheme, parsed.netloc, + path + "/" + quote(payload["dag_run_id"], safe=""), "", "")) + get_headers = {"Authorization": headers["Authorization"]} if "Authorization" in headers else {} + with urlopen(Request(run_url, headers=get_headers, method="GET"), timeout=10) as response: + existing = json.load(response) + conf = existing.get("conf") or {} + expected = payload["conf"] + return (existing.get("dag_run_id") == payload["dag_run_id"] + and conf.get("job_id") == expected["job_id"] + and conf.get("request_id") == expected["request_id"]) + def coordinator_once(self) -> bool: did_work = False job = self.store.claim_prepare(self.settings.lease_seconds) diff --git a/tests/test_service.py b/tests/test_service.py index 9d7c8d5..7fb419f 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -230,7 +230,8 @@ def test_extract_fixed_schema_end_to_end_and_callback(tmp_path): thread.start() try: url = f"http://127.0.0.1:{server.server_port}/v1/chat/completions" - settings = replace(settings_for(tmp_path), ocr_url=url, kie_enabled=True, kie_url=url) + settings = replace(settings_for(tmp_path), ocr_url=url, kie_enabled=True, kie_url=url, + kie_max_tokens=4096) source = tmp_path / "quyet-dinh.pdf" make_pdf(source, count=2) app = create_app(settings) @@ -246,6 +247,7 @@ def test_extract_fixed_schema_end_to_end_and_callback(tmp_path): assert len(kie_requests) == 1 assert len(kie_requests[0]["messages"][0]["content"]) == 3 assert kie_requests[0]["model"] == settings.kie_model + assert kie_requests[0]["max_tokens"] == 4096 extraction = client.get(f"/jobs/{job_id}/extraction").json() assert extraction["status"] == "done" @@ -359,6 +361,7 @@ def test_rejects_truncated_plain_text_and_invalid_bbox(): def test_real_http_ocr_and_callback(tmp_path): callbacks = [] + auth_headers = [] class Handler(BaseHTTPRequestHandler): def do_POST(self): @@ -370,8 +373,20 @@ def test_real_http_ocr_and_callback(tmp_path): '