LCOV - code coverage report
Current view: top level - safekeeper/src - safekeeper.rs (source / functions) Coverage Total Hit
Test: 960803fca14b2e843c565dddf575f7017d250bc3.info Lines: 84.5 % 828 700
Test Date: 2024-06-22 23:41:44 Functions: 52.8 % 214 113

            Line data    Source code
       1              : //! Acceptor part of proposer-acceptor consensus algorithm.
       2              : 
       3              : use anyhow::{bail, Context, Result};
       4              : use byteorder::{LittleEndian, ReadBytesExt};
       5              : use bytes::{Buf, BufMut, Bytes, BytesMut};
       6              : 
       7              : use postgres_ffi::{TimeLineID, MAX_SEND_SIZE};
       8              : use serde::{Deserialize, Serialize};
       9              : use std::cmp::max;
      10              : use std::cmp::min;
      11              : use std::fmt;
      12              : use std::io::Read;
      13              : use storage_broker::proto::SafekeeperTimelineInfo;
      14              : 
      15              : use tracing::*;
      16              : 
      17              : use crate::control_file;
      18              : use crate::send_wal::HotStandbyFeedback;
      19              : 
      20              : use crate::state::TimelineState;
      21              : use crate::wal_storage;
      22              : use pq_proto::SystemId;
      23              : use utils::pageserver_feedback::PageserverFeedback;
      24              : use utils::{
      25              :     bin_ser::LeSer,
      26              :     id::{NodeId, TenantId, TimelineId},
      27              :     lsn::Lsn,
      28              : };
      29              : 
      30              : const SK_PROTOCOL_VERSION: u32 = 2;
      31              : pub const UNKNOWN_SERVER_VERSION: u32 = 0;
      32              : 
      33              : /// Consensus logical timestamp.
      34              : pub type Term = u64;
      35              : pub const INVALID_TERM: Term = 0;
      36              : 
      37            8 : #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
      38              : pub struct TermLsn {
      39              :     pub term: Term,
      40              :     pub lsn: Lsn,
      41              : }
      42              : 
      43              : // Creation from tuple provides less typing (e.g. for unit tests).
      44              : impl From<(Term, Lsn)> for TermLsn {
      45           36 :     fn from(pair: (Term, Lsn)) -> TermLsn {
      46           36 :         TermLsn {
      47           36 :             term: pair.0,
      48           36 :             lsn: pair.1,
      49           36 :         }
      50           36 :     }
      51              : }
      52              : 
      53           12 : #[derive(Clone, Serialize, Deserialize, PartialEq)]
      54              : pub struct TermHistory(pub Vec<TermLsn>);
      55              : 
      56              : impl TermHistory {
      57        11431 :     pub fn empty() -> TermHistory {
      58        11431 :         TermHistory(Vec::new())
      59        11431 :     }
      60              : 
      61              :     // Parse TermHistory as n_entries followed by TermLsn pairs
      62         5811 :     pub fn from_bytes(bytes: &mut Bytes) -> Result<TermHistory> {
      63         5811 :         if bytes.remaining() < 4 {
      64            0 :             bail!("TermHistory misses len");
      65         5811 :         }
      66         5811 :         let n_entries = bytes.get_u32_le();
      67         5811 :         let mut res = Vec::with_capacity(n_entries as usize);
      68         5811 :         for _ in 0..n_entries {
      69        48684 :             if bytes.remaining() < 16 {
      70            0 :                 bail!("TermHistory is incomplete");
      71        48684 :             }
      72        48684 :             res.push(TermLsn {
      73        48684 :                 term: bytes.get_u64_le(),
      74        48684 :                 lsn: bytes.get_u64_le().into(),
      75        48684 :             })
      76              :         }
      77         5811 :         Ok(TermHistory(res))
      78         5811 :     }
      79              : 
      80              :     /// Return copy of self with switches happening strictly after up_to
      81              :     /// truncated.
      82        28464 :     pub fn up_to(&self, up_to: Lsn) -> TermHistory {
      83        28464 :         let mut res = Vec::with_capacity(self.0.len());
      84       151420 :         for e in &self.0 {
      85       123004 :             if e.lsn > up_to {
      86           48 :                 break;
      87       122956 :             }
      88       122956 :             res.push(*e);
      89              :         }
      90        28464 :         TermHistory(res)
      91        28464 :     }
      92              : 
      93              :     /// Find point of divergence between leader (walproposer) term history and
      94              :     /// safekeeper. Arguments are not symmetrics as proposer history ends at
      95              :     /// +infinity while safekeeper at flush_lsn.
      96              :     /// C version is at walproposer SendProposerElected.
      97            8 :     pub fn find_highest_common_point(
      98            8 :         prop_th: &TermHistory,
      99            8 :         sk_th: &TermHistory,
     100            8 :         sk_wal_end: Lsn,
     101            8 :     ) -> Option<TermLsn> {
     102            8 :         let (prop_th, sk_th) = (&prop_th.0, &sk_th.0); // avoid .0 below
     103              : 
     104            8 :         if let Some(sk_th_last) = sk_th.last() {
     105            8 :             assert!(
     106            8 :                 sk_th_last.lsn <= sk_wal_end,
     107            0 :                 "safekeeper term history end {:?} LSN is higher than WAL end {:?}",
     108              :                 sk_th_last,
     109              :                 sk_wal_end
     110              :             );
     111            0 :         }
     112              : 
     113              :         // find last common term, if any...
     114            8 :         let mut last_common_idx = None;
     115           16 :         for i in 0..min(sk_th.len(), prop_th.len()) {
     116           16 :             if prop_th[i].term != sk_th[i].term {
     117            4 :                 break;
     118           12 :             }
     119           12 :             // If term is the same, LSN must be equal as well.
     120           12 :             assert!(
     121           12 :                 prop_th[i].lsn == sk_th[i].lsn,
     122            0 :                 "same term {} has different start LSNs: prop {}, sk {}",
     123            0 :                 prop_th[i].term,
     124            0 :                 prop_th[i].lsn,
     125            0 :                 sk_th[i].lsn
     126              :             );
     127           12 :             last_common_idx = Some(i);
     128              :         }
     129            8 :         let last_common_idx = match last_common_idx {
     130            2 :             None => return None, // no common point
     131            6 :             Some(lci) => lci,
     132            6 :         };
     133            6 :         // Now find where it ends at both prop and sk and take min. End of
     134            6 :         // (common) term is the start of the next except it is the last one;
     135            6 :         // there it is flush_lsn in case of safekeeper or, in case of proposer
     136            6 :         // +infinity, so we just take flush_lsn then.
     137            6 :         if last_common_idx == prop_th.len() - 1 {
     138            2 :             Some(TermLsn {
     139            2 :                 term: prop_th[last_common_idx].term,
     140            2 :                 lsn: sk_wal_end,
     141            2 :             })
     142              :         } else {
     143            4 :             let prop_common_term_end = prop_th[last_common_idx + 1].lsn;
     144            4 :             let sk_common_term_end = if last_common_idx + 1 < sk_th.len() {
     145            2 :                 sk_th[last_common_idx + 1].lsn
     146              :             } else {
     147            2 :                 sk_wal_end
     148              :             };
     149            4 :             Some(TermLsn {
     150            4 :                 term: prop_th[last_common_idx].term,
     151            4 :                 lsn: min(prop_common_term_end, sk_common_term_end),
     152            4 :             })
     153              :         }
     154            8 :     }
     155              : }
     156              : 
     157              : /// Display only latest entries for Debug.
     158              : impl fmt::Debug for TermHistory {
     159          400 :     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
     160          400 :         let n_printed = 20;
     161          400 :         write!(
     162          400 :             fmt,
     163          400 :             "{}{:?}",
     164          400 :             if self.0.len() > n_printed { "... " } else { "" },
     165          400 :             self.0
     166          400 :                 .iter()
     167          400 :                 .rev()
     168          400 :                 .take(n_printed)
     169         2216 :                 .map(|&e| (e.term, e.lsn)) // omit TermSwitchEntry
     170          400 :                 .collect::<Vec<_>>()
     171          400 :         )
     172          400 :     }
     173              : }
     174              : 
     175              : /// Unique id of proposer. Not needed for correctness, used for monitoring.
     176              : pub type PgUuid = [u8; 16];
     177              : 
     178              : /// Persistent consensus state of the acceptor.
     179           12 : #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
     180              : pub struct AcceptorState {
     181              :     /// acceptor's last term it voted for (advanced in 1 phase)
     182              :     pub term: Term,
     183              :     /// History of term switches for safekeeper's WAL.
     184              :     /// Actually it often goes *beyond* WAL contents as we adopt term history
     185              :     /// from the proposer before recovery.
     186              :     pub term_history: TermHistory,
     187              : }
     188              : 
     189              : impl AcceptorState {
     190              :     /// acceptor's last_log_term is the term of the highest entry in the log
     191         5817 :     pub fn get_last_log_term(&self, flush_lsn: Lsn) -> Term {
     192         5817 :         let th = self.term_history.up_to(flush_lsn);
     193         5817 :         match th.0.last() {
     194         4808 :             Some(e) => e.term,
     195         1009 :             None => 0,
     196              :         }
     197         5817 :     }
     198              : }
     199              : 
     200              : /// Information about Postgres. Safekeeper gets it once and then verifies
     201              : /// all further connections from computes match.
     202            8 : #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
     203              : pub struct ServerInfo {
     204              :     /// Postgres server version
     205              :     pub pg_version: u32,
     206              :     pub system_id: SystemId,
     207              :     pub wal_seg_size: u32,
     208              : }
     209              : 
     210            4 : #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
     211              : pub struct PersistedPeerInfo {
     212              :     /// LSN up to which safekeeper offloaded WAL to s3.
     213              :     pub backup_lsn: Lsn,
     214              :     /// Term of the last entry.
     215              :     pub term: Term,
     216              :     /// LSN of the last record.
     217              :     pub flush_lsn: Lsn,
     218              :     /// Up to which LSN safekeeper regards its WAL as committed.
     219              :     pub commit_lsn: Lsn,
     220              : }
     221              : 
     222              : impl PersistedPeerInfo {
     223            0 :     pub fn new() -> Self {
     224            0 :         Self {
     225            0 :             backup_lsn: Lsn::INVALID,
     226            0 :             term: INVALID_TERM,
     227            0 :             flush_lsn: Lsn(0),
     228            0 :             commit_lsn: Lsn(0),
     229            0 :         }
     230            0 :     }
     231              : }
     232              : 
     233              : // make clippy happy
     234              : impl Default for PersistedPeerInfo {
     235            0 :     fn default() -> Self {
     236            0 :         Self::new()
     237            0 :     }
     238              : }
     239              : 
     240              : // protocol messages
     241              : 
     242              : /// Initial Proposer -> Acceptor message
     243       154666 : #[derive(Debug, Deserialize)]
     244              : pub struct ProposerGreeting {
     245              :     /// proposer-acceptor protocol version
     246              :     pub protocol_version: u32,
     247              :     /// Postgres server version
     248              :     pub pg_version: u32,
     249              :     pub proposer_id: PgUuid,
     250              :     pub system_id: SystemId,
     251              :     pub timeline_id: TimelineId,
     252              :     pub tenant_id: TenantId,
     253              :     pub tli: TimeLineID,
     254              :     pub wal_seg_size: u32,
     255              : }
     256              : 
     257              : /// Acceptor -> Proposer initial response: the highest term known to me
     258              : /// (acceptor voted for).
     259              : #[derive(Debug, Serialize)]
     260              : pub struct AcceptorGreeting {
     261              :     term: u64,
     262              :     node_id: NodeId,
     263              : }
     264              : 
     265              : /// Vote request sent from proposer to safekeepers
     266        22643 : #[derive(Debug, Deserialize)]
     267              : pub struct VoteRequest {
     268              :     pub term: Term,
     269              : }
     270              : 
     271              : /// Vote itself, sent from safekeeper to proposer
     272              : #[derive(Debug, Serialize)]
     273              : pub struct VoteResponse {
     274              :     pub term: Term, // safekeeper's current term; if it is higher than proposer's, the compute is out of date.
     275              :     vote_given: u64, // fixme u64 due to padding
     276              :     // Safekeeper flush_lsn (end of WAL) + history of term switches allow
     277              :     // proposer to choose the most advanced one.
     278              :     pub flush_lsn: Lsn,
     279              :     truncate_lsn: Lsn,
     280              :     pub term_history: TermHistory,
     281              :     timeline_start_lsn: Lsn,
     282              : }
     283              : 
     284              : /*
     285              :  * Proposer -> Acceptor message announcing proposer is elected and communicating
     286              :  * term history to it.
     287              :  */
     288              : #[derive(Debug)]
     289              : pub struct ProposerElected {
     290              :     pub term: Term,
     291              :     pub start_streaming_at: Lsn,
     292              :     pub term_history: TermHistory,
     293              :     pub timeline_start_lsn: Lsn,
     294              : }
     295              : 
     296              : /// Request with WAL message sent from proposer to safekeeper. Along the way it
     297              : /// communicates commit_lsn.
     298              : #[derive(Debug)]
     299              : pub struct AppendRequest {
     300              :     pub h: AppendRequestHeader,
     301              :     pub wal_data: Bytes,
     302              : }
     303        19531 : #[derive(Debug, Clone, Deserialize)]
     304              : pub struct AppendRequestHeader {
     305              :     // safekeeper's current term; if it is higher than proposer's, the compute is out of date.
     306              :     pub term: Term,
     307              :     // TODO: remove this field from the protocol, it in unused -- LSN of term
     308              :     // switch can be taken from ProposerElected (as well as from term history).
     309              :     pub term_start_lsn: Lsn,
     310              :     /// start position of message in WAL
     311              :     pub begin_lsn: Lsn,
     312              :     /// end position of message in WAL
     313              :     pub end_lsn: Lsn,
     314              :     /// LSN committed by quorum of safekeepers
     315              :     pub commit_lsn: Lsn,
     316              :     /// minimal LSN which may be needed by proposer to perform recovery of some safekeeper
     317              :     pub truncate_lsn: Lsn,
     318              :     // only for logging/debugging
     319              :     pub proposer_uuid: PgUuid,
     320              : }
     321              : 
     322              : /// Report safekeeper state to proposer
     323              : #[derive(Debug, Serialize, Clone)]
     324              : pub struct AppendResponse {
     325              :     // Current term of the safekeeper; if it is higher than proposer's, the
     326              :     // compute is out of date.
     327              :     pub term: Term,
     328              :     // Flushed end of wal on safekeeper; one should be always mindful from what
     329              :     // term history this value comes, either checking history directly or
     330              :     // observing term being set to one for which WAL truncation is known to have
     331              :     // happened.
     332              :     pub flush_lsn: Lsn,
     333              :     // We report back our awareness about which WAL is committed, as this is
     334              :     // a criterion for walproposer --sync mode exit
     335              :     pub commit_lsn: Lsn,
     336              :     pub hs_feedback: HotStandbyFeedback,
     337              :     pub pageserver_feedback: Option<PageserverFeedback>,
     338              : }
     339              : 
     340              : impl AppendResponse {
     341            1 :     fn term_only(term: Term) -> AppendResponse {
     342            1 :         AppendResponse {
     343            1 :             term,
     344            1 :             flush_lsn: Lsn(0),
     345            1 :             commit_lsn: Lsn(0),
     346            1 :             hs_feedback: HotStandbyFeedback::empty(),
     347            1 :             pageserver_feedback: None,
     348            1 :         }
     349            1 :     }
     350              : }
     351              : 
     352              : /// Proposer -> Acceptor messages
     353              : #[derive(Debug)]
     354              : pub enum ProposerAcceptorMessage {
     355              :     Greeting(ProposerGreeting),
     356              :     VoteRequest(VoteRequest),
     357              :     Elected(ProposerElected),
     358              :     AppendRequest(AppendRequest),
     359              :     NoFlushAppendRequest(AppendRequest),
     360              :     FlushWAL,
     361              : }
     362              : 
     363              : impl ProposerAcceptorMessage {
     364              :     /// Parse proposer message.
     365       202651 :     pub fn parse(msg_bytes: Bytes) -> Result<ProposerAcceptorMessage> {
     366       202651 :         // xxx using Reader is inefficient but easy to work with bincode
     367       202651 :         let mut stream = msg_bytes.reader();
     368              :         // u64 is here to avoid padding; it will be removed once we stop packing C structs into the wire as is
     369       202651 :         let tag = stream.read_u64::<LittleEndian>()? as u8 as char;
     370       202651 :         match tag {
     371              :             'g' => {
     372       154666 :                 let msg = ProposerGreeting::des_from(&mut stream)?;
     373       154666 :                 Ok(ProposerAcceptorMessage::Greeting(msg))
     374              :             }
     375              :             'v' => {
     376        22643 :                 let msg = VoteRequest::des_from(&mut stream)?;
     377        22643 :                 Ok(ProposerAcceptorMessage::VoteRequest(msg))
     378              :             }
     379              :             'e' => {
     380         5811 :                 let mut msg_bytes = stream.into_inner();
     381         5811 :                 if msg_bytes.remaining() < 16 {
     382            0 :                     bail!("ProposerElected message is not complete");
     383         5811 :                 }
     384         5811 :                 let term = msg_bytes.get_u64_le();
     385         5811 :                 let start_streaming_at = msg_bytes.get_u64_le().into();
     386         5811 :                 let term_history = TermHistory::from_bytes(&mut msg_bytes)?;
     387         5811 :                 if msg_bytes.remaining() < 8 {
     388            0 :                     bail!("ProposerElected message is not complete");
     389         5811 :                 }
     390         5811 :                 let timeline_start_lsn = msg_bytes.get_u64_le().into();
     391         5811 :                 let msg = ProposerElected {
     392         5811 :                     term,
     393         5811 :                     start_streaming_at,
     394         5811 :                     timeline_start_lsn,
     395         5811 :                     term_history,
     396         5811 :                 };
     397         5811 :                 Ok(ProposerAcceptorMessage::Elected(msg))
     398              :             }
     399              :             'a' => {
     400              :                 // read header followed by wal data
     401        19531 :                 let hdr = AppendRequestHeader::des_from(&mut stream)?;
     402        19531 :                 let rec_size = hdr
     403        19531 :                     .end_lsn
     404        19531 :                     .checked_sub(hdr.begin_lsn)
     405        19531 :                     .context("begin_lsn > end_lsn in AppendRequest")?
     406              :                     .0 as usize;
     407        19531 :                 if rec_size > MAX_SEND_SIZE {
     408            0 :                     bail!(
     409            0 :                         "AppendRequest is longer than MAX_SEND_SIZE ({})",
     410            0 :                         MAX_SEND_SIZE
     411            0 :                     );
     412        19531 :                 }
     413        19531 : 
     414        19531 :                 let mut wal_data_vec: Vec<u8> = vec![0; rec_size];
     415        19531 :                 stream.read_exact(&mut wal_data_vec)?;
     416        19531 :                 let wal_data = Bytes::from(wal_data_vec);
     417        19531 :                 let msg = AppendRequest { h: hdr, wal_data };
     418        19531 : 
     419        19531 :                 Ok(ProposerAcceptorMessage::AppendRequest(msg))
     420              :             }
     421            0 :             _ => bail!("unknown proposer-acceptor message tag: {}", tag),
     422              :         }
     423       202651 :     }
     424              : }
     425              : 
     426              : /// Acceptor -> Proposer messages
     427              : #[derive(Debug)]
     428              : pub enum AcceptorProposerMessage {
     429              :     Greeting(AcceptorGreeting),
     430              :     VoteResponse(VoteResponse),
     431              :     AppendResponse(AppendResponse),
     432              : }
     433              : 
     434              : impl AcceptorProposerMessage {
     435              :     /// Serialize acceptor -> proposer message.
     436       193523 :     pub fn serialize(&self, buf: &mut BytesMut) -> Result<()> {
     437       193523 :         match self {
     438       154666 :             AcceptorProposerMessage::Greeting(msg) => {
     439       154666 :                 buf.put_u64_le('g' as u64);
     440       154666 :                 buf.put_u64_le(msg.term);
     441       154666 :                 buf.put_u64_le(msg.node_id.0);
     442       154666 :             }
     443        22643 :             AcceptorProposerMessage::VoteResponse(msg) => {
     444        22643 :                 buf.put_u64_le('v' as u64);
     445        22643 :                 buf.put_u64_le(msg.term);
     446        22643 :                 buf.put_u64_le(msg.vote_given);
     447        22643 :                 buf.put_u64_le(msg.flush_lsn.into());
     448        22643 :                 buf.put_u64_le(msg.truncate_lsn.into());
     449        22643 :                 buf.put_u32_le(msg.term_history.0.len() as u32);
     450       103270 :                 for e in &msg.term_history.0 {
     451        80627 :                     buf.put_u64_le(e.term);
     452        80627 :                     buf.put_u64_le(e.lsn.into());
     453        80627 :                 }
     454        22643 :                 buf.put_u64_le(msg.timeline_start_lsn.into());
     455              :             }
     456        16214 :             AcceptorProposerMessage::AppendResponse(msg) => {
     457        16214 :                 buf.put_u64_le('a' as u64);
     458        16214 :                 buf.put_u64_le(msg.term);
     459        16214 :                 buf.put_u64_le(msg.flush_lsn.into());
     460        16214 :                 buf.put_u64_le(msg.commit_lsn.into());
     461        16214 :                 buf.put_i64_le(msg.hs_feedback.ts);
     462        16214 :                 buf.put_u64_le(msg.hs_feedback.xmin);
     463        16214 :                 buf.put_u64_le(msg.hs_feedback.catalog_xmin);
     464              : 
     465              :                 // AsyncReadMessage in walproposer.c will not try to decode pageserver_feedback
     466              :                 // if it is not present.
     467        16214 :                 if let Some(ref msg) = msg.pageserver_feedback {
     468            0 :                     msg.serialize(buf);
     469        16214 :                 }
     470              :             }
     471              :         }
     472              : 
     473       193523 :         Ok(())
     474       193523 :     }
     475              : }
     476              : 
     477              : /// Safekeeper implements consensus to reliably persist WAL across nodes.
     478              : /// It controls all WAL disk writes and updates of control file.
     479              : ///
     480              : /// Currently safekeeper processes:
     481              : /// - messages from compute (proposers) and provides replies
     482              : /// - messages from broker peers
     483              : pub struct SafeKeeper<CTRL: control_file::Storage, WAL: wal_storage::Storage> {
     484              :     /// LSN since the proposer safekeeper currently talking to appends WAL;
     485              :     /// determines last_log_term switch point.
     486              :     pub term_start_lsn: Lsn,
     487              : 
     488              :     pub state: TimelineState<CTRL>, // persistent state storage
     489              :     pub wal_store: WAL,
     490              : 
     491              :     node_id: NodeId, // safekeeper's node id
     492              : }
     493              : 
     494              : impl<CTRL, WAL> SafeKeeper<CTRL, WAL>
     495              : where
     496              :     CTRL: control_file::Storage,
     497              :     WAL: wal_storage::Storage,
     498              : {
     499              :     /// Accepts a control file storage containing the safekeeper state.
     500              :     /// State must be initialized, i.e. contain filled `tenant_id`, `timeline_id`
     501              :     /// and `server` (`wal_seg_size` inside it) fields.
     502        70110 :     pub fn new(state: CTRL, wal_store: WAL, node_id: NodeId) -> Result<SafeKeeper<CTRL, WAL>> {
     503        70110 :         if state.tenant_id == TenantId::from([0u8; 16])
     504        70110 :             || state.timeline_id == TimelineId::from([0u8; 16])
     505              :         {
     506            0 :             bail!(
     507            0 :                 "Calling SafeKeeper::new with empty tenant_id ({}) or timeline_id ({})",
     508            0 :                 state.tenant_id,
     509            0 :                 state.timeline_id
     510            0 :             );
     511        70110 :         }
     512        70110 : 
     513        70110 :         Ok(SafeKeeper {
     514        70110 :             term_start_lsn: Lsn(0),
     515        70110 :             state: TimelineState::new(state),
     516        70110 :             wal_store,
     517        70110 :             node_id,
     518        70110 :         })
     519        70110 :     }
     520              : 
     521              :     /// Get history of term switches for the available WAL
     522        22647 :     fn get_term_history(&self) -> TermHistory {
     523        22647 :         self.state
     524        22647 :             .acceptor_state
     525        22647 :             .term_history
     526        22647 :             .up_to(self.flush_lsn())
     527        22647 :     }
     528              : 
     529              :     /// Get current term.
     530            0 :     pub fn get_term(&self) -> Term {
     531            0 :         self.state.acceptor_state.term
     532            0 :     }
     533              : 
     534         5817 :     pub fn get_last_log_term(&self) -> Term {
     535         5817 :         self.state
     536         5817 :             .acceptor_state
     537         5817 :             .get_last_log_term(self.flush_lsn())
     538         5817 :     }
     539              : 
     540              :     /// wal_store wrapper avoiding commit_lsn <= flush_lsn violation when we don't have WAL yet.
     541        77464 :     pub fn flush_lsn(&self) -> Lsn {
     542        77464 :         max(self.wal_store.flush_lsn(), self.state.timeline_start_lsn)
     543        77464 :     }
     544              : 
     545              :     /// Process message from proposer and possibly form reply. Concurrent
     546              :     /// callers must exclude each other.
     547       218874 :     pub async fn process_msg(
     548       218874 :         &mut self,
     549       218874 :         msg: &ProposerAcceptorMessage,
     550       218874 :     ) -> Result<Option<AcceptorProposerMessage>> {
     551       218874 :         match msg {
     552       154666 :             ProposerAcceptorMessage::Greeting(msg) => self.handle_greeting(msg).await,
     553        22647 :             ProposerAcceptorMessage::VoteRequest(msg) => self.handle_vote_request(msg).await,
     554         5813 :             ProposerAcceptorMessage::Elected(msg) => self.handle_elected(msg).await,
     555            4 :             ProposerAcceptorMessage::AppendRequest(msg) => {
     556            4 :                 self.handle_append_request(msg, true).await
     557              :             }
     558        19531 :             ProposerAcceptorMessage::NoFlushAppendRequest(msg) => {
     559        19531 :                 self.handle_append_request(msg, false).await
     560              :             }
     561        16213 :             ProposerAcceptorMessage::FlushWAL => self.handle_flush().await,
     562              :         }
     563       218874 :     }
     564              : 
     565              :     /// Handle initial message from proposer: check its sanity and send my
     566              :     /// current term.
     567       154666 :     async fn handle_greeting(
     568       154666 :         &mut self,
     569       154666 :         msg: &ProposerGreeting,
     570       154666 :     ) -> Result<Option<AcceptorProposerMessage>> {
     571       154666 :         // Check protocol compatibility
     572       154666 :         if msg.protocol_version != SK_PROTOCOL_VERSION {
     573            0 :             bail!(
     574            0 :                 "incompatible protocol version {}, expected {}",
     575            0 :                 msg.protocol_version,
     576            0 :                 SK_PROTOCOL_VERSION
     577            0 :             );
     578       154666 :         }
     579       154666 :         /* Postgres major version mismatch is treated as fatal error
     580       154666 :          * because safekeepers parse WAL headers and the format
     581       154666 :          * may change between versions.
     582       154666 :          */
     583       154666 :         if msg.pg_version / 10000 != self.state.server.pg_version / 10000
     584            0 :             && self.state.server.pg_version != UNKNOWN_SERVER_VERSION
     585              :         {
     586            0 :             bail!(
     587            0 :                 "incompatible server version {}, expected {}",
     588            0 :                 msg.pg_version,
     589            0 :                 self.state.server.pg_version
     590            0 :             );
     591       154666 :         }
     592       154666 : 
     593       154666 :         if msg.tenant_id != self.state.tenant_id {
     594            0 :             bail!(
     595            0 :                 "invalid tenant ID, got {}, expected {}",
     596            0 :                 msg.tenant_id,
     597            0 :                 self.state.tenant_id
     598            0 :             );
     599       154666 :         }
     600       154666 :         if msg.timeline_id != self.state.timeline_id {
     601            0 :             bail!(
     602            0 :                 "invalid timeline ID, got {}, expected {}",
     603            0 :                 msg.timeline_id,
     604            0 :                 self.state.timeline_id
     605            0 :             );
     606       154666 :         }
     607       154666 :         if self.state.server.wal_seg_size != msg.wal_seg_size {
     608            0 :             bail!(
     609            0 :                 "invalid wal_seg_size, got {}, expected {}",
     610            0 :                 msg.wal_seg_size,
     611            0 :                 self.state.server.wal_seg_size
     612            0 :             );
     613       154666 :         }
     614       154666 : 
     615       154666 :         // system_id will be updated on mismatch
     616       154666 :         // sync-safekeepers doesn't know sysid and sends 0, ignore it
     617       154666 :         if self.state.server.system_id != msg.system_id && msg.system_id != 0 {
     618            0 :             if self.state.server.system_id != 0 {
     619            0 :                 warn!(
     620            0 :                     "unexpected system ID arrived, got {}, expected {}",
     621            0 :                     msg.system_id, self.state.server.system_id
     622              :                 );
     623            0 :             }
     624              : 
     625            0 :             let mut state = self.state.start_change();
     626            0 :             state.server.system_id = msg.system_id;
     627            0 :             if msg.pg_version != UNKNOWN_SERVER_VERSION {
     628            0 :                 state.server.pg_version = msg.pg_version;
     629            0 :             }
     630            0 :             self.state.finish_change(&state).await?;
     631       154666 :         }
     632              : 
     633       154666 :         info!(
     634            0 :             "processed greeting from walproposer {}, sending term {:?}",
     635         4832 :             msg.proposer_id.map(|b| format!("{:X}", b)).join(""),
     636            0 :             self.state.acceptor_state.term
     637              :         );
     638       154666 :         Ok(Some(AcceptorProposerMessage::Greeting(AcceptorGreeting {
     639       154666 :             term: self.state.acceptor_state.term,
     640       154666 :             node_id: self.node_id,
     641       154666 :         })))
     642       154666 :     }
     643              : 
     644              :     /// Give vote for the given term, if we haven't done that previously.
     645        22647 :     async fn handle_vote_request(
     646        22647 :         &mut self,
     647        22647 :         msg: &VoteRequest,
     648        22647 :     ) -> Result<Option<AcceptorProposerMessage>> {
     649        22647 :         // Once voted, we won't accept data from older proposers; flush
     650        22647 :         // everything we've already received so that new proposer starts
     651        22647 :         // streaming at end of our WAL, without overlap. Currently we truncate
     652        22647 :         // WAL at streaming point, so this avoids truncating already committed
     653        22647 :         // WAL.
     654        22647 :         //
     655        22647 :         // TODO: it would be smoother to not truncate committed piece at
     656        22647 :         // handle_elected instead. Currently not a big deal, as proposer is the
     657        22647 :         // only source of WAL; with peer2peer recovery it would be more
     658        22647 :         // important.
     659        22647 :         self.wal_store.flush_wal().await?;
     660              :         // initialize with refusal
     661        22647 :         let mut resp = VoteResponse {
     662        22647 :             term: self.state.acceptor_state.term,
     663        22647 :             vote_given: false as u64,
     664        22647 :             flush_lsn: self.flush_lsn(),
     665        22647 :             truncate_lsn: self.state.inmem.peer_horizon_lsn,
     666        22647 :             term_history: self.get_term_history(),
     667        22647 :             timeline_start_lsn: self.state.timeline_start_lsn,
     668        22647 :         };
     669        22647 :         if self.state.acceptor_state.term < msg.term {
     670        21583 :             let mut state = self.state.start_change();
     671        21583 :             state.acceptor_state.term = msg.term;
     672        21583 :             // persist vote before sending it out
     673        21583 :             self.state.finish_change(&state).await?;
     674              : 
     675        21583 :             resp.term = self.state.acceptor_state.term;
     676        21583 :             resp.vote_given = true as u64;
     677         1064 :         }
     678        22647 :         info!("processed VoteRequest for term {}: {:?}", msg.term, &resp);
     679        22647 :         Ok(Some(AcceptorProposerMessage::VoteResponse(resp)))
     680        22647 :     }
     681              : 
     682              :     /// Form AppendResponse from current state.
     683        16217 :     fn append_response(&self) -> AppendResponse {
     684        16217 :         let ar = AppendResponse {
     685        16217 :             term: self.state.acceptor_state.term,
     686        16217 :             flush_lsn: self.flush_lsn(),
     687        16217 :             commit_lsn: self.state.commit_lsn,
     688        16217 :             // will be filled by the upper code to avoid bothering safekeeper
     689        16217 :             hs_feedback: HotStandbyFeedback::empty(),
     690        16217 :             pageserver_feedback: None,
     691        16217 :         };
     692        16217 :         trace!("formed AppendResponse {:?}", ar);
     693        16217 :         ar
     694        16217 :     }
     695              : 
     696         5813 :     async fn handle_elected(
     697         5813 :         &mut self,
     698         5813 :         msg: &ProposerElected,
     699         5813 :     ) -> Result<Option<AcceptorProposerMessage>> {
     700         5813 :         info!("received ProposerElected {:?}", msg);
     701         5813 :         if self.state.acceptor_state.term < msg.term {
     702            2 :             let mut state = self.state.start_change();
     703            2 :             state.acceptor_state.term = msg.term;
     704            2 :             self.state.finish_change(&state).await?;
     705         5811 :         }
     706              : 
     707              :         // If our term is higher, ignore the message (next feedback will inform the compute)
     708         5813 :         if self.state.acceptor_state.term > msg.term {
     709            0 :             return Ok(None);
     710         5813 :         }
     711         5813 : 
     712         5813 :         // This might happen in a rare race when another (old) connection from
     713         5813 :         // the same walproposer writes + flushes WAL after this connection
     714         5813 :         // already sent flush_lsn in VoteRequest. It is generally safe to
     715         5813 :         // proceed, but to prevent commit_lsn surprisingly going down we should
     716         5813 :         // either refuse the session (simpler) or skip the part we already have
     717         5813 :         // from the stream (can be implemented).
     718         5813 :         if msg.term == self.get_last_log_term() && self.flush_lsn() > msg.start_streaming_at {
     719            0 :             bail!("refusing ProposerElected which is going to overwrite correct WAL: term={}, flush_lsn={}, start_streaming_at={}; restarting the handshake should help",
     720            0 :                    msg.term, self.flush_lsn(), msg.start_streaming_at)
     721         5813 :         }
     722         5813 :         // Otherwise we must never attempt to truncate committed data.
     723         5813 :         assert!(
     724         5813 :             msg.start_streaming_at >= self.state.inmem.commit_lsn,
     725            0 :             "attempt to truncate committed data: start_streaming_at={}, commit_lsn={}",
     726              :             msg.start_streaming_at,
     727              :             self.state.inmem.commit_lsn
     728              :         );
     729              : 
     730              :         // Before first WAL write initialize its segment. It makes first segment
     731              :         // pg_waldump'able because stream from compute doesn't include its
     732              :         // segment and page headers.
     733              :         //
     734              :         // If we fail before first WAL write flush this action would be
     735              :         // repeated, that's ok because it is idempotent.
     736         5813 :         if self.wal_store.flush_lsn() == Lsn::INVALID {
     737         1007 :             self.wal_store
     738         1007 :                 .initialize_first_segment(msg.start_streaming_at)
     739            0 :                 .await?;
     740         4806 :         }
     741              : 
     742              :         // TODO: cross check divergence point, check if msg.start_streaming_at corresponds to
     743              :         // intersection of our history and history from msg
     744              : 
     745              :         // truncate wal, update the LSNs
     746         5813 :         self.wal_store.truncate_wal(msg.start_streaming_at).await?;
     747              : 
     748              :         // and now adopt term history from proposer
     749              :         {
     750         5813 :             let mut state = self.state.start_change();
     751         5813 : 
     752         5813 :             // Here we learn initial LSN for the first time, set fields
     753         5813 :             // interested in that.
     754         5813 : 
     755         5813 :             if state.timeline_start_lsn == Lsn(0) {
     756              :                 // Remember point where WAL begins globally.
     757         1007 :                 state.timeline_start_lsn = msg.timeline_start_lsn;
     758         1007 :                 info!(
     759            0 :                     "setting timeline_start_lsn to {:?}",
     760              :                     state.timeline_start_lsn
     761              :                 );
     762         4806 :             }
     763         5813 :             if state.peer_horizon_lsn == Lsn(0) {
     764         1007 :                 // Update peer_horizon_lsn as soon as we know where timeline starts.
     765         1007 :                 // It means that peer_horizon_lsn cannot be zero after we know timeline_start_lsn.
     766         1007 :                 state.peer_horizon_lsn = msg.timeline_start_lsn;
     767         4806 :             }
     768         5813 :             if state.local_start_lsn == Lsn(0) {
     769         1007 :                 state.local_start_lsn = msg.start_streaming_at;
     770         1007 :                 info!("setting local_start_lsn to {:?}", state.local_start_lsn);
     771         4806 :             }
     772              :             // Initializing commit_lsn before acking first flushed record is
     773              :             // important to let find_end_of_wal skip the hole in the beginning
     774              :             // of the first segment.
     775              :             //
     776              :             // NB: on new clusters, this happens at the same time as
     777              :             // timeline_start_lsn initialization, it is taken outside to provide
     778              :             // upgrade.
     779         5813 :             state.commit_lsn = max(state.commit_lsn, state.timeline_start_lsn);
     780         5813 : 
     781         5813 :             // Initializing backup_lsn is useful to avoid making backup think it should upload 0 segment.
     782         5813 :             state.backup_lsn = max(state.backup_lsn, state.timeline_start_lsn);
     783         5813 :             // similar for remote_consistent_lsn
     784         5813 :             state.remote_consistent_lsn =
     785         5813 :                 max(state.remote_consistent_lsn, state.timeline_start_lsn);
     786         5813 : 
     787         5813 :             state.acceptor_state.term_history = msg.term_history.clone();
     788         5813 :             self.state.finish_change(&state).await?;
     789              :         }
     790              : 
     791         5813 :         info!("start receiving WAL since {:?}", msg.start_streaming_at);
     792              : 
     793              :         // Cache LSN where term starts to immediately fsync control file with
     794              :         // commit_lsn once we reach it -- sync-safekeepers finishes when
     795              :         // persisted commit_lsn on majority of safekeepers aligns.
     796         5813 :         self.term_start_lsn = match msg.term_history.0.last() {
     797            0 :             None => bail!("proposer elected with empty term history"),
     798         5813 :             Some(term_lsn_start) => term_lsn_start.lsn,
     799         5813 :         };
     800         5813 : 
     801         5813 :         Ok(None)
     802         5813 :     }
     803              : 
     804              :     /// Advance commit_lsn taking into account what we have locally.
     805              :     ///
     806              :     /// Note: it is assumed that 'WAL we have is from the right term' check has
     807              :     /// already been done outside.
     808         9791 :     async fn update_commit_lsn(&mut self, mut candidate: Lsn) -> Result<()> {
     809         9791 :         // Both peers and walproposer communicate this value, we might already
     810         9791 :         // have a fresher (higher) version.
     811         9791 :         candidate = max(candidate, self.state.inmem.commit_lsn);
     812         9791 :         let commit_lsn = min(candidate, self.flush_lsn());
     813         9791 :         assert!(
     814         9791 :             commit_lsn >= self.state.inmem.commit_lsn,
     815            0 :             "commit_lsn monotonicity violated: old={} new={}",
     816              :             self.state.inmem.commit_lsn,
     817              :             commit_lsn
     818              :         );
     819              : 
     820         9791 :         self.state.inmem.commit_lsn = commit_lsn;
     821         9791 : 
     822         9791 :         // If new commit_lsn reached term switch, force sync of control
     823         9791 :         // file: walproposer in sync mode is very interested when this
     824         9791 :         // happens. Note: this is for sync-safekeepers mode only, as
     825         9791 :         // otherwise commit_lsn might jump over term_start_lsn.
     826         9791 :         if commit_lsn >= self.term_start_lsn && self.state.commit_lsn < self.term_start_lsn {
     827          745 :             self.state.flush().await?;
     828         9046 :         }
     829              : 
     830         9791 :         Ok(())
     831         9791 :     }
     832              : 
     833              :     /// Handle request to append WAL.
     834              :     #[allow(clippy::comparison_chain)]
     835        19535 :     async fn handle_append_request(
     836        19535 :         &mut self,
     837        19535 :         msg: &AppendRequest,
     838        19535 :         require_flush: bool,
     839        19535 :     ) -> Result<Option<AcceptorProposerMessage>> {
     840        19535 :         if self.state.acceptor_state.term < msg.h.term {
     841            0 :             bail!("got AppendRequest before ProposerElected");
     842        19535 :         }
     843        19535 : 
     844        19535 :         // If our term is higher, immediately refuse the message.
     845        19535 :         if self.state.acceptor_state.term > msg.h.term {
     846            1 :             let resp = AppendResponse::term_only(self.state.acceptor_state.term);
     847            1 :             return Ok(Some(AcceptorProposerMessage::AppendResponse(resp)));
     848        19534 :         }
     849        19534 : 
     850        19534 :         // Now we know that we are in the same term as the proposer,
     851        19534 :         // processing the message.
     852        19534 : 
     853        19534 :         self.state.inmem.proposer_uuid = msg.h.proposer_uuid;
     854        19534 : 
     855        19534 :         // do the job
     856        19534 :         if !msg.wal_data.is_empty() {
     857         3795 :             self.wal_store
     858         3795 :                 .write_wal(msg.h.begin_lsn, &msg.wal_data)
     859            0 :                 .await?;
     860        15739 :         }
     861              : 
     862              :         // flush wal to the disk, if required
     863        19534 :         if require_flush {
     864            4 :             self.wal_store.flush_wal().await?;
     865        19530 :         }
     866              : 
     867              :         // Update commit_lsn.
     868        19534 :         if msg.h.commit_lsn != Lsn(0) {
     869         9791 :             self.update_commit_lsn(msg.h.commit_lsn).await?;
     870         9743 :         }
     871              :         // Value calculated by walproposer can always lag:
     872              :         // - safekeepers can forget inmem value and send to proposer lower
     873              :         //   persisted one on restart;
     874              :         // - if we make safekeepers always send persistent value,
     875              :         //   any compute restart would pull it down.
     876              :         // Thus, take max before adopting.
     877        19534 :         self.state.inmem.peer_horizon_lsn =
     878        19534 :             max(self.state.inmem.peer_horizon_lsn, msg.h.truncate_lsn);
     879        19534 : 
     880        19534 :         // Update truncate and commit LSN in control file.
     881        19534 :         // To avoid negative impact on performance of extra fsync, do it only
     882        19534 :         // when commit_lsn delta exceeds WAL segment size.
     883        19534 :         if self.state.commit_lsn + (self.state.server.wal_seg_size as u64)
     884        19534 :             < self.state.inmem.commit_lsn
     885              :         {
     886            0 :             self.state.flush().await?;
     887        19534 :         }
     888              : 
     889        19534 :         trace!(
     890            0 :             "processed AppendRequest of len {}, end_lsn={:?}, commit_lsn={:?}, truncate_lsn={:?}, flushed={:?}",
     891            0 :             msg.wal_data.len(),
     892              :             msg.h.end_lsn,
     893              :             msg.h.commit_lsn,
     894              :             msg.h.truncate_lsn,
     895              :             require_flush,
     896              :         );
     897              : 
     898              :         // If flush_lsn hasn't updated, AppendResponse is not very useful.
     899        19534 :         if !require_flush {
     900        19530 :             return Ok(None);
     901            4 :         }
     902            4 : 
     903            4 :         let resp = self.append_response();
     904            4 :         Ok(Some(AcceptorProposerMessage::AppendResponse(resp)))
     905        19535 :     }
     906              : 
     907              :     /// Flush WAL to disk. Return AppendResponse with latest LSNs.
     908        16213 :     async fn handle_flush(&mut self) -> Result<Option<AcceptorProposerMessage>> {
     909        16213 :         self.wal_store.flush_wal().await?;
     910        16213 :         Ok(Some(AcceptorProposerMessage::AppendResponse(
     911        16213 :             self.append_response(),
     912        16213 :         )))
     913        16213 :     }
     914              : 
     915              :     /// Update timeline state with peer safekeeper data.
     916            0 :     pub async fn record_safekeeper_info(&mut self, sk_info: &SafekeeperTimelineInfo) -> Result<()> {
     917            0 :         let mut sync_control_file = false;
     918            0 : 
     919            0 :         if (Lsn(sk_info.commit_lsn) != Lsn::INVALID) && (sk_info.last_log_term != INVALID_TERM) {
     920              :             // Note: the check is too restrictive, generally we can update local
     921              :             // commit_lsn if our history matches (is part of) history of advanced
     922              :             // commit_lsn provider.
     923            0 :             if sk_info.last_log_term == self.get_last_log_term() {
     924            0 :                 self.update_commit_lsn(Lsn(sk_info.commit_lsn)).await?;
     925            0 :             }
     926            0 :         }
     927              : 
     928            0 :         self.state.inmem.backup_lsn = max(Lsn(sk_info.backup_lsn), self.state.inmem.backup_lsn);
     929            0 :         sync_control_file |= self.state.backup_lsn + (self.state.server.wal_seg_size as u64)
     930            0 :             < self.state.inmem.backup_lsn;
     931            0 : 
     932            0 :         self.state.inmem.remote_consistent_lsn = max(
     933            0 :             Lsn(sk_info.remote_consistent_lsn),
     934            0 :             self.state.inmem.remote_consistent_lsn,
     935            0 :         );
     936            0 :         sync_control_file |= self.state.remote_consistent_lsn
     937            0 :             + (self.state.server.wal_seg_size as u64)
     938            0 :             < self.state.inmem.remote_consistent_lsn;
     939            0 : 
     940            0 :         self.state.inmem.peer_horizon_lsn = max(
     941            0 :             Lsn(sk_info.peer_horizon_lsn),
     942            0 :             self.state.inmem.peer_horizon_lsn,
     943            0 :         );
     944            0 :         sync_control_file |= self.state.peer_horizon_lsn + (self.state.server.wal_seg_size as u64)
     945            0 :             < self.state.inmem.peer_horizon_lsn;
     946            0 : 
     947            0 :         if sync_control_file {
     948            0 :             self.state.flush().await?;
     949            0 :         }
     950            0 :         Ok(())
     951            0 :     }
     952              : }
     953              : 
     954              : #[cfg(test)]
     955              : mod tests {
     956              :     use futures::future::BoxFuture;
     957              :     use postgres_ffi::{XLogSegNo, WAL_SEGMENT_SIZE};
     958              : 
     959              :     use super::*;
     960              :     use crate::{
     961              :         state::{EvictionState, PersistedPeers, TimelinePersistentState},
     962              :         wal_storage::Storage,
     963              :     };
     964              :     use std::{ops::Deref, str::FromStr, time::Instant};
     965              : 
     966              :     // fake storage for tests
     967              :     struct InMemoryState {
     968              :         persisted_state: TimelinePersistentState,
     969              :     }
     970              : 
     971              :     #[async_trait::async_trait]
     972              :     impl control_file::Storage for InMemoryState {
     973            6 :         async fn persist(&mut self, s: &TimelinePersistentState) -> Result<()> {
     974            6 :             self.persisted_state = s.clone();
     975            6 :             Ok(())
     976            6 :         }
     977              : 
     978            0 :         fn last_persist_at(&self) -> Instant {
     979            0 :             Instant::now()
     980            0 :         }
     981              :     }
     982              : 
     983              :     impl Deref for InMemoryState {
     984              :         type Target = TimelinePersistentState;
     985              : 
     986          120 :         fn deref(&self) -> &Self::Target {
     987          120 :             &self.persisted_state
     988          120 :         }
     989              :     }
     990              : 
     991            4 :     fn test_sk_state() -> TimelinePersistentState {
     992            4 :         let mut state = TimelinePersistentState::empty();
     993            4 :         state.server.wal_seg_size = WAL_SEGMENT_SIZE as u32;
     994            4 :         state.tenant_id = TenantId::from([1u8; 16]);
     995            4 :         state.timeline_id = TimelineId::from([1u8; 16]);
     996            4 :         state
     997            4 :     }
     998              : 
     999              :     struct DummyWalStore {
    1000              :         lsn: Lsn,
    1001              :     }
    1002              : 
    1003              :     #[async_trait::async_trait]
    1004              :     impl wal_storage::Storage for DummyWalStore {
    1005           20 :         fn flush_lsn(&self) -> Lsn {
    1006           20 :             self.lsn
    1007           20 :         }
    1008              : 
    1009            2 :         async fn initialize_first_segment(&mut self, _init_lsn: Lsn) -> Result<()> {
    1010            2 :             Ok(())
    1011            2 :         }
    1012              : 
    1013            4 :         async fn write_wal(&mut self, startpos: Lsn, buf: &[u8]) -> Result<()> {
    1014            4 :             self.lsn = startpos + buf.len() as u64;
    1015            4 :             Ok(())
    1016            4 :         }
    1017              : 
    1018            4 :         async fn truncate_wal(&mut self, end_pos: Lsn) -> Result<()> {
    1019            4 :             self.lsn = end_pos;
    1020            4 :             Ok(())
    1021            4 :         }
    1022              : 
    1023            8 :         async fn flush_wal(&mut self) -> Result<()> {
    1024            8 :             Ok(())
    1025            8 :         }
    1026              : 
    1027            0 :         fn remove_up_to(&self, _segno_up_to: XLogSegNo) -> BoxFuture<'static, anyhow::Result<()>> {
    1028            0 :             Box::pin(async { Ok(()) })
    1029            0 :         }
    1030              : 
    1031            0 :         fn get_metrics(&self) -> crate::metrics::WalStorageMetrics {
    1032            0 :             crate::metrics::WalStorageMetrics::default()
    1033            0 :         }
    1034              :     }
    1035              : 
    1036              :     #[tokio::test]
    1037            2 :     async fn test_voting() {
    1038            2 :         let storage = InMemoryState {
    1039            2 :             persisted_state: test_sk_state(),
    1040            2 :         };
    1041            2 :         let wal_store = DummyWalStore { lsn: Lsn(0) };
    1042            2 :         let mut sk = SafeKeeper::new(storage, wal_store, NodeId(0)).unwrap();
    1043            2 : 
    1044            2 :         // check voting for 1 is ok
    1045            2 :         let vote_request = ProposerAcceptorMessage::VoteRequest(VoteRequest { term: 1 });
    1046            2 :         let mut vote_resp = sk.process_msg(&vote_request).await;
    1047            2 :         match vote_resp.unwrap() {
    1048            2 :             Some(AcceptorProposerMessage::VoteResponse(resp)) => assert!(resp.vote_given != 0),
    1049            2 :             r => panic!("unexpected response: {:?}", r),
    1050            2 :         }
    1051            2 : 
    1052            2 :         // reboot...
    1053            2 :         let state = sk.state.deref().clone();
    1054            2 :         let storage = InMemoryState {
    1055            2 :             persisted_state: state,
    1056            2 :         };
    1057            2 : 
    1058            2 :         sk = SafeKeeper::new(storage, sk.wal_store, NodeId(0)).unwrap();
    1059            2 : 
    1060            2 :         // and ensure voting second time for 1 is not ok
    1061            2 :         vote_resp = sk.process_msg(&vote_request).await;
    1062            2 :         match vote_resp.unwrap() {
    1063            2 :             Some(AcceptorProposerMessage::VoteResponse(resp)) => assert!(resp.vote_given == 0),
    1064            2 :             r => panic!("unexpected response: {:?}", r),
    1065            2 :         }
    1066            2 :     }
    1067              : 
    1068              :     #[tokio::test]
    1069            2 :     async fn test_last_log_term_switch() {
    1070            2 :         let storage = InMemoryState {
    1071            2 :             persisted_state: test_sk_state(),
    1072            2 :         };
    1073            2 :         let wal_store = DummyWalStore { lsn: Lsn(0) };
    1074            2 : 
    1075            2 :         let mut sk = SafeKeeper::new(storage, wal_store, NodeId(0)).unwrap();
    1076            2 : 
    1077            2 :         let mut ar_hdr = AppendRequestHeader {
    1078            2 :             term: 1,
    1079            2 :             term_start_lsn: Lsn(3),
    1080            2 :             begin_lsn: Lsn(1),
    1081            2 :             end_lsn: Lsn(2),
    1082            2 :             commit_lsn: Lsn(0),
    1083            2 :             truncate_lsn: Lsn(0),
    1084            2 :             proposer_uuid: [0; 16],
    1085            2 :         };
    1086            2 :         let mut append_request = AppendRequest {
    1087            2 :             h: ar_hdr.clone(),
    1088            2 :             wal_data: Bytes::from_static(b"b"),
    1089            2 :         };
    1090            2 : 
    1091            2 :         let pem = ProposerElected {
    1092            2 :             term: 1,
    1093            2 :             start_streaming_at: Lsn(1),
    1094            2 :             term_history: TermHistory(vec![TermLsn {
    1095            2 :                 term: 1,
    1096            2 :                 lsn: Lsn(3),
    1097            2 :             }]),
    1098            2 :             timeline_start_lsn: Lsn(0),
    1099            2 :         };
    1100            2 :         sk.process_msg(&ProposerAcceptorMessage::Elected(pem))
    1101            2 :             .await
    1102            2 :             .unwrap();
    1103            2 : 
    1104            2 :         // check that AppendRequest before term_start_lsn doesn't switch last_log_term.
    1105            2 :         let resp = sk
    1106            2 :             .process_msg(&ProposerAcceptorMessage::AppendRequest(append_request))
    1107            2 :             .await;
    1108            2 :         assert!(resp.is_ok());
    1109            2 :         assert_eq!(sk.get_last_log_term(), 0);
    1110            2 : 
    1111            2 :         // but record at term_start_lsn does the switch
    1112            2 :         ar_hdr.begin_lsn = Lsn(2);
    1113            2 :         ar_hdr.end_lsn = Lsn(3);
    1114            2 :         append_request = AppendRequest {
    1115            2 :             h: ar_hdr,
    1116            2 :             wal_data: Bytes::from_static(b"b"),
    1117            2 :         };
    1118            2 :         let resp = sk
    1119            2 :             .process_msg(&ProposerAcceptorMessage::AppendRequest(append_request))
    1120            2 :             .await;
    1121            2 :         assert!(resp.is_ok());
    1122            2 :         sk.wal_store.truncate_wal(Lsn(3)).await.unwrap(); // imitate the complete record at 3 %)
    1123            2 :         assert_eq!(sk.get_last_log_term(), 1);
    1124            2 :     }
    1125              : 
    1126              :     #[test]
    1127            2 :     fn test_find_highest_common_point_none() {
    1128            2 :         let prop_th = TermHistory(vec![(0, Lsn(1)).into()]);
    1129            2 :         let sk_th = TermHistory(vec![(1, Lsn(1)).into(), (2, Lsn(2)).into()]);
    1130            2 :         assert_eq!(
    1131            2 :             TermHistory::find_highest_common_point(&prop_th, &sk_th, Lsn(3),),
    1132            2 :             None
    1133            2 :         );
    1134            2 :     }
    1135              : 
    1136              :     #[test]
    1137            2 :     fn test_find_highest_common_point_middle() {
    1138            2 :         let prop_th = TermHistory(vec![
    1139            2 :             (1, Lsn(10)).into(),
    1140            2 :             (2, Lsn(20)).into(),
    1141            2 :             (4, Lsn(40)).into(),
    1142            2 :         ]);
    1143            2 :         let sk_th = TermHistory(vec![
    1144            2 :             (1, Lsn(10)).into(),
    1145            2 :             (2, Lsn(20)).into(),
    1146            2 :             (3, Lsn(30)).into(), // sk ends last common term 2 at 30
    1147            2 :         ]);
    1148            2 :         assert_eq!(
    1149            2 :             TermHistory::find_highest_common_point(&prop_th, &sk_th, Lsn(40),),
    1150            2 :             Some(TermLsn {
    1151            2 :                 term: 2,
    1152            2 :                 lsn: Lsn(30),
    1153            2 :             })
    1154            2 :         );
    1155            2 :     }
    1156              : 
    1157              :     #[test]
    1158            2 :     fn test_find_highest_common_point_sk_end() {
    1159            2 :         let prop_th = TermHistory(vec![
    1160            2 :             (1, Lsn(10)).into(),
    1161            2 :             (2, Lsn(20)).into(), // last common term 2, sk will end it at 32 sk_end_lsn
    1162            2 :             (4, Lsn(40)).into(),
    1163            2 :         ]);
    1164            2 :         let sk_th = TermHistory(vec![(1, Lsn(10)).into(), (2, Lsn(20)).into()]);
    1165            2 :         assert_eq!(
    1166            2 :             TermHistory::find_highest_common_point(&prop_th, &sk_th, Lsn(32),),
    1167            2 :             Some(TermLsn {
    1168            2 :                 term: 2,
    1169            2 :                 lsn: Lsn(32),
    1170            2 :             })
    1171            2 :         );
    1172            2 :     }
    1173              : 
    1174              :     #[test]
    1175            2 :     fn test_find_highest_common_point_walprop() {
    1176            2 :         let prop_th = TermHistory(vec![(1, Lsn(10)).into(), (2, Lsn(20)).into()]);
    1177            2 :         let sk_th = TermHistory(vec![(1, Lsn(10)).into(), (2, Lsn(20)).into()]);
    1178            2 :         assert_eq!(
    1179            2 :             TermHistory::find_highest_common_point(&prop_th, &sk_th, Lsn(32),),
    1180            2 :             Some(TermLsn {
    1181            2 :                 term: 2,
    1182            2 :                 lsn: Lsn(32),
    1183            2 :             })
    1184            2 :         );
    1185            2 :     }
    1186              : 
    1187              :     #[test]
    1188            2 :     fn test_sk_state_bincode_serde_roundtrip() {
    1189            2 :         use utils::Hex;
    1190            2 :         let tenant_id = TenantId::from_str("cf0480929707ee75372337efaa5ecf96").unwrap();
    1191            2 :         let timeline_id = TimelineId::from_str("112ded66422aa5e953e5440fa5427ac4").unwrap();
    1192            2 :         let state = TimelinePersistentState {
    1193            2 :             tenant_id,
    1194            2 :             timeline_id,
    1195            2 :             acceptor_state: AcceptorState {
    1196            2 :                 term: 42,
    1197            2 :                 term_history: TermHistory(vec![TermLsn {
    1198            2 :                     lsn: Lsn(0x1),
    1199            2 :                     term: 41,
    1200            2 :                 }]),
    1201            2 :             },
    1202            2 :             server: ServerInfo {
    1203            2 :                 pg_version: 14,
    1204            2 :                 system_id: 0x1234567887654321,
    1205            2 :                 wal_seg_size: 0x12345678,
    1206            2 :             },
    1207            2 :             proposer_uuid: {
    1208            2 :                 let mut arr = timeline_id.as_arr();
    1209            2 :                 arr.reverse();
    1210            2 :                 arr
    1211            2 :             },
    1212            2 :             timeline_start_lsn: Lsn(0x12345600),
    1213            2 :             local_start_lsn: Lsn(0x12),
    1214            2 :             commit_lsn: Lsn(1234567800),
    1215            2 :             backup_lsn: Lsn(1234567300),
    1216            2 :             peer_horizon_lsn: Lsn(9999999),
    1217            2 :             remote_consistent_lsn: Lsn(1234560000),
    1218            2 :             peers: PersistedPeers(vec![(
    1219            2 :                 NodeId(1),
    1220            2 :                 PersistedPeerInfo {
    1221            2 :                     backup_lsn: Lsn(1234567000),
    1222            2 :                     term: 42,
    1223            2 :                     flush_lsn: Lsn(1234567800 - 8),
    1224            2 :                     commit_lsn: Lsn(1234567600),
    1225            2 :                 },
    1226            2 :             )]),
    1227            2 :             partial_backup: crate::wal_backup_partial::State::default(),
    1228            2 :             eviction_state: EvictionState::Present,
    1229            2 :         };
    1230            2 : 
    1231            2 :         let ser = state.ser().unwrap();
    1232            2 : 
    1233            2 :         #[rustfmt::skip]
    1234            2 :         let expected = [
    1235            2 :             // tenant_id as length prefixed hex
    1236            2 :             0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    1237            2 :             0x63, 0x66, 0x30, 0x34, 0x38, 0x30, 0x39, 0x32, 0x39, 0x37, 0x30, 0x37, 0x65, 0x65, 0x37, 0x35, 0x33, 0x37, 0x32, 0x33, 0x33, 0x37, 0x65, 0x66, 0x61, 0x61, 0x35, 0x65, 0x63, 0x66, 0x39, 0x36,
    1238            2 :             // timeline_id as length prefixed hex
    1239            2 :             0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    1240            2 :             0x31, 0x31, 0x32, 0x64, 0x65, 0x64, 0x36, 0x36, 0x34, 0x32, 0x32, 0x61, 0x61, 0x35, 0x65, 0x39, 0x35, 0x33, 0x65, 0x35, 0x34, 0x34, 0x30, 0x66, 0x61, 0x35, 0x34, 0x32, 0x37, 0x61, 0x63, 0x34,
    1241            2 :             // term
    1242            2 :             0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    1243            2 :             // length prefix
    1244            2 :             0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    1245            2 :             // unsure why this order is swapped
    1246            2 :             0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    1247            2 :             0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    1248            2 :             // pg_version
    1249            2 :             0x0e, 0x00, 0x00, 0x00,
    1250            2 :             // systemid
    1251            2 :             0x21, 0x43, 0x65, 0x87, 0x78, 0x56, 0x34, 0x12,
    1252            2 :             // wal_seg_size
    1253            2 :             0x78, 0x56, 0x34, 0x12,
    1254            2 :             // pguuid as length prefixed hex
    1255            2 :             0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    1256            2 :             0x63, 0x34, 0x37, 0x61, 0x34, 0x32, 0x61, 0x35, 0x30, 0x66, 0x34, 0x34, 0x65, 0x35, 0x35, 0x33, 0x65, 0x39, 0x61, 0x35, 0x32, 0x61, 0x34, 0x32, 0x36, 0x36, 0x65, 0x64, 0x32, 0x64, 0x31, 0x31,
    1257            2 : 
    1258            2 :             // timeline_start_lsn
    1259            2 :             0x00, 0x56, 0x34, 0x12, 0x00, 0x00, 0x00, 0x00,
    1260            2 :             0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    1261            2 :             0x78, 0x02, 0x96, 0x49, 0x00, 0x00, 0x00, 0x00,
    1262            2 :             0x84, 0x00, 0x96, 0x49, 0x00, 0x00, 0x00, 0x00,
    1263            2 :             0x7f, 0x96, 0x98, 0x00, 0x00, 0x00, 0x00, 0x00,
    1264            2 :             0x00, 0xe4, 0x95, 0x49, 0x00, 0x00, 0x00, 0x00,
    1265            2 :             // length prefix for persistentpeers
    1266            2 :             0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    1267            2 :             // nodeid
    1268            2 :             0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    1269            2 :             // backuplsn
    1270            2 :             0x58, 0xff, 0x95, 0x49, 0x00, 0x00, 0x00, 0x00,
    1271            2 :             0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    1272            2 :             0x70, 0x02, 0x96, 0x49, 0x00, 0x00, 0x00, 0x00,
    1273            2 :             0xb0, 0x01, 0x96, 0x49, 0x00, 0x00, 0x00, 0x00,
    1274            2 :             // partial_backup
    1275            2 :             0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    1276            2 :             // eviction_state
    1277            2 :             0x00, 0x00, 0x00, 0x00,
    1278            2 :         ];
    1279            2 : 
    1280            2 :         assert_eq!(Hex(&ser), Hex(&expected));
    1281              : 
    1282            2 :         let deser = TimelinePersistentState::des(&ser).unwrap();
    1283            2 : 
    1284            2 :         assert_eq!(deser, state);
    1285            2 :     }
    1286              : }
        

Generated by: LCOV version 2.1-beta