pg-proto 0.1.1

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
//! Filtering projection from backend messages to the typed session stream.

use std::collections::{BTreeMap, VecDeque};

use bytes::Bytes;

use crate::codec::{BackendMessage, DiagnosticResponse, TransactionStatus};

/// Position of a command within a connection's session.
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub struct CommandIndex(pub u64);

#[derive(Clone, Debug, Eq, PartialEq)]
/// A backend notice attributed to the command active when it arrived.
pub struct TaggedNotice {
    /// Command to which the notice belongs.
    pub command: CommandIndex,
    /// Structured notice fields.
    pub fields: DiagnosticResponse,
}

#[derive(Clone, Debug, Eq, PartialEq)]
/// A decoded asynchronous notification.
pub struct Notification {
    /// Process identifier of the notifying backend.
    pub process_id: u32,
    /// Notification channel.
    pub channel: Bytes,
    /// Notification payload.
    pub payload: Bytes,
}

/// One ordered `ParameterStatus` update retained for proxy forwarding.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParameterStatus {
    /// Parameter name.
    pub name: Bytes,
    /// Current parameter value.
    pub value: Bytes,
}

/// A causally independent backend event retained in its original wire order.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AsyncEvent {
    /// A positionally tagged notice.
    Notice(TaggedNotice),
    /// A run-time parameter update.
    ParameterStatus(ParameterStatus),
    /// A `LISTEN`/`NOTIFY` notification.
    Notification(Notification),
}

/// Ordering and command attribution for an asynchronous backend event.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OrderedAsyncEvent {
    /// Monotonic sequence number across all asynchronous event kinds.
    pub sequence: u64,
    /// Command active when the event arrived.
    pub command: CommandIndex,
    /// Decoded event.
    pub event: AsyncEvent,
}

#[derive(Clone, Eq, Hash, PartialEq)]
/// Backend cancellation credentials captured during startup.
pub struct CancelKey {
    /// Backend process identifier.
    pub process_id: u32,
    /// Opaque cancellation secret; its debug representation is redacted.
    pub secret_key: Bytes,
}

impl std::fmt::Debug for CancelKey {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("CancelKey")
            .field("process_id", &self.process_id)
            .field("secret_key", &"[REDACTED]")
            .finish()
    }
}

/// A protocol-advancing message, optionally closing a command boundary.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SessionItem {
    /// An ordinary protocol-advancing backend message.
    Message(BackendMessage),
    /// Readiness together with pooling-relevant state accumulated by the demux.
    ReadyForQuery {
        /// Backend transaction status.
        status: TransactionStatus,
        /// Whether run-time parameters differ from their startup baseline.
        parameters_changed: bool,
    },
    /// Command completion with notices accumulated since the previous boundary.
    CommandComplete {
        /// Backend command tag.
        tag: Bytes,
        /// Completed command's position in the session.
        command: CommandIndex,
        /// Notices attributed to this command.
        notices: Vec<TaggedNotice>,
    },
}

/// State owned below the typestate API for causally independent backend messages.
#[derive(Debug, Default)]
pub struct Demux {
    command: CommandIndex,
    pending_notices: Vec<TaggedNotice>,
    notices: VecDeque<TaggedNotice>,
    notifications: VecDeque<Notification>,
    parameter_statuses: VecDeque<ParameterStatus>,
    async_events: VecDeque<OrderedAsyncEvent>,
    next_async_sequence: u64,
    parameters: BTreeMap<Bytes, Bytes>,
    startup_parameters: Option<BTreeMap<Bytes, Bytes>>,
    parameters_changed: bool,
    cancel_key: Option<CancelKey>,
    transaction_status: Option<TransactionStatus>,
}

impl Demux {
    /// Routes one decoded backend message.
    ///
    /// Async messages are consumed and recorded; only session-advancing messages
    /// are returned.
    pub fn route(&mut self, message: BackendMessage) -> Option<SessionItem> {
        match message {
            BackendMessage::NoticeResponse(fields) => {
                let notice = TaggedNotice {
                    command: self.command,
                    fields,
                };
                self.pending_notices.push(notice.clone());
                self.notices.push_back(notice.clone());
                self.push_async(AsyncEvent::Notice(notice));
                None
            }
            BackendMessage::ParameterStatus { name, value } => {
                self.parameters.insert(name.clone(), value.clone());
                let status = ParameterStatus { name, value };
                self.parameter_statuses.push_back(status.clone());
                self.push_async(AsyncEvent::ParameterStatus(status));
                if let Some(startup_parameters) = &self.startup_parameters {
                    self.parameters_changed = self.parameters != *startup_parameters;
                }
                None
            }
            BackendMessage::NotificationResponse {
                process_id,
                channel,
                payload,
            } => {
                let notification = Notification {
                    process_id,
                    channel,
                    payload,
                };
                self.notifications.push_back(notification.clone());
                self.push_async(AsyncEvent::Notification(notification));
                None
            }
            BackendMessage::BackendKeyData {
                process_id,
                secret_key,
            } => {
                self.cancel_key = Some(CancelKey {
                    process_id,
                    secret_key: secret_key.clone(),
                });
                Some(SessionItem::Message(BackendMessage::BackendKeyData {
                    process_id,
                    secret_key,
                }))
            }
            BackendMessage::ReadyForQuery(status) => {
                self.transaction_status = Some(status);
                if self.startup_parameters.is_none() {
                    self.startup_parameters = Some(self.parameters.clone());
                }
                Some(SessionItem::ReadyForQuery {
                    status,
                    parameters_changed: self.parameters_changed,
                })
            }
            BackendMessage::CommandComplete(tag) => {
                let command = self.command;
                let notices = std::mem::take(&mut self.pending_notices);
                self.command.0 = self.command.0.saturating_add(1);
                Some(SessionItem::CommandComplete {
                    tag,
                    command,
                    notices,
                })
            }
            message => Some(SessionItem::Message(message)),
        }
    }

    /// Returns the latest value of every reported run-time parameter.
    #[must_use]
    pub fn parameters(&self) -> &BTreeMap<Bytes, Bytes> {
        &self.parameters
    }

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

    /// Returns the most recently received cancellation key, if any.
    #[must_use]
    pub const fn cancel_key(&self) -> Option<&CancelKey> {
        self.cancel_key.as_ref()
    }

    /// Returns the latest backend transaction status, if readiness was observed.
    #[must_use]
    pub const fn transaction_status(&self) -> Option<TransactionStatus> {
        self.transaction_status
    }

    /// Removes the next queued asynchronous notification.
    pub fn pop_notification(&mut self) -> Option<Notification> {
        self.notifications.pop_front()
    }

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

    /// Removes the next ordered status update for forwarding to a client.
    pub fn pop_parameter_status(&mut self) -> Option<ParameterStatus> {
        self.parameter_statuses.pop_front()
    }

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

    fn push_async(&mut self, event: AsyncEvent) {
        let sequence = self.next_async_sequence;
        self.next_async_sequence = self.next_async_sequence.saturating_add(1);
        self.async_events.push_back(OrderedAsyncEvent {
            sequence,
            command: self.command,
            event,
        });
    }
}

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

    #[test]
    fn notices_are_attached_to_their_command_boundary() {
        let mut demux = Demux::default();
        assert_eq!(
            demux.route(BackendMessage::NoticeResponse(DiagnosticResponse {
                fields: vec![crate::codec::DiagnosticField {
                    code: b'M',
                    value: Bytes::from_static(b"notice"),
                }],
            })),
            None
        );
        let completion = demux
            .route(BackendMessage::CommandComplete(Bytes::from_static(
                b"SELECT 1",
            )))
            .expect("command completion advances the session");
        assert_eq!(
            completion,
            SessionItem::CommandComplete {
                tag: Bytes::from_static(b"SELECT 1"),
                command: CommandIndex(0),
                notices: vec![TaggedNotice {
                    command: CommandIndex(0),
                    fields: DiagnosticResponse {
                        fields: vec![crate::codec::DiagnosticField {
                            code: b'M',
                            value: Bytes::from_static(b"notice"),
                        }],
                    },
                }],
            }
        );
        assert_eq!(
            demux.pop_notice(),
            Some(TaggedNotice {
                command: CommandIndex(0),
                fields: DiagnosticResponse {
                    fields: vec![crate::codec::DiagnosticField {
                        code: b'M',
                        value: Bytes::from_static(b"notice"),
                    }],
                },
            })
        );
        assert_eq!(demux.pop_notice(), None);
    }

    #[test]
    fn startup_parameters_establish_a_clean_baseline() {
        let mut demux = Demux::default();
        assert!(
            demux
                .route(BackendMessage::ParameterStatus {
                    name: Bytes::from_static(b"client_encoding"),
                    value: Bytes::from_static(b"UTF8"),
                })
                .is_none()
        );
        demux.route(BackendMessage::ReadyForQuery(TransactionStatus::Idle));
        assert!(!demux.parameters_changed());

        demux.route(BackendMessage::ParameterStatus {
            name: Bytes::from_static(b"client_encoding"),
            value: Bytes::from_static(b"LATIN1"),
        });
        assert!(demux.parameters_changed());
    }

    #[test]
    fn parameter_statuses_remain_ordered_for_proxy_forwarding() {
        let mut demux = Demux::default();
        for (name, value) in [
            (b"TimeZone".as_slice(), b"UTC".as_slice()),
            (b"TimeZone", b"GMT"),
        ] {
            assert!(
                demux
                    .route(BackendMessage::ParameterStatus {
                        name: Bytes::copy_from_slice(name),
                        value: Bytes::copy_from_slice(value),
                    })
                    .is_none()
            );
        }

        assert_eq!(
            demux.pop_parameter_status(),
            Some(ParameterStatus {
                name: Bytes::from_static(b"TimeZone"),
                value: Bytes::from_static(b"UTC"),
            })
        );
        assert_eq!(
            demux.pop_parameter_status(),
            Some(ParameterStatus {
                name: Bytes::from_static(b"TimeZone"),
                value: Bytes::from_static(b"GMT"),
            })
        );
        assert_eq!(demux.pop_parameter_status(), None);
        assert_eq!(
            demux.parameters().get(b"TimeZone".as_slice()),
            Some(&Bytes::from_static(b"GMT"))
        );
    }

    #[test]
    fn notification_is_not_a_session_transition() {
        let mut demux = Demux::default();
        assert!(
            demux
                .route(BackendMessage::NotificationResponse {
                    process_id: 42,
                    channel: Bytes::from_static(b"events"),
                    payload: Bytes::from_static(b"payload"),
                })
                .is_none()
        );
        assert_eq!(
            demux.pop_notification(),
            Some(Notification {
                process_id: 42,
                channel: Bytes::from_static(b"events"),
                payload: Bytes::from_static(b"payload"),
            })
        );
    }

    #[test]
    fn asynchronous_events_preserve_cross_kind_wire_order() {
        let mut demux = Demux::default();
        demux.route(BackendMessage::ParameterStatus {
            name: Bytes::from_static(b"TimeZone"),
            value: Bytes::from_static(b"UTC"),
        });
        demux.route(BackendMessage::NotificationResponse {
            process_id: 7,
            channel: Bytes::from_static(b"jobs"),
            payload: Bytes::from_static(b"ready"),
        });
        demux.route(BackendMessage::NoticeResponse(DiagnosticResponse {
            fields: vec![],
        }));

        let events = std::iter::from_fn(|| demux.pop_async_event()).collect::<Vec<_>>();
        assert_eq!(events.len(), 3);
        assert_eq!(events[0].sequence, 0);
        assert!(matches!(events[0].event, AsyncEvent::ParameterStatus(_)));
        assert_eq!(events[1].sequence, 1);
        assert!(matches!(events[1].event, AsyncEvent::Notification(_)));
        assert_eq!(events[2].sequence, 2);
        assert!(matches!(events[2].event, AsyncEvent::Notice(_)));
        assert!(events.iter().all(|event| event.command == CommandIndex(0)));
    }
}