import datetime import signal import threading import time _last_seen: dict[int, float] = {} _last_seen_lock = threading.Lock() _session_starts: dict[int, float] = {} _session_starts_lock = threading.Lock() def record_heartbeat(pid: int) -> None: with _last_seen_lock: _last_seen[pid] = time.monotonic() def record_session_start(pid: int) -> None: with _session_starts_lock: _session_starts[pid] = time.monotonic() def flush_session_time(pid: int) -> None: with _session_starts_lock: start = _session_starts.pop(pid, None) if start is None: return elapsed = time.monotonic() - start if elapsed < 5: return try: from core.state import db db.add_playtime(pid, int(elapsed)) except Exception as e: print(f"[Playtime] Failed to flush pid={pid}: {e}") def start_presence_watchdog(): from core.state import ws_registry, session_mgr from core.ws_helpers import push_presence _TIMEOUT_SECS = 90 _CHECK_INTERVAL = 20 def _run(): while True: time.sleep(_CHECK_INTERVAL) try: now = time.monotonic() for pid in ws_registry.connected_ids(): with _last_seen_lock: last = _last_seen.get(pid) if last is None: _last_seen[pid] = now continue if now - last > _TIMEOUT_SECS: print(f"[PresenceWatchdog] Player {pid} timed out ({now - last:.0f}s no heartbeat) — closing") flush_session_time(pid) ws_registry.close_and_unregister(pid) session_mgr.leave_session(pid) push_presence(pid, None, online=False) try: from routes.sessions import session_gift_reset session_gift_reset(pid) except Exception: pass with _last_seen_lock: _last_seen.pop(pid, None) with _last_seen_lock: gone = [p for p in list(_last_seen) if not ws_registry.is_connected(p)] for p in gone: _last_seen.pop(p, None) except Exception as e: print(f"[PresenceWatchdog] Error: {e}") threading.Thread(target=_run, daemon=True, name="presence-watchdog").start() def start_ban_enforcer(): from core.state import db, ws_registry, session_mgr from core.ws_helpers import push_presence def _run(): while True: time.sleep(5) try: for pid in ws_registry.connected_ids(): if db.is_banned(pid): print(f"[BanEnforcer] Closing banned player {pid}") flush_session_time(pid) ws_registry.send(pid, {"Id": 20, "Msg": {}}) ws_registry.close_and_unregister(pid) session_mgr.leave_session(pid) push_presence(pid, None, online=False) except Exception as e: print(f"[BanEnforcer] Error: {e}") threading.Thread(target=_run, daemon=True, name="ban-enforcer").start() def start_player_count_recorder(): from core.state import db, ws_registry, session_mgr def _run(): while True: time.sleep(300) try: online = len(ws_registry.connected_ids()) sessions = len(session_mgr.all_public_sessions()) db.record_player_count(online, sessions) try: from core.discord import check_concurrent_milestone check_concurrent_milestone(online) except Exception: pass except Exception as e: print(f"[CountRecorder] Error: {e}") threading.Thread(target=_run, daemon=True, name="count-recorder").start() def start_quest_gift_daemon(): from core.state import session_mgr, db _QUEST_GUIDS = { "91e16e35-f48f-4700-ab8a-a1b79e50e51b", "949fa41f-4347-45c0-b7ac-489129174045", "7e01cfe0-820a-406f-b1b3-0a5bf575235c", "acc06e66-c2d0-4361-b0cd-46246a4c455c", } _THRESHOLD = 90 _CHECK_INTERVAL = 30 _game_started: dict[tuple[int, int], float] = {} _last_gift_time: dict[int, float] = {} _COOLDOWN = 300 def _run(): while True: time.sleep(_CHECK_INTERVAL) try: now = time.monotonic() active: set[tuple[int, int]] = set() for session in session_mgr.all_sessions(): guid = session.activity_level_id is_quest = guid in _QUEST_GUIDS is_custom = session.special_gamemode != 0 if not (is_quest or is_custom): continue for pid in session.players: key = (pid, session.session_id) active.add(key) if session.game_in_progress and key not in _game_started: _game_started[key] = now if key not in _game_started: continue elapsed = now - _game_started[key] if elapsed < _THRESHOLD: continue if now - _last_gift_time.get(pid, 0) < _COOLDOWN: continue from core.gift_dispatch import dispatch_gift gift = dispatch_gift(pid, guid, gift_context=2, session_id=session.session_id) if gift is None: continue _last_gift_time[pid] = now print(f"[QuestGiftDaemon] Gift pid={pid} session={session.session_id} guid={guid} id={gift.get('Id')}") try: from core.ws_helpers import push_gift push_gift(pid, gift) except Exception: pass stale = [k for k in _game_started if k not in active] for k in stale: _game_started.pop(k, None) except Exception as e: print(f"[QuestGiftDaemon] Error: {e}") threading.Thread(target=_run, daemon=True, name="quest-gift-daemon").start() def register_graceful_shutdown(): from core.state import db, ws_registry def _handler(signum, frame): print("[Shutdown] SIGTERM received — notifying connected players...") try: pids = list(ws_registry.connected_ids()) for _pid in pids: flush_session_time(_pid) _SYSTEM_ID = 23 dm_text = ( "KittyRec is rebooting." "You will be kicked to your dorm room shortly. " "Please reconnect in a few moments!" ) kick_msg = { "Id": 22, "Msg": { "ReportCategory": -1, "Duration": 0, "GameSessionId": 0, "Message": "KittyRec is restarting. Reconnect in a few moments!", }, } for pid in pids: try: msg_id = db.send_message(_SYSTEM_ID, pid, 30, dm_text) ws_registry.send(pid, {"Id": 2, "Msg": { "Id": msg_id, "FromPlayerId": _SYSTEM_ID, "SentTime": datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.000Z"), "Type": 30, "Data": dm_text, "RoomId": None, "PlayerEventId": None, }}) except Exception: pass print(f"[Shutdown] Sent DM to {len(pids)} player(s). Kicking in 3s...") try: from core.discord import send_admin as _da _da( title="Server Shutting Down", color=0xE67E22, fields=[{"name": "Players Online at Shutdown", "value": str(len(pids)), "inline": True}, {"name": "Reason", "value": "SIGTERM received", "inline": True}], ) except Exception: pass time.sleep(3) for pid in pids: try: ws_registry.send(pid, {"Id": "ModerationUpdateRequired", "Msg": {}}) ws_registry.send(pid, kick_msg) except Exception: pass time.sleep(1) except Exception as e: print(f"[Shutdown] Error during graceful shutdown: {e}") finally: print("[Shutdown] Exiting.") raise SystemExit(0) signal.signal(signal.SIGTERM, _handler)