LCOV - code coverage report
Current view: top level - pageserver/src/tenant - metadata.rs (source / functions) Coverage Total Hit
Test: 472031e0b71f3195f7f21b1f2b20de09fd07bb56.info Lines: 92.4 % 369 341
Test Date: 2025-05-26 10:37:33 Functions: 58.2 % 67 39

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

Generated by: LCOV version 2.1-beta