pg-proto 0.3.0

Session-typed PostgreSQL wire protocol
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
//! Buffered, cancellation-safe outbound transport.

use std::{collections::BTreeMap, io, sync::Arc};

use bytes::{Buf, Bytes, BytesMut};
use rustls::{
    ClientConfig, ServerConfig,
    pki_types::{CertificateDer, ServerName},
};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio_util::codec::{Decoder, Encoder};

use crate::{
    Conn,
    auth::TlsServerEndPoint,
    codec::{Backend, BackendMessage, Direction, Frame, Frontend, FrontendMessage, PgCodec},
    demux::{
        CancelKey, Demux, Notification, OrderedAsyncEvent, ParameterStatus, SessionItem,
        TaggedNotice,
    },
    middleware::{
        AcceptsMessage, ClientRole, MessageMiddleware, Middleware, ReceiveError,
        ReconstructableMessage as _, ServerRole, TypedMiddleware, TypedPhase, TypedReceiveError,
    },
    pre_startup::{
        AwaitingSslReply, DEFAULT_MAX_PRE_STARTUP_PACKET_LEN, EncryptionReply, Negotiation,
        PreStartup, PreStartupMessage, ServerSslDecision, SslMode, SslModeNegotiation,
        TlsHandshake, decode_pre_startup_with_limit, gssenc_request_packet, ssl_request_packet,
    },
    tls::{ClientTls, ServerTls},
};

/// Transport wrapper which retains bytes until each write has completed.
#[derive(Debug)]
pub struct Buffered<S, D = Backend> {
    io: S,
    outbound: BytesMut,
    inbound: BytesMut,
    inbound_codec: PgCodec<D>,
    max_pre_startup_packet_len: usize,
    demux: Demux,
}

impl<S> Buffered<S, Backend> {
    /// Wraps an upstream-facing transport which receives backend messages.
    pub fn new(io: S) -> Self {
        Self {
            io,
            outbound: BytesMut::new(),
            inbound: BytesMut::new(),
            inbound_codec: PgCodec::default(),
            max_pre_startup_packet_len: DEFAULT_MAX_PRE_STARTUP_PACKET_LEN,
            demux: Demux::default(),
        }
    }

    /// Creates a backend-facing transport with a bounded tagged-frame size.
    ///
    /// # Errors
    ///
    /// Returns an error when the limit is outside `PostgreSQL`'s frame range.
    pub fn with_max_frame_len(io: S, max_frame_len: usize) -> io::Result<Self> {
        Ok(Self {
            io,
            outbound: BytesMut::new(),
            inbound: BytesMut::new(),
            inbound_codec: PgCodec::with_max_frame_len(max_frame_len)?,
            max_pre_startup_packet_len: DEFAULT_MAX_PRE_STARTUP_PACKET_LEN,
            demux: Demux::default(),
        })
    }
}

impl<S> Buffered<S, Frontend> {
    /// Wraps a client-facing transport which receives frontend messages.
    pub fn new_frontend(io: S) -> Self {
        Self {
            io,
            outbound: BytesMut::new(),
            inbound: BytesMut::new(),
            inbound_codec: PgCodec::default(),
            max_pre_startup_packet_len: DEFAULT_MAX_PRE_STARTUP_PACKET_LEN,
            demux: Demux::default(),
        }
    }

    /// Creates a frontend-facing transport with a bounded tagged-frame size.
    ///
    /// # Errors
    ///
    /// Returns an error when the limit is outside `PostgreSQL`'s frame range.
    pub fn with_max_frame_len_frontend(io: S, max_frame_len: usize) -> io::Result<Self> {
        Self::with_limits_frontend(io, max_frame_len, DEFAULT_MAX_PRE_STARTUP_PACKET_LEN)
    }

    /// Creates a frontend-facing transport with bounded tagged and pre-startup packets.
    ///
    /// # Errors
    ///
    /// Returns an error when either limit is outside `PostgreSQL`'s framing range.
    pub fn with_limits_frontend(
        io: S,
        max_frame_len: usize,
        max_pre_startup_packet_len: usize,
    ) -> io::Result<Self> {
        if !(8..=i32::MAX as usize).contains(&max_pre_startup_packet_len) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "pre-startup packet limit must be between 8 and i32::MAX bytes",
            ));
        }
        Ok(Self {
            io,
            outbound: BytesMut::new(),
            inbound: BytesMut::new(),
            inbound_codec: PgCodec::with_max_frame_len(max_frame_len)?,
            max_pre_startup_packet_len,
            demux: Demux::default(),
        })
    }
}

impl<S, D> Buffered<S, D> {
    /// Encodes a frame synchronously into the outbound buffer.
    ///
    /// # Errors
    ///
    /// Returns an error when the frame is too large to encode.
    pub fn push(&mut self, frame: Frame) -> io::Result<()> {
        self.inbound_codec.encode(frame, &mut self.outbound)
    }

    #[must_use]
    /// Returns encoded bytes which have not yet been fully written.
    pub fn pending(&self) -> &[u8] {
        &self.outbound
    }

    /// Removes buffering and returns the underlying I/O transport.
    pub fn into_inner(self) -> S {
        self.io
    }

    /// Borrows the underlying I/O transport without disturbing codec buffers.
    pub const fn get_ref(&self) -> &S {
        &self.io
    }

    /// Mutably borrows the underlying I/O transport without disturbing codec buffers.
    pub const fn get_mut(&mut self) -> &mut S {
        &mut self.io
    }

    fn push_raw(&mut self, bytes: &[u8]) {
        self.outbound.extend_from_slice(bytes);
    }

    #[must_use]
    /// Returns the backend asynchronous-message demultiplexer.
    pub const fn demux(&self) -> &Demux {
        &self.demux
    }

    /// Returns mutable access to the backend asynchronous-message demultiplexer.
    pub const fn demux_mut(&mut self) -> &mut Demux {
        &mut self.demux
    }
}

impl<S, D> Buffered<S, D>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    async fn connect_tls(
        self,
        server_name: ServerName<'static>,
        config: Arc<ClientConfig>,
    ) -> io::Result<Buffered<ClientTls<S>, D>> {
        if !self.outbound.is_empty() || !self.inbound.is_empty() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "TLS upgrade requires empty plaintext buffers",
            ));
        }
        Ok(Buffered {
            io: crate::tls::connect(self.io, server_name, config).await?,
            outbound: self.outbound,
            inbound: self.inbound,
            inbound_codec: self.inbound_codec,
            max_pre_startup_packet_len: self.max_pre_startup_packet_len,
            demux: self.demux,
        })
    }

    async fn accept_tls(
        self,
        config: Arc<ServerConfig>,
        leaf_certificate: CertificateDer<'static>,
    ) -> io::Result<Buffered<ServerTls<S>, D>> {
        if !self.outbound.is_empty() || !self.inbound.is_empty() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "TLS upgrade requires empty plaintext buffers",
            ));
        }
        Ok(Buffered {
            io: crate::tls::accept(self.io, config, &leaf_certificate).await?,
            outbound: self.outbound,
            inbound: self.inbound,
            inbound_codec: self.inbound_codec,
            max_pre_startup_packet_len: self.max_pre_startup_packet_len,
            demux: self.demux,
        })
    }
}

impl<S: TlsServerEndPoint, D> TlsServerEndPoint for Buffered<S, D> {
    fn tls_server_end_point(&self) -> &[u8] {
        self.io.tls_server_end_point()
    }
}

impl<S: AsyncWrite + Unpin, D> Buffered<S, D> {
    /// Writes all buffered bytes without consuming the connection.
    ///
    /// Completed partial writes are removed immediately. If this future is
    /// cancelled, the connection remains owned by the caller and all unwritten
    /// bytes remain buffered for the next call.
    ///
    /// # Errors
    ///
    /// Returns the underlying transport's write error or `WriteZero`.
    pub async fn flush(&mut self) -> io::Result<()> {
        while !self.outbound.is_empty() {
            let written = self.io.write(&self.outbound).await?;
            if written == 0 {
                return Err(io::Error::new(
                    io::ErrorKind::WriteZero,
                    "transport wrote zero buffered bytes",
                ));
            }
            self.outbound.advance(written);
        }
        self.io.flush().await
    }
}

impl<S: AsyncRead + Unpin, D: Direction> Buffered<S, D> {
    /// Receives one typed message in this transport's inbound direction.
    ///
    /// # Errors
    ///
    /// Returns decoding and underlying transport read errors, or `UnexpectedEof`.
    pub async fn receive_wire(&mut self) -> io::Result<D::Message> {
        loop {
            if let Some(message) = self.inbound_codec.decode(&mut self.inbound)? {
                return Ok(message);
            }
            if self.io.read_buf(&mut self.inbound).await? == 0 {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "peer closed with no complete message",
                ));
            }
        }
    }
}

impl<S: AsyncRead + Unpin> Buffered<S, Backend> {
    async fn receive_encryption_reply(&mut self) -> io::Result<EncryptionReply> {
        let byte = self.io.read_u8().await?;
        EncryptionReply::try_from(byte)
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid encryption reply"))
    }
}

impl<S: AsyncRead + Unpin> Buffered<S, Frontend> {
    /// Receives one raw first packet before tagged frontend framing begins.
    ///
    /// # Errors
    ///
    /// Returns malformed pre-startup data and underlying transport read errors.
    pub async fn receive_pre_startup(&mut self) -> io::Result<PreStartupMessage> {
        loop {
            if let Some(message) =
                decode_pre_startup_with_limit(&mut self.inbound, self.max_pre_startup_packet_len)?
            {
                return Ok(message);
            }
            if self.io.read_buf(&mut self.inbound).await? == 0 {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "client closed with no complete pre-startup packet",
                ));
            }
        }
    }
}

impl<S: AsyncRead + Unpin> Buffered<S, Backend> {
    /// Receives one decoded backend message while retaining partial input.
    ///
    /// # Errors
    ///
    /// Returns decoding and underlying transport read errors, or `UnexpectedEof`.
    pub async fn receive_backend(&mut self) -> io::Result<BackendMessage> {
        self.receive_wire().await
    }

    /// Receives the next protocol-advancing message through the async demux.
    ///
    /// # Errors
    ///
    /// Returns decoding and underlying transport read errors, or `UnexpectedEof`.
    pub async fn receive_session(&mut self) -> io::Result<SessionItem> {
        loop {
            let message = self.receive_backend().await?;
            if let Some(item) = self.project_backend(message) {
                return Ok(item);
            }
        }
    }

    /// Projects an inspected or modified backend message into the session stream.
    pub fn project_backend(&mut self, message: BackendMessage) -> Option<SessionItem> {
        self.demux.route(message)
    }
}

impl<S, D, Phase, Cleanliness> Conn<Buffered<S, D>, Phase, Cleanliness> {
    /// Adds an already-typed message to this connection's outbound buffer.
    ///
    /// # Errors
    ///
    /// Returns an error when the frame is too large to encode.
    pub fn push_frame(&mut self, frame: Frame) -> io::Result<()> {
        self.transport_mut().push(frame)
    }

    #[must_use]
    /// Returns encoded output which has not yet been flushed.
    pub fn pending_output(&self) -> &[u8] {
        self.transport().pending()
    }
}

impl<S, Cleanliness> Conn<Buffered<S, Backend>, PreStartup, Cleanliness> {
    /// Buffers an `SSLRequest` and enters the raw single-byte reply phase.
    pub fn request_ssl(mut self) -> Conn<Buffered<S, Backend>, AwaitingSslReply, Cleanliness> {
        self.transport_mut().push_raw(&ssl_request_packet());
        self.transition()
    }

    /// Buffers a `GSSENCRequest` and enters the raw single-byte reply phase.
    pub fn request_gss(
        mut self,
    ) -> Conn<Buffered<S, Backend>, crate::pre_startup::AwaitingGssReply, Cleanliness> {
        self.transport_mut().push_raw(&gssenc_request_packet());
        self.transition()
    }
}

impl<S, Cleanliness> Conn<Buffered<S, Frontend>, ServerSslDecision, Cleanliness> {
    /// Buffers the server's raw `S` response and enters the TLS handshake phase.
    pub fn approve_ssl(mut self) -> Conn<Buffered<S, Frontend>, TlsHandshake, Cleanliness> {
        self.transport_mut().push_raw(b"S");
        self.transition()
    }

    /// Buffers the server's raw `N` response and returns to pre-startup choice.
    pub fn decline_ssl(mut self) -> Conn<Buffered<S, Frontend>, PreStartup, Cleanliness> {
        self.transport_mut().push_raw(b"N");
        self.transition()
    }

    /// Buffers the historical raw `E` response and terminates negotiation.
    pub fn reject_ssl_with_legacy_error(
        mut self,
    ) -> Conn<Buffered<S, Frontend>, crate::pre_startup::Terminated, Cleanliness> {
        self.transport_mut().push_raw(b"E");
        self.transition()
    }
}

impl<S, Cleanliness>
    Conn<Buffered<S, Frontend>, crate::pre_startup::ServerGssDecision, Cleanliness>
{
    /// Buffers the server's raw `S` response and enters the GSS handshake phase.
    pub fn approve_gss(
        mut self,
    ) -> Conn<Buffered<S, Frontend>, crate::pre_startup::GssHandshake, Cleanliness> {
        self.transport_mut().push_raw(b"S");
        self.transition()
    }

    /// Buffers the server's raw `N` response and returns to pre-startup choice.
    pub fn decline_gss(mut self) -> Conn<Buffered<S, Frontend>, PreStartup, Cleanliness> {
        self.transport_mut().push_raw(b"N");
        self.transition()
    }

    /// Buffers the historical raw `E` response and terminates negotiation.
    pub fn reject_gss_with_legacy_error(
        mut self,
    ) -> Conn<Buffered<S, Frontend>, crate::pre_startup::Terminated, Cleanliness> {
        self.transport_mut().push_raw(b"E");
        self.transition()
    }
}

impl<S: AsyncRead + Unpin, Cleanliness> Conn<Buffered<S, Backend>, AwaitingSslReply, Cleanliness> {
    /// Receives and projects the server's raw SSL decision byte.
    ///
    /// # Errors
    ///
    /// Returns an I/O error or rejects a byte other than `S`, `N`, or `E`.
    pub async fn receive_ssl_reply(
        mut self,
    ) -> io::Result<Negotiation<Buffered<S, Backend>, TlsHandshake, Cleanliness>> {
        let reply = self.transport_mut().receive_encryption_reply().await?;
        Ok(match reply {
            EncryptionReply::Accepted => Negotiation::Accepted(self.transition()),
            EncryptionReply::Rejected => Negotiation::Rejected(self.transition()),
            EncryptionReply::LegacyError => Negotiation::LegacyError(self.transition()),
        })
    }

    /// Receives the server decision and enforces the selected plaintext fallback policy.
    ///
    /// # Errors
    ///
    /// Returns an I/O error or rejects a byte other than `S`, `N`, or `E`.
    pub async fn receive_ssl_reply_for_mode(
        mut self,
        mode: SslMode,
    ) -> io::Result<SslModeNegotiation<Buffered<S, Backend>, Cleanliness>> {
        let reply = self.transport_mut().receive_encryption_reply().await?;
        Ok(self.apply_ssl_reply(reply, mode))
    }
}

impl<S: AsyncRead + Unpin, Cleanliness>
    Conn<Buffered<S, Backend>, crate::pre_startup::AwaitingGssReply, Cleanliness>
{
    /// Receives and projects the server's raw GSSENC decision byte.
    ///
    /// # Errors
    ///
    /// Returns an I/O error or rejects a byte other than `S`, `N`, or `E`.
    pub async fn receive_gss_reply(
        mut self,
    ) -> io::Result<Negotiation<Buffered<S, Backend>, crate::pre_startup::GssHandshake, Cleanliness>>
    {
        let reply = self.transport_mut().receive_encryption_reply().await?;
        Ok(match reply {
            EncryptionReply::Accepted => Negotiation::Accepted(self.transition()),
            EncryptionReply::Rejected => Negotiation::Rejected(self.transition()),
            EncryptionReply::LegacyError => Negotiation::LegacyError(self.transition()),
        })
    }
}

impl<S, Cleanliness> Conn<Buffered<S, Backend>, TlsHandshake, Cleanliness>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    /// Completes a client-side TLS handshake and changes the transport type.
    ///
    /// # Errors
    ///
    /// Returns a TLS handshake, certificate, channel-binding, or buffer-state error.
    pub async fn connect_tls(
        self,
        server_name: ServerName<'static>,
        config: Arc<ClientConfig>,
    ) -> io::Result<Conn<Buffered<ClientTls<S>, Backend>, PreStartup, Cleanliness>> {
        let transport = self.into_transport();
        Ok(Conn::new(transport.connect_tls(server_name, config).await?)
            .transition::<PreStartup, Cleanliness>())
    }
}

impl<S, Cleanliness> Conn<Buffered<S, Frontend>, TlsHandshake, Cleanliness>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    /// Completes a server-side TLS handshake and changes the transport type.
    ///
    /// # Errors
    ///
    /// Returns a TLS handshake, certificate, channel-binding, or buffer-state error.
    pub async fn accept_tls(
        self,
        config: Arc<ServerConfig>,
        leaf_certificate: CertificateDer<'static>,
    ) -> io::Result<Conn<Buffered<ServerTls<S>, Frontend>, PreStartup, Cleanliness>> {
        let transport = self.into_transport();
        Ok(
            Conn::new(transport.accept_tls(config, leaf_certificate).await?)
                .transition::<PreStartup, Cleanliness>(),
        )
    }
}

impl<S, D, Cleanliness> Conn<Buffered<S, D>, crate::pre_startup::Startup, Cleanliness> {
    /// Buffers the raw, untagged startup packet before normal framing begins.
    pub fn push_startup_packet(&mut self, packet: &[u8]) {
        self.transport_mut().outbound.extend_from_slice(packet);
    }
}

impl<S: AsyncWrite + Unpin, D, Phase, Cleanliness> Conn<Buffered<S, D>, Phase, Cleanliness> {
    /// Flushes buffered output while retaining ownership of the typed connection.
    ///
    /// # Errors
    ///
    /// Returns an error from the underlying transport.
    pub async fn flush(&mut self) -> io::Result<()> {
        self.transport_mut().flush().await
    }
}

impl<S: AsyncRead + Unpin, Phase, Cleanliness> Conn<Buffered<S, Backend>, Phase, Cleanliness> {
    /// Receives one backend message before demultiplexing or state advancement.
    /// This is the interception point for proxy policy and message rewriting.
    ///
    /// # Errors
    ///
    /// Returns decoding and underlying transport read errors, or `UnexpectedEof`.
    pub async fn receive_backend_wire(&mut self) -> io::Result<BackendMessage> {
        self.transport_mut().receive_backend().await
    }

    /// Receives one backend message through middleware indexed by this connection phase.
    ///
    /// Unlike [`Self::receive_backend_wire_with_middleware`], callers do not pass
    /// a runtime protocol state. `Phase` selects the generated legal message set
    /// and the server sender role at compile time.
    ///
    /// # Errors
    ///
    /// Returns an I/O or decoding error, an illegal peer message, a middleware
    /// policy error, or a phase-legal replacement with an invalid wire shape.
    pub async fn receive_backend_typed<State, Handler>(
        &mut self,
        middleware: &mut Middleware<State, Handler>,
    ) -> Result<
        <Phase as TypedPhase<ServerRole, BackendMessage>>::Message,
        TypedReceiveError<Handler::Error, BackendMessage>,
    >
    where
        Phase: TypedPhase<ServerRole, BackendMessage>,
        Handler: TypedMiddleware<
                ServerRole,
                <Phase as TypedPhase<ServerRole, BackendMessage>>::ProtocolPhase,
                <Phase as TypedPhase<ServerRole, BackendMessage>>::Message,
                State,
            >,
    {
        let message = self
            .receive_backend_wire()
            .await
            .map_err(TypedReceiveError::Io)?;
        let message = <Phase as TypedPhase<ServerRole, BackendMessage>>::Message::try_from(message)
            .map_err(TypedReceiveError::Illegal)?;
        let message = middleware
            .intercept_typed::<
                ServerRole,
                <Phase as TypedPhase<ServerRole, BackendMessage>>::ProtocolPhase,
                _,
            >(message)
            .await
            .map_err(TypedReceiveError::Middleware)?;
        if message.as_ref().is_reconstructable() {
            Ok(message)
        } else {
            Err(TypedReceiveError::InvalidWire(message.into()))
        }
    }

    /// Receives typed backend traffic until one protocol-advancing item remains.
    ///
    /// Asynchronous messages pass through the same middleware, are recorded by
    /// the demultiplexer in wire order, and leave `Phase` unchanged.
    ///
    /// # Errors
    ///
    /// Returns the same failures as [`Self::receive_backend_typed`].
    pub async fn receive_typed<State, Handler>(
        &mut self,
        middleware: &mut Middleware<State, Handler>,
    ) -> Result<SessionItem, TypedReceiveError<Handler::Error, BackendMessage>>
    where
        Phase: TypedPhase<ServerRole, BackendMessage>,
        Handler: TypedMiddleware<
                ServerRole,
                <Phase as TypedPhase<ServerRole, BackendMessage>>::ProtocolPhase,
                <Phase as TypedPhase<ServerRole, BackendMessage>>::Message,
                State,
            >,
    {
        loop {
            let message = self.receive_backend_typed(middleware).await?;
            if let Some(item) = self.project_backend(message.into()) {
                return Ok(item);
            }
        }
    }

    /// Receives one SSL or GSSENC decision through phase-typed middleware.
    ///
    /// `Phase` must be an encryption-reply phase; callers then consume the
    /// connection with its existing typed `receive_reply` projection.
    ///
    /// # Errors
    ///
    /// Returns an I/O error, illegal decision, middleware policy error, or an
    /// invalid replacement wire shape.
    pub async fn receive_encryption_reply_typed<State, Handler>(
        &mut self,
        middleware: &mut Middleware<State, Handler>,
    ) -> Result<
        <Phase as TypedPhase<ServerRole, EncryptionReply>>::Message,
        TypedReceiveError<Handler::Error, EncryptionReply>,
    >
    where
        Phase: TypedPhase<ServerRole, EncryptionReply>,
        Handler: TypedMiddleware<
                ServerRole,
                <Phase as TypedPhase<ServerRole, EncryptionReply>>::ProtocolPhase,
                <Phase as TypedPhase<ServerRole, EncryptionReply>>::Message,
                State,
            >,
    {
        let message = self
            .transport_mut()
            .receive_encryption_reply()
            .await
            .map_err(TypedReceiveError::Io)?;
        let message =
            <Phase as TypedPhase<ServerRole, EncryptionReply>>::Message::try_from(message)
                .map_err(TypedReceiveError::Illegal)?;
        let message = middleware
            .intercept_typed::<
                ServerRole,
                <Phase as TypedPhase<ServerRole, EncryptionReply>>::ProtocolPhase,
                _,
            >(message)
            .await
            .map_err(TypedReceiveError::Middleware)?;
        if message.as_ref().is_reconstructable() {
            Ok(message)
        } else {
            Err(TypedReceiveError::InvalidWire(message.into()))
        }
    }

    /// Receives, intercepts, and validates one backend message before projection.
    ///
    /// # Errors
    ///
    /// Returns an I/O, decoding, middleware-policy, or state-validation error.
    pub async fn receive_backend_wire_with_middleware<State, Handler, ProtocolState>(
        &mut self,
        middleware: &mut Middleware<State, Handler>,
        protocol_state: &ProtocolState,
    ) -> Result<BackendMessage, ReceiveError<Handler::Error, BackendMessage>>
    where
        Handler: MessageMiddleware<BackendMessage, State>,
        ProtocolState: AcceptsMessage<BackendMessage>,
    {
        let message = self
            .receive_backend_wire()
            .await
            .map_err(ReceiveError::Io)?;
        middleware
            .intercept_checked(protocol_state, message)
            .await
            .map_err(ReceiveError::Intercept)
    }

    /// Projects an inspected or modified message into the filtered session stream.
    pub fn project_backend(&mut self, message: BackendMessage) -> Option<SessionItem> {
        self.transport_mut().project_backend(message)
    }

    /// Receives the next message in the filtered session projection.
    ///
    /// # Errors
    ///
    /// Returns decoding and underlying transport read errors, or `UnexpectedEof`.
    pub async fn receive(&mut self) -> io::Result<SessionItem> {
        self.transport_mut().receive_session().await
    }

    /// Receives backend messages through middleware before demultiplexing.
    ///
    /// Asynchronous messages are intercepted and then recorded by the demux;
    /// this method continues until a protocol-advancing item is available.
    ///
    /// # Errors
    ///
    /// Returns an I/O, decoding, middleware-policy, or state-validation error.
    pub async fn receive_with_middleware<State, Handler, ProtocolState>(
        &mut self,
        middleware: &mut Middleware<State, Handler>,
        protocol_state: &ProtocolState,
    ) -> Result<SessionItem, ReceiveError<Handler::Error, BackendMessage>>
    where
        Handler: MessageMiddleware<BackendMessage, State>,
        ProtocolState: AcceptsMessage<BackendMessage>,
    {
        loop {
            let message = self
                .receive_backend_wire_with_middleware(middleware, protocol_state)
                .await?;
            if let Some(item) = self.project_backend(message) {
                return Ok(item);
            }
        }
    }

    #[must_use]
    /// Returns the latest upstream cancellation key observed during startup.
    pub fn cancel_key(&self) -> Option<&CancelKey> {
        self.transport().demux().cancel_key()
    }

    /// Returns the latest backend parameter values observed by the demux.
    #[must_use]
    pub fn parameters(&self) -> &BTreeMap<Bytes, Bytes> {
        self.transport().demux().parameters()
    }

    /// Returns whether current parameters differ from the startup baseline.
    #[must_use]
    pub fn parameters_changed(&self) -> bool {
        self.transport().demux().parameters_changed()
    }

    /// Returns the latest transaction status observed in `ReadyForQuery`.
    #[must_use]
    pub fn transaction_status(&self) -> Option<crate::codec::TransactionStatus> {
        self.transport().demux().transaction_status()
    }

    /// Removes the oldest queued asynchronous notification.
    pub fn pop_notification(&mut self) -> Option<Notification> {
        self.transport_mut().demux_mut().pop_notification()
    }

    /// Removes the next tagged notice for prompt forwarding to the client.
    pub fn pop_notice(&mut self) -> Option<TaggedNotice> {
        self.transport_mut().demux_mut().pop_notice()
    }

    /// Removes the next ordered parameter update for forwarding to the client.
    pub fn pop_parameter_status(&mut self) -> Option<ParameterStatus> {
        self.transport_mut().demux_mut().pop_parameter_status()
    }

    /// Removes the next independent backend event in original wire order.
    pub fn pop_async_event(&mut self) -> Option<OrderedAsyncEvent> {
        self.transport_mut().demux_mut().pop_async_event()
    }
}

impl<S: AsyncRead + Unpin, Phase, Cleanliness> Conn<Buffered<S, Frontend>, Phase, Cleanliness> {
    /// Receives one frontend message before any server-role state advancement.
    ///
    /// # Errors
    ///
    /// Returns decoding and underlying transport read errors, or `UnexpectedEof`.
    pub async fn receive_frontend_wire(&mut self) -> io::Result<FrontendMessage> {
        self.transport_mut().receive_wire().await
    }

    /// Receives one frontend message through middleware indexed by this connection phase.
    ///
    /// `Phase` selects the generated legal message set and the client sender role
    /// at compile time, so no runtime protocol-state argument is accepted.
    ///
    /// # Errors
    ///
    /// Returns an I/O or decoding error, an illegal peer message, a middleware
    /// policy error, or a phase-legal replacement with an invalid wire shape.
    pub async fn receive_frontend_typed<State, Handler>(
        &mut self,
        middleware: &mut Middleware<State, Handler>,
    ) -> Result<
        <Phase as TypedPhase<ClientRole, FrontendMessage>>::Message,
        TypedReceiveError<Handler::Error, FrontendMessage>,
    >
    where
        Phase: TypedPhase<ClientRole, FrontendMessage>,
        Handler: TypedMiddleware<
                ClientRole,
                <Phase as TypedPhase<ClientRole, FrontendMessage>>::ProtocolPhase,
                <Phase as TypedPhase<ClientRole, FrontendMessage>>::Message,
                State,
            >,
    {
        let message = self
            .receive_frontend_wire()
            .await
            .map_err(TypedReceiveError::Io)?;
        let message =
            <Phase as TypedPhase<ClientRole, FrontendMessage>>::Message::try_from(message)
                .map_err(TypedReceiveError::Illegal)?;
        let message = middleware
            .intercept_typed::<
                ClientRole,
                <Phase as TypedPhase<ClientRole, FrontendMessage>>::ProtocolPhase,
                _,
            >(message)
            .await
            .map_err(TypedReceiveError::Middleware)?;
        if message.as_ref().is_reconstructable() {
            Ok(message)
        } else {
            Err(TypedReceiveError::InvalidWire(message.into()))
        }
    }

    /// Receives, intercepts, and validates one frontend message before projection.
    ///
    /// # Errors
    ///
    /// Returns an I/O, decoding, middleware-policy, or state-validation error.
    pub async fn receive_frontend_wire_with_middleware<State, Handler, ProtocolState>(
        &mut self,
        middleware: &mut Middleware<State, Handler>,
        protocol_state: &ProtocolState,
    ) -> Result<FrontendMessage, ReceiveError<Handler::Error, FrontendMessage>>
    where
        Handler: MessageMiddleware<FrontendMessage, State>,
        ProtocolState: AcceptsMessage<FrontendMessage>,
    {
        let message = self
            .receive_frontend_wire()
            .await
            .map_err(ReceiveError::Io)?;
        middleware
            .intercept_checked(protocol_state, message)
            .await
            .map_err(ReceiveError::Intercept)
    }
}

impl<S: AsyncRead + Unpin, Cleanliness> Conn<Buffered<S, Frontend>, PreStartup, Cleanliness> {
    /// Receives a raw pre-startup packet before server-role state projection.
    ///
    /// # Errors
    ///
    /// Returns malformed pre-startup data and underlying transport read errors.
    pub async fn receive_pre_startup_wire(&mut self) -> io::Result<PreStartupMessage> {
        self.transport_mut().receive_pre_startup().await
    }

    /// Receives a client pre-startup packet through phase-typed middleware.
    ///
    /// # Errors
    ///
    /// Returns an I/O or decoding error, an illegal pre-startup packet, a
    /// middleware policy error, or an invalid replacement wire shape.
    pub async fn receive_pre_startup_typed<State, Handler>(
        &mut self,
        middleware: &mut Middleware<State, Handler>,
    ) -> Result<
        <PreStartup as TypedPhase<ClientRole, PreStartupMessage>>::Message,
        TypedReceiveError<Handler::Error, PreStartupMessage>,
    >
    where
        Handler: TypedMiddleware<
                ClientRole,
                <PreStartup as TypedPhase<ClientRole, PreStartupMessage>>::ProtocolPhase,
                <PreStartup as TypedPhase<ClientRole, PreStartupMessage>>::Message,
                State,
            >,
    {
        let message = self
            .receive_pre_startup_wire()
            .await
            .map_err(TypedReceiveError::Io)?;
        let message =
            <PreStartup as TypedPhase<ClientRole, PreStartupMessage>>::Message::try_from(message)
                .map_err(TypedReceiveError::Illegal)?;
        let message = middleware
            .intercept_typed::<
                ClientRole,
                <PreStartup as TypedPhase<ClientRole, PreStartupMessage>>::ProtocolPhase,
                _,
            >(message)
            .await
            .map_err(TypedReceiveError::Middleware)?;
        if message.as_ref().is_reconstructable() {
            Ok(message)
        } else {
            Err(TypedReceiveError::InvalidWire(message.into()))
        }
    }

    /// Receives, intercepts, and validates one untagged pre-startup message.
    ///
    /// # Errors
    ///
    /// Returns an I/O, decoding, middleware-policy, or state-validation error.
    pub async fn receive_pre_startup_wire_with_middleware<State, Handler, ProtocolState>(
        &mut self,
        middleware: &mut Middleware<State, Handler>,
        protocol_state: &ProtocolState,
    ) -> Result<PreStartupMessage, ReceiveError<Handler::Error, PreStartupMessage>>
    where
        Handler: MessageMiddleware<PreStartupMessage, State>,
        ProtocolState: AcceptsMessage<PreStartupMessage>,
    {
        let message = self
            .receive_pre_startup_wire()
            .await
            .map_err(ReceiveError::Io)?;
        middleware
            .intercept_checked(protocol_state, message)
            .await
            .map_err(ReceiveError::Intercept)
    }
}

#[cfg(test)]
mod tests {
    use std::{
        convert::Infallible,
        future::Future,
        pin::Pin,
        task::{Context, Poll},
    };

    use bytes::Bytes;
    use tokio::io::AsyncWrite;

    use super::*;
    use crate::{
        grammar::{backend, frontend, server_pre_startup},
        middleware::{InterceptError, Middleware, ReceiveError},
    };

    #[derive(Debug, Default)]
    struct ShortWriter {
        output: Vec<u8>,
    }

    impl AsyncWrite for ShortWriter {
        fn poll_write(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buffer: &[u8],
        ) -> Poll<io::Result<usize>> {
            let written = buffer.len().min(2);
            self.output.extend_from_slice(&buffer[..written]);
            Poll::Ready(Ok(written))
        }

        fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
            Poll::Ready(Ok(()))
        }

        fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
            Poll::Ready(Ok(()))
        }
    }

    #[tokio::test]
    async fn flush_handles_partial_writes_without_losing_bytes() {
        let frame = Frame {
            tag: b'S',
            body: Bytes::new(),
        };
        let mut transport = Buffered::new(ShortWriter::default());
        transport.push(frame).expect("encodable frame");
        assert_eq!(transport.pending(), &[b'S', 0, 0, 0, 4]);
        transport.flush().await.expect("writable transport");
        assert!(transport.pending().is_empty());
        assert_eq!(transport.into_inner().output, [b'S', 0, 0, 0, 4]);
    }

    #[test]
    fn buffered_transport_enforces_its_frame_limit_on_output() {
        let mut transport = Buffered::<_, Backend>::with_max_frame_len((), 9).unwrap();
        let error = transport
            .push(Frame {
                tag: b'Q',
                body: Bytes::from_static(b"12345"),
            })
            .unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
        assert!(transport.pending().is_empty());
    }

    #[test]
    fn cancelling_flush_retains_unwritten_bytes() {
        #[derive(Debug, Default)]
        struct PausingWriter {
            output: Vec<u8>,
            blocked: bool,
        }

        impl AsyncWrite for PausingWriter {
            fn poll_write(
                mut self: Pin<&mut Self>,
                _cx: &mut Context<'_>,
                buffer: &[u8],
            ) -> Poll<io::Result<usize>> {
                if self.blocked {
                    return Poll::Pending;
                }
                let written = buffer.len().min(2);
                self.output.extend_from_slice(&buffer[..written]);
                self.blocked = true;
                Poll::Ready(Ok(written))
            }

            fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
                Poll::Ready(Ok(()))
            }

            fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
                Poll::Ready(Ok(()))
            }
        }

        let mut transport = Buffered::new(PausingWriter::default());
        transport
            .push(Frame {
                tag: b'S',
                body: Bytes::new(),
            })
            .expect("encodable frame");

        let mut flush = Box::pin(transport.flush());
        let waker = std::task::Waker::noop();
        let mut context = Context::from_waker(waker);
        assert!(flush.as_mut().poll(&mut context).is_pending());
        drop(flush);

        assert_eq!(transport.pending(), &[0, 0, 4]);
        assert_eq!(transport.io.output, [b'S', 0]);
    }

    #[tokio::test]
    async fn receive_filters_parameter_status_before_session_message() {
        let (client, mut server) = tokio::io::duplex(256);
        let mut wire = BytesMut::new();
        let mut encoder = PgCodec::<Backend>::default();
        encoder
            .encode(
                Frame {
                    tag: b'S',
                    body: Bytes::from_static(b"client_encoding\0UTF8\0"),
                },
                &mut wire,
            )
            .expect("encodable ParameterStatus");
        encoder
            .encode(
                Frame {
                    tag: b'Z',
                    body: Bytes::from_static(b"I"),
                },
                &mut wire,
            )
            .expect("encodable ReadyForQuery");
        server.write_all(&wire).await.expect("writable test peer");

        let mut transport = Buffered::new(client);
        assert_eq!(
            transport.receive_session().await.expect("valid messages"),
            SessionItem::ReadyForQuery {
                status: crate::codec::TransactionStatus::Idle,
                parameters_changed: false,
            }
        );
        assert_eq!(
            transport
                .demux()
                .parameters()
                .get(&Bytes::from_static(b"client_encoding")),
            Some(&Bytes::from_static(b"UTF8"))
        );
        let conn: Conn<_, crate::auth::Ready> = Conn::new(transport).transition();
        assert_eq!(
            conn.parameters().get(b"client_encoding".as_slice()),
            Some(&Bytes::from_static(b"UTF8"))
        );
        assert!(!conn.parameters_changed());
        assert_eq!(
            conn.transaction_status(),
            Some(crate::codec::TransactionStatus::Idle)
        );
        conn.into_transport();
    }

    #[tokio::test]
    async fn wire_message_can_be_modified_before_projection() {
        let (client, mut server) = tokio::io::duplex(128);
        let original = BackendMessage::ParameterStatus {
            name: Bytes::from_static(b"application_name"),
            value: Bytes::from_static(b"upstream"),
        };
        let mut bytes = BytesMut::new();
        PgCodec::<Backend>::default()
            .encode(
                original.to_frame().expect("reconstructable message"),
                &mut bytes,
            )
            .expect("encodable message");
        server.write_all(&bytes).await.expect("writable test peer");

        let mut transport = Buffered::new(client);
        let mut message = transport
            .receive_backend()
            .await
            .expect("decodable message");
        let BackendMessage::ParameterStatus { value, .. } = &mut message else {
            panic!("unexpected message")
        };
        *value = Bytes::from_static(b"proxy");
        assert!(transport.project_backend(message).is_none());
        assert_eq!(
            transport
                .demux()
                .parameters()
                .get(&Bytes::from_static(b"application_name")),
            Some(&Bytes::from_static(b"proxy"))
        );
    }

    #[tokio::test]
    async fn typed_middleware_accepts_async_traffic_without_advancing_ready() {
        let (client, mut server) = tokio::io::duplex(128);
        let original = BackendMessage::ParameterStatus {
            name: Bytes::from_static(b"application_name"),
            value: Bytes::from_static(b"upstream"),
        };
        let mut bytes = BytesMut::new();
        PgCodec::<Backend>::default()
            .encode(
                original.to_frame().expect("reconstructable message"),
                &mut bytes,
            )
            .expect("encodable message");
        server.write_all(&bytes).await.expect("writable test peer");

        let transport = Buffered::new(client);
        let mut conn: Conn<_, crate::auth::Ready> = Conn::new(transport).transition();
        let mut middleware = Middleware::new(0_usize, async |seen: &mut usize, _message| {
            *seen += 1;
            let replacement = BackendMessage::ParameterStatus {
                name: Bytes::from_static(b"application_name"),
                value: Bytes::from_static(b"proxy"),
            };
            match crate::middleware::TypedBackendMessage::try_from(replacement) {
                Ok(replacement) => Ok::<_, Infallible>(replacement),
                Err(message) => panic!("parameter status must be asynchronous: {message:?}"),
            }
        });

        let message = conn
            .receive_backend_typed(&mut middleware)
            .await
            .expect("typed asynchronous message");
        assert!(conn.project_backend(message.into()).is_none());
        assert_eq!(*middleware.state(), 1);
        assert_eq!(
            conn.parameters().get(b"application_name".as_slice()),
            Some(&Bytes::from_static(b"proxy"))
        );
        conn.into_transport();
    }

    #[tokio::test]
    async fn typed_receive_projects_into_the_existing_next_connection_enum() {
        let (client, mut server) = tokio::io::duplex(128);
        let ready = BackendMessage::ReadyForQuery(crate::codec::TransactionStatus::Idle);
        let mut bytes = BytesMut::new();
        PgCodec::<Backend>::default()
            .encode(
                ready.to_frame().expect("reconstructable message"),
                &mut bytes,
            )
            .expect("encodable message");
        server.write_all(&bytes).await.expect("writable test peer");

        let transport = Buffered::new(client);
        let conn: Conn<_, crate::auth::Ready> = Conn::new(transport).transition();
        let (mut query, _) = conn
            .push_stateless_query(b"select 1")
            .expect("encodable query");
        let mut middleware = Middleware::new((), crate::middleware::Identity);
        let item = query
            .receive_typed(&mut middleware)
            .await
            .expect("phase-legal ready message");

        let transition = query.offer(item).expect("typed next-state projection");
        let crate::session::SimpleTransition::Ready(crate::session::ReadyState::Clean(ready)) =
            transition
        else {
            panic!("idle readiness must return a clean ready connection");
        };
        ready.into_transport();
    }

    #[tokio::test]
    async fn typed_receive_keeps_wire_shape_validation_at_runtime() {
        let (client, mut peer) = tokio::io::duplex(256);
        let query = FrontendMessage::Query(Bytes::from_static(b"select 1"));
        let mut bytes = BytesMut::new();
        PgCodec::<Frontend>::default()
            .encode(query.to_frame().expect("reconstructable query"), &mut bytes)
            .expect("encodable query");
        peer.write_all(&bytes).await.expect("writable test peer");

        let transport = Buffered::<_, Frontend>::new_frontend(client);
        let mut conn: Conn<_, crate::auth::Ready> = Conn::new(transport).transition();
        let invalid = FrontendMessage::Parse(crate::codec::Parse {
            statement: Bytes::from_static(b"invalid\0statement"),
            query: Bytes::from_static(b"select 2"),
            parameter_types: Vec::new(),
        });
        let mut middleware = Middleware::new((), async move |_state: &mut (), _message| {
            let invalid = invalid.clone();
            match backend::ReadyExternalMessage::try_from(invalid) {
                Ok(invalid) => Ok::<_, Infallible>(invalid),
                Err(message) => panic!("parse must be protocol-legal while ready: {message:?}"),
            }
        });

        let result = conn.receive_frontend_typed(&mut middleware).await;
        assert!(matches!(
            result,
            Err(TypedReceiveError::InvalidWire(FrontendMessage::Parse(_)))
        ));
        conn.into_transport();
    }

    #[tokio::test]
    async fn middleware_rewrites_backend_before_demux_bookkeeping() {
        let (client, mut server) = tokio::io::duplex(256);
        let mut wire = BytesMut::new();
        let mut encoder = PgCodec::<Backend>::default();
        for message in [
            BackendMessage::BackendKeyData {
                process_id: 7,
                secret_key: Bytes::from_static(b"old!"),
            },
            BackendMessage::ParameterStatus {
                name: Bytes::from_static(b"application_name"),
                value: Bytes::from_static(b"upstream"),
            },
            BackendMessage::ReadyForQuery(crate::codec::TransactionStatus::Idle),
        ] {
            encoder
                .encode(
                    message.to_frame().expect("reconstructable message"),
                    &mut wire,
                )
                .expect("encodable message");
        }
        server.write_all(&wire).await.expect("writable test peer");

        let transport = Buffered::new(client);
        let mut conn: Conn<_, crate::auth::Ready> = Conn::new(transport).transition();
        let mut middleware = Middleware::new(0_usize, async |seen: &mut usize, mut message| {
            *seen += 1;
            if let BackendMessage::ParameterStatus { value, .. } = &mut message {
                *value = Bytes::from_static(b"proxy");
            }
            if let BackendMessage::BackendKeyData {
                process_id,
                secret_key,
            } = &mut message
            {
                *process_id = 9;
                *secret_key = Bytes::from_static(b"new!");
            }
            if let BackendMessage::ReadyForQuery(status) = &mut message {
                *status = crate::codec::TransactionStatus::InTransaction;
            }
            Ok::<_, Infallible>(message)
        });

        assert!(matches!(
            conn.receive_with_middleware(&mut middleware, &frontend::RuntimeState::Simple)
                .await,
            Ok(SessionItem::Message(BackendMessage::BackendKeyData { .. }))
        ));
        assert!(matches!(
            conn.receive_with_middleware(&mut middleware, &frontend::RuntimeState::Simple)
                .await,
            Ok(SessionItem::ReadyForQuery { .. })
        ));
        assert_eq!(*middleware.state(), 3);
        assert_eq!(
            conn.parameters().get(b"application_name".as_slice()),
            Some(&Bytes::from_static(b"proxy"))
        );
        assert_eq!(
            conn.cancel_key(),
            Some(&CancelKey {
                process_id: 9,
                secret_key: Bytes::from_static(b"new!"),
            })
        );
        assert_eq!(
            conn.transaction_status(),
            Some(crate::codec::TransactionStatus::InTransaction)
        );
        conn.into_transport();
    }

    #[tokio::test]
    async fn frontend_middleware_returns_illegal_replacement_before_projection() {
        let (proxy, mut client) = tokio::io::duplex(128);
        let original = FrontendMessage::CopyData(Bytes::from_static(b"row"));
        let mut bytes = BytesMut::new();
        PgCodec::<Frontend>::default()
            .encode(
                original.to_frame().expect("reconstructable message"),
                &mut bytes,
            )
            .expect("encodable message");
        client.write_all(&bytes).await.expect("writable client");

        let mut conn = Conn::new(Buffered::<_, Frontend>::new_frontend(proxy));
        let mut middleware = Middleware::new((), async |_state: &mut (), _message| {
            Ok::<_, Infallible>(FrontendMessage::Query(Bytes::from_static(b"select 1")))
        });
        let result = conn
            .receive_frontend_wire_with_middleware(
                &mut middleware,
                &backend::RuntimeState::SimpleCopyIn,
            )
            .await;

        assert!(matches!(
            result,
            Err(ReceiveError::Intercept(InterceptError::Invalid(
                FrontendMessage::Query(_)
            )))
        ));
        conn.into_transport();
    }

    #[tokio::test]
    async fn middleware_replacement_reaches_the_forwarded_peer() {
        let (client_side, mut client) = tokio::io::duplex(128);
        let original = FrontendMessage::Query(Bytes::from_static(b"select plaintext"));
        let mut bytes = BytesMut::new();
        PgCodec::<Frontend>::default()
            .encode(
                original.to_frame().expect("reconstructable message"),
                &mut bytes,
            )
            .expect("encodable message");
        client.write_all(&bytes).await.expect("writable client");

        let mut downstream = Conn::new(Buffered::<_, Frontend>::new_frontend(client_side));
        let mut middleware = Middleware::new((), async |_state: &mut (), _message| {
            Ok::<_, Infallible>(FrontendMessage::Query(Bytes::from_static(
                b"select encrypted",
            )))
        });
        let rewritten = downstream
            .receive_frontend_wire_with_middleware(&mut middleware, &backend::RuntimeState::Ready)
            .await
            .expect("legal rewritten query");

        let (upstream_side, mut server) = tokio::io::duplex(128);
        let mut upstream = Buffered::<_, Backend>::new(upstream_side);
        upstream
            .push(rewritten.to_frame().expect("reconstructable replacement"))
            .expect("encodable replacement");
        upstream.flush().await.expect("writable upstream");

        let mut received = BytesMut::new();
        server
            .read_buf(&mut received)
            .await
            .expect("readable upstream peer");
        assert_eq!(
            PgCodec::<Frontend>::default()
                .decode(&mut received)
                .expect("decodable frame"),
            Some(FrontendMessage::Query(Bytes::from_static(
                b"select encrypted"
            )))
        );
        downstream.into_transport();
    }

    #[tokio::test]
    async fn pre_startup_middleware_can_replace_with_another_legal_choice() {
        let (proxy, mut client) = tokio::io::duplex(128);
        client
            .write_all(
                &PreStartupMessage::SslRequest
                    .to_packet()
                    .expect("encodable SSLRequest"),
            )
            .await
            .expect("writable client");

        let mut conn = Conn::new(Buffered::<_, Frontend>::new_frontend(proxy));
        let replacement = PreStartupMessage::CancelRequest {
            process_id: 42,
            secret_key: Bytes::from_static(b"key!"),
        };
        let expected = replacement.clone();
        let mut middleware = Middleware::new((), async move |_state: &mut (), _message| {
            Ok::<_, Infallible>(replacement.clone())
        });

        assert_eq!(
            conn.receive_pre_startup_wire_with_middleware(
                &mut middleware,
                &server_pre_startup::RuntimeState::PreStartup,
            )
            .await
            .expect("legal replacement"),
            expected
        );
        conn.into_transport();
    }

    #[tokio::test]
    async fn client_facing_transport_intercepts_typed_frontend_messages() {
        let (proxy, mut client) = tokio::io::duplex(128);
        let message = FrontendMessage::Query(Bytes::from_static(b"select plaintext"));
        let mut bytes = BytesMut::new();
        PgCodec::<Frontend>::default()
            .encode(
                message.to_frame().expect("reconstructable Query"),
                &mut bytes,
            )
            .expect("encodable Query");
        client.write_all(&bytes).await.expect("writable client");

        let mut transport = Buffered::<_, Frontend>::new_frontend(proxy);
        let mut intercepted = transport.receive_wire().await.expect("decodable Query");
        let FrontendMessage::Query(query) = &mut intercepted else {
            panic!("unexpected frontend message")
        };
        *query = Bytes::from_static(b"select encrypted");
        assert_eq!(
            intercepted,
            FrontendMessage::Query(Bytes::from_static(b"select encrypted"))
        );
    }

    #[tokio::test]
    async fn client_facing_transport_projects_repeated_pre_startup_choice() {
        let (proxy, mut client) = tokio::io::duplex(256);
        let ssl = PreStartupMessage::SslRequest
            .to_packet()
            .expect("encodable SSLRequest");
        let startup = PreStartupMessage::Startup(crate::startup::StartupMessage {
            version: crate::startup::ProtocolVersion::V3_2,
            parameters: std::collections::BTreeMap::from([(
                Bytes::from_static(b"user"),
                Bytes::from_static(b"postgres"),
            )]),
        });
        let startup_packet = startup.to_packet().expect("encodable StartupMessage");
        client.write_all(&ssl).await.expect("writable client");
        client
            .write_all(&startup_packet)
            .await
            .expect("writable client");

        let mut conn = Conn::new(Buffered::<_, Frontend>::new_frontend(proxy));
        let ssl = conn
            .receive_pre_startup_wire()
            .await
            .expect("decodable SSLRequest");
        let crate::pre_startup::PreStartupOffer::Ssl(decision) = conn.offer_pre_startup(ssl) else {
            panic!("unexpected pre-startup branch")
        };
        let (mut conn, reply) = decision.reject_ssl();
        assert_eq!(reply, b'N');
        let message = conn
            .receive_pre_startup_wire()
            .await
            .expect("decodable StartupMessage");
        assert_eq!(message, startup);
        let crate::pre_startup::PreStartupOffer::Startup { conn, .. } =
            conn.offer_pre_startup(message)
        else {
            panic!("unexpected pre-startup branch")
        };
        let _transport = conn.into_transport();
    }

    #[tokio::test]
    async fn client_facing_transport_applies_its_pre_startup_limit() {
        let (proxy, mut client) = tokio::io::duplex(32);
        client
            .write_all(&17_u32.to_be_bytes())
            .await
            .expect("writable client");

        let mut transport =
            Buffered::<_, Frontend>::with_limits_frontend(proxy, 64, 16).expect("valid limits");
        let error = transport
            .receive_pre_startup()
            .await
            .expect_err("declared packet exceeds the configured limit");

        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
    }

    #[tokio::test]
    async fn upstream_transport_negotiates_raw_gssenc_reply() {
        let (proxy, mut server) = tokio::io::duplex(32);
        let mut pending = Conn::new(Buffered::new(proxy)).request_gss();
        pending.flush().await.expect("GSSENCRequest is writable");

        let mut request = [0_u8; 8];
        server
            .read_exact(&mut request)
            .await
            .expect("server receives GSSENCRequest");
        assert_eq!(request, gssenc_request_packet());
        server
            .write_all(b"N")
            .await
            .expect("server writes decision");

        let Negotiation::Rejected(plaintext) = pending
            .receive_gss_reply()
            .await
            .expect("valid GSSENC decision")
        else {
            panic!("expected plaintext fallback")
        };
        plaintext.into_transport();
    }

    #[test]
    fn client_facing_transport_buffers_raw_gssenc_decision() {
        let conn = Conn::new(Buffered::<_, Frontend>::new_frontend(()));
        let crate::pre_startup::PreStartupOffer::Gss(decision) =
            conn.offer_pre_startup(PreStartupMessage::GssEncRequest)
        else {
            panic!("expected GSSENC decision")
        };

        let handshake = decision.approve_gss();
        assert_eq!(handshake.pending_output(), b"S");
        handshake.into_transport();

        let conn = Conn::new(Buffered::<_, Frontend>::new_frontend(()));
        let crate::pre_startup::PreStartupOffer::Gss(decision) =
            conn.offer_pre_startup(PreStartupMessage::GssEncRequest)
        else {
            panic!("expected GSSENC decision")
        };
        let terminated = decision.reject_gss_with_legacy_error();
        assert_eq!(terminated.pending_output(), b"E");
        terminated.into_transport();
    }

    #[test]
    fn client_facing_transport_buffers_legacy_ssl_error() {
        let conn = Conn::new(Buffered::<_, Frontend>::new_frontend(()));
        let crate::pre_startup::PreStartupOffer::Ssl(decision) =
            conn.offer_pre_startup(PreStartupMessage::SslRequest)
        else {
            panic!("expected SSL decision")
        };

        let terminated = decision.reject_ssl_with_legacy_error();
        assert_eq!(terminated.pending_output(), b"E");
        terminated.into_transport();
    }
}