zenith-net 0.1.0

Zenith 网络地址与传输层抽象:L2-L4 协议解析、TCP/UDP/QUIC 状态机、来源准入引擎、单队列 Worker 数据面循环
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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
//! UDP 双模式实现
//!
//! 支持两种 UDP 工作模式:
//! 1. 无状态模式:直接转发,无会话跟踪(高性能)
//! 2. 有状态模式:维护 UDP 会话(防火墙/NAT 场景)
//!
//! 设计约束:
//! - 预分配会话表,硬上限
//! - 单 Owner,零堆分配热路径
//! - O(1) 会话查找
//! - 超时自动回收

use crate::error::NetError;
use crate::packet::{IpVersion};
use crate::source_admission::IpAddr;

/// UDP 工作模式
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UdpMode {
    /// 无状态(直接转发,零会话开销)
    Stateless,
    /// 有状态(跟踪会话,超时回收)
    Stateful,
}

/// UDP 会话(有状态模式)
#[derive(Debug, Clone, Copy)]
pub struct UdpSession {
    /// 源 IP
    pub src_ip: IpAddr,
    /// 源端口
    pub src_port: u16,
    /// 目标 IP
    pub dst_ip: IpAddr,
    /// 目标端口
    pub dst_port: u16,
    /// IP 版本
    pub ip_version: IpVersion,
    /// 创建时间戳
    pub created_at: u64,
    /// 最近活动时间戳
    pub last_active: u64,
    /// 入站包计数
    pub inbound_count: u64,
    /// 出站包计数
    pub outbound_count: u64,
    /// 是否活跃
    pub active: bool,
}

impl UdpSession {
    /// 创建空会话(未激活)
    #[inline]
    pub fn empty() -> Self {
        Self {
            src_ip: IpAddr::V4([0; 4]),
            src_port: 0,
            dst_ip: IpAddr::V4([0; 4]),
            dst_port: 0,
            ip_version: IpVersion::V4,
            created_at: 0,
            last_active: 0,
            inbound_count: 0,
            outbound_count: 0,
            active: false,
        }
    }

    /// 激活会话
    #[inline]
    pub fn activate(
        &mut self,
        src_ip: IpAddr,
        src_port: u16,
        dst_ip: IpAddr,
        dst_port: u16,
        ip_version: IpVersion,
        now: u64,
    ) {
        self.src_ip = src_ip;
        self.src_port = src_port;
        self.dst_ip = dst_ip;
        self.dst_port = dst_port;
        self.ip_version = ip_version;
        self.created_at = now;
        self.last_active = now;
        self.inbound_count = 0;
        self.outbound_count = 0;
        self.active = true;
    }

    /// 更新活动时间
    #[inline]
    pub fn touch(&mut self, now: u64) {
        self.last_active = now;
    }

    /// 记录入站包
    #[inline]
    pub fn record_inbound(&mut self) {
        self.inbound_count += 1;
    }

    /// 记录出站包
    #[inline]
    pub fn record_outbound(&mut self) {
        self.outbound_count += 1;
    }

    /// 是否超时
    #[inline]
    pub fn is_expired(&self, now: u64, timeout_ms: u64) -> bool {
        self.active && now.saturating_sub(self.last_active) > timeout_ms
    }

    /// 是否匹配四元组
    #[inline]
    pub fn matches(
        &self,
        src_ip: IpAddr,
        src_port: u16,
        dst_ip: IpAddr,
        dst_port: u16,
        ip_version: IpVersion,
    ) -> bool {
        self.active
            && self.src_ip == src_ip
            && self.src_port == src_port
            && self.dst_ip == dst_ip
            && self.dst_port == dst_port
            && self.ip_version == ip_version
    }

    /// 获取反向匹配键(响应包查找)
    #[inline]
    pub fn reverse_matches(
        &self,
        src_ip: IpAddr,
        src_port: u16,
        dst_ip: IpAddr,
        dst_port: u16,
        ip_version: IpVersion,
    ) -> bool {
        self.active
            && self.src_ip == dst_ip
            && self.src_port == dst_port
            && self.dst_ip == src_ip
            && self.dst_port == src_port
            && self.ip_version == ip_version
    }
}

/// UDP 统计信息
#[derive(Debug, Clone, Copy, Default)]
pub struct UdpStats {
    /// 总会话数
    pub total_sessions: u64,
    /// 活跃会话数
    pub active_sessions: u64,
    /// 入站包计数
    pub inbound_packets: u64,
    /// 出站包计数
    pub outbound_packets: u64,
    /// 会话超时回收数
    pub session_timeouts: u64,
    /// 拒绝包数
    pub rejected: u64,
}

/// 最大 UDP 会话数(硬上限)
pub const MAX_SESSIONS: usize = 32768;

/// 哈希桶数量(必须为 2 的幂)
pub const SESSION_BUCKETS: usize = 8192;

/// UDP 会话表(预分配,零堆分配)
///
/// # 与 [`crate::transport::tcp::ConnectionTable`] 的关系(泛型化评估结论)
/// 两者同为「预分配槽数组 + u32 桶开放寻址 + 线性探测」骨架,但此处
/// **有意保持单态化副本以保内联**,不做泛型化,原因:
/// - 插入语义不同:TCP 侧插入时会复用指向 CLOSED 槽的桶,本表无此逻辑;
/// - 槽类型、空闲判定(`!active` vs `state == Closed`)、键提取方式均不同,
///   泛型化只能以闭包/trait 钩子参数化,虽静态分发但阻碍编译期内联优化;
/// - 桶数常量不同([`SESSION_BUCKETS`] = 8192 vs TCP 侧 16384),
///   且本表在无状态模式下容量为 0(TCP 侧最小为 1)。
///
/// 两侧共享的部分(IP 折叠哈希、五元组哈希)已提取至
/// [`crate::transport::hash_flow_tuple`]。
#[derive(Debug)]
pub struct UdpSessionTable {
    /// 模式
    mode: UdpMode,
    /// 会话槽数组(预分配)
    sessions: Vec<UdpSession>,
    /// 哈希桶(存储会话索引,0 表示空)
    buckets: Vec<u32>,
    /// 已使用会话数
    count: usize,
    /// 最大容量
    capacity: usize,
    /// 统计信息
    stats: UdpStats,
}

impl UdpSessionTable {
    /// 创建会话表
    ///
    /// # 参数
    /// * `mode` - UDP 工作模式
    /// * `capacity` - 最大会话数(硬上限,仅对有状态模式有效)
    pub fn new(mode: UdpMode, capacity: usize) -> Self {
        let cap = if mode == UdpMode::Stateful {
            capacity.clamp(1, MAX_SESSIONS)
        } else {
            0 // 无状态模式不需要会话表
        };
        let mut sessions = Vec::with_capacity(cap);
        for _ in 0..cap {
            sessions.push(UdpSession::empty());
        }
        let buckets = vec![0u32; SESSION_BUCKETS];
        Self {
            mode,
            sessions,
            buckets,
            count: 0,
            capacity: cap,
            stats: UdpStats::default(),
        }
    }

    /// 获取模式
    #[inline]
    pub fn mode(&self) -> UdpMode {
        self.mode
    }

    /// 获取统计信息
    #[inline]
    pub fn stats(&self) -> UdpStats {
        self.stats
    }

    /// 获取当前会话数
    #[inline]
    pub fn count(&self) -> usize {
        self.count
    }

    /// 计算哈希(使用折叠哈希)
    ///
    /// 实现委托给 transport 层共享的 [`crate::transport::hash_flow_tuple`]
    /// (与 TCP 连接表同源,禁止复制实现)。
    #[inline]
    fn compute_hash(
        &self,
        src_ip: IpAddr,
        src_port: u16,
        dst_ip: IpAddr,
        dst_port: u16,
        ip_version: IpVersion,
    ) -> u64 {
        super::hash_flow_tuple(&src_ip, src_port, &dst_ip, dst_port, ip_version)
    }

    /// 查找会话(O(1))
    ///
    /// # 返回
    /// * `Option<usize>` - 会话索引
    #[inline]
    pub fn find_session(
        &self,
        src_ip: IpAddr,
        src_port: u16,
        dst_ip: IpAddr,
        dst_port: u16,
        ip_version: IpVersion,
    ) -> Option<usize> {
        if self.mode == UdpMode::Stateless {
            return None; // 无状态模式直接返回 None
        }

        let hash = self.compute_hash(src_ip, src_port, dst_ip, dst_port, ip_version);
        let bucket_idx = (hash as usize) & (SESSION_BUCKETS - 1);
        let mut i = bucket_idx;
        let mut probe = 0;

        loop {
            let raw = self.buckets[i];
            if raw == 0 {
                return None;
            }
            let real_idx = (raw as usize) - 1;
            let session = &self.sessions[real_idx];
            if session.matches(src_ip, src_port, dst_ip, dst_port, ip_version) {
                return Some(real_idx);
            }
            probe += 1;
            if probe >= SESSION_BUCKETS {
                return None;
            }
            i = (i + 1) & (SESSION_BUCKETS - 1);
        }
    }

    /// 查找反向会话(用于响应包路由)
    #[inline]
    pub fn find_reverse_session(
        &self,
        src_ip: IpAddr,
        src_port: u16,
        dst_ip: IpAddr,
        dst_port: u16,
        ip_version: IpVersion,
    ) -> Option<usize> {
        if self.mode == UdpMode::Stateless {
            return None;
        }

        // 反转四元组查找
        self.find_session(dst_ip, dst_port, src_ip, src_port, ip_version)
    }

    /// 创建新会话
    ///
    /// # 返回
    /// * `Result<usize, NetError>` - 会话索引
    pub fn create_session(
        &mut self,
        src_ip: IpAddr,
        src_port: u16,
        dst_ip: IpAddr,
        dst_port: u16,
        ip_version: IpVersion,
        now: u64,
    ) -> Result<usize, NetError> {
        // 无状态模式不应调用此方法
        if self.mode == UdpMode::Stateless {
            return Err(NetError::InvalidOperation {
                reason: "Cannot create session in stateless mode".to_string(),
            });
        }

        // 检查容量
        if self.count >= self.capacity {
            return Err(NetError::ConnectionTableFull {
                capacity: self.capacity,
            });
        }

        // 查找空闲槽(fail-closed:满表返回错误,绝不静默复用槽 0)
        let slot_idx = self.find_free_session().ok_or(NetError::ConnectionTableFull {
            capacity: self.capacity,
        })?;

        // 插入哈希表
        let hash = self.compute_hash(src_ip, src_port, dst_ip, dst_port, ip_version);
        let bucket_idx = (hash as usize) & (SESSION_BUCKETS - 1);
        let mut i = bucket_idx;
        let mut probe = 0;

        loop {
            if self.buckets[i] == 0 {
                self.buckets[i] = (slot_idx as u32) + 1;
                break;
            }
            probe += 1;
            if probe >= SESSION_BUCKETS {
                return Err(NetError::HashTableFull);
            }
            i = (i + 1) & (SESSION_BUCKETS - 1);
        }

        // 激活会话
        self.sessions[slot_idx].activate(
            src_ip, src_port, dst_ip, dst_port, ip_version, now,
        );
        self.count += 1;
        self.stats.total_sessions += 1;
        self.stats.active_sessions += 1;

        Ok(slot_idx)
    }

    /// 查找空闲会话槽
    ///
    /// # 返回
    /// * `Some(idx)` - 空闲槽索引
    /// * `None` - 表已满(调用方须 fail-closed,禁止静默复用槽 0)
    #[inline]
    fn find_free_session(&self) -> Option<usize> {
        (0..self.capacity).find(|&i| !self.sessions[i].active)
    }

    /// 获取会话引用
    #[inline]
    pub fn get_session(&self, idx: usize) -> Option<&UdpSession> {
        if idx < self.sessions.len() {
            Some(&self.sessions[idx])
        } else {
            None
        }
    }

    /// 获取会话可变引用
    #[inline]
    pub fn get_session_mut(&mut self, idx: usize) -> Option<&mut UdpSession> {
        if idx < self.sessions.len() {
            Some(&mut self.sessions[idx])
        } else {
            None
        }
    }

    /// 处理入站 UDP 包
    ///
    /// # 参数
    /// * `src_ip` - 源 IP
    /// * `src_port` - 源端口
    /// * `dst_ip` - 目标 IP
    /// * `dst_port` - 目标端口
    /// * `ip_version` - IP 版本
    /// * `now` - 当前时间戳
    ///
    /// # 返回
    /// * `UdpAction` - 应采取的动作
    pub fn handle_inbound(
        &mut self,
        src_ip: IpAddr,
        src_port: u16,
        dst_ip: IpAddr,
        dst_port: u16,
        ip_version: IpVersion,
        now: u64,
    ) -> UdpAction {
        self.stats.inbound_packets += 1;

        match self.mode {
            UdpMode::Stateless => UdpAction::Forward,
            UdpMode::Stateful => {
                // 查找现有会话
                if let Some(idx) = self.find_session(src_ip, src_port, dst_ip, dst_port, ip_version) {
                    if let Some(session) = self.get_session_mut(idx) {
                        session.touch(now);
                        session.record_inbound();
                    }
                    UdpAction::Forward
                } else {
                    // 创建新会话
                    match self.create_session(
                        src_ip, src_port, dst_ip, dst_port, ip_version, now,
                    ) {
                        Ok(idx) => {
                            // 新会话也记录入站
                            if let Some(session) = self.get_session_mut(idx) {
                                session.record_inbound();
                            }
                            UdpAction::Forward
                        }
                        Err(_) => {
                            self.stats.rejected += 1;
                            UdpAction::Drop
                        }
                    }
                }
            }
        }
    }

    /// 处理出站 UDP 包
    ///
    /// # 参数
    /// * `src_ip` - 源 IP
    /// * `src_port` - 源端口
    /// * `dst_ip` - 目标 IP
    /// * `dst_port` - 目标端口
    /// * `ip_version` - IP 版本
    /// * `now` - 当前时间戳
    ///
    /// # 返回
    /// * `UdpAction` - 应采取的动作
    pub fn handle_outbound(
        &mut self,
        src_ip: IpAddr,
        src_port: u16,
        dst_ip: IpAddr,
        dst_port: u16,
        ip_version: IpVersion,
        now: u64,
    ) -> UdpAction {
        self.stats.outbound_packets += 1;

        match self.mode {
            UdpMode::Stateless => UdpAction::Forward,
            UdpMode::Stateful => {
                // 查找反向会话(用于 NAT 映射)
                if let Some(idx) =
                    self.find_reverse_session(src_ip, src_port, dst_ip, dst_port, ip_version)
                {
                    if let Some(session) = self.get_session_mut(idx) {
                        session.touch(now);
                        session.record_outbound();
                    }
                    UdpAction::Forward
                } else {
                    // 没有对应会话,可能是新出站流
                    match self.create_session(
                        src_ip, src_port, dst_ip, dst_port, ip_version, now,
                    ) {
                        Ok(idx) => {
                            if let Some(session) = self.get_session_mut(idx) {
                                session.record_outbound();
                            }
                            UdpAction::Forward
                        }
                        Err(_) => {
                            self.stats.rejected += 1;
                            UdpAction::Drop
                        }
                    }
                }
            }
        }
    }

    /// 基于时间戳的超时扫描(兼容性方法)
    ///
    /// # Arguments
    /// * `now` - 当前时间戳
    /// * `timeout_ms` - 超时阈值
    pub fn scan_timeouts(&mut self, now: u64, timeout_ms: u64) -> usize {
        if self.mode == UdpMode::Stateless {
            return 0;
        }

        let mut expired_count = 0;
        for session in self.sessions.iter_mut() {
            if session.is_expired(now, timeout_ms) {
                session.active = false;
                expired_count += 1;
            }
        }

        if expired_count > 0 {
            self.count = self.count.saturating_sub(expired_count);
            self.stats.session_timeouts += expired_count as u64;
            self.stats.active_sessions = self.stats.active_sessions.saturating_sub(expired_count as u64);
            self.rebuild_hash();
        }

        expired_count
    }

    /// 重建哈希表
    fn rebuild_hash(&mut self) {
        self.buckets.fill(0);
        for i in 0..self.sessions.len() {
            if self.sessions[i].active {
                let s = &self.sessions[i];
                let hash =
                    self.compute_hash(s.src_ip, s.src_port, s.dst_ip, s.dst_port, s.ip_version);
                let bucket_idx = (hash as usize) & (SESSION_BUCKETS - 1);
                let mut idx = bucket_idx;
                let mut probe = 0;
                loop {
                    if self.buckets[idx] == 0 {
                        self.buckets[idx] = (i as u32) + 1;
                        break;
                    }
                    probe += 1;
                    if probe >= SESSION_BUCKETS {
                        break;
                    }
                    idx = (idx + 1) & (SESSION_BUCKETS - 1);
                }
            }
        }
    }

    /// 遍历活跃会话
    pub fn iter_active(&self) -> impl Iterator<Item = &UdpSession> {
        self.sessions.iter().filter(|s| s.active)
    }
}

/// UDP 动作
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UdpAction {
    /// 直接转发
    Forward,
    /// 丢弃
    Drop,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn v4(ip: [u8; 4]) -> IpAddr {
        IpAddr::V4(ip)
    }

    #[test]
    fn test_udp_session_activate() {
        let mut session = UdpSession::empty();
        session.activate(v4([10, 0, 0, 1]), 8080, v4([10, 0, 0, 2]), 1234, IpVersion::V4, 1000);

        assert!(session.active);
        assert_eq!(session.src_ip, v4([10, 0, 0, 1]));
        assert_eq!(session.src_port, 8080);
        assert_eq!(session.dst_ip, v4([10, 0, 0, 2]));
        assert_eq!(session.dst_port, 1234);
        assert_eq!(session.created_at, 1000);
        assert_eq!(session.inbound_count, 0);
    }

    #[test]
    fn test_udp_session_matches() {
        let mut session = UdpSession::empty();
        session.activate(v4([10, 0, 0, 1]), 8080, v4([10, 0, 0, 2]), 1234, IpVersion::V4, 1000);

        // 精确匹配
        assert!(session.matches(v4([10, 0, 0, 1]), 8080, v4([10, 0, 0, 2]), 1234, IpVersion::V4));

        // 不匹配
        assert!(!session.matches(v4([10, 0, 0, 1]), 9090, v4([10, 0, 0, 2]), 1234, IpVersion::V4));

        // 反向匹配
        assert!(session.reverse_matches(v4([10, 0, 0, 2]), 1234, v4([10, 0, 0, 1]), 8080, IpVersion::V4));
    }

    #[test]
    fn test_udp_session_expiry() {
        let mut session = UdpSession::empty();
        session.activate(v4([10, 0, 0, 1]), 8080, v4([10, 0, 0, 2]), 1234, IpVersion::V4, 1000);

        // 未超时
        assert!(!session.is_expired(1500, 1000));

        // 超时
        assert!(session.is_expired(2100, 1000));

        // 未激活的会话永不超时
        let empty = UdpSession::empty();
        assert!(!empty.is_expired(99999, 0));
    }

    #[test]
    fn test_udp_session_table_stateless() {
        let mut table = UdpSessionTable::new(UdpMode::Stateless, 1024);

        assert_eq!(table.mode(), UdpMode::Stateless);

        // 无状态模式应直接 Forward
        let action = table.handle_inbound(
            v4([10, 0, 0, 1]),
            8080,
            v4([10, 0, 0, 2]),
            1234,
            IpVersion::V4,
            1000,
        );
        assert_eq!(action, UdpAction::Forward);
        assert_eq!(table.stats().inbound_packets, 1);

        // 查找会话应返回 None
        assert!(table.find_session(
            v4([10, 0, 0, 1]),
            8080,
            v4([10, 0, 0, 2]),
            1234,
            IpVersion::V4,
        ).is_none());
    }

    #[test]
    fn test_udp_session_table_stateful() {
        let mut table = UdpSessionTable::new(UdpMode::Stateful, 1024);

        assert_eq!(table.mode(), UdpMode::Stateful);

        // 第一次包:创建会话
        let action = table.handle_inbound(
            v4([10, 0, 0, 1]),
            8080,
            v4([10, 0, 0, 2]),
            1234,
            IpVersion::V4,
            1000,
        );
        assert_eq!(action, UdpAction::Forward);
        assert_eq!(table.count(), 1);
        assert_eq!(table.stats().total_sessions, 1);

        // 第二次相同包:找到已有会话
        let action2 = table.handle_inbound(
            v4([10, 0, 0, 1]),
            8080,
            v4([10, 0, 0, 2]),
            1234,
            IpVersion::V4,
            1001,
        );
        assert_eq!(action2, UdpAction::Forward);
        assert_eq!(table.count(), 1); // 不应增加

        // 验证会话信息已更新
        let idx = table.find_session(
            v4([10, 0, 0, 1]),
            8080,
            v4([10, 0, 0, 2]),
            1234,
            IpVersion::V4,
        ).unwrap();
        let session = table.get_session(idx).unwrap();
        assert_eq!(session.inbound_count, 2);
        assert_eq!(session.last_active, 1001);
    }

    #[test]
    fn test_udp_session_table_outbound() {
        let mut table = UdpSessionTable::new(UdpMode::Stateful, 1024);

        // 创建入站会话
        table.handle_inbound(
            v4([10, 0, 0, 1]),
            8080,
            v4([10, 0, 0, 2]),
            1234,
            IpVersion::V4,
            1000,
        );

        // 出站包(从会话目标返回)应找到反向会话
        let action = table.handle_outbound(
            v4([10, 0, 0, 2]),
            1234,
            v4([10, 0, 0, 1]),
            8080,
            IpVersion::V4,
            1002,
        );
        assert_eq!(action, UdpAction::Forward);

        // 验证出站计数
        let idx = table.find_session(
            v4([10, 0, 0, 1]),
            8080,
            v4([10, 0, 0, 2]),
            1234,
            IpVersion::V4,
        ).unwrap();
        let session = table.get_session(idx).unwrap();
        assert_eq!(session.outbound_count, 1);
    }

    #[test]
    fn test_udp_session_timeout_scan() {
        let mut table = UdpSessionTable::new(UdpMode::Stateful, 1024);

        // 创建会话
        table.handle_inbound(
            v4([10, 0, 0, 1]),
            8080,
            v4([10, 0, 0, 2]),
            1234,
            IpVersion::V4,
            1000,
        );
        table.handle_inbound(
            v4([10, 0, 0, 3]),
            9090,
            v4([10, 0, 0, 4]),
            5678,
            IpVersion::V4,
            1000,
        );

        assert_eq!(table.count(), 2);

        // 超时扫描
        let expired = table.scan_timeouts(2000, 500); // 500ms 超时
        assert_eq!(expired, 2);
        assert_eq!(table.count(), 0);
        assert_eq!(table.stats().session_timeouts, 2);
    }

    #[test]
    fn test_udp_session_table_full() {
        let mut table = UdpSessionTable::new(UdpMode::Stateful, 4);

        // 填满会话表
        for i in 0..4u16 {
            table.handle_inbound(
                v4([10, 0, 0, i as u8]),
                8000 + i,
                v4([10, 0, 0, 2]),
                1234,
                IpVersion::V4,
                1000 + i as u64,
            );
        }
        assert_eq!(table.count(), 4);

        // 第 5 个应被拒绝
        let action = table.handle_inbound(
            v4([10, 0, 0, 100]),
            9999,
            v4([10, 0, 0, 2]),
            1234,
            IpVersion::V4,
            2000,
        );
        assert_eq!(action, UdpAction::Drop);
        assert_eq!(table.stats().rejected, 1);
    }

    #[test]
    fn test_udp_session_iterator() {
        let mut table = UdpSessionTable::new(UdpMode::Stateful, 1024);

        table.handle_inbound(
            v4([10, 0, 0, 1]),
            8080,
            v4([10, 0, 0, 2]),
            1234,
            IpVersion::V4,
            1000,
        );
        table.handle_inbound(
            v4([10, 0, 0, 3]),
            9090,
            v4([10, 0, 0, 4]),
            5678,
            IpVersion::V4,
            1000,
        );

        let active: Vec<&UdpSession> = table.iter_active().collect();
        assert_eq!(active.len(), 2);
    }

    #[test]
    fn test_udp_session_empty() {
        let session = UdpSession::empty();
        assert!(!session.active);
        assert_eq!(session.inbound_count, 0);
        assert_eq!(session.outbound_count, 0);
        assert_eq!(session.created_at, 0);
        assert_eq!(session.last_active, 0);
        assert!(!session.is_expired(1000, 100));
    }

    #[test]
    fn test_udp_session_touch() {
        let mut session = UdpSession::empty();
        session.activate(v4([10, 0, 0, 1]), 8080, v4([10, 0, 0, 2]), 1234, IpVersion::V4, 1000);
        assert_eq!(session.last_active, 1000);

        session.touch(2000);
        assert_eq!(session.last_active, 2000);
    }

    #[test]
    fn test_udp_session_record_counts() {
        let mut session = UdpSession::empty();
        session.activate(v4([10, 0, 0, 1]), 8080, v4([10, 0, 0, 2]), 1234, IpVersion::V4, 1000);

        session.record_inbound();
        session.record_inbound();
        session.record_outbound();

        assert_eq!(session.inbound_count, 2);
        assert_eq!(session.outbound_count, 1);
    }

    #[test]
    fn test_udp_session_not_active_no_match() {
        let session = UdpSession::empty();
        assert!(!session.matches(v4([10, 0, 0, 1]), 8080, v4([10, 0, 0, 2]), 1234, IpVersion::V4));
        assert!(!session.reverse_matches(v4([10, 0, 0, 2]), 1234, v4([10, 0, 0, 1]), 8080, IpVersion::V4));
    }

    #[test]
    fn test_udp_session_ipv6() {
        let mut session = UdpSession::empty();
        let ip1 = IpAddr::V6([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
        let ip2 = IpAddr::V6([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]);
        session.activate(ip1, 8080, ip2, 1234, IpVersion::V6, 1000);

        assert!(session.matches(ip1, 8080, ip2, 1234, IpVersion::V6));
        assert!(session.reverse_matches(ip2, 1234, ip1, 8080, IpVersion::V6));
        assert!(!session.matches(ip1, 8080, ip2, 1234, IpVersion::V4));
    }

    #[test]
    fn test_udp_session_table_mode() {
        let stateless = UdpSessionTable::new(UdpMode::Stateless, 1024);
        assert_eq!(stateless.mode(), UdpMode::Stateless);

        let stateful = UdpSessionTable::new(UdpMode::Stateful, 1024);
        assert_eq!(stateful.mode(), UdpMode::Stateful);
    }

    #[test]
    fn test_udp_session_table_find_reverse() {
        let mut table = UdpSessionTable::new(UdpMode::Stateful, 1024);

        table.handle_inbound(
            v4([10, 0, 0, 1]),
            8080,
            v4([10, 0, 0, 2]),
            1234,
            IpVersion::V4,
            1000,
        );

        let forward = table.find_session(
            v4([10, 0, 0, 1]),
            8080,
            v4([10, 0, 0, 2]),
            1234,
            IpVersion::V4,
        );
        assert!(forward.is_some());

        let reverse = table.find_reverse_session(
            v4([10, 0, 0, 2]),
            1234,
            v4([10, 0, 0, 1]),
            8080,
            IpVersion::V4,
        );
        assert!(reverse.is_some());
        assert_eq!(forward, reverse);
    }

    #[test]
    fn test_udp_session_table_get_out_of_bounds() {
        let table = UdpSessionTable::new(UdpMode::Stateful, 1024);
        assert!(table.get_session(1024).is_none());
        assert!(table.get_session(9999).is_none());
    }

    #[test]
    fn test_udp_session_table_get_mut_out_of_bounds() {
        let mut table = UdpSessionTable::new(UdpMode::Stateful, 1024);
        assert!(table.get_session_mut(1024).is_none());
        assert!(table.get_session_mut(9999).is_none());
    }

    #[test]
    fn test_udp_stats_default() {
        let stats = UdpStats::default();
        assert_eq!(stats.total_sessions, 0);
        assert_eq!(stats.active_sessions, 0);
        assert_eq!(stats.inbound_packets, 0);
        assert_eq!(stats.outbound_packets, 0);
        assert_eq!(stats.session_timeouts, 0);
        assert_eq!(stats.rejected, 0);
    }

    #[test]
    fn test_udp_session_table_stats_initial() {
        let table = UdpSessionTable::new(UdpMode::Stateful, 1024);
        let stats = table.stats();
        assert_eq!(stats.total_sessions, 0);
        assert_eq!(stats.active_sessions, 0);
    }

    #[test]
    fn test_udp_stateless_outbound() {
        let mut table = UdpSessionTable::new(UdpMode::Stateless, 1024);

        let action = table.handle_outbound(
            v4([10, 0, 0, 2]),
            1234,
            v4([10, 0, 0, 1]),
            8080,
            IpVersion::V4,
            1000,
        );
        assert_eq!(action, UdpAction::Forward);
        assert_eq!(table.stats().outbound_packets, 1);
    }

    #[test]
    fn test_udp_stateful_outbound_no_session() {
        let mut table = UdpSessionTable::new(UdpMode::Stateful, 1024);

        let action = table.handle_outbound(
            v4([10, 0, 0, 2]),
            1234,
            v4([10, 0, 0, 1]),
            8080,
            IpVersion::V4,
            1000,
        );
        assert_eq!(action, UdpAction::Forward);
        assert_eq!(table.count(), 1);
    }

    #[test]
    fn test_udp_session_table_zero_capacity() {
        let table = UdpSessionTable::new(UdpMode::Stateful, 0);
        assert_eq!(table.capacity, 1);
    }

    #[test]
    fn test_udp_session_timeout_boundary() {
        let mut session = UdpSession::empty();
        session.activate(v4([10, 0, 0, 1]), 8080, v4([10, 0, 0, 2]), 1234, IpVersion::V4, 1000);
        assert!(!session.is_expired(1500, 500));
        assert!(session.is_expired(1500, 499));
        assert!(session.is_expired(1501, 500));
        assert!(!session.is_expired(1499, 500));
        assert!(!session.is_expired(1000, 0));
        assert!(session.is_expired(1001, 0));
    }

    #[test]
    fn test_udp_session_table_count() {
        let mut table = UdpSessionTable::new(UdpMode::Stateful, 1024);
        assert_eq!(table.count(), 0);

        table.handle_inbound(
            v4([10, 0, 0, 1]),
            8080,
            v4([10, 0, 0, 2]),
            1234,
            IpVersion::V4,
            1000,
        );
        assert_eq!(table.count(), 1);

        table.handle_inbound(
            v4([10, 0, 0, 3]),
            9090,
            v4([10, 0, 0, 4]),
            5678,
            IpVersion::V4,
            1000,
        );
        assert_eq!(table.count(), 2);
    }
}