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

Generated by: LCOV version 2.1-beta