LCOV - code coverage report
Current view: top level - storage_controller/src - persistence.rs (source / functions) Coverage Total Hit
Test: 4be46b1c0003aa3bbac9ade362c676b419df4c20.info Lines: 0.4 % 1698 7
Test Date: 2025-07-22 17:50:06 Functions: 0.2 % 570 1

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

Generated by: LCOV version 2.1-beta