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 52 : #[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 36 : fn try_from(value: &TimelineMetadataBodyV2) -> Result<Self, Self::Error> {
76 36 : #[derive(Default)]
77 36 : struct Crc32Sink {
78 36 : crc: u32,
79 36 : count: usize,
80 36 : }
81 36 :
82 36 : impl std::io::Write for Crc32Sink {
83 500 : fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
84 500 : self.crc = crc32c::crc32c_append(self.crc, buf);
85 500 : self.count += buf.len();
86 500 : Ok(buf.len())
87 500 : }
88 36 :
89 36 : fn flush(&mut self) -> std::io::Result<()> {
90 0 : Ok(())
91 0 : }
92 36 : }
93 36 :
94 36 : // jump through hoops to calculate the crc32 so that TimelineMetadata::ne works
95 36 : // across serialization versions
96 36 : let mut sink = Crc32Sink::default();
97 36 : <TimelineMetadataBodyV2 as utils::bin_ser::BeSer>::ser_into(value, &mut sink)
98 36 : .map_err(Crc32CalculationFailed)?;
99 :
100 36 : let size = METADATA_HDR_SIZE + sink.count;
101 36 :
102 36 : Ok(TimelineMetadataHeader {
103 36 : checksum: sink.crc,
104 36 : size: size as u16,
105 36 : format_version: METADATA_FORMAT_VERSION,
106 36 : })
107 36 : }
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 288 : #[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 2 : #[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 426 : pub fn new(
159 426 : disk_consistent_lsn: Lsn,
160 426 : prev_record_lsn: Option<Lsn>,
161 426 : ancestor_timeline: Option<TimelineId>,
162 426 : ancestor_lsn: Lsn,
163 426 : latest_gc_cutoff_lsn: Lsn,
164 426 : initdb_lsn: Lsn,
165 426 : pg_version: u32,
166 426 : ) -> Self {
167 426 : Self {
168 426 : hdr: TimelineMetadataHeader {
169 426 : checksum: 0,
170 426 : size: 0,
171 426 : format_version: METADATA_FORMAT_VERSION,
172 426 : },
173 426 : body: TimelineMetadataBodyV2 {
174 426 : disk_consistent_lsn,
175 426 : prev_record_lsn,
176 426 : ancestor_timeline,
177 426 : ancestor_lsn,
178 426 : latest_gc_cutoff_lsn,
179 426 : initdb_lsn,
180 426 : pg_version,
181 426 : },
182 426 : }
183 426 : }
184 :
185 : #[cfg(test)]
186 6 : pub(crate) fn with_recalculated_checksum(mut self) -> anyhow::Result<Self> {
187 6 : self.hdr = TimelineMetadataHeader::try_from(&self.body)?;
188 6 : Ok(self)
189 6 : }
190 :
191 2 : fn upgrade_timeline_metadata(metadata_bytes: &[u8]) -> anyhow::Result<Self> {
192 2 : let mut hdr = TimelineMetadataHeader::des(&metadata_bytes[0..METADATA_HDR_SIZE])?;
193 :
194 : // backward compatible only up to this version
195 2 : ensure!(
196 2 : hdr.format_version == METADATA_OLD_FORMAT_VERSION,
197 0 : "unsupported metadata format version {}",
198 : hdr.format_version
199 : );
200 :
201 2 : let metadata_size = hdr.size as usize;
202 :
203 2 : let body: TimelineMetadataBodyV1 =
204 2 : TimelineMetadataBodyV1::des(&metadata_bytes[METADATA_HDR_SIZE..metadata_size])?;
205 :
206 2 : let body = TimelineMetadataBodyV2 {
207 2 : disk_consistent_lsn: body.disk_consistent_lsn,
208 2 : prev_record_lsn: body.prev_record_lsn,
209 2 : ancestor_timeline: body.ancestor_timeline,
210 2 : ancestor_lsn: body.ancestor_lsn,
211 2 : latest_gc_cutoff_lsn: body.latest_gc_cutoff_lsn,
212 2 : initdb_lsn: body.initdb_lsn,
213 2 : pg_version: 14, // All timelines created before this version had pg_version 14
214 2 : };
215 2 :
216 2 : hdr.format_version = METADATA_FORMAT_VERSION;
217 2 :
218 2 : Ok(Self { hdr, body })
219 2 : }
220 :
221 50 : pub fn from_bytes(metadata_bytes: &[u8]) -> anyhow::Result<Self> {
222 50 : ensure!(
223 50 : metadata_bytes.len() == METADATA_MAX_SIZE,
224 0 : "metadata bytes size is wrong"
225 : );
226 50 : let hdr = TimelineMetadataHeader::des(&metadata_bytes[0..METADATA_HDR_SIZE])?;
227 :
228 50 : let metadata_size = hdr.size as usize;
229 50 : ensure!(
230 50 : metadata_size <= METADATA_MAX_SIZE,
231 0 : "corrupted metadata file"
232 : );
233 50 : let calculated_checksum = crc32c::crc32c(&metadata_bytes[METADATA_HDR_SIZE..metadata_size]);
234 50 : ensure!(
235 50 : hdr.checksum == calculated_checksum,
236 0 : "metadata checksum mismatch"
237 : );
238 :
239 50 : if hdr.format_version != METADATA_FORMAT_VERSION {
240 : // If metadata has the old format,
241 : // upgrade it and return the result
242 2 : TimelineMetadata::upgrade_timeline_metadata(metadata_bytes)
243 : } else {
244 48 : let body =
245 48 : TimelineMetadataBodyV2::des(&metadata_bytes[METADATA_HDR_SIZE..metadata_size])?;
246 48 : ensure!(
247 48 : body.disk_consistent_lsn.is_aligned(),
248 0 : "disk_consistent_lsn is not aligned"
249 : );
250 48 : Ok(TimelineMetadata { hdr, body })
251 : }
252 50 : }
253 :
254 18 : pub fn to_bytes(&self) -> Result<Vec<u8>, SerializeError> {
255 18 : let body_bytes = self.body.ser()?;
256 18 : let metadata_size = METADATA_HDR_SIZE + body_bytes.len();
257 18 : let hdr = TimelineMetadataHeader {
258 18 : size: metadata_size as u16,
259 18 : format_version: METADATA_FORMAT_VERSION,
260 18 : checksum: crc32c::crc32c(&body_bytes),
261 18 : };
262 18 : let hdr_bytes = hdr.ser()?;
263 18 : let mut metadata_bytes = vec![0u8; METADATA_MAX_SIZE];
264 18 : metadata_bytes[0..METADATA_HDR_SIZE].copy_from_slice(&hdr_bytes);
265 18 : metadata_bytes[METADATA_HDR_SIZE..metadata_size].copy_from_slice(&body_bytes);
266 18 : Ok(metadata_bytes)
267 18 : }
268 :
269 : /// [`Lsn`] that corresponds to the corresponding timeline directory
270 : /// contents, stored locally in the pageserver workdir.
271 21192 : pub fn disk_consistent_lsn(&self) -> Lsn {
272 21192 : self.body.disk_consistent_lsn
273 21192 : }
274 :
275 406 : pub fn prev_record_lsn(&self) -> Option<Lsn> {
276 406 : self.body.prev_record_lsn
277 406 : }
278 :
279 418 : pub fn ancestor_timeline(&self) -> Option<TimelineId> {
280 418 : self.body.ancestor_timeline
281 418 : }
282 :
283 634 : pub fn ancestor_lsn(&self) -> Lsn {
284 634 : self.body.ancestor_lsn
285 634 : }
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 406 : pub fn latest_gc_cutoff_lsn(&self) -> Lsn {
309 406 : self.body.latest_gc_cutoff_lsn
310 406 : }
311 :
312 406 : pub fn initdb_lsn(&self) -> Lsn {
313 406 : self.body.initdb_lsn
314 406 : }
315 :
316 406 : pub fn pg_version(&self) -> u32 {
317 406 : self.body.pg_version
318 406 : }
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 12 : pub fn example() -> Self {
324 12 : let instance = Self::new(
325 12 : "0/16960E8".parse::<Lsn>().unwrap(),
326 12 : None,
327 12 : None,
328 12 : Lsn::from_hex("00000000").unwrap(),
329 12 : Lsn::from_hex("00000000").unwrap(),
330 12 : Lsn::from_hex("00000000").unwrap(),
331 12 : 0,
332 12 : );
333 12 : let bytes = instance.to_bytes().unwrap();
334 12 : Self::from_bytes(&bytes).unwrap()
335 12 : }
336 :
337 1140 : pub(crate) fn apply(&mut self, update: &MetadataUpdate) {
338 1140 : self.body.disk_consistent_lsn = update.disk_consistent_lsn;
339 1140 : self.body.prev_record_lsn = update.prev_record_lsn;
340 1140 : self.body.latest_gc_cutoff_lsn = update.latest_gc_cutoff_lsn;
341 1140 : }
342 : }
343 :
344 : pub(crate) mod modern_serde {
345 : use super::{TimelineMetadata, TimelineMetadataBodyV2, TimelineMetadataHeader};
346 : use serde::{Deserialize, Serialize};
347 :
348 46 : pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<TimelineMetadata, D::Error>
349 46 : where
350 46 : D: serde::de::Deserializer<'de>,
351 46 : {
352 46 : // for legacy reasons versions 1-5 had TimelineMetadata serialized as a Vec<u8> field with
353 46 : // BeSer.
354 46 : struct Visitor;
355 46 :
356 46 : impl<'d> serde::de::Visitor<'d> for Visitor {
357 46 : type Value = TimelineMetadata;
358 46 :
359 46 : fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
360 0 : f.write_str("BeSer bytes or json structure")
361 0 : }
362 46 :
363 46 : fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
364 16 : where
365 16 : A: serde::de::SeqAccess<'d>,
366 16 : {
367 16 : use serde::de::Error;
368 16 : let de = serde::de::value::SeqAccessDeserializer::new(seq);
369 16 : Vec::<u8>::deserialize(de)
370 16 : .map(|v| TimelineMetadata::from_bytes(&v).map_err(A::Error::custom))?
371 46 : }
372 46 :
373 46 : fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
374 30 : where
375 30 : A: serde::de::MapAccess<'d>,
376 30 : {
377 30 : use serde::de::Error;
378 30 :
379 30 : let de = serde::de::value::MapAccessDeserializer::new(map);
380 46 : let body = TimelineMetadataBodyV2::deserialize(de)?;
381 46 : let hdr = TimelineMetadataHeader::try_from(&body).map_err(A::Error::custom)?;
382 46 :
383 46 : Ok(TimelineMetadata { hdr, body })
384 46 : }
385 46 : }
386 46 :
387 46 : deserializer.deserialize_any(Visitor)
388 46 : }
389 :
390 2868 : pub(crate) fn serialize<S>(
391 2868 : metadata: &TimelineMetadata,
392 2868 : serializer: S,
393 2868 : ) -> Result<S::Ok, S::Error>
394 2868 : where
395 2868 : S: serde::Serializer,
396 2868 : {
397 2868 : // header is not needed, upon reading we've upgraded all v1 to v2
398 2868 : metadata.body.serialize(serializer)
399 2868 : }
400 :
401 : #[test]
402 2 : fn deserializes_bytes_as_well_as_equivalent_body_v2() {
403 4 : #[derive(serde::Deserialize, serde::Serialize)]
404 2 : struct Wrapper(
405 2 : #[serde(deserialize_with = "deserialize", serialize_with = "serialize")]
406 2 : TimelineMetadata,
407 2 : );
408 2 :
409 2 : 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 2 :
411 2 : let wrapper_from_bytes = serde_json::from_str::<Wrapper>(too_many_bytes).unwrap();
412 2 :
413 2 : let serialized = serde_json::to_value(&wrapper_from_bytes).unwrap();
414 2 :
415 2 : assert_eq!(
416 2 : serialized,
417 2 : serde_json::json! {{
418 2 : "disk_consistent_lsn": "0/149FD90",
419 2 : "prev_record_lsn": "0/149FD18",
420 2 : "ancestor_timeline": null,
421 2 : "ancestor_lsn": "0/0",
422 2 : "latest_gc_cutoff_lsn": "0/149FD18",
423 2 : "initdb_lsn": "0/149FD18",
424 2 : "pg_version": 15
425 2 : }}
426 2 : );
427 :
428 2 : let wrapper_from_json = serde_json::value::from_value::<Wrapper>(serialized).unwrap();
429 2 :
430 2 : assert_eq!(wrapper_from_bytes.0, wrapper_from_json.0);
431 2 : }
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 1140 : pub(crate) fn new(
443 1140 : disk_consistent_lsn: Lsn,
444 1140 : prev_record_lsn: Option<Lsn>,
445 1140 : latest_gc_cutoff_lsn: Lsn,
446 1140 : ) -> Self {
447 1140 : Self {
448 1140 : disk_consistent_lsn,
449 1140 : prev_record_lsn,
450 1140 : latest_gc_cutoff_lsn,
451 1140 : }
452 1140 : }
453 : }
454 :
455 : #[cfg(test)]
456 : mod tests {
457 : use super::*;
458 : use crate::tenant::harness::TIMELINE_ID;
459 :
460 : #[test]
461 2 : fn metadata_serializes_correctly() {
462 2 : let original_metadata = TimelineMetadata::new(
463 2 : Lsn(0x200),
464 2 : Some(Lsn(0x100)),
465 2 : Some(TIMELINE_ID),
466 2 : Lsn(0),
467 2 : Lsn(0),
468 2 : Lsn(0),
469 2 : // Any version will do here, so use the default
470 2 : crate::DEFAULT_PG_VERSION,
471 2 : );
472 2 :
473 2 : let metadata_bytes = original_metadata
474 2 : .to_bytes()
475 2 : .expect("Should serialize correct metadata to bytes");
476 2 :
477 2 : let deserialized_metadata = TimelineMetadata::from_bytes(&metadata_bytes)
478 2 : .expect("Should deserialize its own bytes");
479 2 :
480 2 : 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 2 : }
485 :
486 : // Generate old version metadata and read it with current code.
487 : // Ensure that it is upgraded correctly
488 : #[test]
489 2 : fn test_metadata_upgrade() {
490 2 : #[derive(Debug, Clone, PartialEq, Eq)]
491 2 : struct TimelineMetadataV1 {
492 2 : hdr: TimelineMetadataHeader,
493 2 : body: TimelineMetadataBodyV1,
494 2 : }
495 2 :
496 2 : let metadata_v1 = TimelineMetadataV1 {
497 2 : hdr: TimelineMetadataHeader {
498 2 : checksum: 0,
499 2 : size: 0,
500 2 : format_version: METADATA_OLD_FORMAT_VERSION,
501 2 : },
502 2 : body: TimelineMetadataBodyV1 {
503 2 : disk_consistent_lsn: Lsn(0x200),
504 2 : prev_record_lsn: Some(Lsn(0x100)),
505 2 : ancestor_timeline: Some(TIMELINE_ID),
506 2 : ancestor_lsn: Lsn(0),
507 2 : latest_gc_cutoff_lsn: Lsn(0),
508 2 : initdb_lsn: Lsn(0),
509 2 : },
510 2 : };
511 2 :
512 2 : impl TimelineMetadataV1 {
513 2 : pub fn to_bytes(&self) -> anyhow::Result<Vec<u8>> {
514 2 : let body_bytes = self.body.ser()?;
515 2 : let metadata_size = METADATA_HDR_SIZE + body_bytes.len();
516 2 : let hdr = TimelineMetadataHeader {
517 2 : size: metadata_size as u16,
518 2 : format_version: METADATA_OLD_FORMAT_VERSION,
519 2 : checksum: crc32c::crc32c(&body_bytes),
520 2 : };
521 2 : let hdr_bytes = hdr.ser()?;
522 2 : let mut metadata_bytes = vec![0u8; METADATA_MAX_SIZE];
523 2 : metadata_bytes[0..METADATA_HDR_SIZE].copy_from_slice(&hdr_bytes);
524 2 : metadata_bytes[METADATA_HDR_SIZE..metadata_size].copy_from_slice(&body_bytes);
525 2 : Ok(metadata_bytes)
526 2 : }
527 2 : }
528 2 :
529 2 : let metadata_bytes = metadata_v1
530 2 : .to_bytes()
531 2 : .expect("Should serialize correct metadata to bytes");
532 2 :
533 2 : // This should deserialize to the latest version format
534 2 : let deserialized_metadata = TimelineMetadata::from_bytes(&metadata_bytes)
535 2 : .expect("Should deserialize its own bytes");
536 2 :
537 2 : let expected_metadata = TimelineMetadata::new(
538 2 : Lsn(0x200),
539 2 : Some(Lsn(0x100)),
540 2 : Some(TIMELINE_ID),
541 2 : Lsn(0),
542 2 : Lsn(0),
543 2 : Lsn(0),
544 2 : 14, // All timelines created before this version had pg_version 14
545 2 : );
546 2 :
547 2 : 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 2 : }
553 :
554 : #[test]
555 2 : fn test_metadata_bincode_serde_ensure_roundtrip() {
556 2 : let original_metadata = TimelineMetadata::new(
557 2 : Lsn(0x200),
558 2 : Some(Lsn(0x100)),
559 2 : Some(TIMELINE_ID),
560 2 : Lsn(0),
561 2 : Lsn(0),
562 2 : Lsn(0),
563 2 : // Any version will do here, so use the default
564 2 : crate::DEFAULT_PG_VERSION,
565 2 : );
566 2 : let expected_bytes = vec![
567 2 : /* TimelineMetadataHeader */
568 2 : 74, 104, 158, 105, 0, 70, 0, 4, // checksum, size, format_version (4 + 2 + 2)
569 2 : /* TimelineMetadataBodyV2 */
570 2 : 0, 0, 0, 0, 0, 0, 2, 0, // disk_consistent_lsn (8 bytes)
571 2 : 1, 0, 0, 0, 0, 0, 0, 1, 0, // prev_record_lsn (9 bytes)
572 2 : 1, 17, 34, 51, 68, 85, 102, 119, 136, 17, 34, 51, 68, 85, 102, 119,
573 2 : 136, // ancestor_timeline (17 bytes)
574 2 : 0, 0, 0, 0, 0, 0, 0, 0, // ancestor_lsn (8 bytes)
575 2 : 0, 0, 0, 0, 0, 0, 0, 0, // latest_gc_cutoff_lsn (8 bytes)
576 2 : 0, 0, 0, 0, 0, 0, 0, 0, // initdb_lsn (8 bytes)
577 2 : 0, 0, 0, 16, // pg_version (4 bytes)
578 2 : /* padding bytes */
579 2 : 0, 0, 0, 0, 0, 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 2 : 0, 0, 0, 0, 0, 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 2 : 0, 0, 0, 0, 0, 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 2 : 0, 0, 0, 0, 0, 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 2 : 0, 0, 0, 0, 0, 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 2 : 0, 0, 0, 0, 0, 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 2 : 0, 0, 0, 0, 0, 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 2 : 0, 0, 0, 0, 0, 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 2 : 0, 0, 0, 0, 0, 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 2 : 0, 0, 0, 0, 0, 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 2 : 0, 0, 0, 0, 0, 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 2 : 0, 0, 0, 0, 0, 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 2 : 0, 0, 0, 0, 0, 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 2 : 0, 0, 0, 0, 0, 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 2 : 0, 0, 0, 0, 0, 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 2 : 0, 0, 0, 0, 0, 0, 0,
595 2 : ];
596 2 : let metadata_ser_bytes = original_metadata.to_bytes().unwrap();
597 2 : assert_eq!(metadata_ser_bytes, expected_bytes);
598 :
599 2 : let expected_metadata = {
600 2 : let mut temp_metadata = original_metadata;
601 2 : let body_bytes = temp_metadata
602 2 : .body
603 2 : .ser()
604 2 : .expect("Cannot serialize the metadata body");
605 2 : let metadata_size = METADATA_HDR_SIZE + body_bytes.len();
606 2 : let hdr = TimelineMetadataHeader {
607 2 : size: metadata_size as u16,
608 2 : format_version: METADATA_FORMAT_VERSION,
609 2 : checksum: crc32c::crc32c(&body_bytes),
610 2 : };
611 2 : temp_metadata.hdr = hdr;
612 2 : temp_metadata
613 2 : };
614 2 : let des_metadata = TimelineMetadata::from_bytes(&metadata_ser_bytes).unwrap();
615 2 : assert_eq!(des_metadata, expected_metadata);
616 2 : }
617 : }
|