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

Generated by: LCOV version 2.1-beta