#!/usr/bin/env python3 """Ежедневный обход зон ФГИС: ожидания «форм нет» и отметка успешного обхода. Правила (design-log 2026-11-21з): ожидания — отдельный файл на сервере; «нет» только по успешному ответу портала; сетевой сбой — «не проверено», ожидания не меняются; общий flock с недельным обходом; ожидание снимается по горизонту или уходу зоны; одна строка журнала на прогон. """ from __future__ import annotations import argparse, fcntl, json, os, re, sqlite3, time from datetime import datetime, timezone from pathlib import Path EXPECT_DEFAULT = "/data_fast/smeta-web-data/_external/coverage_expectations.json" STATE_DEFAULT = "/data_fast/smeta-web-data/_external/zone_scan_state.json" LOG_DEFAULT = "/data_fast/smeta-web-data/_external/zone_scan.log" LOCK_DEFAULT = "/tmp/smeta-refresh.lock" DB_DEFAULT = "/data_fast/smeta-web-data/_external/derived/fgis_ref/fgis_ref.sqlite" def _period_key(label: str) -> str: m = re.search(r"(\d)\s*квартал.*?(\d{4})", label or "", re.I) return f"{m.group(2)}-Q{m.group(1)}" if m else (label or "") def _period_rank(key: str) -> tuple[int, int]: m = re.match(r"(\d{4})-Q([1-4])", key or "") return (int(m.group(1)), int(m.group(2))) if m else (0, 0) def plan(existing: list[dict], portal: dict[tuple[int, int], list[dict]], known: set[tuple[int, int, int]], horizon: int = 2, zones_by_subject: dict[int, set[int]] | None = None) -> tuple[list[dict], list[dict]]: """Вернуть (добавить, снять) для ожиданий. Чистая функция — без сети и базы. zones_by_subject — только успешно прочитанные списки зон. Уход зоны доказывается лишь тогда, когда список её субъекта прочитан и зоны в нём нет; при сбое сети субъекта в словаре нет, и его ожидания остаются нетронутыми. """ have = {(int(e["subject_id"]), int(e["zone_id"]), e["period"]) for e in existing} adds, removes = [], [] for (sid, zid), periods in portal.items(): latest = sorted((p["id"], _period_key(p.get("name", ""))) for p in periods) keep_rank = latest[-horizon][0] if len(latest) >= horizon else None for pid, per in latest[-horizon:]: if (sid, zid, per) in have or (sid, zid, pid) in known: continue adds.append({"subject_id": sid, "zone_id": zid, "period": per, "zone_name": None, "reason": "проверяется"}) # снять ожидания старее горизонта for e in existing: if int(e["subject_id"]) != sid or int(e["zone_id"]) != zid: continue if keep_rank is not None and _period_rank(e["period"]) < _period_rank( dict(latest).get(keep_rank, "")): removes.append(e) if zones_by_subject is not None: for e in existing: sid, zid = int(e["subject_id"]), int(e["zone_id"]) if sid in zones_by_subject and zid not in zones_by_subject[sid]: removes.append(e) return adds, removes def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--expect", default=os.environ.get("SCAN_EXPECT", EXPECT_DEFAULT)) ap.add_argument("--state", default=os.environ.get("SCAN_STATE", STATE_DEFAULT)) ap.add_argument("--log", default=os.environ.get("SCAN_LOG", LOG_DEFAULT)) ap.add_argument("--db", default=os.environ.get("FGIS_DB", DB_DEFAULT)) ap.add_argument("--dry-run", action="store_true") a = ap.parse_args() lock = open(os.environ.get("SCAN_LOCK", LOCK_DEFAULT), "w") try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: print("SCAN busy: замок занят недельным обходом", flush=True) return 3 import fgis_client as fc, ext_pull expect_path, state_path = Path(a.expect), Path(a.state) existing = json.loads(expect_path.read_text(encoding="utf-8")) if expect_path.exists() else [] known, portal, failures = set(), {}, [] con = sqlite3.connect(f"file:{a.db}?mode=ro", uri=True) known = {(int(s), int(z), int(p)) for s, z, p in con.execute("select subject_id,zone_id,period_id from zone_snapshots")} con.close() zones_by_subject = {} try: subjects = fc.country_subjects() except Exception as e: # noqa: BLE001 — сеть: не проверено, ожидания не меняем failures.append(f"subjects: {type(e).__name__}"); subjects = [] for s in subjects: try: zones = fc.price_zones(s["id"]) except Exception as e: # noqa: BLE001 — сеть: не проверено, ожидания не меняем failures.append(f"zones {s['id']}: {type(e).__name__}"); continue zones_by_subject[s["id"]] = {z["id"] for z in zones} for z in zones: try: portal[(s["id"], z["id"])] = fc.periods(z["id"]) except Exception as e: # noqa: BLE001 failures.append(f"periods {s['id']}/{z['id']}: {type(e).__name__}") adds, removes = plan(existing, portal, known, zones_by_subject=zones_by_subject) checked = downloaded = expectations_added = 0 for add in adds: sid, zid = add["subject_id"], add["zone_id"] pid = next(p["id"] for p in portal[(sid, zid)] if _period_key(p.get("name", "")) == add["period"]) try: ext_pull.pull_split_form(sid, zid, pid) downloaded += 1 except Exception as e: # noqa: BLE001 text = str(e) if "404" in text: add.update(zone_name=None, reason="на портале ФГИС ЦС форм за период нет (проверено " + datetime.now(timezone.utc).strftime("%Y-%m-%d") + ")") existing.append(add); expectations_added += 1 else: failures.append(f"form {sid}/{zid}/{pid}: {type(e).__name__}") checked += 1 existing = [e for e in existing if e not in removes] stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") if not a.dry_run: if expectations_added or removes: tmp = expect_path.with_suffix(".tmp") tmp.write_text(json.dumps(existing, ensure_ascii=False, indent=1), encoding="utf-8") tmp.replace(expect_path) previous = {} if state_path.exists(): try: previous = json.loads(state_path.read_text(encoding="utf-8")) except Exception: # noqa: BLE001 — битая отметка не отменяет сам обход previous = {} state_path.write_text(json.dumps({ "last_attempt": stamp, "last_success": stamp if not failures else previous.get("last_success"), "zones": len(portal), "new_periods": checked, "downloaded": downloaded, "expectations_added": expectations_added, "removed": len(removes), "failures": failures}, ensure_ascii=False), encoding="utf-8") line = (f"{stamp} зон={len(portal)} новых={checked} добавлено={downloaded} " f"ожиданий={expectations_added} снято={len(removes)} " + ("без изменений" if not checked and not removes else "изменения") + (f" сбоев={len(failures)}" if failures else "")) with open(a.log, "a", encoding="utf-8") as f: f.write(line + "\n") print(line) return 0 if not failures else 1 if __name__ == "__main__": raise SystemExit(main())