redis-tower 0.1.2

A Tower-based Redis client with strong typing, composable middleware, and resilience
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
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
//! Redis Pub/Sub support.
//!
//! Provides [`PubSubConnection`], which consumes a [`RedisConnection`] and
//! exposes an async [`Stream`] of [`PubSubMessage`] values.
//! Supports channel subscriptions, pattern subscriptions, and shard
//! subscriptions (Redis 7+).
//!
//! # Example
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use redis_tower::{PubSubConnection, RedisConnection};
//! use tokio_stream::StreamExt;
//!
//! let conn = RedisConnection::connect("127.0.0.1:6379").await?;
//! let mut pubsub = PubSubConnection::from_connection(conn)?;
//! pubsub.subscribe(&["events"]).await?;
//!
//! while let Some(msg) = pubsub.next().await {
//!     let msg = msg?;
//!     println!("{}: {:?}", msg.channel, msg.payload);
//! }
//! # Ok(())
//! # }
//! ```

use std::collections::{BTreeSet, HashSet, VecDeque};
use std::pin::Pin;
use std::task::{Context, Poll};

use bytes::Bytes;
use futures::SinkExt;
use redis_tower_core::{Frame, RedisConnection, RedisError};
use redis_tower_protocol::helpers::{array, bulk};
use tokio_stream::{Stream, StreamExt};
use tokio_util::codec::Framed;

use redis_tower_core::RedisStream;
use redis_tower_protocol::{ProtocolError, RespCodec};

use crate::reconnect::{ConnectionFactory, ReconnectConfig, connect_with_timeout};

/// Channel representation used by the text and binary Pub/Sub APIs.
///
/// `String` retains the text API's lossy UTF-8 decoding; `Bytes` preserves
/// every wire byte. Applications normally use the concrete type aliases.
pub trait PubSubName: Clone + Ord + Send + Sync + Unpin + 'static {
    /// Decode a received channel or pattern name.
    fn from_name_bytes(bytes: &[u8]) -> Self;
    /// Return this name's wire representation.
    fn name_bytes(&self) -> &[u8];
}

impl PubSubName for String {
    fn from_name_bytes(bytes: &[u8]) -> Self {
        String::from_utf8_lossy(bytes).into_owned()
    }
    fn name_bytes(&self) -> &[u8] {
        self.as_bytes()
    }
}
impl PubSubName for Bytes {
    fn from_name_bytes(bytes: &[u8]) -> Self {
        Bytes::copy_from_slice(bytes)
    }
    fn name_bytes(&self) -> &[u8] {
        self.as_ref()
    }
}

/// Pub/Sub message with text channel and pattern names.
#[derive(Debug, Clone)]
pub struct PubSubMessage {
    /// Message family.
    pub kind: MessageKind,
    /// Received channel name.
    pub channel: String,
    /// Matching pattern, for pattern subscriptions.
    pub pattern: Option<String>,
    /// Message payload.
    pub payload: Bytes,
}

impl From<NamedPubSubMessage<String>> for PubSubMessage {
    fn from(message: NamedPubSubMessage<String>) -> Self {
        Self {
            kind: message.kind,
            channel: message.channel,
            pattern: message.pattern,
            payload: message.payload,
        }
    }
}
/// Pub/Sub message preserving binary channel and pattern names.
pub type BinaryPubSubMessage = NamedPubSubMessage<Bytes>;
/// Confirmed text subscriptions.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Subscriptions {
    /// Channels from `SUBSCRIBE`.
    pub channels: BTreeSet<String>,
    /// Patterns from `PSUBSCRIBE`.
    pub patterns: BTreeSet<String>,
    /// Shard channels from `SSUBSCRIBE`.
    pub shard_channels: BTreeSet<String>,
}

impl From<&NamedSubscriptions<String>> for Subscriptions {
    fn from(names: &NamedSubscriptions<String>) -> Self {
        Self {
            channels: names.channels.clone(),
            patterns: names.patterns.clone(),
            shard_channels: names.shard_channels.clone(),
        }
    }
}
impl Subscriptions {
    /// True when nothing is subscribed.
    pub fn is_empty(&self) -> bool {
        self.channels.is_empty() && self.patterns.is_empty() && self.shard_channels.is_empty()
    }
    /// Frames replaying every confirmed subscription.
    pub fn replay_frames(&self) -> Vec<Frame> {
        NamedSubscriptions {
            channels: self.channels.clone(),
            patterns: self.patterns.clone(),
            shard_channels: self.shard_channels.clone(),
        }
        .replay_frames()
    }
}
/// Confirmed binary subscriptions.
pub type BinarySubscriptions = NamedSubscriptions<Bytes>;
/// Pub/Sub connection with text channel and pattern names.
pub struct PubSubConnection {
    inner: NamedPubSubConnection<String>,
    // Preserve the concrete public text subscription type and borrowed getter.
    subscriptions: Subscriptions,
}

impl From<NamedPubSubConnection<String>> for PubSubConnection {
    fn from(inner: NamedPubSubConnection<String>) -> Self {
        let subscriptions = inner.subscriptions().into();
        Self {
            inner,
            subscriptions,
        }
    }
}
impl PubSubConnection {
    /// Consume a dedicated connection, retaining its decode limits.
    pub fn from_connection(connection: RedisConnection) -> Result<Self, RedisError> {
        NamedPubSubConnection::from_connection(connection).map(Self::from)
    }
    /// Confirmed subscriptions replayed after a reconnect.
    pub fn subscriptions(&self) -> &Subscriptions {
        &self.subscriptions
    }
    /// Consume the connection as a typed keyspace event stream.
    pub fn into_keyspace_events(self) -> KeyspaceEventStream {
        KeyspaceEventStream { inner: self }
    }
    /// See [`NamedPubSubConnection::subscribe`].
    pub async fn subscribe(&mut self, names: &[&str]) -> Result<(), RedisError> {
        let result = self.inner.subscribe(names).await;
        self.subscriptions = self.inner.subscriptions().into();
        result
    }
    /// See [`NamedPubSubConnection::psubscribe`].
    pub async fn psubscribe(&mut self, names: &[&str]) -> Result<(), RedisError> {
        let result = self.inner.psubscribe(names).await;
        self.subscriptions = self.inner.subscriptions().into();
        result
    }
    /// See [`NamedPubSubConnection::ssubscribe`].
    pub async fn ssubscribe(&mut self, names: &[&str]) -> Result<(), RedisError> {
        let result = self.inner.ssubscribe(names).await;
        self.subscriptions = self.inner.subscriptions().into();
        result
    }
    /// See [`NamedPubSubConnection::unsubscribe`].
    pub async fn unsubscribe(&mut self, names: &[&str]) -> Result<(), RedisError> {
        let result = self.inner.unsubscribe(names).await;
        self.subscriptions = self.inner.subscriptions().into();
        result
    }
    /// See [`NamedPubSubConnection::punsubscribe`].
    pub async fn punsubscribe(&mut self, names: &[&str]) -> Result<(), RedisError> {
        let result = self.inner.punsubscribe(names).await;
        self.subscriptions = self.inner.subscriptions().into();
        result
    }
    /// See [`NamedPubSubConnection::sunsubscribe`].
    pub async fn sunsubscribe(&mut self, names: &[&str]) -> Result<(), RedisError> {
        let result = self.inner.sunsubscribe(names).await;
        self.subscriptions = self.inner.subscriptions().into();
        result
    }
    /// See [`NamedPubSubConnection::psubscribe_keyspace`].
    pub async fn psubscribe_keyspace(&mut self, db: u32, pattern: &str) -> Result<(), RedisError> {
        let result = self.inner.psubscribe_keyspace(db, pattern).await;
        self.subscriptions = self.inner.subscriptions().into();
        result
    }
    /// See [`NamedPubSubConnection::psubscribe_keyevent`].
    pub async fn psubscribe_keyevent(&mut self, db: u32, pattern: &str) -> Result<(), RedisError> {
        let result = self.inner.psubscribe_keyevent(db, pattern).await;
        self.subscriptions = self.inner.subscriptions().into();
        result
    }
    /// Replay confirmed subscriptions on the current socket.
    pub async fn resubscribe(&mut self) -> Result<(), RedisError> {
        let result = self.inner.resubscribe().await;
        self.subscriptions = self.inner.subscriptions().into();
        result
    }
    /// Reconnect using the supplied factory and replay confirmed subscriptions.
    pub async fn reconnect_with(
        &mut self,
        factory: &dyn ConnectionFactory,
    ) -> Result<(), RedisError> {
        let result = self.inner.reconnect_with(factory).await;
        self.subscriptions = self.inner.subscriptions().into();
        result
    }
    /// Reconnect and replay under the supplied retry and backoff policy.
    pub async fn reconnect_with_backoff(
        &mut self,
        factory: &dyn ConnectionFactory,
        config: &ReconnectConfig,
    ) -> Result<(), RedisError> {
        let result = self.inner.reconnect_with_backoff(factory, config).await;
        self.subscriptions = self.inner.subscriptions().into();
        result
    }
    #[cfg(test)]
    fn parse_message(frame: Frame) -> Result<Option<PubSubMessage>, RedisError> {
        NamedPubSubConnection::<String>::parse_message(frame).map(|message| message.map(Into::into))
    }
}
impl Stream for PubSubConnection {
    type Item = Result<PubSubMessage, RedisError>;
    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.inner)
            .poll_next(cx)
            .map(|message| message.map(|message| message.map(Into::into)))
    }
}

/// Pub/Sub connection preserving binary channel and pattern names.
///
/// Use the `*_bytes` subscription methods and consume its ordinary `Stream`.
/// Reconnect and resubscription preserve the exact names, including non-UTF-8.
pub type BinaryPubSubConnection = NamedPubSubConnection<Bytes>;

/// A message received on a pub/sub channel.
#[derive(Debug, Clone)]
pub struct NamedPubSubMessage<N> {
    /// The kind of message (channel or pattern).
    pub kind: MessageKind,
    /// The channel name this message was received on.
    pub channel: N,
    /// The pattern that matched (only for pattern subscriptions).
    pub pattern: Option<N>,
    /// The message payload.
    pub payload: Bytes,
}

/// The kind of pub/sub message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MessageKind {
    /// A message from a direct channel subscription.
    Message,
    /// A message from a pattern subscription.
    PMessage,
    /// A message from a sharded channel subscription.
    SMessage,
}

/// Which family a keyspace notification belongs to.
///
/// Redis publishes every key event twice when `notify-keyspace-events` is
/// configured with both `K` and `E`: once on the keyspace channel and once on
/// the keyevent channel. They carry the same `(key, event)` pair but differ in
/// how it is split between the channel name and the payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotificationKind {
    /// A `__keyspace@<db>__:<key>` notification: the channel names the key and
    /// the payload is the event name.
    Keyspace,
    /// A `__keyevent@<db>__:<event>` notification: the channel names the event
    /// and the payload is the key.
    Keyevent,
}

/// A parsed Redis keyspace/keyevent notification.
///
/// Redis publishes keyspace notifications on channels of the form
/// `__keyspace@<db>__:<key>` (payload is the event name) and
/// `__keyevent@<db>__:<event>` (payload is the key), gated on the server's
/// `notify-keyspace-events` config. [`KeyspaceEvent`] normalizes both forms
/// into the same `(db, key, event)` triple, recording which channel family it
/// came from in [`kind`](Self::kind).
///
/// Build one from a received [`PubSubMessage`] with
/// [`from_message`](Self::from_message), or stream them directly with
/// [`PubSubConnection::into_keyspace_events`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyspaceEvent {
    /// Which channel family this notification arrived on.
    pub kind: NotificationKind,
    /// The logical database number from the channel (`@<db>`).
    pub db: u32,
    /// The key the event happened to.
    pub key: String,
    /// The event name (for example `set`, `del`, `expired`).
    pub event: String,
}

impl KeyspaceEvent {
    /// Parse a keyspace/keyevent notification channel into its
    /// `(kind, db, tail)` parts, where `tail` is the key (for keyspace) or the
    /// event (for keyevent). Returns `None` if `channel` is not a keyspace or
    /// keyevent channel.
    fn parse_channel(channel: &str) -> Option<(NotificationKind, u32, &str)> {
        for (prefix, kind) in [
            ("__keyspace@", NotificationKind::Keyspace),
            ("__keyevent@", NotificationKind::Keyevent),
        ] {
            if let Some(rest) = channel.strip_prefix(prefix)
                && let Some((db_str, tail)) = rest.split_once("__:")
                && let Ok(db) = db_str.parse::<u32>()
            {
                return Some((kind, db, tail));
            }
        }
        None
    }

    /// Parse a [`KeyspaceEvent`] from a received [`PubSubMessage`].
    ///
    /// Returns `None` when the message's channel is not a keyspace or keyevent
    /// channel, so it can be used to filter a mixed [`PubSubConnection`] stream.
    /// The payload is decoded with [`String::from_utf8_lossy`].
    pub fn from_message(msg: &PubSubMessage) -> Option<KeyspaceEvent> {
        let (kind, db, tail) = Self::parse_channel(&msg.channel)?;
        let payload = String::from_utf8_lossy(&msg.payload).into_owned();
        let (key, event) = match kind {
            NotificationKind::Keyspace => (tail.to_string(), payload),
            NotificationKind::Keyevent => (payload, tail.to_string()),
        };
        Some(KeyspaceEvent {
            kind,
            db,
            key,
            event,
        })
    }
}

/// The subscriptions a [`PubSubConnection`] is tracking, so they can be
/// replayed after a reconnect.
///
/// Redis drops every subscription when the connection is lost, so a pub/sub
/// consumer that reconnects must re-issue them or it silently stops receiving
/// messages. [`PubSubConnection`] records each confirmed subscription here and
/// replays them via [`PubSubConnection::resubscribe`] and
/// [`PubSubConnection::reconnect_with`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct NamedSubscriptions<N> {
    /// Channels from `SUBSCRIBE`.
    pub channels: BTreeSet<N>,
    /// Patterns from `PSUBSCRIBE`.
    pub patterns: BTreeSet<N>,
    /// Shard channels from `SSUBSCRIBE`.
    pub shard_channels: BTreeSet<N>,
}

impl<N: PubSubName> NamedSubscriptions<N> {
    /// True when nothing is subscribed.
    pub fn is_empty(&self) -> bool {
        self.channels.is_empty() && self.patterns.is_empty() && self.shard_channels.is_empty()
    }

    /// The command frames that re-establish every tracked subscription: one
    /// each of `SUBSCRIBE` / `PSUBSCRIBE` / `SSUBSCRIBE` for the non-empty
    /// sets, in that order.
    pub fn replay_frames(&self) -> Vec<Frame> {
        let mut frames = Vec::new();
        for (cmd, set) in [
            ("SUBSCRIBE", &self.channels),
            ("PSUBSCRIBE", &self.patterns),
            ("SSUBSCRIBE", &self.shard_channels),
        ] {
            if !set.is_empty() {
                let mut args = vec![bulk(cmd)];
                args.extend(set.iter().map(|s| bulk(s.name_bytes())));
                frames.push(array(args));
            }
        }
        frames
    }

    /// Add subscription names (channels/patterns/shard channels) to `set`.
    fn add(set: &mut BTreeSet<N>, names: &[&[u8]]) {
        set.extend(names.iter().map(|n| N::from_name_bytes(n)));
    }

    /// Remove subscription names from `set`. An empty `names` clears the whole
    /// set, mirroring Redis `UNSUBSCRIBE`/`PUNSUBSCRIBE`/`SUNSUBSCRIBE` with no
    /// arguments (unsubscribe from everything of that kind).
    fn remove(set: &mut BTreeSet<N>, names: &[&[u8]]) {
        if names.is_empty() {
            set.clear();
        } else {
            for n in names {
                set.remove(&N::from_name_bytes(n));
            }
        }
    }
}

/// A Redis connection in pub/sub mode.
///
/// Consumes a [`RedisConnection`] and provides an async [`Stream`] of
/// [`PubSubMessage`] values. Once in pub/sub mode, the connection can
/// only subscribe/unsubscribe and receive messages.
///
/// Active subscriptions are tracked and can be replayed after a connection
/// drop via [`reconnect_with`](Self::reconnect_with), so a blip does not
/// silently end message delivery.
///
/// # Example
///
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use redis_tower::{PubSubConnection, RedisConnection};
/// use tokio_stream::StreamExt;
///
/// let conn = RedisConnection::connect("127.0.0.1:6379").await?;
/// let mut pubsub = PubSubConnection::from_connection(conn)?;
/// pubsub.subscribe(&["events"]).await?;
///
/// while let Some(msg) = pubsub.next().await {
///     let msg = msg?;
///     println!("{}: {:?}", msg.channel, msg.payload);
/// }
/// # Ok(())
/// # }
/// ```
pub struct NamedPubSubConnection<N> {
    framed: Framed<RedisStream, RespCodec>,
    /// Buffer for frames read while searching for specific confirmations.
    /// This prevents confirmations from one subscribe call being silently
    /// consumed by another's confirmation loop.
    buffered_frames: VecDeque<Frame>,
    /// Active subscriptions, tracked so they can be replayed after a reconnect.
    subs: NamedSubscriptions<N>,
}

impl<N: PubSubName> NamedPubSubConnection<N> {
    /// Convert a `RedisConnection` into a pub/sub connection.
    ///
    /// The connection must not be shared (no outstanding clones of the
    /// internal Arc). Use a fresh connection for pub/sub.
    /// Any RESP decode limits configured on the connection are retained.
    pub fn from_connection(conn: RedisConnection) -> Result<Self, RedisError> {
        let framed = conn.into_framed()?;
        Ok(Self {
            framed,
            buffered_frames: VecDeque::new(),
            subs: NamedSubscriptions {
                channels: BTreeSet::new(),
                patterns: BTreeSet::new(),
                shard_channels: BTreeSet::new(),
            },
        })
    }

    /// Send a subscribe-family command and await its confirmations, without
    /// touching the tracked set.
    async fn send_subscribe(
        &mut self,
        cmd: &str,
        names: &[&[u8]],
        kind: &str,
    ) -> Result<(), RedisError> {
        let names = Self::unique_names(names)?;
        let mut args = vec![bulk(cmd)];
        for name in &names {
            args.push(bulk(*name));
        }
        self.framed
            .send(array(args))
            .await
            .map_err(RedisError::from)?;
        self.await_confirmations(&names, kind).await
    }

    /// Subscribe to one or more channels.
    pub async fn subscribe(&mut self, channels: &[&str]) -> Result<(), RedisError> {
        let names: Vec<&[u8]> = channels.iter().map(|name| name.as_bytes()).collect();
        self.subscribe_bytes(&names).await
    }

    /// Byte-oriented `SUBSCRIBE`; names and acknowledgements retain exact bytes.
    pub async fn subscribe_bytes(&mut self, channels: &[&[u8]]) -> Result<(), RedisError> {
        self.send_subscribe("SUBSCRIBE", channels, "subscribe")
            .await?;
        NamedSubscriptions::add(&mut self.subs.channels, channels);
        Ok(())
    }

    /// Subscribe to one or more patterns.
    pub async fn psubscribe(&mut self, patterns: &[&str]) -> Result<(), RedisError> {
        let names: Vec<&[u8]> = patterns.iter().map(|name| name.as_bytes()).collect();
        self.psubscribe_bytes(&names).await
    }

    /// Byte-oriented `PSUBSCRIBE`; names and acknowledgements retain exact bytes.
    pub async fn psubscribe_bytes(&mut self, patterns: &[&[u8]]) -> Result<(), RedisError> {
        self.send_subscribe("PSUBSCRIBE", patterns, "psubscribe")
            .await?;
        NamedSubscriptions::add(&mut self.subs.patterns, patterns);
        Ok(())
    }

    /// Subscribe to keyspace notifications for `db`, matching keys against
    /// `key_pattern` (a glob, for example `*` or `user:*`).
    ///
    /// This pattern-subscribes to `__keyspace@<db>__:<key_pattern>`; received
    /// messages carry the event name as the payload. The server must have
    /// keyspace notifications enabled (`notify-keyspace-events` must include
    /// `K` plus the relevant class flags). Decode messages with
    /// [`KeyspaceEvent::from_message`], or convert the connection with
    /// [`into_keyspace_events`](Self::into_keyspace_events).
    pub async fn psubscribe_keyspace(
        &mut self,
        db: u32,
        key_pattern: &str,
    ) -> Result<(), RedisError> {
        let pattern = format!("__keyspace@{db}__:{key_pattern}");
        self.psubscribe(&[pattern.as_str()]).await
    }

    /// Subscribe to keyevent notifications for `db`, matching events against
    /// `event_pattern` (a glob, for example `*` or `expired`).
    ///
    /// This pattern-subscribes to `__keyevent@<db>__:<event_pattern>`; received
    /// messages carry the affected key as the payload. The server must have
    /// keyspace notifications enabled (`notify-keyspace-events` must include
    /// `E` plus the relevant class flags). Decode messages with
    /// [`KeyspaceEvent::from_message`], or convert the connection with
    /// [`into_keyspace_events`](Self::into_keyspace_events).
    pub async fn psubscribe_keyevent(
        &mut self,
        db: u32,
        event_pattern: &str,
    ) -> Result<(), RedisError> {
        let pattern = format!("__keyevent@{db}__:{event_pattern}");
        self.psubscribe(&[pattern.as_str()]).await
    }

    /// Unsubscribe from one or more channels.
    ///
    /// If `channels` is empty, unsubscribes from all channels.
    pub async fn unsubscribe(&mut self, channels: &[&str]) -> Result<(), RedisError> {
        let names: Vec<&[u8]> = channels.iter().map(|name| name.as_bytes()).collect();
        self.unsubscribe_bytes(&names).await
    }

    /// Byte-oriented `UNSUBSCRIBE`; names and acknowledgements retain exact bytes.
    pub async fn unsubscribe_bytes(&mut self, channels: &[&[u8]]) -> Result<(), RedisError> {
        let tracked: Vec<N> = self.subs.channels.iter().cloned().collect();
        self.send_unsubscribe("UNSUBSCRIBE", channels, "unsubscribe", &tracked)
            .await?;

        NamedSubscriptions::remove(&mut self.subs.channels, channels);
        Ok(())
    }

    /// Subscribe to one or more shard channels.
    pub async fn ssubscribe(&mut self, channels: &[&str]) -> Result<(), RedisError> {
        let names: Vec<&[u8]> = channels.iter().map(|name| name.as_bytes()).collect();
        self.ssubscribe_bytes(&names).await
    }

    /// Byte-oriented `SSUBSCRIBE`; names and acknowledgements retain exact bytes.
    pub async fn ssubscribe_bytes(&mut self, channels: &[&[u8]]) -> Result<(), RedisError> {
        self.send_subscribe("SSUBSCRIBE", channels, "ssubscribe")
            .await?;
        NamedSubscriptions::add(&mut self.subs.shard_channels, channels);
        Ok(())
    }

    /// Unsubscribe from one or more shard channels.
    ///
    /// If `channels` is empty, unsubscribes from all shard channels.
    pub async fn sunsubscribe(&mut self, channels: &[&str]) -> Result<(), RedisError> {
        let names: Vec<&[u8]> = channels.iter().map(|name| name.as_bytes()).collect();
        self.sunsubscribe_bytes(&names).await
    }

    /// Byte-oriented `SUNSUBSCRIBE`; names and acknowledgements retain exact bytes.
    pub async fn sunsubscribe_bytes(&mut self, channels: &[&[u8]]) -> Result<(), RedisError> {
        let tracked: Vec<N> = self.subs.shard_channels.iter().cloned().collect();
        self.send_unsubscribe("SUNSUBSCRIBE", channels, "sunsubscribe", &tracked)
            .await?;

        NamedSubscriptions::remove(&mut self.subs.shard_channels, channels);
        Ok(())
    }

    /// Unsubscribe from one or more patterns.
    pub async fn punsubscribe(&mut self, patterns: &[&str]) -> Result<(), RedisError> {
        let names: Vec<&[u8]> = patterns.iter().map(|name| name.as_bytes()).collect();
        self.punsubscribe_bytes(&names).await
    }

    /// Byte-oriented `PUNSUBSCRIBE`; names and acknowledgements retain exact bytes.
    pub async fn punsubscribe_bytes(&mut self, patterns: &[&[u8]]) -> Result<(), RedisError> {
        let tracked: Vec<N> = self.subs.patterns.iter().cloned().collect();
        self.send_unsubscribe("PUNSUBSCRIBE", patterns, "punsubscribe", &tracked)
            .await?;

        NamedSubscriptions::remove(&mut self.subs.patterns, patterns);
        Ok(())
    }

    /// The subscriptions currently tracked on this connection.
    ///
    /// These are replayed by [`resubscribe`](Self::resubscribe) and
    /// [`reconnect_with`](Self::reconnect_with).
    pub fn subscriptions(&self) -> &NamedSubscriptions<N> {
        &self.subs
    }

    /// Re-issue every tracked subscription over the current connection.
    ///
    /// Redis drops all subscriptions on disconnect, so call this after
    /// replacing the underlying connection to restore message delivery. It is
    /// a no-op when nothing is subscribed. The tracked set is unchanged.
    pub async fn resubscribe(&mut self) -> Result<(), RedisError> {
        // Snapshot to release the borrow on `self.subs` before sending.
        let channels: Vec<N> = self.subs.channels.iter().cloned().collect();
        let patterns: Vec<N> = self.subs.patterns.iter().cloned().collect();
        let shard: Vec<N> = self.subs.shard_channels.iter().cloned().collect();

        if !channels.is_empty() {
            let refs: Vec<&[u8]> = channels.iter().map(PubSubName::name_bytes).collect();
            self.send_subscribe("SUBSCRIBE", &refs, "subscribe").await?;
        }
        if !patterns.is_empty() {
            let refs: Vec<&[u8]> = patterns.iter().map(PubSubName::name_bytes).collect();
            self.send_subscribe("PSUBSCRIBE", &refs, "psubscribe")
                .await?;
        }
        if !shard.is_empty() {
            let refs: Vec<&[u8]> = shard.iter().map(PubSubName::name_bytes).collect();
            self.send_subscribe("SSUBSCRIBE", &refs, "ssubscribe")
                .await?;
        }
        Ok(())
    }

    /// Rebuild the underlying connection from `factory` and replay all tracked
    /// subscriptions.
    ///
    /// Use this when the pub/sub stream reports a connection error: instead of
    /// silently going quiet, the connection is re-established and every
    /// subscription is restored, so message delivery resumes.
    /// Connection settings, including RESP decode limits, are determined by
    /// the factory and therefore apply to every replacement connection.
    pub async fn reconnect_with(
        &mut self,
        factory: &dyn ConnectionFactory,
    ) -> Result<(), RedisError> {
        let conn = factory.connect().await?;
        self.install_replacement(conn).await
    }

    /// Rebuild the underlying connection with the retry, backoff, and timeout
    /// policy in `config`, then replay every tracked subscription.
    ///
    /// Each attempt waits for [`ReconnectConfig::base_delay`] (growing up to
    /// its configured maximum) and applies the per-attempt connection timeout.
    /// A successfully-created candidate replays every subscription before it
    /// replaces the current transport; a failed replay therefore cannot expose
    /// a partially subscribed session. If a finite retry budget is exhausted,
    /// the final error is retained as the structured cause of
    /// [`RedisError::ReconnectFailed`].
    ///
    /// As on the other reconnecting surfaces, `connect_timeout` bounds only
    /// [`ConnectionFactory::connect`]. Subscription-confirmation waits have the
    /// same caller-controlled lifetime as [`subscribe`](Self::subscribe) and
    /// [`resubscribe`](Self::resubscribe); wrap this future in an operation
    /// timeout when the complete reconnect-and-replay sequence needs a deadline.
    pub async fn reconnect_with_backoff(
        &mut self,
        factory: &dyn ConnectionFactory,
        config: &ReconnectConfig,
    ) -> Result<(), RedisError> {
        let mut attempt = 0;

        loop {
            tokio::time::sleep(config.delay_for_attempt(attempt)).await;
            let result = match connect_with_timeout(factory, config.connect_timeout).await {
                Ok(conn) => self.install_replacement(conn).await,
                Err(error) => Err(error),
            };

            match result {
                Ok(()) => return Ok(()),
                Err(last_error) => {
                    let attempts = attempt.saturating_add(1);
                    attempt = attempts;
                    if config.attempt_exhausted(attempt) {
                        return Err(RedisError::ReconnectFailed {
                            attempts,
                            last_error: std::sync::Arc::new(last_error),
                        });
                    }
                }
            }
        }
    }

    /// Prepare, fully resubscribe, then atomically install one replacement.
    ///
    /// Keeping the candidate transport local means a failed replay cannot
    /// leave `self` pointing at a partially subscribed session. Messages that
    /// arrive while the replay confirmations are read move across with the
    /// successful candidate's delivery buffer.
    async fn install_replacement(&mut self, conn: RedisConnection) -> Result<(), RedisError> {
        let mut replacement = Self {
            framed: conn.into_framed()?,
            buffered_frames: VecDeque::new(),
            subs: self.subs.clone(),
        };
        replacement.resubscribe().await?;
        self.framed = replacement.framed;
        self.buffered_frames = replacement.buffered_frames;
        Ok(())
    }

    /// Send an unsubscribe-family command and await its confirmations without
    /// discarding messages that arrive between acknowledgements.
    async fn send_unsubscribe(
        &mut self,
        cmd: &str,
        names: &[&[u8]],
        kind: &str,
        tracked: &[N],
    ) -> Result<(), RedisError> {
        let unique_names = if names.is_empty() {
            Vec::new()
        } else {
            Self::unique_names(names)?
        };
        let mut args = vec![bulk(cmd)];
        args.extend(unique_names.iter().map(|name| bulk(*name)));
        self.framed
            .send(array(args))
            .await
            .map_err(RedisError::from)?;

        if !unique_names.is_empty() {
            return self.await_confirmations(&unique_names, kind).await;
        }

        // With no arguments Redis acknowledges every subscription of this
        // family. Match those names instead of waiting for a total count of
        // zero: subscriptions in the other two families contribute to that
        // count and may intentionally remain active.
        if !tracked.is_empty() {
            let names: Vec<&[u8]> = tracked.iter().map(PubSubName::name_bytes).collect();
            return self.await_confirmations(&names, kind).await;
        }

        // Redis still emits one acknowledgement with a null name when there
        // was nothing of this family to unsubscribe from.
        self.await_confirmation(kind).await
    }

    /// Reject an empty subscribe request and retain only the first occurrence
    /// of each name so the number of expected acknowledgements matches the
    /// command sent on the wire.
    fn unique_names<'a>(names: &'a [&'a [u8]]) -> Result<Vec<&'a [u8]>, RedisError> {
        if names.is_empty() {
            return Err(RedisError::Redis(
                "pub/sub subscribe requires at least one name".to_string(),
            ));
        }

        let mut seen = HashSet::with_capacity(names.len());
        Ok(names
            .iter()
            .copied()
            .filter(|name| seen.insert(*name))
            .collect())
    }

    /// Read a newly arrived frame directly from the transport.
    ///
    /// Confirmation searches deliberately bypass `buffered_frames`: those
    /// frames predate the command whose acknowledgement is being awaited and
    /// repeatedly popping and requeueing one would never make wire progress.
    async fn next_wire_frame(&mut self) -> Result<Frame, RedisError> {
        self.framed
            .next()
            .await
            .ok_or(RedisError::ConnectionClosed)?
            .map_err(RedisError::from)
    }

    /// Wait for subscribe/psubscribe/ssubscribe confirmations, matching each
    /// confirmation's channel name against the expected set.
    ///
    /// Frames that are valid confirmations for the right `kind` but whose
    /// channel name does not match any expected channel are buffered so they
    /// can be consumed by a subsequent confirmation loop or the message stream.
    async fn await_confirmations(
        &mut self,
        names: &[&[u8]],
        expected_kind: &str,
    ) -> Result<(), RedisError> {
        let mut pending: HashSet<&[u8]> = names.iter().copied().collect();
        let mut deferred = VecDeque::new();

        let result = loop {
            if pending.is_empty() {
                break Ok(());
            }

            let frame = match self.next_wire_frame().await {
                Ok(frame) => frame,
                Err(error) => break Err(error),
            };

            match Self::extract_confirmation_channel(&frame, expected_kind) {
                Some(Ok(channel)) => {
                    if pending.remove(channel.as_ref()) {
                        // Matched an expected channel -- continue.
                        continue;
                    }
                    // Confirmation for a channel we did not request in this call.
                    // Buffer it so the caller that IS waiting for it can consume it.
                    deferred.push_back(frame);
                }
                Some(Err(error)) => break Err(error),
                None => {
                    // Not a confirmation of the expected kind at all. Buffer it.
                    deferred.push_back(frame);
                }
            }
        };

        // Existing buffered frames are older than anything read above. Append
        // deferred wire frames to retain delivery order for the message stream.
        self.buffered_frames.extend(deferred);
        result
    }

    /// Wait for one confirmation of `expected_kind`, preserving every frame
    /// unrelated to that acknowledgement.
    async fn await_confirmation(&mut self, expected_kind: &str) -> Result<(), RedisError> {
        let mut deferred = VecDeque::new();

        let result = loop {
            let frame = match self.next_wire_frame().await {
                Ok(frame) => frame,
                Err(error) => break Err(error),
            };

            match Self::is_confirmation(&frame, expected_kind) {
                Some(Ok(())) => break Ok(()),
                Some(Err(error)) => break Err(error),
                None => deferred.push_back(frame),
            }
        };

        self.buffered_frames.extend(deferred);
        result
    }

    /// Try to extract the channel name from a subscribe confirmation frame.
    ///
    /// Returns `Some(Ok(channel))` if the frame is a confirmation of the
    /// expected kind, `Some(Err(_))` if the frame is an error, or `None`
    /// if it is not a confirmation of the expected kind.
    fn extract_confirmation_channel(
        frame: &Frame,
        expected_kind: &str,
    ) -> Option<Result<Bytes, RedisError>> {
        let items = match frame {
            Frame::Array(Some(items)) | Frame::Push(items) => items,
            Frame::Error(e) => {
                return Some(Err(RedisError::Redis(
                    String::from_utf8_lossy(e).into_owned(),
                )));
            }
            _ => return None,
        };

        // items[0] = kind, items[1] = channel, items[2] = subscription count
        if items.len() < 3 {
            return None;
        }

        let kind = match &items[0] {
            Frame::BulkString(Some(b)) | Frame::SimpleString(b) => b,
            _ => return None,
        };

        if kind.as_ref() != expected_kind.as_bytes() {
            return None;
        }

        // Extract channel name from items[1].
        match &items[1] {
            Frame::BulkString(Some(b)) => Some(Ok(b.clone())),
            Frame::SimpleString(b) => Some(Ok(b.clone())),
            _ => None,
        }
    }

    /// Check whether `frame` is a confirmation of `expected_kind`.
    ///
    /// A null name is valid when an unsubscribe command targets an empty
    /// subscription family.
    fn is_confirmation(frame: &Frame, expected_kind: &str) -> Option<Result<(), RedisError>> {
        let items = match frame {
            Frame::Array(Some(items)) | Frame::Push(items) => items,
            Frame::Error(error) => {
                return Some(Err(RedisError::Redis(
                    String::from_utf8_lossy(error).into_owned(),
                )));
            }
            _ => return None,
        };
        if items.len() < 3 || !matches!(items.last(), Some(Frame::Integer(_))) {
            return None;
        }

        let kind = match &items[0] {
            Frame::BulkString(Some(kind)) | Frame::SimpleString(kind) => kind,
            _ => return None,
        };
        if kind.as_ref() != expected_kind.as_bytes() {
            return None;
        }

        match &items[1] {
            Frame::BulkString(_) | Frame::SimpleString(_) => Some(Ok(())),
            Frame::Null if expected_kind.ends_with("unsubscribe") => Some(Ok(())),
            _ => None,
        }
    }

    /// Parse a pub/sub message frame.
    fn parse_message(frame: Frame) -> Result<Option<NamedPubSubMessage<N>>, RedisError> {
        let items = match frame {
            Frame::Array(Some(items)) | Frame::Push(items) => items,
            other => {
                return Err(RedisError::UnexpectedResponse {
                    expected: "pub/sub message array",
                    actual: format!("{other:?}"),
                });
            }
        };

        let kind_bytes = match items.first() {
            Some(Frame::BulkString(Some(b))) => b,
            _ => {
                return Err(RedisError::UnexpectedResponse {
                    expected: "message type",
                    actual: format!("{items:?}"),
                });
            }
        };

        match kind_bytes.as_ref() {
            b"message" if items.len() == 3 => {
                let channel = Self::extract_string(&items[1])?;
                let payload = Self::extract_bytes(&items[2])?;
                Ok(Some(NamedPubSubMessage {
                    kind: MessageKind::Message,
                    channel,
                    pattern: None,
                    payload,
                }))
            }
            b"pmessage" if items.len() == 4 => {
                let pattern = Self::extract_string(&items[1])?;
                let channel = Self::extract_string(&items[2])?;
                let payload = Self::extract_bytes(&items[3])?;
                Ok(Some(NamedPubSubMessage {
                    kind: MessageKind::PMessage,
                    channel,
                    pattern: Some(pattern),
                    payload,
                }))
            }
            b"smessage" if items.len() == 3 => {
                let channel = Self::extract_string(&items[1])?;
                let payload = Self::extract_bytes(&items[2])?;
                Ok(Some(NamedPubSubMessage {
                    kind: MessageKind::SMessage,
                    channel,
                    pattern: None,
                    payload,
                }))
            }
            // Subscribe/unsubscribe confirmations -- skip.
            b"subscribe" | b"unsubscribe" | b"psubscribe" | b"punsubscribe" | b"ssubscribe"
            | b"sunsubscribe" => Ok(None),
            other => Err(RedisError::UnexpectedResponse {
                expected: "message or pmessage",
                actual: format!("{}", String::from_utf8_lossy(other)),
            }),
        }
    }

    fn extract_string(frame: &Frame) -> Result<N, RedisError> {
        match frame {
            Frame::BulkString(Some(b)) => Ok(N::from_name_bytes(b)),
            Frame::SimpleString(b) => Ok(N::from_name_bytes(b)),
            other => Err(RedisError::UnexpectedResponse {
                expected: "string",
                actual: format!("{other:?}"),
            }),
        }
    }

    fn extract_bytes(frame: &Frame) -> Result<Bytes, RedisError> {
        match frame {
            Frame::BulkString(Some(b)) => Ok(b.clone()),
            Frame::SimpleString(b) => Ok(b.clone()),
            other => Err(RedisError::UnexpectedResponse {
                expected: "bytes",
                actual: format!("{other:?}"),
            }),
        }
    }
}

fn pubsub_stream_error(error: ProtocolError) -> RedisError {
    match error {
        ProtocolError::Io(error) if error.kind() != std::io::ErrorKind::Unsupported => error.into(),
        error => error.into(),
    }
}

impl<N: PubSubName> Stream for NamedPubSubConnection<N> {
    type Item = Result<NamedPubSubMessage<N>, RedisError>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        loop {
            // Drain any buffered frames before reading from the transport.
            let frame = if let Some(frame) = self.buffered_frames.pop_front() {
                frame
            } else {
                match Pin::new(&mut self.framed).poll_next(cx) {
                    Poll::Ready(Some(Ok(frame))) => frame,
                    Poll::Ready(Some(Err(e))) => {
                        return Poll::Ready(Some(Err(pubsub_stream_error(e))));
                    }
                    Poll::Ready(None) => return Poll::Ready(None),
                    Poll::Pending => return Poll::Pending,
                }
            };

            match Self::parse_message(frame) {
                Ok(Some(msg)) => return Poll::Ready(Some(Ok(msg))),
                Ok(None) => continue, // skip confirmations
                Err(e) => return Poll::Ready(Some(Err(e))),
            }
        }
    }
}

impl NamedPubSubConnection<String> {
    /// Consume this connection and yield a [`Stream`] of typed
    /// [`KeyspaceEvent`] values instead of raw [`PubSubMessage`]s.
    ///
    /// Messages whose channel is not a keyspace/keyevent channel are skipped,
    /// so it is safe to use even if other subscriptions are active. Subscribe
    /// to the relevant channels first with
    /// [`psubscribe_keyspace`](Self::psubscribe_keyspace) or
    /// [`psubscribe_keyevent`](Self::psubscribe_keyevent).
    pub fn into_keyspace_events(self) -> KeyspaceEventStream {
        KeyspaceEventStream { inner: self.into() }
    }
}

/// A [`Stream`] of typed [`KeyspaceEvent`] values, layered over a
/// [`PubSubConnection`].
///
/// Created by [`PubSubConnection::into_keyspace_events`]. Messages received on
/// channels that are not keyspace/keyevent channels are silently skipped;
/// transport errors are surfaced as `Err` items.
pub struct KeyspaceEventStream {
    inner: PubSubConnection,
}

impl KeyspaceEventStream {
    /// Borrow the underlying [`PubSubConnection`], for example to inspect
    /// [`subscriptions`](PubSubConnection::subscriptions).
    pub fn get_ref(&self) -> &PubSubConnection {
        &self.inner
    }

    /// Mutably borrow the underlying [`PubSubConnection`], for example to add
    /// or remove subscriptions while streaming.
    pub fn get_mut(&mut self) -> &mut PubSubConnection {
        &mut self.inner
    }

    /// Recover the underlying [`PubSubConnection`].
    pub fn into_inner(self) -> PubSubConnection {
        self.inner
    }
}

impl Stream for KeyspaceEventStream {
    type Item = Result<KeyspaceEvent, RedisError>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        loop {
            match Pin::new(&mut self.inner).poll_next(cx) {
                Poll::Ready(Some(Ok(msg))) => match KeyspaceEvent::from_message(&msg) {
                    Some(event) => return Poll::Ready(Some(Ok(event))),
                    None => continue, // not a keyspace notification -- skip
                },
                Poll::Ready(Some(Err(e))) => return Poll::Ready(Some(Err(e))),
                Poll::Ready(None) => return Poll::Ready(None),
                Poll::Pending => return Poll::Pending,
            }
        }
    }
}

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

    #[test]
    fn stream_errors_distinguish_transport_loss_from_unsupported_protocol() {
        let reset = ProtocolError::Io(std::io::Error::from(std::io::ErrorKind::ConnectionReset));
        assert!(pubsub_stream_error(reset).is_connection_error());
        let unsupported = ProtocolError::Io(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "RESP3 attributed replies are not supported",
        ));
        assert!(matches!(
            pubsub_stream_error(unsupported),
            RedisError::Protocol(_)
        ));
    }

    use redis_tower_protocol::helpers::{array, bulk};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::Duration;

    /// Helper to build a subscribe confirmation frame.
    fn sub_confirmation(kind: &str, channel: &str, count: i64) -> Frame {
        array(vec![bulk(kind), bulk(channel), Frame::Integer(count)])
    }

    fn message(channel: &str, payload: &str) -> Frame {
        array(vec![bulk("message"), bulk(channel), bulk(payload)])
    }

    #[cfg(unix)]
    async fn redis_stream_pair() -> (RedisStream, RedisStream) {
        let (client, server) = tokio::net::UnixStream::pair().unwrap();
        (RedisStream::Unix(client), RedisStream::Unix(server))
    }

    #[cfg(not(unix))]
    async fn redis_stream_pair() -> (RedisStream, RedisStream) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let (client, accepted) =
            tokio::join!(tokio::net::TcpStream::connect(addr), listener.accept());
        let (server, _) = accepted.unwrap();
        (RedisStream::Tcp(client.unwrap()), RedisStream::Tcp(server))
    }

    async fn pubsub_pair() -> (
        PubSubConnection,
        Framed<RedisStream, redis_tower_protocol::RespCodec>,
    ) {
        let (client, server) = redis_stream_pair().await;
        let connection = RedisConnection::from_stream(client);
        let pubsub = PubSubConnection::from_connection(connection).unwrap();
        let server = Framed::new(server, redis_tower_protocol::RespCodec::new());
        (pubsub, server)
    }

    #[tokio::test]
    async fn binary_names_survive_confirmations_delivery_and_reconnect() {
        let (client, server) = redis_stream_pair().await;
        let mut pubsub =
            BinaryPubSubConnection::from_connection(RedisConnection::from_stream(client)).unwrap();
        let mut server = Framed::new(server, redis_tower_protocol::RespCodec::new());
        let first = Bytes::from_static(b"channel\xff");
        let second = Bytes::from_static(b"channel\xfe");
        let wire_names = [first.clone(), second.clone()];
        let server_task = tokio::spawn(async move {
            assert_eq!(
                server.next().await.unwrap().unwrap(),
                array(vec![
                    bulk("SUBSCRIBE"),
                    bulk(wire_names[0].clone()),
                    bulk(wire_names[1].clone())
                ])
            );
            // These names have the same lossy UTF-8 rendering. Matching
            // acknowledgements as text would lose or prematurely accept one.
            for name in &wire_names {
                server
                    .send(Frame::Push(vec![
                        bulk("subscribe"),
                        bulk(name.clone()),
                        Frame::Integer(2),
                    ]))
                    .await
                    .unwrap();
            }
            server
                .send(Frame::Push(vec![
                    bulk("message"),
                    bulk(wire_names[1].clone()),
                    bulk(Bytes::from_static(b"\0\xffpayload")),
                ]))
                .await
                .unwrap();
        });
        tokio::time::timeout(
            Duration::from_secs(1),
            pubsub.subscribe_bytes(&[&first, &second]),
        )
        .await
        .unwrap()
        .unwrap();
        let message = pubsub.next().await.unwrap().unwrap();
        assert_eq!(message.channel, second);
        assert_eq!(message.payload.as_ref(), b"\0\xffpayload");
        server_task.await.unwrap();
        assert_eq!(pubsub.subscriptions().channels.len(), 2);
        let (replacement, server) = redis_stream_pair().await;
        let replacement = std::sync::Mutex::new(Some(replacement));
        let factory = move || {
            let stream = replacement.lock().unwrap().take().unwrap();
            async move { Ok(RedisConnection::from_stream(stream)) }
        };
        let mut server = Framed::new(server, redis_tower_protocol::RespCodec::new());
        let names = pubsub
            .subscriptions()
            .channels
            .iter()
            .cloned()
            .collect::<Vec<_>>();
        let expected = pubsub.subscriptions().replay_frames();
        let replay = tokio::spawn(async move {
            assert_eq!(server.next().await.unwrap().unwrap(), expected[0]);
            for name in &names {
                server
                    .send(Frame::Push(vec![
                        bulk("subscribe"),
                        bulk(name.clone()),
                        Frame::Integer(2),
                    ]))
                    .await
                    .unwrap();
            }
            assert_eq!(
                server.next().await.unwrap().unwrap(),
                array(vec![bulk("UNSUBSCRIBE")])
            );
            for name in &names {
                server
                    .send(Frame::Push(vec![
                        bulk("unsubscribe"),
                        bulk(name.clone()),
                        Frame::Integer(0),
                    ]))
                    .await
                    .unwrap();
            }
        });
        tokio::time::timeout(Duration::from_secs(1), pubsub.reconnect_with(&factory))
            .await
            .unwrap()
            .unwrap();
        tokio::time::timeout(Duration::from_secs(1), pubsub.unsubscribe_bytes(&[]))
            .await
            .unwrap()
            .unwrap();
        assert!(pubsub.subscriptions().is_empty());
        replay.await.unwrap();
    }

    #[test]
    fn binary_pattern_and_shard_messages_preserve_names() {
        let pattern = Bytes::from_static(b"prefix\xff*");
        let channel = Bytes::from_static(b"prefix\xffitem");
        let message = BinaryPubSubConnection::parse_message(Frame::Push(vec![
            bulk("pmessage"),
            bulk(pattern.clone()),
            bulk(channel.clone()),
            bulk("value"),
        ]))
        .unwrap()
        .unwrap();
        assert_eq!(message.pattern, Some(pattern));
        assert_eq!(message.channel, channel);
        let message = BinaryPubSubConnection::parse_message(array(vec![
            bulk("smessage"),
            bulk(channel.clone()),
            bulk("value"),
        ]))
        .unwrap()
        .unwrap();
        assert_eq!(message.channel, channel);
        assert_eq!(message.kind, MessageKind::SMessage);
    }

    #[test]
    fn extract_confirmation_channel_matches_expected_kind() {
        let frame = sub_confirmation("subscribe", "events", 1);
        let result =
            NamedPubSubConnection::<String>::extract_confirmation_channel(&frame, "subscribe");
        assert!(result.is_some());
        assert_eq!(result.unwrap().unwrap(), "events");
    }

    #[test]
    fn extract_confirmation_channel_accepts_simple_string_kind() {
        let frame = array(vec![
            Frame::SimpleString(Bytes::from_static(b"subscribe")),
            bulk("events"),
            Frame::Integer(1),
        ]);
        assert_eq!(
            NamedPubSubConnection::<String>::extract_confirmation_channel(&frame, "subscribe")
                .unwrap()
                .unwrap(),
            "events"
        );
    }

    #[test]
    fn extract_confirmation_channel_returns_none_for_wrong_kind() {
        let frame = sub_confirmation("psubscribe", "events.*", 1);
        let result =
            NamedPubSubConnection::<String>::extract_confirmation_channel(&frame, "subscribe");
        assert!(result.is_none());
    }

    #[test]
    fn extract_confirmation_channel_returns_err_for_error_frame() {
        let frame = Frame::Error(b"ERR something"[..].into());
        let result =
            NamedPubSubConnection::<String>::extract_confirmation_channel(&frame, "subscribe");
        assert!(result.is_some());
        assert!(result.unwrap().is_err());
    }

    #[test]
    fn extract_confirmation_channel_returns_none_for_message_frame() {
        let frame = array(vec![bulk("message"), bulk("events"), bulk("hello")]);
        let result =
            NamedPubSubConnection::<String>::extract_confirmation_channel(&frame, "subscribe");
        assert!(result.is_none());
    }

    #[test]
    fn extract_confirmation_channel_returns_none_for_short_array() {
        let frame = array(vec![bulk("subscribe")]);
        let result =
            NamedPubSubConnection::<String>::extract_confirmation_channel(&frame, "subscribe");
        assert!(result.is_none());
    }

    #[test]
    fn parse_message_returns_channel_message() {
        let frame = array(vec![bulk("message"), bulk("events"), bulk("payload")]);
        let msg = PubSubConnection::parse_message(frame).unwrap().unwrap();
        assert_eq!(msg.kind, MessageKind::Message);
        assert_eq!(msg.channel, "events");
        assert_eq!(msg.payload.as_ref(), b"payload");
        assert!(msg.pattern.is_none());
    }

    #[test]
    fn parse_message_returns_pmessage() {
        let frame = array(vec![
            bulk("pmessage"),
            bulk("ev*"),
            bulk("events"),
            bulk("data"),
        ]);
        let msg = PubSubConnection::parse_message(frame).unwrap().unwrap();
        assert_eq!(msg.kind, MessageKind::PMessage);
        assert_eq!(msg.channel, "events");
        assert_eq!(msg.pattern, Some("ev*".to_string()));
    }

    #[test]
    fn parse_message_skips_subscribe_confirmation() {
        let frame = sub_confirmation("subscribe", "ch1", 1);
        assert!(PubSubConnection::parse_message(frame).unwrap().is_none());
    }

    #[test]
    fn is_confirmation_accepts_zero_count() {
        let frame = array(vec![bulk("unsubscribe"), bulk("ch1"), Frame::Integer(0)]);
        assert!(matches!(
            NamedPubSubConnection::<String>::is_confirmation(&frame, "unsubscribe"),
            Some(Ok(()))
        ));
    }

    #[test]
    fn is_confirmation_accepts_nonzero_count() {
        let frame = array(vec![bulk("unsubscribe"), bulk("ch1"), Frame::Integer(2)]);
        assert!(matches!(
            NamedPubSubConnection::<String>::is_confirmation(&frame, "unsubscribe"),
            Some(Ok(()))
        ));
    }

    #[test]
    fn is_confirmation_accepts_null_unsubscribe_name() {
        let frame = array(vec![
            bulk("unsubscribe"),
            Frame::BulkString(None),
            Frame::Integer(0),
        ]);
        assert!(matches!(
            NamedPubSubConnection::<String>::is_confirmation(&frame, "unsubscribe"),
            Some(Ok(()))
        ));
    }

    #[test]
    fn is_confirmation_accepts_resp3_null_unsubscribe_name() {
        let frame = Frame::Push(vec![bulk("unsubscribe"), Frame::Null, Frame::Integer(0)]);
        assert!(matches!(
            NamedPubSubConnection::<String>::is_confirmation(&frame, "unsubscribe"),
            Some(Ok(()))
        ));
    }

    #[tokio::test]
    async fn subscribe_bypasses_existing_buffer_and_preserves_wire_messages() {
        let (mut pubsub, mut server) = pubsub_pair().await;
        pubsub
            .inner
            .buffered_frames
            .push_back(message("events", "already-buffered"));

        let server_task = tokio::spawn(async move {
            assert_eq!(
                server.next().await.unwrap().unwrap(),
                array(vec![bulk("SUBSCRIBE"), bulk("new")])
            );
            server.send(message("events", "from-wire")).await.unwrap();
            server
                .send(sub_confirmation("subscribe", "new", 2))
                .await
                .unwrap();
        });

        tokio::time::timeout(Duration::from_secs(1), pubsub.subscribe(&["new"]))
            .await
            .expect("subscribe confirmation search cycled buffered data")
            .unwrap();
        server_task.await.unwrap();

        let first = pubsub.next().await.unwrap().unwrap();
        let second = pubsub.next().await.unwrap().unwrap();
        assert_eq!(first.payload.as_ref(), b"already-buffered");
        assert_eq!(second.payload.as_ref(), b"from-wire");
    }

    #[tokio::test]
    async fn subscribe_rejects_empty_names_before_wire_io() {
        let (mut pubsub, mut server) = pubsub_pair().await;

        let error = pubsub.subscribe(&[]).await.unwrap_err();
        assert!(error.to_string().contains("at least one name"));
        assert!(
            tokio::time::timeout(Duration::from_millis(20), server.next())
                .await
                .is_err(),
            "empty subscribe unexpectedly wrote a command"
        );
    }

    #[tokio::test]
    async fn subscribe_deduplicates_names_before_wire_and_confirmation_wait() {
        let (mut pubsub, mut server) = pubsub_pair().await;
        let server_task = tokio::spawn(async move {
            assert_eq!(
                server.next().await.unwrap().unwrap(),
                array(vec![bulk("SUBSCRIBE"), bulk("a"), bulk("b")])
            );
            server
                .send(sub_confirmation("subscribe", "a", 1))
                .await
                .unwrap();
            server
                .send(sub_confirmation("subscribe", "b", 2))
                .await
                .unwrap();
        });

        tokio::time::timeout(
            Duration::from_secs(1),
            pubsub.subscribe(&["a", "a", "b", "a"]),
        )
        .await
        .expect("duplicate subscribe names left an acknowledgement pending")
        .unwrap();
        server_task.await.unwrap();
        assert_eq!(
            pubsub
                .subscriptions()
                .channels
                .iter()
                .map(String::as_str)
                .collect::<Vec<_>>(),
            vec!["a", "b"]
        );
    }

    #[tokio::test]
    async fn unsubscribe_all_matches_family_names_and_preserves_interleaved_message() {
        let (mut pubsub, mut server) = pubsub_pair().await;
        NamedSubscriptions::add(
            &mut pubsub.inner.subs.channels,
            &[b"a".as_slice(), b"b".as_slice()],
        );
        NamedSubscriptions::add(
            &mut pubsub.inner.subs.patterns,
            &[b"still-active.*".as_slice()],
        );

        let server_task = tokio::spawn(async move {
            assert_eq!(
                server.next().await.unwrap().unwrap(),
                array(vec![bulk("UNSUBSCRIBE")])
            );
            // The total never reaches zero because a pattern subscription is
            // intentionally left active.
            server
                .send(sub_confirmation("unsubscribe", "a", 2))
                .await
                .unwrap();
            server.send(message("a", "between-acks")).await.unwrap();
            server
                .send(sub_confirmation("unsubscribe", "b", 1))
                .await
                .unwrap();
        });

        tokio::time::timeout(Duration::from_secs(1), pubsub.unsubscribe(&[]))
            .await
            .expect("unsubscribe waited for an aggregate count of zero")
            .unwrap();
        server_task.await.unwrap();

        assert!(pubsub.subscriptions().channels.is_empty());
        assert_eq!(
            pubsub
                .subscriptions()
                .patterns
                .iter()
                .next()
                .map(String::as_str),
            Some("still-active.*")
        );
        let buffered = pubsub.next().await.unwrap().unwrap();
        assert_eq!(buffered.payload.as_ref(), b"between-acks");
    }

    #[tokio::test]
    async fn unsubscribe_empty_family_accepts_resp3_null_ack_and_preserves_message() {
        let (mut pubsub, mut server) = pubsub_pair().await;
        let server_task = tokio::spawn(async move {
            assert_eq!(
                server.next().await.unwrap().unwrap(),
                array(vec![bulk("UNSUBSCRIBE")])
            );
            server
                .send(message("other", "before-null-ack"))
                .await
                .unwrap();
            server
                .send(Frame::Push(vec![
                    bulk("unsubscribe"),
                    Frame::Null,
                    Frame::Integer(0),
                ]))
                .await
                .unwrap();
        });

        tokio::time::timeout(Duration::from_secs(1), pubsub.unsubscribe(&[]))
            .await
            .unwrap()
            .unwrap();
        server_task.await.unwrap();

        let buffered = pubsub.next().await.unwrap().unwrap();
        assert_eq!(buffered.payload.as_ref(), b"before-null-ack");
    }

    #[tokio::test]
    async fn unsubscribe_deduplicates_names_before_wire_and_confirmation_wait() {
        let (mut pubsub, mut server) = pubsub_pair().await;
        NamedSubscriptions::add(
            &mut pubsub.inner.subs.channels,
            &[b"a".as_slice(), b"b".as_slice()],
        );
        let server_task = tokio::spawn(async move {
            assert_eq!(
                server.next().await.unwrap().unwrap(),
                array(vec![bulk("UNSUBSCRIBE"), bulk("a"), bulk("b")])
            );
            server
                .send(sub_confirmation("unsubscribe", "a", 1))
                .await
                .unwrap();
            server
                .send(sub_confirmation("unsubscribe", "b", 0))
                .await
                .unwrap();
        });

        tokio::time::timeout(Duration::from_secs(1), pubsub.unsubscribe(&["a", "a", "b"]))
            .await
            .expect("duplicate unsubscribe names left an acknowledgement pending")
            .unwrap();
        server_task.await.unwrap();
        assert!(pubsub.subscriptions().channels.is_empty());
    }

    #[tokio::test]
    async fn failed_replacement_replay_does_not_install_partial_session() {
        let (pubsub, mut original_server) = pubsub_pair().await;
        let mut pubsub = pubsub.inner;
        NamedSubscriptions::add(
            &mut pubsub.subs.channels,
            &[b"a".as_slice(), b"b".as_slice()],
        );
        pubsub
            .buffered_frames
            .push_back(message("old", "old-buffer"));

        let (candidate, candidate_server) = redis_stream_pair().await;
        let candidate = RedisConnection::from_stream(candidate);
        let mut candidate_server =
            Framed::new(candidate_server, redis_tower_protocol::RespCodec::new());

        let candidate_task = tokio::spawn(async move {
            assert_eq!(
                candidate_server.next().await.unwrap().unwrap(),
                array(vec![bulk("SUBSCRIBE"), bulk("a"), bulk("b")])
            );
            candidate_server
                .send(sub_confirmation("subscribe", "a", 1))
                .await
                .unwrap();
            candidate_server
                .send(message("candidate", "must-not-leak"))
                .await
                .unwrap();
            candidate_server
                .send(Frame::Error(Bytes::from_static(b"ERR replay failed")))
                .await
                .unwrap();
        });

        let error = pubsub.install_replacement(candidate).await.unwrap_err();
        assert!(error.to_string().contains("replay failed"));
        candidate_task.await.unwrap();

        original_server
            .send(message("old", "old-wire"))
            .await
            .unwrap();
        let buffered = pubsub.next().await.unwrap().unwrap();
        let from_original_wire = pubsub.next().await.unwrap().unwrap();
        assert_eq!(buffered.payload.as_ref(), b"old-buffer");
        assert_eq!(from_original_wire.payload.as_ref(), b"old-wire");
        assert_eq!(pubsub.subscriptions().channels.len(), 2);
    }

    #[tokio::test]
    async fn reconnect_with_backoff_returns_final_error_after_zero_delay_budget() {
        let (mut pubsub, _server) = pubsub_pair().await;
        let calls = Arc::new(AtomicUsize::new(0));
        let factory = {
            let calls = Arc::clone(&calls);
            move || {
                calls.fetch_add(1, Ordering::SeqCst);
                std::future::ready(Err::<RedisConnection, _>(RedisError::ConnectionClosed))
            }
        };
        let config = ReconnectConfig::default()
            .max_retries(2)
            .base_delay(Duration::ZERO)
            .max_delay(Duration::ZERO)
            .jitter(false);

        let error = tokio::time::timeout(
            Duration::from_secs(1),
            pubsub.reconnect_with_backoff(&factory, &config),
        )
        .await
        .unwrap()
        .unwrap_err();

        assert_eq!(calls.load(Ordering::SeqCst), 3);
        match error {
            RedisError::ReconnectFailed {
                attempts,
                last_error,
            } => {
                assert_eq!(attempts, 3);
                assert!(matches!(last_error.as_ref(), RedisError::ConnectionClosed));
            }
            other => panic!("expected ReconnectFailed, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn reconnect_with_backoff_wraps_per_attempt_timeout() {
        let (mut pubsub, _server) = pubsub_pair().await;
        let factory =
            || async { futures::future::pending::<Result<RedisConnection, RedisError>>().await };
        let config = ReconnectConfig::default()
            .max_retries(0)
            .base_delay(Duration::ZERO)
            .max_delay(Duration::ZERO)
            .jitter(false)
            .connect_timeout(Duration::from_millis(10));

        let error = tokio::time::timeout(
            Duration::from_secs(1),
            pubsub.reconnect_with_backoff(&factory, &config),
        )
        .await
        .unwrap()
        .unwrap_err();

        match error {
            RedisError::ReconnectFailed {
                attempts,
                last_error,
            } => {
                assert_eq!(attempts, 1);
                assert!(matches!(last_error.as_ref(), RedisError::ConnectTimeout));
            }
            other => panic!("expected ReconnectFailed, got {other:?}"),
        }
    }

    // -- subscription tracking (replayed on reconnect) --

    #[test]
    fn subscriptions_add_accumulates_each_kind() {
        let mut subs = Subscriptions::default();
        assert!(subs.is_empty());
        NamedSubscriptions::add(&mut subs.channels, &[b"a".as_slice(), b"b".as_slice()]);
        NamedSubscriptions::add(&mut subs.patterns, &[b"p.*".as_slice()]);
        NamedSubscriptions::add(&mut subs.shard_channels, &[b"s".as_slice()]);
        NamedSubscriptions::add(&mut subs.channels, &[b"b".as_slice(), b"c".as_slice()]); // dedups b
        assert!(!subs.is_empty());
        assert_eq!(
            subs.channels.iter().cloned().collect::<Vec<_>>(),
            vec!["a", "b", "c"]
        );
        assert_eq!(subs.patterns.len(), 1);
        assert_eq!(subs.shard_channels.len(), 1);
    }

    #[test]
    fn subscriptions_remove_named_leaves_the_rest() {
        let mut subs = Subscriptions::default();
        NamedSubscriptions::add(
            &mut subs.channels,
            &[b"a".as_slice(), b"b".as_slice(), b"c".as_slice()],
        );
        NamedSubscriptions::remove(&mut subs.channels, &[b"b".as_slice()]);
        assert_eq!(
            subs.channels.iter().cloned().collect::<Vec<_>>(),
            vec!["a", "c"]
        );
    }

    #[test]
    fn subscriptions_remove_empty_clears_that_kind_only() {
        // UNSUBSCRIBE with no args clears all channels but not patterns/shards.
        let mut subs = Subscriptions::default();
        NamedSubscriptions::add(&mut subs.channels, &[b"a".as_slice(), b"b".as_slice()]);
        NamedSubscriptions::add(&mut subs.patterns, &[b"p.*".as_slice()]);
        NamedSubscriptions::remove(&mut subs.channels, &[]);
        assert!(subs.channels.is_empty());
        assert_eq!(subs.patterns.len(), 1);
        assert!(!subs.is_empty());
    }

    #[test]
    fn replay_frames_emits_one_command_per_nonempty_kind() {
        let mut subs = Subscriptions::default();
        NamedSubscriptions::add(&mut subs.channels, &[b"c1".as_slice(), b"c2".as_slice()]);
        NamedSubscriptions::add(&mut subs.shard_channels, &[b"s1".as_slice()]);
        // No patterns -> no PSUBSCRIBE frame.
        let frames = subs.replay_frames();
        assert_eq!(
            frames,
            vec![
                array(vec![bulk("SUBSCRIBE"), bulk("c1"), bulk("c2")]),
                array(vec![bulk("SSUBSCRIBE"), bulk("s1")]),
            ]
        );
    }

    #[test]
    fn replay_frames_is_empty_when_nothing_subscribed() {
        assert!(Subscriptions::default().replay_frames().is_empty());
    }

    // -- keyspace notifications --

    /// Build a `pmessage` frame the way Redis delivers a keyspace notification.
    fn keyspace_pmessage(pattern: &str, channel: &str, payload: &str) -> Frame {
        array(vec![
            bulk("pmessage"),
            bulk(pattern),
            bulk(channel),
            bulk(payload),
        ])
    }

    #[test]
    fn keyspace_event_parses_keyspace_channel() {
        let msg = PubSubConnection::parse_message(keyspace_pmessage(
            "__keyspace@0__:*",
            "__keyspace@0__:foo",
            "set",
        ))
        .unwrap()
        .unwrap();
        let event = KeyspaceEvent::from_message(&msg).unwrap();
        assert_eq!(event.kind, NotificationKind::Keyspace);
        assert_eq!(event.db, 0);
        assert_eq!(event.key, "foo");
        assert_eq!(event.event, "set");
    }

    #[test]
    fn keyspace_event_parses_keyevent_channel() {
        let msg = PubSubConnection::parse_message(keyspace_pmessage(
            "__keyevent@3__:*",
            "__keyevent@3__:expired",
            "session:42",
        ))
        .unwrap()
        .unwrap();
        let event = KeyspaceEvent::from_message(&msg).unwrap();
        assert_eq!(event.kind, NotificationKind::Keyevent);
        assert_eq!(event.db, 3);
        assert_eq!(event.key, "session:42");
        assert_eq!(event.event, "expired");
    }

    #[test]
    fn keyspace_event_preserves_colons_in_key() {
        // Keys containing the `__:` delimiter's `:` must survive: `split_once`
        // splits on the first `__:` only.
        let msg = PubSubConnection::parse_message(keyspace_pmessage(
            "__keyspace@0__:*",
            "__keyspace@0__:a:b:c",
            "del",
        ))
        .unwrap()
        .unwrap();
        let event = KeyspaceEvent::from_message(&msg).unwrap();
        assert_eq!(event.key, "a:b:c");
        assert_eq!(event.event, "del");
    }

    #[test]
    fn keyspace_event_returns_none_for_ordinary_channel() {
        let msg = PubSubConnection::parse_message(array(vec![
            bulk("message"),
            bulk("events"),
            bulk("payload"),
        ]))
        .unwrap()
        .unwrap();
        assert!(KeyspaceEvent::from_message(&msg).is_none());
    }

    #[test]
    fn keyspace_event_returns_none_for_non_numeric_db() {
        let msg = PubSubConnection::parse_message(keyspace_pmessage(
            "__keyspace@x__:*",
            "__keyspace@x__:foo",
            "set",
        ))
        .unwrap()
        .unwrap();
        assert!(KeyspaceEvent::from_message(&msg).is_none());
    }

    #[test]
    fn keyspace_event_stream_filter_skips_non_keyspace() {
        // KeyspaceEventStream::poll_next maps each PubSubMessage through
        // KeyspaceEvent::from_message and skips the `None`s: a plain message is
        // dropped while a keyspace notification is converted.
        let plain = PubSubConnection::parse_message(array(vec![
            bulk("message"),
            bulk("events"),
            bulk("hi"),
        ]))
        .unwrap()
        .unwrap();
        assert!(KeyspaceEvent::from_message(&plain).is_none());

        let ks = PubSubConnection::parse_message(keyspace_pmessage(
            "__keyspace@0__:*",
            "__keyspace@0__:k",
            "lpush",
        ))
        .unwrap()
        .unwrap();
        let event = KeyspaceEvent::from_message(&ks).unwrap();
        assert_eq!(event.event, "lpush");
        assert_eq!(event.key, "k");
    }
}