добавленны обработки 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,56 +677,38 @@ 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")
with ThreadPoolExecutor(max_workers=6) as pool:
while not stop_event.is_set(): while not stop_event.is_set():
try: try:
try: try:
state = build_render_state() state = build_render_state()
except Exception as build_err: except Exception as build_err:
# до тех пор, пока api_game не готов или битый — просто ждём logger.debug(f"[RENDER_THREAD] build_render_state not ready: {build_err}")
logger.debug(
f"[RENDER_THREAD] build_render_state not ready: {build_err}"
)
time.sleep(0.2) time.sleep(0.2)
continue 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),
}
# аккуратно собрать исключения, но не умереть целиком
for name, fut in tasks.items():
try: try:
Json_Team_Generation(state, who="team1") fut.result()
except Exception as e: except Exception as e:
logger.debug(f"[RENDER_THREAD] skip Json_Team_Generation team1: {e}") logger.debug(f"[RENDER_THREAD] skip {name}: {e}")
try: # остальное можно сделать синхронно, это быстро
Json_Team_Generation(state, who="team2")
except Exception as e:
logger.debug(f"[RENDER_THREAD] skip Json_Team_Generation team2: {e}")
try:
Scores_Quarter(state)
except Exception as e:
logger.debug(f"[RENDER_THREAD] skip Scores_Quarter: {e}")
try:
Referee(state)
except Exception as e:
logger.debug(f"[RENDER_THREAD] skip Referee: {e}")
try:
Play_By_Play(state)
except Exception as e:
logger.debug(f"[RENDER_THREAD] skip Play_By_Play: {e}")
# записываем live_status и общий state/game.json, но тоже мягко
try: try:
live_status_to_write = [] live_status_to_write = []
rs = state.get("result", {}) rs = state.get("result", {})
if isinstance(rs, dict) and "live_status" in rs: if isinstance(rs, dict) and "live_status" in rs:
live_status_to_write = [rs["live_status"]] live_status_to_write = [rs["live_status"]]
atomic_write_json(live_status_to_write, "live_status") atomic_write_json(live_status_to_write, "live_status")
except Exception as e: except Exception as e:
logger.debug(f"[RENDER_THREAD] skip live_status write: {e}") logger.debug(f"[RENDER_THREAD] skip live_status write: {e}")
@@ -737,7 +719,6 @@ def render_loop(stop_event: threading.Event, out_name: str = "game") -> None:
logger.debug(f"[RENDER_THREAD] skip {out_name}.json write: {e}") logger.debug(f"[RENDER_THREAD] skip {out_name}.json write: {e}")
except Exception as ex: except Exception as ex:
# крайняя защита цикла — никогда не вываливаться из потока
logger.exception(f"[RENDER_THREAD] unexpected error: {ex}") logger.exception(f"[RENDER_THREAD] unexpected error: {ex}")
time.sleep(0.2) time.sleep(0.2)