LCOV - code coverage report
Current view: top level - pageserver/src/tenant - remote_timeline_client.rs (source / functions) Coverage Total Hit
Test: 960803fca14b2e843c565dddf575f7017d250bc3.info Lines: 73.2 % 1654 1211
Test Date: 2024-06-22 23:41:44 Functions: 59.5 % 148 88

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

Generated by: LCOV version 2.1-beta