LCOV - code coverage report
Current view: top level - pageserver/src/tenant - remote_timeline_client.rs (source / functions) Coverage Total Hit
Test: 1e20c4f2b28aa592527961bb32170ebbd2c9172f.info Lines: 62.1 % 1848 1148
Test Date: 2025-07-16 12:29:03 Functions: 56.3 % 190 107

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

Generated by: LCOV version 2.1-beta