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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
use std::{net::SocketAddr, time::Duration};

use async_std::{
    channel::{Receiver, Sender},
    task,
};
use de_messages::{FromGame, JoinError, Readiness, ToGame};
use de_net::{OutPackage, Peers, Reliability};
use tracing::{error, info, warn};

use super::{
    message::{InMessage, MessageMeta},
    state::{GameState, JoinError as JoinErrorInner},
};
use crate::clients::Clients;

pub(super) struct GameProcessor {
    port: u16,
    owner: SocketAddr,
    messages: Receiver<InMessage<ToGame>>,
    outputs: Sender<OutPackage>,
    state: GameState,
    clients: Clients,
}

impl GameProcessor {
    pub(super) fn new(
        port: u16,
        owner: SocketAddr,
        messages: Receiver<InMessage<ToGame>>,
        outputs: Sender<OutPackage>,
        state: GameState,
        clients: Clients,
    ) -> Self {
        Self {
            port,
            owner,
            messages,
            outputs,
            state,
            clients,
        }
    }

    pub(super) async fn run(mut self) {
        info!(
            "Starting game server message handler on port {}...",
            self.port
        );

        // Wait a little to ensure that game creation message (send from main
        // server) is delivered first.
        task::sleep(Duration::from_millis(100)).await;
        self.join(self.owner).await.unwrap();

        loop {
            if self.outputs.is_closed() {
                error!(
                    "Output message channel on port {} is unexpectedly closed.",
                    self.port
                );
                break;
            }

            let Ok(message) = self.messages.recv().await else {
                error!(
                    "Game message channel on port {} is unexpectedly closed.",
                    self.port
                );
                break;
            };

            if self.handle_ignore(&message).await {
                continue;
            }

            match message.message() {
                ToGame::Ping(id) => {
                    self.process_ping(message.meta(), *id).await;
                }
                ToGame::Join => {
                    self.process_join(message.meta()).await;
                }
                ToGame::Leave => {
                    self.process_leave(message.meta()).await;
                }
                ToGame::Readiness(readiness) => {
                    self.process_readiness(message.meta(), *readiness).await;
                }
            }

            if self.state.is_empty().await {
                info!("Everybody disconnected, quitting...");
                break;
            }
        }

        info!(
            "Game server message handler on port {} finished.",
            self.port
        );
    }

    /// Returns true if the massage should be ignored and further handles such
    /// messages.
    async fn handle_ignore(&self, message: &InMessage<ToGame>) -> bool {
        if matches!(message.message(), ToGame::Join | ToGame::Leave) {
            // Join must be excluded from the condition because of the
            // chicken and egg problem.
            //
            // Leave must be excluded due to possibility that the message
            // was redelivered.
            return false;
        }

        if self.state.contains(message.meta().source).await {
            return false;
        }

        warn!(
            "Received a game message from a non-participating client: {:?}.",
            message.meta().source
        );
        let _ = self
            .outputs
            .send(
                OutPackage::encode_single(
                    &FromGame::NotJoined,
                    message.meta().reliability,
                    Peers::Server,
                    message.meta().source,
                )
                .unwrap(),
            )
            .await;
        true
    }

    /// Process a ping message.
    async fn process_ping(&self, meta: MessageMeta, id: u32) {
        let _ = self
            .outputs
            .send(
                OutPackage::encode_single(
                    &FromGame::Pong(id),
                    meta.reliability,
                    Peers::Server,
                    meta.source,
                )
                .unwrap(),
            )
            .await;
    }

    /// Process connect message.
    async fn process_join(&mut self, meta: MessageMeta) {
        if let Err(err) = self.clients.reserve(meta.source).await {
            warn!("Join request error: {err}");
            self.send(
                &FromGame::JoinError(JoinError::DifferentGame),
                Reliability::Unordered,
                meta.source,
            )
            .await;
            return;
        }

        match self.join(meta.source).await {
            Ok(_) => {
                self.clients.set(meta.source, self.port).await;
            }
            Err(err) => {
                self.clients.free(meta.source).await;

                match err {
                    JoinErrorInner::AlreadyJoined => {
                        warn!(
                            "Player {:?} has already joined game on port {}.",
                            meta.source, self.port
                        );

                        self.send(
                            &FromGame::JoinError(JoinError::AlreadyJoined),
                            Reliability::Unordered,
                            meta.source,
                        )
                        .await;
                    }
                    JoinErrorInner::GameFull => {
                        warn!(
                            "Player {:?} could not join game on port {} because the game is full.",
                            meta.source, self.port
                        );

                        self.send(
                            &FromGame::JoinError(JoinError::GameFull),
                            Reliability::Unordered,
                            meta.source,
                        )
                        .await;
                    }
                    JoinErrorInner::GameNotOpened => {
                        warn!(
                            "Player {:?} could not join game on port {} because the game is no \
                             longer opened.",
                            meta.source, self.port
                        );

                        self.send(
                            &FromGame::JoinError(JoinError::GameNotOpened),
                            Reliability::Unordered,
                            meta.source,
                        )
                        .await;
                    }
                }
            }
        }
    }

    async fn join(&mut self, addr: SocketAddr) -> Result<(), JoinErrorInner> {
        let id = self.state.add(addr).await?;
        info!(
            "Player {id} on {addr:?} just joined game on port {}.",
            self.port
        );
        self.send(&FromGame::Joined(id), Reliability::SemiOrdered, addr)
            .await;
        self.send_all(
            &FromGame::PeerJoined(id),
            Reliability::SemiOrdered,
            Some(addr),
        )
        .await;
        Ok(())
    }

    /// Process disconnect message.
    async fn process_leave(&mut self, meta: MessageMeta) {
        let Some(mut player_state) = self.state.remove(meta.source).await else {
            warn!("Tried to remove non-existent player {:?}.", meta.source);
            return;
        };

        self.clients.free(meta.source).await;

        info!(
            "Player {} on {:?} just left game on port {}.",
            player_state.id(),
            meta.source,
            self.port
        );

        for output in player_state.buffer_mut().build_all() {
            let _ = self.outputs.send(output).await;
        }

        self.send(&FromGame::Left, Reliability::SemiOrdered, meta.source)
            .await;
        self.send_all(
            &FromGame::PeerLeft(player_state.id()),
            Reliability::SemiOrdered,
            None,
        )
        .await;
    }

    async fn process_readiness(&mut self, meta: MessageMeta, readiness: Readiness) {
        match self.state.update_readiness(meta.source, readiness).await {
            Ok(progressed) => {
                if progressed {
                    self.send_all(
                        &FromGame::GameReadiness(readiness),
                        Reliability::SemiOrdered,
                        None,
                    )
                    .await;
                }
            }
            Err(err) => warn!(
                "Invalid readiness update from {source:?}: {err:?}",
                source = meta.source
            ),
        }
    }

    /// Send a reliable message to all players of the game.
    ///
    /// # Arguments
    ///
    /// * `message` - message to be sent.
    ///
    /// * `reliability` - reliability mode for the message.
    ///
    /// * `exclude` - if not None, the message will be delivered to all but
    ///   this player.
    async fn send_all<E>(&self, message: &E, reliability: Reliability, exclude: Option<SocketAddr>)
    where
        E: bincode::Encode,
    {
        for target in self.state.targets(exclude).await {
            self.send(message, reliability, target).await;
        }
    }

    async fn send<E>(&self, message: &E, reliability: Reliability, target: SocketAddr)
    where
        E: bincode::Encode,
    {
        let message =
            OutPackage::encode_single(message, reliability, Peers::Server, target).unwrap();
        let _ = self.outputs.send(message).await;
    }
}