import asyncio from fastapi import FastAPI, WebSocket, WebSocketDisconnect import subprocess import logging # Configure basic logging logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") logger = logging.getLogger(__name__) app = FastAPI() STOCKFISH_PATH = "/usr/local/bin/stockfish" @app.get("/") def read_root(): return {"status": "Stockfish 18 Cloud API is running"} @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() client_ip = websocket.client.host logger.info(f"WebSocket connection OPENED from {client_ip}") try: process = subprocess.Popen( [STOCKFISH_PATH], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1 # Line-buffered ) logger.info(f"Stockfish process started with PID: {process.pid}") except Exception as e: logger.error(f"Error starting engine: {e}") await websocket.send_text(f"Error starting engine: {e}") await websocket.close() return async def read_from_stockfish(): loop = asyncio.get_event_loop() try: while True: line = await loop.run_in_executor(None, process.stdout.readline) if not line: break line_str = line.strip() # Log only important lines or every line if debugging heavily. # logger.debug(f"[Engine -> WS]: {line_str}") await websocket.send_text(line_str) except Exception as e: logger.error(f"Error reading from stockfish: {e}") task = asyncio.create_task(read_from_stockfish()) try: while True: data = await websocket.receive_text() # logger.info(f"[WS -> Engine]: {data}") # Uncomment to see every command sent to engine if data.startswith("position"): logger.info(f"📍 Received Position FEN -> Ready for analysis") elif data.startswith("go"): logger.info(f"🚀 Started Engine Search: {data}") elif data.startswith("stop"): logger.info(f"🛑 Received Stop Command -> Aborting search") if process.poll() is None: process.stdin.write(data + "\n") process.stdin.flush() except WebSocketDisconnect: logger.info(f"WebSocket connection CLOSED by client {client_ip}") finally: task.cancel() if process.poll() is None: logger.info(f"Terminating Stockfish process {process.pid}") process.terminate() process.wait()