LCOV - code coverage report
Current view: top level - libs/postgres_ffi/src - lib.rs (source / functions) Coverage Total Hit
Test: 691a4c28fe7169edd60b367c52d448a0a6605f1f.info Lines: 30.9 % 94 29
Test Date: 2024-05-10 13:18:37 Functions: 50.0 % 14 7

            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 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::{
     122              :     XLOG_SIZE_OF_XLOG_LONG_PHD, XLOG_SIZE_OF_XLOG_RECORD, XLOG_SIZE_OF_XLOG_SHORT_PHD,
     123              : };
     124              : 
     125              : pub use v14::bindings::{CheckPoint, ControlFileData};
     126              : 
     127              : // from pg_config.h. These can be changed with configure options --with-blocksize=BLOCKSIZE and
     128              : // --with-segsize=SEGSIZE, but assume the defaults for now.
     129              : pub const BLCKSZ: u16 = 8192;
     130              : pub const RELSEG_SIZE: u32 = 1024 * 1024 * 1024 / (BLCKSZ as u32);
     131              : pub const XLOG_BLCKSZ: usize = 8192;
     132              : pub const WAL_SEGMENT_SIZE: usize = 16 * 1024 * 1024;
     133              : 
     134              : pub const MAX_SEND_SIZE: usize = XLOG_BLCKSZ * 16;
     135              : 
     136              : // Export some version independent functions that are used outside of this mod
     137              : pub use v14::xlog_utils::encode_logical_message;
     138              : pub use v14::xlog_utils::from_pg_timestamp;
     139              : pub use v14::xlog_utils::get_current_timestamp;
     140              : pub use v14::xlog_utils::to_pg_timestamp;
     141              : pub use v14::xlog_utils::XLogFileName;
     142              : 
     143              : pub use v14::bindings::DBState_DB_SHUTDOWNED;
     144              : 
     145           84 : pub fn bkpimage_is_compressed(bimg_info: u8, version: u32) -> anyhow::Result<bool> {
     146           84 :     dispatch_pgversion!(version, Ok(pgv::bindings::bkpimg_is_compressed(bimg_info)))
     147           84 : }
     148              : 
     149            0 : pub fn generate_wal_segment(
     150            0 :     segno: u64,
     151            0 :     system_id: u64,
     152            0 :     pg_version: u32,
     153            0 :     lsn: Lsn,
     154            0 : ) -> Result<Bytes, SerializeError> {
     155            0 :     assert_eq!(segno, lsn.segment_number(WAL_SEGMENT_SIZE));
     156              : 
     157              :     dispatch_pgversion!(
     158            0 :         pg_version,
     159            0 :         pgv::xlog_utils::generate_wal_segment(segno, system_id, lsn),
     160            0 :         Err(SerializeError::BadInput)
     161              :     )
     162            0 : }
     163              : 
     164            0 : pub fn generate_pg_control(
     165            0 :     pg_control_bytes: &[u8],
     166            0 :     checkpoint_bytes: &[u8],
     167            0 :     lsn: Lsn,
     168            0 :     pg_version: u32,
     169            0 : ) -> anyhow::Result<(Bytes, u64)> {
     170            0 :     dispatch_pgversion!(
     171            0 :         pg_version,
     172            0 :         pgv::xlog_utils::generate_pg_control(pg_control_bytes, checkpoint_bytes, lsn),
     173            0 :         anyhow::bail!("Unknown version {}", pg_version)
     174              :     )
     175            0 : }
     176              : 
     177              : // PG timeline is always 1, changing it doesn't have any useful meaning in Neon.
     178              : //
     179              : // NOTE: this is not to be confused with Neon timelines; different concept!
     180              : //
     181              : // It's a shaky assumption, that it's always 1. We might import a
     182              : // PostgreSQL data directory that has gone through timeline bumps,
     183              : // for example. FIXME later.
     184              : pub const PG_TLI: u32 = 1;
     185              : 
     186              : //  See TransactionIdIsNormal in transam.h
     187            0 : pub const fn transaction_id_is_normal(id: TransactionId) -> bool {
     188            0 :     id > pg_constants::FIRST_NORMAL_TRANSACTION_ID
     189            0 : }
     190              : 
     191              : // See TransactionIdPrecedes in transam.c
     192            0 : pub const fn transaction_id_precedes(id1: TransactionId, id2: TransactionId) -> bool {
     193            0 :     /*
     194            0 :      * If either ID is a permanent XID then we can just do unsigned
     195            0 :      * comparison.  If both are normal, do a modulo-2^32 comparison.
     196            0 :      */
     197            0 : 
     198            0 :     if !(transaction_id_is_normal(id1)) || !transaction_id_is_normal(id2) {
     199            0 :         return id1 < id2;
     200            0 :     }
     201            0 : 
     202            0 :     let diff = id1.wrapping_sub(id2) as i32;
     203            0 :     diff < 0
     204            0 : }
     205              : 
     206              : // Check if page is not yet initialized (port of Postgres PageIsInit() macro)
     207           24 : pub fn page_is_new(pg: &[u8]) -> bool {
     208           24 :     pg[14] == 0 && pg[15] == 0 // pg_upper == 0
     209           24 : }
     210              : 
     211              : // ExtractLSN from page header
     212            0 : pub fn page_get_lsn(pg: &[u8]) -> Lsn {
     213            0 :     Lsn(
     214            0 :         ((u32::from_le_bytes(pg[0..4].try_into().unwrap()) as u64) << 32)
     215            0 :             | u32::from_le_bytes(pg[4..8].try_into().unwrap()) as u64,
     216            0 :     )
     217            0 : }
     218              : 
     219           18 : pub fn page_set_lsn(pg: &mut [u8], lsn: Lsn) {
     220           18 :     pg[0..4].copy_from_slice(&((lsn.0 >> 32) as u32).to_le_bytes());
     221           18 :     pg[4..8].copy_from_slice(&(lsn.0 as u32).to_le_bytes());
     222           18 : }
     223              : 
     224              : // This is port of function with the same name from freespace.c.
     225              : // The only difference is that it does not have "level" parameter because XLogRecordPageWithFreeSpace
     226              : // always call it with level=FSM_BOTTOM_LEVEL
     227            0 : pub fn fsm_logical_to_physical(addr: BlockNumber) -> BlockNumber {
     228            0 :     let mut leafno = addr;
     229            0 :     const FSM_TREE_DEPTH: u32 = if pg_constants::SLOTS_PER_FSM_PAGE >= 1626 {
     230            0 :         3
     231            0 :     } else {
     232            0 :         4
     233            0 :     };
     234            0 : 
     235            0 :     /* Count upper level nodes required to address the leaf page */
     236            0 :     let mut pages: BlockNumber = 0;
     237            0 :     for _l in 0..FSM_TREE_DEPTH {
     238            0 :         pages += leafno + 1;
     239            0 :         leafno /= pg_constants::SLOTS_PER_FSM_PAGE;
     240            0 :     }
     241              :     /* Turn the page count into 0-based block number */
     242            0 :     pages - 1
     243            0 : }
     244              : 
     245              : pub mod waldecoder {
     246              :     use bytes::{Buf, Bytes, BytesMut};
     247              :     use std::num::NonZeroU32;
     248              :     use thiserror::Error;
     249              :     use utils::lsn::Lsn;
     250              : 
     251              :     pub enum State {
     252              :         WaitingForRecord,
     253              :         ReassemblingRecord {
     254              :             recordbuf: BytesMut,
     255              :             contlen: NonZeroU32,
     256              :         },
     257              :         SkippingEverything {
     258              :             skip_until_lsn: Lsn,
     259              :         },
     260              :     }
     261              : 
     262              :     pub struct WalStreamDecoder {
     263              :         pub lsn: Lsn,
     264              :         pub pg_version: u32,
     265              :         pub inputbuf: BytesMut,
     266              :         pub state: State,
     267              :     }
     268              : 
     269            0 :     #[derive(Error, Debug, Clone)]
     270              :     #[error("{msg} at {lsn}")]
     271              :     pub struct WalDecodeError {
     272              :         pub msg: String,
     273              :         pub lsn: Lsn,
     274              :     }
     275              : 
     276              :     impl WalStreamDecoder {
     277        82358 :         pub fn new(lsn: Lsn, pg_version: u32) -> WalStreamDecoder {
     278        82358 :             WalStreamDecoder {
     279        82358 :                 lsn,
     280        82358 :                 pg_version,
     281        82358 :                 inputbuf: BytesMut::new(),
     282        82358 :                 state: State::WaitingForRecord,
     283        82358 :             }
     284        82358 :         }
     285              : 
     286              :         // The latest LSN position fed to the decoder.
     287         4144 :         pub fn available(&self) -> Lsn {
     288         4144 :             self.lsn + self.inputbuf.remaining() as u64
     289         4144 :         }
     290              : 
     291       508612 :         pub fn feed_bytes(&mut self, buf: &[u8]) {
     292       508612 :             self.inputbuf.extend_from_slice(buf);
     293       508612 :         }
     294              : 
     295       737463 :         pub fn poll_decode(&mut self) -> Result<Option<(Lsn, Bytes)>, WalDecodeError> {
     296       737463 :             dispatch_pgversion!(
     297       737463 :                 self.pg_version,
     298              :                 {
     299              :                     use pgv::waldecoder_handler::WalStreamDecoderHandler;
     300         8334 :                     self.poll_decode_internal()
     301              :                 },
     302            0 :                 Err(WalDecodeError {
     303            0 :                     msg: format!("Unknown version {}", self.pg_version),
     304            0 :                     lsn: self.lsn,
     305            0 :                 })
     306              :             )
     307       737463 :         }
     308              :     }
     309              : }
        

Generated by: LCOV version 2.1-beta