-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathprotocol.py
90 lines (70 loc) · 3.1 KB
/
protocol.py
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
79
80
81
82
83
84
85
86
87
88
89
90
from __future__ import annotations
import asyncio
import sys
from contextlib import suppress
from aiohttp.client_ws import ClientWebSocketResponse
from loguru import logger
# pyre-fixme[21]
from s2clientprotocol import sc2api_pb2 as sc_pb
from sc2.data import Status
class ProtocolError(Exception):
@property
def is_game_over_error(self) -> bool:
return self.args[0] in ["['Game has already ended']", "['Not supported if game has already ended']"]
class ConnectionAlreadyClosedError(ProtocolError):
pass
class Protocol:
def __init__(self, ws: ClientWebSocketResponse) -> None:
"""
A class for communicating with an SCII application.
:param ws: the websocket (type: aiohttp.ClientWebSocketResponse) used to communicate with a specific SCII app
"""
assert ws
self._ws: ClientWebSocketResponse = ws
# pyre-fixme[11]
self._status: Status | None = None
async def __request(self, request):
logger.debug(f"Sending request: {request !r}")
try:
await self._ws.send_bytes(request.SerializeToString())
except TypeError as exc:
logger.exception("Cannot send: Connection already closed.")
raise ConnectionAlreadyClosedError("Connection already closed.") from exc
logger.debug("Request sent")
response = sc_pb.Response()
try:
response_bytes = await self._ws.receive_bytes()
except TypeError as exc:
if self._status == Status.ended:
logger.info("Cannot receive: Game has already ended.")
raise ConnectionAlreadyClosedError("Game has already ended") from exc
logger.error("Cannot receive: Connection already closed.")
raise ConnectionAlreadyClosedError("Connection already closed.") from exc
except asyncio.CancelledError:
# If request is sent, the response must be received before reraising cancel
try:
await self._ws.receive_bytes()
except asyncio.CancelledError:
logger.critical("Requests must not be cancelled multiple times")
sys.exit(2)
raise
response.ParseFromString(response_bytes)
logger.debug("Response received")
return response
async def _execute(self, **kwargs):
assert len(kwargs) == 1, "Only one request allowed by the API"
response = await self.__request(sc_pb.Request(**kwargs))
new_status = Status(response.status)
if new_status != self._status:
logger.info(f"Client status changed to {new_status} (was {self._status})")
self._status = new_status
if response.error:
logger.debug(f"Response contained an error: {response.error}")
raise ProtocolError(f"{response.error}")
return response
async def ping(self):
result = await self._execute(ping=sc_pb.RequestPing())
return result
async def quit(self) -> None:
with suppress(ConnectionAlreadyClosedError, ConnectionResetError):
await self._execute(quit=sc_pb.RequestQuit())