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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#![allow(missing_docs)]

use super::online::{
    MatchmakerConnectionState, OnlineMatchmakerRequest, OnlineMatchmakerResponse,
    READ_TO_END_BYTE_COUNT,
};
use crate::{
    networking::{socket::establish_peer_connections, NetworkMatchSocket},
    prelude::*,
    utils::BiChannelServer,
};
use bones_matchmaker_proto::{GameID, LobbyId, LobbyInfo, MatchmakerRequest, MatchmakerResponse};
use std::sync::Arc;
use tracing::info;

pub(crate) async fn resolve_list_lobbies(
    user_channel: &BiChannelServer<OnlineMatchmakerRequest, OnlineMatchmakerResponse>,
    matchmaker_connection_state: &mut MatchmakerConnectionState,
    game_id: GameID,
) -> anyhow::Result<()> {
    let conn = matchmaker_connection_state.acquire_connection().await?;
    let (mut send, mut recv) = conn.open_bi().await?;

    let message = MatchmakerRequest::ListLobbies(game_id);
    let message = postcard::to_allocvec(&message)?;
    send.write_all(&message).await?;
    send.finish()?;
    send.stopped().await?;

    let response = recv.read_to_end(5 * 1024).await?;
    let message: MatchmakerResponse = postcard::from_bytes(&response)?;

    match message {
        MatchmakerResponse::LobbiesList(lobbies) => {
            user_channel.try_send(OnlineMatchmakerResponse::LobbiesList(lobbies))?;
        }
        other => anyhow::bail!("Unexpected message from matchmaker: {other:?}"),
    }

    Ok(())
}

pub(crate) async fn resolve_create_lobby(
    user_channel: &BiChannelServer<OnlineMatchmakerRequest, OnlineMatchmakerResponse>,
    matchmaker_connection_state: &mut MatchmakerConnectionState,
    lobby_info: LobbyInfo,
) -> anyhow::Result<()> {
    let conn = matchmaker_connection_state.acquire_connection().await?;
    let (mut send, mut recv) = conn.open_bi().await?;

    let message = MatchmakerRequest::CreateLobby(lobby_info);
    let message = postcard::to_allocvec(&message)?;
    send.write_all(&message).await?;
    send.finish()?;
    send.stopped().await?;

    let response = recv.read_to_end(READ_TO_END_BYTE_COUNT).await?;
    let message: MatchmakerResponse = postcard::from_bytes(&response)?;

    match message {
        MatchmakerResponse::LobbyCreated(lobby_id) => {
            user_channel.try_send(OnlineMatchmakerResponse::LobbyCreated(lobby_id))?;
        }
        MatchmakerResponse::Error(err) => {
            user_channel.try_send(OnlineMatchmakerResponse::Error(err))?;
        }
        other => anyhow::bail!("Unexpected message from matchmaker: {other:?}"),
    }

    Ok(())
}

pub(crate) async fn resolve_join_lobby(
    user_channel: &BiChannelServer<OnlineMatchmakerRequest, OnlineMatchmakerResponse>,
    matchmaker_connection_state: &mut MatchmakerConnectionState,
    game_id: GameID,
    lobby_id: LobbyId,
    password: Option<String>,
) -> anyhow::Result<()> {
    let conn = matchmaker_connection_state.acquire_connection().await?;
    let (mut send, mut recv) = conn.open_bi().await?;

    let message = MatchmakerRequest::JoinLobby(game_id, lobby_id.clone(), password);
    let message = postcard::to_allocvec(&message)?;
    send.write_all(&message).await?;
    send.finish()?;
    send.stopped().await?;

    let response = recv.read_to_end(READ_TO_END_BYTE_COUNT).await?;
    let message: MatchmakerResponse = postcard::from_bytes(&response)?;

    match message {
        MatchmakerResponse::LobbyJoined(joined_lobby_id) => {
            user_channel.try_send(OnlineMatchmakerResponse::LobbyJoined {
                lobby_id: joined_lobby_id,
                player_count: 0, // We don't have this information yet
            })?;

            // Wait for further messages (updates or game start)
            while let Ok(recv) = conn.accept_uni().await {
                let mut recv = recv;
                let message = recv.read_to_end(5 * 1024).await?;
                let message: MatchmakerResponse = postcard::from_bytes(&message)?;

                match message {
                    MatchmakerResponse::LobbyUpdate { player_count } => {
                        info!("Online lobby updated player count: {player_count}");
                        user_channel
                            .try_send(OnlineMatchmakerResponse::LobbyUpdate { player_count })?;
                    }
                    MatchmakerResponse::Success {
                        random_seed,
                        player_idx,
                        player_count,
                        player_ids,
                    } => {
                        let peer_connections =
                            establish_peer_connections(player_idx, player_count, player_ids, None)
                                .await?;

                        let socket = super::socket::Socket::new(player_idx, peer_connections);

                        user_channel.try_send(OnlineMatchmakerResponse::GameStarting {
                            socket: NetworkMatchSocket(Arc::new(socket)),
                            player_idx: player_idx as _,
                            player_count: player_count as _,
                            random_seed,
                        })?;
                        break;
                    }
                    MatchmakerResponse::Error(err) => {
                        user_channel.try_send(OnlineMatchmakerResponse::Error(err))?;
                        break;
                    }
                    other => anyhow::bail!("Unexpected message from matchmaker: {other:?}"),
                }
            }
        }
        MatchmakerResponse::Error(err) => {
            user_channel.try_send(OnlineMatchmakerResponse::Error(err))?;
        }
        other => anyhow::bail!("Unexpected message from matchmaker: {other:?}"),
    }

    Ok(())
}