release: Themiz на Gitea
This commit is contained in:
+53
-30
@@ -18,10 +18,6 @@ import update_legal_corpus as corpus
|
||||
|
||||
CACHE_TTL = timedelta(days=7)
|
||||
MAX_BODY_BYTES = 10 * 1024 * 1024
|
||||
BLOCKED_FETCH_CODES = frozenset({
|
||||
"access_denied", "auth_required", "captcha", "paid_required", "paywall",
|
||||
"policy_denied", "robots_denied", "unapproved_sudact_path",
|
||||
})
|
||||
|
||||
|
||||
class Deadline(Exception):
|
||||
@@ -214,6 +210,14 @@ def _snapshot(root: Path, output: Path, job: Path, state: dict) -> bytes | None:
|
||||
return body
|
||||
raise RuntimeError("CAS: local corpus appeared")
|
||||
return None
|
||||
if not original_path.exists(): # снимок удален извне: живой файл принимаем только с известным SHA
|
||||
current = output.read_bytes() if output.exists() else None
|
||||
if current is None or _sha(current) not in {saved.get("sha256"), state.get("activated_sha256")}:
|
||||
raise RuntimeError("CAS: local corpus changed")
|
||||
state["original"] = {"exists": True, "sha256": _sha(current)}
|
||||
_atomic(original_path, current)
|
||||
_write_checkpoint(job, state)
|
||||
return current
|
||||
body = original_path.read_bytes()
|
||||
if saved.get("sha256") != _sha(body):
|
||||
raise ValueError("saved original changed")
|
||||
@@ -340,18 +344,47 @@ def _run_catalog(resource: dict, job: Path, now: datetime, deadline: float, stat
|
||||
"progress": _progress(len(discovered), len(discovered)), "discovered_resources": discovered}
|
||||
|
||||
|
||||
def _generic_failed(exc: Exception) -> RuntimeError:
|
||||
"""Отказ проверки документа; текст ValueError - наш, из реестра: по нему видно, какая проверка не прошла."""
|
||||
return RuntimeError(f"generic candidate failed: {type(exc).__name__}"
|
||||
+ (f": {exc}" if isinstance(exc, ValueError) else ""))
|
||||
|
||||
|
||||
def _part_receipts(job: Path, toc: list[dict], now: datetime, deadline: float, state: dict) -> list[dict]:
|
||||
"""Квитанции частей акта по оглавлению. Каждую часть проверяет реестр, и сразу после проверки она
|
||||
подтверждается и пишется в state["receipts"]: обрыв по сроку не заставляет качать проверенное заново."""
|
||||
import corpus_registry
|
||||
parts = []
|
||||
for part in toc:
|
||||
receipt = _receipt(job, part["url"], now, deadline) # срок и отказ сети идут наружу как есть
|
||||
try:
|
||||
corpus_registry.act_part_section(part, receipt)
|
||||
except Exception as exc:
|
||||
raise _generic_failed(exc) from exc
|
||||
_verify_receipt(job, receipt)
|
||||
state["receipts"][part["url"]] = {key: receipt[key] for key in receipt if key != "body"}
|
||||
_write_checkpoint(job, state)
|
||||
parts.append(receipt)
|
||||
return parts
|
||||
|
||||
|
||||
def _run_generic(root: Path, resource: dict, job: Path, now: datetime, deadline: float, state: dict) -> dict:
|
||||
output = _output(root, resource)
|
||||
original = _snapshot(root, output, job, state)
|
||||
receipt = _receipt(job, resource["url"], now, deadline)
|
||||
review = resource["parser"] == "vsrf-review"
|
||||
try:
|
||||
import corpus_registry
|
||||
builder = (corpus_registry.build_review_candidate
|
||||
if resource["parser"] == "vsrf-review"
|
||||
else corpus_registry.build_generic_candidate)
|
||||
relative_output, candidate = builder(resource, receipt, now)
|
||||
builder = corpus_registry.build_review_candidate if review else corpus_registry.build_generic_candidate
|
||||
toc = [] if review else corpus_registry.act_parts(resource, receipt)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"generic candidate failed: {type(exc).__name__}") from exc
|
||||
raise _generic_failed(exc) from exc
|
||||
parts = _part_receipts(job, toc, now, deadline, state)
|
||||
args = (resource, receipt, now) if review else (resource, receipt, now, parts)
|
||||
try:
|
||||
relative_output, candidate = builder(*args)
|
||||
except Exception as exc:
|
||||
raise _generic_failed(exc) from exc
|
||||
if relative_output != resource["output"] or not isinstance(candidate, bytes):
|
||||
raise ValueError("generic candidate missing")
|
||||
_verify_receipt(job, receipt)
|
||||
@@ -359,10 +392,13 @@ def _run_generic(root: Path, resource: dict, job: Path, now: datetime, deadline:
|
||||
state["activated_sha256"] = _sha(candidate)
|
||||
state["receipts"][resource["url"]] = {key: receipt[key] for key in receipt if key != "body"}
|
||||
_write_checkpoint(job, state)
|
||||
pages = 1 + len(parts)
|
||||
checked = min(datetime.fromisoformat(item["checked_at"].replace("Z", "+00:00"))
|
||||
for item in (receipt, *parts)) # документ свеж настолько, насколько свежа старейшая страница
|
||||
return {"id": resource["id"], "status": status, "detail": "verified generic candidate",
|
||||
"last_checked": receipt["checked_at"],
|
||||
"last_checked": checked.isoformat().replace("+00:00", "Z"),
|
||||
"last_updated": datetime.now(UTC).isoformat().replace("+00:00", "Z") if status == "updated" else None,
|
||||
"progress": _progress(1, 1)}
|
||||
"progress": _progress(pages, pages)}
|
||||
|
||||
|
||||
def _run_code(root: Path, resource: dict, job: Path, now: datetime, deadline: float, state: dict) -> dict:
|
||||
@@ -375,8 +411,10 @@ def _run_code(root: Path, resource: dict, job: Path, now: datetime, deadline: fl
|
||||
if output != root / "knowledge" / "kodeksy" / f"{slug}.md":
|
||||
raise ValueError("code output does not match registry")
|
||||
original = _snapshot(root, output, job, state)
|
||||
from maintenance_sources import _corpus
|
||||
result = _corpus(output, job, now, True, deadline, force_rebuild=True,
|
||||
from maintenance_sources import _corpus, _extraction_proof
|
||||
# Полная перекачка - только без проверенной выгрузки этого файла: иначе хватает сверки редакции.
|
||||
proven = original is not None and _extraction_proof(job, slug, original)
|
||||
result = _corpus(output, job, now, True, deadline, force_rebuild=not proven,
|
||||
initialize_missing=True, original_snapshot=original,
|
||||
snapshot_exists=state["original"]["exists"])
|
||||
state["delegate"] = {key: result.get(key) for key in ("status", "detail", "source_revision")}
|
||||
@@ -396,17 +434,6 @@ def _run_code(root: Path, resource: dict, job: Path, now: datetime, deadline: fl
|
||||
"failure_code": result.get("failure_code"), "progress": progress}
|
||||
|
||||
|
||||
def _blocked_fetch(exc: maintenance_fetch.MaintenanceFetchError) -> str | None:
|
||||
if exc.code in BLOCKED_FETCH_CODES:
|
||||
return exc.code
|
||||
attempts = exc.diagnostic.get("attempts") if isinstance(exc.diagnostic, dict) else None
|
||||
if isinstance(attempts, list):
|
||||
for attempt in attempts:
|
||||
if isinstance(attempt, dict) and attempt.get("code") in BLOCKED_FETCH_CODES:
|
||||
return attempt["code"]
|
||||
return None
|
||||
|
||||
|
||||
def run_job(root: Path, resource: dict, state_dir: Path, deadline: float) -> dict:
|
||||
"""Строит ровно один ресурс; deadline — абсолютное monotonic-время."""
|
||||
try:
|
||||
@@ -414,10 +441,6 @@ def run_job(root: Path, resource: dict, state_dir: Path, deadline: float) -> dic
|
||||
or not math.isfinite(deadline)):
|
||||
raise ValueError("deadline invalid")
|
||||
root, resource = Path(root).resolve(), _resource(resource)
|
||||
if resource["parser"] == "vsrf-review":
|
||||
return {"id": resource["id"], "status": "blocked",
|
||||
"detail": "review_parser_not_verified", "failure_code": "review_parser_not_verified",
|
||||
"progress": _progress(0, 0)}
|
||||
now = datetime.now(UTC)
|
||||
job = _job_dir(root, Path(state_dir).resolve(), resource["id"])
|
||||
state = _read_checkpoint(job, resource)
|
||||
@@ -428,14 +451,14 @@ def run_job(root: Path, resource: dict, state_dir: Path, deadline: float) -> dic
|
||||
return _run_plenum(root, resource, job, now, deadline, state)
|
||||
if resource["parser"] == "sudact-catalog":
|
||||
return _run_catalog(resource, job, now, deadline, state)
|
||||
if resource["parser"] == "consultant-act":
|
||||
if resource["parser"] in {"consultant-act", "vsrf-review"}:
|
||||
return _run_generic(root, resource, job, now, deadline, state)
|
||||
return _run_code(root, resource, job, now, deadline, state)
|
||||
except Deadline:
|
||||
return {"id": resource.get("id", "unknown") if isinstance(resource, dict) else "unknown",
|
||||
"status": "deferred", "detail": "deadline exhausted", "progress": _progress(0, 0)}
|
||||
except maintenance_fetch.MaintenanceFetchError as exc:
|
||||
code = _blocked_fetch(exc)
|
||||
code = maintenance_fetch.blocked_code(exc)
|
||||
return {"id": resource.get("id", "unknown") if isinstance(resource, dict) else "unknown",
|
||||
"status": "blocked" if code else "failed",
|
||||
"detail": f"source access blocked: {code}" if code else f"fetch failed: {exc.code}",
|
||||
|
||||
Reference in New Issue
Block a user