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
// websocketcommunication.rs
//! module that cares about WebSocket communication

#![allow(clippy::panic)]

//region: use
use crate::*;

use mem6_common::*;

use unwrap::unwrap;
use js_sys::Reflect;
use wasm_bindgen::{prelude::*, JsCast};
use wasm_bindgen_futures::spawn_local;
use web_sys::{ErrorEvent, WebSocket};
use gloo_timers::future::TimeoutFuture;
//endregion

//the location_href is not consumed in this function and Clippy wants a reference instead a value
//but I don't want references, because they have the lifetime problem.
#[allow(clippy::needless_pass_by_value)]
///setup WebSocket connection
pub fn setup_ws_connection(
    location_href: String,
    client_ws_id: usize,
    players_ws_uid: String,
) -> WebSocket {
    //web-sys has WebSocket for Rust exactly like JavaScript has¸
    //location_href comes in this format  http://localhost:4000/
    let mut loc_href = location_href
        .replace("http://", "ws://")
        .replace("https://", "wss://");
    //Only for debugging in the development environment
    //let mut loc_href = String::from("ws://192.168.1.57:80/");
    logmod::debug_write(&loc_href);
    //remove the hash at the end
    if let Some(pos) = loc_href.find('#') {
        loc_href = unwrap!(loc_href.get(..pos)).to_string();
    }
    logmod::debug_write(&loc_href);
    loc_href.push_str("mem6ws/");

    //send the client ws id as url_param for the first connect
    //and reconnect on lost connection
    loc_href.push_str(client_ws_id.to_string().as_str());
    /*
        logmod::debug_write(&format!(
            "location_href {}  loc_href {} client_ws_id {}",
            location_href, loc_href, client_ws_id
        ));
    */

    //same server address and port as http server
    //for reconnect the old ws id will be an url param
    let ws = unwrap!(WebSocket::new(&loc_href), "WebSocket failed to connect.");

    //I don't know why is clone needed
    let ws_c = ws.clone();
    //It looks that the first send is in some way a handshake and is part of the connection
    //it will be execute on open as a closure
    let open_handler = Box::new(move || {
        //logmod::debug_write("Connection opened, sending MsgRequestWsUid to server");
        unwrap!(
            ws_c.send_with_str(&unwrap!(serde_json::to_string(
                &WsMessage::MsgRequestWsUid {
                    my_ws_uid: client_ws_id,
                    players_ws_uid: players_ws_uid.clone(),
                }
            )),),
            "Failed to send 'test' to server"
        );
        //region heartbeat ping pong keepalive
        let ws2 = ws_c.clone();
        let timeout = gloo_timers::callback::Interval::new(10_000, move || {
            // Do something after the one second timeout is up!
            let u32_size = u32_size();
            let msg = WsMessage::MsgPing { msg_id: u32_size };
            ws_send_msg(ws2.as_ref(), &msg);
            //logmod::console_log(format!("gloo timer: {}", u32_size).as_str());
        });
        // Since we don't plan on cancelling the timeout, call `forget`.
        timeout.forget();
        //endregion
    });

    let cb_oh: Closure<dyn Fn()> = Closure::wrap(open_handler);
    ws.set_onopen(Some(cb_oh.as_ref().unchecked_ref()));

    //don't drop the open_handler memory
    cb_oh.forget();

    ws
}

///usize of time
#[allow(clippy::integer_arithmetic)]
//u32 will not overflow, the minutes are max 60, so 6 mio
pub fn u32_size() -> u32 {
    let now = js_sys::Date::new_0();
    now.get_minutes() * 100_000 + now.get_seconds() * 1_000 + now.get_milliseconds()
}

/// receive WebSocket msg callback.
#[allow(clippy::unneeded_field_pattern)]
#[allow(clippy::too_many_lines)] // I know is long
pub fn setup_ws_msg_recv(ws: &WebSocket, vdom: dodrio::VdomWeak) {
    let msg_recv_handler = Box::new(move |msg: JsValue| {
        let data: JsValue = unwrap!(
            Reflect::get(&msg, &"data".into()),
            "No 'data' field in WebSocket message!"
        );
        let data = unwrap!(data.as_string());
        //don't log ping pong there are too much
        if !(data.to_string().contains("MsgPing") || data.to_string().contains("MsgPong")) {
            //logmod::debug_write(&data);
        }
        //serde_json can find out the variant of WsMessage
        //parse json and put data in the enum
        let msg: WsMessage = serde_json::from_str(&data).unwrap_or_else(|_x| WsMessage::MsgDummy {
            dummy: String::from("error"),
        });

        //match enum by variant and prepares the future that will be executed on the next tick
        //in this big enum I put only boilerplate code that don't change any data.
        //for changing data I put code in separate functions for easy reading.
        spawn_local({
            let vdom = vdom.clone();
            async move {
                let _result = vdom
                    .with_component({
                        let vdom = vdom.clone();
                        move |root| {
                            let rrc = root.unwrap_mut::<RootRenderingComponent>();

                            match msg {
                                //I don't know why I need a dummy, but is entertaining to have one.
                                WsMessage::MsgDummy { dummy } => {
                                    logmod::debug_write(dummy.as_str())
                                }
                                WsMessage::MsgPing { msg_id: _ } => {
                                    unreachable!("mem6 wasm must not receive MsgPing");
                                }
                                WsMessage::MsgPong { msg_id: _ } => {
                                    //logmod::debug_write(format!("MsgPong {}", msg_id).as_str())
                                }
                                WsMessage::MsgRequestWsUid {
                                    my_ws_uid,
                                    players_ws_uid: _,
                                } => logmod::debug_write(
                                    format!("MsgRequestWsUid {}", my_ws_uid).as_str(),
                                ),
                                WsMessage::MsgResponseWsUid {
                                    your_ws_uid,
                                    server_version: _,
                                } => {
                                    //logmod::debug_write(&format!("MsgResponseWsUid: {}  ", your_ws_uid));
                                    on_response_ws_uid(rrc, your_ws_uid);
                                }
                                WsMessage::MsgJoin {
                                    my_ws_uid,
                                    players_ws_uid: _,
                                    my_nickname,
                                } => {
                                    statusjoinedmod::on_msg_joined(rrc, my_ws_uid, my_nickname);
                                    vdom.schedule_render();
                                }
                                WsMessage::MsgStartGame {
                                    my_ws_uid: _,
                                    players_ws_uid: _,
                                    card_grid_data,
                                    game_config,
                                    players,
                                    game_name,
                                } => {
                                    let vdom = vdom.clone();
                                    statusgamedatainitmod::on_msg_start_game(
                                        rrc,
                                        &card_grid_data,
                                        &game_config,
                                        &players,
                                        &game_name,
                                    );
                                    fncallermod::open_new_local_page("#p11");
                                    vdom.schedule_render();
                                }
                                WsMessage::MsgClick1stCard {
                                    my_ws_uid,
                                    players_ws_uid: _,
                                    card_index_of_first_click,
                                    msg_id,
                                } => {
                                    status1stcardmod::on_msg_click_1st_card(
                                        rrc,
                                        &vdom,
                                        my_ws_uid,
                                        card_index_of_first_click,
                                        msg_id,
                                    );
                                    vdom.schedule_render();
                                }
                                WsMessage::MsgClick2ndCard {
                                    my_ws_uid,
                                    players_ws_uid: _,
                                    card_index_of_second_click,
                                    is_point,
                                    msg_id,
                                } => {
                                    status2ndcardmod::on_msg_click_2nd_card(
                                        rrc,
                                        my_ws_uid,
                                        card_index_of_second_click,
                                        is_point,
                                        msg_id,
                                    );
                                    vdom.schedule_render();
                                }
                                WsMessage::MsgDrinkEnd {
                                    my_ws_uid,
                                    players_ws_uid: _,
                                } => {
                                    statusdrinkmod::on_msg_drink_end(rrc, my_ws_uid, &vdom);
                                    vdom.schedule_render();
                                }
                                WsMessage::MsgTakeTurn {
                                    my_ws_uid,
                                    players_ws_uid: _,
                                    msg_id,
                                } => {
                                    statustaketurnmod::on_msg_take_turn(rrc, my_ws_uid, msg_id);
                                    vdom.schedule_render();
                                }
                                WsMessage::MsgGameOver {
                                    my_ws_uid: _,
                                    players_ws_uid: _,
                                } => {
                                    statusgameovermod::on_msg_game_over(rrc);
                                    vdom.schedule_render();
                                }
                                WsMessage::MsgPlayAgain {
                                    my_ws_uid: _,
                                    players_ws_uid: _,
                                } => {
                                    statusgameovermod::on_msg_play_again(rrc);
                                }
                                WsMessage::MsgAck {
                                    my_ws_uid,
                                    players_ws_uid: _,
                                    msg_id,
                                    msg_ack_kind,
                                } => {
                                    match msg_ack_kind {
                                        MsgAckKind::MsgTakeTurn => {
                                            statustaketurnmod::on_msg_ack_take_turn(
                                                rrc, my_ws_uid, msg_id,
                                            );
                                        }
                                        MsgAckKind::MsgClick1stCard => {
                                            status1stcardmod::on_msg_ack_click_1st_card(
                                                rrc, my_ws_uid, msg_id,
                                            );
                                        }
                                        MsgAckKind::MsgClick2ndCard => {
                                            status2ndcardmod::on_msg_ack_player_click2nd_card(
                                                rrc, my_ws_uid, msg_id, &vdom,
                                            );
                                        }
                                    }
                                    vdom.schedule_render();
                                }
                                WsMessage::MsgAskPlayer1ForResync {
                                    my_ws_uid: _,
                                    players_ws_uid: _,
                                } => {
                                    websocketreconnectmod::send_msg_for_resync(
                                        rrc,
                                        rrc.game_data.my_ws_uid,
                                    );
                                    vdom.schedule_render();
                                }
                                WsMessage::MsgAllGameData {
                                    my_ws_uid: _,
                                    players_ws_uid: _,
                                    players,
                                    card_grid_data,
                                    card_index_of_first_click,
                                    card_index_of_second_click,
                                    player_turn,
                                    game_status,
                                } => {
                                    websocketreconnectmod::on_msg_all_game_data(
                                        rrc,
                                        players,
                                        card_grid_data,
                                        card_index_of_first_click,
                                        card_index_of_second_click,
                                        player_turn,
                                        game_status,
                                    );
                                    vdom.schedule_render();
                                }
                            }
                        }
                    })
                    .await;
            }
        });
    });

    //magic ??
    let cb_mrh: Closure<dyn Fn(JsValue)> = Closure::wrap(msg_recv_handler);
    ws.set_onmessage(Some(cb_mrh.as_ref().unchecked_ref()));

    //don't drop the event listener from memory
    cb_mrh.forget();
}

/// on error write it on the screen for debugging
#[allow(clippy::as_conversions)]
pub fn setup_ws_onerror(ws: &WebSocket, vdom: dodrio::VdomWeak) {
    let onerror_callback = Closure::wrap(Box::new(move |e: ErrorEvent| {
        let err_text = format!("error event {:?}", e);
        //logmod::debug_write(&err_text);
        {
            spawn_local({
                let vdom = vdom.clone();
                async move {
                    let _result = vdom
                        .with_component({
                            let vdom = vdom.clone();
                            move |root| {
                                let rrc = root.unwrap_mut::<RootRenderingComponent>();
                                rrc.game_data.error_text = err_text;
                                vdom.schedule_render();
                            }
                        })
                        .await;
                }
            });
        }
    }) as Box<dyn FnMut(ErrorEvent)>);
    ws.set_onerror(Some(onerror_callback.as_ref().unchecked_ref()));
    onerror_callback.forget();
}

/// on close WebSocket connection
#[allow(clippy::as_conversions)]
pub fn setup_ws_onclose(ws: &WebSocket, vdom: dodrio::VdomWeak) {
    let onclose_callback = Closure::wrap(Box::new(move |e: ErrorEvent| {
        let err_text = format!("ws_onclose {:?}", e);
        logmod::debug_write(&format!("onclose_callback {}", &err_text));
        {
            spawn_local({
                let vdom = vdom.clone();
                async move {
                    let _result = vdom
                        .with_component({
                            let vdom = vdom.clone();
                            move |root| {
                                let rrc = root.unwrap_mut::<RootRenderingComponent>();
                                //I want to show a reconnect button to the user
                                rrc.game_data.is_reconnect = true;
                                vdom.schedule_render();
                            }
                        })
                        .await;
                }
            });
        }
    }) as Box<dyn FnMut(ErrorEvent)>);
    ws.set_onclose(Some(onclose_callback.as_ref().unchecked_ref()));
    onclose_callback.forget();
}
///setup all ws events
pub fn setup_all_ws_events(ws: &WebSocket, vdom: dodrio::VdomWeak) {
    //WebSocket on receive message callback
    setup_ws_msg_recv(ws, vdom.clone());

    //WebSocket on error message callback
    setup_ws_onerror(ws, vdom.clone());

    //WebSocket on close message callback
    setup_ws_onclose(ws, vdom);
}

///generic send ws message
pub fn ws_send_msg(ws: &WebSocket, ws_message: &WsMessage) {
    let x = ws.send_with_str(&unwrap!(serde_json::to_string(ws_message)));
    // retry send a 10 times before panicking
    if let Err(_err) = x {
        let ws = ws.clone();
        let ws_message = ws_message.clone();
        spawn_local({
            async move {
                let mut retries: usize = 1;
                while retries <= 10 {
                    logmod::debug_write(&format!("send retries: {}", retries));
                    //Wait 100 ms
                    TimeoutFuture::new(100).await;
                    let x = ws.send_with_str(&unwrap!(serde_json::to_string(&ws_message)));
                    if let Ok(_y) = x {
                        break;
                    }
                    // this will go until 10 and cannot overflow
                    #[allow(clippy::integer_arithmetic)]
                    {
                        retries += 1;
                    }
                }
                if retries == 0 {
                    panic!("error 10 times retry ws_send_msg");
                }
            }
        });
    }
}

///msg response with ws_uid, just to check.
pub fn on_response_ws_uid(rrc: &mut RootRenderingComponent, your_ws_uid: usize) {
    if rrc.game_data.my_ws_uid != your_ws_uid {
        rrc.game_data.error_text = "my_ws_uid is incorrect!".to_string();
    }
}