File size: 2,766 Bytes
5255936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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()