pg-proto 0.4.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
//! Bounded, payload-free orchestration for proxy request pipelines.
//!
//! The ledger in this module records protocol obligations, not wire messages.
//! Applications retain ownership of decoded messages until [`FrontendAction`] or
//! [`BackendAction`] tells them to forward, emit, retry, or discard the value.
//! Upstream transports may continue using [`Demux`]: drain its ordered async
//! events before passing each returned [`SessionItem`] to
//! [`Pipeline::accept_session_item`]. This retains the existing notice tagging,
//! parameter map, notification queue, cancellation key, and transaction evidence.

use std::{collections::VecDeque, convert::Infallible, sync::Arc};

use tokio::sync::Notify;

use crate::{
    codec::{BackendMessage, FrontendMessage},
    demux::{Demux, SessionItem},
    grammar::backend,
    middleware::{
        AsynchronousBackendMessage, ChainError, MessageMiddleware, Middleware,
        ReconstructableMessage as _, Then,
    },
};

/// Stable identity of an accepted frontend operation.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct OperationId(u64);

/// Pipeline policy which preserves the historical lock-step behaviour.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct NoPipeline;

/// Configuration for a bounded frontend operation pipeline.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct BoundedPipeline {
    max_operations: usize,
}

impl BoundedPipeline {
    /// Creates a pipeline with a non-zero operation-count limit.
    ///
    /// # Errors
    ///
    /// Returns an error when `max_operations` is zero.
    pub fn new(max_operations: usize) -> Result<Self, PipelineConfigError> {
        if max_operations == 0 {
            return Err(PipelineConfigError);
        }
        Ok(Self { max_operations })
    }

    /// Returns the maximum number of incomplete operations.
    #[must_use]
    pub const fn max_operations(self) -> usize {
        self.max_operations
    }
}

/// A zero operation-count limit is not a usable pipeline configuration.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PipelineConfigError;

impl std::fmt::Display for PipelineConfigError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("pipeline operation limit must be non-zero")
    }
}

impl std::error::Error for PipelineConfigError {}

mod private {
    pub trait Sealed {}
}

/// Configuration accepted by [`Pipeline`].
pub trait PipelinePolicy: private::Sealed + Copy {
    /// Maximum number of incomplete operation records.
    fn operation_limit(self) -> usize;
}

impl private::Sealed for NoPipeline {}
impl PipelinePolicy for NoPipeline {
    fn operation_limit(self) -> usize {
        1
    }
}

impl private::Sealed for BoundedPipeline {}
impl PipelinePolicy for BoundedPipeline {
    fn operation_limit(self) -> usize {
        self.max_operations
    }
}

/// Whether an accepted frontend operation is locally handled or forwarded.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FrontendHandling {
    /// Send the returned message to the upstream connection.
    Forward,
    /// Do not send the request upstream; application code will synthesize its response.
    Local,
}

/// Application action for one successfully projected frontend message.
#[derive(Debug, Eq, PartialEq)]
pub enum FrontendAction {
    /// Forward the owned message upstream.
    Forward {
        /// Accepted operation identity.
        id: OperationId,
        /// Original, unretained frontend message.
        message: FrontendMessage,
    },
    /// The operation is locally handled and the message can be discarded.
    Discard {
        /// Accepted operation identity.
        id: OperationId,
    },
    /// Capacity is exhausted; pause reads and retry this unchanged message.
    Backpressure(FrontendMessage),
}

/// Position of a successfully accepted operation.
#[derive(Debug, Eq, PartialEq)]
pub enum FrontendAdmission {
    /// Nothing earlier prevents this operation's response from being emitted.
    Immediate(FrontendAction),
    /// The operation was accepted but an earlier response must be emitted first.
    Waiting(FrontendAction),
}

impl FrontendAdmission {
    /// Returns the application action, discarding only the positional annotation.
    #[must_use]
    pub fn into_action(self) -> FrontendAction {
        match self {
            Self::Immediate(action) | Self::Waiting(action) => action,
        }
    }
}

/// Why a frontend message could not be accepted.
#[derive(Debug, Eq, PartialEq)]
pub enum FrontendProjectionError {
    /// The bounded ledger is full; the unchanged message may be retried.
    Capacity(Box<FrontendMessage>),
    /// The message is not legal in the projected frontend protocol state.
    Illegal {
        /// Projected state at rejection.
        state: PipelineState,
        /// Unchanged illegal message.
        message: Box<FrontendMessage>,
    },
}

/// Application action for a backend message.
#[derive(Debug, Eq, PartialEq)]
pub enum BackendAction {
    /// Emit this owned message to the downstream client now.
    Emit(BackendMessage),
    /// An earlier operation must complete; retry this unchanged message later.
    Deferred(BackendMessage),
}

/// A backend message was not legal for any outstanding operation.
#[derive(Debug, Eq, PartialEq)]
pub struct BackendProjectionError {
    /// Current response-side state.
    pub state: PipelineState,
    /// Unchanged illegal message.
    pub message: BackendMessage,
}

/// Public summary of the pipeline's projected frontend state.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PipelineState {
    /// A simple or extended cycle may begin.
    Ready,
    /// Extended-query messages are being accepted.
    Extended,
    /// An extended error discards messages through `Sync`.
    ExtendedError,
    /// COPY IN accepts frontend data.
    CopyIn,
    /// COPY OUT accepts only backend data.
    CopyOut,
    /// COPY BOTH accepts data in both directions.
    CopyBoth,
    /// The connection has terminated.
    Terminated,
}

/// Error returned while dispatching a pipeline message through typed middleware.
#[derive(Debug)]
pub enum PipelineMiddlewareError<MiddlewareError, ProjectionError> {
    /// Middleware rejected the phase-typed message.
    Middleware(MiddlewareError),
    /// The pipeline rejected the original or rewritten message.
    Projection(ProjectionError),
}

macro_rules! frontend_pipeline_phases {
    ($consumer:ident) => {
        $consumer! {
            Ready => frontend_ready => backend::ReadyExternalMessage,
            Building => frontend_building => backend::BuildingExternalMessage,
            ExtendedError => frontend_extended_error => backend::ExtendedErrorExternalMessage,
            SimpleCopyIn => frontend_simple_copy_in => backend::SimpleCopyInExternalMessage,
            ExtendedCopyIn => frontend_extended_copy_in => backend::ExtendedCopyInExternalMessage,
            SimpleCopyBoth => frontend_simple_copy_both => backend::SimpleCopyBothExternalMessage,
            ExtendedCopyBoth => frontend_extended_copy_both => backend::ExtendedCopyBothExternalMessage,
        }
    };
}

macro_rules! backend_pipeline_phases {
    ($consumer:ident) => {
        $consumer! {
            Asynchronous => backend_asynchronous => AsynchronousBackendMessage,
            Simple => backend_simple => backend::SimpleInternalMessage,
            SimpleError => backend_simple_error => backend::SimpleErrorInternalMessage,
            ParseResponse => backend_parse_response => backend::ParseResponseInternalMessage,
            BindResponse => backend_bind_response => backend::BindResponseInternalMessage,
            DescribeResponse => backend_describe_response => backend::DescribeResponseInternalMessage,
            ExecuteResponse => backend_execute_response => backend::ExecuteResponseInternalMessage,
            CloseResponse => backend_close_response => backend::CloseResponseInternalMessage,
            SyncResponse => backend_sync_response => backend::SyncResponseInternalMessage,
            FunctionResponse => backend_function_response => backend::FunctionResponseInternalMessage,
            FunctionReady => backend_function_ready => backend::FunctionReadyInternalMessage,
            SimpleCopyInDone => backend_simple_copy_in_done => backend::SimpleCopyInDoneInternalMessage,
            SimpleCopyInFailed => backend_simple_copy_in_failed => backend::SimpleCopyInFailedInternalMessage,
            SimpleCopyOut => backend_simple_copy_out => backend::SimpleCopyOutInternalMessage,
            SimpleCopyOutDone => backend_simple_copy_out_done => backend::SimpleCopyOutDoneInternalMessage,
            SimpleCopyReady => backend_simple_copy_ready => backend::SimpleCopyReadyInternalMessage,
            ExtendedCopyInDone => backend_extended_copy_in_done => backend::ExtendedCopyInDoneInternalMessage,
            ExtendedCopyInFailed => backend_extended_copy_in_failed => backend::ExtendedCopyInFailedInternalMessage,
            ExtendedCopyOut => backend_extended_copy_out => backend::ExtendedCopyOutInternalMessage,
            ExtendedCopyOutDone => backend_extended_copy_out_done => backend::ExtendedCopyOutDoneInternalMessage,
            SimpleCopyBoth => backend_simple_copy_both => backend::SimpleCopyBothInternalMessage,
            SimpleCopyBothClientDone => backend_simple_copy_both_client_done => backend::SimpleCopyBothClientDoneInternalMessage,
            SimpleCopyBothDone => backend_simple_copy_both_done => backend::SimpleCopyBothDoneInternalMessage,
            SimpleCopyBothFailed => backend_simple_copy_both_failed => backend::SimpleCopyBothFailedInternalMessage,
            ExtendedCopyBoth => backend_extended_copy_both => backend::ExtendedCopyBothInternalMessage,
            ExtendedCopyBothClientDone => backend_extended_copy_both_client_done => backend::ExtendedCopyBothClientDoneInternalMessage,
            ExtendedCopyBothDone => backend_extended_copy_both_done => backend::ExtendedCopyBothDoneInternalMessage,
            ExtendedCopyBothFailed => backend_extended_copy_both_failed => backend::ExtendedCopyBothFailedInternalMessage,
        }
    };
}

macro_rules! declare_pipeline_hooks {
    ($($phase:ident => $method:ident => $message:path),+ $(,)?) => {
        $(
            #[doc = concat!("Intercepts backend messages in generated `", stringify!($message), "` phase.")]
            async fn $method(
                &mut self,
                _state: &mut State,
                message: $message,
            ) -> Result<$message, Self::Error> {
                Ok(message)
            }
        )+
    };
}

/// Async middleware for frontend messages selected from the runtime ledger phase.
#[allow(async_fn_in_trait)]
pub trait FrontendPipelineMiddleware<State> {
    /// An error which prevents the message from continuing through the pipeline.
    type Error;
    frontend_pipeline_phases!(declare_pipeline_hooks);
}

/// Async middleware for backend messages selected from the runtime ledger phase.
#[allow(async_fn_in_trait)]
pub trait BackendPipelineMiddleware<State> {
    /// An error which prevents the message from continuing through the pipeline.
    type Error;
    backend_pipeline_phases!(declare_pipeline_hooks);
}

impl<State> FrontendPipelineMiddleware<State> for crate::middleware::Identity {
    type Error = Infallible;
}

impl<State> BackendPipelineMiddleware<State> for crate::middleware::Identity {
    type Error = Infallible;
}

macro_rules! chained_pipeline_hooks {
    ($($phase:ident => $method:ident => $message:ty),+ $(,)?) => {
        $(
            async fn $method(
                &mut self,
                state: &mut State,
                message: $message,
            ) -> Result<$message, Self::Error> {
                let (first, second) = self.parts_mut();
                let message = first
                    .$method(state, message)
                    .await
                    .map_err(ChainError::First)?;
                second
                    .$method(state, message)
                    .await
                    .map_err(ChainError::Second)
            }
        )+
    };
}

impl<State, First, Second> FrontendPipelineMiddleware<State> for Then<First, Second>
where
    First: FrontendPipelineMiddleware<State>,
    Second: FrontendPipelineMiddleware<State>,
{
    type Error = ChainError<First::Error, Second::Error>;

    frontend_pipeline_phases!(chained_pipeline_hooks);
}

impl<State, First, Second> BackendPipelineMiddleware<State> for Then<First, Second>
where
    First: BackendPipelineMiddleware<State>,
    Second: BackendPipelineMiddleware<State>,
{
    type Error = ChainError<First::Error, Second::Error>;
    backend_pipeline_phases!(chained_pipeline_hooks);
}

/// Adapts direction-wide async middleware to every typed pipeline hook.
pub struct PipelineWireAdapter<Handler> {
    handler: Handler,
}

impl<Handler> PipelineWireAdapter<Handler> {
    /// Wraps direction-wide middleware for runtime phase dispatch.
    pub const fn new(handler: Handler) -> Self {
        Self { handler }
    }

    /// Returns the wrapped direction-wide middleware.
    pub fn into_inner(self) -> Handler {
        self.handler
    }
}

/// Failure from direction-wide middleware adapted to typed pipeline dispatch.
#[derive(Debug)]
pub enum FrontendPipelineWireAdapterError<Error> {
    /// The wrapped middleware rejected a message.
    Middleware(Error),
    /// The wrapped middleware returned a frontend message illegal in the selected phase.
    IllegalFrontend(FrontendMessage),
}

/// Failure from backend wire middleware adapted to typed pipeline dispatch.
#[derive(Debug)]
pub enum BackendPipelineWireAdapterError<Error> {
    /// The wrapped middleware rejected a message.
    Middleware(Error),
    /// The wrapped middleware returned a message illegal in the selected phase.
    Illegal(BackendMessage),
}

macro_rules! pipeline_adapter_frontend_hooks {
    ($($phase:ident => $method:ident => $message:ty),+ $(,)?) => {
        $(
            async fn $method(
                &mut self,
                state: &mut State,
                message: $message,
            ) -> Result<$message, Self::Error> {
                let message: FrontendMessage = message.into();
                let message = self
                    .handler
                    .intercept(state, message)
                    .await
                    .map_err(FrontendPipelineWireAdapterError::Middleware)?;
                <$message>::try_from(message)
                    .map_err(FrontendPipelineWireAdapterError::IllegalFrontend)
            }
        )+
    };
}

macro_rules! pipeline_adapter_backend_hooks {
    ($ignored:ident => $async_method:ident => AsynchronousBackendMessage, $($phase:ident => $method:ident => $message:ty),+ $(,)?) => {
        async fn $async_method(
            &mut self,
            state: &mut State,
            message: AsynchronousBackendMessage,
        ) -> Result<AsynchronousBackendMessage, Self::Error> {
            let message = self.handler.intercept(state, message.into_wire()).await
                .map_err(BackendPipelineWireAdapterError::Middleware)?;
            AsynchronousBackendMessage::try_from(message)
                .map_err(BackendPipelineWireAdapterError::Illegal)
        }
        $(
            async fn $method(
                &mut self,
                state: &mut State,
                message: $message,
            ) -> Result<$message, Self::Error> {
                let message: BackendMessage = message.into();
                let message = self
                    .handler
                    .intercept(state, message)
                    .await
                    .map_err(BackendPipelineWireAdapterError::Middleware)?;
                <$message>::try_from(message).map_err(BackendPipelineWireAdapterError::Illegal)
            }
        )+
    };
}

impl<State, Handler> FrontendPipelineMiddleware<State> for PipelineWireAdapter<Handler>
where
    Handler: MessageMiddleware<FrontendMessage, State>,
{
    type Error = FrontendPipelineWireAdapterError<Handler::Error>;
    frontend_pipeline_phases!(pipeline_adapter_frontend_hooks);
}

impl<State, Handler> BackendPipelineMiddleware<State> for PipelineWireAdapter<Handler>
where
    Handler: MessageMiddleware<BackendMessage, State>,
{
    type Error = BackendPipelineWireAdapterError<Handler::Error>;
    backend_pipeline_phases!(pipeline_adapter_backend_hooks);
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum RequestState {
    Ready,
    Extended { bound: bool },
    ExtendedError,
    CopyIn,
    CopyOut,
    CopyBoth,
    Terminated,
}

impl RequestState {
    const fn public(self) -> PipelineState {
        match self {
            Self::Ready => PipelineState::Ready,
            Self::Extended { .. } => PipelineState::Extended,
            Self::ExtendedError => PipelineState::ExtendedError,
            Self::CopyIn => PipelineState::CopyIn,
            Self::CopyOut => PipelineState::CopyOut,
            Self::CopyBoth => PipelineState::CopyBoth,
            Self::Terminated => PipelineState::Terminated,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Origin {
    Forwarded,
    Local,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum OperationKind {
    Query,
    FunctionCall,
    Parse,
    Bind,
    Describe,
    Execute,
    Close,
    Flush,
    Sync,
    CopyData,
    CopyDone,
    CopyFail,
    Terminate,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PreparedResponse {
    Asynchronous,
    Emit {
        head: Operation,
        response_state: backend::RuntimeState,
    },
    Deferred,
    Illegal,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum FrontendPhase {
    Ready,
    Building,
    ExtendedError,
    SimpleCopyIn,
    ExtendedCopyIn,
    SimpleCopyBoth,
    ExtendedCopyBoth,
}

#[derive(Clone, Copy, Debug)]
struct PreparedFrontend {
    phase: FrontendPhase,
    request_state: RequestState,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Operation {
    id: OperationId,
    kind: OperationKind,
    origin: Origin,
    discarded: bool,
    response_state: backend::RuntimeState,
}

/// A bounded ledger coordinating independently owned frontend and backend values.
#[derive(Debug)]
pub struct Pipeline<P = NoPipeline> {
    policy: P,
    operations: VecDeque<Operation>,
    request_state: RequestState,
    response_state: Option<PipelineState>,
    next_id: u64,
    changed: Arc<Notify>,
}

impl Default for Pipeline<NoPipeline> {
    fn default() -> Self {
        Self::new(NoPipeline)
    }
}

impl<P: PipelinePolicy> Pipeline<P> {
    /// Creates an empty pipeline using `policy`.
    #[must_use]
    pub fn new(policy: P) -> Self {
        Self {
            policy,
            operations: VecDeque::new(),
            request_state: RequestState::Ready,
            response_state: None,
            next_id: 0,
            changed: Arc::new(Notify::new()),
        }
    }

    /// Returns the projected frontend protocol state.
    #[must_use]
    pub fn state(&self) -> PipelineState {
        self.response_state
            .unwrap_or_else(|| self.request_state.public())
    }

    /// Returns the number of incomplete lightweight operation records.
    #[must_use]
    pub fn len(&self) -> usize {
        self.operations.len()
    }

    /// Reports whether no operations remain outstanding.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.operations.is_empty()
    }

    /// Projects and accepts one frontend message without retaining its payload.
    ///
    /// Capacity and legality failures return the original owned message. A
    /// capacity failure does not mutate either projected state or the ledger.
    ///
    /// # Errors
    ///
    /// Returns the unchanged boxed message when capacity is exhausted or the
    /// message is illegal in the projected state.
    pub fn accept_frontend(
        &mut self,
        message: FrontendMessage,
        handling: FrontendHandling,
    ) -> Result<FrontendAdmission, FrontendProjectionError> {
        let prepared = self.prepare_frontend(&message)?;
        Ok(self.commit_frontend(prepared, message, handling))
    }

    fn prepare_frontend(
        &self,
        message: &FrontendMessage,
    ) -> Result<PreparedFrontend, FrontendProjectionError> {
        if self.operations.len() == self.policy.operation_limit() {
            return Err(FrontendProjectionError::Capacity(Box::new(message.clone())));
        }
        if project_frontend(self.request_state, message).is_none() {
            return Err(FrontendProjectionError::Illegal {
                state: self.state(),
                message: Box::new(message.clone()),
            });
        }
        Ok(PreparedFrontend {
            phase: frontend_phase(
                self.request_state,
                self.operations.front().map(|operation| operation.kind),
            ),
            request_state: self.request_state,
        })
    }

    fn commit_frontend(
        &mut self,
        prepared: PreparedFrontend,
        message: FrontendMessage,
        handling: FrontendHandling,
    ) -> FrontendAdmission {
        let (kind, next_state) = classify_frontend(prepared.request_state, &message)
            .expect("phase-typed frontend replacement has a ledger classification");
        let waiting = !self.operations.is_empty();
        let id = OperationId(self.next_id);
        self.next_id = self.next_id.saturating_add(1);
        self.request_state = next_state;
        let origin = match handling {
            FrontendHandling::Forward => Origin::Forwarded,
            FrontendHandling::Local => Origin::Local,
        };
        if let Some(head) = self.operations.front_mut()
            && let Some(event) = backend::project_external(head.response_state, &message)
            && let Some(transition) = backend::transition(head.response_state, event)
        {
            head.response_state = transition.target;
        }
        self.operations.push_back(Operation {
            id,
            kind,
            origin,
            discarded: matches!(self.request_state, RequestState::ExtendedError)
                && kind != OperationKind::Sync,
            response_state: initial_response_state(kind),
        });
        let action = match handling {
            FrontendHandling::Forward => FrontendAction::Forward { id, message },
            FrontendHandling::Local => FrontendAction::Discard { id },
        };
        let admission = if waiting {
            FrontendAdmission::Waiting(action)
        } else {
            FrontendAdmission::Immediate(action)
        };
        self.remove_inert_heads();
        admission
    }

    /// Convenience projection which reports capacity as [`FrontendAction::Backpressure`].
    ///
    /// # Errors
    ///
    /// Returns the unchanged message for capacity or protocol illegality.
    pub fn project_frontend(
        &mut self,
        message: FrontendMessage,
        handling: FrontendHandling,
    ) -> Result<FrontendAdmission, FrontendProjectionError> {
        self.accept_frontend(message, handling)
    }

    /// Projects a frontend value into the compact application-action vocabulary.
    ///
    /// Use [`Self::accept_frontend`] when the caller also needs to distinguish an
    /// immediately emittable operation from an accepted waiting operation.
    ///
    /// # Errors
    ///
    /// Returns an illegal message; capacity is represented as a successful
    /// [`FrontendAction::Backpressure`] action.
    pub fn frontend_action(
        &mut self,
        message: FrontendMessage,
        handling: FrontendHandling,
    ) -> Result<FrontendAction, FrontendProjectionError> {
        match self.accept_frontend(message, handling) {
            Ok(admission) => Ok(admission.into_action()),
            Err(FrontendProjectionError::Capacity(message)) => {
                Ok(FrontendAction::Backpressure(*message))
            }
            Err(error @ FrontendProjectionError::Illegal { .. }) => Err(error),
        }
    }

    /// Projects, asynchronously intercepts, and accepts one frontend message.
    ///
    /// The ledger selects the phase-specific middleware hook at runtime. The
    /// selected hook can only return a message legal in that same phase.
    /// Middleware is not invoked when capacity is exhausted.
    ///
    /// # Errors
    ///
    /// Returns a middleware error, an illegal original or replacement message,
    /// or the unchanged message when capacity is exhausted.
    pub async fn accept_frontend_typed<State, Handler>(
        &mut self,
        middleware: &mut Middleware<State, Handler>,
        message: FrontendMessage,
        handling: FrontendHandling,
    ) -> Result<FrontendAdmission, PipelineMiddlewareError<Handler::Error, FrontendProjectionError>>
    where
        Handler: FrontendPipelineMiddleware<State>,
    {
        let prepared = self
            .prepare_frontend(&message)
            .map_err(PipelineMiddlewareError::Projection)?;

        let message = self
            .intercept_frontend(prepared.phase, middleware, message)
            .await
            .map_err(PipelineMiddlewareError::Middleware)?;
        if !message.is_reconstructable() {
            return Err(PipelineMiddlewareError::Projection(
                FrontendProjectionError::Illegal {
                    state: self.state(),
                    message: Box::new(message),
                },
            ));
        }
        Ok(self.commit_frontend(prepared, message, handling))
    }

    /// Typed-middleware counterpart to [`Self::project_frontend`].
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`Self::accept_frontend_typed`].
    pub async fn project_frontend_typed<State, Handler>(
        &mut self,
        middleware: &mut Middleware<State, Handler>,
        message: FrontendMessage,
        handling: FrontendHandling,
    ) -> Result<FrontendAdmission, PipelineMiddlewareError<Handler::Error, FrontendProjectionError>>
    where
        Handler: FrontendPipelineMiddleware<State>,
    {
        self.accept_frontend_typed(middleware, message, handling)
            .await
    }

    /// Typed-middleware counterpart to [`Self::frontend_action`].
    ///
    /// Capacity is returned as [`FrontendAction::Backpressure`] without running
    /// middleware. Accepted messages are dispatched to their phase-specific hook.
    ///
    /// # Errors
    ///
    /// Returns a middleware error or an illegal original or replacement message.
    pub async fn frontend_action_typed<State, Handler>(
        &mut self,
        middleware: &mut Middleware<State, Handler>,
        message: FrontendMessage,
        handling: FrontendHandling,
    ) -> Result<FrontendAction, PipelineMiddlewareError<Handler::Error, FrontendProjectionError>>
    where
        Handler: FrontendPipelineMiddleware<State>,
    {
        match self
            .accept_frontend_typed(middleware, message, handling)
            .await
        {
            Ok(admission) => Ok(admission.into_action()),
            Err(PipelineMiddlewareError::Projection(FrontendProjectionError::Capacity(
                message,
            ))) => Ok(FrontendAction::Backpressure(*message)),
            Err(error) => Err(error),
        }
    }

    /// Projects one upstream backend message and preserves response order.
    ///
    /// # Errors
    ///
    /// Returns an unchanged response which cannot belong to any outstanding operation.
    pub fn accept_backend(
        &mut self,
        message: BackendMessage,
    ) -> Result<BackendAction, BackendProjectionError> {
        self.accept_response(None, message)
    }

    /// Intercepts an emittable backend response through its operation-typed hook.
    ///
    /// Responses belonging to a later operation are returned unchanged as
    /// [`BackendAction::Deferred`] and are intercepted only when retried at the
    /// response head. Asynchronous messages use their non-advancing hook.
    ///
    /// # Errors
    ///
    /// Returns a middleware error or an unchanged response which cannot belong
    /// to any outstanding operation.
    pub async fn accept_backend_typed<State, Handler>(
        &mut self,
        middleware: &mut Middleware<State, Handler>,
        message: BackendMessage,
    ) -> Result<BackendAction, PipelineMiddlewareError<Handler::Error, BackendProjectionError>>
    where
        Handler: BackendPipelineMiddleware<State>,
    {
        self.accept_response_typed(None, middleware, message).await
    }

    /// Projects one protocol-advancing item returned by the existing [`Demux`].
    ///
    /// Before calling this method, forward any values from
    /// [`Demux::pop_async_event`] in queue order. Command notices remain available
    /// through the demux's notice queue; the ledger itself stores no notice payload.
    ///
    /// # Errors
    ///
    /// Returns an unchanged reconstructed response which cannot belong to any
    /// outstanding operation.
    pub fn accept_session_item(
        &mut self,
        item: SessionItem,
    ) -> Result<BackendAction, BackendProjectionError> {
        let message = match item {
            SessionItem::Message(message) => message,
            SessionItem::ReadyForQuery { status, .. } => BackendMessage::ReadyForQuery(status),
            SessionItem::CommandComplete { tag, .. } => BackendMessage::CommandComplete(tag),
        };
        self.accept_backend(message)
    }

    /// Typed-middleware counterpart to [`Self::accept_session_item`].
    ///
    /// # Errors
    ///
    /// Returns a middleware or backend projection error.
    pub async fn accept_session_item_typed<State, Handler>(
        &mut self,
        middleware: &mut Middleware<State, Handler>,
        item: SessionItem,
    ) -> Result<BackendAction, PipelineMiddlewareError<Handler::Error, BackendProjectionError>>
    where
        Handler: BackendPipelineMiddleware<State>,
    {
        let message = match item {
            SessionItem::Message(message) => message,
            SessionItem::ReadyForQuery { status, .. } => BackendMessage::ReadyForQuery(status),
            SessionItem::CommandComplete { tag, .. } => BackendMessage::CommandComplete(tag),
        };
        self.accept_backend_typed(middleware, message).await
    }

    /// Attempts to register and emit a locally synthesized response.
    ///
    /// The message is returned as [`BackendAction::Deferred`] when `id` has not
    /// reached the head. No backend payload is retained by the ledger.
    ///
    /// # Errors
    ///
    /// Returns the unchanged message when it is illegal for the named operation.
    pub fn try_emit_local(
        &mut self,
        id: OperationId,
        message: BackendMessage,
    ) -> Result<BackendAction, BackendProjectionError> {
        self.accept_response(Some(id), message)
    }

    /// Typed-middleware counterpart to [`Self::try_emit_local`].
    ///
    /// Deferred local responses are not intercepted until their operation reaches
    /// the response head.
    ///
    /// # Errors
    ///
    /// Returns a middleware error or an illegal response for the named operation.
    pub async fn try_emit_local_typed<State, Handler>(
        &mut self,
        middleware: &mut Middleware<State, Handler>,
        id: OperationId,
        message: BackendMessage,
    ) -> Result<BackendAction, PipelineMiddlewareError<Handler::Error, BackendProjectionError>>
    where
        Handler: BackendPipelineMiddleware<State>,
    {
        self.accept_response_typed(Some(id), middleware, message)
            .await
    }

    /// Waits until a local operation reaches the response head.
    ///
    /// Cancellation is safe: polling this future never reserves or removes a
    /// ledger entry. The caller should then invoke [`Self::try_emit_local`].
    pub async fn wait_until_emittable(&self, id: OperationId) {
        loop {
            let notified = self.changed.notified();
            if self
                .operations
                .front()
                .is_some_and(|operation| operation.id == id)
            {
                return;
            }
            notified.await;
        }
    }

    async fn intercept_frontend<State, Handler>(
        &self,
        phase: FrontendPhase,
        middleware: &mut Middleware<State, Handler>,
        message: FrontendMessage,
    ) -> Result<FrontendMessage, Handler::Error>
    where
        Handler: FrontendPipelineMiddleware<State>,
    {
        let (state, handler) = middleware.parts_mut();
        macro_rules! dispatch {
            ($message:expr, $type:path, $handler:ident, $state:ident, $method:ident) => {{
                let Ok(typed) = <$type>::try_from($message) else {
                    unreachable!("frontend message was prevalidated for pipeline phase")
                };
                $handler.$method($state, typed).await?.into()
            }};
        }

        macro_rules! dispatch_catalogue {
            ($($catalogue_phase:ident => $method:ident => $message_type:path),+ $(,)?) => {
                match phase {
                    $(
                        FrontendPhase::$catalogue_phase =>
                            dispatch!(message, $message_type, handler, state, $method),
                    )+
                }
            };
        }

        Ok(frontend_pipeline_phases!(dispatch_catalogue))
    }

    #[allow(clippy::too_many_lines)]
    async fn accept_response_typed<State, Handler>(
        &mut self,
        local_id: Option<OperationId>,
        middleware: &mut Middleware<State, Handler>,
        message: BackendMessage,
    ) -> Result<BackendAction, PipelineMiddlewareError<Handler::Error, BackendProjectionError>>
    where
        Handler: BackendPipelineMiddleware<State>,
    {
        let prepared = self.prepare_response(local_id, &message);
        if matches!(prepared, PreparedResponse::Deferred) {
            return Ok(BackendAction::Deferred(message));
        }
        if matches!(prepared, PreparedResponse::Illegal) {
            return Err(PipelineMiddlewareError::Projection(
                BackendProjectionError {
                    state: self.state(),
                    message,
                },
            ));
        }

        let (state, handler) = middleware.parts_mut();
        let message = match prepared {
            PreparedResponse::Asynchronous => {
                let Ok(typed) = AsynchronousBackendMessage::try_from(message) else {
                    unreachable!("asynchronous response was prevalidated")
                };
                handler
                    .backend_asynchronous(state, typed)
                    .await
                    .map_err(PipelineMiddlewareError::Middleware)?
                    .into_wire()
            }
            PreparedResponse::Emit { response_state, .. } => {
                macro_rules! dispatch {
                    ($message:ty, $method:ident) => {{
                        let typed = match <$message>::try_from(message) {
                            Ok(typed) => typed,
                            Err(message) => {
                                return Err(PipelineMiddlewareError::Projection(
                                    BackendProjectionError {
                                        state: self.state(),
                                        message,
                                    },
                                ));
                            }
                        };
                        handler
                            .$method(state, typed)
                            .await
                            .map_err(PipelineMiddlewareError::Middleware)?
                            .into_wire()
                    }};
                }

                macro_rules! dispatch_catalogue {
                    ($ignored:ident => $ignored_method:ident => AsynchronousBackendMessage,
                     $($catalogue_phase:ident => $method:ident => $message_type:path),+ $(,)?) => {
                        match response_state {
                            $(
                                backend::RuntimeState::$catalogue_phase =>
                                    dispatch!($message_type, $method),
                            )+
                            _ => unreachable!("response phase has no backend-selected transition"),
                        }
                    };
                }

                backend_pipeline_phases!(dispatch_catalogue)
            }
            PreparedResponse::Deferred | PreparedResponse::Illegal => unreachable!(),
        };

        if !message.is_reconstructable() {
            return Err(PipelineMiddlewareError::Projection(
                BackendProjectionError {
                    state: self.state(),
                    message,
                },
            ));
        }
        self.commit_response(prepared, message)
            .map_err(PipelineMiddlewareError::Projection)
    }

    fn prepare_response(
        &self,
        local_id: Option<OperationId>,
        message: &BackendMessage,
    ) -> PreparedResponse {
        if is_asynchronous(message) {
            return PreparedResponse::Asynchronous;
        }
        let Some(head) = self.operations.front().copied() else {
            return PreparedResponse::Illegal;
        };
        if let Some(id) = local_id {
            if head.id != id {
                return PreparedResponse::Deferred;
            }
            if head.origin != Origin::Local {
                return PreparedResponse::Illegal;
            }
        } else if head.origin == Origin::Local {
            return if self.operations.iter().skip(1).any(|operation| {
                operation.origin == Origin::Forwarded && response_fits(*operation, message)
            }) {
                PreparedResponse::Deferred
            } else {
                PreparedResponse::Illegal
            };
        }
        if head.discarded || !response_fits(head, message) {
            return if self
                .operations
                .iter()
                .skip(1)
                .any(|operation| response_fits(*operation, message))
            {
                PreparedResponse::Deferred
            } else {
                PreparedResponse::Illegal
            };
        }
        PreparedResponse::Emit {
            head,
            response_state: head.response_state,
        }
    }

    fn accept_response(
        &mut self,
        local_id: Option<OperationId>,
        message: BackendMessage,
    ) -> Result<BackendAction, BackendProjectionError> {
        let prepared = self.prepare_response(local_id, &message);
        self.commit_response(prepared, message)
    }

    fn commit_response(
        &mut self,
        prepared: PreparedResponse,
        message: BackendMessage,
    ) -> Result<BackendAction, BackendProjectionError> {
        let PreparedResponse::Emit {
            head,
            response_state,
        } = prepared
        else {
            return match prepared {
                PreparedResponse::Asynchronous => Ok(BackendAction::Emit(message)),
                PreparedResponse::Deferred => Ok(BackendAction::Deferred(message)),
                PreparedResponse::Illegal => Err(BackendProjectionError {
                    state: self.state(),
                    message,
                }),
                PreparedResponse::Emit { .. } => unreachable!(),
            };
        };
        let event = backend::project_internal(response_state, &message)
            .expect("response was validated against its generated backend phase");
        let next_response_state = backend::transition(response_state, event)
            .expect("projected backend event has a generated transition")
            .target;
        let terminal = response_is_terminal(head.kind, &message);
        let error = matches!(message, BackendMessage::ErrorResponse(_));
        let copy_state = response_copy_state(next_response_state);
        if terminal {
            self.operations.pop_front();
            if error && is_extended_kind(head.kind) {
                self.enter_extended_error();
            }
        } else if let Some(head) = self.operations.front_mut() {
            head.response_state = next_response_state;
        }
        if !terminal {
            self.response_state = copy_state.map(RequestState::public);
        }
        if let Some(state) = copy_state
            && matches!(state, RequestState::CopyIn | RequestState::CopyBoth)
        {
            self.request_state = state;
        }
        if terminal {
            self.response_state = None;
            match head.kind {
                OperationKind::Sync | OperationKind::Query => {
                    self.request_state = RequestState::Ready;
                }
                OperationKind::Execute if !error => {
                    self.request_state = RequestState::Extended { bound: true };
                }
                _ => {}
            }
        }
        self.remove_inert_heads();
        self.changed.notify_waiters();
        Ok(BackendAction::Emit(message))
    }

    fn enter_extended_error(&mut self) {
        self.request_state = RequestState::ExtendedError;
        self.response_state = None;
        for operation in &mut self.operations {
            if operation.kind == OperationKind::Sync {
                break;
            }
            operation.discarded = true;
        }
    }

    fn remove_inert_heads(&mut self) {
        let previous_len = self.operations.len();
        while self.operations.front().is_some_and(|operation| {
            operation.kind == OperationKind::Flush
                || operation.kind == OperationKind::CopyData
                || operation.kind == OperationKind::CopyDone
                || operation.kind == OperationKind::CopyFail
                || operation.kind == OperationKind::Terminate
                || operation.discarded
        }) {
            self.operations.pop_front();
        }
        if self.operations.len() != previous_len {
            self.changed.notify_waiters();
        }
    }
}

fn project_frontend(
    state: RequestState,
    message: &FrontendMessage,
) -> Option<(OperationKind, RequestState)> {
    use RequestState as S;
    let generated_state = match state {
        S::Ready => backend::RuntimeState::Ready,
        S::Extended { .. } => backend::RuntimeState::Building,
        S::ExtendedError => backend::RuntimeState::ExtendedError,
        S::CopyIn => backend::RuntimeState::ExtendedCopyIn,
        S::CopyOut => backend::RuntimeState::ExtendedCopyOut,
        S::CopyBoth => backend::RuntimeState::ExtendedCopyBoth,
        S::Terminated => backend::RuntimeState::Terminated,
    };
    backend::project_external(generated_state, message)?;
    classify_frontend(state, message)
}

fn classify_frontend(
    state: RequestState,
    message: &FrontendMessage,
) -> Option<(OperationKind, RequestState)> {
    use FrontendMessage as F;
    use OperationKind as O;
    use RequestState as S;

    match (state, message) {
        (S::Ready, F::Query(_)) => Some((O::Query, S::Ready)),
        (S::Ready, F::FunctionCall(_)) => Some((O::FunctionCall, S::Ready)),
        (S::Ready, F::Parse(_)) => Some((O::Parse, S::Extended { bound: false })),
        (S::Ready | S::Extended { .. }, F::Bind(_)) => Some((O::Bind, S::Extended { bound: true })),
        (S::Ready, F::Describe(_)) => Some((O::Describe, S::Extended { bound: false })),
        (S::Ready | S::Extended { .. }, F::Execute(_)) => {
            Some((O::Execute, S::Extended { bound: true }))
        }
        (S::Ready, F::Close(_)) => Some((O::Close, S::Extended { bound: false })),
        (S::Ready, F::Terminate) => Some((O::Terminate, S::Terminated)),
        (S::Extended { bound }, F::Parse(_)) => Some((O::Parse, S::Extended { bound })),
        (S::Extended { bound }, F::Describe(_)) => Some((O::Describe, S::Extended { bound })),
        (S::Extended { bound }, F::Close(_)) => Some((O::Close, S::Extended { bound })),
        (S::Extended { bound }, F::Flush) => Some((O::Flush, S::Extended { bound })),
        (S::Extended { .. } | S::ExtendedError, F::Sync) => Some((O::Sync, S::Ready)),
        (S::ExtendedError, _) => Some((classify_discard(message)?, S::ExtendedError)),
        (S::CopyIn, F::CopyData(_)) => Some((O::CopyData, S::CopyIn)),
        (S::CopyIn, F::CopyDone) => Some((O::CopyDone, S::Extended { bound: true })),
        (S::CopyIn, F::CopyFail(_)) => Some((O::CopyFail, S::ExtendedError)),
        (S::CopyBoth, F::CopyData(_)) => Some((O::CopyData, S::CopyBoth)),
        (S::CopyBoth, F::CopyDone) => Some((O::CopyDone, S::CopyBoth)),
        _ => None,
    }
}

fn frontend_phase(state: RequestState, response_head: Option<OperationKind>) -> FrontendPhase {
    match (state, response_head) {
        (RequestState::Ready, _) => FrontendPhase::Ready,
        (RequestState::Extended { .. }, _) => FrontendPhase::Building,
        (RequestState::ExtendedError, _) => FrontendPhase::ExtendedError,
        (RequestState::CopyIn, Some(OperationKind::Query)) => FrontendPhase::SimpleCopyIn,
        (RequestState::CopyIn, Some(OperationKind::Execute)) => FrontendPhase::ExtendedCopyIn,
        (RequestState::CopyBoth, Some(OperationKind::Query)) => FrontendPhase::SimpleCopyBoth,
        (RequestState::CopyBoth, Some(OperationKind::Execute)) => FrontendPhase::ExtendedCopyBoth,
        (RequestState::CopyIn | RequestState::CopyBoth, _) => {
            unreachable!("COPY phase must belong to Query or Execute")
        }
        (RequestState::CopyOut | RequestState::Terminated, _) => {
            unreachable!("non-accepting frontend phase cannot be prepared")
        }
    }
}

fn classify_discard(message: &FrontendMessage) -> Option<OperationKind> {
    Some(match message {
        FrontendMessage::Parse(_) => OperationKind::Parse,
        FrontendMessage::Bind(_) => OperationKind::Bind,
        FrontendMessage::Describe(_) => OperationKind::Describe,
        FrontendMessage::Execute(_) => OperationKind::Execute,
        FrontendMessage::Close(_) => OperationKind::Close,
        FrontendMessage::Flush => OperationKind::Flush,
        FrontendMessage::Query(_) => OperationKind::Query,
        FrontendMessage::FunctionCall(_) => OperationKind::FunctionCall,
        FrontendMessage::CopyData(_) => OperationKind::CopyData,
        FrontendMessage::CopyDone => OperationKind::CopyDone,
        FrontendMessage::CopyFail(_) => OperationKind::CopyFail,
        FrontendMessage::Terminate => OperationKind::Terminate,
        FrontendMessage::PasswordResponse(_) => return None,
        FrontendMessage::Sync => unreachable!("Sync is classified before discard"),
    })
}

const fn initial_response_state(kind: OperationKind) -> backend::RuntimeState {
    use OperationKind as O;
    match kind {
        O::Query => backend::RuntimeState::Simple,
        O::FunctionCall => backend::RuntimeState::FunctionResponse,
        O::Parse => backend::RuntimeState::ParseResponse,
        O::Bind => backend::RuntimeState::BindResponse,
        O::Describe => backend::RuntimeState::DescribeResponse,
        O::Execute => backend::RuntimeState::ExecuteResponse,
        O::Close => backend::RuntimeState::CloseResponse,
        O::Sync => backend::RuntimeState::SyncResponse,
        O::Flush | O::CopyData | O::CopyDone | O::CopyFail | O::Terminate => {
            backend::RuntimeState::Terminated
        }
    }
}

fn response_fits(operation: Operation, message: &BackendMessage) -> bool {
    backend::project_internal(operation.response_state, message).is_some()
}

fn response_is_terminal(kind: OperationKind, message: &BackendMessage) -> bool {
    use BackendMessage as B;
    use OperationKind as O;
    match kind {
        O::Query | O::FunctionCall | O::Sync => matches!(message, B::ReadyForQuery(_)),
        O::Parse => matches!(message, B::ParseComplete | B::ErrorResponse(_)),
        O::Bind => matches!(message, B::BindComplete | B::ErrorResponse(_)),
        O::Describe => matches!(
            message,
            B::RowDescription(_) | B::NoData | B::ErrorResponse(_)
        ),
        O::Execute => matches!(
            message,
            B::CommandComplete(_) | B::PortalSuspended | B::ErrorResponse(_)
        ),
        O::Close => matches!(message, B::CloseComplete | B::ErrorResponse(_)),
        O::CopyDone => matches!(
            message,
            B::CopyDone | B::CommandComplete(_) | B::ErrorResponse(_)
        ),
        O::CopyFail => matches!(message, B::ErrorResponse(_)),
        O::Flush | O::CopyData | O::Terminate => true,
    }
}

fn is_extended_kind(kind: OperationKind) -> bool {
    !matches!(
        kind,
        OperationKind::Query | OperationKind::FunctionCall | OperationKind::Terminate
    )
}

fn response_copy_state(state: backend::RuntimeState) -> Option<RequestState> {
    use backend::RuntimeState as S;
    match state {
        S::SimpleCopyIn | S::ExtendedCopyIn => Some(RequestState::CopyIn),
        S::SimpleCopyOut | S::ExtendedCopyOut => Some(RequestState::CopyOut),
        S::SimpleCopyBoth
        | S::SimpleCopyBothClientDone
        | S::SimpleCopyBothServerDone
        | S::ExtendedCopyBoth
        | S::ExtendedCopyBothClientDone
        | S::ExtendedCopyBothServerDone => Some(RequestState::CopyBoth),
        _ => None,
    }
}

fn is_asynchronous(message: &BackendMessage) -> bool {
    Demux::is_asynchronous(message)
}