mahjong_service/
db_storage.rs

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
use crate::{
    auth::{AuthInfo, AuthInfoData, GetAuthInfo, Username},
    common::Storage,
    db_storage::models::{
        DieselAuthInfo, DieselAuthInfoEmail, DieselAuthInfoGithub, DieselGame, DieselGamePlayer,
        DieselGameScore, DieselPlayer,
    },
    env::{ENV_PG_URL, ENV_REDIS_URL},
};
use async_trait::async_trait;
use diesel::pg::PgConnection;
use diesel::prelude::*;
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
use mahjong_core::{Game, GameId, PlayerId, Players};
use redis::Commands;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use service_contracts::{ServiceGame, ServicePlayer, ServicePlayerGame};
use tracing::debug;

pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations");

use self::{
    models::{
        DieselAuthInfoAnonymous, DieselGameBoard, DieselGameDrawWall, DieselGameHand,
        DieselGameSettings,
    },
    models_translation::DieselGameExtra,
};

mod models;
mod models_translation;
mod schema;

pub struct DBStorage {
    db_path: String,
    redis_path: String,
}

#[derive(Serialize, Deserialize)]
struct FileContent {
    auth: Option<FxHashMap<Username, AuthInfo>>,
    games: Option<FxHashMap<GameId, Game>>,
    players: Option<FxHashMap<PlayerId, ServicePlayer>>,
}

#[async_trait]
impl Storage for DBStorage {
    async fn get_auth_info(&self, get_auth_info: GetAuthInfo) -> Result<Option<AuthInfo>, String> {
        let mut connection = PgConnection::establish(&self.db_path).unwrap();

        match get_auth_info {
            GetAuthInfo::EmailUsername(username) => {
                DieselAuthInfoEmail::get_info_by_username(&mut connection, &username)
            }
            GetAuthInfo::GithubUsername(username) => {
                DieselAuthInfoGithub::get_info_by_username(&mut connection, &username)
            }
            GetAuthInfo::PlayerId(player_id) => {
                DieselAuthInfo::get_info_by_id(&mut connection, &player_id)
            }
            GetAuthInfo::AnonymousToken(id_token) => {
                DieselAuthInfoAnonymous::get_info_by_hashed_token(&mut connection, &id_token)
            }
        }
    }

    async fn get_player_total_score(&self, player_id: &PlayerId) -> Result<i32, String> {
        let mut connection = PgConnection::establish(&self.db_path).unwrap();

        let total_score = DieselGameScore::read_total_from_player(&mut connection, player_id);

        Ok(total_score)
    }

    async fn save_auth_info(&self, auth_info: &AuthInfo) -> Result<(), String> {
        use schema::auth_info::table;
        use schema::auth_info_anonymous::table as anonymous_table;
        use schema::auth_info_email::table as email_table;
        use schema::auth_info_github::table as github_table;

        let mut connection = PgConnection::establish(&self.db_path).unwrap();
        let diesel_auth_info = DieselAuthInfo::from_raw(auth_info);

        diesel::insert_into(table)
            .values(&diesel_auth_info)
            .execute(&mut connection)
            .unwrap();

        match auth_info.data {
            AuthInfoData::Email(ref email) => {
                let diesel_auth_info_email = DieselAuthInfoEmail::from_raw(email);

                diesel::insert_into(email_table)
                    .values(&diesel_auth_info_email)
                    .execute(&mut connection)
                    .unwrap();
            }
            AuthInfoData::Github(ref github) => {
                let diesel_auth_info_github = DieselAuthInfoGithub::from_raw(github);

                diesel::insert_into(github_table)
                    .values(&diesel_auth_info_github)
                    .execute(&mut connection)
                    .unwrap();
            }
            AuthInfoData::Anonymous(ref anonymous) => {
                let diesel_auth_info_anonymous = DieselAuthInfoAnonymous::from_raw(anonymous);

                diesel::insert_into(anonymous_table)
                    .values(&diesel_auth_info_anonymous)
                    .execute(&mut connection)
                    .unwrap();
            }
        }

        Ok(())
    }

    async fn save_game(&self, service_game: &ServiceGame) -> Result<(), String> {
        let mut connection = PgConnection::establish(&self.db_path).unwrap();
        let redis_client = redis::Client::open(self.redis_path.clone()).unwrap();
        let mut redis_connection = redis_client.get_connection().unwrap();

        let game_str = serde_json::to_string(&service_game).unwrap();
        let redis_key = format!("game:{}", service_game.game.id);

        let _: () = redis_connection.set(redis_key.clone(), game_str).unwrap();
        let _: () = redis_connection.expire(redis_key, 60 * 60).unwrap();

        DieselPlayer::update_from_game(&mut connection, service_game);

        let diesel_game_extra = DieselGameExtra {
            created_at: chrono::DateTime::from_timestamp_millis(service_game.created_at)
                .unwrap()
                .naive_utc(),
            game: service_game.game.clone(),
            updated_at: chrono::DateTime::from_timestamp_millis(service_game.updated_at)
                .unwrap()
                .naive_utc(),
        };

        let diesel_game = DieselGame::from_raw(&diesel_game_extra);

        diesel_game.update(&mut connection);

        let diesel_game_players = DieselGamePlayer::from_game(&service_game.game);
        DieselGamePlayer::update(&mut connection, &diesel_game_players, &service_game.game);

        DieselGameScore::update_from_game(&mut connection, service_game);
        DieselGameBoard::update_from_game(&mut connection, service_game);
        DieselGameDrawWall::update_from_game(&mut connection, service_game);
        DieselGameHand::update_from_game(&mut connection, service_game);
        DieselGameSettings::update_from_game(&mut connection, service_game);

        Ok(())
    }

    async fn get_game(&self, id: &GameId, use_cache: bool) -> Result<Option<ServiceGame>, String> {
        let redis_client = redis::Client::open(self.redis_path.clone()).unwrap();
        let mut redis_connection = redis_client.get_connection().unwrap();

        let redis_key = format!("game:{}", id);

        if use_cache {
            let game_str: Option<String> = redis_connection.get(redis_key).unwrap();

            if game_str.is_some() {
                let game: ServiceGame = serde_json::from_str(&game_str.unwrap()).unwrap();

                return Ok(Some(game));
            }
        } else {
            redis_connection.del::<String, bool>(redis_key).unwrap();
        }

        let mut connection = PgConnection::establish(&self.db_path).unwrap();

        let result = DieselGame::read_from_id(&mut connection, id);

        if result.is_none() {
            return Ok(None);
        }

        let game_players = DieselGamePlayer::read_from_game(&mut connection, id);
        let players = DieselPlayer::read_from_ids(&mut connection, &game_players);

        let score = DieselGameScore::read_from_game(&mut connection, id);
        let board = DieselGameBoard::read_from_game(&mut connection, id);
        let draw_wall = DieselGameDrawWall::read_from_game(&mut connection, id);
        let (hands, bonus_tiles) = DieselGameHand::read_from_game(&mut connection, id);
        let settings = DieselGameSettings::read_from_game(&mut connection, id);

        if settings.is_none() {
            return Ok(None);
        }

        let game_extra = result.unwrap();
        let mut game = game_extra.game;
        game.players = Players(game_players);
        game.score = score;
        game.table.hands = hands;
        game.table.bonus_tiles = bonus_tiles;
        game.table.board = board;
        game.table.draw_wall = draw_wall;

        let service_game = ServiceGame {
            created_at: game_extra.created_at.and_utc().timestamp_millis(),
            game,
            players,
            settings: settings.unwrap(),
            updated_at: game_extra.updated_at.and_utc().timestamp_millis(),
        };

        Ok(Some(service_game))
    }

    async fn get_player_games(
        &self,
        player_id: &Option<PlayerId>,
    ) -> Result<Vec<ServicePlayerGame>, String> {
        let mut connection = PgConnection::establish(&self.db_path).unwrap();

        if player_id.is_some() {
            let result =
                DieselGamePlayer::read_from_player(&mut connection, &player_id.clone().unwrap());

            return Ok(result);
        }

        let all = DieselGame::read_player_games(&mut connection);

        Ok(all)
    }

    async fn get_player(&self, player_id: &PlayerId) -> Result<Option<ServicePlayer>, String> {
        let mut connection = PgConnection::establish(&self.db_path).unwrap();

        let player = DieselPlayer::read_from_id(&mut connection, player_id);

        Ok(player)
    }

    async fn save_player(&self, player: &ServicePlayer) -> Result<(), String> {
        let mut connection = PgConnection::establish(&self.db_path).unwrap();

        DieselPlayer::save(&mut connection, player);

        Ok(())
    }

    async fn delete_games(&self, ids: &[GameId]) -> Result<(), String> {
        let mut connection = PgConnection::establish(&self.db_path).unwrap();

        DieselGamePlayer::delete_games(&mut connection, ids);
        DieselGameScore::delete_games(&mut connection, ids);
        DieselGameBoard::delete_games(&mut connection, ids);
        DieselGameDrawWall::delete_games(&mut connection, ids);
        DieselGameHand::delete_games(&mut connection, ids);
        DieselGameSettings::delete_games(&mut connection, ids);
        DieselGame::delete_games(&mut connection, ids);

        Ok(())
    }
}

impl DBStorage {
    #[allow(dead_code)]
    pub fn new_dyn() -> Box<dyn Storage> {
        let db_path = std::env::var(ENV_PG_URL)
            .unwrap_or("postgres://postgres:postgres@localhost/mahjong".to_string());
        let redis_path = std::env::var(ENV_REDIS_URL).unwrap_or("redis://localhost".to_string());

        debug!("DBStorage: {} {}", db_path, redis_path);

        let file_storage = Self {
            db_path: db_path.clone(),
            redis_path,
        };

        let mut connection = PgConnection::establish(&db_path).unwrap();

        connection.run_pending_migrations(MIGRATIONS).unwrap();

        Box::new(file_storage)
    }
}