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
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
use eval::Context;
use parking_lot::RwLock;
use std::io;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::runtime::Runtime;

use launchdarkly_server_sdk_evaluation::{self as eval, Detail, FlagValue, PrerequisiteEvent};
use serde::Serialize;
use thiserror::Error;
use tokio::sync::{broadcast, Semaphore};

use super::config::Config;
use super::data_source::DataSource;
use super::data_source_builders::BuildError as DataSourceError;
use super::evaluation::{FlagDetail, FlagDetailConfig};
use super::stores::store::DataStore;
use super::stores::store_builders::BuildError as DataStoreError;
use crate::config::BuildError as ConfigBuildError;
use crate::events::event::EventFactory;
use crate::events::event::InputEvent;
use crate::events::processor::EventProcessor;
use crate::events::processor_builders::BuildError as EventProcessorError;
use crate::{MigrationOpTracker, Stage};

struct EventsScope {
    disabled: bool,
    event_factory: EventFactory,
    prerequisite_event_recorder: Box<dyn eval::PrerequisiteEventRecorder + Send + Sync>,
}

struct PrerequisiteEventRecorder {
    event_factory: EventFactory,
    event_processor: Arc<dyn EventProcessor>,
}

impl eval::PrerequisiteEventRecorder for PrerequisiteEventRecorder {
    fn record(&self, event: PrerequisiteEvent) {
        let evt = self.event_factory.new_eval_event(
            &event.prerequisite_flag.key,
            event.context.clone(),
            &event.prerequisite_flag,
            event.prerequisite_result,
            FlagValue::Json(serde_json::Value::Null),
            Some(event.target_flag_key),
        );

        self.event_processor.send(evt);
    }
}

/// Error type used to represent failures when building a [Client] instance.
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum BuildError {
    /// Error used when a configuration setting is invalid. This typically indicates an invalid URL.
    #[error("invalid client config: {0}")]
    InvalidConfig(String),
}

impl From<DataSourceError> for BuildError {
    fn from(error: DataSourceError) -> Self {
        Self::InvalidConfig(error.to_string())
    }
}

impl From<DataStoreError> for BuildError {
    fn from(error: DataStoreError) -> Self {
        Self::InvalidConfig(error.to_string())
    }
}

impl From<EventProcessorError> for BuildError {
    fn from(error: EventProcessorError) -> Self {
        Self::InvalidConfig(error.to_string())
    }
}

impl From<ConfigBuildError> for BuildError {
    fn from(error: ConfigBuildError) -> Self {
        Self::InvalidConfig(error.to_string())
    }
}

/// Error type used to represent failures when starting the [Client].
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum StartError {
    /// Error used when spawning a background there fails.
    #[error("couldn't spawn background thread for client: {0}")]
    SpawnFailed(io::Error),
}

#[derive(PartialEq, Copy, Clone, Debug)]
enum ClientInitState {
    Initializing = 0,
    Initialized = 1,
    InitializationFailed = 2,
}

impl PartialEq<usize> for ClientInitState {
    fn eq(&self, other: &usize) -> bool {
        *self as usize == *other
    }
}

impl From<usize> for ClientInitState {
    fn from(val: usize) -> Self {
        match val {
            0 => ClientInitState::Initializing,
            1 => ClientInitState::Initialized,
            2 => ClientInitState::InitializationFailed,
            _ => unreachable!(),
        }
    }
}

/// A client for the LaunchDarkly API.
///
/// In order to create a client instance, first create a config using [crate::ConfigBuilder].
///
/// # Examples
///
/// Creating a client, with default configuration.
/// ```
/// # use launchdarkly_server_sdk::{Client, ConfigBuilder, BuildError};
/// # fn main() -> Result<(), BuildError> {
///     let ld_client = Client::build(ConfigBuilder::new("sdk-key").build()?)?;
/// #   Ok(())
/// # }
/// ```
///
/// Creating an instance which connects to a relay proxy.
/// ```
/// # use launchdarkly_server_sdk::{Client, ConfigBuilder, ServiceEndpointsBuilder, BuildError};
/// # fn main() -> Result<(), BuildError> {
///     let ld_client = Client::build(ConfigBuilder::new("sdk-key")
///         .service_endpoints(ServiceEndpointsBuilder::new()
///             .relay_proxy("http://my-relay-hostname:8080")
///         ).build()?
///     )?;
/// #   Ok(())
/// # }
/// ```
///
/// Each builder type includes usage examples for the builder.
pub struct Client {
    event_processor: Arc<dyn EventProcessor>,
    data_source: Arc<dyn DataSource>,
    data_store: Arc<RwLock<dyn DataStore>>,
    events_default: EventsScope,
    events_with_reasons: EventsScope,
    init_notify: Arc<Semaphore>,
    init_state: Arc<AtomicUsize>,
    started: AtomicBool,
    offline: bool,
    sdk_key: String,
    shutdown_broadcast: broadcast::Sender<()>,
    runtime: RwLock<Option<Runtime>>,
}

impl Client {
    /// Create a new instance of a [Client] based on the provided [Config] parameter.
    pub fn build(config: Config) -> Result<Self, BuildError> {
        if config.offline() {
            info!("Started LaunchDarkly Client in offline mode");
        }

        let tags = config.application_tag();

        let endpoints = config.service_endpoints_builder().build()?;
        let event_processor =
            config
                .event_processor_builder()
                .build(&endpoints, config.sdk_key(), tags.clone())?;
        let data_source =
            config
                .data_source_builder()
                .build(&endpoints, config.sdk_key(), tags.clone())?;
        let data_store = config.data_store_builder().build()?;

        let events_default = EventsScope {
            disabled: config.offline(),
            event_factory: EventFactory::new(false),
            prerequisite_event_recorder: Box::new(PrerequisiteEventRecorder {
                event_factory: EventFactory::new(false),
                event_processor: event_processor.clone(),
            }),
        };

        let events_with_reasons = EventsScope {
            disabled: config.offline(),
            event_factory: EventFactory::new(true),
            prerequisite_event_recorder: Box::new(PrerequisiteEventRecorder {
                event_factory: EventFactory::new(true),
                event_processor: event_processor.clone(),
            }),
        };

        let (shutdown_tx, _) = broadcast::channel(1);

        Ok(Client {
            event_processor,
            data_source,
            data_store,
            events_default,
            events_with_reasons,
            init_notify: Arc::new(Semaphore::new(0)),
            init_state: Arc::new(AtomicUsize::new(ClientInitState::Initializing as usize)),
            started: AtomicBool::new(false),
            offline: config.offline(),
            sdk_key: config.sdk_key().into(),
            shutdown_broadcast: shutdown_tx,
            runtime: RwLock::new(None),
        })
    }

    /// Starts a client in the current thread, which must have a default tokio runtime.
    pub fn start_with_default_executor(&self) {
        if self.started.load(Ordering::SeqCst) {
            return;
        }
        self.started.store(true, Ordering::SeqCst);
        self.start_with_default_executor_internal();
    }

    fn start_with_default_executor_internal(&self) {
        // These clones are going to move into the closure, we
        // do not want to move or reference `self`, because
        // then lifetimes will get involved.
        let notify = self.init_notify.clone();
        let init_state = self.init_state.clone();

        self.data_source.subscribe(
            self.data_store.clone(),
            Arc::new(move |success| {
                init_state.store(
                    (if success {
                        ClientInitState::Initialized
                    } else {
                        ClientInitState::InitializationFailed
                    }) as usize,
                    Ordering::SeqCst,
                );
                notify.add_permits(1);
            }),
            self.shutdown_broadcast.subscribe(),
        );
    }

    /// Creates a new tokio runtime and then starts the client. Tasks from the client will
    /// be executed on created runtime.
    /// If your application already has a tokio runtime, then you can use
    /// [crate::Client::start_with_default_executor] and the client will dispatch tasks to
    /// your existing runtime.
    pub fn start_with_runtime(&self) -> Result<bool, StartError> {
        if self.started.load(Ordering::SeqCst) {
            return Ok(true);
        }
        self.started.store(true, Ordering::SeqCst);

        let runtime = Runtime::new().map_err(StartError::SpawnFailed)?;
        let _guard = runtime.enter();
        self.runtime.write().replace(runtime);

        self.start_with_default_executor_internal();

        Ok(true)
    }

    /// This is an async method that will resolve once initialization is complete.
    /// Initialization being complete does not mean that initialization was a success.
    /// The return value from the method indicates if the client successfully initialized.
    #[deprecated(
        note = "blocking without a timeout is discouraged, use wait_for_initialization instead"
    )]
    pub async fn initialized_async(&self) -> bool {
        self.initialized_async_internal().await
    }

    /// This is an async method that will resolve once initialization is complete or the specified
    /// timeout has occurred.
    ///
    /// If the timeout is triggered, this method will return `None`. Otherwise, the method will
    /// return a boolean indicating whether or not the SDK has successfully initialized.
    pub async fn wait_for_initialization(&self, timeout: Duration) -> Option<bool> {
        if timeout > Duration::from_secs(60) {
            warn!("wait_for_initialization was configured to block for up to {} seconds. We recommend blocking no longer than 60 seconds.", timeout.as_secs());
        }

        let initialized = tokio::time::timeout(timeout, self.initialized_async_internal()).await;
        match initialized {
            Ok(result) => Some(result),
            Err(_) => None,
        }
    }

    async fn initialized_async_internal(&self) -> bool {
        if self.offline {
            return true;
        }

        // If the client is not initialized, then we need to wait for it to be initialized.
        // Because we are using atomic types, and not a lock, then there is still the possibility
        // that the value will change between the read and when we wait. We use a semaphore to wait,
        // and we do not forget the permit, therefore if the permit has been added, then we will get
        // it very quickly and reduce blocking.
        if ClientInitState::Initialized != self.init_state.load(Ordering::SeqCst) {
            let _permit = self.init_notify.acquire().await;
        }
        ClientInitState::Initialized == self.init_state.load(Ordering::SeqCst)
    }

    /// This function synchronously returns if the SDK is initialized.
    /// In the case of unrecoverable errors in establishing a connection it is possible for the
    /// SDK to never become initialized.
    pub fn initialized(&self) -> bool {
        self.offline || ClientInitState::Initialized == self.init_state.load(Ordering::SeqCst)
    }

    /// Close shuts down the LaunchDarkly client. After calling this, the LaunchDarkly client
    /// should no longer be used. The method will block until all pending analytics events (if any)
    /// been sent.
    pub fn close(&self) {
        self.event_processor.close();

        // If the system is in offline mode, no receiver will be listening to this broadcast
        // channel, so sending on it would always result in an error.
        if !self.offline {
            if let Err(e) = self.shutdown_broadcast.send(()) {
                error!("Failed to shutdown client appropriately: {}", e);
            }
        }

        // Potentially take the runtime we created when starting the client and do nothing with it
        // so it drops, closing out all spawned tasks.
        self.runtime.write().take();
    }

    /// Flush tells the client that all pending analytics events (if any) should be delivered as
    /// soon as possible. Flushing is asynchronous, so this method will return before it is
    /// complete. However, if you call [Client::close], events are guaranteed to be sent before
    /// that method returns.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/flush#rust>.
    pub fn flush(&self) {
        self.event_processor.flush();
    }

    /// Identify reports details about a context.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/identify#rust>
    pub fn identify(&self, context: Context) {
        if self.events_default.disabled {
            return;
        }

        self.send_internal(self.events_default.event_factory.new_identify(context));
    }

    /// Returns the value of a boolean feature flag for a given context.
    ///
    /// Returns `default` if there is an error, if the flag doesn't exist, or the feature is turned
    /// off and has no off variation.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/evaluating#rust>.
    pub fn bool_variation(&self, context: &Context, flag_key: &str, default: bool) -> bool {
        let val = self.variation(context, flag_key, default);
        if let Some(b) = val.as_bool() {
            b
        } else {
            warn!(
                "bool_variation called for a non-bool flag {:?} (got {:?})",
                flag_key, val
            );
            default
        }
    }

    /// Returns the value of a string feature flag for a given context.
    ///
    /// Returns `default` if there is an error, if the flag doesn't exist, or the feature is turned
    /// off and has no off variation.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/evaluating#rust>.
    pub fn str_variation(&self, context: &Context, flag_key: &str, default: String) -> String {
        let val = self.variation(context, flag_key, default.clone());
        if let Some(s) = val.as_string() {
            s
        } else {
            warn!(
                "str_variation called for a non-string flag {:?} (got {:?})",
                flag_key, val
            );
            default
        }
    }

    /// Returns the value of a float feature flag for a given context.
    ///
    /// Returns `default` if there is an error, if the flag doesn't exist, or the feature is turned
    /// off and has no off variation.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/evaluating#rust>.
    pub fn float_variation(&self, context: &Context, flag_key: &str, default: f64) -> f64 {
        let val = self.variation(context, flag_key, default);
        if let Some(f) = val.as_float() {
            f
        } else {
            warn!(
                "float_variation called for a non-float flag {:?} (got {:?})",
                flag_key, val
            );
            default
        }
    }

    /// Returns the value of a integer feature flag for a given context.
    ///
    /// Returns `default` if there is an error, if the flag doesn't exist, or the feature is turned
    /// off and has no off variation.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/evaluating#rust>.
    pub fn int_variation(&self, context: &Context, flag_key: &str, default: i64) -> i64 {
        let val = self.variation(context, flag_key, default);
        if let Some(f) = val.as_int() {
            f
        } else {
            warn!(
                "int_variation called for a non-int flag {:?} (got {:?})",
                flag_key, val
            );
            default
        }
    }

    /// Returns the value of a feature flag for the given context, allowing the value to be
    /// of any JSON type.
    ///
    /// The value is returned as an [serde_json::Value].
    ///
    /// Returns `default` if there is an error, if the flag doesn't exist, or the feature is turned off.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/evaluating#rust>.
    pub fn json_variation(
        &self,
        context: &Context,
        flag_key: &str,
        default: serde_json::Value,
    ) -> serde_json::Value {
        self.variation(context, flag_key, default.clone())
            .as_json()
            .unwrap_or(default)
    }

    /// This method is the same as [Client::bool_variation], but also returns further information
    /// about how the value was calculated. The "reason" data will also be included in analytics
    /// events.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/evaluation-reasons#rust>.
    pub fn bool_variation_detail(
        &self,
        context: &Context,
        flag_key: &str,
        default: bool,
    ) -> Detail<bool> {
        self.variation_detail(context, flag_key, default).try_map(
            |val| val.as_bool(),
            default,
            eval::Error::WrongType,
        )
    }

    /// This method is the same as [Client::str_variation], but also returns further information
    /// about how the value was calculated. The "reason" data will also be included in analytics
    /// events.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/evaluation-reasons#rust>.
    pub fn str_variation_detail(
        &self,
        context: &Context,
        flag_key: &str,
        default: String,
    ) -> Detail<String> {
        self.variation_detail(context, flag_key, default.clone())
            .try_map(|val| val.as_string(), default, eval::Error::WrongType)
    }

    /// This method is the same as [Client::float_variation], but also returns further information
    /// about how the value was calculated. The "reason" data will also be included in analytics
    /// events.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/evaluation-reasons#rust>.
    pub fn float_variation_detail(
        &self,
        context: &Context,
        flag_key: &str,
        default: f64,
    ) -> Detail<f64> {
        self.variation_detail(context, flag_key, default).try_map(
            |val| val.as_float(),
            default,
            eval::Error::WrongType,
        )
    }

    /// This method is the same as [Client::int_variation], but also returns further information
    /// about how the value was calculated. The "reason" data will also be included in analytics
    /// events.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/evaluation-reasons#rust>.
    pub fn int_variation_detail(
        &self,
        context: &Context,
        flag_key: &str,
        default: i64,
    ) -> Detail<i64> {
        self.variation_detail(context, flag_key, default).try_map(
            |val| val.as_int(),
            default,
            eval::Error::WrongType,
        )
    }

    /// This method is the same as [Client::json_variation], but also returns further information
    /// about how the value was calculated. The "reason" data will also be included in analytics
    /// events.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/evaluation-reasons#rust>.
    pub fn json_variation_detail(
        &self,
        context: &Context,
        flag_key: &str,
        default: serde_json::Value,
    ) -> Detail<serde_json::Value> {
        self.variation_detail(context, flag_key, default.clone())
            .try_map(|val| val.as_json(), default, eval::Error::WrongType)
    }

    /// Generates the secure mode hash value for a context.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/secure-mode#rust>.
    pub fn secure_mode_hash(&self, context: &Context) -> String {
        let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, self.sdk_key.as_bytes());
        let tag = ring::hmac::sign(&key, context.canonical_key().as_bytes());

        data_encoding::HEXLOWER.encode(tag.as_ref())
    }

    /// Returns an object that encapsulates the state of all feature flags for a given context. This
    /// includes the flag values, and also metadata that can be used on the front end.
    ///
    /// The most common use case for this method is to bootstrap a set of client-side feature flags
    /// from a back-end service.
    ///
    /// You may pass any configuration of [FlagDetailConfig] to control what data is included.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/all-flags#rust>
    pub fn all_flags_detail(
        &self,
        context: &Context,
        flag_state_config: FlagDetailConfig,
    ) -> FlagDetail {
        if self.offline {
            warn!(
                "all_flags_detail() called, but client is in offline mode. Returning empty state"
            );
            return FlagDetail::new(false);
        }

        if !self.initialized() {
            warn!("all_flags_detail() called before client has finished initializing! Feature store unavailable - returning empty state");
            return FlagDetail::new(false);
        }

        let data_store = self.data_store.read();

        let mut flag_detail = FlagDetail::new(true);
        flag_detail.populate(&*data_store, context, flag_state_config);

        flag_detail
    }

    /// This method is the same as [Client::variation], but also returns further information about
    /// how the value was calculated. The "reason" data will also be included in analytics events.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/evaluation-reasons#rust>.
    pub fn variation_detail<T: Into<FlagValue> + Clone>(
        &self,
        context: &Context,
        flag_key: &str,
        default: T,
    ) -> Detail<FlagValue> {
        let (detail, _) =
            self.variation_internal(context, flag_key, default, &self.events_with_reasons);
        detail
    }

    /// This is a generic function which returns the value of a feature flag for a given context.
    ///
    /// This method is an alternatively to the type specified methods (e.g.
    /// [Client::bool_variation], [Client::int_variation], etc.).
    ///
    /// Returns `default` if there is an error, if the flag doesn't exist, or the feature is turned
    /// off and has no off variation.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/evaluating#rust>.
    pub fn variation<T: Into<FlagValue> + Clone>(
        &self,
        context: &Context,
        flag_key: &str,
        default: T,
    ) -> FlagValue {
        let (detail, _) = self.variation_internal(context, flag_key, default, &self.events_default);
        detail.value.unwrap()
    }

    /// This method returns the migration stage of the migration feature flag for the given
    /// evaluation context.
    ///
    /// This method returns the default stage if there is an error or the flag does not exist.
    pub fn migration_variation(
        &self,
        context: &Context,
        flag_key: &str,
        default_stage: Stage,
    ) -> (Stage, Arc<Mutex<MigrationOpTracker>>) {
        let (detail, flag) =
            self.variation_internal(context, flag_key, default_stage, &self.events_default);

        let migration_detail =
            detail.try_map(|v| v.try_into().ok(), default_stage, eval::Error::WrongType);
        let tracker = MigrationOpTracker::new(
            flag_key.into(),
            flag,
            context.clone(),
            migration_detail.clone(),
            default_stage,
        );

        (
            migration_detail.value.unwrap_or(default_stage),
            Arc::new(Mutex::new(tracker)),
        )
    }

    /// Reports that a context has performed an event.
    ///
    /// The `key` parameter is defined by the application and will be shown in analytics reports;
    /// it normally corresponds to the event name of a metric that you have created through the
    /// LaunchDarkly dashboard. If you want to associate additional data with this event, use
    /// [Client::track_data] or [Client::track_metric].
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/events#rust>.
    pub fn track_event(&self, context: Context, key: impl Into<String>) {
        let _ = self.track(context, key, None, serde_json::Value::Null);
    }

    /// Reports that a context has performed an event, and associates it with custom data.
    ///
    /// The `key` parameter is defined by the application and will be shown in analytics reports;
    /// it normally corresponds to the event name of a metric that you have created through the
    /// LaunchDarkly dashboard.
    ///
    /// `data` parameter is any type that implements [Serialize]. If no such value is needed, use
    /// [serde_json::Value::Null] (or call [Client::track_event] instead). To send a numeric value
    /// for experimentation, use [Client::track_metric].
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/events#rust>.
    pub fn track_data(
        &self,
        context: Context,
        key: impl Into<String>,
        data: impl Serialize,
    ) -> serde_json::Result<()> {
        self.track(context, key, None, data)
    }

    /// Reports that a context has performed an event, and associates it with a numeric value. This
    /// value is used by the LaunchDarkly experimentation feature in numeric custom metrics, and
    /// will also be returned as part of the custom event for Data Export.
    ///
    /// The `key` parameter is defined by the application and will be shown in analytics reports;
    /// it normally corresponds to the event name of a metric that you have created through the
    /// LaunchDarkly dashboard.
    ///
    /// For more information, see the Reference Guide:
    /// <https://docs.launchdarkly.com/sdk/features/events#rust>.
    pub fn track_metric(
        &self,
        context: Context,
        key: impl Into<String>,
        value: f64,
        data: impl Serialize,
    ) {
        let _ = self.track(context, key, Some(value), data);
    }

    fn track(
        &self,
        context: Context,
        key: impl Into<String>,
        metric_value: Option<f64>,
        data: impl Serialize,
    ) -> serde_json::Result<()> {
        if !self.events_default.disabled {
            let event =
                self.events_default
                    .event_factory
                    .new_custom(context, key, metric_value, data)?;

            self.send_internal(event);
        }

        Ok(())
    }

    /// Tracks the results of a migrations operation. This event includes measurements which can be
    /// used to enhance the observability of a migration within the LaunchDarkly UI.
    ///
    /// This event should be generated through [crate::MigrationOpTracker]. If you are using the
    /// [crate::Migrator] to handle migrations, this event will be created and emitted
    /// automatically.
    pub fn track_migration_op(&self, tracker: Arc<Mutex<MigrationOpTracker>>) {
        if self.events_default.disabled {
            return;
        }

        match tracker.lock() {
            Ok(tracker) => {
                let event = tracker.build();
                match event {
                    Ok(event) => {
                        self.send_internal(
                            self.events_default.event_factory.new_migration_op(event),
                        );
                    }
                    Err(e) => error!(
                        "Failed to build migration event, no event will be sent: {}",
                        e
                    ),
                }
            }
            Err(e) => error!(
                "Failed to lock migration tracker, no event will be sent: {}",
                e
            ),
        }
    }

    fn variation_internal<T: Into<FlagValue> + Clone>(
        &self,
        context: &Context,
        flag_key: &str,
        default: T,
        events_scope: &EventsScope,
    ) -> (Detail<FlagValue>, Option<eval::Flag>) {
        if self.offline {
            return (
                Detail::err_default(eval::Error::ClientNotReady, default.into()),
                None,
            );
        }

        let (flag, result) = match self.initialized() {
            false => (
                None,
                Detail::err_default(eval::Error::ClientNotReady, default.clone().into()),
            ),
            true => {
                let data_store = self.data_store.read();
                match data_store.flag(flag_key) {
                    Some(flag) => {
                        let result = eval::evaluate(
                            data_store.to_store(),
                            &flag,
                            context,
                            Some(&*events_scope.prerequisite_event_recorder),
                        )
                        .map(|v| v.clone())
                        .or(default.clone().into());

                        (Some(flag), result)
                    }
                    None => (
                        None,
                        Detail::err_default(eval::Error::FlagNotFound, default.clone().into()),
                    ),
                }
            }
        };

        if !events_scope.disabled {
            let event = match &flag {
                Some(f) => events_scope.event_factory.new_eval_event(
                    flag_key,
                    context.clone(),
                    f,
                    result.clone(),
                    default.into(),
                    None,
                ),
                None => events_scope.event_factory.new_unknown_flag_event(
                    flag_key,
                    context.clone(),
                    result.clone(),
                    default.into(),
                ),
            };
            self.send_internal(event);
        }

        (result, flag)
    }

    fn send_internal(&self, event: InputEvent) {
        self.event_processor.send(event);
    }
}

#[cfg(test)]
mod tests {
    use crossbeam_channel::Receiver;
    use eval::{ContextBuilder, MultiContextBuilder};
    use futures::FutureExt;
    use hyper::client::HttpConnector;
    use launchdarkly_server_sdk_evaluation::Reason;
    use std::collections::HashMap;

    use tokio::time::Instant;

    use crate::data_source::MockDataSource;
    use crate::data_source_builders::MockDataSourceBuilder;
    use crate::events::create_event_sender;
    use crate::events::event::{OutputEvent, VariationKey};
    use crate::events::processor_builders::EventProcessorBuilder;
    use crate::stores::store_types::{PatchTarget, StorageItem};
    use crate::test_common::{
        self, basic_flag, basic_flag_with_prereq, basic_int_flag, basic_migration_flag,
        basic_off_flag,
    };
    use crate::{ConfigBuilder, MigratorBuilder, Operation, Origin};
    use test_case::test_case;

    use super::*;

    fn is_send_and_sync<T: Send + Sync>() {}

    #[test]
    fn ensure_client_is_send_and_sync() {
        is_send_and_sync::<Client>()
    }

    #[tokio::test]
    async fn client_asynchronously_initializes() {
        let (client, _event_rx) = make_mocked_client_with_delay(1000, false);
        client.start_with_default_executor();

        let now = Instant::now();
        let initialized = client.initialized_async().await;
        let elapsed_time = now.elapsed();
        assert!(initialized);
        // Give ourself a good margin for thread scheduling.
        assert!(elapsed_time.as_millis() > 500)
    }

    #[tokio::test]
    async fn client_asynchronously_initializes_within_timeout() {
        let (client, _event_rx) = make_mocked_client_with_delay(1000, false);
        client.start_with_default_executor();

        let now = Instant::now();
        let initialized = client
            .wait_for_initialization(Duration::from_millis(1500))
            .await;
        let elapsed_time = now.elapsed();
        // Give ourself a good margin for thread scheduling.
        assert!(elapsed_time.as_millis() > 500);
        assert_eq!(initialized, Some(true));
    }

    #[tokio::test]
    async fn client_asynchronously_initializes_slower_than_timeout() {
        let (client, _event_rx) = make_mocked_client_with_delay(2000, false);
        client.start_with_default_executor();

        let now = Instant::now();
        let initialized = client
            .wait_for_initialization(Duration::from_millis(500))
            .await;
        let elapsed_time = now.elapsed();
        // Give ourself a good margin for thread scheduling.
        assert!(elapsed_time.as_millis() < 750);
        assert!(initialized.is_none());
    }

    #[tokio::test]
    async fn client_initializes_immediately_in_offline_mode() {
        let (client, _event_rx) = make_mocked_client_with_delay(1000, true);
        client.start_with_default_executor();

        assert!(client.initialized());

        let now = Instant::now();
        let initialized = client
            .wait_for_initialization(Duration::from_millis(2000))
            .await;
        let elapsed_time = now.elapsed();
        assert_eq!(initialized, Some(true));
        assert!(elapsed_time.as_millis() < 500)
    }

    #[test_case(basic_flag("myFlag"), false.into(), true.into())]
    #[test_case(basic_int_flag("myFlag"), 0.into(), test_common::FLOAT_TO_INT_MAX.into())]
    fn client_updates_changes_evaluation_results(
        flag: eval::Flag,
        default: FlagValue,
        expected: FlagValue,
    ) {
        let context = ContextBuilder::new("foo")
            .build()
            .expect("Failed to create context");

        let (client, _event_rx) = make_mocked_client();

        let result = client.variation_detail(&context, "myFlag", default.clone());
        assert_eq!(result.value.unwrap(), default);

        client.start_with_default_executor();
        client
            .data_store
            .write()
            .upsert(
                &flag.key,
                PatchTarget::Flag(StorageItem::Item(flag.clone())),
            )
            .expect("patch should apply");

        let result = client.variation_detail(&context, "myFlag", default);
        assert_eq!(result.value.unwrap(), expected);
        assert!(matches!(
            result.reason,
            Reason::Fallthrough {
                in_experiment: false
            }
        ));
    }

    #[test]
    fn variation_tracks_events_correctly() {
        let (client, event_rx) = make_mocked_client();
        client.start_with_default_executor();
        client
            .data_store
            .write()
            .upsert(
                "myFlag",
                PatchTarget::Flag(StorageItem::Item(basic_flag("myFlag"))),
            )
            .expect("patch should apply");
        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        let flag_value = client.variation(&context, "myFlag", FlagValue::Bool(false));

        assert!(flag_value.as_bool().unwrap());
        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].kind(), "index");
        assert_eq!(events[1].kind(), "summary");

        if let OutputEvent::Summary(event_summary) = events[1].clone() {
            let variation_key = VariationKey {
                version: Some(42),
                variation: Some(1),
            };
            let feature = event_summary.features.get("myFlag");
            assert!(feature.is_some());

            let feature = feature.unwrap();
            assert!(feature.counters.contains_key(&variation_key));
        } else {
            panic!("Event should be a summary type");
        }
    }

    #[test]
    fn variation_handles_offline_mode() {
        let (client, event_rx) = make_mocked_offline_client();
        client.start_with_default_executor();

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");
        let flag_value = client.variation(&context, "myFlag", FlagValue::Bool(false));

        assert!(!flag_value.as_bool().unwrap());
        client.flush();
        client.close();

        assert_eq!(event_rx.iter().count(), 0);
    }

    #[test]
    fn variation_handles_unknown_flags() {
        let (client, event_rx) = make_mocked_client();
        client.start_with_default_executor();
        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        let flag_value = client.variation(&context, "non-existent-flag", FlagValue::Bool(false));

        assert!(!flag_value.as_bool().unwrap());
        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].kind(), "index");
        assert_eq!(events[1].kind(), "summary");

        if let OutputEvent::Summary(event_summary) = events[1].clone() {
            let variation_key = VariationKey {
                version: None,
                variation: None,
            };

            let feature = event_summary.features.get("non-existent-flag");
            assert!(feature.is_some());

            let feature = feature.unwrap();
            assert!(feature.counters.contains_key(&variation_key));
        } else {
            panic!("Event should be a summary type");
        }
    }

    #[test]
    fn variation_detail_handles_debug_events_correctly() {
        let (client, event_rx) = make_mocked_client();
        client.start_with_default_executor();

        let mut flag = basic_flag("myFlag");
        flag.debug_events_until_date = Some(64_060_606_800_000); // Jan. 1st, 4000

        client
            .data_store
            .write()
            .upsert(
                &flag.key,
                PatchTarget::Flag(StorageItem::Item(flag.clone())),
            )
            .expect("patch should apply");
        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        let detail = client.variation_detail(&context, "myFlag", FlagValue::Bool(false));

        assert!(detail.value.unwrap().as_bool().unwrap());
        assert!(matches!(
            detail.reason,
            Reason::Fallthrough {
                in_experiment: false
            }
        ));
        client.flush();
        client.close();

        let events = event_rx.try_iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 3);
        assert_eq!(events[0].kind(), "index");
        assert_eq!(events[1].kind(), "debug");
        assert_eq!(events[2].kind(), "summary");

        if let OutputEvent::Summary(event_summary) = events[2].clone() {
            let variation_key = VariationKey {
                version: Some(42),
                variation: Some(1),
            };

            let feature = event_summary.features.get("myFlag");
            assert!(feature.is_some());

            let feature = feature.unwrap();
            assert!(feature.counters.contains_key(&variation_key));
        } else {
            panic!("Event should be a summary type");
        }
    }

    #[test]
    fn variation_detail_tracks_events_correctly() {
        let (client, event_rx) = make_mocked_client();
        client.start_with_default_executor();

        client
            .data_store
            .write()
            .upsert(
                "myFlag",
                PatchTarget::Flag(StorageItem::Item(basic_flag("myFlag"))),
            )
            .expect("patch should apply");
        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        let detail = client.variation_detail(&context, "myFlag", FlagValue::Bool(false));

        assert!(detail.value.unwrap().as_bool().unwrap());
        assert!(matches!(
            detail.reason,
            Reason::Fallthrough {
                in_experiment: false
            }
        ));
        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].kind(), "index");
        assert_eq!(events[1].kind(), "summary");

        if let OutputEvent::Summary(event_summary) = events[1].clone() {
            let variation_key = VariationKey {
                version: Some(42),
                variation: Some(1),
            };

            let feature = event_summary.features.get("myFlag");
            assert!(feature.is_some());

            let feature = feature.unwrap();
            assert!(feature.counters.contains_key(&variation_key));
        } else {
            panic!("Event should be a summary type");
        }
    }

    #[test]
    fn variation_detail_handles_offline_mode() {
        let (client, event_rx) = make_mocked_offline_client();
        client.start_with_default_executor();

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        let detail = client.variation_detail(&context, "myFlag", FlagValue::Bool(false));

        assert!(!detail.value.unwrap().as_bool().unwrap());
        assert!(matches!(
            detail.reason,
            Reason::Error {
                error: eval::Error::ClientNotReady
            }
        ));
        client.flush();
        client.close();

        assert_eq!(event_rx.iter().count(), 0);
    }

    #[test]
    fn variation_handles_off_flag_without_variation() {
        let (client, event_rx) = make_mocked_client();
        client.start_with_default_executor();

        client
            .data_store
            .write()
            .upsert(
                "myFlag",
                PatchTarget::Flag(StorageItem::Item(basic_off_flag("myFlag"))),
            )
            .expect("patch should apply");
        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        let result = client.variation(&context, "myFlag", FlagValue::Bool(false));

        assert!(!result.as_bool().unwrap());
        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].kind(), "index");
        assert_eq!(events[1].kind(), "summary");

        if let OutputEvent::Summary(event_summary) = events[1].clone() {
            let variation_key = VariationKey {
                version: Some(42),
                variation: None,
            };
            let feature = event_summary.features.get("myFlag");
            assert!(feature.is_some());

            let feature = feature.unwrap();
            assert!(feature.counters.contains_key(&variation_key));
        } else {
            panic!("Event should be a summary type");
        }
    }

    #[test]
    fn variation_detail_tracks_prereq_events_correctly() {
        let (client, event_rx) = make_mocked_client();
        client.start_with_default_executor();

        let mut basic_preqreq_flag = basic_flag("prereqFlag");
        basic_preqreq_flag.track_events = true;

        client
            .data_store
            .write()
            .upsert(
                "prereqFlag",
                PatchTarget::Flag(StorageItem::Item(basic_preqreq_flag)),
            )
            .expect("patch should apply");

        let mut basic_flag = basic_flag_with_prereq("myFlag", "prereqFlag");
        basic_flag.track_events = true;
        client
            .data_store
            .write()
            .upsert("myFlag", PatchTarget::Flag(StorageItem::Item(basic_flag)))
            .expect("patch should apply");
        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        let detail = client.variation_detail(&context, "myFlag", FlagValue::Bool(false));

        assert!(detail.value.unwrap().as_bool().unwrap());
        assert!(matches!(
            detail.reason,
            Reason::Fallthrough {
                in_experiment: false
            }
        ));
        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 4);
        assert_eq!(events[0].kind(), "index");
        assert_eq!(events[1].kind(), "feature");
        assert_eq!(events[2].kind(), "feature");
        assert_eq!(events[3].kind(), "summary");

        if let OutputEvent::Summary(event_summary) = events[3].clone() {
            let variation_key = VariationKey {
                version: Some(42),
                variation: Some(1),
            };
            let feature = event_summary.features.get("myFlag");
            assert!(feature.is_some());

            let feature = feature.unwrap();
            assert!(feature.counters.contains_key(&variation_key));

            let variation_key = VariationKey {
                version: Some(42),
                variation: Some(1),
            };
            let feature = event_summary.features.get("prereqFlag");
            assert!(feature.is_some());

            let feature = feature.unwrap();
            assert!(feature.counters.contains_key(&variation_key));
        }
    }

    #[test]
    fn variation_handles_failed_prereqs_correctly() {
        let (client, event_rx) = make_mocked_client();
        client.start_with_default_executor();

        let mut basic_preqreq_flag = basic_off_flag("prereqFlag");
        basic_preqreq_flag.track_events = true;

        client
            .data_store
            .write()
            .upsert(
                "prereqFlag",
                PatchTarget::Flag(StorageItem::Item(basic_preqreq_flag)),
            )
            .expect("patch should apply");

        let mut basic_flag = basic_flag_with_prereq("myFlag", "prereqFlag");
        basic_flag.track_events = true;
        client
            .data_store
            .write()
            .upsert("myFlag", PatchTarget::Flag(StorageItem::Item(basic_flag)))
            .expect("patch should apply");
        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        let detail = client.variation(&context, "myFlag", FlagValue::Bool(false));

        assert!(!detail.as_bool().unwrap());
        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 4);
        assert_eq!(events[0].kind(), "index");
        assert_eq!(events[1].kind(), "feature");
        assert_eq!(events[2].kind(), "feature");
        assert_eq!(events[3].kind(), "summary");

        if let OutputEvent::Summary(event_summary) = events[3].clone() {
            let variation_key = VariationKey {
                version: Some(42),
                variation: Some(0),
            };
            let feature = event_summary.features.get("myFlag");
            assert!(feature.is_some());

            let feature = feature.unwrap();
            assert!(feature.counters.contains_key(&variation_key));

            let variation_key = VariationKey {
                version: Some(42),
                variation: None,
            };
            let feature = event_summary.features.get("prereqFlag");
            assert!(feature.is_some());

            let feature = feature.unwrap();
            assert!(feature.counters.contains_key(&variation_key));
        }
    }

    #[test]
    fn variation_detail_handles_flag_not_found() {
        let (client, event_rx) = make_mocked_client();
        client.start_with_default_executor();

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");
        let detail = client.variation_detail(&context, "non-existent-flag", FlagValue::Bool(false));

        assert!(!detail.value.unwrap().as_bool().unwrap());
        assert!(matches!(
            detail.reason,
            Reason::Error {
                error: eval::Error::FlagNotFound
            }
        ));
        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].kind(), "index");
        assert_eq!(events[1].kind(), "summary");

        if let OutputEvent::Summary(event_summary) = events[1].clone() {
            let variation_key = VariationKey {
                version: None,
                variation: None,
            };
            let feature = event_summary.features.get("non-existent-flag");
            assert!(feature.is_some());

            let feature = feature.unwrap();
            assert!(feature.counters.contains_key(&variation_key));
        } else {
            panic!("Event should be a summary type");
        }
    }

    #[tokio::test]
    async fn variation_detail_handles_client_not_ready() {
        let (client, event_rx) = make_mocked_client_with_delay(u64::MAX, false);
        client.start_with_default_executor();
        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        let detail = client.variation_detail(&context, "non-existent-flag", FlagValue::Bool(false));

        assert!(!detail.value.unwrap().as_bool().unwrap());
        assert!(matches!(
            detail.reason,
            Reason::Error {
                error: eval::Error::ClientNotReady
            }
        ));
        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].kind(), "index");
        assert_eq!(events[1].kind(), "summary");

        if let OutputEvent::Summary(event_summary) = events[1].clone() {
            let variation_key = VariationKey {
                version: None,
                variation: None,
            };
            let feature = event_summary.features.get("non-existent-flag");
            assert!(feature.is_some());

            let feature = feature.unwrap();
            assert!(feature.counters.contains_key(&variation_key));
        } else {
            panic!("Event should be a summary type");
        }
    }

    #[test]
    fn identify_sends_identify_event() {
        let (client, event_rx) = make_mocked_client();
        client.start_with_default_executor();

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        client.identify(context);
        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].kind(), "identify");
    }

    #[test]
    fn identify_sends_sends_nothing_in_offline_mode() {
        let (client, event_rx) = make_mocked_offline_client();
        client.start_with_default_executor();

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        client.identify(context);
        client.flush();
        client.close();

        assert_eq!(event_rx.iter().count(), 0);
    }

    #[test]
    fn secure_mode_hash() {
        let config = ConfigBuilder::new("secret")
            .offline(true)
            .build()
            .expect("config should build");
        let client = Client::build(config).expect("Should be built.");
        let context = ContextBuilder::new("Message")
            .build()
            .expect("Failed to create context");

        assert_eq!(
            client.secure_mode_hash(&context),
            "aa747c502a898200f9e4fa21bac68136f886a0e27aec70ba06daf2e2a5cb5597"
        );
    }

    #[test]
    fn secure_mode_hash_with_multi_kind() {
        let config = ConfigBuilder::new("secret")
            .offline(true)
            .build()
            .expect("config should build");
        let client = Client::build(config).expect("Should be built.");

        let org = ContextBuilder::new("org-key|1")
            .kind("org")
            .build()
            .expect("Failed to create context");
        let user = ContextBuilder::new("user-key:2")
            .build()
            .expect("Failed to create context");

        let context = MultiContextBuilder::new()
            .add_context(org)
            .add_context(user)
            .build()
            .expect("failed to build multi-context");

        assert_eq!(
            client.secure_mode_hash(&context),
            "5687e6383b920582ed50c2a96c98a115f1b6aad85a60579d761d9b8797415163"
        );
    }

    #[derive(Serialize)]
    struct MyCustomData {
        pub answer: u32,
    }

    #[test]
    fn track_sends_track_and_index_events() -> serde_json::Result<()> {
        let (client, event_rx) = make_mocked_client();
        client.start_with_default_executor();

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        client.track_event(context.clone(), "event-with-null");
        client.track_data(context.clone(), "event-with-string", "string-data")?;
        client.track_data(context.clone(), "event-with-json", json!({"answer": 42}))?;
        client.track_data(
            context.clone(),
            "event-with-struct",
            MyCustomData { answer: 42 },
        )?;
        client.track_metric(context, "event-with-metric", 42.0, serde_json::Value::Null);

        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 6);

        let mut events_by_type: HashMap<&str, usize> = HashMap::new();
        for event in events {
            if let Some(count) = events_by_type.get_mut(event.kind()) {
                *count += 1;
            } else {
                events_by_type.insert(event.kind(), 1);
            }
        }
        assert!(matches!(events_by_type.get("index"), Some(1)));
        assert!(matches!(events_by_type.get("custom"), Some(5)));

        Ok(())
    }

    #[test]
    fn track_sends_nothing_in_offline_mode() -> serde_json::Result<()> {
        let (client, event_rx) = make_mocked_offline_client();
        client.start_with_default_executor();

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        client.track_event(context.clone(), "event-with-null");
        client.track_data(context.clone(), "event-with-string", "string-data")?;
        client.track_data(context.clone(), "event-with-json", json!({"answer": 42}))?;
        client.track_data(
            context.clone(),
            "event-with-struct",
            MyCustomData { answer: 42 },
        )?;
        client.track_metric(context, "event-with-metric", 42.0, serde_json::Value::Null);

        client.flush();
        client.close();

        assert_eq!(event_rx.iter().count(), 0);

        Ok(())
    }

    #[test]
    fn migration_handles_flag_not_found() {
        let (client, _event_rx) = make_mocked_client();
        client.start_with_default_executor();

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        let (stage, _tracker) =
            client.migration_variation(&context, "non-existent-flag-key", Stage::Off);

        assert_eq!(stage, Stage::Off);
    }

    #[test]
    fn migration_uses_non_migration_flag() {
        let (client, _event_rx) = make_mocked_client();
        client.start_with_default_executor();
        client
            .data_store
            .write()
            .upsert(
                "boolean-flag",
                PatchTarget::Flag(StorageItem::Item(basic_flag("boolean-flag"))),
            )
            .expect("patch should apply");

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        let (stage, _tracker) = client.migration_variation(&context, "boolean-flag", Stage::Off);

        assert_eq!(stage, Stage::Off);
    }

    #[test_case(Stage::Off)]
    #[test_case(Stage::DualWrite)]
    #[test_case(Stage::Shadow)]
    #[test_case(Stage::Live)]
    #[test_case(Stage::Rampdown)]
    #[test_case(Stage::Complete)]
    fn migration_can_determine_correct_stage_from_flag(stage: Stage) {
        let (client, _event_rx) = make_mocked_client();
        client.start_with_default_executor();
        client
            .data_store
            .write()
            .upsert(
                "stage-flag",
                PatchTarget::Flag(StorageItem::Item(basic_migration_flag("stage-flag", stage))),
            )
            .expect("patch should apply");

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        let (evaluated_stage, _tracker) =
            client.migration_variation(&context, "stage-flag", Stage::Off);

        assert_eq!(evaluated_stage, stage);
    }

    #[tokio::test]
    async fn migration_tracks_invoked_correctly() {
        migration_tracks_invoked_correctly_driver(Stage::Off, Operation::Read, vec![Origin::Old])
            .await;
        migration_tracks_invoked_correctly_driver(
            Stage::DualWrite,
            Operation::Read,
            vec![Origin::Old],
        )
        .await;
        migration_tracks_invoked_correctly_driver(
            Stage::Shadow,
            Operation::Read,
            vec![Origin::Old, Origin::New],
        )
        .await;
        migration_tracks_invoked_correctly_driver(
            Stage::Live,
            Operation::Read,
            vec![Origin::Old, Origin::New],
        )
        .await;
        migration_tracks_invoked_correctly_driver(
            Stage::Rampdown,
            Operation::Read,
            vec![Origin::New],
        )
        .await;
        migration_tracks_invoked_correctly_driver(
            Stage::Complete,
            Operation::Read,
            vec![Origin::New],
        )
        .await;
        migration_tracks_invoked_correctly_driver(Stage::Off, Operation::Write, vec![Origin::Old])
            .await;
        migration_tracks_invoked_correctly_driver(
            Stage::DualWrite,
            Operation::Write,
            vec![Origin::Old, Origin::New],
        )
        .await;
        migration_tracks_invoked_correctly_driver(
            Stage::Shadow,
            Operation::Write,
            vec![Origin::Old, Origin::New],
        )
        .await;
        migration_tracks_invoked_correctly_driver(
            Stage::Live,
            Operation::Write,
            vec![Origin::Old, Origin::New],
        )
        .await;
        migration_tracks_invoked_correctly_driver(
            Stage::Rampdown,
            Operation::Write,
            vec![Origin::Old, Origin::New],
        )
        .await;
        migration_tracks_invoked_correctly_driver(
            Stage::Complete,
            Operation::Write,
            vec![Origin::New],
        )
        .await;
    }

    async fn migration_tracks_invoked_correctly_driver(
        stage: Stage,
        operation: Operation,
        origins: Vec<Origin>,
    ) {
        let (client, event_rx) = make_mocked_client();
        let client = Arc::new(client);
        client.start_with_default_executor();
        client
            .data_store
            .write()
            .upsert(
                "stage-flag",
                PatchTarget::Flag(StorageItem::Item(basic_migration_flag("stage-flag", stage))),
            )
            .expect("patch should apply");

        let mut migrator = MigratorBuilder::new(client.clone())
            .read(
                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
                Some(|_, _| true),
            )
            .write(
                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
            )
            .build()
            .expect("migrator should build");

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        if let Operation::Read = operation {
            migrator
                .read(
                    &context,
                    "stage-flag".into(),
                    Stage::Off,
                    serde_json::Value::Null,
                )
                .await;
        } else {
            migrator
                .write(
                    &context,
                    "stage-flag".into(),
                    Stage::Off,
                    serde_json::Value::Null,
                )
                .await;
        }

        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 3);
        match &events[1] {
            OutputEvent::MigrationOp(event) => {
                assert!(event.invoked.len() == origins.len());
                assert!(event.invoked.iter().all(|i| origins.contains(i)));
            }
            _ => panic!("Expected migration event"),
        }
    }

    #[tokio::test]
    async fn migration_tracks_latency() {
        migration_tracks_latency_driver(Stage::Off, Operation::Read, vec![Origin::Old]).await;
        migration_tracks_latency_driver(Stage::DualWrite, Operation::Read, vec![Origin::Old]).await;
        migration_tracks_latency_driver(
            Stage::Shadow,
            Operation::Read,
            vec![Origin::Old, Origin::New],
        )
        .await;
        migration_tracks_latency_driver(
            Stage::Live,
            Operation::Read,
            vec![Origin::Old, Origin::New],
        )
        .await;
        migration_tracks_latency_driver(Stage::Rampdown, Operation::Read, vec![Origin::New]).await;
        migration_tracks_latency_driver(Stage::Complete, Operation::Read, vec![Origin::New]).await;
        migration_tracks_latency_driver(Stage::Off, Operation::Write, vec![Origin::Old]).await;
        migration_tracks_latency_driver(
            Stage::DualWrite,
            Operation::Write,
            vec![Origin::Old, Origin::New],
        )
        .await;
        migration_tracks_latency_driver(
            Stage::Shadow,
            Operation::Write,
            vec![Origin::Old, Origin::New],
        )
        .await;
        migration_tracks_latency_driver(
            Stage::Live,
            Operation::Write,
            vec![Origin::Old, Origin::New],
        )
        .await;
        migration_tracks_latency_driver(
            Stage::Rampdown,
            Operation::Write,
            vec![Origin::Old, Origin::New],
        )
        .await;
        migration_tracks_latency_driver(Stage::Complete, Operation::Write, vec![Origin::New]).await;
    }

    async fn migration_tracks_latency_driver(
        stage: Stage,
        operation: Operation,
        origins: Vec<Origin>,
    ) {
        let (client, event_rx) = make_mocked_client();
        let client = Arc::new(client);
        client.start_with_default_executor();
        client
            .data_store
            .write()
            .upsert(
                "stage-flag",
                PatchTarget::Flag(StorageItem::Item(basic_migration_flag("stage-flag", stage))),
            )
            .expect("patch should apply");

        let mut migrator = MigratorBuilder::new(client.clone())
            .track_latency(true)
            .read(
                |_| {
                    async move {
                        async_std::task::sleep(Duration::from_millis(100)).await;
                        Ok(serde_json::Value::Null)
                    }
                    .boxed()
                },
                |_| {
                    async move {
                        async_std::task::sleep(Duration::from_millis(100)).await;
                        Ok(serde_json::Value::Null)
                    }
                    .boxed()
                },
                Some(|_, _| true),
            )
            .write(
                |_| {
                    async move {
                        async_std::task::sleep(Duration::from_millis(100)).await;
                        Ok(serde_json::Value::Null)
                    }
                    .boxed()
                },
                |_| {
                    async move {
                        async_std::task::sleep(Duration::from_millis(100)).await;
                        Ok(serde_json::Value::Null)
                    }
                    .boxed()
                },
            )
            .build()
            .expect("migrator should build");

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        if let Operation::Read = operation {
            migrator
                .read(
                    &context,
                    "stage-flag".into(),
                    Stage::Off,
                    serde_json::Value::Null,
                )
                .await;
        } else {
            migrator
                .write(
                    &context,
                    "stage-flag".into(),
                    Stage::Off,
                    serde_json::Value::Null,
                )
                .await;
        }

        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 3);
        match &events[1] {
            OutputEvent::MigrationOp(event) => {
                assert!(event.latency.len() == origins.len());
                assert!(event
                    .latency
                    .values()
                    .all(|l| l > &Duration::from_millis(100)));
            }
            _ => panic!("Expected migration event"),
        }
    }

    #[tokio::test]
    async fn migration_tracks_read_errors() {
        migration_tracks_read_errors_driver(Stage::Off, vec![Origin::Old]).await;
        migration_tracks_read_errors_driver(Stage::DualWrite, vec![Origin::Old]).await;
        migration_tracks_read_errors_driver(Stage::Shadow, vec![Origin::Old, Origin::New]).await;
        migration_tracks_read_errors_driver(Stage::Live, vec![Origin::Old, Origin::New]).await;
        migration_tracks_read_errors_driver(Stage::Rampdown, vec![Origin::New]).await;
        migration_tracks_read_errors_driver(Stage::Complete, vec![Origin::New]).await;
    }

    async fn migration_tracks_read_errors_driver(stage: Stage, origins: Vec<Origin>) {
        let (client, event_rx) = make_mocked_client();
        let client = Arc::new(client);
        client.start_with_default_executor();
        client
            .data_store
            .write()
            .upsert(
                "stage-flag",
                PatchTarget::Flag(StorageItem::Item(basic_migration_flag("stage-flag", stage))),
            )
            .expect("patch should apply");

        let mut migrator = MigratorBuilder::new(client.clone())
            .track_latency(true)
            .read(
                |_| async move { Err("fail".into()) }.boxed(),
                |_| async move { Err("fail".into()) }.boxed(),
                Some(|_: &String, _: &String| true),
            )
            .write(
                |_| async move { Err("fail".into()) }.boxed(),
                |_| async move { Err("fail".into()) }.boxed(),
            )
            .build()
            .expect("migrator should build");

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        migrator
            .read(
                &context,
                "stage-flag".into(),
                Stage::Off,
                serde_json::Value::Null,
            )
            .await;
        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 3);
        match &events[1] {
            OutputEvent::MigrationOp(event) => {
                assert!(event.errors.len() == origins.len());
                assert!(event.errors.iter().all(|i| origins.contains(i)));
            }
            _ => panic!("Expected migration event"),
        }
    }

    #[tokio::test]
    async fn migration_tracks_authoritative_write_errors() {
        migration_tracks_authoritative_write_errors_driver(Stage::Off, vec![Origin::Old]).await;
        migration_tracks_authoritative_write_errors_driver(Stage::DualWrite, vec![Origin::Old])
            .await;
        migration_tracks_authoritative_write_errors_driver(Stage::Shadow, vec![Origin::Old]).await;
        migration_tracks_authoritative_write_errors_driver(Stage::Live, vec![Origin::New]).await;
        migration_tracks_authoritative_write_errors_driver(Stage::Rampdown, vec![Origin::New])
            .await;
        migration_tracks_authoritative_write_errors_driver(Stage::Complete, vec![Origin::New])
            .await;
    }

    async fn migration_tracks_authoritative_write_errors_driver(
        stage: Stage,
        origins: Vec<Origin>,
    ) {
        let (client, event_rx) = make_mocked_client();
        let client = Arc::new(client);
        client.start_with_default_executor();
        client
            .data_store
            .write()
            .upsert(
                "stage-flag",
                PatchTarget::Flag(StorageItem::Item(basic_migration_flag("stage-flag", stage))),
            )
            .expect("patch should apply");

        let mut migrator = MigratorBuilder::new(client.clone())
            .track_latency(true)
            .read(
                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
                None,
            )
            .write(
                |_| async move { Err("fail".into()) }.boxed(),
                |_| async move { Err("fail".into()) }.boxed(),
            )
            .build()
            .expect("migrator should build");

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        migrator
            .write(
                &context,
                "stage-flag".into(),
                Stage::Off,
                serde_json::Value::Null,
            )
            .await;

        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 3);
        match &events[1] {
            OutputEvent::MigrationOp(event) => {
                assert!(event.errors.len() == origins.len());
                assert!(event.errors.iter().all(|i| origins.contains(i)));
            }
            _ => panic!("Expected migration event"),
        }
    }

    #[tokio::test]
    async fn migration_tracks_nonauthoritative_write_errors() {
        migration_tracks_nonauthoritative_write_errors_driver(
            Stage::DualWrite,
            false,
            true,
            vec![Origin::New],
        )
        .await;
        migration_tracks_nonauthoritative_write_errors_driver(
            Stage::Shadow,
            false,
            true,
            vec![Origin::New],
        )
        .await;
        migration_tracks_nonauthoritative_write_errors_driver(
            Stage::Live,
            true,
            false,
            vec![Origin::Old],
        )
        .await;
        migration_tracks_nonauthoritative_write_errors_driver(
            Stage::Rampdown,
            true,
            false,
            vec![Origin::Old],
        )
        .await;
    }

    async fn migration_tracks_nonauthoritative_write_errors_driver(
        stage: Stage,
        fail_old: bool,
        fail_new: bool,
        origins: Vec<Origin>,
    ) {
        let (client, event_rx) = make_mocked_client();
        let client = Arc::new(client);
        client.start_with_default_executor();
        client
            .data_store
            .write()
            .upsert(
                "stage-flag",
                PatchTarget::Flag(StorageItem::Item(basic_migration_flag("stage-flag", stage))),
            )
            .expect("patch should apply");

        let mut migrator = MigratorBuilder::new(client.clone())
            .track_latency(true)
            .read(
                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
                None,
            )
            .write(
                move |_| {
                    async move {
                        if fail_old {
                            Err("fail".into())
                        } else {
                            Ok(serde_json::Value::Null)
                        }
                    }
                    .boxed()
                },
                move |_| {
                    async move {
                        if fail_new {
                            Err("fail".into())
                        } else {
                            Ok(serde_json::Value::Null)
                        }
                    }
                    .boxed()
                },
            )
            .build()
            .expect("migrator should build");

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        migrator
            .write(
                &context,
                "stage-flag".into(),
                Stage::Off,
                serde_json::Value::Null,
            )
            .await;

        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 3);
        match &events[1] {
            OutputEvent::MigrationOp(event) => {
                assert!(event.errors.len() == origins.len());
                assert!(event.errors.iter().all(|i| origins.contains(i)));
            }
            _ => panic!("Expected migration event"),
        }
    }

    #[tokio::test]
    async fn migration_tracks_consistency() {
        migration_tracks_consistency_driver(Stage::Shadow, "same", "same", true).await;
        migration_tracks_consistency_driver(Stage::Shadow, "same", "different", false).await;
        migration_tracks_consistency_driver(Stage::Live, "same", "same", true).await;
        migration_tracks_consistency_driver(Stage::Live, "same", "different", false).await;
    }

    async fn migration_tracks_consistency_driver(
        stage: Stage,
        old_return: &'static str,
        new_return: &'static str,
        expected_consistency: bool,
    ) {
        let (client, event_rx) = make_mocked_client();
        let client = Arc::new(client);
        client.start_with_default_executor();
        client
            .data_store
            .write()
            .upsert(
                "stage-flag",
                PatchTarget::Flag(StorageItem::Item(basic_migration_flag("stage-flag", stage))),
            )
            .expect("patch should apply");

        let mut migrator = MigratorBuilder::new(client.clone())
            .track_latency(true)
            .read(
                |_| {
                    async move {
                        async_std::task::sleep(Duration::from_millis(100)).await;
                        Ok(serde_json::Value::String(old_return.to_string()))
                    }
                    .boxed()
                },
                |_| {
                    async move {
                        async_std::task::sleep(Duration::from_millis(100)).await;
                        Ok(serde_json::Value::String(new_return.to_string()))
                    }
                    .boxed()
                },
                Some(|lhs, rhs| lhs == rhs),
            )
            .write(
                |_| {
                    async move {
                        async_std::task::sleep(Duration::from_millis(100)).await;
                        Ok(serde_json::Value::Null)
                    }
                    .boxed()
                },
                |_| {
                    async move {
                        async_std::task::sleep(Duration::from_millis(100)).await;
                        Ok(serde_json::Value::Null)
                    }
                    .boxed()
                },
            )
            .build()
            .expect("migrator should build");

        let context = ContextBuilder::new("bob")
            .build()
            .expect("Failed to create context");

        migrator
            .read(
                &context,
                "stage-flag".into(),
                Stage::Off,
                serde_json::Value::Null,
            )
            .await;

        client.flush();
        client.close();

        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
        assert_eq!(events.len(), 3);
        match &events[1] {
            OutputEvent::MigrationOp(event) => {
                assert!(event.consistency_check == Some(expected_consistency))
            }
            _ => panic!("Expected migration event"),
        }
    }

    fn make_mocked_client_with_delay(delay: u64, offline: bool) -> (Client, Receiver<OutputEvent>) {
        let updates = Arc::new(MockDataSource::new_with_init_delay(delay));
        let (event_sender, event_rx) = create_event_sender();

        let config = ConfigBuilder::new("sdk-key")
            .offline(offline)
            .data_source(MockDataSourceBuilder::new().data_source(updates))
            .event_processor(
                EventProcessorBuilder::<HttpConnector>::new().event_sender(Arc::new(event_sender)),
            )
            .build()
            .expect("config should build");

        let client = Client::build(config).expect("Should be built.");

        (client, event_rx)
    }

    fn make_mocked_offline_client() -> (Client, Receiver<OutputEvent>) {
        make_mocked_client_with_delay(0, true)
    }

    fn make_mocked_client() -> (Client, Receiver<OutputEvent>) {
        make_mocked_client_with_delay(0, false)
    }
}