LCOV - code coverage report
Current view: top level - storage_controller/src - persistence.rs (source / functions) Coverage Total Hit
Test: 553e39c2773e5840c720c90d86e56f89a4330d43.info Lines: 0.4 % 1600 7
Test Date: 2025-06-13 20:01:21 Functions: 0.2 % 632 1

            Line data    Source code
       1              : pub(crate) mod split_state;
       2              : use std::collections::HashMap;
       3              : use std::io::Write;
       4              : use std::str::FromStr;
       5              : use std::sync::Arc;
       6              : use std::time::{Duration, Instant};
       7              : 
       8              : use diesel::deserialize::{FromSql, FromSqlRow};
       9              : use diesel::expression::AsExpression;
      10              : use diesel::pg::Pg;
      11              : use diesel::prelude::*;
      12              : use diesel::serialize::{IsNull, ToSql};
      13              : use diesel_async::async_connection_wrapper::AsyncConnectionWrapper;
      14              : use diesel_async::pooled_connection::bb8::Pool;
      15              : use diesel_async::pooled_connection::{AsyncDieselConnectionManager, ManagerConfig};
      16              : use diesel_async::{AsyncPgConnection, RunQueryDsl};
      17              : use diesel_migrations::{EmbeddedMigrations, embed_migrations};
      18              : use futures::FutureExt;
      19              : use futures::future::BoxFuture;
      20              : use itertools::Itertools;
      21              : use pageserver_api::controller_api::{
      22              :     AvailabilityZone, MetadataHealthRecord, NodeLifecycle, NodeSchedulingPolicy, PlacementPolicy,
      23              :     SafekeeperDescribeResponse, ShardSchedulingPolicy, SkSchedulingPolicy,
      24              : };
      25              : use pageserver_api::models::{ShardImportStatus, TenantConfig};
      26              : use pageserver_api::shard::{
      27              :     ShardConfigError, ShardCount, ShardIdentity, ShardNumber, ShardStripeSize, TenantShardId,
      28              : };
      29              : use rustls::client::WebPkiServerVerifier;
      30              : use rustls::client::danger::{ServerCertVerified, ServerCertVerifier};
      31              : use rustls::crypto::ring;
      32              : use scoped_futures::ScopedBoxFuture;
      33              : use serde::{Deserialize, Serialize};
      34              : use utils::generation::Generation;
      35              : use utils::id::{NodeId, TenantId, TimelineId};
      36              : use utils::lsn::Lsn;
      37              : 
      38              : use self::split_state::SplitState;
      39              : use crate::metrics::{
      40              :     DatabaseQueryErrorLabelGroup, DatabaseQueryLatencyLabelGroup, METRICS_REGISTRY,
      41              : };
      42              : use crate::node::Node;
      43              : use crate::timeline_import::{
      44              :     TimelineImport, TimelineImportUpdateError, TimelineImportUpdateFollowUp,
      45              : };
      46              : const MIGRATIONS: EmbeddedMigrations = embed_migrations!("./migrations");
      47              : 
      48              : /// ## What do we store?
      49              : ///
      50              : /// The storage controller service does not store most of its state durably.
      51              : ///
      52              : /// The essential things to store durably are:
      53              : /// - generation numbers, as these must always advance monotonically to ensure data safety.
      54              : /// - Tenant's PlacementPolicy and TenantConfig, as the source of truth for these is something external.
      55              : /// - Node's scheduling policies, as the source of truth for these is something external.
      56              : ///
      57              : /// Other things we store durably as an implementation detail:
      58              : /// - Node's host/port: this could be avoided it we made nodes emit a self-registering heartbeat,
      59              : ///   but it is operationally simpler to make this service the authority for which nodes
      60              : ///   it talks to.
      61              : ///
      62              : /// ## Performance/efficiency
      63              : ///
      64              : /// The storage controller service does not go via the database for most things: there are
      65              : /// a couple of places where we must, and where efficiency matters:
      66              : /// - Incrementing generation numbers: the Reconciler has to wait for this to complete
      67              : ///   before it can attach a tenant, so this acts as a bound on how fast things like
      68              : ///   failover can happen.
      69              : /// - Pageserver re-attach: we will increment many shards' generations when this happens,
      70              : ///   so it is important to avoid e.g. issuing O(N) queries.
      71              : ///
      72              : /// Database calls relating to nodes have low performance requirements, as they are very rarely
      73              : /// updated, and reads of nodes are always from memory, not the database.  We only require that
      74              : /// we can UPDATE a node's scheduling mode reasonably quickly to mark a bad node offline.
      75              : pub struct Persistence {
      76              :     connection_pool: Pool<AsyncPgConnection>,
      77              : }
      78              : 
      79              : /// Legacy format, for use in JSON compat objects in test environment
      80            0 : #[derive(Serialize, Deserialize)]
      81              : struct JsonPersistence {
      82              :     tenants: HashMap<TenantShardId, TenantShardPersistence>,
      83              : }
      84              : 
      85              : #[derive(thiserror::Error, Debug)]
      86              : pub(crate) enum DatabaseError {
      87              :     #[error(transparent)]
      88              :     Query(#[from] diesel::result::Error),
      89              :     #[error(transparent)]
      90              :     Connection(#[from] diesel::result::ConnectionError),
      91              :     #[error(transparent)]
      92              :     ConnectionPool(#[from] diesel_async::pooled_connection::bb8::RunError),
      93              :     #[error("Logical error: {0}")]
      94              :     Logical(String),
      95              :     #[error("Migration error: {0}")]
      96              :     Migration(String),
      97              : }
      98              : 
      99              : #[derive(measured::FixedCardinalityLabel, Copy, Clone)]
     100              : pub(crate) enum DatabaseOperation {
     101              :     InsertNode,
     102              :     UpdateNode,
     103              :     DeleteNode,
     104              :     ListNodes,
     105              :     ListTombstones,
     106              :     BeginShardSplit,
     107              :     CompleteShardSplit,
     108              :     AbortShardSplit,
     109              :     Detach,
     110              :     ReAttach,
     111              :     IncrementGeneration,
     112              :     TenantGenerations,
     113              :     ShardGenerations,
     114              :     ListTenantShards,
     115              :     LoadTenant,
     116              :     InsertTenantShards,
     117              :     UpdateTenantShard,
     118              :     DeleteTenant,
     119              :     UpdateTenantConfig,
     120              :     UpdateMetadataHealth,
     121              :     ListMetadataHealth,
     122              :     ListMetadataHealthUnhealthy,
     123              :     ListMetadataHealthOutdated,
     124              :     ListSafekeepers,
     125              :     GetLeader,
     126              :     UpdateLeader,
     127              :     SetPreferredAzs,
     128              :     InsertTimeline,
     129              :     GetTimeline,
     130              :     InsertTimelineReconcile,
     131              :     RemoveTimelineReconcile,
     132              :     ListTimelineReconcile,
     133              :     ListTimelineReconcileStartup,
     134              :     InsertTimelineImport,
     135              :     UpdateTimelineImport,
     136              :     DeleteTimelineImport,
     137              :     ListTimelineImports,
     138              :     IsTenantImportingTimeline,
     139              : }
     140              : 
     141              : #[must_use]
     142              : pub(crate) enum AbortShardSplitStatus {
     143              :     /// We aborted the split in the database by reverting to the parent shards
     144              :     Aborted,
     145              :     /// The split had already been persisted.
     146              :     Complete,
     147              : }
     148              : 
     149              : pub(crate) type DatabaseResult<T> = Result<T, DatabaseError>;
     150              : 
     151              : /// Some methods can operate on either a whole tenant or a single shard
     152              : #[derive(Clone)]
     153              : pub(crate) enum TenantFilter {
     154              :     Tenant(TenantId),
     155              :     Shard(TenantShardId),
     156              : }
     157              : 
     158              : /// Represents the results of looking up generation+pageserver for the shards of a tenant
     159              : pub(crate) struct ShardGenerationState {
     160              :     pub(crate) tenant_shard_id: TenantShardId,
     161              :     pub(crate) generation: Option<Generation>,
     162              :     pub(crate) generation_pageserver: Option<NodeId>,
     163              : }
     164              : 
     165              : // A generous allowance for how many times we may retry serializable transactions
     166              : // before giving up.  This is not expected to be hit: it is a defensive measure in case we
     167              : // somehow engineer a situation where duelling transactions might otherwise live-lock.
     168              : const MAX_RETRIES: usize = 128;
     169              : 
     170              : impl Persistence {
     171              :     // The default postgres connection limit is 100.  We use up to 99, to leave one free for a human admin under
     172              :     // normal circumstances.  This assumes we have exclusive use of the database cluster to which we connect.
     173              :     pub const MAX_CONNECTIONS: u32 = 99;
     174              : 
     175              :     // We don't want to keep a lot of connections alive: close them down promptly if they aren't being used.
     176              :     const IDLE_CONNECTION_TIMEOUT: Duration = Duration::from_secs(10);
     177              :     const MAX_CONNECTION_LIFETIME: Duration = Duration::from_secs(60);
     178              : 
     179            0 :     pub async fn new(database_url: String) -> Self {
     180            0 :         let mut mgr_config = ManagerConfig::default();
     181            0 :         mgr_config.custom_setup = Box::new(establish_connection_rustls);
     182            0 : 
     183            0 :         let manager = AsyncDieselConnectionManager::<AsyncPgConnection>::new_with_config(
     184            0 :             database_url,
     185            0 :             mgr_config,
     186            0 :         );
     187              : 
     188              :         // We will use a connection pool: this is primarily to _limit_ our connection count, rather than to optimize time
     189              :         // to execute queries (database queries are not generally on latency-sensitive paths).
     190            0 :         let connection_pool = Pool::builder()
     191            0 :             .max_size(Self::MAX_CONNECTIONS)
     192            0 :             .max_lifetime(Some(Self::MAX_CONNECTION_LIFETIME))
     193            0 :             .idle_timeout(Some(Self::IDLE_CONNECTION_TIMEOUT))
     194            0 :             // Always keep at least one connection ready to go
     195            0 :             .min_idle(Some(1))
     196            0 :             .test_on_check_out(true)
     197            0 :             .build(manager)
     198            0 :             .await
     199            0 :             .expect("Could not build connection pool");
     200            0 : 
     201            0 :         Self { connection_pool }
     202            0 :     }
     203              : 
     204              :     /// A helper for use during startup, where we would like to tolerate concurrent restarts of the
     205              :     /// database and the storage controller, therefore the database might not be available right away
     206            0 :     pub async fn await_connection(
     207            0 :         database_url: &str,
     208            0 :         timeout: Duration,
     209            0 :     ) -> Result<(), diesel::ConnectionError> {
     210            0 :         let started_at = Instant::now();
     211            0 :         log_postgres_connstr_info(database_url)
     212            0 :             .map_err(|e| diesel::ConnectionError::InvalidConnectionUrl(e.to_string()))?;
     213              :         loop {
     214            0 :             match establish_connection_rustls(database_url).await {
     215              :                 Ok(_) => {
     216            0 :                     tracing::info!("Connected to database.");
     217            0 :                     return Ok(());
     218              :                 }
     219            0 :                 Err(e) => {
     220            0 :                     if started_at.elapsed() > timeout {
     221            0 :                         return Err(e);
     222              :                     } else {
     223            0 :                         tracing::info!("Database not yet available, waiting... ({e})");
     224            0 :                         tokio::time::sleep(Duration::from_millis(100)).await;
     225              :                     }
     226              :                 }
     227              :             }
     228              :         }
     229            0 :     }
     230              : 
     231              :     /// Execute the diesel migrations that are built into this binary
     232            0 :     pub(crate) async fn migration_run(&self) -> DatabaseResult<()> {
     233              :         use diesel_migrations::{HarnessWithOutput, MigrationHarness};
     234              : 
     235              :         // Can't use self.with_conn here as we do spawn_blocking which requires static.
     236            0 :         let conn = self
     237            0 :             .connection_pool
     238            0 :             .dedicated_connection()
     239            0 :             .await
     240            0 :             .map_err(|e| DatabaseError::Migration(e.to_string()))?;
     241            0 :         let mut async_wrapper: AsyncConnectionWrapper<AsyncPgConnection> =
     242            0 :             AsyncConnectionWrapper::from(conn);
     243            0 :         tokio::task::spawn_blocking(move || {
     244            0 :             let mut retry_count = 0;
     245            0 :             loop {
     246            0 :                 let result = HarnessWithOutput::write_to_stdout(&mut async_wrapper)
     247            0 :                     .run_pending_migrations(MIGRATIONS)
     248            0 :                     .map(|_| ())
     249            0 :                     .map_err(|e| DatabaseError::Migration(e.to_string()));
     250            0 :                 match result {
     251            0 :                     Ok(r) => break Ok(r),
     252              :                     Err(
     253            0 :                         err @ DatabaseError::Query(diesel::result::Error::DatabaseError(
     254            0 :                             diesel::result::DatabaseErrorKind::SerializationFailure,
     255            0 :                             _,
     256            0 :                         )),
     257            0 :                     ) => {
     258            0 :                         retry_count += 1;
     259            0 :                         if retry_count > MAX_RETRIES {
     260            0 :                             tracing::error!(
     261            0 :                                 "Exceeded max retries on SerializationFailure errors: {err:?}"
     262              :                             );
     263            0 :                             break Err(err);
     264              :                         } else {
     265              :                             // Retry on serialization errors: these are expected, because even though our
     266              :                             // transactions don't fight for the same rows, they will occasionally collide
     267              :                             // on index pages (e.g. increment_generation for unrelated shards can collide)
     268            0 :                             tracing::debug!(
     269            0 :                                 "Retrying transaction on serialization failure {err:?}"
     270              :                             );
     271            0 :                             continue;
     272              :                         }
     273              :                     }
     274            0 :                     Err(e) => break Err(e),
     275              :                 }
     276              :             }
     277            0 :         })
     278            0 :         .await
     279            0 :         .map_err(|e| DatabaseError::Migration(e.to_string()))??;
     280            0 :         Ok(())
     281            0 :     }
     282              : 
     283              :     /// Wraps `with_conn` in order to collect latency and error metrics
     284            0 :     async fn with_measured_conn<'a, 'b, F, R>(
     285            0 :         &self,
     286            0 :         op: DatabaseOperation,
     287            0 :         func: F,
     288            0 :     ) -> DatabaseResult<R>
     289            0 :     where
     290            0 :         F: for<'r> Fn(&'r mut AsyncPgConnection) -> ScopedBoxFuture<'b, 'r, DatabaseResult<R>>
     291            0 :             + Send
     292            0 :             + std::marker::Sync
     293            0 :             + 'a,
     294            0 :         R: Send + 'b,
     295            0 :     {
     296            0 :         let latency = &METRICS_REGISTRY
     297            0 :             .metrics_group
     298            0 :             .storage_controller_database_query_latency;
     299            0 :         let _timer = latency.start_timer(DatabaseQueryLatencyLabelGroup { operation: op });
     300              : 
     301            0 :         let res = self.with_conn(func).await;
     302              : 
     303            0 :         if let Err(err) = &res {
     304            0 :             let error_counter = &METRICS_REGISTRY
     305            0 :                 .metrics_group
     306            0 :                 .storage_controller_database_query_error;
     307            0 :             error_counter.inc(DatabaseQueryErrorLabelGroup {
     308            0 :                 error_type: err.error_label(),
     309            0 :                 operation: op,
     310            0 :             })
     311            0 :         }
     312              : 
     313            0 :         res
     314            0 :     }
     315              : 
     316              :     /// Call the provided function with a Diesel database connection in a retry loop
     317            0 :     async fn with_conn<'a, 'b, F, R>(&self, func: F) -> DatabaseResult<R>
     318            0 :     where
     319            0 :         F: for<'r> Fn(&'r mut AsyncPgConnection) -> ScopedBoxFuture<'b, 'r, DatabaseResult<R>>
     320            0 :             + Send
     321            0 :             + std::marker::Sync
     322            0 :             + 'a,
     323            0 :         R: Send + 'b,
     324            0 :     {
     325            0 :         let mut retry_count = 0;
     326              :         loop {
     327            0 :             let mut conn = self.connection_pool.get().await?;
     328            0 :             match conn
     329            0 :                 .build_transaction()
     330            0 :                 .serializable()
     331            0 :                 .run(|c| func(c))
     332            0 :                 .await
     333              :             {
     334            0 :                 Ok(r) => break Ok(r),
     335              :                 Err(
     336            0 :                     err @ DatabaseError::Query(diesel::result::Error::DatabaseError(
     337            0 :                         diesel::result::DatabaseErrorKind::SerializationFailure,
     338            0 :                         _,
     339            0 :                     )),
     340            0 :                 ) => {
     341            0 :                     retry_count += 1;
     342            0 :                     if retry_count > MAX_RETRIES {
     343            0 :                         tracing::error!(
     344            0 :                             "Exceeded max retries on SerializationFailure errors: {err:?}"
     345              :                         );
     346            0 :                         break Err(err);
     347              :                     } else {
     348              :                         // Retry on serialization errors: these are expected, because even though our
     349              :                         // transactions don't fight for the same rows, they will occasionally collide
     350              :                         // on index pages (e.g. increment_generation for unrelated shards can collide)
     351            0 :                         tracing::debug!("Retrying transaction on serialization failure {err:?}");
     352            0 :                         continue;
     353              :                     }
     354              :                 }
     355            0 :                 Err(e) => break Err(e),
     356              :             }
     357              :         }
     358            0 :     }
     359              : 
     360              :     /// When a node is first registered, persist it before using it for anything
     361              :     /// If the provided node_id already exists, it will be error.
     362              :     /// The common case is when a node marked for deletion wants to register.
     363            0 :     pub(crate) async fn insert_node(&self, node: &Node) -> DatabaseResult<()> {
     364            0 :         let np = &node.to_persistent();
     365            0 :         self.with_measured_conn(DatabaseOperation::InsertNode, move |conn| {
     366            0 :             Box::pin(async move {
     367            0 :                 diesel::insert_into(crate::schema::nodes::table)
     368            0 :                     .values(np)
     369            0 :                     .execute(conn)
     370            0 :                     .await?;
     371            0 :                 Ok(())
     372            0 :             })
     373            0 :         })
     374            0 :         .await
     375            0 :     }
     376              : 
     377              :     /// At startup, populate the list of nodes which our shards may be placed on
     378            0 :     pub(crate) async fn list_nodes(&self) -> DatabaseResult<Vec<NodePersistence>> {
     379              :         use crate::schema::nodes::dsl::*;
     380              : 
     381            0 :         let result: Vec<NodePersistence> = self
     382            0 :             .with_measured_conn(DatabaseOperation::ListNodes, move |conn| {
     383            0 :                 Box::pin(async move {
     384            0 :                     Ok(crate::schema::nodes::table
     385            0 :                         .filter(lifecycle.ne(String::from(NodeLifecycle::Deleted)))
     386            0 :                         .load::<NodePersistence>(conn)
     387            0 :                         .await?)
     388            0 :                 })
     389            0 :             })
     390            0 :             .await?;
     391              : 
     392            0 :         tracing::info!("list_nodes: loaded {} nodes", result.len());
     393              : 
     394            0 :         Ok(result)
     395            0 :     }
     396              : 
     397            0 :     pub(crate) async fn list_tombstones(&self) -> DatabaseResult<Vec<NodePersistence>> {
     398              :         use crate::schema::nodes::dsl::*;
     399              : 
     400            0 :         let result: Vec<NodePersistence> = self
     401            0 :             .with_measured_conn(DatabaseOperation::ListTombstones, move |conn| {
     402            0 :                 Box::pin(async move {
     403            0 :                     Ok(crate::schema::nodes::table
     404            0 :                         .filter(lifecycle.eq(String::from(NodeLifecycle::Deleted)))
     405            0 :                         .load::<NodePersistence>(conn)
     406            0 :                         .await?)
     407            0 :                 })
     408            0 :             })
     409            0 :             .await?;
     410              : 
     411            0 :         tracing::info!("list_tombstones: loaded {} nodes", result.len());
     412              : 
     413            0 :         Ok(result)
     414            0 :     }
     415              : 
     416            0 :     pub(crate) async fn update_node<V>(
     417            0 :         &self,
     418            0 :         input_node_id: NodeId,
     419            0 :         values: V,
     420            0 :     ) -> DatabaseResult<()>
     421            0 :     where
     422            0 :         V: diesel::AsChangeset<Target = crate::schema::nodes::table> + Clone + Send + Sync,
     423            0 :         V::Changeset: diesel::query_builder::QueryFragment<diesel::pg::Pg> + Send, // valid Postgres SQL
     424            0 :     {
     425              :         use crate::schema::nodes::dsl::*;
     426            0 :         let updated = self
     427            0 :             .with_measured_conn(DatabaseOperation::UpdateNode, move |conn| {
     428            0 :                 let values = values.clone();
     429            0 :                 Box::pin(async move {
     430            0 :                     let updated = diesel::update(nodes)
     431            0 :                         .filter(node_id.eq(input_node_id.0 as i64))
     432            0 :                         .filter(lifecycle.ne(String::from(NodeLifecycle::Deleted)))
     433            0 :                         .set(values)
     434            0 :                         .execute(conn)
     435            0 :                         .await?;
     436            0 :                     Ok(updated)
     437            0 :                 })
     438            0 :             })
     439            0 :             .await?;
     440              : 
     441            0 :         if updated != 1 {
     442            0 :             Err(DatabaseError::Logical(format!(
     443            0 :                 "Node {node_id:?} not found for update",
     444            0 :             )))
     445              :         } else {
     446            0 :             Ok(())
     447              :         }
     448            0 :     }
     449              : 
     450            0 :     pub(crate) async fn update_node_scheduling_policy(
     451            0 :         &self,
     452            0 :         input_node_id: NodeId,
     453            0 :         input_scheduling: NodeSchedulingPolicy,
     454            0 :     ) -> DatabaseResult<()> {
     455              :         use crate::schema::nodes::dsl::*;
     456            0 :         self.update_node(
     457            0 :             input_node_id,
     458            0 :             scheduling_policy.eq(String::from(input_scheduling)),
     459            0 :         )
     460            0 :         .await
     461            0 :     }
     462              : 
     463            0 :     pub(crate) async fn update_node_on_registration(
     464            0 :         &self,
     465            0 :         input_node_id: NodeId,
     466            0 :         input_https_port: Option<u16>,
     467            0 :     ) -> DatabaseResult<()> {
     468              :         use crate::schema::nodes::dsl::*;
     469            0 :         self.update_node(
     470            0 :             input_node_id,
     471            0 :             listen_https_port.eq(input_https_port.map(|x| x as i32)),
     472            0 :         )
     473            0 :         .await
     474            0 :     }
     475              : 
     476              :     /// Tombstone is a special state where the node is not deleted from the database,
     477              :     /// but it is not available for usage.
     478              :     /// The main reason for it is to prevent the flaky node to register.
     479            0 :     pub(crate) async fn set_tombstone(&self, del_node_id: NodeId) -> DatabaseResult<()> {
     480              :         use crate::schema::nodes::dsl::*;
     481            0 :         self.update_node(
     482            0 :             del_node_id,
     483            0 :             lifecycle.eq(String::from(NodeLifecycle::Deleted)),
     484            0 :         )
     485            0 :         .await
     486            0 :     }
     487              : 
     488            0 :     pub(crate) async fn delete_node(&self, del_node_id: NodeId) -> DatabaseResult<()> {
     489              :         use crate::schema::nodes::dsl::*;
     490            0 :         self.with_measured_conn(DatabaseOperation::DeleteNode, move |conn| {
     491            0 :             Box::pin(async move {
     492              :                 // You can hard delete a node only if it has a tombstone.
     493              :                 // So we need to check if the node has lifecycle set to deleted.
     494            0 :                 let node_to_delete = nodes
     495            0 :                     .filter(node_id.eq(del_node_id.0 as i64))
     496            0 :                     .first::<NodePersistence>(conn)
     497            0 :                     .await
     498            0 :                     .optional()?;
     499              : 
     500            0 :                 if let Some(np) = node_to_delete {
     501            0 :                     let lc = NodeLifecycle::from_str(&np.lifecycle).map_err(|e| {
     502            0 :                         DatabaseError::Logical(format!(
     503            0 :                             "Node {} has invalid lifecycle: {}",
     504            0 :                             del_node_id, e
     505            0 :                         ))
     506            0 :                     })?;
     507              : 
     508            0 :                     if lc != NodeLifecycle::Deleted {
     509            0 :                         return Err(DatabaseError::Logical(format!(
     510            0 :                             "Node {} was not soft deleted before, cannot hard delete it",
     511            0 :                             del_node_id
     512            0 :                         )));
     513            0 :                     }
     514            0 : 
     515            0 :                     diesel::delete(nodes)
     516            0 :                         .filter(node_id.eq(del_node_id.0 as i64))
     517            0 :                         .execute(conn)
     518            0 :                         .await?;
     519            0 :                 }
     520              : 
     521            0 :                 Ok(())
     522            0 :             })
     523            0 :         })
     524            0 :         .await
     525            0 :     }
     526              : 
     527              :     /// At startup, load the high level state for shards, such as their config + policy.  This will
     528              :     /// be enriched at runtime with state discovered on pageservers.
     529              :     ///
     530              :     /// We exclude shards configured to be detached.  During startup, if we see any attached locations
     531              :     /// for such shards, they will automatically be detached as 'orphans'.
     532            0 :     pub(crate) async fn load_active_tenant_shards(
     533            0 :         &self,
     534            0 :     ) -> DatabaseResult<Vec<TenantShardPersistence>> {
     535              :         use crate::schema::tenant_shards::dsl::*;
     536            0 :         self.with_measured_conn(DatabaseOperation::ListTenantShards, move |conn| {
     537            0 :             Box::pin(async move {
     538            0 :                 let query = tenant_shards.filter(
     539            0 :                     placement_policy.ne(serde_json::to_string(&PlacementPolicy::Detached).unwrap()),
     540            0 :                 );
     541            0 :                 let result = query.load::<TenantShardPersistence>(conn).await?;
     542              : 
     543            0 :                 Ok(result)
     544            0 :             })
     545            0 :         })
     546            0 :         .await
     547            0 :     }
     548              : 
     549              :     /// When restoring a previously detached tenant into memory, load it from the database
     550            0 :     pub(crate) async fn load_tenant(
     551            0 :         &self,
     552            0 :         filter_tenant_id: TenantId,
     553            0 :     ) -> DatabaseResult<Vec<TenantShardPersistence>> {
     554              :         use crate::schema::tenant_shards::dsl::*;
     555            0 :         self.with_measured_conn(DatabaseOperation::LoadTenant, move |conn| {
     556            0 :             Box::pin(async move {
     557            0 :                 let query = tenant_shards.filter(tenant_id.eq(filter_tenant_id.to_string()));
     558            0 :                 let result = query.load::<TenantShardPersistence>(conn).await?;
     559              : 
     560            0 :                 Ok(result)
     561            0 :             })
     562            0 :         })
     563            0 :         .await
     564            0 :     }
     565              : 
     566              :     /// Tenants must be persisted before we schedule them for the first time.  This enables us
     567              :     /// to correctly retain generation monotonicity, and the externally provided placement policy & config.
     568            0 :     pub(crate) async fn insert_tenant_shards(
     569            0 :         &self,
     570            0 :         shards: Vec<TenantShardPersistence>,
     571            0 :     ) -> DatabaseResult<()> {
     572              :         use crate::schema::{metadata_health, tenant_shards};
     573              : 
     574            0 :         let now = chrono::Utc::now();
     575            0 : 
     576            0 :         let metadata_health_records = shards
     577            0 :             .iter()
     578            0 :             .map(|t| MetadataHealthPersistence {
     579            0 :                 tenant_id: t.tenant_id.clone(),
     580            0 :                 shard_number: t.shard_number,
     581            0 :                 shard_count: t.shard_count,
     582            0 :                 healthy: true,
     583            0 :                 last_scrubbed_at: now,
     584            0 :             })
     585            0 :             .collect::<Vec<_>>();
     586            0 : 
     587            0 :         let shards = &shards;
     588            0 :         let metadata_health_records = &metadata_health_records;
     589            0 :         self.with_measured_conn(DatabaseOperation::InsertTenantShards, move |conn| {
     590            0 :             Box::pin(async move {
     591            0 :                 diesel::insert_into(tenant_shards::table)
     592            0 :                     .values(shards)
     593            0 :                     .execute(conn)
     594            0 :                     .await?;
     595              : 
     596            0 :                 diesel::insert_into(metadata_health::table)
     597            0 :                     .values(metadata_health_records)
     598            0 :                     .execute(conn)
     599            0 :                     .await?;
     600            0 :                 Ok(())
     601            0 :             })
     602            0 :         })
     603            0 :         .await
     604            0 :     }
     605              : 
     606              :     /// Ordering: call this _after_ deleting the tenant on pageservers, but _before_ dropping state for
     607              :     /// the tenant from memory on this server.
     608            0 :     pub(crate) async fn delete_tenant(&self, del_tenant_id: TenantId) -> DatabaseResult<()> {
     609              :         use crate::schema::tenant_shards::dsl::*;
     610            0 :         self.with_measured_conn(DatabaseOperation::DeleteTenant, move |conn| {
     611            0 :             Box::pin(async move {
     612            0 :                 // `metadata_health` status (if exists) is also deleted based on the cascade behavior.
     613            0 :                 diesel::delete(tenant_shards)
     614            0 :                     .filter(tenant_id.eq(del_tenant_id.to_string()))
     615            0 :                     .execute(conn)
     616            0 :                     .await?;
     617            0 :                 Ok(())
     618            0 :             })
     619            0 :         })
     620            0 :         .await
     621            0 :     }
     622              : 
     623              :     /// When a tenant invokes the /re-attach API, this function is responsible for doing an efficient
     624              :     /// batched increment of the generations of all tenants whose generation_pageserver is equal to
     625              :     /// the node that called /re-attach.
     626              :     #[tracing::instrument(skip_all, fields(node_id))]
     627              :     pub(crate) async fn re_attach(
     628              :         &self,
     629              :         input_node_id: NodeId,
     630              :     ) -> DatabaseResult<HashMap<TenantShardId, Generation>> {
     631              :         use crate::schema::nodes::dsl::{scheduling_policy, *};
     632              :         use crate::schema::tenant_shards::dsl::*;
     633              :         let updated = self
     634            0 :             .with_measured_conn(DatabaseOperation::ReAttach, move |conn| {
     635            0 :                 Box::pin(async move {
     636              :                     // Check if the node is not marked as deleted
     637            0 :                     let deleted_node: i64 = nodes
     638            0 :                         .filter(node_id.eq(input_node_id.0 as i64))
     639            0 :                         .filter(lifecycle.eq(String::from(NodeLifecycle::Deleted)))
     640            0 :                         .count()
     641            0 :                         .get_result(conn)
     642            0 :                         .await?;
     643            0 :                     if deleted_node > 0 {
     644            0 :                         return Err(DatabaseError::Logical(format!(
     645            0 :                             "Node {} is marked as deleted, re-attach is not allowed",
     646            0 :                             input_node_id
     647            0 :                         )));
     648            0 :                     }
     649              : 
     650            0 :                     let rows_updated = diesel::update(tenant_shards)
     651            0 :                         .filter(generation_pageserver.eq(input_node_id.0 as i64))
     652            0 :                         .set(generation.eq(generation + 1))
     653            0 :                         .execute(conn)
     654            0 :                         .await?;
     655              : 
     656            0 :                     tracing::info!("Incremented {} tenants' generations", rows_updated);
     657              : 
     658              :                     // TODO: UPDATE+SELECT in one query
     659              : 
     660            0 :                     let updated = tenant_shards
     661            0 :                         .filter(generation_pageserver.eq(input_node_id.0 as i64))
     662            0 :                         .select(TenantShardPersistence::as_select())
     663            0 :                         .load(conn)
     664            0 :                         .await?;
     665              : 
     666              :                     // If the node went through a drain and restart phase before re-attaching,
     667              :                     // then reset it's node scheduling policy to active.
     668            0 :                     diesel::update(nodes)
     669            0 :                         .filter(node_id.eq(input_node_id.0 as i64))
     670            0 :                         .filter(
     671            0 :                             scheduling_policy
     672            0 :                                 .eq(String::from(NodeSchedulingPolicy::PauseForRestart))
     673            0 :                                 .or(scheduling_policy
     674            0 :                                     .eq(String::from(NodeSchedulingPolicy::Draining)))
     675            0 :                                 .or(scheduling_policy
     676            0 :                                     .eq(String::from(NodeSchedulingPolicy::Filling))),
     677            0 :                         )
     678            0 :                         .set(scheduling_policy.eq(String::from(NodeSchedulingPolicy::Active)))
     679            0 :                         .execute(conn)
     680            0 :                         .await?;
     681              : 
     682            0 :                     Ok(updated)
     683            0 :                 })
     684            0 :             })
     685              :             .await?;
     686              : 
     687              :         let mut result = HashMap::new();
     688              :         for tsp in updated {
     689              :             let tenant_shard_id = TenantShardId {
     690              :                 tenant_id: TenantId::from_str(tsp.tenant_id.as_str())
     691            0 :                     .map_err(|e| DatabaseError::Logical(format!("Malformed tenant id: {e}")))?,
     692              :                 shard_number: ShardNumber(tsp.shard_number as u8),
     693              :                 shard_count: ShardCount::new(tsp.shard_count as u8),
     694              :             };
     695              : 
     696              :             let Some(g) = tsp.generation else {
     697              :                 // If the generation_pageserver column was non-NULL, then the generation column should also be non-NULL:
     698              :                 // we only set generation_pageserver when setting generation.
     699              :                 return Err(DatabaseError::Logical(
     700              :                     "Generation should always be set after incrementing".to_string(),
     701              :                 ));
     702              :             };
     703              :             result.insert(tenant_shard_id, Generation::new(g as u32));
     704              :         }
     705              : 
     706              :         Ok(result)
     707              :     }
     708              : 
     709              :     /// Reconciler calls this immediately before attaching to a new pageserver, to acquire a unique, monotonically
     710              :     /// advancing generation number.  We also store the NodeId for which the generation was issued, so that in
     711              :     /// [`Self::re_attach`] we can do a bulk UPDATE on the generations for that node.
     712            0 :     pub(crate) async fn increment_generation(
     713            0 :         &self,
     714            0 :         tenant_shard_id: TenantShardId,
     715            0 :         node_id: NodeId,
     716            0 :     ) -> anyhow::Result<Generation> {
     717              :         use crate::schema::tenant_shards::dsl::*;
     718            0 :         let updated = self
     719            0 :             .with_measured_conn(DatabaseOperation::IncrementGeneration, move |conn| {
     720            0 :                 Box::pin(async move {
     721            0 :                     let updated = diesel::update(tenant_shards)
     722            0 :                         .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
     723            0 :                         .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
     724            0 :                         .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
     725            0 :                         .set((
     726            0 :                             generation.eq(generation + 1),
     727            0 :                             generation_pageserver.eq(node_id.0 as i64),
     728            0 :                         ))
     729            0 :                         // TODO: only returning() the generation column
     730            0 :                         .returning(TenantShardPersistence::as_returning())
     731            0 :                         .get_result(conn)
     732            0 :                         .await?;
     733              : 
     734            0 :                     Ok(updated)
     735            0 :                 })
     736            0 :             })
     737            0 :             .await?;
     738              : 
     739              :         // Generation is always non-null in the rseult: if the generation column had been NULL, then we
     740              :         // should have experienced an SQL Confilict error while executing a query that tries to increment it.
     741            0 :         debug_assert!(updated.generation.is_some());
     742            0 :         let Some(g) = updated.generation else {
     743            0 :             return Err(DatabaseError::Logical(
     744            0 :                 "Generation should always be set after incrementing".to_string(),
     745            0 :             )
     746            0 :             .into());
     747              :         };
     748              : 
     749            0 :         Ok(Generation::new(g as u32))
     750            0 :     }
     751              : 
     752              :     /// When we want to call out to the running shards for a tenant, e.g. during timeline CRUD operations,
     753              :     /// we need to know where the shard is attached, _and_ the generation, so that we can re-check the generation
     754              :     /// afterwards to confirm that our timeline CRUD operation is truly persistent (it must have happened in the
     755              :     /// latest generation)
     756              :     ///
     757              :     /// If the tenant doesn't exist, an empty vector is returned.
     758              :     ///
     759              :     /// Output is sorted by shard number
     760            0 :     pub(crate) async fn tenant_generations(
     761            0 :         &self,
     762            0 :         filter_tenant_id: TenantId,
     763            0 :     ) -> Result<Vec<ShardGenerationState>, DatabaseError> {
     764              :         use crate::schema::tenant_shards::dsl::*;
     765            0 :         let rows = self
     766            0 :             .with_measured_conn(DatabaseOperation::TenantGenerations, move |conn| {
     767            0 :                 Box::pin(async move {
     768            0 :                     let result = tenant_shards
     769            0 :                         .filter(tenant_id.eq(filter_tenant_id.to_string()))
     770            0 :                         .select(TenantShardPersistence::as_select())
     771            0 :                         .order(shard_number)
     772            0 :                         .load(conn)
     773            0 :                         .await?;
     774            0 :                     Ok(result)
     775            0 :                 })
     776            0 :             })
     777            0 :             .await?;
     778              : 
     779            0 :         Ok(rows
     780            0 :             .into_iter()
     781            0 :             .map(|p| ShardGenerationState {
     782            0 :                 tenant_shard_id: p
     783            0 :                     .get_tenant_shard_id()
     784            0 :                     .expect("Corrupt tenant shard id in database"),
     785            0 :                 generation: p.generation.map(|g| Generation::new(g as u32)),
     786            0 :                 generation_pageserver: p.generation_pageserver.map(|n| NodeId(n as u64)),
     787            0 :             })
     788            0 :             .collect())
     789            0 :     }
     790              : 
     791              :     /// Read the generation number of specific tenant shards
     792              :     ///
     793              :     /// Output is unsorted.  Output may not include values for all inputs, if they are missing in the database.
     794            0 :     pub(crate) async fn shard_generations(
     795            0 :         &self,
     796            0 :         mut tenant_shard_ids: impl Iterator<Item = &TenantShardId>,
     797            0 :     ) -> Result<Vec<(TenantShardId, Option<Generation>)>, DatabaseError> {
     798            0 :         let mut rows = Vec::with_capacity(tenant_shard_ids.size_hint().0);
     799              : 
     800              :         // We will chunk our input to avoid composing arbitrarily long `IN` clauses.  Typically we are
     801              :         // called with a single digit number of IDs, but in principle we could be called with tens
     802              :         // of thousands (all the shards on one pageserver) from the generation validation API.
     803            0 :         loop {
     804            0 :             // A modest hardcoded chunk size to handle typical cases in a single query but never generate particularly
     805            0 :             // large query strings.
     806            0 :             let chunk_ids = tenant_shard_ids.by_ref().take(32);
     807            0 : 
     808            0 :             // Compose a comma separated list of tuples for matching on (tenant_id, shard_number, shard_count)
     809            0 :             let in_clause = chunk_ids
     810            0 :                 .map(|tsid| {
     811            0 :                     format!(
     812            0 :                         "('{}', {}, {})",
     813            0 :                         tsid.tenant_id, tsid.shard_number.0, tsid.shard_count.0
     814            0 :                     )
     815            0 :                 })
     816            0 :                 .join(",");
     817            0 : 
     818            0 :             // We are done when our iterator gives us nothing to filter on
     819            0 :             if in_clause.is_empty() {
     820            0 :                 break;
     821            0 :             }
     822            0 : 
     823            0 :             let in_clause = &in_clause;
     824            0 :             let chunk_rows = self
     825            0 :                 .with_measured_conn(DatabaseOperation::ShardGenerations, move |conn| {
     826            0 :                     Box::pin(async move {
     827              :                         // diesel doesn't support multi-column IN queries, so we compose raw SQL.  No escaping is required because
     828              :                         // the inputs are strongly typed and cannot carry any user-supplied raw string content.
     829            0 :                         let result : Vec<TenantShardPersistence> = diesel::sql_query(
     830            0 :                             format!("SELECT * from tenant_shards where (tenant_id, shard_number, shard_count) in ({in_clause});").as_str()
     831            0 :                         ).load(conn).await?;
     832              : 
     833            0 :                         Ok(result)
     834            0 :                     })
     835            0 :                 })
     836            0 :                 .await?;
     837            0 :             rows.extend(chunk_rows.into_iter())
     838              :         }
     839              : 
     840            0 :         Ok(rows
     841            0 :             .into_iter()
     842            0 :             .map(|tsp| {
     843            0 :                 (
     844            0 :                     tsp.get_tenant_shard_id()
     845            0 :                         .expect("Bad tenant ID in database"),
     846            0 :                     tsp.generation.map(|g| Generation::new(g as u32)),
     847            0 :                 )
     848            0 :             })
     849            0 :             .collect())
     850            0 :     }
     851              : 
     852              :     #[allow(non_local_definitions)]
     853              :     /// For use when updating a persistent property of a tenant, such as its config or placement_policy.
     854              :     ///
     855              :     /// Do not use this for settting generation, unless in the special onboarding code path (/location_config)
     856              :     /// API: use [`Self::increment_generation`] instead.  Setting the generation via this route is a one-time thing
     857              :     /// that we only do the first time a tenant is set to an attached policy via /location_config.
     858            0 :     pub(crate) async fn update_tenant_shard(
     859            0 :         &self,
     860            0 :         tenant: TenantFilter,
     861            0 :         input_placement_policy: Option<PlacementPolicy>,
     862            0 :         input_config: Option<TenantConfig>,
     863            0 :         input_generation: Option<Generation>,
     864            0 :         input_scheduling_policy: Option<ShardSchedulingPolicy>,
     865            0 :     ) -> DatabaseResult<()> {
     866              :         use crate::schema::tenant_shards::dsl::*;
     867              : 
     868            0 :         let tenant = &tenant;
     869            0 :         let input_placement_policy = &input_placement_policy;
     870            0 :         let input_config = &input_config;
     871            0 :         let input_generation = &input_generation;
     872            0 :         let input_scheduling_policy = &input_scheduling_policy;
     873            0 :         self.with_measured_conn(DatabaseOperation::UpdateTenantShard, move |conn| {
     874            0 :             Box::pin(async move {
     875            0 :                 let query = match tenant {
     876            0 :                     TenantFilter::Shard(tenant_shard_id) => diesel::update(tenant_shards)
     877            0 :                         .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
     878            0 :                         .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
     879            0 :                         .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
     880            0 :                         .into_boxed(),
     881            0 :                     TenantFilter::Tenant(input_tenant_id) => diesel::update(tenant_shards)
     882            0 :                         .filter(tenant_id.eq(input_tenant_id.to_string()))
     883            0 :                         .into_boxed(),
     884              :                 };
     885              : 
     886              :                 // Clear generation_pageserver if we are moving into a state where we won't have
     887              :                 // any attached pageservers.
     888            0 :                 let input_generation_pageserver = match input_placement_policy {
     889            0 :                     None | Some(PlacementPolicy::Attached(_)) => None,
     890            0 :                     Some(PlacementPolicy::Detached | PlacementPolicy::Secondary) => Some(None),
     891              :                 };
     892              : 
     893            0 :                 #[derive(AsChangeset)]
     894              :                 #[diesel(table_name = crate::schema::tenant_shards)]
     895              :                 struct ShardUpdate {
     896              :                     generation: Option<i32>,
     897              :                     placement_policy: Option<String>,
     898              :                     config: Option<String>,
     899              :                     scheduling_policy: Option<String>,
     900              :                     generation_pageserver: Option<Option<i64>>,
     901              :                 }
     902              : 
     903            0 :                 let update = ShardUpdate {
     904            0 :                     generation: input_generation.map(|g| g.into().unwrap() as i32),
     905            0 :                     placement_policy: input_placement_policy
     906            0 :                         .as_ref()
     907            0 :                         .map(|p| serde_json::to_string(&p).unwrap()),
     908            0 :                     config: input_config
     909            0 :                         .as_ref()
     910            0 :                         .map(|c| serde_json::to_string(&c).unwrap()),
     911            0 :                     scheduling_policy: input_scheduling_policy
     912            0 :                         .map(|p| serde_json::to_string(&p).unwrap()),
     913            0 :                     generation_pageserver: input_generation_pageserver,
     914            0 :                 };
     915            0 : 
     916            0 :                 query.set(update).execute(conn).await?;
     917              : 
     918            0 :                 Ok(())
     919            0 :             })
     920            0 :         })
     921            0 :         .await?;
     922              : 
     923            0 :         Ok(())
     924            0 :     }
     925              : 
     926              :     /// Note that passing None for a shard clears the preferred AZ (rather than leaving it unmodified)
     927            0 :     pub(crate) async fn set_tenant_shard_preferred_azs(
     928            0 :         &self,
     929            0 :         preferred_azs: Vec<(TenantShardId, Option<AvailabilityZone>)>,
     930            0 :     ) -> DatabaseResult<Vec<(TenantShardId, Option<AvailabilityZone>)>> {
     931              :         use crate::schema::tenant_shards::dsl::*;
     932              : 
     933            0 :         let preferred_azs = preferred_azs.as_slice();
     934            0 :         self.with_measured_conn(DatabaseOperation::SetPreferredAzs, move |conn| {
     935            0 :             Box::pin(async move {
     936            0 :                 let mut shards_updated = Vec::default();
     937              : 
     938            0 :                 for (tenant_shard_id, preferred_az) in preferred_azs.iter() {
     939            0 :                     let updated = diesel::update(tenant_shards)
     940            0 :                         .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
     941            0 :                         .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
     942            0 :                         .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
     943            0 :                         .set(preferred_az_id.eq(preferred_az.as_ref().map(|az| az.0.clone())))
     944            0 :                         .execute(conn)
     945            0 :                         .await?;
     946              : 
     947            0 :                     if updated == 1 {
     948            0 :                         shards_updated.push((*tenant_shard_id, preferred_az.clone()));
     949            0 :                     }
     950              :                 }
     951              : 
     952            0 :                 Ok(shards_updated)
     953            0 :             })
     954            0 :         })
     955            0 :         .await
     956            0 :     }
     957              : 
     958            0 :     pub(crate) async fn detach(&self, tenant_shard_id: TenantShardId) -> anyhow::Result<()> {
     959              :         use crate::schema::tenant_shards::dsl::*;
     960            0 :         self.with_measured_conn(DatabaseOperation::Detach, move |conn| {
     961            0 :             Box::pin(async move {
     962            0 :                 let updated = diesel::update(tenant_shards)
     963            0 :                     .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
     964            0 :                     .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
     965            0 :                     .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
     966            0 :                     .set((
     967            0 :                         generation_pageserver.eq(Option::<i64>::None),
     968            0 :                         placement_policy
     969            0 :                             .eq(serde_json::to_string(&PlacementPolicy::Detached).unwrap()),
     970            0 :                     ))
     971            0 :                     .execute(conn)
     972            0 :                     .await?;
     973              : 
     974            0 :                 Ok(updated)
     975            0 :             })
     976            0 :         })
     977            0 :         .await?;
     978              : 
     979            0 :         Ok(())
     980            0 :     }
     981              : 
     982              :     // When we start shard splitting, we must durably mark the tenant so that
     983              :     // on restart, we know that we must go through recovery.
     984              :     //
     985              :     // We create the child shards here, so that they will be available for increment_generation calls
     986              :     // if some pageserver holding a child shard needs to restart before the overall tenant split is complete.
     987            0 :     pub(crate) async fn begin_shard_split(
     988            0 :         &self,
     989            0 :         old_shard_count: ShardCount,
     990            0 :         split_tenant_id: TenantId,
     991            0 :         parent_to_children: Vec<(TenantShardId, Vec<TenantShardPersistence>)>,
     992            0 :     ) -> DatabaseResult<()> {
     993              :         use crate::schema::tenant_shards::dsl::*;
     994            0 :         let parent_to_children = parent_to_children.as_slice();
     995            0 :         self.with_measured_conn(DatabaseOperation::BeginShardSplit, move |conn| {
     996            0 :             Box::pin(async move {
     997              :             // Mark parent shards as splitting
     998              : 
     999            0 :             let updated = diesel::update(tenant_shards)
    1000            0 :                 .filter(tenant_id.eq(split_tenant_id.to_string()))
    1001            0 :                 .filter(shard_count.eq(old_shard_count.literal() as i32))
    1002            0 :                 .set((splitting.eq(1),))
    1003            0 :                 .execute(conn).await?;
    1004            0 :             if u8::try_from(updated)
    1005            0 :                 .map_err(|_| DatabaseError::Logical(
    1006            0 :                     format!("Overflow existing shard count {} while splitting", updated))
    1007            0 :                 )? != old_shard_count.count() {
    1008              :                 // Perhaps a deletion or another split raced with this attempt to split, mutating
    1009              :                 // the parent shards that we intend to split. In this case the split request should fail.
    1010            0 :                 return Err(DatabaseError::Logical(
    1011            0 :                     format!("Unexpected existing shard count {updated} when preparing tenant for split (expected {})", old_shard_count.count())
    1012            0 :                 ));
    1013            0 :             }
    1014            0 : 
    1015            0 :             // FIXME: spurious clone to sidestep closure move rules
    1016            0 :             let parent_to_children = parent_to_children.to_vec();
    1017              : 
    1018              :             // Insert child shards
    1019            0 :             for (parent_shard_id, children) in parent_to_children {
    1020            0 :                 let mut parent = crate::schema::tenant_shards::table
    1021            0 :                     .filter(tenant_id.eq(parent_shard_id.tenant_id.to_string()))
    1022            0 :                     .filter(shard_number.eq(parent_shard_id.shard_number.0 as i32))
    1023            0 :                     .filter(shard_count.eq(parent_shard_id.shard_count.literal() as i32))
    1024            0 :                     .load::<TenantShardPersistence>(conn).await?;
    1025            0 :                 let parent = if parent.len() != 1 {
    1026            0 :                     return Err(DatabaseError::Logical(format!(
    1027            0 :                         "Parent shard {parent_shard_id} not found"
    1028            0 :                     )));
    1029              :                 } else {
    1030            0 :                     parent.pop().unwrap()
    1031              :                 };
    1032            0 :                 for mut shard in children {
    1033              :                     // Carry the parent's generation into the child
    1034            0 :                     shard.generation = parent.generation;
    1035            0 : 
    1036            0 :                     debug_assert!(shard.splitting == SplitState::Splitting);
    1037            0 :                     diesel::insert_into(tenant_shards)
    1038            0 :                         .values(shard)
    1039            0 :                         .execute(conn).await?;
    1040              :                 }
    1041              :             }
    1042              : 
    1043            0 :             Ok(())
    1044            0 :         })
    1045            0 :         })
    1046            0 :         .await
    1047            0 :     }
    1048              : 
    1049              :     // When we finish shard splitting, we must atomically clean up the old shards
    1050              :     // and insert the new shards, and clear the splitting marker.
    1051            0 :     pub(crate) async fn complete_shard_split(
    1052            0 :         &self,
    1053            0 :         split_tenant_id: TenantId,
    1054            0 :         old_shard_count: ShardCount,
    1055            0 :         new_shard_count: ShardCount,
    1056            0 :     ) -> DatabaseResult<()> {
    1057              :         use crate::schema::tenant_shards::dsl::*;
    1058            0 :         self.with_measured_conn(DatabaseOperation::CompleteShardSplit, move |conn| {
    1059            0 :             Box::pin(async move {
    1060            0 :                 // Sanity: child shards must still exist, as we're deleting parent shards
    1061            0 :                 let child_shards_query = tenant_shards
    1062            0 :                     .filter(tenant_id.eq(split_tenant_id.to_string()))
    1063            0 :                     .filter(shard_count.eq(new_shard_count.literal() as i32));
    1064            0 :                 let child_shards = child_shards_query
    1065            0 :                     .load::<TenantShardPersistence>(conn)
    1066            0 :                     .await?;
    1067            0 :                 if child_shards.len() != new_shard_count.count() as usize {
    1068            0 :                     return Err(DatabaseError::Logical(format!(
    1069            0 :                         "Unexpected child shard count {} while completing split to \
    1070            0 :                             count {new_shard_count:?} on tenant {split_tenant_id}",
    1071            0 :                         child_shards.len()
    1072            0 :                     )));
    1073            0 :                 }
    1074            0 : 
    1075            0 :                 // Drop parent shards
    1076            0 :                 diesel::delete(tenant_shards)
    1077            0 :                     .filter(tenant_id.eq(split_tenant_id.to_string()))
    1078            0 :                     .filter(shard_count.eq(old_shard_count.literal() as i32))
    1079            0 :                     .execute(conn)
    1080            0 :                     .await?;
    1081              : 
    1082              :                 // Clear sharding flag
    1083            0 :                 let updated = diesel::update(tenant_shards)
    1084            0 :                     .filter(tenant_id.eq(split_tenant_id.to_string()))
    1085            0 :                     .filter(shard_count.eq(new_shard_count.literal() as i32))
    1086            0 :                     .set((splitting.eq(0),))
    1087            0 :                     .execute(conn)
    1088            0 :                     .await?;
    1089            0 :                 assert!(updated == new_shard_count.count() as usize);
    1090              : 
    1091            0 :                 Ok(())
    1092            0 :             })
    1093            0 :         })
    1094            0 :         .await
    1095            0 :     }
    1096              : 
    1097              :     /// Used when the remote part of a shard split failed: we will revert the database state to have only
    1098              :     /// the parent shards, with SplitState::Idle.
    1099            0 :     pub(crate) async fn abort_shard_split(
    1100            0 :         &self,
    1101            0 :         split_tenant_id: TenantId,
    1102            0 :         new_shard_count: ShardCount,
    1103            0 :     ) -> DatabaseResult<AbortShardSplitStatus> {
    1104              :         use crate::schema::tenant_shards::dsl::*;
    1105            0 :         self.with_measured_conn(DatabaseOperation::AbortShardSplit, move |conn| {
    1106            0 :             Box::pin(async move {
    1107              :                 // Clear the splitting state on parent shards
    1108            0 :                 let updated = diesel::update(tenant_shards)
    1109            0 :                     .filter(tenant_id.eq(split_tenant_id.to_string()))
    1110            0 :                     .filter(shard_count.ne(new_shard_count.literal() as i32))
    1111            0 :                     .set((splitting.eq(0),))
    1112            0 :                     .execute(conn)
    1113            0 :                     .await?;
    1114              : 
    1115              :                 // Parent shards are already gone: we cannot abort.
    1116            0 :                 if updated == 0 {
    1117            0 :                     return Ok(AbortShardSplitStatus::Complete);
    1118            0 :                 }
    1119            0 : 
    1120            0 :                 // Sanity check: if parent shards were present, their cardinality should
    1121            0 :                 // be less than the number of child shards.
    1122            0 :                 if updated >= new_shard_count.count() as usize {
    1123            0 :                     return Err(DatabaseError::Logical(format!(
    1124            0 :                         "Unexpected parent shard count {updated} while aborting split to \
    1125            0 :                             count {new_shard_count:?} on tenant {split_tenant_id}"
    1126            0 :                     )));
    1127            0 :                 }
    1128            0 : 
    1129            0 :                 // Erase child shards
    1130            0 :                 diesel::delete(tenant_shards)
    1131            0 :                     .filter(tenant_id.eq(split_tenant_id.to_string()))
    1132            0 :                     .filter(shard_count.eq(new_shard_count.literal() as i32))
    1133            0 :                     .execute(conn)
    1134            0 :                     .await?;
    1135              : 
    1136            0 :                 Ok(AbortShardSplitStatus::Aborted)
    1137            0 :             })
    1138            0 :         })
    1139            0 :         .await
    1140            0 :     }
    1141              : 
    1142              :     /// Stores all the latest metadata health updates durably. Updates existing entry on conflict.
    1143              :     ///
    1144              :     /// **Correctness:** `metadata_health_updates` should all belong the tenant shards managed by the storage controller.
    1145              :     #[allow(dead_code)]
    1146            0 :     pub(crate) async fn update_metadata_health_records(
    1147            0 :         &self,
    1148            0 :         healthy_records: Vec<MetadataHealthPersistence>,
    1149            0 :         unhealthy_records: Vec<MetadataHealthPersistence>,
    1150            0 :         now: chrono::DateTime<chrono::Utc>,
    1151            0 :     ) -> DatabaseResult<()> {
    1152              :         use crate::schema::metadata_health::dsl::*;
    1153              : 
    1154            0 :         let healthy_records = healthy_records.as_slice();
    1155            0 :         let unhealthy_records = unhealthy_records.as_slice();
    1156            0 :         self.with_measured_conn(DatabaseOperation::UpdateMetadataHealth, move |conn| {
    1157            0 :             Box::pin(async move {
    1158            0 :                 diesel::insert_into(metadata_health)
    1159            0 :                     .values(healthy_records)
    1160            0 :                     .on_conflict((tenant_id, shard_number, shard_count))
    1161            0 :                     .do_update()
    1162            0 :                     .set((healthy.eq(true), last_scrubbed_at.eq(now)))
    1163            0 :                     .execute(conn)
    1164            0 :                     .await?;
    1165              : 
    1166            0 :                 diesel::insert_into(metadata_health)
    1167            0 :                     .values(unhealthy_records)
    1168            0 :                     .on_conflict((tenant_id, shard_number, shard_count))
    1169            0 :                     .do_update()
    1170            0 :                     .set((healthy.eq(false), last_scrubbed_at.eq(now)))
    1171            0 :                     .execute(conn)
    1172            0 :                     .await?;
    1173            0 :                 Ok(())
    1174            0 :             })
    1175            0 :         })
    1176            0 :         .await
    1177            0 :     }
    1178              : 
    1179              :     /// Lists all the metadata health records.
    1180              :     #[allow(dead_code)]
    1181            0 :     pub(crate) async fn list_metadata_health_records(
    1182            0 :         &self,
    1183            0 :     ) -> DatabaseResult<Vec<MetadataHealthPersistence>> {
    1184            0 :         self.with_measured_conn(DatabaseOperation::ListMetadataHealth, move |conn| {
    1185            0 :             Box::pin(async {
    1186            0 :                 Ok(crate::schema::metadata_health::table
    1187            0 :                     .load::<MetadataHealthPersistence>(conn)
    1188            0 :                     .await?)
    1189            0 :             })
    1190            0 :         })
    1191            0 :         .await
    1192            0 :     }
    1193              : 
    1194              :     /// Lists all the metadata health records that is unhealthy.
    1195              :     #[allow(dead_code)]
    1196            0 :     pub(crate) async fn list_unhealthy_metadata_health_records(
    1197            0 :         &self,
    1198            0 :     ) -> DatabaseResult<Vec<MetadataHealthPersistence>> {
    1199              :         use crate::schema::metadata_health::dsl::*;
    1200            0 :         self.with_measured_conn(
    1201            0 :             DatabaseOperation::ListMetadataHealthUnhealthy,
    1202            0 :             move |conn| {
    1203            0 :                 Box::pin(async {
    1204            0 :                     DatabaseResult::Ok(
    1205            0 :                         crate::schema::metadata_health::table
    1206            0 :                             .filter(healthy.eq(false))
    1207            0 :                             .load::<MetadataHealthPersistence>(conn)
    1208            0 :                             .await?,
    1209              :                     )
    1210            0 :                 })
    1211            0 :             },
    1212            0 :         )
    1213            0 :         .await
    1214            0 :     }
    1215              : 
    1216              :     /// Lists all the metadata health records that have not been updated since an `earlier` time.
    1217              :     #[allow(dead_code)]
    1218            0 :     pub(crate) async fn list_outdated_metadata_health_records(
    1219            0 :         &self,
    1220            0 :         earlier: chrono::DateTime<chrono::Utc>,
    1221            0 :     ) -> DatabaseResult<Vec<MetadataHealthPersistence>> {
    1222              :         use crate::schema::metadata_health::dsl::*;
    1223              : 
    1224            0 :         self.with_measured_conn(DatabaseOperation::ListMetadataHealthOutdated, move |conn| {
    1225            0 :             Box::pin(async move {
    1226            0 :                 let query = metadata_health.filter(last_scrubbed_at.lt(earlier));
    1227            0 :                 let res = query.load::<MetadataHealthPersistence>(conn).await?;
    1228              : 
    1229            0 :                 Ok(res)
    1230            0 :             })
    1231            0 :         })
    1232            0 :         .await
    1233            0 :     }
    1234              : 
    1235              :     /// Get the current entry from the `leader` table if one exists.
    1236              :     /// It is an error for the table to contain more than one entry.
    1237            0 :     pub(crate) async fn get_leader(&self) -> DatabaseResult<Option<ControllerPersistence>> {
    1238            0 :         let mut leader: Vec<ControllerPersistence> = self
    1239            0 :             .with_measured_conn(DatabaseOperation::GetLeader, move |conn| {
    1240            0 :                 Box::pin(async move {
    1241            0 :                     Ok(crate::schema::controllers::table
    1242            0 :                         .load::<ControllerPersistence>(conn)
    1243            0 :                         .await?)
    1244            0 :                 })
    1245            0 :             })
    1246            0 :             .await?;
    1247              : 
    1248            0 :         if leader.len() > 1 {
    1249            0 :             return Err(DatabaseError::Logical(format!(
    1250            0 :                 "More than one entry present in the leader table: {leader:?}"
    1251            0 :             )));
    1252            0 :         }
    1253            0 : 
    1254            0 :         Ok(leader.pop())
    1255            0 :     }
    1256              : 
    1257              :     /// Update the new leader with compare-exchange semantics. If `prev` does not
    1258              :     /// match the current leader entry, then the update is treated as a failure.
    1259              :     /// When `prev` is not specified, the update is forced.
    1260            0 :     pub(crate) async fn update_leader(
    1261            0 :         &self,
    1262            0 :         prev: Option<ControllerPersistence>,
    1263            0 :         new: ControllerPersistence,
    1264            0 :     ) -> DatabaseResult<()> {
    1265              :         use crate::schema::controllers::dsl::*;
    1266              : 
    1267            0 :         let updated = self
    1268            0 :             .with_measured_conn(DatabaseOperation::UpdateLeader, move |conn| {
    1269            0 :                 let prev = prev.clone();
    1270            0 :                 let new = new.clone();
    1271            0 :                 Box::pin(async move {
    1272            0 :                     let updated = match &prev {
    1273            0 :                         Some(prev) => {
    1274            0 :                             diesel::update(controllers)
    1275            0 :                                 .filter(address.eq(prev.address.clone()))
    1276            0 :                                 .filter(started_at.eq(prev.started_at))
    1277            0 :                                 .set((
    1278            0 :                                     address.eq(new.address.clone()),
    1279            0 :                                     started_at.eq(new.started_at),
    1280            0 :                                 ))
    1281            0 :                                 .execute(conn)
    1282            0 :                                 .await?
    1283              :                         }
    1284              :                         None => {
    1285            0 :                             diesel::insert_into(controllers)
    1286            0 :                                 .values(new.clone())
    1287            0 :                                 .execute(conn)
    1288            0 :                                 .await?
    1289              :                         }
    1290              :                     };
    1291              : 
    1292            0 :                     Ok(updated)
    1293            0 :                 })
    1294            0 :             })
    1295            0 :             .await?;
    1296              : 
    1297            0 :         if updated == 0 {
    1298            0 :             return Err(DatabaseError::Logical(
    1299            0 :                 "Leader table update failed".to_string(),
    1300            0 :             ));
    1301            0 :         }
    1302            0 : 
    1303            0 :         Ok(())
    1304            0 :     }
    1305              : 
    1306              :     /// At startup, populate the list of nodes which our shards may be placed on
    1307            0 :     pub(crate) async fn list_safekeepers(&self) -> DatabaseResult<Vec<SafekeeperPersistence>> {
    1308            0 :         let safekeepers: Vec<SafekeeperPersistence> = self
    1309            0 :             .with_measured_conn(DatabaseOperation::ListNodes, move |conn| {
    1310            0 :                 Box::pin(async move {
    1311            0 :                     Ok(crate::schema::safekeepers::table
    1312            0 :                         .load::<SafekeeperPersistence>(conn)
    1313            0 :                         .await?)
    1314            0 :                 })
    1315            0 :             })
    1316            0 :             .await?;
    1317              : 
    1318            0 :         tracing::info!("list_safekeepers: loaded {} nodes", safekeepers.len());
    1319              : 
    1320            0 :         Ok(safekeepers)
    1321            0 :     }
    1322              : 
    1323            0 :     pub(crate) async fn safekeeper_upsert(
    1324            0 :         &self,
    1325            0 :         record: SafekeeperUpsert,
    1326            0 :     ) -> Result<(), DatabaseError> {
    1327              :         use crate::schema::safekeepers::dsl::*;
    1328              : 
    1329            0 :         self.with_conn(move |conn| {
    1330            0 :             let record = record.clone();
    1331            0 :             Box::pin(async move {
    1332            0 :                 let bind = record
    1333            0 :                     .as_insert_or_update()
    1334            0 :                     .map_err(|e| DatabaseError::Logical(format!("{e}")))?;
    1335              : 
    1336            0 :                 let inserted_updated = diesel::insert_into(safekeepers)
    1337            0 :                     .values(&bind)
    1338            0 :                     .on_conflict(id)
    1339            0 :                     .do_update()
    1340            0 :                     .set(&bind)
    1341            0 :                     .execute(conn)
    1342            0 :                     .await?;
    1343              : 
    1344            0 :                 if inserted_updated != 1 {
    1345            0 :                     return Err(DatabaseError::Logical(format!(
    1346            0 :                         "unexpected number of rows ({})",
    1347            0 :                         inserted_updated
    1348            0 :                     )));
    1349            0 :                 }
    1350            0 : 
    1351            0 :                 Ok(())
    1352            0 :             })
    1353            0 :         })
    1354            0 :         .await
    1355            0 :     }
    1356              : 
    1357            0 :     pub(crate) async fn set_safekeeper_scheduling_policy(
    1358            0 :         &self,
    1359            0 :         id_: i64,
    1360            0 :         scheduling_policy_: SkSchedulingPolicy,
    1361            0 :     ) -> Result<(), DatabaseError> {
    1362              :         use crate::schema::safekeepers::dsl::*;
    1363              : 
    1364            0 :         self.with_conn(move |conn| {
    1365            0 :             Box::pin(async move {
    1366            0 :                 #[derive(Insertable, AsChangeset)]
    1367              :                 #[diesel(table_name = crate::schema::safekeepers)]
    1368              :                 struct UpdateSkSchedulingPolicy<'a> {
    1369              :                     id: i64,
    1370              :                     scheduling_policy: &'a str,
    1371              :                 }
    1372            0 :                 let scheduling_policy_ = String::from(scheduling_policy_);
    1373              : 
    1374            0 :                 let rows_affected = diesel::update(safekeepers.filter(id.eq(id_)))
    1375            0 :                     .set(scheduling_policy.eq(scheduling_policy_))
    1376            0 :                     .execute(conn)
    1377            0 :                     .await?;
    1378              : 
    1379            0 :                 if rows_affected != 1 {
    1380            0 :                     return Err(DatabaseError::Logical(format!(
    1381            0 :                         "unexpected number of rows ({rows_affected})",
    1382            0 :                     )));
    1383            0 :                 }
    1384            0 : 
    1385            0 :                 Ok(())
    1386            0 :             })
    1387            0 :         })
    1388            0 :         .await
    1389            0 :     }
    1390              : 
    1391              :     /// Persist timeline. Returns if the timeline was newly inserted. If it wasn't, we haven't done any writes.
    1392            0 :     pub(crate) async fn insert_timeline(&self, entry: TimelinePersistence) -> DatabaseResult<bool> {
    1393              :         use crate::schema::timelines;
    1394              : 
    1395            0 :         let entry = &entry;
    1396            0 :         self.with_measured_conn(DatabaseOperation::InsertTimeline, move |conn| {
    1397            0 :             Box::pin(async move {
    1398            0 :                 let inserted_updated = diesel::insert_into(timelines::table)
    1399            0 :                     .values(entry)
    1400            0 :                     .on_conflict((timelines::tenant_id, timelines::timeline_id))
    1401            0 :                     .do_nothing()
    1402            0 :                     .execute(conn)
    1403            0 :                     .await?;
    1404              : 
    1405            0 :                 match inserted_updated {
    1406            0 :                     0 => Ok(false),
    1407            0 :                     1 => Ok(true),
    1408            0 :                     _ => Err(DatabaseError::Logical(format!(
    1409            0 :                         "unexpected number of rows ({})",
    1410            0 :                         inserted_updated
    1411            0 :                     ))),
    1412              :                 }
    1413            0 :             })
    1414            0 :         })
    1415            0 :         .await
    1416            0 :     }
    1417              : 
    1418              :     /// Load timeline from db. Returns `None` if not present.
    1419            0 :     pub(crate) async fn get_timeline(
    1420            0 :         &self,
    1421            0 :         tenant_id: TenantId,
    1422            0 :         timeline_id: TimelineId,
    1423            0 :     ) -> DatabaseResult<Option<TimelinePersistence>> {
    1424              :         use crate::schema::timelines::dsl;
    1425              : 
    1426            0 :         let tenant_id = &tenant_id;
    1427            0 :         let timeline_id = &timeline_id;
    1428            0 :         let timeline_from_db = self
    1429            0 :             .with_measured_conn(DatabaseOperation::GetTimeline, move |conn| {
    1430            0 :                 Box::pin(async move {
    1431            0 :                     let mut from_db: Vec<TimelineFromDb> = dsl::timelines
    1432            0 :                         .filter(
    1433            0 :                             dsl::tenant_id
    1434            0 :                                 .eq(&tenant_id.to_string())
    1435            0 :                                 .and(dsl::timeline_id.eq(&timeline_id.to_string())),
    1436            0 :                         )
    1437            0 :                         .load(conn)
    1438            0 :                         .await?;
    1439            0 :                     if from_db.is_empty() {
    1440            0 :                         return Ok(None);
    1441            0 :                     }
    1442            0 :                     if from_db.len() != 1 {
    1443            0 :                         return Err(DatabaseError::Logical(format!(
    1444            0 :                             "unexpected number of rows ({})",
    1445            0 :                             from_db.len()
    1446            0 :                         )));
    1447            0 :                     }
    1448            0 : 
    1449            0 :                     Ok(Some(from_db.pop().unwrap().into_persistence()))
    1450            0 :                 })
    1451            0 :             })
    1452            0 :             .await?;
    1453              : 
    1454            0 :         Ok(timeline_from_db)
    1455            0 :     }
    1456              : 
    1457              :     /// Set `delete_at` for the given timeline
    1458            0 :     pub(crate) async fn timeline_set_deleted_at(
    1459            0 :         &self,
    1460            0 :         tenant_id: TenantId,
    1461            0 :         timeline_id: TimelineId,
    1462            0 :     ) -> DatabaseResult<()> {
    1463              :         use crate::schema::timelines;
    1464              : 
    1465            0 :         let deletion_time = chrono::Local::now().to_utc();
    1466            0 :         self.with_measured_conn(DatabaseOperation::InsertTimeline, move |conn| {
    1467            0 :             Box::pin(async move {
    1468            0 :                 let updated = diesel::update(timelines::table)
    1469            0 :                     .filter(timelines::tenant_id.eq(tenant_id.to_string()))
    1470            0 :                     .filter(timelines::timeline_id.eq(timeline_id.to_string()))
    1471            0 :                     .set(timelines::deleted_at.eq(Some(deletion_time)))
    1472            0 :                     .execute(conn)
    1473            0 :                     .await?;
    1474              : 
    1475            0 :                 match updated {
    1476            0 :                     0 => Ok(()),
    1477            0 :                     1 => Ok(()),
    1478            0 :                     _ => Err(DatabaseError::Logical(format!(
    1479            0 :                         "unexpected number of rows ({})",
    1480            0 :                         updated
    1481            0 :                     ))),
    1482              :                 }
    1483            0 :             })
    1484            0 :         })
    1485            0 :         .await
    1486            0 :     }
    1487              : 
    1488              :     /// Load timeline from db. Returns `None` if not present.
    1489              :     ///
    1490              :     /// Only works if `deleted_at` is set, so you should call [`Self::timeline_set_deleted_at`] before.
    1491            0 :     pub(crate) async fn delete_timeline(
    1492            0 :         &self,
    1493            0 :         tenant_id: TenantId,
    1494            0 :         timeline_id: TimelineId,
    1495            0 :     ) -> DatabaseResult<()> {
    1496              :         use crate::schema::timelines::dsl;
    1497              : 
    1498            0 :         let tenant_id = &tenant_id;
    1499            0 :         let timeline_id = &timeline_id;
    1500            0 :         self.with_measured_conn(DatabaseOperation::GetTimeline, move |conn| {
    1501            0 :             Box::pin(async move {
    1502            0 :                 diesel::delete(dsl::timelines)
    1503            0 :                     .filter(dsl::tenant_id.eq(&tenant_id.to_string()))
    1504            0 :                     .filter(dsl::timeline_id.eq(&timeline_id.to_string()))
    1505            0 :                     .filter(dsl::deleted_at.is_not_null())
    1506            0 :                     .execute(conn)
    1507            0 :                     .await?;
    1508            0 :                 Ok(())
    1509            0 :             })
    1510            0 :         })
    1511            0 :         .await?;
    1512              : 
    1513            0 :         Ok(())
    1514            0 :     }
    1515              : 
    1516              :     /// Loads a list of all timelines from database.
    1517            0 :     pub(crate) async fn list_timelines_for_tenant(
    1518            0 :         &self,
    1519            0 :         tenant_id: TenantId,
    1520            0 :     ) -> DatabaseResult<Vec<TimelinePersistence>> {
    1521              :         use crate::schema::timelines::dsl;
    1522              : 
    1523            0 :         let tenant_id = &tenant_id;
    1524            0 :         let timelines = self
    1525            0 :             .with_measured_conn(DatabaseOperation::GetTimeline, move |conn| {
    1526            0 :                 Box::pin(async move {
    1527            0 :                     let timelines: Vec<TimelineFromDb> = dsl::timelines
    1528            0 :                         .filter(dsl::tenant_id.eq(&tenant_id.to_string()))
    1529            0 :                         .load(conn)
    1530            0 :                         .await?;
    1531            0 :                     Ok(timelines)
    1532            0 :                 })
    1533            0 :             })
    1534            0 :             .await?;
    1535              : 
    1536            0 :         let timelines = timelines
    1537            0 :             .into_iter()
    1538            0 :             .map(TimelineFromDb::into_persistence)
    1539            0 :             .collect();
    1540            0 :         Ok(timelines)
    1541            0 :     }
    1542              : 
    1543              :     /// Persist pending op. Returns if it was newly inserted. If it wasn't, we haven't done any writes.
    1544            0 :     pub(crate) async fn insert_pending_op(
    1545            0 :         &self,
    1546            0 :         entry: TimelinePendingOpPersistence,
    1547            0 :     ) -> DatabaseResult<bool> {
    1548              :         use crate::schema::safekeeper_timeline_pending_ops as skpo;
    1549              :         // This overrides the `filter` fn used in other functions, so contain the mayhem via a function-local use
    1550              :         use diesel::query_dsl::methods::FilterDsl;
    1551              : 
    1552            0 :         let entry = &entry;
    1553            0 :         self.with_measured_conn(DatabaseOperation::InsertTimelineReconcile, move |conn| {
    1554            0 :             Box::pin(async move {
    1555              :                 // For simplicity it makes sense to keep only the last operation
    1556              :                 // per (tenant, timeline, sk) tuple: if we migrated a timeline
    1557              :                 // from node and adding it back it is not necessary to remove
    1558              :                 // data on it. Hence, generation is not part of primary key and
    1559              :                 // we override any rows with lower generations here.
    1560            0 :                 let inserted_updated = diesel::insert_into(skpo::table)
    1561            0 :                     .values(entry)
    1562            0 :                     .on_conflict((skpo::tenant_id, skpo::timeline_id, skpo::sk_id))
    1563            0 :                     .do_update()
    1564            0 :                     .set(entry)
    1565            0 :                     .filter(skpo::generation.lt(entry.generation))
    1566            0 :                     .execute(conn)
    1567            0 :                     .await?;
    1568              : 
    1569            0 :                 match inserted_updated {
    1570            0 :                     0 => Ok(false),
    1571            0 :                     1 => Ok(true),
    1572            0 :                     _ => Err(DatabaseError::Logical(format!(
    1573            0 :                         "unexpected number of rows ({})",
    1574            0 :                         inserted_updated
    1575            0 :                     ))),
    1576              :                 }
    1577            0 :             })
    1578            0 :         })
    1579            0 :         .await
    1580            0 :     }
    1581              :     /// Remove persisted pending op.
    1582            0 :     pub(crate) async fn remove_pending_op(
    1583            0 :         &self,
    1584            0 :         tenant_id: TenantId,
    1585            0 :         timeline_id: Option<TimelineId>,
    1586            0 :         sk_id: NodeId,
    1587            0 :         generation: u32,
    1588            0 :     ) -> DatabaseResult<()> {
    1589              :         use crate::schema::safekeeper_timeline_pending_ops::dsl;
    1590              : 
    1591            0 :         let tenant_id = &tenant_id;
    1592            0 :         let timeline_id = &timeline_id;
    1593            0 :         self.with_measured_conn(DatabaseOperation::RemoveTimelineReconcile, move |conn| {
    1594            0 :             let timeline_id_str = timeline_id.map(|tid| tid.to_string()).unwrap_or_default();
    1595            0 :             Box::pin(async move {
    1596            0 :                 diesel::delete(dsl::safekeeper_timeline_pending_ops)
    1597            0 :                     .filter(dsl::tenant_id.eq(tenant_id.to_string()))
    1598            0 :                     .filter(dsl::timeline_id.eq(timeline_id_str))
    1599            0 :                     .filter(dsl::sk_id.eq(sk_id.0 as i64))
    1600            0 :                     .filter(dsl::generation.eq(generation as i32))
    1601            0 :                     .execute(conn)
    1602            0 :                     .await?;
    1603            0 :                 Ok(())
    1604            0 :             })
    1605            0 :         })
    1606            0 :         .await
    1607            0 :     }
    1608              : 
    1609              :     /// Load pending operations from db, joined together with timeline data.
    1610            0 :     pub(crate) async fn list_pending_ops_with_timelines(
    1611            0 :         &self,
    1612            0 :     ) -> DatabaseResult<Vec<(TimelinePendingOpPersistence, Option<TimelinePersistence>)>> {
    1613              :         use crate::schema::safekeeper_timeline_pending_ops::dsl;
    1614              :         use crate::schema::timelines;
    1615              : 
    1616            0 :         let timeline_from_db = self
    1617            0 :             .with_measured_conn(
    1618            0 :                 DatabaseOperation::ListTimelineReconcileStartup,
    1619            0 :                 move |conn| {
    1620            0 :                     Box::pin(async move {
    1621            0 :                         let from_db: Vec<(TimelinePendingOpPersistence, Option<TimelineFromDb>)> =
    1622            0 :                             dsl::safekeeper_timeline_pending_ops
    1623            0 :                                 .left_join(
    1624            0 :                                     timelines::table.on(timelines::tenant_id
    1625            0 :                                         .eq(dsl::tenant_id)
    1626            0 :                                         .and(timelines::timeline_id.eq(dsl::timeline_id))),
    1627            0 :                                 )
    1628            0 :                                 .select((
    1629            0 :                                     TimelinePendingOpPersistence::as_select(),
    1630            0 :                                     Option::<TimelineFromDb>::as_select(),
    1631            0 :                                 ))
    1632            0 :                                 .load(conn)
    1633            0 :                                 .await?;
    1634            0 :                         Ok(from_db)
    1635            0 :                     })
    1636            0 :                 },
    1637            0 :             )
    1638            0 :             .await?;
    1639              : 
    1640            0 :         Ok(timeline_from_db
    1641            0 :             .into_iter()
    1642            0 :             .map(|(op, tl_opt)| (op, tl_opt.map(|tl_opt| tl_opt.into_persistence())))
    1643            0 :             .collect())
    1644            0 :     }
    1645              :     /// List pending operations for a given timeline (including tenant-global ones)
    1646            0 :     pub(crate) async fn list_pending_ops_for_timeline(
    1647            0 :         &self,
    1648            0 :         tenant_id: TenantId,
    1649            0 :         timeline_id: TimelineId,
    1650            0 :     ) -> DatabaseResult<Vec<TimelinePendingOpPersistence>> {
    1651              :         use crate::schema::safekeeper_timeline_pending_ops::dsl;
    1652              : 
    1653            0 :         let timelines_from_db = self
    1654            0 :             .with_measured_conn(DatabaseOperation::ListTimelineReconcile, move |conn| {
    1655            0 :                 Box::pin(async move {
    1656            0 :                     let from_db: Vec<TimelinePendingOpPersistence> =
    1657            0 :                         dsl::safekeeper_timeline_pending_ops
    1658            0 :                             .filter(dsl::tenant_id.eq(tenant_id.to_string()))
    1659            0 :                             .filter(
    1660            0 :                                 dsl::timeline_id
    1661            0 :                                     .eq(timeline_id.to_string())
    1662            0 :                                     .or(dsl::timeline_id.eq("")),
    1663            0 :                             )
    1664            0 :                             .load(conn)
    1665            0 :                             .await?;
    1666            0 :                     Ok(from_db)
    1667            0 :                 })
    1668            0 :             })
    1669            0 :             .await?;
    1670              : 
    1671            0 :         Ok(timelines_from_db)
    1672            0 :     }
    1673              : 
    1674              :     /// Delete all pending ops for the given timeline.
    1675              :     ///
    1676              :     /// Use this only at timeline deletion, otherwise use generation based APIs
    1677            0 :     pub(crate) async fn remove_pending_ops_for_timeline(
    1678            0 :         &self,
    1679            0 :         tenant_id: TenantId,
    1680            0 :         timeline_id: Option<TimelineId>,
    1681            0 :     ) -> DatabaseResult<()> {
    1682              :         use crate::schema::safekeeper_timeline_pending_ops::dsl;
    1683              : 
    1684            0 :         let tenant_id = &tenant_id;
    1685            0 :         let timeline_id = &timeline_id;
    1686            0 :         self.with_measured_conn(DatabaseOperation::RemoveTimelineReconcile, move |conn| {
    1687            0 :             let timeline_id_str = timeline_id.map(|tid| tid.to_string()).unwrap_or_default();
    1688            0 :             Box::pin(async move {
    1689            0 :                 diesel::delete(dsl::safekeeper_timeline_pending_ops)
    1690            0 :                     .filter(dsl::tenant_id.eq(tenant_id.to_string()))
    1691            0 :                     .filter(dsl::timeline_id.eq(timeline_id_str))
    1692            0 :                     .execute(conn)
    1693            0 :                     .await?;
    1694            0 :                 Ok(())
    1695            0 :             })
    1696            0 :         })
    1697            0 :         .await?;
    1698              : 
    1699            0 :         Ok(())
    1700            0 :     }
    1701              : 
    1702            0 :     pub(crate) async fn insert_timeline_import(
    1703            0 :         &self,
    1704            0 :         import: TimelineImportPersistence,
    1705            0 :     ) -> DatabaseResult<bool> {
    1706            0 :         self.with_measured_conn(DatabaseOperation::InsertTimelineImport, move |conn| {
    1707            0 :             Box::pin({
    1708            0 :                 let import = import.clone();
    1709            0 :                 async move {
    1710            0 :                     let inserted = diesel::insert_into(crate::schema::timeline_imports::table)
    1711            0 :                         .values(import)
    1712            0 :                         .execute(conn)
    1713            0 :                         .await?;
    1714            0 :                     Ok(inserted == 1)
    1715            0 :                 }
    1716            0 :             })
    1717            0 :         })
    1718            0 :         .await
    1719            0 :     }
    1720              : 
    1721            0 :     pub(crate) async fn list_timeline_imports(&self) -> DatabaseResult<Vec<TimelineImport>> {
    1722              :         use crate::schema::timeline_imports::dsl;
    1723            0 :         let persistent = self
    1724            0 :             .with_measured_conn(DatabaseOperation::ListTimelineImports, move |conn| {
    1725            0 :                 Box::pin(async move {
    1726            0 :                     let from_db: Vec<TimelineImportPersistence> =
    1727            0 :                         dsl::timeline_imports.load(conn).await?;
    1728            0 :                     Ok(from_db)
    1729            0 :                 })
    1730            0 :             })
    1731            0 :             .await?;
    1732              : 
    1733            0 :         let imports: Result<Vec<TimelineImport>, _> = persistent
    1734            0 :             .into_iter()
    1735            0 :             .map(TimelineImport::from_persistent)
    1736            0 :             .collect();
    1737            0 :         match imports {
    1738            0 :             Ok(ok) => Ok(ok.into_iter().collect()),
    1739            0 :             Err(err) => Err(DatabaseError::Logical(format!(
    1740            0 :                 "failed to deserialize import: {err}"
    1741            0 :             ))),
    1742              :         }
    1743            0 :     }
    1744              : 
    1745            0 :     pub(crate) async fn get_timeline_import(
    1746            0 :         &self,
    1747            0 :         tenant_id: TenantId,
    1748            0 :         timeline_id: TimelineId,
    1749            0 :     ) -> DatabaseResult<Option<TimelineImport>> {
    1750              :         use crate::schema::timeline_imports::dsl;
    1751            0 :         let persistent_import = self
    1752            0 :             .with_measured_conn(DatabaseOperation::ListTimelineImports, move |conn| {
    1753            0 :                 Box::pin(async move {
    1754            0 :                     let mut from_db: Vec<TimelineImportPersistence> = dsl::timeline_imports
    1755            0 :                         .filter(dsl::tenant_id.eq(tenant_id.to_string()))
    1756            0 :                         .filter(dsl::timeline_id.eq(timeline_id.to_string()))
    1757            0 :                         .load(conn)
    1758            0 :                         .await?;
    1759              : 
    1760            0 :                     if from_db.len() > 1 {
    1761            0 :                         return Err(DatabaseError::Logical(format!(
    1762            0 :                             "unexpected number of rows ({})",
    1763            0 :                             from_db.len()
    1764            0 :                         )));
    1765            0 :                     }
    1766            0 : 
    1767            0 :                     Ok(from_db.pop())
    1768            0 :                 })
    1769            0 :             })
    1770            0 :             .await?;
    1771              : 
    1772            0 :         persistent_import
    1773            0 :             .map(TimelineImport::from_persistent)
    1774            0 :             .transpose()
    1775            0 :             .map_err(|err| DatabaseError::Logical(format!("failed to deserialize import: {err}")))
    1776            0 :     }
    1777              : 
    1778            0 :     pub(crate) async fn delete_timeline_import(
    1779            0 :         &self,
    1780            0 :         tenant_id: TenantId,
    1781            0 :         timeline_id: TimelineId,
    1782            0 :     ) -> DatabaseResult<()> {
    1783              :         use crate::schema::timeline_imports::dsl;
    1784              : 
    1785            0 :         self.with_measured_conn(DatabaseOperation::DeleteTimelineImport, move |conn| {
    1786            0 :             Box::pin(async move {
    1787            0 :                 diesel::delete(crate::schema::timeline_imports::table)
    1788            0 :                     .filter(
    1789            0 :                         dsl::tenant_id
    1790            0 :                             .eq(tenant_id.to_string())
    1791            0 :                             .and(dsl::timeline_id.eq(timeline_id.to_string())),
    1792            0 :                     )
    1793            0 :                     .execute(conn)
    1794            0 :                     .await?;
    1795              : 
    1796            0 :                 Ok(())
    1797            0 :             })
    1798            0 :         })
    1799            0 :         .await
    1800            0 :     }
    1801              : 
    1802              :     /// Idempotently update the status of one shard for an ongoing timeline import
    1803              :     ///
    1804              :     /// If the update was persisted to the database, then the current state of the
    1805              :     /// import is returned to the caller. In case of logical errors a bespoke
    1806              :     /// [`TimelineImportUpdateError`] instance is returned. Other database errors
    1807              :     /// are covered by the outer [`DatabaseError`].
    1808            0 :     pub(crate) async fn update_timeline_import(
    1809            0 :         &self,
    1810            0 :         tenant_shard_id: TenantShardId,
    1811            0 :         timeline_id: TimelineId,
    1812            0 :         shard_status: ShardImportStatus,
    1813            0 :     ) -> DatabaseResult<Result<Option<TimelineImport>, TimelineImportUpdateError>> {
    1814              :         use crate::schema::timeline_imports::dsl;
    1815              : 
    1816            0 :         self.with_measured_conn(DatabaseOperation::UpdateTimelineImport, move |conn| {
    1817            0 :             Box::pin({
    1818            0 :                 let shard_status = shard_status.clone();
    1819            0 :                 async move {
    1820              :                     // Load the current state from the database
    1821            0 :                     let mut from_db: Vec<TimelineImportPersistence> = dsl::timeline_imports
    1822            0 :                         .filter(
    1823            0 :                             dsl::tenant_id
    1824            0 :                                 .eq(tenant_shard_id.tenant_id.to_string())
    1825            0 :                                 .and(dsl::timeline_id.eq(timeline_id.to_string())),
    1826            0 :                         )
    1827            0 :                         .load(conn)
    1828            0 :                         .await?;
    1829              : 
    1830            0 :                     assert!(from_db.len() <= 1);
    1831              : 
    1832            0 :                     let mut status = match from_db.pop() {
    1833            0 :                         Some(some) => TimelineImport::from_persistent(some).unwrap(),
    1834              :                         None => {
    1835            0 :                             return Ok(Err(TimelineImportUpdateError::ImportNotFound {
    1836            0 :                                 tenant_id: tenant_shard_id.tenant_id,
    1837            0 :                                 timeline_id,
    1838            0 :                             }));
    1839              :                         }
    1840              :                     };
    1841              : 
    1842              :                     // Perform the update in-memory
    1843            0 :                     let follow_up = match status.update(tenant_shard_id.to_index(), shard_status) {
    1844            0 :                         Ok(ok) => ok,
    1845            0 :                         Err(err) => {
    1846            0 :                             return Ok(Err(err));
    1847              :                         }
    1848              :                     };
    1849              : 
    1850            0 :                     let new_persistent = status.to_persistent();
    1851            0 : 
    1852            0 :                     // Write back if required (in the same transaction)
    1853            0 :                     match follow_up {
    1854              :                         TimelineImportUpdateFollowUp::Persist => {
    1855            0 :                             let updated = diesel::update(dsl::timeline_imports)
    1856            0 :                                 .filter(
    1857            0 :                                     dsl::tenant_id
    1858            0 :                                         .eq(tenant_shard_id.tenant_id.to_string())
    1859            0 :                                         .and(dsl::timeline_id.eq(timeline_id.to_string())),
    1860            0 :                                 )
    1861            0 :                                 .set(dsl::shard_statuses.eq(new_persistent.shard_statuses))
    1862            0 :                                 .execute(conn)
    1863            0 :                                 .await?;
    1864              : 
    1865            0 :                             if updated != 1 {
    1866            0 :                                 return Ok(Err(TimelineImportUpdateError::ImportNotFound {
    1867            0 :                                     tenant_id: tenant_shard_id.tenant_id,
    1868            0 :                                     timeline_id,
    1869            0 :                                 }));
    1870            0 :                             }
    1871            0 : 
    1872            0 :                             Ok(Ok(Some(status)))
    1873              :                         }
    1874            0 :                         TimelineImportUpdateFollowUp::None => Ok(Ok(None)),
    1875              :                     }
    1876            0 :                 }
    1877            0 :             })
    1878            0 :         })
    1879            0 :         .await
    1880            0 :     }
    1881              : 
    1882            0 :     pub(crate) async fn is_tenant_importing_timeline(
    1883            0 :         &self,
    1884            0 :         tenant_id: TenantId,
    1885            0 :     ) -> DatabaseResult<bool> {
    1886              :         use crate::schema::timeline_imports::dsl;
    1887            0 :         self.with_measured_conn(DatabaseOperation::IsTenantImportingTimeline, move |conn| {
    1888            0 :             Box::pin(async move {
    1889            0 :                 let imports: i64 = dsl::timeline_imports
    1890            0 :                     .filter(dsl::tenant_id.eq(tenant_id.to_string()))
    1891            0 :                     .count()
    1892            0 :                     .get_result(conn)
    1893            0 :                     .await?;
    1894              : 
    1895            0 :                 Ok(imports > 0)
    1896            0 :             })
    1897            0 :         })
    1898            0 :         .await
    1899            0 :     }
    1900              : }
    1901              : 
    1902            0 : pub(crate) fn load_certs() -> anyhow::Result<Arc<rustls::RootCertStore>> {
    1903            0 :     let der_certs = rustls_native_certs::load_native_certs();
    1904            0 : 
    1905            0 :     if !der_certs.errors.is_empty() {
    1906            0 :         anyhow::bail!("could not parse certificates: {:?}", der_certs.errors);
    1907            0 :     }
    1908            0 : 
    1909            0 :     let mut store = rustls::RootCertStore::empty();
    1910            0 :     store.add_parsable_certificates(der_certs.certs);
    1911            0 :     Ok(Arc::new(store))
    1912            0 : }
    1913              : 
    1914              : #[derive(Debug)]
    1915              : /// A verifier that accepts all certificates (but logs an error still)
    1916              : struct AcceptAll(Arc<WebPkiServerVerifier>);
    1917              : impl ServerCertVerifier for AcceptAll {
    1918            0 :     fn verify_server_cert(
    1919            0 :         &self,
    1920            0 :         end_entity: &rustls::pki_types::CertificateDer<'_>,
    1921            0 :         intermediates: &[rustls::pki_types::CertificateDer<'_>],
    1922            0 :         server_name: &rustls::pki_types::ServerName<'_>,
    1923            0 :         ocsp_response: &[u8],
    1924            0 :         now: rustls::pki_types::UnixTime,
    1925            0 :     ) -> Result<ServerCertVerified, rustls::Error> {
    1926            0 :         let r =
    1927            0 :             self.0
    1928            0 :                 .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now);
    1929            0 :         if let Err(err) = r {
    1930            0 :             tracing::info!(
    1931              :                 ?server_name,
    1932            0 :                 "ignoring db connection TLS validation error: {err:?}"
    1933              :             );
    1934            0 :             return Ok(ServerCertVerified::assertion());
    1935            0 :         }
    1936            0 :         r
    1937            0 :     }
    1938            0 :     fn verify_tls12_signature(
    1939            0 :         &self,
    1940            0 :         message: &[u8],
    1941            0 :         cert: &rustls::pki_types::CertificateDer<'_>,
    1942            0 :         dss: &rustls::DigitallySignedStruct,
    1943            0 :     ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
    1944            0 :         self.0.verify_tls12_signature(message, cert, dss)
    1945            0 :     }
    1946            0 :     fn verify_tls13_signature(
    1947            0 :         &self,
    1948            0 :         message: &[u8],
    1949            0 :         cert: &rustls::pki_types::CertificateDer<'_>,
    1950            0 :         dss: &rustls::DigitallySignedStruct,
    1951            0 :     ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
    1952            0 :         self.0.verify_tls13_signature(message, cert, dss)
    1953            0 :     }
    1954            0 :     fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
    1955            0 :         self.0.supported_verify_schemes()
    1956            0 :     }
    1957              : }
    1958              : 
    1959              : /// Loads the root certificates and constructs a client config suitable for connecting.
    1960              : /// This function is blocking.
    1961            0 : fn client_config_with_root_certs() -> anyhow::Result<rustls::ClientConfig> {
    1962            0 :     let client_config =
    1963            0 :         rustls::ClientConfig::builder_with_provider(Arc::new(ring::default_provider()))
    1964            0 :             .with_safe_default_protocol_versions()
    1965            0 :             .expect("ring should support the default protocol versions");
    1966              :     static DO_CERT_CHECKS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    1967            0 :     let do_cert_checks =
    1968            0 :         DO_CERT_CHECKS.get_or_init(|| std::env::var("STORCON_DB_CERT_CHECKS").is_ok());
    1969            0 :     Ok(if *do_cert_checks {
    1970            0 :         client_config
    1971            0 :             .with_root_certificates(load_certs()?)
    1972            0 :             .with_no_client_auth()
    1973              :     } else {
    1974            0 :         let verifier = AcceptAll(
    1975              :             WebPkiServerVerifier::builder_with_provider(
    1976            0 :                 load_certs()?,
    1977            0 :                 Arc::new(ring::default_provider()),
    1978            0 :             )
    1979            0 :             .build()?,
    1980              :         );
    1981            0 :         client_config
    1982            0 :             .dangerous()
    1983            0 :             .with_custom_certificate_verifier(Arc::new(verifier))
    1984            0 :             .with_no_client_auth()
    1985              :     })
    1986            0 : }
    1987              : 
    1988            0 : fn establish_connection_rustls(config: &str) -> BoxFuture<ConnectionResult<AsyncPgConnection>> {
    1989            0 :     let fut = async {
    1990              :         // We first set up the way we want rustls to work.
    1991            0 :         let rustls_config = client_config_with_root_certs()
    1992            0 :             .map_err(|err| ConnectionError::BadConnection(format!("{err:?}")))?;
    1993            0 :         let tls = tokio_postgres_rustls::MakeRustlsConnect::new(rustls_config);
    1994            0 :         let (client, conn) = tokio_postgres::connect(config, tls)
    1995            0 :             .await
    1996            0 :             .map_err(|e| ConnectionError::BadConnection(e.to_string()))?;
    1997              : 
    1998            0 :         AsyncPgConnection::try_from_client_and_connection(client, conn).await
    1999            0 :     };
    2000            0 :     fut.boxed()
    2001            0 : }
    2002              : 
    2003              : #[cfg_attr(test, test)]
    2004            1 : fn test_config_debug_censors_password() {
    2005            1 :     let has_pw =
    2006            1 :         "host=/var/lib/postgresql,localhost port=1234 user=specialuser password='NOT ALLOWED TAG'";
    2007            1 :     let has_pw_cfg = has_pw.parse::<tokio_postgres::Config>().unwrap();
    2008            1 :     assert!(format!("{has_pw_cfg:?}").contains("specialuser"));
    2009              :     // Ensure that the password is not leaked by the debug impl
    2010            1 :     assert!(!format!("{has_pw_cfg:?}").contains("NOT ALLOWED TAG"));
    2011            1 : }
    2012              : 
    2013            0 : fn log_postgres_connstr_info(config_str: &str) -> anyhow::Result<()> {
    2014            0 :     let config = config_str
    2015            0 :         .parse::<tokio_postgres::Config>()
    2016            0 :         .map_err(|_e| anyhow::anyhow!("Couldn't parse config str"))?;
    2017              :     // We use debug formatting here, and use a unit test to ensure that we don't leak the password.
    2018              :     // To make extra sure the test gets ran, run it every time the function is called
    2019              :     // (this is rather cold code, we can afford it).
    2020              :     #[cfg(not(test))]
    2021            0 :     test_config_debug_censors_password();
    2022            0 :     tracing::info!("database connection config: {config:?}");
    2023            0 :     Ok(())
    2024            0 : }
    2025              : 
    2026              : /// Parts of [`crate::tenant_shard::TenantShard`] that are stored durably
    2027              : #[derive(
    2028            0 :     QueryableByName, Queryable, Selectable, Insertable, Serialize, Deserialize, Clone, Eq, PartialEq,
    2029              : )]
    2030              : #[diesel(table_name = crate::schema::tenant_shards)]
    2031              : pub(crate) struct TenantShardPersistence {
    2032              :     #[serde(default)]
    2033              :     pub(crate) tenant_id: String,
    2034              :     #[serde(default)]
    2035              :     pub(crate) shard_number: i32,
    2036              :     #[serde(default)]
    2037              :     pub(crate) shard_count: i32,
    2038              :     #[serde(default)]
    2039              :     pub(crate) shard_stripe_size: i32,
    2040              : 
    2041              :     // Latest generation number: next time we attach, increment this
    2042              :     // and use the incremented number when attaching.
    2043              :     //
    2044              :     // Generation is only None when first onboarding a tenant, where it may
    2045              :     // be in PlacementPolicy::Secondary and therefore have no valid generation state.
    2046              :     pub(crate) generation: Option<i32>,
    2047              : 
    2048              :     // Currently attached pageserver
    2049              :     #[serde(rename = "pageserver")]
    2050              :     pub(crate) generation_pageserver: Option<i64>,
    2051              : 
    2052              :     #[serde(default)]
    2053              :     pub(crate) placement_policy: String,
    2054              :     #[serde(default)]
    2055              :     pub(crate) splitting: SplitState,
    2056              :     #[serde(default)]
    2057              :     pub(crate) config: String,
    2058              :     #[serde(default)]
    2059              :     pub(crate) scheduling_policy: String,
    2060              : 
    2061              :     // Hint that we should attempt to schedule this tenant shard the given
    2062              :     // availability zone in order to minimise the chances of cross-AZ communication
    2063              :     // with compute.
    2064              :     pub(crate) preferred_az_id: Option<String>,
    2065              : }
    2066              : 
    2067              : impl TenantShardPersistence {
    2068            0 :     fn get_shard_count(&self) -> Result<ShardCount, ShardConfigError> {
    2069            0 :         self.shard_count
    2070            0 :             .try_into()
    2071            0 :             .map(ShardCount)
    2072            0 :             .map_err(|_| ShardConfigError::InvalidCount)
    2073            0 :     }
    2074              : 
    2075            0 :     fn get_shard_number(&self) -> Result<ShardNumber, ShardConfigError> {
    2076            0 :         self.shard_number
    2077            0 :             .try_into()
    2078            0 :             .map(ShardNumber)
    2079            0 :             .map_err(|_| ShardConfigError::InvalidNumber)
    2080            0 :     }
    2081              : 
    2082            0 :     fn get_stripe_size(&self) -> Result<ShardStripeSize, ShardConfigError> {
    2083            0 :         self.shard_stripe_size
    2084            0 :             .try_into()
    2085            0 :             .map(ShardStripeSize)
    2086            0 :             .map_err(|_| ShardConfigError::InvalidStripeSize)
    2087            0 :     }
    2088              : 
    2089            0 :     pub(crate) fn get_shard_identity(&self) -> Result<ShardIdentity, ShardConfigError> {
    2090            0 :         if self.shard_count == 0 {
    2091              :             // NB: carry over the stripe size from the persisted record, to avoid consistency check
    2092              :             // failures if the persisted value differs from the default stripe size. The stripe size
    2093              :             // doesn't really matter for unsharded tenants anyway.
    2094              :             Ok(ShardIdentity::unsharded_with_stripe_size(
    2095            0 :                 self.get_stripe_size()?,
    2096              :             ))
    2097              :         } else {
    2098              :             Ok(ShardIdentity::new(
    2099            0 :                 self.get_shard_number()?,
    2100            0 :                 self.get_shard_count()?,
    2101            0 :                 self.get_stripe_size()?,
    2102            0 :             )?)
    2103              :         }
    2104            0 :     }
    2105              : 
    2106            0 :     pub(crate) fn get_tenant_shard_id(&self) -> anyhow::Result<TenantShardId> {
    2107            0 :         Ok(TenantShardId {
    2108            0 :             tenant_id: TenantId::from_str(self.tenant_id.as_str())?,
    2109            0 :             shard_number: self.get_shard_number()?,
    2110            0 :             shard_count: self.get_shard_count()?,
    2111              :         })
    2112            0 :     }
    2113              : }
    2114              : 
    2115              : /// Parts of [`crate::node::Node`] that are stored durably
    2116            0 : #[derive(Serialize, Deserialize, Queryable, Selectable, Insertable, Eq, PartialEq)]
    2117              : #[diesel(table_name = crate::schema::nodes)]
    2118              : pub(crate) struct NodePersistence {
    2119              :     pub(crate) node_id: i64,
    2120              :     pub(crate) scheduling_policy: String,
    2121              :     pub(crate) listen_http_addr: String,
    2122              :     pub(crate) listen_http_port: i32,
    2123              :     pub(crate) listen_pg_addr: String,
    2124              :     pub(crate) listen_pg_port: i32,
    2125              :     pub(crate) availability_zone_id: String,
    2126              :     pub(crate) listen_https_port: Option<i32>,
    2127              :     pub(crate) lifecycle: String,
    2128              : }
    2129              : 
    2130              : /// Tenant metadata health status that are stored durably.
    2131            0 : #[derive(Queryable, Selectable, Insertable, Serialize, Deserialize, Clone, Eq, PartialEq)]
    2132              : #[diesel(table_name = crate::schema::metadata_health)]
    2133              : pub(crate) struct MetadataHealthPersistence {
    2134              :     #[serde(default)]
    2135              :     pub(crate) tenant_id: String,
    2136              :     #[serde(default)]
    2137              :     pub(crate) shard_number: i32,
    2138              :     #[serde(default)]
    2139              :     pub(crate) shard_count: i32,
    2140              : 
    2141              :     pub(crate) healthy: bool,
    2142              :     pub(crate) last_scrubbed_at: chrono::DateTime<chrono::Utc>,
    2143              : }
    2144              : 
    2145              : impl MetadataHealthPersistence {
    2146            0 :     pub fn new(
    2147            0 :         tenant_shard_id: TenantShardId,
    2148            0 :         healthy: bool,
    2149            0 :         last_scrubbed_at: chrono::DateTime<chrono::Utc>,
    2150            0 :     ) -> Self {
    2151            0 :         let tenant_id = tenant_shard_id.tenant_id.to_string();
    2152            0 :         let shard_number = tenant_shard_id.shard_number.0 as i32;
    2153            0 :         let shard_count = tenant_shard_id.shard_count.literal() as i32;
    2154            0 : 
    2155            0 :         MetadataHealthPersistence {
    2156            0 :             tenant_id,
    2157            0 :             shard_number,
    2158            0 :             shard_count,
    2159            0 :             healthy,
    2160            0 :             last_scrubbed_at,
    2161            0 :         }
    2162            0 :     }
    2163              : 
    2164              :     #[allow(dead_code)]
    2165            0 :     pub(crate) fn get_tenant_shard_id(&self) -> Result<TenantShardId, hex::FromHexError> {
    2166            0 :         Ok(TenantShardId {
    2167            0 :             tenant_id: TenantId::from_str(self.tenant_id.as_str())?,
    2168            0 :             shard_number: ShardNumber(self.shard_number as u8),
    2169            0 :             shard_count: ShardCount::new(self.shard_count as u8),
    2170              :         })
    2171            0 :     }
    2172              : }
    2173              : 
    2174              : impl From<MetadataHealthPersistence> for MetadataHealthRecord {
    2175            0 :     fn from(value: MetadataHealthPersistence) -> Self {
    2176            0 :         MetadataHealthRecord {
    2177            0 :             tenant_shard_id: value
    2178            0 :                 .get_tenant_shard_id()
    2179            0 :                 .expect("stored tenant id should be valid"),
    2180            0 :             healthy: value.healthy,
    2181            0 :             last_scrubbed_at: value.last_scrubbed_at,
    2182            0 :         }
    2183            0 :     }
    2184              : }
    2185              : 
    2186              : #[derive(
    2187            0 :     Serialize, Deserialize, Queryable, Selectable, Insertable, Eq, PartialEq, Debug, Clone,
    2188              : )]
    2189              : #[diesel(table_name = crate::schema::controllers)]
    2190              : pub(crate) struct ControllerPersistence {
    2191              :     pub(crate) address: String,
    2192              :     pub(crate) started_at: chrono::DateTime<chrono::Utc>,
    2193              : }
    2194              : 
    2195              : // What we store in the database
    2196            0 : #[derive(Serialize, Deserialize, Queryable, Selectable, Eq, PartialEq, Debug, Clone)]
    2197              : #[diesel(table_name = crate::schema::safekeepers)]
    2198              : pub(crate) struct SafekeeperPersistence {
    2199              :     pub(crate) id: i64,
    2200              :     pub(crate) region_id: String,
    2201              :     /// 1 is special, it means just created (not currently posted to storcon).
    2202              :     /// Zero or negative is not really expected.
    2203              :     /// Otherwise the number from `release-$(number_of_commits_on_branch)` tag.
    2204              :     pub(crate) version: i64,
    2205              :     pub(crate) host: String,
    2206              :     pub(crate) port: i32,
    2207              :     pub(crate) http_port: i32,
    2208              :     pub(crate) availability_zone_id: String,
    2209              :     pub(crate) scheduling_policy: SkSchedulingPolicyFromSql,
    2210              :     pub(crate) https_port: Option<i32>,
    2211              : }
    2212              : 
    2213              : /// Wrapper struct around [`SkSchedulingPolicy`] because both it and [`FromSql`] are from foreign crates,
    2214              : /// and we don't want to make [`safekeeper_api`] depend on [`diesel`].
    2215            0 : #[derive(Serialize, Deserialize, FromSqlRow, Eq, PartialEq, Debug, Copy, Clone)]
    2216              : pub(crate) struct SkSchedulingPolicyFromSql(pub(crate) SkSchedulingPolicy);
    2217              : 
    2218              : impl From<SkSchedulingPolicy> for SkSchedulingPolicyFromSql {
    2219            0 :     fn from(value: SkSchedulingPolicy) -> Self {
    2220            0 :         SkSchedulingPolicyFromSql(value)
    2221            0 :     }
    2222              : }
    2223              : 
    2224              : impl FromSql<diesel::sql_types::VarChar, Pg> for SkSchedulingPolicyFromSql {
    2225            0 :     fn from_sql(
    2226            0 :         bytes: <Pg as diesel::backend::Backend>::RawValue<'_>,
    2227            0 :     ) -> diesel::deserialize::Result<Self> {
    2228            0 :         let bytes = bytes.as_bytes();
    2229            0 :         match core::str::from_utf8(bytes) {
    2230            0 :             Ok(s) => match SkSchedulingPolicy::from_str(s) {
    2231            0 :                 Ok(policy) => Ok(SkSchedulingPolicyFromSql(policy)),
    2232            0 :                 Err(e) => Err(format!("can't parse: {e}").into()),
    2233              :             },
    2234            0 :             Err(e) => Err(format!("invalid UTF-8 for scheduling policy: {e}").into()),
    2235              :         }
    2236            0 :     }
    2237              : }
    2238              : 
    2239              : impl SafekeeperPersistence {
    2240            0 :     pub(crate) fn from_upsert(
    2241            0 :         upsert: SafekeeperUpsert,
    2242            0 :         scheduling_policy: SkSchedulingPolicy,
    2243            0 :     ) -> Self {
    2244            0 :         crate::persistence::SafekeeperPersistence {
    2245            0 :             id: upsert.id,
    2246            0 :             region_id: upsert.region_id,
    2247            0 :             version: upsert.version,
    2248            0 :             host: upsert.host,
    2249            0 :             port: upsert.port,
    2250            0 :             http_port: upsert.http_port,
    2251            0 :             https_port: upsert.https_port,
    2252            0 :             availability_zone_id: upsert.availability_zone_id,
    2253            0 :             scheduling_policy: SkSchedulingPolicyFromSql(scheduling_policy),
    2254            0 :         }
    2255            0 :     }
    2256            0 :     pub(crate) fn as_describe_response(&self) -> Result<SafekeeperDescribeResponse, DatabaseError> {
    2257            0 :         Ok(SafekeeperDescribeResponse {
    2258            0 :             id: NodeId(self.id as u64),
    2259            0 :             region_id: self.region_id.clone(),
    2260            0 :             version: self.version,
    2261            0 :             host: self.host.clone(),
    2262            0 :             port: self.port,
    2263            0 :             http_port: self.http_port,
    2264            0 :             https_port: self.https_port,
    2265            0 :             availability_zone_id: self.availability_zone_id.clone(),
    2266            0 :             scheduling_policy: self.scheduling_policy.0,
    2267            0 :         })
    2268            0 :     }
    2269              : }
    2270              : 
    2271              : /// What we expect from the upsert http api
    2272            0 : #[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone)]
    2273              : pub(crate) struct SafekeeperUpsert {
    2274              :     pub(crate) id: i64,
    2275              :     pub(crate) region_id: String,
    2276              :     /// 1 is special, it means just created (not currently posted to storcon).
    2277              :     /// Zero or negative is not really expected.
    2278              :     /// Otherwise the number from `release-$(number_of_commits_on_branch)` tag.
    2279              :     pub(crate) version: i64,
    2280              :     pub(crate) host: String,
    2281              :     pub(crate) port: i32,
    2282              :     /// The active flag will not be stored in the database and will be ignored.
    2283              :     pub(crate) active: Option<bool>,
    2284              :     pub(crate) http_port: i32,
    2285              :     pub(crate) https_port: Option<i32>,
    2286              :     pub(crate) availability_zone_id: String,
    2287              : }
    2288              : 
    2289              : impl SafekeeperUpsert {
    2290            0 :     fn as_insert_or_update(&self) -> anyhow::Result<InsertUpdateSafekeeper<'_>> {
    2291            0 :         if self.version < 0 {
    2292            0 :             anyhow::bail!("negative version: {}", self.version);
    2293            0 :         }
    2294            0 :         Ok(InsertUpdateSafekeeper {
    2295            0 :             id: self.id,
    2296            0 :             region_id: &self.region_id,
    2297            0 :             version: self.version,
    2298            0 :             host: &self.host,
    2299            0 :             port: self.port,
    2300            0 :             http_port: self.http_port,
    2301            0 :             https_port: self.https_port,
    2302            0 :             availability_zone_id: &self.availability_zone_id,
    2303            0 :             // None means a wish to not update this column. We expose abilities to update it via other means.
    2304            0 :             scheduling_policy: None,
    2305            0 :         })
    2306            0 :     }
    2307              : }
    2308              : 
    2309            0 : #[derive(Insertable, AsChangeset)]
    2310              : #[diesel(table_name = crate::schema::safekeepers)]
    2311              : struct InsertUpdateSafekeeper<'a> {
    2312              :     id: i64,
    2313              :     region_id: &'a str,
    2314              :     version: i64,
    2315              :     host: &'a str,
    2316              :     port: i32,
    2317              :     http_port: i32,
    2318              :     https_port: Option<i32>,
    2319              :     availability_zone_id: &'a str,
    2320              :     scheduling_policy: Option<&'a str>,
    2321              : }
    2322              : 
    2323            0 : #[derive(Serialize, Deserialize, FromSqlRow, AsExpression, Eq, PartialEq, Debug, Copy, Clone)]
    2324              : #[diesel(sql_type = crate::schema::sql_types::PgLsn)]
    2325              : pub(crate) struct LsnWrapper(pub(crate) Lsn);
    2326              : 
    2327              : impl From<Lsn> for LsnWrapper {
    2328            0 :     fn from(value: Lsn) -> Self {
    2329            0 :         LsnWrapper(value)
    2330            0 :     }
    2331              : }
    2332              : 
    2333              : impl FromSql<crate::schema::sql_types::PgLsn, Pg> for LsnWrapper {
    2334            0 :     fn from_sql(
    2335            0 :         bytes: <Pg as diesel::backend::Backend>::RawValue<'_>,
    2336            0 :     ) -> diesel::deserialize::Result<Self> {
    2337            0 :         let byte_arr: diesel::deserialize::Result<[u8; 8]> = bytes
    2338            0 :             .as_bytes()
    2339            0 :             .try_into()
    2340            0 :             .map_err(|_| "Can't obtain lsn from sql".into());
    2341            0 :         Ok(LsnWrapper(Lsn(u64::from_be_bytes(byte_arr?))))
    2342            0 :     }
    2343              : }
    2344              : 
    2345              : impl ToSql<crate::schema::sql_types::PgLsn, Pg> for LsnWrapper {
    2346            0 :     fn to_sql<'b>(
    2347            0 :         &'b self,
    2348            0 :         out: &mut diesel::serialize::Output<'b, '_, Pg>,
    2349            0 :     ) -> diesel::serialize::Result {
    2350            0 :         out.write_all(&u64::to_be_bytes(self.0.0))
    2351            0 :             .map(|_| IsNull::No)
    2352            0 :             .map_err(Into::into)
    2353            0 :     }
    2354              : }
    2355              : 
    2356            0 : #[derive(Insertable, AsChangeset, Clone)]
    2357              : #[diesel(table_name = crate::schema::timelines)]
    2358              : pub(crate) struct TimelinePersistence {
    2359              :     pub(crate) tenant_id: String,
    2360              :     pub(crate) timeline_id: String,
    2361              :     pub(crate) start_lsn: LsnWrapper,
    2362              :     pub(crate) generation: i32,
    2363              :     pub(crate) sk_set: Vec<i64>,
    2364              :     pub(crate) new_sk_set: Option<Vec<i64>>,
    2365              :     pub(crate) cplane_notified_generation: i32,
    2366              :     pub(crate) deleted_at: Option<chrono::DateTime<chrono::Utc>>,
    2367              : }
    2368              : 
    2369              : /// This is separate from [TimelinePersistence] only because postgres allows NULLs
    2370              : /// in arrays and there is no way to forbid that at schema level. Hence diesel
    2371              : /// wants `sk_set` to be `Vec<Option<i64>>` instead of `Vec<i64>` for
    2372              : /// Queryable/Selectable. It does however allow insertions without redundant
    2373              : /// Option(s), so [TimelinePersistence] doesn't have them.
    2374            0 : #[derive(Queryable, Selectable)]
    2375              : #[diesel(table_name = crate::schema::timelines)]
    2376              : pub(crate) struct TimelineFromDb {
    2377              :     pub(crate) tenant_id: String,
    2378              :     pub(crate) timeline_id: String,
    2379              :     pub(crate) start_lsn: LsnWrapper,
    2380              :     pub(crate) generation: i32,
    2381              :     pub(crate) sk_set: Vec<Option<i64>>,
    2382              :     pub(crate) new_sk_set: Option<Vec<Option<i64>>>,
    2383              :     pub(crate) cplane_notified_generation: i32,
    2384              :     pub(crate) deleted_at: Option<chrono::DateTime<chrono::Utc>>,
    2385              : }
    2386              : 
    2387              : impl TimelineFromDb {
    2388            0 :     fn into_persistence(self) -> TimelinePersistence {
    2389            0 :         // We should never encounter null entries in the sets, but we need to filter them out.
    2390            0 :         // There is no way to forbid this in the schema that diesel recognizes (to our knowledge).
    2391            0 :         let sk_set = self.sk_set.into_iter().flatten().collect::<Vec<_>>();
    2392            0 :         let new_sk_set = self
    2393            0 :             .new_sk_set
    2394            0 :             .map(|s| s.into_iter().flatten().collect::<Vec<_>>());
    2395            0 :         TimelinePersistence {
    2396            0 :             tenant_id: self.tenant_id,
    2397            0 :             timeline_id: self.timeline_id,
    2398            0 :             start_lsn: self.start_lsn,
    2399            0 :             generation: self.generation,
    2400            0 :             sk_set,
    2401            0 :             new_sk_set,
    2402            0 :             cplane_notified_generation: self.cplane_notified_generation,
    2403            0 :             deleted_at: self.deleted_at,
    2404            0 :         }
    2405            0 :     }
    2406              : }
    2407              : 
    2408            0 : #[derive(Insertable, AsChangeset, Queryable, Selectable, Clone)]
    2409              : #[diesel(table_name = crate::schema::safekeeper_timeline_pending_ops)]
    2410              : pub(crate) struct TimelinePendingOpPersistence {
    2411              :     pub(crate) sk_id: i64,
    2412              :     pub(crate) tenant_id: String,
    2413              :     pub(crate) timeline_id: String,
    2414              :     pub(crate) generation: i32,
    2415              :     pub(crate) op_kind: SafekeeperTimelineOpKind,
    2416              : }
    2417              : 
    2418            0 : #[derive(Serialize, Deserialize, FromSqlRow, AsExpression, Eq, PartialEq, Debug, Copy, Clone)]
    2419              : #[diesel(sql_type = diesel::sql_types::VarChar)]
    2420              : pub(crate) enum SafekeeperTimelineOpKind {
    2421              :     Pull,
    2422              :     Exclude,
    2423              :     Delete,
    2424              : }
    2425              : 
    2426              : impl FromSql<diesel::sql_types::VarChar, Pg> for SafekeeperTimelineOpKind {
    2427            0 :     fn from_sql(
    2428            0 :         bytes: <Pg as diesel::backend::Backend>::RawValue<'_>,
    2429            0 :     ) -> diesel::deserialize::Result<Self> {
    2430            0 :         let bytes = bytes.as_bytes();
    2431            0 :         match core::str::from_utf8(bytes) {
    2432            0 :             Ok(s) => match s {
    2433            0 :                 "pull" => Ok(SafekeeperTimelineOpKind::Pull),
    2434            0 :                 "exclude" => Ok(SafekeeperTimelineOpKind::Exclude),
    2435            0 :                 "delete" => Ok(SafekeeperTimelineOpKind::Delete),
    2436            0 :                 _ => Err(format!("can't parse: {s}").into()),
    2437              :             },
    2438            0 :             Err(e) => Err(format!("invalid UTF-8 for op_kind: {e}").into()),
    2439              :         }
    2440            0 :     }
    2441              : }
    2442              : 
    2443              : impl ToSql<diesel::sql_types::VarChar, Pg> for SafekeeperTimelineOpKind {
    2444            0 :     fn to_sql<'b>(
    2445            0 :         &'b self,
    2446            0 :         out: &mut diesel::serialize::Output<'b, '_, Pg>,
    2447            0 :     ) -> diesel::serialize::Result {
    2448            0 :         let kind_str = match self {
    2449            0 :             SafekeeperTimelineOpKind::Pull => "pull",
    2450            0 :             SafekeeperTimelineOpKind::Exclude => "exclude",
    2451            0 :             SafekeeperTimelineOpKind::Delete => "delete",
    2452              :         };
    2453            0 :         out.write_all(kind_str.as_bytes())
    2454            0 :             .map(|_| IsNull::No)
    2455            0 :             .map_err(Into::into)
    2456            0 :     }
    2457              : }
    2458              : 
    2459            0 : #[derive(Serialize, Deserialize, Queryable, Selectable, Insertable, Eq, PartialEq, Clone)]
    2460              : #[diesel(table_name = crate::schema::timeline_imports)]
    2461              : pub(crate) struct TimelineImportPersistence {
    2462              :     pub(crate) tenant_id: String,
    2463              :     pub(crate) timeline_id: String,
    2464              :     pub(crate) shard_statuses: serde_json::Value,
    2465              : }
        

Generated by: LCOV version 2.1-beta