LCOV - code coverage report
Current view: top level - safekeeper/src - send_wal.rs (source / functions) Coverage Total Hit
Test: 050dd70dd490b28fffe527eae9fb8a1222b5c59c.info Lines: 21.9 % 498 109
Test Date: 2024-06-25 21:28:46 Functions: 9.8 % 112 11

            Line data    Source code
       1              : //! This module implements the streaming side of replication protocol, starting
       2              : //! with the "START_REPLICATION" message, and registry of walsenders.
       3              : 
       4              : use crate::handler::SafekeeperPostgresHandler;
       5              : use crate::metrics::RECEIVED_PS_FEEDBACKS;
       6              : use crate::receive_wal::WalReceivers;
       7              : use crate::safekeeper::{Term, TermLsn};
       8              : use crate::timeline::FullAccessTimeline;
       9              : use crate::wal_service::ConnectionId;
      10              : use crate::wal_storage::WalReader;
      11              : use crate::GlobalTimelines;
      12              : use anyhow::{bail, Context as AnyhowContext};
      13              : use bytes::Bytes;
      14              : use parking_lot::Mutex;
      15              : use postgres_backend::PostgresBackend;
      16              : use postgres_backend::{CopyStreamHandlerEnd, PostgresBackendReader, QueryError};
      17              : use postgres_ffi::get_current_timestamp;
      18              : use postgres_ffi::{TimestampTz, MAX_SEND_SIZE};
      19              : use pq_proto::{BeMessage, WalSndKeepAlive, XLogDataBody};
      20              : use serde::{Deserialize, Serialize};
      21              : use tokio::io::{AsyncRead, AsyncWrite};
      22              : use utils::failpoint_support;
      23              : use utils::id::TenantTimelineId;
      24              : use utils::pageserver_feedback::PageserverFeedback;
      25              : 
      26              : use std::cmp::{max, min};
      27              : use std::net::SocketAddr;
      28              : use std::str;
      29              : use std::sync::Arc;
      30              : use std::time::Duration;
      31              : use tokio::sync::watch::Receiver;
      32              : use tokio::time::timeout;
      33              : use tracing::*;
      34              : use utils::{bin_ser::BeSer, lsn::Lsn};
      35              : 
      36              : // See: https://www.postgresql.org/docs/13/protocol-replication.html
      37              : const HOT_STANDBY_FEEDBACK_TAG_BYTE: u8 = b'h';
      38              : const STANDBY_STATUS_UPDATE_TAG_BYTE: u8 = b'r';
      39              : // neon extension of replication protocol
      40              : const NEON_STATUS_UPDATE_TAG_BYTE: u8 = b'z';
      41              : 
      42              : type FullTransactionId = u64;
      43              : 
      44              : /// Hot standby feedback received from replica
      45            0 : #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
      46              : pub struct HotStandbyFeedback {
      47              :     pub ts: TimestampTz,
      48              :     pub xmin: FullTransactionId,
      49              :     pub catalog_xmin: FullTransactionId,
      50              : }
      51              : 
      52              : const INVALID_FULL_TRANSACTION_ID: FullTransactionId = 0;
      53              : 
      54              : impl HotStandbyFeedback {
      55        16542 :     pub fn empty() -> HotStandbyFeedback {
      56        16542 :         HotStandbyFeedback {
      57        16542 :             ts: 0,
      58        16542 :             xmin: 0,
      59        16542 :             catalog_xmin: 0,
      60        16542 :         }
      61        16542 :     }
      62              : }
      63              : 
      64              : /// Standby status update
      65            0 : #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
      66              : pub struct StandbyReply {
      67              :     pub write_lsn: Lsn, // The location of the last WAL byte + 1 received and written to disk in the standby.
      68              :     pub flush_lsn: Lsn, // The location of the last WAL byte + 1 flushed to disk in the standby.
      69              :     pub apply_lsn: Lsn, // The location of the last WAL byte + 1 applied in the standby.
      70              :     pub reply_ts: TimestampTz, // The client's system clock at the time of transmission, as microseconds since midnight on 2000-01-01.
      71              :     pub reply_requested: bool,
      72              : }
      73              : 
      74              : impl StandbyReply {
      75           16 :     fn empty() -> Self {
      76           16 :         StandbyReply {
      77           16 :             write_lsn: Lsn::INVALID,
      78           16 :             flush_lsn: Lsn::INVALID,
      79           16 :             apply_lsn: Lsn::INVALID,
      80           16 :             reply_ts: 0,
      81           16 :             reply_requested: false,
      82           16 :         }
      83           16 :     }
      84              : }
      85              : 
      86            0 : #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
      87              : pub struct StandbyFeedback {
      88              :     pub reply: StandbyReply,
      89              :     pub hs_feedback: HotStandbyFeedback,
      90              : }
      91              : 
      92              : impl StandbyFeedback {
      93            4 :     pub fn empty() -> Self {
      94            4 :         StandbyFeedback {
      95            4 :             reply: StandbyReply::empty(),
      96            4 :             hs_feedback: HotStandbyFeedback::empty(),
      97            4 :         }
      98            4 :     }
      99              : }
     100              : 
     101              : /// WalSenders registry. Timeline holds it (wrapped in Arc).
     102              : pub struct WalSenders {
     103              :     mutex: Mutex<WalSendersShared>,
     104              :     walreceivers: Arc<WalReceivers>,
     105              : }
     106              : 
     107              : impl WalSenders {
     108            0 :     pub fn new(walreceivers: Arc<WalReceivers>) -> Arc<WalSenders> {
     109            0 :         Arc::new(WalSenders {
     110            0 :             mutex: Mutex::new(WalSendersShared::new()),
     111            0 :             walreceivers,
     112            0 :         })
     113            0 :     }
     114              : 
     115              :     /// Register new walsender. Returned guard provides access to the slot and
     116              :     /// automatically deregisters in Drop.
     117            0 :     fn register(
     118            0 :         self: &Arc<WalSenders>,
     119            0 :         ttid: TenantTimelineId,
     120            0 :         addr: SocketAddr,
     121            0 :         conn_id: ConnectionId,
     122            0 :         appname: Option<String>,
     123            0 :     ) -> WalSenderGuard {
     124            0 :         let slots = &mut self.mutex.lock().slots;
     125            0 :         let walsender_state = WalSenderState {
     126            0 :             ttid,
     127            0 :             addr,
     128            0 :             conn_id,
     129            0 :             appname,
     130            0 :             feedback: ReplicationFeedback::Pageserver(PageserverFeedback::empty()),
     131            0 :         };
     132              :         // find empty slot or create new one
     133            0 :         let pos = if let Some(pos) = slots.iter().position(|s| s.is_none()) {
     134            0 :             slots[pos] = Some(walsender_state);
     135            0 :             pos
     136              :         } else {
     137            0 :             let pos = slots.len();
     138            0 :             slots.push(Some(walsender_state));
     139            0 :             pos
     140              :         };
     141            0 :         WalSenderGuard {
     142            0 :             id: pos,
     143            0 :             walsenders: self.clone(),
     144            0 :         }
     145            0 :     }
     146              : 
     147              :     /// Get state of all walsenders.
     148            0 :     pub fn get_all(self: &Arc<WalSenders>) -> Vec<WalSenderState> {
     149            0 :         self.mutex.lock().slots.iter().flatten().cloned().collect()
     150            0 :     }
     151              : 
     152              :     /// Get LSN of the most lagging pageserver receiver. Return None if there are no
     153              :     /// active walsenders.
     154            0 :     pub fn laggard_lsn(self: &Arc<WalSenders>) -> Option<Lsn> {
     155            0 :         self.mutex
     156            0 :             .lock()
     157            0 :             .slots
     158            0 :             .iter()
     159            0 :             .flatten()
     160            0 :             .filter_map(|s| match s.feedback {
     161            0 :                 ReplicationFeedback::Pageserver(feedback) => Some(feedback.last_received_lsn),
     162            0 :                 ReplicationFeedback::Standby(_) => None,
     163            0 :             })
     164            0 :             .min()
     165            0 :     }
     166              : 
     167              :     /// Returns total counter of pageserver feedbacks received and last feedback.
     168            0 :     pub fn get_ps_feedback_stats(self: &Arc<WalSenders>) -> (u64, PageserverFeedback) {
     169            0 :         let shared = self.mutex.lock();
     170            0 :         (shared.ps_feedback_counter, shared.last_ps_feedback)
     171            0 :     }
     172              : 
     173              :     /// Get aggregated hot standby feedback (we send it to compute).
     174            0 :     pub fn get_hotstandby(self: &Arc<WalSenders>) -> StandbyFeedback {
     175            0 :         self.mutex.lock().agg_standby_feedback
     176            0 :     }
     177              : 
     178              :     /// Record new pageserver feedback, update aggregated values.
     179            0 :     fn record_ps_feedback(self: &Arc<WalSenders>, id: WalSenderId, feedback: &PageserverFeedback) {
     180            0 :         let mut shared = self.mutex.lock();
     181            0 :         shared.get_slot_mut(id).feedback = ReplicationFeedback::Pageserver(*feedback);
     182            0 :         shared.last_ps_feedback = *feedback;
     183            0 :         shared.ps_feedback_counter += 1;
     184            0 :         drop(shared);
     185            0 : 
     186            0 :         RECEIVED_PS_FEEDBACKS.inc();
     187            0 : 
     188            0 :         // send feedback to connected walproposers
     189            0 :         self.walreceivers.broadcast_pageserver_feedback(*feedback);
     190            0 :     }
     191              : 
     192              :     /// Record standby reply.
     193            0 :     fn record_standby_reply(self: &Arc<WalSenders>, id: WalSenderId, reply: &StandbyReply) {
     194            0 :         let mut shared = self.mutex.lock();
     195            0 :         let slot = shared.get_slot_mut(id);
     196            0 :         debug!(
     197            0 :             "Record standby reply: ts={} apply_lsn={}",
     198              :             reply.reply_ts, reply.apply_lsn
     199              :         );
     200            0 :         match &mut slot.feedback {
     201            0 :             ReplicationFeedback::Standby(sf) => sf.reply = *reply,
     202              :             ReplicationFeedback::Pageserver(_) => {
     203            0 :                 slot.feedback = ReplicationFeedback::Standby(StandbyFeedback {
     204            0 :                     reply: *reply,
     205            0 :                     hs_feedback: HotStandbyFeedback::empty(),
     206            0 :                 })
     207              :             }
     208              :         }
     209            0 :     }
     210              : 
     211              :     /// Record hot standby feedback, update aggregated value.
     212            0 :     fn record_hs_feedback(self: &Arc<WalSenders>, id: WalSenderId, feedback: &HotStandbyFeedback) {
     213            0 :         let mut shared = self.mutex.lock();
     214            0 :         let slot = shared.get_slot_mut(id);
     215            0 :         match &mut slot.feedback {
     216            0 :             ReplicationFeedback::Standby(sf) => sf.hs_feedback = *feedback,
     217              :             ReplicationFeedback::Pageserver(_) => {
     218            0 :                 slot.feedback = ReplicationFeedback::Standby(StandbyFeedback {
     219            0 :                     reply: StandbyReply::empty(),
     220            0 :                     hs_feedback: *feedback,
     221            0 :                 })
     222              :             }
     223              :         }
     224            0 :         shared.update_reply_feedback();
     225            0 :     }
     226              : 
     227              :     /// Get remote_consistent_lsn reported by the pageserver. Returns None if
     228              :     /// client is not pageserver.
     229            0 :     fn get_ws_remote_consistent_lsn(self: &Arc<WalSenders>, id: WalSenderId) -> Option<Lsn> {
     230            0 :         let shared = self.mutex.lock();
     231            0 :         let slot = shared.get_slot(id);
     232            0 :         match slot.feedback {
     233            0 :             ReplicationFeedback::Pageserver(feedback) => Some(feedback.remote_consistent_lsn),
     234            0 :             _ => None,
     235              :         }
     236            0 :     }
     237              : 
     238              :     /// Unregister walsender.
     239            0 :     fn unregister(self: &Arc<WalSenders>, id: WalSenderId) {
     240            0 :         let mut shared = self.mutex.lock();
     241            0 :         shared.slots[id] = None;
     242            0 :         shared.update_reply_feedback();
     243            0 :     }
     244              : }
     245              : 
     246              : struct WalSendersShared {
     247              :     // aggregated over all walsenders value
     248              :     agg_standby_feedback: StandbyFeedback,
     249              :     // last feedback ever received from any pageserver, empty if none
     250              :     last_ps_feedback: PageserverFeedback,
     251              :     // total counter of pageserver feedbacks received
     252              :     ps_feedback_counter: u64,
     253              :     slots: Vec<Option<WalSenderState>>,
     254              : }
     255              : 
     256              : impl WalSendersShared {
     257            4 :     fn new() -> Self {
     258            4 :         WalSendersShared {
     259            4 :             agg_standby_feedback: StandbyFeedback::empty(),
     260            4 :             last_ps_feedback: PageserverFeedback::empty(),
     261            4 :             ps_feedback_counter: 0,
     262            4 :             slots: Vec::new(),
     263            4 :         }
     264            4 :     }
     265              : 
     266              :     /// Get content of provided id slot, it must exist.
     267            0 :     fn get_slot(&self, id: WalSenderId) -> &WalSenderState {
     268            0 :         self.slots[id].as_ref().expect("walsender doesn't exist")
     269            0 :     }
     270              : 
     271              :     /// Get mut content of provided id slot, it must exist.
     272            0 :     fn get_slot_mut(&mut self, id: WalSenderId) -> &mut WalSenderState {
     273            0 :         self.slots[id].as_mut().expect("walsender doesn't exist")
     274            0 :     }
     275              : 
     276              :     /// Update aggregated hot standy and normal reply feedbacks. We just take min of valid xmins
     277              :     /// and ts.
     278            4 :     fn update_reply_feedback(&mut self) {
     279            4 :         let mut agg = HotStandbyFeedback::empty();
     280            4 :         let mut reply_agg = StandbyReply::empty();
     281            8 :         for ws_state in self.slots.iter().flatten() {
     282            8 :             if let ReplicationFeedback::Standby(standby_feedback) = ws_state.feedback {
     283            8 :                 let hs_feedback = standby_feedback.hs_feedback;
     284            8 :                 // doing Option math like op1.iter().chain(op2.iter()).min()
     285            8 :                 // would be nicer, but we serialize/deserialize this struct
     286            8 :                 // directly, so leave as is for now
     287            8 :                 if hs_feedback.xmin != INVALID_FULL_TRANSACTION_ID {
     288            4 :                     if agg.xmin != INVALID_FULL_TRANSACTION_ID {
     289            2 :                         agg.xmin = min(agg.xmin, hs_feedback.xmin);
     290            2 :                     } else {
     291            2 :                         agg.xmin = hs_feedback.xmin;
     292            2 :                     }
     293            4 :                     agg.ts = max(agg.ts, hs_feedback.ts);
     294            4 :                 }
     295            8 :                 if hs_feedback.catalog_xmin != INVALID_FULL_TRANSACTION_ID {
     296            0 :                     if agg.catalog_xmin != INVALID_FULL_TRANSACTION_ID {
     297            0 :                         agg.catalog_xmin = min(agg.catalog_xmin, hs_feedback.catalog_xmin);
     298            0 :                     } else {
     299            0 :                         agg.catalog_xmin = hs_feedback.catalog_xmin;
     300            0 :                     }
     301            0 :                     agg.ts = max(agg.ts, hs_feedback.ts);
     302            8 :                 }
     303            8 :                 let reply = standby_feedback.reply;
     304            8 :                 if reply.write_lsn != Lsn::INVALID {
     305            0 :                     if reply_agg.write_lsn != Lsn::INVALID {
     306            0 :                         reply_agg.write_lsn = Lsn::min(reply_agg.write_lsn, reply.write_lsn);
     307            0 :                     } else {
     308            0 :                         reply_agg.write_lsn = reply.write_lsn;
     309            0 :                     }
     310            8 :                 }
     311            8 :                 if reply.flush_lsn != Lsn::INVALID {
     312            0 :                     if reply_agg.flush_lsn != Lsn::INVALID {
     313            0 :                         reply_agg.flush_lsn = Lsn::min(reply_agg.flush_lsn, reply.flush_lsn);
     314            0 :                     } else {
     315            0 :                         reply_agg.flush_lsn = reply.flush_lsn;
     316            0 :                     }
     317            8 :                 }
     318            8 :                 if reply.apply_lsn != Lsn::INVALID {
     319            0 :                     if reply_agg.apply_lsn != Lsn::INVALID {
     320            0 :                         reply_agg.apply_lsn = Lsn::min(reply_agg.apply_lsn, reply.apply_lsn);
     321            0 :                     } else {
     322            0 :                         reply_agg.apply_lsn = reply.apply_lsn;
     323            0 :                     }
     324            8 :                 }
     325            8 :                 if reply.reply_ts != 0 {
     326            0 :                     if reply_agg.reply_ts != 0 {
     327            0 :                         reply_agg.reply_ts = TimestampTz::min(reply_agg.reply_ts, reply.reply_ts);
     328            0 :                     } else {
     329            0 :                         reply_agg.reply_ts = reply.reply_ts;
     330            0 :                     }
     331            8 :                 }
     332            0 :             }
     333              :         }
     334            4 :         self.agg_standby_feedback = StandbyFeedback {
     335            4 :             reply: reply_agg,
     336            4 :             hs_feedback: agg,
     337            4 :         };
     338            4 :     }
     339              : }
     340              : 
     341              : // Serialized is used only for pretty printing in json.
     342            0 : #[derive(Debug, Clone, Serialize, Deserialize)]
     343              : pub struct WalSenderState {
     344              :     ttid: TenantTimelineId,
     345              :     addr: SocketAddr,
     346              :     conn_id: ConnectionId,
     347              :     // postgres application_name
     348              :     appname: Option<String>,
     349              :     feedback: ReplicationFeedback,
     350              : }
     351              : 
     352              : // Receiver is either pageserver or regular standby, which have different
     353              : // feedbacks.
     354            0 : #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
     355              : enum ReplicationFeedback {
     356              :     Pageserver(PageserverFeedback),
     357              :     Standby(StandbyFeedback),
     358              : }
     359              : 
     360              : // id of the occupied slot in WalSenders to access it (and save in the
     361              : // WalSenderGuard). We could give Arc directly to the slot, but there is not
     362              : // much sense in that as values aggregation which is performed on each feedback
     363              : // receival iterates over all walsenders.
     364              : pub type WalSenderId = usize;
     365              : 
     366              : /// Scope guard to access slot in WalSenders registry and unregister from it in
     367              : /// Drop.
     368              : pub struct WalSenderGuard {
     369              :     id: WalSenderId,
     370              :     walsenders: Arc<WalSenders>,
     371              : }
     372              : 
     373              : impl Drop for WalSenderGuard {
     374            0 :     fn drop(&mut self) {
     375            0 :         self.walsenders.unregister(self.id);
     376            0 :     }
     377              : }
     378              : 
     379              : impl SafekeeperPostgresHandler {
     380              :     /// Wrapper around handle_start_replication_guts handling result. Error is
     381              :     /// handled here while we're still in walsender ttid span; with API
     382              :     /// extension, this can probably be moved into postgres_backend.
     383            0 :     pub async fn handle_start_replication<IO: AsyncRead + AsyncWrite + Unpin>(
     384            0 :         &mut self,
     385            0 :         pgb: &mut PostgresBackend<IO>,
     386            0 :         start_pos: Lsn,
     387            0 :         term: Option<Term>,
     388            0 :     ) -> Result<(), QueryError> {
     389            0 :         let tli = GlobalTimelines::get(self.ttid).map_err(|e| QueryError::Other(e.into()))?;
     390            0 :         let full_access = tli.full_access_guard().await?;
     391              : 
     392            0 :         if let Err(end) = self
     393            0 :             .handle_start_replication_guts(pgb, start_pos, term, full_access)
     394            0 :             .await
     395              :         {
     396            0 :             let info = tli.get_safekeeper_info(&self.conf).await;
     397              :             // Log the result and probably send it to the client, closing the stream.
     398            0 :             pgb.handle_copy_stream_end(end)
     399            0 :             .instrument(info_span!("", term=%info.term, last_log_term=%info.last_log_term, flush_lsn=%Lsn(info.flush_lsn), commit_lsn=%Lsn(info.flush_lsn)))
     400            0 :             .await;
     401            0 :         }
     402            0 :         Ok(())
     403            0 :     }
     404              : 
     405            0 :     pub async fn handle_start_replication_guts<IO: AsyncRead + AsyncWrite + Unpin>(
     406            0 :         &mut self,
     407            0 :         pgb: &mut PostgresBackend<IO>,
     408            0 :         start_pos: Lsn,
     409            0 :         term: Option<Term>,
     410            0 :         tli: FullAccessTimeline,
     411            0 :     ) -> Result<(), CopyStreamHandlerEnd> {
     412            0 :         let appname = self.appname.clone();
     413            0 : 
     414            0 :         // Use a guard object to remove our entry from the timeline when we are done.
     415            0 :         let ws_guard = Arc::new(tli.get_walsenders().register(
     416            0 :             self.ttid,
     417            0 :             *pgb.get_peer_addr(),
     418            0 :             self.conn_id,
     419            0 :             self.appname.clone(),
     420            0 :         ));
     421              : 
     422              :         // Walsender can operate in one of two modes which we select by
     423              :         // application_name: give only committed WAL (used by pageserver) or all
     424              :         // existing WAL (up to flush_lsn, used by walproposer or peer recovery).
     425              :         // The second case is always driven by a consensus leader which term
     426              :         // must be supplied.
     427            0 :         let end_watch = if term.is_some() {
     428            0 :             EndWatch::Flush(tli.get_term_flush_lsn_watch_rx())
     429              :         } else {
     430            0 :             EndWatch::Commit(tli.get_commit_lsn_watch_rx())
     431              :         };
     432              :         // we don't check term here; it will be checked on first waiting/WAL reading anyway.
     433            0 :         let end_pos = end_watch.get();
     434            0 : 
     435            0 :         if end_pos < start_pos {
     436            0 :             warn!(
     437            0 :                 "requested start_pos {} is ahead of available WAL end_pos {}",
     438              :                 start_pos, end_pos
     439              :             );
     440            0 :         }
     441              : 
     442            0 :         info!(
     443            0 :             "starting streaming from {:?}, available WAL ends at {}, recovery={}, appname={:?}",
     444              :             start_pos,
     445              :             end_pos,
     446            0 :             matches!(end_watch, EndWatch::Flush(_)),
     447              :             appname
     448              :         );
     449              : 
     450              :         // switch to copy
     451            0 :         pgb.write_message(&BeMessage::CopyBothResponse).await?;
     452              : 
     453            0 :         let wal_reader = tli.get_walreader(start_pos).await?;
     454              : 
     455              :         // Split to concurrently receive and send data; replies are generally
     456              :         // not synchronized with sends, so this avoids deadlocks.
     457            0 :         let reader = pgb.split().context("START_REPLICATION split")?;
     458              : 
     459            0 :         let mut sender = WalSender {
     460            0 :             pgb,
     461            0 :             tli: tli.clone(),
     462            0 :             appname,
     463            0 :             start_pos,
     464            0 :             end_pos,
     465            0 :             term,
     466            0 :             end_watch,
     467            0 :             ws_guard: ws_guard.clone(),
     468            0 :             wal_reader,
     469            0 :             send_buf: [0; MAX_SEND_SIZE],
     470            0 :         };
     471            0 :         let mut reply_reader = ReplyReader {
     472            0 :             reader,
     473            0 :             ws_guard: ws_guard.clone(),
     474            0 :             tli,
     475            0 :         };
     476              : 
     477            0 :         let res = tokio::select! {
     478              :             // todo: add read|write .context to these errors
     479              :             r = sender.run() => r,
     480              :             r = reply_reader.run() => r,
     481              :         };
     482              : 
     483            0 :         let ws_state = ws_guard
     484            0 :             .walsenders
     485            0 :             .mutex
     486            0 :             .lock()
     487            0 :             .get_slot(ws_guard.id)
     488            0 :             .clone();
     489            0 :         info!(
     490            0 :             "finished streaming to {}, feedback={:?}",
     491              :             ws_state.addr, ws_state.feedback,
     492              :         );
     493              : 
     494              :         // Join pg backend back.
     495            0 :         pgb.unsplit(reply_reader.reader)?;
     496              : 
     497            0 :         res
     498            0 :     }
     499              : }
     500              : 
     501              : /// Walsender streams either up to commit_lsn (normally) or flush_lsn in the
     502              : /// given term (recovery by walproposer or peer safekeeper).
     503              : enum EndWatch {
     504              :     Commit(Receiver<Lsn>),
     505              :     Flush(Receiver<TermLsn>),
     506              : }
     507              : 
     508              : impl EndWatch {
     509              :     /// Get current end of WAL.
     510            0 :     fn get(&self) -> Lsn {
     511            0 :         match self {
     512            0 :             EndWatch::Commit(r) => *r.borrow(),
     513            0 :             EndWatch::Flush(r) => r.borrow().lsn,
     514              :         }
     515            0 :     }
     516              : 
     517              :     /// Wait for the update.
     518            0 :     async fn changed(&mut self) -> anyhow::Result<()> {
     519            0 :         match self {
     520            0 :             EndWatch::Commit(r) => r.changed().await?,
     521            0 :             EndWatch::Flush(r) => r.changed().await?,
     522              :         }
     523            0 :         Ok(())
     524            0 :     }
     525              : }
     526              : 
     527              : /// A half driving sending WAL.
     528              : struct WalSender<'a, IO> {
     529              :     pgb: &'a mut PostgresBackend<IO>,
     530              :     tli: FullAccessTimeline,
     531              :     appname: Option<String>,
     532              :     // Position since which we are sending next chunk.
     533              :     start_pos: Lsn,
     534              :     // WAL up to this position is known to be locally available.
     535              :     // Usually this is the same as the latest commit_lsn, but in case of
     536              :     // walproposer recovery, this is flush_lsn.
     537              :     //
     538              :     // We send this LSN to the receiver as wal_end, so that it knows how much
     539              :     // WAL this safekeeper has. This LSN should be as fresh as possible.
     540              :     end_pos: Lsn,
     541              :     /// When streaming uncommitted part, the term the client acts as the leader
     542              :     /// in. Streaming is stopped if local term changes to a different (higher)
     543              :     /// value.
     544              :     term: Option<Term>,
     545              :     /// Watch channel receiver to learn end of available WAL (and wait for its advancement).
     546              :     end_watch: EndWatch,
     547              :     ws_guard: Arc<WalSenderGuard>,
     548              :     wal_reader: WalReader,
     549              :     // buffer for readling WAL into to send it
     550              :     send_buf: [u8; MAX_SEND_SIZE],
     551              : }
     552              : 
     553              : const POLL_STATE_TIMEOUT: Duration = Duration::from_secs(1);
     554              : 
     555              : impl<IO: AsyncRead + AsyncWrite + Unpin> WalSender<'_, IO> {
     556              :     /// Send WAL until
     557              :     /// - an error occurs
     558              :     /// - receiver is caughtup and there is no computes (if streaming up to commit_lsn)
     559              :     ///
     560              :     /// Err(CopyStreamHandlerEnd) is always returned; Result is used only for ?
     561              :     /// convenience.
     562            0 :     async fn run(&mut self) -> Result<(), CopyStreamHandlerEnd> {
     563              :         loop {
     564              :             // Wait for the next portion if it is not there yet, or just
     565              :             // update our end of WAL available for sending value, we
     566              :             // communicate it to the receiver.
     567            0 :             self.wait_wal().await?;
     568            0 :             assert!(
     569            0 :                 self.end_pos > self.start_pos,
     570            0 :                 "nothing to send after waiting for WAL"
     571              :             );
     572              : 
     573              :             // try to send as much as available, capped by MAX_SEND_SIZE
     574            0 :             let mut chunk_end_pos = self.start_pos + MAX_SEND_SIZE as u64;
     575            0 :             // if we went behind available WAL, back off
     576            0 :             if chunk_end_pos >= self.end_pos {
     577            0 :                 chunk_end_pos = self.end_pos;
     578            0 :             } else {
     579            0 :                 // If sending not up to end pos, round down to page boundary to
     580            0 :                 // avoid breaking WAL record not at page boundary, as protocol
     581            0 :                 // demands. See walsender.c (XLogSendPhysical).
     582            0 :                 chunk_end_pos = chunk_end_pos
     583            0 :                     .checked_sub(chunk_end_pos.block_offset())
     584            0 :                     .unwrap();
     585            0 :             }
     586            0 :             let send_size = (chunk_end_pos.0 - self.start_pos.0) as usize;
     587            0 :             let send_buf = &mut self.send_buf[..send_size];
     588              :             let send_size: usize;
     589              :             {
     590              :                 // If uncommitted part is being pulled, check that the term is
     591              :                 // still the expected one.
     592            0 :                 let _term_guard = if let Some(t) = self.term {
     593            0 :                     Some(self.tli.acquire_term(t).await?)
     594              :                 } else {
     595            0 :                     None
     596              :                 };
     597              :                 // Read WAL into buffer. send_size can be additionally capped to
     598              :                 // segment boundary here.
     599            0 :                 send_size = self.wal_reader.read(send_buf).await?
     600              :             };
     601            0 :             let send_buf = &send_buf[..send_size];
     602            0 : 
     603            0 :             // and send it
     604            0 :             self.pgb
     605            0 :                 .write_message(&BeMessage::XLogData(XLogDataBody {
     606            0 :                     wal_start: self.start_pos.0,
     607            0 :                     wal_end: self.end_pos.0,
     608            0 :                     timestamp: get_current_timestamp(),
     609            0 :                     data: send_buf,
     610            0 :                 }))
     611            0 :                 .await?;
     612              : 
     613            0 :             if let Some(appname) = &self.appname {
     614            0 :                 if appname == "replica" {
     615            0 :                     failpoint_support::sleep_millis_async!("sk-send-wal-replica-sleep");
     616            0 :                 }
     617            0 :             }
     618            0 :             trace!(
     619            0 :                 "sent {} bytes of WAL {}-{}",
     620            0 :                 send_size,
     621            0 :                 self.start_pos,
     622            0 :                 self.start_pos + send_size as u64
     623              :             );
     624            0 :             self.start_pos += send_size as u64;
     625              :         }
     626            0 :     }
     627              : 
     628              :     /// wait until we have WAL to stream, sending keepalives and checking for
     629              :     /// exit in the meanwhile
     630            0 :     async fn wait_wal(&mut self) -> Result<(), CopyStreamHandlerEnd> {
     631              :         loop {
     632            0 :             self.end_pos = self.end_watch.get();
     633            0 :             let have_something_to_send = (|| {
     634            0 :                 fail::fail_point!(
     635            0 :                     "sk-pause-send",
     636            0 :                     self.appname.as_deref() != Some("pageserver"),
     637            0 :                     |_| { false }
     638              :                 );
     639            0 :                 self.end_pos > self.start_pos
     640            0 :             })();
     641            0 : 
     642            0 :             if have_something_to_send {
     643            0 :                 trace!("got end_pos {:?}, streaming", self.end_pos);
     644            0 :                 return Ok(());
     645            0 :             }
     646              : 
     647              :             // Wait for WAL to appear, now self.end_pos == self.start_pos.
     648            0 :             if let Some(lsn) = self.wait_for_lsn().await? {
     649            0 :                 self.end_pos = lsn;
     650            0 :                 trace!("got end_pos {:?}, streaming", self.end_pos);
     651            0 :                 return Ok(());
     652            0 :             }
     653            0 : 
     654            0 :             // Timed out waiting for WAL, check for termination and send KA.
     655            0 :             // Check for termination only if we are streaming up to commit_lsn
     656            0 :             // (to pageserver).
     657            0 :             if let EndWatch::Commit(_) = self.end_watch {
     658            0 :                 if let Some(remote_consistent_lsn) = self
     659            0 :                     .ws_guard
     660            0 :                     .walsenders
     661            0 :                     .get_ws_remote_consistent_lsn(self.ws_guard.id)
     662              :                 {
     663            0 :                     if self.tli.should_walsender_stop(remote_consistent_lsn).await {
     664              :                         // Terminate if there is nothing more to send.
     665              :                         // Note that "ending streaming" part of the string is used by
     666              :                         // pageserver to identify WalReceiverError::SuccessfulCompletion,
     667              :                         // do not change this string without updating pageserver.
     668            0 :                         return Err(CopyStreamHandlerEnd::ServerInitiated(format!(
     669            0 :                         "ending streaming to {:?} at {}, receiver is caughtup and there is no computes",
     670            0 :                         self.appname, self.start_pos,
     671            0 :                     )));
     672            0 :                     }
     673            0 :                 }
     674            0 :             }
     675              : 
     676            0 :             self.pgb
     677            0 :                 .write_message(&BeMessage::KeepAlive(WalSndKeepAlive {
     678            0 :                     wal_end: self.end_pos.0,
     679            0 :                     timestamp: get_current_timestamp(),
     680            0 :                     request_reply: true,
     681            0 :                 }))
     682            0 :                 .await?;
     683              :         }
     684            0 :     }
     685              : 
     686              :     /// Wait until we have available WAL > start_pos or timeout expires. Returns
     687              :     /// - Ok(Some(end_pos)) if needed lsn is successfully observed;
     688              :     /// - Ok(None) if timeout expired;
     689              :     /// - Err in case of error -- only if 1) term changed while fetching in recovery
     690              :     ///   mode 2) watch channel closed, which must never happen.
     691            0 :     async fn wait_for_lsn(&mut self) -> anyhow::Result<Option<Lsn>> {
     692            0 :         let fp = (|| {
     693            0 :             fail::fail_point!(
     694            0 :                 "sk-pause-send",
     695            0 :                 self.appname.as_deref() != Some("pageserver"),
     696            0 :                 |_| { true }
     697              :             );
     698            0 :             false
     699            0 :         })();
     700            0 :         if fp {
     701            0 :             tokio::time::sleep(POLL_STATE_TIMEOUT).await;
     702            0 :             return Ok(None);
     703            0 :         }
     704              : 
     705            0 :         let res = timeout(POLL_STATE_TIMEOUT, async move {
     706              :             loop {
     707            0 :                 let end_pos = self.end_watch.get();
     708            0 :                 if end_pos > self.start_pos {
     709            0 :                     return Ok(end_pos);
     710            0 :                 }
     711            0 :                 if let EndWatch::Flush(rx) = &self.end_watch {
     712            0 :                     let curr_term = rx.borrow().term;
     713            0 :                     if let Some(client_term) = self.term {
     714            0 :                         if curr_term != client_term {
     715            0 :                             bail!("term changed: requested {}, now {}", client_term, curr_term);
     716            0 :                         }
     717            0 :                     }
     718            0 :                 }
     719            0 :                 self.end_watch.changed().await?;
     720              :             }
     721            0 :         })
     722            0 :         .await;
     723              : 
     724            0 :         match res {
     725              :             // success
     726            0 :             Ok(Ok(commit_lsn)) => Ok(Some(commit_lsn)),
     727              :             // error inside closure
     728            0 :             Ok(Err(err)) => Err(err),
     729              :             // timeout
     730            0 :             Err(_) => Ok(None),
     731              :         }
     732            0 :     }
     733              : }
     734              : 
     735              : /// A half driving receiving replies.
     736              : struct ReplyReader<IO> {
     737              :     reader: PostgresBackendReader<IO>,
     738              :     ws_guard: Arc<WalSenderGuard>,
     739              :     tli: FullAccessTimeline,
     740              : }
     741              : 
     742              : impl<IO: AsyncRead + AsyncWrite + Unpin> ReplyReader<IO> {
     743            0 :     async fn run(&mut self) -> Result<(), CopyStreamHandlerEnd> {
     744              :         loop {
     745            0 :             let msg = self.reader.read_copy_message().await?;
     746            0 :             self.handle_feedback(&msg).await?
     747              :         }
     748            0 :     }
     749              : 
     750            0 :     async fn handle_feedback(&mut self, msg: &Bytes) -> anyhow::Result<()> {
     751            0 :         match msg.first().cloned() {
     752            0 :             Some(HOT_STANDBY_FEEDBACK_TAG_BYTE) => {
     753            0 :                 // Note: deserializing is on m[1..] because we skip the tag byte.
     754            0 :                 let mut hs_feedback = HotStandbyFeedback::des(&msg[1..])
     755            0 :                     .context("failed to deserialize HotStandbyFeedback")?;
     756              :                 // TODO: xmin/catalog_xmin are serialized by walreceiver.c in this way:
     757              :                 // pq_sendint32(&reply_message, xmin);
     758              :                 // pq_sendint32(&reply_message, xmin_epoch);
     759              :                 // So it is two big endian 32-bit words in low endian order!
     760            0 :                 hs_feedback.xmin = (hs_feedback.xmin >> 32) | (hs_feedback.xmin << 32);
     761            0 :                 hs_feedback.catalog_xmin =
     762            0 :                     (hs_feedback.catalog_xmin >> 32) | (hs_feedback.catalog_xmin << 32);
     763            0 :                 self.ws_guard
     764            0 :                     .walsenders
     765            0 :                     .record_hs_feedback(self.ws_guard.id, &hs_feedback);
     766              :             }
     767            0 :             Some(STANDBY_STATUS_UPDATE_TAG_BYTE) => {
     768            0 :                 let reply =
     769            0 :                     StandbyReply::des(&msg[1..]).context("failed to deserialize StandbyReply")?;
     770            0 :                 self.ws_guard
     771            0 :                     .walsenders
     772            0 :                     .record_standby_reply(self.ws_guard.id, &reply);
     773              :             }
     774              :             Some(NEON_STATUS_UPDATE_TAG_BYTE) => {
     775              :                 // pageserver sends this.
     776              :                 // Note: deserializing is on m[9..] because we skip the tag byte and len bytes.
     777            0 :                 let buf = Bytes::copy_from_slice(&msg[9..]);
     778            0 :                 let ps_feedback = PageserverFeedback::parse(buf);
     779            0 : 
     780            0 :                 trace!("PageserverFeedback is {:?}", ps_feedback);
     781            0 :                 self.ws_guard
     782            0 :                     .walsenders
     783            0 :                     .record_ps_feedback(self.ws_guard.id, &ps_feedback);
     784            0 :                 self.tli
     785            0 :                     .update_remote_consistent_lsn(ps_feedback.remote_consistent_lsn)
     786            0 :                     .await;
     787              :                 // in principle new remote_consistent_lsn could allow to
     788              :                 // deactivate the timeline, but we check that regularly through
     789              :                 // broker updated, not need to do it here
     790              :             }
     791            0 :             _ => warn!("unexpected message {:?}", msg),
     792              :         }
     793            0 :         Ok(())
     794            0 :     }
     795              : }
     796              : 
     797              : #[cfg(test)]
     798              : mod tests {
     799              :     use utils::id::{TenantId, TimelineId};
     800              : 
     801              :     use super::*;
     802              : 
     803            8 :     fn mock_ttid() -> TenantTimelineId {
     804            8 :         TenantTimelineId {
     805            8 :             tenant_id: TenantId::from_slice(&[0x00; 16]).unwrap(),
     806            8 :             timeline_id: TimelineId::from_slice(&[0x00; 16]).unwrap(),
     807            8 :         }
     808            8 :     }
     809              : 
     810            8 :     fn mock_addr() -> SocketAddr {
     811            8 :         "127.0.0.1:8080".parse().unwrap()
     812            8 :     }
     813              : 
     814              :     // add to wss specified feedback setting other fields to dummy values
     815            8 :     fn push_feedback(wss: &mut WalSendersShared, feedback: ReplicationFeedback) {
     816            8 :         let walsender_state = WalSenderState {
     817            8 :             ttid: mock_ttid(),
     818            8 :             addr: mock_addr(),
     819            8 :             conn_id: 1,
     820            8 :             appname: None,
     821            8 :             feedback,
     822            8 :         };
     823            8 :         wss.slots.push(Some(walsender_state))
     824            8 :     }
     825              : 
     826              :     // form standby feedback with given hot standby feedback ts/xmin and the
     827              :     // rest set to dummy values.
     828            8 :     fn hs_feedback(ts: TimestampTz, xmin: FullTransactionId) -> ReplicationFeedback {
     829            8 :         ReplicationFeedback::Standby(StandbyFeedback {
     830            8 :             reply: StandbyReply::empty(),
     831            8 :             hs_feedback: HotStandbyFeedback {
     832            8 :                 ts,
     833            8 :                 xmin,
     834            8 :                 catalog_xmin: 0,
     835            8 :             },
     836            8 :         })
     837            8 :     }
     838              : 
     839              :     // test that hs aggregation works as expected
     840              :     #[test]
     841            2 :     fn test_hs_feedback_no_valid() {
     842            2 :         let mut wss = WalSendersShared::new();
     843            2 :         push_feedback(&mut wss, hs_feedback(1, INVALID_FULL_TRANSACTION_ID));
     844            2 :         wss.update_reply_feedback();
     845            2 :         assert_eq!(
     846            2 :             wss.agg_standby_feedback.hs_feedback.xmin,
     847            2 :             INVALID_FULL_TRANSACTION_ID
     848            2 :         );
     849            2 :     }
     850              : 
     851              :     #[test]
     852            2 :     fn test_hs_feedback() {
     853            2 :         let mut wss = WalSendersShared::new();
     854            2 :         push_feedback(&mut wss, hs_feedback(1, INVALID_FULL_TRANSACTION_ID));
     855            2 :         push_feedback(&mut wss, hs_feedback(1, 42));
     856            2 :         push_feedback(&mut wss, hs_feedback(1, 64));
     857            2 :         wss.update_reply_feedback();
     858            2 :         assert_eq!(wss.agg_standby_feedback.hs_feedback.xmin, 42);
     859            2 :     }
     860              : }
        

Generated by: LCOV version 2.1-beta