fix(ext): устойчивость чекера + точный фильтр XSD-схем (фиксы Fable Фазы 4/5)
- run_check: каждый источник в _safe_check — ЛЮБОЙ сбой (не только FetchError) становится problem-находкой, а не убивает весь прогон (отчёт/письмо/heartbeat). - run_check: неблокирующий .check.lock — наложение cron-прогонов пропускается, а не плодит дубль работы и писем. - run_check: EXT_REGIONS=all, но список субъектов не получен → problem (факт), а не тихое «не задан». - xsd_client: фильтр схем сверен с живой страницей Минстроя (151 .zip). Убран слишком широкий маркер skhema/схема — цеплял «схему пояснительной записки проекта». Берём только сметные/экспертизные схемы, отсекаем журналы/акты. - Тесты: баг-в-чекере→problem, all-но-недоступен→problem, наложение→skip, реальные имена файлов в XSD-тестах. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
+84
-28
@@ -10,9 +10,11 @@ reports/<ts>.json, watch.log, heartbeat.json. Уведомляет операт
|
|||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import fcntl
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
from contextlib import contextmanager
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -33,61 +35,74 @@ def _regions() -> list[int]:
|
|||||||
|
|
||||||
|
|
||||||
def check_opendata(seen: dict, *, client=None) -> tuple[list[dict], dict]:
|
def check_opendata(seen: dict, *, client=None) -> tuple[list[dict], dict]:
|
||||||
"""Обновлённые датасеты открытых данных (КСР/ФСНБ/СПСРП/оплата труда/ПССР) по lastChangeDate."""
|
"""Обновлённые датасеты (КСР/ФСНБ/СПСРП/оплата труда/ПССР) по lastChangeDate.
|
||||||
prev = seen.get("opendata_lastchange", {})
|
Первый прогон (ключа нет) — тихий засев + ОДНА info-строка, а не N (иначе завал оператора)."""
|
||||||
try:
|
try:
|
||||||
datasets = fc.opendata_list(client=client)
|
datasets = fc.opendata_list(client=client)
|
||||||
except ext_fetch.FetchError as e:
|
except ext_fetch.FetchError as e:
|
||||||
return [{"source": "opendata", "level": "problem", "message": f"OpenData недоступен: {e}"}], seen
|
return [{"source": "opendata", "level": "problem", "message": f"OpenData недоступен: {e}"}], seen
|
||||||
|
first_run = "opendata_lastchange" not in seen
|
||||||
|
prev = seen.get("opendata_lastchange", {})
|
||||||
findings = []
|
findings = []
|
||||||
for ds in datasets:
|
for ds in datasets:
|
||||||
did = str(ds["id"])
|
did, lc = str(ds["id"]), ds.get("lastChangeDate")
|
||||||
lc = ds.get("lastChangeDate")
|
|
||||||
if prev.get(did) != lc:
|
if prev.get(did) != lc:
|
||||||
findings.append({
|
if not first_run:
|
||||||
"source": "fgis_opendata", "level": "update",
|
findings.append({"source": "fgis_opendata", "level": "update",
|
||||||
"message": f"Обновлён датасет «{ds.get('datasetName')}» (изм. {lc})",
|
"message": f"Обновлён датасет «{ds.get('datasetName')}» (изм. {lc})",
|
||||||
"action": f"python3 ext_pull.py --source opendata --dataset {ds['id']}",
|
"action": f"python3 ext_pull.py --source opendata --dataset {ds['id']}"})
|
||||||
})
|
|
||||||
prev[did] = lc
|
prev[did] = lc
|
||||||
|
if first_run:
|
||||||
|
findings.append({"source": "fgis_opendata", "level": "info",
|
||||||
|
"message": f"Базовая линия: {len(datasets)} датасетов открытых данных зафиксирована"})
|
||||||
seen["opendata_lastchange"] = prev
|
seen["opendata_lastchange"] = prev
|
||||||
return findings, seen
|
return findings, seen
|
||||||
|
|
||||||
|
|
||||||
def check_bim(seen: dict, *, client=None) -> tuple[list[dict], dict]:
|
def check_bim(seen: dict, *, client=None) -> tuple[list[dict], dict]:
|
||||||
"""Новые письма-индексы (БИМ) — новые guid листовых документов дерева."""
|
"""Новые письма-индексы (БИМ). Дедуп по guid (не обрезаем — UUID нельзя сортировкой)."""
|
||||||
seen_g = set(seen.get("bim_guids", []))
|
|
||||||
try:
|
try:
|
||||||
docs = fc.bim_leaf_docs(client=client)
|
docs = fc.bim_leaf_docs(client=client)
|
||||||
except ext_fetch.FetchError as e:
|
except ext_fetch.FetchError as e:
|
||||||
return [{"source": "bim", "level": "problem", "message": f"БИМ-письма недоступны: {e}"}], seen
|
return [{"source": "bim", "level": "problem", "message": f"БИМ-письма недоступны: {e}"}], seen
|
||||||
|
first_run = "bim_guids" not in seen
|
||||||
|
seen_g = set(seen.get("bim_guids", []))
|
||||||
findings = []
|
findings = []
|
||||||
for d in docs:
|
for d in docs:
|
||||||
if d["guid"] not in seen_g:
|
if d["guid"] not in seen_g:
|
||||||
findings.append({"source": "fgis_bim", "level": "update",
|
if not first_run:
|
||||||
"message": f"Новое письмо-индекс: {d.get('name') or d['guid']}",
|
findings.append({"source": "fgis_bim", "level": "update",
|
||||||
"action": "python3 ext_pull.py --source bim"})
|
"message": f"Новое письмо-индекс: {d.get('name') or d['guid']}",
|
||||||
|
"action": "python3 ext_pull.py --source bim"})
|
||||||
seen_g.add(d["guid"])
|
seen_g.add(d["guid"])
|
||||||
seen["bim_guids"] = sorted(seen_g)[-2000:]
|
if first_run:
|
||||||
|
findings.append({"source": "fgis_bim", "level": "info",
|
||||||
|
"message": f"Базовая линия: {len(seen_g)} писем-индексов зафиксирована"})
|
||||||
|
seen["bim_guids"] = sorted(seen_g) # UUID — храним ВСЕ (обрезка sorted ломала бы дедуп)
|
||||||
return findings, seen
|
return findings, seen
|
||||||
|
|
||||||
|
|
||||||
def check_xsd(seen: dict, *, client=None) -> tuple[list[dict], dict]:
|
def check_xsd(seen: dict, *, client=None) -> tuple[list[dict], dict]:
|
||||||
"""Новые/изменённые пакеты XSD-схем экспертизы (по списку ссылок)."""
|
"""Новые/изменённые пакеты XSD-схем экспертизы (по списку ссылок)."""
|
||||||
import xsd_client
|
import xsd_client
|
||||||
seen_l = set(seen.get("xsd_links", []))
|
|
||||||
try:
|
try:
|
||||||
links = xsd_client.schema_links(client=client)
|
links = xsd_client.schema_links(client=client)
|
||||||
except ext_fetch.FetchError as e:
|
except ext_fetch.FetchError as e:
|
||||||
return [{"source": "xsd", "level": "problem", "message": f"XSD-схемы: {e}"}], seen
|
return [{"source": "xsd", "level": "problem", "message": f"XSD-схемы: {e}"}], seen
|
||||||
|
first_run = "xsd_links" not in seen
|
||||||
|
seen_l = set(seen.get("xsd_links", []))
|
||||||
findings = []
|
findings = []
|
||||||
for href in links:
|
for href in links:
|
||||||
if href not in seen_l:
|
if href not in seen_l:
|
||||||
findings.append({"source": "xsd_schema", "level": "update",
|
if not first_run:
|
||||||
"message": f"Новый/изменённый пакет схем: {xsd_client._fname(href)}. "
|
findings.append({"source": "xsd_schema", "level": "update",
|
||||||
f"NB: вступает в силу через ~3 мес после публикации.",
|
"message": f"Новый/изменённый пакет схем: {xsd_client._fname(href)}. "
|
||||||
"action": "python3 ext_pull.py --source xsd"})
|
f"NB: вступает в силу через ~3 мес после публикации.",
|
||||||
|
"action": "python3 ext_pull.py --source xsd"})
|
||||||
seen_l.add(href)
|
seen_l.add(href)
|
||||||
|
if first_run:
|
||||||
|
findings.append({"source": "xsd_schema", "level": "info",
|
||||||
|
"message": f"Базовая линия: {len(seen_l)} пакетов схем зафиксирована"})
|
||||||
seen["xsd_links"] = sorted(seen_l)
|
seen["xsd_links"] = sorted(seen_l)
|
||||||
return findings, seen
|
return findings, seen
|
||||||
|
|
||||||
@@ -208,20 +223,61 @@ def _notify(findings: list[dict]) -> bool:
|
|||||||
return bool(email_service.send_operator_digest(to, subj, body))
|
return bool(email_service.send_operator_digest(to, subj, body))
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_check(name: str, fn, seen: dict) -> tuple[list[dict], dict]:
|
||||||
|
"""Вызвать чекер источника; ЛЮБОЙ сбой (не только FetchError) → problem-finding, а не
|
||||||
|
смерть всего прогона (иначе баг одного источника убил бы отчёт/heartbeat/письмо)."""
|
||||||
|
try:
|
||||||
|
return fn(seen)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
return [{"source": name, "level": "problem",
|
||||||
|
"message": f"внутренняя ошибка чекера: {type(e).__name__}: {e}"}], seen
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _solo_run():
|
||||||
|
"""Неблокирующий guard: если предыдущий cron-прогон чекера ещё идёт — новый не запускается
|
||||||
|
(иначе два прогона делают одну работу и шлют дубль писем). Отдельный файл, не state-lock."""
|
||||||
|
lock_path = ext_state.ext_dir() / ".check.lock"
|
||||||
|
fd = os.open(str(lock_path), os.O_CREAT | os.O_RDWR, 0o644)
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
except OSError:
|
||||||
|
yield False
|
||||||
|
return
|
||||||
|
yield True
|
||||||
|
finally:
|
||||||
|
os.close(fd)
|
||||||
|
|
||||||
|
|
||||||
def run_check(regions: list[int] | None = None, *, notify: bool = True) -> dict:
|
def run_check(regions: list[int] | None = None, *, notify: bool = True) -> dict:
|
||||||
"""Один прогон чекера. Возвращает отчёт. НЕ трогает state.json."""
|
"""Один прогон чекера. Возвращает отчёт. НЕ трогает state.json."""
|
||||||
|
with _solo_run() as solo:
|
||||||
|
if not solo:
|
||||||
|
with open(ext_state.ext_dir() / "watch.log", "a", encoding="utf-8") as f:
|
||||||
|
f.write(" ⏭ пропуск: предыдущий прогон чекера ещё идёт (наложение cron)\n")
|
||||||
|
return {"findings": [], "regions": [], "notify_ok": True,
|
||||||
|
"updates": 0, "problems": 0, "skipped": True}
|
||||||
|
return _run_check_body(regions, notify=notify)
|
||||||
|
|
||||||
|
|
||||||
|
def _run_check_body(regions: list[int] | None, *, notify: bool) -> dict:
|
||||||
|
raw = os.environ.get("EXT_REGIONS", "").strip()
|
||||||
regions = regions if regions is not None else _regions()
|
regions = regions if regions is not None else _regions()
|
||||||
seen = ext_state.load_watch_seen()
|
seen = ext_state.load_watch_seen()
|
||||||
findings: list[dict] = []
|
findings: list[dict] = []
|
||||||
if not regions:
|
if not regions:
|
||||||
findings.append({"source": "config", "level": "warning",
|
if raw.lower() == "all": # факт, а не гипотеза: переменная задана, но список не получен
|
||||||
"message": "EXT_REGIONS не задан — ФГИС не мониторится (проверяются только приказы)"})
|
findings.append({"source": "config", "level": "problem",
|
||||||
f_fgis, seen = check_fgis(regions, seen)
|
"message": "EXT_REGIONS=all, но список субъектов ФГИС не получен (сеть/схема)"})
|
||||||
f_pravo, seen = check_pravo(seen)
|
else:
|
||||||
f_od, seen = check_opendata(seen)
|
findings.append({"source": "config", "level": "warning",
|
||||||
f_bim, seen = check_bim(seen)
|
"message": "EXT_REGIONS не задан — ФГИС не мониторится (проверяются приказы/схемы)"})
|
||||||
f_xsd, seen = check_xsd(seen)
|
for name, fn in (("check_fgis", lambda s: check_fgis(regions, s)),
|
||||||
findings += f_fgis + f_pravo + f_od + f_bim + f_xsd
|
("check_pravo", check_pravo), ("check_opendata", check_opendata),
|
||||||
|
("check_bim", check_bim), ("check_xsd", check_xsd)):
|
||||||
|
f, seen = _safe_check(name, fn, seen)
|
||||||
|
findings += f
|
||||||
_write_report(findings, regions)
|
_write_report(findings, regions)
|
||||||
|
|
||||||
updates = [f for f in findings if f["level"] in ("update", "problem")]
|
updates = [f for f in findings if f["level"] in ("update", "problem")]
|
||||||
|
|||||||
@@ -79,8 +79,29 @@ def fetch_json(url: str, params: dict | None = None, *, client: httpx.Client | N
|
|||||||
raise FetchError(f"fetch_json {url}: {type(last).__name__}: {last}")
|
raise FetchError(f"fetch_json {url}: {type(last).__name__}: {last}")
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_text(url: str, params: dict | None = None, *, client: httpx.Client | None = None) -> str:
|
||||||
|
"""GET → текст (HTML), с ретраями и конвертацией httpx-ошибок в FetchError (иначе
|
||||||
|
сырое httpx-исключение пролетело бы мимо except FetchError и уронило вызывающего)."""
|
||||||
|
last: Exception | None = None
|
||||||
|
for attempt in range(RETRIES):
|
||||||
|
c = client or make_client()
|
||||||
|
try:
|
||||||
|
r = c.get(url, params=params)
|
||||||
|
r.raise_for_status()
|
||||||
|
return r.text
|
||||||
|
except httpx.HTTPError as e:
|
||||||
|
last = e
|
||||||
|
if attempt < RETRIES - 1:
|
||||||
|
_sleep_backoff(attempt)
|
||||||
|
finally:
|
||||||
|
if client is None:
|
||||||
|
c.close()
|
||||||
|
raise FetchError(f"fetch_text {url}: {type(last).__name__}: {last}")
|
||||||
|
|
||||||
|
|
||||||
def fetch_file(url: str, dest: os.PathLike | str, *, params: dict | None = None,
|
def fetch_file(url: str, dest: os.PathLike | str, *, params: dict | None = None,
|
||||||
expect_min_size: int = 1, expected_content_type: str | None = None,
|
expect_min_size: int = 1, expected_content_type: str | None = None,
|
||||||
|
reject_content_type: str | None = None,
|
||||||
client: httpx.Client | None = None) -> dict:
|
client: httpx.Client | None = None) -> dict:
|
||||||
"""Потоково скачать в dest (через *.part). Возвращает {path, size, sha256}.
|
"""Потоково скачать в dest (через *.part). Возвращает {path, size, sha256}.
|
||||||
fail-loud: мал/не тот тип → FetchError, dest не создан (остаётся .part для разбора)."""
|
fail-loud: мал/не тот тип → FetchError, dest не создан (остаётся .part для разбора)."""
|
||||||
@@ -100,6 +121,8 @@ def fetch_file(url: str, dest: os.PathLike | str, *, params: dict | None = None,
|
|||||||
ct = r.headers.get("content-type", "")
|
ct = r.headers.get("content-type", "")
|
||||||
if expected_content_type and expected_content_type not in ct:
|
if expected_content_type and expected_content_type not in ct:
|
||||||
raise FetchError(f"неожиданный content-type {ct!r} (ждали {expected_content_type!r})")
|
raise FetchError(f"неожиданный content-type {ct!r} (ждали {expected_content_type!r})")
|
||||||
|
if reject_content_type and reject_content_type in ct:
|
||||||
|
raise FetchError(f"отклонён content-type {ct!r} (страница ошибки вместо данных?)")
|
||||||
with open(part, "wb") as f:
|
with open(part, "wb") as f:
|
||||||
for chunk in r.iter_bytes(1 << 16):
|
for chunk in r.iter_bytes(1 << 16):
|
||||||
f.write(chunk)
|
f.write(chunk)
|
||||||
|
|||||||
+85
-21
@@ -15,6 +15,7 @@ from __future__ import annotations
|
|||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import shutil
|
||||||
import sys
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
import time
|
import time
|
||||||
@@ -26,6 +27,31 @@ import fgis_client as fc
|
|||||||
|
|
||||||
SNAP = "snapshots/fgis"
|
SNAP = "snapshots/fgis"
|
||||||
POLITE_PAUSE_S = 1.5 # пауза между запросами при обходах (вежливость к гос-API, анти-429)
|
POLITE_PAUSE_S = 1.5 # пауза между запросами при обходах (вежливость к гос-API, анти-429)
|
||||||
|
MIN_FREE_GB = 5.0 # жёсткий минимум свободного места (DATA_DIR общий с живым сервисом)
|
||||||
|
|
||||||
|
|
||||||
|
def _disk_free_gb() -> float:
|
||||||
|
d = ext_state.ext_dir()
|
||||||
|
while not d.exists() and d != d.parent:
|
||||||
|
d = d.parent
|
||||||
|
try:
|
||||||
|
return shutil.disk_usage(str(d)).free / 1e9
|
||||||
|
except OSError:
|
||||||
|
return 999.0 # не смогли измерить — не блокируем
|
||||||
|
|
||||||
|
|
||||||
|
def _disk_ok() -> bool:
|
||||||
|
return _disk_free_gb() >= MIN_FREE_GB
|
||||||
|
|
||||||
|
|
||||||
|
def _check_disk(n_subjects: int) -> None:
|
||||||
|
"""Оценка объёма «всех регионов» + fail-loud при нехватке (диск общий с прод-сервисом)."""
|
||||||
|
est_gb = n_subjects * 0.03 * 3 # ~30МБ × 3 источника на регион (сплит+индексы+salary), грубо
|
||||||
|
free = _disk_free_gb()
|
||||||
|
print(f" диск: свободно {free:.1f} ГБ, оценка загрузки ~{est_gb:.1f} ГБ ({n_subjects} регионов)")
|
||||||
|
if free < max(MIN_FREE_GB, est_gb * 2):
|
||||||
|
raise SystemExit(f"мало места: свободно {free:.1f} ГБ < нужно ~{max(MIN_FREE_GB, est_gb*2):.1f} ГБ. "
|
||||||
|
f"Освободи диск или качай меньше регионов (--regions <список>).")
|
||||||
|
|
||||||
|
|
||||||
def _verify_xlsx(path: Path, min_rows: int) -> None:
|
def _verify_xlsx(path: Path, min_rows: int) -> None:
|
||||||
@@ -113,13 +139,26 @@ def pull_salary(subject_id: int, zone_id: int, period_id: int | None = None) ->
|
|||||||
return {**meta, "items": data.get("total")}
|
return {**meta, "items": data.get("total")}
|
||||||
|
|
||||||
|
|
||||||
|
_RESERVED = {"meta.json"}
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_name(name: str | None, fallback: str) -> str:
|
||||||
|
"""Имя файла из внешнего API — не даём совпасть со служебными именами снапшота
|
||||||
|
(meta.json/*.tmp/*.part) и не пускаем traversal (Path().name срезает каталоги)."""
|
||||||
|
base = Path(str(name or "")).name
|
||||||
|
if (not base or base in _RESERVED or base in ("..", ".")
|
||||||
|
or base.endswith((".tmp", ".part", ".copytmp"))):
|
||||||
|
return fallback
|
||||||
|
return base
|
||||||
|
|
||||||
|
|
||||||
def pull_opendata(dataset_id: int) -> dict:
|
def pull_opendata(dataset_id: int) -> dict:
|
||||||
"""Скачать текущий файл датасета открытых данных (КСР/ФСНБ/СПСРП/оплата труда/ПССР)."""
|
"""Скачать текущий файл датасета открытых данных (КСР/ФСНБ/СПСРП/оплата труда/ПССР)."""
|
||||||
dest_dir = ext_state.ext_dir() / "snapshots/fgis/opendata" / str(dataset_id)
|
dest_dir = ext_state.ext_dir() / "snapshots/fgis/opendata" / str(dataset_id)
|
||||||
with tempfile.TemporaryDirectory() as td:
|
with tempfile.TemporaryDirectory() as td:
|
||||||
tmp = Path(td) / "download.bin"
|
tmp = Path(td) / "download.bin"
|
||||||
_res, name = fc.download_opendata(dataset_id, tmp)
|
_res, name = fc.download_opendata(dataset_id, tmp)
|
||||||
named = Path(td) / (Path(name).name or f"dataset_{dataset_id}")
|
named = Path(td) / _safe_name(name, f"dataset_{dataset_id}.bin")
|
||||||
tmp.replace(named)
|
tmp.replace(named)
|
||||||
meta = ext_state.register_snapshot(
|
meta = ext_state.register_snapshot(
|
||||||
dest_dir, named, source="fgis_opendata", key=f"opendata/{dataset_id}",
|
dest_dir, named, source="fgis_opendata", key=f"opendata/{dataset_id}",
|
||||||
@@ -135,14 +174,16 @@ def pull_all_opendata() -> list[dict]:
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def pull_bim() -> list[dict]:
|
def pull_bim(refetch_all: bool = False) -> list[dict]:
|
||||||
"""Скачать все письма-индексы (БИМ) — листовые документы дерева NormLegalDocPublished."""
|
"""Скачать письма-индексы (БИМ). ИНКРЕМЕНТАЛЬНО: пропускаем guid, чей снапшот уже есть
|
||||||
|
(иначе каждый прогон качал бы весь корпус ~2000 файлов). --refetch-all для полной сверки."""
|
||||||
out = []
|
out = []
|
||||||
docs = fc.bim_leaf_docs()
|
for d in fc.bim_leaf_docs():
|
||||||
for d in docs:
|
|
||||||
dest_dir = ext_state.ext_dir() / "snapshots/fgis/bim_letters" / d["guid"]
|
dest_dir = ext_state.ext_dir() / "snapshots/fgis/bim_letters" / d["guid"]
|
||||||
|
if not refetch_all and (dest_dir / "meta.json").exists():
|
||||||
|
continue # уже качали это письмо — не дёргаем гос-API повторно
|
||||||
with tempfile.TemporaryDirectory() as td:
|
with tempfile.TemporaryDirectory() as td:
|
||||||
tmp = Path(td) / (Path(str(d.get("filePath") or "letter")).name or "letter.pdf")
|
tmp = Path(td) / _safe_name(Path(str(d.get("filePath") or "")).name, "letter.pdf")
|
||||||
fc.download_by_guid(d["guid"], tmp, expect_min_size=500)
|
fc.download_by_guid(d["guid"], tmp, expect_min_size=500)
|
||||||
meta = ext_state.register_snapshot(
|
meta = ext_state.register_snapshot(
|
||||||
dest_dir, tmp, source="fgis_bim", key=f"bim/{d['guid']}",
|
dest_dir, tmp, source="fgis_bim", key=f"bim/{d['guid']}",
|
||||||
@@ -153,17 +194,22 @@ def pull_bim() -> list[dict]:
|
|||||||
|
|
||||||
|
|
||||||
def pull_xsd() -> list[dict]:
|
def pull_xsd() -> list[dict]:
|
||||||
"""Скачать все .zip-пакеты XSD-схем экспертизы со страницы Минстроя."""
|
"""Скачать .zip-пакеты XSD-схем экспертизы (после фильтра схем) со страницы Минстроя."""
|
||||||
|
import hashlib
|
||||||
|
|
||||||
import xsd_client
|
import xsd_client
|
||||||
out = []
|
out = []
|
||||||
for href in xsd_client.schema_links():
|
for url in xsd_client.schema_links():
|
||||||
fname = xsd_client._fname(href)
|
fname = xsd_client._fname(url)
|
||||||
dest_dir = ext_state.ext_dir() / "snapshots/xsd" / fname
|
# каталог/ключ по ПОЛНОМУ url (не basename) — иначе годовые версии с одним именем
|
||||||
|
# делили бы каталог и давали ложный «перезалив» каждый прогон.
|
||||||
|
uid = hashlib.sha1(url.encode()).hexdigest()[:12]
|
||||||
|
dest_dir = ext_state.ext_dir() / "snapshots/xsd" / f"{uid}_{fname}"
|
||||||
with tempfile.TemporaryDirectory() as td:
|
with tempfile.TemporaryDirectory() as td:
|
||||||
tmp = Path(td) / fname
|
tmp = Path(td) / fname
|
||||||
xsd_client.download_schema(href, tmp)
|
xsd_client.download_schema(url, tmp)
|
||||||
meta = ext_state.register_snapshot(
|
meta = ext_state.register_snapshot(
|
||||||
dest_dir, tmp, source="xsd_schema", key=f"xsd/{fname}", url=href)
|
dest_dir, tmp, source="xsd_schema", key=f"xsd/{url}", url=url)
|
||||||
out.append(meta)
|
out.append(meta)
|
||||||
time.sleep(POLITE_PAUSE_S)
|
time.sleep(POLITE_PAUSE_S)
|
||||||
return out
|
return out
|
||||||
@@ -177,9 +223,10 @@ def all_subject_ids() -> list[int]:
|
|||||||
return [s["id"] for s in fc.country_subjects()]
|
return [s["id"] for s in fc.country_subjects()]
|
||||||
|
|
||||||
|
|
||||||
def pull_all_for_subject(subject_id: int, period_id: int | None = None) -> list[dict]:
|
def pull_all_for_subject(subject_id: int, period_id: int | None = None,
|
||||||
|
zones: list[int] | None = None) -> list[dict]:
|
||||||
out = []
|
out = []
|
||||||
for zone_id in _zones_of(subject_id):
|
for zone_id in (zones if zones is not None else _zones_of(subject_id)):
|
||||||
out.append(pull_split_form(subject_id, zone_id, period_id))
|
out.append(pull_split_form(subject_id, zone_id, period_id))
|
||||||
time.sleep(POLITE_PAUSE_S) # вежливость к гос-API (анти-429)
|
time.sleep(POLITE_PAUSE_S) # вежливость к гос-API (анти-429)
|
||||||
out.append(pull_indices(subject_id, zone_id, period_id))
|
out.append(pull_indices(subject_id, zone_id, period_id))
|
||||||
@@ -231,9 +278,15 @@ def main(argv=None) -> int:
|
|||||||
_p(r)
|
_p(r)
|
||||||
return 0
|
return 0
|
||||||
if args.source == "all-sources":
|
if args.source == "all-sources":
|
||||||
for r in pull_all_opendata() + pull_bim() + pull_xsd():
|
failed = 0
|
||||||
_p(r)
|
for name, fn in (("opendata", pull_all_opendata), ("bim", pull_bim), ("xsd", pull_xsd)):
|
||||||
return 0
|
try:
|
||||||
|
for r in fn():
|
||||||
|
_p(r)
|
||||||
|
except Exception as e: # noqa: BLE001 — один источник не отменяет остальные
|
||||||
|
failed += 1
|
||||||
|
print(f" ✗ {name}: {type(e).__name__}: {e}", file=sys.stderr)
|
||||||
|
return 1 if failed else 0
|
||||||
|
|
||||||
# ФГИС по регионам (цены/индексы/оплата)
|
# ФГИС по регионам (цены/индексы/оплата)
|
||||||
if not fc.alive():
|
if not fc.alive():
|
||||||
@@ -244,10 +297,16 @@ def main(argv=None) -> int:
|
|||||||
if not subjects:
|
if not subjects:
|
||||||
print("не заданы регионы: --subject, --regions=all или env EXT_REGIONS", file=sys.stderr)
|
print("не заданы регионы: --subject, --regions=all или env EXT_REGIONS", file=sys.stderr)
|
||||||
return 2
|
return 2
|
||||||
|
_check_disk(len(subjects)) # оценка объёма + fail-loud при нехватке места
|
||||||
failed = 0
|
failed = 0
|
||||||
for sid in subjects:
|
for sid in subjects:
|
||||||
|
if not _disk_ok():
|
||||||
|
print(" ✗ мало места на диске — прерываю обход регионов", file=sys.stderr)
|
||||||
|
failed += 1
|
||||||
|
break
|
||||||
try:
|
try:
|
||||||
for r in pull_all_for_subject(sid, args.period):
|
zlist = [args.zone] if args.zone else None # --zone уважается (команда из чекера корректна)
|
||||||
|
for r in pull_all_for_subject(sid, args.period, zones=zlist):
|
||||||
_p(r)
|
_p(r)
|
||||||
except Exception as e: # noqa: BLE001 — один регион не валит остальные
|
except Exception as e: # noqa: BLE001 — один регион не валит остальные
|
||||||
failed += 1
|
failed += 1
|
||||||
@@ -259,9 +318,14 @@ def main(argv=None) -> int:
|
|||||||
return 2
|
return 2
|
||||||
zones = [args.zone] if args.zone else _zones_of(args.subject)
|
zones = [args.zone] if args.zone else _zones_of(args.subject)
|
||||||
fn = {"split_form": pull_split_form, "indices": pull_indices, "salary": pull_salary}[args.source]
|
fn = {"split_form": pull_split_form, "indices": pull_indices, "salary": pull_salary}[args.source]
|
||||||
for zone_id in zones:
|
failed = 0
|
||||||
_p(fn(args.subject, zone_id, args.period))
|
for zone_id in zones: # одна зона не валит остальные (симметрично ветке all)
|
||||||
return 0
|
try:
|
||||||
|
_p(fn(args.subject, zone_id, args.period))
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
failed += 1
|
||||||
|
print(f" ✗ зона {zone_id}: {type(e).__name__}: {e}", file=sys.stderr)
|
||||||
|
return 1 if failed else 0
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
+30
-15
@@ -100,9 +100,11 @@ def download_indices(period_id: int, price_zone_id: int, dest, client=None) -> d
|
|||||||
|
|
||||||
|
|
||||||
def download_by_guid(guid: str, dest, client=None, expect_min_size: int = 100) -> dict:
|
def download_by_guid(guid: str, dest, client=None, expect_min_size: int = 100) -> dict:
|
||||||
"""Скачать файл ФГИС по guid (общий механизм: /api/values/GetFileContent/{guid})."""
|
"""Скачать файл ФГИС по guid (общий механизм: /api/values/GetFileContent/{guid}).
|
||||||
|
Отклоняем text/html — это страница ошибки, а не данные (иначе испортила бы current)."""
|
||||||
return ext_fetch.fetch_file(f"{BASE}/api/values/GetFileContent/{guid}", dest,
|
return ext_fetch.fetch_file(f"{BASE}/api/values/GetFileContent/{guid}", dest,
|
||||||
expect_min_size=expect_min_size, client=client)
|
expect_min_size=expect_min_size, reject_content_type="text/html",
|
||||||
|
client=client)
|
||||||
|
|
||||||
|
|
||||||
# --- Открытые данные (15 датасетов: КСР, ФСНБ-2020/2022, СПСРП, оплата труда, 9 ПССР) ---
|
# --- Открытые данные (15 датасетов: КСР, ФСНБ-2020/2022, СПСРП, оплата труда, 9 ПССР) ---
|
||||||
@@ -144,38 +146,51 @@ def _norm_tree(parent_guid: str | None, client=None) -> list[dict]:
|
|||||||
if parent_guid:
|
if parent_guid:
|
||||||
params["parentGuid"] = parent_guid
|
params["parentGuid"] = parent_guid
|
||||||
data = ext_fetch.fetch_json(f"{BASE}/api/NormLegalDocPublished", params=params, client=client)
|
data = ext_fetch.fetch_json(f"{BASE}/api/NormLegalDocPublished", params=params, client=client)
|
||||||
# Ответ вида {"": [ ... ]} или список — берём значения.
|
# Ответ вида {"": [ ... ]} или список — берём значения-списки.
|
||||||
|
nodes = []
|
||||||
if isinstance(data, dict):
|
if isinstance(data, dict):
|
||||||
nodes = []
|
|
||||||
for v in data.values():
|
for v in data.values():
|
||||||
if isinstance(v, list):
|
if isinstance(v, list):
|
||||||
nodes.extend(v)
|
nodes.extend(v)
|
||||||
return nodes
|
elif isinstance(data, list):
|
||||||
return data if isinstance(data, list) else []
|
nodes = data
|
||||||
|
else:
|
||||||
|
raise FgisFormatError(f"дерево БИМ: неожиданный тип ответа {type(data).__name__}")
|
||||||
|
for n in nodes: # узел ОБЯЗАН быть объектом — иначе .get() ниже дал бы AttributeError и убил чекер
|
||||||
|
if not isinstance(n, dict):
|
||||||
|
raise FgisFormatError(f"дерево БИМ: узел не объект: {str(n)[:80]}")
|
||||||
|
return nodes
|
||||||
|
|
||||||
|
|
||||||
def bim_leaf_docs(max_nodes: int = 4000, client=None) -> list[dict]:
|
def bim_leaf_docs(max_nodes: int = 50000, client=None) -> list[dict]:
|
||||||
"""Все листовые документы дерева БИМ-писем (у листа есть filePath). Обход по parentGuid
|
"""Все листовые документы дерева БИМ-писем (у листа есть filePath). Обход по parentGuid.
|
||||||
с потолком узлов (защита от зацикливания при дрейфе схемы)."""
|
fail-loud (не тихая обрезка): пустой корень при живом API = смена схемы → исключение;
|
||||||
|
превышение потолка уникальных узлов = зацикливание/аномалия → исключение."""
|
||||||
out: list[dict] = []
|
out: list[dict] = []
|
||||||
stack = [None]
|
stack = [None]
|
||||||
seen: set[str] = set()
|
seen: set[str] = set()
|
||||||
visited = 0
|
accepted = 0
|
||||||
while stack and visited < max_nodes:
|
root_count = None
|
||||||
|
while stack:
|
||||||
pg = stack.pop()
|
pg = stack.pop()
|
||||||
for node in _norm_tree(pg, client=client):
|
children = _norm_tree(pg, client=client)
|
||||||
visited += 1
|
if pg is None:
|
||||||
|
root_count = len(children)
|
||||||
|
for node in children:
|
||||||
g = node.get("guid")
|
g = node.get("guid")
|
||||||
if not g or g in seen:
|
if not g or g in seen:
|
||||||
continue
|
continue
|
||||||
seen.add(g)
|
seen.add(g)
|
||||||
|
accepted += 1
|
||||||
|
if accepted > max_nodes: # не тихо обрезаем — падаем: потолок мал или зацикливание
|
||||||
|
raise FgisFormatError(f"дерево БИМ превысило {max_nodes} узлов — зацикливание/аномалия")
|
||||||
if node.get("filePath"): # лист-документ
|
if node.get("filePath"): # лист-документ
|
||||||
out.append({"guid": g, "name": node.get("name"), "date": node.get("date"),
|
out.append({"guid": g, "name": node.get("name"), "date": node.get("date"),
|
||||||
"number": node.get("number"), "filePath": node.get("filePath")})
|
"number": node.get("number"), "filePath": node.get("filePath")})
|
||||||
else: # папка (год/квартал) — углубляемся
|
else: # папка (год/квартал) — углубляемся
|
||||||
stack.append(g)
|
stack.append(g)
|
||||||
if visited >= max_nodes:
|
if not root_count: # письма-индексы существуют с 2020 — пустого корня не бывает
|
||||||
break
|
raise FgisFormatError("дерево БИМ: пустой корень — API сменил схему?")
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
Сеть замокана (fgis_client/pravo_client).
|
Сеть замокана (fgis_client/pravo_client).
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
|
import os
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -172,6 +173,48 @@ def test_new_sources_detected_and_deduped(_tmp, monkeypatch):
|
|||||||
assert not [f for f in rep2["findings"] if f["source"] in ("fgis_opendata", "fgis_bim", "xsd_schema")]
|
assert not [f for f in rep2["findings"] if f["source"] in ("fgis_opendata", "fgis_bim", "xsd_schema")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_checker_bug_becomes_problem_not_crash(_tmp, monkeypatch):
|
||||||
|
"""Фаза 4/5: НЕ-FetchError (баг в чекере) в одном источнике → problem-finding source=имя
|
||||||
|
чекера, а прогон продолжается (pravo проверен, heartbeat записан). Иначе баг убил бы отчёт."""
|
||||||
|
_mock_fgis(monkeypatch, latest=426)
|
||||||
|
_mock_pravo(monkeypatch, [{"eoNumber": "E1", "number": "1", "name": "смета",
|
||||||
|
"documentDate": "2026-07-01", "relevant": True, "pdf_url": "u"}])
|
||||||
|
def bug(client=None):
|
||||||
|
raise ValueError("нежданный KeyError-класс баг") # НЕ FetchError
|
||||||
|
monkeypatch.setattr(fc, "opendata_list", bug)
|
||||||
|
rep = ec.run_check(regions=[323], notify=False)
|
||||||
|
assert any(f["source"] == "check_opendata" and f["level"] == "problem" for f in rep["findings"])
|
||||||
|
assert any(f["source"] == "pravo" for f in rep["findings"]) # прогон не умер
|
||||||
|
assert es.heartbeat_age_days() is not None # heartbeat записан
|
||||||
|
|
||||||
|
|
||||||
|
def test_regions_all_but_unreachable_is_problem(_tmp, monkeypatch):
|
||||||
|
"""EXT_REGIONS=all, но список субъектов не получен (сеть/схема) → problem (факт), а не
|
||||||
|
тихое 'не задан' — оператор должен видеть, что мониторинг ФГИС фактически не идёт."""
|
||||||
|
monkeypatch.setenv("EXT_REGIONS", "all")
|
||||||
|
monkeypatch.setattr(fc, "country_subjects",
|
||||||
|
lambda client=None: (_ for _ in ()).throw(__import__("ext_fetch").FetchError("down")))
|
||||||
|
_mock_pravo(monkeypatch, [])
|
||||||
|
rep = ec.run_check(notify=False) # regions=None → _regions() → []
|
||||||
|
assert any(f["source"] == "config" and f["level"] == "problem"
|
||||||
|
and "all" in f["message"] for f in rep["findings"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_overlapping_run_is_skipped(_tmp, monkeypatch):
|
||||||
|
"""Неблокирующий guard: пока один прогон держит .check.lock, второй пропускается (не дубль)."""
|
||||||
|
_mock_fgis(monkeypatch, latest=426)
|
||||||
|
_mock_pravo(monkeypatch, [])
|
||||||
|
import fcntl
|
||||||
|
lock_path = es.ext_dir() / ".check.lock"
|
||||||
|
fd = os.open(str(lock_path), os.O_CREAT | os.O_RDWR, 0o644)
|
||||||
|
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) # имитируем идущий прогон
|
||||||
|
try:
|
||||||
|
rep = ec.run_check(regions=[323], notify=False)
|
||||||
|
finally:
|
||||||
|
os.close(fd)
|
||||||
|
assert rep.get("skipped") is True and rep["findings"] == []
|
||||||
|
|
||||||
|
|
||||||
def test_notify_called_only_with_findings(_tmp, monkeypatch):
|
def test_notify_called_only_with_findings(_tmp, monkeypatch):
|
||||||
_mock_fgis(monkeypatch, latest=426)
|
_mock_fgis(monkeypatch, latest=426)
|
||||||
_mock_pravo(monkeypatch, [])
|
_mock_pravo(monkeypatch, [])
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import httpx
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
import ext_fetch # noqa: E402
|
||||||
import fgis_client as fc # noqa: E402
|
import fgis_client as fc # noqa: E402
|
||||||
import xsd_client # noqa: E402
|
import xsd_client # noqa: E402
|
||||||
|
|
||||||
@@ -45,16 +46,31 @@ def test_bim_tree_recursion_collects_leaf_docs():
|
|||||||
|
|
||||||
|
|
||||||
def test_xsd_schema_links_extracted():
|
def test_xsd_schema_links_extracted():
|
||||||
html = '<a href="/upload/x/KAC-4_02.zip">КАЦ</a> <a href="/other.html">нет</a> ' \
|
"""Реальные имена со страницы Минстроя (сверено 2026-07): берём сметные/экспертизные схемы,
|
||||||
'<a href="/upload/y/LSR.zip">ЛСР</a>'
|
отсекаем журналы/акты И «схему пояснительной записки проекта» (её ловил старый маркер skhema)."""
|
||||||
|
html = (
|
||||||
|
'<a href="/upload/a/LocalEstimateResourceIndexMethod.zip">ЛСР РИМ</a>'
|
||||||
|
'<a href="/upload/a/SummaryEstimate.zip">ССР</a>'
|
||||||
|
'<a href="/upload/a/Format_predstavleniya_rezultatov_konyunkturnogo_analiza.zip">КА</a>'
|
||||||
|
'<a href="/upload/a/XML-схема заключения экспертизы.zip">эксп</a>'
|
||||||
|
'<a href="/upload/a/Журнал монтажа кабельных муфт.zip">журнал</a>'
|
||||||
|
'<a href="/upload/a/Obshchii_zhurnal_rabot.zip">общий журнал</a>'
|
||||||
|
'<a href="/upload/a/2_XML_skhema_poyasnitelnoi_zapiski.zip">ПЗ проекта</a>'
|
||||||
|
'<a href="/other.html">не zip</a>')
|
||||||
with httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, text=html))) as c:
|
with httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, text=html))) as c:
|
||||||
links = xsd_client.schema_links(client=c)
|
links = xsd_client.schema_links(client=c)
|
||||||
assert links == ["/upload/x/KAC-4_02.zip", "/upload/y/LSR.zip"]
|
names = {xsd_client._fname(u) for u in links}
|
||||||
assert xsd_client._fname("/upload/x/KAC-4_02.zip") == "KAC-4_02.zip"
|
assert names == {"LocalEstimateResourceIndexMethod.zip", "SummaryEstimate.zip",
|
||||||
|
"Format_predstavleniya_rezultatov_konyunkturnogo_analiza.zip",
|
||||||
|
"XML-схема заключения экспертизы.zip"}
|
||||||
|
assert all(u.startswith(xsd_client.BASE) for u in links) # абсолютные (urljoin)
|
||||||
|
|
||||||
|
|
||||||
def test_xsd_fail_loud_on_zero_links():
|
def test_xsd_fail_loud_on_only_non_schema_zips():
|
||||||
"""0 ссылок = вёрстка сменилась → FetchError, а не тихое «обновлений нет»."""
|
"""Страница из одних журналов/актов → 0 схем после фильтра → FetchError,
|
||||||
with httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, text="<html>no links</html>"))) as c:
|
а НЕ тихое скачивание журналов как «схем» (реальный баг, замеченный пользователем)."""
|
||||||
with pytest.raises(Exception):
|
html = ('<a href="/a/Журнал монтажа кабельных муфт.zip">ж</a>'
|
||||||
|
'<a href="/a/Akt_osvidetelstvovaniya_skrytykh_rabot.zip">акт</a>')
|
||||||
|
with httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, text=html))) as c:
|
||||||
|
with pytest.raises(ext_fetch.FetchError):
|
||||||
xsd_client.schema_links(client=c)
|
xsd_client.schema_links(client=c)
|
||||||
|
|||||||
+44
-23
@@ -1,59 +1,80 @@
|
|||||||
"""xsd_client — XSD-схемы сметной документации/экспертизы с minstroyrf.gov.ru (срез 5.1).
|
"""xsd_client — XSD-схемы сметной документации/экспертизы с minstroyrf.gov.ru (срез 5.1).
|
||||||
|
|
||||||
Единственный НЕ-API источник: HTML-страница /tim/xml-skhemy/ со ссылками на .zip-пакеты
|
Единственный НЕ-API источник: HTML /tim/xml-skhemy/. Страница содержит ~150 .zip, но лишь
|
||||||
схем (ЛСР, ОСР, КАЦ и т.д.). Скрейп стандартным html.parser (без новых зависимостей).
|
часть — сметные/экспертизные схемы (LocalEstimate/ObjectEstimate/SummaryEstimate/CostsSummary/
|
||||||
fail-loud: 0 ссылок = вёрстка изменилась (НЕ «обновлений нет» — типовая тихая ложь скрейпера).
|
MarketAnalysis/Format_predstavleniya/заключение экспертизы); остальное — строительные журналы
|
||||||
Скачивание/версионирование только; валидация gge_export по схемам (нужен lxml) — отдельный
|
и акты. Фильтруем по маркерам схем (иначе качали бы мусор). fail-loud: 0 после фильтра =
|
||||||
срез 5.2 по согласованию.
|
вёрстка сменилась. SSRF-защита: скачиваем только с хоста Минстроя (urljoin + allowlist).
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import os
|
||||||
from html.parser import HTMLParser
|
from html.parser import HTMLParser
|
||||||
|
from urllib.parse import urljoin, urlsplit
|
||||||
|
|
||||||
import ext_fetch
|
import ext_fetch
|
||||||
|
|
||||||
BASE = os.environ.get("MINSTROY_BASE", "https://minstroyrf.gov.ru")
|
BASE = os.environ.get("MINSTROY_BASE", "https://minstroyrf.gov.ru")
|
||||||
PAGE = os.environ.get("MINSTROY_XSD_PAGE", "/tim/xml-skhemy/")
|
PAGE = os.environ.get("MINSTROY_XSD_PAGE", "/tim/xml-skhemy/")
|
||||||
|
|
||||||
|
# Маркеры реальных сметных/экспертизных схем (нижний регистр; латиница транслита + кириллица).
|
||||||
|
# Сверено с живой страницей (151 .zip, 2026-07): ловим LocalEstimate*/ObjectEstimate/
|
||||||
|
# SummaryEstimate/CostsSummary/MarketAnalysis*/Format_predstavleniya_*/*zaklyucheniya_ekspertizy*/
|
||||||
|
# «XML-схема заключения экспертизы»/«Пояснительная записка к сметной документации».
|
||||||
|
# НЕ берём голые "skhema"/"схема" — они цепляют "XML_skhema_poyasnitelnoi_zapiski" (схема
|
||||||
|
# пояснительной записки ПРОЕКТА, не смета); экспертизу и так ловят zaklyuchen/заключен.
|
||||||
|
SCHEMA_MARKERS = (
|
||||||
|
"estimate", "costssummary", "marketanalysis", "konyunktur", "конъюнктур",
|
||||||
|
"format_predstavl", "zaklyuchen", "заключен", "сметн", "smetn",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class _ZipLinkParser(HTMLParser):
|
class _ZipLinkParser(HTMLParser):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.links: list[str] = []
|
self.hrefs: list[str] = []
|
||||||
|
|
||||||
def handle_starttag(self, tag, attrs):
|
def handle_starttag(self, tag, attrs):
|
||||||
if tag == "a":
|
if tag == "a":
|
||||||
href = dict(attrs).get("href", "") or ""
|
href = dict(attrs).get("href", "") or ""
|
||||||
if href.lower().endswith(".zip"):
|
if urlsplit(href).path.lower().endswith(".zip"): # .zip по ПУТИ (query/якорь отброшены)
|
||||||
self.links.append(href)
|
self.hrefs.append(href)
|
||||||
|
|
||||||
|
|
||||||
|
def _is_schema(url: str) -> bool:
|
||||||
|
name = urlsplit(url).path.rsplit("/", 1)[-1].lower()
|
||||||
|
return any(m in name for m in SCHEMA_MARKERS)
|
||||||
|
|
||||||
|
|
||||||
def _page_html(client=None) -> str:
|
def _page_html(client=None) -> str:
|
||||||
c = client or ext_fetch.make_client()
|
return ext_fetch.fetch_text(f"{BASE}{PAGE}", client=client) # FetchError + ретраи (не сырой httpx)
|
||||||
try:
|
|
||||||
r = c.get(f"{BASE}{PAGE}")
|
|
||||||
r.raise_for_status()
|
def _same_host(url: str) -> bool:
|
||||||
return r.text
|
return urlsplit(url).netloc == urlsplit(BASE).netloc
|
||||||
finally:
|
|
||||||
if client is None:
|
|
||||||
c.close()
|
|
||||||
|
|
||||||
|
|
||||||
def schema_links(client=None) -> list[str]:
|
def schema_links(client=None) -> list[str]:
|
||||||
"""Ссылки на .zip-пакеты схем со страницы. fail-loud при 0 (вёрстка сменилась)."""
|
"""Абсолютные URL .zip-пакетов СХЕМ (сметные/экспертиза) с хоста Минстроя.
|
||||||
|
fail-loud при 0 после фильтра (вёрстка/страница сменилась)."""
|
||||||
p = _ZipLinkParser()
|
p = _ZipLinkParser()
|
||||||
p.feed(_page_html(client=client))
|
p.feed(_page_html(client=client))
|
||||||
links = sorted(set(p.links))
|
urls = []
|
||||||
|
for href in p.hrefs:
|
||||||
|
absu = urljoin(f"{BASE}{PAGE}", href) # относительные без слэша резолвятся корректно
|
||||||
|
if _same_host(absu) and _is_schema(absu): # только Минстрой и только схемы (не журналы/акты)
|
||||||
|
urls.append(absu)
|
||||||
|
links = sorted(set(urls))
|
||||||
if not links:
|
if not links:
|
||||||
raise ext_fetch.FetchError("страница XSD-схем: 0 ссылок .zip — изменилась вёрстка/страница?")
|
raise ext_fetch.FetchError("страница XSD-схем: 0 схемных .zip после фильтра — вёрстка сменилась?")
|
||||||
return links
|
return links
|
||||||
|
|
||||||
|
|
||||||
def _fname(href: str) -> str:
|
def _fname(url: str) -> str:
|
||||||
return href.rstrip("/").split("/")[-1] or "schema.zip"
|
return urlsplit(url).path.rstrip("/").split("/")[-1] or "schema.zip"
|
||||||
|
|
||||||
|
|
||||||
def download_schema(href: str, dest, client=None) -> dict:
|
def download_schema(url: str, dest, client=None) -> dict:
|
||||||
url = href if href.startswith("http") else f"{BASE}{href}"
|
if not _same_host(url):
|
||||||
|
raise ext_fetch.FetchError(f"внешний хост в ссылке схемы: {url}")
|
||||||
return ext_fetch.fetch_file(url, dest, expect_min_size=100, client=client)
|
return ext_fetch.fetch_file(url, dest, expect_min_size=100, client=client)
|
||||||
|
|||||||
Reference in New Issue
Block a user