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
use crate::card_service::ch::ClickHouseDB;
use crate::card_service::redis::RedisConnect;
use crate::database::mysql::SlotsBetRatios;
use crate::static_def::{game_slot_bet_ratios, CONFIG};
use anyhow::bail;
use aqueue::Actor;
use clickhouse::{RowOwned, RowRead};
use once_cell::sync::Lazy;
use rand::prelude::IndexedRandom;
use rand::SeedableRng;
use rand_chacha::ChaCha20Rng;
use std::collections::{HashMap, VecDeque};

pub mod ch;
pub mod redis;
pub mod replay;

/// ClickHouse 数据库实例,使用 Lazy 初始化
pub static CH: Lazy<ClickHouseDB> = Lazy::new(|| ClickHouseDB::new(&CONFIG.clickhouse));

/// Redis 连接实例,使用 OnceCell 初始化
pub static REDIS_CONNECT_CELL: tokio::sync::OnceCell<RedisConnect> =
    tokio::sync::OnceCell::const_new();

/// 牌库数据结构体,包含牌库 ID 和索引
pub trait IDrawingData: 'static + RowOwned + RowRead {
    /// 获取牌库 ID
    fn get_drawing(&self) -> i32;
    /// 获取牌库索引
    fn get_index(&self) -> i64;
    /// 获取当前期牌tag
    fn get_tag(&self) -> i32;
    /// 设置使用位置
    fn set_position(&mut self, _position: u32) {}
    /// 获取使用位置
    fn get_position(&self) -> u32 {
        0
    }
}

/// 牌库服务结构体,用于管理牌库数据
#[derive(Default)]
pub struct CardServices<T> {
    /// 存储牌库数据的哈希表,键为 Redis 的 key,值为牌库数据队列
    cards: HashMap<String, VecDeque<T>>,
    /// 用于未用完的牌库回收
    temp_cards: HashMap<String, VecDeque<T>>,
}

impl<T: IDrawingData> CardServices<T> {
    /// 创建一个新的 `CardServices` 实例
    pub fn new() -> Self {
        Self {
            cards: HashMap::new(),
            temp_cards: Default::default(),
        }
    }

    /// 初始化服务
    ///
    /// # 参数
    /// - `reset`: 是否重置 Redis 数据
    ///
    /// # 返回
    /// - `anyhow::Result<()>`: 初始化结果
    pub async fn init(&mut self, reset: bool) -> anyhow::Result<()> {
        // 初始化 Redis 连接
        RedisConnect::init().await?;
        if reset {
            // 清空 Redis 数据
            for ratio in game_slot_bet_ratios() {
                RedisConnect::set_current_status(ratio.get_redis_key(), 0, 0).await?;
            }
            // 清理所有 unfinish_{server_id}_* key
            let len = RedisConnect::delete_unfinish_by_server_id().await?;
            if len > 0 {
                log::warn!("Redis数据已重置,清理未完成牌:{len}");
            } else {
                log::warn!("Redis数据已重置");
            }
        }

        // 加载未完成牌到内存中
        let all_unfinish_data = RedisConnect::get_all_unfinish_by_server()
            .await?
            .into_iter()
            .map(|x| (x.get_redis_key().to_string(), x))
            .collect::<HashMap<_, _>>();

        // 根据限制配置的倍率信息加载未完成牌
        for ratio in game_slot_bet_ratios() {
            let ratio_key = ratio.get_redis_key().to_string();
            // 如果存在未完成牌数据,则从 ClickHouse 获取对应的牌库数据并回收
            if let Some(unfinish) = all_unfinish_data.get(&ratio_key) {
                if let Some(mut data) = CH
                    .get_drawing_data_by_index::<T>(unfinish.tag, unfinish.drawing, unfinish.index)
                    .await?
                {
                    // 设置位置并回收未完成牌 这一步很重要
                    data.set_position(unfinish.position);

                    self.temp_cards
                        .entry(ratio_key)
                        .or_default()
                        .push_back(data);
                } else {
                    log::warn!(
                        "等级:{}-押注金额:{}-难度:{} 从ClickHouse获取未完成牌库数据失败,期数:{},位置:{}",
                        unfinish.level_id,
                        unfinish.bet_money,
                        unfinish.tag,
                        unfinish.drawing,
                        unfinish.index
                    );
                }
            }
        }

        // 加载牌库数据到内存
        for ratio in game_slot_bet_ratios() {
            let ratio_key = ratio.get_redis_key().to_string();
            let data = self.load_drawing_card(ratio).await?;
            self.cards.insert(ratio_key, VecDeque::from(data));
        }

        Ok(())
    }

    /// 加载指定押注比例的牌库数据
    ///
    /// # 参数
    /// - `ratio`: 押注比例信息
    ///
    /// # 返回
    /// - `anyhow::Result<Vec<DrawingData>>`: 加载的牌库数据
    #[inline]
    async fn load_drawing_card(&self, ratio: &SlotsBetRatios) -> anyhow::Result<Vec<T>> {
        let mut last_id = 0; // 上次分配的牌库 ID,初始为 0
        let data = loop {
            let (drawing, index) = {
                // 获取 Redis 中当前的牌库状态
                let (drawing, index) =
                    RedisConnect::get_current_status(ratio.get_redis_key()).await?;
                if drawing == 0 {
                    // 如果没有分配牌库,则随机分配一个
                    let drawing = self.get_random_drawing_index(ratio.radio, last_id).await?;
                    (drawing, 0)
                } else {
                    (drawing, index)
                }
            };

            // 从 ClickHouse 获取牌库数据
            let data = CH
                .get_drawing_data::<T>(ratio.radio, drawing, index, 1000)
                .await?;

            if data.is_empty() {
                // 如果数据为空,检查牌库是否已完成
                let count = CH.get_drawing_per(ratio.radio, drawing).await?;
                if count == 0 {
                    bail!(
                        "No drawing data found for tag {} and drawing {}",
                        ratio.radio,
                        drawing
                    );
                } else if count <= index {
                    last_id = drawing; // 更新上次分配的牌库 ID
                                       // 如果牌库已完成,重置 Redis 状态并重新分配
                    RedisConnect::set_current_status(ratio.get_redis_key(), 0, 0).await?;
                    log::warn!(
                        "等级:{}-押注金额:{}-难度:{} 已经分配牌库期数:{drawing} 但是已经完成了,开始重新分配",
                        ratio.level_id,
                        ratio.bet_money,
                        ratio.radio
                    );
                    continue;
                }
            }

            // 更新 Redis 状态
            log::info!(
                "等级:{}-押注金额:{}-难度:{} 分配牌库期数:{drawing},开始位置:{index},读取数量:{}",
                ratio.level_id,
                ratio.bet_money,
                ratio.radio,
                data.len()
            );

            RedisConnect::set_current_status(ratio.get_redis_key(), drawing, index).await?;
            break data;
        };
        Ok(data)
    }

    /// 随机获取一个未被使用且不同于上次分配的牌库 ID
    ///
    /// # 参数
    /// - `tag`: 押注比例标识
    /// - `last_id`: 上次分配的牌库 ID
    ///
    /// # 返回
    /// - `anyhow::Result<i32>`: 随机分配的牌库 ID
    #[inline]
    async fn get_random_drawing_index(&self, tag: i32, last_id: i32) -> anyhow::Result<i32> {
        // 获取所有可用的牌库 ID
        let ids = CH.get_drawing_ids(tag).await?;
        // 初始化随机数生成器
        let mut rng = ChaCha20Rng::from_os_rng();
        let mut check_loop = 0usize;
        loop {
            // 随机选择一个牌库 ID
            if let Some(id) = ids.choose_multiple(&mut rng, 1).last() {
                // 跳过与上次分配相同的牌库 ID
                if *id == last_id {
                    if check_loop > 1000 {
                        // 如果检查次数超过 1000 次,返回错误
                        bail!(
                            "难度tag:{tag} 随机了1000次无法找到合适的期牌,请检查期牌数量 当前期牌数量:{}",
                            ids.len()
                        );
                    }
                    check_loop += 1;
                    continue;
                }
                // 跳过当前tag下已被使用的期牌期数
                if self
                    .cards
                    .values()
                    .flatten()
                    .any(|x| x.get_tag() == tag && x.get_drawing() == *id)
                {
                    if check_loop > 1000 {
                        // 如果检查次数超过 1000 次,返回错误
                        bail!(
                            "难度tag:{tag} 随机了1000次在正在使用的当前期数上检查,却无法找到合适的期牌,请检查期牌数量 当前期牌数量:{}",
                            ids.len()
                        );
                    }

                    check_loop += 1;
                    continue;
                }
                // 返回未被使用且不同于上次分配的牌库 ID
                return Ok(*id);
            } else {
                // 未找到可用的牌库 ID,返回错误
                bail!("No drawing ids found for tag {}", tag);
            }
        }
    }

    /// 获取指定押注比例的下一条牌库数据
    ///
    /// # 参数
    /// - `&mut self`:可变引用,允许修改牌库队列
    /// - `ratio: &SlotsBetRatios`:押注比例信息
    ///
    /// # 返回
    /// - `anyhow::Result<DrawingData>`:成功时返回一条牌库数据,失败时返回错误
    #[inline]
    async fn get_drawing_data(&mut self, ratio: &SlotsBetRatios) -> anyhow::Result<T> {
        if let Some(data) = self.cards.get_mut(ratio.get_redis_key()) {
            let (data, queue) = if let Some(drawing_data) = data.pop_front() {
                // 队列有数据,直接弹出
                (drawing_data, None)
            } else {
                // 队列为空,异步加载新数据
                let mut new_data = VecDeque::from(self.load_drawing_card(ratio).await?);
                if let Some(drawing_data) = new_data.pop_front() {
                    (drawing_data, Some(new_data))
                } else {
                    bail!("No drawing data found for key {}", ratio.get_redis_key());
                }
            };

            if let Some(new_data) = queue {
                // 有新数据则更新队列
                self.cards
                    .insert(ratio.get_redis_key().to_string(), new_data);
            }

            // 同步更新 Redis 当前状态
            RedisConnect::set_current_status(
                ratio.get_redis_key(),
                data.get_drawing(),
                data.get_index(),
            )
            .await?;

            Ok(data)
        } else {
            bail!("No drawing data found for key {}", ratio.get_redis_key());
        }
    }

    /// 获取指定押注比例的未完成牌数据
    ///
    /// # 参数
    /// - `&mut self`:可变引用,允许修改牌库队列
    /// - `ratio: &SlotsBetRatios`:押注比例信息
    ///
    /// # 返回
    /// - `anyhow::Result<Option<DrawingData>>`:有返回一条牌库数据,没有返回None
    #[inline]
    async fn get_unfinish_drawing_data(&mut self, ratio: &SlotsBetRatios) -> Option<T> {
        // 首先从未完成的队列里面找找看,如果存在返回一张未完成的,返回,没有返回None
        if let Some(temp_queue) = self.temp_cards.get_mut(ratio.get_redis_key()) {
            if let Some(data) = temp_queue.pop_front() {
                // 从未完成队列中获取到数据,直接返回
                log::info!(
                    "等级:{}-押注金额:{}-难度:{} 从未完成牌库获取到数据,期数:{},牌库索引:{},使用位置:{}",
                    ratio.level_id,
                    ratio.bet_money,
                    ratio.radio,
                    data.get_drawing(),
                    data.get_index(),
                    data.get_position()
                );
                Some(data)
            } else {
                None
            }
        } else {
            None
        }
    }

    /// 回收未使用的牌
    /// # 参数
    /// - `&mut self`:可变引用,允许修改牌库队列
    /// - `key: &SlotsBetRatios`:押注比例信息
    /// - `data: T`:要回收的牌库数据
    /// # 返回
    /// - `anyhow::Result<()>`:回收结果,成功时返回 Ok,失败时返回错误
    #[inline]
    async fn recycle_unfinish_card(&mut self, key: &SlotsBetRatios, data: T) -> anyhow::Result<()> {
        let ratio_key = key.get_redis_key().to_string();
        self.temp_cards
            .entry(ratio_key)
            .or_default()
            .push_back(data);
        Ok(())
    }
}

/// 牌库服务接口定义
pub trait ICardServices<T> {
    /// 初始化服务
    ///
    /// # 参数
    /// - `reset`: 是否重置 Redis 数据
    ///
    /// # 返回
    /// - `anyhow::Result<()>`: 初始化结果
    async fn init(&self, reset: bool) -> anyhow::Result<()>;
    /// 获取指定押注比例的下一条牌库数据
    ///
    /// # 参数
    /// - `ratio: &SlotsBetRatios`:押注比例信息
    ///
    /// # 返回
    /// - `anyhow::Result<DrawingData>`:成功时返回一条牌库数据,失败时返回错误
    async fn get_drawing_data(&self, ratio: &SlotsBetRatios) -> anyhow::Result<T>;

    /// 获取指定押注比例的未完成牌数据
    ///
    /// # 参数
    /// - `&mut self`:可变引用,允许修改牌库队列
    /// - `ratio: &SlotsBetRatios`:押注比例信息
    ///
    /// # 返回
    /// - `anyhow::Result<Option<DrawingData>>`:有返回一条牌库数据,没有返回None
    async fn get_unfinish_drawing_data(&self, ratio: &SlotsBetRatios) -> Option<T>;

    /// 回收未使用的牌
    /// # 参数
    /// - `&mut self`:可变引用,允许修改牌库队列
    /// - `key: &SlotsBetRatios`:押注比例信息
    /// - `data: T`:要回收的牌库数据
    /// # 返回
    /// - `anyhow::Result<()>`:回收结果,成功时返回 Ok,失败时返回错误
    async fn recycle_unfinish_card(&self, key: &SlotsBetRatios, data: T) -> anyhow::Result<()>;
}

impl<T: IDrawingData> ICardServices<T> for Actor<CardServices<T>> {
    #[inline]
    async fn init(&self, reset: bool) -> anyhow::Result<()> {
        self.inner_call(|inner| async move { inner.get_mut().init(reset).await })
            .await
    }
    #[inline]
    async fn get_drawing_data(&self, ratio: &SlotsBetRatios) -> anyhow::Result<T> {
        self.inner_call(|inner| async move { inner.get_mut().get_drawing_data(ratio).await })
            .await
    }

    #[inline]
    async fn get_unfinish_drawing_data(&self, ratio: &SlotsBetRatios) -> Option<T> {
        self.inner_call(
            |inner| async move { inner.get_mut().get_unfinish_drawing_data(ratio).await },
        )
        .await
    }

    #[inline]
    async fn recycle_unfinish_card(&self, key: &SlotsBetRatios, data: T) -> anyhow::Result<()> {
        self.inner_call(
            |inner| async move { inner.get_mut().recycle_unfinish_card(key, data).await },
        )
        .await
    }
}