rs-store 3.0.0

Redux Store for Rust
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
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
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
use crate::metrics::Metrics;
#[cfg(feature = "store-log")]
use crate::store_impl::describe_action_op;
use crate::ActionOp;
use std::collections::VecDeque;
use std::fmt;
use std::marker::PhantomData;
use std::sync::{Arc, Condvar, Mutex};

/// the Backpressure policy
#[derive(Default)]
pub enum BackpressurePolicy<T>
where
    T: Send + Sync + Clone + 'static,
{
    /// Block the sender when the queue is full
    #[default]
    BlockOnFull,
    /// Drop items based on predicate when the queue is full, it drops from the newest to the oldest
    /// With this policy, [send] method can be Err when all items are not droppable
    /// Predicate is only applied to ActionOp::Action variants, other variants are never dropped
    #[allow(clippy::type_complexity)]
    DropLatestIf(Option<Box<dyn Fn(&T) -> bool + Send + Sync>>),
    /// Drop items based on predicate when the queue is full, it drops from the oldest to the newest
    /// With this policy, [send] method can be Err when all items are not droppable
    /// Predicate is only applied to ActionOp::Action variants, other variants are never dropped
    #[allow(clippy::type_complexity)]
    DropOldestIf(Option<Box<dyn Fn(&T) -> bool + Send + Sync>>),
}

#[derive(thiserror::Error)]
pub(crate) enum SenderError<T> {
    #[error("Failed to send item")]
    SendError(T),
    #[error("Channel is closed")]
    ChannelClosed,
}

impl<T> fmt::Debug for SenderError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SenderError::SendError(_) => f.write_str("SendError(..)"),
            SenderError::ChannelClosed => f.write_str("ChannelClosed"),
        }
    }
}

/// Internal MPSC Queue implementation
struct MpscQueue<T>
where
    T: Send + Sync + Clone + 'static,
{
    queue: Mutex<VecDeque<ActionOp<T>>>,
    condvar: Condvar,
    capacity: usize,
    policy: BackpressurePolicy<T>,
    metrics: Option<Arc<dyn Metrics + Send + Sync>>,
    closed: Mutex<bool>,
}

impl<T> MpscQueue<T>
where
    T: Send + Sync + Clone + 'static,
{
    fn new(
        capacity: usize,
        policy: BackpressurePolicy<T>,
        metrics: Option<Arc<dyn Metrics + Send + Sync>>,
    ) -> Self {
        Self {
            queue: Mutex::new(VecDeque::new()),
            condvar: Condvar::new(),
            capacity,
            policy,
            metrics,
            closed: Mutex::new(false),
        }
    }

    /// send put an item to the queue with backpressure policy
    /// when it is full, the send will try to drop an item based on the policy:
    /// - with BlockOnFull policy, the send will block until the space is available
    /// - with DropOldestIf policy, the send will drop an item if the predicate is true from the oldest to the newest
    /// - with DropLatestIf policy, the send will drop an item if the predicate is true from the latest to the oldest
    ///
    /// if nothing is dropped, the send will block until the space is available
    fn send(&self, item: ActionOp<T>) -> Result<i64, SenderError<ActionOp<T>>> {
        // Check if channel is closed
        if *self.closed.lock().unwrap() {
            return Err(SenderError::ChannelClosed);
        }

        let mut queue: std::sync::MutexGuard<'_, VecDeque<ActionOp<T>>> =
            self.queue.lock().unwrap();

        // Loop until we can successfully add the item to the queue
        loop {
            if queue.len() < self.capacity {
                // Queue has space, add the item
                queue.push_back(item);
                break;
            }

            // Queue is full, try to handle based on policy
            #[allow(deprecated)]
            match &self.policy {
                BackpressurePolicy::BlockOnFull => {
                    // Wait until space is available
                    while queue.len() >= self.capacity {
                        queue = self.condvar.wait(queue).unwrap();
                        if *self.closed.lock().unwrap() {
                            return Err(SenderError::ChannelClosed);
                        }
                    }
                    // Continue loop to add item
                }
                BackpressurePolicy::DropOldestIf(None) => {
                    // Drop the oldest item, but only if it's an Action variant
                    let mut found_action_to_drop = false;
                    let mut i = 0;
                    while i < queue.len() {
                        if matches!(queue[i], ActionOp::Action(_)) {
                            if let Some(dropped_item) = queue.remove(i) {
                                found_action_to_drop = true;
                                if let Some(metrics) = &self.metrics {
                                    if let ActionOp::Action(action) = &dropped_item {
                                        metrics.action_dropped(Some(action as &dyn std::any::Any));
                                    }
                                }
                                break;
                            }
                        }
                        i += 1;
                    }

                    // If no Action variant was found to drop, block until space is available
                    if !found_action_to_drop {
                        queue = self.condvar.wait(queue).unwrap();
                        if *self.closed.lock().unwrap() {
                            return Err(SenderError::ChannelClosed);
                        }
                        continue; // Continue the outer loop to try again
                    }
                    // Continue loop to add item
                }
                BackpressurePolicy::DropLatestIf(None) => {
                    // Drop the new item only if it's an Action variant
                    let mut found_action_to_drop = false;
                    let mut i = 0;
                    while i < queue.len() {
                        let idx = queue.len() - i - 1;
                        if matches!(queue[idx], ActionOp::Action(_)) {
                            if let Some(dropped_item) = queue.remove(idx) {
                                found_action_to_drop = true;
                                if let Some(metrics) = &self.metrics {
                                    if let ActionOp::Action(action) = &dropped_item {
                                        metrics.action_dropped(Some(action as &dyn std::any::Any));
                                    }
                                }
                                break;
                            }
                        }
                        i += 1;
                    }

                    // If no Action variant was found to drop, block until space is available
                    if !found_action_to_drop {
                        queue = self.condvar.wait(queue).unwrap();
                        if *self.closed.lock().unwrap() {
                            return Err(SenderError::ChannelClosed);
                        }
                        continue; // Continue the outer loop to try again
                    }
                    // Continue loop to add item
                }
                BackpressurePolicy::DropOldestIf(Some(predicate)) => {
                    // Find and drop items that match the predicate from oldest to newest
                    let mut dropped_count = 0;
                    let mut i = 0;
                    while i < queue.len() {
                        #[cfg(feature = "store-log")]
                        eprintln!(
                            "store: check droppable {}/{}: {}",
                            i,
                            queue.len(),
                            describe_action_op(&queue[i])
                        );
                        // Only apply predicate to Action variants
                        let should_drop = if let ActionOp::Action(action) = &queue[i] {
                            predicate(action)
                        } else {
                            false // Never drop non-Action variants
                        };
                        if should_drop {
                            if let Some(dropped_item) = queue.remove(i) {
                                dropped_count += 1;
                                if let Some(metrics) = &self.metrics {
                                    if let ActionOp::Action(action) = &dropped_item {
                                        metrics.action_dropped(Some(action as &dyn std::any::Any));
                                    }
                                }
                                break;
                            }
                        }
                        i += 1;
                    }

                    if dropped_count == 0 {
                        // Nothing was dropped, block until space is available
                        #[cfg(feature = "store-log")]
                        eprintln!(
                            "store: no droppable items found, blocking until space available: queue len={}",
                            queue.len()
                        );
                        queue = self.condvar.wait(queue).unwrap();
                        if *self.closed.lock().unwrap() {
                            return Err(SenderError::ChannelClosed);
                        }
                    }
                    // Continue loop to try again
                }
                BackpressurePolicy::DropLatestIf(Some(predicate)) => {
                    // Find and drop items that match the predicate from latest to oldest
                    let mut dropped_count = 0;
                    let mut i = 0;
                    while i < queue.len() {
                        let index = queue.len() - i - 1;
                        #[cfg(feature = "store-log")]
                        eprintln!(
                            "store: check droppable {}/{}: {}",
                            index,
                            queue.len(),
                            describe_action_op(&queue[index])
                        );
                        // Only apply predicate to Action variants
                        let should_drop = if let ActionOp::Action(action) = &queue[index] {
                            predicate(action)
                        } else {
                            false // Never drop non-Action variants
                        };
                        if should_drop {
                            if let Some(dropped_item) = queue.remove(index) {
                                dropped_count += 1;
                                if let Some(metrics) = &self.metrics {
                                    if let ActionOp::Action(action) = &dropped_item {
                                        metrics.action_dropped(Some(action as &dyn std::any::Any));
                                    }
                                }
                                break;
                            }
                        }
                        i += 1;
                    }

                    if dropped_count == 0 {
                        // Nothing was dropped, block until space is available
                        #[cfg(feature = "store-log")]
                        eprintln!(
                            "store: no droppable items found, blocking until space available: queue len={}",
                            queue.len()
                        );
                        queue = self.condvar.wait(queue).unwrap();
                        if *self.closed.lock().unwrap() {
                            return Err(SenderError::ChannelClosed);
                        }
                    }
                    // Continue loop to try again
                }
            }
        }

        // Update metrics
        if let Some(metrics) = &self.metrics {
            metrics.queue_size(queue.len());
        }

        self.condvar.notify_one();
        Ok(queue.len() as i64)
    }

    fn try_send(&self, item: ActionOp<T>) -> Result<i64, SenderError<ActionOp<T>>> {
        // Check if channel is closed
        if *self.closed.lock().unwrap() {
            return Err(SenderError::ChannelClosed);
        }

        let mut queue = self.queue.lock().unwrap();

        if queue.len() < self.capacity {
            queue.push_back(item);
        } else {
            #[allow(deprecated)]
            match &self.policy {
                BackpressurePolicy::BlockOnFull => {
                    return Err(SenderError::SendError(item));
                }
                BackpressurePolicy::DropOldestIf(None) => {
                    // Drop the oldest item, but only if it's an Action variant
                    let mut found_action_to_drop = false;
                    let mut i = 0;
                    while i < queue.len() {
                        if matches!(queue[i], ActionOp::Action(_)) {
                            if let Some(dropped_item) = queue.remove(i) {
                                found_action_to_drop = true;
                                if let Some(metrics) = &self.metrics {
                                    if let ActionOp::Action(action) = &dropped_item {
                                        metrics.action_dropped(Some(action as &dyn std::any::Any));
                                    }
                                }
                                break;
                            }
                        }
                        i += 1;
                    }

                    if found_action_to_drop {
                        queue.push_back(item);
                    } else {
                        // No Action variant found to drop, return error
                        #[cfg(feature = "store-log")]
                        eprintln!(
                            "store: failed to drop oldest action while trying to send: queue len={}",
                            queue.len()
                        );
                        return Err(SenderError::SendError(item));
                    }
                }
                BackpressurePolicy::DropLatestIf(None) => {
                    let mut found_action_to_drop = false;
                    let mut i = 0;
                    while i < queue.len() {
                        let index = queue.len() - i - 1;
                        if matches!(queue[index], ActionOp::Action(_)) {
                            if let Some(dropped_item) = queue.remove(index) {
                                found_action_to_drop = true;
                                if let Some(metrics) = &self.metrics {
                                    if let ActionOp::Action(action) = &dropped_item {
                                        metrics.action_dropped(Some(action as &dyn std::any::Any));
                                    }
                                }
                                break;
                            }
                        }
                        i += 1;
                    }

                    if found_action_to_drop {
                        queue.push_back(item);
                    } else {
                        // No Action variant found to drop, return error
                        #[cfg(feature = "store-log")]
                        eprintln!(
                            "store: failed to drop latest action while trying to send: queue len={}",
                            queue.len()
                        );
                        return Err(SenderError::SendError(item));
                    }
                }
                BackpressurePolicy::DropOldestIf(Some(predicate)) => {
                    // Find and drop items that match the predicate
                    let mut dropped_count = 0;
                    let mut i = 0;
                    while i < queue.len() {
                        #[cfg(feature = "store-log")]
                        eprintln!(
                            "store: check droppable {}/{}: {}",
                            i,
                            queue.len(),
                            describe_action_op(&queue[i])
                        );
                        // Only apply predicate to Action variants
                        let should_drop = if let ActionOp::Action(action) = &queue[i] {
                            predicate(action)
                        } else {
                            false // Never drop non-Action variants
                        };
                        if should_drop {
                            if let Some(dropped_item) = queue.remove(i) {
                                dropped_count += 1;
                                if let Some(metrics) = &self.metrics {
                                    if let ActionOp::Action(action) = &dropped_item {
                                        metrics.action_dropped(Some(action as &dyn std::any::Any));
                                    }
                                }
                                break;
                            }
                        }
                        i += 1;
                    }

                    if dropped_count > 0 {
                        queue.push_back(item);
                    } else {
                        #[cfg(feature = "store-log")]
                        eprintln!(
                            "store: failed to drop the oldestif while trying to send: queue len={}",
                            queue.len()
                        );
                        return Err(SenderError::SendError(item));
                    }
                }
                BackpressurePolicy::DropLatestIf(Some(predicate)) => {
                    // Find and drop items that match the predicate
                    let mut dropped_count = 0;
                    let mut i = 0;
                    while i < queue.len() {
                        let index = queue.len() - i - 1;
                        #[cfg(feature = "store-log")]
                        eprintln!(
                            "store: check droppable {}/{}: {}",
                            index,
                            queue.len(),
                            describe_action_op(&queue[index])
                        );
                        // Only apply predicate to Action variants
                        let should_drop = if let ActionOp::Action(action) = &queue[index] {
                            predicate(action)
                        } else {
                            false // Never drop non-Action variants
                        };
                        if should_drop {
                            if let Some(dropped_item) = queue.remove(index) {
                                dropped_count += 1;
                                if let Some(metrics) = &self.metrics {
                                    if let ActionOp::Action(action) = &dropped_item {
                                        metrics.action_dropped(Some(action as &dyn std::any::Any));
                                    }
                                }
                                break;
                            }
                        }
                        i += 1;
                    }

                    if dropped_count > 0 {
                        queue.push_back(item);
                    } else {
                        #[cfg(feature = "store-log")]
                        eprintln!(
                            "store: failed to drop the latestif while trying to send: queue len={}",
                            queue.len()
                        );
                        return Err(SenderError::SendError(item));
                    }
                }
            }
        }

        // Update metrics
        if let Some(metrics) = &self.metrics {
            metrics.queue_size(queue.len());
        }

        self.condvar.notify_one();
        Ok(queue.len() as i64)
    }

    fn recv(&self) -> Option<ActionOp<T>> {
        let mut queue = self.queue.lock().unwrap();

        // Wait until there's an item or channel is closed
        while queue.is_empty() {
            if *self.closed.lock().unwrap() {
                return None;
            }
            queue = self.condvar.wait(queue).unwrap();
        }

        let item = queue.pop_front();
        self.condvar.notify_one();
        item
    }

    fn try_recv(&self) -> Option<ActionOp<T>> {
        let mut queue = self.queue.lock().unwrap();
        let item = queue.pop_front();
        if item.is_some() {
            self.condvar.notify_one();
        }
        item
    }

    fn len(&self) -> usize {
        self.queue.lock().unwrap().len()
    }

    fn close(&self) {
        *self.closed.lock().unwrap() = true;
        self.condvar.notify_all();
    }
}

/// Channel to hold the sender with backpressure policy
#[derive(Clone)]
pub(crate) struct SenderChannel<T>
where
    T: Send + Sync + Clone + 'static,
{
    _name: String,
    queue: Arc<MpscQueue<T>>,
}

impl<Action> Drop for SenderChannel<Action>
where
    Action: Send + Sync + Clone + 'static,
{
    fn drop(&mut self) {
        #[cfg(feature = "store-log")]
        eprintln!("store: drop '{}' sender channel", self._name);
    }
}

#[allow(dead_code)]
impl<T> SenderChannel<T>
where
    T: Send + Sync + Clone + 'static,
{
    /// when it is full, the send will try to drop an item based on the policy
    /// if nothing is dropped, the send will block until the space is available
    pub fn send(&self, item: ActionOp<T>) -> Result<i64, SenderError<ActionOp<T>>> {
        self.queue.send(item)
    }

    /// when it is full, it will return Err
    pub fn try_send(&self, item: ActionOp<T>) -> Result<i64, SenderError<ActionOp<T>>> {
        self.queue.try_send(item)
    }
}

#[allow(dead_code)]
pub(crate) struct ReceiverChannel<T>
where
    T: Send + Sync + Clone + 'static,
{
    name: String,
    queue: Arc<MpscQueue<T>>,
    metrics: Option<Arc<dyn Metrics + Send + Sync>>,
}

impl<Action> Drop for ReceiverChannel<Action>
where
    Action: Send + Sync + Clone + 'static,
{
    fn drop(&mut self) {
        #[cfg(feature = "store-log")]
        eprintln!("store: drop '{}' receiver channel", self.name);
        self.close();
    }
}

#[allow(dead_code)]
impl<T> ReceiverChannel<T>
where
    T: Send + Sync + Clone + 'static,
{
    pub fn recv(&self) -> Option<ActionOp<T>> {
        self.queue.recv()
    }

    #[allow(dead_code)]
    pub fn try_recv(&self) -> Option<ActionOp<T>> {
        self.queue.try_recv()
    }

    pub fn len(&self) -> usize {
        self.queue.len()
    }

    pub fn close(&self) {
        self.queue.close();
    }
}

/// Channel with back pressure
pub(crate) struct BackpressureChannel<MSG>
where
    MSG: Send + Sync + Clone + 'static,
{
    phantom_data: PhantomData<MSG>,
}

impl<MSG> BackpressureChannel<MSG>
where
    MSG: Send + Sync + Clone + 'static,
{
    #[allow(dead_code)]
    pub fn pair(
        capacity: usize,
        policy: BackpressurePolicy<MSG>,
    ) -> (SenderChannel<MSG>, ReceiverChannel<MSG>) {
        Self::pair_with("<anon>", capacity, policy, None)
    }

    #[allow(dead_code)]
    pub fn pair_with_metrics(
        capacity: usize,
        policy: BackpressurePolicy<MSG>,
        metrics: Option<Arc<dyn Metrics + Send + Sync>>,
    ) -> (SenderChannel<MSG>, ReceiverChannel<MSG>) {
        Self::pair_with("<anon>", capacity, policy, metrics)
    }

    #[allow(dead_code)]
    pub fn pair_with(
        name: &str,
        capacity: usize,
        policy: BackpressurePolicy<MSG>,
        metrics: Option<Arc<dyn Metrics + Send + Sync>>,
    ) -> (SenderChannel<MSG>, ReceiverChannel<MSG>) {
        let queue = Arc::new(MpscQueue::new(capacity, policy, metrics.clone()));

        (
            SenderChannel {
                _name: name.to_string(),
                queue: queue.clone(),
            },
            ReceiverChannel {
                name: name.to_string(),
                queue,
                metrics,
            },
        )
    }
}

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

    #[test]
    fn test_basic_send_recv() {
        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(5, BackpressurePolicy::BlockOnFull);

        sender.send(ActionOp::Action(1)).unwrap();
        sender.send(ActionOp::Action(2)).unwrap();

        assert_eq!(receiver.recv(), Some(ActionOp::Action(1)));
        assert_eq!(receiver.recv(), Some(ActionOp::Action(2)));
        assert_eq!(receiver.try_recv(), None);
    }

    #[test]
    fn test_drop_oldest() {
        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(2, BackpressurePolicy::DropOldestIf(None));

        sender.send(ActionOp::Action(1)).unwrap();
        sender.send(ActionOp::Action(2)).unwrap();
        sender.send(ActionOp::Action(3)).unwrap(); // Should drop 1

        assert_eq!(receiver.recv(), Some(ActionOp::Action(2)));
        assert_eq!(receiver.recv(), Some(ActionOp::Action(3)));
        assert_eq!(receiver.try_recv(), None);
    }

    #[test]
    fn test_drop_latest() {
        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(2, BackpressurePolicy::DropLatestIf(None));

        sender.send(ActionOp::Action(1)).unwrap();
        sender.send(ActionOp::Action(2)).unwrap(); // should drop 2
        sender.send(ActionOp::Action(3)).unwrap();

        assert_eq!(receiver.recv(), Some(ActionOp::Action(1)));
        assert_eq!(receiver.recv(), Some(ActionOp::Action(3)));
        assert_eq!(receiver.try_recv(), None);
    }

    #[test]
    fn test_predicate_dropping() {
        // predicate: 5보다 작은 값들은 drop
        let predicate = Box::new(|value: &i32| *value < 5);

        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(2, BackpressurePolicy::DropLatestIf(Some(predicate)));

        // 채널을 가득 채우기
        sender.send(ActionOp::Action(1)).unwrap(); // 첫 번째 아이템 (drop 대상)
        sender.send(ActionOp::Action(6)).unwrap(); // 두 번째 아이템 (유지 대상)

        // 세 번째 아이템을 보내면 채널이 가득 차서 predicate가 적용됨
        let result = sender.send(ActionOp::Action(7)); // 세 번째 아이템 (유지 대상)
        assert!(
            result.is_ok(),
            "Should succeed because predicate should drop the first item"
        );

        // 소비자에서 아이템 확인
        let received_item = receiver.recv();
        assert!(received_item.is_some());
        if let Some(ActionOp::Action(value)) = received_item {
            // predicate에 의해 1이 drop되고 6이 유지되어야 함
            assert_eq!(value, 6, "Should receive 6, not 1");
        }

        let received_item = receiver.recv();
        assert!(received_item.is_some());
        if let Some(ActionOp::Action(value)) = received_item {
            assert_eq!(value, 7, "Should receive 7");
        }
    }

    #[test]
    fn test_add_subscriber_action() {
        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(5, BackpressurePolicy::BlockOnFull);

        // AddSubscriber 액션 전송
        sender.send(ActionOp::AddSubscriber).unwrap();

        // 수신 확인
        let received = receiver.recv();
        assert!(received.is_some());
        match received.unwrap() {
            ActionOp::AddSubscriber => {
                // AddSubscriber 액션이 정상적으로 수신됨
            }
            _ => panic!("Expected AddSubscriber action"),
        }
    }

    #[test]
    fn test_add_subscriber_with_predicate() {
        // predicate는 Action에만 적용되므로 AddSubscriber는 자동으로 보존됨
        let predicate = Box::new(|value: &i32| *value < 5);

        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(2, BackpressurePolicy::DropLatestIf(Some(predicate)));

        // 채널을 가득 채우기
        sender.send(ActionOp::Action(1)).unwrap(); // drop 대상
        sender.send(ActionOp::Action(6)).unwrap(); // 유지 대상

        // AddSubscriber 액션을 보내면 predicate에 의해 다른 액션이 drop되어야 함
        let result = sender.send(ActionOp::AddSubscriber);
        assert!(result.is_ok(), "AddSubscriber should be sent successfully");

        // 수신 확인
        let received_items: Vec<_> = std::iter::from_fn(|| receiver.try_recv()).collect();
        assert_eq!(received_items.len(), 2);

        // AddSubscriber가 포함되어 있는지 확인
        let has_add_subscriber =
            received_items.iter().any(|item| matches!(item, ActionOp::AddSubscriber));
        assert!(has_add_subscriber, "AddSubscriber should be received");
    }

    #[test]
    fn test_mixed_action_types() {
        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(10, BackpressurePolicy::BlockOnFull);

        // 다양한 타입의 액션들을 전송
        sender.send(ActionOp::Action(1)).unwrap();
        sender.send(ActionOp::AddSubscriber).unwrap();
        sender.send(ActionOp::Action(2)).unwrap();
        sender.send(ActionOp::AddSubscriber).unwrap();
        sender.send(ActionOp::Action(3)).unwrap();

        // 수신 확인
        let received_items: Vec<_> = std::iter::from_fn(|| receiver.try_recv()).collect();
        assert_eq!(received_items.len(), 5);

        // 순서 확인
        match &received_items[0] {
            ActionOp::Action(value) => assert_eq!(*value, 1),
            _ => panic!("Expected Action(1)"),
        }
        match &received_items[1] {
            ActionOp::AddSubscriber => {
                // AddSubscriber 액션
            }
            _ => panic!("Expected AddSubscriber"),
        }
        match &received_items[2] {
            ActionOp::Action(value) => assert_eq!(*value, 2),
            _ => panic!("Expected Action(2)"),
        }
        match &received_items[3] {
            ActionOp::AddSubscriber => {
                // AddSubscriber 액션
            }
            _ => panic!("Expected AddSubscriber"),
        }
        match &received_items[4] {
            ActionOp::Action(value) => assert_eq!(*value, 3),
            _ => panic!("Expected Action(3)"),
        }
    }

    #[test]
    fn test_block_on_full() {
        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(1, BackpressurePolicy::BlockOnFull);

        sender.send(ActionOp::Action(1)).unwrap();

        // Try to send another item - should block or fail
        let result = sender.try_send(ActionOp::Action(2));
        assert!(result.is_err(), "Should fail because channel is full");

        // Receive the first item
        assert_eq!(receiver.recv(), Some(ActionOp::Action(1)));

        // Now we can send again
        sender.send(ActionOp::Action(2)).unwrap();
        assert_eq!(receiver.recv(), Some(ActionOp::Action(2)));
    }

    #[test]
    fn test_drop_oldest_if_predicate_always_false() {
        let (sender, receiver) = BackpressureChannel::pair(
            3,
            BackpressurePolicy::DropOldestIf(Some(Box::new(|_| false))), // Predicate always returns false
        );

        // Fill the channel to capacity
        assert!(sender.try_send(ActionOp::Action(1)).is_ok());
        assert!(sender.try_send(ActionOp::Action(2)).is_ok());
        assert!(sender.try_send(ActionOp::Action(3)).is_ok());
        assert_eq!(receiver.len(), 3);

        // Try to send one more item - should fail since predicate is false
        // and no items can be dropped
        let result = sender.try_send(ActionOp::Action(4));
        assert!(
            result.is_err(),
            "Should fail because no items match the predicate"
        );

        // Verify the channel contents are unchanged
        assert_eq!(receiver.len(), 3);
        assert_eq!(receiver.recv(), Some(ActionOp::Action(1)));
        assert_eq!(receiver.recv(), Some(ActionOp::Action(2)));
        assert_eq!(receiver.recv(), Some(ActionOp::Action(3)));
    }

    #[test]
    fn test_drop_oldest_if_predicate_sometimes_true() {
        let (sender, receiver) = BackpressureChannel::pair(
            3,
            BackpressurePolicy::DropOldestIf(Some(Box::new(|value: &i32| *value < 5))), // Drop values less than 5
        );

        // Fill the channel to capacity with values that don't match predicate
        assert!(sender.try_send(ActionOp::Action(6)).is_ok()); // >= 5, not droppable
        assert!(sender.try_send(ActionOp::Action(2)).is_ok()); // < 5, droppable
        assert!(sender.try_send(ActionOp::Action(8)).is_ok()); // >= 5, not droppable
        assert_eq!(receiver.len(), 3);

        // Try to send a value that doesn't match predicate - should fail
        let result = sender.try_send(ActionOp::Action(9));
        assert!(
            result.is_ok(),
            "Should fail because no items match the predicate"
        );

        // Now send a value that matches predicate - should fail because no items match predicate
        let result = sender.try_send(ActionOp::Action(10)); // This should fail because no items < 5
        assert!(
            result.is_err(),
            "Should fail because no items match the predicate"
        );

        // Verify the channel contents are unchanged
        assert_eq!(receiver.len(), 3);
        assert_eq!(receiver.recv(), Some(ActionOp::Action(6)));
        assert_eq!(receiver.recv(), Some(ActionOp::Action(8)));
        assert_eq!(receiver.recv(), Some(ActionOp::Action(9)));
    }

    #[test]
    fn test_drop_oldest_only_actions() {
        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(2, BackpressurePolicy::DropOldestIf(None));

        // Fill the channel with non-Action items
        sender.send(ActionOp::AddSubscriber).unwrap();
        sender.send(ActionOp::Exit(std::time::Instant::now())).unwrap();
        assert_eq!(receiver.len(), 2);

        // Try to send an Action - should block because no Actions to drop
        let result = sender.try_send(ActionOp::Action(1));
        assert!(
            result.is_err(),
            "Should fail because no Actions can be dropped"
        );

        // Channel should still contain the original non-Action items
        assert_eq!(receiver.len(), 2);
        assert_eq!(receiver.recv(), Some(ActionOp::AddSubscriber));
        assert!(matches!(receiver.recv(), Some(ActionOp::Exit(_))));
    }

    #[test]
    fn test_drop_oldest_with_mixed_types() {
        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(3, BackpressurePolicy::DropOldestIf(None));

        // Fill the channel with mixed types
        sender.send(ActionOp::Action(1)).unwrap(); // This should be droppable
        sender.send(ActionOp::AddSubscriber).unwrap(); // This should NOT be droppable
        sender.send(ActionOp::Action(2)).unwrap(); // This should be droppable
        assert_eq!(receiver.len(), 3);

        // Send another Action - should drop the first Action(1)
        sender.send(ActionOp::Action(3)).unwrap();
        assert_eq!(receiver.len(), 3);

        // Verify contents: AddSubscriber should still be there, Action(1) should be dropped
        let received_items: Vec<_> = std::iter::from_fn(|| receiver.try_recv()).collect();
        assert_eq!(received_items.len(), 3);

        // Should contain AddSubscriber, Action(2), and Action(3)
        let has_add_subscriber =
            received_items.iter().any(|item| matches!(item, ActionOp::AddSubscriber));
        let has_action_2 = received_items.iter().any(|item| matches!(item, ActionOp::Action(2)));
        let has_action_3 = received_items.iter().any(|item| matches!(item, ActionOp::Action(3)));
        let has_action_1 = received_items.iter().any(|item| matches!(item, ActionOp::Action(1)));

        assert!(has_add_subscriber, "AddSubscriber should be preserved");
        assert!(has_action_2, "Action(2) should be preserved");
        assert!(has_action_3, "Action(3) should be added");
        assert!(!has_action_1, "Action(1) should be dropped");
    }

    #[test]
    fn test_drop_latest_only_actions() {
        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(3, BackpressurePolicy::DropLatestIf(None));

        // Fill the channel with non-Action items
        sender.send(ActionOp::AddSubscriber).unwrap();
        sender.send(ActionOp::Action(1)).unwrap();
        sender.send(ActionOp::Exit(std::time::Instant::now())).unwrap();
        assert_eq!(receiver.len(), 3);

        // Try to send an Action - should be dropped
        let result = sender.try_send(ActionOp::Action(2));
        assert!(result.is_ok(), "Action should be dropped successfully");

        // Try to send an Action - should be dropped
        let result = sender.try_send(ActionOp::StateFunction);
        assert!(result.is_ok(), "Action should be dropped successfully");

        // Try to send a non-Action - should fail because channel is full
        let result = sender.try_send(ActionOp::AddSubscriber);
        assert!(
            result.is_err(),
            "Should fail because channel is full and non-Actions can't be dropped"
        );

        // Channel should still contain the original non-Action items
        assert_eq!(receiver.len(), 3);
        assert_eq!(receiver.recv(), Some(ActionOp::AddSubscriber));
        assert!(matches!(receiver.recv(), Some(ActionOp::Exit(_))));
        assert_eq!(receiver.recv(), Some(ActionOp::StateFunction));
    }

    #[test]
    fn test_drop_policy_preserves_critical_operations() {
        // 이 테스트는 중요한 작업(AddSubscriber, Exit)이 drop되지 않는지 확인합니다
        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(3, BackpressurePolicy::DropOldestIf(None));

        // 채널을 가득 채우기: 2개의 Action과 1개의 AddSubscriber
        sender.send(ActionOp::Action(1)).unwrap();
        sender.send(ActionOp::Action(2)).unwrap();
        sender.send(ActionOp::AddSubscriber).unwrap();
        assert_eq!(receiver.len(), 3);

        // 새로운 Action을 보내면 기존 Action 중 하나가 drop되어야 함
        sender.send(ActionOp::Action(3)).unwrap();
        assert_eq!(receiver.len(), 3);

        // AddSubscriber는 여전히 존재해야 함
        let received_items: Vec<_> = std::iter::from_fn(|| receiver.try_recv()).collect();
        let has_add_subscriber =
            received_items.iter().any(|item| matches!(item, ActionOp::AddSubscriber));
        assert!(
            has_add_subscriber,
            "AddSubscriber should never be dropped by drop policy"
        );

        // Action(1)이 drop되고 Action(2), Action(3)이 남아있어야 함
        let action_values: Vec<i32> = received_items
            .iter()
            .filter_map(|item| {
                if let ActionOp::Action(val) = item {
                    Some(*val)
                } else {
                    None
                }
            })
            .collect();
        assert_eq!(action_values.len(), 2, "Should have 2 Actions remaining");
        assert!(action_values.contains(&2), "Action(2) should be preserved");
        assert!(action_values.contains(&3), "Action(3) should be added");
        assert!(!action_values.contains(&1), "Action(1) should be dropped");
    }

    #[test]
    fn test_drop_policy_with_exit_operations() {
        // Exit 작업이 drop되지 않는지 확인하는 테스트
        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(2, BackpressurePolicy::DropLatestIf(None));

        let exit_time = std::time::Instant::now();

        // 채널을 가득 채우기: 1개의 Action과 1개의 Exit
        sender.send(ActionOp::Action(1)).unwrap();
        sender.send(ActionOp::Exit(exit_time)).unwrap();
        assert_eq!(receiver.len(), 2);

        // 새로운 Action을 보내면 최근 아이템이 drop되어야 함 (Exit은 보존)
        let result = sender.send(ActionOp::Action(2));
        assert!(result.is_ok(), "Action should be dropped, not Exit");

        // Exit은 여전히 존재해야 함
        let received_items: Vec<_> = std::iter::from_fn(|| receiver.try_recv()).collect();
        assert_eq!(received_items.len(), 2);

        let has_action_1 = received_items.get(0).unwrap() == &ActionOp::Action(1);
        assert!(!has_action_1, "Action(1) should be dropped");

        let has_exit = received_items.get(0).unwrap() == &ActionOp::Exit(exit_time);
        assert!(has_exit, "Exit should never be dropped by drop policy");

        let has_action_2 = received_items.get(1).unwrap() == &ActionOp::Action(2);
        assert!(has_action_2, "Action(2) added");
    }

    #[test]
    fn test_drop_oldest_action_ordering() {
        // DropOldest가 Action들 중에서 가장 오래된 것을 drop하는지 확인
        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(4, BackpressurePolicy::DropOldestIf(None));

        // 채널에 순서대로 추가: Action(1), AddSubscriber, Action(2), Action(3)
        sender.send(ActionOp::Action(1)).unwrap(); // 가장 오래된 Action
        sender.send(ActionOp::AddSubscriber).unwrap();
        sender.send(ActionOp::Action(2)).unwrap();
        sender.send(ActionOp::Action(3)).unwrap();
        assert_eq!(receiver.len(), 4);

        // 새로운 Action을 보내면 Action(1)이 drop되어야 함
        sender.send(ActionOp::Action(4)).unwrap();
        assert_eq!(receiver.len(), 4);

        let received_items: Vec<_> = std::iter::from_fn(|| receiver.try_recv()).collect();

        // AddSubscriber는 보존되어야 함
        let has_add_subscriber =
            received_items.iter().any(|item| matches!(item, ActionOp::AddSubscriber));
        assert!(has_add_subscriber, "AddSubscriber should be preserved");

        // Action 값들 확인
        let action_values: Vec<i32> = received_items
            .iter()
            .filter_map(|item| {
                if let ActionOp::Action(val) = item {
                    Some(*val)
                } else {
                    None
                }
            })
            .collect();

        assert_eq!(action_values.len(), 3, "Should have 3 Actions remaining");
        assert!(
            !action_values.contains(&1),
            "Action(1) should be dropped (oldest)"
        );
        assert!(action_values.contains(&2), "Action(2) should be preserved");
        assert!(action_values.contains(&3), "Action(3) should be preserved");
        assert!(action_values.contains(&4), "Action(4) should be added");
    }

    #[test]
    fn test_drop_policy_blocking_behavior() {
        // Action이 없을 때 blocking 동작을 확인하는 테스트
        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(2, BackpressurePolicy::DropOldestIf(None));

        // 채널을 non-Action items로 가득 채우기
        sender.send(ActionOp::AddSubscriber).unwrap();
        sender.send(ActionOp::Exit(std::time::Instant::now())).unwrap();
        assert_eq!(receiver.len(), 2);

        // try_send로 새로운 Action을 보내려 하면 실패해야 함 (drop할 Action이 없음)
        let result = sender.try_send(ActionOp::Action(1));
        assert!(
            result.is_err(),
            "Should fail because no Actions available to drop"
        );

        // try_send로 새로운 non-Action을 보내려 해도 실패해야 함
        let result = sender.try_send(ActionOp::AddSubscriber);
        assert!(
            result.is_err(),
            "Should fail because channel is full and no Actions to drop"
        );

        // 채널 내용이 변경되지 않았는지 확인
        assert_eq!(receiver.len(), 2);
        assert_eq!(receiver.recv(), Some(ActionOp::AddSubscriber));
        assert!(matches!(receiver.recv(), Some(ActionOp::Exit(_))));
    }

    #[test]
    fn test_drop_oldest_if_predicate_always_true() {
        let (sender, receiver) = BackpressureChannel::<i32>::pair(
            3,
            BackpressurePolicy::DropOldestIf(Some(Box::new(|_| true))),
        );

        sender.send(ActionOp::Action(1)).unwrap();
        sender.send(ActionOp::Action(2)).unwrap();
        sender.send(ActionOp::Action(3)).unwrap();

        let result = sender.send(ActionOp::Action(4));
        assert!(result.is_ok(), "Action should be dropped successfully");

        let received_items: Vec<_> = std::iter::from_fn(|| receiver.try_recv()).collect();
        assert_eq!(received_items.len(), 3);

        let has_action_1 = received_items.get(0).unwrap() == &ActionOp::Action(1);
        assert!(!has_action_1, "Action(1) should be dropped");

        let has_action_2 = received_items.get(0).unwrap() == &ActionOp::Action(2);
        assert!(has_action_2, "Action(2) should be preserved");

        let has_action_3 = received_items.get(1).unwrap() == &ActionOp::Action(3);
        assert!(has_action_3, "Action(3) should be preserved");

        let has_action_4 = received_items.get(2).unwrap() == &ActionOp::Action(4);
        assert!(has_action_4, "Action(4) should be added");
    }

    #[test]
    fn test_drop_latest_if_predicate_always_true() {
        let (sender, receiver) = BackpressureChannel::<i32>::pair(
            3,
            BackpressurePolicy::DropLatestIf(Some(Box::new(|_| true))),
        );

        sender.send(ActionOp::Action(1)).unwrap();
        sender.send(ActionOp::Action(2)).unwrap();
        sender.send(ActionOp::Action(3)).unwrap(); // should be dropped

        let result = sender.send(ActionOp::Action(4));
        assert!(result.is_ok(), "Action should be dropped successfully");

        let received_items: Vec<_> = std::iter::from_fn(|| receiver.try_recv()).collect();
        assert_eq!(received_items.len(), 3);

        let has_action_1 = received_items.get(0).unwrap() == &ActionOp::Action(1);
        assert!(has_action_1, "Action(1) should be preserved");

        let has_action_2 = received_items.get(1).unwrap() == &ActionOp::Action(2);
        assert!(has_action_2, "Action(2) should be preserved");

        let has_action_3 = received_items.get(2).unwrap() == &ActionOp::Action(3);
        assert!(!has_action_3, "Action(3) should be dropped");

        let has_action_4 = received_items.get(2).unwrap() == &ActionOp::Action(4);
        assert!(has_action_4, "Action(4) should be added");
    }

    #[test]
    fn test_drop_latest_vs_drop_oldest_action_selection() {
        // DropLatest와 DropOldest가 서로 같은 Action을 선택하는지 확인

        // DropOldest 테스트
        let (sender_oldest, receiver_oldest) =
            BackpressureChannel::<i32>::pair(3, BackpressurePolicy::DropOldestIf(None));

        sender_oldest.send(ActionOp::Action(10)).unwrap(); // 가장 오래된 Action
        sender_oldest.send(ActionOp::AddSubscriber).unwrap();
        sender_oldest.send(ActionOp::Action(20)).unwrap(); // 가장 새로운 Action

        sender_oldest.send(ActionOp::Action(30)).unwrap(); // Action(10)이 drop되어야 함

        let oldest_items: Vec<_> = std::iter::from_fn(|| receiver_oldest.try_recv()).collect();
        let oldest_actions: Vec<i32> = oldest_items
            .iter()
            .filter_map(|item| {
                if let ActionOp::Action(val) = item {
                    Some(*val)
                } else {
                    None
                }
            })
            .collect();

        assert!(
            oldest_actions.contains(&20),
            "DropOldest should preserve Action(20)"
        );
        assert!(
            oldest_actions.contains(&30),
            "DropOldest should preserve Action(30)"
        );

        // DropLatest 테스트
        let (sender_latest, receiver_latest) =
            BackpressureChannel::<i32>::pair(3, BackpressurePolicy::DropLatestIf(None));

        sender_latest.send(ActionOp::Action(100)).unwrap(); // 가장 오래된 Action
        sender_latest.send(ActionOp::AddSubscriber).unwrap();
        sender_latest.send(ActionOp::Action(200)).unwrap(); // should be dropped

        // 새로운 Action을 보내면 마지막 drop되어야 함
        let result = sender_latest.send(ActionOp::Action(300));
        assert!(
            result.is_ok(),
            "send Action should be success, should drop the latest Action(200)"
        );

        let latest_items: Vec<_> = std::iter::from_fn(|| receiver_latest.try_recv()).collect();
        assert_eq!(latest_items.len(), 3);

        let has_action_100 = latest_items.get(0).unwrap() == &ActionOp::Action(100);
        assert!(has_action_100, "DropLatest should preserve Action(100)");

        assert_eq!(
            latest_items.get(1).unwrap(),
            &ActionOp::AddSubscriber,
            "DropLatest should preserve AddSubscriber"
        );

        let has_action_200 = latest_items.get(2).unwrap() == &ActionOp::Action(200);
        assert!(!has_action_200, "DropLatest should drop Action(200)");

        let has_action_300 = latest_items.get(2).unwrap() == &ActionOp::Action(300);
        assert!(has_action_300, "DropLatest should add Action(300)");
    }

    #[test]
    fn test_comprehensive_drop_policy_verification() {
        // 종합적인 drop policy 검증 테스트
        let (sender, receiver) =
            BackpressureChannel::<String>::pair(5, BackpressurePolicy::DropOldestIf(None));

        // 다양한 타입의 ActionOp를 순서대로 추가
        sender.send(ActionOp::Action("action1".to_string())).unwrap();
        sender.send(ActionOp::AddSubscriber).unwrap();
        sender.send(ActionOp::Action("action2".to_string())).unwrap();
        sender.send(ActionOp::Exit(std::time::Instant::now())).unwrap();
        sender.send(ActionOp::Action("action3".to_string())).unwrap();
        assert_eq!(receiver.len(), 5);

        // 채널이 가득 찬 상태에서 새로운 Action 추가
        // action1이 drop되어야 함 (가장 오래된 Action)
        sender.send(ActionOp::Action("action4".to_string())).unwrap();
        assert_eq!(receiver.len(), 5);

        let received_items: Vec<_> = std::iter::from_fn(|| receiver.try_recv()).collect();

        // 모든 non-Action items는 보존되어야 함
        let has_add_subscriber =
            received_items.iter().any(|item| matches!(item, ActionOp::AddSubscriber));
        let has_exit = received_items.iter().any(|item| matches!(item, ActionOp::Exit(_)));
        assert!(has_add_subscriber, "AddSubscriber must be preserved");
        assert!(has_exit, "Exit must be preserved");

        // Action items 검증
        let action_values: Vec<String> = received_items
            .iter()
            .filter_map(|item| {
                if let ActionOp::Action(val) = item {
                    Some(val.clone())
                } else {
                    None
                }
            })
            .collect();

        assert_eq!(action_values.len(), 3, "Should have 3 Actions remaining");
        assert!(
            !action_values.contains(&"action1".to_string()),
            "action1 should be dropped (oldest Action)"
        );
        assert!(
            action_values.contains(&"action2".to_string()),
            "action2 should be preserved"
        );
        assert!(
            action_values.contains(&"action3".to_string()),
            "action3 should be preserved"
        );
        assert!(
            action_values.contains(&"action4".to_string()),
            "action4 should be added"
        );

        // 전체 아이템 개수 확인
        assert_eq!(received_items.len(), 5, "Total items should remain 5");
    }
}