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
use crate::store::StoreError;
use std::any::Any;
use std::fmt::Formatter;
use std::ops::Sub;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::{fmt, sync::atomic::AtomicUsize, time::Duration};

/// Metrics is a trait for metrics that can be used to track the state of the store.
#[allow(dead_code)]
#[allow(unused_variables)]
pub(crate) trait Metrics: Send + Sync {
    /// action_received is called when an action is received including Exit.
    /// data is the ActionOp that is received.
    fn action_received(&self, data: Option<&dyn Any>) {}

    /// action_dropped is called when an action is dropped.
    fn action_dropped(&self, data: Option<&dyn Any>) {}

    /// action_executed is called when an action is processed in which contains the total time spent to process the action.
    fn action_executed(&self, data: Option<&dyn Any>, duration: Duration) {}

    /// middleware_execution_time is called when a middleware is executed,
    /// it includes the time spent of reducing the action and the time spent in the middleware
    fn middleware_executed(
        &self,
        data: Option<&dyn Any>,
        middleware_name: &str,
        count: usize,
        duration: Duration,
    ) {
    }

    /// action_reduced is called when an action is reduced.
    /// `duration_from_received` contains the total time spent from receiving to reducing.
    fn action_reduced(
        &self,
        data: Option<&dyn Any>,
        duration: Duration,
        duration_from_received: Duration,
    ) {
    }

    /// effect_issued is called when the number of effects issued.
    fn effect_issued(&self, count: usize) {}

    /// effect_executed is called when an effect is executed.
    fn effect_executed(&self, count: usize, duration: Duration) {}

    /// state_notified is called when the state is notified.
    fn state_notified(&self, data: Option<&dyn Any>) {}

    /// subscriber_notified is called when after all subscribers are notified even if there are no subscribers.
    fn subscriber_notified(&self, data: Option<&dyn Any>, count: usize, duration: Duration) {}

    /// queue_size is called when the remaining queue is changed.
    fn queue_size(&self, current_size: usize) {}

    /// error_occurred is called when an error occurs.
    fn error_occurred(&self, error: &StoreError) {}
}

pub(crate) struct CountMetrics {
    /// total number of actions received
    pub action_received: AtomicUsize,
    /// total number of actions dropped
    pub action_dropped: AtomicUsize,
    /// total time spent to process actions which includes reducing and notifying states.
    pub action_execution_time: AtomicUsize,

    /// total number of actions reduced
    pub action_reduced: AtomicUsize,
    /// max time spent in reducers
    pub reducer_time_max: AtomicUsize,
    /// min time spent in reducers
    pub reducer_time_min: AtomicUsize,
    /// total time spent in reducers
    pub reducer_execution_time: AtomicUsize,
    /// total time spent from receiving and reducing the action
    pub action_received_and_reduced_execution_time: AtomicUsize,

    /// total number of effects issued
    pub effect_issued: AtomicUsize,
    // total number of effects executed
    pub effect_executed: AtomicUsize,

    /// total number of middleware executed
    pub middleware_executed: AtomicUsize,
    /// max time spent in middleware
    pub middleware_time_max: AtomicUsize,
    /// min time spent in middleware
    pub middleware_time_min: AtomicUsize,
    /// total time spent in middleware
    pub middleware_execution_time: AtomicUsize,

    /// total number of states notified
    pub state_notified: AtomicUsize,
    /// total number of subscribers notified
    pub subscriber_notified: AtomicUsize,
    /// max time spent in subscribers
    pub subscriber_time_max: AtomicUsize,
    /// min time spent in subscribers
    pub subscriber_time_min: AtomicUsize,
    /// total time spent in subscribers
    pub subscriber_execution_time: AtomicUsize,

    /// remaining number of actions in the queue
    pub remaining_queue: AtomicUsize,
    /// max number of remaining actions in the queue
    pub remaining_queue_max: AtomicUsize,
    //pub remaining_queue_min: AtomicUsize,
    /// total number of errors occurred
    pub error_occurred: AtomicUsize,
}

impl Default for CountMetrics {
    fn default() -> Self {
        Self {
            action_received: AtomicUsize::new(0),
            action_dropped: AtomicUsize::new(0),
            action_execution_time: AtomicUsize::new(0),
            action_reduced: AtomicUsize::new(0),
            effect_issued: AtomicUsize::new(0),
            effect_executed: AtomicUsize::new(0),
            reducer_time_max: AtomicUsize::new(0),
            reducer_time_min: AtomicUsize::new(0),
            reducer_execution_time: AtomicUsize::new(0),
            action_received_and_reduced_execution_time: AtomicUsize::new(0),
            middleware_executed: AtomicUsize::new(0),
            middleware_time_max: AtomicUsize::new(0),
            middleware_time_min: AtomicUsize::new(0),
            middleware_execution_time: AtomicUsize::new(0),
            state_notified: Default::default(),
            subscriber_notified: AtomicUsize::new(0),
            subscriber_time_max: AtomicUsize::new(0),
            subscriber_time_min: AtomicUsize::new(0),
            subscriber_execution_time: AtomicUsize::new(0),
            remaining_queue: AtomicUsize::new(0),
            remaining_queue_max: AtomicUsize::new(0),
            //remaining_queue_min: AtomicUsize::new(0),
            error_occurred: AtomicUsize::new(0),
        }
    }
}

impl fmt::Display for CountMetrics {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "action_received: {:?}",
            self.action_received.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", action_dropped: {:?}",
            self.action_dropped.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", action_execution_time: {:?}",
            self.action_execution_time.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", action_reduced: {:?}",
            self.action_reduced.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", action_received_and_reduced_execution_time: {:?}",
            self.action_received_and_reduced_execution_time.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", reducer_time_max: {:?}",
            self.reducer_time_max.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", reducer_time_min: {:?}",
            self.reducer_time_min.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", reducer_execution_time: {:?}",
            self.reducer_execution_time.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", middleware_executed: {:?}",
            self.middleware_executed.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", middleware_time_max: {:?}",
            self.middleware_time_max.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", middleware_time_min: {:?}",
            self.middleware_time_min.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", middleware_execution_time: {:?}",
            self.middleware_execution_time.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", state_notified: {:?}",
            self.state_notified.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", subscriber_notified: {:?}",
            self.subscriber_notified.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", subscriber_time_max: {:?}",
            self.subscriber_time_max.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", subscriber_time_min: {:?}",
            self.subscriber_time_min.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", subscriber_execution_time: {:?}",
            self.subscriber_execution_time.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", remaining_queue: {:?}",
            self.remaining_queue.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", remaining_queue_max: {:?}",
            self.remaining_queue_max.load(Ordering::SeqCst)
        )?;
        write!(
            f,
            ", error_occurred: {:?}",
            self.error_occurred.load(Ordering::SeqCst)
        )?;

        Ok(())
    }
}

#[allow(unused_variables)]
impl Metrics for CountMetrics {
    fn action_received(&self, data: Option<&dyn Any>) {
        // #[cfg(feature = "store-log")]
        // eprintln!("action_received: {:?}", data);

        self.action_received.fetch_add(1, Ordering::SeqCst);
    }
    fn action_dropped(&self, data: Option<&dyn Any>) {
        // #[cfg(feature = "store-log")]
        // eprintln!("action_dropped: {:?}", data);
        self.action_dropped.fetch_add(1, Ordering::SeqCst);
    }
    fn action_executed(&self, data: Option<&dyn Any>, duration: Duration) {
        let duration_ms = duration.as_millis() as usize;
        self.action_execution_time.fetch_add(duration_ms, Ordering::SeqCst);
    }

    fn middleware_executed(
        &self,
        data: Option<&dyn Any>,
        _middleware_name: &str,
        count: usize,
        duration: Duration,
    ) {
        self.middleware_executed.fetch_add(count, Ordering::SeqCst);
        let duration_ms = duration.as_millis() as usize;
        if duration_ms > self.middleware_time_max.load(Ordering::SeqCst) {
            self.middleware_time_max.store(duration_ms, Ordering::SeqCst);
        }
        if self.middleware_time_min.load(Ordering::SeqCst) == 0
            || duration_ms < self.middleware_time_min.load(Ordering::SeqCst)
        {
            self.middleware_time_min.store(duration_ms, Ordering::SeqCst);
        }
        self.middleware_execution_time.fetch_add(duration_ms, Ordering::SeqCst);
    }

    fn action_reduced(
        &self,
        data: Option<&dyn Any>,
        duration: Duration,
        duration_from_received: Duration,
    ) {
        self.action_reduced.fetch_add(1, Ordering::SeqCst);
        let duration_ms = duration.as_millis() as usize;
        if duration_ms > self.reducer_time_max.load(Ordering::SeqCst) {
            self.reducer_time_max.store(duration_ms, Ordering::SeqCst);
        }
        if self.reducer_time_min.load(Ordering::SeqCst) == 0
            || duration_ms < self.reducer_time_min.load(Ordering::SeqCst)
        {
            self.reducer_time_min.store(duration_ms, Ordering::SeqCst);
        }
        self.reducer_execution_time.fetch_add(duration_ms, Ordering::SeqCst);
        self.action_received_and_reduced_execution_time.fetch_add(
            duration_from_received.as_millis() as usize,
            Ordering::SeqCst,
        );
    }

    fn effect_issued(&self, count: usize) {
        self.effect_issued.fetch_add(count, Ordering::SeqCst);
    }

    fn effect_executed(&self, count: usize, _duration: Duration) {
        self.effect_executed.fetch_add(count, Ordering::SeqCst);
    }

    fn state_notified(&self, data: Option<&dyn Any>) {
        self.state_notified.fetch_add(1, Ordering::SeqCst);
    }

    fn subscriber_notified(&self, data: Option<&dyn Any>, count: usize, duration: Duration) {
        self.subscriber_notified.fetch_add(count, Ordering::SeqCst);
        let duration_ms = duration.as_millis() as usize;
        if duration_ms > self.subscriber_time_max.load(Ordering::SeqCst) {
            self.subscriber_time_max.store(duration_ms, Ordering::SeqCst);
        }
        if self.subscriber_time_min.load(Ordering::SeqCst) == 0
            || duration_ms < self.subscriber_time_min.load(Ordering::SeqCst)
        {
            self.subscriber_time_min.store(duration_ms, Ordering::SeqCst);
        }
        self.subscriber_execution_time.fetch_add(duration_ms, Ordering::SeqCst);
    }

    fn queue_size(&self, current_size: usize) {
        self.remaining_queue.store(current_size, Ordering::SeqCst);
        if current_size > self.remaining_queue_max.load(Ordering::SeqCst) {
            self.remaining_queue_max.store(current_size, Ordering::SeqCst);
        }
        // if current_size < self.remaining_queue_min.load(Ordering::SeqCst) {
        //     self.remaining_queue_min.store(current_size, Ordering::SeqCst);
        // }
    }

    fn error_occurred(&self, error: &StoreError) {
        self.error_occurred.fetch_add(1, Ordering::SeqCst);
    }
}

#[allow(dead_code)]
impl CountMetrics {
    pub fn new() -> Arc<Self> {
        Arc::new(Self::default())
    }

    pub fn reset(&self) {
        self.action_received.store(0, Ordering::SeqCst);
        self.action_dropped.store(0, Ordering::SeqCst);
        self.action_reduced.store(0, Ordering::SeqCst);
        self.action_received_and_reduced_execution_time.store(0, Ordering::SeqCst);
        self.effect_issued.store(0, Ordering::SeqCst);
        self.effect_executed.store(0, Ordering::SeqCst);
        self.reducer_time_max.store(0, Ordering::SeqCst);
        self.reducer_time_min.store(0, Ordering::SeqCst);
        self.reducer_execution_time.store(0, Ordering::SeqCst);
        self.middleware_executed.store(0, Ordering::SeqCst);
        self.middleware_time_max.store(0, Ordering::SeqCst);
        self.middleware_time_min.store(0, Ordering::SeqCst);
        self.middleware_execution_time.store(0, Ordering::SeqCst);
        self.state_notified.store(0, Ordering::SeqCst);
        self.subscriber_notified.store(0, Ordering::SeqCst);
        self.subscriber_time_max.store(0, Ordering::SeqCst);
        self.subscriber_time_min.store(0, Ordering::SeqCst);
        self.subscriber_execution_time.store(0, Ordering::SeqCst);
        self.remaining_queue.store(0, Ordering::SeqCst);
        self.remaining_queue_max.store(0, Ordering::SeqCst);
        self.error_occurred.store(0, Ordering::SeqCst);
    }
}

/// MetricsSnapshot is a snapshot of the metrics.
#[allow(dead_code)]
#[derive(Default)]
pub struct MetricsSnapshot {
    /// total number of actions received
    pub action_received: usize,
    /// total number of actions dropped
    pub action_dropped: usize,
    /// total time spent to process actions which includes received and reduced states.
    pub action_received_and_reduced_execution_time: usize,

    /// total number of actions reduced
    pub action_reduced: usize,
    /// total number of effects issued
    pub effect_issued: usize,
    // total number of effects executed
    pub(crate) effect_executed: usize,
    /// max time spent in reducers
    pub reducer_time_max: usize,
    /// min time spent in reducers
    pub reducer_time_min: usize,
    /// total time spent in reducers
    pub reducer_execution_time: usize,
    /// total number of middleware executed
    pub middleware_executed: usize,
    /// max time spent in middleware
    pub middleware_time_max: usize,
    /// min time spent in middleware
    pub middleware_time_min: usize,
    /// total time spent in middleware
    pub middleware_execution_time: usize,
    /// total number of states notified
    pub state_notified: usize,
    /// total number of subscribers notified
    pub subscriber_notified: usize,
    /// max time spent in subscribers
    pub subscriber_time_max: usize,
    /// min time spent in subscribers
    pub subscriber_time_min: usize,
    /// total time spent in subscribers
    pub subscriber_execution_time: usize,

    // remaining number of actions in the queue
    pub(crate) remaining_queue: usize,
    // max number of remaining actions in the queue
    pub(crate) remaining_queue_max: usize,
    //pub remaining_queue_min: usize,
    /// total number of errors occurred
    pub error_occurred: usize,
}

impl From<&CountMetrics> for MetricsSnapshot {
    fn from(value: &CountMetrics) -> Self {
        Self {
            action_received: value.action_received.load(Ordering::SeqCst),
            action_dropped: value.action_dropped.load(Ordering::SeqCst),
            action_reduced: value.action_reduced.load(Ordering::SeqCst),
            action_received_and_reduced_execution_time: value
                .action_received_and_reduced_execution_time
                .load(Ordering::SeqCst),
            effect_issued: value.effect_issued.load(Ordering::SeqCst),
            effect_executed: value.effect_executed.load(Ordering::SeqCst),
            reducer_time_max: value.reducer_time_max.load(Ordering::SeqCst),
            reducer_time_min: value.reducer_time_min.load(Ordering::SeqCst),
            reducer_execution_time: value.reducer_execution_time.load(Ordering::SeqCst),
            middleware_executed: value.middleware_executed.load(Ordering::SeqCst),
            middleware_time_max: value.middleware_time_max.load(Ordering::SeqCst),
            middleware_time_min: value.middleware_time_min.load(Ordering::SeqCst),
            middleware_execution_time: value.middleware_execution_time.load(Ordering::SeqCst),
            state_notified: value.state_notified.load(Ordering::SeqCst),
            subscriber_notified: value.subscriber_notified.load(Ordering::SeqCst),
            subscriber_time_max: value.subscriber_time_max.load(Ordering::SeqCst),
            subscriber_time_min: value.subscriber_time_min.load(Ordering::SeqCst),
            subscriber_execution_time: value.subscriber_execution_time.load(Ordering::SeqCst),
            remaining_queue: value.remaining_queue.load(Ordering::SeqCst),
            remaining_queue_max: value.remaining_queue_max.load(Ordering::SeqCst),
            error_occurred: value.error_occurred.load(Ordering::SeqCst),
        }
    }
}

impl Sub<MetricsSnapshot> for MetricsSnapshot {
    type Output = MetricsSnapshot;

    fn sub(self, rhs: MetricsSnapshot) -> Self::Output {
        Self::Output {
            action_received: self.action_received - rhs.action_received,
            action_dropped: self.action_dropped - rhs.action_dropped,
            action_reduced: self.action_reduced - rhs.action_reduced,
            action_received_and_reduced_execution_time: self
                .action_received_and_reduced_execution_time
                - rhs.action_received_and_reduced_execution_time,
            effect_issued: self.effect_issued - rhs.effect_issued,
            effect_executed: self.effect_executed - rhs.effect_executed,
            reducer_time_max: self.reducer_time_max - rhs.reducer_time_max,
            reducer_time_min: self.reducer_time_min - rhs.reducer_time_min,
            reducer_execution_time: self.reducer_execution_time - rhs.reducer_execution_time,
            middleware_executed: self.middleware_executed - rhs.middleware_executed,
            middleware_time_max: self.middleware_time_max - rhs.middleware_time_max,
            middleware_time_min: self.middleware_time_min - rhs.middleware_time_min,
            middleware_execution_time: self.middleware_execution_time
                - rhs.middleware_execution_time,
            state_notified: self.state_notified - rhs.state_notified,
            subscriber_notified: self.subscriber_notified - rhs.subscriber_notified,
            subscriber_time_max: self.subscriber_time_max - rhs.subscriber_time_max,
            subscriber_time_min: self.subscriber_time_min - rhs.subscriber_time_min,
            subscriber_execution_time: self.subscriber_execution_time
                - rhs.subscriber_execution_time,
            remaining_queue: self.remaining_queue - rhs.remaining_queue,
            remaining_queue_max: self.remaining_queue_max - rhs.remaining_queue_max,
            error_occurred: self.error_occurred - rhs.error_occurred,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        BackpressurePolicy, Dispatcher, MiddlewareFn, MiddlewareFnFactory, Reducer, StoreImpl,
    };
    use std::sync::Arc;
    use std::thread;

    struct TestReducer;
    impl Reducer<i32, i32> for TestReducer {
        fn reduce(&self, state: &i32, action: &i32) -> crate::DispatchOp<i32, i32> {
            let new_state = state + action;
            thread::sleep(Duration::from_millis(10)); // Add delay to test timing
            crate::DispatchOp::Dispatch(new_state, vec![])
        }
    }

    struct TestMiddleware {
        #[allow(dead_code)]
        name: String,
    }

    impl TestMiddleware {
        fn new(name: &str) -> Self {
            Self {
                name: name.to_string(),
            }
        }
    }

    impl<State, Action> MiddlewareFnFactory<State, Action> for TestMiddleware
    where
        State: Send + Sync + Clone + 'static,
        Action: Send + Sync + Clone + 'static,
    {
        fn create(&self, inner: MiddlewareFn<State, Action>) -> MiddlewareFn<State, Action> {
            Arc::new(move |state: &State, action: &Action| inner(state, action))
        }
    }

    #[test]
    fn test_count_metrics_basic() {
        let store = StoreImpl::new_with(
            0,
            vec![Box::new(TestReducer)],
            "test".to_string(),
            5,
            BackpressurePolicy::DropOldestIf(None),
            vec![],
        )
        .unwrap();

        // when
        // Test multiple actions
        let _ = store.dispatch(1);
        let _ = store.dispatch(2);
        let _ = store.dispatch(3);

        // +1 : ActionExit
        match store.stop() {
            Ok(_) => println!("store stopped"),
            Err(e) => {
                panic!("store stop failed  : {:?}", e);
            }
        }

        // then
        let metrics = store.get_metrics();
        // +1 for ActionExit
        assert_eq!(metrics.action_received, 3 + 1);
        assert_eq!(metrics.action_reduced, 3);
        assert!(metrics.reducer_execution_time > 0);
    }

    #[test]
    fn test_count_metrics_with_dropped_actions() {
        // given
        let store = StoreImpl::new_with(
            0,
            vec![Box::new(TestReducer)],
            "test".to_string(),
            2,
            BackpressurePolicy::DropOldestIf(None),
            vec![],
        )
        .unwrap();

        // when
        // Dispatch more actions than capacity
        for i in 0..5 {
            let _ = store.dispatch(i);
        }
        match store.stop() {
            Ok(_) => println!("store stopped"),
            Err(e) => {
                panic!("store stop failed  : {:?}", e);
            }
        }

        // then
        let metrics = store.get_metrics();
        // actions should be dropped
        assert!(metrics.action_dropped > 0);
        // Remaining queue should be less than or equal to capacity
        assert!(metrics.remaining_queue_max <= 2);
    }

    #[test]
    fn test_count_metrics_with_middleware() {
        // given
        let middleware = Arc::new(TestMiddleware::new("test"));
        #[allow(deprecated)]
        let store = StoreImpl::new_with(
            0,
            vec![Box::new(TestReducer)],
            "test".to_string(),
            5,
            BackpressurePolicy::DropOldestIf(None),
            vec![middleware],
        )
        .unwrap();

        // when
        store.dispatch(1).expect("no error");
        match store.stop() {
            Ok(_) => println!("store stopped"),
            Err(e) => {
                panic!("store stop failed  : {:?}", e);
            }
        }

        // +1 for ActionExit
        let metrics = store.get_metrics();
        assert_eq!(metrics.action_received, 1 + 1);
        assert_eq!(metrics.action_reduced, 1);
        assert_eq!(metrics.state_notified, 1);
        // no subscribers
        assert_eq!(metrics.subscriber_notified, 0);
        // Middleware should be executed
        assert!(metrics.middleware_execution_time > 0);
        assert!(metrics.reducer_execution_time > 0);
        // Middleware should take longer than reducer
        assert!(
            metrics.middleware_execution_time >= metrics.reducer_execution_time,
            "middleware time should be greater than reducer time"
        );
    }

    #[test]
    fn test_count_metrics_reset() {
        let metrics: CountMetrics = CountMetrics::default();

        // Add some counts
        metrics.action_received.fetch_add(5, Ordering::SeqCst);
        metrics.action_reduced.fetch_add(3, Ordering::SeqCst);
        metrics.subscriber_notified.fetch_add(2, Ordering::SeqCst);

        // Reset
        metrics.reset();

        // Verify all counters are zero
        assert_eq!(metrics.action_received.load(Ordering::SeqCst), 0);
        assert_eq!(metrics.action_reduced.load(Ordering::SeqCst), 0);
        assert_eq!(metrics.subscriber_notified.load(Ordering::SeqCst), 0);
        assert_eq!(metrics.middleware_execution_time.load(Ordering::SeqCst), 0);
        assert_eq!(metrics.reducer_execution_time.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn test_metrics_snapshot_sub() {
        let metrics1 = MetricsSnapshot {
            action_received: 1,
            action_dropped: 2,
            action_reduced: 3,
            ..Default::default()
        };
        let metrics2 = MetricsSnapshot {
            action_received: 11,
            action_dropped: 12,
            action_reduced: 13,
            ..Default::default()
        };
        let diff = metrics2 - metrics1;
        assert_eq!(diff.action_received, 10);
        assert_eq!(diff.action_dropped, 10);
        assert_eq!(diff.action_reduced, 10);
    }
}