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

Generated by: LCOV version 2.1-beta