Line data Source code
1 : //! Describes the legacy now hopefully no longer modified per-timeline metadata stored in
2 : //! `index_part.json` managed by [`remote_timeline_client`]. For many tenants and their timelines,
3 : //! this struct and it's original serialization format is still needed because they were written a
4 : //! long time ago.
5 : //!
6 : //! Instead of changing and adding versioning to this, just change [`IndexPart`] with soft json
7 : //! versioning.
8 : //!
9 : //! To clean up this module we need to migrate all index_part.json files to a later version.
10 : //! While doing this, we need to be mindful about s3 based recovery as well, so it might take
11 : //! however long we keep the old versions to be able to delete the old code. After that, we can
12 : //! remove everything else than [`TimelineMetadataBodyV2`], rename it as `TimelineMetadata` and
13 : //! move it to `index.rs`. Before doing all of this, we need to keep the structures for backwards
14 : //! compatibility.
15 : //!
16 : //! [`remote_timeline_client`]: super::remote_timeline_client
17 : //! [`IndexPart`]: super::remote_timeline_client::index::IndexPart
18 :
19 : use anyhow::ensure;
20 : use serde::{Deserialize, Serialize};
21 : use utils::bin_ser::SerializeError;
22 : use utils::{bin_ser::BeSer, id::TimelineId, lsn::Lsn};
23 :
24 : /// Use special format number to enable backward compatibility.
25 : const METADATA_FORMAT_VERSION: u16 = 4;
26 :
27 : /// Previous supported format versions.
28 : ///
29 : /// In practice, none of these should remain, all are [`METADATA_FORMAT_VERSION`], but confirming
30 : /// that requires a scrubber run which is yet to be done.
31 : const METADATA_OLD_FORMAT_VERSION: u16 = 3;
32 :
33 : /// When the file existed on disk we assumed that a write of up to METADATA_MAX_SIZE bytes is atomic.
34 : ///
35 : /// This is the same assumption that PostgreSQL makes with the control file,
36 : ///
37 : /// see PG_CONTROL_MAX_SAFE_SIZE
38 : const METADATA_MAX_SIZE: usize = 512;
39 :
40 : /// Legacy metadata stored as a component of `index_part.json` per timeline.
41 : ///
42 : /// Do not make new changes to this type or the module. In production, we have two different kinds
43 : /// of serializations of this type: bincode and json. Bincode version reflects what used to be
44 : /// stored on disk in earlier versions and does internal crc32 checksumming.
45 : ///
46 : /// This type should not implement `serde::Serialize` or `serde::Deserialize` because there would
47 : /// be a confusion whether you want the old version ([`TimelineMetadata::from_bytes`]) or the modern
48 : /// as-exists in `index_part.json` ([`self::modern_serde`]).
49 : ///
50 : /// ```compile_fail
51 : /// #[derive(serde::Serialize)]
52 : /// struct DoNotDoThis(pageserver::tenant::metadata::TimelineMetadata);
53 : /// ```
54 : ///
55 : /// ```compile_fail
56 : /// #[derive(serde::Deserialize)]
57 : /// struct NeitherDoThis(pageserver::tenant::metadata::TimelineMetadata);
58 : /// ```
59 : #[derive(Debug, Clone, PartialEq, Eq)]
60 : pub struct TimelineMetadata {
61 : hdr: TimelineMetadataHeader,
62 : body: TimelineMetadataBodyV2,
63 : }
64 :
65 156 : #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66 : struct TimelineMetadataHeader {
67 : checksum: u32, // CRC of serialized metadata body
68 : size: u16, // size of serialized metadata
69 : format_version: u16, // metadata format version (used for compatibility checks)
70 : }
71 :
72 : impl TryFrom<&TimelineMetadataBodyV2> for TimelineMetadataHeader {
73 : type Error = Crc32CalculationFailed;
74 :
75 108 : fn try_from(value: &TimelineMetadataBodyV2) -> Result<Self, Self::Error> {
76 108 : #[derive(Default)]
77 108 : struct Crc32Sink {
78 108 : crc: u32,
79 108 : count: usize,
80 108 : }
81 108 :
82 108 : impl std::io::Write for Crc32Sink {
83 1500 : fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
84 1500 : self.crc = crc32c::crc32c_append(self.crc, buf);
85 1500 : self.count += buf.len();
86 1500 : Ok(buf.len())
87 1500 : }
88 108 :
89 108 : fn flush(&mut self) -> std::io::Result<()> {
90 0 : Ok(())
91 0 : }
92 108 : }
93 108 :
94 108 : // jump through hoops to calculate the crc32 so that TimelineMetadata::ne works
95 108 : // across serialization versions
96 108 : let mut sink = Crc32Sink::default();
97 108 : <TimelineMetadataBodyV2 as utils::bin_ser::BeSer>::ser_into(value, &mut sink)
98 108 : .map_err(Crc32CalculationFailed)?;
99 :
100 108 : let size = METADATA_HDR_SIZE + sink.count;
101 108 :
102 108 : Ok(TimelineMetadataHeader {
103 108 : checksum: sink.crc,
104 108 : size: size as u16,
105 108 : format_version: METADATA_FORMAT_VERSION,
106 108 : })
107 108 : }
108 : }
109 :
110 0 : #[derive(thiserror::Error, Debug)]
111 : #[error("re-serializing for crc32 failed")]
112 : struct Crc32CalculationFailed(#[source] utils::bin_ser::SerializeError);
113 :
114 : const METADATA_HDR_SIZE: usize = size_of::<TimelineMetadataHeader>();
115 :
116 864 : #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117 : struct TimelineMetadataBodyV2 {
118 : disk_consistent_lsn: Lsn,
119 : // This is only set if we know it. We track it in memory when the page
120 : // server is running, but we only track the value corresponding to
121 : // 'last_record_lsn', not 'disk_consistent_lsn' which can lag behind by a
122 : // lot. We only store it in the metadata file when we flush *all* the
123 : // in-memory data so that 'last_record_lsn' is the same as
124 : // 'disk_consistent_lsn'. That's OK, because after page server restart, as
125 : // soon as we reprocess at least one record, we will have a valid
126 : // 'prev_record_lsn' value in memory again. This is only really needed when
127 : // doing a clean shutdown, so that there is no more WAL beyond
128 : // 'disk_consistent_lsn'
129 : prev_record_lsn: Option<Lsn>,
130 : ancestor_timeline: Option<TimelineId>,
131 : ancestor_lsn: Lsn,
132 : latest_gc_cutoff_lsn: Lsn,
133 : initdb_lsn: Lsn,
134 : pg_version: u32,
135 : }
136 :
137 6 : #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
138 : struct TimelineMetadataBodyV1 {
139 : disk_consistent_lsn: Lsn,
140 : // This is only set if we know it. We track it in memory when the page
141 : // server is running, but we only track the value corresponding to
142 : // 'last_record_lsn', not 'disk_consistent_lsn' which can lag behind by a
143 : // lot. We only store it in the metadata file when we flush *all* the
144 : // in-memory data so that 'last_record_lsn' is the same as
145 : // 'disk_consistent_lsn'. That's OK, because after page server restart, as
146 : // soon as we reprocess at least one record, we will have a valid
147 : // 'prev_record_lsn' value in memory again. This is only really needed when
148 : // doing a clean shutdown, so that there is no more WAL beyond
149 : // 'disk_consistent_lsn'
150 : prev_record_lsn: Option<Lsn>,
151 : ancestor_timeline: Option<TimelineId>,
152 : ancestor_lsn: Lsn,
153 : latest_gc_cutoff_lsn: Lsn,
154 : initdb_lsn: Lsn,
155 : }
156 :
157 : impl TimelineMetadata {
158 1296 : pub fn new(
159 1296 : disk_consistent_lsn: Lsn,
160 1296 : prev_record_lsn: Option<Lsn>,
161 1296 : ancestor_timeline: Option<TimelineId>,
162 1296 : ancestor_lsn: Lsn,
163 1296 : latest_gc_cutoff_lsn: Lsn,
164 1296 : initdb_lsn: Lsn,
165 1296 : pg_version: u32,
166 1296 : ) -> Self {
167 1296 : Self {
168 1296 : hdr: TimelineMetadataHeader {
169 1296 : checksum: 0,
170 1296 : size: 0,
171 1296 : format_version: METADATA_FORMAT_VERSION,
172 1296 : },
173 1296 : body: TimelineMetadataBodyV2 {
174 1296 : disk_consistent_lsn,
175 1296 : prev_record_lsn,
176 1296 : ancestor_timeline,
177 1296 : ancestor_lsn,
178 1296 : latest_gc_cutoff_lsn,
179 1296 : initdb_lsn,
180 1296 : pg_version,
181 1296 : },
182 1296 : }
183 1296 : }
184 :
185 : #[cfg(test)]
186 18 : pub(crate) fn with_recalculated_checksum(mut self) -> anyhow::Result<Self> {
187 18 : self.hdr = TimelineMetadataHeader::try_from(&self.body)?;
188 18 : Ok(self)
189 18 : }
190 :
191 6 : fn upgrade_timeline_metadata(metadata_bytes: &[u8]) -> anyhow::Result<Self> {
192 6 : let mut hdr = TimelineMetadataHeader::des(&metadata_bytes[0..METADATA_HDR_SIZE])?;
193 :
194 : // backward compatible only up to this version
195 6 : ensure!(
196 6 : hdr.format_version == METADATA_OLD_FORMAT_VERSION,
197 0 : "unsupported metadata format version {}",
198 : hdr.format_version
199 : );
200 :
201 6 : let metadata_size = hdr.size as usize;
202 :
203 6 : let body: TimelineMetadataBodyV1 =
204 6 : TimelineMetadataBodyV1::des(&metadata_bytes[METADATA_HDR_SIZE..metadata_size])?;
205 :
206 6 : let body = TimelineMetadataBodyV2 {
207 6 : disk_consistent_lsn: body.disk_consistent_lsn,
208 6 : prev_record_lsn: body.prev_record_lsn,
209 6 : ancestor_timeline: body.ancestor_timeline,
210 6 : ancestor_lsn: body.ancestor_lsn,
211 6 : latest_gc_cutoff_lsn: body.latest_gc_cutoff_lsn,
212 6 : initdb_lsn: body.initdb_lsn,
213 6 : pg_version: 14, // All timelines created before this version had pg_version 14
214 6 : };
215 6 :
216 6 : hdr.format_version = METADATA_FORMAT_VERSION;
217 6 :
218 6 : Ok(Self { hdr, body })
219 6 : }
220 :
221 150 : pub fn from_bytes(metadata_bytes: &[u8]) -> anyhow::Result<Self> {
222 150 : ensure!(
223 150 : metadata_bytes.len() == METADATA_MAX_SIZE,
224 0 : "metadata bytes size is wrong"
225 : );
226 150 : let hdr = TimelineMetadataHeader::des(&metadata_bytes[0..METADATA_HDR_SIZE])?;
227 :
228 150 : let metadata_size = hdr.size as usize;
229 150 : ensure!(
230 150 : metadata_size <= METADATA_MAX_SIZE,
231 0 : "corrupted metadata file"
232 : );
233 150 : let calculated_checksum = crc32c::crc32c(&metadata_bytes[METADATA_HDR_SIZE..metadata_size]);
234 150 : ensure!(
235 150 : hdr.checksum == calculated_checksum,
236 0 : "metadata checksum mismatch"
237 : );
238 :
239 150 : if hdr.format_version != METADATA_FORMAT_VERSION {
240 : // If metadata has the old format,
241 : // upgrade it and return the result
242 6 : TimelineMetadata::upgrade_timeline_metadata(metadata_bytes)
243 : } else {
244 144 : let body =
245 144 : TimelineMetadataBodyV2::des(&metadata_bytes[METADATA_HDR_SIZE..metadata_size])?;
246 144 : ensure!(
247 144 : body.disk_consistent_lsn.is_aligned(),
248 0 : "disk_consistent_lsn is not aligned"
249 : );
250 144 : Ok(TimelineMetadata { hdr, body })
251 : }
252 150 : }
253 :
254 54 : pub fn to_bytes(&self) -> Result<Vec<u8>, SerializeError> {
255 54 : let body_bytes = self.body.ser()?;
256 54 : let metadata_size = METADATA_HDR_SIZE + body_bytes.len();
257 54 : let hdr = TimelineMetadataHeader {
258 54 : size: metadata_size as u16,
259 54 : format_version: METADATA_FORMAT_VERSION,
260 54 : checksum: crc32c::crc32c(&body_bytes),
261 54 : };
262 54 : let hdr_bytes = hdr.ser()?;
263 54 : let mut metadata_bytes = vec![0u8; METADATA_MAX_SIZE];
264 54 : metadata_bytes[0..METADATA_HDR_SIZE].copy_from_slice(&hdr_bytes);
265 54 : metadata_bytes[METADATA_HDR_SIZE..metadata_size].copy_from_slice(&body_bytes);
266 54 : Ok(metadata_bytes)
267 54 : }
268 :
269 : /// [`Lsn`] that corresponds to the corresponding timeline directory
270 : /// contents, stored locally in the pageserver workdir.
271 63629 : pub fn disk_consistent_lsn(&self) -> Lsn {
272 63629 : self.body.disk_consistent_lsn
273 63629 : }
274 :
275 1236 : pub fn prev_record_lsn(&self) -> Option<Lsn> {
276 1236 : self.body.prev_record_lsn
277 1236 : }
278 :
279 1272 : pub fn ancestor_timeline(&self) -> Option<TimelineId> {
280 1272 : self.body.ancestor_timeline
281 1272 : }
282 :
283 1920 : pub fn ancestor_lsn(&self) -> Lsn {
284 1920 : self.body.ancestor_lsn
285 1920 : }
286 :
287 : /// When reparenting, the `ancestor_lsn` does not change.
288 : ///
289 : /// Returns true if anything was changed.
290 0 : pub fn reparent(&mut self, timeline: &TimelineId) {
291 0 : assert!(self.body.ancestor_timeline.is_some());
292 : // no assertion for redoing this: it's fine, we may have to repeat this multiple times over
293 0 : self.body.ancestor_timeline = Some(*timeline);
294 0 : }
295 :
296 : /// Returns true if anything was changed
297 0 : pub fn detach_from_ancestor(&mut self, branchpoint: &(TimelineId, Lsn)) {
298 0 : if let Some(ancestor) = self.body.ancestor_timeline {
299 0 : assert_eq!(ancestor, branchpoint.0);
300 0 : }
301 0 : if self.body.ancestor_lsn != Lsn(0) {
302 0 : assert_eq!(self.body.ancestor_lsn, branchpoint.1);
303 0 : }
304 0 : self.body.ancestor_timeline = None;
305 0 : self.body.ancestor_lsn = Lsn(0);
306 0 : }
307 :
308 1236 : pub fn latest_gc_cutoff_lsn(&self) -> Lsn {
309 1236 : self.body.latest_gc_cutoff_lsn
310 1236 : }
311 :
312 1236 : pub fn initdb_lsn(&self) -> Lsn {
313 1236 : self.body.initdb_lsn
314 1236 : }
315 :
316 1236 : pub fn pg_version(&self) -> u32 {
317 1236 : self.body.pg_version
318 1236 : }
319 :
320 : // Checksums make it awkward to build a valid instance by hand. This helper
321 : // provides a TimelineMetadata with a valid checksum in its header.
322 : #[cfg(test)]
323 36 : pub fn example() -> Self {
324 36 : let instance = Self::new(
325 36 : "0/16960E8".parse::<Lsn>().unwrap(),
326 36 : None,
327 36 : None,
328 36 : Lsn::from_hex("00000000").unwrap(),
329 36 : Lsn::from_hex("00000000").unwrap(),
330 36 : Lsn::from_hex("00000000").unwrap(),
331 36 : 0,
332 36 : );
333 36 : let bytes = instance.to_bytes().unwrap();
334 36 : Self::from_bytes(&bytes).unwrap()
335 36 : }
336 :
337 3438 : pub(crate) fn apply(&mut self, update: &MetadataUpdate) {
338 3438 : self.body.disk_consistent_lsn = update.disk_consistent_lsn;
339 3438 : self.body.prev_record_lsn = update.prev_record_lsn;
340 3438 : self.body.latest_gc_cutoff_lsn = update.latest_gc_cutoff_lsn;
341 3438 : }
342 : }
343 :
344 : pub(crate) mod modern_serde {
345 : use super::{TimelineMetadata, TimelineMetadataBodyV2, TimelineMetadataHeader};
346 : use serde::{Deserialize, Serialize};
347 :
348 138 : pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<TimelineMetadata, D::Error>
349 138 : where
350 138 : D: serde::de::Deserializer<'de>,
351 138 : {
352 138 : // for legacy reasons versions 1-5 had TimelineMetadata serialized as a Vec<u8> field with
353 138 : // BeSer.
354 138 : struct Visitor;
355 138 :
356 138 : impl<'d> serde::de::Visitor<'d> for Visitor {
357 138 : type Value = TimelineMetadata;
358 138 :
359 138 : fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
360 0 : f.write_str("BeSer bytes or json structure")
361 0 : }
362 138 :
363 138 : fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
364 48 : where
365 48 : A: serde::de::SeqAccess<'d>,
366 48 : {
367 48 : use serde::de::Error;
368 48 : let de = serde::de::value::SeqAccessDeserializer::new(seq);
369 48 : Vec::<u8>::deserialize(de)
370 48 : .map(|v| TimelineMetadata::from_bytes(&v).map_err(A::Error::custom))?
371 138 : }
372 138 :
373 138 : fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
374 90 : where
375 90 : A: serde::de::MapAccess<'d>,
376 90 : {
377 90 : use serde::de::Error;
378 90 :
379 90 : let de = serde::de::value::MapAccessDeserializer::new(map);
380 138 : let body = TimelineMetadataBodyV2::deserialize(de)?;
381 138 : let hdr = TimelineMetadataHeader::try_from(&body).map_err(A::Error::custom)?;
382 138 :
383 138 : Ok(TimelineMetadata { hdr, body })
384 138 : }
385 138 : }
386 138 :
387 138 : deserializer.deserialize_any(Visitor)
388 138 : }
389 :
390 8639 : pub(crate) fn serialize<S>(
391 8639 : metadata: &TimelineMetadata,
392 8639 : serializer: S,
393 8639 : ) -> Result<S::Ok, S::Error>
394 8639 : where
395 8639 : S: serde::Serializer,
396 8639 : {
397 8639 : // header is not needed, upon reading we've upgraded all v1 to v2
398 8639 : metadata.body.serialize(serializer)
399 8639 : }
400 :
401 : #[test]
402 6 : fn deserializes_bytes_as_well_as_equivalent_body_v2() {
403 12 : #[derive(serde::Deserialize, serde::Serialize)]
404 6 : struct Wrapper(
405 6 : #[serde(deserialize_with = "deserialize", serialize_with = "serialize")]
406 6 : TimelineMetadata,
407 6 : );
408 6 :
409 6 : let too_many_bytes = "[216,111,252,208,0,54,0,4,0,0,0,0,1,73,253,144,1,0,0,0,0,1,73,253,24,0,0,0,0,0,0,0,0,0,0,0,0,0,1,73,253,24,0,0,0,0,1,73,253,24,0,0,0,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]";
410 6 :
411 6 : let wrapper_from_bytes = serde_json::from_str::<Wrapper>(too_many_bytes).unwrap();
412 6 :
413 6 : let serialized = serde_json::to_value(&wrapper_from_bytes).unwrap();
414 6 :
415 6 : assert_eq!(
416 6 : serialized,
417 6 : serde_json::json! {{
418 6 : "disk_consistent_lsn": "0/149FD90",
419 6 : "prev_record_lsn": "0/149FD18",
420 6 : "ancestor_timeline": null,
421 6 : "ancestor_lsn": "0/0",
422 6 : "latest_gc_cutoff_lsn": "0/149FD18",
423 6 : "initdb_lsn": "0/149FD18",
424 6 : "pg_version": 15
425 6 : }}
426 6 : );
427 :
428 6 : let wrapper_from_json = serde_json::value::from_value::<Wrapper>(serialized).unwrap();
429 6 :
430 6 : assert_eq!(wrapper_from_bytes.0, wrapper_from_json.0);
431 6 : }
432 : }
433 :
434 : /// Parts of the metadata which are regularly modified.
435 : pub(crate) struct MetadataUpdate {
436 : disk_consistent_lsn: Lsn,
437 : prev_record_lsn: Option<Lsn>,
438 : latest_gc_cutoff_lsn: Lsn,
439 : }
440 :
441 : impl MetadataUpdate {
442 3438 : pub(crate) fn new(
443 3438 : disk_consistent_lsn: Lsn,
444 3438 : prev_record_lsn: Option<Lsn>,
445 3438 : latest_gc_cutoff_lsn: Lsn,
446 3438 : ) -> Self {
447 3438 : Self {
448 3438 : disk_consistent_lsn,
449 3438 : prev_record_lsn,
450 3438 : latest_gc_cutoff_lsn,
451 3438 : }
452 3438 : }
453 : }
454 :
455 : #[cfg(test)]
456 : mod tests {
457 : use super::*;
458 : use crate::tenant::harness::TIMELINE_ID;
459 :
460 : #[test]
461 6 : fn metadata_serializes_correctly() {
462 6 : let original_metadata = TimelineMetadata::new(
463 6 : Lsn(0x200),
464 6 : Some(Lsn(0x100)),
465 6 : Some(TIMELINE_ID),
466 6 : Lsn(0),
467 6 : Lsn(0),
468 6 : Lsn(0),
469 6 : // Any version will do here, so use the default
470 6 : crate::DEFAULT_PG_VERSION,
471 6 : );
472 6 :
473 6 : let metadata_bytes = original_metadata
474 6 : .to_bytes()
475 6 : .expect("Should serialize correct metadata to bytes");
476 6 :
477 6 : let deserialized_metadata = TimelineMetadata::from_bytes(&metadata_bytes)
478 6 : .expect("Should deserialize its own bytes");
479 6 :
480 6 : assert_eq!(
481 : deserialized_metadata.body, original_metadata.body,
482 0 : "Metadata that was serialized to bytes and deserialized back should not change"
483 : );
484 6 : }
485 :
486 : // Generate old version metadata and read it with current code.
487 : // Ensure that it is upgraded correctly
488 : #[test]
489 6 : fn test_metadata_upgrade() {
490 6 : #[derive(Debug, Clone, PartialEq, Eq)]
491 6 : struct TimelineMetadataV1 {
492 6 : hdr: TimelineMetadataHeader,
493 6 : body: TimelineMetadataBodyV1,
494 6 : }
495 6 :
496 6 : let metadata_v1 = TimelineMetadataV1 {
497 6 : hdr: TimelineMetadataHeader {
498 6 : checksum: 0,
499 6 : size: 0,
500 6 : format_version: METADATA_OLD_FORMAT_VERSION,
501 6 : },
502 6 : body: TimelineMetadataBodyV1 {
503 6 : disk_consistent_lsn: Lsn(0x200),
504 6 : prev_record_lsn: Some(Lsn(0x100)),
505 6 : ancestor_timeline: Some(TIMELINE_ID),
506 6 : ancestor_lsn: Lsn(0),
507 6 : latest_gc_cutoff_lsn: Lsn(0),
508 6 : initdb_lsn: Lsn(0),
509 6 : },
510 6 : };
511 6 :
512 6 : impl TimelineMetadataV1 {
513 6 : pub fn to_bytes(&self) -> anyhow::Result<Vec<u8>> {
514 6 : let body_bytes = self.body.ser()?;
515 6 : let metadata_size = METADATA_HDR_SIZE + body_bytes.len();
516 6 : let hdr = TimelineMetadataHeader {
517 6 : size: metadata_size as u16,
518 6 : format_version: METADATA_OLD_FORMAT_VERSION,
519 6 : checksum: crc32c::crc32c(&body_bytes),
520 6 : };
521 6 : let hdr_bytes = hdr.ser()?;
522 6 : let mut metadata_bytes = vec![0u8; METADATA_MAX_SIZE];
523 6 : metadata_bytes[0..METADATA_HDR_SIZE].copy_from_slice(&hdr_bytes);
524 6 : metadata_bytes[METADATA_HDR_SIZE..metadata_size].copy_from_slice(&body_bytes);
525 6 : Ok(metadata_bytes)
526 6 : }
527 6 : }
528 6 :
529 6 : let metadata_bytes = metadata_v1
530 6 : .to_bytes()
531 6 : .expect("Should serialize correct metadata to bytes");
532 6 :
533 6 : // This should deserialize to the latest version format
534 6 : let deserialized_metadata = TimelineMetadata::from_bytes(&metadata_bytes)
535 6 : .expect("Should deserialize its own bytes");
536 6 :
537 6 : let expected_metadata = TimelineMetadata::new(
538 6 : Lsn(0x200),
539 6 : Some(Lsn(0x100)),
540 6 : Some(TIMELINE_ID),
541 6 : Lsn(0),
542 6 : Lsn(0),
543 6 : Lsn(0),
544 6 : 14, // All timelines created before this version had pg_version 14
545 6 : );
546 6 :
547 6 : assert_eq!(
548 : deserialized_metadata.body, expected_metadata.body,
549 0 : "Metadata of the old version {} should be upgraded to the latest version {}",
550 : METADATA_OLD_FORMAT_VERSION, METADATA_FORMAT_VERSION
551 : );
552 6 : }
553 :
554 : #[test]
555 6 : fn test_metadata_bincode_serde_ensure_roundtrip() {
556 6 : let original_metadata = TimelineMetadata::new(
557 6 : Lsn(0x200),
558 6 : Some(Lsn(0x100)),
559 6 : Some(TIMELINE_ID),
560 6 : Lsn(0),
561 6 : Lsn(0),
562 6 : Lsn(0),
563 6 : // Any version will do here, so use the default
564 6 : crate::DEFAULT_PG_VERSION,
565 6 : );
566 6 : let expected_bytes = vec![
567 6 : /* TimelineMetadataHeader */
568 6 : 74, 104, 158, 105, 0, 70, 0, 4, // checksum, size, format_version (4 + 2 + 2)
569 6 : /* TimelineMetadataBodyV2 */
570 6 : 0, 0, 0, 0, 0, 0, 2, 0, // disk_consistent_lsn (8 bytes)
571 6 : 1, 0, 0, 0, 0, 0, 0, 1, 0, // prev_record_lsn (9 bytes)
572 6 : 1, 17, 34, 51, 68, 85, 102, 119, 136, 17, 34, 51, 68, 85, 102, 119,
573 6 : 136, // ancestor_timeline (17 bytes)
574 6 : 0, 0, 0, 0, 0, 0, 0, 0, // ancestor_lsn (8 bytes)
575 6 : 0, 0, 0, 0, 0, 0, 0, 0, // latest_gc_cutoff_lsn (8 bytes)
576 6 : 0, 0, 0, 0, 0, 0, 0, 0, // initdb_lsn (8 bytes)
577 6 : 0, 0, 0, 16, // pg_version (4 bytes)
578 6 : /* padding bytes */
579 6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
580 6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
581 6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
582 6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
583 6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
584 6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
585 6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
586 6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
587 6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
588 6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
589 6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
590 6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
591 6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
592 6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
593 6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
594 6 : 0, 0, 0, 0, 0, 0, 0,
595 6 : ];
596 6 : let metadata_ser_bytes = original_metadata.to_bytes().unwrap();
597 6 : assert_eq!(metadata_ser_bytes, expected_bytes);
598 :
599 6 : let expected_metadata = {
600 6 : let mut temp_metadata = original_metadata;
601 6 : let body_bytes = temp_metadata
602 6 : .body
603 6 : .ser()
604 6 : .expect("Cannot serialize the metadata body");
605 6 : let metadata_size = METADATA_HDR_SIZE + body_bytes.len();
606 6 : let hdr = TimelineMetadataHeader {
607 6 : size: metadata_size as u16,
608 6 : format_version: METADATA_FORMAT_VERSION,
609 6 : checksum: crc32c::crc32c(&body_bytes),
610 6 : };
611 6 : temp_metadata.hdr = hdr;
612 6 : temp_metadata
613 6 : };
614 6 : let des_metadata = TimelineMetadata::from_bytes(&metadata_ser_bytes).unwrap();
615 6 : assert_eq!(des_metadata, expected_metadata);
616 6 : }
617 : }
|