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
|
#![allow(dead_code)]
use super::traits::{GameError, GameState};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use uuid::Uuid;
#[derive(Debug, Clone)]
pub struct GameSession {
pub session_id: String,
pub username: String,
pub game_type: String,
pub bet_amount: u64,
pub state: GameState,
}
pub struct SessionManager {
sessions: Arc<Mutex<HashMap<String, GameSession>>>,
}
impl SessionManager {
pub fn new() -> Self {
Self {
sessions: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn create_session(&self, username: &str, game_type: String, state: GameState) -> String {
let session_id = Uuid::new_v4().to_string();
let session = GameSession {
session_id: session_id.clone(),
username: username.to_string(),
game_type,
bet_amount: state.bet_amount,
state,
};
let mut sessions = self.sessions.lock().unwrap();
sessions.insert(session_id.clone(), session);
session_id
}
pub fn get_session(&self, session_id: &str) -> Result<GameSession, GameError> {
let sessions = self.sessions.lock().unwrap();
sessions
.get(session_id)
.cloned()
.ok_or(GameError::SessionNotFound)
}
pub fn update_session(&self, session_id: &str, new_state: GameState) -> Result<(), GameError> {
let mut sessions = self.sessions.lock().unwrap();
if let Some(session) = sessions.get_mut(session_id) {
session.state = new_state;
Ok(())
} else {
Err(GameError::SessionNotFound)
}
}
pub fn remove_session(&self, session_id: &str) -> Result<(), GameError> {
let mut sessions = self.sessions.lock().unwrap();
sessions
.remove(session_id)
.ok_or(GameError::SessionNotFound)
.map(|_| ())
}
pub fn get_user_sessions(&self, username: &str) -> Vec<GameSession> {
let sessions = self.sessions.lock().unwrap();
sessions
.values()
.filter(|s| s.username == username)
.cloned()
.collect()
}
}
|