qail-pg 0.27.2

Fastest async PostgreSQL driver - AST to wire protocol, optional io_uring on Linux
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
//! Core I/O operations for PostgreSQL connection.
//!
//! This module provides low-level send/receive methods.

use super::{PgConnection, PgError, PgResult, is_ignorable_session_message};
use crate::protocol::{BackendMessage, FrontendMessage, PgEncoder};
use bytes::BytesMut;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

pub(crate) const MAX_MESSAGE_SIZE: usize = 64 * 1024 * 1024; // 64 MB — prevents OOM from malicious server messages

/// Default read timeout for individual socket reads.
/// Prevents Slowloris DoS where a server sends partial data then goes silent.
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
/// Default write timeout for individual socket writes/flushes.
/// Prevents indefinitely blocked writes from pinning pool slots.
const DEFAULT_WRITE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

#[inline]
fn parse_data_row_payload_owned(payload: &[u8]) -> PgResult<Vec<Option<Vec<u8>>>> {
    if payload.len() < 2 {
        return Err(PgError::Protocol("DataRow payload too short".into()));
    }

    let raw_count = i16::from_be_bytes([payload[0], payload[1]]);
    if raw_count < 0 {
        return Err(PgError::Protocol(format!(
            "DataRow invalid column count: {}",
            raw_count
        )));
    }
    let column_count = raw_count as usize;
    if column_count > (payload.len() - 2) / 4 + 1 {
        return Err(PgError::Protocol(format!(
            "DataRow claims {} columns but payload is only {} bytes",
            column_count,
            payload.len()
        )));
    }

    let mut columns = Vec::with_capacity(column_count);
    let mut pos = 2;
    for _ in 0..column_count {
        if pos + 4 > payload.len() {
            return Err(PgError::Protocol(
                "DataRow truncated: missing column length".into(),
            ));
        }

        let len = i32::from_be_bytes([
            payload[pos],
            payload[pos + 1],
            payload[pos + 2],
            payload[pos + 3],
        ]);
        pos += 4;

        if len == -1 {
            columns.push(None);
            continue;
        }
        if len < -1 {
            return Err(PgError::Protocol(format!(
                "DataRow invalid column length: {}",
                len
            )));
        }

        let len = len as usize;
        if len > payload.len().saturating_sub(pos) {
            return Err(PgError::Protocol(
                "DataRow truncated: column data exceeds payload".into(),
            ));
        }
        columns.push(Some(payload[pos..pos + len].to_vec()));
        pos += len;
    }

    if pos != payload.len() {
        return Err(PgError::Protocol("DataRow has trailing bytes".into()));
    }

    Ok(columns)
}

impl PgConnection {
    #[inline]
    pub(crate) fn mark_io_desynced(&mut self) {
        self.io_desynced = true;
    }

    #[inline]
    pub(crate) fn is_io_desynced(&self) -> bool {
        self.io_desynced
    }

    #[inline]
    fn protocol_desync<T>(&mut self, msg: String) -> PgResult<T> {
        self.mark_io_desynced();
        Err(PgError::Protocol(msg))
    }

    #[inline]
    fn connection_desync<T>(&mut self, msg: String) -> PgResult<T> {
        self.mark_io_desynced();
        Err(PgError::Connection(msg))
    }

    /// Send queued statement `Close` messages and drain until `ReadyForQuery`.
    ///
    /// We ignore `26000 prepared statement ... does not exist` because this
    /// can happen after failover or server-side invalidation, and in that case
    /// local state is already being reconciled by retry paths.
    async fn flush_pending_statement_closes(&mut self) -> PgResult<()> {
        if self.draining_statement_closes || self.pending_statement_closes.is_empty() {
            return Ok(());
        }

        self.draining_statement_closes = true;
        let close_names = std::mem::take(&mut self.pending_statement_closes);

        let estimated_payload_len: usize = close_names
            .iter()
            .map(|name| 16usize.saturating_add(name.len()))
            .sum();
        let mut buf = BytesMut::with_capacity(estimated_payload_len.saturating_add(5));
        for stmt_name in &close_names {
            let close_msg = PgEncoder::try_encode_close(false, stmt_name)
                .map_err(|e| PgError::Encode(e.to_string()))?;
            buf.extend_from_slice(&close_msg);
        }
        PgEncoder::encode_sync_to(&mut buf);

        if let Err(err) = self
            .write_all_with_timeout_inner(&buf, "pending statement close write")
            .await
        {
            self.draining_statement_closes = false;
            return Err(err);
        }
        if let Err(err) = self
            .flush_with_timeout("pending statement close flush")
            .await
        {
            self.draining_statement_closes = false;
            return Err(err);
        }

        let mut error: Option<PgError> = None;
        loop {
            let msg = match self.recv().await {
                Ok(msg) => msg,
                Err(err) => {
                    self.draining_statement_closes = false;
                    return Err(err);
                }
            };
            match msg {
                BackendMessage::CloseComplete => {}
                BackendMessage::ReadyForQuery(_) => {
                    self.draining_statement_closes = false;
                    if let Some(err) = error {
                        return Err(err);
                    }
                    return Ok(());
                }
                BackendMessage::ErrorResponse(err_fields) => {
                    if error.is_none() {
                        let code_26000 = err_fields.code.eq_ignore_ascii_case("26000");
                        let msg_lower = err_fields.message.to_ascii_lowercase();
                        let missing_prepared = msg_lower.contains("prepared statement")
                            && msg_lower.contains("does not exist");
                        if !(code_26000 && missing_prepared) {
                            error = Some(PgError::QueryServer(err_fields.into()));
                        }
                    }
                }
                msg if is_ignorable_session_message(&msg) => {}
                other => {
                    self.draining_statement_closes = false;
                    return self.protocol_desync(format!(
                        "Unexpected backend message during pending statement close drain: {:?}",
                        other
                    ));
                }
            }
        }
    }

    /// Write all bytes with a timeout guard.
    ///
    /// Prevents stuck kernel send buffers or dead sockets from hanging forever.
    pub(crate) async fn write_all_with_timeout(
        &mut self,
        bytes: &[u8],
        operation: &str,
    ) -> PgResult<()> {
        if !self.draining_statement_closes && !self.pending_statement_closes.is_empty() {
            self.flush_pending_statement_closes().await?;
        }
        self.write_all_with_timeout_inner(bytes, operation).await
    }

    async fn write_all_with_timeout_inner(
        &mut self,
        bytes: &[u8],
        operation: &str,
    ) -> PgResult<()> {
        if bytes.is_empty() {
            return Err(PgError::Encode(
                "refusing to send empty frontend payload".to_string(),
            ));
        }
        use super::stream::PgStream;
        let mut mark_desync = false;
        let result = match &mut self.stream {
            PgStream::Tcp(stream) => {
                match tokio::time::timeout(DEFAULT_WRITE_TIMEOUT, stream.write_all(bytes)).await {
                    Ok(Ok(())) => Ok(()),
                    Ok(Err(e)) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!("Write error: {}", e)))
                    }
                    Err(_) => {
                        mark_desync = true;
                        Err(PgError::Timeout(format!(
                            "{} timeout after {:?}",
                            operation, DEFAULT_WRITE_TIMEOUT
                        )))
                    }
                }
            }
            PgStream::Tls(stream) => {
                match tokio::time::timeout(DEFAULT_WRITE_TIMEOUT, stream.write_all(bytes)).await {
                    Ok(Ok(())) => Ok(()),
                    Ok(Err(e)) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!("Write error: {}", e)))
                    }
                    Err(_) => {
                        mark_desync = true;
                        Err(PgError::Timeout(format!(
                            "{} timeout after {:?}",
                            operation, DEFAULT_WRITE_TIMEOUT
                        )))
                    }
                }
            }
            #[cfg(all(target_os = "linux", feature = "io_uring"))]
            PgStream::Uring(stream) => {
                match tokio::time::timeout(DEFAULT_WRITE_TIMEOUT, stream.write_all(bytes)).await {
                    Ok(Ok(())) => Ok(()),
                    Ok(Err(e)) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!("Write error: {}", e)))
                    }
                    Err(_) => {
                        mark_desync = true;
                        let _ = stream.abort_inflight();
                        Err(PgError::Timeout(format!(
                            "{} timeout after {:?}",
                            operation, DEFAULT_WRITE_TIMEOUT
                        )))
                    }
                }
            }
            #[cfg(unix)]
            PgStream::Unix(stream) => {
                match tokio::time::timeout(DEFAULT_WRITE_TIMEOUT, stream.write_all(bytes)).await {
                    Ok(Ok(())) => Ok(()),
                    Ok(Err(e)) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!("Write error: {}", e)))
                    }
                    Err(_) => {
                        mark_desync = true;
                        Err(PgError::Timeout(format!(
                            "{} timeout after {:?}",
                            operation, DEFAULT_WRITE_TIMEOUT
                        )))
                    }
                }
            }
            #[cfg(all(feature = "enterprise-gssapi", target_os = "linux"))]
            PgStream::GssEnc(stream) => {
                match tokio::time::timeout(DEFAULT_WRITE_TIMEOUT, stream.write_all(bytes)).await {
                    Ok(Ok(())) => Ok(()),
                    Ok(Err(e)) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!("Write error: {}", e)))
                    }
                    Err(_) => {
                        mark_desync = true;
                        Err(PgError::Timeout(format!(
                            "{} timeout after {:?}",
                            operation, DEFAULT_WRITE_TIMEOUT
                        )))
                    }
                }
            }
        };
        if mark_desync {
            self.mark_io_desynced();
        }
        result
    }

    /// Flush with a timeout guard.
    pub(crate) async fn flush_with_timeout(&mut self, operation: &str) -> PgResult<()> {
        use super::stream::PgStream;
        let mut mark_desync = false;
        let result = match &mut self.stream {
            PgStream::Tcp(stream) => {
                match tokio::time::timeout(DEFAULT_WRITE_TIMEOUT, stream.flush()).await {
                    Ok(Ok(())) => Ok(()),
                    Ok(Err(e)) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!("Flush error: {}", e)))
                    }
                    Err(_) => {
                        mark_desync = true;
                        Err(PgError::Timeout(format!(
                            "{} timeout after {:?}",
                            operation, DEFAULT_WRITE_TIMEOUT
                        )))
                    }
                }
            }
            PgStream::Tls(stream) => {
                match tokio::time::timeout(DEFAULT_WRITE_TIMEOUT, stream.flush()).await {
                    Ok(Ok(())) => Ok(()),
                    Ok(Err(e)) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!("Flush error: {}", e)))
                    }
                    Err(_) => {
                        mark_desync = true;
                        Err(PgError::Timeout(format!(
                            "{} timeout after {:?}",
                            operation, DEFAULT_WRITE_TIMEOUT
                        )))
                    }
                }
            }
            #[cfg(all(target_os = "linux", feature = "io_uring"))]
            PgStream::Uring(stream) => {
                match tokio::time::timeout(DEFAULT_WRITE_TIMEOUT, stream.flush()).await {
                    Ok(Ok(())) => Ok(()),
                    Ok(Err(e)) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!("Flush error: {}", e)))
                    }
                    Err(_) => {
                        mark_desync = true;
                        let _ = stream.abort_inflight();
                        Err(PgError::Timeout(format!(
                            "{} timeout after {:?}",
                            operation, DEFAULT_WRITE_TIMEOUT
                        )))
                    }
                }
            }
            #[cfg(unix)]
            PgStream::Unix(stream) => {
                match tokio::time::timeout(DEFAULT_WRITE_TIMEOUT, stream.flush()).await {
                    Ok(Ok(())) => Ok(()),
                    Ok(Err(e)) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!("Flush error: {}", e)))
                    }
                    Err(_) => {
                        mark_desync = true;
                        Err(PgError::Timeout(format!(
                            "{} timeout after {:?}",
                            operation, DEFAULT_WRITE_TIMEOUT
                        )))
                    }
                }
            }
            #[cfg(all(feature = "enterprise-gssapi", target_os = "linux"))]
            PgStream::GssEnc(stream) => {
                match tokio::time::timeout(DEFAULT_WRITE_TIMEOUT, stream.flush()).await {
                    Ok(Ok(())) => Ok(()),
                    Ok(Err(e)) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!("Flush error: {}", e)))
                    }
                    Err(_) => {
                        mark_desync = true;
                        Err(PgError::Timeout(format!(
                            "{} timeout after {:?}",
                            operation, DEFAULT_WRITE_TIMEOUT
                        )))
                    }
                }
            }
        };
        if mark_desync {
            self.mark_io_desynced();
        }
        result
    }

    /// Send a frontend message.
    pub async fn send(&mut self, msg: FrontendMessage) -> PgResult<()> {
        let bytes = msg
            .encode_checked()
            .map_err(|e| PgError::Encode(e.to_string()))?;
        self.write_all_with_timeout(&bytes, "send frontend message")
            .await?;
        Ok(())
    }

    /// Loops until a complete message is available.
    /// Automatically buffers NotificationResponse messages for LISTEN/NOTIFY.
    pub async fn recv(&mut self) -> PgResult<BackendMessage> {
        loop {
            // Try to decode from buffer first
            if self.buffer.len() >= 5 {
                let msg_len = u32::from_be_bytes([
                    self.buffer[1],
                    self.buffer[2],
                    self.buffer[3],
                    self.buffer[4],
                ]) as usize;

                if msg_len < 4 {
                    return self.protocol_desync(format!(
                        "Invalid message length: {} (minimum 4)",
                        msg_len
                    ));
                }

                if msg_len > MAX_MESSAGE_SIZE {
                    return self.protocol_desync(format!(
                        "Message too large: {} bytes (max {})",
                        msg_len, MAX_MESSAGE_SIZE
                    ));
                }

                if self.buffer.len() > msg_len {
                    // We have a complete message - zero-copy split
                    let msg_bytes = self.buffer.split_to(msg_len + 1);
                    let (msg, _) = match BackendMessage::decode(&msg_bytes) {
                        Ok(decoded) => decoded,
                        Err(e) => return self.protocol_desync(e),
                    };

                    // Intercept async notifications — buffer them instead of returning
                    if let BackendMessage::NotificationResponse {
                        process_id,
                        channel,
                        payload,
                    } = msg
                    {
                        self.notifications
                            .push_back(super::notification::Notification {
                                process_id,
                                channel,
                                payload,
                            });
                        continue; // Keep reading for the actual response
                    }

                    return Ok(msg);
                }
            }

            let n = self.read_with_timeout().await?;
            if n == 0 {
                return self.connection_desync("Connection closed".to_string());
            }
        }
    }

    /// Receive a backend message with idle-friendly timeout behavior.
    ///
    /// For long-lived idle streams (e.g. logical replication), an empty
    /// buffer uses no-timeout reads so inactivity does not fail the stream.
    /// If a backend frame is already partially buffered, switch back to the
    /// normal read timeout to fail-closed on partial-frame stalls.
    pub(crate) async fn recv_without_timeout(&mut self) -> PgResult<BackendMessage> {
        loop {
            if self.buffer.len() >= 5 {
                let msg_len = u32::from_be_bytes([
                    self.buffer[1],
                    self.buffer[2],
                    self.buffer[3],
                    self.buffer[4],
                ]) as usize;

                if msg_len < 4 {
                    return self.protocol_desync(format!(
                        "Invalid message length: {} (minimum 4)",
                        msg_len
                    ));
                }

                if msg_len > MAX_MESSAGE_SIZE {
                    return self.protocol_desync(format!(
                        "Message too large: {} bytes (max {})",
                        msg_len, MAX_MESSAGE_SIZE
                    ));
                }

                if self.buffer.len() > msg_len {
                    let msg_bytes = self.buffer.split_to(msg_len + 1);
                    let (msg, _) = match BackendMessage::decode(&msg_bytes) {
                        Ok(decoded) => decoded,
                        Err(e) => return self.protocol_desync(e),
                    };

                    if let BackendMessage::NotificationResponse {
                        process_id,
                        channel,
                        payload,
                    } = msg
                    {
                        self.notifications
                            .push_back(super::notification::Notification {
                                process_id,
                                channel,
                                payload,
                            });
                        continue;
                    }

                    return Ok(msg);
                }
            }

            let n = if self.buffer.is_empty() {
                self.read_without_timeout().await?
            } else {
                self.read_with_timeout().await?
            };
            if n == 0 {
                return self.connection_desync("Connection closed".to_string());
            }
        }
    }

    /// Read from the socket with a timeout guard.
    /// Returns the number of bytes read, or an error if the timeout fires.
    /// This prevents Slowloris DoS attacks where a malicious server sends
    /// partial data then goes silent, causing the driver to hang forever.
    #[inline]
    pub(crate) async fn read_with_timeout(&mut self) -> PgResult<usize> {
        if self.buffer.capacity() - self.buffer.len() < 65536 {
            self.buffer.reserve(131072);
        }

        use super::stream::PgStream;
        let (stream, buffer) = (&mut self.stream, &mut self.buffer);
        let mut mark_desync = false;
        let result = match stream {
            PgStream::Tcp(stream) => {
                match tokio::time::timeout(DEFAULT_READ_TIMEOUT, stream.read_buf(buffer)).await {
                    Ok(Ok(n)) => Ok(n),
                    Ok(Err(e)) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!("Read error: {}", e)))
                    }
                    Err(_) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!(
                            "Read timeout after {:?} — possible Slowloris attack or dead connection",
                            DEFAULT_READ_TIMEOUT
                        )))
                    }
                }
            }
            PgStream::Tls(stream) => {
                match tokio::time::timeout(DEFAULT_READ_TIMEOUT, stream.read_buf(buffer)).await {
                    Ok(Ok(n)) => Ok(n),
                    Ok(Err(e)) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!("Read error: {}", e)))
                    }
                    Err(_) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!(
                            "Read timeout after {:?} — possible Slowloris attack or dead connection",
                            DEFAULT_READ_TIMEOUT
                        )))
                    }
                }
            }
            #[cfg(all(target_os = "linux", feature = "io_uring"))]
            PgStream::Uring(stream) => {
                match tokio::time::timeout(DEFAULT_READ_TIMEOUT, stream.read_into(buffer, 131072))
                    .await
                {
                    Ok(Ok(n)) => Ok(n),
                    Ok(Err(e)) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!("Read error: {}", e)))
                    }
                    Err(_) => {
                        mark_desync = true;
                        let _ = stream.abort_inflight();
                        Err(PgError::Connection(format!(
                            "Read timeout after {:?} — possible Slowloris attack or dead connection",
                            DEFAULT_READ_TIMEOUT
                        )))
                    }
                }
            }
            #[cfg(unix)]
            PgStream::Unix(stream) => {
                match tokio::time::timeout(DEFAULT_READ_TIMEOUT, stream.read_buf(buffer)).await {
                    Ok(Ok(n)) => Ok(n),
                    Ok(Err(e)) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!("Read error: {}", e)))
                    }
                    Err(_) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!(
                            "Read timeout after {:?} — possible Slowloris attack or dead connection",
                            DEFAULT_READ_TIMEOUT
                        )))
                    }
                }
            }
            #[cfg(all(feature = "enterprise-gssapi", target_os = "linux"))]
            PgStream::GssEnc(stream) => {
                match tokio::time::timeout(DEFAULT_READ_TIMEOUT, stream.read_buf(buffer)).await {
                    Ok(Ok(n)) => Ok(n),
                    Ok(Err(e)) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!("Read error: {}", e)))
                    }
                    Err(_) => {
                        mark_desync = true;
                        Err(PgError::Connection(format!(
                            "Read timeout after {:?} — possible Slowloris attack or dead connection",
                            DEFAULT_READ_TIMEOUT
                        )))
                    }
                }
            }
        };
        if mark_desync {
            self.mark_io_desynced();
        }
        result
    }

    /// Read from socket without timeout guard.
    ///
    /// Used for long-idle LISTEN/NOTIFY connections.
    pub(crate) async fn read_without_timeout(&mut self) -> PgResult<usize> {
        if self.buffer.capacity() - self.buffer.len() < 65536 {
            self.buffer.reserve(131072);
        }

        use super::stream::PgStream;
        let (stream, buffer) = (&mut self.stream, &mut self.buffer);
        let read_result = match stream {
            PgStream::Tcp(stream) => stream.read_buf(buffer).await,
            PgStream::Tls(stream) => stream.read_buf(buffer).await,
            #[cfg(all(target_os = "linux", feature = "io_uring"))]
            PgStream::Uring(stream) => stream.read_into(buffer, 131072).await,
            #[cfg(unix)]
            PgStream::Unix(stream) => stream.read_buf(buffer).await,
            #[cfg(all(feature = "enterprise-gssapi", target_os = "linux"))]
            PgStream::GssEnc(stream) => stream.read_buf(buffer).await,
        };

        match read_result {
            Ok(n) => Ok(n),
            Err(e) => {
                self.mark_io_desynced();
                Err(PgError::Connection(format!("Read error: {}", e)))
            }
        }
    }

    /// Send raw bytes to the stream.
    /// Includes flush for TLS safety — TLS buffers internally and
    /// needs flush to push encrypted data to the underlying TCP socket.
    pub async fn send_bytes(&mut self, bytes: &[u8]) -> PgResult<()> {
        self.write_all_with_timeout(bytes, "send raw bytes").await?;
        self.flush_with_timeout("flush raw bytes").await?;
        Ok(())
    }

    // ==================== BUFFERED WRITE API (High Performance) ====================

    /// Buffer bytes for later flush (NO SYSCALL).
    /// Use flush_write_buf() to send all buffered data.
    #[inline]
    pub fn buffer_bytes(&mut self, bytes: &[u8]) {
        self.write_buf.extend_from_slice(bytes);
    }

    /// Flush the write buffer to the stream (single write_all + flush).
    /// The flush is critical for TLS connections.
    pub async fn flush_write_buf(&mut self) -> PgResult<()> {
        if !self.write_buf.is_empty() {
            let payload = std::mem::take(&mut self.write_buf);
            self.write_all_with_timeout(&payload, "flush write buffer")
                .await?;
            self.flush_with_timeout("flush write buffer").await?;
        }
        Ok(())
    }

    /// FAST receive - returns only message type byte, skips parsing.
    /// This is ~10x faster than recv() for pipelining benchmarks.
    /// Returns: message_type
    #[inline]
    pub(crate) async fn recv_msg_type_fast(&mut self) -> PgResult<u8> {
        loop {
            if self.buffer.len() >= 5 {
                let msg_len = u32::from_be_bytes([
                    self.buffer[1],
                    self.buffer[2],
                    self.buffer[3],
                    self.buffer[4],
                ]) as usize;

                if msg_len < 4 {
                    return self.protocol_desync(format!(
                        "Invalid message length: {} (minimum 4)",
                        msg_len
                    ));
                }

                if msg_len > MAX_MESSAGE_SIZE {
                    return self.protocol_desync(format!(
                        "Message too large: {} bytes (max {})",
                        msg_len, MAX_MESSAGE_SIZE
                    ));
                }

                if self.buffer.len() > msg_len {
                    let msg_type = self.buffer[0];

                    if msg_type == b'E' || msg_type == b'A' {
                        let msg_bytes = self.buffer.split_to(msg_len + 1);
                        let (msg, _) = match BackendMessage::decode(&msg_bytes) {
                            Ok(decoded) => decoded,
                            Err(e) => return self.protocol_desync(e),
                        };
                        match msg {
                            BackendMessage::ErrorResponse(err) => {
                                return Err(PgError::QueryServer(err.into()));
                            }
                            BackendMessage::NotificationResponse {
                                process_id,
                                channel,
                                payload,
                            } => {
                                self.notifications
                                    .push_back(super::notification::Notification {
                                        process_id,
                                        channel,
                                        payload,
                                    });
                                continue;
                            }
                            _ => {
                                return Err(PgError::Protocol(
                                    "Unexpected fast-path message".into(),
                                ));
                            }
                        }
                    }

                    let _ = self.buffer.split_to(msg_len + 1);
                    return Ok(msg_type);
                }
            }

            let n = self.read_with_timeout().await?;
            if n == 0 {
                return self.connection_desync("Connection closed".to_string());
            }
        }
    }

    /// FAST receive for result consumption - inline DataRow parsing.
    /// Returns: (msg_type, Option<row_data>)
    /// For 'D' (DataRow): returns parsed columns
    /// For other types: returns None
    /// This avoids BackendMessage enum allocation for non-DataRow messages.
    #[inline]
    pub(crate) async fn recv_with_data_fast(
        &mut self,
    ) -> PgResult<(u8, Option<Vec<Option<Vec<u8>>>>)> {
        loop {
            if self.buffer.len() >= 5 {
                let msg_len = u32::from_be_bytes([
                    self.buffer[1],
                    self.buffer[2],
                    self.buffer[3],
                    self.buffer[4],
                ]) as usize;

                if msg_len < 4 {
                    return self.protocol_desync(format!(
                        "Invalid message length: {} (minimum 4)",
                        msg_len
                    ));
                }

                if msg_len > MAX_MESSAGE_SIZE {
                    return self.protocol_desync(format!(
                        "Message too large: {} bytes (max {})",
                        msg_len, MAX_MESSAGE_SIZE
                    ));
                }

                if self.buffer.len() > msg_len {
                    let msg_type = self.buffer[0];

                    if msg_type == b'E' || msg_type == b'A' {
                        let msg_bytes = self.buffer.split_to(msg_len + 1);
                        let (msg, _) = match BackendMessage::decode(&msg_bytes) {
                            Ok(decoded) => decoded,
                            Err(e) => return self.protocol_desync(e),
                        };
                        match msg {
                            BackendMessage::ErrorResponse(err) => {
                                return Err(PgError::QueryServer(err.into()));
                            }
                            BackendMessage::NotificationResponse {
                                process_id,
                                channel,
                                payload,
                            } => {
                                self.notifications
                                    .push_back(super::notification::Notification {
                                        process_id,
                                        channel,
                                        payload,
                                    });
                                continue;
                            }
                            _ => {
                                return Err(PgError::Protocol(
                                    "Unexpected fast-path message".into(),
                                ));
                            }
                        }
                    }

                    // Fast path: DataRow - parse inline
                    if msg_type == b'D' {
                        let parse_result = {
                            let payload = &self.buffer[5..msg_len + 1];
                            parse_data_row_payload_owned(payload)
                        };

                        let _ = self.buffer.split_to(msg_len + 1);
                        match parse_result {
                            Ok(columns) => return Ok((msg_type, Some(columns))),
                            Err(err) => return Err(err),
                        }
                    }

                    // Other messages - skip
                    let _ = self.buffer.split_to(msg_len + 1);
                    return Ok((msg_type, None));
                }
            }

            let n = self.read_with_timeout().await?;
            if n == 0 {
                return self.connection_desync("Connection closed".to_string());
            }
        }
    }

    /// ZERO-COPY receive for DataRow.
    /// Uses bytes::Bytes for reference-counted slicing instead of Vec copy.
    /// Returns: (msg_type, Option<row_data>)
    /// For 'D' (DataRow): returns Bytes slices (no copy!)
    /// For other types: returns None
    #[inline]
    pub(crate) async fn recv_data_zerocopy(
        &mut self,
    ) -> PgResult<(u8, Option<Vec<Option<bytes::Bytes>>>)> {
        use bytes::Buf;

        loop {
            if self.buffer.len() >= 5 {
                let msg_len = u32::from_be_bytes([
                    self.buffer[1],
                    self.buffer[2],
                    self.buffer[3],
                    self.buffer[4],
                ]) as usize;

                if msg_len < 4 {
                    return self.protocol_desync(format!(
                        "Invalid message length: {} (minimum 4)",
                        msg_len
                    ));
                }

                if msg_len > MAX_MESSAGE_SIZE {
                    return self.protocol_desync(format!(
                        "Message too large: {} bytes (max {})",
                        msg_len, MAX_MESSAGE_SIZE
                    ));
                }

                if self.buffer.len() > msg_len {
                    let msg_type = self.buffer[0];

                    if msg_type == b'E' || msg_type == b'A' {
                        let msg_bytes = self.buffer.split_to(msg_len + 1);
                        let (msg, _) = match BackendMessage::decode(&msg_bytes) {
                            Ok(decoded) => decoded,
                            Err(e) => return self.protocol_desync(e),
                        };
                        match msg {
                            BackendMessage::ErrorResponse(err) => {
                                return Err(PgError::QueryServer(err.into()));
                            }
                            BackendMessage::NotificationResponse {
                                process_id,
                                channel,
                                payload,
                            } => {
                                self.notifications
                                    .push_back(super::notification::Notification {
                                        process_id,
                                        channel,
                                        payload,
                                    });
                                continue;
                            }
                            _ => {
                                return Err(PgError::Protocol(
                                    "Unexpected fast-path message".into(),
                                ));
                            }
                        }
                    }

                    // Fast path: DataRow - ZERO-COPY using Bytes
                    if msg_type == b'D' {
                        // Split off the entire message
                        let mut msg_bytes = self.buffer.split_to(msg_len + 1);

                        // Skip type byte (1) + length (4) = 5 bytes
                        msg_bytes.advance(5);

                        if msg_bytes.len() >= 2 {
                            let raw_count = msg_bytes.get_i16();
                            if raw_count < 0 {
                                return Err(PgError::Protocol(format!(
                                    "DataRow invalid column count: {}",
                                    raw_count
                                )));
                            }
                            let column_count = raw_count as usize;
                            if column_count > msg_bytes.remaining() / 4 + 1 {
                                return Err(PgError::Protocol(format!(
                                    "DataRow claims {} columns but payload is only {} bytes",
                                    column_count,
                                    msg_bytes.remaining() + 2
                                )));
                            }
                            let mut columns = Vec::with_capacity(column_count);

                            for _ in 0..column_count {
                                if msg_bytes.remaining() < 4 {
                                    return Err(PgError::Protocol(
                                        "DataRow truncated: missing column length".into(),
                                    ));
                                }

                                let len = msg_bytes.get_i32();

                                if len == -1 {
                                    columns.push(None);
                                } else {
                                    if len < -1 {
                                        return Err(PgError::Protocol(format!(
                                            "DataRow invalid column length: {}",
                                            len
                                        )));
                                    }
                                    let len = len as usize;
                                    if msg_bytes.remaining() < len {
                                        return Err(PgError::Protocol(
                                            "DataRow truncated: column data exceeds payload".into(),
                                        ));
                                    }
                                    let col_data = msg_bytes.split_to(len).freeze();
                                    columns.push(Some(col_data));
                                }
                            }

                            if msg_bytes.remaining() != 0 {
                                return Err(PgError::Protocol("DataRow has trailing bytes".into()));
                            }

                            return Ok((msg_type, Some(columns)));
                        }
                        return Ok((msg_type, None));
                    }

                    // Other messages - skip
                    let _ = self.buffer.split_to(msg_len + 1);
                    return Ok((msg_type, None));
                }
            }

            let n = self.read_with_timeout().await?;
            if n == 0 {
                return self.connection_desync("Connection closed".to_string());
            }
        }
    }

    /// ULTRA-FAST receive for 2-column DataRow (id, name pattern).
    /// Uses fixed-size array instead of Vec allocation.
    /// Returns: (msg_type, Option<(col0, col1)>)
    #[inline(always)]
    pub(crate) async fn recv_data_ultra(
        &mut self,
    ) -> PgResult<(u8, Option<(bytes::Bytes, bytes::Bytes)>)> {
        use bytes::Buf;

        loop {
            if self.buffer.len() >= 5 {
                let msg_len = u32::from_be_bytes([
                    self.buffer[1],
                    self.buffer[2],
                    self.buffer[3],
                    self.buffer[4],
                ]) as usize;

                if msg_len < 4 {
                    return self.protocol_desync(format!(
                        "Invalid message length: {} (minimum 4)",
                        msg_len
                    ));
                }

                if msg_len > MAX_MESSAGE_SIZE {
                    return self.protocol_desync(format!(
                        "Message too large: {} bytes (max {})",
                        msg_len, MAX_MESSAGE_SIZE
                    ));
                }

                if self.buffer.len() > msg_len {
                    let msg_type = self.buffer[0];

                    // Error and async-notify checks
                    if msg_type == b'E' || msg_type == b'A' {
                        let msg_bytes = self.buffer.split_to(msg_len + 1);
                        let (msg, _) = match BackendMessage::decode(&msg_bytes) {
                            Ok(decoded) => decoded,
                            Err(e) => return self.protocol_desync(e),
                        };
                        match msg {
                            BackendMessage::ErrorResponse(err) => {
                                return Err(PgError::QueryServer(err.into()));
                            }
                            BackendMessage::NotificationResponse {
                                process_id,
                                channel,
                                payload,
                            } => {
                                self.notifications
                                    .push_back(super::notification::Notification {
                                        process_id,
                                        channel,
                                        payload,
                                    });
                                continue;
                            }
                            _ => {
                                return Err(PgError::Protocol(
                                    "Unexpected fast-path message".into(),
                                ));
                            }
                        }
                    }

                    if msg_type == b'D' {
                        let mut msg_bytes = self.buffer.split_to(msg_len + 1);
                        msg_bytes.advance(5); // Skip type + length

                        // Bounds checks to prevent panic on truncated DataRow
                        if msg_bytes.remaining() < 2 {
                            return Err(PgError::Protocol(
                                "DataRow ultra: too short for column count".into(),
                            ));
                        }

                        // Read column count (expect 2)
                        let col_count = msg_bytes.get_i16();
                        if col_count != 2 {
                            return Err(PgError::Protocol(format!(
                                "DataRow ultra expects exactly 2 columns, got {}",
                                col_count
                            )));
                        }

                        if msg_bytes.remaining() < 4 {
                            return Err(PgError::Protocol(
                                "DataRow ultra: truncated before col0 length".into(),
                            ));
                        }
                        let len0 = msg_bytes.get_i32();
                        let col0 = if len0 > 0 {
                            let len0 = len0 as usize;
                            if msg_bytes.remaining() < len0 {
                                return Err(PgError::Protocol(
                                    "DataRow ultra: col0 data exceeds payload".into(),
                                ));
                            }
                            msg_bytes.split_to(len0).freeze()
                        } else if len0 == 0 {
                            bytes::Bytes::new()
                        } else if len0 == -1 {
                            return Err(PgError::Protocol(
                                "DataRow ultra does not support NULL columns".into(),
                            ));
                        } else {
                            return Err(PgError::Protocol(format!(
                                "DataRow ultra: invalid col0 length {}",
                                len0
                            )));
                        };

                        if msg_bytes.remaining() < 4 {
                            return Err(PgError::Protocol(
                                "DataRow ultra: truncated before col1 length".into(),
                            ));
                        }
                        let len1 = msg_bytes.get_i32();
                        let col1 = if len1 > 0 {
                            let len1 = len1 as usize;
                            if msg_bytes.remaining() < len1 {
                                return Err(PgError::Protocol(
                                    "DataRow ultra: col1 data exceeds payload".into(),
                                ));
                            }
                            msg_bytes.split_to(len1).freeze()
                        } else if len1 == 0 {
                            bytes::Bytes::new()
                        } else if len1 == -1 {
                            return Err(PgError::Protocol(
                                "DataRow ultra does not support NULL columns".into(),
                            ));
                        } else {
                            return Err(PgError::Protocol(format!(
                                "DataRow ultra: invalid col1 length {}",
                                len1
                            )));
                        };

                        if msg_bytes.remaining() != 0 {
                            return Err(PgError::Protocol(
                                "DataRow ultra: trailing bytes after expected columns".into(),
                            ));
                        }

                        return Ok((msg_type, Some((col0, col1))));
                    }

                    // Other messages - skip
                    let _ = self.buffer.split_to(msg_len + 1);
                    return Ok((msg_type, None));
                }
            }

            let n = self.read_with_timeout().await?;
            if n == 0 {
                return self.connection_desync("Connection closed".to_string());
            }
        }
    }
}