chessai.ui.web

  1import base64
  2import errno
  3import http
  4import http.server
  5import io
  6import logging
  7import mimetypes
  8import os
  9import re
 10import socket
 11import threading
 12import time
 13import typing
 14import urllib.parse
 15import webbrowser
 16
 17import PIL.Image
 18import edq.util.dirent
 19import edq.util.json
 20
 21import chessai.core.gamestate
 22import chessai.core.ui
 23
 24THIS_DIR: str = os.path.join(os.path.dirname(os.path.realpath(__file__)))
 25STATIC_DIR: str = os.path.join(THIS_DIR, '..', 'resources', 'webui')
 26
 27START_PORT: int = 30000
 28END_PORT: int = 40000
 29
 30INITIAL_SLEEP_TIME_SEC: float = 0.05
 31SOCKET_SLEEP_TIME_SECS: float = 0.10
 32SERVER_WAIT_TIME_SECS: float = 0.25
 33REAP_TIME_SECS: float = 0.25
 34COMPLETE_WAIT_TIME_SECS: float = 0.15
 35
 36SERVER_POLL_INTERVAL_SECS: float = 0.1
 37
 38RequestHandlerResult: typing.TypeAlias = tuple[dict | str | bytes | None, int | None, dict | None] | None
 39
 40class HTTPHandler(http.server.BaseHTTPRequestHandler):
 41    """ Handle HTTP requests for the web UI. """
 42
 43    _lock: threading.Lock = threading.Lock()
 44    """ A lock to protect the data sent to the web page. """
 45
 46    _state: chessai.core.gamestate.GameState | None = None
 47    """ The current game state. """
 48
 49    _image_url: str | None = None
 50    """ The data URL for the current image. """
 51
 52    @classmethod
 53    def ui_setup(cls) -> None:
 54        """ Initialize this handler with information from the UI. """
 55
 56    @classmethod
 57    def set_data(cls, state: chessai.core.gamestate.GameState, image: PIL.Image.Image) -> None:
 58        """ Set the data passed back to the web page. """
 59
 60        buffer = io.BytesIO()
 61        image.save(buffer, format = 'png')
 62        data_64 = base64.b64encode(buffer.getvalue()).decode(edq.util.dirent.DEFAULT_ENCODING)
 63        data_url = f"data:image/png;base64,{data_64}"
 64
 65        with cls._lock:
 66            cls._state = state.copy()
 67            cls._image_url = data_url
 68
 69    @classmethod
 70    def get_data(cls) -> tuple[chessai.core.gamestate.GameState | None, str | None]:
 71        """ Get the data passed back to the web page. """
 72
 73        with cls._lock:
 74            return cls._state, cls._image_url
 75
 76    def log_message(self, *args: typing.Any) -> None:
 77        """
 78        Reduce the logging noise.
 79        """
 80
 81    def handle(self) -> None:
 82        """
 83        Override handle() to ignore dropped connections.
 84        """
 85
 86        try:
 87            http.server.BaseHTTPRequestHandler.handle(self)
 88        except BrokenPipeError:
 89            logging.info("Connection closed on the client side.")
 90
 91    def do_POST(self) -> None:  # pylint: disable=invalid-name
 92        """ Handle POST requests. """
 93
 94        self._handle_request(self._get_post_data)
 95
 96    def do_GET(self) -> None:  # pylint: disable=invalid-name
 97        """ Handle GET requests. """
 98
 99        self._handle_request(self._get_get_data)
100
101    def _handle_request(self, data_handler: typing.Callable) -> None:
102        logging.trace("Serving: '%s'.", self.path)  # type: ignore[attr-defined]  # pylint: disable=no-member
103
104        code: int = http.HTTPStatus.OK
105        headers: dict[str, typing.Any] = {}
106
107        result = None
108        try:
109            data = data_handler()
110            result = self._route(self.path, data)
111        except Exception as ex:
112            # An error occured during data handling (routing captures their own errors).
113            logging.debug("Error handling '%s'.", self.path, exc_info = ex)
114            result = (str(ex), http.HTTPStatus.BAD_REQUEST, None)
115
116        if (result is None):
117            # All handling was done internally, the response is complete.
118            return
119
120        # A standard response structure was returned, continue processing.
121        payload, response_code, response_headers = result
122
123        if (isinstance(payload, dict)):
124            payload = edq.util.json.dumps(payload)
125            headers['Content-Type'] = 'application/json'
126
127        if (isinstance(payload, str)):
128            payload = payload.encode(edq.util.dirent.DEFAULT_ENCODING)
129
130        if (payload is not None):
131            headers['Content-Length'] = len(payload)
132
133        if (response_headers is not None):
134            for key, value in response_headers.items():
135                headers[key] = value
136
137        if (response_code is not None):
138            code = response_code
139
140        self.send_response(code)
141
142        for (key, value) in headers.items():
143            self.send_header(key, value)
144        self.end_headers()
145
146        if (payload is not None):
147            self.wfile.write(payload)
148
149    def _route(self, path: str, params: dict[str, typing.Any]) -> RequestHandlerResult:
150        path = path.strip()
151
152        target = _handler_not_found
153        for (regex, handler_func) in ROUTES:
154            if (re.search(regex, path) is not None):
155                target = handler_func
156                break
157
158        try:
159            return target(self, path, params)
160        except Exception as ex:
161            logging.error("Error on path '%s', handler '%s'.", path, str(target), exc_info = ex)
162            return str(ex), http.HTTPStatus.INTERNAL_SERVER_ERROR, None
163
164    def _get_get_data(self) -> dict[str, typing.Any]:
165        path = self.path.strip().rstrip('/')
166        url = urllib.parse.urlparse(path)
167
168        raw_params = urllib.parse.parse_qs(url.query)
169        params: dict[str, typing.Any] = {}
170
171        for (key, values) in raw_params.items():
172            if ((len(values) == 0) or (values[0] == '')):
173                continue
174
175            if (len(values) == 1):
176                params[key] = values[0]
177            else:
178                params[key] = values
179
180        return params
181
182    def _get_post_data(self) -> dict[str, typing.Any]:
183        length = int(self.headers['Content-Length'])
184        payload = self.rfile.read(length).decode(edq.util.dirent.DEFAULT_ENCODING)
185
186        try:
187            request = edq.util.json.loads(payload)
188        except Exception as ex:
189            raise ValueError("Payload is not valid json.") from ex
190
191        return request  # type: ignore[no-any-return]
192
193class WebUI(chessai.core.ui.UI):
194    """
195    A UI that starts a web server and launches a brower window to serve a UI.
196    The web server will accept requests that contains user inputs,
197    and respond with the current game state and a visual representation of the game (a base64 encoded png).
198    """
199
200    def __init__(self,
201            **kwargs: typing.Any) -> None:
202        super().__init__(**kwargs)
203
204        self._port: int = -1
205        """
206        The port to start the web server on.
207        The first open port in [START_PORT, END_PORT] will be used.
208        """
209
210        self._startup_barrier: threading.Barrier = threading.Barrier(2)
211        """ Use a threading barrier to wait for the server thread to start. """
212
213        self._server_thread: threading.Thread | None = None
214        """ The thread the server will be run on. """
215
216        self._server: http.server.HTTPServer | None = None
217        """ The HTTP server. """
218
219    def game_start(self,
220            initial_state: chessai.core.gamestate.GameState,
221            **kwargs: typing.Any) -> None:
222        self._start_server()
223
224        super().game_start(initial_state)
225
226        self._launch_page(initial_state)
227
228    def game_complete(self,
229            final_state: chessai.core.gamestate.GameState,
230            termination_reason: chessai.core.types.TerminationReason,
231            ) -> None:
232        super().game_complete(final_state, termination_reason)
233
234        # Wait for the UI to make a final request.
235        time.sleep(COMPLETE_WAIT_TIME_SECS)
236
237        self._stop_server()
238
239    def draw(self,
240            state: chessai.core.gamestate.GameState,
241            termination_reason: chessai.core.types.TerminationReason | None = None,
242            **kwargs: typing.Any,
243            ) -> None:
244        image = self.draw_image(state)
245        HTTPHandler.set_data(state, image)
246
247    def _start_server(self) -> None:
248        """ Start the HTTP server on another thread. """
249
250        # Fetch the port.
251        self._port = _find_open_port()
252
253        # Setup the barrier to wait for the server thread to start.
254        self._startup_barrier.reset()
255
256        # Create, but don't start the server.
257        self._server = http.server.ThreadingHTTPServer(('', self._port), HTTPHandler)
258
259        # Setup the handler.
260        HTTPHandler.ui_setup()
261
262        self._server_thread = threading.Thread(target = _run_server, args = (self._server, self._startup_barrier))
263        self._server_thread.start()
264
265        # Wait for the server to startup.
266        self._startup_barrier.wait()
267        time.sleep(INITIAL_SLEEP_TIME_SEC)
268
269    def _stop_server(self) -> None:
270        """ Stop the HTTP server and thread. """
271
272        if ((self._server is None) or (self._server_thread is None)):
273            return
274
275        self._server.shutdown()
276        time.sleep(SERVER_WAIT_TIME_SECS)
277
278        if (self._server_thread.is_alive()):
279            self._server_thread.join(REAP_TIME_SECS)
280
281        self._server = None
282        self._server_thread = None
283
284    def _launch_page(self, initial_state: chessai.core.gamestate.GameState) -> None:
285        """ Open the browser window to the web UI page. """
286
287        image = self.draw_image(initial_state)
288        HTTPHandler.set_data(initial_state, image)
289
290        logging.info("Starting web UI on port %d.", self._port)
291        logging.info("If a browser window does not open, you may use the following link:")
292        logging.info("http://127.0.0.1:%d", self._port)
293
294        webbrowser.open(f"http://127.0.0.1:{self._port}/static/index.html")
295
296def _find_open_port() -> int:
297    """ Go through [START_PORT, END_PORT] looking for open ports. """
298
299    for port in range(START_PORT, END_PORT + 1):
300        try:
301            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
302            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
303            sock.bind(('127.0.0.1', port))
304
305            # Explicitly close the port and wait a short amount of time for the port to clear.
306            # This should not be required because of the socket option above,
307            # but the cost is small.
308            sock.close()
309            time.sleep(SOCKET_SLEEP_TIME_SECS)
310
311            return port
312        except socket.error as ex:
313            sock.close()
314
315            if (ex.errno == errno.EADDRINUSE):
316                continue
317
318            # Unknown error.
319            raise ex
320
321    raise ValueError(f"Could not find open port in [{START_PORT}, {END_PORT}].")
322
323def _run_server(server: http.server.HTTPServer, startup_barrier: threading.Barrier) -> None:
324    """ Run the http server on this curent thread. """
325
326    startup_barrier.wait()
327    server.serve_forever(poll_interval = SERVER_POLL_INTERVAL_SECS)
328    server.server_close()
329
330@typing.runtime_checkable
331class RequestHandler(typing.Protocol):
332    """ Functions that can be used as HTTP request handlers by HTTPHandler. """
333
334    def __call__(self, handler: HTTPHandler, path: str, params: dict) -> RequestHandlerResult:
335        ...
336
337def _handler_not_found(handler: HTTPHandler, path: str, params: dict) -> RequestHandlerResult:
338    """ Handle a 404. """
339
340    return (f"404 route not found: '{path}'.", http.HTTPStatus.NOT_FOUND, None)
341
342def _handler_redirect(target: str) -> RequestHandler:
343    """ Get a handler that redirects to the specific target. """
344
345    def handler_func(handler: HTTPHandler, path: str, params: dict) -> RequestHandlerResult:
346        return (None, http.HTTPStatus.MOVED_PERMANENTLY, {'Location': target})
347
348    return handler_func
349
350def _handler_static(handler: HTTPHandler, path: str, params: dict) -> RequestHandlerResult:
351    """ Get a static (bundled) file. """
352
353    # Note that the path is currently a URL path, and therefore separated with slashes.
354    parts = path.strip().lstrip('/').split('/')
355
356    # Remove the static prefix.
357    if (parts[0] == 'static'):
358        parts.pop(0)
359
360    static_path = os.path.join(STATIC_DIR, *parts)
361    logging.trace("Serving static path: '%s'.", static_path)  # type: ignore[attr-defined]  # pylint: disable=no-member
362
363    if (not os.path.isfile(static_path)):
364        return (f"404 static path not found '{path}'.", http.HTTPStatus.NOT_FOUND, None)
365
366    data = edq.util.dirent.read_file_bytes(static_path)
367
368    code = http.HTTPStatus.OK
369    headers = {}
370
371    mime_info = mimetypes.guess_type(path)
372    if (mime_info is not None):
373        headers['Content-Type'] = mime_info[0]
374
375    return data, code, headers
376
377def _handler_init(handler: HTTPHandler, path: str, params: dict) -> RequestHandlerResult:
378    """ Handle a request by the browser to initialize. """
379
380    data = {
381        'title': 'chessai',
382    }
383
384    return (data, None, None)
385
386def _handler_update(handler: HTTPHandler, path: str, params: dict) -> RequestHandlerResult:
387    """ Handle a request by the browser for more data. """
388
389    state, image_url = handler.get_data()
390    data = {
391        'state': state,
392        'image_url': image_url,
393    }
394
395    return (data, None, None)
396
397ROUTES: list[tuple[str, RequestHandler]] = [
398    (r'^/$', _handler_redirect('/static/index.html')),
399    (r'^/index.html$', _handler_redirect('/static/index.html')),
400    (r'^/static$', _handler_redirect('/static/index.html')),
401    (r'^/static/$', _handler_redirect('/static/index.html')),
402
403    (r'^/favicon.ico$', _handler_redirect('/static/favicon.ico')),
404
405    (r'^/static/', _handler_static),
406
407    (r'^/api/init$', _handler_init),
408    (r'^/api/update$', _handler_update),
409]
THIS_DIR: str = '/home/runner/work/chessai/chessai/chessai/ui'
STATIC_DIR: str = '/home/runner/work/chessai/chessai/chessai/ui/../resources/webui'
START_PORT: int = 30000
END_PORT: int = 40000
INITIAL_SLEEP_TIME_SEC: float = 0.05
SOCKET_SLEEP_TIME_SECS: float = 0.1
SERVER_WAIT_TIME_SECS: float = 0.25
REAP_TIME_SECS: float = 0.25
COMPLETE_WAIT_TIME_SECS: float = 0.15
SERVER_POLL_INTERVAL_SECS: float = 0.1
RequestHandlerResult: TypeAlias = tuple[dict | str | bytes | None, int | None, dict | None] | None
class HTTPHandler(http.server.BaseHTTPRequestHandler):
 41class HTTPHandler(http.server.BaseHTTPRequestHandler):
 42    """ Handle HTTP requests for the web UI. """
 43
 44    _lock: threading.Lock = threading.Lock()
 45    """ A lock to protect the data sent to the web page. """
 46
 47    _state: chessai.core.gamestate.GameState | None = None
 48    """ The current game state. """
 49
 50    _image_url: str | None = None
 51    """ The data URL for the current image. """
 52
 53    @classmethod
 54    def ui_setup(cls) -> None:
 55        """ Initialize this handler with information from the UI. """
 56
 57    @classmethod
 58    def set_data(cls, state: chessai.core.gamestate.GameState, image: PIL.Image.Image) -> None:
 59        """ Set the data passed back to the web page. """
 60
 61        buffer = io.BytesIO()
 62        image.save(buffer, format = 'png')
 63        data_64 = base64.b64encode(buffer.getvalue()).decode(edq.util.dirent.DEFAULT_ENCODING)
 64        data_url = f"data:image/png;base64,{data_64}"
 65
 66        with cls._lock:
 67            cls._state = state.copy()
 68            cls._image_url = data_url
 69
 70    @classmethod
 71    def get_data(cls) -> tuple[chessai.core.gamestate.GameState | None, str | None]:
 72        """ Get the data passed back to the web page. """
 73
 74        with cls._lock:
 75            return cls._state, cls._image_url
 76
 77    def log_message(self, *args: typing.Any) -> None:
 78        """
 79        Reduce the logging noise.
 80        """
 81
 82    def handle(self) -> None:
 83        """
 84        Override handle() to ignore dropped connections.
 85        """
 86
 87        try:
 88            http.server.BaseHTTPRequestHandler.handle(self)
 89        except BrokenPipeError:
 90            logging.info("Connection closed on the client side.")
 91
 92    def do_POST(self) -> None:  # pylint: disable=invalid-name
 93        """ Handle POST requests. """
 94
 95        self._handle_request(self._get_post_data)
 96
 97    def do_GET(self) -> None:  # pylint: disable=invalid-name
 98        """ Handle GET requests. """
 99
100        self._handle_request(self._get_get_data)
101
102    def _handle_request(self, data_handler: typing.Callable) -> None:
103        logging.trace("Serving: '%s'.", self.path)  # type: ignore[attr-defined]  # pylint: disable=no-member
104
105        code: int = http.HTTPStatus.OK
106        headers: dict[str, typing.Any] = {}
107
108        result = None
109        try:
110            data = data_handler()
111            result = self._route(self.path, data)
112        except Exception as ex:
113            # An error occured during data handling (routing captures their own errors).
114            logging.debug("Error handling '%s'.", self.path, exc_info = ex)
115            result = (str(ex), http.HTTPStatus.BAD_REQUEST, None)
116
117        if (result is None):
118            # All handling was done internally, the response is complete.
119            return
120
121        # A standard response structure was returned, continue processing.
122        payload, response_code, response_headers = result
123
124        if (isinstance(payload, dict)):
125            payload = edq.util.json.dumps(payload)
126            headers['Content-Type'] = 'application/json'
127
128        if (isinstance(payload, str)):
129            payload = payload.encode(edq.util.dirent.DEFAULT_ENCODING)
130
131        if (payload is not None):
132            headers['Content-Length'] = len(payload)
133
134        if (response_headers is not None):
135            for key, value in response_headers.items():
136                headers[key] = value
137
138        if (response_code is not None):
139            code = response_code
140
141        self.send_response(code)
142
143        for (key, value) in headers.items():
144            self.send_header(key, value)
145        self.end_headers()
146
147        if (payload is not None):
148            self.wfile.write(payload)
149
150    def _route(self, path: str, params: dict[str, typing.Any]) -> RequestHandlerResult:
151        path = path.strip()
152
153        target = _handler_not_found
154        for (regex, handler_func) in ROUTES:
155            if (re.search(regex, path) is not None):
156                target = handler_func
157                break
158
159        try:
160            return target(self, path, params)
161        except Exception as ex:
162            logging.error("Error on path '%s', handler '%s'.", path, str(target), exc_info = ex)
163            return str(ex), http.HTTPStatus.INTERNAL_SERVER_ERROR, None
164
165    def _get_get_data(self) -> dict[str, typing.Any]:
166        path = self.path.strip().rstrip('/')
167        url = urllib.parse.urlparse(path)
168
169        raw_params = urllib.parse.parse_qs(url.query)
170        params: dict[str, typing.Any] = {}
171
172        for (key, values) in raw_params.items():
173            if ((len(values) == 0) or (values[0] == '')):
174                continue
175
176            if (len(values) == 1):
177                params[key] = values[0]
178            else:
179                params[key] = values
180
181        return params
182
183    def _get_post_data(self) -> dict[str, typing.Any]:
184        length = int(self.headers['Content-Length'])
185        payload = self.rfile.read(length).decode(edq.util.dirent.DEFAULT_ENCODING)
186
187        try:
188            request = edq.util.json.loads(payload)
189        except Exception as ex:
190            raise ValueError("Payload is not valid json.") from ex
191
192        return request  # type: ignore[no-any-return]

Handle HTTP requests for the web UI.

@classmethod
def ui_setup(cls) -> None:
53    @classmethod
54    def ui_setup(cls) -> None:
55        """ Initialize this handler with information from the UI. """

Initialize this handler with information from the UI.

@classmethod
def set_data( cls, state: chessai.core.gamestate.GameState, image: PIL.Image.Image) -> None:
57    @classmethod
58    def set_data(cls, state: chessai.core.gamestate.GameState, image: PIL.Image.Image) -> None:
59        """ Set the data passed back to the web page. """
60
61        buffer = io.BytesIO()
62        image.save(buffer, format = 'png')
63        data_64 = base64.b64encode(buffer.getvalue()).decode(edq.util.dirent.DEFAULT_ENCODING)
64        data_url = f"data:image/png;base64,{data_64}"
65
66        with cls._lock:
67            cls._state = state.copy()
68            cls._image_url = data_url

Set the data passed back to the web page.

@classmethod
def get_data(cls) -> tuple[chessai.core.gamestate.GameState | None, str | None]:
70    @classmethod
71    def get_data(cls) -> tuple[chessai.core.gamestate.GameState | None, str | None]:
72        """ Get the data passed back to the web page. """
73
74        with cls._lock:
75            return cls._state, cls._image_url

Get the data passed back to the web page.

def log_message(self, *args: Any) -> None:
77    def log_message(self, *args: typing.Any) -> None:
78        """
79        Reduce the logging noise.
80        """

Reduce the logging noise.

def handle(self) -> None:
82    def handle(self) -> None:
83        """
84        Override handle() to ignore dropped connections.
85        """
86
87        try:
88            http.server.BaseHTTPRequestHandler.handle(self)
89        except BrokenPipeError:
90            logging.info("Connection closed on the client side.")

Override handle() to ignore dropped connections.

def do_POST(self) -> None:
92    def do_POST(self) -> None:  # pylint: disable=invalid-name
93        """ Handle POST requests. """
94
95        self._handle_request(self._get_post_data)

Handle POST requests.

def do_GET(self) -> None:
 97    def do_GET(self) -> None:  # pylint: disable=invalid-name
 98        """ Handle GET requests. """
 99
100        self._handle_request(self._get_get_data)

Handle GET requests.

class WebUI(chessai.core.ui.UI):
194class WebUI(chessai.core.ui.UI):
195    """
196    A UI that starts a web server and launches a brower window to serve a UI.
197    The web server will accept requests that contains user inputs,
198    and respond with the current game state and a visual representation of the game (a base64 encoded png).
199    """
200
201    def __init__(self,
202            **kwargs: typing.Any) -> None:
203        super().__init__(**kwargs)
204
205        self._port: int = -1
206        """
207        The port to start the web server on.
208        The first open port in [START_PORT, END_PORT] will be used.
209        """
210
211        self._startup_barrier: threading.Barrier = threading.Barrier(2)
212        """ Use a threading barrier to wait for the server thread to start. """
213
214        self._server_thread: threading.Thread | None = None
215        """ The thread the server will be run on. """
216
217        self._server: http.server.HTTPServer | None = None
218        """ The HTTP server. """
219
220    def game_start(self,
221            initial_state: chessai.core.gamestate.GameState,
222            **kwargs: typing.Any) -> None:
223        self._start_server()
224
225        super().game_start(initial_state)
226
227        self._launch_page(initial_state)
228
229    def game_complete(self,
230            final_state: chessai.core.gamestate.GameState,
231            termination_reason: chessai.core.types.TerminationReason,
232            ) -> None:
233        super().game_complete(final_state, termination_reason)
234
235        # Wait for the UI to make a final request.
236        time.sleep(COMPLETE_WAIT_TIME_SECS)
237
238        self._stop_server()
239
240    def draw(self,
241            state: chessai.core.gamestate.GameState,
242            termination_reason: chessai.core.types.TerminationReason | None = None,
243            **kwargs: typing.Any,
244            ) -> None:
245        image = self.draw_image(state)
246        HTTPHandler.set_data(state, image)
247
248    def _start_server(self) -> None:
249        """ Start the HTTP server on another thread. """
250
251        # Fetch the port.
252        self._port = _find_open_port()
253
254        # Setup the barrier to wait for the server thread to start.
255        self._startup_barrier.reset()
256
257        # Create, but don't start the server.
258        self._server = http.server.ThreadingHTTPServer(('', self._port), HTTPHandler)
259
260        # Setup the handler.
261        HTTPHandler.ui_setup()
262
263        self._server_thread = threading.Thread(target = _run_server, args = (self._server, self._startup_barrier))
264        self._server_thread.start()
265
266        # Wait for the server to startup.
267        self._startup_barrier.wait()
268        time.sleep(INITIAL_SLEEP_TIME_SEC)
269
270    def _stop_server(self) -> None:
271        """ Stop the HTTP server and thread. """
272
273        if ((self._server is None) or (self._server_thread is None)):
274            return
275
276        self._server.shutdown()
277        time.sleep(SERVER_WAIT_TIME_SECS)
278
279        if (self._server_thread.is_alive()):
280            self._server_thread.join(REAP_TIME_SECS)
281
282        self._server = None
283        self._server_thread = None
284
285    def _launch_page(self, initial_state: chessai.core.gamestate.GameState) -> None:
286        """ Open the browser window to the web UI page. """
287
288        image = self.draw_image(initial_state)
289        HTTPHandler.set_data(initial_state, image)
290
291        logging.info("Starting web UI on port %d.", self._port)
292        logging.info("If a browser window does not open, you may use the following link:")
293        logging.info("http://127.0.0.1:%d", self._port)
294
295        webbrowser.open(f"http://127.0.0.1:{self._port}/static/index.html")

A UI that starts a web server and launches a brower window to serve a UI. The web server will accept requests that contains user inputs, and respond with the current game state and a visual representation of the game (a base64 encoded png).

WebUI(**kwargs: Any)
201    def __init__(self,
202            **kwargs: typing.Any) -> None:
203        super().__init__(**kwargs)
204
205        self._port: int = -1
206        """
207        The port to start the web server on.
208        The first open port in [START_PORT, END_PORT] will be used.
209        """
210
211        self._startup_barrier: threading.Barrier = threading.Barrier(2)
212        """ Use a threading barrier to wait for the server thread to start. """
213
214        self._server_thread: threading.Thread | None = None
215        """ The thread the server will be run on. """
216
217        self._server: http.server.HTTPServer | None = None
218        """ The HTTP server. """
def game_start( self, initial_state: chessai.core.gamestate.GameState, **kwargs: Any) -> None:
220    def game_start(self,
221            initial_state: chessai.core.gamestate.GameState,
222            **kwargs: typing.Any) -> None:
223        self._start_server()
224
225        super().game_start(initial_state)
226
227        self._launch_page(initial_state)

Initialize the UI with the game's initial state.

def game_complete( self, final_state: chessai.core.gamestate.GameState, termination_reason: chessai.core.types.TerminationReason) -> None:
229    def game_complete(self,
230            final_state: chessai.core.gamestate.GameState,
231            termination_reason: chessai.core.types.TerminationReason,
232            ) -> None:
233        super().game_complete(final_state, termination_reason)
234
235        # Wait for the UI to make a final request.
236        time.sleep(COMPLETE_WAIT_TIME_SECS)
237
238        self._stop_server()

Update the UI with the game's final state.

def draw( self, state: chessai.core.gamestate.GameState, termination_reason: chessai.core.types.TerminationReason | None = None, **kwargs: Any) -> None:
240    def draw(self,
241            state: chessai.core.gamestate.GameState,
242            termination_reason: chessai.core.types.TerminationReason | None = None,
243            **kwargs: typing.Any,
244            ) -> None:
245        image = self.draw_image(state)
246        HTTPHandler.set_data(state, image)

Visualize the state of the game to the UI. This is the typically the main override point for children. Note that how this method visualizes the game completely unrelated to how the draw_image() method works. draw() will render to whatever the specific UI for the child class is, while draw_image() specifically creates an image which will be used for animations. If the child UI is also image-based than it can leverage draw_image(), but there is no requirement to do that.

@typing.runtime_checkable
class RequestHandler(typing.Protocol):
331@typing.runtime_checkable
332class RequestHandler(typing.Protocol):
333    """ Functions that can be used as HTTP request handlers by HTTPHandler. """
334
335    def __call__(self, handler: HTTPHandler, path: str, params: dict) -> RequestHandlerResult:
336        ...

Functions that can be used as HTTP request handlers by HTTPHandler.

RequestHandler(*args, **kwargs)
1953def _no_init_or_replace_init(self, *args, **kwargs):
1954    cls = type(self)
1955
1956    if cls._is_protocol:
1957        raise TypeError('Protocols cannot be instantiated')
1958
1959    # Already using a custom `__init__`. No need to calculate correct
1960    # `__init__` to call. This can lead to RecursionError. See bpo-45121.
1961    if cls.__init__ is not _no_init_or_replace_init:
1962        return
1963
1964    # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`.
1965    # The first instantiation of the subclass will call `_no_init_or_replace_init` which
1966    # searches for a proper new `__init__` in the MRO. The new `__init__`
1967    # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent
1968    # instantiation of the protocol subclass will thus use the new
1969    # `__init__` and no longer call `_no_init_or_replace_init`.
1970    for base in cls.__mro__:
1971        init = base.__dict__.get('__init__', _no_init_or_replace_init)
1972        if init is not _no_init_or_replace_init:
1973            cls.__init__ = init
1974            break
1975    else:
1976        # should not happen
1977        cls.__init__ = object.__init__
1978
1979    cls.__init__(self, *args, **kwargs)
ROUTES: list[tuple[str, RequestHandler]] = [('^/$', <function _handler_redirect.<locals>.handler_func>), ('^/index.html$', <function _handler_redirect.<locals>.handler_func>), ('^/static$', <function _handler_redirect.<locals>.handler_func>), ('^/static/$', <function _handler_redirect.<locals>.handler_func>), ('^/favicon.ico$', <function _handler_redirect.<locals>.handler_func>), ('^/static/', <function _handler_static>), ('^/api/init$', <function _handler_init>), ('^/api/update$', <function _handler_update>)]