fix(обход): сбой сети не снимает ожидания, здоровье краснеет при сбоях
Уход зоны доказывается только успешно прочитанным списком зон субъекта: при сбое списка зон или периодов ожидания остаются. last_success пишется только при пустом списке сбоев, попытка отмечается отдельно. Health-проверка zone_scan краснеет от сбоев и от возраста свыше 36 часов, в журнале сторожа виден возраст обхода. Проверки: три ветки на выдуманных данных, мутации ловятся. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
+42
-18
@@ -29,8 +29,14 @@ def _period_rank(key: str) -> tuple[int, int]:
|
||||
|
||||
|
||||
def plan(existing: list[dict], portal: dict[tuple[int, int], list[dict]],
|
||||
known: set[tuple[int, int, int]], horizon: int = 2) -> tuple[list[dict], 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():
|
||||
@@ -48,10 +54,11 @@ def plan(existing: list[dict], portal: dict[tuple[int, int], list[dict]],
|
||||
if keep_rank is not None and _period_rank(e["period"]) < _period_rank(
|
||||
dict(latest).get(keep_rank, "")):
|
||||
removes.append(e)
|
||||
zones = set(portal)
|
||||
for e in existing:
|
||||
if (int(e["subject_id"]), int(e["zone_id"])) not in zones:
|
||||
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
|
||||
|
||||
|
||||
@@ -77,46 +84,63 @@ def main() -> int:
|
||||
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()
|
||||
subjects = fc.country_subjects()
|
||||
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)
|
||||
checked = added = 0
|
||||
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); added += 1
|
||||
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:
|
||||
tmp = expect_path.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(existing, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
tmp.replace(expect_path)
|
||||
state_path.write_text(json.dumps({"last_success": stamp, "zones": len(portal),
|
||||
"added": added, "removed": len(removes),
|
||||
"failures": failures}, ensure_ascii=False), encoding="utf-8")
|
||||
line = (f"{stamp} зон={len(portal)} добавлено={added} снято={len(removes)} "
|
||||
+ ("без изменений" if not added and not removes else "изменения")
|
||||
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")
|
||||
|
||||
Reference in New Issue
Block a user