"""ext_pull — скачивание внешних данных ФГИС ЦС в версионированные снапшоты (срез 1.2). ОСОЗНАННЫЙ шаг (не чекер): качает сплит-форму / индексы ГОСР / оплату труда по региону+ кварталу, кладёт в снапшот (ext_state.register_snapshot — crash-safe, версионирование), отмечает в state. НЕ активирует данные для движка (это ext_apply). НЕ рестартит сервис. Объёмы: сплит-форма ~13.7МБ × регион × квартал. По умолчанию только EXT_REGIONS (id регионов через запятую) — НЕ все 85. Периоды: latest, если не задан. CLI: python3 ext_pull.py --source split_form --subject 323 [--zone 191] [--period 426] python3 ext_pull.py --source all --regions 323 # split+indices+salary """ from __future__ import annotations import argparse import json import os import shutil import sys import tempfile import time from pathlib import Path import ext_fetch import ext_state import fgis_client as fc SNAP = "snapshots/fgis" 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 0.0 # не смогли измерить → fail-closed: guard срабатывает (диск общий с продом) 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: """Лёгкая проверка скачанного xlsx ДО регистрации: открывается + строк ≥ min. Ловит server-side обрезанные HTTP-200 выгрузки, которые прошли по размеру (баг Fable).""" import openpyxl try: wb = openpyxl.load_workbook(str(path), read_only=True) try: ws = wb.active n = sum(1 for _ in ws.iter_rows(min_col=1, max_col=1, values_only=True)) finally: wb.close() except Exception as e: # noqa: BLE001 raise ext_fetch.FetchError(f"скачанный файл не открывается как xlsx: {type(e).__name__}: {e}") if n < min_rows: raise ext_fetch.FetchError(f"скачано строк {n} < {min_rows} — обрезанная выгрузка?") def _snap_dir(kind: str, subject_id: int, zone_id: int, period_id: int) -> Path: return ext_state.ext_dir() / SNAP / kind / str(subject_id) / str(zone_id) / str(period_id) def _record_state(kind: str, subject_id: int, zone_id: int, period_id: int, meta: dict) -> None: with ext_state.update_state() as st: srcs = st["sources"].setdefault(f"fgis_{kind}", {}) srcs[f"{subject_id}/{zone_id}"] = { "period_id": period_id, "sha256": meta["sha256"], "rev": meta["rev"], "pulled_at": meta["fetched_at"], "reuploaded": meta.get("reuploaded", False), } def _resolve_period(zone_id: int, period_id: int | None) -> int: if period_id: return period_id lp = fc.latest_period(zone_id) if not lp: raise ext_fetch.FetchError(f"нет периодов для зоны {zone_id}") # не SystemExit из библиотеки return lp["id"] def pull_split_form(subject_id: int, zone_id: int, period_id: int | None = None) -> dict: period_id = _resolve_period(zone_id, period_id) dest_dir = _snap_dir("split_form", subject_id, zone_id, period_id) with tempfile.TemporaryDirectory() as td: tmp = Path(td) / "fgis_split_form.xlsx" res = fc.download_split_form(period_id, zone_id, tmp) _verify_xlsx(tmp, min_rows=1000) # битое/обрезанное не регистрируем meta = ext_state.register_snapshot( dest_dir, tmp, source="fgis_split_form", key=f"{subject_id}/{zone_id}/{period_id}", url=fc.BASE + "/api/EstimatedPrice/BuildingResources/ExportSplitForm", params={"periodId": period_id, "priceZoneId": zone_id}) _record_state("split_form", subject_id, zone_id, period_id, meta) return {**meta, "downloaded_size": res["size"]} def pull_indices(subject_id: int, zone_id: int, period_id: int | None = None) -> dict: period_id = _resolve_period(zone_id, period_id) dest_dir = _snap_dir("indices_gosr", subject_id, zone_id, period_id) with tempfile.TemporaryDirectory() as td: tmp = Path(td) / "fgis_indices_gosr.xlsx" fc.download_indices(period_id, zone_id, tmp) _verify_xlsx(tmp, min_rows=50) # индексы ГОСР — сотни строк; обрезанное не регистрируем meta = ext_state.register_snapshot( dest_dir, tmp, source="fgis_indices_gosr", key=f"{subject_id}/{zone_id}/{period_id}", url=fc.BASE + "/api/IndicesForResourcesGroups/GenerateCustomReport", params={"periodId": period_id, "priceZoneId": zone_id}) _record_state("indices_gosr", subject_id, zone_id, period_id, meta) return meta def pull_salary(subject_id: int, zone_id: int, period_id: int | None = None) -> dict: period_id = _resolve_period(zone_id, period_id) dest_dir = _snap_dir("salary", subject_id, zone_id, period_id) data = fc.salary_registry(zone_id, period_id) with tempfile.TemporaryDirectory() as td: tmp = Path(td) / "salary_registry.json" tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8") meta = ext_state.register_snapshot( dest_dir, tmp, source="fgis_salary", key=f"{subject_id}/{zone_id}/{period_id}", url=fc.BASE + "/api/EstimatedPrice/RimWorkerSalaryRegistry", params={"priceZoneId": zone_id, "periodId": period_id}) _record_state("salary", subject_id, zone_id, period_id, meta) 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: """Скачать текущий файл датасета открытых данных (КСР/ФСНБ/СПСРП/оплата труда/ПССР).""" dest_dir = ext_state.ext_dir() / "snapshots/fgis/opendata" / str(dataset_id) with tempfile.TemporaryDirectory() as td: tmp = Path(td) / "download.bin" _res, name = fc.download_opendata(dataset_id, tmp) named = Path(td) / _safe_name(name, f"dataset_{dataset_id}.bin") tmp.replace(named) meta = ext_state.register_snapshot( dest_dir, named, source="fgis_opendata", key=f"opendata/{dataset_id}", url=fc.BASE + f"/api/OpenData/{dataset_id}") return {**meta, "dataset_id": dataset_id} def pull_all_opendata() -> list[dict]: out = [] for ds in fc.opendata_list(): out.append(pull_opendata(ds["id"])) time.sleep(POLITE_PAUSE_S) return out def pull_bim(refetch_all: bool = False) -> list[dict]: """Скачать письма-индексы (БИМ). ИНКРЕМЕНТАЛЬНО: пропускаем guid, чей снапшот уже есть (иначе каждый прогон качал бы весь корпус ~2000 файлов). --refetch-all для полной сверки.""" out = [] failed = 0 for d in fc.bim_leaf_docs(): dest_dir = ext_state.ext_dir() / "snapshots/fgis/bim_letters" / d["guid"] if not refetch_all and (dest_dir / "meta.json").exists(): continue # уже качали это письмо — не дёргаем гос-API повторно try: with tempfile.TemporaryDirectory() as td: 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) meta = ext_state.register_snapshot( dest_dir, tmp, source="fgis_bim", key=f"bim/{d['guid']}", url=fc.BASE + f"/api/values/GetFileContent/{d['guid']}") except ext_fetch.FetchError as e: # одно «ядовитое» письмо (удалено上游→HTML, битое) НЕ должно навсегда блокировать # хвост корпуса: инкрементальный skip иначе застревал бы на нём каждый прогон. failed += 1 print(f" ✗ БИМ-письмо {d.get('name') or d['guid']}: {e}", file=sys.stderr) continue out.append({**meta, "letter": d.get("name")}) time.sleep(POLITE_PAUSE_S) if failed: print(f" ⚠ БИМ: {failed} писем не скачалось (пропущены, хвост корпуса докачан)", file=sys.stderr) return out def pull_xsd() -> list[dict]: """Скачать .zip-пакеты XSD-схем экспертизы (после фильтра схем) со страницы Минстроя. Каталог/ключ по ИМЕНИ файла (не по url): версии схем имеют уникальные имена (…-4_01/…-4_02/ …_1_09 — сверено на живой странице), а имя устойчиво к смене относительный→абсолютный URL.""" import xsd_client out = [] failed = 0 for url in xsd_client.schema_links(): fname = xsd_client._fname(url) dest_dir = ext_state.ext_dir() / "snapshots/xsd" / fname try: with tempfile.TemporaryDirectory() as td: tmp = Path(td) / fname xsd_client.download_schema(url, tmp) meta = ext_state.register_snapshot( dest_dir, tmp, source="xsd_schema", key=f"xsd/{fname}", url=url) except ext_fetch.FetchError as e: failed += 1 print(f" ✗ схема {fname}: {e}", file=sys.stderr) continue out.append(meta) time.sleep(POLITE_PAUSE_S) if failed: print(f" ⚠ XSD: {failed} схем не скачалось (пропущены, остальные — ок)", file=sys.stderr) return out def _zones_of(subject_id: int) -> list[int]: return [z["id"] for z in fc.price_zones(subject_id)] def all_subject_ids() -> list[int]: return [s["id"] for s in fc.country_subjects()] def pull_all_for_subject(subject_id: int, period_id: int | None = None, zones: list[int] | None = None) -> list[dict]: out = [] 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)) time.sleep(POLITE_PAUSE_S) # вежливость к гос-API (анти-429) out.append(pull_indices(subject_id, zone_id, period_id)) time.sleep(POLITE_PAUSE_S) out.append(pull_salary(subject_id, zone_id, period_id)) time.sleep(POLITE_PAUSE_S) return out def _regions_from_env(cli_regions: str | None) -> list[int]: raw = (cli_regions or os.environ.get("EXT_REGIONS", "")).strip() if raw.lower() == "all": return all_subject_ids() return [int(x) for x in raw.replace(";", ",").split(",") if x.strip().isdigit()] def _p(r: dict) -> None: print(f" ✓ {r['source']} {r['key']} rev={r['rev']} sha={r['sha256'][:12]}" + (" ⚠ПЕРЕЗАЛИВ" if r.get("reuploaded") else "")) def main(argv=None) -> int: ap = argparse.ArgumentParser(description="Скачать данные ФГИС/схемы в снапшоты (осознанный шаг).") ap.add_argument("--source", required=True, choices=[ "split_form", "indices", "salary", "all", # цены ФГИС по региону "opendata", "bim", "xsd", "all-sources"]) # справочники/письма/схемы ap.add_argument("--subject", type=int, help="id региона") ap.add_argument("--zone", type=int, help="id ценовой зоны (если не задан — все зоны региона)") ap.add_argument("--period", type=int, help="id периода (по умолчанию последний)") ap.add_argument("--dataset", type=int, help="id датасета для --source opendata (иначе все)") ap.add_argument("--regions", help="id регионов через запятую, или 'all', или env EXT_REGIONS") args = ap.parse_args(argv) # источники без региона (opendata/bim/xsd) — не требуют ФГИС-alive-пречека кроме ФГИС-овских if args.source in ("opendata", "bim", "all-sources") and not fc.alive(): print("ФГИС ЦС недоступен (/api/alive). Прервано.", file=sys.stderr) return 2 if args.source == "opendata": for r in ([pull_opendata(args.dataset)] if args.dataset else pull_all_opendata()): _p(r) return 0 if args.source == "bim": for r in pull_bim(): _p(r) return 0 if args.source == "xsd": for r in pull_xsd(): _p(r) return 0 if args.source == "all-sources": failed = 0 for name, fn in (("opendata", pull_all_opendata), ("bim", pull_bim), ("xsd", pull_xsd)): 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(): print("ФГИС ЦС недоступен (/api/alive). Прервано.", file=sys.stderr) return 2 if args.source == "all": subjects = [args.subject] if args.subject else _regions_from_env(args.regions) if not subjects: print("не заданы регионы: --subject, --regions=all или env EXT_REGIONS", file=sys.stderr) return 2 if args.zone and len(subjects) > 1: # --zone применялась бы КО ВСЕМ регионам: зона 191 (Москва) записалась бы под # ключами чужих субъектов (50/191, 77/191…) → чужие цены в state.json. fail-loud. print("--zone нельзя с несколькими регионами (у каждого свои зоны); " "задай один --subject или убери --zone", file=sys.stderr) return 2 _check_disk(len(subjects)) # оценка объёма + fail-loud при нехватке места failed = 0 for sid in subjects: if not _disk_ok(): print(" ✗ мало места на диске — прерываю обход регионов", file=sys.stderr) failed += 1 break try: zlist = [args.zone] if args.zone else None # --zone уважается (команда из чекера корректна) for r in pull_all_for_subject(sid, args.period, zones=zlist): _p(r) except Exception as e: # noqa: BLE001 — один регион не валит остальные failed += 1 print(f" ✗ регион {sid}: {type(e).__name__}: {e}", file=sys.stderr) return 1 if failed else 0 if not args.subject: print("--subject обязателен", file=sys.stderr) return 2 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] failed = 0 for zone_id in zones: # одна зона не валит остальные (симметрично ветке all) 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__": raise SystemExit(main())