LCOV - code coverage report
Current view: top level - libs/pageserver_api/src - key.rs (source / functions) Coverage Total Hit
Test: fc67f8dc6087a0b4f4f0bcd74f6e1dc25fab8cf3.info Lines: 64.1 % 449 288
Test Date: 2024-09-24 13:57:57 Functions: 61.4 % 57 35

            Line data    Source code
       1              : use anyhow::{bail, Result};
       2              : use byteorder::{ByteOrder, BE};
       3              : use postgres_ffi::relfile_utils::{FSM_FORKNUM, VISIBILITYMAP_FORKNUM};
       4              : use postgres_ffi::Oid;
       5              : use postgres_ffi::RepOriginId;
       6              : use serde::{Deserialize, Serialize};
       7              : use std::{fmt, ops::Range};
       8              : 
       9              : use crate::reltag::{BlockNumber, RelTag, SlruKind};
      10              : 
      11              : /// Key used in the Repository kv-store.
      12              : ///
      13              : /// The Repository treats this as an opaque struct, but see the code in pgdatadir_mapping.rs
      14              : /// for what we actually store in these fields.
      15         6912 : #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd, Serialize, Deserialize)]
      16              : pub struct Key {
      17              :     pub field1: u8,
      18              :     pub field2: u32,
      19              :     pub field3: u32,
      20              :     pub field4: u32,
      21              :     pub field5: u8,
      22              :     pub field6: u32,
      23              : }
      24              : 
      25              : /// When working with large numbers of Keys in-memory, it is more efficient to handle them as i128 than as
      26              : /// a struct of fields.
      27              : #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
      28              : pub struct CompactKey(i128);
      29              : 
      30              : /// The storage key size.
      31              : pub const KEY_SIZE: usize = 18;
      32              : 
      33              : /// The metadata key size. 2B fewer than the storage key size because field2 is not fully utilized.
      34              : /// See [`Key::to_i128`] for more information on the encoding.
      35              : pub const METADATA_KEY_SIZE: usize = 16;
      36              : 
      37              : /// The key prefix start range for the metadata keys. All keys with the first byte >= 0x60 is a metadata key.
      38              : pub const METADATA_KEY_BEGIN_PREFIX: u8 = 0x60;
      39              : pub const METADATA_KEY_END_PREFIX: u8 = 0x7F;
      40              : 
      41              : /// The (reserved) key prefix of relation sizes.
      42              : pub const RELATION_SIZE_PREFIX: u8 = 0x61;
      43              : 
      44              : /// The key prefix of AUX file keys.
      45              : pub const AUX_KEY_PREFIX: u8 = 0x62;
      46              : 
      47              : /// The key prefix of ReplOrigin keys.
      48              : pub const REPL_ORIGIN_KEY_PREFIX: u8 = 0x63;
      49              : 
      50              : /// Check if the key falls in the range of metadata keys.
      51          122 : pub const fn is_metadata_key_slice(key: &[u8]) -> bool {
      52          122 :     key[0] >= METADATA_KEY_BEGIN_PREFIX && key[0] < METADATA_KEY_END_PREFIX
      53          122 : }
      54              : 
      55              : impl Key {
      56              :     /// Check if the key falls in the range of metadata keys.
      57          199 :     pub const fn is_metadata_key(&self) -> bool {
      58          199 :         self.field1 >= METADATA_KEY_BEGIN_PREFIX && self.field1 < METADATA_KEY_END_PREFIX
      59          199 :     }
      60              : 
      61              :     /// Encode a metadata key to a storage key.
      62          121 :     pub fn from_metadata_key_fixed_size(key: &[u8; METADATA_KEY_SIZE]) -> Self {
      63          121 :         assert!(is_metadata_key_slice(key), "key not in metadata key range");
      64              :         // Metadata key space ends at 0x7F so it's fine to directly convert it to i128.
      65          121 :         Self::from_i128(i128::from_be_bytes(*key))
      66          121 :     }
      67              : 
      68              :     /// Encode a metadata key to a storage key.
      69            1 :     pub fn from_metadata_key(key: &[u8]) -> Self {
      70            1 :         Self::from_metadata_key_fixed_size(key.try_into().expect("expect 16 byte metadata key"))
      71            1 :     }
      72              : 
      73              :     /// Get the range of metadata keys.
      74         3468 :     pub const fn metadata_key_range() -> Range<Self> {
      75         3468 :         Key {
      76         3468 :             field1: METADATA_KEY_BEGIN_PREFIX,
      77         3468 :             field2: 0,
      78         3468 :             field3: 0,
      79         3468 :             field4: 0,
      80         3468 :             field5: 0,
      81         3468 :             field6: 0,
      82         3468 :         }..Key {
      83         3468 :             field1: METADATA_KEY_END_PREFIX,
      84         3468 :             field2: 0,
      85         3468 :             field3: 0,
      86         3468 :             field4: 0,
      87         3468 :             field5: 0,
      88         3468 :             field6: 0,
      89         3468 :         }
      90         3468 :     }
      91              : 
      92              :     /// Get the range of aux keys.
      93          948 :     pub fn metadata_aux_key_range() -> Range<Self> {
      94          948 :         Key {
      95          948 :             field1: AUX_KEY_PREFIX,
      96          948 :             field2: 0,
      97          948 :             field3: 0,
      98          948 :             field4: 0,
      99          948 :             field5: 0,
     100          948 :             field6: 0,
     101          948 :         }..Key {
     102          948 :             field1: AUX_KEY_PREFIX + 1,
     103          948 :             field2: 0,
     104          948 :             field3: 0,
     105          948 :             field4: 0,
     106          948 :             field5: 0,
     107          948 :             field6: 0,
     108          948 :         }
     109          948 :     }
     110              : 
     111              :     /// This function checks more extensively what keys we can take on the write path.
     112              :     /// If a key beginning with 00 does not have a global/default tablespace OID, it
     113              :     /// will be rejected on the write path.
     114              :     #[allow(dead_code)]
     115            0 :     pub fn is_valid_key_on_write_path_strong(&self) -> bool {
     116              :         use postgres_ffi::pg_constants::{DEFAULTTABLESPACE_OID, GLOBALTABLESPACE_OID};
     117            0 :         if !self.is_i128_representable() {
     118            0 :             return false;
     119            0 :         }
     120            0 :         if self.field1 == 0
     121            0 :             && !(self.field2 == GLOBALTABLESPACE_OID
     122            0 :                 || self.field2 == DEFAULTTABLESPACE_OID
     123            0 :                 || self.field2 == 0)
     124              :         {
     125            0 :             return false; // User defined tablespaces are not supported
     126            0 :         }
     127            0 :         true
     128            0 :     }
     129              : 
     130              :     /// This is a weaker version of `is_valid_key_on_write_path_strong` that simply
     131              :     /// checks if the key is i128 representable. Note that some keys can be successfully
     132              :     /// ingested into the pageserver, but will cause errors on generating basebackup.
     133     14013072 :     pub fn is_valid_key_on_write_path(&self) -> bool {
     134     14013072 :         self.is_i128_representable()
     135     14013072 :     }
     136              : 
     137     48483896 :     pub fn is_i128_representable(&self) -> bool {
     138     48483896 :         self.field2 <= 0xFFFF || self.field2 == 0xFFFFFFFF || self.field2 == 0x22222222
     139     48483896 :     }
     140              : 
     141              :     /// 'field2' is used to store tablespaceid for relations and small enum numbers for other relish.
     142              :     /// As long as Neon does not support tablespace (because of lack of access to local file system),
     143              :     /// we can assume that only some predefined namespace OIDs are used which can fit in u16
     144     34470824 :     pub fn to_i128(&self) -> i128 {
     145     34470824 :         assert!(self.is_i128_representable(), "invalid key: {self}");
     146     34470824 :         (((self.field1 & 0x7F) as i128) << 120)
     147     34470824 :             | (((self.field2 & 0xFFFF) as i128) << 104)
     148     34470824 :             | ((self.field3 as i128) << 72)
     149     34470824 :             | ((self.field4 as i128) << 40)
     150     34470824 :             | ((self.field5 as i128) << 32)
     151     34470824 :             | self.field6 as i128
     152     34470824 :     }
     153              : 
     154     16378078 :     pub const fn from_i128(x: i128) -> Self {
     155     16378078 :         Key {
     156     16378078 :             field1: ((x >> 120) & 0x7F) as u8,
     157     16378078 :             field2: ((x >> 104) & 0xFFFF) as u32,
     158     16378078 :             field3: (x >> 72) as u32,
     159     16378078 :             field4: (x >> 40) as u32,
     160     16378078 :             field5: (x >> 32) as u8,
     161     16378078 :             field6: x as u32,
     162     16378078 :         }
     163     16378078 :     }
     164              : 
     165     19806934 :     pub fn to_compact(&self) -> CompactKey {
     166     19806934 :         CompactKey(self.to_i128())
     167     19806934 :     }
     168              : 
     169     14653750 :     pub fn from_compact(k: CompactKey) -> Self {
     170     14653750 :         Self::from_i128(k.0)
     171     14653750 :     }
     172              : 
     173     26526897 :     pub const fn next(&self) -> Key {
     174     26526897 :         self.add(1)
     175     26526897 :     }
     176              : 
     177     26541189 :     pub const fn add(&self, x: u32) -> Key {
     178     26541189 :         let mut key = *self;
     179     26541189 : 
     180     26541189 :         let r = key.field6.overflowing_add(x);
     181     26541189 :         key.field6 = r.0;
     182     26541189 :         if r.1 {
     183      2481285 :             let r = key.field5.overflowing_add(1);
     184      2481285 :             key.field5 = r.0;
     185      2481285 :             if r.1 {
     186            0 :                 let r = key.field4.overflowing_add(1);
     187            0 :                 key.field4 = r.0;
     188            0 :                 if r.1 {
     189            0 :                     let r = key.field3.overflowing_add(1);
     190            0 :                     key.field3 = r.0;
     191            0 :                     if r.1 {
     192            0 :                         let r = key.field2.overflowing_add(1);
     193            0 :                         key.field2 = r.0;
     194            0 :                         if r.1 {
     195            0 :                             let r = key.field1.overflowing_add(1);
     196            0 :                             key.field1 = r.0;
     197            0 :                             assert!(!r.1);
     198            0 :                         }
     199            0 :                     }
     200            0 :                 }
     201      2481285 :             }
     202     24059904 :         }
     203     26541189 :         key
     204     26541189 :     }
     205              : 
     206              :     /// Convert a 18B slice to a key. This function should not be used for 16B metadata keys because `field2` is handled differently.
     207              :     /// Use [`Key::from_i128`] instead if you want to handle 16B keys (i.e., metadata keys). There are some restrictions on `field2`,
     208              :     /// and therefore not all 18B slices are valid page server keys.
     209     17614002 :     pub fn from_slice(b: &[u8]) -> Self {
     210     17614002 :         Key {
     211     17614002 :             field1: b[0],
     212     17614002 :             field2: u32::from_be_bytes(b[1..5].try_into().unwrap()),
     213     17614002 :             field3: u32::from_be_bytes(b[5..9].try_into().unwrap()),
     214     17614002 :             field4: u32::from_be_bytes(b[9..13].try_into().unwrap()),
     215     17614002 :             field5: b[13],
     216     17614002 :             field6: u32::from_be_bytes(b[14..18].try_into().unwrap()),
     217     17614002 :         }
     218     17614002 :     }
     219              : 
     220              :     /// Convert a key to a 18B slice. This function should not be used for getting a 16B metadata key because `field2` is handled differently.
     221              :     /// Use [`Key::to_i128`] instead if you want to get a 16B key (i.e., metadata keys).
     222     21880772 :     pub fn write_to_byte_slice(&self, buf: &mut [u8]) {
     223     21880772 :         buf[0] = self.field1;
     224     21880772 :         BE::write_u32(&mut buf[1..5], self.field2);
     225     21880772 :         BE::write_u32(&mut buf[5..9], self.field3);
     226     21880772 :         BE::write_u32(&mut buf[9..13], self.field4);
     227     21880772 :         buf[13] = self.field5;
     228     21880772 :         BE::write_u32(&mut buf[14..18], self.field6);
     229     21880772 :     }
     230              : }
     231              : 
     232              : impl fmt::Display for Key {
     233      1124755 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     234      1124755 :         write!(
     235      1124755 :             f,
     236      1124755 :             "{:02X}{:08X}{:08X}{:08X}{:02X}{:08X}",
     237      1124755 :             self.field1, self.field2, self.field3, self.field4, self.field5, self.field6
     238      1124755 :         )
     239      1124755 :     }
     240              : }
     241              : 
     242              : impl fmt::Display for CompactKey {
     243            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     244            0 :         let k = Key::from_compact(*self);
     245            0 :         k.fmt(f)
     246            0 :     }
     247              : }
     248              : 
     249              : impl Key {
     250              :     pub const MIN: Key = Key {
     251              :         field1: u8::MIN,
     252              :         field2: u32::MIN,
     253              :         field3: u32::MIN,
     254              :         field4: u32::MIN,
     255              :         field5: u8::MIN,
     256              :         field6: u32::MIN,
     257              :     };
     258              :     pub const MAX: Key = Key {
     259              :         field1: u8::MAX,
     260              :         field2: u32::MAX,
     261              :         field3: u32::MAX,
     262              :         field4: u32::MAX,
     263              :         field5: u8::MAX,
     264              :         field6: u32::MAX,
     265              :     };
     266              : 
     267       115637 :     pub fn from_hex(s: &str) -> Result<Self> {
     268       115637 :         if s.len() != 36 {
     269            4 :             bail!("parse error");
     270       115633 :         }
     271       115633 :         Ok(Key {
     272       115633 :             field1: u8::from_str_radix(&s[0..2], 16)?,
     273       115633 :             field2: u32::from_str_radix(&s[2..10], 16)?,
     274       115633 :             field3: u32::from_str_radix(&s[10..18], 16)?,
     275       115633 :             field4: u32::from_str_radix(&s[18..26], 16)?,
     276       115633 :             field5: u8::from_str_radix(&s[26..28], 16)?,
     277       115633 :             field6: u32::from_str_radix(&s[28..36], 16)?,
     278              :         })
     279       115637 :     }
     280              : }
     281              : 
     282              : // Layout of the Key address space
     283              : //
     284              : // The Key struct, used to address the underlying key-value store, consists of
     285              : // 18 bytes, split into six fields. See 'Key' in repository.rs. We need to map
     286              : // all the data and metadata keys into those 18 bytes.
     287              : //
     288              : // Principles for the mapping:
     289              : //
     290              : // - Things that are often accessed or modified together, should be close to
     291              : //   each other in the key space. For example, if a relation is extended by one
     292              : //   block, we create a new key-value pair for the block data, and update the
     293              : //   relation size entry. Because of that, the RelSize key comes after all the
     294              : //   RelBlocks of a relation: the RelSize and the last RelBlock are always next
     295              : //   to each other.
     296              : //
     297              : // The key space is divided into four major sections, identified by the first
     298              : // byte, and the form a hierarchy:
     299              : //
     300              : // 00 Relation data and metadata
     301              : //
     302              : //   DbDir    () -> (dbnode, spcnode)
     303              : //   Filenodemap
     304              : //   RelDir   -> relnode forknum
     305              : //       RelBlocks
     306              : //       RelSize
     307              : //
     308              : // 01 SLRUs
     309              : //
     310              : //   SlruDir  kind
     311              : //   SlruSegBlocks segno
     312              : //   SlruSegSize
     313              : //
     314              : // 02 pg_twophase
     315              : //
     316              : // 03 misc
     317              : //    Controlfile
     318              : //    checkpoint
     319              : //    pg_version
     320              : //
     321              : // 04 aux files
     322              : //
     323              : // Below is a full list of the keyspace allocation:
     324              : //
     325              : // DbDir:
     326              : // 00 00000000 00000000 00000000 00   00000000
     327              : //
     328              : // Filenodemap:
     329              : // 00 SPCNODE  DBNODE   00000000 00   00000000
     330              : //
     331              : // RelDir:
     332              : // 00 SPCNODE  DBNODE   00000000 00   00000001 (Postgres never uses relfilenode 0)
     333              : //
     334              : // RelBlock:
     335              : // 00 SPCNODE  DBNODE   RELNODE  FORK BLKNUM
     336              : //
     337              : // RelSize:
     338              : // 00 SPCNODE  DBNODE   RELNODE  FORK FFFFFFFF
     339              : //
     340              : // SlruDir:
     341              : // 01 kind     00000000 00000000 00   00000000
     342              : //
     343              : // SlruSegBlock:
     344              : // 01 kind     00000001 SEGNO    00   BLKNUM
     345              : //
     346              : // SlruSegSize:
     347              : // 01 kind     00000001 SEGNO    00   FFFFFFFF
     348              : //
     349              : // TwoPhaseDir:
     350              : // 02 00000000 00000000 00000000 00   00000000
     351              : //
     352              : // TwoPhaseFile:
     353              : //
     354              : // 02 00000000 00000000 00XXXXXX XX   XXXXXXXX
     355              : //
     356              : //                        \______XID_________/
     357              : //
     358              : // The 64-bit XID is stored a little awkwardly in field6, field5 and
     359              : // field4. PostgreSQL v16 and below only stored a 32-bit XID, which
     360              : // fit completely in field6, but starting with PostgreSQL v17, a full
     361              : // 64-bit XID is used. Most pageserver code that accesses
     362              : // TwoPhaseFiles now deals with 64-bit XIDs even on v16, the high bits
     363              : // are just unused.
     364              : //
     365              : // ControlFile:
     366              : // 03 00000000 00000000 00000000 00   00000000
     367              : //
     368              : // Checkpoint:
     369              : // 03 00000000 00000000 00000000 00   00000001
     370              : //
     371              : // AuxFiles:
     372              : // 03 00000000 00000000 00000000 00   00000002
     373              : //
     374              : 
     375              : //-- Section 01: relation data and metadata
     376              : 
     377              : pub const DBDIR_KEY: Key = Key {
     378              :     field1: 0x00,
     379              :     field2: 0,
     380              :     field3: 0,
     381              :     field4: 0,
     382              :     field5: 0,
     383              :     field6: 0,
     384              : };
     385              : 
     386              : #[inline(always)]
     387            0 : pub fn dbdir_key_range(spcnode: Oid, dbnode: Oid) -> Range<Key> {
     388            0 :     Key {
     389            0 :         field1: 0x00,
     390            0 :         field2: spcnode,
     391            0 :         field3: dbnode,
     392            0 :         field4: 0,
     393            0 :         field5: 0,
     394            0 :         field6: 0,
     395            0 :     }..Key {
     396            0 :         field1: 0x00,
     397            0 :         field2: spcnode,
     398            0 :         field3: dbnode,
     399            0 :         field4: 0xffffffff,
     400            0 :         field5: 0xff,
     401            0 :         field6: 0xffffffff,
     402            0 :     }
     403            0 : }
     404              : 
     405              : #[inline(always)]
     406           48 : pub fn relmap_file_key(spcnode: Oid, dbnode: Oid) -> Key {
     407           48 :     Key {
     408           48 :         field1: 0x00,
     409           48 :         field2: spcnode,
     410           48 :         field3: dbnode,
     411           48 :         field4: 0,
     412           48 :         field5: 0,
     413           48 :         field6: 0,
     414           48 :     }
     415           48 : }
     416              : 
     417              : #[inline(always)]
     418         5844 : pub fn rel_dir_to_key(spcnode: Oid, dbnode: Oid) -> Key {
     419         5844 :     Key {
     420         5844 :         field1: 0x00,
     421         5844 :         field2: spcnode,
     422         5844 :         field3: dbnode,
     423         5844 :         field4: 0,
     424         5844 :         field5: 0,
     425         5844 :         field6: 1,
     426         5844 :     }
     427         5844 : }
     428              : 
     429              : #[inline(always)]
     430      3445890 : pub fn rel_block_to_key(rel: RelTag, blknum: BlockNumber) -> Key {
     431      3445890 :     Key {
     432      3445890 :         field1: 0x00,
     433      3445890 :         field2: rel.spcnode,
     434      3445890 :         field3: rel.dbnode,
     435      3445890 :         field4: rel.relnode,
     436      3445890 :         field5: rel.forknum,
     437      3445890 :         field6: blknum,
     438      3445890 :     }
     439      3445890 : }
     440              : 
     441              : #[inline(always)]
     442       869262 : pub fn rel_size_to_key(rel: RelTag) -> Key {
     443       869262 :     Key {
     444       869262 :         field1: 0x00,
     445       869262 :         field2: rel.spcnode,
     446       869262 :         field3: rel.dbnode,
     447       869262 :         field4: rel.relnode,
     448       869262 :         field5: rel.forknum,
     449       869262 :         field6: 0xffff_ffff,
     450       869262 :     }
     451       869262 : }
     452              : 
     453              : impl Key {
     454              :     #[inline(always)]
     455            0 :     pub fn is_rel_size_key(&self) -> bool {
     456            0 :         self.field1 == 0 && self.field6 == u32::MAX
     457            0 :     }
     458              : }
     459              : 
     460              : #[inline(always)]
     461            6 : pub fn rel_key_range(rel: RelTag) -> Range<Key> {
     462            6 :     Key {
     463            6 :         field1: 0x00,
     464            6 :         field2: rel.spcnode,
     465            6 :         field3: rel.dbnode,
     466            6 :         field4: rel.relnode,
     467            6 :         field5: rel.forknum,
     468            6 :         field6: 0,
     469            6 :     }..Key {
     470            6 :         field1: 0x00,
     471            6 :         field2: rel.spcnode,
     472            6 :         field3: rel.dbnode,
     473            6 :         field4: rel.relnode,
     474            6 :         field5: rel.forknum + 1,
     475            6 :         field6: 0,
     476            6 :     }
     477            6 : }
     478              : 
     479              : //-- Section 02: SLRUs
     480              : 
     481              : #[inline(always)]
     482         4248 : pub fn slru_dir_to_key(kind: SlruKind) -> Key {
     483         4248 :     Key {
     484         4248 :         field1: 0x01,
     485         4248 :         field2: match kind {
     486         1416 :             SlruKind::Clog => 0x00,
     487         1416 :             SlruKind::MultiXactMembers => 0x01,
     488         1416 :             SlruKind::MultiXactOffsets => 0x02,
     489              :         },
     490              :         field3: 0,
     491              :         field4: 0,
     492              :         field5: 0,
     493              :         field6: 0,
     494              :     }
     495         4248 : }
     496              : 
     497              : #[inline(always)]
     498            0 : pub fn slru_dir_kind(key: &Key) -> Option<Result<SlruKind, u32>> {
     499            0 :     if key.field1 == 0x01
     500            0 :         && key.field3 == 0
     501            0 :         && key.field4 == 0
     502            0 :         && key.field5 == 0
     503            0 :         && key.field6 == 0
     504              :     {
     505            0 :         match key.field2 {
     506            0 :             0 => Some(Ok(SlruKind::Clog)),
     507            0 :             1 => Some(Ok(SlruKind::MultiXactMembers)),
     508            0 :             2 => Some(Ok(SlruKind::MultiXactOffsets)),
     509            0 :             x => Some(Err(x)),
     510              :         }
     511              :     } else {
     512            0 :         None
     513              :     }
     514            0 : }
     515              : 
     516              : #[inline(always)]
     517           42 : pub fn slru_block_to_key(kind: SlruKind, segno: u32, blknum: BlockNumber) -> Key {
     518           42 :     Key {
     519           42 :         field1: 0x01,
     520           42 :         field2: match kind {
     521           30 :             SlruKind::Clog => 0x00,
     522            6 :             SlruKind::MultiXactMembers => 0x01,
     523            6 :             SlruKind::MultiXactOffsets => 0x02,
     524              :         },
     525              :         field3: 1,
     526           42 :         field4: segno,
     527           42 :         field5: 0,
     528           42 :         field6: blknum,
     529           42 :     }
     530           42 : }
     531              : 
     532              : #[inline(always)]
     533           18 : pub fn slru_segment_size_to_key(kind: SlruKind, segno: u32) -> Key {
     534           18 :     Key {
     535           18 :         field1: 0x01,
     536           18 :         field2: match kind {
     537            6 :             SlruKind::Clog => 0x00,
     538            6 :             SlruKind::MultiXactMembers => 0x01,
     539            6 :             SlruKind::MultiXactOffsets => 0x02,
     540              :         },
     541              :         field3: 1,
     542           18 :         field4: segno,
     543           18 :         field5: 0,
     544           18 :         field6: 0xffff_ffff,
     545           18 :     }
     546           18 : }
     547              : 
     548              : impl Key {
     549            0 :     pub fn is_slru_segment_size_key(&self) -> bool {
     550            0 :         self.field1 == 0x01
     551            0 :             && self.field2 < 0x03
     552            0 :             && self.field3 == 0x01
     553            0 :             && self.field5 == 0
     554            0 :             && self.field6 == u32::MAX
     555            0 :     }
     556              : }
     557              : 
     558              : #[inline(always)]
     559            0 : pub fn slru_segment_key_range(kind: SlruKind, segno: u32) -> Range<Key> {
     560            0 :     let field2 = match kind {
     561            0 :         SlruKind::Clog => 0x00,
     562            0 :         SlruKind::MultiXactMembers => 0x01,
     563            0 :         SlruKind::MultiXactOffsets => 0x02,
     564              :     };
     565              : 
     566            0 :     Key {
     567            0 :         field1: 0x01,
     568            0 :         field2,
     569            0 :         field3: 1,
     570            0 :         field4: segno,
     571            0 :         field5: 0,
     572            0 :         field6: 0,
     573            0 :     }..Key {
     574            0 :         field1: 0x01,
     575            0 :         field2,
     576            0 :         field3: 1,
     577            0 :         field4: segno,
     578            0 :         field5: 1,
     579            0 :         field6: 0,
     580            0 :     }
     581            0 : }
     582              : 
     583              : //-- Section 03: pg_twophase
     584              : 
     585              : pub const TWOPHASEDIR_KEY: Key = Key {
     586              :     field1: 0x02,
     587              :     field2: 0,
     588              :     field3: 0,
     589              :     field4: 0,
     590              :     field5: 0,
     591              :     field6: 0,
     592              : };
     593              : 
     594              : #[inline(always)]
     595            0 : pub fn twophase_file_key(xid: u64) -> Key {
     596            0 :     Key {
     597            0 :         field1: 0x02,
     598            0 :         field2: 0,
     599            0 :         field3: 0,
     600            0 :         field4: ((xid & 0xFFFFFF0000000000) >> 40) as u32,
     601            0 :         field5: ((xid & 0x000000FF00000000) >> 32) as u8,
     602            0 :         field6: (xid & 0x00000000FFFFFFFF) as u32,
     603            0 :     }
     604            0 : }
     605              : 
     606              : #[inline(always)]
     607            0 : pub fn twophase_key_range(xid: u64) -> Range<Key> {
     608            0 :     // 64-bit XIDs really should not overflow
     609            0 :     let (next_xid, overflowed) = xid.overflowing_add(1);
     610            0 : 
     611            0 :     Key {
     612            0 :         field1: 0x02,
     613            0 :         field2: 0,
     614            0 :         field3: 0,
     615            0 :         field4: ((xid & 0xFFFFFF0000000000) >> 40) as u32,
     616            0 :         field5: ((xid & 0x000000FF00000000) >> 32) as u8,
     617            0 :         field6: (xid & 0x00000000FFFFFFFF) as u32,
     618            0 :     }..Key {
     619            0 :         field1: 0x02,
     620            0 :         field2: 0,
     621            0 :         field3: u32::from(overflowed),
     622            0 :         field4: ((next_xid & 0xFFFFFF0000000000) >> 40) as u32,
     623            0 :         field5: ((next_xid & 0x000000FF00000000) >> 32) as u8,
     624            0 :         field6: (next_xid & 0x00000000FFFFFFFF) as u32,
     625            0 :     }
     626            0 : }
     627              : 
     628              : //-- Section 03: Control file
     629              : pub const CONTROLFILE_KEY: Key = Key {
     630              :     field1: 0x03,
     631              :     field2: 0,
     632              :     field3: 0,
     633              :     field4: 0,
     634              :     field5: 0,
     635              :     field6: 0,
     636              : };
     637              : 
     638              : pub const CHECKPOINT_KEY: Key = Key {
     639              :     field1: 0x03,
     640              :     field2: 0,
     641              :     field3: 0,
     642              :     field4: 0,
     643              :     field5: 0,
     644              :     field6: 1,
     645              : };
     646              : 
     647              : pub const AUX_FILES_KEY: Key = Key {
     648              :     field1: 0x03,
     649              :     field2: 0,
     650              :     field3: 0,
     651              :     field4: 0,
     652              :     field5: 0,
     653              :     field6: 2,
     654              : };
     655              : 
     656              : #[inline(always)]
     657            0 : pub fn repl_origin_key(origin_id: RepOriginId) -> Key {
     658            0 :     Key {
     659            0 :         field1: REPL_ORIGIN_KEY_PREFIX,
     660            0 :         field2: 0,
     661            0 :         field3: 0,
     662            0 :         field4: 0,
     663            0 :         field5: 0,
     664            0 :         field6: origin_id as u32,
     665            0 :     }
     666            0 : }
     667              : 
     668              : /// Get the range of replorigin keys.
     669          876 : pub fn repl_origin_key_range() -> Range<Key> {
     670          876 :     Key {
     671          876 :         field1: REPL_ORIGIN_KEY_PREFIX,
     672          876 :         field2: 0,
     673          876 :         field3: 0,
     674          876 :         field4: 0,
     675          876 :         field5: 0,
     676          876 :         field6: 0,
     677          876 :     }..Key {
     678          876 :         field1: REPL_ORIGIN_KEY_PREFIX,
     679          876 :         field2: 0,
     680          876 :         field3: 0,
     681          876 :         field4: 0,
     682          876 :         field5: 0,
     683          876 :         field6: 0x10000,
     684          876 :     }
     685          876 : }
     686              : 
     687              : // Reverse mappings for a few Keys.
     688              : // These are needed by WAL redo manager.
     689              : 
     690              : /// Non inherited range for vectored get.
     691              : pub const NON_INHERITED_RANGE: Range<Key> = AUX_FILES_KEY..AUX_FILES_KEY.next();
     692              : /// Sparse keyspace range for vectored get. Missing key error will be ignored for this range.
     693              : pub const NON_INHERITED_SPARSE_RANGE: Range<Key> = Key::metadata_key_range();
     694              : 
     695              : impl Key {
     696              :     // AUX_FILES currently stores only data for logical replication (slots etc), and
     697              :     // we don't preserve these on a branch because safekeepers can't follow timeline
     698              :     // switch (and generally it likely should be optional), so ignore these.
     699              :     #[inline(always)]
     700            0 :     pub fn is_inherited_key(self) -> bool {
     701            0 :         !NON_INHERITED_RANGE.contains(&self) && !NON_INHERITED_SPARSE_RANGE.contains(&self)
     702            0 :     }
     703              : 
     704              :     #[inline(always)]
     705            0 :     pub fn is_rel_fsm_block_key(self) -> bool {
     706            0 :         self.field1 == 0x00
     707            0 :             && self.field4 != 0
     708            0 :             && self.field5 == FSM_FORKNUM
     709            0 :             && self.field6 != 0xffffffff
     710            0 :     }
     711              : 
     712              :     #[inline(always)]
     713            0 :     pub fn is_rel_vm_block_key(self) -> bool {
     714            0 :         self.field1 == 0x00
     715            0 :             && self.field4 != 0
     716            0 :             && self.field5 == VISIBILITYMAP_FORKNUM
     717            0 :             && self.field6 != 0xffffffff
     718            0 :     }
     719              : 
     720              :     #[inline(always)]
     721            0 :     pub fn to_slru_block(self) -> anyhow::Result<(SlruKind, u32, BlockNumber)> {
     722            0 :         Ok(match self.field1 {
     723              :             0x01 => {
     724            0 :                 let kind = match self.field2 {
     725            0 :                     0x00 => SlruKind::Clog,
     726            0 :                     0x01 => SlruKind::MultiXactMembers,
     727            0 :                     0x02 => SlruKind::MultiXactOffsets,
     728            0 :                     _ => anyhow::bail!("unrecognized slru kind 0x{:02x}", self.field2),
     729              :                 };
     730            0 :                 let segno = self.field4;
     731            0 :                 let blknum = self.field6;
     732            0 : 
     733            0 :                 (kind, segno, blknum)
     734              :             }
     735            0 :             _ => anyhow::bail!("unexpected value kind 0x{:02x}", self.field1),
     736              :         })
     737            0 :     }
     738              : 
     739              :     #[inline(always)]
     740      1717848 :     pub fn is_slru_block_key(self) -> bool {
     741      1717848 :         self.field1 == 0x01                // SLRU-related
     742         1698 :         && self.field3 == 0x00000001   // but not SlruDir
     743           60 :         && self.field6 != 0xffffffff // and not SlruSegSize
     744      1717848 :     }
     745              : 
     746              :     #[inline(always)]
     747     20512690 :     pub fn is_rel_block_key(&self) -> bool {
     748     20512690 :         self.field1 == 0x00 && self.field4 != 0 && self.field6 != 0xffffffff
     749     20512690 :     }
     750              : 
     751              :     /// Guaranteed to return `Ok()` if [`Self::is_rel_block_key`] returns `true` for `key`.
     752              :     #[inline(always)]
     753           18 :     pub fn to_rel_block(self) -> anyhow::Result<(RelTag, BlockNumber)> {
     754           18 :         Ok(match self.field1 {
     755           18 :             0x00 => (
     756           18 :                 RelTag {
     757           18 :                     spcnode: self.field2,
     758           18 :                     dbnode: self.field3,
     759           18 :                     relnode: self.field4,
     760           18 :                     forknum: self.field5,
     761           18 :                 },
     762           18 :                 self.field6,
     763           18 :             ),
     764            0 :             _ => anyhow::bail!("unexpected value kind 0x{:02x}", self.field1),
     765              :         })
     766           18 :     }
     767              : }
     768              : 
     769              : impl std::str::FromStr for Key {
     770              :     type Err = anyhow::Error;
     771              : 
     772            9 :     fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
     773            9 :         Self::from_hex(s)
     774            9 :     }
     775              : }
     776              : 
     777              : #[cfg(test)]
     778              : mod tests {
     779              :     use std::str::FromStr;
     780              : 
     781              :     use crate::key::is_metadata_key_slice;
     782              :     use crate::key::Key;
     783              : 
     784              :     use rand::Rng;
     785              :     use rand::SeedableRng;
     786              : 
     787              :     use super::AUX_KEY_PREFIX;
     788              : 
     789              :     #[test]
     790            1 :     fn display_fromstr_bijection() {
     791            1 :         let mut rng = rand::rngs::StdRng::seed_from_u64(42);
     792            1 : 
     793            1 :         let key = Key {
     794            1 :             field1: rng.gen(),
     795            1 :             field2: rng.gen(),
     796            1 :             field3: rng.gen(),
     797            1 :             field4: rng.gen(),
     798            1 :             field5: rng.gen(),
     799            1 :             field6: rng.gen(),
     800            1 :         };
     801            1 : 
     802            1 :         assert_eq!(key, Key::from_str(&format!("{key}")).unwrap());
     803            1 :     }
     804              : 
     805              :     #[test]
     806            1 :     fn test_metadata_keys() {
     807            1 :         let mut metadata_key = vec![AUX_KEY_PREFIX];
     808            1 :         metadata_key.extend_from_slice(&[0xFF; 15]);
     809            1 :         let encoded_key = Key::from_metadata_key(&metadata_key);
     810            1 :         let output_key = encoded_key.to_i128().to_be_bytes();
     811            1 :         assert_eq!(metadata_key, output_key);
     812            1 :         assert!(encoded_key.is_metadata_key());
     813            1 :         assert!(is_metadata_key_slice(&metadata_key));
     814            1 :     }
     815              : 
     816              :     #[test]
     817            1 :     fn test_possible_largest_key() {
     818            1 :         Key::from_i128(0x7FFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF);
     819            1 :         // TODO: put this key into the system and see if anything breaks.
     820            1 :     }
     821              : }
        

Generated by: LCOV version 2.1-beta