LCOV - code coverage report
Current view: top level - pageserver/src/tenant - remote_timeline_client.rs (source / functions) Coverage Total Hit
Test: b4ae4c4857f9ef3e144e982a35ee23bc84c71983.info Lines: 66.7 % 1802 1202
Test Date: 2024-10-22 22:13:45 Functions: 51.8 % 168 87

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

Generated by: LCOV version 2.1-beta