LCOV - differential code coverage report
Current view: top level - libs/postgres_ffi/src - lib.rs (source / functions) Coverage Total Hit UBC CBC
Current: cd44433dd675caa99df17a61b18949c8387e2242.info Lines: 86.2 % 94 81 13 81
Current Date: 2024-01-09 02:06:09 Functions: 81.2 % 16 13 3 13
Baseline: 66c52a629a0f4a503e193045e0df4c77139e344b.info
Baseline Date: 2024-01-08 15:34:46

           TLA  Line data    Source code
       1                 : #![allow(non_upper_case_globals)]
       2                 : #![allow(non_camel_case_types)]
       3                 : #![allow(non_snake_case)]
       4                 : // bindgen creates some unsafe code with no doc comments.
       5                 : #![allow(clippy::missing_safety_doc)]
       6                 : // noted at 1.63 that in many cases there's a u32 -> u32 transmutes in bindgen code.
       7                 : #![allow(clippy::useless_transmute)]
       8                 : // modules included with the postgres_ffi macro depend on the types of the specific version's
       9                 : // types, and trigger a too eager lint.
      10                 : #![allow(clippy::duplicate_mod)]
      11                 : #![deny(clippy::undocumented_unsafe_blocks)]
      12                 : 
      13                 : use bytes::Bytes;
      14                 : use utils::bin_ser::SerializeError;
      15                 : use utils::lsn::Lsn;
      16                 : 
      17                 : macro_rules! postgres_ffi {
      18                 :     ($version:ident) => {
      19                 :         #[path = "."]
      20                 :         pub mod $version {
      21                 :             pub mod bindings {
      22                 :                 // bindgen generates bindings for a lot of stuff we don't need
      23                 :                 #![allow(dead_code)]
      24                 :                 #![allow(clippy::undocumented_unsafe_blocks)]
      25                 : 
      26                 :                 use serde::{Deserialize, Serialize};
      27                 :                 include!(concat!(
      28                 :                     env!("OUT_DIR"),
      29                 :                     "/bindings_",
      30                 :                     stringify!($version),
      31                 :                     ".rs"
      32                 :                 ));
      33                 : 
      34                 :                 include!(concat!("pg_constants_", stringify!($version), ".rs"));
      35                 :             }
      36                 :             pub mod controlfile_utils;
      37                 :             pub mod nonrelfile_utils;
      38                 :             pub mod wal_craft_test_export;
      39                 :             pub mod waldecoder_handler;
      40                 :             pub mod xlog_utils;
      41                 : 
      42                 :             pub const PG_MAJORVERSION: &str = stringify!($version);
      43                 : 
      44                 :             // Re-export some symbols from bindings
      45                 :             pub use bindings::DBState_DB_SHUTDOWNED;
      46                 :             pub use bindings::{CheckPoint, ControlFileData, XLogRecord};
      47                 :         }
      48                 :     };
      49                 : }
      50                 : 
      51                 : #[macro_export]
      52                 : macro_rules! for_all_postgres_versions {
      53                 :     ($macro:tt) => {
      54                 :         $macro!(v14);
      55                 :         $macro!(v15);
      56                 :         $macro!(v16);
      57                 :     };
      58                 : }
      59                 : 
      60                 : for_all_postgres_versions! { postgres_ffi }
      61                 : 
      62                 : /// dispatch_pgversion
      63                 : ///
      64                 : /// Run a code block in a context where the postgres_ffi bindings for a
      65                 : /// specific (supported) PostgreSQL version are `use`-ed in scope under the pgv
      66                 : /// identifier.
      67                 : /// If the provided pg_version is not supported, we panic!(), unless the
      68                 : /// optional third argument was provided (in which case that code will provide
      69                 : /// the default handling instead).
      70                 : ///
      71                 : /// Use like
      72                 : ///
      73                 : /// dispatch_pgversion!(my_pgversion, { pgv::constants::XLOG_DBASE_CREATE })
      74                 : /// dispatch_pgversion!(my_pgversion, pgv::constants::XLOG_DBASE_CREATE)
      75                 : ///
      76                 : /// Other uses are for macro-internal purposes only and strictly unsupported.
      77                 : ///
      78                 : #[macro_export]
      79                 : macro_rules! dispatch_pgversion {
      80                 :     ($version:expr, $code:expr) => {
      81                 :         dispatch_pgversion!($version, $code, panic!("Unknown PostgreSQL version {}", $version))
      82                 :     };
      83                 :     ($version:expr, $code:expr, $invalid_pgver_handling:expr) => {
      84                 :         dispatch_pgversion!(
      85                 :             $version => $code,
      86                 :             default = $invalid_pgver_handling,
      87                 :             pgversions = [
      88                 :                 14 : v14,
      89                 :                 15 : v15,
      90                 :                 16 : v16,
      91                 :             ]
      92                 :         )
      93                 :     };
      94                 :     ($pgversion:expr => $code:expr,
      95                 :      default = $default:expr,
      96                 :      pgversions = [$($sv:literal : $vsv:ident),+ $(,)?]) => {
      97                 :         match ($pgversion) {
      98                 :             $($sv => {
      99                 :                 use $crate::$vsv as pgv;
     100                 :                 $code
     101                 :             },)+
     102                 :             _ => {
     103                 :                 $default
     104                 :             }
     105                 :         }
     106                 :     };
     107                 : }
     108                 : 
     109                 : pub mod pg_constants;
     110                 : pub mod relfile_utils;
     111                 : 
     112                 : // Export some widely used datatypes that are unlikely to change across Postgres versions
     113                 : pub use v14::bindings::{uint32, uint64, Oid};
     114                 : pub use v14::bindings::{BlockNumber, OffsetNumber};
     115                 : pub use v14::bindings::{MultiXactId, TransactionId};
     116                 : pub use v14::bindings::{TimeLineID, TimestampTz, XLogRecPtr, XLogSegNo};
     117                 : 
     118                 : // Likewise for these, although the assumption that these don't change is a little more iffy.
     119                 : pub use v14::bindings::{MultiXactOffset, MultiXactStatus};
     120                 : pub use v14::bindings::{PageHeaderData, XLogRecord};
     121                 : pub use v14::xlog_utils::{XLOG_SIZE_OF_XLOG_RECORD, XLOG_SIZE_OF_XLOG_SHORT_PHD};
     122                 : 
     123                 : pub use v14::bindings::{CheckPoint, ControlFileData};
     124                 : 
     125                 : // from pg_config.h. These can be changed with configure options --with-blocksize=BLOCKSIZE and
     126                 : // --with-segsize=SEGSIZE, but assume the defaults for now.
     127                 : pub const BLCKSZ: u16 = 8192;
     128                 : pub const RELSEG_SIZE: u32 = 1024 * 1024 * 1024 / (BLCKSZ as u32);
     129                 : pub const XLOG_BLCKSZ: usize = 8192;
     130                 : pub const WAL_SEGMENT_SIZE: usize = 16 * 1024 * 1024;
     131                 : 
     132                 : pub const MAX_SEND_SIZE: usize = XLOG_BLCKSZ * 16;
     133                 : 
     134                 : // Export some version independent functions that are used outside of this mod
     135                 : pub use v14::xlog_utils::encode_logical_message;
     136                 : pub use v14::xlog_utils::from_pg_timestamp;
     137                 : pub use v14::xlog_utils::get_current_timestamp;
     138                 : pub use v14::xlog_utils::to_pg_timestamp;
     139                 : pub use v14::xlog_utils::XLogFileName;
     140                 : 
     141                 : pub use v14::bindings::DBState_DB_SHUTDOWNED;
     142                 : 
     143 CBC      278059 : pub fn bkpimage_is_compressed(bimg_info: u8, version: u32) -> anyhow::Result<bool> {
     144          278059 :     dispatch_pgversion!(version, Ok(pgv::bindings::bkpimg_is_compressed(bimg_info)))
     145          278059 : }
     146                 : 
     147             562 : pub fn generate_wal_segment(
     148             562 :     segno: u64,
     149             562 :     system_id: u64,
     150             562 :     pg_version: u32,
     151             562 :     lsn: Lsn,
     152             562 : ) -> Result<Bytes, SerializeError> {
     153             562 :     assert_eq!(segno, lsn.segment_number(WAL_SEGMENT_SIZE));
     154                 : 
     155                 :     dispatch_pgversion!(
     156             562 :         pg_version,
     157             562 :         pgv::xlog_utils::generate_wal_segment(segno, system_id, lsn),
     158 UBC           0 :         Err(SerializeError::BadInput)
     159                 :     )
     160 CBC         562 : }
     161                 : 
     162             557 : pub fn generate_pg_control(
     163             557 :     pg_control_bytes: &[u8],
     164             557 :     checkpoint_bytes: &[u8],
     165             557 :     lsn: Lsn,
     166             557 :     pg_version: u32,
     167             557 : ) -> anyhow::Result<(Bytes, u64)> {
     168             557 :     dispatch_pgversion!(
     169             557 :         pg_version,
     170             557 :         pgv::xlog_utils::generate_pg_control(pg_control_bytes, checkpoint_bytes, lsn),
     171 UBC           0 :         anyhow::bail!("Unknown version {}", pg_version)
     172                 :     )
     173 CBC         557 : }
     174                 : 
     175                 : // PG timeline is always 1, changing it doesn't have any useful meaning in Neon.
     176                 : //
     177                 : // NOTE: this is not to be confused with Neon timelines; different concept!
     178                 : //
     179                 : // It's a shaky assumption, that it's always 1. We might import a
     180                 : // PostgreSQL data directory that has gone through timeline bumps,
     181                 : // for example. FIXME later.
     182                 : pub const PG_TLI: u32 = 1;
     183                 : 
     184                 : //  See TransactionIdIsNormal in transam.h
     185              80 : pub const fn transaction_id_is_normal(id: TransactionId) -> bool {
     186              80 :     id > pg_constants::FIRST_NORMAL_TRANSACTION_ID
     187              80 : }
     188                 : 
     189                 : // See TransactionIdPrecedes in transam.c
     190              40 : pub const fn transaction_id_precedes(id1: TransactionId, id2: TransactionId) -> bool {
     191              40 :     /*
     192              40 :      * If either ID is a permanent XID then we can just do unsigned
     193              40 :      * comparison.  If both are normal, do a modulo-2^32 comparison.
     194              40 :      */
     195              40 : 
     196              40 :     if !(transaction_id_is_normal(id1)) || !transaction_id_is_normal(id2) {
     197 UBC           0 :         return id1 < id2;
     198 CBC          40 :     }
     199              40 : 
     200              40 :     let diff = id1.wrapping_sub(id2) as i32;
     201              40 :     diff < 0
     202              40 : }
     203                 : 
     204                 : // Check if page is not yet initialized (port of Postgres PageIsInit() macro)
     205          129995 : pub fn page_is_new(pg: &[u8]) -> bool {
     206          129995 :     pg[14] == 0 && pg[15] == 0 // pg_upper == 0
     207          129995 : }
     208                 : 
     209                 : // ExtractLSN from page header
     210 UBC           0 : pub fn page_get_lsn(pg: &[u8]) -> Lsn {
     211               0 :     Lsn(
     212               0 :         ((u32::from_le_bytes(pg[0..4].try_into().unwrap()) as u64) << 32)
     213               0 :             | u32::from_le_bytes(pg[4..8].try_into().unwrap()) as u64,
     214               0 :     )
     215               0 : }
     216                 : 
     217 CBC      125364 : pub fn page_set_lsn(pg: &mut [u8], lsn: Lsn) {
     218          125364 :     pg[0..4].copy_from_slice(&((lsn.0 >> 32) as u32).to_le_bytes());
     219          125364 :     pg[4..8].copy_from_slice(&(lsn.0 as u32).to_le_bytes());
     220          125364 : }
     221                 : 
     222                 : // This is port of function with the same name from freespace.c.
     223                 : // The only difference is that it does not have "level" parameter because XLogRecordPageWithFreeSpace
     224                 : // always call it with level=FSM_BOTTOM_LEVEL
     225              44 : pub fn fsm_logical_to_physical(addr: BlockNumber) -> BlockNumber {
     226              44 :     let mut leafno = addr;
     227              44 :     const FSM_TREE_DEPTH: u32 = if pg_constants::SLOTS_PER_FSM_PAGE >= 1626 {
     228              44 :         3
     229              44 :     } else {
     230              44 :         4
     231              44 :     };
     232              44 : 
     233              44 :     /* Count upper level nodes required to address the leaf page */
     234              44 :     let mut pages: BlockNumber = 0;
     235             176 :     for _l in 0..FSM_TREE_DEPTH {
     236             132 :         pages += leafno + 1;
     237             132 :         leafno /= pg_constants::SLOTS_PER_FSM_PAGE;
     238             132 :     }
     239                 :     /* Turn the page count into 0-based block number */
     240              44 :     pages - 1
     241              44 : }
     242                 : 
     243                 : pub mod waldecoder {
     244                 :     use bytes::{Buf, Bytes, BytesMut};
     245                 :     use std::num::NonZeroU32;
     246                 :     use thiserror::Error;
     247                 :     use utils::lsn::Lsn;
     248                 : 
     249                 :     pub enum State {
     250                 :         WaitingForRecord,
     251                 :         ReassemblingRecord {
     252                 :             recordbuf: BytesMut,
     253                 :             contlen: NonZeroU32,
     254                 :         },
     255                 :         SkippingEverything {
     256                 :             skip_until_lsn: Lsn,
     257                 :         },
     258                 :     }
     259                 : 
     260                 :     pub struct WalStreamDecoder {
     261                 :         pub lsn: Lsn,
     262                 :         pub pg_version: u32,
     263                 :         pub inputbuf: BytesMut,
     264                 :         pub state: State,
     265                 :     }
     266                 : 
     267              21 :     #[derive(Error, Debug, Clone)]
     268                 :     #[error("{msg} at {lsn}")]
     269                 :     pub struct WalDecodeError {
     270                 :         pub msg: String,
     271                 :         pub lsn: Lsn,
     272                 :     }
     273                 : 
     274                 :     impl WalStreamDecoder {
     275            2520 :         pub fn new(lsn: Lsn, pg_version: u32) -> WalStreamDecoder {
     276            2520 :             WalStreamDecoder {
     277            2520 :                 lsn,
     278            2520 :                 pg_version,
     279            2520 :                 inputbuf: BytesMut::new(),
     280            2520 :                 state: State::WaitingForRecord,
     281            2520 :             }
     282            2520 :         }
     283                 : 
     284                 :         // The latest LSN position fed to the decoder.
     285         1217064 :         pub fn available(&self) -> Lsn {
     286         1217064 :             self.lsn + self.inputbuf.remaining() as u64
     287         1217064 :         }
     288                 : 
     289         2074537 :         pub fn feed_bytes(&mut self, buf: &[u8]) {
     290         2074537 :             self.inputbuf.extend_from_slice(buf);
     291         2074537 :         }
     292                 : 
     293       125970203 :         pub fn poll_decode(&mut self) -> Result<Option<(Lsn, Bytes)>, WalDecodeError> {
     294       125970203 :             dispatch_pgversion!(
     295       125970203 :                 self.pg_version,
     296                 :                 {
     297                 :                     use pgv::waldecoder_handler::WalStreamDecoderHandler;
     298       125970203 :                     self.poll_decode_internal()
     299                 :                 },
     300 UBC           0 :                 Err(WalDecodeError {
     301               0 :                     msg: format!("Unknown version {}", self.pg_version),
     302               0 :                     lsn: self.lsn,
     303               0 :                 })
     304                 :             )
     305 CBC   125970203 :         }
     306                 :     }
     307                 : }
        

Generated by: LCOV version 2.1-beta