Debian Codegraph @

example/tutorial/step3/app.py

raw
1 #!/usr/bin/env python
2
3 import asyncio
4 import http
5 import json
6 import os
7 import secrets
8 import signal
9
10 from websockets.asyncio.server import broadcast, serve
11
12 from connect4 import PLAYER1, PLAYER2, Connect4
13
14
15 JOIN = {}
16
17 WATCH = {}
18
19
20 async def error(websocket, message):
21 """
22 Send an error message.
23
24 """
25 event = {
26 "type": "error",
27 "message": message,
28 }
29 await websocket.send(json.dumps(event))
30
31
32 async def replay(websocket, game):
33 """
34 Send previous moves.
35
36 """
37 # Make a copy to avoid an exception if game.moves changes while iteration
38 # is in progress. If a move is played while replay is running, moves will
39 # be sent out of order but each move will be sent once and eventually the
40 # UI will be consistent.
41 for player, column, row in game.moves.copy():
42 event = {
43 "type": "play",
44 "player": player,
45 "column": column,
46 "row": row,
47 }
48 await websocket.send(json.dumps(event))
49
50
51 async def play(websocket, game, player, connected):
52 """
53 Receive and process moves from a player.
54
55 """
56 async for message in websocket:
57 # Parse a "play" event from the UI.
58 event = json.loads(message)
59 assert event["type"] == "play"
60 column = event["column"]
61
62 try:
63 # Play the move.
64 row = game.play(player, column)
65 except ValueError as exc:
66 # Send an "error" event if the move was illegal.
67 await error(websocket, str(exc))
68 continue
69
70 # Send a "play" event to update the UI.
71 event = {
72 "type": "play",
73 "player": player,
74 "column": column,
75 "row": row,
76 }
77 broadcast(connected, json.dumps(event))
78
79 # If move is winning, send a "win" event.
80 if game.winner is not None:
81 event = {
82 "type": "win",
83 "player": game.winner,
84 }
85 broadcast(connected, json.dumps(event))
86
87
88 async def start(websocket):
89 """
90 Handle a connection from the first player: start a new game.
91
92 """
93 # Initialize a Connect Four game, the set of WebSocket connections
94 # receiving moves from this game, and secret access tokens.
95 game = Connect4()
96 connected = {websocket}
97
98 join_key = secrets.token_urlsafe(12)
99 JOIN[join_key] = game, connected
100
101 watch_key = secrets.token_urlsafe(12)
102 WATCH[watch_key] = game, connected
103
104 try:
105 # Send the secret access tokens to the browser of the first player,
106 # where they'll be used for building "join" and "watch" links.
107 event = {
108 "type": "init",
109 "join": join_key,
110 "watch": watch_key,
111 }
112 await websocket.send(json.dumps(event))
113 # Receive and process moves from the first player.
114 await play(websocket, game, PLAYER1, connected)
115 finally:
116 del JOIN[join_key]
117 del WATCH[watch_key]
118
119
120 async def join(websocket, join_key):
121 """
122 Handle a connection from the second player: join an existing game.
123
124 """
125 # Find the Connect Four game.
126 try:
127 game, connected = JOIN[join_key]
128 except KeyError:
129 await error(websocket, "Game not found.")
130 return
131
132 # Register to receive moves from this game.
133 connected.add(websocket)
134 try:
135 # Send the first move, in case the first player already played it.
136 await replay(websocket, game)
137 # Receive and process moves from the second player.
138 await play(websocket, game, PLAYER2, connected)
139 finally:
140 connected.remove(websocket)
141
142
143 async def watch(websocket, watch_key):
144 """
145 Handle a connection from a spectator: watch an existing game.
146
147 """
148 # Find the Connect Four game.
149 try:
150 game, connected = WATCH[watch_key]
151 except KeyError:
152 await error(websocket, "Game not found.")
153 return
154
155 # Register to receive moves from this game.
156 connected.add(websocket)
157 try:
158 # Send previous moves, in case the game already started.
159 await replay(websocket, game)
160 # Keep the connection open, but don't receive any messages.
161 await websocket.wait_closed()
162 finally:
163 connected.remove(websocket)
164
165
166 async def handler(websocket):
167 """
168 Handle a connection and dispatch it according to who is connecting.
169
170 """
171 # Receive and parse the "init" event from the UI.
172 message = await websocket.recv()
173 event = json.loads(message)
174 assert event["type"] == "init"
175
176 if "join" in event:
177 # Second player joins an existing game.
178 await join(websocket, event["join"])
179 elif "watch" in event:
180 # Spectator watches an existing game.
181 await watch(websocket, event["watch"])
182 else:
183 # First player starts a new game.
184 await start(websocket)
185
186
187 def health_check(connection, request):
188 if request.path == "/healthz":
189 return connection.respond(http.HTTPStatus.OK, "OK\n")
190
191
192 async def main():
193 port = int(os.environ.get("PORT", "8001"))
194 async with serve(handler, "", port, process_request=health_check) as server:
195 loop = asyncio.get_running_loop()
196 loop.add_signal_handler(signal.SIGTERM, server.close)
197 await server.wait_closed()
198
199
200 if __name__ == "__main__":
201 asyncio.run(main())