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

Generated by: LCOV version 2.1-beta