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
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
use crate::channel::{BackpressureChannel, BackpressurePolicy, ReceiverChannel, SenderChannel};
use crate::dispatcher::Dispatcher;
use crate::metrics::{CountMetrics, Metrics, MetricsSnapshot};
use crate::middleware::{MiddlewareFn, MiddlewareFnFactory};
use crate::subscriber::SubscriberWithId;
use crate::{DispatchOp, Effect, Reducer, SenderError, Subscriber, Subscription};
use rusty_pool::ThreadPool;
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use std::{fmt, thread};
use crate::iterator::{StateIterator, StateIteratorSubscriber};
use crate::store::{Store, StoreError, DEFAULT_CAPACITY, DEFAULT_STORE_NAME};
const DEFAULT_STOP_TIMEOUT: Duration = Duration::from_secs(5);
/// ActionOp is used to dispatch an action to the store
#[derive(Clone, PartialEq)]
pub(crate) enum ActionOp<Action>
where
Action: Send + Sync + Clone + 'static,
{
/// Action is used to dispatch an action to the store
Action(Action),
/// AddSubscriber is used to add a subscriber to the store
AddSubscriber,
/// StateFunction is used to execute a function with the current state
StateFunction,
/// Exit is used to exit the store and should not be dropped
#[allow(dead_code)]
Exit(Instant),
}
impl<Action> fmt::Debug for ActionOp<Action>
where
Action: fmt::Debug + Send + Sync + Clone + 'static,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ActionOp::Action(action) => f.debug_tuple("Action").field(action).finish(),
ActionOp::AddSubscriber => f.write_str("AddSubscriber"),
ActionOp::StateFunction => f.write_str("StateFunction"),
ActionOp::Exit(instant) => f.debug_tuple("Exit").field(instant).finish(),
}
}
}
// format Action without Debug
#[cfg(feature = "store-log")]
pub(crate) fn describe_action<Action>(_action: &Action) -> String
where
Action: Send + Sync + Clone + 'static,
{
format!("Action<{}>(..)", std::any::type_name::<Action>())
}
// format ActionOp<Action> in which Action is not bound to Debug
// #[cfg(feature = "store-log")]
pub(crate) fn describe_action_op<Action>(action_op: &ActionOp<Action>) -> String
where
Action: Send + Sync + Clone + 'static,
{
match action_op {
ActionOp::Action(_) => {
format!("Action<{}>(..)", std::any::type_name::<Action>())
}
ActionOp::AddSubscriber => "AddSubscriber".to_string(),
ActionOp::StateFunction => "StateFunction".to_string(),
ActionOp::Exit(instant) => format!("Exit({instant:?})"),
}
}
/// StoreImpl is the default implementation of a Redux store.
///
/// ## Caution
/// [`StoreImpl`] is the default implementation of the [`Store`] trait, and its interface can be changed in the future.
/// [`Store`] is the stable interface for the store that user code should depend on.
#[allow(clippy::type_complexity)]
pub struct StoreImpl<State, Action>
where
State: Send + Sync + Clone + 'static,
Action: Send + Sync + Clone + 'static,
{
#[allow(dead_code)]
pub(crate) name: String,
state: Mutex<State>,
pub(crate) reducers: Mutex<Vec<Box<dyn Reducer<State, Action> + Send + Sync>>>,
pub(crate) subscribers: Arc<Mutex<Vec<SubscriberWithId<State, Action>>>>,
/// temporary vector to store subscribers to be added
adding_subscribers: Arc<Mutex<Vec<SubscriberWithId<State, Action>>>>,
state_functions: Arc<Mutex<Vec<Box<dyn FnOnce(&State) + Send + Sync + 'static>>>>,
pub(crate) dispatch_tx: Mutex<Option<SenderChannel<Action>>>,
/// middleware factories
middleware_factories: Mutex<Vec<Arc<dyn MiddlewareFnFactory<State, Action> + Send + Sync>>>, // New middleware chain
pub(crate) metrics: Arc<CountMetrics>,
/// thread pool for the store
pub(crate) pool: Mutex<Option<ThreadPool>>,
}
/// Subscription for a subscriber
/// the subscriber can use it to unsubscribe from the store
struct SubscriberSubscription {
#[allow(dead_code)]
subscriber_id: u64, // Store subscriber ID instead of Arc reference
unsubscribe: Box<dyn Fn(u64) + Send + Sync>,
}
impl Subscription for SubscriberSubscription {
fn unsubscribe(&self) {
(self.unsubscribe)(self.subscriber_id);
}
}
impl<State, Action> StoreImpl<State, Action>
where
State: Send + Sync + Clone + 'static,
Action: Send + Sync + Clone + 'static,
{
// /// create a new store with an initial state
// pub(crate) fn new(state: State) -> Result<Arc<StoreImpl<State, Action>>, StoreError> {
// Self::new_with(
// state,
// vec![],
// DEFAULT_STORE_NAME.into(),
// DEFAULT_CAPACITY,
// BackpressurePolicy::default(),
// vec![],
// )
// }
/// create a new store with a reducer and an initial state
pub fn new_with_reducer(
state: State,
reducer: Box<dyn Reducer<State, Action> + Send + Sync>,
) -> Result<Arc<StoreImpl<State, Action>>, StoreError> {
Self::new_with(
state,
vec![reducer],
DEFAULT_STORE_NAME.into(),
DEFAULT_CAPACITY,
BackpressurePolicy::default(),
vec![],
)
}
/// create a new store with name
pub fn new_with_name(
state: State,
reducer: Box<dyn Reducer<State, Action> + Send + Sync>,
name: String,
) -> Result<Arc<StoreImpl<State, Action>>, StoreError> {
Self::new_with(
state,
vec![reducer],
name,
DEFAULT_CAPACITY,
BackpressurePolicy::default(),
vec![],
)
}
/// create a new store
pub fn new_with(
state: State,
reducers: Vec<Box<dyn Reducer<State, Action> + Send + Sync>>,
name: String,
capacity: usize,
policy: BackpressurePolicy<Action>,
middlewares: Vec<Arc<dyn MiddlewareFnFactory<State, Action> + Send + Sync>>,
) -> Result<Arc<StoreImpl<State, Action>>, StoreError> {
let metrics = Arc::new(CountMetrics::default());
let (tx, rx) = BackpressureChannel::<Action>::pair_with(
"dispatch",
capacity,
policy,
Some(metrics.clone()),
);
if reducers.is_empty() {
return Err(StoreError::InitError(
"At least one reducer is required".to_string(),
));
}
let store_impl = StoreImpl {
name: name.clone(),
state: Mutex::new(state),
reducers: Mutex::new(reducers),
subscribers: Arc::new(Mutex::new(Vec::default())),
adding_subscribers: Arc::new(Mutex::new(Vec::default())),
state_functions: Arc::new(Mutex::new(Vec::default())),
middleware_factories: Mutex::new(middlewares),
dispatch_tx: Mutex::new(Some(tx)),
metrics,
pool: Mutex::new(Some(
rusty_pool::Builder::new().name(format!("{}-pool", name)).build(),
)),
};
// start a thread in which the store will listen for actions
let rx_store = Arc::new(store_impl);
let tx_store = rx_store.clone();
// reducer thread
match tx_store.pool.lock() {
Ok(pool) => {
if let Some(pool) = pool.as_ref() {
pool.execute(move || {
StoreImpl::reducer_thread(rx, rx_store);
})
}
}
Err(_e) => {
#[cfg(feature = "store-log")]
eprintln!("store: Error while locking pool: {:?}", _e);
return Err(StoreError::InitError(format!(
"Error while locking pool: {:?}",
_e
)));
}
}
Ok(tx_store)
}
// reducer thread
pub(crate) fn reducer_thread(
rx: ReceiverChannel<Action>,
store_impl: Arc<StoreImpl<State, Action>>,
) {
#[cfg(feature = "store-log")]
eprintln!("store: reducer thread started");
let store_clone = store_impl.clone();
let reducer_middleware: MiddlewareFn<State, Action> =
Arc::new(move |state: &State, action: &Action| {
let started_at = Instant::now();
let dispatch_op = if store_clone.reducers.lock().unwrap().len() == 1 {
store_clone.reducers.lock().unwrap()[0].reduce(state, action)
} else {
let reducers = store_clone.reducers.lock().unwrap();
let mut iter = reducers.iter();
// First reducer uses the input references directly
let mut result = iter.next().unwrap().reduce(state, action);
// Remaining reducers use the result from previous reducer
for reducer in iter {
match result {
DispatchOp::Dispatch(current_state, current_effects) => {
result = reducer.reduce(¤t_state, action);
// Merge effects from both reducers
match result {
DispatchOp::Dispatch(s, mut e) => {
e.extend(current_effects);
result = DispatchOp::Dispatch(s, e);
}
DispatchOp::Keep(s, mut e) => {
e.extend(current_effects);
result = DispatchOp::Keep(s, e);
}
}
}
DispatchOp::Keep(current_state, current_effects) => {
result = reducer.reduce(¤t_state, action);
// Merge effects from both reducers
match result {
DispatchOp::Dispatch(s, mut e) => {
e.extend(current_effects);
result = DispatchOp::Dispatch(s, e);
}
DispatchOp::Keep(s, mut e) => {
e.extend(current_effects);
result = DispatchOp::Keep(s, e);
}
}
}
}
}
result
};
store_clone.metrics.action_reduced(
Some(action),
started_at.elapsed(),
Instant::now().elapsed(),
);
Ok(dispatch_op)
});
let mut middleware_deco = reducer_middleware;
// chain middlewares in **REVERSE** order
for middleware in store_impl.middleware_factories.lock().unwrap().iter().rev() {
middleware_deco = middleware.create(middleware_deco);
}
let middleware_deco_arc = Arc::new(middleware_deco);
while let Some(action_op) = rx.recv() {
let action_received_at = Instant::now();
store_impl.metrics.action_received(Some(&action_op));
#[cfg(feature = "store-log")]
eprintln!(
"store: dispatch: action: {:?}, remains: {}",
describe_action_op(&action_op),
rx.len()
);
match action_op {
ActionOp::Action(action) => {
// do reduce
// Get current state reference while holding lock for minimal time
let current_state_ref = {
let state_guard = store_impl.state.lock().unwrap();
state_guard.clone()
};
let mut effects = vec![];
let result = store_impl.do_reduce(
¤t_state_ref,
&action,
&mut effects,
middleware_deco_arc.clone(),
);
match result {
Ok(dispatch_op) => {
// do effects remain
store_impl.do_effect(&mut effects, store_impl.clone());
// do notify subscribers and update store state
match dispatch_op {
DispatchOp::Dispatch(new_state, _) => {
// Update store state
*store_impl.state.lock().unwrap() = new_state.clone();
// Notify subscribers with refs
store_impl.do_notify(
&action,
&new_state,
store_impl.clone(),
action_received_at,
);
}
DispatchOp::Keep(new_state, _) => {
// Update store state even if not dispatching
*store_impl.state.lock().unwrap() = new_state;
}
}
}
Err(_e) => {
#[cfg(feature = "store-log")]
eprintln!(
"store: error do_reduce: action: {}, remains: {}",
describe_action(&action),
rx.len()
);
}
}
// store_impl.metrics.action_executed(Some(&action), action_received_at.elapsed());
}
ActionOp::AddSubscriber => {
let mut new_subscribers = store_impl.adding_subscribers.lock().unwrap();
let new_subscribers_len = new_subscribers.len();
if new_subscribers_len > 0 {
let current_state = store_impl.state.lock().unwrap().clone();
let iter_subscribers = new_subscribers.drain(..);
store_impl.do_subscribe(current_state, iter_subscribers);
}
#[cfg(feature = "store-log")]
eprintln!("store: {} subscribers added", new_subscribers_len);
}
// ActionOp::RemoveSubscriber(subscriber_id) => {
// rx_store.do_remove_subscriber(subscriber_id);
// #[cfg(feature = "store-log")]
// eprintln!("store: {} subscribers removed", subscriber_id);
// }
ActionOp::StateFunction => {
store_impl.do_state_function();
}
ActionOp::Exit(_) => {
store_impl.on_close(action_received_at);
#[cfg(feature = "store-log")]
eprintln!("store: reducer loop exit");
break;
}
}
store_impl.metrics.action_executed(None, action_received_at.elapsed());
}
// drop all subscribers
store_impl.clear_subscribers();
#[cfg(feature = "store-log")]
eprintln!("store: reducer thread done");
}
/// get the latest state(for debugging)
///
/// prefer to use `subscribe` to get the state
pub fn get_state(&self) -> State {
self.state.lock().unwrap().clone()
}
/// get the metrics
pub fn get_metrics(&self) -> MetricsSnapshot {
(&(*self.metrics)).into()
}
// /// add a reducer to the store
// pub(crate) fn add_reducer(&self, reducer: Box<dyn Reducer<State, Action> + Send + Sync>) {
// let reducer_arc = Arc::from(reducer);
// let mut chain_guard = self.reducer_chain.lock().unwrap();
// if let Some(reducer_chain) = chain_guard.take() {
// // Chain the new reducer to the existing chain
// *chain_guard = Some(reducer_chain.chain(reducer_arc));
// } else {
// // Create new chain if none exists
// *chain_guard = Some(ReducerChain::new(reducer_arc));
// }
// }
/// add a subscriber to the store
pub fn add_subscriber(
&self,
subscriber: Arc<dyn Subscriber<State, Action> + Send + Sync>,
) -> Result<Box<dyn Subscription>, StoreError> {
// SubscriberWithId로 래핑하여 unique ID 할당
let subscriber_with_id = SubscriberWithId::new(subscriber);
let subscriber_id = subscriber_with_id.id;
// 새로운 subscriber를 adding_subscribers에 추가
self.adding_subscribers.lock().unwrap().push(subscriber_with_id);
// ActionOp::AddSubscriber 액션을 전달하여 reducer에서 처리하도록 함
if let Some(tx) = self.dispatch_tx.lock().unwrap().as_ref() {
match tx.send(ActionOp::AddSubscriber) {
Ok(_) => {}
Err(_e) => {
#[cfg(feature = "store-log")]
eprintln!(
"store: Error while sending add subscriber to dispatch channel: {:?}",
_e
);
self.adding_subscribers.lock().unwrap().retain(|s| s.id != subscriber_id);
return Err(StoreError::DispatchError(format!(
"Error while sending add subscriber to dispatch channel: {:?}",
_e
)));
}
}
} else {
self.adding_subscribers.lock().unwrap().retain(|s| s.id != subscriber_id);
return Err(StoreError::DispatchError(
"Dispatch channel is closed".to_string(),
));
}
// disposer for the subscriber
let subscribers = self.subscribers.clone();
let adding_subscribers = self.adding_subscribers.clone();
let subscription = Box::new(SubscriberSubscription {
subscriber_id, // Store the ID for comparison
unsubscribe: Box::new(move |subscriber_id| {
// dispacher는 Arc<StoreImpl<State, Action>> 이므로 RemoveSubscriber action 을 사용할 수 없는 이유
// 그래서 직접 vector에서 제거한다.
// remove from adding_subscribers
let mut adding = adding_subscribers.lock().unwrap();
adding.retain(|s| s.id != subscriber_id); // Compare by ID
let mut subscribers = subscribers.lock().unwrap();
subscribers.retain(|s| {
let retain = s.id != subscriber_id; // Compare by ID
if !retain {
s.on_unsubscribe();
}
retain
});
}),
});
Ok(subscription)
}
/// clear all subscribers
pub(crate) fn clear_subscribers(&self) {
#[cfg(feature = "store-log")]
eprintln!("store: clear_subscribers");
match self.subscribers.lock() {
Ok(mut subscribers) => {
for subscriber_with_id in subscribers.iter() {
subscriber_with_id.on_unsubscribe();
}
subscribers.clear();
}
Err(mut e) => {
#[cfg(feature = "store-log")]
eprintln!("store: Error while locking subscribers: {:?}", e);
for subscriber_with_id in e.get_ref().iter() {
subscriber_with_id.on_unsubscribe();
}
e.get_mut().clear();
}
}
}
/// Run middleware + reducers for a single action.
///
/// ### Parameters
/// * `state`: Current state reference
/// * `action`: Action reference
/// * `effects`: Mutable reference to an effects buffer that will be extended with all emitted effects
/// * `middleware_deco`: Middleware chain entry point
///
/// ### Returns
/// * `Ok(DispatchOp<State, Action>)`: dispatch operation containing the next state and effects
/// * `Err(StoreError)`: if an error occurs in middleware or reducers
pub(crate) fn do_reduce(
&self,
state: &State,
action: &Action,
effects: &mut Vec<Effect<Action>>,
middleware_deco: Arc<MiddlewareFn<State, Action>>,
) -> Result<DispatchOp<State, Action>, StoreError> {
let started_at = Instant::now();
// call middleware chain
let mut dispatch_op = middleware_deco(state, action)?;
// Extract effects from DispatchOp and add to effects vector (mutable parameter)
match &mut dispatch_op {
DispatchOp::Dispatch(_, ref mut result_effects) => {
effects.append(result_effects);
}
DispatchOp::Keep(_, ref mut result_effects) => {
effects.append(result_effects);
}
}
self.metrics.middleware_executed(Some(action), "", 1, started_at.elapsed());
Ok(dispatch_op)
}
pub(crate) fn do_effect(
&self,
effects: &mut Vec<Effect<Action>>,
dispatcher: Arc<StoreImpl<State, Action>>,
) {
let effect_start = Instant::now();
self.metrics.effect_issued(effects.len());
let effects_total = effects.len();
while !effects.is_empty() {
let effect = effects.remove(0);
match effect {
Effect::Action(a) => {
dispatcher.dispatch_thunk(Box::new(
move |weak_dispatcher| match weak_dispatcher.dispatch(a) {
Ok(_) => {}
Err(_e) => {
#[cfg(feature = "store-log")]
eprintln!("Error while dispatching action: {:?}", _e);
}
},
));
}
Effect::Task(task) => {
dispatcher.dispatch_task(task);
}
Effect::Thunk(thunk) => {
dispatcher.dispatch_thunk(thunk);
}
Effect::Function(_tok, func) => {
let dispatcher_clone = dispatcher.clone();
dispatcher.dispatch_task(Box::new(move || {
// Execute the function and try to convert result to Action
match func() {
Ok(result) => {
// Try to downcast the result to Action type first
if let Ok(action) = result.downcast::<Action>() {
let _ = dispatcher_clone.dispatch(*action);
return;
}
// Note: Generic conversion from result to Action is not type-safe
// Effect::Function results should be handled by middleware or
// use Effect::Thunk/Effect::Action instead for type safety
#[cfg(feature = "store-log")]
eprintln!("Effect function should be handled by a middleware, did you miss a middleware?");
}
Err(_e) => {
// Error in effect function, ignore
#[cfg(feature = "store-log")]
eprintln!("Effect function error: {:?}", _e);
}
}
}));
}
};
}
let duration = effect_start.elapsed();
self.metrics.effect_executed(effects_total, duration);
}
pub(crate) fn do_notify(
&self,
action: &Action,
next_state: &State,
_dispatcher: Arc<StoreImpl<State, Action>>,
_action_received_at: Instant,
) {
let notify_start = Instant::now();
self.metrics.state_notified(Some(next_state));
#[cfg(feature = "store-log")]
eprintln!("store: notify: action: {}", describe_action(action));
let subscribers = self.subscribers.lock().unwrap().clone();
let subscriber_count = subscribers.len();
// Clone action for metrics
let action_for_metrics = action.clone();
// Notify all subscribers with refs (no clone needed)
for subscriber_with_id in subscribers.iter() {
subscriber_with_id.on_notify(next_state, action);
}
let duration = notify_start.elapsed();
self.metrics.subscriber_notified(Some(&action_for_metrics), subscriber_count, duration);
}
fn do_subscribe(
&self,
state: State,
new_subscribers: impl Iterator<Item = SubscriberWithId<State, Action>>,
) {
let mut subscribers = self.subscribers.lock().unwrap();
// notify new subscribers with the latest state and add to subscribers
for subscriber_with_id in new_subscribers {
subscriber_with_id.on_subscribe(&state);
subscribers.push(subscriber_with_id);
}
}
#[allow(dead_code)]
fn do_remove_subscriber(&self, subscriber_id: u64) {
// remove from adding_subscribers
let mut adding_subscribers = self.adding_subscribers.lock().unwrap();
adding_subscribers.retain(|s| s.id != subscriber_id);
// remove from subscribers
let mut subscribers = self.subscribers.lock().unwrap();
subscribers.retain(|s| {
let retain = s.id != subscriber_id;
if !retain {
s.on_unsubscribe();
}
retain
});
}
fn do_state_function(&self) {
let state_ref = match self.state.lock() {
Ok(state) => state,
Err(_e) => {
#[cfg(feature = "store-log")]
eprintln!("store: Error while locking state: {:?}", _e);
return;
}
};
match self.state_functions.lock() {
Ok(mut state_functions) => {
for state_function in state_functions.drain(..) {
state_function(&state_ref);
}
//state_functions.clear();
}
Err(_e) => {
#[cfg(feature = "store-log")]
eprintln!("store: Error while locking state functions: {:?}", _e);
}
};
}
fn on_close(&self, action_received_at: Instant) {
#[cfg(feature = "store-log")]
eprintln!("store: on_close");
self.metrics.action_executed(None, action_received_at.elapsed());
}
/// close the store
///
/// send an exit action to the store and drop the dispatch channel
///
/// ## Return
/// * Ok(()) : if the store is closed
/// * Err(StoreError) : if the store is not closed, this can be happened when the queue is full
pub fn close(&self) -> Result<(), StoreError> {
// take the ownership and release the lock to avoid deadlock
let dispatch_tx = self.dispatch_tx.lock().map(|mut tx| tx.take());
match dispatch_tx {
Ok(Some(tx)) => {
#[cfg(feature = "store-log")]
eprintln!("store: close: sending exit to dispatch channel");
match tx.send(ActionOp::Exit(Instant::now())) {
Ok(_) => {
#[cfg(feature = "store-log")]
eprintln!("store: close: dispatch channel sent exit");
}
Err(_e) => {
#[cfg(feature = "store-log")]
eprintln!(
"store: close: Error while sending exit to dispatch channel: {:?}",
_e
);
return Err(StoreError::DispatchError(format!(
"Error while sending exit to dispatch channel, try it later: {:?}",
_e
)));
}
}
}
Ok(None) => {
#[cfg(feature = "store-log")]
eprintln!("store: close: dispatch channel already closed");
return Ok(());
}
Err(_e) => {
#[cfg(feature = "store-log")]
eprintln!(
"store: close: Error while locking dispatch channel: {:?}",
_e
);
return Err(StoreError::DispatchError(format!(
"Error while locking dispatch channel: {:?}",
_e
)));
}
}
#[cfg(feature = "store-log")]
eprintln!("store: close: dispatch channel closed");
Ok(())
}
/// close the store and wait for the dispatcher to finish
///
/// ## Return
/// * Ok(()) : if the store is closed
/// * Err(StoreError) : if the store is not closed, this can be happened when the queue is full
pub fn stop(&self) -> Result<(), StoreError> {
self.stop_with_timeout(Duration::from_millis(0))
}
/// close the store and wait for the dispatcher to finish
pub fn stop_with_timeout(&self, timeout: Duration) -> Result<(), StoreError> {
match self.close() {
Ok(_) => {}
Err(_e) => {
#[cfg(feature = "store-log")]
eprintln!("store: Error while closing dispatch channel: {:?}", _e);
// fall through
//return Err(_e);
}
}
// Shutdown the thread pool with timeout
// take the ownership and release the lock to avoid deadlock
let pool = self.pool.lock().map(|mut pool_guard| pool_guard.take());
match pool {
Ok(Some(pool)) => {
if timeout.is_zero() {
pool.shutdown_join();
} else {
pool.shutdown_join_timeout(timeout);
}
#[cfg(feature = "store-log")]
eprintln!("store: pool shutdown completed");
}
Ok(None) => {
#[cfg(feature = "store-log")]
eprintln!("store: pool already shutdown");
}
Err(_e) => {
#[cfg(feature = "store-log")]
eprintln!("store: Error while locking pool: {:?}", _e);
return Err(StoreError::DispatchError(format!(
"Error while shutting down pool: {:?}",
_e
)));
}
}
#[cfg(feature = "store-log")]
eprintln!("store: stopped");
Ok(())
}
/// dispatch an action
///
/// ### Return
/// * Ok(()) : if the action is dispatched
/// * Err(StoreError) : if the dispatch channel is closed
pub(crate) fn dispatch(&self, action: Action) -> Result<(), StoreError> {
let sender = self.dispatch_tx.lock().unwrap();
if let Some(tx) = sender.as_ref() {
// the number of remaining actions in the channel
match tx.send(ActionOp::Action(action)) {
Ok(remains) => {
self.metrics.queue_size(remains as usize);
Ok(())
}
Err(e) => match e {
SenderError::SendError(action_op) => {
let action_desc = describe_action_op(&action_op);
let err = StoreError::DispatchError(format!(
"Error while sending '{}' to dispatch channel",
action_desc
));
self.metrics.error_occurred(&err);
Err(err)
}
SenderError::ChannelClosed => {
let err =
StoreError::DispatchError("Dispatch channel is closed".to_string());
self.metrics.error_occurred(&err);
Err(err)
}
},
}
} else {
let err = StoreError::DispatchError("Dispatch channel is closed".to_string());
self.metrics.error_occurred(&err);
Err(err)
}
}
/// Query the current state with a function.
///
/// The function will be executed in the store thread with the current state *moved* into it.
/// This is useful for read‑only inspections or aggregations that should observe a consistent snapshot.
///
/// ### Parameters
/// * `query_fn`: A function that receives the current state by value (`State`)
///
/// ### Returns
/// * `Ok(())` : if the query is scheduled successfully
/// * `Err(StoreError)` : if the store is not available
pub fn query_state<F>(&self, query_fn: F) -> Result<(), StoreError>
where
F: FnOnce(&State) + Send + Sync + 'static,
{
self.state_functions.lock().unwrap().push(Box::new(query_fn));
if let Ok(tx) = self.dispatch_tx.lock() {
if let Some(tx) = tx.as_ref() {
return match tx.send(ActionOp::StateFunction) {
Ok(_) => Ok(()),
Err(e) => Err(StoreError::DispatchError(format!(
"Error while sending state function to dispatch channel: {:?}",
e
))),
};
}
Err(StoreError::DispatchError(
"Dispatch channel is closed".to_string(),
))
} else {
Err(StoreError::DispatchError(
"Dispatch channel is closed".to_string(),
))
}
}
// /// Add middleware
// pub(crate) fn add_middleware(&self, middleware: Arc<dyn NewMiddlewareFnFactory<State, Action> + Send + Sync>) {
// self.middleware_factories.lock().unwrap().push(middleware);
// }
/// Iterator for the state
///
/// it uses a channel to subscribe to the state changes
/// the channel is rendezvous(capacity 1), the store will block on the channel until the subscriber consumes the state
#[allow(dead_code)]
#[doc(hidden)]
pub(crate) fn iter(&self) -> Result<impl Iterator<Item = (State, Action)>, StoreError> {
self.iter_with(1, BackpressurePolicy::BlockOnFull)
}
/// Iterator for the state
///
/// ### Parameters
/// * capacity: the capacity of the channel
/// * policy: the backpressure policy
#[allow(dead_code)]
#[doc(hidden)]
pub(crate) fn iter_with(
&self,
capacity: usize,
policy: BackpressurePolicy<(State, Action)>,
) -> Result<impl Iterator<Item = (State, Action)>, StoreError> {
let (iter_tx, iter_rx) = BackpressureChannel::<(State, Action)>::pair_with(
"store_iter",
capacity,
policy,
Some(self.metrics.clone()),
);
let subscription = self.add_subscriber(Arc::new(StateIteratorSubscriber::new(iter_tx)));
Ok(StateIterator::new(iter_rx, subscription?))
}
/// subscribing to store updates in new context
/// with default capacity and `BlockOnFull` policy when the channel is full
///
/// ## Parameters
/// * subscriber: The subscriber to subscribe to the store
///
/// ## Return
/// * Subscription: Subscription for the store,
pub fn subscribed(
&self,
subscriber: Box<dyn Subscriber<State, Action> + Send + Sync>,
) -> Result<Box<dyn Subscription>, StoreError> {
self.subscribed_with(
DEFAULT_CAPACITY,
BackpressurePolicy::BlockOnFull,
subscriber,
)
}
/// subscribing to store updates in new context
///
/// ### Parameters
/// * capacity: Channel buffer capacity
/// * policy: Backpressure policy for when down channel(store to subscriber) is full
///
/// ### Return
/// * Subscription: Subscription for the store,
pub fn subscribed_with(
&self,
capacity: usize,
policy: BackpressurePolicy<(Instant, State, Action)>,
subscriber: Box<dyn Subscriber<State, Action> + Send + Sync>,
) -> Result<Box<dyn Subscription>, StoreError> {
// spsc channel
let (tx, rx) = BackpressureChannel::<(Instant, State, Action)>::pair_with(
format!("{}-channel", self.name).as_str(),
capacity,
policy,
Some(self.metrics.clone()),
);
// channeled thread
let thread_name = format!("{}-channeled-subscriber", self.name);
let metrics_clone = self.metrics.clone();
let builder = thread::Builder::new().name(thread_name.clone());
let handle = match builder.spawn(move || {
// subscribe to the store
Self::subscribed_loop(thread_name, rx, subscriber, metrics_clone);
}) {
Ok(h) => h,
Err(e) => {
#[cfg(feature = "store-log")]
eprintln!("store: Error while spawning channel thread: {:?}", e);
return Err(StoreError::SubscriptionError(format!(
"Error while spawning channel thread: {:?}",
e
)));
}
};
// subscribe to the store
let channel_subscriber = Arc::new(ChanneledSubscriber::new(handle, tx));
let subscription = self.add_subscriber(channel_subscriber);
// return subscription
#[allow(clippy::let_and_return)]
subscription
}
fn subscribed_loop(
_name: String,
rx: ReceiverChannel<(Instant, State, Action)>,
subscriber: Box<dyn Subscriber<State, Action>>,
metrics: Arc<dyn Metrics>,
) {
#[cfg(feature = "store-log")]
eprintln!("store: {} channel thread started", _name);
while let Some(msg) = rx.recv() {
match msg {
ActionOp::Action((created_at, state, action)) => {
let started_at = Instant::now();
{
subscriber.on_notify(&state, &action);
}
metrics.subscriber_notified(Some(&action), 1, started_at.elapsed());
// action executed
metrics.action_executed(Some(&action), created_at.elapsed());
}
ActionOp::AddSubscriber => {
// AddSubscriber는 채널된 subscriber에서는 처리하지 않음
// 이는 메인 reducer 스레드에서만 처리됨
#[cfg(feature = "store-log")]
eprintln!("store: {} received AddSubscriber (ignored)", _name);
}
ActionOp::StateFunction => {
#[cfg(feature = "store-log")]
eprintln!("store: {} received StateFunction (ignored)", _name);
}
ActionOp::Exit(created_at) => {
metrics.action_executed(None, created_at.elapsed());
#[cfg(feature = "store-log")]
eprintln!("store: {} channel thread loop exit", _name);
break;
}
}
}
#[cfg(feature = "store-log")]
eprintln!("store: {} channel thread done", _name);
}
}
/// Subscriber implementation that forwards store updates to a channel
struct ChanneledSubscriber<T>
where
T: Send + Sync + Clone + 'static,
{
handle: Mutex<Option<JoinHandle<()>>>,
tx: Mutex<Option<SenderChannel<T>>>,
}
impl<T> ChanneledSubscriber<T>
where
T: Send + Sync + Clone + 'static,
{
pub(crate) fn new(handle: JoinHandle<()>, tx: SenderChannel<T>) -> Self {
Self {
handle: Mutex::new(Some(handle)),
tx: Mutex::new(Some(tx)),
}
}
fn clear_resource(&self) {
// drop channel
// take the ownership and release the lock to avoid deadlock
let tx_owned = self.tx.lock().map(|mut tx| tx.take());
match tx_owned {
Ok(Some(tx)) => {
#[cfg(feature = "store-log")]
eprintln!("store: ChanneledSubscriber: clearing resource: sending exit");
let _ = tx.send(ActionOp::Exit(Instant::now()));
drop(tx);
}
Ok(None) => {
#[cfg(feature = "store-log")]
eprintln!("store: ChanneledSubscriber: clearing resource: channel already closed");
}
Err(_e) => {
#[cfg(feature = "store-log")]
eprintln!(
"store: ChanneledSubscriber: clearing resource: Error while locking channel: {:?}",
_e
);
}
}
// join the thread
let handled_owned = self.handle.lock().map(|mut handle| handle.take());
match handled_owned {
Ok(Some(h)) => {
#[cfg(feature = "store-log")]
eprintln!("store: ChanneledSubscriber: clearing resource: joining thread");
let _ = h.join();
}
Ok(None) => {
#[cfg(feature = "store-log")]
eprintln!("store: ChanneledSubscriber: clearing resource: thread already joined");
}
Err(_e) => {
#[cfg(feature = "store-log")]
eprintln!(
"store: ChanneledSubscriber: clearing resource: Error while locking thread handle: {:?}",
_e
);
}
}
}
}
impl<State, Action> Subscriber<State, Action> for ChanneledSubscriber<(Instant, State, Action)>
where
State: Send + Sync + Clone + 'static,
Action: Send + Sync + Clone + 'static,
{
fn on_notify(&self, state: &State, action: &Action) {
match self.tx.lock() {
Ok(tx) => {
// Clone needed for sending through channel
tx.as_ref().map(|tx| {
tx.send(ActionOp::Action((
Instant::now(),
state.clone(),
action.clone(),
)))
});
}
Err(_e) => {
#[cfg(feature = "store-log")]
eprintln!("store: Error while locking channel: {:?}", _e);
}
}
}
fn on_unsubscribe(&self) {
self.clear_resource();
}
}
impl<T> Subscription for ChanneledSubscriber<T>
where
T: Send + Sync + Clone + 'static,
{
fn unsubscribe(&self) {
self.clear_resource();
}
}
/// close tx channel when the store is dropped, but not the dispatcher
/// if you want to stop the dispatcher, call the stop method
impl<State, Action> Drop for StoreImpl<State, Action>
where
State: Send + Sync + Clone + 'static,
Action: Send + Sync + Clone + 'static,
{
fn drop(&mut self) {
let _ = self.close();
// Shutdown the thread pool with timeout
let _ = self.stop_with_timeout(DEFAULT_STOP_TIMEOUT);
// if let Ok(mut lk) = self.pool.lock() {
// if let Some(pool) = lk.take() {
// pool.shutdown_join_timeout(Duration::from_secs(3));
// }
// }
#[cfg(feature = "store-log")]
eprintln!("store: '{}' dropped", self.name);
}
}
impl<State, Action> Store<State, Action> for StoreImpl<State, Action>
where
State: Send + Sync + Clone + 'static,
Action: Send + Sync + Clone + std::fmt::Debug + 'static,
{
fn get_state(&self) -> State {
self.get_state()
}
fn dispatch(&self, action: Action) -> Result<(), StoreError> {
self.dispatch(action)
}
fn add_subscriber(
&self,
subscriber: Arc<dyn Subscriber<State, Action> + Send + Sync>,
) -> Result<Box<dyn Subscription>, StoreError> {
self.add_subscriber(subscriber)
}
fn subscribed(
&self,
subscriber: Box<dyn Subscriber<State, Action> + Send + Sync>,
) -> Result<Box<dyn Subscription>, StoreError> {
self.subscribed(subscriber)
}
fn subscribed_with(
&self,
capacity: usize,
policy: BackpressurePolicy<(Instant, State, Action)>,
subscriber: Box<dyn Subscriber<State, Action> + Send + Sync>,
) -> Result<Box<dyn Subscription>, StoreError> {
self.subscribed_with(capacity, policy, subscriber)
}
fn stop(&self) -> Result<(), StoreError> {
self.stop()
}
fn stop_timeout(&self, timeout: Duration) -> Result<(), StoreError> {
self.stop_with_timeout(timeout)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{BackpressurePolicy, Dispatcher, Effect, FnReducer, Reducer, StoreBuilder};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
struct TestChannelSubscriber {
received: Arc<Mutex<Vec<(i32, i32)>>>,
}
impl TestChannelSubscriber {
fn new(received: Arc<Mutex<Vec<(i32, i32)>>>) -> Self {
Self { received }
}
}
impl Subscriber<i32, i32> for TestChannelSubscriber {
fn on_notify(&self, state: &i32, action: &i32) {
//println!("TestChannelSubscriber: state={}, action={}", state, action);
self.received.lock().unwrap().push((*state, *action));
}
}
struct TestReducer;
impl Reducer<i32, i32> for TestReducer {
fn reduce(&self, state: &i32, action: &i32) -> DispatchOp<i32, i32> {
DispatchOp::Dispatch(state + action, vec![])
}
}
struct SlowSubscriber {
received: Arc<Mutex<Vec<(i32, i32)>>>,
delay: Duration,
}
impl SlowSubscriber {
fn new(received: Arc<Mutex<Vec<(i32, i32)>>>, delay: Duration) -> Self {
Self { received, delay }
}
}
impl Subscriber<i32, i32> for SlowSubscriber {
fn on_notify(&self, state: &i32, action: &i32) {
//println!("SlowSubscriber: state={}, action={}", state, action);
std::thread::sleep(self.delay);
self.received.lock().unwrap().push((*state, *action));
}
}
#[test]
fn test_store_subscribed_basic() {
// Setup store with a simple counter
let initial_state = 0;
let reducer = Box::new(TestReducer);
let store_result = StoreImpl::new_with_reducer(initial_state, reducer);
assert!(store_result.is_ok());
let store = store_result.unwrap();
// Create subscriber to receive updates
let received_states = Arc::new(Mutex::new(Vec::new()));
let subscriber1 = Box::new(TestChannelSubscriber::new(received_states.clone()));
// Create channel
let subscription =
store.subscribed_with(10, BackpressurePolicy::DropOldestIf(None), subscriber1);
// Dispatch some actions
store.dispatch(1).unwrap();
store.dispatch(2).unwrap();
// Give some time for processing
// thread::sleep(Duration::from_millis(100));
match store.stop() {
Ok(_) => println!("store stopped"),
Err(e) => {
panic!("store stop failed : {:?}", e);
}
}
// unsubscribe from the channel
subscription.unwrap().unsubscribe();
// Verify received updates
let states = received_states.lock().unwrap();
assert_eq!(states.len(), 2);
assert_eq!(states[0], (1, 1)); // (state, action)
assert_eq!(states[1], (3, 2)); // state=1+2, action=2
}
#[test]
fn test_store_subscribed_backpressure() {
let store_result = StoreImpl::new_with_reducer(0, Box::new(TestReducer));
assert!(store_result.is_ok());
let store = store_result.unwrap();
let received = Arc::new(Mutex::new(Vec::new()));
let received_clone = received.clone();
let subscriber = Box::new(SlowSubscriber::new(
received_clone,
Duration::from_millis(100),
));
// Create channel with small capacity
let subscription =
store.subscribed_with(1, BackpressurePolicy::DropOldestIf(None), subscriber);
// Fill the channel
for i in 0..5 {
let _ = store.dispatch(i).unwrap();
}
// Give some time for having channel thread to process
thread::sleep(Duration::from_millis(200));
match store.stop() {
Ok(_) => println!("store stopped"),
Err(e) => {
panic!("store stop failed : {:?}", e);
}
}
subscription.unwrap().unsubscribe();
// Should only receive the latest updates due to backpressure
let received = received.lock().unwrap();
assert!(received.len() <= 2); // Some messages should be dropped
if let Some((state, action)) = received.last() {
assert_eq!(*action, 4); // Last action should be received
assert!(*state <= 10); // Final state should be sum of 0..5
}
}
#[test]
fn test_store_subscribed_subscription() {
let store = StoreImpl::new_with_reducer(0, Box::new(TestReducer)).unwrap();
let received = Arc::new(Mutex::new(Vec::new()));
let subscriber1 = Box::new(TestChannelSubscriber::new(received.clone()));
let subscription =
store.subscribed_with(10, BackpressurePolicy::DropOldestIf(None), subscriber1);
// Dispatch some actions
store.dispatch(1).unwrap();
// give some time for processing
thread::sleep(Duration::from_millis(100));
// subscriber should receive the state
assert_eq!(received.lock().unwrap().len(), 1);
// unsubscribe
subscription.unwrap().unsubscribe();
// dispatch more actions
store.dispatch(2).unwrap();
store.dispatch(3).unwrap();
// give some time for processing
match store.stop() {
Ok(_) => println!("store stopped"),
Err(e) => {
panic!("store stop failed : {:?}", e);
}
}
// subscriber should not receive the state
assert_eq!(received.lock().unwrap().len(), 1);
}
// 새로운 subscriber가 추가될 때 최신 상태를 받는지 테스트
#[test]
fn test_new_subscriber_receives_latest_state() {
let store = StoreImpl::new_with_reducer(0, Box::new(TestReducer)).unwrap();
// 첫 번째 subscriber 추가
let received1 = Arc::new(Mutex::new(Vec::new()));
let subscriber1 = Arc::new(TestChannelSubscriber::new(received1.clone()));
store.add_subscriber(subscriber1).unwrap();
// 액션을 dispatch하여 상태 변경
store.dispatch(5).unwrap();
store.dispatch(10).unwrap();
// 잠시 대기하여 액션이 처리되도록 함
thread::sleep(Duration::from_millis(100));
// 두 번째 subscriber 추가 (현재 상태는 15)
let received2 = Arc::new(Mutex::new(Vec::new()));
let subscriber2 = Arc::new(TestChannelSubscriber::new(received2.clone()));
store.add_subscriber(subscriber2).unwrap();
// 잠시 대기하여 AddSubscriber 액션이 처리되도록 함
thread::sleep(Duration::from_millis(100));
// 새로운 액션을 dispatch
store.dispatch(20).unwrap();
// 잠시 대기하여 액션이 처리되도록 함
thread::sleep(Duration::from_millis(100));
// 첫 번째 subscriber는 모든 상태 변경을 받아야 함
let received1 = received1.lock().unwrap();
assert_eq!(received1.len(), 3);
assert_eq!(received1[0], (5, 5));
assert_eq!(received1[1], (15, 10));
assert_eq!(received1[2], (35, 20));
// 두 번째 subscriber는 추가된 후의 상태 변경만 받아야 함
let received2 = received2.lock().unwrap();
assert_eq!(received2.len(), 1);
assert_eq!(received2[0], (35, 20));
}
// 새로운 subscriber가 추가될 때 on_subscribe가 호출되는지 테스트
#[test]
fn test_new_subscriber_on_subscribe_called() {
let store = StoreImpl::new_with_reducer(0, Box::new(TestReducer)).unwrap();
// 액션을 dispatch하여 상태 변경
store.dispatch(5).unwrap();
// on_subscribe를 구현한 subscriber 추가
let received_states = Arc::new(Mutex::new(Vec::new()));
let subscribe_called = Arc::new(Mutex::new(false));
struct TestSubscribeSubscriber {
received_states: Arc<Mutex<Vec<i32>>>,
subscribe_called: Arc<Mutex<bool>>,
}
impl Subscriber<i32, i32> for TestSubscribeSubscriber {
fn on_subscribe(&self, state: &i32) {
self.received_states.lock().unwrap().push(*state);
*self.subscribe_called.lock().unwrap() = true;
}
fn on_notify(&self, state: &i32, _action: &i32) {
self.received_states.lock().unwrap().push(*state);
}
}
let subscriber = Arc::new(TestSubscribeSubscriber {
received_states: received_states.clone(),
subscribe_called: subscribe_called.clone(),
});
store.add_subscriber(subscriber).unwrap();
// 잠시 대기하여 AddSubscriber 액션이 처리되도록 함
thread::sleep(Duration::from_millis(100));
// on_subscribe가 호출되었는지 확인
assert!(*subscribe_called.lock().unwrap());
// 최신 상태(5)를 받았는지 확인
let states = received_states.lock().unwrap();
assert_eq!(states.len(), 1);
assert_eq!(states[0], 5);
}
// 여러 subscriber가 동시에 추가될 때 테스트
#[test]
fn test_multiple_subscribers_added_simultaneously() {
let store = StoreImpl::new_with_reducer(0, Box::new(TestReducer)).unwrap();
// 액션을 dispatch하여 상태 변경
store.dispatch(10).unwrap();
store.dispatch(20).unwrap();
// 잠시 대기하여 액션이 처리되도록 함
thread::sleep(Duration::from_millis(100));
// 여러 subscriber를 동시에 추가
let subscribers = vec![
Arc::new(TestChannelSubscriber::new(Arc::new(Mutex::new(Vec::new())))),
Arc::new(TestChannelSubscriber::new(Arc::new(Mutex::new(Vec::new())))),
Arc::new(TestChannelSubscriber::new(Arc::new(Mutex::new(Vec::new())))),
];
for subscriber in &subscribers {
store.add_subscriber(subscriber.clone()).unwrap();
}
// 잠시 대기하여 AddSubscriber 액션이 처리되도록 함
thread::sleep(Duration::from_millis(100));
// 새로운 액션을 dispatch
store.dispatch(30).unwrap();
// 잠시 대기하여 액션이 처리되도록 함
thread::sleep(Duration::from_millis(100));
// 모든 subscriber가 새로운 액션을 받았는지 확인
for subscriber in &subscribers {
let received = subscriber.received.lock().unwrap();
assert_eq!(received.len(), 1);
assert_eq!(received[0], (60, 30)); // state: 30+30, action: 30
}
}
// subscriber 추가 후 즉시 unsubscribe하는 테스트
#[test]
fn test_subscriber_unsubscribe_after_add() {
let store = StoreImpl::new_with_reducer(0, Box::new(TestReducer)).unwrap();
// 액션을 dispatch하여 상태 변경
store.dispatch(5).unwrap();
// subscriber 추가
let received = Arc::new(Mutex::new(Vec::new()));
let subscriber = Arc::new(TestChannelSubscriber::new(received.clone()));
let subscription = store.add_subscriber(subscriber).unwrap();
// 잠시 대기하여 AddSubscriber 액션이 처리되도록 함
thread::sleep(Duration::from_millis(100));
// 즉시 unsubscribe
subscription.unsubscribe();
// 새로운 액션을 dispatch
store.dispatch(10).unwrap();
// 잠시 대기하여 액션이 처리되도록 함
thread::sleep(Duration::from_millis(100));
// subscriber가 새로운 액션을 받지 않았는지 확인
let received = received.lock().unwrap();
assert_eq!(received.len(), 0);
}
// store가 중지된 후 subscriber를 추가하는 테스트
#[test]
fn test_add_subscriber_after_store_stop() {
let store = StoreImpl::new_with_reducer(0, Box::new(TestReducer)).unwrap();
// store 중지
match store.stop() {
Ok(_) => println!("store stopped"),
Err(e) => {
panic!("store stop failed : {:?}", e);
}
}
// subscriber 추가 시도
let received = Arc::new(Mutex::new(Vec::new()));
let subscriber = Arc::new(TestChannelSubscriber::new(received.clone()));
let subscription = store.add_subscriber(subscriber);
assert!(subscription.is_err());
}
// on_subscribe에서 상태를 수정하는 subscriber 테스트
#[test]
fn test_subscriber_modifies_state_in_on_subscribe() {
let store = StoreImpl::new_with_reducer(0, Box::new(TestReducer)).unwrap();
// 액션을 dispatch하여 상태 변경
store.dispatch(5).unwrap();
struct ModifyingSubscriber {
received_states: Arc<Mutex<Vec<i32>>>,
subscribe_called: Arc<Mutex<bool>>,
}
impl Subscriber<i32, i32> for ModifyingSubscriber {
fn on_subscribe(&self, state: &i32) {
// on_subscribe에서 상태를 수정해도 store의 상태는 변경되지 않음
self.received_states.lock().unwrap().push(*state);
*self.subscribe_called.lock().unwrap() = true;
}
fn on_notify(&self, state: &i32, _action: &i32) {
self.received_states.lock().unwrap().push(*state);
}
}
let subscriber = Arc::new(ModifyingSubscriber {
received_states: Arc::new(Mutex::new(Vec::new())),
subscribe_called: Arc::new(Mutex::new(false)),
});
store.add_subscriber(subscriber.clone()).unwrap();
// 잠시 대기하여 AddSubscriber 액션이 처리되도록 함
thread::sleep(Duration::from_millis(100));
// on_subscribe가 호출되었는지 확인
assert!(*subscriber.subscribe_called.lock().unwrap());
// 최신 상태(5)를 받았는지 확인
let states = subscriber.received_states.lock().unwrap();
assert_eq!(states.len(), 1);
assert_eq!(states[0], 5);
// store의 상태가 변경되지 않았는지 확인
assert_eq!(store.get_state(), 5);
}
// 여러 번의 AddSubscriber 액션이 연속으로 발생하는 테스트
#[test]
fn test_consecutive_add_subscriber_actions() {
let store = StoreImpl::new_with_reducer(0, Box::new(TestReducer)).unwrap();
// 첫 번째 subscriber 추가
let received1 = Arc::new(Mutex::new(Vec::new()));
let subscriber1 = Arc::new(TestChannelSubscriber::new(received1.clone()));
store.add_subscriber(subscriber1).unwrap();
// 잠시 대기
thread::sleep(Duration::from_millis(50));
// 두 번째 subscriber 추가
let received2 = Arc::new(Mutex::new(Vec::new()));
let subscriber2 = Arc::new(TestChannelSubscriber::new(received2.clone()));
store.add_subscriber(subscriber2).unwrap();
// 잠시 대기
thread::sleep(Duration::from_millis(50));
// 세 번째 subscriber 추가
let received3 = Arc::new(Mutex::new(Vec::new()));
let subscriber3 = Arc::new(TestChannelSubscriber::new(received3.clone()));
store.add_subscriber(subscriber3).unwrap();
// 잠시 대기하여 모든 AddSubscriber 액션이 처리되도록 함
thread::sleep(Duration::from_millis(100));
// 새로운 액션을 dispatch
store.dispatch(10).unwrap();
// 잠시 대기하여 액션이 처리되도록 함
thread::sleep(Duration::from_millis(100));
// 모든 subscriber가 새로운 액션을 받았는지 확인
assert_eq!(received1.lock().unwrap().len(), 1);
assert_eq!(received2.lock().unwrap().len(), 1);
assert_eq!(received3.lock().unwrap().len(), 1);
}
/// Test basic iterator functionality
#[test]
fn test_store_iter_basic() {
// given: store with reducer
// let store = StoreBuilder::new(0)
// .with_reducer(Box::new(FnReducer::from(|state: &i32, action: &i32| {
// DispatchOp::Dispatch(state + action, None)
// })))
// .build()
// .unwrap();
let store = StoreImpl::new_with_reducer(0, Box::new(TestReducer)).unwrap();
// when: create iterator and dispatch actions
let mut iter = store.iter().unwrap();
// dispatch actions
store.dispatch(10).expect("dispatch should succeed");
store.dispatch(20).expect("dispatch should succeed");
store.dispatch(30).expect("dispatch should succeed");
// then: iterator should return state and action pairs
assert_eq!(iter.next(), Some((10, 10))); // state: 0+10=10, action: 10
assert_eq!(iter.next(), Some((30, 20))); // state: 10+20=30, action: 20
assert_eq!(iter.next(), Some((60, 30))); // state: 30+30=60, action: 30
// stop store and verify iterator ends
store.stop().expect("store should stop");
assert_eq!(iter.next(), None);
}
/// Test iterator with no actions dispatched
#[test]
fn test_store_iter_no_actions() {
// given: store with reducer
let store = StoreImpl::new_with_reducer(0, Box::new(TestReducer)).unwrap();
// when: create iterator without dispatching actions
let mut iter = store.iter().unwrap();
// then: iterator should return None immediately
// since no actions were dispatched, no state changes occurred
store.stop().expect("store should stop");
assert_eq!(iter.next(), None);
}
/// Test iterator with complex state and action types
#[test]
fn test_store_iter_complex_types() {
// given: store with complex state and action
#[derive(Debug, Clone, PartialEq)]
struct ComplexState {
value: i32,
name: String,
}
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq)]
enum ComplexAction {
Add(i32),
SetName(String),
Reset,
}
let store = StoreImpl::new_with_reducer(
ComplexState {
value: 0,
name: "initial".to_string(),
},
Box::new(FnReducer::from(
|state: &ComplexState, action: &ComplexAction| match action {
ComplexAction::Add(n) => DispatchOp::Dispatch(
ComplexState {
value: state.value + n,
name: state.name.clone(),
},
vec![],
),
ComplexAction::SetName(name) => DispatchOp::Dispatch(
ComplexState {
value: state.value,
name: name.clone(),
},
vec![],
),
ComplexAction::Reset => DispatchOp::Dispatch(
ComplexState {
value: 0,
name: "reset".to_string(),
},
vec![],
),
},
)),
)
.unwrap();
// when: create iterator and dispatch actions
let mut iter = store.iter().unwrap();
store.dispatch(ComplexAction::Add(10)).expect("dispatch should succeed");
store
.dispatch(ComplexAction::SetName("test".to_string()))
.expect("dispatch should succeed");
store.dispatch(ComplexAction::Add(5)).expect("dispatch should succeed");
// then: iterator should return correct state and action pairs
assert_eq!(
iter.next(),
Some((
ComplexState {
value: 10,
name: "initial".to_string(),
},
ComplexAction::Add(10)
))
);
assert_eq!(
iter.next(),
Some((
ComplexState {
value: 10,
name: "test".to_string(),
},
ComplexAction::SetName("test".to_string())
))
);
assert_eq!(
iter.next(),
Some((
ComplexState {
value: 15,
name: "test".to_string(),
},
ComplexAction::Add(5)
))
);
store.stop().expect("store should stop");
assert_eq!(iter.next(), None);
}
/// Test iterator with multiple concurrent actions
#[test]
fn test_store_iter_concurrent_actions() {
// given: store with reducer
let store = StoreImpl::new_with_reducer(0, Box::new(TestReducer)).unwrap();
// when: create iterator and dispatch many actions quickly
let mut iter = store.iter().unwrap();
// dispatch multiple actions
for i in 1..=10 {
store.dispatch(i).expect("dispatch should succeed");
}
// then: iterator should return all state and action pairs in order
let mut expected_state = 0;
for i in 1..=10 {
expected_state += i;
assert_eq!(iter.next(), Some((expected_state, i)));
}
store.stop().expect("store should stop");
assert_eq!(iter.next(), None);
}
/// Test iterator with store that has middleware
#[test]
fn test_store_iter_with_middleware() {
// given: store with middleware
struct TestMiddleware;
impl<State, Action> MiddlewareFnFactory<State, Action> for TestMiddleware
where
State: Send + Sync + Clone + 'static,
Action: Send + Sync + Clone + std::fmt::Debug + 'static,
{
fn create(&self, inner: MiddlewareFn<State, Action>) -> MiddlewareFn<State, Action> {
inner
}
}
let store = StoreImpl::new_with(
0,
vec![Box::new(FnReducer::from(|state: &i32, action: &i32| {
DispatchOp::Dispatch(state + action, vec![])
}))],
"test".to_string(),
1,
BackpressurePolicy::default(),
vec![Arc::new(TestMiddleware)],
)
.unwrap();
// when: create iterator and dispatch actions
let mut iter = store.iter().unwrap();
store.dispatch(5).expect("dispatch should succeed");
store.dispatch(10).expect("dispatch should succeed");
// then: iterator should work correctly with middleware
assert_eq!(iter.next(), Some((5, 5)));
assert_eq!(iter.next(), Some((15, 10)));
store.stop().expect("store should stop");
assert_eq!(iter.next(), None);
}
/// Test iterator with store that has effects
#[test]
fn test_store_iter_with_effects() {
// given: store with reducer that produces effects
let store = StoreImpl::new_with_reducer(
0,
Box::new(FnReducer::from(|state: &i32, action: &i32| {
let new_state = state + action;
let mut effects_vec = vec![];
if *action > 5 {
effects_vec.push(Effect::Task(Box::new(|| {
// effect that does nothing
})));
}
DispatchOp::Dispatch(new_state, effects_vec)
})),
)
.unwrap();
// when: create iterator and dispatch actions
let mut iter = store.iter().unwrap();
store.dispatch(3).expect("dispatch should succeed"); // no effect
store.dispatch(10).expect("dispatch should succeed"); // with effect
// then: iterator should work correctly with effects
assert_eq!(iter.next(), Some((3, 3)));
assert_eq!(iter.next(), Some((13, 10)));
store.stop().expect("store should stop");
assert_eq!(iter.next(), None);
}
/// Test iterator with store that has multiple reducers
#[test]
fn test_store_iter_with_multiple_reducers() {
// given: store with multiple reducers
// StoreBuilder의 with_reducer는 기존 리듀서를 대체하므로
// 실제로는 마지막 리듀서만 사용됩니다
let store = StoreBuilder::new(0)
.with_reducer(Box::new(FnReducer::from(|state: &i32, action: &i32| {
DispatchOp::Dispatch(state + action, vec![])
})))
.with_reducer(Box::new(FnReducer::from(|state: &i32, _action: &i32| {
DispatchOp::Dispatch(state * 2, vec![])
})))
.build()
.unwrap();
// when: create iterator and dispatch actions
// let mut iter = store.iter().unwrap();
store.dispatch(5).expect("dispatch should succeed");
store.dispatch(10).expect("dispatch should succeed");
// // then: iterator should work with multiple reducers
// // 실제로는 마지막 리듀서만 사용되므로: 0 * 2 = 0, 0 * 2 = 0
// let first_result = iter.next();
// println!("First result: {:?}", first_result);
// let second_result = iter.next();
// println!("Second result: {:?}", second_result);
// // 마지막 리듀서만 사용되므로 상태는 항상 0
// assert_eq!(first_result, Some((0, 5)));
// assert_eq!(second_result, Some((0, 10)));
store.stop().expect("store should stop");
// assert_eq!(iter.next(), None);
}
/// Test iterator behavior when store is stopped before consuming all items
#[test]
fn test_store_iter_early_stop() {
// given: store with reducer
let store = StoreImpl::new_with_reducer(0, Box::new(TestReducer)).unwrap();
// when: create iterator, dispatch actions, but stop store early
let mut iter = store.iter().unwrap();
store.dispatch(5).expect("dispatch should succeed");
store.dispatch(10).expect("dispatch should succeed");
store.dispatch(15).expect("dispatch should succeed");
// consume all items before stopping store
assert_eq!(iter.next(), Some((5, 5)));
assert_eq!(iter.next(), Some((15, 10))); // 5 + 10 = 15
assert_eq!(iter.next(), Some((30, 15))); // 15 + 15 = 30
// stop store after consuming all items
store.stop().expect("store should stop");
}
/// Test iterator with different backpressure policies
#[test]
fn test_store_iter_with_block_on_full() {
// given: store with different backpressure policies
let store = StoreImpl::new_with(
0,
vec![Box::new(FnReducer::from(|state: &i32, action: &i32| {
DispatchOp::Dispatch(state + action, vec![])
}))],
"test".to_string(),
2,
BackpressurePolicy::BlockOnFull,
vec![],
)
.unwrap();
// when: create iterator with different capacity and policy
let mut iter = store.iter_with(1, BackpressurePolicy::BlockOnFull).unwrap();
store.dispatch(5).expect("dispatch should succeed");
store.dispatch(10).expect("dispatch should succeed");
// then: iterator should work with custom capacity and policy
assert_eq!(iter.next(), Some((5, 5)));
assert_eq!(iter.next(), Some((15, 10)));
store.stop().expect("store should stop");
}
// #[test]
// fn test_store_iter_with_different_policies() {
// // given: store with different backpressure policies
// let store = StoreBuilder::new(0)
// .with_reducer(Box::new(FnReducer::from(|state: &i32, action: &i32| {
// DispatchOp::Dispatch(state + action, None)
// })))
// .with_capacity(2)
// .with_policy(BackpressurePolicy::DropOldestIf(None))
// .build()
// .unwrap();
//
// // when: create iterator with different capacity and policy
// let mut iter = store.iter_with(1, BackpressurePolicy::BlockOnFull);
//
// store.dispatch(5).expect("dispat
// ch should succeed");
// store.dispatch(10).expect("dispatch should succeed");
//
// // then: iterator should work with custom capacity and policy
// assert_eq!(iter.next(), Some((5, 5)));
// assert_eq!(iter.next(), Some((15, 10)));
//
// store.stop().expect("store should stop");
// }
/// Test iterator with string state and action
#[test]
fn test_store_iter_string_types() {
// given: store with string state and action
let store = StoreImpl::new_with_reducer(
"".to_string(),
Box::new(FnReducer::from(|state: &String, action: &String| {
let new_state = format!("{}{}", state, action);
DispatchOp::Dispatch(new_state, vec![])
})),
)
.unwrap();
// when: create iterator and dispatch string actions
let mut iter = store.iter().unwrap();
store.dispatch("hello".to_string()).expect("dispatch should succeed");
store.dispatch(" world".to_string()).expect("dispatch should succeed");
// then: iterator should work with string types
assert_eq!(
iter.next(),
Some(("hello".to_string(), "hello".to_string()))
);
assert_eq!(
iter.next(),
Some(("hello world".to_string(), " world".to_string()))
);
store.stop().expect("store should stop");
assert_eq!(iter.next(), None);
}
/// Test iterator with empty state changes (reducer returns same state)
#[test]
fn test_store_iter_no_state_change() {
// given: store with reducer that doesn't change state
let store = StoreImpl::new_with_reducer(
0,
Box::new(FnReducer::from(|state: &i32, _action: &i32| {
DispatchOp::Dispatch(state.clone(), vec![]) // return same state
})),
)
.unwrap();
// when: create iterator and dispatch actions
let mut iter = store.iter().unwrap();
store.dispatch(5).expect("dispatch should succeed");
store.dispatch(10).expect("dispatch should succeed");
// then: iterator should still return state and action pairs
assert_eq!(iter.next(), Some((0, 5))); // state remains 0
assert_eq!(iter.next(), Some((0, 10))); // state remains 0
store.stop().expect("store should stop");
assert_eq!(iter.next(), None);
}
/// Test query_state functionality
#[test]
fn test_query_state_basic() {
// given: store with a simple counter
let store = StoreImpl::new_with_reducer(0, Box::new(TestReducer)).unwrap();
// dispatch some actions to change state
store.dispatch(5).unwrap();
store.dispatch(10).unwrap();
// wait for actions to be processed
std::thread::sleep(std::time::Duration::from_millis(100));
// when: query the current state
let queried_value = std::sync::Arc::new(std::sync::Mutex::new(0));
let queried_value_clone = queried_value.clone();
store
.query_state(move |state| {
*queried_value_clone.lock().unwrap() = *state;
})
.unwrap();
let _ = store.stop();
// then: should get the current state (0 + 5 + 10 = 15)
assert_eq!(*queried_value.lock().unwrap(), 15);
}
/// Test query_state with complex state
#[test]
fn test_query_state_complex() {
// given: store with complex state
#[derive(Debug, Clone, PartialEq)]
struct ComplexState {
value: i32,
name: String,
}
#[derive(Debug, Clone, PartialEq)]
enum ComplexAction {
Add(i32),
SetName(String),
}
let store = StoreImpl::new_with_reducer(
ComplexState {
value: 0,
name: "initial".to_string(),
},
Box::new(FnReducer::from(
|state: &ComplexState, action: &ComplexAction| match action {
ComplexAction::Add(n) => DispatchOp::Dispatch(
ComplexState {
value: state.value + n,
name: state.name.clone(),
},
vec![],
),
ComplexAction::SetName(name) => DispatchOp::Dispatch(
ComplexState {
value: state.value,
name: name.clone(),
},
vec![],
),
},
)),
)
.unwrap();
// dispatch some actions
store.dispatch(ComplexAction::Add(10)).unwrap();
store.dispatch(ComplexAction::SetName("test".to_string())).unwrap();
store.dispatch(ComplexAction::Add(5)).unwrap();
// when: query the current state
let queried_value = std::sync::Arc::new(std::sync::Mutex::new(0));
let queried_name = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
let queried_value_clone = queried_value.clone();
let queried_name_clone = queried_name.clone();
store
.query_state(move |state| {
*queried_value_clone.lock().unwrap() = state.value;
*queried_name_clone.lock().unwrap() = state.name.clone();
})
.unwrap();
store.stop().unwrap();
// then: should get the current state
assert_eq!(*queried_value.lock().unwrap(), 15); // 0 + 10 + 5
assert_eq!(*queried_name.lock().unwrap(), "test");
}
/// Test query_state with multiple queries
#[test]
fn test_query_state_multiple_queries() {
// given: store with a simple counter
let store = StoreImpl::new_with_reducer(0, Box::new(TestReducer)).unwrap();
// dispatch some actions
store.dispatch(5).unwrap();
store.dispatch(10).unwrap();
// wait for actions to be processed
std::thread::sleep(std::time::Duration::from_millis(100));
// when: query the state multiple times
let query1_result = std::sync::Arc::new(std::sync::Mutex::new(0));
let query2_result = std::sync::Arc::new(std::sync::Mutex::new(0));
let query1_clone = query1_result.clone();
store
.query_state(move |state| {
*query1_clone.lock().unwrap() = *state;
})
.unwrap();
store.dispatch(20).unwrap();
// wait for action to be processed
std::thread::sleep(std::time::Duration::from_millis(100));
let query2_clone = query2_result.clone();
store
.query_state(move |state| {
*query2_clone.lock().unwrap() = *state;
})
.unwrap();
store.stop().unwrap();
// then: should get the correct states
assert_eq!(*query1_result.lock().unwrap(), 15); // 0 + 5 + 10
assert_eq!(*query2_result.lock().unwrap(), 35); // 15 + 20
}
/// Test query_state with error handling
#[test]
fn test_query_state_error_handling() {
// given: store with a simple counter
let store = StoreImpl::new_with_reducer(0, Box::new(TestReducer)).unwrap();
// when: query the state (should succeed)
let queried_value = std::sync::Arc::new(std::sync::Mutex::new(0));
let queried_value_clone = queried_value.clone();
let result = store.query_state(move |state| {
*queried_value_clone.lock().unwrap() = *state;
});
// then: should succeed and get the initial state
assert!(result.is_ok());
assert_eq!(*queried_value.lock().unwrap(), 0);
}
}