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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
use crate::card_service::REDIS_CONNECT_CELL;
use std::future::Future;
use std::time::Duration;

use crate::static_def::{BASE_CONFIG, CONFIG};
use anyhow::Result;
use once_cell::sync::OnceCell;
use redis::aio::{ConnectionManager, ConnectionManagerConfig};
use redis::{Client, IntoConnectionInfo, RedisResult};
use tokio::sync::Mutex;

/// 重试次数
const REDIS_RETRY_COUNT: usize = 5;
static LOCK_REDIS_INIT: Mutex<()> = Mutex::const_new(());

/// Redis连接管理器
pub struct RedisConnect {
    /// redis 连接管理器
    connect: ConnectionManager,
}

/// 未完成牌局信息
#[derive(Debug, Clone, Default)]
pub struct UnfinishInfo {
    /// 等级
    pub level_id: i32,
    /// 押注
    pub bet_money: f64,
    /// 牌库标签
    pub tag: i32,
    /// 当前期数
    pub drawing: i32,
    /// 当前期数index
    pub index: i64,
    /// 当前牌型位置
    pub position: u32,
    /// key
    key: OnceCell<String>,
}

impl UnfinishInfo {
    /// 获取redis缓存的key
    #[inline]
    pub fn get_redis_key(&self) -> &str {
        self.key.get_or_init(|| {
            format!(
                "game_cache:{}_{}_{}_{}",
                BASE_CONFIG.base.server_id, self.level_id, self.bet_money, self.tag
            )
        })
    }
}

impl RedisConnect {
    /// 安装redis
    pub async fn init() -> Result<()> {
        let _guard = LOCK_REDIS_INIT.lock().await;
        if !REDIS_CONNECT_CELL.initialized() {
            let test_connect_info = (&*CONFIG.redis.redis_url).into_connection_info()?;
            let url = if test_connect_info.redis_settings().db() == 0
                && CONFIG.redis.redis_index.unwrap_or(0) != 0
            {
                format!(
                    "{}/{}",
                    CONFIG.redis.redis_url,
                    CONFIG.redis.redis_index.unwrap_or(0)
                )
            } else {
                CONFIG.redis.redis_url.clone()
            };

            let connect = ConnectionManager::new_with_config(
                Client::open(url)?,
                ConnectionManagerConfig::new()
                    .set_connection_timeout(Some(Duration::from_secs(5)))
                    .set_response_timeout(Some(Duration::from_secs(5)))
                    .set_number_of_retries(6)
                    .set_max_delay(Duration::from_secs(10)),
            )
            .await?;

            REDIS_CONNECT_CELL
                .set(RedisConnect { connect })
                .map_err(|_| anyhow::anyhow!("redis init error"))?;
            log::info!("redis init ok");
        }
        Ok(())
    }

    /// 指数退避(带轻量抖动),避免并发重试风暴
    #[inline]
    fn retry_delay(attempt: usize) -> Duration {
        const BASE_MS: u64 = 5;
        const MAX_MS: u64 = 1_000;
        let exp = 1u64 << attempt.min(6);
        let backoff = BASE_MS.saturating_mul(exp).min(MAX_MS);
        let jitter = ((attempt as u64 * 13) % 17) + 3;
        Duration::from_millis(backoff.saturating_add(jitter))
    }

    /// 重试 redis 操作:仅重试可恢复的网络/连接类错误
    #[inline]
    pub async fn retry_redis_func<F, Fut, T>(mut func: F) -> Result<T>
    where
        F: FnMut() -> Fut,
        Fut: Future<Output = RedisResult<T>>,
    {
        let mut retries = 0;
        loop {
            match func().await {
                Ok(result) => return Ok(result),
                Err(e) => {
                    if !e.is_connection_dropped() {
                        log::warn!(                           
                            "Redis operation failed with non-retryable error attempt:{} max_retries:{REDIS_RETRY_COUNT} error:{e}",
                            retries + 1
                        );
                        return Err(anyhow::anyhow!(e));
                    }

                    if retries >= REDIS_RETRY_COUNT {
                        return Err(anyhow::anyhow!(
                            "Redis operation failed after {} retries: {}",
                            REDIS_RETRY_COUNT,
                            e
                        ));
                    }
                    retries += 1;
                    let delay = Self::retry_delay(retries);
                    log::warn!(                      
                        "Redis operation failed, retrying attempt:{retries} max_retries:{REDIS_RETRY_COUNT} error:{e}, next retry in {} ms",
                        delay.as_millis() as u64
                    );
                    tokio::time::sleep(delay).await;
                }
            }
        }
    }

    /// 获取redis连接 如果redis噶了报错
    #[inline]
    fn get_redis_connect() -> ConnectionManager {
        REDIS_CONNECT_CELL
            .get()
            .expect("not found redis connect init")
            .connect
            .clone()
    }

    /// 设置当前牌库状态
    pub async fn set_current_status(key: &str, drawing: i32, current_index: i64) -> Result<()> {
        Self::retry_redis_func(|| async {
            let mut connect = Self::get_redis_connect();
            redis::pipe()
                .hset(key, "drawing", drawing)
                .hset(key, "current_index", current_index)
                .query_async::<()>(&mut connect)
                .await
        })
        .await
    }

    /// 获取当前牌库状态
    pub async fn get_current_status(key: &str) -> Result<(i32, i64)> {
        let result = Self::retry_redis_func(|| async {
            let mut connect = Self::get_redis_connect();
            redis::pipe()
                .hget(key, "drawing")
                .hget(key, "current_index")
                .query_async(&mut connect)
                .await
        })
        .await;

        match result {
            Ok(Some((drawing, current_index))) => Ok((drawing, current_index)),
            _ => {
                Self::set_current_status(key, 0, 0).await?;
                Ok((0, 0))
            }
        }
    }

    /// 生成未完成 key
    fn make_unfinish_key(
        server_id: u32,
        level_id: i32,
        bet_money: f64,
        tag: i32,
        drawing: i32,
        index: i64,
    ) -> String {
        format!("unfinish_{server_id}_{level_id}_{bet_money}_{tag}_{drawing}_{index}")
    }

    /// 设置未完成 index
    pub async fn set_unfinish_index(
        level_id: i32,
        bet_money: f64,
        tag: i32,
        drawing: i32,
        index: i64,
        position: u32,
    ) -> Result<()> {
        let key = Self::make_unfinish_key(
            BASE_CONFIG.base.server_id,
            level_id,
            bet_money,
            tag,
            drawing,
            index,
        );

        Self::retry_redis_func(|| async {
            let mut connect = Self::get_redis_connect();
            redis::cmd("set")
                .arg(&key)
                .arg(position)
                .query_async::<()>(&mut connect)
                .await
        })
        .await
    }

    /// 获取未完成 index
    pub async fn get_unfinish_index(
        level_id: i32,
        bet_money: f64,
        tag: i32,
        drawing: i32,
        index: i64,
    ) -> Result<Option<u32>> {
        let key = Self::make_unfinish_key(
            BASE_CONFIG.base.server_id,
            level_id,
            bet_money,
            tag,
            drawing,
            index,
        );
        Self::retry_redis_func(|| async {
            let mut connect = Self::get_redis_connect();
            let result: Option<u32> = redis::cmd("get")
                .arg(&key)
                .query_async(&mut connect)
                .await?;
            Ok(result)
        })
        .await
    }

    /// 删除所有以 unfinish_{server_id}_ 开头的 key,使用 scan 防止阻塞
    pub async fn delete_unfinish_by_server_id() -> Result<u32> {
        let pattern = format!("unfinish_{}_*", BASE_CONFIG.base.server_id);
        Self::retry_redis_func(|| async {
            let mut connect = Self::get_redis_connect();
            let mut cursor: u64 = 0;
            let mut total_deleted = 0u32;
            loop {
                let (next_cursor, keys): (u64, Vec<String>) = redis::cmd("scan")
                    .arg(cursor)
                    .arg("MATCH")
                    .arg(&pattern)
                    .arg("COUNT")
                    .arg(200)
                    .query_async(&mut connect)
                    .await?;
                if !keys.is_empty() {
                    let deleted: u32 = redis::cmd("del")
                        .arg(keys)
                        .query_async(&mut connect)
                        .await?;
                    total_deleted += deleted;
                }
                if next_cursor == 0 {
                    break;
                }
                cursor = next_cursor;
            }
            Ok(total_deleted)
        })
        .await
    }

    /// 删除指定未完成 index
    pub async fn delete_unfinish_index(
        level_id: i32,
        bet_money: f64,
        tag: i32,
        drawing: i32,
        index: i64,
    ) -> Result<u32> {
        let key = Self::make_unfinish_key(
            BASE_CONFIG.base.server_id,
            level_id,
            bet_money,
            tag,
            drawing,
            index,
        );
        Self::retry_redis_func(|| async {
            let mut connect = Self::get_redis_connect();
            let deleted: u32 = redis::cmd("del")
                .arg(&key)
                .query_async(&mut connect)
                .await?;
            Ok(deleted)
        })
        .await
    }

    /// 获取所有以 unfinish_{server_id}_ 开头的未完成数据,使用 scan 防止阻塞
    pub async fn get_all_unfinish_by_server() -> Result<Vec<UnfinishInfo>> {
        let pattern = format!("unfinish_{}_*", BASE_CONFIG.base.server_id);
        Self::retry_redis_func(|| async {
            let mut connect = Self::get_redis_connect();
            let mut cursor: u64 = 0;
            let mut all_keys = Vec::new();
            loop {
                let (next_cursor, keys): (u64, Vec<String>) = redis::cmd("scan")
                    .arg(cursor)
                    .arg("MATCH")
                    .arg(&pattern)
                    .arg("COUNT")
                    .arg(100)
                    .query_async(&mut connect)
                    .await?;
                all_keys.extend(keys);
                if next_cursor == 0 {
                    break;
                }
                cursor = next_cursor;
            }
            if all_keys.is_empty() {
                return Ok(vec![]);
            }
            // 批量获取所有 index
            let indexes: Vec<Option<u32>> = redis::cmd("mget")
                .arg(all_keys.clone())
                .query_async(&mut connect)
                .await?;

            let mut result = Vec::new();
            for (key, position_opt) in all_keys.into_iter().zip(indexes.into_iter()) {
                if let Some(position) = position_opt {
                    // 解析 key
                    // 格式: unfinish_{server_id}_{level_id}_{bet_money}_{tag}_{drawing}_{index}
                    let parts: Vec<&str> = key.split('_').collect();
                    if parts.len() == 7 {
                        if let (Ok(level_id), Ok(bet_money), Ok(tag), Ok(drawing), Ok(index)) = (
                            parts[2].parse::<i32>(),
                            parts[3].parse::<f64>(),
                            parts[4].parse::<i32>(),
                            parts[5].parse::<i32>(),
                            parts[6].parse::<i64>(),
                        ) {
                            result.push(UnfinishInfo {
                                level_id,
                                bet_money,
                                tag,
                                drawing,
                                index,
                                position,
                                key: Default::default(),
                            });
                        }
                    }
                }
            }
            Ok(result)
        })
        .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;
    use std::time::{SystemTime, UNIX_EPOCH};
    use tokio;
    use tokio::sync::Mutex;

    static LOCK_REDIS: Mutex<()> = Mutex::const_new(());

    // 测试参数
    const TEST_LEVEL_ID: i32 = 101;
    const TEST_BET_MONEY: f64 = 50.5;
    const TEST_TAG: i32 = 9007;
    const TEST_DRAWING: i32 = 1;
    const TEST_INDEX: i64 = 10;
    const TEST_POSITION: u32 = 888;
    const TEST_POSITION2: u32 = 999;

    async fn clean_test_keys() {
        // 清理所有 unfinish_{server_id}_* key
        let _ = RedisConnect::delete_unfinish_by_server_id().await;
    }

    fn make_test_status_key(case_name: &str) -> String {
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        format!(
            "test:current_status:{}:{}:{}",
            BASE_CONFIG.base.server_id, case_name, nonce
        )
    }

    async fn cleanup_status_key(key: &str) {
        let _ = RedisConnect::retry_redis_func(|| async {
            let mut connect = RedisConnect::get_redis_connect();
            let _: u32 = redis::cmd("del").arg(key).query_async(&mut connect).await?;
            Ok(())
        })
        .await;
    }

    #[tokio::test]
    async fn test_set_and_get_unfinish_index() {
        let _lock = LOCK_REDIS.lock().await;
        RedisConnect::init().await.unwrap();
        clean_test_keys().await;
        // 写入
        RedisConnect::set_unfinish_index(
            TEST_LEVEL_ID,
            TEST_BET_MONEY,
            TEST_TAG,
            TEST_DRAWING,
            TEST_INDEX,
            TEST_POSITION,
        )
        .await
        .unwrap();
        // 读取
        let idx = RedisConnect::get_unfinish_index(
            TEST_LEVEL_ID,
            TEST_BET_MONEY,
            TEST_TAG,
            TEST_DRAWING,
            TEST_INDEX,
        )
        .await
        .unwrap();
        assert_eq!(idx, Some(TEST_POSITION));
        clean_test_keys().await;
    }

    #[tokio::test]
    async fn test_update_unfinish_index() {
        let _lock = LOCK_REDIS.lock().await;
        RedisConnect::init().await.unwrap();
        clean_test_keys().await;
        // 写入
        RedisConnect::set_unfinish_index(
            TEST_LEVEL_ID,
            TEST_BET_MONEY,
            TEST_TAG,
            TEST_DRAWING,
            TEST_INDEX,
            TEST_POSITION,
        )
        .await
        .unwrap();
        // 更新
        RedisConnect::set_unfinish_index(
            TEST_LEVEL_ID,
            TEST_BET_MONEY,
            TEST_TAG,
            TEST_DRAWING,
            TEST_INDEX,
            TEST_POSITION2,
        )
        .await
        .unwrap();
        // 读取
        let idx = RedisConnect::get_unfinish_index(
            TEST_LEVEL_ID,
            TEST_BET_MONEY,
            TEST_TAG,
            TEST_DRAWING,
            TEST_INDEX,
        )
        .await
        .unwrap();
        assert_eq!(idx, Some(TEST_POSITION2));
        clean_test_keys().await;
    }

    #[tokio::test]
    async fn test_delete_unfinish_index() {
        let _lock = LOCK_REDIS.lock().await;
        RedisConnect::init().await.unwrap();
        clean_test_keys().await;
        RedisConnect::set_unfinish_index(
            TEST_LEVEL_ID,
            TEST_BET_MONEY,
            TEST_TAG,
            TEST_DRAWING,
            TEST_INDEX,
            TEST_POSITION,
        )
        .await
        .unwrap();
        let deleted = RedisConnect::delete_unfinish_index(
            TEST_LEVEL_ID,
            TEST_BET_MONEY,
            TEST_TAG,
            TEST_DRAWING,
            TEST_INDEX,
        )
        .await
        .unwrap();
        assert_eq!(deleted, 1);
        let idx = RedisConnect::get_unfinish_index(
            TEST_LEVEL_ID,
            TEST_BET_MONEY,
            TEST_TAG,
            TEST_DRAWING,
            TEST_INDEX,
        )
        .await
        .unwrap();
        assert_eq!(idx, None);
        clean_test_keys().await;
    }

    #[tokio::test]
    async fn test_get_all_unfinish_by_server() {
        let _lock = LOCK_REDIS.lock().await;
        RedisConnect::init().await.unwrap();
        clean_test_keys().await;
        // 插入多条
        let mut expected = HashSet::new();
        for i in 0..300 {
            let drawing = TEST_DRAWING + i;
            let index = TEST_INDEX + i as i64;
            let position = TEST_POSITION + i as u32;
            RedisConnect::set_unfinish_index(
                TEST_LEVEL_ID,
                TEST_BET_MONEY,
                TEST_TAG,
                drawing,
                index,
                position,
            )
            .await
            .unwrap();
            expected.insert((
                TEST_LEVEL_ID,
                TEST_BET_MONEY.to_bits(),
                TEST_TAG,
                drawing,
                index,
                position,
            ));
        }
        let all = RedisConnect::get_all_unfinish_by_server().await.unwrap();
        let got: HashSet<_> = all
            .into_iter()
            .map(|u| {
                (
                    u.level_id,
                    u.bet_money.to_bits(),
                    u.tag,
                    u.drawing,
                    u.index,
                    u.position,
                )
            })
            .collect();
        assert_eq!(got, expected);
        clean_test_keys().await;
    }

    #[tokio::test]
    async fn test_delete_unfinish_by_server_id() {
        let _lock = LOCK_REDIS.lock().await;
        RedisConnect::init().await.unwrap();
        clean_test_keys().await;
        // 插入多条
        for i in 0..300 {
            let drawing = TEST_DRAWING + i;
            let index = TEST_INDEX + i as i64;
            let position = TEST_POSITION + i as u32;
            RedisConnect::set_unfinish_index(
                TEST_LEVEL_ID,
                TEST_BET_MONEY,
                TEST_TAG,
                drawing,
                index,
                position,
            )
            .await
            .unwrap();
        }
        let deleted = RedisConnect::delete_unfinish_by_server_id().await.unwrap();
        assert!(deleted >= 300);
        let all = RedisConnect::get_all_unfinish_by_server().await.unwrap();
        assert!(all.is_empty());
    }

    #[tokio::test]
    async fn test_get_unfinish_index_not_exist() {
        let _lock = LOCK_REDIS.lock().await;
        RedisConnect::init().await.unwrap();
        clean_test_keys().await;
        let idx = RedisConnect::get_unfinish_index(9999, 1.0, 1, 1, 1)
            .await
            .unwrap();
        assert_eq!(idx, None);
    }

    #[tokio::test]
    async fn test_get_all_unfinish_empty() {
        let _lock = LOCK_REDIS.lock().await;
        RedisConnect::init().await.unwrap();
        clean_test_keys().await;
        let all = RedisConnect::get_all_unfinish_by_server().await.unwrap();
        assert!(all.is_empty());
    }

    #[tokio::test]
    async fn test_current_status_set_then_get() {
        RedisConnect::init().await.unwrap();
        let key = make_test_status_key("set_then_get");
        cleanup_status_key(&key).await;

        RedisConnect::set_current_status(&key, 123, 456)
            .await
            .unwrap();
        let (drawing, current_index) = RedisConnect::get_current_status(&key).await.unwrap();

        assert_eq!(drawing, 123);
        assert_eq!(current_index, 456);
        cleanup_status_key(&key).await;
    }

    #[tokio::test]
    async fn test_current_status_get_missing_key_init_default() {
        RedisConnect::init().await.unwrap();
        let key = make_test_status_key("missing_default");
        cleanup_status_key(&key).await;

        let (drawing, current_index) = RedisConnect::get_current_status(&key).await.unwrap();
        assert_eq!((drawing, current_index), (0, 0));

        // 再读一次,确认默认值已被写回 Redis
        let (drawing2, current_index2) = RedisConnect::get_current_status(&key).await.unwrap();
        assert_eq!((drawing2, current_index2), (0, 0));
        cleanup_status_key(&key).await;
    }

    #[tokio::test]
    async fn test_current_status_set_overwrite() {
        RedisConnect::init().await.unwrap();
        let key = make_test_status_key("set_overwrite");
        cleanup_status_key(&key).await;

        RedisConnect::set_current_status(&key, 1, 10).await.unwrap();
        RedisConnect::set_current_status(&key, 2, 20).await.unwrap();
        let got = RedisConnect::get_current_status(&key).await.unwrap();

        assert_eq!(got, (2, 20));
        cleanup_status_key(&key).await;
    }
}