Skip to content

Commit 3223f74

Browse files
author
linomp
committed
cleanup for merge
1 parent d108ece commit 3223f74

File tree

6 files changed

+41
-32
lines changed

6 files changed

+41
-32
lines changed

mvp/client/ui/src/messaging/mqttFunctions.ts

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ export const getClient = async (
2323
{
2424
username: connectionDetails.username,
2525
password: connectionDetails.password,
26+
protocolVersion: 4, // MQTT 3.1.1
2627
}
2728
);
2829

mvp/client/ui/src/pages/HomePage.svelte

+21-16
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,27 @@
2020
import type { GameSessionDTO } from "src/api/generated";
2121
2222
const updateGameSession = async (newGameSessionDto: GameSessionDTO) => {
23+
// TODO: this is a workaround to prevent the game from updating the game session if it receives an outdated one
24+
// e.g. if an MQTT message arrives after the last POST request is resolved
25+
if (
26+
$gameSession &&
27+
($gameSession?.is_game_over ||
28+
(newGameSessionDto.current_step < $gameSession?.current_step ?? 0))
29+
) {
30+
return;
31+
}
32+
33+
gameOver.set(newGameSessionDto.is_game_over);
34+
gameOverReason.set(newGameSessionDto.game_over_reason ?? null);
35+
36+
if (newGameSessionDto.is_game_over) {
37+
if (import.meta.env.VITE_DEBUG) {
38+
console.log("Game over. Last known GameSessionDTO:", newGameSessionDto);
39+
}
40+
41+
$mqttClientUnsubscribe?.();
42+
}
43+
2344
gameSession.update(
2445
(
2546
previousGameSession: GameSessionWithTimeSeries | null,
@@ -36,20 +57,6 @@
3657
};
3758
},
3859
);
39-
checkForGameOver();
40-
};
41-
42-
const checkForGameOver = () => {
43-
if (isUndefinedOrNull($gameSession)) {
44-
return;
45-
}
46-
47-
gameOver.set($gameSession?.is_game_over ?? false);
48-
gameOverReason.set($gameSession?.game_over_reason ?? null);
49-
50-
if ($gameSession?.is_game_over) {
51-
$mqttClientUnsubscribe?.();
52-
}
5360
};
5461
</script>
5562

@@ -76,8 +83,6 @@
7683
display: flex;
7784
flex-direction: column;
7885
align-items: center;
79-
padding-left: 2em;
80-
padding-right: 2em;
8186
}
8287
8388
.title {

mvp/server/core/constants.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
GAME_TICK_INTERVAL = 0.03 # 30ms
55
IDLE_SESSION_TTL_SECONDS = 60 * 30 # 15 minutes
66
SESSION_CLEANUP_INTERVAL_SECONDS = 60 * 60 # 60 minutes
7-
TIMESTEPS_PER_MOVE = 24 # we conceptualize every player move as a full working day, or "8 hours"
7+
TIMESTEPS_PER_MOVE = 24 # "hours"
88
GAME_OVER_MESSAGE_MACHINE_BREAKDOWN = "Machine health has reached 0%"
99
GAME_OVER_MESSAGE_NO_MONEY = "Player ran out of money"
1010

mvp/server/core/game/GameSession.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,9 @@ async def advance_one_turn(self) -> list[MachineState]:
8383

8484
self.current_step += 1
8585
self.machine_state.update_parameters(self.current_step)
86+
8687
# Player earns money for the production at every timestep
8788
self.available_funds += math.ceil(REVENUE_PER_DAY / TIMESTEPS_PER_MOVE)
88-
self._log()
8989

9090
# Publish state every 2 steps (to reduce the load on the MQTT broker)
9191
if self.current_step % 2 == 0:
@@ -131,7 +131,3 @@ def purchase_prediction(self, prediction: str) -> bool:
131131
self.available_funds -= PREDICTION_MODEL_COST
132132
self.available_predictions[prediction] = True
133133
return True
134-
135-
def _log(self, multiple=5) -> None:
136-
if self.current_step % multiple == 0:
137-
print(f"{datetime.now()}: GameSession '{self.id}' - step: {self.current_step} - {self.machine_state}")

mvp/server/messaging/mqtt_client.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,12 @@ def __init__(self):
3232
if MQTT_USER is None:
3333
return
3434

35-
client = paho.Client(client_id="pdmgame_server", userdata=None, protocol=paho.MQTTv5,
36-
callback_api_version=CallbackAPIVersion.VERSION2)
35+
client = paho.Client(
36+
protocol=paho.MQTTv311,
37+
callback_api_version=CallbackAPIVersion.VERSION2,
38+
reconnect_on_failure=False,
39+
clean_session=True
40+
)
3741
client.on_connect = on_connect
3842

3943
client.tls_set(tls_version=mqtt.client.ssl.PROTOCOL_TLS)

mvp/server/routers/sessions.py

+11-8
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,18 @@ def get_session_dependency(session_id: str) -> GameSession:
3636
async def cleanup_inactive_sessions():
3737
print(f"{datetime.now()}: Cleaning up sessions...")
3838

39-
for session_id, session in list(sessions.items()):
40-
must_be_dropped = session.is_game_over or session.is_abandoned()
41-
42-
if session.is_abandoned():
43-
game_metrics.update_on_game_abandoned(len(sessions) - 1)
39+
sessions_to_drop = []
4440

45-
if must_be_dropped:
41+
for session_id, session in list(sessions.items()):
42+
is_abandoned = session.is_abandoned()
43+
if session.is_game_over or is_abandoned:
4644
print(f"{datetime.now()}: Session '{session_id}' will be dropped")
47-
sessions.pop(session_id)
45+
sessions_to_drop.append((session_id, is_abandoned))
46+
47+
for session_id, is_abandoned in sessions_to_drop:
48+
sessions.pop(session_id)
49+
if is_abandoned:
50+
game_metrics.update_on_game_abandoned(len(sessions))
4851

4952

5053
@router.on_event("shutdown")
@@ -68,7 +71,7 @@ def publishing_func(game_session: GameSession) -> None:
6871
session = GameSession.new_game_session(_id=new_session_id, _state_publish_function=publishing_func)
6972
sessions[new_session_id] = session
7073

71-
game_metrics.update_on_game_started(len(sessions))
74+
game_metrics.update_on_game_started(len(sessions))
7275

7376
return GameSessionDTO.from_session(sessions[new_session_id])
7477

0 commit comments

Comments
 (0)