LCOV - code coverage report
Current view: top level - pageserver/src/tenant - remote_timeline_client.rs (source / functions) Coverage Total Hit
Test: b9728233c33232dfae45024a493738ef141ccd5d.info Lines: 65.5 % 2044 1338
Test Date: 2025-01-10 20:41:15 Functions: 53.2 % 188 100

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

Generated by: LCOV version 2.1-beta