This commit is contained in:
2026-09-24 14:27:43 +07:00
parent e9d7c6d391
commit 79b70bed12
6 changed files with 83 additions and 11 deletions

View File

@@ -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)