LCOV - code coverage report
Current view: top level - pageserver/src/tenant - remote_timeline_client.rs (source / functions) Coverage Total Hit
Test: b9d67f908f91f00e353a27440ba89f642a869959.info Lines: 67.9 % 1858 1261
Test Date: 2024-11-19 21:44:13 Functions: 52.4 % 185 97

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

Generated by: LCOV version 2.1-beta