LCOV - code coverage report
Current view: top level - pageserver/src/tenant - remote_timeline_client.rs (source / functions) Coverage Total Hit
Test: 49aa928ec5b4b510172d8b5c6d154da28e70a46c.info Lines: 66.3 % 1843 1222
Test Date: 2024-11-13 18:23:39 Functions: 50.3 % 179 90

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

Generated by: LCOV version 2.1-beta