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