gn-matchmaking-state 0.1.12

Component for shared state-management in the game-night backend
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use std::{
    collections::HashMap, future::Future, sync::{Arc, Mutex}
};

use crate::models::Match;

use super::{
    DataAdapter, Gettable, InfoPublisher, Insertable, Matcher, Publishable, Removable, Searchable,
    Updateable,
};
pub use redis::{Commands, Connection, FromRedisValue, Msg, Pipeline, PubSub, ToRedisArgs};
use tracing::{error, info};

mod io;
pub mod publisher;

#[derive(Default, Debug)]
pub struct MatchProposal {
    pub found_region: Option<String>,
    pub found_mode: Option<String>,
    pub found_game: Option<String>,
    pub found_players: HashMap<String, Vec<String>>,
    pub found_ai: Option<bool>,
}

impl MatchProposal {
    #[inline]
    pub fn is_complete(&self) -> bool {
        return !self.found_players.is_empty()
            && self.found_region.is_some()
            && self.found_ai.is_some();
    }
}

pub type RedisAdapterDefault = RedisAdapter<redis::Connection>;

// TODO: There are definetly some thread-mutability issues in the RedisAdapter due to the excesive use of Arc<Mutex>. Fix this in a #Refractoring
pub struct RedisAdapter<I> {
    pub client: redis::Client,
    auto_delete: Option<i64>,
    connection: Arc<Mutex<redis::Connection>>,
    publisher: Option<Arc<Mutex<dyn InfoPublisher<I> + Send + Sync>>>,
    handlers: Arc<Mutex<Vec<Arc<dyn Send + Sync + 'static + Fn(Match) -> ()>>>>,
}

impl<I> From<redis::Client> for RedisAdapter<I> {
    fn from(client: redis::Client) -> Self {
        let connection =
            Arc::new(Mutex::new(client.get_connection().expect(
                format!("Could not connect to redis server at {:?}", client).as_str(),
            )));
        Self {
            client,
            connection,
            publisher: None,
            handlers: Arc::new(Mutex::new(Vec::new())),
            auto_delete: None,
        }
    }
}

impl<I> Clone for RedisAdapter<I> {
    fn clone(&self) -> Self {
        let client = self.client.clone();
        Self {
            connection: Arc::new(Mutex::new(client.get_connection().unwrap())),
            publisher: self.publisher.clone(),
            client,
            handlers: self.handlers.clone(),
            auto_delete: self.auto_delete,
        }
    }
}

impl<I> RedisAdapter<I>
where
    I: 'static,
    std::string::String: Publishable<I>,
{
    /// Connects to a redis server using the given url.

    ///
    /// # Arguments
    ///
    /// * `url` - The url to connect to the redis server.
    ///     - *format*: `redis://[<username>][:<password>@]<hostname>[:port][/<db>]`
    ///     - *example*: `redis://john:password@127.0.0.1:6379/0`
    ///
    /// # Returns
    ///
    /// A `Result` with the any connection error. If Ok a new `RedisAdapter` object is returned.
    pub fn connect(url: &str) -> Result<Self, Box<dyn std::error::Error>> {
        let client = redis::Client::open(url)?;
        Ok(Self::from(client))
    }

    pub fn with_publisher(
        mut self,
        publisher: impl InfoPublisher<I> + Send + Sync + 'static,
    ) -> Self {
        self.publisher = Some(Arc::new(Mutex::new(publisher)));
        self
    }

    pub fn with_auto_timeout(mut self, timeout: i64) -> Self {
        self.auto_delete = Some(timeout);
        self
    }

    pub fn reconnect(&self) -> Result<Connection, Box<dyn std::error::Error>> {
        Ok(self.client.get_connection()?)
    }

    /// Starts the match check in a new task. Creates a new seperate connection to the redis server.
    ///
    /// # Returns
    ///
    /// A `tokio::task::JoinHandle` that represents the spawned task.
    pub fn start_match_check(&self) -> tokio::task::JoinHandle<()> {
        let self_clone = self.clone();
        tokio::task::spawn(async move {
            self_clone.match_check().unwrap();
        })
    }

    /// Starts the match check in the current thread. Creates a new seperate connection to the redis server using it as a pubsub connection for events.
    ///
    /// # Returns
    ///
    /// A `Result` with the error if any occured. Under normal conditions this function will not exit and therefore the result should be `!`.
    /// This is currently an experimental feature in Rust and therefore not implemented here yet.
    pub fn match_check(self) -> Result<(), Box<dyn std::error::Error>> {
        // NOTE: Result should be '!' for Ok values. This is currently expermintal tough and therefore not implemented here.
        let mut connection = self.client.get_connection()?;
        let mut connection = connection.as_pubsub();

        connection.psubscribe("*:match:*")?;
        info!("Subscribed to match events");

        self.acc_searchers(connection)
    }

    fn acc_searchers(mut self, mut connection: PubSub) -> Result<(), Box<dyn std::error::Error>> {
        let mut match_proposal = MatchProposal::default();

        // TODO: Multithread this as soon as the problem with the order of messages is fixed.
        loop {
            let msg = connection.get_message().unwrap();
            info!("Message received: {:?}", msg);
            self.handle_msg(msg, &mut match_proposal);
        }
    }

    fn handle_msg(&mut self, msg: Msg, match_proposal: &mut MatchProposal) {
        let payload = msg.get_payload::<String>().unwrap();

        info!("Payload: {:?}", payload);

        let channel = msg.get_channel_name().split(":").collect::<Vec<&str>>();

        let last = channel.last().unwrap();
        let uuid = channel.first().unwrap().to_string();

        if last.to_string() == "region".to_string() {
            match_proposal.found_region = Some(payload);
            return;
        }

        if last.to_string() == "mode".to_string() {
            match_proposal.found_mode = Some(payload);
            return;
        }

        if last.to_string() == "game".to_string() {
            match_proposal.found_game = Some(payload);
            return;
        }

        if last.to_string() == "ai".to_string() {
            match_proposal.found_ai = Some(payload.parse::<i32>().unwrap() == 1);
            return;
        }

        if last.to_string() == "done".to_string() {
            self.on_done_msg(&uuid, payload, &match_proposal).unwrap();
            // TODO: The order of messages is likely but not guaranteed. This could be a potential error and should be handled accordingly.
            return;
        }

        if channel.get(channel.len() - 2).unwrap().to_string() == "players".to_string() {
            if let Some(players) = match_proposal.found_players.get_mut(&uuid) {
                players.push(payload);
                return;
            }
            match_proposal
                .found_players
                .insert(channel.first().unwrap().to_string(), vec![payload]);
        }
    }

    fn on_done_msg(
        &mut self,
        uuid: &String,
        payload: String,
        match_proposal: &MatchProposal,
    ) -> Result<tokio::task::JoinHandle<()>, Box<dyn std::error::Error>> {
        let region = match_proposal.found_region.as_ref();
        if region.is_none() {
            todo!("Handle the server error accordingly");
        }
        let region = region.unwrap().clone();

        let players = match_proposal.found_players.get(uuid);
        if players.is_none() || players.unwrap().len() == 0 {
            todo!("Handle the player error accordingly");
        }
        let players = players.unwrap().clone();
        if players.len() as i32 != payload.parse::<i32>()? {
            todo!("Handle the player count error accordingly");
        }

        let new_match = Match {
            region,
            players: players.clone(),
            mode: match_proposal.found_mode.as_ref().unwrap().clone(),
            game: match_proposal.found_game.as_ref().unwrap().clone(),
            ai: match_proposal.found_ai.unwrap(),
        };

        let handles: Vec<_> = self
            .handlers
            .lock()
            .unwrap()
            .iter()
            .cloned()
            .collect::<Vec<_>>()
            .into_iter()
            .map(move |fun| {
                let match_clone = new_match.clone();
                tokio::task::spawn(async move { fun(match_clone) })
            })
            .collect();

        let self_clone = self.clone();
        Ok(tokio::task::spawn(async move {
            // TODO: Tasks should be joined in async
            for handle in handles {
                handle.await.unwrap();
            }

            players.iter().for_each(|player| {
                if let Err(err) =
                    self_clone.remove(&player.splitn(3, ":").take(2).collect::<Vec<_>>().join(":"))
                {
                    error!("Error removing player 'uuid: {}': {}", player, err);
                }
            });
        }))
    }
}

pub trait RedisFilter<T> {
    fn is_ok(&self, check: &T) -> bool;
}

pub trait RedisUpdater<T> {
    fn update(&self, pipe: &mut Pipeline, uuid: &str) -> Result<(), Box<dyn std::error::Error>>;
}

pub trait RedisIdentifiable {
    fn name() -> String;
    fn next_uuid(connection: &mut Connection) -> Result<String, Box<dyn std::error::Error>> {
        let counter: i64 = connection.incr("uuid_inc", 1)?;
        Ok(format!("{}:{}", counter, Self::name()))
    }
}

pub trait RedisExpireable {
    fn expire(&self, pipe: &mut Pipeline, base_key: &str, timeout: i64) -> Result<(), Box<dyn std::error::Error>>;
}

pub trait RedisInsertWriter {
    fn write(&self, pipe: &mut Pipeline, base_key: &str) -> Result<(), Box<dyn std::error::Error>>;
}

/// TODO: Currently functions in this trait require the arguments to be static. This solution prohibits removing existing handlers.
/// This should be fixed by using some Context-Manager which provides the PubSub connection and handler. When the Context-Manager is dropped the handler and handler-thread should be killed.
/// This trait should also be moved to the super-module
pub trait NotifyOnRedisEvent<I> {
    fn on_update<T>(
        connection: &RedisAdapter<I>,
        handler: impl FnMut(T) -> () + Send + Sync + 'static,
    ) -> Result<tokio::task::JoinHandle<()>, Box<dyn std::error::Error>>
    where
        T: FromRedisValue;

    fn on_insert<T>(
        connection: &RedisAdapter<I>,
        handler: impl FnMut(T) -> () + Send + Sync + 'static,
    ) -> Result<tokio::task::JoinHandle<()>, Box<dyn std::error::Error>>
    where
        T: FromRedisValue;

    fn on_delete<T>(
        connection: &RedisAdapter<I>,
        handler: impl FnMut(T) -> () + Send + Sync + 'static,
    ) -> Result<tokio::task::JoinHandle<()>, Box<dyn std::error::Error>>
    where
        T: FromRedisValue;
}

pub trait RedisOutputReader
where
    Self: Sized,
{
    fn read(
        connection: &mut Connection,
        base_key: &str,
    ) -> Result<Self, Box<dyn std::error::Error>>;
}

impl<I> Removable for RedisAdapter<I>
where
    std::string::String: Publishable<I>,
{
    fn remove(&self, uuid: &str) -> Result<(), Box<dyn std::error::Error>> {
        let mut connection = self.connection.lock().unwrap();
        let iter = connection
            .scan_match(format!("{}*", uuid))?
            .into_iter()
            .collect::<Vec<String>>();

        redis::transaction(&mut connection, iter.as_slice(), |conn, pipe| {
            iter.iter().for_each(|key| {
                pipe.del(key).ignore();
            });
            pipe.query(conn)
        })?;

        if let Some(publisher) = self.publisher.as_ref() {
            publisher
                .lock()
                .unwrap()
                .publish(&uuid.to_string(), format!("remove:{uuid}"))?;
        }
        Ok(())
    }
}

impl<T, I> Insertable<T> for RedisAdapter<I>
where
    T: RedisInsertWriter + RedisExpireable + RedisIdentifiable + Clone,
    std::string::String: Publishable<I>,
{
    fn insert(&self, data: T) -> Result<String, Box<dyn std::error::Error>> {
        let key = { T::next_uuid(&mut self.connection.lock().unwrap())? };

        let mut pipe = redis::pipe();
        pipe.atomic();
        data.write(&mut pipe, &key)?;
        pipe.set(key.clone(), "");

        if let Some(auto_delete) = self.auto_delete {
            pipe.expire(key.clone(), auto_delete);
            data.expire(&mut pipe, &key, auto_delete)?;
        }

        'query: {
            let mut connection = self.connection.lock().unwrap();
            pipe.query(&mut connection)?;

            if self.publisher.is_none() {
                break 'query;
            }

            self.publisher
                .as_ref()
                .unwrap()
                .lock()
                .unwrap()
                .publish(&key, format!("insert:{key}"))?;
        }

        let mut split = key.split(":");
        Ok(split
            .next()
            .expect(format!("Invalid id on object of type {}", T::name()).as_str())
            .to_string()
            + ":"
            + split
                .next()
                .expect(format!("Invalid id on object of type {}", T::name()).as_str()))
    }
}

impl<'a, O, I> Gettable<'a, O> for RedisAdapter<I>
where
    O: RedisOutputReader + RedisIdentifiable,
{
    type Type = Box<dyn Iterator<Item = O> + 'a>;

    fn all(&'a self) -> Result<Self::Type, Box<dyn std::error::Error>> {
        let mut iter = self
            .connection
            .lock()
            .unwrap()
            .scan_match(format!("*:{}", O::name()))?
            .collect::<Vec<String>>()
            .into_iter();

        let connection_ref = self.connection.clone();
        let iter_fun = std::iter::from_fn(move || {
            if let Some(key) = iter.next() {
                let res = O::read(&mut connection_ref.lock().unwrap(), &key).ok()?;
                return Some(res);
            }
            None
        });

        Ok(Box::new(iter_fun))
    }

    fn get(&self, uuid: &str) -> Result<O, Box<dyn std::error::Error>> {
        O::read(&mut self.connection.lock().unwrap(), uuid)
    }
}

impl<'a, O, F, I> Searchable<'a, O, F> for RedisAdapter<I>
where
    O: RedisOutputReader + RedisIdentifiable + 'a,
    F: RedisFilter<O> + Default + 'a,
{
    type Type = Box<dyn Iterator<Item = O> + 'a>;

    fn filter(&'a self, filter: F) -> Result<Self::Type, Box<dyn std::error::Error>> {
        let mut iter = self
            .connection
            .lock()
            .unwrap()
            .scan_match(format!("*:{}", O::name()))?
            .collect::<Vec<String>>()
            .into_iter();

        let connection_ref = self.connection.clone();
        let iter = std::iter::from_fn(move || {
            while let Some(key) = iter.next() {
                let res = O::read(&mut connection_ref.lock().unwrap(), &key).ok()?;
                if filter.is_ok(&res) {
                    return Some(res);
                }
            }
            None
        });

        Ok(Box::new(iter))
    }
}

impl<T, U, I> Updateable<T, U> for RedisAdapter<I>
where
    U: RedisUpdater<T> + Clone,
    std::string::String: Publishable<I>,
{
    fn update(&self, uuid: &str, data: U) -> Result<(), Box<dyn std::error::Error>> {
        let mut pipe = redis::pipe();
        pipe.atomic();
        data.clone().update(&mut pipe, uuid)?;

        let mut connection = self.connection.lock().unwrap();
        pipe.query(&mut connection)?;

        if let Some(publisher) = self.publisher.as_ref() {
            publisher
                .lock()
                .unwrap()
                .publish(&uuid.to_string(), format!("update:{uuid}"))?;
        }
        Ok(())
    }
}

impl<I> Matcher for RedisAdapter<I> {
    // NOTE: This function is a temporary inefficient implementation and will be migrated to a server-side lua script using channels
    fn on_match<T>(&self, handler: T)
    where
        T: Send + Sync + 'static + Fn(Match) -> (),
    {
        self.handlers.lock().unwrap().push(Arc::new(handler));
    }
}

impl<'a, T, O, F, U> DataAdapter<'a, T, O, F, U> for RedisAdapter<redis::Connection>
where
    T: Clone + RedisInsertWriter + RedisExpireable + RedisIdentifiable + 'a,
    O: RedisOutputReader + RedisIdentifiable + 'a,
    F: RedisFilter<O> + Default + 'a,
    U: RedisUpdater<T> + Clone + 'a,
{
}