добавленны обработки json в потоках

This commit is contained in:
2025-10-29 10:58:29 +03:00
parent ea34b6521f
commit 6721951c34

View File

@@ -58,7 +58,7 @@ URLS = [
{ {
"name": "game", "name": "game",
"url": "{host}/api/abc/games/game?Id={game_id}&Lang={lang}", "url": "{host}/api/abc/games/game?Id={game_id}&Lang={lang}",
"interval": 600, # раз в 10 минут "interval": 60, # раз в 10 минут
}, },
{ {
"name": "pregame", "name": "pregame",
@@ -468,7 +468,7 @@ def classify_game_state_from_status(status_raw: str) -> str:
status = (status_raw or "").lower() status = (status_raw or "").lower()
if status in ("resultconfirmed", "finished", "result"): if status in ("resultconfirmed", "finished", "result"):
return "finished" return "finished"
if status in ("scheduled", "notstarted", "draft"): if status in ("", "notstarted", "draft"):
return "upcoming" return "upcoming"
# всё остальное считаем лайвом # всё остальное считаем лайвом
return "live" return "live"
@@ -560,7 +560,7 @@ def poll_game_live(
if game_finished: if game_finished:
break break
time.sleep(0.5) time.sleep(0.2)
if stop_event.is_set(): if stop_event.is_set():
logger.info( logger.info(
@@ -677,70 +677,51 @@ def build_render_state() -> dict:
def render_loop(stop_event: threading.Event, out_name: str = "game") -> None: def render_loop(stop_event: threading.Event, out_name: str = "game") -> None:
logger.info("[RENDER_THREAD] start render loop") logger.info("[RENDER_THREAD] start render loop")
while not stop_event.is_set(): with ThreadPoolExecutor(max_workers=6) as pool:
try: while not stop_event.is_set():
try: try:
state = build_render_state() try:
except Exception as build_err: state = build_render_state()
# до тех пор, пока api_game не готов или битый — просто ждём except Exception as build_err:
logger.debug( logger.debug(f"[RENDER_THREAD] build_render_state not ready: {build_err}")
f"[RENDER_THREAD] build_render_state not ready: {build_err}" time.sleep(0.2)
) continue
time.sleep(0.2)
continue
# пробуем каждую генерацию отдельно, чтобы одна не убила остальные tasks = {
try: "team_stats": pool.submit(Team_Both_Stat, state),
Team_Both_Stat(state) "team1": pool.submit(Json_Team_Generation, state, who="team1"),
except Exception as e: "team2": pool.submit(Json_Team_Generation, state, who="team2"),
logger.debug(f"[RENDER_THREAD] skip Team_Both_Stat: {e}") "scores": pool.submit(Scores_Quarter, state),
"referee": pool.submit(Referee, state),
"pbp": pool.submit(Play_By_Play, state),
}
try: # аккуратно собрать исключения, но не умереть целиком
Json_Team_Generation(state, who="team1") for name, fut in tasks.items():
except Exception as e: try:
logger.debug(f"[RENDER_THREAD] skip Json_Team_Generation team1: {e}") fut.result()
except Exception as e:
logger.debug(f"[RENDER_THREAD] skip {name}: {e}")
try: # остальное можно сделать синхронно, это быстро
Json_Team_Generation(state, who="team2") try:
except Exception as e: live_status_to_write = []
logger.debug(f"[RENDER_THREAD] skip Json_Team_Generation team2: {e}") rs = state.get("result", {})
if isinstance(rs, dict) and "live_status" in rs:
live_status_to_write = [rs["live_status"]]
atomic_write_json(live_status_to_write, "live_status")
except Exception as e:
logger.debug(f"[RENDER_THREAD] skip live_status write: {e}")
try: try:
Scores_Quarter(state) atomic_write_json(state.get("result", {}), out_name)
except Exception as e: except Exception as e:
logger.debug(f"[RENDER_THREAD] skip Scores_Quarter: {e}") logger.debug(f"[RENDER_THREAD] skip {out_name}.json write: {e}")
try: except Exception as ex:
Referee(state) logger.exception(f"[RENDER_THREAD] unexpected error: {ex}")
except Exception as e:
logger.debug(f"[RENDER_THREAD] skip Referee: {e}")
try: time.sleep(0.2)
Play_By_Play(state)
except Exception as e:
logger.debug(f"[RENDER_THREAD] skip Play_By_Play: {e}")
# записываем live_status и общий state/game.json, но тоже мягко
try:
live_status_to_write = []
rs = state.get("result", {})
if isinstance(rs, dict) and "live_status" in rs:
live_status_to_write = [rs["live_status"]]
atomic_write_json(live_status_to_write, "live_status")
except Exception as e:
logger.debug(f"[RENDER_THREAD] skip live_status write: {e}")
try:
atomic_write_json(state.get("result", {}), out_name)
except Exception as e:
logger.debug(f"[RENDER_THREAD] skip {out_name}.json write: {e}")
except Exception as ex:
# крайняя защита цикла — никогда не вываливаться из потока
logger.exception(f"[RENDER_THREAD] unexpected error: {ex}")
time.sleep(0.2)
logger.info("[RENDER_THREAD] stop render loop") logger.info("[RENDER_THREAD] stop render loop")