LCOV - code coverage report
Current view: top level - libs/pageserver_api/src - key.rs (source / functions) Coverage Total Hit
Test: 6fa910d1c9aea142e54ede6987809ef55544c500.info Lines: 63.8 % 458 292
Test Date: 2024-11-19 23:07:42 Functions: 59.0 % 61 36

            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         2380 : #[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            0 : #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd, Serialize, Deserialize)]
      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           36 : pub const fn is_metadata_key_slice(key: &[u8]) -> bool {
      52           36 :     key[0] >= METADATA_KEY_BEGIN_PREFIX && key[0] < METADATA_KEY_END_PREFIX
      53           36 : }
      54              : 
      55              : impl Key {
      56              :     /// Check if the key falls in the range of metadata keys.
      57           67 :     pub const fn is_metadata_key(&self) -> bool {
      58           67 :         self.field1 >= METADATA_KEY_BEGIN_PREFIX && self.field1 < METADATA_KEY_END_PREFIX
      59           67 :     }
      60              : 
      61              :     /// Encode a metadata key to a storage key.
      62           35 :     pub fn from_metadata_key_fixed_size(key: &[u8; METADATA_KEY_SIZE]) -> Self {
      63           35 :         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           35 :         Self::from_i128(i128::from_be_bytes(*key))
      66           35 :     }
      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         1184 :     pub const fn metadata_key_range() -> Range<Self> {
      75         1184 :         Key {
      76         1184 :             field1: METADATA_KEY_BEGIN_PREFIX,
      77         1184 :             field2: 0,
      78         1184 :             field3: 0,
      79         1184 :             field4: 0,
      80         1184 :             field5: 0,
      81         1184 :             field6: 0,
      82         1184 :         }..Key {
      83         1184 :             field1: METADATA_KEY_END_PREFIX,
      84         1184 :             field2: 0,
      85         1184 :             field3: 0,
      86         1184 :             field4: 0,
      87         1184 :             field5: 0,
      88         1184 :             field6: 0,
      89         1184 :         }
      90         1184 :     }
      91              : 
      92              :     /// Get the range of aux keys.
      93          304 :     pub fn metadata_aux_key_range() -> Range<Self> {
      94          304 :         Key {
      95          304 :             field1: AUX_KEY_PREFIX,
      96          304 :             field2: 0,
      97          304 :             field3: 0,
      98          304 :             field4: 0,
      99          304 :             field5: 0,
     100          304 :             field6: 0,
     101          304 :         }..Key {
     102          304 :             field1: AUX_KEY_PREFIX + 1,
     103          304 :             field2: 0,
     104          304 :             field3: 0,
     105          304 :             field4: 0,
     106          304 :             field5: 0,
     107          304 :             field6: 0,
     108          304 :         }
     109          304 :     }
     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      4816642 :     pub fn is_valid_key_on_write_path(&self) -> bool {
     134      4816642 :         self.is_i128_representable()
     135      4816642 :     }
     136              : 
     137     16471243 :     pub fn is_i128_representable(&self) -> bool {
     138     16471243 :         self.field2 <= 0xFFFF || self.field2 == 0xFFFFFFFF || self.field2 == 0x22222222
     139     16471243 :     }
     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     11654601 :     pub fn to_i128(&self) -> i128 {
     145     11654601 :         assert!(self.is_i128_representable(), "invalid key: {self}");
     146     11654601 :         (((self.field1 & 0x7F) as i128) << 120)
     147     11654601 :             | (((self.field2 & 0xFFFF) as i128) << 104)
     148     11654601 :             | ((self.field3 as i128) << 72)
     149     11654601 :             | ((self.field4 as i128) << 40)
     150     11654601 :             | ((self.field5 as i128) << 32)
     151     11654601 :             | self.field6 as i128
     152     11654601 :     }
     153              : 
     154      5531172 :     pub const fn from_i128(x: i128) -> Self {
     155      5531172 :         Key {
     156      5531172 :             field1: ((x >> 120) & 0x7F) as u8,
     157      5531172 :             field2: ((x >> 104) & 0xFFFF) as u32,
     158      5531172 :             field3: (x >> 72) as u32,
     159      5531172 :             field4: (x >> 40) as u32,
     160      5531172 :             field5: (x >> 32) as u8,
     161      5531172 :             field6: x as u32,
     162      5531172 :         }
     163      5531172 :     }
     164              : 
     165      6875777 :     pub fn to_compact(&self) -> CompactKey {
     166      6875777 :         CompactKey(self.to_i128())
     167      6875777 :     }
     168              : 
     169      5030174 :     pub fn from_compact(k: CompactKey) -> Self {
     170      5030174 :         Self::from_i128(k.0)
     171      5030174 :     }
     172              : 
     173      8883096 :     pub const fn next(&self) -> Key {
     174      8883096 :         self.add(1)
     175      8883096 :     }
     176              : 
     177      8893001 :     pub const fn add(&self, x: u32) -> Key {
     178      8893001 :         let mut key = *self;
     179      8893001 : 
     180      8893001 :         let r = key.field6.overflowing_add(x);
     181      8893001 :         key.field6 = r.0;
     182      8893001 :         if r.1 {
     183       827101 :             let r = key.field5.overflowing_add(1);
     184       827101 :             key.field5 = r.0;
     185       827101 :             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       827101 :             }
     202      8065900 :         }
     203      8893001 :         key
     204      8893001 :     }
     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      5942421 :     pub fn from_slice(b: &[u8]) -> Self {
     210      5942421 :         Key {
     211      5942421 :             field1: b[0],
     212      5942421 :             field2: u32::from_be_bytes(b[1..5].try_into().unwrap()),
     213      5942421 :             field3: u32::from_be_bytes(b[5..9].try_into().unwrap()),
     214      5942421 :             field4: u32::from_be_bytes(b[9..13].try_into().unwrap()),
     215      5942421 :             field5: b[13],
     216      5942421 :             field6: u32::from_be_bytes(b[14..18].try_into().unwrap()),
     217      5942421 :         }
     218      5942421 :     }
     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      7256839 :     pub fn write_to_byte_slice(&self, buf: &mut [u8]) {
     223      7256839 :         buf[0] = self.field1;
     224      7256839 :         BE::write_u32(&mut buf[1..5], self.field2);
     225      7256839 :         BE::write_u32(&mut buf[5..9], self.field3);
     226      7256839 :         BE::write_u32(&mut buf[9..13], self.field4);
     227      7256839 :         buf[13] = self.field5;
     228      7256839 :         BE::write_u32(&mut buf[14..18], self.field6);
     229      7256839 :     }
     230              : }
     231              : 
     232              : impl fmt::Display for Key {
     233       375559 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     234       375559 :         write!(
     235       375559 :             f,
     236       375559 :             "{:02X}{:08X}{:08X}{:08X}{:02X}{:08X}",
     237       375559 :             self.field1, self.field2, self.field3, self.field4, self.field5, self.field6
     238       375559 :         )
     239       375559 :     }
     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        39613 :     pub fn from_hex(s: &str) -> Result<Self> {
     268        39613 :         if s.len() != 36 {
     269            4 :             bail!("parse error");
     270        39609 :         }
     271        39609 :         Ok(Key {
     272        39609 :             field1: u8::from_str_radix(&s[0..2], 16)?,
     273        39609 :             field2: u32::from_str_radix(&s[2..10], 16)?,
     274        39609 :             field3: u32::from_str_radix(&s[10..18], 16)?,
     275        39609 :             field4: u32::from_str_radix(&s[18..26], 16)?,
     276        39609 :             field5: u8::from_str_radix(&s[26..28], 16)?,
     277        39609 :             field6: u32::from_str_radix(&s[28..36], 16)?,
     278              :         })
     279        39613 :     }
     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           16 : pub fn relmap_file_key(spcnode: Oid, dbnode: Oid) -> Key {
     407           16 :     Key {
     408           16 :         field1: 0x00,
     409           16 :         field2: spcnode,
     410           16 :         field3: dbnode,
     411           16 :         field4: 0,
     412           16 :         field5: 0,
     413           16 :         field6: 0,
     414           16 :     }
     415           16 : }
     416              : 
     417              : #[inline(always)]
     418         1948 : pub fn rel_dir_to_key(spcnode: Oid, dbnode: Oid) -> Key {
     419         1948 :     Key {
     420         1948 :         field1: 0x00,
     421         1948 :         field2: spcnode,
     422         1948 :         field3: dbnode,
     423         1948 :         field4: 0,
     424         1948 :         field5: 0,
     425         1948 :         field6: 1,
     426         1948 :     }
     427         1948 : }
     428              : 
     429              : #[inline(always)]
     430      1291898 : pub fn rel_block_to_key(rel: RelTag, blknum: BlockNumber) -> Key {
     431      1291898 :     Key {
     432      1291898 :         field1: 0x00,
     433      1291898 :         field2: rel.spcnode,
     434      1291898 :         field3: rel.dbnode,
     435      1291898 :         field4: rel.relnode,
     436      1291898 :         field5: rel.forknum,
     437      1291898 :         field6: blknum,
     438      1291898 :     }
     439      1291898 : }
     440              : 
     441              : #[inline(always)]
     442       289754 : pub fn rel_size_to_key(rel: RelTag) -> Key {
     443       289754 :     Key {
     444       289754 :         field1: 0x00,
     445       289754 :         field2: rel.spcnode,
     446       289754 :         field3: rel.dbnode,
     447       289754 :         field4: rel.relnode,
     448       289754 :         field5: rel.forknum,
     449       289754 :         field6: 0xffff_ffff,
     450       289754 :     }
     451       289754 : }
     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            2 : pub fn rel_key_range(rel: RelTag) -> Range<Key> {
     462            2 :     Key {
     463            2 :         field1: 0x00,
     464            2 :         field2: rel.spcnode,
     465            2 :         field3: rel.dbnode,
     466            2 :         field4: rel.relnode,
     467            2 :         field5: rel.forknum,
     468            2 :         field6: 0,
     469            2 :     }..Key {
     470            2 :         field1: 0x00,
     471            2 :         field2: rel.spcnode,
     472            2 :         field3: rel.dbnode,
     473            2 :         field4: rel.relnode,
     474            2 :         field5: rel.forknum + 1,
     475            2 :         field6: 0,
     476            2 :     }
     477            2 : }
     478              : 
     479              : //-- Section 02: SLRUs
     480              : 
     481              : #[inline(always)]
     482         1416 : pub fn slru_dir_to_key(kind: SlruKind) -> Key {
     483         1416 :     Key {
     484         1416 :         field1: 0x01,
     485         1416 :         field2: match kind {
     486          472 :             SlruKind::Clog => 0x00,
     487          472 :             SlruKind::MultiXactMembers => 0x01,
     488          472 :             SlruKind::MultiXactOffsets => 0x02,
     489              :         },
     490              :         field3: 0,
     491              :         field4: 0,
     492              :         field5: 0,
     493              :         field6: 0,
     494              :     }
     495         1416 : }
     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           14 : pub fn slru_block_to_key(kind: SlruKind, segno: u32, blknum: BlockNumber) -> Key {
     518           14 :     Key {
     519           14 :         field1: 0x01,
     520           14 :         field2: match kind {
     521           10 :             SlruKind::Clog => 0x00,
     522            2 :             SlruKind::MultiXactMembers => 0x01,
     523            2 :             SlruKind::MultiXactOffsets => 0x02,
     524              :         },
     525              :         field3: 1,
     526           14 :         field4: segno,
     527           14 :         field5: 0,
     528           14 :         field6: blknum,
     529           14 :     }
     530           14 : }
     531              : 
     532              : #[inline(always)]
     533            6 : pub fn slru_segment_size_to_key(kind: SlruKind, segno: u32) -> Key {
     534            6 :     Key {
     535            6 :         field1: 0x01,
     536            6 :         field2: match kind {
     537            2 :             SlruKind::Clog => 0x00,
     538            2 :             SlruKind::MultiXactMembers => 0x01,
     539            2 :             SlruKind::MultiXactOffsets => 0x02,
     540              :         },
     541              :         field3: 1,
     542            6 :         field4: segno,
     543            6 :         field5: 0,
     544            6 :         field6: 0xffff_ffff,
     545            6 :     }
     546            6 : }
     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          292 : pub fn repl_origin_key_range() -> Range<Key> {
     670          292 :     Key {
     671          292 :         field1: REPL_ORIGIN_KEY_PREFIX,
     672          292 :         field2: 0,
     673          292 :         field3: 0,
     674          292 :         field4: 0,
     675          292 :         field5: 0,
     676          292 :         field6: 0,
     677          292 :     }..Key {
     678          292 :         field1: REPL_ORIGIN_KEY_PREFIX,
     679          292 :         field2: 0,
     680          292 :         field3: 0,
     681          292 :         field4: 0,
     682          292 :         field5: 0,
     683          292 :         field6: 0x10000,
     684          292 :     }
     685          292 : }
     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       572578 :     pub fn is_slru_block_key(self) -> bool {
     741       572578 :         self.field1 == 0x01                // SLRU-related
     742          566 :         && self.field3 == 0x00000001   // but not SlruDir
     743           20 :         && self.field6 != 0xffffffff // and not SlruSegSize
     744       572578 :     }
     745              : 
     746              :     #[inline(always)]
     747      6696156 :     pub fn is_rel_block_key(&self) -> bool {
     748      6696156 :         self.field1 == 0x00 && self.field4 != 0 && self.field6 != 0xffffffff
     749      6696156 :     }
     750              : 
     751              :     #[inline(always)]
     752          200 :     pub fn is_rel_dir_key(&self) -> bool {
     753          200 :         self.field1 == 0x00
     754          200 :             && self.field2 != 0
     755            0 :             && self.field3 != 0
     756            0 :             && self.field4 == 0
     757            0 :             && self.field5 == 0
     758            0 :             && self.field6 == 1
     759          200 :     }
     760              : 
     761              :     /// Guaranteed to return `Ok()` if [`Self::is_rel_block_key`] returns `true` for `key`.
     762              :     #[inline(always)]
     763       145648 :     pub fn to_rel_block(self) -> anyhow::Result<(RelTag, BlockNumber)> {
     764       145648 :         Ok(match self.field1 {
     765       145648 :             0x00 => (
     766       145648 :                 RelTag {
     767       145648 :                     spcnode: self.field2,
     768       145648 :                     dbnode: self.field3,
     769       145648 :                     relnode: self.field4,
     770       145648 :                     forknum: self.field5,
     771       145648 :                 },
     772       145648 :                 self.field6,
     773       145648 :             ),
     774            0 :             _ => anyhow::bail!("unexpected value kind 0x{:02x}", self.field1),
     775              :         })
     776       145648 :     }
     777              : }
     778              : 
     779              : impl std::str::FromStr for Key {
     780              :     type Err = anyhow::Error;
     781              : 
     782            9 :     fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
     783            9 :         Self::from_hex(s)
     784            9 :     }
     785              : }
     786              : 
     787              : #[cfg(test)]
     788              : mod tests {
     789              :     use std::str::FromStr;
     790              : 
     791              :     use crate::key::is_metadata_key_slice;
     792              :     use crate::key::Key;
     793              : 
     794              :     use rand::Rng;
     795              :     use rand::SeedableRng;
     796              : 
     797              :     use super::AUX_KEY_PREFIX;
     798              : 
     799              :     #[test]
     800            1 :     fn display_fromstr_bijection() {
     801            1 :         let mut rng = rand::rngs::StdRng::seed_from_u64(42);
     802            1 : 
     803            1 :         let key = Key {
     804            1 :             field1: rng.gen(),
     805            1 :             field2: rng.gen(),
     806            1 :             field3: rng.gen(),
     807            1 :             field4: rng.gen(),
     808            1 :             field5: rng.gen(),
     809            1 :             field6: rng.gen(),
     810            1 :         };
     811            1 : 
     812            1 :         assert_eq!(key, Key::from_str(&format!("{key}")).unwrap());
     813            1 :     }
     814              : 
     815              :     #[test]
     816            1 :     fn test_metadata_keys() {
     817            1 :         let mut metadata_key = vec![AUX_KEY_PREFIX];
     818            1 :         metadata_key.extend_from_slice(&[0xFF; 15]);
     819            1 :         let encoded_key = Key::from_metadata_key(&metadata_key);
     820            1 :         let output_key = encoded_key.to_i128().to_be_bytes();
     821            1 :         assert_eq!(metadata_key, output_key);
     822            1 :         assert!(encoded_key.is_metadata_key());
     823            1 :         assert!(is_metadata_key_slice(&metadata_key));
     824            1 :     }
     825              : 
     826              :     #[test]
     827            1 :     fn test_possible_largest_key() {
     828            1 :         Key::from_i128(0x7FFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF);
     829            1 :         // TODO: put this key into the system and see if anything breaks.
     830            1 :     }
     831              : }
        

Generated by: LCOV version 2.1-beta