Line data Source code
1 : use std::time::{Duration, SystemTime};
2 :
3 : use bytes::{Buf, BufMut, Bytes, BytesMut};
4 : use pq_proto::{read_cstr, PG_EPOCH};
5 : use serde::{Deserialize, Serialize};
6 : use tracing::{trace, warn};
7 :
8 : use crate::lsn::Lsn;
9 :
10 : /// Feedback pageserver sends to safekeeper and safekeeper resends to compute.
11 : /// Serialized in custom flexible key/value format. In replication protocol, it
12 : /// is marked with NEON_STATUS_UPDATE_TAG_BYTE to differentiate from postgres
13 : /// Standby status update / Hot standby feedback messages.
14 : ///
15 : /// serde Serialize is used only for human readable dump to json (e.g. in
16 : /// safekeepers debug_dump).
17 114 : #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18 : pub struct PageserverFeedback {
19 : /// Last known size of the timeline. Used to enforce timeline size limit.
20 : pub current_timeline_size: u64,
21 : /// LSN last received and ingested by the pageserver. Controls backpressure.
22 : pub last_received_lsn: Lsn,
23 : /// LSN up to which data is persisted by the pageserver to its local disc.
24 : /// Controls backpressure.
25 : pub disk_consistent_lsn: Lsn,
26 : /// LSN up to which data is persisted by the pageserver on s3; safekeepers
27 : /// consider WAL before it can be removed.
28 : pub remote_consistent_lsn: Lsn,
29 : // Serialize with RFC3339 format.
30 : #[serde(with = "serde_systemtime")]
31 : pub replytime: SystemTime,
32 : }
33 :
34 : // NOTE: Do not forget to increment this number when adding new fields to PageserverFeedback.
35 : // Do not remove previously available fields because this might be backwards incompatible.
36 : pub const PAGESERVER_FEEDBACK_FIELDS_NUMBER: u8 = 5;
37 :
38 : impl PageserverFeedback {
39 3256191 : pub fn empty() -> PageserverFeedback {
40 3256191 : PageserverFeedback {
41 3256191 : current_timeline_size: 0,
42 3256191 : last_received_lsn: Lsn::INVALID,
43 3256191 : remote_consistent_lsn: Lsn::INVALID,
44 3256191 : disk_consistent_lsn: Lsn::INVALID,
45 3256191 : replytime: *PG_EPOCH,
46 3256191 : }
47 3256191 : }
48 :
49 : // Serialize PageserverFeedback using custom format
50 : // to support protocol extensibility.
51 : //
52 : // Following layout is used:
53 : // char - number of key-value pairs that follow.
54 : //
55 : // key-value pairs:
56 : // null-terminated string - key,
57 : // uint32 - value length in bytes
58 : // value itself
59 : //
60 : // TODO: change serialized fields names once all computes migrate to rename.
61 2457591 : pub fn serialize(&self, buf: &mut BytesMut) {
62 2457591 : buf.put_u8(PAGESERVER_FEEDBACK_FIELDS_NUMBER); // # of keys
63 2457591 : buf.put_slice(b"current_timeline_size\0");
64 2457591 : buf.put_i32(8);
65 2457591 : buf.put_u64(self.current_timeline_size);
66 2457591 :
67 2457591 : buf.put_slice(b"ps_writelsn\0");
68 2457591 : buf.put_i32(8);
69 2457591 : buf.put_u64(self.last_received_lsn.0);
70 2457591 : buf.put_slice(b"ps_flushlsn\0");
71 2457591 : buf.put_i32(8);
72 2457591 : buf.put_u64(self.disk_consistent_lsn.0);
73 2457591 : buf.put_slice(b"ps_applylsn\0");
74 2457591 : buf.put_i32(8);
75 2457591 : buf.put_u64(self.remote_consistent_lsn.0);
76 2457591 :
77 2457591 : let timestamp = self
78 2457591 : .replytime
79 2457591 : .duration_since(*PG_EPOCH)
80 2457591 : .expect("failed to serialize pg_replytime earlier than PG_EPOCH")
81 2457591 : .as_micros() as i64;
82 2457591 :
83 2457591 : buf.put_slice(b"ps_replytime\0");
84 2457591 : buf.put_i32(8);
85 2457591 : buf.put_i64(timestamp);
86 2457591 : }
87 :
88 : // Deserialize PageserverFeedback message
89 : // TODO: change serialized fields names once all computes migrate to rename.
90 797261 : pub fn parse(mut buf: Bytes) -> PageserverFeedback {
91 797261 : let mut rf = PageserverFeedback::empty();
92 797261 : let nfields = buf.get_u8();
93 797261 : for _ in 0..nfields {
94 3986307 : let key = read_cstr(&mut buf).unwrap();
95 3986307 : match key.as_ref() {
96 3986307 : b"current_timeline_size" => {
97 797261 : let len = buf.get_i32();
98 797261 : assert_eq!(len, 8);
99 797261 : rf.current_timeline_size = buf.get_u64();
100 : }
101 3189046 : b"ps_writelsn" => {
102 797261 : let len = buf.get_i32();
103 797261 : assert_eq!(len, 8);
104 797261 : rf.last_received_lsn = Lsn(buf.get_u64());
105 : }
106 : b"ps_flushlsn" => {
107 797261 : let len = buf.get_i32();
108 797261 : assert_eq!(len, 8);
109 797261 : rf.disk_consistent_lsn = Lsn(buf.get_u64());
110 : }
111 : b"ps_applylsn" => {
112 797261 : let len = buf.get_i32();
113 797261 : assert_eq!(len, 8);
114 797261 : rf.remote_consistent_lsn = Lsn(buf.get_u64());
115 : }
116 797263 : b"ps_replytime" => {
117 797261 : let len = buf.get_i32();
118 797261 : assert_eq!(len, 8);
119 797261 : let raw_time = buf.get_i64();
120 797261 : if raw_time > 0 {
121 797261 : rf.replytime = *PG_EPOCH + Duration::from_micros(raw_time as u64);
122 797261 : } else {
123 0 : rf.replytime = *PG_EPOCH - Duration::from_micros(-raw_time as u64);
124 0 : }
125 : }
126 : _ => {
127 2 : let len = buf.get_i32();
128 2 : warn!(
129 0 : "PageserverFeedback parse. unknown key {} of len {len}. Skip it.",
130 0 : String::from_utf8_lossy(key.as_ref())
131 0 : );
132 2 : buf.advance(len as usize);
133 : }
134 : }
135 : }
136 797261 : trace!("PageserverFeedback parsed is {:?}", rf);
137 797261 : rf
138 797261 : }
139 : }
140 :
141 : mod serde_systemtime {
142 : use std::time::SystemTime;
143 :
144 : use chrono::{DateTime, Utc};
145 : use serde::{Deserialize, Deserializer, Serializer};
146 :
147 114 : pub fn serialize<S>(ts: &SystemTime, serializer: S) -> Result<S::Ok, S::Error>
148 114 : where
149 114 : S: Serializer,
150 114 : {
151 114 : let chrono_dt: DateTime<Utc> = (*ts).into();
152 114 : serializer.serialize_str(&chrono_dt.to_rfc3339())
153 114 : }
154 :
155 2 : pub fn deserialize<'de, D>(deserializer: D) -> Result<SystemTime, D::Error>
156 2 : where
157 2 : D: Deserializer<'de>,
158 2 : {
159 2 : let time: String = Deserialize::deserialize(deserializer)?;
160 2 : Ok(DateTime::parse_from_rfc3339(&time)
161 2 : .map_err(serde::de::Error::custom)?
162 2 : .into())
163 2 : }
164 : }
165 :
166 : #[cfg(test)]
167 : mod tests {
168 : use super::*;
169 :
170 2 : #[test]
171 2 : fn test_replication_feedback_serialization() {
172 2 : let mut rf = PageserverFeedback::empty();
173 2 : // Fill rf with some values
174 2 : rf.current_timeline_size = 12345678;
175 2 : // Set rounded time to be able to compare it with deserialized value,
176 2 : // because it is rounded up to microseconds during serialization.
177 2 : rf.replytime = *PG_EPOCH + Duration::from_secs(100_000_000);
178 2 : let mut data = BytesMut::new();
179 2 : rf.serialize(&mut data);
180 2 :
181 2 : let rf_parsed = PageserverFeedback::parse(data.freeze());
182 2 : assert_eq!(rf, rf_parsed);
183 2 : }
184 :
185 2 : #[test]
186 2 : fn test_replication_feedback_unknown_key() {
187 2 : let mut rf = PageserverFeedback::empty();
188 2 : // Fill rf with some values
189 2 : rf.current_timeline_size = 12345678;
190 2 : // Set rounded time to be able to compare it with deserialized value,
191 2 : // because it is rounded up to microseconds during serialization.
192 2 : rf.replytime = *PG_EPOCH + Duration::from_secs(100_000_000);
193 2 : let mut data = BytesMut::new();
194 2 : rf.serialize(&mut data);
195 :
196 : // Add an extra field to the buffer and adjust number of keys
197 2 : if let Some(first) = data.first_mut() {
198 2 : *first = PAGESERVER_FEEDBACK_FIELDS_NUMBER + 1;
199 2 : }
200 :
201 2 : data.put_slice(b"new_field_one\0");
202 2 : data.put_i32(8);
203 2 : data.put_u64(42);
204 2 :
205 2 : // Parse serialized data and check that new field is not parsed
206 2 : let rf_parsed = PageserverFeedback::parse(data.freeze());
207 2 : assert_eq!(rf, rf_parsed);
208 2 : }
209 : }
|