LCOV - code coverage report
Current view: top level - pageserver/src/tenant - remote_timeline_client.rs (source / functions) Coverage Total Hit
Test: 91bf6c8f32e5e69adde6241313e732fdd6d6e277.info Lines: 64.0 % 2075 1329
Test Date: 2025-03-04 12:19:20 Functions: 51.8 % 195 101

            Line data    Source code
       1              : //! This module manages synchronizing local FS with remote storage.
       2              : //!
       3              : //! # Overview
       4              : //!
       5              : //! * [`RemoteTimelineClient`] provides functions related to upload/download of a particular timeline.
       6              : //!   It contains a queue of pending uploads, and manages the queue, performing uploads in parallel
       7              : //!   when it's safe to do so.
       8              : //!
       9              : //! * Stand-alone function, [`list_remote_timelines`], to get list of timelines of a tenant.
      10              : //!
      11              : //! These functions use the low-level remote storage client, [`remote_storage::RemoteStorage`].
      12              : //!
      13              : //! # APIs & How To Use Them
      14              : //!
      15              : //! There is a [RemoteTimelineClient] for each [Timeline][`crate::tenant::Timeline`] in the system,
      16              : //! unless the pageserver is configured without remote storage.
      17              : //!
      18              : //! We allocate the client instance in [Timeline][`crate::tenant::Timeline`], i.e.,
      19              : //! either in [`crate::tenant::mgr`] during startup or when creating a new
      20              : //! timeline.
      21              : //! However, the client does not become ready for use until we've initialized its upload queue:
      22              : //!
      23              : //! - For timelines that already have some state on the remote storage, we use
      24              : //!   [`RemoteTimelineClient::init_upload_queue`] .
      25              : //! - For newly created timelines, we use
      26              : //!   [`RemoteTimelineClient::init_upload_queue_for_empty_remote`].
      27              : //!
      28              : //! The former takes the remote's [`IndexPart`] as an argument, possibly retrieved
      29              : //! using [`list_remote_timelines`]. We'll elaborate on [`IndexPart`] in the next section.
      30              : //!
      31              : //! Whenever we've created/updated/deleted a file in a timeline directory, we schedule
      32              : //! the corresponding remote operation with the timeline's [`RemoteTimelineClient`]:
      33              : //!
      34              : //! - [`RemoteTimelineClient::schedule_layer_file_upload`]  when we've created a new layer file.
      35              : //! - [`RemoteTimelineClient::schedule_index_upload_for_metadata_update`] when we've updated the timeline metadata file.
      36              : //! - [`RemoteTimelineClient::schedule_index_upload_for_file_changes`] to upload an updated index file, after we've scheduled file uploads
      37              : //! - [`RemoteTimelineClient::schedule_layer_file_deletion`] when we've deleted one or more layer files.
      38              : //!
      39              : //! Internally, these functions create [`UploadOp`]s and put them in a queue.
      40              : //!
      41              : //! There are also APIs for downloading files.
      42              : //! These are not part of the aforementioned queuing and will not be discussed
      43              : //! further here, except in the section covering tenant attach.
      44              : //!
      45              : //! # Remote Storage Structure & [`IndexPart`] Index File
      46              : //!
      47              : //! The "directory structure" in the remote storage mirrors the local directory structure, with paths
      48              : //! like `tenants/<tenant_id>/timelines/<timeline_id>/<layer filename>`.
      49              : //! Yet instead of keeping the `metadata` file remotely, we wrap it with more
      50              : //! data in an "index file" aka [`IndexPart`], containing the list of **all** remote
      51              : //! files for a given timeline.
      52              : //! If a file is not referenced from [`IndexPart`], it's not part of the remote storage state.
      53              : //!
      54              : //! Having the `IndexPart` also avoids expensive and slow `S3 list` commands.
      55              : //!
      56              : //! # Consistency
      57              : //!
      58              : //! To have a consistent remote structure, it's important that uploads and
      59              : //! deletions are performed in the right order. For example, the index file
      60              : //! contains a list of layer files, so it must not be uploaded until all the
      61              : //! layer files that are in its list have been successfully uploaded.
      62              : //!
      63              : //! The contract between client and its user is that the user is responsible of
      64              : //! scheduling operations in an order that keeps the remote consistent as
      65              : //! described above.
      66              : //!
      67              : //! From the user's perspective, the operations are executed sequentially.
      68              : //! Internally, the client knows which operations can be performed in parallel,
      69              : //! and which operations act like a "barrier" that require preceding operations
      70              : //! to finish. The calling code just needs to call the schedule-functions in the
      71              : //! correct order, and the client will parallelize the operations in a way that
      72              : //! is safe. For more details, see `UploadOp::can_bypass`.
      73              : //!
      74              : //! All of this relies on the following invariants:
      75              : //!
      76              : //! - We rely on read-after write consistency in the remote storage.
      77              : //! - Layer files are immutable.
      78              : //!
      79              : //! NB: Pageserver assumes that it has exclusive write access to the tenant in remote
      80              : //! storage. Different tenants can be attached to different pageservers, but if the
      81              : //! same tenant is attached to two pageservers at the same time, they will overwrite
      82              : //! each other's index file updates, and confusion will ensue. There's no interlock or
      83              : //! mechanism to detect that in the pageserver, we rely on the control plane to ensure
      84              : //! that that doesn't happen.
      85              : //!
      86              : //! ## Implementation Note
      87              : //!
      88              : //! The *actual* remote state lags behind the *desired* remote state while
      89              : //! there are in-flight operations.
      90              : //! We keep track of the desired remote state in [`UploadQueueInitialized::dirty`].
      91              : //! It is initialized based on the [`IndexPart`] that was passed during init
      92              : //! and updated with every `schedule_*` function call.
      93              : //! All this is necessary necessary to compute the future [`IndexPart`]s
      94              : //! when scheduling an operation while other operations that also affect the
      95              : //! remote [`IndexPart`] are in flight.
      96              : //!
      97              : //! # Retries & Error Handling
      98              : //!
      99              : //! The client retries operations indefinitely, using exponential back-off.
     100              : //! There is no way to force a retry, i.e., interrupt the back-off.
     101              : //! This could be built easily.
     102              : //!
     103              : //! # Cancellation
     104              : //!
     105              : //! The operations execute as plain [`task_mgr`] tasks, scoped to
     106              : //! the client's tenant and timeline.
     107              : //! Dropping the client will drop queued operations but not executing operations.
     108              : //! These will complete unless the `task_mgr` tasks are cancelled using `task_mgr`
     109              : //! APIs, e.g., during pageserver shutdown, timeline delete, or tenant detach.
     110              : //!
     111              : //! # Completion
     112              : //!
     113              : //! Once an operation has completed, we update [`UploadQueueInitialized::clean`] immediately,
     114              : //! and submit a request through the DeletionQueue to update
     115              : //! [`UploadQueueInitialized::visible_remote_consistent_lsn`] after it has
     116              : //! validated that our generation is not stale.  It is this visible value
     117              : //! that is advertized to safekeepers as a signal that that they can
     118              : //! delete the WAL up to that LSN.
     119              : //!
     120              : //! The [`RemoteTimelineClient::wait_completion`] method can be used to wait
     121              : //! for all pending operations to complete. It does not prevent more
     122              : //! operations from getting scheduled.
     123              : //!
     124              : //! # Crash Consistency
     125              : //!
     126              : //! We do not persist the upload queue state.
     127              : //! If we drop the client, or crash, all unfinished operations are lost.
     128              : //!
     129              : //! To recover, the following steps need to be taken:
     130              : //! - Retrieve the current remote [`IndexPart`]. This gives us a
     131              : //!   consistent remote state, assuming the user scheduled the operations in
     132              : //!   the correct order.
     133              : //! - Initiate upload queue with that [`IndexPart`].
     134              : //! - Reschedule all lost operations by comparing the local filesystem state
     135              : //!   and remote state as per [`IndexPart`]. This is done in
     136              : //!   [`Tenant::timeline_init_and_sync`].
     137              : //!
     138              : //! Note that if we crash during file deletion between the index update
     139              : //! that removes the file from the list of files, and deleting the remote file,
     140              : //! the file is leaked in the remote storage. Similarly, if a new file is created
     141              : //! and uploaded, but the pageserver dies permanently before updating the
     142              : //! remote index file, the new file is leaked in remote storage. We accept and
     143              : //! tolerate that for now.
     144              : //! Note further that we cannot easily fix this by scheduling deletes for every
     145              : //! file that is present only on the remote, because we cannot distinguish the
     146              : //! following two cases:
     147              : //! - (1) We had the file locally, deleted it locally, scheduled a remote delete,
     148              : //!   but crashed before it finished remotely.
     149              : //! - (2) We never had the file locally because we haven't on-demand downloaded
     150              : //!   it yet.
     151              : //!
     152              : //! # Downloads
     153              : //!
     154              : //! In addition to the upload queue, [`RemoteTimelineClient`] has functions for
     155              : //! downloading files from the remote storage. Downloads are performed immediately
     156              : //! against the `RemoteStorage`, independently of the upload queue.
     157              : //!
     158              : //! When we attach a tenant, we perform the following steps:
     159              : //! - create `Tenant` object in `TenantState::Attaching` state
     160              : //! - List timelines that are present in remote storage, and for each:
     161              : //!   - download their remote [`IndexPart`]s
     162              : //!   - create `Timeline` struct and a `RemoteTimelineClient`
     163              : //!   - initialize the client's upload queue with its `IndexPart`
     164              : //!   - schedule uploads for layers that are only present locally.
     165              : //! - After the above is done for each timeline, open the tenant for business by
     166              : //!   transitioning it from `TenantState::Attaching` to `TenantState::Active` state.
     167              : //!   This starts the timelines' WAL-receivers and the tenant's GC & Compaction loops.
     168              : //!
     169              : //! # Operating Without Remote Storage
     170              : //!
     171              : //! If no remote storage configuration is provided, the [`RemoteTimelineClient`] is
     172              : //! not created and the uploads are skipped.
     173              : //!
     174              : //! [`Tenant::timeline_init_and_sync`]: super::Tenant::timeline_init_and_sync
     175              : //! [`Timeline::load_layer_map`]: super::Timeline::load_layer_map
     176              : 
     177              : pub(crate) mod download;
     178              : pub mod index;
     179              : pub mod manifest;
     180              : pub(crate) mod upload;
     181              : 
     182              : use std::collections::{HashMap, HashSet, VecDeque};
     183              : use std::ops::DerefMut;
     184              : use std::sync::atomic::{AtomicU32, Ordering};
     185              : use std::sync::{Arc, Mutex, OnceLock};
     186              : use std::time::Duration;
     187              : 
     188              : use anyhow::Context;
     189              : use camino::Utf8Path;
     190              : use chrono::{NaiveDateTime, Utc};
     191              : pub(crate) use download::{
     192              :     download_index_part, download_initdb_tar_zst, download_tenant_manifest, is_temp_download_file,
     193              :     list_remote_tenant_shards, list_remote_timelines,
     194              : };
     195              : use index::GcCompactionState;
     196              : pub(crate) use index::LayerFileMetadata;
     197              : use pageserver_api::models::{RelSizeMigration, TimelineArchivalState};
     198              : use pageserver_api::shard::{ShardIndex, TenantShardId};
     199              : use regex::Regex;
     200              : use remote_storage::{
     201              :     DownloadError, GenericRemoteStorage, ListingMode, RemotePath, TimeoutOrCancel,
     202              : };
     203              : use scopeguard::ScopeGuard;
     204              : use tokio_util::sync::CancellationToken;
     205              : use tracing::{Instrument, debug, error, info, info_span, instrument, warn};
     206              : pub(crate) use upload::upload_initdb_dir;
     207              : use utils::backoff::{
     208              :     self, DEFAULT_BASE_BACKOFF_SECONDS, DEFAULT_MAX_BACKOFF_SECONDS, exponential_backoff,
     209              : };
     210              : use utils::id::{TenantId, TimelineId};
     211              : use utils::lsn::Lsn;
     212              : use utils::pausable_failpoint;
     213              : use utils::shard::ShardNumber;
     214              : 
     215              : use self::index::IndexPart;
     216              : use super::config::AttachedLocationConfig;
     217              : use super::metadata::MetadataUpdate;
     218              : use super::storage_layer::{Layer, LayerName, ResidentLayer};
     219              : use super::timeline::import_pgdata;
     220              : use super::upload_queue::{NotInitialized, SetDeletedFlagProgress};
     221              : use super::{DeleteTimelineError, Generation};
     222              : use crate::config::PageServerConf;
     223              : use crate::context::RequestContext;
     224              : use crate::deletion_queue::{DeletionQueueClient, DeletionQueueError};
     225              : use crate::metrics::{
     226              :     MeasureRemoteOp, REMOTE_ONDEMAND_DOWNLOADED_BYTES, REMOTE_ONDEMAND_DOWNLOADED_LAYERS,
     227              :     RemoteOpFileKind, RemoteOpKind, RemoteTimelineClientMetrics,
     228              :     RemoteTimelineClientMetricsCallTrackSize,
     229              : };
     230              : use crate::task_mgr::{BACKGROUND_RUNTIME, TaskKind, shutdown_token};
     231              : use crate::tenant::metadata::TimelineMetadata;
     232              : use crate::tenant::remote_timeline_client::download::download_retry;
     233              : use crate::tenant::storage_layer::AsLayerDesc;
     234              : use crate::tenant::upload_queue::{
     235              :     Delete, OpType, UploadOp, UploadQueue, UploadQueueInitialized, UploadQueueStopped,
     236              :     UploadQueueStoppedDeletable, UploadTask,
     237              : };
     238              : use crate::tenant::{TIMELINES_SEGMENT_NAME, debug_assert_current_span_has_tenant_and_timeline_id};
     239              : use crate::{TENANT_HEATMAP_BASENAME, task_mgr};
     240              : 
     241              : // Occasional network issues and such can cause remote operations to fail, and
     242              : // that's expected. If a download fails, we log it at info-level, and retry.
     243              : // But after FAILED_DOWNLOAD_WARN_THRESHOLD retries, we start to log it at WARN
     244              : // level instead, as repeated failures can mean a more serious problem. If it
     245              : // fails more than FAILED_DOWNLOAD_RETRIES times, we give up
     246              : pub(crate) const FAILED_DOWNLOAD_WARN_THRESHOLD: u32 = 3;
     247              : pub(crate) const FAILED_REMOTE_OP_RETRIES: u32 = 10;
     248              : 
     249              : // Similarly log failed uploads and deletions at WARN level, after this many
     250              : // retries. Uploads and deletions are retried forever, though.
     251              : pub(crate) const FAILED_UPLOAD_WARN_THRESHOLD: u32 = 3;
     252              : 
     253              : pub(crate) const INITDB_PATH: &str = "initdb.tar.zst";
     254              : 
     255              : pub(crate) const INITDB_PRESERVED_PATH: &str = "initdb-preserved.tar.zst";
     256              : 
     257              : /// Default buffer size when interfacing with [`tokio::fs::File`].
     258              : pub(crate) const BUFFER_SIZE: usize = 32 * 1024;
     259              : 
     260              : /// Doing non-essential flushes of deletion queue is subject to this timeout, after
     261              : /// which we warn and skip.
     262              : const DELETION_QUEUE_FLUSH_TIMEOUT: Duration = Duration::from_secs(10);
     263              : 
     264              : pub enum MaybeDeletedIndexPart {
     265              :     IndexPart(IndexPart),
     266              :     Deleted(IndexPart),
     267              : }
     268              : 
     269              : #[derive(Debug, thiserror::Error)]
     270              : pub enum PersistIndexPartWithDeletedFlagError {
     271              :     #[error("another task is already setting the deleted_flag, started at {0:?}")]
     272              :     AlreadyInProgress(NaiveDateTime),
     273              :     #[error("the deleted_flag was already set, value is {0:?}")]
     274              :     AlreadyDeleted(NaiveDateTime),
     275              :     #[error(transparent)]
     276              :     Other(#[from] anyhow::Error),
     277              : }
     278              : 
     279              : #[derive(Debug, thiserror::Error)]
     280              : pub enum WaitCompletionError {
     281              :     #[error(transparent)]
     282              :     NotInitialized(NotInitialized),
     283              :     #[error("wait_completion aborted because upload queue was stopped")]
     284              :     UploadQueueShutDownOrStopped,
     285              : }
     286              : 
     287              : #[derive(Debug, thiserror::Error)]
     288              : #[error("Upload queue either in unexpected state or hasn't downloaded manifest yet")]
     289              : pub struct UploadQueueNotReadyError;
     290              : 
     291              : #[derive(Debug, thiserror::Error)]
     292              : pub enum ShutdownIfArchivedError {
     293              :     #[error(transparent)]
     294              :     NotInitialized(NotInitialized),
     295              :     #[error("timeline is not archived")]
     296              :     NotArchived,
     297              : }
     298              : 
     299              : /// Behavioral modes that enable seamless live migration.
     300              : ///
     301              : /// See docs/rfcs/028-pageserver-migration.md to understand how these fit in.
     302              : struct RemoteTimelineClientConfig {
     303              :     /// If this is false, then update to remote_consistent_lsn are dropped rather
     304              :     /// than being submitted to DeletionQueue for validation.  This behavior is
     305              :     /// used when a tenant attachment is known to have a stale generation number,
     306              :     /// such that validation attempts will always fail.  This is not necessary
     307              :     /// for correctness, but avoids spamming error statistics with failed validations
     308              :     /// when doing migrations of tenants.
     309              :     process_remote_consistent_lsn_updates: bool,
     310              : 
     311              :     /// If this is true, then object deletions are held in a buffer in RemoteTimelineClient
     312              :     /// rather than being submitted to the DeletionQueue.  This behavior is used when a tenant
     313              :     /// is known to be multi-attached, in order to avoid disrupting other attached tenants
     314              :     /// whose generations' metadata refers to the deleted objects.
     315              :     block_deletions: bool,
     316              : }
     317              : 
     318              : /// RemoteTimelineClientConfig's state is entirely driven by LocationConf, but we do
     319              : /// not carry the entire LocationConf structure: it's much more than we need.  The From
     320              : /// impl extracts the subset of the LocationConf that is interesting to RemoteTimelineClient.
     321              : impl From<&AttachedLocationConfig> for RemoteTimelineClientConfig {
     322          924 :     fn from(lc: &AttachedLocationConfig) -> Self {
     323          924 :         Self {
     324          924 :             block_deletions: !lc.may_delete_layers_hint(),
     325          924 :             process_remote_consistent_lsn_updates: lc.may_upload_layers_hint(),
     326          924 :         }
     327          924 :     }
     328              : }
     329              : 
     330              : /// A client for accessing a timeline's data in remote storage.
     331              : ///
     332              : /// This takes care of managing the number of connections, and balancing them
     333              : /// across tenants. This also handles retries of failed uploads.
     334              : ///
     335              : /// Upload and delete requests are ordered so that before a deletion is
     336              : /// performed, we wait for all preceding uploads to finish. This ensures sure
     337              : /// that if you perform a compaction operation that reshuffles data in layer
     338              : /// files, we don't have a transient state where the old files have already been
     339              : /// deleted, but new files have not yet been uploaded.
     340              : ///
     341              : /// Similarly, this enforces an order between index-file uploads, and layer
     342              : /// uploads.  Before an index-file upload is performed, all preceding layer
     343              : /// uploads must be finished.
     344              : ///
     345              : /// This also maintains a list of remote files, and automatically includes that
     346              : /// in the index part file, whenever timeline metadata is uploaded.
     347              : ///
     348              : /// Downloads are not queued, they are performed immediately.
     349              : pub(crate) struct RemoteTimelineClient {
     350              :     conf: &'static PageServerConf,
     351              : 
     352              :     runtime: tokio::runtime::Handle,
     353              : 
     354              :     tenant_shard_id: TenantShardId,
     355              :     timeline_id: TimelineId,
     356              :     generation: Generation,
     357              : 
     358              :     upload_queue: Mutex<UploadQueue>,
     359              : 
     360              :     pub(crate) metrics: Arc<RemoteTimelineClientMetrics>,
     361              : 
     362              :     storage_impl: GenericRemoteStorage,
     363              : 
     364              :     deletion_queue_client: DeletionQueueClient,
     365              : 
     366              :     /// Subset of tenant configuration used to control upload behaviors during migrations
     367              :     config: std::sync::RwLock<RemoteTimelineClientConfig>,
     368              : 
     369              :     cancel: CancellationToken,
     370              : }
     371              : 
     372              : impl Drop for RemoteTimelineClient {
     373           40 :     fn drop(&mut self) {
     374           40 :         debug!("dropping RemoteTimelineClient");
     375           40 :     }
     376              : }
     377              : 
     378              : impl RemoteTimelineClient {
     379              :     ///
     380              :     /// Create a remote storage client for given timeline
     381              :     ///
     382              :     /// Note: the caller must initialize the upload queue before any uploads can be scheduled,
     383              :     /// by calling init_upload_queue.
     384              :     ///
     385          904 :     pub(crate) fn new(
     386          904 :         remote_storage: GenericRemoteStorage,
     387          904 :         deletion_queue_client: DeletionQueueClient,
     388          904 :         conf: &'static PageServerConf,
     389          904 :         tenant_shard_id: TenantShardId,
     390          904 :         timeline_id: TimelineId,
     391          904 :         generation: Generation,
     392          904 :         location_conf: &AttachedLocationConfig,
     393          904 :     ) -> RemoteTimelineClient {
     394          904 :         RemoteTimelineClient {
     395          904 :             conf,
     396          904 :             runtime: if cfg!(test) {
     397              :                 // remote_timeline_client.rs tests rely on current-thread runtime
     398          904 :                 tokio::runtime::Handle::current()
     399              :             } else {
     400            0 :                 BACKGROUND_RUNTIME.handle().clone()
     401              :             },
     402          904 :             tenant_shard_id,
     403          904 :             timeline_id,
     404          904 :             generation,
     405          904 :             storage_impl: remote_storage,
     406          904 :             deletion_queue_client,
     407          904 :             upload_queue: Mutex::new(UploadQueue::Uninitialized),
     408          904 :             metrics: Arc::new(RemoteTimelineClientMetrics::new(
     409          904 :                 &tenant_shard_id,
     410          904 :                 &timeline_id,
     411          904 :             )),
     412          904 :             config: std::sync::RwLock::new(RemoteTimelineClientConfig::from(location_conf)),
     413          904 :             cancel: CancellationToken::new(),
     414          904 :         }
     415          904 :     }
     416              : 
     417              :     /// Initialize the upload queue for a remote storage that already received
     418              :     /// an index file upload, i.e., it's not empty.
     419              :     /// The given `index_part` must be the one on the remote.
     420           12 :     pub fn init_upload_queue(&self, index_part: &IndexPart) -> anyhow::Result<()> {
     421           12 :         // Set the maximum number of inprogress tasks to the remote storage concurrency. There's
     422           12 :         // certainly no point in starting more upload tasks than this.
     423           12 :         let inprogress_limit = self
     424           12 :             .conf
     425           12 :             .remote_storage_config
     426           12 :             .as_ref()
     427           12 :             .map_or(0, |r| r.concurrency_limit());
     428           12 :         let mut upload_queue = self.upload_queue.lock().unwrap();
     429           12 :         upload_queue.initialize_with_current_remote_index_part(index_part, inprogress_limit)?;
     430           12 :         self.update_remote_physical_size_gauge(Some(index_part));
     431           12 :         info!(
     432            0 :             "initialized upload queue from remote index with {} layer files",
     433            0 :             index_part.layer_metadata.len()
     434              :         );
     435           12 :         Ok(())
     436           12 :     }
     437              : 
     438              :     /// Initialize the upload queue for the case where the remote storage is empty,
     439              :     /// i.e., it doesn't have an `IndexPart`.
     440          892 :     pub fn init_upload_queue_for_empty_remote(
     441          892 :         &self,
     442          892 :         local_metadata: &TimelineMetadata,
     443          892 :     ) -> anyhow::Result<()> {
     444          892 :         // Set the maximum number of inprogress tasks to the remote storage concurrency. There's
     445          892 :         // certainly no point in starting more upload tasks than this.
     446          892 :         let inprogress_limit = self
     447          892 :             .conf
     448          892 :             .remote_storage_config
     449          892 :             .as_ref()
     450          892 :             .map_or(0, |r| r.concurrency_limit());
     451          892 :         let mut upload_queue = self.upload_queue.lock().unwrap();
     452          892 :         upload_queue.initialize_empty_remote(local_metadata, inprogress_limit)?;
     453          892 :         self.update_remote_physical_size_gauge(None);
     454          892 :         info!("initialized upload queue as empty");
     455          892 :         Ok(())
     456          892 :     }
     457              : 
     458              :     /// Initialize the queue in stopped state. Used in startup path
     459              :     /// to continue deletion operation interrupted by pageserver crash or restart.
     460            0 :     pub fn init_upload_queue_stopped_to_continue_deletion(
     461            0 :         &self,
     462            0 :         index_part: &IndexPart,
     463            0 :     ) -> anyhow::Result<()> {
     464              :         // FIXME: consider newtype for DeletedIndexPart.
     465            0 :         let deleted_at = index_part.deleted_at.ok_or(anyhow::anyhow!(
     466            0 :             "bug: it is responsibility of the caller to provide index part from MaybeDeletedIndexPart::Deleted"
     467            0 :         ))?;
     468            0 :         let inprogress_limit = self
     469            0 :             .conf
     470            0 :             .remote_storage_config
     471            0 :             .as_ref()
     472            0 :             .map_or(0, |r| r.concurrency_limit());
     473            0 : 
     474            0 :         let mut upload_queue = self.upload_queue.lock().unwrap();
     475            0 :         upload_queue.initialize_with_current_remote_index_part(index_part, inprogress_limit)?;
     476            0 :         self.update_remote_physical_size_gauge(Some(index_part));
     477            0 :         self.stop_impl(&mut upload_queue);
     478            0 : 
     479            0 :         upload_queue
     480            0 :             .stopped_mut()
     481            0 :             .expect("stopped above")
     482            0 :             .deleted_at = SetDeletedFlagProgress::Successful(deleted_at);
     483            0 : 
     484            0 :         Ok(())
     485            0 :     }
     486              : 
     487              :     /// Notify this client of a change to its parent tenant's config, as this may cause us to
     488              :     /// take action (unblocking deletions when transitioning from AttachedMulti to AttachedSingle)
     489            0 :     pub(super) fn update_config(&self, location_conf: &AttachedLocationConfig) {
     490            0 :         let new_conf = RemoteTimelineClientConfig::from(location_conf);
     491            0 :         let unblocked = !new_conf.block_deletions;
     492            0 : 
     493            0 :         // Update config before draining deletions, so that we don't race with more being
     494            0 :         // inserted.  This can result in deletions happening our of order, but that does not
     495            0 :         // violate any invariants: deletions only need to be ordered relative to upload of the index
     496            0 :         // that dereferences the deleted objects, and we are not changing that order.
     497            0 :         *self.config.write().unwrap() = new_conf;
     498            0 : 
     499            0 :         if unblocked {
     500              :             // If we may now delete layers, drain any that were blocked in our old
     501              :             // configuration state
     502            0 :             let mut queue_locked = self.upload_queue.lock().unwrap();
     503              : 
     504            0 :             if let Ok(queue) = queue_locked.initialized_mut() {
     505            0 :                 let blocked_deletions = std::mem::take(&mut queue.blocked_deletions);
     506            0 :                 for d in blocked_deletions {
     507            0 :                     if let Err(e) = self.deletion_queue_client.push_layers(
     508            0 :                         self.tenant_shard_id,
     509            0 :                         self.timeline_id,
     510            0 :                         self.generation,
     511            0 :                         d.layers,
     512            0 :                     ) {
     513              :                         // This could happen if the pageserver is shut down while a tenant
     514              :                         // is transitioning from a deletion-blocked state: we will leak some
     515              :                         // S3 objects in this case.
     516            0 :                         warn!("Failed to drain blocked deletions: {}", e);
     517            0 :                         break;
     518            0 :                     }
     519              :                 }
     520            0 :             }
     521            0 :         }
     522            0 :     }
     523              : 
     524              :     /// Returns `None` if nothing is yet uplodaded, `Some(disk_consistent_lsn)` otherwise.
     525            0 :     pub fn remote_consistent_lsn_projected(&self) -> Option<Lsn> {
     526            0 :         match &mut *self.upload_queue.lock().unwrap() {
     527            0 :             UploadQueue::Uninitialized => None,
     528            0 :             UploadQueue::Initialized(q) => q.get_last_remote_consistent_lsn_projected(),
     529            0 :             UploadQueue::Stopped(UploadQueueStopped::Uninitialized) => None,
     530            0 :             UploadQueue::Stopped(UploadQueueStopped::Deletable(q)) => q
     531            0 :                 .upload_queue_for_deletion
     532            0 :                 .get_last_remote_consistent_lsn_projected(),
     533              :         }
     534            0 :     }
     535              : 
     536            0 :     pub fn remote_consistent_lsn_visible(&self) -> Option<Lsn> {
     537            0 :         match &mut *self.upload_queue.lock().unwrap() {
     538            0 :             UploadQueue::Uninitialized => None,
     539            0 :             UploadQueue::Initialized(q) => Some(q.get_last_remote_consistent_lsn_visible()),
     540            0 :             UploadQueue::Stopped(UploadQueueStopped::Uninitialized) => None,
     541            0 :             UploadQueue::Stopped(UploadQueueStopped::Deletable(q)) => Some(
     542            0 :                 q.upload_queue_for_deletion
     543            0 :                     .get_last_remote_consistent_lsn_visible(),
     544            0 :             ),
     545              :         }
     546            0 :     }
     547              : 
     548              :     /// Returns true if this timeline was previously detached at this Lsn and the remote timeline
     549              :     /// client is currently initialized.
     550            0 :     pub(crate) fn is_previous_ancestor_lsn(&self, lsn: Lsn) -> bool {
     551            0 :         self.upload_queue
     552            0 :             .lock()
     553            0 :             .unwrap()
     554            0 :             .initialized_mut()
     555            0 :             .map(|uq| uq.clean.0.lineage.is_previous_ancestor_lsn(lsn))
     556            0 :             .unwrap_or(false)
     557            0 :     }
     558              : 
     559              :     /// Returns whether the timeline is archived.
     560              :     /// Return None if the remote index_part hasn't been downloaded yet.
     561            0 :     pub(crate) fn is_archived(&self) -> Option<bool> {
     562            0 :         self.upload_queue
     563            0 :             .lock()
     564            0 :             .unwrap()
     565            0 :             .initialized_mut()
     566            0 :             .map(|q| q.clean.0.archived_at.is_some())
     567            0 :             .ok()
     568            0 :     }
     569              : 
     570              :     /// Returns `Ok(Some(timestamp))` if the timeline has been archived, `Ok(None)` if the timeline hasn't been archived.
     571              :     ///
     572              :     /// Return Err(_) if the remote index_part hasn't been downloaded yet, or the timeline hasn't been stopped yet.
     573            4 :     pub(crate) fn archived_at_stopped_queue(
     574            4 :         &self,
     575            4 :     ) -> Result<Option<NaiveDateTime>, UploadQueueNotReadyError> {
     576            4 :         self.upload_queue
     577            4 :             .lock()
     578            4 :             .unwrap()
     579            4 :             .stopped_mut()
     580            4 :             .map(|q| q.upload_queue_for_deletion.clean.0.archived_at)
     581            4 :             .map_err(|_| UploadQueueNotReadyError)
     582            4 :     }
     583              : 
     584         3887 :     fn update_remote_physical_size_gauge(&self, current_remote_index_part: Option<&IndexPart>) {
     585         3887 :         let size: u64 = if let Some(current_remote_index_part) = current_remote_index_part {
     586         2995 :             current_remote_index_part
     587         2995 :                 .layer_metadata
     588         2995 :                 .values()
     589        35853 :                 .map(|ilmd| ilmd.file_size)
     590         2995 :                 .sum()
     591              :         } else {
     592          892 :             0
     593              :         };
     594         3887 :         self.metrics.remote_physical_size_gauge.set(size);
     595         3887 :     }
     596              : 
     597            4 :     pub fn get_remote_physical_size(&self) -> u64 {
     598            4 :         self.metrics.remote_physical_size_gauge.get()
     599            4 :     }
     600              : 
     601              :     //
     602              :     // Download operations.
     603              :     //
     604              :     // These don't use the per-timeline queue. They do use the global semaphore in
     605              :     // S3Bucket, to limit the total number of concurrent operations, though.
     606              :     //
     607              : 
     608              :     /// Download index file
     609           40 :     pub async fn download_index_file(
     610           40 :         &self,
     611           40 :         cancel: &CancellationToken,
     612           40 :     ) -> Result<MaybeDeletedIndexPart, DownloadError> {
     613           40 :         let _unfinished_gauge_guard = self.metrics.call_begin(
     614           40 :             &RemoteOpFileKind::Index,
     615           40 :             &RemoteOpKind::Download,
     616           40 :             crate::metrics::RemoteTimelineClientMetricsCallTrackSize::DontTrackSize {
     617           40 :                 reason: "no need for a downloads gauge",
     618           40 :             },
     619           40 :         );
     620              : 
     621           40 :         let (index_part, index_generation, index_last_modified) = download::download_index_part(
     622           40 :             &self.storage_impl,
     623           40 :             &self.tenant_shard_id,
     624           40 :             &self.timeline_id,
     625           40 :             self.generation,
     626           40 :             cancel,
     627           40 :         )
     628           40 :         .measure_remote_op(
     629           40 :             RemoteOpFileKind::Index,
     630           40 :             RemoteOpKind::Download,
     631           40 :             Arc::clone(&self.metrics),
     632           40 :         )
     633           40 :         .await?;
     634              : 
     635              :         // Defense in depth: monotonicity of generation numbers is an important correctness guarantee, so when we see a very
     636              :         // old index, we do extra checks in case this is the result of backward time-travel of the generation number (e.g.
     637              :         // in case of a bug in the service that issues generation numbers). Indices are allowed to be old, but we expect that
     638              :         // when we load an old index we are loading the _latest_ index: if we are asked to load an old index and there is
     639              :         // also a newer index available, that is surprising.
     640              :         const INDEX_AGE_CHECKS_THRESHOLD: Duration = Duration::from_secs(14 * 24 * 3600);
     641           40 :         let index_age = index_last_modified.elapsed().unwrap_or_else(|e| {
     642            0 :             if e.duration() > Duration::from_secs(5) {
     643              :                 // We only warn if the S3 clock and our local clock are >5s out: because this is a low resolution
     644              :                 // timestamp, it is common to be out by at least 1 second.
     645            0 :                 tracing::warn!("Index has modification time in the future: {e}");
     646            0 :             }
     647            0 :             Duration::ZERO
     648           40 :         });
     649           40 :         if index_age > INDEX_AGE_CHECKS_THRESHOLD {
     650            0 :             tracing::info!(
     651              :                 ?index_generation,
     652            0 :                 age = index_age.as_secs_f64(),
     653            0 :                 "Loaded an old index, checking for other indices..."
     654              :             );
     655              : 
     656              :             // Find the highest-generation index
     657            0 :             let (_latest_index_part, latest_index_generation, latest_index_mtime) =
     658            0 :                 download::download_index_part(
     659            0 :                     &self.storage_impl,
     660            0 :                     &self.tenant_shard_id,
     661            0 :                     &self.timeline_id,
     662            0 :                     Generation::MAX,
     663            0 :                     cancel,
     664            0 :                 )
     665            0 :                 .await?;
     666              : 
     667            0 :             if latest_index_generation > index_generation {
     668              :                 // Unexpected!  Why are we loading such an old index if a more recent one exists?
     669              :                 // We will refuse to proceed, as there is no reasonable scenario where this should happen, but
     670              :                 // there _is_ a clear bug/corruption scenario where it would happen (controller sets the generation
     671              :                 // backwards).
     672            0 :                 tracing::error!(
     673              :                     ?index_generation,
     674              :                     ?latest_index_generation,
     675              :                     ?latest_index_mtime,
     676            0 :                     "Found a newer index while loading an old one"
     677              :                 );
     678            0 :                 return Err(DownloadError::Fatal(
     679            0 :                     "Index age exceeds threshold and a newer index exists".into(),
     680            0 :                 ));
     681            0 :             }
     682           40 :         }
     683              : 
     684           40 :         if index_part.deleted_at.is_some() {
     685            0 :             Ok(MaybeDeletedIndexPart::Deleted(index_part))
     686              :         } else {
     687           40 :             Ok(MaybeDeletedIndexPart::IndexPart(index_part))
     688              :         }
     689           40 :     }
     690              : 
     691              :     /// Download a (layer) file from `path`, into local filesystem.
     692              :     ///
     693              :     /// 'layer_metadata' is the metadata from the remote index file.
     694              :     ///
     695              :     /// On success, returns the size of the downloaded file.
     696           28 :     pub async fn download_layer_file(
     697           28 :         &self,
     698           28 :         layer_file_name: &LayerName,
     699           28 :         layer_metadata: &LayerFileMetadata,
     700           28 :         local_path: &Utf8Path,
     701           28 :         gate: &utils::sync::gate::Gate,
     702           28 :         cancel: &CancellationToken,
     703           28 :         ctx: &RequestContext,
     704           28 :     ) -> Result<u64, DownloadError> {
     705           28 :         let downloaded_size = {
     706           28 :             let _unfinished_gauge_guard = self.metrics.call_begin(
     707           28 :                 &RemoteOpFileKind::Layer,
     708           28 :                 &RemoteOpKind::Download,
     709           28 :                 crate::metrics::RemoteTimelineClientMetricsCallTrackSize::DontTrackSize {
     710           28 :                     reason: "no need for a downloads gauge",
     711           28 :                 },
     712           28 :             );
     713           28 :             download::download_layer_file(
     714           28 :                 self.conf,
     715           28 :                 &self.storage_impl,
     716           28 :                 self.tenant_shard_id,
     717           28 :                 self.timeline_id,
     718           28 :                 layer_file_name,
     719           28 :                 layer_metadata,
     720           28 :                 local_path,
     721           28 :                 gate,
     722           28 :                 cancel,
     723           28 :                 ctx,
     724           28 :             )
     725           28 :             .measure_remote_op(
     726           28 :                 RemoteOpFileKind::Layer,
     727           28 :                 RemoteOpKind::Download,
     728           28 :                 Arc::clone(&self.metrics),
     729           28 :             )
     730           28 :             .await?
     731              :         };
     732              : 
     733           28 :         REMOTE_ONDEMAND_DOWNLOADED_LAYERS.inc();
     734           28 :         REMOTE_ONDEMAND_DOWNLOADED_BYTES.inc_by(downloaded_size);
     735           28 : 
     736           28 :         Ok(downloaded_size)
     737           28 :     }
     738              : 
     739              :     //
     740              :     // Upload operations.
     741              :     //
     742              : 
     743              :     /// Launch an index-file upload operation in the background, with
     744              :     /// fully updated metadata.
     745              :     ///
     746              :     /// This should only be used to upload initial metadata to remote storage.
     747              :     ///
     748              :     /// The upload will be added to the queue immediately, but it
     749              :     /// won't be performed until all previously scheduled layer file
     750              :     /// upload operations have completed successfully.  This is to
     751              :     /// ensure that when the index file claims that layers X, Y and Z
     752              :     /// exist in remote storage, they really do. To wait for the upload
     753              :     /// to complete, use `wait_completion`.
     754              :     ///
     755              :     /// If there were any changes to the list of files, i.e. if any
     756              :     /// layer file uploads were scheduled, since the last index file
     757              :     /// upload, those will be included too.
     758          460 :     pub fn schedule_index_upload_for_full_metadata_update(
     759          460 :         self: &Arc<Self>,
     760          460 :         metadata: &TimelineMetadata,
     761          460 :     ) -> anyhow::Result<()> {
     762          460 :         let mut guard = self.upload_queue.lock().unwrap();
     763          460 :         let upload_queue = guard.initialized_mut()?;
     764              : 
     765              :         // As documented in the struct definition, it's ok for latest_metadata to be
     766              :         // ahead of what's _actually_ on the remote during index upload.
     767          460 :         upload_queue.dirty.metadata = metadata.clone();
     768          460 : 
     769          460 :         self.schedule_index_upload(upload_queue);
     770          460 : 
     771          460 :         Ok(())
     772          460 :     }
     773              : 
     774              :     /// Launch an index-file upload operation in the background, with only parts of the metadata
     775              :     /// updated.
     776              :     ///
     777              :     /// This is the regular way of updating metadata on layer flushes or Gc.
     778              :     ///
     779              :     /// Using this lighter update mechanism allows for reparenting and detaching without changes to
     780              :     /// `index_part.json`, while being more clear on what values update regularly.
     781         2456 :     pub(crate) fn schedule_index_upload_for_metadata_update(
     782         2456 :         self: &Arc<Self>,
     783         2456 :         update: &MetadataUpdate,
     784         2456 :     ) -> anyhow::Result<()> {
     785         2456 :         let mut guard = self.upload_queue.lock().unwrap();
     786         2456 :         let upload_queue = guard.initialized_mut()?;
     787              : 
     788         2456 :         upload_queue.dirty.metadata.apply(update);
     789         2456 : 
     790         2456 :         // Defense in depth: if we somehow generated invalid metadata, do not persist it.
     791         2456 :         upload_queue
     792         2456 :             .dirty
     793         2456 :             .validate()
     794         2456 :             .map_err(|e| anyhow::anyhow!(e))?;
     795              : 
     796         2456 :         self.schedule_index_upload(upload_queue);
     797         2456 : 
     798         2456 :         Ok(())
     799         2456 :     }
     800              : 
     801              :     /// Launch an index-file upload operation in the background, with only the `archived_at` field updated.
     802              :     ///
     803              :     /// Returns whether it is required to wait for the queue to be empty to ensure that the change is uploaded,
     804              :     /// so either if the change is already sitting in the queue, but not commited yet, or the change has not
     805              :     /// been in the queue yet.
     806            4 :     pub(crate) fn schedule_index_upload_for_timeline_archival_state(
     807            4 :         self: &Arc<Self>,
     808            4 :         state: TimelineArchivalState,
     809            4 :     ) -> anyhow::Result<bool> {
     810            4 :         let mut guard = self.upload_queue.lock().unwrap();
     811            4 :         let upload_queue = guard.initialized_mut()?;
     812              : 
     813              :         /// Returns Some(_) if a change is needed, and Some(true) if it's a
     814              :         /// change needed to set archived_at.
     815            8 :         fn need_change(
     816            8 :             archived_at: &Option<NaiveDateTime>,
     817            8 :             state: TimelineArchivalState,
     818            8 :         ) -> Option<bool> {
     819            8 :             match (archived_at, state) {
     820              :                 (Some(_), TimelineArchivalState::Archived)
     821              :                 | (None, TimelineArchivalState::Unarchived) => {
     822              :                     // Nothing to do
     823            0 :                     tracing::info!("intended state matches present state");
     824            0 :                     None
     825              :                 }
     826            8 :                 (None, TimelineArchivalState::Archived) => Some(true),
     827            0 :                 (Some(_), TimelineArchivalState::Unarchived) => Some(false),
     828              :             }
     829            8 :         }
     830            4 :         let need_upload_scheduled = need_change(&upload_queue.dirty.archived_at, state);
     831              : 
     832            4 :         if let Some(archived_at_set) = need_upload_scheduled {
     833            4 :             let intended_archived_at = archived_at_set.then(|| Utc::now().naive_utc());
     834            4 :             upload_queue.dirty.archived_at = intended_archived_at;
     835            4 :             self.schedule_index_upload(upload_queue);
     836            4 :         }
     837              : 
     838            4 :         let need_wait = need_change(&upload_queue.clean.0.archived_at, state).is_some();
     839            4 :         Ok(need_wait)
     840            4 :     }
     841              : 
     842              :     /// Shuts the timeline client down, but only if the timeline is archived.
     843              :     ///
     844              :     /// This function and [`Self::schedule_index_upload_for_timeline_archival_state`] use the
     845              :     /// same lock to prevent races between unarchival and offloading: unarchival requires the
     846              :     /// upload queue to be initialized, and leaves behind an upload queue where either dirty
     847              :     /// or clean has archived_at of `None`. offloading leaves behind an uninitialized upload
     848              :     /// queue.
     849            4 :     pub(crate) async fn shutdown_if_archived(
     850            4 :         self: &Arc<Self>,
     851            4 :     ) -> Result<(), ShutdownIfArchivedError> {
     852            4 :         {
     853            4 :             let mut guard = self.upload_queue.lock().unwrap();
     854            4 :             let upload_queue = guard
     855            4 :                 .initialized_mut()
     856            4 :                 .map_err(ShutdownIfArchivedError::NotInitialized)?;
     857              : 
     858            4 :             match (
     859            4 :                 upload_queue.dirty.archived_at.is_none(),
     860            4 :                 upload_queue.clean.0.archived_at.is_none(),
     861            4 :             ) {
     862              :                 // The expected case: the timeline is archived and we don't want to unarchive
     863            4 :                 (false, false) => {}
     864              :                 (true, false) => {
     865            0 :                     tracing::info!("can't shut down timeline: timeline slated for unarchival");
     866            0 :                     return Err(ShutdownIfArchivedError::NotArchived);
     867              :                 }
     868            0 :                 (dirty_archived, true) => {
     869            0 :                     tracing::info!(%dirty_archived, "can't shut down timeline: timeline not archived in remote storage");
     870            0 :                     return Err(ShutdownIfArchivedError::NotArchived);
     871              :                 }
     872              :             }
     873              : 
     874              :             // Set the shutting_down flag while the guard from the archival check is held.
     875              :             // This prevents a race with unarchival, as initialized_mut will not return
     876              :             // an upload queue from this point.
     877              :             // Also launch the queued tasks like shutdown() does.
     878            4 :             if !upload_queue.shutting_down {
     879            4 :                 upload_queue.shutting_down = true;
     880            4 :                 upload_queue.queued_operations.push_back(UploadOp::Shutdown);
     881            4 :                 // this operation is not counted similar to Barrier
     882            4 :                 self.launch_queued_tasks(upload_queue);
     883            4 :             }
     884              :         }
     885              : 
     886            4 :         self.shutdown().await;
     887              : 
     888            4 :         Ok(())
     889            4 :     }
     890              : 
     891              :     /// Launch an index-file upload operation in the background, setting `import_pgdata` field.
     892            0 :     pub(crate) fn schedule_index_upload_for_import_pgdata_state_update(
     893            0 :         self: &Arc<Self>,
     894            0 :         state: Option<import_pgdata::index_part_format::Root>,
     895            0 :     ) -> anyhow::Result<()> {
     896            0 :         let mut guard = self.upload_queue.lock().unwrap();
     897            0 :         let upload_queue = guard.initialized_mut()?;
     898            0 :         upload_queue.dirty.import_pgdata = state;
     899            0 :         self.schedule_index_upload(upload_queue);
     900            0 :         Ok(())
     901            0 :     }
     902              : 
     903              :     /// Launch an index-file upload operation in the background, setting `gc_compaction_state` field.
     904            0 :     pub(crate) fn schedule_index_upload_for_gc_compaction_state_update(
     905            0 :         self: &Arc<Self>,
     906            0 :         gc_compaction_state: GcCompactionState,
     907            0 :     ) -> anyhow::Result<()> {
     908            0 :         let mut guard = self.upload_queue.lock().unwrap();
     909            0 :         let upload_queue = guard.initialized_mut()?;
     910            0 :         upload_queue.dirty.gc_compaction = Some(gc_compaction_state);
     911            0 :         self.schedule_index_upload(upload_queue);
     912            0 :         Ok(())
     913            0 :     }
     914              : 
     915              :     /// Launch an index-file upload operation in the background, setting `rel_size_v2_status` field.
     916            0 :     pub(crate) fn schedule_index_upload_for_rel_size_v2_status_update(
     917            0 :         self: &Arc<Self>,
     918            0 :         rel_size_v2_status: RelSizeMigration,
     919            0 :     ) -> anyhow::Result<()> {
     920            0 :         let mut guard = self.upload_queue.lock().unwrap();
     921            0 :         let upload_queue = guard.initialized_mut()?;
     922            0 :         upload_queue.dirty.rel_size_migration = Some(rel_size_v2_status);
     923            0 :         // TODO: allow this operation to bypass the validation check because we might upload the index part
     924            0 :         // with no layers but the flag updated. For now, we just modify the index part in memory and the next
     925            0 :         // upload will include the flag.
     926            0 :         // self.schedule_index_upload(upload_queue);
     927            0 :         Ok(())
     928            0 :     }
     929              : 
     930              :     ///
     931              :     /// Launch an index-file upload operation in the background, if necessary.
     932              :     ///
     933              :     /// Use this function to schedule the update of the index file after
     934              :     /// scheduling file uploads or deletions. If no file uploads or deletions
     935              :     /// have been scheduled since the last index file upload, this does
     936              :     /// nothing.
     937              :     ///
     938              :     /// Like schedule_index_upload_for_metadata_update(), this merely adds
     939              :     /// the upload to the upload queue and returns quickly.
     940          740 :     pub fn schedule_index_upload_for_file_changes(self: &Arc<Self>) -> Result<(), NotInitialized> {
     941          740 :         let mut guard = self.upload_queue.lock().unwrap();
     942          740 :         let upload_queue = guard.initialized_mut()?;
     943              : 
     944          740 :         if upload_queue.latest_files_changes_since_metadata_upload_scheduled > 0 {
     945           28 :             self.schedule_index_upload(upload_queue);
     946          712 :         }
     947              : 
     948          740 :         Ok(())
     949          740 :     }
     950              : 
     951              :     /// Launch an index-file upload operation in the background (internal function)
     952         3092 :     fn schedule_index_upload(self: &Arc<Self>, upload_queue: &mut UploadQueueInitialized) {
     953         3092 :         let disk_consistent_lsn = upload_queue.dirty.metadata.disk_consistent_lsn();
     954         3092 :         // fix up the duplicated field
     955         3092 :         upload_queue.dirty.disk_consistent_lsn = disk_consistent_lsn;
     956         3092 : 
     957         3092 :         // make sure it serializes before doing it in perform_upload_task so that it doesn't
     958         3092 :         // look like a retryable error
     959         3092 :         let void = std::io::sink();
     960         3092 :         serde_json::to_writer(void, &upload_queue.dirty).expect("serialize index_part.json");
     961         3092 : 
     962         3092 :         let index_part = &upload_queue.dirty;
     963         3092 : 
     964         3092 :         info!(
     965            0 :             "scheduling metadata upload up to consistent LSN {disk_consistent_lsn} with {} files ({} changed)",
     966            0 :             index_part.layer_metadata.len(),
     967              :             upload_queue.latest_files_changes_since_metadata_upload_scheduled,
     968              :         );
     969              : 
     970         3092 :         let op = UploadOp::UploadMetadata {
     971         3092 :             uploaded: Box::new(index_part.clone()),
     972         3092 :         };
     973         3092 :         self.metric_begin(&op);
     974         3092 :         upload_queue.queued_operations.push_back(op);
     975         3092 :         upload_queue.latest_files_changes_since_metadata_upload_scheduled = 0;
     976         3092 : 
     977         3092 :         // Launch the task immediately, if possible
     978         3092 :         self.launch_queued_tasks(upload_queue);
     979         3092 :     }
     980              : 
     981              :     /// Reparent this timeline to a new parent.
     982              :     ///
     983              :     /// A retryable step of timeline ancestor detach.
     984            0 :     pub(crate) async fn schedule_reparenting_and_wait(
     985            0 :         self: &Arc<Self>,
     986            0 :         new_parent: &TimelineId,
     987            0 :     ) -> anyhow::Result<()> {
     988            0 :         let receiver = {
     989            0 :             let mut guard = self.upload_queue.lock().unwrap();
     990            0 :             let upload_queue = guard.initialized_mut()?;
     991              : 
     992            0 :             let Some(prev) = upload_queue.dirty.metadata.ancestor_timeline() else {
     993            0 :                 return Err(anyhow::anyhow!(
     994            0 :                     "cannot reparent without a current ancestor"
     995            0 :                 ));
     996              :             };
     997              : 
     998            0 :             let uploaded = &upload_queue.clean.0.metadata;
     999            0 : 
    1000            0 :             if uploaded.ancestor_timeline().is_none() && !uploaded.ancestor_lsn().is_valid() {
    1001              :                 // nothing to do
    1002            0 :                 None
    1003              :             } else {
    1004            0 :                 upload_queue.dirty.metadata.reparent(new_parent);
    1005            0 :                 upload_queue.dirty.lineage.record_previous_ancestor(&prev);
    1006            0 : 
    1007            0 :                 self.schedule_index_upload(upload_queue);
    1008            0 : 
    1009            0 :                 Some(self.schedule_barrier0(upload_queue))
    1010              :             }
    1011              :         };
    1012              : 
    1013            0 :         if let Some(receiver) = receiver {
    1014            0 :             Self::wait_completion0(receiver).await?;
    1015            0 :         }
    1016            0 :         Ok(())
    1017            0 :     }
    1018              : 
    1019              :     /// Schedules uploading a new version of `index_part.json` with the given layers added,
    1020              :     /// detaching from ancestor and waits for it to complete.
    1021              :     ///
    1022              :     /// This is used with `Timeline::detach_ancestor` functionality.
    1023            0 :     pub(crate) async fn schedule_adding_existing_layers_to_index_detach_and_wait(
    1024            0 :         self: &Arc<Self>,
    1025            0 :         layers: &[Layer],
    1026            0 :         adopted: (TimelineId, Lsn),
    1027            0 :     ) -> anyhow::Result<()> {
    1028            0 :         let barrier = {
    1029            0 :             let mut guard = self.upload_queue.lock().unwrap();
    1030            0 :             let upload_queue = guard.initialized_mut()?;
    1031              : 
    1032            0 :             if upload_queue.clean.0.lineage.detached_previous_ancestor() == Some(adopted) {
    1033            0 :                 None
    1034              :             } else {
    1035            0 :                 upload_queue.dirty.metadata.detach_from_ancestor(&adopted);
    1036            0 :                 upload_queue.dirty.lineage.record_detaching(&adopted);
    1037              : 
    1038            0 :                 for layer in layers {
    1039            0 :                     let prev = upload_queue
    1040            0 :                         .dirty
    1041            0 :                         .layer_metadata
    1042            0 :                         .insert(layer.layer_desc().layer_name(), layer.metadata());
    1043            0 :                     assert!(prev.is_none(), "copied layer existed already {layer}");
    1044              :                 }
    1045              : 
    1046            0 :                 self.schedule_index_upload(upload_queue);
    1047            0 : 
    1048            0 :                 Some(self.schedule_barrier0(upload_queue))
    1049              :             }
    1050              :         };
    1051              : 
    1052            0 :         if let Some(barrier) = barrier {
    1053            0 :             Self::wait_completion0(barrier).await?;
    1054            0 :         }
    1055            0 :         Ok(())
    1056            0 :     }
    1057              : 
    1058              :     /// Adds a gc blocking reason for this timeline if one does not exist already.
    1059              :     ///
    1060              :     /// A retryable step of timeline detach ancestor.
    1061              :     ///
    1062              :     /// Returns a future which waits until the completion of the upload.
    1063            0 :     pub(crate) fn schedule_insert_gc_block_reason(
    1064            0 :         self: &Arc<Self>,
    1065            0 :         reason: index::GcBlockingReason,
    1066            0 :     ) -> Result<impl std::future::Future<Output = Result<(), WaitCompletionError>>, NotInitialized>
    1067            0 :     {
    1068            0 :         let maybe_barrier = {
    1069            0 :             let mut guard = self.upload_queue.lock().unwrap();
    1070            0 :             let upload_queue = guard.initialized_mut()?;
    1071              : 
    1072            0 :             if let index::GcBlockingReason::DetachAncestor = reason {
    1073            0 :                 if upload_queue.dirty.metadata.ancestor_timeline().is_none() {
    1074            0 :                     drop(guard);
    1075            0 :                     panic!("cannot start detach ancestor if there is nothing to detach from");
    1076            0 :                 }
    1077            0 :             }
    1078              : 
    1079            0 :             let wanted = |x: Option<&index::GcBlocking>| x.is_some_and(|x| x.blocked_by(reason));
    1080              : 
    1081            0 :             let current = upload_queue.dirty.gc_blocking.as_ref();
    1082            0 :             let uploaded = upload_queue.clean.0.gc_blocking.as_ref();
    1083            0 : 
    1084            0 :             match (current, uploaded) {
    1085            0 :                 (x, y) if wanted(x) && wanted(y) => None,
    1086            0 :                 (x, y) if wanted(x) && !wanted(y) => Some(self.schedule_barrier0(upload_queue)),
    1087              :                 // Usual case: !wanted(x) && !wanted(y)
    1088              :                 //
    1089              :                 // Unusual: !wanted(x) && wanted(y) which means we have two processes waiting to
    1090              :                 // turn on and off some reason.
    1091            0 :                 (x, y) => {
    1092            0 :                     if !wanted(x) && wanted(y) {
    1093              :                         // this could be avoided by having external in-memory synchronization, like
    1094              :                         // timeline detach ancestor
    1095            0 :                         warn!(
    1096              :                             ?reason,
    1097              :                             op = "insert",
    1098            0 :                             "unexpected: two racing processes to enable and disable a gc blocking reason"
    1099              :                         );
    1100            0 :                     }
    1101              : 
    1102              :                     // at this point, the metadata must always show that there is a parent
    1103            0 :                     upload_queue.dirty.gc_blocking = current
    1104            0 :                         .map(|x| x.with_reason(reason))
    1105            0 :                         .or_else(|| Some(index::GcBlocking::started_now_for(reason)));
    1106            0 :                     self.schedule_index_upload(upload_queue);
    1107            0 :                     Some(self.schedule_barrier0(upload_queue))
    1108              :                 }
    1109              :             }
    1110              :         };
    1111              : 
    1112            0 :         Ok(async move {
    1113            0 :             if let Some(barrier) = maybe_barrier {
    1114            0 :                 Self::wait_completion0(barrier).await?;
    1115            0 :             }
    1116            0 :             Ok(())
    1117            0 :         })
    1118            0 :     }
    1119              : 
    1120              :     /// Removes a gc blocking reason for this timeline if one exists.
    1121              :     ///
    1122              :     /// A retryable step of timeline detach ancestor.
    1123              :     ///
    1124              :     /// Returns a future which waits until the completion of the upload.
    1125            0 :     pub(crate) fn schedule_remove_gc_block_reason(
    1126            0 :         self: &Arc<Self>,
    1127            0 :         reason: index::GcBlockingReason,
    1128            0 :     ) -> Result<impl std::future::Future<Output = Result<(), WaitCompletionError>>, NotInitialized>
    1129            0 :     {
    1130            0 :         let maybe_barrier = {
    1131            0 :             let mut guard = self.upload_queue.lock().unwrap();
    1132            0 :             let upload_queue = guard.initialized_mut()?;
    1133              : 
    1134            0 :             if let index::GcBlockingReason::DetachAncestor = reason {
    1135            0 :                 if !upload_queue.clean.0.lineage.is_detached_from_ancestor() {
    1136            0 :                     drop(guard);
    1137            0 :                     panic!("cannot complete timeline_ancestor_detach while not detached");
    1138            0 :                 }
    1139            0 :             }
    1140              : 
    1141            0 :             let wanted = |x: Option<&index::GcBlocking>| {
    1142            0 :                 x.is_none() || x.is_some_and(|b| !b.blocked_by(reason))
    1143            0 :             };
    1144              : 
    1145            0 :             let current = upload_queue.dirty.gc_blocking.as_ref();
    1146            0 :             let uploaded = upload_queue.clean.0.gc_blocking.as_ref();
    1147            0 : 
    1148            0 :             match (current, uploaded) {
    1149            0 :                 (x, y) if wanted(x) && wanted(y) => None,
    1150            0 :                 (x, y) if wanted(x) && !wanted(y) => Some(self.schedule_barrier0(upload_queue)),
    1151            0 :                 (x, y) => {
    1152            0 :                     if !wanted(x) && wanted(y) {
    1153            0 :                         warn!(
    1154              :                             ?reason,
    1155              :                             op = "remove",
    1156            0 :                             "unexpected: two racing processes to enable and disable a gc blocking reason (remove)"
    1157              :                         );
    1158            0 :                     }
    1159              : 
    1160            0 :                     upload_queue.dirty.gc_blocking =
    1161            0 :                         current.as_ref().and_then(|x| x.without_reason(reason));
    1162            0 :                     assert!(wanted(upload_queue.dirty.gc_blocking.as_ref()));
    1163            0 :                     self.schedule_index_upload(upload_queue);
    1164            0 :                     Some(self.schedule_barrier0(upload_queue))
    1165              :                 }
    1166              :             }
    1167              :         };
    1168              : 
    1169            0 :         Ok(async move {
    1170            0 :             if let Some(barrier) = maybe_barrier {
    1171            0 :                 Self::wait_completion0(barrier).await?;
    1172            0 :             }
    1173            0 :             Ok(())
    1174            0 :         })
    1175            0 :     }
    1176              : 
    1177              :     /// Launch an upload operation in the background; the file is added to be included in next
    1178              :     /// `index_part.json` upload.
    1179         2760 :     pub(crate) fn schedule_layer_file_upload(
    1180         2760 :         self: &Arc<Self>,
    1181         2760 :         layer: ResidentLayer,
    1182         2760 :     ) -> Result<(), NotInitialized> {
    1183         2760 :         let mut guard = self.upload_queue.lock().unwrap();
    1184         2760 :         let upload_queue = guard.initialized_mut()?;
    1185              : 
    1186         2760 :         self.schedule_layer_file_upload0(upload_queue, layer);
    1187         2760 :         self.launch_queued_tasks(upload_queue);
    1188         2760 :         Ok(())
    1189         2760 :     }
    1190              : 
    1191         3484 :     fn schedule_layer_file_upload0(
    1192         3484 :         self: &Arc<Self>,
    1193         3484 :         upload_queue: &mut UploadQueueInitialized,
    1194         3484 :         layer: ResidentLayer,
    1195         3484 :     ) {
    1196         3484 :         let metadata = layer.metadata();
    1197         3484 : 
    1198         3484 :         upload_queue
    1199         3484 :             .dirty
    1200         3484 :             .layer_metadata
    1201         3484 :             .insert(layer.layer_desc().layer_name(), metadata.clone());
    1202         3484 :         upload_queue.latest_files_changes_since_metadata_upload_scheduled += 1;
    1203         3484 : 
    1204         3484 :         info!(
    1205              :             gen=?metadata.generation,
    1206              :             shard=?metadata.shard,
    1207            0 :             "scheduled layer file upload {layer}",
    1208              :         );
    1209              : 
    1210         3484 :         let op = UploadOp::UploadLayer(layer, metadata, None);
    1211         3484 :         self.metric_begin(&op);
    1212         3484 :         upload_queue.queued_operations.push_back(op);
    1213         3484 :     }
    1214              : 
    1215              :     /// Launch a delete operation in the background.
    1216              :     ///
    1217              :     /// The operation does not modify local filesystem state.
    1218              :     ///
    1219              :     /// Note: This schedules an index file upload before the deletions.  The
    1220              :     /// deletion won't actually be performed, until all previously scheduled
    1221              :     /// upload operations, and the index file upload, have completed
    1222              :     /// successfully.
    1223           16 :     pub fn schedule_layer_file_deletion(
    1224           16 :         self: &Arc<Self>,
    1225           16 :         names: &[LayerName],
    1226           16 :     ) -> anyhow::Result<()> {
    1227           16 :         let mut guard = self.upload_queue.lock().unwrap();
    1228           16 :         let upload_queue = guard.initialized_mut()?;
    1229              : 
    1230           16 :         let with_metadata =
    1231           16 :             self.schedule_unlinking_of_layers_from_index_part0(upload_queue, names.iter().cloned());
    1232           16 : 
    1233           16 :         self.schedule_deletion_of_unlinked0(upload_queue, with_metadata);
    1234           16 : 
    1235           16 :         // Launch the tasks immediately, if possible
    1236           16 :         self.launch_queued_tasks(upload_queue);
    1237           16 :         Ok(())
    1238           16 :     }
    1239              : 
    1240              :     /// Unlinks the layer files from `index_part.json` but does not yet schedule deletion for the
    1241              :     /// layer files, leaving them dangling.
    1242              :     ///
    1243              :     /// The files will be leaked in remote storage unless [`Self::schedule_deletion_of_unlinked`]
    1244              :     /// is invoked on them.
    1245            8 :     pub(crate) fn schedule_gc_update(
    1246            8 :         self: &Arc<Self>,
    1247            8 :         gc_layers: &[Layer],
    1248            8 :     ) -> Result<(), NotInitialized> {
    1249            8 :         let mut guard = self.upload_queue.lock().unwrap();
    1250            8 :         let upload_queue = guard.initialized_mut()?;
    1251              : 
    1252              :         // just forget the return value; after uploading the next index_part.json, we can consider
    1253              :         // the layer files as "dangling". this is fine, at worst case we create work for the
    1254              :         // scrubber.
    1255              : 
    1256            8 :         let names = gc_layers.iter().map(|x| x.layer_desc().layer_name());
    1257            8 : 
    1258            8 :         self.schedule_unlinking_of_layers_from_index_part0(upload_queue, names);
    1259            8 : 
    1260            8 :         self.launch_queued_tasks(upload_queue);
    1261            8 : 
    1262            8 :         Ok(())
    1263            8 :     }
    1264              : 
    1265              :     /// Update the remote index file, removing the to-be-deleted files from the index,
    1266              :     /// allowing scheduling of actual deletions later.
    1267          176 :     fn schedule_unlinking_of_layers_from_index_part0<I>(
    1268          176 :         self: &Arc<Self>,
    1269          176 :         upload_queue: &mut UploadQueueInitialized,
    1270          176 :         names: I,
    1271          176 :     ) -> Vec<(LayerName, LayerFileMetadata)>
    1272          176 :     where
    1273          176 :         I: IntoIterator<Item = LayerName>,
    1274          176 :     {
    1275          176 :         // Decorate our list of names with each name's metadata, dropping
    1276          176 :         // names that are unexpectedly missing from our metadata.  This metadata
    1277          176 :         // is later used when physically deleting layers, to construct key paths.
    1278          176 :         let with_metadata: Vec<_> = names
    1279          176 :             .into_iter()
    1280         1024 :             .filter_map(|name| {
    1281         1024 :                 let meta = upload_queue.dirty.layer_metadata.remove(&name);
    1282              : 
    1283         1024 :                 if let Some(meta) = meta {
    1284         1024 :                     upload_queue.latest_files_changes_since_metadata_upload_scheduled += 1;
    1285         1024 :                     Some((name, meta))
    1286              :                 } else {
    1287              :                     // This can only happen if we forgot to to schedule the file upload
    1288              :                     // before scheduling the delete. Log it because it is a rare/strange
    1289              :                     // situation, and in case something is misbehaving, we'd like to know which
    1290              :                     // layers experienced this.
    1291            0 :                     info!("Deleting layer {name} not found in latest_files list, never uploaded?");
    1292            0 :                     None
    1293              :                 }
    1294         1024 :             })
    1295          176 :             .collect();
    1296              : 
    1297              :         #[cfg(feature = "testing")]
    1298         1200 :         for (name, metadata) in &with_metadata {
    1299         1024 :             let gen_ = metadata.generation;
    1300         1024 :             if let Some(unexpected) = upload_queue.dangling_files.insert(name.to_owned(), gen_) {
    1301            0 :                 if unexpected == gen_ {
    1302            0 :                     tracing::error!("{name} was unlinked twice with same generation");
    1303              :                 } else {
    1304            0 :                     tracing::error!(
    1305            0 :                         "{name} was unlinked twice with different generations {gen_:?} and {unexpected:?}"
    1306              :                     );
    1307              :                 }
    1308         1024 :             }
    1309              :         }
    1310              : 
    1311              :         // after unlinking files from the upload_queue.latest_files we must always schedule an
    1312              :         // index_part update, because that needs to be uploaded before we can actually delete the
    1313              :         // files.
    1314          176 :         if upload_queue.latest_files_changes_since_metadata_upload_scheduled > 0 {
    1315          144 :             self.schedule_index_upload(upload_queue);
    1316          144 :         }
    1317              : 
    1318          176 :         with_metadata
    1319          176 :     }
    1320              : 
    1321              :     /// Schedules deletion for layer files which have previously been unlinked from the
    1322              :     /// `index_part.json` with [`Self::schedule_gc_update`] or [`Self::schedule_compaction_update`].
    1323         1025 :     pub(crate) fn schedule_deletion_of_unlinked(
    1324         1025 :         self: &Arc<Self>,
    1325         1025 :         layers: Vec<(LayerName, LayerFileMetadata)>,
    1326         1025 :     ) -> anyhow::Result<()> {
    1327         1025 :         let mut guard = self.upload_queue.lock().unwrap();
    1328         1025 :         let upload_queue = guard.initialized_mut()?;
    1329              : 
    1330         1025 :         self.schedule_deletion_of_unlinked0(upload_queue, layers);
    1331         1025 :         self.launch_queued_tasks(upload_queue);
    1332         1025 :         Ok(())
    1333         1025 :     }
    1334              : 
    1335         1037 :     fn schedule_deletion_of_unlinked0(
    1336         1037 :         self: &Arc<Self>,
    1337         1037 :         upload_queue: &mut UploadQueueInitialized,
    1338         1037 :         mut with_metadata: Vec<(LayerName, LayerFileMetadata)>,
    1339         1037 :     ) {
    1340         1037 :         // Filter out any layers which were not created by this tenant shard.  These are
    1341         1037 :         // layers that originate from some ancestor shard after a split, and may still
    1342         1037 :         // be referenced by other shards. We are free to delete them locally and remove
    1343         1037 :         // them from our index (and would have already done so when we reach this point
    1344         1037 :         // in the code), but we may not delete them remotely.
    1345         1037 :         with_metadata.retain(|(name, meta)| {
    1346         1025 :             let retain = meta.shard.shard_number == self.tenant_shard_id.shard_number
    1347         1025 :                 && meta.shard.shard_count == self.tenant_shard_id.shard_count;
    1348         1025 :             if !retain {
    1349            0 :                 tracing::debug!(
    1350            0 :                     "Skipping deletion of ancestor-shard layer {name}, from shard {}",
    1351              :                     meta.shard
    1352              :                 );
    1353         1025 :             }
    1354         1025 :             retain
    1355         1037 :         });
    1356              : 
    1357         2062 :         for (name, meta) in &with_metadata {
    1358         1025 :             info!(
    1359            0 :                 "scheduling deletion of layer {}{} (shard {})",
    1360            0 :                 name,
    1361            0 :                 meta.generation.get_suffix(),
    1362              :                 meta.shard
    1363              :             );
    1364              :         }
    1365              : 
    1366              :         #[cfg(feature = "testing")]
    1367         2062 :         for (name, meta) in &with_metadata {
    1368         1025 :             let gen_ = meta.generation;
    1369         1025 :             match upload_queue.dangling_files.remove(name) {
    1370         1017 :                 Some(same) if same == gen_ => { /* expected */ }
    1371            0 :                 Some(other) => {
    1372            0 :                     tracing::error!("{name} was unlinked with {other:?} but deleted with {gen_:?}");
    1373              :                 }
    1374              :                 None => {
    1375            8 :                     tracing::error!("{name} was unlinked but was not dangling");
    1376              :                 }
    1377              :             }
    1378              :         }
    1379              : 
    1380              :         // schedule the actual deletions
    1381         1037 :         if with_metadata.is_empty() {
    1382              :             // avoid scheduling the op & bumping the metric
    1383           12 :             return;
    1384         1025 :         }
    1385         1025 :         let op = UploadOp::Delete(Delete {
    1386         1025 :             layers: with_metadata,
    1387         1025 :         });
    1388         1025 :         self.metric_begin(&op);
    1389         1025 :         upload_queue.queued_operations.push_back(op);
    1390         1037 :     }
    1391              : 
    1392              :     /// Schedules a compaction update to the remote `index_part.json`.
    1393              :     ///
    1394              :     /// `compacted_from` represent the L0 names which have been `compacted_to` L1 layers.
    1395          152 :     pub(crate) fn schedule_compaction_update(
    1396          152 :         self: &Arc<Self>,
    1397          152 :         compacted_from: &[Layer],
    1398          152 :         compacted_to: &[ResidentLayer],
    1399          152 :     ) -> Result<(), NotInitialized> {
    1400          152 :         let mut guard = self.upload_queue.lock().unwrap();
    1401          152 :         let upload_queue = guard.initialized_mut()?;
    1402              : 
    1403          876 :         for layer in compacted_to {
    1404          724 :             self.schedule_layer_file_upload0(upload_queue, layer.clone());
    1405          724 :         }
    1406              : 
    1407         1012 :         let names = compacted_from.iter().map(|x| x.layer_desc().layer_name());
    1408          152 : 
    1409          152 :         self.schedule_unlinking_of_layers_from_index_part0(upload_queue, names);
    1410          152 :         self.launch_queued_tasks(upload_queue);
    1411          152 : 
    1412          152 :         Ok(())
    1413          152 :     }
    1414              : 
    1415              :     /// Wait for all previously scheduled uploads/deletions to complete
    1416         2796 :     pub(crate) async fn wait_completion(self: &Arc<Self>) -> Result<(), WaitCompletionError> {
    1417         2796 :         let receiver = {
    1418         2796 :             let mut guard = self.upload_queue.lock().unwrap();
    1419         2796 :             let upload_queue = guard
    1420         2796 :                 .initialized_mut()
    1421         2796 :                 .map_err(WaitCompletionError::NotInitialized)?;
    1422         2796 :             self.schedule_barrier0(upload_queue)
    1423         2796 :         };
    1424         2796 : 
    1425         2796 :         Self::wait_completion0(receiver).await
    1426         2796 :     }
    1427              : 
    1428         2796 :     async fn wait_completion0(
    1429         2796 :         mut receiver: tokio::sync::watch::Receiver<()>,
    1430         2796 :     ) -> Result<(), WaitCompletionError> {
    1431         2796 :         if receiver.changed().await.is_err() {
    1432            0 :             return Err(WaitCompletionError::UploadQueueShutDownOrStopped);
    1433         2796 :         }
    1434         2796 : 
    1435         2796 :         Ok(())
    1436         2796 :     }
    1437              : 
    1438           12 :     pub(crate) fn schedule_barrier(self: &Arc<Self>) -> anyhow::Result<()> {
    1439           12 :         let mut guard = self.upload_queue.lock().unwrap();
    1440           12 :         let upload_queue = guard.initialized_mut()?;
    1441           12 :         self.schedule_barrier0(upload_queue);
    1442           12 :         Ok(())
    1443           12 :     }
    1444              : 
    1445         2808 :     fn schedule_barrier0(
    1446         2808 :         self: &Arc<Self>,
    1447         2808 :         upload_queue: &mut UploadQueueInitialized,
    1448         2808 :     ) -> tokio::sync::watch::Receiver<()> {
    1449         2808 :         let (sender, receiver) = tokio::sync::watch::channel(());
    1450         2808 :         let barrier_op = UploadOp::Barrier(sender);
    1451         2808 : 
    1452         2808 :         upload_queue.queued_operations.push_back(barrier_op);
    1453         2808 :         // Don't count this kind of operation!
    1454         2808 : 
    1455         2808 :         // Launch the task immediately, if possible
    1456         2808 :         self.launch_queued_tasks(upload_queue);
    1457         2808 : 
    1458         2808 :         receiver
    1459         2808 :     }
    1460              : 
    1461              :     /// Wait for all previously scheduled operations to complete, and then stop.
    1462              :     ///
    1463              :     /// Not cancellation safe
    1464           20 :     pub(crate) async fn shutdown(self: &Arc<Self>) {
    1465           20 :         // On cancellation the queue is left in ackward state of refusing new operations but
    1466           20 :         // proper stop is yet to be called. On cancel the original or some later task must call
    1467           20 :         // `stop` or `shutdown`.
    1468           20 :         let sg = scopeguard::guard((), |_| {
    1469            0 :             tracing::error!(
    1470            0 :                 "RemoteTimelineClient::shutdown was cancelled; this should not happen, do not make this into an allowed_error"
    1471              :             )
    1472           20 :         });
    1473              : 
    1474           16 :         let fut = {
    1475           20 :             let mut guard = self.upload_queue.lock().unwrap();
    1476           20 :             let upload_queue = match &mut *guard {
    1477              :                 UploadQueue::Stopped(_) => {
    1478            4 :                     scopeguard::ScopeGuard::into_inner(sg);
    1479            4 :                     return;
    1480              :                 }
    1481              :                 UploadQueue::Uninitialized => {
    1482              :                     // transition into Stopped state
    1483            0 :                     self.stop_impl(&mut guard);
    1484            0 :                     scopeguard::ScopeGuard::into_inner(sg);
    1485            0 :                     return;
    1486              :                 }
    1487           16 :                 UploadQueue::Initialized(init) => init,
    1488           16 :             };
    1489           16 : 
    1490           16 :             // if the queue is already stuck due to a shutdown operation which was cancelled, then
    1491           16 :             // just don't add more of these as they would never complete.
    1492           16 :             //
    1493           16 :             // TODO: if launch_queued_tasks were to be refactored to accept a &mut UploadQueue
    1494           16 :             // in every place we would not have to jump through this hoop, and this method could be
    1495           16 :             // made cancellable.
    1496           16 :             if !upload_queue.shutting_down {
    1497           12 :                 upload_queue.shutting_down = true;
    1498           12 :                 upload_queue.queued_operations.push_back(UploadOp::Shutdown);
    1499           12 :                 // this operation is not counted similar to Barrier
    1500           12 : 
    1501           12 :                 self.launch_queued_tasks(upload_queue);
    1502           12 :             }
    1503              : 
    1504           16 :             upload_queue.shutdown_ready.clone().acquire_owned()
    1505              :         };
    1506              : 
    1507           16 :         let res = fut.await;
    1508              : 
    1509           16 :         scopeguard::ScopeGuard::into_inner(sg);
    1510           16 : 
    1511           16 :         match res {
    1512            0 :             Ok(_permit) => unreachable!("shutdown_ready should not have been added permits"),
    1513           16 :             Err(_closed) => {
    1514           16 :                 // expected
    1515           16 :             }
    1516           16 :         }
    1517           16 : 
    1518           16 :         self.stop();
    1519           20 :     }
    1520              : 
    1521              :     /// Set the deleted_at field in the remote index file.
    1522              :     ///
    1523              :     /// This fails if the upload queue has not been `stop()`ed.
    1524              :     ///
    1525              :     /// The caller is responsible for calling `stop()` AND for waiting
    1526              :     /// for any ongoing upload tasks to finish after `stop()` has succeeded.
    1527              :     /// Check method [`RemoteTimelineClient::stop`] for details.
    1528              :     #[instrument(skip_all)]
    1529              :     pub(crate) async fn persist_index_part_with_deleted_flag(
    1530              :         self: &Arc<Self>,
    1531              :     ) -> Result<(), PersistIndexPartWithDeletedFlagError> {
    1532              :         let index_part_with_deleted_at = {
    1533              :             let mut locked = self.upload_queue.lock().unwrap();
    1534              : 
    1535              :             // We must be in stopped state because otherwise
    1536              :             // we can have inprogress index part upload that can overwrite the file
    1537              :             // with missing is_deleted flag that we going to set below
    1538              :             let stopped = locked.stopped_mut()?;
    1539              : 
    1540              :             match stopped.deleted_at {
    1541              :                 SetDeletedFlagProgress::NotRunning => (), // proceed
    1542              :                 SetDeletedFlagProgress::InProgress(at) => {
    1543              :                     return Err(PersistIndexPartWithDeletedFlagError::AlreadyInProgress(at));
    1544              :                 }
    1545              :                 SetDeletedFlagProgress::Successful(at) => {
    1546              :                     return Err(PersistIndexPartWithDeletedFlagError::AlreadyDeleted(at));
    1547              :                 }
    1548              :             };
    1549              :             let deleted_at = Utc::now().naive_utc();
    1550              :             stopped.deleted_at = SetDeletedFlagProgress::InProgress(deleted_at);
    1551              : 
    1552              :             let mut index_part = stopped.upload_queue_for_deletion.dirty.clone();
    1553              :             index_part.deleted_at = Some(deleted_at);
    1554              :             index_part
    1555              :         };
    1556              : 
    1557            0 :         let undo_deleted_at = scopeguard::guard(Arc::clone(self), |self_clone| {
    1558            0 :             let mut locked = self_clone.upload_queue.lock().unwrap();
    1559            0 :             let stopped = locked
    1560            0 :                 .stopped_mut()
    1561            0 :                 .expect("there's no way out of Stopping, and we checked it's Stopping above");
    1562            0 :             stopped.deleted_at = SetDeletedFlagProgress::NotRunning;
    1563            0 :         });
    1564              : 
    1565              :         pausable_failpoint!("persist_deleted_index_part");
    1566              : 
    1567              :         backoff::retry(
    1568            0 :             || {
    1569            0 :                 upload::upload_index_part(
    1570            0 :                     &self.storage_impl,
    1571            0 :                     &self.tenant_shard_id,
    1572            0 :                     &self.timeline_id,
    1573            0 :                     self.generation,
    1574            0 :                     &index_part_with_deleted_at,
    1575            0 :                     &self.cancel,
    1576            0 :                 )
    1577            0 :             },
    1578            0 :             |_e| false,
    1579              :             1,
    1580              :             // have just a couple of attempts
    1581              :             // when executed as part of timeline deletion this happens in context of api call
    1582              :             // when executed as part of tenant deletion this happens in the background
    1583              :             2,
    1584              :             "persist_index_part_with_deleted_flag",
    1585              :             &self.cancel,
    1586              :         )
    1587              :         .await
    1588            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    1589            0 :         .and_then(|x| x)?;
    1590              : 
    1591              :         // all good, disarm the guard and mark as success
    1592              :         ScopeGuard::into_inner(undo_deleted_at);
    1593              :         {
    1594              :             let mut locked = self.upload_queue.lock().unwrap();
    1595              : 
    1596              :             let stopped = locked
    1597              :                 .stopped_mut()
    1598              :                 .expect("there's no way out of Stopping, and we checked it's Stopping above");
    1599              :             stopped.deleted_at = SetDeletedFlagProgress::Successful(
    1600              :                 index_part_with_deleted_at
    1601              :                     .deleted_at
    1602              :                     .expect("we set it above"),
    1603              :             );
    1604              :         }
    1605              : 
    1606              :         Ok(())
    1607              :     }
    1608              : 
    1609            0 :     pub(crate) fn is_deleting(&self) -> bool {
    1610            0 :         let mut locked = self.upload_queue.lock().unwrap();
    1611            0 :         locked.stopped_mut().is_ok()
    1612            0 :     }
    1613              : 
    1614            0 :     pub(crate) async fn preserve_initdb_archive(
    1615            0 :         self: &Arc<Self>,
    1616            0 :         tenant_id: &TenantId,
    1617            0 :         timeline_id: &TimelineId,
    1618            0 :         cancel: &CancellationToken,
    1619            0 :     ) -> anyhow::Result<()> {
    1620            0 :         backoff::retry(
    1621            0 :             || async {
    1622            0 :                 upload::preserve_initdb_archive(&self.storage_impl, tenant_id, timeline_id, cancel)
    1623            0 :                     .await
    1624            0 :             },
    1625            0 :             TimeoutOrCancel::caused_by_cancel,
    1626            0 :             FAILED_DOWNLOAD_WARN_THRESHOLD,
    1627            0 :             FAILED_REMOTE_OP_RETRIES,
    1628            0 :             "preserve_initdb_tar_zst",
    1629            0 :             &cancel.clone(),
    1630            0 :         )
    1631            0 :         .await
    1632            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    1633            0 :         .and_then(|x| x)
    1634            0 :         .context("backing up initdb archive")?;
    1635            0 :         Ok(())
    1636            0 :     }
    1637              : 
    1638              :     /// Uploads the given layer **without** adding it to be part of a future `index_part.json` upload.
    1639              :     ///
    1640              :     /// This is not normally needed.
    1641            0 :     pub(crate) async fn upload_layer_file(
    1642            0 :         self: &Arc<Self>,
    1643            0 :         uploaded: &ResidentLayer,
    1644            0 :         cancel: &CancellationToken,
    1645            0 :     ) -> anyhow::Result<()> {
    1646            0 :         let remote_path = remote_layer_path(
    1647            0 :             &self.tenant_shard_id.tenant_id,
    1648            0 :             &self.timeline_id,
    1649            0 :             uploaded.metadata().shard,
    1650            0 :             &uploaded.layer_desc().layer_name(),
    1651            0 :             uploaded.metadata().generation,
    1652            0 :         );
    1653            0 : 
    1654            0 :         backoff::retry(
    1655            0 :             || async {
    1656            0 :                 upload::upload_timeline_layer(
    1657            0 :                     &self.storage_impl,
    1658            0 :                     uploaded.local_path(),
    1659            0 :                     &remote_path,
    1660            0 :                     uploaded.metadata().file_size,
    1661            0 :                     cancel,
    1662            0 :                 )
    1663            0 :                 .await
    1664            0 :             },
    1665            0 :             TimeoutOrCancel::caused_by_cancel,
    1666            0 :             FAILED_UPLOAD_WARN_THRESHOLD,
    1667            0 :             FAILED_REMOTE_OP_RETRIES,
    1668            0 :             "upload a layer without adding it to latest files",
    1669            0 :             cancel,
    1670            0 :         )
    1671            0 :         .await
    1672            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    1673            0 :         .and_then(|x| x)
    1674            0 :         .context("upload a layer without adding it to latest files")
    1675            0 :     }
    1676              : 
    1677              :     /// Copies the `adopted` remote existing layer to the remote path of `adopted_as`. The layer is
    1678              :     /// not added to be part of a future `index_part.json` upload.
    1679            0 :     pub(crate) async fn copy_timeline_layer(
    1680            0 :         self: &Arc<Self>,
    1681            0 :         adopted: &Layer,
    1682            0 :         adopted_as: &Layer,
    1683            0 :         cancel: &CancellationToken,
    1684            0 :     ) -> anyhow::Result<()> {
    1685            0 :         let source_remote_path = remote_layer_path(
    1686            0 :             &self.tenant_shard_id.tenant_id,
    1687            0 :             &adopted
    1688            0 :                 .get_timeline_id()
    1689            0 :                 .expect("Source timeline should be alive"),
    1690            0 :             adopted.metadata().shard,
    1691            0 :             &adopted.layer_desc().layer_name(),
    1692            0 :             adopted.metadata().generation,
    1693            0 :         );
    1694            0 : 
    1695            0 :         let target_remote_path = remote_layer_path(
    1696            0 :             &self.tenant_shard_id.tenant_id,
    1697            0 :             &self.timeline_id,
    1698            0 :             adopted_as.metadata().shard,
    1699            0 :             &adopted_as.layer_desc().layer_name(),
    1700            0 :             adopted_as.metadata().generation,
    1701            0 :         );
    1702            0 : 
    1703            0 :         backoff::retry(
    1704            0 :             || async {
    1705            0 :                 upload::copy_timeline_layer(
    1706            0 :                     &self.storage_impl,
    1707            0 :                     &source_remote_path,
    1708            0 :                     &target_remote_path,
    1709            0 :                     cancel,
    1710            0 :                 )
    1711            0 :                 .await
    1712            0 :             },
    1713            0 :             TimeoutOrCancel::caused_by_cancel,
    1714            0 :             FAILED_UPLOAD_WARN_THRESHOLD,
    1715            0 :             FAILED_REMOTE_OP_RETRIES,
    1716            0 :             "copy timeline layer",
    1717            0 :             cancel,
    1718            0 :         )
    1719            0 :         .await
    1720            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    1721            0 :         .and_then(|x| x)
    1722            0 :         .context("remote copy timeline layer")
    1723            0 :     }
    1724              : 
    1725            0 :     async fn flush_deletion_queue(&self) -> Result<(), DeletionQueueError> {
    1726            0 :         match tokio::time::timeout(
    1727            0 :             DELETION_QUEUE_FLUSH_TIMEOUT,
    1728            0 :             self.deletion_queue_client.flush_immediate(),
    1729            0 :         )
    1730            0 :         .await
    1731              :         {
    1732            0 :             Ok(result) => result,
    1733            0 :             Err(_timeout) => {
    1734            0 :                 // Flushing remote deletions is not mandatory: we flush here to make the system easier to test, and
    1735            0 :                 // to ensure that _usually_ objects are really gone after a DELETE is acked.  However, in case of deletion
    1736            0 :                 // queue issues (https://github.com/neondatabase/neon/issues/6440), we don't want to wait indefinitely here.
    1737            0 :                 tracing::warn!(
    1738            0 :                     "Timed out waiting for deletion queue flush, acking deletion anyway"
    1739              :                 );
    1740            0 :                 Ok(())
    1741              :             }
    1742              :         }
    1743            0 :     }
    1744              : 
    1745              :     /// Prerequisites: UploadQueue should be in stopped state and deleted_at should be successfuly set.
    1746              :     /// The function deletes layer files one by one, then lists the prefix to see if we leaked something
    1747              :     /// deletes leaked files if any and proceeds with deletion of index file at the end.
    1748            0 :     pub(crate) async fn delete_all(self: &Arc<Self>) -> Result<(), DeleteTimelineError> {
    1749            0 :         debug_assert_current_span_has_tenant_and_timeline_id();
    1750              : 
    1751            0 :         let layers: Vec<RemotePath> = {
    1752            0 :             let mut locked = self.upload_queue.lock().unwrap();
    1753            0 :             let stopped = locked.stopped_mut().map_err(DeleteTimelineError::Other)?;
    1754              : 
    1755            0 :             if !matches!(stopped.deleted_at, SetDeletedFlagProgress::Successful(_)) {
    1756            0 :                 return Err(DeleteTimelineError::Other(anyhow::anyhow!(
    1757            0 :                     "deleted_at is not set"
    1758            0 :                 )));
    1759            0 :             }
    1760            0 : 
    1761            0 :             debug_assert!(stopped.upload_queue_for_deletion.no_pending_work());
    1762              : 
    1763            0 :             stopped
    1764            0 :                 .upload_queue_for_deletion
    1765            0 :                 .dirty
    1766            0 :                 .layer_metadata
    1767            0 :                 .drain()
    1768            0 :                 .filter(|(_file_name, meta)| {
    1769            0 :                     // Filter out layers that belonged to an ancestor shard.  Since we are deleting the whole timeline from
    1770            0 :                     // all shards anyway, we _could_ delete these, but
    1771            0 :                     // - it creates a potential race if other shards are still
    1772            0 :                     //   using the layers while this shard deletes them.
    1773            0 :                     // - it means that if we rolled back the shard split, the ancestor shards would be in a state where
    1774            0 :                     //   these timelines are present but corrupt (their index exists but some layers don't)
    1775            0 :                     //
    1776            0 :                     // These layers will eventually be cleaned up by the scrubber when it does physical GC.
    1777            0 :                     meta.shard.shard_number == self.tenant_shard_id.shard_number
    1778            0 :                         && meta.shard.shard_count == self.tenant_shard_id.shard_count
    1779            0 :                 })
    1780            0 :                 .map(|(file_name, meta)| {
    1781            0 :                     remote_layer_path(
    1782            0 :                         &self.tenant_shard_id.tenant_id,
    1783            0 :                         &self.timeline_id,
    1784            0 :                         meta.shard,
    1785            0 :                         &file_name,
    1786            0 :                         meta.generation,
    1787            0 :                     )
    1788            0 :                 })
    1789            0 :                 .collect()
    1790            0 :         };
    1791            0 : 
    1792            0 :         let layer_deletion_count = layers.len();
    1793            0 :         self.deletion_queue_client
    1794            0 :             .push_immediate(layers)
    1795            0 :             .await
    1796            0 :             .map_err(|_| DeleteTimelineError::Cancelled)?;
    1797              : 
    1798              :         // Delete the initdb.tar.zst, which is not always present, but deletion attempts of
    1799              :         // inexistant objects are not considered errors.
    1800            0 :         let initdb_path =
    1801            0 :             remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &self.timeline_id);
    1802            0 :         self.deletion_queue_client
    1803            0 :             .push_immediate(vec![initdb_path])
    1804            0 :             .await
    1805            0 :             .map_err(|_| DeleteTimelineError::Cancelled)?;
    1806              : 
    1807              :         // Do not delete index part yet, it is needed for possible retry. If we remove it first
    1808              :         // and retry will arrive to different pageserver there wont be any traces of it on remote storage
    1809            0 :         let timeline_storage_path = remote_timeline_path(&self.tenant_shard_id, &self.timeline_id);
    1810            0 : 
    1811            0 :         // Execute all pending deletions, so that when we proceed to do a listing below, we aren't
    1812            0 :         // taking the burden of listing all the layers that we already know we should delete.
    1813            0 :         self.flush_deletion_queue()
    1814            0 :             .await
    1815            0 :             .map_err(|_| DeleteTimelineError::Cancelled)?;
    1816              : 
    1817            0 :         let cancel = shutdown_token();
    1818              : 
    1819            0 :         let remaining = download_retry(
    1820            0 :             || async {
    1821            0 :                 self.storage_impl
    1822            0 :                     .list(
    1823            0 :                         Some(&timeline_storage_path),
    1824            0 :                         ListingMode::NoDelimiter,
    1825            0 :                         None,
    1826            0 :                         &cancel,
    1827            0 :                     )
    1828            0 :                     .await
    1829            0 :             },
    1830            0 :             "list remaining files",
    1831            0 :             &cancel,
    1832            0 :         )
    1833            0 :         .await
    1834            0 :         .context("list files remaining files")?
    1835              :         .keys;
    1836              : 
    1837              :         // We will delete the current index_part object last, since it acts as a deletion
    1838              :         // marker via its deleted_at attribute
    1839            0 :         let latest_index = remaining
    1840            0 :             .iter()
    1841            0 :             .filter(|o| {
    1842            0 :                 o.key
    1843            0 :                     .object_name()
    1844            0 :                     .map(|n| n.starts_with(IndexPart::FILE_NAME))
    1845            0 :                     .unwrap_or(false)
    1846            0 :             })
    1847            0 :             .filter_map(|o| {
    1848            0 :                 parse_remote_index_path(o.key.clone()).map(|gen_| (o.key.clone(), gen_))
    1849            0 :             })
    1850            0 :             .max_by_key(|i| i.1)
    1851            0 :             .map(|i| i.0.clone())
    1852            0 :             .unwrap_or(
    1853            0 :                 // No generation-suffixed indices, assume we are dealing with
    1854            0 :                 // a legacy index.
    1855            0 :                 remote_index_path(&self.tenant_shard_id, &self.timeline_id, Generation::none()),
    1856            0 :             );
    1857            0 : 
    1858            0 :         let remaining_layers: Vec<RemotePath> = remaining
    1859            0 :             .into_iter()
    1860            0 :             .filter_map(|o| {
    1861            0 :                 if o.key == latest_index || o.key.object_name() == Some(INITDB_PRESERVED_PATH) {
    1862            0 :                     None
    1863              :                 } else {
    1864            0 :                     Some(o.key)
    1865              :                 }
    1866            0 :             })
    1867            0 :             .inspect(|path| {
    1868            0 :                 if let Some(name) = path.object_name() {
    1869            0 :                     info!(%name, "deleting a file not referenced from index_part.json");
    1870              :                 } else {
    1871            0 :                     warn!(%path, "deleting a nameless or non-utf8 object not referenced from index_part.json");
    1872              :                 }
    1873            0 :             })
    1874            0 :             .collect();
    1875            0 : 
    1876            0 :         let not_referenced_count = remaining_layers.len();
    1877            0 :         if !remaining_layers.is_empty() {
    1878            0 :             self.deletion_queue_client
    1879            0 :                 .push_immediate(remaining_layers)
    1880            0 :                 .await
    1881            0 :                 .map_err(|_| DeleteTimelineError::Cancelled)?;
    1882            0 :         }
    1883              : 
    1884            0 :         fail::fail_point!("timeline-delete-before-index-delete", |_| {
    1885            0 :             Err(DeleteTimelineError::Other(anyhow::anyhow!(
    1886            0 :                 "failpoint: timeline-delete-before-index-delete"
    1887            0 :             )))?
    1888            0 :         });
    1889              : 
    1890            0 :         debug!("enqueuing index part deletion");
    1891            0 :         self.deletion_queue_client
    1892            0 :             .push_immediate([latest_index].to_vec())
    1893            0 :             .await
    1894            0 :             .map_err(|_| DeleteTimelineError::Cancelled)?;
    1895              : 
    1896              :         // Timeline deletion is rare and we have probably emitted a reasonably number of objects: wait
    1897              :         // for a flush to a persistent deletion list so that we may be sure deletion will occur.
    1898            0 :         self.flush_deletion_queue()
    1899            0 :             .await
    1900            0 :             .map_err(|_| DeleteTimelineError::Cancelled)?;
    1901              : 
    1902            0 :         fail::fail_point!("timeline-delete-after-index-delete", |_| {
    1903            0 :             Err(DeleteTimelineError::Other(anyhow::anyhow!(
    1904            0 :                 "failpoint: timeline-delete-after-index-delete"
    1905            0 :             )))?
    1906            0 :         });
    1907              : 
    1908            0 :         info!(prefix=%timeline_storage_path, referenced=layer_deletion_count, not_referenced=%not_referenced_count, "done deleting in timeline prefix, including index_part.json");
    1909              : 
    1910            0 :         Ok(())
    1911            0 :     }
    1912              : 
    1913              :     /// Pick next tasks from the queue, and start as many of them as possible without violating
    1914              :     /// the ordering constraints.
    1915              :     ///
    1916              :     /// TODO: consider limiting the number of in-progress tasks, beyond what remote_storage does.
    1917              :     /// This can launch an unbounded number of queued tasks. `UploadQueue::next_ready()` also has
    1918              :     /// worst-case quadratic cost in the number of tasks, and may struggle beyond 10,000 tasks.
    1919        16646 :     fn launch_queued_tasks(self: &Arc<Self>, upload_queue: &mut UploadQueueInitialized) {
    1920        26646 :         while let Some((mut next_op, coalesced_ops)) = upload_queue.next_ready() {
    1921        10000 :             debug!("starting op: {next_op}");
    1922              : 
    1923              :             // Prepare upload.
    1924        10000 :             match &mut next_op {
    1925         3484 :                 UploadOp::UploadLayer(layer, meta, mode) => {
    1926         3484 :                     if upload_queue
    1927         3484 :                         .recently_deleted
    1928         3484 :                         .remove(&(layer.layer_desc().layer_name().clone(), meta.generation))
    1929            0 :                     {
    1930            0 :                         *mode = Some(OpType::FlushDeletion);
    1931            0 :                     } else {
    1932         3484 :                         *mode = Some(OpType::MayReorder)
    1933              :                     }
    1934              :                 }
    1935         3024 :                 UploadOp::UploadMetadata { .. } => {}
    1936          684 :                 UploadOp::Delete(Delete { layers }) => {
    1937         1368 :                     for (name, meta) in layers {
    1938          684 :                         upload_queue
    1939          684 :                             .recently_deleted
    1940          684 :                             .insert((name.clone(), meta.generation));
    1941          684 :                     }
    1942              :                 }
    1943         2808 :                 UploadOp::Barrier(sender) => {
    1944         2808 :                     sender.send_replace(());
    1945         2808 :                     continue;
    1946              :                 }
    1947            0 :                 UploadOp::Shutdown => unreachable!("shutdown is intentionally never popped off"),
    1948              :             };
    1949              : 
    1950              :             // Assign unique ID to this task
    1951         7192 :             upload_queue.task_counter += 1;
    1952         7192 :             let upload_task_id = upload_queue.task_counter;
    1953         7192 : 
    1954         7192 :             // Add it to the in-progress map
    1955         7192 :             let task = Arc::new(UploadTask {
    1956         7192 :                 task_id: upload_task_id,
    1957         7192 :                 op: next_op,
    1958         7192 :                 coalesced_ops,
    1959         7192 :                 retries: AtomicU32::new(0),
    1960         7192 :             });
    1961         7192 :             upload_queue
    1962         7192 :                 .inprogress_tasks
    1963         7192 :                 .insert(task.task_id, Arc::clone(&task));
    1964         7192 : 
    1965         7192 :             // Spawn task to perform the task
    1966         7192 :             let self_rc = Arc::clone(self);
    1967         7192 :             let tenant_shard_id = self.tenant_shard_id;
    1968         7192 :             let timeline_id = self.timeline_id;
    1969         7192 :             task_mgr::spawn(
    1970         7192 :                 &self.runtime,
    1971         7192 :                 TaskKind::RemoteUploadTask,
    1972         7192 :                 self.tenant_shard_id,
    1973         7192 :                 Some(self.timeline_id),
    1974         7192 :                 "remote upload",
    1975         7047 :                 async move {
    1976         7047 :                     self_rc.perform_upload_task(task).await;
    1977         6773 :                     Ok(())
    1978         6773 :                 }
    1979         7192 :                 .instrument(info_span!(parent: None, "remote_upload", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), %timeline_id, %upload_task_id)),
    1980              :             );
    1981              : 
    1982              :             // Loop back to process next task
    1983              :         }
    1984        16646 :     }
    1985              : 
    1986              :     ///
    1987              :     /// Perform an upload task.
    1988              :     ///
    1989              :     /// The task is in the `inprogress_tasks` list. This function will try to
    1990              :     /// execute it, retrying forever. On successful completion, the task is
    1991              :     /// removed it from the `inprogress_tasks` list, and any next task(s) in the
    1992              :     /// queue that were waiting by the completion are launched.
    1993              :     ///
    1994              :     /// The task can be shut down, however. That leads to stopping the whole
    1995              :     /// queue.
    1996              :     ///
    1997         7047 :     async fn perform_upload_task(self: &Arc<Self>, task: Arc<UploadTask>) {
    1998         7047 :         let cancel = shutdown_token();
    1999              :         // Loop to retry until it completes.
    2000              :         loop {
    2001              :             // If we're requested to shut down, close up shop and exit.
    2002              :             //
    2003              :             // Note: We only check for the shutdown requests between retries, so
    2004              :             // if a shutdown request arrives while we're busy uploading, in the
    2005              :             // upload::upload:*() call below, we will wait not exit until it has
    2006              :             // finished. We probably could cancel the upload by simply dropping
    2007              :             // the Future, but we're not 100% sure if the remote storage library
    2008              :             // is cancellation safe, so we don't dare to do that. Hopefully, the
    2009              :             // upload finishes or times out soon enough.
    2010         7047 :             if cancel.is_cancelled() {
    2011            0 :                 info!("upload task cancelled by shutdown request");
    2012            0 :                 self.stop();
    2013            0 :                 return;
    2014         7047 :             }
    2015         7047 : 
    2016         7047 :             // Assert that we don't modify a layer that's referenced by the current index.
    2017         7047 :             if cfg!(debug_assertions) {
    2018         7047 :                 let modified = match &task.op {
    2019         3365 :                     UploadOp::UploadLayer(layer, layer_metadata, _) => {
    2020         3365 :                         vec![(layer.layer_desc().layer_name(), layer_metadata)]
    2021              :                     }
    2022          684 :                     UploadOp::Delete(delete) => {
    2023          684 :                         delete.layers.iter().map(|(n, m)| (n.clone(), m)).collect()
    2024              :                     }
    2025              :                     // These don't modify layers.
    2026         2998 :                     UploadOp::UploadMetadata { .. } => Vec::new(),
    2027            0 :                     UploadOp::Barrier(_) => Vec::new(),
    2028            0 :                     UploadOp::Shutdown => Vec::new(),
    2029              :                 };
    2030         7047 :                 if let Ok(queue) = self.upload_queue.lock().unwrap().initialized_mut() {
    2031        11088 :                     for (ref name, metadata) in modified {
    2032         4049 :                         debug_assert!(
    2033         4049 :                             !queue.clean.0.references(name, metadata),
    2034            8 :                             "layer {name} modified while referenced by index",
    2035              :                         );
    2036              :                     }
    2037            0 :                 }
    2038            0 :             }
    2039              : 
    2040         7039 :             let upload_result: anyhow::Result<()> = match &task.op {
    2041         3365 :                 UploadOp::UploadLayer(layer, layer_metadata, mode) => {
    2042              :                     // TODO: check if this mechanism can be removed now that can_bypass() performs
    2043              :                     // conflict checks during scheduling.
    2044         3365 :                     if let Some(OpType::FlushDeletion) = mode {
    2045            0 :                         if self.config.read().unwrap().block_deletions {
    2046              :                             // Of course, this is not efficient... but usually the queue should be empty.
    2047            0 :                             let mut queue_locked = self.upload_queue.lock().unwrap();
    2048            0 :                             let mut detected = false;
    2049            0 :                             if let Ok(queue) = queue_locked.initialized_mut() {
    2050            0 :                                 for list in queue.blocked_deletions.iter_mut() {
    2051            0 :                                     list.layers.retain(|(name, meta)| {
    2052            0 :                                         if name == &layer.layer_desc().layer_name()
    2053            0 :                                             && meta.generation == layer_metadata.generation
    2054              :                                         {
    2055            0 :                                             detected = true;
    2056            0 :                                             // remove the layer from deletion queue
    2057            0 :                                             false
    2058              :                                         } else {
    2059              :                                             // keep the layer
    2060            0 :                                             true
    2061              :                                         }
    2062            0 :                                     });
    2063            0 :                                 }
    2064            0 :                             }
    2065            0 :                             if detected {
    2066            0 :                                 info!(
    2067            0 :                                     "cancelled blocked deletion of layer {} at gen {:?}",
    2068            0 :                                     layer.layer_desc().layer_name(),
    2069              :                                     layer_metadata.generation
    2070              :                                 );
    2071            0 :                             }
    2072              :                         } else {
    2073              :                             // TODO: we did not guarantee that upload task starts after deletion task, so there could be possibly race conditions
    2074              :                             // that we still get the layer deleted. But this only happens if someone creates a layer immediately after it's deleted,
    2075              :                             // which is not possible in the current system.
    2076            0 :                             info!(
    2077            0 :                                 "waiting for deletion queue flush to complete before uploading layer {} at gen {:?}",
    2078            0 :                                 layer.layer_desc().layer_name(),
    2079              :                                 layer_metadata.generation
    2080              :                             );
    2081              :                             {
    2082              :                                 // We are going to flush, we can clean up the recently deleted list.
    2083            0 :                                 let mut queue_locked = self.upload_queue.lock().unwrap();
    2084            0 :                                 if let Ok(queue) = queue_locked.initialized_mut() {
    2085            0 :                                     queue.recently_deleted.clear();
    2086            0 :                                 }
    2087              :                             }
    2088            0 :                             if let Err(e) = self.deletion_queue_client.flush_execute().await {
    2089            0 :                                 warn!(
    2090            0 :                                     "failed to flush the deletion queue before uploading layer {} at gen {:?}, still proceeding to upload: {e:#} ",
    2091            0 :                                     layer.layer_desc().layer_name(),
    2092              :                                     layer_metadata.generation
    2093              :                                 );
    2094              :                             } else {
    2095            0 :                                 info!(
    2096            0 :                                     "done flushing deletion queue before uploading layer {} at gen {:?}",
    2097            0 :                                     layer.layer_desc().layer_name(),
    2098              :                                     layer_metadata.generation
    2099              :                                 );
    2100              :                             }
    2101              :                         }
    2102         3365 :                     }
    2103         3365 :                     let local_path = layer.local_path();
    2104         3365 : 
    2105         3365 :                     // We should only be uploading layers created by this `Tenant`'s lifetime, so
    2106         3365 :                     // the metadata in the upload should always match our current generation.
    2107         3365 :                     assert_eq!(layer_metadata.generation, self.generation);
    2108              : 
    2109         3365 :                     let remote_path = remote_layer_path(
    2110         3365 :                         &self.tenant_shard_id.tenant_id,
    2111         3365 :                         &self.timeline_id,
    2112         3365 :                         layer_metadata.shard,
    2113         3365 :                         &layer.layer_desc().layer_name(),
    2114         3365 :                         layer_metadata.generation,
    2115         3365 :                     );
    2116         3365 : 
    2117         3365 :                     upload::upload_timeline_layer(
    2118         3365 :                         &self.storage_impl,
    2119         3365 :                         local_path,
    2120         3365 :                         &remote_path,
    2121         3365 :                         layer_metadata.file_size,
    2122         3365 :                         &self.cancel,
    2123         3365 :                     )
    2124         3365 :                     .measure_remote_op(
    2125         3365 :                         RemoteOpFileKind::Layer,
    2126         3365 :                         RemoteOpKind::Upload,
    2127         3365 :                         Arc::clone(&self.metrics),
    2128         3365 :                     )
    2129         3365 :                     .await
    2130              :                 }
    2131         2998 :                 UploadOp::UploadMetadata { uploaded } => {
    2132         2998 :                     let res = upload::upload_index_part(
    2133         2998 :                         &self.storage_impl,
    2134         2998 :                         &self.tenant_shard_id,
    2135         2998 :                         &self.timeline_id,
    2136         2998 :                         self.generation,
    2137         2998 :                         uploaded,
    2138         2998 :                         &self.cancel,
    2139         2998 :                     )
    2140         2998 :                     .measure_remote_op(
    2141         2998 :                         RemoteOpFileKind::Index,
    2142         2998 :                         RemoteOpKind::Upload,
    2143         2998 :                         Arc::clone(&self.metrics),
    2144         2998 :                     )
    2145         2998 :                     .await;
    2146         2983 :                     if res.is_ok() {
    2147         2983 :                         self.update_remote_physical_size_gauge(Some(uploaded));
    2148         2983 :                         let mention_having_future_layers = if cfg!(feature = "testing") {
    2149         2983 :                             uploaded
    2150         2983 :                                 .layer_metadata
    2151         2983 :                                 .keys()
    2152        35453 :                                 .any(|x| x.is_in_future(uploaded.metadata.disk_consistent_lsn()))
    2153              :                         } else {
    2154            0 :                             false
    2155              :                         };
    2156         2983 :                         if mention_having_future_layers {
    2157              :                             // find rationale near crate::tenant::timeline::init::cleanup_future_layer
    2158          128 :                             tracing::info!(
    2159            0 :                                 disk_consistent_lsn = %uploaded.metadata.disk_consistent_lsn(),
    2160            0 :                                 "uploaded an index_part.json with future layers -- this is ok! if shutdown now, expect future layer cleanup"
    2161              :                             );
    2162         2855 :                         }
    2163            0 :                     }
    2164         2983 :                     res
    2165              :                 }
    2166          676 :                 UploadOp::Delete(delete) => {
    2167          676 :                     if self.config.read().unwrap().block_deletions {
    2168            0 :                         let mut queue_locked = self.upload_queue.lock().unwrap();
    2169            0 :                         if let Ok(queue) = queue_locked.initialized_mut() {
    2170            0 :                             queue.blocked_deletions.push(delete.clone());
    2171            0 :                         }
    2172            0 :                         Ok(())
    2173              :                     } else {
    2174          676 :                         pausable_failpoint!("before-delete-layer-pausable");
    2175          676 :                         self.deletion_queue_client
    2176          676 :                             .push_layers(
    2177          676 :                                 self.tenant_shard_id,
    2178          676 :                                 self.timeline_id,
    2179          676 :                                 self.generation,
    2180          676 :                                 delete.layers.clone(),
    2181          676 :                             )
    2182          676 :                             .map_err(|e| anyhow::anyhow!(e))
    2183              :                     }
    2184              :                 }
    2185            0 :                 unexpected @ UploadOp::Barrier(_) | unexpected @ UploadOp::Shutdown => {
    2186              :                     // unreachable. Barrier operations are handled synchronously in
    2187              :                     // launch_queued_tasks
    2188            0 :                     warn!("unexpected {unexpected:?} operation in perform_upload_task");
    2189            0 :                     break;
    2190              :                 }
    2191              :             };
    2192              : 
    2193            0 :             match upload_result {
    2194              :                 Ok(()) => {
    2195         6773 :                     break;
    2196              :                 }
    2197            0 :                 Err(e) if TimeoutOrCancel::caused_by_cancel(&e) => {
    2198            0 :                     // loop around to do the proper stopping
    2199            0 :                     continue;
    2200              :                 }
    2201            0 :                 Err(e) => {
    2202            0 :                     let retries = task.retries.fetch_add(1, Ordering::SeqCst);
    2203            0 : 
    2204            0 :                     // Uploads can fail due to rate limits (IAM, S3), spurious network problems,
    2205            0 :                     // or other external reasons. Such issues are relatively regular, so log them
    2206            0 :                     // at info level at first, and only WARN if the operation fails repeatedly.
    2207            0 :                     //
    2208            0 :                     // (See similar logic for downloads in `download::download_retry`)
    2209            0 :                     if retries < FAILED_UPLOAD_WARN_THRESHOLD {
    2210            0 :                         info!(
    2211            0 :                             "failed to perform remote task {}, will retry (attempt {}): {:#}",
    2212            0 :                             task.op, retries, e
    2213              :                         );
    2214              :                     } else {
    2215            0 :                         warn!(
    2216            0 :                             "failed to perform remote task {}, will retry (attempt {}): {:?}",
    2217            0 :                             task.op, retries, e
    2218              :                         );
    2219              :                     }
    2220              : 
    2221              :                     // sleep until it's time to retry, or we're cancelled
    2222            0 :                     exponential_backoff(
    2223            0 :                         retries,
    2224            0 :                         DEFAULT_BASE_BACKOFF_SECONDS,
    2225            0 :                         DEFAULT_MAX_BACKOFF_SECONDS,
    2226            0 :                         &cancel,
    2227            0 :                     )
    2228            0 :                     .await;
    2229              :                 }
    2230              :             }
    2231              :         }
    2232              : 
    2233         6773 :         let retries = task.retries.load(Ordering::SeqCst);
    2234         6773 :         if retries > 0 {
    2235            0 :             info!(
    2236            0 :                 "remote task {} completed successfully after {} retries",
    2237            0 :                 task.op, retries
    2238              :             );
    2239              :         } else {
    2240         6773 :             debug!("remote task {} completed successfully", task.op);
    2241              :         }
    2242              : 
    2243              :         // The task has completed successfully. Remove it from the in-progress list.
    2244         6773 :         let lsn_update = {
    2245         6773 :             let mut upload_queue_guard = self.upload_queue.lock().unwrap();
    2246         6773 :             let upload_queue = match upload_queue_guard.deref_mut() {
    2247            0 :                 UploadQueue::Uninitialized => panic!(
    2248            0 :                     "callers are responsible for ensuring this is only called on an initialized queue"
    2249            0 :                 ),
    2250            0 :                 UploadQueue::Stopped(_stopped) => None,
    2251         6773 :                 UploadQueue::Initialized(qi) => Some(qi),
    2252              :             };
    2253              : 
    2254         6773 :             let upload_queue = match upload_queue {
    2255         6773 :                 Some(upload_queue) => upload_queue,
    2256              :                 None => {
    2257            0 :                     info!("another concurrent task already stopped the queue");
    2258            0 :                     return;
    2259              :                 }
    2260              :             };
    2261              : 
    2262         6773 :             upload_queue.inprogress_tasks.remove(&task.task_id);
    2263              : 
    2264         6773 :             let lsn_update = match task.op {
    2265         3114 :                 UploadOp::UploadLayer(_, _, _) => None,
    2266         2983 :                 UploadOp::UploadMetadata { ref uploaded } => {
    2267         2983 :                     // the task id is reused as a monotonicity check for storing the "clean"
    2268         2983 :                     // IndexPart.
    2269         2983 :                     let last_updater = upload_queue.clean.1;
    2270         2983 :                     let is_later = last_updater.is_some_and(|task_id| task_id < task.task_id);
    2271         2983 :                     let monotone = is_later || last_updater.is_none();
    2272              : 
    2273         2983 :                     assert!(
    2274         2983 :                         monotone,
    2275            0 :                         "no two index uploads should be completing at the same time, prev={last_updater:?}, task.task_id={}",
    2276            0 :                         task.task_id
    2277              :                     );
    2278              : 
    2279              :                     // not taking ownership is wasteful
    2280         2983 :                     upload_queue.clean.0.clone_from(uploaded);
    2281         2983 :                     upload_queue.clean.1 = Some(task.task_id);
    2282         2983 : 
    2283         2983 :                     let lsn = upload_queue.clean.0.metadata.disk_consistent_lsn();
    2284         2983 :                     self.metrics
    2285         2983 :                         .projected_remote_consistent_lsn_gauge
    2286         2983 :                         .set(lsn.0);
    2287         2983 : 
    2288         2983 :                     if self.generation.is_none() {
    2289              :                         // Legacy mode: skip validating generation
    2290            0 :                         upload_queue.visible_remote_consistent_lsn.store(lsn);
    2291            0 :                         None
    2292         2983 :                     } else if self
    2293         2983 :                         .config
    2294         2983 :                         .read()
    2295         2983 :                         .unwrap()
    2296         2983 :                         .process_remote_consistent_lsn_updates
    2297              :                     {
    2298         2983 :                         Some((lsn, upload_queue.visible_remote_consistent_lsn.clone()))
    2299              :                     } else {
    2300              :                         // Our config disables remote_consistent_lsn updates: drop it.
    2301            0 :                         None
    2302              :                     }
    2303              :                 }
    2304          676 :                 UploadOp::Delete(_) => None,
    2305            0 :                 UploadOp::Barrier(..) | UploadOp::Shutdown => unreachable!(),
    2306              :             };
    2307              : 
    2308              :             // Launch any queued tasks that were unblocked by this one.
    2309         6773 :             self.launch_queued_tasks(upload_queue);
    2310         6773 :             lsn_update
    2311              :         };
    2312              : 
    2313         6773 :         if let Some((lsn, slot)) = lsn_update {
    2314              :             // Updates to the remote_consistent_lsn we advertise to pageservers
    2315              :             // are all routed through the DeletionQueue, to enforce important
    2316              :             // data safety guarantees (see docs/rfcs/025-generation-numbers.md)
    2317         2983 :             self.deletion_queue_client
    2318         2983 :                 .update_remote_consistent_lsn(
    2319         2983 :                     self.tenant_shard_id,
    2320         2983 :                     self.timeline_id,
    2321         2983 :                     self.generation,
    2322         2983 :                     lsn,
    2323         2983 :                     slot,
    2324         2983 :                 )
    2325         2983 :                 .await;
    2326         3790 :         }
    2327              : 
    2328         6773 :         self.metric_end(&task.op);
    2329         6773 :         for coalesced_op in &task.coalesced_ops {
    2330            2 :             self.metric_end(coalesced_op);
    2331            2 :         }
    2332         6773 :     }
    2333              : 
    2334        14392 :     fn metric_impl(
    2335        14392 :         &self,
    2336        14392 :         op: &UploadOp,
    2337        14392 :     ) -> Option<(
    2338        14392 :         RemoteOpFileKind,
    2339        14392 :         RemoteOpKind,
    2340        14392 :         RemoteTimelineClientMetricsCallTrackSize,
    2341        14392 :     )> {
    2342              :         use RemoteTimelineClientMetricsCallTrackSize::DontTrackSize;
    2343        14392 :         let res = match op {
    2344         6598 :             UploadOp::UploadLayer(_, m, _) => (
    2345         6598 :                 RemoteOpFileKind::Layer,
    2346         6598 :                 RemoteOpKind::Upload,
    2347         6598 :                 RemoteTimelineClientMetricsCallTrackSize::Bytes(m.file_size),
    2348         6598 :             ),
    2349         6077 :             UploadOp::UploadMetadata { .. } => (
    2350         6077 :                 RemoteOpFileKind::Index,
    2351         6077 :                 RemoteOpKind::Upload,
    2352         6077 :                 DontTrackSize {
    2353         6077 :                     reason: "metadata uploads are tiny",
    2354         6077 :                 },
    2355         6077 :             ),
    2356         1701 :             UploadOp::Delete(_delete) => (
    2357         1701 :                 RemoteOpFileKind::Layer,
    2358         1701 :                 RemoteOpKind::Delete,
    2359         1701 :                 DontTrackSize {
    2360         1701 :                     reason: "should we track deletes? positive or negative sign?",
    2361         1701 :                 },
    2362         1701 :             ),
    2363              :             UploadOp::Barrier(..) | UploadOp::Shutdown => {
    2364              :                 // we do not account these
    2365           16 :                 return None;
    2366              :             }
    2367              :         };
    2368        14376 :         Some(res)
    2369        14392 :     }
    2370              : 
    2371         7601 :     fn metric_begin(&self, op: &UploadOp) {
    2372         7601 :         let (file_kind, op_kind, track_bytes) = match self.metric_impl(op) {
    2373         7601 :             Some(x) => x,
    2374            0 :             None => return,
    2375              :         };
    2376         7601 :         let guard = self.metrics.call_begin(&file_kind, &op_kind, track_bytes);
    2377         7601 :         guard.will_decrement_manually(); // in metric_end(), see right below
    2378         7601 :     }
    2379              : 
    2380         6791 :     fn metric_end(&self, op: &UploadOp) {
    2381         6791 :         let (file_kind, op_kind, track_bytes) = match self.metric_impl(op) {
    2382         6775 :             Some(x) => x,
    2383           16 :             None => return,
    2384              :         };
    2385         6775 :         self.metrics.call_end(&file_kind, &op_kind, track_bytes);
    2386         6791 :     }
    2387              : 
    2388              :     /// Close the upload queue for new operations and cancel queued operations.
    2389              :     ///
    2390              :     /// Use [`RemoteTimelineClient::shutdown`] for graceful stop.
    2391              :     ///
    2392              :     /// In-progress operations will still be running after this function returns.
    2393              :     /// Use `task_mgr::shutdown_tasks(Some(TaskKind::RemoteUploadTask), Some(self.tenant_shard_id), Some(timeline_id))`
    2394              :     /// to wait for them to complete, after calling this function.
    2395           36 :     pub(crate) fn stop(&self) {
    2396           36 :         // Whichever *task* for this RemoteTimelineClient grabs the mutex first will transition the queue
    2397           36 :         // into stopped state, thereby dropping all off the queued *ops* which haven't become *tasks* yet.
    2398           36 :         // The other *tasks* will come here and observe an already shut down queue and hence simply wrap up their business.
    2399           36 :         let mut guard = self.upload_queue.lock().unwrap();
    2400           36 :         self.stop_impl(&mut guard);
    2401           36 :     }
    2402              : 
    2403           36 :     fn stop_impl(&self, guard: &mut std::sync::MutexGuard<UploadQueue>) {
    2404           36 :         match &mut **guard {
    2405              :             UploadQueue::Uninitialized => {
    2406            0 :                 info!("UploadQueue is in state Uninitialized, nothing to do");
    2407            0 :                 **guard = UploadQueue::Stopped(UploadQueueStopped::Uninitialized);
    2408              :             }
    2409              :             UploadQueue::Stopped(_) => {
    2410              :                 // nothing to do
    2411           16 :                 info!("another concurrent task already shut down the queue");
    2412              :             }
    2413           20 :             UploadQueue::Initialized(initialized) => {
    2414           20 :                 info!("shutting down upload queue");
    2415              : 
    2416              :                 // Replace the queue with the Stopped state, taking ownership of the old
    2417              :                 // Initialized queue. We will do some checks on it, and then drop it.
    2418           20 :                 let qi = {
    2419              :                     // Here we preserve working version of the upload queue for possible use during deletions.
    2420              :                     // In-place replace of Initialized to Stopped can be done with the help of https://github.com/Sgeo/take_mut
    2421              :                     // but for this use case it doesnt really makes sense to bring unsafe code only for this usage point.
    2422              :                     // Deletion is not really perf sensitive so there shouldnt be any problems with cloning a fraction of it.
    2423           20 :                     let upload_queue_for_deletion = UploadQueueInitialized {
    2424           20 :                         inprogress_limit: initialized.inprogress_limit,
    2425           20 :                         task_counter: 0,
    2426           20 :                         dirty: initialized.dirty.clone(),
    2427           20 :                         clean: initialized.clean.clone(),
    2428           20 :                         latest_files_changes_since_metadata_upload_scheduled: 0,
    2429           20 :                         visible_remote_consistent_lsn: initialized
    2430           20 :                             .visible_remote_consistent_lsn
    2431           20 :                             .clone(),
    2432           20 :                         inprogress_tasks: HashMap::default(),
    2433           20 :                         queued_operations: VecDeque::default(),
    2434           20 :                         #[cfg(feature = "testing")]
    2435           20 :                         dangling_files: HashMap::default(),
    2436           20 :                         blocked_deletions: Vec::new(),
    2437           20 :                         shutting_down: false,
    2438           20 :                         shutdown_ready: Arc::new(tokio::sync::Semaphore::new(0)),
    2439           20 :                         recently_deleted: HashSet::new(),
    2440           20 :                     };
    2441           20 : 
    2442           20 :                     let upload_queue = std::mem::replace(
    2443           20 :                         &mut **guard,
    2444           20 :                         UploadQueue::Stopped(UploadQueueStopped::Deletable(
    2445           20 :                             UploadQueueStoppedDeletable {
    2446           20 :                                 upload_queue_for_deletion,
    2447           20 :                                 deleted_at: SetDeletedFlagProgress::NotRunning,
    2448           20 :                             },
    2449           20 :                         )),
    2450           20 :                     );
    2451           20 :                     if let UploadQueue::Initialized(qi) = upload_queue {
    2452           20 :                         qi
    2453              :                     } else {
    2454            0 :                         unreachable!("we checked in the match above that it is Initialized");
    2455              :                     }
    2456              :                 };
    2457              : 
    2458              :                 // We don't need to do anything here for in-progress tasks. They will finish
    2459              :                 // on their own, decrement the unfinished-task counter themselves, and observe
    2460              :                 // that the queue is Stopped.
    2461           20 :                 drop(qi.inprogress_tasks);
    2462              : 
    2463              :                 // Tear down queued ops
    2464           20 :                 for op in qi.queued_operations.into_iter() {
    2465           16 :                     self.metric_end(&op);
    2466           16 :                     // Dropping UploadOp::Barrier() here will make wait_completion() return with an Err()
    2467           16 :                     // which is exactly what we want to happen.
    2468           16 :                     drop(op);
    2469           16 :                 }
    2470              :             }
    2471              :         }
    2472           36 :     }
    2473              : 
    2474              :     /// Returns an accessor which will hold the UploadQueue mutex for accessing the upload queue
    2475              :     /// externally to RemoteTimelineClient.
    2476            0 :     pub(crate) fn initialized_upload_queue(
    2477            0 :         &self,
    2478            0 :     ) -> Result<UploadQueueAccessor<'_>, NotInitialized> {
    2479            0 :         let mut inner = self.upload_queue.lock().unwrap();
    2480            0 :         inner.initialized_mut()?;
    2481            0 :         Ok(UploadQueueAccessor { inner })
    2482            0 :     }
    2483              : 
    2484           16 :     pub(crate) fn no_pending_work(&self) -> bool {
    2485           16 :         let inner = self.upload_queue.lock().unwrap();
    2486           16 :         match &*inner {
    2487              :             UploadQueue::Uninitialized
    2488            0 :             | UploadQueue::Stopped(UploadQueueStopped::Uninitialized) => true,
    2489           16 :             UploadQueue::Stopped(UploadQueueStopped::Deletable(x)) => {
    2490           16 :                 x.upload_queue_for_deletion.no_pending_work()
    2491              :             }
    2492            0 :             UploadQueue::Initialized(x) => x.no_pending_work(),
    2493              :         }
    2494           16 :     }
    2495              : 
    2496              :     /// 'foreign' in the sense that it does not belong to this tenant shard.  This method
    2497              :     /// is used during GC for other shards to get the index of shard zero.
    2498            0 :     pub(crate) async fn download_foreign_index(
    2499            0 :         &self,
    2500            0 :         shard_number: ShardNumber,
    2501            0 :         cancel: &CancellationToken,
    2502            0 :     ) -> Result<(IndexPart, Generation, std::time::SystemTime), DownloadError> {
    2503            0 :         let foreign_shard_id = TenantShardId {
    2504            0 :             shard_number,
    2505            0 :             shard_count: self.tenant_shard_id.shard_count,
    2506            0 :             tenant_id: self.tenant_shard_id.tenant_id,
    2507            0 :         };
    2508            0 :         download_index_part(
    2509            0 :             &self.storage_impl,
    2510            0 :             &foreign_shard_id,
    2511            0 :             &self.timeline_id,
    2512            0 :             Generation::MAX,
    2513            0 :             cancel,
    2514            0 :         )
    2515            0 :         .await
    2516            0 :     }
    2517              : }
    2518              : 
    2519              : pub(crate) struct UploadQueueAccessor<'a> {
    2520              :     inner: std::sync::MutexGuard<'a, UploadQueue>,
    2521              : }
    2522              : 
    2523              : impl UploadQueueAccessor<'_> {
    2524            0 :     pub(crate) fn latest_uploaded_index_part(&self) -> &IndexPart {
    2525            0 :         match &*self.inner {
    2526            0 :             UploadQueue::Initialized(x) => &x.clean.0,
    2527              :             UploadQueue::Uninitialized | UploadQueue::Stopped(_) => {
    2528            0 :                 unreachable!("checked before constructing")
    2529              :             }
    2530              :         }
    2531            0 :     }
    2532              : }
    2533              : 
    2534            0 : pub fn remote_tenant_path(tenant_shard_id: &TenantShardId) -> RemotePath {
    2535            0 :     let path = format!("tenants/{tenant_shard_id}");
    2536            0 :     RemotePath::from_string(&path).expect("Failed to construct path")
    2537            0 : }
    2538              : 
    2539         1360 : pub fn remote_tenant_manifest_path(
    2540         1360 :     tenant_shard_id: &TenantShardId,
    2541         1360 :     generation: Generation,
    2542         1360 : ) -> RemotePath {
    2543         1360 :     let path = format!(
    2544         1360 :         "tenants/{tenant_shard_id}/tenant-manifest{}.json",
    2545         1360 :         generation.get_suffix()
    2546         1360 :     );
    2547         1360 :     RemotePath::from_string(&path).expect("Failed to construct path")
    2548         1360 : }
    2549              : 
    2550              : /// Prefix to all generations' manifest objects in a tenant shard
    2551          452 : pub fn remote_tenant_manifest_prefix(tenant_shard_id: &TenantShardId) -> RemotePath {
    2552          452 :     let path = format!("tenants/{tenant_shard_id}/tenant-manifest",);
    2553          452 :     RemotePath::from_string(&path).expect("Failed to construct path")
    2554          452 : }
    2555              : 
    2556          512 : pub fn remote_timelines_path(tenant_shard_id: &TenantShardId) -> RemotePath {
    2557          512 :     let path = format!("tenants/{tenant_shard_id}/{TIMELINES_SEGMENT_NAME}");
    2558          512 :     RemotePath::from_string(&path).expect("Failed to construct path")
    2559          512 : }
    2560              : 
    2561            0 : fn remote_timelines_path_unsharded(tenant_id: &TenantId) -> RemotePath {
    2562            0 :     let path = format!("tenants/{tenant_id}/{TIMELINES_SEGMENT_NAME}");
    2563            0 :     RemotePath::from_string(&path).expect("Failed to construct path")
    2564            0 : }
    2565              : 
    2566           60 : pub fn remote_timeline_path(
    2567           60 :     tenant_shard_id: &TenantShardId,
    2568           60 :     timeline_id: &TimelineId,
    2569           60 : ) -> RemotePath {
    2570           60 :     remote_timelines_path(tenant_shard_id).join(Utf8Path::new(&timeline_id.to_string()))
    2571           60 : }
    2572              : 
    2573              : /// Obtains the path of the given Layer in the remote
    2574              : ///
    2575              : /// Note that the shard component of a remote layer path is _not_ always the same
    2576              : /// as in the TenantShardId of the caller: tenants may reference layers from a different
    2577              : /// ShardIndex.  Use the ShardIndex from the layer's metadata.
    2578         3989 : pub fn remote_layer_path(
    2579         3989 :     tenant_id: &TenantId,
    2580         3989 :     timeline_id: &TimelineId,
    2581         3989 :     shard: ShardIndex,
    2582         3989 :     layer_file_name: &LayerName,
    2583         3989 :     generation: Generation,
    2584         3989 : ) -> RemotePath {
    2585         3989 :     // Generation-aware key format
    2586         3989 :     let path = format!(
    2587         3989 :         "tenants/{tenant_id}{0}/{TIMELINES_SEGMENT_NAME}/{timeline_id}/{1}{2}",
    2588         3989 :         shard.get_suffix(),
    2589         3989 :         layer_file_name,
    2590         3989 :         generation.get_suffix()
    2591         3989 :     );
    2592         3989 : 
    2593         3989 :     RemotePath::from_string(&path).expect("Failed to construct path")
    2594         3989 : }
    2595              : 
    2596              : /// Returns true if a and b have the same layer path within a tenant/timeline. This is essentially
    2597              : /// remote_layer_path(a) == remote_layer_path(b) without the string allocations.
    2598              : ///
    2599              : /// TODO: there should be a variant of LayerName for the physical path that contains information
    2600              : /// about the shard and generation, such that this could be replaced by a simple comparison.
    2601      2351919 : pub fn is_same_remote_layer_path(
    2602      2351919 :     aname: &LayerName,
    2603      2351919 :     ameta: &LayerFileMetadata,
    2604      2351919 :     bname: &LayerName,
    2605      2351919 :     bmeta: &LayerFileMetadata,
    2606      2351919 : ) -> bool {
    2607      2351919 :     // NB: don't assert remote_layer_path(a) == remote_layer_path(b); too expensive even for debug.
    2608      2351919 :     aname == bname && ameta.shard == bmeta.shard && ameta.generation == bmeta.generation
    2609      2351919 : }
    2610              : 
    2611            8 : pub fn remote_initdb_archive_path(tenant_id: &TenantId, timeline_id: &TimelineId) -> RemotePath {
    2612            8 :     RemotePath::from_string(&format!(
    2613            8 :         "tenants/{tenant_id}/{TIMELINES_SEGMENT_NAME}/{timeline_id}/{INITDB_PATH}"
    2614            8 :     ))
    2615            8 :     .expect("Failed to construct path")
    2616            8 : }
    2617              : 
    2618            4 : pub fn remote_initdb_preserved_archive_path(
    2619            4 :     tenant_id: &TenantId,
    2620            4 :     timeline_id: &TimelineId,
    2621            4 : ) -> RemotePath {
    2622            4 :     RemotePath::from_string(&format!(
    2623            4 :         "tenants/{tenant_id}/{TIMELINES_SEGMENT_NAME}/{timeline_id}/{INITDB_PRESERVED_PATH}"
    2624            4 :     ))
    2625            4 :     .expect("Failed to construct path")
    2626            4 : }
    2627              : 
    2628         3130 : pub fn remote_index_path(
    2629         3130 :     tenant_shard_id: &TenantShardId,
    2630         3130 :     timeline_id: &TimelineId,
    2631         3130 :     generation: Generation,
    2632         3130 : ) -> RemotePath {
    2633         3130 :     RemotePath::from_string(&format!(
    2634         3130 :         "tenants/{tenant_shard_id}/{TIMELINES_SEGMENT_NAME}/{timeline_id}/{0}{1}",
    2635         3130 :         IndexPart::FILE_NAME,
    2636         3130 :         generation.get_suffix()
    2637         3130 :     ))
    2638         3130 :     .expect("Failed to construct path")
    2639         3130 : }
    2640              : 
    2641            0 : pub(crate) fn remote_heatmap_path(tenant_shard_id: &TenantShardId) -> RemotePath {
    2642            0 :     RemotePath::from_string(&format!(
    2643            0 :         "tenants/{tenant_shard_id}/{TENANT_HEATMAP_BASENAME}"
    2644            0 :     ))
    2645            0 :     .expect("Failed to construct path")
    2646            0 : }
    2647              : 
    2648              : /// Given the key of an index, parse out the generation part of the name
    2649           36 : pub fn parse_remote_index_path(path: RemotePath) -> Option<Generation> {
    2650           36 :     let file_name = match path.get_path().file_name() {
    2651           36 :         Some(f) => f,
    2652              :         None => {
    2653              :             // Unexpected: we should be seeing index_part.json paths only
    2654            0 :             tracing::warn!("Malformed index key {}", path);
    2655            0 :             return None;
    2656              :         }
    2657              :     };
    2658              : 
    2659           36 :     match file_name.split_once('-') {
    2660           24 :         Some((_, gen_suffix)) => Generation::parse_suffix(gen_suffix),
    2661           12 :         None => None,
    2662              :     }
    2663           36 : }
    2664              : 
    2665              : /// Given the key of a tenant manifest, parse out the generation number
    2666            0 : pub fn parse_remote_tenant_manifest_path(path: RemotePath) -> Option<Generation> {
    2667              :     static RE: OnceLock<Regex> = OnceLock::new();
    2668            0 :     let re = RE.get_or_init(|| Regex::new(r".*tenant-manifest-([0-9a-f]{8}).json").unwrap());
    2669            0 :     re.captures(path.get_path().as_str())
    2670            0 :         .and_then(|c| c.get(1))
    2671            0 :         .and_then(|m| Generation::parse_suffix(m.as_str()))
    2672            0 : }
    2673              : 
    2674              : #[cfg(test)]
    2675              : mod tests {
    2676              :     use std::collections::HashSet;
    2677              : 
    2678              :     use super::*;
    2679              :     use crate::DEFAULT_PG_VERSION;
    2680              :     use crate::context::RequestContext;
    2681              :     use crate::tenant::config::AttachmentMode;
    2682              :     use crate::tenant::harness::{TIMELINE_ID, TenantHarness};
    2683              :     use crate::tenant::storage_layer::layer::local_layer_path;
    2684              :     use crate::tenant::{Tenant, Timeline};
    2685              : 
    2686           16 :     pub(super) fn dummy_contents(name: &str) -> Vec<u8> {
    2687           16 :         format!("contents for {name}").into()
    2688           16 :     }
    2689              : 
    2690            4 :     pub(super) fn dummy_metadata(disk_consistent_lsn: Lsn) -> TimelineMetadata {
    2691            4 :         let metadata = TimelineMetadata::new(
    2692            4 :             disk_consistent_lsn,
    2693            4 :             None,
    2694            4 :             None,
    2695            4 :             Lsn(0),
    2696            4 :             Lsn(0),
    2697            4 :             Lsn(0),
    2698            4 :             // Any version will do
    2699            4 :             // but it should be consistent with the one in the tests
    2700            4 :             crate::DEFAULT_PG_VERSION,
    2701            4 :         );
    2702            4 : 
    2703            4 :         // go through serialize + deserialize to fix the header, including checksum
    2704            4 :         TimelineMetadata::from_bytes(&metadata.to_bytes().unwrap()).unwrap()
    2705            4 :     }
    2706              : 
    2707            4 :     fn assert_file_list(a: &HashSet<LayerName>, b: &[&str]) {
    2708           12 :         let mut avec: Vec<String> = a.iter().map(|x| x.to_string()).collect();
    2709            4 :         avec.sort();
    2710            4 : 
    2711            4 :         let mut bvec = b.to_vec();
    2712            4 :         bvec.sort_unstable();
    2713            4 : 
    2714            4 :         assert_eq!(avec, bvec);
    2715            4 :     }
    2716              : 
    2717            8 :     fn assert_remote_files(expected: &[&str], remote_path: &Utf8Path, generation: Generation) {
    2718            8 :         let mut expected: Vec<String> = expected
    2719            8 :             .iter()
    2720           32 :             .map(|x| format!("{}{}", x, generation.get_suffix()))
    2721            8 :             .collect();
    2722            8 :         expected.sort();
    2723            8 : 
    2724            8 :         let mut found: Vec<String> = Vec::new();
    2725           32 :         for entry in std::fs::read_dir(remote_path).unwrap().flatten() {
    2726           32 :             let entry_name = entry.file_name();
    2727           32 :             let fname = entry_name.to_str().unwrap();
    2728           32 :             found.push(String::from(fname));
    2729           32 :         }
    2730            8 :         found.sort();
    2731            8 : 
    2732            8 :         assert_eq!(found, expected);
    2733            8 :     }
    2734              : 
    2735              :     struct TestSetup {
    2736              :         harness: TenantHarness,
    2737              :         tenant: Arc<Tenant>,
    2738              :         timeline: Arc<Timeline>,
    2739              :         tenant_ctx: RequestContext,
    2740              :     }
    2741              : 
    2742              :     impl TestSetup {
    2743           16 :         async fn new(test_name: &str) -> anyhow::Result<Self> {
    2744           16 :             let test_name = Box::leak(Box::new(format!("remote_timeline_client__{test_name}")));
    2745           16 :             let harness = TenantHarness::create(test_name).await?;
    2746           16 :             let (tenant, ctx) = harness.load().await;
    2747              : 
    2748           16 :             let timeline = tenant
    2749           16 :                 .create_test_timeline(TIMELINE_ID, Lsn(8), DEFAULT_PG_VERSION, &ctx)
    2750           16 :                 .await?;
    2751              : 
    2752           16 :             Ok(Self {
    2753           16 :                 harness,
    2754           16 :                 tenant,
    2755           16 :                 timeline,
    2756           16 :                 tenant_ctx: ctx,
    2757           16 :             })
    2758           16 :         }
    2759              : 
    2760              :         /// Construct a RemoteTimelineClient in an arbitrary generation
    2761           20 :         fn build_client(&self, generation: Generation) -> Arc<RemoteTimelineClient> {
    2762           20 :             let location_conf = AttachedLocationConfig {
    2763           20 :                 generation,
    2764           20 :                 attach_mode: AttachmentMode::Single,
    2765           20 :             };
    2766           20 :             Arc::new(RemoteTimelineClient {
    2767           20 :                 conf: self.harness.conf,
    2768           20 :                 runtime: tokio::runtime::Handle::current(),
    2769           20 :                 tenant_shard_id: self.harness.tenant_shard_id,
    2770           20 :                 timeline_id: TIMELINE_ID,
    2771           20 :                 generation,
    2772           20 :                 storage_impl: self.harness.remote_storage.clone(),
    2773           20 :                 deletion_queue_client: self.harness.deletion_queue.new_client(),
    2774           20 :                 upload_queue: Mutex::new(UploadQueue::Uninitialized),
    2775           20 :                 metrics: Arc::new(RemoteTimelineClientMetrics::new(
    2776           20 :                     &self.harness.tenant_shard_id,
    2777           20 :                     &TIMELINE_ID,
    2778           20 :                 )),
    2779           20 :                 config: std::sync::RwLock::new(RemoteTimelineClientConfig::from(&location_conf)),
    2780           20 :                 cancel: CancellationToken::new(),
    2781           20 :             })
    2782           20 :         }
    2783              : 
    2784              :         /// A tracing::Span that satisfies remote_timeline_client methods that assert tenant_id
    2785              :         /// and timeline_id are present.
    2786           12 :         fn span(&self) -> tracing::Span {
    2787           12 :             tracing::info_span!(
    2788              :                 "test",
    2789              :                 tenant_id = %self.harness.tenant_shard_id.tenant_id,
    2790            0 :                 shard_id = %self.harness.tenant_shard_id.shard_slug(),
    2791              :                 timeline_id = %TIMELINE_ID
    2792              :             )
    2793           12 :         }
    2794              :     }
    2795              : 
    2796              :     // Test scheduling
    2797              :     #[tokio::test]
    2798            4 :     async fn upload_scheduling() {
    2799            4 :         // Test outline:
    2800            4 :         //
    2801            4 :         // Schedule upload of a bunch of layers. Check that they are started immediately, not queued
    2802            4 :         // Schedule upload of index. Check that it is queued
    2803            4 :         // let the layer file uploads finish. Check that the index-upload is now started
    2804            4 :         // let the index-upload finish.
    2805            4 :         //
    2806            4 :         // Download back the index.json. Check that the list of files is correct
    2807            4 :         //
    2808            4 :         // Schedule upload. Schedule deletion. Check that the deletion is queued
    2809            4 :         // let upload finish. Check that deletion is now started
    2810            4 :         // Schedule another deletion. Check that it's launched immediately.
    2811            4 :         // Schedule index upload. Check that it's queued
    2812            4 : 
    2813            4 :         let test_setup = TestSetup::new("upload_scheduling").await.unwrap();
    2814            4 :         let span = test_setup.span();
    2815            4 :         let _guard = span.enter();
    2816            4 : 
    2817            4 :         let TestSetup {
    2818            4 :             harness,
    2819            4 :             tenant: _tenant,
    2820            4 :             timeline,
    2821            4 :             tenant_ctx: _tenant_ctx,
    2822            4 :         } = test_setup;
    2823            4 : 
    2824            4 :         let client = &timeline.remote_client;
    2825            4 : 
    2826            4 :         // Download back the index.json, and check that the list of files is correct
    2827            4 :         let initial_index_part = match client
    2828            4 :             .download_index_file(&CancellationToken::new())
    2829            4 :             .await
    2830            4 :             .unwrap()
    2831            4 :         {
    2832            4 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2833            4 :             MaybeDeletedIndexPart::Deleted(_) => panic!("unexpectedly got deleted index part"),
    2834            4 :         };
    2835            4 :         let initial_layers = initial_index_part
    2836            4 :             .layer_metadata
    2837            4 :             .keys()
    2838            4 :             .map(|f| f.to_owned())
    2839            4 :             .collect::<HashSet<LayerName>>();
    2840            4 :         let initial_layer = {
    2841            4 :             assert!(initial_layers.len() == 1);
    2842            4 :             initial_layers.into_iter().next().unwrap()
    2843            4 :         };
    2844            4 : 
    2845            4 :         let timeline_path = harness.timeline_path(&TIMELINE_ID);
    2846            4 : 
    2847            4 :         println!("workdir: {}", harness.conf.workdir);
    2848            4 : 
    2849            4 :         let remote_timeline_dir = harness
    2850            4 :             .remote_fs_dir
    2851            4 :             .join(timeline_path.strip_prefix(&harness.conf.workdir).unwrap());
    2852            4 :         println!("remote_timeline_dir: {remote_timeline_dir}");
    2853            4 : 
    2854            4 :         let generation = harness.generation;
    2855            4 :         let shard = harness.shard;
    2856            4 : 
    2857            4 :         // Create a couple of dummy files,  schedule upload for them
    2858            4 : 
    2859            4 :         let layers = [
    2860            4 :             ("000000000000000000000000000000000000-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__00000000016B59D8-00000000016B5A51".parse().unwrap(), dummy_contents("foo")),
    2861            4 :             ("000000000000000000000000000000000000-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__00000000016B59D9-00000000016B5A52".parse().unwrap(), dummy_contents("bar")),
    2862            4 :             ("000000000000000000000000000000000000-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__00000000016B59DA-00000000016B5A53".parse().unwrap(), dummy_contents("baz"))
    2863            4 :         ]
    2864            4 :         .into_iter()
    2865           12 :         .map(|(name, contents): (LayerName, Vec<u8>)| {
    2866           12 : 
    2867           12 :             let local_path = local_layer_path(
    2868           12 :                 harness.conf,
    2869           12 :                 &timeline.tenant_shard_id,
    2870           12 :                 &timeline.timeline_id,
    2871           12 :                 &name,
    2872           12 :                 &generation,
    2873           12 :             );
    2874           12 :             std::fs::write(&local_path, &contents).unwrap();
    2875           12 : 
    2876           12 :             Layer::for_resident(
    2877           12 :                 harness.conf,
    2878           12 :                 &timeline,
    2879           12 :                 local_path,
    2880           12 :                 name,
    2881           12 :                 LayerFileMetadata::new(contents.len() as u64, generation, shard),
    2882           12 :             )
    2883           12 :         }).collect::<Vec<_>>();
    2884            4 : 
    2885            4 :         client
    2886            4 :             .schedule_layer_file_upload(layers[0].clone())
    2887            4 :             .unwrap();
    2888            4 :         client
    2889            4 :             .schedule_layer_file_upload(layers[1].clone())
    2890            4 :             .unwrap();
    2891            4 : 
    2892            4 :         // Check that they are started immediately, not queued
    2893            4 :         //
    2894            4 :         // this works because we running within block_on, so any futures are now queued up until
    2895            4 :         // our next await point.
    2896            4 :         {
    2897            4 :             let mut guard = client.upload_queue.lock().unwrap();
    2898            4 :             let upload_queue = guard.initialized_mut().unwrap();
    2899            4 :             assert!(upload_queue.queued_operations.is_empty());
    2900            4 :             assert_eq!(upload_queue.inprogress_tasks.len(), 2);
    2901            4 :             assert_eq!(upload_queue.num_inprogress_layer_uploads(), 2);
    2902            4 : 
    2903            4 :             // also check that `latest_file_changes` was updated
    2904            4 :             assert!(upload_queue.latest_files_changes_since_metadata_upload_scheduled == 2);
    2905            4 :         }
    2906            4 : 
    2907            4 :         // Schedule upload of index. Check that it is queued
    2908            4 :         let metadata = dummy_metadata(Lsn(0x20));
    2909            4 :         client
    2910            4 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    2911            4 :             .unwrap();
    2912            4 :         {
    2913            4 :             let mut guard = client.upload_queue.lock().unwrap();
    2914            4 :             let upload_queue = guard.initialized_mut().unwrap();
    2915            4 :             assert!(upload_queue.queued_operations.len() == 1);
    2916            4 :             assert!(upload_queue.latest_files_changes_since_metadata_upload_scheduled == 0);
    2917            4 :         }
    2918            4 : 
    2919            4 :         // Wait for the uploads to finish
    2920            4 :         client.wait_completion().await.unwrap();
    2921            4 :         {
    2922            4 :             let mut guard = client.upload_queue.lock().unwrap();
    2923            4 :             let upload_queue = guard.initialized_mut().unwrap();
    2924            4 : 
    2925            4 :             assert!(upload_queue.queued_operations.is_empty());
    2926            4 :             assert!(upload_queue.inprogress_tasks.is_empty());
    2927            4 :         }
    2928            4 : 
    2929            4 :         // Download back the index.json, and check that the list of files is correct
    2930            4 :         let index_part = match client
    2931            4 :             .download_index_file(&CancellationToken::new())
    2932            4 :             .await
    2933            4 :             .unwrap()
    2934            4 :         {
    2935            4 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2936            4 :             MaybeDeletedIndexPart::Deleted(_) => panic!("unexpectedly got deleted index part"),
    2937            4 :         };
    2938            4 : 
    2939            4 :         assert_file_list(
    2940            4 :             &index_part
    2941            4 :                 .layer_metadata
    2942            4 :                 .keys()
    2943           12 :                 .map(|f| f.to_owned())
    2944            4 :                 .collect(),
    2945            4 :             &[
    2946            4 :                 &initial_layer.to_string(),
    2947            4 :                 &layers[0].layer_desc().layer_name().to_string(),
    2948            4 :                 &layers[1].layer_desc().layer_name().to_string(),
    2949            4 :             ],
    2950            4 :         );
    2951            4 :         assert_eq!(index_part.metadata, metadata);
    2952            4 : 
    2953            4 :         // Schedule upload and then a deletion. Check that the deletion is queued
    2954            4 :         client
    2955            4 :             .schedule_layer_file_upload(layers[2].clone())
    2956            4 :             .unwrap();
    2957            4 : 
    2958            4 :         // this is no longer consistent with how deletion works with Layer::drop, but in this test
    2959            4 :         // keep using schedule_layer_file_deletion because we don't have a way to wait for the
    2960            4 :         // spawn_blocking started by the drop.
    2961            4 :         client
    2962            4 :             .schedule_layer_file_deletion(&[layers[0].layer_desc().layer_name()])
    2963            4 :             .unwrap();
    2964            4 :         {
    2965            4 :             let mut guard = client.upload_queue.lock().unwrap();
    2966            4 :             let upload_queue = guard.initialized_mut().unwrap();
    2967            4 : 
    2968            4 :             // Deletion schedules upload of the index file, and the file deletion itself
    2969            4 :             assert_eq!(upload_queue.queued_operations.len(), 2);
    2970            4 :             assert_eq!(upload_queue.inprogress_tasks.len(), 1);
    2971            4 :             assert_eq!(upload_queue.num_inprogress_layer_uploads(), 1);
    2972            4 :             assert_eq!(upload_queue.num_inprogress_deletions(), 0);
    2973            4 :             assert_eq!(
    2974            4 :                 upload_queue.latest_files_changes_since_metadata_upload_scheduled,
    2975            4 :                 0
    2976            4 :             );
    2977            4 :         }
    2978            4 :         assert_remote_files(
    2979            4 :             &[
    2980            4 :                 &initial_layer.to_string(),
    2981            4 :                 &layers[0].layer_desc().layer_name().to_string(),
    2982            4 :                 &layers[1].layer_desc().layer_name().to_string(),
    2983            4 :                 "index_part.json",
    2984            4 :             ],
    2985            4 :             &remote_timeline_dir,
    2986            4 :             generation,
    2987            4 :         );
    2988            4 : 
    2989            4 :         // Finish them
    2990            4 :         client.wait_completion().await.unwrap();
    2991            4 :         harness.deletion_queue.pump().await;
    2992            4 : 
    2993            4 :         assert_remote_files(
    2994            4 :             &[
    2995            4 :                 &initial_layer.to_string(),
    2996            4 :                 &layers[1].layer_desc().layer_name().to_string(),
    2997            4 :                 &layers[2].layer_desc().layer_name().to_string(),
    2998            4 :                 "index_part.json",
    2999            4 :             ],
    3000            4 :             &remote_timeline_dir,
    3001            4 :             generation,
    3002            4 :         );
    3003            4 :     }
    3004              : 
    3005              :     #[tokio::test]
    3006            4 :     async fn bytes_unfinished_gauge_for_layer_file_uploads() {
    3007            4 :         // Setup
    3008            4 : 
    3009            4 :         let TestSetup {
    3010            4 :             harness,
    3011            4 :             tenant: _tenant,
    3012            4 :             timeline,
    3013            4 :             ..
    3014            4 :         } = TestSetup::new("metrics").await.unwrap();
    3015            4 :         let client = &timeline.remote_client;
    3016            4 : 
    3017            4 :         let layer_file_name_1: LayerName = "000000000000000000000000000000000000-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__00000000016B59D8-00000000016B5A51".parse().unwrap();
    3018            4 :         let local_path = local_layer_path(
    3019            4 :             harness.conf,
    3020            4 :             &timeline.tenant_shard_id,
    3021            4 :             &timeline.timeline_id,
    3022            4 :             &layer_file_name_1,
    3023            4 :             &harness.generation,
    3024            4 :         );
    3025            4 :         let content_1 = dummy_contents("foo");
    3026            4 :         std::fs::write(&local_path, &content_1).unwrap();
    3027            4 : 
    3028            4 :         let layer_file_1 = Layer::for_resident(
    3029            4 :             harness.conf,
    3030            4 :             &timeline,
    3031            4 :             local_path,
    3032            4 :             layer_file_name_1.clone(),
    3033            4 :             LayerFileMetadata::new(content_1.len() as u64, harness.generation, harness.shard),
    3034            4 :         );
    3035            4 : 
    3036            4 :         #[derive(Debug, PartialEq, Clone, Copy)]
    3037            4 :         struct BytesStartedFinished {
    3038            4 :             started: Option<usize>,
    3039            4 :             finished: Option<usize>,
    3040            4 :         }
    3041            4 :         impl std::ops::Add for BytesStartedFinished {
    3042            4 :             type Output = Self;
    3043            8 :             fn add(self, rhs: Self) -> Self::Output {
    3044            8 :                 Self {
    3045            8 :                     started: self.started.map(|v| v + rhs.started.unwrap_or(0)),
    3046            8 :                     finished: self.finished.map(|v| v + rhs.finished.unwrap_or(0)),
    3047            8 :                 }
    3048            8 :             }
    3049            4 :         }
    3050           12 :         let get_bytes_started_stopped = || {
    3051           12 :             let started = client
    3052           12 :                 .metrics
    3053           12 :                 .get_bytes_started_counter_value(&RemoteOpFileKind::Layer, &RemoteOpKind::Upload)
    3054           12 :                 .map(|v| v.try_into().unwrap());
    3055           12 :             let stopped = client
    3056           12 :                 .metrics
    3057           12 :                 .get_bytes_finished_counter_value(&RemoteOpFileKind::Layer, &RemoteOpKind::Upload)
    3058           12 :                 .map(|v| v.try_into().unwrap());
    3059           12 :             BytesStartedFinished {
    3060           12 :                 started,
    3061           12 :                 finished: stopped,
    3062           12 :             }
    3063           12 :         };
    3064            4 : 
    3065            4 :         // Test
    3066            4 :         tracing::info!("now doing actual test");
    3067            4 : 
    3068            4 :         let actual_a = get_bytes_started_stopped();
    3069            4 : 
    3070            4 :         client
    3071            4 :             .schedule_layer_file_upload(layer_file_1.clone())
    3072            4 :             .unwrap();
    3073            4 : 
    3074            4 :         let actual_b = get_bytes_started_stopped();
    3075            4 : 
    3076            4 :         client.wait_completion().await.unwrap();
    3077            4 : 
    3078            4 :         let actual_c = get_bytes_started_stopped();
    3079            4 : 
    3080            4 :         // Validate
    3081            4 : 
    3082            4 :         let expected_b = actual_a
    3083            4 :             + BytesStartedFinished {
    3084            4 :                 started: Some(content_1.len()),
    3085            4 :                 // assert that the _finished metric is created eagerly so that subtractions work on first sample
    3086            4 :                 finished: Some(0),
    3087            4 :             };
    3088            4 :         assert_eq!(actual_b, expected_b);
    3089            4 : 
    3090            4 :         let expected_c = actual_a
    3091            4 :             + BytesStartedFinished {
    3092            4 :                 started: Some(content_1.len()),
    3093            4 :                 finished: Some(content_1.len()),
    3094            4 :             };
    3095            4 :         assert_eq!(actual_c, expected_c);
    3096            4 :     }
    3097              : 
    3098           24 :     async fn inject_index_part(test_state: &TestSetup, generation: Generation) -> IndexPart {
    3099           24 :         // An empty IndexPart, just sufficient to ensure deserialization will succeed
    3100           24 :         let example_index_part = IndexPart::example();
    3101           24 : 
    3102           24 :         let index_part_bytes = serde_json::to_vec(&example_index_part).unwrap();
    3103           24 : 
    3104           24 :         let index_path = test_state.harness.remote_fs_dir.join(
    3105           24 :             remote_index_path(
    3106           24 :                 &test_state.harness.tenant_shard_id,
    3107           24 :                 &TIMELINE_ID,
    3108           24 :                 generation,
    3109           24 :             )
    3110           24 :             .get_path(),
    3111           24 :         );
    3112           24 : 
    3113           24 :         std::fs::create_dir_all(index_path.parent().unwrap())
    3114           24 :             .expect("creating test dir should work");
    3115           24 : 
    3116           24 :         eprintln!("Writing {index_path}");
    3117           24 :         std::fs::write(&index_path, index_part_bytes).unwrap();
    3118           24 :         example_index_part
    3119           24 :     }
    3120              : 
    3121              :     /// Assert that when a RemoteTimelineclient in generation `get_generation` fetches its
    3122              :     /// index, the IndexPart returned is equal to `expected`
    3123           20 :     async fn assert_got_index_part(
    3124           20 :         test_state: &TestSetup,
    3125           20 :         get_generation: Generation,
    3126           20 :         expected: &IndexPart,
    3127           20 :     ) {
    3128           20 :         let client = test_state.build_client(get_generation);
    3129              : 
    3130           20 :         let download_r = client
    3131           20 :             .download_index_file(&CancellationToken::new())
    3132           20 :             .await
    3133           20 :             .expect("download should always succeed");
    3134           20 :         assert!(matches!(download_r, MaybeDeletedIndexPart::IndexPart(_)));
    3135           20 :         match download_r {
    3136           20 :             MaybeDeletedIndexPart::IndexPart(index_part) => {
    3137           20 :                 assert_eq!(&index_part, expected);
    3138              :             }
    3139            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => panic!("Test doesn't set deleted_at"),
    3140              :         }
    3141           20 :     }
    3142              : 
    3143              :     #[tokio::test]
    3144            4 :     async fn index_part_download_simple() -> anyhow::Result<()> {
    3145            4 :         let test_state = TestSetup::new("index_part_download_simple").await.unwrap();
    3146            4 :         let span = test_state.span();
    3147            4 :         let _guard = span.enter();
    3148            4 : 
    3149            4 :         // Simple case: we are in generation N, load the index from generation N - 1
    3150            4 :         let generation_n = 5;
    3151            4 :         let injected = inject_index_part(&test_state, Generation::new(generation_n - 1)).await;
    3152            4 : 
    3153            4 :         assert_got_index_part(&test_state, Generation::new(generation_n), &injected).await;
    3154            4 : 
    3155            4 :         Ok(())
    3156            4 :     }
    3157              : 
    3158              :     #[tokio::test]
    3159            4 :     async fn index_part_download_ordering() -> anyhow::Result<()> {
    3160            4 :         let test_state = TestSetup::new("index_part_download_ordering")
    3161            4 :             .await
    3162            4 :             .unwrap();
    3163            4 : 
    3164            4 :         let span = test_state.span();
    3165            4 :         let _guard = span.enter();
    3166            4 : 
    3167            4 :         // A generation-less IndexPart exists in the bucket, we should find it
    3168            4 :         let generation_n = 5;
    3169            4 :         let injected_none = inject_index_part(&test_state, Generation::none()).await;
    3170            4 :         assert_got_index_part(&test_state, Generation::new(generation_n), &injected_none).await;
    3171            4 : 
    3172            4 :         // If a more recent-than-none generation exists, we should prefer to load that
    3173            4 :         let injected_1 = inject_index_part(&test_state, Generation::new(1)).await;
    3174            4 :         assert_got_index_part(&test_state, Generation::new(generation_n), &injected_1).await;
    3175            4 : 
    3176            4 :         // If a more-recent-than-me generation exists, we should ignore it.
    3177            4 :         let _injected_10 = inject_index_part(&test_state, Generation::new(10)).await;
    3178            4 :         assert_got_index_part(&test_state, Generation::new(generation_n), &injected_1).await;
    3179            4 : 
    3180            4 :         // If a directly previous generation exists, _and_ an index exists in my own
    3181            4 :         // generation, I should prefer my own generation.
    3182            4 :         let _injected_prev =
    3183            4 :             inject_index_part(&test_state, Generation::new(generation_n - 1)).await;
    3184            4 :         let injected_current = inject_index_part(&test_state, Generation::new(generation_n)).await;
    3185            4 :         assert_got_index_part(
    3186            4 :             &test_state,
    3187            4 :             Generation::new(generation_n),
    3188            4 :             &injected_current,
    3189            4 :         )
    3190            4 :         .await;
    3191            4 : 
    3192            4 :         Ok(())
    3193            4 :     }
    3194              : }
        

Generated by: LCOV version 2.1-beta