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