ygopro-handler 0.1.3

A type-erased, plugin-based message handler framework for YGOPro duel rooms.
Documentation
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! Practical types used in the ygopro message flow.
//!
//! This module provides the request/response machinery that handlers use to extract
//! their parameters and to produce a response.
//!
//! Due to Rust's orphan rule and impl-conflict limitations, only the following
//! [`FromRequest`] implementations are provided. Names in `<>` are the free type
//! variables of each impl.
//!
//! **Blanket impls**:
//!
//! | Extracted type | Source |
//! |----------------|--------|
//! | `Extra` (`SocketAddr`, `Netplayer`, `CorePlayer`, `usize`, `u8`, `u32`) | `Request<Message, Extra>` |
//! | `&Message` | `Request<Message, Extra>` |
//! | `&mut Bundle<Req, State, Res>` | `Bundle<Req, State, Res>` |
//! | `&mut Response<Message>` | `Bundle<Req, State, Response<Message>>` |
//! | `&mut StopFlag` | `Bundle<Req, State, Res>` |
//! | `&mut Box<dyn Any + Send>` | `Bundle<Box<dyn Any + Send>, State, Res>` |
//! | `&mut anymap` | `Bundle<Req, State, Res>` (requires `State: ContainsMapMut`) |
//!
//! **Per-variant impls** (generated for every message variant of `ctos::`, `stoc::` and
//! `gm::`, which are treated equally; one example per family):
//!
//! | Extracted type | Source |
//! |----------------|--------|
//! | `&ctos::JoinGame` | `Request<ctos::Message, Extra>` / `ctos::Message` |
//! | `&stoc::JoinGame` | `Request<stoc::Message, Extra>` / `stoc::Message` |
//! | `&gm::Move` | `Request<gm::Message, Extra>` / `gm::Message` |
//! | `&ctos::JoinGame` | `Request<Complex<ctos::Message>, Extra>` / `Complex<ctos::Message>` |
//! | `&stoc::JoinGame` | `Request<Complex<stoc::Message>, Extra>` / `Complex<stoc::Message>` |
//! | `&gm::Move` | `Request<Complex<gm::Message>, Extra>` / `Complex<gm::Message>` |
//! | `&gm::Move` | `Request<Complex<stoc::Message>, Extra>` / `Complex<stoc::Message>` |

use std::any::Any;
use std::convert::Infallible;
use std::net::SocketAddr;

use ygopro_data::complex::Complex;
use ygopro_data::constants::CorePlayer;
use ygopro_data::constants::Netplayer;
use ygopro_data::message::ctos;
use ygopro_data::message::stoc;
use ygopro_data::message::gm;

use crate::IntoResponse;
use crate::handler::Bundle;
use crate::handler::FromRequest;

/// A request carrying a message and an extra message.
pub struct Request<Message, Extra> {
    /// The message to dispatch.
    pub message: Message,
    /// The extra data attached to the request (e.g. the sender's address or position).
    pub extra: Extra,
}

macro_rules! impl_extractable {
    ($extra:ty) => {
        impl<Message, State, Res> FromRequest<Request<Message, $extra>, State, Res> for $extra
        where
            Message: Send,
            State: Send,
            Res: Send,
        {
            fn from_request(bundle: &mut Bundle<Request<Message, $extra>, State, Res>) -> Option<Self> {
                Some(bundle.request.extra)
            }
        }
    };
}

impl_extractable!(SocketAddr);
impl_extractable!(Netplayer);
impl_extractable!(CorePlayer);
impl_extractable!(usize);
impl_extractable!(u8);
impl_extractable!(u32);

impl<Req, State, Res> FromRequest<Req, State, Res> for &mut Bundle<Req, State, Res>
where Req: Send, State: Send, Res: Send 
{
    fn from_request(bundle: &mut Bundle<Req, State, Res>) -> Option<Self> {
        Some(unsafe { &mut *(bundle as *mut Bundle<Req, State, Res>) })
    }
}

impl<State, Res> FromRequest<Box<dyn Any + Send>, State, Res> for &mut Box<dyn Any + Send>
where
    State: Send,
    Res: Send,
{
    fn from_request(bundle: &mut Bundle<Box<dyn Any + Send>, State, Res>) -> Option<Self> {
        Some(unsafe { &mut *(&mut bundle.request as *mut Box<dyn Any + Send>) })
    }
}

impl<Message, Extra, State, Res> FromRequest<Request<Message, Extra>, State, Res> for &Message
where
    Message: Send,
    Extra: Send,
    State: Send,
    Res: Send,
{
    fn from_request(bundle: &mut Bundle<Request<Message, Extra>, State, Res>) -> Option<Self> {
        Some(unsafe { &*(&bundle.request.message as *const Message) })
    }
}

macro_rules! impl_variant_ref {
    ($message_mod:ident, $variant:ident) => {
        impl<Extra, State, Res> FromRequest<Request<$message_mod::Message, Extra>, State, Res> for &$message_mod::$variant
        where
            Extra: Send,
            State: Send,
            Res: Send,
        {
            fn from_request(bundle: &mut Bundle<Request<$message_mod::Message, Extra>, State, Res>) -> Option<Self> {
                if let $message_mod::Message::$variant(inner) = &bundle.request.message {
                    Some(unsafe { &*(inner as *const $message_mod::$variant) })
                } else {
                    None
                }
            }
        }

        impl<State, Res> FromRequest<$message_mod::Message, State, Res> for &$message_mod::$variant
        where
            State: Send,
            Res: Send,
        {
            fn from_request(bundle: &mut Bundle<$message_mod::Message, State, Res>) -> Option<Self> {
                if let $message_mod::Message::$variant(inner) = &bundle.request {
                    Some(unsafe { &*(inner as *const $message_mod::$variant) })
                } else {
                    None
                }
            }
        }
    };
}

macro_rules! impl_variant_complex_ref {
    ($message_mod:ident, $variant:ident) => {
        impl<Extra, State, Res> FromRequest<Request<Complex<$message_mod::Message>, Extra>, State, Res> for &$message_mod::$variant
        where
            Extra: Send,
            State: Send,
            Res: Send,
        {
            fn from_request(bundle: &mut Bundle<Request<Complex<$message_mod::Message>, Extra>, State, Res>) -> Option<Self> {
                if let $message_mod::Message::$variant(inner) = &*bundle.request.message {
                    Some(unsafe { &*std::ptr::from_ref(inner) })
                } else {
                    None
                }
            }
        }

        impl<State, Res> FromRequest<Complex<$message_mod::Message>, State, Res> for &$message_mod::$variant
        where
            State: Send,
            Res: Send,
        {
            fn from_request(bundle: &mut Bundle<Complex<$message_mod::Message>, State, Res>) -> Option<Self> {
                if let $message_mod::Message::$variant(inner) = &*bundle.request {
                    Some(unsafe { &*std::ptr::from_ref(inner) })
                } else {
                    None
                }
            }
        }
    };
}

macro_rules! impl_variant_gm_from_stoc {
    ($variant:ident) => {
        impl<Extra, State, Res> FromRequest<Request<Complex<stoc::Message>, Extra>, State, Res> for &gm::$variant
        where
            Extra: Send,
            State: Send,
            Res: Send,
        {
            fn from_request(bundle: &mut Bundle<Request<Complex<stoc::Message>, Extra>, State, Res>) -> Option<Self> {
                if let stoc::Message::GameMessage(game_message) = &*bundle.request.message {
                    if let gm::Message::$variant(inner) = &game_message.message {
                        return Some(unsafe { &*std::ptr::from_ref(inner) });
                    }
                }
                None
            }
        }

        impl<State, Res> FromRequest<Complex<stoc::Message>, State, Res> for &gm::$variant
        where
            State: Send,
            Res: Send,
        {
            fn from_request(bundle: &mut Bundle<Complex<stoc::Message>, State, Res>) -> Option<Self> {
                if let stoc::Message::GameMessage(game_message) = &*bundle.request {
                    if let gm::Message::$variant(inner) = &game_message.message {
                        return Some(unsafe { &*std::ptr::from_ref(inner) });
                    }
                }
                None
            }
        }
    };
}

macro_rules! impl_variant_gm_response_as_stoc {
    ($variant:ident) => {
        impl IntoResponse<Response<stoc::Message>> for gm::$variant {
            fn into_response(self) -> Response<stoc::Message> {
                Response::Replace(gm::Message::$variant(self).into())
            }
        }
    };
}

macro_rules! impl_ctos {
    ($($variant:ident = $flag:literal),* $(,)?) => {
        $( impl_variant_ref!(ctos, $variant); )*
        $( impl_variant_complex_ref!(ctos, $variant); )*
        $( impl_variant_response!(ctos, $variant); )*
    };
}

macro_rules! impl_stoc {
    ($($variant:ident = $flag:literal),* $(,)?) => {
        $( impl_variant_ref!(stoc, $variant); )*
        $( impl_variant_complex_ref!(stoc, $variant); )*
        $( impl_variant_response!(stoc, $variant); )*
    };
}

macro_rules! impl_gm {
    ($($variant:ident = $flag:literal),* $(,)?) => {
        $( impl_variant_ref!(gm, $variant); )*
        $( impl_variant_complex_ref!(gm, $variant); )*
        $( impl_variant_response!(gm, $variant); )*
        $( impl_variant_gm_from_stoc!($variant); )*
        $( impl_variant_gm_response_as_stoc!($variant); )*
    };
}

/// An enum conforming to the ygopro data flow.
/// 
/// Its variants carry no inherent meaning; what each one means is decided by how the
/// downstream handles the result.
pub enum Response<Message> {
    /// Continue processing the message as normal.
    Continue,
    /// Message will be replaced with the given message when sending to its target.
    Replace(Message),
    /// Message will be replaced with multiple messages when sending to its target.
    ReplaceMultiple(Vec<Message>),
    /// This message will not send to its target.
    Swallow,
    /// This message will not send to its target, and stop current room.
    Terminate,
    /// This message will not send to its target, and kick its source.
    Kick,
}

impl<Req, State, Message> FromRequest<Req, State, Response<Message>> for &mut Response<Message> where Req: Send, State: Send, Message: Send + Sync {
    fn from_request(bundle: &mut Bundle<Req, State, Response<Message>>) -> Option<Self> {
        Some(unsafe { &mut *(&mut bundle.response as *mut Response<Message>) })
    }
}

impl<Message> std::ops::Mul for Response<Message> {
    type Output = Response<Message>;

    fn mul(self, rhs: Self) -> Self::Output {
        match (self, rhs) {
            (Response::Continue, other) | (other, Response::Continue) => other,
            (Response::Kick, _) | (_, Response::Kick) => Response::Kick,
            (Response::Terminate, _) | (_, Response::Terminate) => Response::Terminate,
            (Response::Swallow, _) | (_, Response::Swallow) => Response::Swallow,
            (Response::Replace(lhs_message), Response::Replace(rhs_message)) => {
                Response::ReplaceMultiple(vec![lhs_message, rhs_message])
            }
            (Response::Replace(message), Response::ReplaceMultiple(mut messages)) => {
                messages.insert(0, message);
                Response::ReplaceMultiple(messages)
            }
            (Response::ReplaceMultiple(mut messages), Response::Replace(message)) => {
                messages.push(message);
                Response::ReplaceMultiple(messages)
            }
            (Response::ReplaceMultiple(mut lhs_messages), Response::ReplaceMultiple(mut rhs_messages)) => {
                lhs_messages.append(&mut rhs_messages);
                Response::ReplaceMultiple(lhs_messages)
            }
        }
    }
}

impl<Message> Default for Response<Message> {
    fn default() -> Self {
        Response::Continue
    }
}

impl IntoResponse<Response<ctos::Message>> for ctos::Message {
    fn into_response(self) -> Response<ctos::Message> {
        Response::Replace(self)
    }
}

impl IntoResponse<Response<stoc::Message>> for stoc::Message {
    fn into_response(self) -> Response<stoc::Message> {
        Response::Replace(self)
    }
}

impl IntoResponse<Response<gm::Message>> for gm::Message {
    fn into_response(self) -> Response<gm::Message> {
        Response::Replace(self)
    }
}

impl IntoResponse<Response<stoc::Message>> for gm::Message {
    fn into_response(self) -> Response<stoc::Message> {
        Response::Replace(self.into())
    }
}

macro_rules! impl_variant_response {
    ($message_mod:ident, $variant:ident) => {
        impl IntoResponse<Response<$message_mod::Message>> for $message_mod::$variant {
            fn into_response(self) -> Response<$message_mod::Message> {
                Response::Replace($message_mod::Message::$variant(self))
            }
        }
    };
}

impl<Message> IntoResponse<Response<Message>> for () {
    fn into_response(self) -> Response<Message> {
        Response::Continue
    }
}

impl<Message> IntoResponse<Response<Message>> for Infallible {
    fn into_response(self) -> Response<Message> {
        Response::Continue
    }
}

impl<Message> IntoResponse<Response<Message>> for Vec<Message> {
    fn into_response(self) -> Response<Message> {
        Response::ReplaceMultiple(self)
    }
}

impl<Message> IntoResponse<Response<Message>> for bool {
    fn into_response(self) -> Response<Message> {
        if self { Response::Terminate } else { Response::Continue }
    }
}

impl<Message> IntoResponse<Response<Message>> for &'static str {
    fn into_response(self) -> Response<Message> {
        match self {
            "continue" => Response::Continue,
            "terminate" => Response::Terminate,
            "kick" => Response::Kick,
            "cancel" | "_cancel" => Response::Swallow,
            _ => Response::Continue,
        }
    }
}

impl<Message, T> IntoResponse<Response<Message>> for Option<T> where T: IntoResponse<Response<Message>> {
    fn into_response(self) -> Response<Message> {
        match self {
            Some(value) => value.into_response(),
            None => Response::Continue,
        }
    }
}

impl<Message, Response1, Response2> IntoResponse<Response<Message>> for Result<Response1, Response2>
where Response1: IntoResponse<Response<Message>>, Response2: IntoResponse<Response<Message>> {
    fn into_response(self) -> Response<Message> {
        match self {
            Ok(response1) => response1.into_response(),
            Err(response2) => response2.into_response(),
        }
    }
}

impl<Message> Response<Message> {
    /// Map the message(s) inside this response to a new type.
    pub fn map<Message2>(self, mut f: impl FnMut(Message) -> Message2) -> Response<Message2> {
        match self {
            Response::Continue => Response::Continue,
            Response::Replace(message) => Response::Replace(f(message)),
            Response::ReplaceMultiple(messages) => Response::ReplaceMultiple(messages.into_iter().map(f).collect()),
            Response::Swallow => Response::Swallow,
            Response::Terminate => Response::Terminate,
            Response::Kick => Response::Kick,
        }
    }
}

impl<Req, State, Res> FromRequest<Req, State, Res> for &mut crate::StopFlag
where Req: Send, State: Send, Res: Send {
    fn from_request(bundle: &mut Bundle<Req, State, Res>) -> Option<Self> {
        Some(unsafe { &mut *(&mut bundle.stop_flag as *mut crate::StopFlag) })
    }
}

ygopro_data::every_client_to_server_flat_message!(impl_ctos);
ygopro_data::every_server_to_client_flat_message!(impl_stoc);
ygopro_data::every_game_message_flat_message!(impl_gm);

/// A state that exposes an `anymap` by shared reference.
///
/// Data is taken out by cloning (`CloneAny`), so it is only suitable for small,
/// read-only values such as configuration.
pub trait ContainsMap {
    /// Get the `anymap` by shared reference.
    fn get_map(&self) -> &anymap3::Map<dyn anymap3::CloneAny + Send>;
}

impl<S: ContainsMap> ContainsMap for std::mem::ManuallyDrop<S> {
    fn get_map(&self) -> &anymap3::Map<dyn anymap3::CloneAny + Send> {
        ContainsMap::get_map(&**self)
    }
}

/// A state that exposes an `anymap` by mutable reference.
pub trait ContainsMapMut {
    /// Get the `anymap` by mutable reference.
    fn get_map(&mut self) -> &mut anymap3::Map<dyn std::any::Any + Send>;
}

impl<S: ContainsMapMut> ContainsMapMut for std::mem::ManuallyDrop<S> {
    fn get_map(&mut self) -> &mut anymap3::Map<dyn std::any::Any + Send> {
        ContainsMapMut::get_map(&mut **self)
    }
}

// impl<Req, State, Res> FromRequest<Req, State, Res> for &anymap3::Map<dyn anymap3::CloneAny + Send> where State: ContainsMap + Send, Req: Send, Res: Send {
//     fn from_request(bundle: &mut Bundle<Req, State, Res>) -> Option<Self> {
//         Some(unsafe { &*(bundle.state.get_map() as *const anymap3::Map<dyn anymap3::CloneAny + Send> )})
//     }
// }

impl<Req, State, Res> FromRequest<Req, State, Res> for &mut anymap3::Map<dyn std::any::Any + Send> where State: ContainsMapMut + Send, Req: Send, Res: Send {
    fn from_request(bundle: &mut Bundle<Req, State, Res>) -> Option<Self> {
        Some(unsafe { &mut *(bundle.state.get_map() as *mut anymap3::Map<dyn std::any::Any + Send> )})
    }
}