LCOV - code coverage report
Current view: top level - pageserver/src/tenant - remote_timeline_client.rs (source / functions) Coverage Total Hit
Test: 727bdccc1d7d53837da843959afb612f56da4e79.info Lines: 65.1 % 2046 1331
Test Date: 2025-01-30 15:18:43 Functions: 52.3 % 193 101

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

Generated by: LCOV version 2.1-beta