nadis 2.0.0

Redis 基础层:业务键有序分区消费、Stream/Proxy 生命周期、有界微批、幂等管线、锁与 RedisJob
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
// Redis 客户端负责连接、协议标记校验与组件装配。
// connect 建立连接并校验 namespace 内的 profile 与命名配置,一致后才返回可用客户端。
// 锁、partition 与 search 由调用方显式创建,不因连接成功就自动启动各自后台任务。
// 协议标记由遵循该约定的客户端写入和校验,不能约束绕过标记的其它客户端。
// 不同协议的 namespace 与 group 必须由部署配置隔离,避免误连破坏数据布局或时钟边界。

use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::Duration;

use redis::aio::ConnectionManager;
use redis::AsyncCommands;
#[cfg(feature = "job")]
use redis::IntoConnectionInfo;

use crate::config::{CompatibilityProfile, RedisConfig};
use crate::error::{NasaRedisError, Result};

/// 传输抽象:单节点使用 `ConnectionManager`,Cluster 使用 `cluster_async::ClusterConnection`。
/// 两者均 impl `ConnectionLike`(故 `AsyncCommands`/`query_async` 在 `Conn` 上通用),Clone 廉价(多路
/// 复用句柄)。Cluster 变体**跟随 MOVED/ASK**,单键命令按 slot 路由到正确节点;多键 Lua/MULTI 仍要求
/// 同槽 key(否则 CROSSSLOT);partition 多键脚本由 group 级 relayout 保证同槽。
#[derive(Clone)]
pub enum Conn {
    /// 单点 Redis 连接管理器。
    Single(ConnectionManager),
    /// Redis Cluster 异步连接,可跟随 MOVED/ASK 重定向。
    Cluster(redis::cluster_async::ClusterConnection),
}

impl redis::aio::ConnectionLike for Conn {
    // Routes one packed command through the selected connection mode.
    ///
    /// # 参数
    /// 业务作用:- `cmd`: 底层 Redis 命令对象。
    fn req_packed_command<'a>(
        &'a mut self,
        cmd: &'a redis::Cmd,
    ) -> redis::RedisFuture<'a, redis::Value> {
        match self {
            Conn::Single(c) => c.req_packed_command(cmd),
            Conn::Cluster(c) => c.req_packed_command(cmd),
        }
    }

    // Routes a packed command batch through the selected connection mode.
    ///
    /// # 参数
    /// 业务作用:- `cmd`: 底层 Redis 命令对象。
    /// - `offset`: 列表、字符串或分页操作的偏移量。
    /// - `count`: Redis 命令、分页或批处理使用的数量上限。
    fn req_packed_commands<'a>(
        &'a mut self,
        cmd: &'a redis::Pipeline,
        offset: usize,
        count: usize,
    ) -> redis::RedisFuture<'a, Vec<redis::Value>> {
        match self {
            Conn::Single(c) => c.req_packed_commands(cmd, offset, count),
            Conn::Cluster(c) => c.req_packed_commands(cmd, offset, count),
        }
    }

    /// 业务作用:返回当前 Redis 连接配置的逻辑库编号。
    ///
    /// 单机连接返回实际 `SELECT` 的 db;cluster 连接返回配置值,用于上层保持统一的客户端配置视图。
    fn get_db(&self) -> i64 {
        match self {
            Conn::Single(c) => c.get_db(),
            Conn::Cluster(c) => c.get_db(),
        }
    }
}

/// 业务作用:协议标记 key。
///
/// # 参数
/// - `namespace`: Redis key 使用的业务命名空间。
fn marker_key(namespace: &str) -> String {
    format!("nasa:protocol:{namespace}")
}

/// 业务作用:canonical 命名配置串:字段顺序固定、缺省值展开。
///**存完整 canonical 串做相等比对**,不再用 CRC16——16 位摘要碰撞域仅 65536,
/// 不同命名配置可能撞同摘要使 fail-closed 判重 **fail-open**(误配被当幂等放行)。CRC16 是校验位非
/// 抗碰撞摘要;完整串相等比对零碰撞,成本仅几十字节。
///
/// # 参数
/// - `cfg`: 配置对象,用于初始化组件或校验运行参数。
fn naming_config_canonical(cfg: &RedisConfig) -> String {
    let base = format!(
        "v1|profile={}|lock.prefix={}|partition.default_group={}|partition.count={}",
        cfg.profile.wire_name(),
        cfg.lock.prefix,
        cfg.partition.default_group,
        cfg.partition.count
    );
    //**多组 marker**——`partition.groups` 直接决定 topic 路由 / stream 前缀 / consumer
    // group 名 / lock·fence·disposition·DLQ key 命名空间 / cluster hash-tag,异构 groups 配置必须 fail-closed,
    // 否则同 namespace 一部分节点走隔离组、一部分走默认组 → 同 topic 物理队列分裂(高频/低频隔离最怕)。
    // **空 groups 逐字节保持旧 v1 串**(不破坏现存单组/legacy CRC16 部署);非空才追加稳定序列化 groups。
    if cfg.partition.groups.is_empty() {
        base
    } else {
        format!("{base}|partition.groups={}", canonical_groups(cfg))
    }
}

/// 业务作用:稳定序列化多组配置(label `partition.groups`)。**结构化 JSON**(非手拼分隔符,含 `,`/`;`
/// 的 topic 会注入碰撞 fail-open;JSON 转义单射)。形态 `{default:<runtime>, groups:{逻辑名:<topics+runtime>}}`:
/// - **`default`**:默认组 resolved runtime(= 父级 PartitionCfg + 全局 StreamCfg;默认组也消费
///   所有未隔离 topic,其 rebalance/min_idle/drain/batch 等不一致同样致跨节点 liveness/背压/drain 判定分裂,
///   故默认组运行参数也必须进入 marker)。
/// - **`groups`**:各隔离组 resolved(topics 排序 + 空 topics 归一逻辑名 + count/runtime 取 override→父级/全局)。
///
/// 所有字段 resolved(`0 继承`与显式父级值同 canonical,不误 fail-closed);BTreeMap 排序键稳定。
///
/// # 参数
/// - `cfg`: 配置对象,用于初始化组件或校验运行参数。
fn canonical_groups(cfg: &RedisConfig) -> String {
    let p = &cfg.partition;
    let s = &cfg.stream;
    /// 保存 CanonRuntime 运行状态;用于管理后台任务和共享资源。
    #[derive(serde::Serialize)]
    struct CanonRuntime {
        count: u32,
        rebalance_ms: u64,
        min_idle_ms: u64,
        holds_check_interval_ms: u64,
        drain_timeout_ms: u64,
        handler_timeout_ms: u64,
        max_redeliver: u32,
        poison_policy: crate::config::PoisonPolicy,
        batch_size: usize,
        poll_timeout_ms: u64,
        inflight_max: usize,
    }
    /// 承载规范化后的分组名;用于统一 Redis 分组标记的比较口径。
    #[derive(serde::Serialize)]
    struct CanonGroup<'a> {
        topics: Vec<&'a str>,
        #[serde(flatten)]
        rt: CanonRuntime,
    }
    /// 承载规范化后的分片名;用于统一 Redis 分片标记的比较口径。
    #[derive(serde::Serialize)]
    struct CanonPartition<'a> {
        default: CanonRuntime,
        groups: std::collections::BTreeMap<&'a str, CanonGroup<'a>>,
    }
    // 默认组 resolved runtime = 父级 partition + 全局 stream(默认组无 per-group 覆盖)。
    let default = CanonRuntime {
        count: p.count,
        rebalance_ms: p.rebalance_ms,
        min_idle_ms: p.min_idle_ms,
        holds_check_interval_ms: p.holds_check_interval_ms,
        drain_timeout_ms: p.drain_timeout_ms,
        handler_timeout_ms: p.handler_timeout_ms,
        max_redeliver: p.max_redeliver,
        poison_policy: p.poison_policy,
        batch_size: s.batch_size,
        // validate 已拒绝 0;这里保留 `.max(1)` 只是防御性地确保 canonical 值与运行时有效值一致。
        poll_timeout_ms: s.poll_timeout_ms.max(1),
        inflight_max: s.inflight_max,
    };
    let mut groups: std::collections::BTreeMap<&str, CanonGroup> =
        std::collections::BTreeMap::new();
    for (logical, g) in &p.groups {
        let mut topics: Vec<&str> = if g.topics.is_empty() {
            vec![logical.as_str()] // 空 topics → 逻辑名即 topic(对照路由/validate)
        } else {
            g.topics.iter().map(|s| s.as_str()).collect()
        };
        topics.sort_unstable();
        groups.insert(
            logical.as_str(),
            CanonGroup {
                topics,
                rt: CanonRuntime {
                    count: if g.count > 0 {
                        g.count
                    } else {
                        p.count
                    },
                    rebalance_ms: g.rebalance_ms.unwrap_or(p.rebalance_ms),
                    min_idle_ms: g.min_idle_ms.unwrap_or(p.min_idle_ms),
                    holds_check_interval_ms: g
                        .holds_check_interval_ms
                        .unwrap_or(p.holds_check_interval_ms),
                    drain_timeout_ms: g.drain_timeout_ms.unwrap_or(p.drain_timeout_ms),
                    handler_timeout_ms: g.handler_timeout_ms.unwrap_or(p.handler_timeout_ms),
                    max_redeliver: g.max_redeliver.unwrap_or(p.max_redeliver),
                    poison_policy: g.poison_policy.unwrap_or(p.poison_policy),
                    batch_size: g.batch_size.unwrap_or(s.batch_size),
                    poll_timeout_ms: g.poll_timeout_ms.unwrap_or(s.poll_timeout_ms).max(1),
                    inflight_max: g.inflight_max.unwrap_or(s.inflight_max),
                },
            },
        );
    }
    serde_json::to_string(&CanonPartition { default, groups })
        .expect("canonical partition json 序列化不应失败")
}

/// 业务作用:兼容**旧格式 marker**( 升级前的 `{"profile":..,"naming_config_hash":"<crc16>"}`):
/// 升级到完整 canonical 串后,既有部署里残留的旧 marker **不应因格式变更被 fail-closed 拒启动**。
/// 旧 marker 仍按其 CRC16 语义校验(profile 相等 + hash==crc16(本节点 canonical));通过即放行(不重写)。
/// 新建一律写完整串(零碰撞);旧 marker 自然老化(删/重建后变新格式)。返回 true=旧 marker 校验通过。
///
/// # 参数
/// - `existing`: Redis 中已存在的协议标记或缓存值。
/// - `cfg`: 配置对象,用于初始化组件或校验运行参数。
fn legacy_marker_matches(existing: &str, cfg: &RedisConfig) -> bool {
    let Ok(v) = serde_json::from_str::<serde_json::Value>(existing) else {
        return false;
    };
    match (
        v.get("profile").and_then(|x| x.as_str()),
        v.get("naming_config_hash").and_then(|x| x.as_str()),
    ) {
        (Some(prof), Some(hash)) => {
            // profile 必须与本节点持久 wire 名相等;RustV2 与 LegacyV1 严格区分。
            if prof != cfg.profile.wire_name() {
                return false;
            }
            let canon = naming_config_canonical(cfg);
            let crc = |s: &str| format!("{:04x}", crate::keytag::crc16(s.as_bytes()));
            hash == crc(&canon)
        }
        _ => false,
    }
}

/// 业务作用:协议标记**语义相等**:把两边 parse 成 `serde_json::Value` 比较(键值集合相等,
/// 与键序无关)。先前依赖 serde_json 默认字母序做裸字符串相等,开启 preserve_order
/// 后键序变为声明序,旧部署里残留的字母序 marker 会被误判不一致——故改成语义比对。
/// parse 失败(非 JSON)退回原始字符串相等(保守)。
/// 构造协议标记 payload:`{"profile": <wire_name>, "naming_config": <canonical>}`。
/// profile 用**持久 wire 名**(`wire_name()`),而非枚举 Debug 名,保升级兼容。
///
/// # 参数
/// - `cfg`: 配置对象,用于初始化组件或校验运行参数。
fn marker_payload(cfg: &RedisConfig) -> String {
    serde_json::json!({
        "profile": cfg.profile.wire_name(),
        "naming_config": naming_config_canonical(cfg),
    })
    .to_string()
}

/// 业务作用:比较协议标记的语义等价性;用于兼容旧格式和新格式的启动校验。
///
/// # 参数
/// - `existing`: Redis 中已存在的协议标记或缓存值。
/// - `payload`: 当前配置生成的协议标记 JSON 字符串。
fn marker_semantically_equal(existing: &str, payload: &str) -> bool {
    match (
        serde_json::from_str::<serde_json::Value>(existing),
        serde_json::from_str::<serde_json::Value>(payload),
    ) {
        (Ok(a), Ok(b)) => a == b,
        _ => existing == payload,
    }
}

/// Redis 客户端。
pub struct RedisClient {
    cfg: RedisConfig,
    /// 连接管理器:clone 共享同一 socket,**断线后台自动重连**(direct command 角色,
    /// 连接角色表;裸 MultiplexedConnection 断线后不恢复,改用
    /// ConnectionManager)。**注意**:重连是后台进行的,**命中断开的
    /// 那一条命令仍会返回 IO 错误**(不是透明重试成功)——框架不能透明重试非幂等命令;
    /// 后续命令在重连完成后恢复。调用方必须自行处理首次 IO 错误 / ExecutionUnknown。
    conn: Conn,
    /// 底层 client:派生专用连接(Pub/Sub、阻塞命令)用(cluster 下为 seed 节点;classic pubsub 跨节点)。
    raw: redis::Client,
    /// 目标是否为 Cluster 模式;partition 多键脚本依赖 group 级 relayout 保证同槽。
    is_cluster: bool,
    /// **pipeline 专用 lane**:独立多路复用连接,与 direct/control/lock 隔离,
    /// 防大批量 pipeline 头阻塞共享连接。**惰性**——首次 pipeline 才建连(`pipeline.dedicated_conn=true` 时)。
    pipe_cell: tokio::sync::OnceCell<Conn>,
    /// Job 状态脚本专用 lane:与普通命令、Pipeline 和阻塞读取隔离,避免业务流量阻塞租约与完成提交。
    #[cfg(feature = "job")]
    job_control_cell: tokio::sync::OnceCell<Conn>,
    /// Job 心跳专用 lane:传输重建与截止内重发不能让其它状态脚本继承同一断链结局。
    #[cfg(feature = "job")]
    job_heartbeat_cell: tokio::sync::OnceCell<Conn>,
    /// 当前 Job source generation 的本地指标弱引用;运行时换代可替换,客户端不会反向延长其生命周期。
    #[cfg(feature = "job")]
    job_metrics: RwLock<Option<std::sync::Weak<crate::job::metrics::JobMetrics>>>,
    /// nonce 幂等计数运行时:惰性构造,只用基础命令的应用不承担布局解析与能力探测成本;
    /// 首次 `*_idempotent` 调用才解析共享 marker(见连接角色表的幂等计数零成本不变量)。
    pub(crate) idempotent:
        std::sync::OnceLock<crate::idempotent::runtime::IdempotentCounterRuntime>,
}

/// 业务作用:给建连 future 套整体 deadline(`ms=0` 不限)。超时返回 IoError(Redis 不可达
/// 时 `connect()` 不再永久 pending,启动 fail-fast 生效)。
///
/// # 参数
/// - `fut`: 需要在 Redis 执行上下文中运行的异步任务。
/// - `ms`: 毫秒时间值。
/// - `what`: 错误或超时日志中标识当前操作的名称。
async fn await_with_deadline<F, T>(
    fut: F,
    ms: u64,
    what: &str,
) -> std::result::Result<T, redis::RedisError>
where
    F: std::future::Future<Output = std::result::Result<T, redis::RedisError>>,
{
    if ms == 0 {
        return fut.await;
    }
    match tokio::time::timeout(Duration::from_millis(ms), fut).await {
        Ok(r) => r,
        Err(_) => Err(redis::RedisError::from((
            redis::ErrorKind::Io,
            "建连超时",
            format!("{what} 超过 {ms}ms 未就绪(Redis 不可达?)"),
        ))),
    }
}

/// 业务作用:把某建连阶段的底层 redis 错误包装成带阶段与脱敏 endpoint 的 [`NasaRedisError::ConnectProbe`]。
///
/// # 参数
/// - `stage`: 失败阶段词(`connect`/`topology`/`cluster-discovery`/`protocol-marker`)。
/// - `cfg`: 当前 Redis 配置,取其 `safe_endpoint()` 作定位信息(不含凭据)。
/// - `source`: 底层 redis 错误,原样保留为错误链根因。
fn connect_probe(
    stage: &'static str,
    cfg: &RedisConfig,
    source: redis::RedisError,
) -> NasaRedisError {
    NasaRedisError::ConnectProbe {
        stage,
        endpoint: cfg.safe_endpoint(),
        source,
    }
}

impl RedisClient {
    /// 业务作用:构造即就绪:建连接 → 校验/创建协议标记 → 返回 Arc。
    ///
    /// 各建连阶段的失败都经内部 `connect_probe` 标注阶段与脱敏 endpoint 并保留底层错误链,让启动
    /// 诊断能一次性定位是哪一步、什么根因;单连接建连/拓扑探测/标记读写的所有权语义保持不变。
    ///
    /// # 参数
    /// - `cfg`: Redis 连接、命名空间、profile 和各子模块运行参数。
    pub async fn connect(cfg: RedisConfig) -> Result<Arc<RedisClient>> {
        cfg.validate()?;
        let raw =
            redis::Client::open(cfg.url.as_str()).map_err(|e| connect_probe("connect", &cfg, e))?;
        //连接级 response_timeout——覆盖所有命令(含 partition runtime 绕过
        // `timed()` 的裸调用),Redis 黑洞时返错而非永久 pending。0 = 不限(escape hatch)。
        let resp_timeout = cfg.command.response_timeout_ms;
        //**建连本身**也要有 deadline——response_timeout 只覆盖已建连后的命令,
        // 建连 / `INFO cluster` 探测 / cluster `get_async_connection()` 若无超时,Redis 不可达/TCP 黑洞时
        // `connect()` 永久 pending、**启动 fail-fast 失效**。故:① builder 设 connection_timeout;
        // ② 整个建连过程再套 `tokio::time::timeout` 兜底(覆盖 DNS/builder 未覆盖处)。0 = 不限(escape hatch)。
        let mgr_cfg = {
            let mut c = redis::aio::ConnectionManagerConfig::new();
            if resp_timeout > 0 {
                let d = Duration::from_millis(resp_timeout);
                c = c
                    .set_response_timeout(Some(d))
                    .set_connection_timeout(Some(d));
            }
            c
        };
        // 先用单节点 ConnectionManager 探测拓扑(INFO cluster);再据此选 transport。
        let mut bootstrap = await_with_deadline(
            ConnectionManager::new_with_config(raw.clone(), mgr_cfg),
            resp_timeout,
            "ConnectionManager 建连",
        )
        .await
        .map_err(|e| connect_probe("connect", &cfg, e))?;

        //`cluster_enabled:1` 在 **`INFO`(cluster 段)**(不在 `CLUSTER INFO`)。
        // 检测到 Cluster 后必须使用 `cluster_async::ClusterConnection` 跟随 MOVED/ASK。
        // standalone 也须通过 INFO 明确返回 cluster_enabled:0;连接异常或 ACL 拒绝不构成拓扑证据。
        // 探测重试三次仍失败时拒绝启动,避免给 Cluster 建立无法处理 MOVED 的 Single 连接。
        let is_cluster = {
            let mut last_err = None;
            let mut detected = None;
            for attempt in 0..3 {
                match redis::cmd("INFO")
                    .arg("cluster")
                    .query_async::<String>(&mut bootstrap)
                    .await
                {
                    Ok(info) => {
                        detected = Some(info.contains("cluster_enabled:1"));
                        break;
                    }
                    Err(e) => {
                        tracing::warn!(attempt, err = %e, "`INFO cluster` 失败(连接故障),重试");
                        last_err = Some(e);
                        if resp_timeout > 0 {
                            tokio::time::sleep(Duration::from_millis(
                                (resp_timeout / 3).clamp(50, 500),
                            ))
                            .await;
                        }
                    }
                }
            }
            match detected {
                Some(b) => b,
                None => {
                    // fail-closed:重试耗尽仍失败 = 真·连接故障/节点不可达/ACL 禁 INFO,绝不静默降级
                    // standalone(否则目标实为 cluster 时会建出不跟 MOVED 的 Single → 运行期 MOVED 风暴)。
                    //:保留底层错误链 + `topology` 阶段,供启动诊断定位,不再把根因 to_string 后丢弃 source。
                    return Err(match last_err {
                        Some(e) => connect_probe("topology", &cfg, e),
                        None => NasaRedisError::Config(
                            "`INFO cluster` 拓扑探测失败且无底层错误可用(不应发生)".into(),
                        ),
                    });
                }
            }
        };
        let mut conn = if is_cluster {
            // Cluster transport 由 seed URL 触发拓扑发现,并跟随 MOVED/ASK 路由。
            // 同样设连接级 response_timeout(覆盖 cluster 下裸命令)。
            let mut builder = redis::cluster::ClusterClient::builder(vec![cfg.url.as_str()]);
            if resp_timeout > 0 {
                let d = Duration::from_millis(resp_timeout);
                builder = builder.response_timeout(d).connection_timeout(d);
            }
            let cc = builder
                .build()
                .map_err(|e| connect_probe("cluster-discovery", &cfg, e))?;
            tracing::info!(namespace = %cfg.namespace, "目标 Redis 为 Cluster 模式,启用 cluster_async transport(跟随 MOVED/ASK)");
            // cluster 建连也套整体 deadline(get_async_connection 触发拓扑发现,可能久挂)
            Conn::Cluster(
                await_with_deadline(cc.get_async_connection(), resp_timeout, "cluster 建连")
                    .await
                    .map_err(|e| connect_probe("cluster-discovery", &cfg, e))?,
            )
        } else {
            Conn::Single(bootstrap)
        };

        // ── 协议标记:SET NX 创建,已存在则校验──
        // 用 serde_json 构造 payload:naming_config 完整串里若含引号/反斜杠(prefix/group 自定义)
        // 也安全转义。比对走**语义相等**(parse 成 Value 比 key-value 集合,不依赖键序)——
        // serde_json 开 preserve_order 后键序 = 声明序,不再字母序,故不能再做裸字符串相等。
        let key = marker_key(&cfg.namespace);
        let payload = marker_payload(&cfg);
        let created: bool = redis::cmd("SET")
            .arg(&key)
            .arg(&payload)
            .arg("NX")
            .query_async::<Option<String>>(&mut conn)
            .await
            .map_err(|e| connect_probe("protocol-marker", &cfg, e))?
            .is_some();
        if !created {
            let existing: String = conn
                .get(&key)
                .await
                .map_err(|e| connect_probe("protocol-marker", &cfg, e))?;
            // 语义相等(新格式,键序无关)或旧格式 CRC16 校验通过(迁移兼容)即放行
            if !marker_semantically_equal(&existing, &payload)
                && !legacy_marker_matches(&existing, &cfg)
            {
                return Err(NasaRedisError::ProtocolMarker(format!(
                    "namespace={} 既有标记 {existing} 与本节点 {payload} 不一致——profile 或命名配置不符,拒绝启动",
                    cfg.namespace
                )));
            }
        } else {
            tracing::info!(namespace = %cfg.namespace, profile = ?cfg.profile, "协议标记已创建");
        }

        Ok(Arc::new(RedisClient {
            cfg,
            conn,
            raw,
            is_cluster,
            pipe_cell: tokio::sync::OnceCell::new(),
            #[cfg(feature = "job")]
            job_control_cell: tokio::sync::OnceCell::new(),
            #[cfg(feature = "job")]
            job_heartbeat_cell: tokio::sync::OnceCell::new(),
            #[cfg(feature = "job")]
            job_metrics: RwLock::new(None),
            idempotent: std::sync::OnceLock::new(),
        }))
    }

    /// 业务作用:返回目标是否为 Cluster 模式;partition 多键脚本通过 group 级 relayout 保证同槽。
    pub fn is_cluster(&self) -> bool {
        self.is_cluster
    }

    /// 业务作用:返回当前连接使用的兼容性 profile。
    pub fn profile(&self) -> CompatibilityProfile {
        self.cfg.profile
    }

    /// 业务作用:返回语言无关的逻辑数据源标识;持久键、任务身份和指标维度均使用该值。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:启动期已规范化并冻结的 source id,默认值为 `primary`。
    pub fn qualifier(&self) -> &str {
        &self.cfg.qualifier
    }

    /// 业务作用:返回当前客户端的冻结配置。
    pub fn config(&self) -> &RedisConfig {
        &self.cfg
    }

    /// 业务作用:direct command 连接(`Conn`:单节点 ConnectionManager 或 cluster ClusterConnection,
    /// clone 共享多路复用句柄 + 自动重连/重路由; 角色表第一行)。
    pub fn conn(&self) -> Conn {
        self.conn.clone()
    }

    /// 业务作用:**pipeline 专用连接**:`pipeline.dedicated_conn=true`(默认)时返回一条
    /// 与 direct/control/lock 隔离的独立多路复用连接(**惰性创建**,首次调用建连、之后 clone 复用);
    /// `=false` 则退回共享 `conn()`(旧行为)。pipeline 路径(`PipelineSession`/`AutoPipeline`)走此。
    pub(crate) async fn pipe_conn(&self) -> Result<Conn> {
        if !self.cfg.pipeline.dedicated_conn {
            return Ok(self.conn());
        }
        let c = self
            .pipe_cell
            .get_or_try_init(|| self.build_transport("pipeline 专用"))
            .await?;
        Ok(c.clone())
    }

    /// 业务作用:为单个 Job source 建立启用 RESP3 Push 的独占 Pub/Sub lane,通知断线与重订不影响控制命令。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:支持普通或 Sharded 订阅的连接与 Push 接收端;握手或拓扑建立失败时拒绝 source 启动。
    #[cfg(feature = "job")]
    pub(crate) async fn job_pubsub_conn(
        &self,
        push_sender: Arc<dyn redis::aio::AsyncPushSender>,
    ) -> Result<Conn> {
        let timeout_ms = self.cfg.command.response_timeout_ms;
        let conn = if self.is_cluster {
            let mut builder = redis::cluster::ClusterClient::builder(vec![self.cfg.url.as_str()])
                .use_protocol(redis::ProtocolVersion::RESP3)
                .push_sender(push_sender.clone());
            if timeout_ms > 0 {
                let timeout = Duration::from_millis(timeout_ms);
                builder = builder
                    .response_timeout(timeout)
                    .connection_timeout(timeout);
            }
            let client = builder.build().map_err(NasaRedisError::Redis)?;
            Conn::Cluster(
                await_with_deadline(
                    client.get_async_connection(),
                    timeout_ms,
                    "Job RESP3 Cluster lane 建连",
                )
                .await
                .map_err(NasaRedisError::Redis)?,
            )
        } else {
            let mut info = self
                .cfg
                .url
                .as_str()
                .into_connection_info()
                .map_err(NasaRedisError::Redis)?;
            let redis_settings = info
                .redis_settings()
                .clone()
                .set_protocol(redis::ProtocolVersion::RESP3);
            info = info.set_redis_settings(redis_settings);
            let client = redis::Client::open(info).map_err(NasaRedisError::Redis)?;
            let mut manager = redis::aio::ConnectionManagerConfig::new()
                .set_push_sender(push_sender)
                .set_automatic_resubscription();
            if timeout_ms > 0 {
                let timeout = Duration::from_millis(timeout_ms);
                manager = manager
                    .set_response_timeout(Some(timeout))
                    .set_connection_timeout(Some(timeout));
            }
            Conn::Single(
                await_with_deadline(
                    ConnectionManager::new_with_config(client, manager),
                    timeout_ms,
                    "Job RESP3 lane 建连",
                )
                .await
                .map_err(NasaRedisError::Redis)?,
            )
        };
        Ok(conn)
    }

    /// 业务作用:返回 Job 状态脚本独占的惰性连接,隔离租约、领取和完成提交与业务命令流量。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:首次调用建立独立 transport,后续复用其可克隆句柄;建连失败返回脱敏后的连接错误。
    #[cfg(feature = "job")]
    pub(crate) async fn job_control_conn(&self) -> Result<Conn> {
        let conn = self
            .job_control_cell
            .get_or_try_init(|| self.build_transport("Job control lane"))
            .await?;
        Ok(conn.clone())
    }

    /// 业务作用:返回 Job 心跳独占的惰性连接,使截止内重发不影响其它状态动作的结局分类。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:首次心跳建立独立 transport,后续复用可自动重连的句柄;建连失败返回传输错误。
    #[cfg(feature = "job")]
    pub(crate) async fn job_heartbeat_conn(&self) -> Result<Conn> {
        let conn = self
            .job_heartbeat_cell
            .get_or_try_init(|| self.build_transport("Job heartbeat lane"))
            .await?;
        Ok(conn.clone())
    }

    /// 业务作用:新建一条独立 transport(与 connect() 的主连接同款建法;供 pipeline lane 惰性建连)。
    ///
    /// # 参数
    /// - `what`: 错误或超时日志中标识当前操作的名称。
    ///
    /// 返回:按已探测拓扑建立独立单节点或 Cluster transport;建连或截止时间失败返回带操作归因的传输错误。
    async fn build_transport(&self, what: &str) -> Result<Conn> {
        let resp_timeout = self.cfg.command.response_timeout_ms;
        if self.is_cluster {
            let mut builder = redis::cluster::ClusterClient::builder(vec![self.cfg.url.as_str()]);
            if resp_timeout > 0 {
                let d = Duration::from_millis(resp_timeout);
                builder = builder.response_timeout(d).connection_timeout(d);
            }
            let cc = builder.build()?;
            let conn = await_with_deadline(
                cc.get_async_connection(),
                resp_timeout,
                &format!("{what} cluster 建连"),
            )
            .await?;
            Ok(Conn::Cluster(conn))
        } else {
            let mut mgr_cfg = redis::aio::ConnectionManagerConfig::new();
            if resp_timeout > 0 {
                let d = Duration::from_millis(resp_timeout);
                mgr_cfg = mgr_cfg
                    .set_response_timeout(Some(d))
                    .set_connection_timeout(Some(d));
            }
            let conn = await_with_deadline(
                ConnectionManager::new_with_config(self.raw.clone(), mgr_cfg),
                resp_timeout,
                &format!("{what} 建连"),
            )
            .await?;
            Ok(Conn::Single(conn))
        }
    }

    /// 业务作用:派生专用连接(Pub/Sub / 阻塞命令角色;调用方持有生命周期)。
    pub(crate) fn raw_client(&self) -> &redis::Client {
        &self.raw
    }

    /// 业务作用:派生一条**独立 transport**(与主连接同款建法),供 stream 阻塞订阅等【阻塞命令】专用。
    /// 关键:XREAD/XREADGROUP `BLOCK` 若走共享 `conn()` 会把并发命令排在阻塞响应之后,
    /// 故订阅任务持有自己的一条连接。cluster 下是独立 `ClusterConnection`(按 stream key slot 路由,非 seed 单连接)。
    /// 连接级 `response_timeout_ms`(默认 30s)照常生效——远大于典型 `block_ms`(500ms),不会误杀 `BLOCK`,
    /// 但网络真断时能让阻塞读返错、订阅任务据此重建连接。
    pub(crate) async fn dedicated_conn(&self, what: &str) -> Result<Conn> {
        self.build_transport(what).await
    }

    /// 业务作用:把客户端状态脚本事件绑定到当前 source generation 的固定指标容器。
    ///
    /// 参数说明:`metrics` 必须与本客户端对应的 canonical source 一致。
    ///
    /// 返回:无;新 generation 原子替换旧弱引用,客户端不拥有运行时生命周期。
    #[cfg(feature = "job")]
    pub(crate) fn attach_job_metrics(&self, metrics: &Arc<crate::job::metrics::JobMetrics>) {
        *self
            .job_metrics
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::downgrade(metrics));
    }

    /// 业务作用:记录控制面因目标 Redis 未缓存脚本而执行整文本回退,供 source 观测脚本缓存换代。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:无;运行时尚未绑定或已经结束时不建立游离指标。
    #[cfg(feature = "job")]
    pub(crate) fn record_job_script_reload(&self) {
        let metrics = self
            .job_metrics
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .as_ref()
            .and_then(std::sync::Weak::upgrade);
        if let Some(metrics) = metrics {
            metrics.add("redis_job_script_reload_total", 1);
        }
    }

    /// 业务作用:受控原始入口:不暴露 ConnectionManager 等底层类型,
    /// 调用方组装 redis::Cmd,本方法执行——逃生舱,非常规路径。
    /// 同样受 `command.timeout_ms` 约束,确保单命令逃生路径不会无限等待。
    ///
    /// # 参数
    /// - `cmd`: 底层 Redis 命令对象。
    pub async fn execute_raw<T: redis::FromRedisValue>(&self, cmd: &redis::Cmd) -> Result<T> {
        let mut c = self.conn();
        self.timed(cmd.query_async(&mut c)).await
    }

    /// 业务作用:低频健康探针(napp readiness 复用):执行 `PING` 判活。
    ///
    /// 成功表示连接可用且服务器响应;沿用 `command.timeout_ms` 单命令超时。只做只读判活,
    /// 不改变任何拓扑或数据。上层据此发布运行期就绪观测。
    ///
    /// # 返回
    ///
    /// 服务器正常应答返回 `Ok(())`;连接、超时或协议错误返回 `Err`。
    pub async fn ping(&self) -> Result<()> {
        self.execute_raw::<redis::Value>(&redis::cmd("PING"))
            .await
            .map(|_| ())
    }

    /// 业务作用:显式停机:multiplexed 连接随 Arc 释放;此处为对称占位,
    /// 高级设施(锁看门狗等)各自持 CancellationToken 自行退出。
    pub async fn shutdown(&self) {
        tracing::info!(namespace = %self.cfg.namespace, "RedisClient shutdown");
    }
}

/// 显式注册表(重复 qualifier 拒绝、注销;主要注入方式仍是显式传 Arc)。
#[derive(Default)]
pub struct RedisRegistry {
    map: RwLock<HashMap<String, Arc<RedisClient>>>,
}

impl RedisRegistry {
    /// 业务作用:创建空的命名客户端注册表。
    pub fn new() -> Self {
        Self::default()
    }

    /// 业务作用:注册;重复 qualifier 返回错误(不静默覆盖)。
    ///锁中毒**恢复**而非 panic——表内只存 `Arc` clone,panic 不会留下不一致状态,
    /// `into_inner()` 拿回守卫继续用,比让整个注册表 API 在一次无关 panic 后全 panic 稳健。
    ///
    /// # 参数
    /// - `qualifier`: 客户端在注册表中的唯一业务名。
    /// - `client`: 要注册的 Redis 客户端共享句柄。
    pub fn register(&self, qualifier: &str, client: Arc<RedisClient>) -> Result<()> {
        if qualifier != client.qualifier() {
            return Err(NasaRedisError::Config(format!(
                "注册表 key {qualifier} 与 RedisClient qualifier {} 不一致",
                client.qualifier()
            )));
        }
        let mut m = self.map.write().unwrap_or_else(|e| e.into_inner());
        if m.contains_key(qualifier) {
            return Err(NasaRedisError::Config(format!(
                "qualifier 重复注册: {qualifier}"
            )));
        }
        m.insert(qualifier.to_string(), client);
        Ok(())
    }

    /// 业务作用:返回指定 qualifier 对应的 Redis 客户端。
    ///
    /// # 参数
    /// - `qualifier`: 注册时使用的唯一业务名。
    pub fn get(&self, qualifier: &str) -> Option<Arc<RedisClient>> {
        self.map
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .get(qualifier)
            .cloned()
    }

    /// 业务作用:注销指定 qualifier 对应的 Redis 客户端。
    ///
    /// # 参数
    /// - `qualifier`: 要从注册表移除的唯一业务名。
    pub fn deregister(&self, qualifier: &str) -> Option<Arc<RedisClient>> {
        self.map
            .write()
            .unwrap_or_else(|e| e.into_inner())
            .remove(qualifier)
    }
}