LCOV - code coverage report
Current view: top level - safekeeper/src - timeline.rs (source / functions) Coverage Total Hit
Test: 472031e0b71f3195f7f21b1f2b20de09fd07bb56.info Lines: 33.1 % 765 253
Test Date: 2025-05-26 10:37:33 Functions: 38.1 % 126 48

            Line data    Source code
       1              : //! This module implements Timeline lifecycle management and has all necessary code
       2              : //! to glue together SafeKeeper and all other background services.
       3              : 
       4              : use std::cmp::max;
       5              : use std::ops::{Deref, DerefMut};
       6              : use std::sync::Arc;
       7              : use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
       8              : use std::time::Duration;
       9              : 
      10              : use anyhow::{Result, anyhow, bail};
      11              : use camino::{Utf8Path, Utf8PathBuf};
      12              : use http_utils::error::ApiError;
      13              : use remote_storage::RemotePath;
      14              : use safekeeper_api::Term;
      15              : use safekeeper_api::membership::Configuration;
      16              : use safekeeper_api::models::{
      17              :     PeerInfo, TimelineMembershipSwitchResponse, TimelineTermBumpResponse,
      18              : };
      19              : use storage_broker::proto::{SafekeeperTimelineInfo, TenantTimelineId as ProtoTenantTimelineId};
      20              : use tokio::fs::{self};
      21              : use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard, watch};
      22              : use tokio::time::Instant;
      23              : use tokio_util::sync::CancellationToken;
      24              : use tracing::*;
      25              : use utils::id::{NodeId, TenantId, TenantTimelineId};
      26              : use utils::lsn::Lsn;
      27              : use utils::sync::gate::Gate;
      28              : 
      29              : use crate::metrics::{FullTimelineInfo, MISC_OPERATION_SECONDS, WalStorageMetrics};
      30              : use crate::rate_limit::RateLimiter;
      31              : use crate::receive_wal::WalReceivers;
      32              : use crate::safekeeper::{AcceptorProposerMessage, ProposerAcceptorMessage, SafeKeeper, TermLsn};
      33              : use crate::send_wal::{WalSenders, WalSendersTimelineMetricValues};
      34              : use crate::state::{EvictionState, TimelineMemState, TimelinePersistentState, TimelineState};
      35              : use crate::timeline_guard::ResidenceGuard;
      36              : use crate::timeline_manager::{AtomicStatus, ManagerCtl};
      37              : use crate::timelines_set::TimelinesSet;
      38              : use crate::wal_backup;
      39              : use crate::wal_backup::{WalBackup, remote_timeline_path};
      40              : use crate::wal_backup_partial::PartialRemoteSegment;
      41              : use crate::wal_storage::{Storage as wal_storage_iface, WalReader};
      42              : use crate::{SafeKeeperConf, control_file, debug_dump, timeline_manager, wal_storage};
      43              : 
      44            0 : fn peer_info_from_sk_info(sk_info: &SafekeeperTimelineInfo, ts: Instant) -> PeerInfo {
      45            0 :     PeerInfo {
      46            0 :         sk_id: NodeId(sk_info.safekeeper_id),
      47            0 :         term: sk_info.term,
      48            0 :         last_log_term: sk_info.last_log_term,
      49            0 :         flush_lsn: Lsn(sk_info.flush_lsn),
      50            0 :         commit_lsn: Lsn(sk_info.commit_lsn),
      51            0 :         local_start_lsn: Lsn(sk_info.local_start_lsn),
      52            0 :         pg_connstr: sk_info.safekeeper_connstr.clone(),
      53            0 :         http_connstr: sk_info.http_connstr.clone(),
      54            0 :         https_connstr: sk_info.https_connstr.clone(),
      55            0 :         ts,
      56            0 :     }
      57            0 : }
      58              : 
      59              : // vector-based node id -> peer state map with very limited functionality we
      60              : // need.
      61              : #[derive(Debug, Clone, Default)]
      62              : pub struct PeersInfo(pub Vec<PeerInfo>);
      63              : 
      64              : impl PeersInfo {
      65            0 :     fn get(&mut self, id: NodeId) -> Option<&mut PeerInfo> {
      66            0 :         self.0.iter_mut().find(|p| p.sk_id == id)
      67            0 :     }
      68              : 
      69            0 :     fn upsert(&mut self, p: &PeerInfo) {
      70            0 :         match self.get(p.sk_id) {
      71            0 :             Some(rp) => *rp = p.clone(),
      72            0 :             None => self.0.push(p.clone()),
      73              :         }
      74            0 :     }
      75              : }
      76              : 
      77              : pub type ReadGuardSharedState<'a> = RwLockReadGuard<'a, SharedState>;
      78              : 
      79              : /// WriteGuardSharedState is a wrapper around `RwLockWriteGuard<SharedState>` that
      80              : /// automatically updates `watch::Sender` channels with state on drop.
      81              : pub struct WriteGuardSharedState<'a> {
      82              :     tli: Arc<Timeline>,
      83              :     guard: RwLockWriteGuard<'a, SharedState>,
      84              : }
      85              : 
      86              : impl<'a> WriteGuardSharedState<'a> {
      87         1245 :     fn new(tli: Arc<Timeline>, guard: RwLockWriteGuard<'a, SharedState>) -> Self {
      88         1245 :         WriteGuardSharedState { tli, guard }
      89         1245 :     }
      90              : }
      91              : 
      92              : impl Deref for WriteGuardSharedState<'_> {
      93              :     type Target = SharedState;
      94              : 
      95            0 :     fn deref(&self) -> &Self::Target {
      96            0 :         &self.guard
      97            0 :     }
      98              : }
      99              : 
     100              : impl DerefMut for WriteGuardSharedState<'_> {
     101         1240 :     fn deref_mut(&mut self) -> &mut Self::Target {
     102         1240 :         &mut self.guard
     103         1240 :     }
     104              : }
     105              : 
     106              : impl Drop for WriteGuardSharedState<'_> {
     107         1245 :     fn drop(&mut self) {
     108         1245 :         let term_flush_lsn =
     109         1245 :             TermLsn::from((self.guard.sk.last_log_term(), self.guard.sk.flush_lsn()));
     110         1245 :         let commit_lsn = self.guard.sk.state().inmem.commit_lsn;
     111         1245 : 
     112         1245 :         let _ = self.tli.term_flush_lsn_watch_tx.send_if_modified(|old| {
     113         1245 :             if *old != term_flush_lsn {
     114          620 :                 *old = term_flush_lsn;
     115          620 :                 true
     116              :             } else {
     117          625 :                 false
     118              :             }
     119         1245 :         });
     120         1245 : 
     121         1245 :         let _ = self.tli.commit_lsn_watch_tx.send_if_modified(|old| {
     122         1245 :             if *old != commit_lsn {
     123          615 :                 *old = commit_lsn;
     124          615 :                 true
     125              :             } else {
     126          630 :                 false
     127              :             }
     128         1245 :         });
     129         1245 : 
     130         1245 :         // send notification about shared state update
     131         1245 :         self.tli.shared_state_version_tx.send_modify(|old| {
     132         1245 :             *old += 1;
     133         1245 :         });
     134         1245 :     }
     135              : }
     136              : 
     137              : /// This structure is stored in shared state and represents the state of the timeline.
     138              : ///
     139              : /// Usually it holds SafeKeeper, but it also supports offloaded timeline state. In this
     140              : /// case, SafeKeeper is not available (because WAL is not present on disk) and all
     141              : /// operations can be done only with control file.
     142              : #[allow(clippy::large_enum_variant, reason = "TODO")]
     143              : pub enum StateSK {
     144              :     Loaded(SafeKeeper<control_file::FileStorage, wal_storage::PhysicalStorage>),
     145              :     Offloaded(Box<TimelineState<control_file::FileStorage>>),
     146              :     // Not used, required for moving between states.
     147              :     Empty,
     148              : }
     149              : 
     150              : impl StateSK {
     151         2578 :     pub fn flush_lsn(&self) -> Lsn {
     152         2578 :         match self {
     153         2578 :             StateSK::Loaded(sk) => sk.wal_store.flush_lsn(),
     154            0 :             StateSK::Offloaded(state) => match state.eviction_state {
     155            0 :                 EvictionState::Offloaded(flush_lsn) => flush_lsn,
     156            0 :                 _ => panic!("StateSK::Offloaded mismatches with eviction_state from control_file"),
     157              :             },
     158            0 :             StateSK::Empty => unreachable!(),
     159              :         }
     160         2578 :     }
     161              : 
     162              :     /// Get a reference to the control file's timeline state.
     163         2611 :     pub fn state(&self) -> &TimelineState<control_file::FileStorage> {
     164         2611 :         match self {
     165         2611 :             StateSK::Loaded(sk) => &sk.state,
     166            0 :             StateSK::Offloaded(s) => s,
     167            0 :             StateSK::Empty => unreachable!(),
     168              :         }
     169         2611 :     }
     170              : 
     171            0 :     pub fn state_mut(&mut self) -> &mut TimelineState<control_file::FileStorage> {
     172            0 :         match self {
     173            0 :             StateSK::Loaded(sk) => &mut sk.state,
     174            0 :             StateSK::Offloaded(s) => s,
     175            0 :             StateSK::Empty => unreachable!(),
     176              :         }
     177            0 :     }
     178              : 
     179         1289 :     pub fn last_log_term(&self) -> Term {
     180         1289 :         self.state()
     181         1289 :             .acceptor_state
     182         1289 :             .get_last_log_term(self.flush_lsn())
     183         1289 :     }
     184              : 
     185            0 :     pub async fn term_bump(&mut self, to: Option<Term>) -> Result<TimelineTermBumpResponse> {
     186            0 :         self.state_mut().term_bump(to).await
     187            0 :     }
     188              : 
     189            0 :     pub async fn membership_switch(
     190            0 :         &mut self,
     191            0 :         to: Configuration,
     192            0 :     ) -> Result<TimelineMembershipSwitchResponse> {
     193            0 :         self.state_mut().membership_switch(to).await
     194            0 :     }
     195              : 
     196              :     /// Close open WAL files to release FDs.
     197            0 :     fn close_wal_store(&mut self) {
     198            0 :         if let StateSK::Loaded(sk) = self {
     199            0 :             sk.wal_store.close();
     200            0 :         }
     201            0 :     }
     202              : 
     203              :     /// Update timeline state with peer safekeeper data.
     204            0 :     pub async fn record_safekeeper_info(&mut self, sk_info: &SafekeeperTimelineInfo) -> Result<()> {
     205            0 :         // update commit_lsn if safekeeper is loaded
     206            0 :         match self {
     207            0 :             StateSK::Loaded(sk) => sk.record_safekeeper_info(sk_info).await?,
     208            0 :             StateSK::Offloaded(_) => {}
     209            0 :             StateSK::Empty => unreachable!(),
     210              :         }
     211              : 
     212              :         // update everything else, including remote_consistent_lsn and backup_lsn
     213            0 :         let mut sync_control_file = false;
     214            0 :         let state = self.state_mut();
     215            0 :         let wal_seg_size = state.server.wal_seg_size as u64;
     216            0 : 
     217            0 :         state.inmem.backup_lsn = max(Lsn(sk_info.backup_lsn), state.inmem.backup_lsn);
     218            0 :         sync_control_file |= state.backup_lsn + wal_seg_size < state.inmem.backup_lsn;
     219            0 : 
     220            0 :         state.inmem.remote_consistent_lsn = max(
     221            0 :             Lsn(sk_info.remote_consistent_lsn),
     222            0 :             state.inmem.remote_consistent_lsn,
     223            0 :         );
     224            0 :         sync_control_file |=
     225            0 :             state.remote_consistent_lsn + wal_seg_size < state.inmem.remote_consistent_lsn;
     226            0 : 
     227            0 :         state.inmem.peer_horizon_lsn =
     228            0 :             max(Lsn(sk_info.peer_horizon_lsn), state.inmem.peer_horizon_lsn);
     229            0 :         sync_control_file |= state.peer_horizon_lsn + wal_seg_size < state.inmem.peer_horizon_lsn;
     230            0 : 
     231            0 :         if sync_control_file {
     232            0 :             state.flush().await?;
     233            0 :         }
     234            0 :         Ok(())
     235            0 :     }
     236              : 
     237              :     /// Previously known as epoch_start_lsn. Needed only for reference in some APIs.
     238            0 :     pub fn term_start_lsn(&self) -> Lsn {
     239            0 :         match self {
     240            0 :             StateSK::Loaded(sk) => sk.term_start_lsn,
     241            0 :             StateSK::Offloaded(_) => Lsn(0),
     242            0 :             StateSK::Empty => unreachable!(),
     243              :         }
     244            0 :     }
     245              : 
     246              :     /// Used for metrics only.
     247            0 :     pub fn wal_storage_metrics(&self) -> WalStorageMetrics {
     248            0 :         match self {
     249            0 :             StateSK::Loaded(sk) => sk.wal_store.get_metrics(),
     250            0 :             StateSK::Offloaded(_) => WalStorageMetrics::default(),
     251            0 :             StateSK::Empty => unreachable!(),
     252              :         }
     253            0 :     }
     254              : 
     255              :     /// Returns WAL storage internal LSNs for debug dump.
     256            0 :     pub fn wal_storage_internal_state(&self) -> (Lsn, Lsn, Lsn, bool) {
     257            0 :         match self {
     258            0 :             StateSK::Loaded(sk) => sk.wal_store.internal_state(),
     259              :             StateSK::Offloaded(_) => {
     260            0 :                 let flush_lsn = self.flush_lsn();
     261            0 :                 (flush_lsn, flush_lsn, flush_lsn, false)
     262              :             }
     263            0 :             StateSK::Empty => unreachable!(),
     264              :         }
     265            0 :     }
     266              : 
     267              :     /// Access to SafeKeeper object. Panics if offloaded, should be good to use from WalResidentTimeline.
     268         1240 :     pub fn safekeeper(
     269         1240 :         &mut self,
     270         1240 :     ) -> &mut SafeKeeper<control_file::FileStorage, wal_storage::PhysicalStorage> {
     271         1240 :         match self {
     272         1240 :             StateSK::Loaded(sk) => sk,
     273              :             StateSK::Offloaded(_) => {
     274            0 :                 panic!("safekeeper is offloaded, cannot be used")
     275              :             }
     276            0 :             StateSK::Empty => unreachable!(),
     277              :         }
     278         1240 :     }
     279              : 
     280              :     /// Moves control file's state structure out of the enum. Used to switch states.
     281            0 :     fn take_state(self) -> TimelineState<control_file::FileStorage> {
     282            0 :         match self {
     283            0 :             StateSK::Loaded(sk) => sk.state,
     284            0 :             StateSK::Offloaded(state) => *state,
     285            0 :             StateSK::Empty => unreachable!(),
     286              :         }
     287            0 :     }
     288              : }
     289              : 
     290              : /// Shared state associated with database instance
     291              : pub struct SharedState {
     292              :     /// Safekeeper object
     293              :     pub(crate) sk: StateSK,
     294              :     /// In memory list containing state of peers sent in latest messages from them.
     295              :     pub(crate) peers_info: PeersInfo,
     296              :     // True value hinders old WAL removal; this is used by snapshotting. We
     297              :     // could make it a counter, but there is no need to.
     298              :     pub(crate) wal_removal_on_hold: bool,
     299              : }
     300              : 
     301              : impl SharedState {
     302              :     /// Creates a new SharedState.
     303            5 :     pub fn new(sk: StateSK) -> Self {
     304            5 :         Self {
     305            5 :             sk,
     306            5 :             peers_info: PeersInfo(vec![]),
     307            5 :             wal_removal_on_hold: false,
     308            5 :         }
     309            5 :     }
     310              : 
     311              :     /// Restore SharedState from control file. If file doesn't exist, bails out.
     312            0 :     pub fn restore(conf: &SafeKeeperConf, ttid: &TenantTimelineId) -> Result<Self> {
     313            0 :         let timeline_dir = get_timeline_dir(conf, ttid);
     314            0 :         let control_store = control_file::FileStorage::restore_new(&timeline_dir, conf.no_sync)?;
     315            0 :         if control_store.server.wal_seg_size == 0 {
     316            0 :             bail!(TimelineError::UninitializedWalSegSize(*ttid));
     317            0 :         }
     318              : 
     319            0 :         let sk = match control_store.eviction_state {
     320              :             EvictionState::Present => {
     321            0 :                 let wal_store = wal_storage::PhysicalStorage::new(
     322            0 :                     ttid,
     323            0 :                     &timeline_dir,
     324            0 :                     &control_store,
     325            0 :                     conf.no_sync,
     326            0 :                 )?;
     327            0 :                 StateSK::Loaded(SafeKeeper::new(
     328            0 :                     TimelineState::new(control_store),
     329            0 :                     wal_store,
     330            0 :                     conf.my_id,
     331            0 :                 )?)
     332              :             }
     333              :             EvictionState::Offloaded(_) => {
     334            0 :                 StateSK::Offloaded(Box::new(TimelineState::new(control_store)))
     335              :             }
     336              :         };
     337              : 
     338            0 :         Ok(Self::new(sk))
     339            0 :     }
     340              : 
     341            5 :     pub(crate) fn get_wal_seg_size(&self) -> usize {
     342            5 :         self.sk.state().server.wal_seg_size as usize
     343            5 :     }
     344              : 
     345            0 :     fn get_safekeeper_info(
     346            0 :         &self,
     347            0 :         ttid: &TenantTimelineId,
     348            0 :         conf: &SafeKeeperConf,
     349            0 :         standby_apply_lsn: Lsn,
     350            0 :     ) -> SafekeeperTimelineInfo {
     351            0 :         SafekeeperTimelineInfo {
     352            0 :             safekeeper_id: conf.my_id.0,
     353            0 :             tenant_timeline_id: Some(ProtoTenantTimelineId {
     354            0 :                 tenant_id: ttid.tenant_id.as_ref().to_owned(),
     355            0 :                 timeline_id: ttid.timeline_id.as_ref().to_owned(),
     356            0 :             }),
     357            0 :             term: self.sk.state().acceptor_state.term,
     358            0 :             last_log_term: self.sk.last_log_term(),
     359            0 :             flush_lsn: self.sk.flush_lsn().0,
     360            0 :             // note: this value is not flushed to control file yet and can be lost
     361            0 :             commit_lsn: self.sk.state().inmem.commit_lsn.0,
     362            0 :             remote_consistent_lsn: self.sk.state().inmem.remote_consistent_lsn.0,
     363            0 :             peer_horizon_lsn: self.sk.state().inmem.peer_horizon_lsn.0,
     364            0 :             safekeeper_connstr: conf
     365            0 :                 .advertise_pg_addr
     366            0 :                 .to_owned()
     367            0 :                 .unwrap_or(conf.listen_pg_addr.clone()),
     368            0 :             http_connstr: conf.listen_http_addr.to_owned(),
     369            0 :             https_connstr: conf.listen_https_addr.to_owned(),
     370            0 :             backup_lsn: self.sk.state().inmem.backup_lsn.0,
     371            0 :             local_start_lsn: self.sk.state().local_start_lsn.0,
     372            0 :             availability_zone: conf.availability_zone.clone(),
     373            0 :             standby_horizon: standby_apply_lsn.0,
     374            0 :         }
     375            0 :     }
     376              : 
     377              :     /// Get our latest view of alive peers status on the timeline.
     378              :     /// We pass our own info through the broker as well, so when we don't have connection
     379              :     /// to the broker returned vec is empty.
     380           39 :     pub(crate) fn get_peers(&self, heartbeat_timeout: Duration) -> Vec<PeerInfo> {
     381           39 :         let now = Instant::now();
     382           39 :         self.peers_info
     383           39 :             .0
     384           39 :             .iter()
     385           39 :             // Regard peer as absent if we haven't heard from it within heartbeat_timeout.
     386           39 :             .filter(|p| now.duration_since(p.ts) <= heartbeat_timeout)
     387           39 :             .cloned()
     388           39 :             .collect()
     389           39 :     }
     390              : }
     391              : 
     392              : #[derive(Debug, thiserror::Error)]
     393              : pub enum TimelineError {
     394              :     #[error("Timeline {0} was cancelled and cannot be used anymore")]
     395              :     Cancelled(TenantTimelineId),
     396              :     #[error("Timeline {0} was not found in global map")]
     397              :     NotFound(TenantTimelineId),
     398              :     #[error("Timeline {0} creation is in progress")]
     399              :     CreationInProgress(TenantTimelineId),
     400              :     #[error("Timeline {0} exists on disk, but wasn't loaded on startup")]
     401              :     Invalid(TenantTimelineId),
     402              :     #[error("Timeline {0} is already exists")]
     403              :     AlreadyExists(TenantTimelineId),
     404              :     #[error("Timeline {0} is not initialized, wal_seg_size is zero")]
     405              :     UninitializedWalSegSize(TenantTimelineId),
     406              :     #[error("Timeline {0} is not initialized, pg_version is unknown")]
     407              :     UninitialinzedPgVersion(TenantTimelineId),
     408              : }
     409              : 
     410              : // Convert to HTTP API error.
     411              : impl From<TimelineError> for ApiError {
     412            0 :     fn from(te: TimelineError) -> ApiError {
     413            0 :         match te {
     414            0 :             TimelineError::NotFound(ttid) => {
     415            0 :                 ApiError::NotFound(anyhow!("timeline {} not found", ttid).into())
     416              :             }
     417            0 :             _ => ApiError::InternalServerError(anyhow!("{}", te)),
     418              :         }
     419            0 :     }
     420              : }
     421              : 
     422              : /// We run remote deletion in a background task, this is how it sends its results back.
     423              : type RemoteDeletionReceiver = tokio::sync::watch::Receiver<Option<anyhow::Result<()>>>;
     424              : 
     425              : /// Timeline struct manages lifecycle (creation, deletion, restore) of a safekeeper timeline.
     426              : /// It also holds SharedState and provides mutually exclusive access to it.
     427              : pub struct Timeline {
     428              :     pub ttid: TenantTimelineId,
     429              :     pub remote_path: RemotePath,
     430              : 
     431              :     /// Used to broadcast commit_lsn updates to all background jobs.
     432              :     commit_lsn_watch_tx: watch::Sender<Lsn>,
     433              :     commit_lsn_watch_rx: watch::Receiver<Lsn>,
     434              : 
     435              :     /// Broadcasts (current term, flush_lsn) updates, walsender is interested in
     436              :     /// them when sending in recovery mode (to walproposer or peers). Note: this
     437              :     /// is just a notification, WAL reading should always done with lock held as
     438              :     /// term can change otherwise.
     439              :     term_flush_lsn_watch_tx: watch::Sender<TermLsn>,
     440              :     term_flush_lsn_watch_rx: watch::Receiver<TermLsn>,
     441              : 
     442              :     /// Broadcasts shared state updates.
     443              :     shared_state_version_tx: watch::Sender<usize>,
     444              :     shared_state_version_rx: watch::Receiver<usize>,
     445              : 
     446              :     /// Safekeeper and other state, that should remain consistent and
     447              :     /// synchronized with the disk. This is tokio mutex as we write WAL to disk
     448              :     /// while holding it, ensuring that consensus checks are in order.
     449              :     mutex: RwLock<SharedState>,
     450              :     walsenders: Arc<WalSenders>,
     451              :     walreceivers: Arc<WalReceivers>,
     452              :     timeline_dir: Utf8PathBuf,
     453              :     manager_ctl: ManagerCtl,
     454              :     conf: Arc<SafeKeeperConf>,
     455              : 
     456              :     pub(crate) wal_backup: Arc<WalBackup>,
     457              : 
     458              :     remote_deletion: std::sync::Mutex<Option<RemoteDeletionReceiver>>,
     459              : 
     460              :     /// Hold this gate from code that depends on the Timeline's non-shut-down state.  While holding
     461              :     /// this gate, you must respect [`Timeline::cancel`]
     462              :     pub(crate) gate: Gate,
     463              : 
     464              :     /// Delete/cancel will trigger this, background tasks should drop out as soon as it fires
     465              :     pub(crate) cancel: CancellationToken,
     466              : 
     467              :     // timeline_manager controlled state
     468              :     pub(crate) broker_active: AtomicBool,
     469              :     pub(crate) wal_backup_active: AtomicBool,
     470              :     pub(crate) last_removed_segno: AtomicU64,
     471              :     pub(crate) mgr_status: AtomicStatus,
     472              : }
     473              : 
     474              : impl Timeline {
     475              :     /// Constructs a new timeline.
     476            5 :     pub fn new(
     477            5 :         ttid: TenantTimelineId,
     478            5 :         timeline_dir: &Utf8Path,
     479            5 :         remote_path: &RemotePath,
     480            5 :         shared_state: SharedState,
     481            5 :         conf: Arc<SafeKeeperConf>,
     482            5 :         wal_backup: Arc<WalBackup>,
     483            5 :     ) -> Arc<Self> {
     484            5 :         let (commit_lsn_watch_tx, commit_lsn_watch_rx) =
     485            5 :             watch::channel(shared_state.sk.state().commit_lsn);
     486            5 :         let (term_flush_lsn_watch_tx, term_flush_lsn_watch_rx) = watch::channel(TermLsn::from((
     487            5 :             shared_state.sk.last_log_term(),
     488            5 :             shared_state.sk.flush_lsn(),
     489            5 :         )));
     490            5 :         let (shared_state_version_tx, shared_state_version_rx) = watch::channel(0);
     491            5 : 
     492            5 :         let walreceivers = WalReceivers::new();
     493            5 : 
     494            5 :         Arc::new(Self {
     495            5 :             ttid,
     496            5 :             remote_path: remote_path.to_owned(),
     497            5 :             timeline_dir: timeline_dir.to_owned(),
     498            5 :             commit_lsn_watch_tx,
     499            5 :             commit_lsn_watch_rx,
     500            5 :             term_flush_lsn_watch_tx,
     501            5 :             term_flush_lsn_watch_rx,
     502            5 :             shared_state_version_tx,
     503            5 :             shared_state_version_rx,
     504            5 :             mutex: RwLock::new(shared_state),
     505            5 :             walsenders: WalSenders::new(walreceivers.clone()),
     506            5 :             walreceivers,
     507            5 :             gate: Default::default(),
     508            5 :             cancel: CancellationToken::default(),
     509            5 :             remote_deletion: std::sync::Mutex::new(None),
     510            5 :             manager_ctl: ManagerCtl::new(),
     511            5 :             conf,
     512            5 :             broker_active: AtomicBool::new(false),
     513            5 :             wal_backup_active: AtomicBool::new(false),
     514            5 :             last_removed_segno: AtomicU64::new(0),
     515            5 :             mgr_status: AtomicStatus::new(),
     516            5 :             wal_backup,
     517            5 :         })
     518            5 :     }
     519              : 
     520              :     /// Load existing timeline from disk.
     521            0 :     pub fn load_timeline(
     522            0 :         conf: Arc<SafeKeeperConf>,
     523            0 :         ttid: TenantTimelineId,
     524            0 :         wal_backup: Arc<WalBackup>,
     525            0 :     ) -> Result<Arc<Timeline>> {
     526            0 :         let _enter = info_span!("load_timeline", timeline = %ttid.timeline_id).entered();
     527              : 
     528            0 :         let shared_state = SharedState::restore(conf.as_ref(), &ttid)?;
     529            0 :         let timeline_dir = get_timeline_dir(conf.as_ref(), &ttid);
     530            0 :         let remote_path = remote_timeline_path(&ttid)?;
     531              : 
     532            0 :         Ok(Timeline::new(
     533            0 :             ttid,
     534            0 :             &timeline_dir,
     535            0 :             &remote_path,
     536            0 :             shared_state,
     537            0 :             conf,
     538            0 :             wal_backup,
     539            0 :         ))
     540            0 :     }
     541              : 
     542              :     /// Bootstrap new or existing timeline starting background tasks.
     543            5 :     pub fn bootstrap(
     544            5 :         self: &Arc<Timeline>,
     545            5 :         _shared_state: &mut WriteGuardSharedState<'_>,
     546            5 :         conf: &SafeKeeperConf,
     547            5 :         broker_active_set: Arc<TimelinesSet>,
     548            5 :         partial_backup_rate_limiter: RateLimiter,
     549            5 :         wal_backup: Arc<WalBackup>,
     550            5 :     ) {
     551            5 :         let (tx, rx) = self.manager_ctl.bootstrap_manager();
     552              : 
     553            5 :         let Ok(gate_guard) = self.gate.enter() else {
     554              :             // Init raced with shutdown
     555            0 :             return;
     556              :         };
     557              : 
     558              :         // Start manager task which will monitor timeline state and update
     559              :         // background tasks.
     560            5 :         tokio::spawn({
     561            5 :             let this = self.clone();
     562            5 :             let conf = conf.clone();
     563            5 :             async move {
     564            5 :                 let _gate_guard = gate_guard;
     565            5 :                 timeline_manager::main_task(
     566            5 :                     ManagerTimeline { tli: this },
     567            5 :                     conf,
     568            5 :                     broker_active_set,
     569            5 :                     tx,
     570            5 :                     rx,
     571            5 :                     partial_backup_rate_limiter,
     572            5 :                     wal_backup,
     573            5 :                 )
     574            5 :                 .await
     575            5 :             }
     576            5 :         });
     577            5 :     }
     578              : 
     579              :     /// Cancel the timeline, requesting background activity to stop. Closing
     580              :     /// the `self.gate` waits for that.
     581            0 :     pub async fn cancel(&self) {
     582            0 :         info!("timeline {} shutting down", self.ttid);
     583            0 :         self.cancel.cancel();
     584            0 :     }
     585              : 
     586              :     /// Background timeline activities (which hold Timeline::gate) will no
     587              :     /// longer run once this function completes. `Self::cancel` must have been
     588              :     /// already called.
     589            0 :     pub async fn close(&self) {
     590            0 :         assert!(self.cancel.is_cancelled());
     591              : 
     592              :         // Wait for any concurrent tasks to stop using this timeline, to avoid e.g. attempts
     593              :         // to read deleted files.
     594            0 :         self.gate.close().await;
     595            0 :     }
     596              : 
     597              :     /// Delete timeline from disk completely, by removing timeline directory.
     598              :     ///
     599              :     /// Also deletes WAL in s3. Might fail if e.g. s3 is unavailable, but
     600              :     /// deletion API endpoint is retriable.
     601              :     ///
     602              :     /// Timeline must be in shut-down state (i.e. call [`Self::close`] first)
     603            0 :     pub async fn delete(
     604            0 :         &self,
     605            0 :         shared_state: &mut WriteGuardSharedState<'_>,
     606            0 :         only_local: bool,
     607            0 :     ) -> Result<bool> {
     608            0 :         // Assert that [`Self::close`] was already called
     609            0 :         assert!(self.cancel.is_cancelled());
     610            0 :         assert!(self.gate.close_complete());
     611              : 
     612            0 :         info!("deleting timeline {} from disk", self.ttid);
     613              : 
     614              :         // Close associated FDs. Nobody will be able to touch timeline data once
     615              :         // it is cancelled, so WAL storage won't be opened again.
     616            0 :         shared_state.sk.close_wal_store();
     617            0 : 
     618            0 :         if !only_local {
     619            0 :             self.remote_delete().await?;
     620            0 :         }
     621              : 
     622            0 :         let dir_existed = delete_dir(&self.timeline_dir).await?;
     623            0 :         Ok(dir_existed)
     624            0 :     }
     625              : 
     626              :     /// Delete timeline content from remote storage.  If the returned future is dropped,
     627              :     /// deletion will continue in the background.
     628              :     ///
     629              :     /// This function ordinarily spawns a task and stashes a result receiver into [`Self::remote_deletion`].  If
     630              :     /// deletion is already happening, it may simply wait for an existing task's result.
     631              :     ///
     632              :     /// Note: we concurrently delete remote storage data from multiple
     633              :     /// safekeepers. That's ok, s3 replies 200 if object doesn't exist and we
     634              :     /// do some retries anyway.
     635            0 :     async fn remote_delete(&self) -> Result<()> {
     636              :         // We will start a background task to do the deletion, so that it proceeds even if our
     637              :         // API request is dropped.  Future requests will see the existing deletion task and wait
     638              :         // for it to complete.
     639            0 :         let mut result_rx = {
     640            0 :             let mut remote_deletion_state = self.remote_deletion.lock().unwrap();
     641            0 :             let result_rx = if let Some(result_rx) = remote_deletion_state.as_ref() {
     642            0 :                 if let Some(result) = result_rx.borrow().as_ref() {
     643            0 :                     if let Err(e) = result {
     644              :                         // A previous remote deletion failed: we will start a new one
     645            0 :                         tracing::error!("remote deletion failed, will retry ({e})");
     646            0 :                         None
     647              :                     } else {
     648              :                         // A previous remote deletion call already succeeded
     649            0 :                         return Ok(());
     650              :                     }
     651              :                 } else {
     652              :                     // Remote deletion is still in flight
     653            0 :                     Some(result_rx.clone())
     654              :                 }
     655              :             } else {
     656              :                 // Remote deletion was not attempted yet, start it now.
     657            0 :                 None
     658              :             };
     659              : 
     660            0 :             match result_rx {
     661            0 :                 Some(result_rx) => result_rx,
     662            0 :                 None => self.start_remote_delete(&mut remote_deletion_state),
     663              :             }
     664              :         };
     665              : 
     666              :         // Wait for a result
     667            0 :         let Ok(result) = result_rx.wait_for(|v| v.is_some()).await else {
     668              :             // Unexpected: sender should always send a result before dropping the channel, even if it has an error
     669            0 :             return Err(anyhow::anyhow!(
     670            0 :                 "remote deletion task future was dropped without sending a result"
     671            0 :             ));
     672              :         };
     673              : 
     674            0 :         result
     675            0 :             .as_ref()
     676            0 :             .expect("We did a wait_for on this being Some above")
     677            0 :             .as_ref()
     678            0 :             .map(|_| ())
     679            0 :             .map_err(|e| anyhow::anyhow!("remote deletion failed: {e}"))
     680            0 :     }
     681              : 
     682              :     /// Spawn background task to do remote deletion, return a receiver for its outcome
     683            0 :     fn start_remote_delete(
     684            0 :         &self,
     685            0 :         guard: &mut std::sync::MutexGuard<Option<RemoteDeletionReceiver>>,
     686            0 :     ) -> RemoteDeletionReceiver {
     687            0 :         tracing::info!("starting remote deletion");
     688            0 :         let storage = self.wal_backup.get_storage().clone();
     689            0 :         let (result_tx, result_rx) = tokio::sync::watch::channel(None);
     690            0 :         let ttid = self.ttid;
     691            0 :         tokio::task::spawn(
     692            0 :             async move {
     693            0 :                 let r = if let Some(storage) = storage {
     694            0 :                     wal_backup::delete_timeline(&storage, &ttid).await
     695              :                 } else {
     696            0 :                     tracing::info!(
     697            0 :                         "skipping remote deletion because no remote storage is configured; this effectively leaks the objects in remote storage"
     698              :                     );
     699            0 :                     Ok(())
     700              :                 };
     701              : 
     702            0 :                 if let Err(e) = &r {
     703              :                     // Log error here in case nobody ever listens for our result (e.g. dropped API request)
     704            0 :                     tracing::error!("remote deletion failed: {e}");
     705            0 :                 }
     706              : 
     707              :                 // Ignore send results: it's legal for the Timeline to give up waiting for us.
     708            0 :                 let _ = result_tx.send(Some(r));
     709            0 :             }
     710            0 :             .instrument(info_span!("remote_delete", timeline = %self.ttid)),
     711              :         );
     712              : 
     713            0 :         **guard = Some(result_rx.clone());
     714            0 : 
     715            0 :         result_rx
     716            0 :     }
     717              : 
     718              :     /// Returns if timeline is cancelled.
     719         2505 :     pub fn is_cancelled(&self) -> bool {
     720         2505 :         self.cancel.is_cancelled()
     721         2505 :     }
     722              : 
     723              :     /// Take a writing mutual exclusive lock on timeline shared_state.
     724         1245 :     pub async fn write_shared_state(self: &Arc<Self>) -> WriteGuardSharedState<'_> {
     725         1245 :         WriteGuardSharedState::new(self.clone(), self.mutex.write().await)
     726         1245 :     }
     727              : 
     728           58 :     pub async fn read_shared_state(&self) -> ReadGuardSharedState {
     729           58 :         self.mutex.read().await
     730           58 :     }
     731              : 
     732              :     /// Returns commit_lsn watch channel.
     733            5 :     pub fn get_commit_lsn_watch_rx(&self) -> watch::Receiver<Lsn> {
     734            5 :         self.commit_lsn_watch_rx.clone()
     735            5 :     }
     736              : 
     737              :     /// Returns term_flush_lsn watch channel.
     738            0 :     pub fn get_term_flush_lsn_watch_rx(&self) -> watch::Receiver<TermLsn> {
     739            0 :         self.term_flush_lsn_watch_rx.clone()
     740            0 :     }
     741              : 
     742              :     /// Returns watch channel for SharedState update version.
     743            5 :     pub fn get_state_version_rx(&self) -> watch::Receiver<usize> {
     744            5 :         self.shared_state_version_rx.clone()
     745            5 :     }
     746              : 
     747              :     /// Returns wal_seg_size.
     748            5 :     pub async fn get_wal_seg_size(&self) -> usize {
     749            5 :         self.read_shared_state().await.get_wal_seg_size()
     750            5 :     }
     751              : 
     752              :     /// Returns state of the timeline.
     753            9 :     pub async fn get_state(&self) -> (TimelineMemState, TimelinePersistentState) {
     754            9 :         let state = self.read_shared_state().await;
     755            9 :         (
     756            9 :             state.sk.state().inmem.clone(),
     757            9 :             TimelinePersistentState::clone(state.sk.state()),
     758            9 :         )
     759            9 :     }
     760              : 
     761              :     /// Returns latest backup_lsn.
     762            0 :     pub async fn get_wal_backup_lsn(&self) -> Lsn {
     763            0 :         self.read_shared_state().await.sk.state().inmem.backup_lsn
     764            0 :     }
     765              : 
     766              :     /// Sets backup_lsn to the given value.
     767            0 :     pub async fn set_wal_backup_lsn(self: &Arc<Self>, backup_lsn: Lsn) -> Result<()> {
     768            0 :         if self.is_cancelled() {
     769            0 :             bail!(TimelineError::Cancelled(self.ttid));
     770            0 :         }
     771              : 
     772            0 :         let mut state = self.write_shared_state().await;
     773            0 :         state.sk.state_mut().inmem.backup_lsn = max(state.sk.state().inmem.backup_lsn, backup_lsn);
     774            0 :         // we should check whether to shut down offloader, but this will be done
     775            0 :         // soon by peer communication anyway.
     776            0 :         Ok(())
     777            0 :     }
     778              : 
     779              :     /// Get safekeeper info for broadcasting to broker and other peers.
     780            0 :     pub async fn get_safekeeper_info(&self, conf: &SafeKeeperConf) -> SafekeeperTimelineInfo {
     781            0 :         let standby_apply_lsn = self.walsenders.get_hotstandby().reply.apply_lsn;
     782            0 :         let shared_state = self.read_shared_state().await;
     783            0 :         shared_state.get_safekeeper_info(&self.ttid, conf, standby_apply_lsn)
     784            0 :     }
     785              : 
     786              :     /// Update timeline state with peer safekeeper data.
     787            0 :     pub async fn record_safekeeper_info(
     788            0 :         self: &Arc<Self>,
     789            0 :         sk_info: SafekeeperTimelineInfo,
     790            0 :     ) -> Result<()> {
     791              :         {
     792            0 :             let mut shared_state = self.write_shared_state().await;
     793            0 :             shared_state.sk.record_safekeeper_info(&sk_info).await?;
     794            0 :             let peer_info = peer_info_from_sk_info(&sk_info, Instant::now());
     795            0 :             shared_state.peers_info.upsert(&peer_info);
     796            0 :         }
     797            0 :         Ok(())
     798            0 :     }
     799              : 
     800            0 :     pub async fn get_peers(&self, conf: &SafeKeeperConf) -> Vec<PeerInfo> {
     801            0 :         let shared_state = self.read_shared_state().await;
     802            0 :         shared_state.get_peers(conf.heartbeat_timeout)
     803            0 :     }
     804              : 
     805            5 :     pub fn get_walsenders(&self) -> &Arc<WalSenders> {
     806            5 :         &self.walsenders
     807            5 :     }
     808              : 
     809           15 :     pub fn get_walreceivers(&self) -> &Arc<WalReceivers> {
     810           15 :         &self.walreceivers
     811           15 :     }
     812              : 
     813              :     /// Returns flush_lsn.
     814            0 :     pub async fn get_flush_lsn(&self) -> Lsn {
     815            0 :         self.read_shared_state().await.sk.flush_lsn()
     816            0 :     }
     817              : 
     818              :     /// Gather timeline data for metrics.
     819            0 :     pub async fn info_for_metrics(&self) -> Option<FullTimelineInfo> {
     820            0 :         if self.is_cancelled() {
     821            0 :             return None;
     822            0 :         }
     823            0 : 
     824            0 :         let WalSendersTimelineMetricValues {
     825            0 :             ps_feedback_counter,
     826            0 :             last_ps_feedback,
     827            0 :             interpreted_wal_reader_tasks,
     828            0 :         } = self.walsenders.info_for_metrics();
     829              : 
     830            0 :         let state = self.read_shared_state().await;
     831            0 :         Some(FullTimelineInfo {
     832            0 :             ttid: self.ttid,
     833            0 :             ps_feedback_count: ps_feedback_counter,
     834            0 :             last_ps_feedback,
     835            0 :             wal_backup_active: self.wal_backup_active.load(Ordering::Relaxed),
     836            0 :             timeline_is_active: self.broker_active.load(Ordering::Relaxed),
     837            0 :             num_computes: self.walreceivers.get_num() as u32,
     838            0 :             last_removed_segno: self.last_removed_segno.load(Ordering::Relaxed),
     839            0 :             interpreted_wal_reader_tasks,
     840            0 :             epoch_start_lsn: state.sk.term_start_lsn(),
     841            0 :             mem_state: state.sk.state().inmem.clone(),
     842            0 :             persisted_state: TimelinePersistentState::clone(state.sk.state()),
     843            0 :             flush_lsn: state.sk.flush_lsn(),
     844            0 :             wal_storage: state.sk.wal_storage_metrics(),
     845            0 :         })
     846            0 :     }
     847              : 
     848              :     /// Returns in-memory timeline state to build a full debug dump.
     849            0 :     pub async fn memory_dump(&self) -> debug_dump::Memory {
     850            0 :         let state = self.read_shared_state().await;
     851              : 
     852            0 :         let (write_lsn, write_record_lsn, flush_lsn, file_open) =
     853            0 :             state.sk.wal_storage_internal_state();
     854            0 : 
     855            0 :         debug_dump::Memory {
     856            0 :             is_cancelled: self.is_cancelled(),
     857            0 :             peers_info_len: state.peers_info.0.len(),
     858            0 :             walsenders: self.walsenders.get_all_public(),
     859            0 :             wal_backup_active: self.wal_backup_active.load(Ordering::Relaxed),
     860            0 :             active: self.broker_active.load(Ordering::Relaxed),
     861            0 :             num_computes: self.walreceivers.get_num() as u32,
     862            0 :             last_removed_segno: self.last_removed_segno.load(Ordering::Relaxed),
     863            0 :             epoch_start_lsn: state.sk.term_start_lsn(),
     864            0 :             mem_state: state.sk.state().inmem.clone(),
     865            0 :             mgr_status: self.mgr_status.get(),
     866            0 :             write_lsn,
     867            0 :             write_record_lsn,
     868            0 :             flush_lsn,
     869            0 :             file_open,
     870            0 :         }
     871            0 :     }
     872              : 
     873              :     /// Apply a function to the control file state and persist it.
     874            0 :     pub async fn map_control_file<T>(
     875            0 :         self: &Arc<Self>,
     876            0 :         f: impl FnOnce(&mut TimelinePersistentState) -> Result<T>,
     877            0 :     ) -> Result<T> {
     878            0 :         let mut state = self.write_shared_state().await;
     879            0 :         let mut persistent_state = state.sk.state_mut().start_change();
     880              :         // If f returns error, we abort the change and don't persist anything.
     881            0 :         let res = f(&mut persistent_state)?;
     882              :         // If persisting fails, we abort the change and return error.
     883            0 :         state
     884            0 :             .sk
     885            0 :             .state_mut()
     886            0 :             .finish_change(&persistent_state)
     887            0 :             .await?;
     888            0 :         Ok(res)
     889            0 :     }
     890              : 
     891            0 :     pub async fn term_bump(self: &Arc<Self>, to: Option<Term>) -> Result<TimelineTermBumpResponse> {
     892            0 :         let mut state = self.write_shared_state().await;
     893            0 :         state.sk.term_bump(to).await
     894            0 :     }
     895              : 
     896            0 :     pub async fn membership_switch(
     897            0 :         self: &Arc<Self>,
     898            0 :         to: Configuration,
     899            0 :     ) -> Result<TimelineMembershipSwitchResponse> {
     900            0 :         let mut state = self.write_shared_state().await;
     901            0 :         state.sk.membership_switch(to).await
     902            0 :     }
     903              : 
     904              :     /// Guts of [`Self::wal_residence_guard`] and [`Self::try_wal_residence_guard`]
     905           10 :     async fn do_wal_residence_guard(
     906           10 :         self: &Arc<Self>,
     907           10 :         block: bool,
     908           10 :     ) -> Result<Option<WalResidentTimeline>> {
     909           10 :         let op_label = if block {
     910           10 :             "wal_residence_guard"
     911              :         } else {
     912            0 :             "try_wal_residence_guard"
     913              :         };
     914              : 
     915           10 :         if self.is_cancelled() {
     916            0 :             bail!(TimelineError::Cancelled(self.ttid));
     917           10 :         }
     918           10 : 
     919           10 :         debug!("requesting WalResidentTimeline guard");
     920           10 :         let started_at = Instant::now();
     921           10 :         let status_before = self.mgr_status.get();
     922              : 
     923              :         // Wait 30 seconds for the guard to be acquired. It can time out if someone is
     924              :         // holding the lock (e.g. during `SafeKeeper::process_msg()`) or manager task
     925              :         // is stuck.
     926           10 :         let res = tokio::time::timeout_at(started_at + Duration::from_secs(30), async {
     927           10 :             if block {
     928           10 :                 self.manager_ctl.wal_residence_guard().await.map(Some)
     929              :             } else {
     930            0 :                 self.manager_ctl.try_wal_residence_guard().await
     931              :             }
     932           10 :         })
     933           10 :         .await;
     934              : 
     935           10 :         let guard = match res {
     936           10 :             Ok(Ok(guard)) => {
     937           10 :                 let finished_at = Instant::now();
     938           10 :                 let elapsed = finished_at - started_at;
     939           10 :                 MISC_OPERATION_SECONDS
     940           10 :                     .with_label_values(&[op_label])
     941           10 :                     .observe(elapsed.as_secs_f64());
     942           10 : 
     943           10 :                 guard
     944              :             }
     945            0 :             Ok(Err(e)) => {
     946            0 :                 warn!(
     947            0 :                     "error acquiring in {op_label}, statuses {:?} => {:?}",
     948            0 :                     status_before,
     949            0 :                     self.mgr_status.get()
     950              :                 );
     951            0 :                 return Err(e);
     952              :             }
     953              :             Err(_) => {
     954            0 :                 warn!(
     955            0 :                     "timeout acquiring in {op_label} guard, statuses {:?} => {:?}",
     956            0 :                     status_before,
     957            0 :                     self.mgr_status.get()
     958              :                 );
     959            0 :                 anyhow::bail!("timeout while acquiring WalResidentTimeline guard");
     960              :             }
     961              :         };
     962              : 
     963           10 :         Ok(guard.map(|g| WalResidentTimeline::new(self.clone(), g)))
     964           10 :     }
     965              : 
     966              :     /// Get the timeline guard for reading/writing WAL files.
     967              :     /// If WAL files are not present on disk (evicted), they will be automatically
     968              :     /// downloaded from remote storage. This is done in the manager task, which is
     969              :     /// responsible for issuing all guards.
     970              :     ///
     971              :     /// NB: don't use this function from timeline_manager, it will deadlock.
     972              :     /// NB: don't use this function while holding shared_state lock.
     973           10 :     pub async fn wal_residence_guard(self: &Arc<Self>) -> Result<WalResidentTimeline> {
     974           10 :         self.do_wal_residence_guard(true)
     975           10 :             .await
     976           10 :             .map(|m| m.expect("Always get Some in block=true mode"))
     977           10 :     }
     978              : 
     979              :     /// Get the timeline guard for reading/writing WAL files if the timeline is resident,
     980              :     /// else return None
     981            0 :     pub(crate) async fn try_wal_residence_guard(
     982            0 :         self: &Arc<Self>,
     983            0 :     ) -> Result<Option<WalResidentTimeline>> {
     984            0 :         self.do_wal_residence_guard(false).await
     985            0 :     }
     986              : 
     987            0 :     pub async fn backup_partial_reset(self: &Arc<Self>) -> Result<Vec<String>> {
     988            0 :         self.manager_ctl.backup_partial_reset().await
     989            0 :     }
     990              : }
     991              : 
     992              : /// This is a guard that allows to read/write disk timeline state.
     993              : /// All tasks that are trying to read/write WAL from disk should use this guard.
     994              : pub struct WalResidentTimeline {
     995              :     pub tli: Arc<Timeline>,
     996              :     _guard: ResidenceGuard,
     997              : }
     998              : 
     999              : impl WalResidentTimeline {
    1000           15 :     pub fn new(tli: Arc<Timeline>, _guard: ResidenceGuard) -> Self {
    1001           15 :         WalResidentTimeline { tli, _guard }
    1002           15 :     }
    1003              : }
    1004              : 
    1005              : impl Deref for WalResidentTimeline {
    1006              :     type Target = Arc<Timeline>;
    1007              : 
    1008         5666 :     fn deref(&self) -> &Self::Target {
    1009         5666 :         &self.tli
    1010         5666 :     }
    1011              : }
    1012              : 
    1013              : impl WalResidentTimeline {
    1014              :     /// Returns true if walsender should stop sending WAL to pageserver. We
    1015              :     /// terminate it if remote_consistent_lsn reached commit_lsn and there is no
    1016              :     /// computes. While there might be nothing to stream already, we learn about
    1017              :     /// remote_consistent_lsn update through replication feedback, and we want
    1018              :     /// to stop pushing to the broker if pageserver is fully caughtup.
    1019            0 :     pub async fn should_walsender_stop(&self, reported_remote_consistent_lsn: Lsn) -> bool {
    1020            0 :         if self.is_cancelled() {
    1021            0 :             return true;
    1022            0 :         }
    1023            0 :         let shared_state = self.read_shared_state().await;
    1024            0 :         if self.walreceivers.get_num() == 0 {
    1025            0 :             return shared_state.sk.state().inmem.commit_lsn == Lsn(0) || // no data at all yet
    1026            0 :             reported_remote_consistent_lsn >= shared_state.sk.state().inmem.commit_lsn;
    1027            0 :         }
    1028            0 :         false
    1029            0 :     }
    1030              : 
    1031              :     /// Ensure that current term is t, erroring otherwise, and lock the state.
    1032            0 :     pub async fn acquire_term(&self, t: Term) -> Result<ReadGuardSharedState> {
    1033            0 :         let ss = self.read_shared_state().await;
    1034            0 :         if ss.sk.state().acceptor_state.term != t {
    1035            0 :             bail!(
    1036            0 :                 "failed to acquire term {}, current term {}",
    1037            0 :                 t,
    1038            0 :                 ss.sk.state().acceptor_state.term
    1039            0 :             );
    1040            0 :         }
    1041            0 :         Ok(ss)
    1042            0 :     }
    1043              : 
    1044              :     /// Pass arrived message to the safekeeper.
    1045         1240 :     pub async fn process_msg(
    1046         1240 :         &self,
    1047         1240 :         msg: &ProposerAcceptorMessage,
    1048         1240 :     ) -> Result<Option<AcceptorProposerMessage>> {
    1049         1240 :         if self.is_cancelled() {
    1050            0 :             bail!(TimelineError::Cancelled(self.ttid));
    1051         1240 :         }
    1052              : 
    1053              :         let mut rmsg: Option<AcceptorProposerMessage>;
    1054              :         {
    1055         1240 :             let mut shared_state = self.write_shared_state().await;
    1056         1240 :             rmsg = shared_state.sk.safekeeper().process_msg(msg).await?;
    1057              : 
    1058              :             // if this is AppendResponse, fill in proper hot standby feedback.
    1059          620 :             if let Some(AcceptorProposerMessage::AppendResponse(ref mut resp)) = rmsg {
    1060          620 :                 resp.hs_feedback = self.walsenders.get_hotstandby().hs_feedback;
    1061          620 :             }
    1062              :         }
    1063         1240 :         Ok(rmsg)
    1064         1240 :     }
    1065              : 
    1066            9 :     pub async fn get_walreader(&self, start_lsn: Lsn) -> Result<WalReader> {
    1067            9 :         let (_, persisted_state) = self.get_state().await;
    1068              : 
    1069            9 :         WalReader::new(
    1070            9 :             &self.ttid,
    1071            9 :             self.timeline_dir.clone(),
    1072            9 :             &persisted_state,
    1073            9 :             start_lsn,
    1074            9 :             self.wal_backup.clone(),
    1075            9 :         )
    1076            9 :     }
    1077              : 
    1078            0 :     pub fn get_timeline_dir(&self) -> Utf8PathBuf {
    1079            0 :         self.timeline_dir.clone()
    1080            0 :     }
    1081              : 
    1082              :     /// Update in memory remote consistent lsn.
    1083            0 :     pub async fn update_remote_consistent_lsn(&self, candidate: Lsn) {
    1084            0 :         let mut shared_state = self.write_shared_state().await;
    1085            0 :         shared_state.sk.state_mut().inmem.remote_consistent_lsn = max(
    1086            0 :             shared_state.sk.state().inmem.remote_consistent_lsn,
    1087            0 :             candidate,
    1088            0 :         );
    1089            0 :     }
    1090              : }
    1091              : 
    1092              : /// This struct contains methods that are used by timeline manager task.
    1093              : pub(crate) struct ManagerTimeline {
    1094              :     pub(crate) tli: Arc<Timeline>,
    1095              : }
    1096              : 
    1097              : impl Deref for ManagerTimeline {
    1098              :     type Target = Arc<Timeline>;
    1099              : 
    1100          417 :     fn deref(&self) -> &Self::Target {
    1101          417 :         &self.tli
    1102          417 :     }
    1103              : }
    1104              : 
    1105              : impl ManagerTimeline {
    1106            0 :     pub(crate) fn timeline_dir(&self) -> &Utf8PathBuf {
    1107            0 :         &self.tli.timeline_dir
    1108            0 :     }
    1109              : 
    1110              :     /// Manager requests this state on startup.
    1111            5 :     pub(crate) async fn bootstrap_mgr(&self) -> (bool, Option<PartialRemoteSegment>) {
    1112            5 :         let shared_state = self.read_shared_state().await;
    1113            5 :         let is_offloaded = matches!(
    1114            5 :             shared_state.sk.state().eviction_state,
    1115              :             EvictionState::Offloaded(_)
    1116              :         );
    1117            5 :         let partial_backup_uploaded = shared_state.sk.state().partial_backup.uploaded_segment();
    1118            5 : 
    1119            5 :         (is_offloaded, partial_backup_uploaded)
    1120            5 :     }
    1121              : 
    1122              :     /// Try to switch state Present->Offloaded.
    1123            0 :     pub(crate) async fn switch_to_offloaded(
    1124            0 :         &self,
    1125            0 :         partial: &PartialRemoteSegment,
    1126            0 :     ) -> anyhow::Result<()> {
    1127            0 :         let mut shared = self.write_shared_state().await;
    1128              : 
    1129              :         // updating control file
    1130            0 :         let mut pstate = shared.sk.state_mut().start_change();
    1131              : 
    1132            0 :         if !matches!(pstate.eviction_state, EvictionState::Present) {
    1133            0 :             bail!(
    1134            0 :                 "cannot switch to offloaded state, current state is {:?}",
    1135            0 :                 pstate.eviction_state
    1136            0 :             );
    1137            0 :         }
    1138            0 : 
    1139            0 :         if partial.flush_lsn != shared.sk.flush_lsn() {
    1140            0 :             bail!(
    1141            0 :                 "flush_lsn mismatch in partial backup, expected {}, got {}",
    1142            0 :                 shared.sk.flush_lsn(),
    1143            0 :                 partial.flush_lsn
    1144            0 :             );
    1145            0 :         }
    1146            0 : 
    1147            0 :         if partial.commit_lsn != pstate.commit_lsn {
    1148            0 :             bail!(
    1149            0 :                 "commit_lsn mismatch in partial backup, expected {}, got {}",
    1150            0 :                 pstate.commit_lsn,
    1151            0 :                 partial.commit_lsn
    1152            0 :             );
    1153            0 :         }
    1154            0 : 
    1155            0 :         if partial.term != shared.sk.last_log_term() {
    1156            0 :             bail!(
    1157            0 :                 "term mismatch in partial backup, expected {}, got {}",
    1158            0 :                 shared.sk.last_log_term(),
    1159            0 :                 partial.term
    1160            0 :             );
    1161            0 :         }
    1162            0 : 
    1163            0 :         pstate.eviction_state = EvictionState::Offloaded(shared.sk.flush_lsn());
    1164            0 :         shared.sk.state_mut().finish_change(&pstate).await?;
    1165              :         // control file is now switched to Offloaded state
    1166              : 
    1167              :         // now we can switch shared.sk to Offloaded, shouldn't fail
    1168            0 :         let prev_sk = std::mem::replace(&mut shared.sk, StateSK::Empty);
    1169            0 :         let cfile_state = prev_sk.take_state();
    1170            0 :         shared.sk = StateSK::Offloaded(Box::new(cfile_state));
    1171            0 : 
    1172            0 :         Ok(())
    1173            0 :     }
    1174              : 
    1175              :     /// Try to switch state Offloaded->Present.
    1176            0 :     pub(crate) async fn switch_to_present(&self) -> anyhow::Result<()> {
    1177            0 :         let mut shared = self.write_shared_state().await;
    1178              : 
    1179              :         // trying to restore WAL storage
    1180            0 :         let wal_store = wal_storage::PhysicalStorage::new(
    1181            0 :             &self.ttid,
    1182            0 :             &self.timeline_dir,
    1183            0 :             shared.sk.state(),
    1184            0 :             self.conf.no_sync,
    1185            0 :         )?;
    1186              : 
    1187              :         // updating control file
    1188            0 :         let mut pstate = shared.sk.state_mut().start_change();
    1189              : 
    1190            0 :         if !matches!(pstate.eviction_state, EvictionState::Offloaded(_)) {
    1191            0 :             bail!(
    1192            0 :                 "cannot switch to present state, current state is {:?}",
    1193            0 :                 pstate.eviction_state
    1194            0 :             );
    1195            0 :         }
    1196            0 : 
    1197            0 :         if wal_store.flush_lsn() != shared.sk.flush_lsn() {
    1198            0 :             bail!(
    1199            0 :                 "flush_lsn mismatch in restored WAL, expected {}, got {}",
    1200            0 :                 shared.sk.flush_lsn(),
    1201            0 :                 wal_store.flush_lsn()
    1202            0 :             );
    1203            0 :         }
    1204            0 : 
    1205            0 :         pstate.eviction_state = EvictionState::Present;
    1206            0 :         shared.sk.state_mut().finish_change(&pstate).await?;
    1207              : 
    1208              :         // now we can switch shared.sk to Present, shouldn't fail
    1209            0 :         let prev_sk = std::mem::replace(&mut shared.sk, StateSK::Empty);
    1210            0 :         let cfile_state = prev_sk.take_state();
    1211            0 :         shared.sk = StateSK::Loaded(SafeKeeper::new(cfile_state, wal_store, self.conf.my_id)?);
    1212              : 
    1213            0 :         Ok(())
    1214            0 :     }
    1215              : 
    1216              :     /// Update current manager state, useful for debugging manager deadlocks.
    1217          226 :     pub(crate) fn set_status(&self, status: timeline_manager::Status) {
    1218          226 :         self.mgr_status.store(status, Ordering::Relaxed);
    1219          226 :     }
    1220              : }
    1221              : 
    1222              : /// Deletes directory and it's contents. Returns false if directory does not exist.
    1223            0 : pub async fn delete_dir(path: &Utf8PathBuf) -> Result<bool> {
    1224            0 :     match fs::remove_dir_all(path).await {
    1225            0 :         Ok(_) => Ok(true),
    1226            0 :         Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
    1227            0 :         Err(e) => Err(e.into()),
    1228              :     }
    1229            0 : }
    1230              : 
    1231              : /// Get a path to the tenant directory. If you just need to get a timeline directory,
    1232              : /// use WalResidentTimeline::get_timeline_dir instead.
    1233           10 : pub fn get_tenant_dir(conf: &SafeKeeperConf, tenant_id: &TenantId) -> Utf8PathBuf {
    1234           10 :     conf.workdir.join(tenant_id.to_string())
    1235           10 : }
    1236              : 
    1237              : /// Get a path to the timeline directory. If you need to read WAL files from disk,
    1238              : /// use WalResidentTimeline::get_timeline_dir instead. This function does not check
    1239              : /// timeline eviction status and WAL files might not be present on disk.
    1240           10 : pub fn get_timeline_dir(conf: &SafeKeeperConf, ttid: &TenantTimelineId) -> Utf8PathBuf {
    1241           10 :     get_tenant_dir(conf, &ttid.tenant_id).join(ttid.timeline_id.to_string())
    1242           10 : }
        

Generated by: LCOV version 2.1-beta