nfs-rs 0.8.3

An asynchronous pure Rust client library for NFSv3, experimental NFSv4.0, and NFSv4.1
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
// Copyright 2025 NetApp Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

pub mod auth;
pub mod header;

use crate::error::{NfsError, Result};
use byteorder::{BigEndian, ByteOrder};
use bytes::{Bytes, BytesMut};
use std::collections::HashMap;
use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};
use tokio::sync::{Mutex as TokioMutex, MutexGuard as TokioMutexGuard, Notify, oneshot};
use tokio::task::JoinHandle;
use tracing::{debug, error, info, trace, warn};

use auth::Auth;
pub(crate) use header::Header;

pub(crate) const RPC_VERSION: u32 = 2;
pub(crate) const PORTMAP_PROG: u32 = 100000;
pub(crate) const PORTMAP_VERSION: u32 = 2;
pub(crate) const PORTMAP_PORT: u16 = 111;
pub(crate) const MOUNT_PROG: u32 = 100005;
pub(crate) const MOUNT3_VERSION: u32 = 3;
pub(crate) const NFS_PROG: u32 = 100003;
pub(crate) const NFS3_VERSION: u32 = 3;

const IPPROTO_TCP: u32 = 6;

/// Timeout for portmap queries (lightweight metadata operations).
const METADATA_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

/// Controls whether the RPC transport may retransmit the exact logical request.
///
/// A retransmission receives a fresh transport XID, but its encoded RPC body and
/// optional zero-copy payload remain byte-identical. Protocol engines must opt in
/// explicitly because only they know whether replay is safe.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct ReplayPolicy {
    max_attempts: usize,
}

impl ReplayPolicy {
    pub(crate) const ONE_ATTEMPT: Self = Self { max_attempts: 1 };

    pub(crate) const fn byte_identical(max_attempts: usize) -> Self {
        assert!(
            max_attempts > 1,
            "byte-identical RPC replay requires at least 2 attempts"
        );
        Self { max_attempts }
    }

    const fn max_attempts(self) -> usize {
        self.max_attempts
    }
}

enum PortmapProc2 {
    Null = 0,
    GetPort = 3,
}

pub(crate) async fn portmap(
    addrs: &Vec<SocketAddr>,
    prog: u32,
    vers: u32,
    auth: &Auth,
    max_retries: usize,
    noresvport: bool,
) -> Result<u16> {
    let mut last_err: Option<(SocketAddr, NfsError)> = None;
    for addr in addrs {
        debug!(addr = %addr, prog, vers, "attempting portmapper lookup");
        match portmap_on_addr(addr, prog, vers, auth, max_retries, noresvport).await {
            Ok(port) => {
                info!(addr = %addr, prog, vers, port, "portmapper resolved port");
                return Ok(port);
            }
            Err(e) => {
                warn!(addr = %addr, prog, vers, error = %e, "portmapper lookup failed on address");
                last_err = Some((*addr, e));
            }
        }
    }
    Err(NfsError::Rpc(format!(
        "portmapper lookup failed for prog={} vers={}: {}",
        prog,
        vers,
        last_err
            .map(|(addr, e)| format!("{}: {}", addr, e))
            .unwrap_or_else(|| "no addresses tried".to_string()),
    )))
}

async fn portmap_on_addr(
    addr: &SocketAddr,
    prog: u32,
    vers: u32,
    auth: &Auth,
    max_retries: usize,
    noresvport: bool,
) -> Result<u16> {
    let mux = StreamMux::connect(*addr, noresvport).await?;
    let client = Client::new(mux, None);
    let result = portmap_calls(&client, prog, vers, auth, max_retries).await;
    let _ = client.shutdown().await;
    result
}

async fn portmap_calls(
    client: &Client,
    prog: u32,
    vers: u32,
    auth: &Auth,
    max_retries: usize,
) -> Result<u16> {
    // PORTMAP NULL
    let mut buf = Vec::<u8>::new();
    Header::new(
        RPC_VERSION,
        PORTMAP_PROG,
        PORTMAP_VERSION,
        PortmapProc2::Null as u32,
        auth,
        &Auth::new_null(),
    )
    .encode(&mut buf);
    client
        .call(
            buf,
            ReplayPolicy::byte_identical(max_retries),
            METADATA_TIMEOUT,
        )
        .await?;

    // PORTMAP GETPORT
    let args = GETPORT2args {
        header: Header::new(
            RPC_VERSION,
            PORTMAP_PROG,
            PORTMAP_VERSION,
            PortmapProc2::GetPort as u32,
            auth,
            &Auth::new_null(),
        ),
        prog,
        vers,
        proto: IPPROTO_TCP,
        port: 0,
    };
    let mut buf = Vec::<u8>::new();
    args.encode(&mut buf);
    let res = client
        .call(
            buf,
            ReplayPolicy::byte_identical(max_retries),
            METADATA_TIMEOUT,
        )
        .await?;
    let bytes: [u8; 4] = res
        .as_ref()
        .try_into()
        .map_err(|_| NfsError::Xdr("GETPORT result must contain exactly 4 bytes".into()))?;
    let port = u16::try_from(u32::from_be_bytes(bytes))
        .map_err(|_| NfsError::Xdr("GETPORT port exceeds 65535".into()))?;
    if port == 0 {
        return Err(NfsError::Rpc("GETPORT service is not registered".into()));
    }
    Ok(port)
}

#[derive(Debug, PartialEq)]
struct GETPORT2args {
    header: Header,
    prog: u32,
    vers: u32,
    proto: u32,
    port: u32,
}

impl GETPORT2args {
    fn encode(&self, buf: &mut Vec<u8>) {
        self.header.encode(buf);
        buf.extend_from_slice(&self.prog.to_be_bytes());
        buf.extend_from_slice(&self.vers.to_be_bytes());
        buf.extend_from_slice(&self.proto.to_be_bytes());
        buf.extend_from_slice(&self.port.to_be_bytes());
    }
}

// ─── StreamMux ───────────────────────────────────────────────────────────────
//
// Multiplexes multiple concurrent RPC calls over a single TCP connection.
// A background reader task dispatches responses by XID via oneshot channels.
// The writer is protected by a TokioMutex that is only held during the write
// phase, allowing true concurrent request/response overlap.

type PendingMap = Arc<std::sync::Mutex<HashMap<u32, oneshot::Sender<Result<Bytes>>>>>;

struct PendingRequestGuard {
    pending: PendingMap,
    xid: u32,
}

impl Drop for PendingRequestGuard {
    fn drop(&mut self) {
        if let Ok(mut map) = self.pending.lock() {
            map.remove(&self.xid);
        }
    }
}

/// Handler for inbound NFSv4.1 backchannel CALLs (server→client CB_COMPOUND).
///
/// Input: the full RPC CALL frame, starting at the xid (record mark already stripped).
/// Output: the full RPC reply frame (also starting at the xid, without record mark),
/// or `None` to drop the message silently (e.g. on a parse error).
///
/// The handler is synchronous — CB processing is pure parsing plus a non-blocking
/// `try_send` to the recall channel, so it never needs to await.
pub(crate) type BackchannelHandler = Arc<dyn Fn(Bytes) -> Option<Vec<u8>> + Send + Sync>;
type ReconnectFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;
type ReconnectHandler = Arc<dyn Fn(Client, u64) -> ReconnectFuture + Send + Sync>;

const CONNECTION_READY: u8 = 0;
const CONNECTION_REBINDING: u8 = 1;
const CONNECTION_FAILED: u8 = 2;

struct RebindPublicationGuard<'a> {
    readiness: &'a AtomicU8,
    notify: &'a Notify,
    published: bool,
}

impl RebindPublicationGuard<'_> {
    fn publish(mut self) {
        self.readiness.store(CONNECTION_READY, Ordering::Release);
        self.notify.notify_waiters();
        self.published = true;
    }
}

impl Drop for RebindPublicationGuard<'_> {
    fn drop(&mut self) {
        if !self.published {
            self.readiness.store(CONNECTION_FAILED, Ordering::Release);
            self.notify.notify_waiters();
        }
    }
}

/// Shared slot for the optional backchannel handler. Installed after the session
/// is established (see `enable_backchannel`); read by the reader loop on each CALL.
type BackchannelSlot = Arc<std::sync::Mutex<Option<BackchannelHandler>>>;

/// A partially written record cannot be followed by another RPC record.
/// Synchronous socket shutdown in Drop also covers task cancellation and timeout.
struct FrameWriteGuard<'a> {
    writer: TokioMutexGuard<'a, OwnedWriteHalf>,
    complete: bool,
}

impl Drop for FrameWriteGuard<'_> {
    fn drop(&mut self) {
        if !self.complete {
            let _ = socket2::SockRef::from(self.writer.as_ref()).shutdown(std::net::Shutdown::Both);
        }
    }
}

async fn connect_stream(addr: SocketAddr, noresvport: bool) -> Result<tokio::net::TcpStream> {
    tokio::time::timeout(
        METADATA_TIMEOUT,
        crate::connect_to_target(&addr, noresvport),
    )
    .await
    .map_err(|_| {
        NfsError::Io(std::io::Error::new(
            std::io::ErrorKind::TimedOut,
            "RPC connect timeout",
        ))
    })?
}

pub(crate) struct StreamMux {
    /// Wrapped in an `Arc` so the reader loop can also write backchannel replies
    /// onto the same connection (NFSv4.1 backchannel rides the fore-channel TCP).
    writer: Arc<TokioMutex<OwnedWriteHalf>>,
    pending: PendingMap,
    backchannel: BackchannelSlot,
    addr: SocketAddr,
    noresvport: bool,
    generation: AtomicU64,
    reconnect_lock: TokioMutex<()>,
    reconnect_handler: std::sync::Mutex<Option<ReconnectHandler>>,
    readiness: AtomicU8,
    readiness_notify: Notify,
    reader_handle: std::sync::Mutex<Option<JoinHandle<()>>>,
    /// 标记 shutdown 已调用,阻止后续 reconnect 尝试
    shutdown_flag: AtomicBool,
}

impl StreamMux {
    pub(crate) async fn connect(addr: SocketAddr, noresvport: bool) -> Result<Arc<Self>> {
        let stream = connect_stream(addr, noresvport).await?;
        let (reader, writer) = stream.into_split();
        let pending: PendingMap = Arc::new(std::sync::Mutex::new(HashMap::new()));
        let writer = Arc::new(TokioMutex::new(writer));
        let backchannel: BackchannelSlot = Arc::new(std::sync::Mutex::new(None));
        let reader = BufReader::with_capacity(1_048_576, reader);
        let reader_handle = tokio::spawn(reader_loop(
            reader,
            Arc::clone(&pending),
            Arc::clone(&writer),
            Arc::clone(&backchannel),
        ));
        info!(addr = %addr, "RPC stream mux connected");
        Ok(Arc::new(Self {
            writer,
            pending,
            backchannel,
            addr,
            noresvport,
            generation: AtomicU64::new(0),
            reconnect_lock: TokioMutex::new(()),
            reconnect_handler: std::sync::Mutex::new(None),
            readiness: AtomicU8::new(CONNECTION_READY),
            readiness_notify: Notify::new(),
            reader_handle: std::sync::Mutex::new(Some(reader_handle)),
            shutdown_flag: AtomicBool::new(false),
        }))
    }

    fn generation(&self) -> u64 {
        self.generation.load(Ordering::Acquire)
    }

    /// Install the backchannel handler so the reader loop dispatches inbound
    /// server CB_COMPOUND CALLs. Called once after the session is established.
    fn enable_backchannel(&self, handler: BackchannelHandler) {
        match self.backchannel.lock() {
            Ok(mut slot) => *slot = Some(handler),
            Err(_) => warn!("backchannel slot lock poisoned; cannot enable backchannel"),
        }
    }

    fn set_reconnect_handler(&self, handler: ReconnectHandler) -> Result<()> {
        let mut slot = self
            .reconnect_handler
            .lock()
            .map_err(|_| NfsError::Rpc("reconnect handler lock poisoned".to_string()))?;
        *slot = Some(handler);
        Ok(())
    }

    async fn wait_until_ready(&self) -> Result<()> {
        loop {
            match self.readiness.load(Ordering::Acquire) {
                CONNECTION_READY => return Ok(()),
                CONNECTION_FAILED => {
                    return Err(NfsError::Rpc(
                        "NFSv4.1 connection rebind failed; connection is not ready".to_string(),
                    ));
                }
                _ => {
                    let notified = self.readiness_notify.notified();
                    if self.readiness.load(Ordering::Acquire) == CONNECTION_REBINDING {
                        notified.await;
                    }
                }
            }
        }
    }

    /// `header` is the pre-assembled RPC frame header + msg_body (prefix already prepended).
    /// `data` is the optional large payload (e.g. WRITE data), sent zero-copy after the header.
    async fn send_and_receive_inner(
        &self,
        xid: u32,
        header: &[u8],
        data: &[u8],
        data_pad: usize,
        timeout: std::time::Duration,
        bypass_readiness: bool,
    ) -> Result<Bytes> {
        let mut transmission = crate::RequestTransmission::NotSent;
        let attempt = async {
            if !bypass_readiness {
                self.wait_until_ready().await.map_err(|error| {
                    NfsError::transport(crate::RequestTransmission::NotSent, error)
                })?;
            }
            let (tx, rx) = oneshot::channel();
            self.pending
                .lock()
                .map_err(|_| {
                    NfsError::transport(
                        crate::RequestTransmission::NotSent,
                        NfsError::Rpc("pending map lock poisoned".to_string()),
                    )
                })?
                .insert(xid, tx);
            let _pending_guard = PendingRequestGuard {
                pending: Arc::clone(&self.pending),
                xid,
            };

            // Write request under the writer lock — released before awaiting the response.
            // `header` already contains the RPC frame prefix + msg_body (zero-copy, no extra alloc).
            let write_result = {
                let writer = self.writer.lock().await;
                let mut frame = FrameWriteGuard {
                    writer,
                    complete: false,
                };
                transmission = crate::RequestTransmission::Sent;
                async {
                    frame.writer.write_all(header).await?;
                    if !data.is_empty() {
                        frame.writer.write_all(data).await?;
                        if data_pad > 0 {
                            frame.writer.write_all(&[0u8; 4][..data_pad]).await?;
                        }
                    }
                    frame.complete = true;
                    Ok::<(), NfsError>(())
                }
                .await
            };

            write_result
                .map_err(|error| NfsError::transport(crate::RequestTransmission::Sent, error))?;

            // Wait for response from the reader task with timeout.
            match tokio::time::timeout(timeout, rx).await {
                Ok(Ok(Err(error @ NfsError::Io(_)))) => {
                    Err(NfsError::transport(crate::RequestTransmission::Sent, error))
                }
                Ok(Ok(result)) => result,
                Ok(Err(_)) => Err(NfsError::transport(
                    crate::RequestTransmission::Sent,
                    NfsError::Io(std::io::Error::new(
                        std::io::ErrorKind::BrokenPipe,
                        "reader task terminated",
                    )),
                )),
                Err(_) => Err(NfsError::transport(
                    crate::RequestTransmission::Sent,
                    NfsError::Io(std::io::Error::new(
                        std::io::ErrorKind::TimedOut,
                        "RPC response timeout",
                    )),
                )),
            }
        };
        tokio::time::timeout(timeout, attempt).await.map_err(|_| {
            NfsError::transport(
                transmission,
                NfsError::Io(std::io::Error::new(
                    std::io::ErrorKind::TimedOut,
                    "RPC attempt timeout",
                )),
            )
        })?
    }

    async fn reconnect(self: &Arc<Self>, failed_gen: u64) -> Result<()> {
        // 已关闭的连接不再重连
        if self.shutdown_flag.load(Ordering::Acquire) {
            return Err(NfsError::Io(std::io::Error::new(
                std::io::ErrorKind::NotConnected,
                "mux is shut down",
            )));
        }
        let _reconnect = self.reconnect_lock.lock().await;
        info!(addr = %self.addr, failed_gen, "initiating reconnection");
        // Fast path: another caller already reconnected (no lock needed).
        let current_gen = self.generation.load(Ordering::Acquire);
        if current_gen > failed_gen {
            debug!(addr = %self.addr, current_gen, failed_gen, "reconnection already performed by another caller");
            return Ok(());
        }
        // Establish new TCP connection OUTSIDE the writer lock so that
        // concurrent send_and_receive() calls are not blocked during connect.
        let stream = connect_stream(self.addr, self.noresvport).await?;
        let (reader, new_writer) = stream.into_split();
        let reader = BufReader::with_capacity(1_048_576, reader);

        // Take the lock only to swap writer/reader (microsecond-level hold).
        let mut writer = self.writer.lock().await;
        let current_gen = self.generation.load(Ordering::Acquire);
        if current_gen > failed_gen {
            debug!(addr = %self.addr, current_gen, failed_gen, "reconnection already performed by another caller (after connect)");
            return Ok(()); // discard the connection we just built
        }
        // 再次检查 shutdown,避免在等锁期间被 shutdown
        if self.shutdown_flag.load(Ordering::Acquire) {
            return Err(NfsError::Io(std::io::Error::new(
                std::io::ErrorKind::NotConnected,
                "mux is shut down",
            )));
        }
        self.readiness
            .store(CONNECTION_REBINDING, Ordering::Release);
        let publication = RebindPublicationGuard {
            readiness: &self.readiness,
            notify: &self.readiness_notify,
            published: false,
        };
        // Abort old reader.
        if let Ok(mut guard) = self.reader_handle.lock()
            && let Some(handle) = guard.take()
        {
            handle.abort();
        }
        // Fail all pending requests.
        {
            let mut map = self
                .pending
                .lock()
                .map_err(|_| NfsError::Rpc("pending map lock poisoned".to_string()))?;
            if !map.is_empty() {
                debug!(addr = %self.addr, pending_count = map.len(), "failing pending requests due to reconnection");
            }
            for (_, tx) in map.drain() {
                let _ = tx.send(Err(NfsError::Io(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "reconnecting",
                ))));
            }
        }
        // Install new connection.
        *writer = new_writer;
        {
            let mut guard = self
                .reader_handle
                .lock()
                .map_err(|_| NfsError::Rpc("reader_handle lock poisoned".to_string()))?;
            *guard = Some(tokio::spawn(reader_loop(
                reader,
                Arc::clone(&self.pending),
                Arc::clone(&self.writer),
                Arc::clone(&self.backchannel),
            )));
        }
        drop(writer);
        let next_generation = failed_gen.saturating_add(1);
        let handler = self
            .reconnect_handler
            .lock()
            .map_err(|_| NfsError::Rpc("reconnect handler lock poisoned".to_string()))?
            .clone();
        if let Some(handler) = handler
            && let Err(error) = handler(Client::new(Arc::clone(self), None), next_generation).await
        {
            return Err(error);
        }
        self.generation.store(next_generation, Ordering::Release);
        publication.publish();
        info!(addr = %self.addr, generation = next_generation, "reconnection ready");
        Ok(())
    }

    async fn shutdown(&self) {
        self.shutdown_flag.store(true, Ordering::Release);
        debug!(addr = %self.addr, "shutting down StreamMux");
        if let Ok(mut guard) = self.reader_handle.lock()
            && let Some(handle) = guard.take()
        {
            handle.abort();
        }
        let mut writer = self.writer.lock().await;
        let _ = writer.shutdown().await;
        if let Ok(mut map) = self.pending.lock() {
            for (_, tx) in map.drain() {
                let _ = tx.send(Err(NfsError::Io(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "shutdown",
                ))));
            }
        }
    }
}

impl Drop for StreamMux {
    fn drop(&mut self) {
        if let Ok(mut guard) = self.reader_handle.lock()
            && let Some(handle) = guard.take()
        {
            handle.abort();
        }
        if let Ok(mut map) = self.pending.lock() {
            for (_, tx) in map.drain() {
                let _ = tx.send(Err(NfsError::Io(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "connection closed",
                ))));
            }
        }
    }
}

/// Background task: reads RPC messages from the TCP stream. Server REPLY messages
/// are dispatched to the waiting caller via the PendingMap; server CALL messages
/// (NFSv4.1 backchannel CB_COMPOUND, which ride the fore-channel connection) are
/// handed to the registered backchannel handler and the reply is written back on
/// the same connection.
async fn reader_loop(
    mut reader: BufReader<OwnedReadHalf>,
    pending: PendingMap,
    writer: Arc<TokioMutex<OwnedWriteHalf>>,
    backchannel: BackchannelSlot,
) {
    loop {
        match read_one_response(&mut reader).await {
            Ok((xid, data)) => {
                // RPC msg_type lives at bytes [4..8]: 0 = CALL, 1 = REPLY.
                // A CALL here is a server-initiated backchannel request, not a
                // response to one of our outstanding calls.
                let msg_type = if data.len() >= 8 {
                    BigEndian::read_u32(&data[4..8])
                } else {
                    MessageType::Response as u32
                };
                if msg_type == MessageType::Request as u32 {
                    dispatch_backchannel_call(xid, data, &writer, &backchannel).await;
                    continue;
                }
                match pending.lock() {
                    Ok(mut map) => match map.remove(&xid) {
                        Some(tx) => {
                            let _ = tx.send(Ok(data));
                        }
                        _ => {
                            debug!(
                                xid,
                                "dropping response for unmatched XID (likely stale retry)"
                            );
                        }
                    },
                    _ => {
                        warn!("pending map lock poisoned in reader loop, terminating");
                        break;
                    }
                }
            }
            Err(e) => {
                warn!(error = %e, "reader loop terminated due to connection error");
                // Connection broken: fail all pending requests.
                if let Ok(mut map) = pending.lock() {
                    for (_, tx) in map.drain() {
                        let error = match &e {
                            NfsError::Rpc(message) => NfsError::Rpc(message.clone()),
                            _ => NfsError::Io(std::io::Error::new(
                                std::io::ErrorKind::BrokenPipe,
                                e.to_string(),
                            )),
                        };
                        let _ = tx.send(Err(error));
                    }
                }
                break;
            }
        }
    }
}

/// Handle a server-initiated backchannel CALL (CB_COMPOUND) received on the
/// fore-channel connection: dispatch it to the registered handler and write the
/// reply back on the same connection. If no handler is registered, the CALL is
/// dropped (the server will observe this via SEQ4_STATUS on the fore channel).
async fn dispatch_backchannel_call(
    xid: u32,
    data: Bytes,
    writer: &Arc<TokioMutex<OwnedWriteHalf>>,
    backchannel: &BackchannelSlot,
) {
    let handler = match backchannel.lock() {
        Ok(slot) => slot.clone(),
        Err(_) => {
            warn!("backchannel slot lock poisoned, dropping backchannel CALL");
            return;
        }
    };
    let Some(handler) = handler else {
        debug!(
            xid,
            "backchannel CALL received but no handler registered, dropping"
        );
        return;
    };
    let Some(reply) = handler(data) else {
        debug!(xid, "backchannel handler dropped CALL (parse error)");
        return;
    };
    // Frame with the RPC record mark (MSB = last fragment) and write on the
    // shared writer; this serializes against concurrent fore-channel requests.
    let mark = (reply.len() as u32) | 0x80000000;
    let mut out = Vec::with_capacity(4 + reply.len());
    out.extend_from_slice(&mark.to_be_bytes());
    out.extend_from_slice(&reply);
    let result = tokio::time::timeout(METADATA_TIMEOUT, async {
        let mut frame = FrameWriteGuard {
            writer: writer.lock().await,
            complete: false,
        };
        frame.writer.write_all(&out).await?;
        frame.complete = true;
        Ok::<(), std::io::Error>(())
    })
    .await;
    if !matches!(result, Ok(Ok(()))) {
        warn!(xid, "failed to write backchannel reply before deadline");
    }
}

/// Maximum RPC response size (4 MiB + 4 KiB overhead). Responses exceeding this
/// are rejected to prevent memory exhaustion from malicious or buggy servers.
const MAX_RPC_RESPONSE: usize = 4 * 1024 * 1024 + 4096;

async fn read_one_response(reader: &mut BufReader<OwnedReadHalf>) -> Result<(u32, Bytes)> {
    let mut hdr = [0u8; 4];
    reader.read_exact(&mut hdr).await?;
    let raw = BigEndian::read_u32(&hdr);
    let last = (raw & 0x80000000) != 0;
    let sz = (raw & 0x7FFFFFFF) as usize;
    if sz > MAX_RPC_RESPONSE {
        return Err(NfsError::Rpc(format!(
            "RPC fragment size {} exceeds maximum {}",
            sz, MAX_RPC_RESPONSE
        )));
    }

    let mut buf = BytesMut::with_capacity(sz);
    buf.resize(sz, 0);
    reader.read_exact(&mut buf[..sz]).await?;

    if !last {
        // Multi-fragment: keep reading until the last fragment.
        loop {
            reader.read_exact(&mut hdr).await?;
            let raw = BigEndian::read_u32(&hdr);
            let last = (raw & 0x80000000) != 0;
            let sz = (raw & 0x7FFFFFFF) as usize;
            let total = buf.len() + sz;
            if total > MAX_RPC_RESPONSE {
                return Err(NfsError::Rpc(format!(
                    "RPC accumulated response size {} exceeds maximum {}",
                    total, MAX_RPC_RESPONSE
                )));
            }
            let offset = buf.len();
            buf.resize(total, 0);
            reader.read_exact(&mut buf[offset..]).await?;
            if last {
                break;
            }
        }
    }

    if buf.len() < std::mem::size_of::<u32>() {
        return Err(NfsError::Rpc(format!(
            "RPC record size {} is shorter than XID",
            buf.len()
        )));
    }

    let xid = BigEndian::read_u32(&buf[0..4]);
    Ok((xid, buf.freeze()))
}

// ─── Client ──────────────────────────────────────────────────────────────────

#[derive(Debug, Clone)]
pub(crate) struct Client {
    nfs_mux: Arc<StreamMux>,
    mount_mux: Option<Arc<StreamMux>>,
}

impl std::fmt::Debug for StreamMux {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StreamMux")
            .field("addr", &self.addr)
            .field("generation", &self.generation.load(Ordering::Acquire))
            .finish()
    }
}

impl Client {
    pub(crate) fn new(nfs_mux: Arc<StreamMux>, mount_mux: Option<Arc<StreamMux>>) -> Self {
        Self { nfs_mux, mount_mux }
    }

    /// Install the NFSv4.1 backchannel handler on the NFS connection so the
    /// reader loop dispatches inbound server CB_COMPOUND CALLs.
    pub(crate) fn enable_backchannel(&self, handler: BackchannelHandler) {
        self.nfs_mux.enable_backchannel(handler);
    }

    pub(crate) fn set_reconnect_handler<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(Client, u64) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        self.nfs_mux
            .set_reconnect_handler(Arc::new(move |client, generation| {
                Box::pin(handler(client, generation))
            }))
    }

    fn get_mux(&self, program: u32) -> Result<&Arc<StreamMux>> {
        match program {
            MOUNT_PROG => Ok(self.mount_mux.as_ref().unwrap_or(&self.nfs_mux)),
            NFS_PROG | PORTMAP_PROG => Ok(&self.nfs_mux),
            _ => Err(NfsError::InvalidInput(format!(
                "unknown RPC program {}",
                program
            ))),
        }
    }

    pub(crate) async fn call(
        &self,
        msg_body: Vec<u8>,
        replay_policy: ReplayPolicy,
        timeout: std::time::Duration,
    ) -> Result<Bytes> {
        self.call_with_data(msg_body, Bytes::new(), replay_policy, timeout)
            .await
    }

    /// Like `call`, but sends `data` after `msg_body` without copying it into the request buffer.
    /// `msg_body` must already contain the XDR length-prefix for the data field (4 bytes at the
    /// end); the raw payload bytes and their padding are written to the stream separately.
    pub(crate) async fn call_with_data(
        &self,
        msg_body: Vec<u8>,
        data: Bytes,
        replay_policy: ReplayPolicy,
        timeout: std::time::Duration,
    ) -> Result<Bytes> {
        self.call_with_data_inner(msg_body, data, replay_policy, timeout, false)
            .await
    }

    pub(crate) async fn call_during_reconnect(
        &self,
        msg_body: Vec<u8>,
        timeout: std::time::Duration,
    ) -> Result<Bytes> {
        self.call_with_data_inner(
            msg_body,
            Bytes::new(),
            ReplayPolicy::ONE_ATTEMPT,
            timeout,
            true,
        )
        .await
    }

    async fn call_with_data_inner(
        &self,
        mut msg_body: Vec<u8>,
        data: Bytes,
        replay_policy: ReplayPolicy,
        timeout: std::time::Duration,
        bypass_readiness: bool,
    ) -> Result<Bytes> {
        const SIZE_HDR_BIT: u32 = 0x80000000;
        const PREFIX_LEN: usize = 12;

        let max_attempts = replay_policy.max_attempts();
        let mut attempt = 0usize;
        let mut last_error = None;
        let mut logical_transmission = crate::RequestTransmission::NotSent;
        let start = tokio::time::Instant::now();
        // Total replay budget: 3x the per-attempt timeout, so we fail fast instead
        // of accumulating max_attempts * timeout worth of delay.
        let max_total = timeout.saturating_mul(3);
        let deadline = start + max_total;

        // Determine mux from the program field in msg_body (offset 4, big-endian u32).
        let program = if msg_body.len() >= 8 {
            BigEndian::read_u32(&msg_body[4..8])
        } else {
            NFS_PROG
        };
        let mux = self.get_mux(program)?;

        let data_len = data.len();
        let data_pad = (4 - data_len % 4) % 4;
        let payload_len = (8 + msg_body.len() + data_len + data_pad) as u32;

        // Prepend 12-byte RPC frame prefix space to msg_body (one-time allocation).
        // XID at offset 4..8 is overwritten per retry; the rest is constant.
        msg_body.splice(0..0, [0u8; PREFIX_LEN]);
        BigEndian::write_u32(&mut msg_body[0..4], payload_len | SIZE_HDR_BIT);
        // msg_body[4..8] = xid, written per retry below
        BigEndian::write_u32(&mut msg_body[8..12], MessageType::Request as u32);

        while attempt < max_attempts {
            // Bail out if total elapsed time exceeds the budget.
            if tokio::time::Instant::now() >= deadline {
                break;
            }

            // Each retry uses a fresh XID (the old one may have stale responses in flight).
            let xid = get_xid();
            BigEndian::write_u32(&mut msg_body[4..8], xid);

            debug!(
                xid,
                attempt = attempt + 1,
                max_attempts,
                ?replay_policy,
                program,
                "sending RPC request"
            );
            let r#gen = mux.generation();
            let res = mux
                .send_and_receive_inner(
                    xid,
                    &msg_body,
                    &data,
                    data_pad,
                    timeout.min(deadline.saturating_duration_since(tokio::time::Instant::now())),
                    bypass_readiness,
                )
                .await;

            match res {
                Ok(response_data) => {
                    trace!(xid, "RPC response received");
                    return parse_rpc_response(response_data, xid);
                }
                Err(mut e) => {
                    if e.request_transmission() == Some(crate::RequestTransmission::Sent) {
                        logical_transmission = crate::RequestTransmission::Sent;
                    } else if logical_transmission == crate::RequestTransmission::Sent {
                        e = NfsError::transport(crate::RequestTransmission::Sent, e);
                    }
                    if bypass_readiness {
                        return Err(e);
                    }
                    let kind = e.kind();
                    let is_conn_error = matches!(
                        kind,
                        std::io::ErrorKind::BrokenPipe
                            | std::io::ErrorKind::ConnectionAborted
                            | std::io::ErrorKind::ConnectionReset
                    );
                    let is_timeout = kind == std::io::ErrorKind::TimedOut;
                    if is_conn_error {
                        attempt += 1;
                        if attempt >= max_attempts {
                            last_error = Some(e);
                            continue;
                        }
                        // Connection dead — reconnect then retry.
                        warn!(
                            xid,
                            attempt,
                            max_attempts,
                            error = %e,
                            "RPC call failed (connection error), reconnecting"
                        );
                        let jitter = rand::random_range(0..50u64);
                        let backoff = std::cmp::min(100u64 << (attempt - 1), 2000) + jitter;
                        let reconnect = async {
                            tokio::time::sleep(tokio::time::Duration::from_millis(backoff)).await;
                            mux.reconnect(r#gen).await
                        };
                        match tokio::time::timeout_at(deadline, reconnect).await {
                            Ok(Ok(())) => {}
                            Ok(Err(reconn_err)) => {
                                warn!(error = %reconn_err, "reconnect failed, will retry")
                            }
                            Err(_) => {
                                last_error = Some(NfsError::transport(
                                    logical_transmission,
                                    NfsError::Io(std::io::Error::new(
                                        std::io::ErrorKind::TimedOut,
                                        "RPC total attempt budget exhausted during reconnect",
                                    )),
                                ));
                                break;
                            }
                        }
                        last_error = Some(e);
                        continue;
                    } else if is_timeout {
                        attempt += 1;
                        if attempt >= max_attempts {
                            last_error = Some(e);
                            continue;
                        }
                        // Timeout — server may be slow but connection could still be alive.
                        // Retry without reconnect to avoid killing other in-flight requests.
                        warn!(
                            xid,
                            attempt,
                            max_attempts,
                            error = %e,
                            "RPC call timed out, retrying without reconnect"
                        );
                        last_error = Some(e);
                        continue;
                    } else {
                        error!(xid, error = %e, "RPC call failed with non-retryable error");
                        return Err(e);
                    }
                }
            }
        }
        error!(
            max_attempts,
            ?replay_policy,
            elapsed_ms = start.elapsed().as_millis() as u64,
            program,
            "RPC retries exhausted, giving up"
        );
        Err(last_error.unwrap_or_else(|| {
            NfsError::Io(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                "RPC total attempt budget exhausted",
            ))
        }))
    }

    pub(crate) async fn shutdown(&self) {
        self.nfs_mux.shutdown().await;
        if let Some(ref mount_mux) = self.mount_mux {
            mount_mux.shutdown().await;
        }
    }

    #[cfg(test)]
    pub(crate) async fn new_dummy() -> Self {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let (stream_result, _accept_result) =
            tokio::join!(tokio::net::TcpStream::connect(addr), listener.accept());
        let stream = stream_result.unwrap();
        stream.set_nodelay(true).unwrap();
        let (reader, writer) = stream.into_split();
        let pending: PendingMap = Arc::new(std::sync::Mutex::new(HashMap::new()));
        let writer = Arc::new(TokioMutex::new(writer));
        let backchannel: BackchannelSlot = Arc::new(std::sync::Mutex::new(None));
        let reader = BufReader::with_capacity(1_048_576, reader);
        let reader_handle = tokio::spawn(reader_loop(
            reader,
            Arc::clone(&pending),
            Arc::clone(&writer),
            Arc::clone(&backchannel),
        ));
        let mux = Arc::new(StreamMux {
            writer,
            pending,
            backchannel,
            addr,
            noresvport: false,
            generation: AtomicU64::new(0),
            reconnect_lock: TokioMutex::new(()),
            reconnect_handler: std::sync::Mutex::new(None),
            readiness: AtomicU8::new(CONNECTION_READY),
            readiness_notify: Notify::new(),
            reader_handle: std::sync::Mutex::new(Some(reader_handle)),
            shutdown_flag: AtomicBool::new(false),
        });
        Self {
            nfs_mux: mux,
            mount_mux: None,
        }
    }
}

/// Strip the RPC response envelope and return the NFS payload as a zero-copy `Bytes` slice.
///
/// Format: [xid(4)] [msgtype(4)] [msg_status(4)] [verf_flavor(4)] [verf_len(4)]
///         [verf_data…] [accept_stat(4)] [payload…]
fn parse_rpc_response(res: Bytes, xid: u32) -> Result<Bytes> {
    let read_u32 = |data: &[u8], p: usize| -> Result<u32> {
        if p + 4 > data.len() {
            return Err(NfsError::Rpc("response truncated".to_string()));
        }
        Ok(BigEndian::read_u32(&data[p..p + 4]))
    };

    if res.len() < 8 {
        error!(xid, response_len = res.len(), "RPC response too short");
        return Err(NfsError::Rpc("response too short".to_string()));
    }
    let res_xid = BigEndian::read_u32(&res[0..4]);
    let res_msgtype = BigEndian::read_u32(&res[4..8]);
    if res_xid != xid {
        error!(
            expected_xid = xid,
            actual_xid = res_xid,
            "RPC response XID mismatch"
        );
        return Err(NfsError::Rpc(
            "response id does not match expected one".to_string(),
        ));
    }
    if res_msgtype != MessageType::Response as u32 {
        error!(
            xid,
            msgtype = res_msgtype,
            "RPC response has unexpected message type"
        );
        return Err(NfsError::Rpc(
            "response type does not match expected one".to_string(),
        ));
    }

    // reply_body: [msg_status(4)] [verf_flavor(4)] [verf_len(4)] [verf_data] [accept_stat(4)] [data…]
    let mut pos = 8usize;
    let msg_status = read_u32(&res, pos)? as i32;
    pos += 4;
    if msg_status != MessageStatus::Accepted as i32 {
        error!(xid, msg_status, "RPC response rejected (bad status)");
        return Err(NfsError::Rpc(
            "could not parse response due to bad status".to_string(),
        ));
    }
    pos += 4; // skip verifier flavor
    let verf_len = read_u32(&res, pos)? as usize;
    pos += 4;
    let verf_padded = verf_len + (4 - verf_len % 4) % 4;
    if pos + verf_padded > res.len() {
        error!(
            xid,
            response_len = res.len(),
            "RPC response truncated (verifier)"
        );
        return Err(NfsError::Rpc("response truncated (verifier)".to_string()));
    }
    pos += verf_padded;
    let accept_status = read_u32(&res, pos)? as i32;
    pos += 4;
    if accept_status != AcceptStatus::Success as i32 {
        error!(xid, accept_status, "RPC request rejected by server");
        return Err(NfsError::Rpc("request rejected".to_string()));
    }

    // Zero-copy: slice off the RPC envelope, sharing the underlying buffer.
    Ok(res.slice(pos..))
}

#[derive(Debug, Clone, PartialEq)]
enum MessageType {
    Request = 0,
    Response = 1,
}

enum MessageStatus {
    Accepted = 0,
    #[allow(unused)]
    Denied = 1,
}

enum AcceptStatus {
    Success = 0,
    #[allow(unused)]
    ProgUnavail = 1,
    #[allow(unused)]
    ProgMismatch = 2,
    #[allow(unused)]
    ProcUnavail = 3,
    #[allow(unused)]
    GarbageArgs = 4,
}

static XID: AtomicU32 = AtomicU32::new(0);

fn get_xid() -> u32 {
    // Seed with wall-clock time on the very first call; a CAS ensures only one thread seeds.
    if XID.load(Ordering::Relaxed) == 0 {
        XID.compare_exchange(0, get_current_time(), Ordering::Relaxed, Ordering::Relaxed)
            .ok();
    }
    XID.fetch_add(1, Ordering::Relaxed).wrapping_add(1)
}

pub(crate) fn get_current_time() -> u32 {
    let now = std::time::SystemTime::now();
    let since_epoch = now
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default();
    (since_epoch.as_secs() as u32).wrapping_mul(1000) + since_epoch.subsec_millis()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::AtomicUsize;

    async fn read_test_record(stream: &mut tokio::net::TcpStream) -> std::io::Result<Vec<u8>> {
        let marker = stream.read_u32().await?;
        let len = (marker & 0x7fff_ffff) as usize;
        let mut record = vec![0; len];
        stream.read_exact(&mut record).await?;
        Ok(record)
    }

    async fn write_test_rpc_reply(
        stream: &mut tokio::net::TcpStream,
        xid: u32,
        payload: &[u8],
    ) -> std::io::Result<()> {
        let mut reply = Vec::with_capacity(24 + payload.len());
        reply.extend_from_slice(&xid.to_be_bytes());
        reply.extend_from_slice(&(MessageType::Response as u32).to_be_bytes());
        reply.extend_from_slice(&(MessageStatus::Accepted as u32).to_be_bytes());
        reply.extend_from_slice(&0u32.to_be_bytes()); // AUTH_NONE
        reply.extend_from_slice(&0u32.to_be_bytes()); // verifier length
        reply.extend_from_slice(&(AcceptStatus::Success as u32).to_be_bytes());
        stream
            .write_u32(0x8000_0000 | reply.len().saturating_add(payload.len()) as u32)
            .await?;
        stream.write_all(&reply).await?;
        stream.write_all(payload).await
    }

    #[tokio::test]
    async fn short_rpc_records_are_rejected_without_panicking() {
        for payload_len in 0..4usize {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
            let addr = listener.local_addr().unwrap();
            let server = tokio::spawn(async move {
                let (mut stream, _) = listener.accept().await.unwrap();
                stream
                    .write_u32(0x8000_0000 | payload_len as u32)
                    .await
                    .unwrap();
                stream.write_all(&vec![0xa5; payload_len]).await.unwrap();
            });
            let stream = tokio::net::TcpStream::connect(addr).await.unwrap();
            let (reader, _) = stream.into_split();
            let mut reader = BufReader::new(reader);

            let error = read_one_response(&mut reader)
                .await
                .expect_err("an RPC record without an XID must be rejected");
            assert!(
                matches!(error, NfsError::Rpc(ref message) if message.contains("shorter than XID")),
                "short RPC record must produce a framing error, got: {error}"
            );
            server.await.unwrap();
        }
    }

    #[tokio::test]
    async fn pending_call_preserves_short_rpc_record_as_a_protocol_error() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (mut stream, _) = listener.accept().await.unwrap();
            let _request = read_test_record(&mut stream).await.unwrap();
            stream.write_u32(0x8000_0003).await.unwrap();
            stream.write_all(&[0xa5; 3]).await.unwrap();
        });
        let mux = StreamMux::connect(addr, true).await.unwrap();
        let client = Client::new(mux, None);
        let mut body = Vec::new();
        body.extend_from_slice(&RPC_VERSION.to_be_bytes());
        body.extend_from_slice(&NFS_PROG.to_be_bytes());
        body.extend_from_slice(&crate::nfs41::NFS4_VERSION.to_be_bytes());
        body.extend_from_slice(&0u32.to_be_bytes());
        let error = client
            .call(
                body,
                ReplayPolicy::ONE_ATTEMPT,
                std::time::Duration::from_secs(1),
            )
            .await
            .expect_err("short record must fail the pending RPC call");
        assert!(
            matches!(error, NfsError::Rpc(ref message) if message.contains("shorter than XID")),
            "RPC framing type was not preserved: {error}"
        );
        server.await.unwrap();
    }

    #[tokio::test]
    async fn concurrent_reconnect_observers_run_one_effective_rebind() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let accepted = Arc::new(Notify::new());
        let accepted_for_server = Arc::clone(&accepted);
        let server = tokio::spawn(async move {
            let (first, _) = listener.accept().await?;
            let (second, _) = listener.accept().await?;
            accepted_for_server.notify_one();
            tokio::time::sleep(std::time::Duration::from_secs(5)).await;
            Ok::<_, std::io::Error>((first, second))
        });
        let mux = StreamMux::connect(addr, true).await.unwrap();
        let binds = Arc::new(AtomicUsize::new(0));
        let binds_for_handler = Arc::clone(&binds);
        mux.set_reconnect_handler(Arc::new(move |_client, generation| {
            let binds = Arc::clone(&binds_for_handler);
            Box::pin(async move {
                assert_eq!(generation, 1);
                binds.fetch_add(1, Ordering::AcqRel);
                Ok(())
            })
        }))
        .unwrap();

        let tasks = (0..64)
            .map(|_| {
                let mux = Arc::clone(&mux);
                tokio::spawn(async move { mux.reconnect(0).await })
            })
            .collect::<Vec<_>>();
        accepted.notified().await;
        for task in tasks {
            task.await.unwrap().unwrap();
        }
        assert_eq!(binds.load(Ordering::Acquire), 1);
        assert_eq!(mux.generation(), 1);
        assert_eq!(mux.readiness.load(Ordering::Acquire), CONNECTION_READY);
        server.abort();
    }

    #[tokio::test]
    async fn failed_rebind_marks_replacement_connection_unready() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (first, _) = listener.accept().await?;
            let (second, _) = listener.accept().await?;
            tokio::time::sleep(std::time::Duration::from_secs(5)).await;
            Ok::<_, std::io::Error>((first, second))
        });
        let mux = StreamMux::connect(addr, true).await.unwrap();
        mux.set_reconnect_handler(Arc::new(|_client, _generation| {
            Box::pin(async { Err(NfsError::Rpc("injected bind failure".to_string())) })
        }))
        .unwrap();

        assert!(mux.reconnect(0).await.is_err());
        assert_eq!(mux.readiness.load(Ordering::Acquire), CONNECTION_FAILED);
        assert!(mux.wait_until_ready().await.is_err());
        let error = mux
            .send_and_receive_inner(
                7,
                &[0; 12],
                &[],
                0,
                std::time::Duration::from_millis(10),
                false,
            )
            .await
            .expect_err("failed readiness must reject before sending");
        assert_eq!(
            error.request_transmission(),
            Some(crate::RequestTransmission::NotSent)
        );
        server.abort();
    }

    #[tokio::test]
    async fn cancelled_rebind_marks_replacement_connection_unready() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (first, _) = listener.accept().await?;
            let (second, _) = listener.accept().await?;
            tokio::time::sleep(std::time::Duration::from_secs(5)).await;
            Ok::<_, std::io::Error>((first, second))
        });
        let mux = StreamMux::connect(addr, true).await.unwrap();
        let entered = Arc::new(Notify::new());
        let entered_for_handler = Arc::clone(&entered);
        mux.set_reconnect_handler(Arc::new(move |_client, _generation| {
            let entered = Arc::clone(&entered_for_handler);
            Box::pin(async move {
                entered.notify_one();
                std::future::pending::<Result<()>>().await
            })
        }))
        .unwrap();

        let mux_for_task = Arc::clone(&mux);
        let task = tokio::spawn(async move { mux_for_task.reconnect(0).await });
        entered.notified().await;
        task.abort();
        let _ = task.await;
        assert_eq!(mux.readiness.load(Ordering::Acquire), CONNECTION_FAILED);
        assert!(mux.wait_until_ready().await.is_err());
        server.abort();
    }

    #[test]
    fn message_rpc_version() {
        // Program field is at offset 4 in the body: rpcvers(4) prog(4) vers(4) proc(4)
        let body = vec![0u8, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5];
        assert_eq!(BigEndian::read_u32(&body[0..4]), 2);
    }

    #[test]
    fn message_program() {
        let body = vec![0u8, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5];
        assert_eq!(BigEndian::read_u32(&body[4..8]), 3);
    }

    #[test]
    fn message_version() {
        let body = vec![0u8, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5];
        assert_eq!(BigEndian::read_u32(&body[8..12]), 4);
    }

    #[test]
    fn message_procedure() {
        let body = vec![0u8, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5];
        assert_eq!(BigEndian::read_u32(&body[12..16]), 5);
    }

    #[tokio::test]
    async fn portmap_error_includes_underlying_detail() {
        // Connect to a localhost port nobody listens on → ConnectionRefused
        let dead_addr: SocketAddr = "127.0.0.1:1".parse().unwrap();
        let auth = Auth::new_null();
        let res = portmap(&vec![dead_addr], NFS_PROG, NFS3_VERSION, &auth, 2, false).await;
        let err = res.expect_err("dead port should fail");
        let msg = err.to_string();
        assert!(
            msg.contains("127.0.0.1:1")
                || msg.to_lowercase().contains("refused")
                || msg.to_lowercase().contains("connect"),
            "portmap error should expose underlying detail, got: {}",
            msg
        );
    }

    #[tokio::test]
    async fn retransmission_changes_only_xid_and_preserves_zero_copy_payload() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (mut stream, _) = listener.accept().await?;
            let first = read_test_record(&mut stream).await?;
            let second = read_test_record(&mut stream).await?;
            if first.len() < 8 || second.len() < 8 {
                return Err(std::io::Error::other("RPC request too short"));
            }
            if first[0..4] == second[0..4] {
                return Err(std::io::Error::other(
                    "transport attempts must use distinct XIDs",
                ));
            }
            if first[4..] != second[4..] {
                return Err(std::io::Error::other(
                    "logical request changed across retransmission",
                ));
            }
            let xid = BigEndian::read_u32(&second[0..4]);
            write_test_rpc_reply(&mut stream, xid, b"cached-result").await?;
            Ok::<(Vec<u8>, Vec<u8>), std::io::Error>((first, second))
        });

        let mux = StreamMux::connect(addr, true).await.unwrap();
        let client = Client::new(mux, None);
        let payload = Bytes::from(vec![0x5a; 64 * 1024]);
        let payload_ptr = payload.as_ptr();
        let session_id = [0x33; 16];
        let state_id = [0x44; 16];
        let builder = crate::nfs41::compound::CompoundBuilder::new("retry-write")
            .sequence(&session_id, 17, 3, 7)
            .putfh(b"file-handle")
            .write_header(&state_id, 4096, 2, payload.len() as u32)
            .apply_sequence_cache_policy(4096)
            .unwrap();
        let mut body = Vec::new();
        builder.encode_with_header(&Auth::new_null(), &mut body);
        let response = client
            .call_with_data(
                body,
                payload.clone(),
                ReplayPolicy::byte_identical(2),
                std::time::Duration::from_millis(20),
            )
            .await
            .unwrap();
        assert_eq!(response, b"cached-result"[..]);
        assert_eq!(payload.as_ptr(), payload_ptr);

        let (first, second) = server.await.unwrap().unwrap();
        let mut request_identity = Vec::from(session_id);
        request_identity.extend_from_slice(&17u32.to_be_bytes());
        request_identity.extend_from_slice(&3u32.to_be_bytes());
        assert!(
            first
                .windows(request_identity.len())
                .any(|window| window == request_identity)
        );
        assert_eq!(&first[first.len() - payload.len()..], payload.as_ref());
        assert_eq!(&second[second.len() - payload.len()..], payload.as_ref());
        client.shutdown().await;
    }

    #[tokio::test]
    async fn one_attempt_does_not_retransmit_and_preserves_timeout() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (mut stream, _) = listener.accept().await?;
            let first = read_test_record(&mut stream).await?;
            let second = tokio::time::timeout(
                std::time::Duration::from_millis(80),
                read_test_record(&mut stream),
            )
            .await;
            Ok::<(Vec<u8>, bool), std::io::Error>((first, second.is_ok()))
        });

        let mux = StreamMux::connect(addr, true).await.unwrap();
        let client = Client::new(mux, None);
        let mut body = Vec::new();
        body.extend_from_slice(&RPC_VERSION.to_be_bytes());
        body.extend_from_slice(&NFS_PROG.to_be_bytes());
        body.extend_from_slice(&crate::nfs41::NFS4_VERSION.to_be_bytes());
        body.extend_from_slice(&1u32.to_be_bytes());

        let err = client
            .call(
                body,
                ReplayPolicy::ONE_ATTEMPT,
                std::time::Duration::from_millis(20),
            )
            .await
            .expect_err("an unanswered one-attempt call must time out");
        assert!(
            err.kind() == std::io::ErrorKind::TimedOut
                && err.request_transmission() == Some(crate::RequestTransmission::Sent),
            "one-attempt call must preserve its authoritative timeout: {err}"
        );

        let (first, saw_second) = server.await.unwrap().unwrap();
        assert!(!first.is_empty());
        assert!(!saw_second, "one-attempt policy must not retransmit");
        client.shutdown().await;
    }

    #[tokio::test]
    async fn one_attempt_connection_failure_does_not_reconnect() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (mut first_stream, _) = listener.accept().await?;
            let first = read_test_record(&mut first_stream).await?;
            drop(first_stream);
            let reconnected =
                tokio::time::timeout(std::time::Duration::from_millis(250), listener.accept())
                    .await
                    .is_ok();
            Ok::<(Vec<u8>, bool), std::io::Error>((first, reconnected))
        });

        let mux = StreamMux::connect(addr, true).await.unwrap();
        let client = Client::new(mux, None);
        let mut body = Vec::new();
        body.extend_from_slice(&RPC_VERSION.to_be_bytes());
        body.extend_from_slice(&NFS_PROG.to_be_bytes());
        body.extend_from_slice(&crate::nfs41::NFS4_VERSION.to_be_bytes());
        body.extend_from_slice(&1u32.to_be_bytes());
        let err = client
            .call(
                body,
                ReplayPolicy::ONE_ATTEMPT,
                std::time::Duration::from_secs(1),
            )
            .await
            .expect_err("closed connection must fail the call");
        assert_eq!(
            err.request_transmission(),
            Some(crate::RequestTransmission::Sent)
        );
        assert!(matches!(
            err.kind(),
            std::io::ErrorKind::BrokenPipe | std::io::ErrorKind::ConnectionReset
        ));

        let (first, reconnected) = server.await.unwrap().unwrap();
        assert!(!first.is_empty());
        assert!(!reconnected, "one-attempt policy must not reconnect");
        client.shutdown().await;
    }

    #[tokio::test]
    async fn logical_request_keeps_sent_evidence_after_a_later_before_send_failure() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (mut first_stream, _) = listener.accept().await?;
            let first = read_test_record(&mut first_stream).await?;
            drop(first_stream);
            let (_replacement, _) = listener.accept().await?;
            Ok::<Vec<u8>, std::io::Error>(first)
        });

        let mux = StreamMux::connect(addr, true).await.unwrap();
        mux.set_reconnect_handler(Arc::new(|_client, _generation| {
            Box::pin(async { Err(NfsError::Rpc("injected bind failure".to_string())) })
        }))
        .unwrap();
        let client = Client::new(mux, None);
        let mut body = Vec::new();
        body.extend_from_slice(&RPC_VERSION.to_be_bytes());
        body.extend_from_slice(&NFS_PROG.to_be_bytes());
        body.extend_from_slice(&crate::nfs41::NFS4_VERSION.to_be_bytes());
        body.extend_from_slice(&1u32.to_be_bytes());

        let error = client
            .call(
                body,
                ReplayPolicy::byte_identical(2),
                std::time::Duration::from_secs(1),
            )
            .await
            .expect_err("failed rebind must fail the logical request");

        assert_eq!(
            error.request_transmission(),
            Some(crate::RequestTransmission::Sent),
            "an earlier sent attempt must remain authoritative"
        );
        assert!(!server.await.unwrap().unwrap().is_empty());
        client.shutdown().await;
    }

    #[tokio::test]
    async fn byte_identical_replay_reconnects_once_after_connection_failure() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (mut first_stream, _) = listener.accept().await?;
            let first = read_test_record(&mut first_stream).await?;
            drop(first_stream);

            let (mut second_stream, _) = listener.accept().await?;
            let second = read_test_record(&mut second_stream).await?;
            let xid = BigEndian::read_u32(&second[0..4]);
            write_test_rpc_reply(&mut second_stream, xid, b"after-reconnect").await?;
            Ok::<(Vec<u8>, Vec<u8>), std::io::Error>((first, second))
        });

        let mux = StreamMux::connect(addr, true).await.unwrap();
        let client = Client::new(mux, None);
        let mut body = Vec::new();
        body.extend_from_slice(&RPC_VERSION.to_be_bytes());
        body.extend_from_slice(&NFS_PROG.to_be_bytes());
        body.extend_from_slice(&crate::nfs41::NFS4_VERSION.to_be_bytes());
        body.extend_from_slice(&1u32.to_be_bytes());
        let response = client
            .call(
                body,
                ReplayPolicy::byte_identical(2),
                std::time::Duration::from_secs(1),
            )
            .await
            .unwrap();
        assert_eq!(response, b"after-reconnect"[..]);

        let (first, second) = server.await.unwrap().unwrap();
        assert_ne!(&first[0..4], &second[0..4], "attempts need fresh XIDs");
        assert_eq!(&first[4..], &second[4..], "logical request must be stable");
        client.shutdown().await;
    }

    #[test]
    #[should_panic(expected = "requires at least 2 attempts")]
    fn byte_identical_replay_requires_multiple_attempts() {
        let _ = ReplayPolicy::byte_identical(1);
    }

    #[tokio::test]
    async fn cancelled_rpc_removes_pending_xid() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let (received_tx, received_rx) = oneshot::channel();
        let server = tokio::spawn(async move {
            let (mut stream, _) = listener.accept().await?;
            let _request = read_test_record(&mut stream).await?;
            let _ = received_tx.send(());
            std::future::pending::<()>().await;
            #[allow(unreachable_code)]
            Ok::<(), std::io::Error>(())
        });

        let mux = StreamMux::connect(addr, true).await.unwrap();
        let client = Client::new(Arc::clone(&mux), None);
        let mut body = Vec::new();
        body.extend_from_slice(&RPC_VERSION.to_be_bytes());
        body.extend_from_slice(&NFS_PROG.to_be_bytes());
        body.extend_from_slice(&crate::nfs41::NFS4_VERSION.to_be_bytes());
        body.extend_from_slice(&1u32.to_be_bytes());
        let call_client = client.clone();
        let call = tokio::spawn(async move {
            call_client
                .call(
                    body,
                    ReplayPolicy::ONE_ATTEMPT,
                    std::time::Duration::from_secs(30),
                )
                .await
        });
        received_rx.await.unwrap();
        call.abort();
        let _ = call.await;
        tokio::task::yield_now().await;
        assert_eq!(mux.pending.lock().unwrap().len(), 0);

        server.abort();
        let _ = server.await;
        client.shutdown().await;
    }
    fn nfs_test_body() -> Vec<u8> {
        [RPC_VERSION, NFS_PROG, 4, 1]
            .into_iter()
            .flat_map(u32::to_be_bytes)
            .collect()
    }

    #[tokio::test]
    async fn rpc_timeout_includes_waiting_for_writer() {
        let client = Client::new_dummy().await;
        let writer = client.nfs_mux.writer.lock().await;
        let result = tokio::time::timeout(
            std::time::Duration::from_millis(300),
            client.call(
                nfs_test_body(),
                ReplayPolicy::ONE_ATTEMPT,
                std::time::Duration::from_millis(20),
            ),
        )
        .await
        .expect("RPC deadline must include lock admission")
        .unwrap_err();
        assert_eq!(result.kind(), std::io::ErrorKind::TimedOut);
        assert_eq!(
            result.request_transmission(),
            Some(crate::RequestTransmission::NotSent)
        );
        drop(writer);
        client.shutdown().await;
    }

    #[tokio::test]
    async fn portmap_rejects_short_and_out_of_range_results() {
        for payload in [
            vec![],
            vec![0; 3],
            65536u32.to_be_bytes().to_vec(),
            0u32.to_be_bytes().to_vec(),
        ] {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
            let addr = listener.local_addr().unwrap();
            let server = tokio::spawn(async move {
                let (mut stream, _) = listener.accept().await.unwrap();
                for data in [vec![], payload] {
                    let record = read_test_record(&mut stream).await.unwrap();
                    let xid = BigEndian::read_u32(&record[..4]);
                    write_test_rpc_reply(&mut stream, xid, &data).await.unwrap();
                }
            });
            let client = Client::new(StreamMux::connect(addr, true).await.unwrap(), None);
            assert!(
                portmap_calls(&client, NFS_PROG, 3, &Auth::new_null(), 2)
                    .await
                    .is_err()
            );
            client.shutdown().await;
            server.await.unwrap();
        }
    }

    async fn unfinished_frame_is_discarded(cancel: bool) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let (started_tx, started_rx) = oneshot::channel();
        let (drain_tx, drain_rx) = oneshot::channel();
        let server = tokio::spawn(async move {
            let (mut stream, _) = listener.accept().await.unwrap();
            let marker = stream.read_u32().await.unwrap();
            started_tx.send(()).unwrap();
            drain_rx.await.unwrap();
            let mut received = Vec::new();
            tokio::time::timeout(
                std::time::Duration::from_secs(2),
                stream.read_to_end(&mut received),
            )
            .await
            .expect("cancelled partial frame must close its socket")
            .unwrap();
            assert!(received.len() < (marker & 0x7fffffff) as usize);
            let (mut stream, _) = listener.accept().await.unwrap();
            let record = read_test_record(&mut stream).await.unwrap();
            assert_eq!(&record[8..], &nfs_test_body());
            write_test_rpc_reply(&mut stream, BigEndian::read_u32(&record[..4]), b"ok")
                .await
                .unwrap();
        });
        let client = Client::new(StreamMux::connect(addr, true).await.unwrap(), None);
        {
            let writer = client.nfs_mux.writer.lock().await;
            socket2::SockRef::from(writer.as_ref())
                .set_send_buffer_size(1024)
                .unwrap();
        }
        let task_client = client.clone();
        let call = tokio::spawn(async move {
            task_client
                .call_with_data(
                    nfs_test_body(),
                    Bytes::from(vec![1; 16 * 1024 * 1024]),
                    ReplayPolicy::ONE_ATTEMPT,
                    if cancel {
                        std::time::Duration::from_secs(10)
                    } else {
                        std::time::Duration::from_millis(20)
                    },
                )
                .await
        });
        started_rx.await.unwrap();
        if cancel {
            call.abort();
            let _ = call.await;
        } else {
            let error = call.await.unwrap().unwrap_err();
            assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
            assert_eq!(
                error.request_transmission(),
                Some(crate::RequestTransmission::Sent)
            );
        }
        drain_tx.send(()).unwrap();
        let result = client
            .call(
                nfs_test_body(),
                ReplayPolicy::byte_identical(2),
                std::time::Duration::from_secs(3),
            )
            .await;
        server.await.unwrap();
        assert_eq!(result.unwrap(), Bytes::from_static(b"ok"));
        client.shutdown().await;
    }
    #[tokio::test]
    async fn cancelling_partial_frame_closes_stream_and_next_call_reconnects() {
        unfinished_frame_is_discarded(true).await;
    }

    #[tokio::test]
    async fn sending_deadline_discards_partial_frame() {
        unfinished_frame_is_discarded(false).await;
    }

    #[tokio::test]
    async fn rpc_timeout_includes_readiness() {
        let client = Client::new_dummy().await;
        client
            .nfs_mux
            .readiness
            .store(CONNECTION_REBINDING, Ordering::Release);
        let error = client
            .call(
                nfs_test_body(),
                ReplayPolicy::ONE_ATTEMPT,
                std::time::Duration::from_millis(20),
            )
            .await
            .unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
        assert_eq!(
            error.request_transmission(),
            Some(crate::RequestTransmission::NotSent)
        );
        client.shutdown().await;
    }
}