LCOV - code coverage report
Current view: top level - pageserver/src/tenant - remote_timeline_client.rs (source / functions) Coverage Total Hit
Test: 472031e0b71f3195f7f21b1f2b20de09fd07bb56.info Lines: 64.1 % 2142 1373
Test Date: 2025-05-26 10:37:33 Functions: 53.5 % 202 108

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

Generated by: LCOV version 2.1-beta