diff --git a/bin/dipper-service/src/chain_client.rs b/bin/dipper-service/src/chain_client.rs index 6bc5e3ee..3c0d05ed 100644 --- a/bin/dipper-service/src/chain_client.rs +++ b/bin/dipper-service/src/chain_client.rs @@ -31,6 +31,26 @@ pub use eip5267::{fetch_rca_eip712_domain, refresh_rca_eip712_domain}; pub use manager_role::verify_signer_has_agreement_manager_role; use thegraph_core::alloy::primitives::{Address, B256, Bytes, U256}; +/// Asks, for each chain broadcast, whether this process may make it. Only dipper's writer may, so +/// a process another one has taken over from can't send a transaction the new writer doesn't +/// know of. See [`crate::writer::WriterGate`]. +#[async_trait] +pub trait BroadcastGate: Send + Sync { + /// Starts 1 broadcast's turn, which lasts until it is dropped. A takeover waits for it. + async fn open(&self) -> anyhow::Result>; +} + +/// 1 broadcast's turn, from [`BroadcastGate::open`]. +#[async_trait] +pub trait BroadcastTurn: Send + Sync { + /// Whether this process may still broadcast: asked before each attempt, so a broadcast stops + /// at the first attempt after a takeover. + async fn still_writer(&self) -> anyhow::Result; + + /// Ends the turn once the broadcast is over, so a takeover no longer waits for it. + async fn end(self: Box); +} + /// Error type for chain client operations #[derive(Debug, thiserror::Error)] pub enum ChainClientError { diff --git a/bin/dipper-service/src/chain_client/client.rs b/bin/dipper-service/src/chain_client/client.rs index 629c77ef..0fc9f774 100644 --- a/bin/dipper-service/src/chain_client/client.rs +++ b/bin/dipper-service/src/chain_client/client.rs @@ -32,8 +32,8 @@ use super::{ }; use crate::{ chain_client::{ - AgreementOnChain, ChainClient, ChainClientError, EscrowAccount, ManagerEscrowReader, - TrackedProviders, + AgreementOnChain, BroadcastGate, ChainClient, ChainClientError, EscrowAccount, + ManagerEscrowReader, TrackedProviders, }, config::ChainClientConfig, worker::service::PROCESS_JOB_TIMEOUT, @@ -525,6 +525,17 @@ fn classify_fill_nonce_gap_outcome( } } +/// Why a broadcast stopped once this process was found no longer to be dipper's writer. +const NOT_THE_WRITER: &str = "this process is no longer dipper's writer, so it may not broadcast"; + +/// Whether an attempt of the broadcast has already found it may not go on. +fn has_stopped(stopped: &std::sync::Mutex>) -> bool { + stopped + .lock() + .map(|stopped| stopped.is_some()) + .unwrap_or(true) +} + /// Production implementation of `ChainClient` using alloy. `Clone` via internal `Arc` /// wrapping, so it can be shared across async task contexts. #[derive(Clone)] @@ -580,17 +591,21 @@ struct AlloyChainClientInner { seen_block: std::sync::Mutex, /// Each endpoint's latest block, so a run of reads asks for it once a second, not every read. endpoint_heads: EndpointHeads, + /// Lets a broadcast through only while this process is dipper's writer. + broadcast_gate: Arc, } impl AlloyChainClient { /// Create a new AlloyChainClient from configuration. Errors if no RPC providers are - /// configured or the signer cannot be constructed. + /// configured or the signer cannot be constructed. Every broadcast asks `broadcast_gate` + /// first, and again before each attempt. pub fn new( config: &ChainClientConfig, chain_id: u64, recurring_collector: Address, recurring_agreement_manager: Address, secret_key: &[u8; 32], + broadcast_gate: Arc, ) -> Result { let signer = PrivateKeySigner::from_bytes(&FixedBytes::from(*secret_key)) .map_err(|e| ChainClientError::ConfigError(format!("Invalid signing key: {e}")))?; @@ -633,6 +648,7 @@ impl AlloyChainClient { submit_deadline, seen_block: std::sync::Mutex::new(SeenBlock::new()), endpoint_heads, + broadcast_gate, }), }) } @@ -882,11 +898,44 @@ impl AlloyChainClient { let signed_hash = *signed.tx_hash(); let raw = signed.encoded_2718(); - self.inner + // Only dipper's writer may broadcast, and a takeover waits for this turn to end. Each + // attempt asks again, so a broadcast stops at its first attempt after a takeover, however + // long its walk through the endpoints is. + let turn = self + .inner + .broadcast_gate + .open() + .await + .map_err(ChainClientError::SubmitFailed)?; + // Why the broadcast stopped, once an attempt found it may not go on. + let stopped: std::sync::Mutex> = std::sync::Mutex::new(None); + + let sent = self + .inner .rpc_pool .execute("send_transaction", |provider| { let raw = raw.clone(); + let (turn, stopped) = (&turn, &stopped); async move { + // Not worth retrying, so the pool moves on through the remaining endpoints + // at once, each attempt stopping here as well. + let not_the_writer = || Err(TransportErrorKind::custom_str(NOT_THE_WRITER)); + if has_stopped(stopped) { + return not_the_writer(); + } + let refusal = match turn.still_writer().await { + Ok(true) => None, + Ok(false) => Some(anyhow::anyhow!(NOT_THE_WRITER)), + Err(err) => Some(err.context( + "could not confirm that this process is still dipper's writer", + )), + }; + if let Some(refusal) = refusal { + if let Ok(mut stopped) = stopped.lock() { + *stopped = Some(refusal); + } + return not_the_writer(); + } match provider.send_raw_transaction(&raw).await { // The hash follows from the bytes, so report the one we signed // instead of what this endpoint echoed back. A wrong hash sends the @@ -900,14 +949,18 @@ impl AlloyChainClient { } } }) - .await - .map_err(|e| match e { - // A submission that got nowhere is a failed submission, whatever the - // endpoints happened to say. Anything the pool could name precisely, such - // as a rejection from the contract, keeps the name it already has. - ChainClientError::RpcError(cause) => ChainClientError::SubmitFailed(cause), - other => other, - }) + .await; + turn.end().await; + if let Ok(Some(reason)) = stopped.into_inner() { + return Err(ChainClientError::SubmitFailed(reason)); + } + sent.map_err(|e| match e { + // A submission that got nowhere is a failed submission, whatever the + // endpoints happened to say. Anything the pool could name precisely, such + // as a rejection from the contract, keeps the name it already has. + ChainClientError::RpcError(cause) => ChainClientError::SubmitFailed(cause), + other => other, + }) } /// Send a reconcile call to the manager and wait for its receipt, as offers and @@ -1511,6 +1564,7 @@ mod tests { }; use super::*; + use crate::chain_client::BroadcastTurn; /// A cancel must leave nothing the indexer can still be paid through: neither /// an accepted agreement without a cancellation notice, nor an offer still @@ -1619,6 +1673,124 @@ mod tests { } fn client_over_retrying(providers: Vec, max_retries: u32) -> AlloyChainClient { + client_gated(providers, max_retries, Arc::new(AlwaysWriter)) + } + + /// Lets every broadcast through, as for a process that stays the writer. + struct AlwaysWriter; + + #[async_trait] + impl BroadcastGate for AlwaysWriter { + async fn open(&self) -> anyhow::Result> { + Ok(Box::new(AlwaysWriter)) + } + } + + #[async_trait] + impl BroadcastTurn for AlwaysWriter { + async fn still_writer(&self) -> anyhow::Result { + Ok(true) + } + + async fn end(self: Box) {} + } + + /// Answers each check of a broadcast's turn from a script, then that the process is no + /// longer the writer, and counts the checks. + #[derive(Clone)] + struct ScriptedGate { + answers: Arc>>, + asked: Arc, + } + + impl ScriptedGate { + fn answering(answers: &[bool]) -> Self { + Self { + answers: Arc::new(std::sync::Mutex::new(answers.iter().copied().collect())), + asked: Arc::new(AtomicU64::new(0)), + } + } + + fn asked(&self) -> u64 { + self.asked.load(Ordering::Relaxed) + } + } + + #[async_trait] + impl BroadcastGate for ScriptedGate { + async fn open(&self) -> anyhow::Result> { + Ok(Box::new(self.clone())) + } + } + + #[async_trait] + impl BroadcastTurn for ScriptedGate { + async fn still_writer(&self) -> anyhow::Result { + self.asked.fetch_add(1, Ordering::Relaxed); + let next = self.answers.lock().expect("script").pop_front(); + Ok(next.unwrap_or(false)) + } + + async fn end(self: Box) {} + } + + /// A gate whose check can't reach the database, as when a takeover has ended its session. + struct UnreachableGate; + + #[async_trait] + impl BroadcastGate for UnreachableGate { + async fn open(&self) -> anyhow::Result> { + Ok(Box::new(UnreachableGate)) + } + } + + #[async_trait] + impl BroadcastTurn for UnreachableGate { + async fn still_writer(&self) -> anyhow::Result { + anyhow::bail!("the database connection was ended") + } + + async fn end(self: Box) {} + } + + /// A check that can't tell whether this process is still the writer stops the broadcast as a + /// refusal does: a takeover ends a replaced process's sessions, so a lost connection may be + /// one. + #[tokio::test] + async fn send_transaction_sends_nothing_when_its_check_fails() { + let endpoint = server_answering_with(B256::repeat_byte(0xab)).await; + let client = client_gated( + vec![endpoint.uri().parse().expect("provider URL")], + 0, + Arc::new(UnreachableGate), + ); + let tx = ready_to_send_tx(client.inner.signer.address()); + + let err = client + .send_transaction(&tx) + .await + .expect_err("an unchecked broadcast must not go out"); + + assert!( + matches!(&err, ChainClientError::SubmitFailed(cause) + if format!("{cause:#}").contains("could not confirm")), + "got {err}" + ); + assert!( + endpoint + .received_requests() + .await + .unwrap_or_default() + .is_empty(), + "no endpoint is offered the transaction" + ); + } + + fn client_gated( + providers: Vec, + max_retries: u32, + gate: Arc, + ) -> AlloyChainClient { let config = ChainClientConfig { enabled: true, providers: providers.into_iter().map(Into::into).collect(), @@ -1638,6 +1810,7 @@ mod tests { Address::repeat_byte(0x11), Address::repeat_byte(0x22), &[0x42; 32], + gate, ) .expect("chain client") } @@ -1708,6 +1881,91 @@ mod tests { ); } + /// A process another one has taken over from sends nothing: the new writer may already be + /// using the nonce, or have cancelled what this transaction offers. + #[tokio::test] + async fn send_transaction_sends_nothing_once_the_process_is_not_the_writer() { + let endpoint = server_answering_with(B256::repeat_byte(0xab)).await; + let other = server_answering_with(B256::repeat_byte(0xab)).await; + let gate = ScriptedGate::answering(&[]); + let client = client_gated( + vec![ + endpoint.uri().parse().expect("provider URL"), + other.uri().parse().expect("other provider URL"), + ], + 0, + Arc::new(gate.clone()), + ); + let tx = ready_to_send_tx(client.inner.signer.address()); + + let err = client + .send_transaction(&tx) + .await + .expect_err("a replaced process must not broadcast"); + + assert!( + matches!(&err, ChainClientError::SubmitFailed(cause) if cause.to_string() == NOT_THE_WRITER), + "got {err}" + ); + for server in [&endpoint, &other] { + assert!( + server + .received_requests() + .await + .unwrap_or_default() + .is_empty(), + "no endpoint is offered the transaction" + ); + } + assert_eq!( + gate.asked(), + 1, + "the other endpoints aren't asked about again" + ); + } + + /// A broadcast already walking the endpoints when another process takes over stops at its + /// next attempt, rather than offering the transaction to the endpoints left. + #[tokio::test] + async fn send_transaction_stops_at_the_first_attempt_after_a_takeover() { + let sick = server_answering_500().await; + let healthy = server_answering_with(B256::repeat_byte(0xab)).await; + let gate = ScriptedGate::answering(&[true]); + let client = client_gated( + vec![ + sick.uri().parse().expect("sick provider URL"), + healthy.uri().parse().expect("healthy provider URL"), + ], + 0, + Arc::new(gate.clone()), + ); + let tx = ready_to_send_tx(client.inner.signer.address()); + + let err = client + .send_transaction(&tx) + .await + .expect_err("the takeover stops the broadcast"); + + assert!( + matches!(err, ChainClientError::SubmitFailed(_)), + "got {err}" + ); + assert_eq!( + sick.received_requests().await.unwrap_or_default().len(), + 1, + "the 1st attempt, made while still the writer, went out" + ); + assert!( + healthy + .received_requests() + .await + .unwrap_or_default() + .is_empty(), + "the attempt after the takeover never went out" + ); + assert_eq!(gate.asked(), 2, "each attempt asked before going out"); + } + /// With a single provider there is nowhere to rotate to, so the fault must surface rather /// than be retried forever or silently swallowed. It surfaces as a failed submission rather /// than the pool's generic RPC fault, which is what says the transaction went nowhere. @@ -2144,6 +2402,7 @@ mod tests { Address::repeat_byte(0x11), Address::repeat_byte(0x22), &[0x42; 32], + Arc::new(AlwaysWriter), ) .expect("chain client"); diff --git a/bin/dipper-service/src/config.rs b/bin/dipper-service/src/config.rs index 96392ec4..cfda0ef3 100644 --- a/bin/dipper-service/src/config.rs +++ b/bin/dipper-service/src/config.rs @@ -821,6 +821,12 @@ impl Default for AlertsConfig { "price_ceilings_changed", "suggested_minimums_refused", "suggested_minimums_fetch_failed", + "writer_waiting", + "writer_superseded", + "writer_drain_blocked", + "writer_refused_while_writer", + "writer_fence_off", + "writer_fence_attach_waiting", ] .map(str::to_owned) .to_vec(), @@ -1657,8 +1663,10 @@ pub struct ChainClientConfig { /// rotating to the next on persistent failures. pub providers: Vec, - /// Request timeout per RPC call in seconds (default: 10s). Every call here is a small one, - /// so this is headroom rather than a working limit, and it multiplies with `max_retries`. + /// Request timeout per RPC call in seconds (default: 10s, at most 12s). Every call here is a + /// small one, so this is headroom rather than a working limit, and it multiplies with + /// `max_retries`. It is held below the 15 seconds a dipper taking over waits for a broadcast + /// attempt of the one it replaces. #[serde(default = "default_chain_client_request_timeout")] #[serde_as(as = "serde_with::DurationSeconds")] pub request_timeout: Duration, @@ -1726,6 +1734,30 @@ pub(crate) fn default_chain_client_request_timeout() -> Duration { Duration::from_secs(10) } +/// How much shorter than a takeover's wait for the old writer a broadcast attempt must be. +const REQUEST_TIMEOUT_MARGIN: Duration = Duration::from_secs(3); + +impl ChainClientConfig { + /// Refuses a request timeout a broadcast attempt could outlast a takeover by. A process that + /// another one takes over from may have 1 attempt in flight, which the new writer waits for + /// up to [`crate::writer::DRAIN_WAIT`] before it goes on; an attempt longer than that could + /// still land afterwards. + pub fn validate(&self) -> Result<(), String> { + let longest = crate::writer::DRAIN_WAIT.saturating_sub(REQUEST_TIMEOUT_MARGIN); + if self.request_timeout > longest { + return Err(format!( + "chain_client.request_timeout ({}s) must be at most {}s: a dipper taking over \ + waits {}s for a broadcast attempt of the one it replaces, and an attempt can \ + take as long as this timeout", + self.request_timeout.as_secs(), + longest.as_secs(), + crate::writer::DRAIN_WAIT.as_secs(), + )); + } + Ok(()) + } +} + fn default_domain_refresh_interval() -> Duration { Duration::from_secs(3600) } @@ -5020,6 +5052,24 @@ mod tests { ); } + /// A broadcast attempt must end well within the 15 seconds a dipper taking over waits for + /// one of the process it replaces. + #[test] + fn chain_client_request_timeout_stays_below_a_takeovers_wait() { + let with = |secs: u64| { + example_config_edited(|config| { + config["chain_client"]["request_timeout"] = secs.into(); + }) + .chain_client + .expect("the example has a chain_client section") + .validate() + }; + assert_eq!(with(10), Ok(()), "the default"); + assert_eq!(with(12), Ok(())); + let err = with(13).expect_err("too close to the takeover's wait"); + assert!(err.contains("at most 12s"), "{err}"); + } + #[test] fn health_validate_rejects_an_ephemeral_port() { let health = HealthConfig { diff --git a/bin/dipper-service/src/db.rs b/bin/dipper-service/src/db.rs index 52424ccd..0a433ce0 100644 --- a/bin/dipper-service/src/db.rs +++ b/bin/dipper-service/src/db.rs @@ -1,10 +1,12 @@ use std::time::Duration; use anyhow::Context; +use dipper_pgregistry::writer_fence; use sqlx::{ Connection as _, PgConnection, Pool, Postgres, postgres::{PgConnectOptions, PgPoolOptions}, }; +use uuid::Uuid; use crate::config::DbConfig; @@ -16,23 +18,35 @@ pub const DEFAULT_MAX_CONNECTIONS: u32 = 32; /// instead of relying on the driver default. const ACQUIRE_TIMEOUT: Duration = Duration::from_secs(30); -/// Connect to the database -#[expect( - clippy::expect_used, - reason = "predates this lint; fix when next touched" -)] -pub async fn connect(conf: &DbConfig) -> anyhow::Result> { +/// How to reach the database as configured, credentials included. +fn connect_options(conf: &DbConfig) -> anyhow::Result { // sqlx checks a `verify-ca` certificate with rustls's process-wide provider. crate::tls::install_crypto_provider(); - let mut conn_options: PgConnectOptions = conf.url.as_str().parse().expect("Invalid DB URL"); - conn_options = conn_options.username(&conf.username); + let conn_options: PgConnectOptions = conf + .url + .as_str() + .parse() + .context("db.url is not a Postgres connection URL")?; + let conn_options = conn_options.username(&conf.username); + Ok(match &conf.password { + Some(password) => conn_options.password(password), + None => conn_options, + }) +} + +/// Connects the pool every database call of this process goes through, once the database +/// answers. Each of its sessions belongs to the process with `writer` as its token: the writer +/// fence lets its writes through only while that process is the writer, and a takeover by +/// another process ends them (see [`crate::writer`]). The connections opened from the pool's +/// options, such as the queue's listener and the Studio consumer's lock, belong to it too. +pub async fn connect(conf: &DbConfig, writer: Uuid) -> anyhow::Result> { + let conn_options = connect_options(conf)?; // Without a password, dipper only gets in where the server asks for none. - match &conf.password { - Some(password) => conn_options = conn_options.password(password), - None => tracing::info!( + if conf.password.is_none() { + tracing::info!( "db.password is not set: connecting without a password of dipper's own, as through \ the Cloud SQL Auth Proxy with automatic IAM authentication" - ), + ); } // Wait for the database with 1 connection at a time, each cut off at the time left of the @@ -74,7 +88,7 @@ pub async fn connect(conf: &DbConfig) -> anyhow::Result> { let pool = PgPoolOptions::new() .max_connections(conf.max_connections.unwrap_or(DEFAULT_MAX_CONNECTIONS)) .acquire_timeout(ACQUIRE_TIMEOUT) - .connect_with(conn_options) + .connect_with(writer_fence::writer_options(conn_options, writer)) .await .map_err(|err| explain_refusal(err, conf.password.is_none())) .context("failed to connect to DB")?; @@ -82,6 +96,29 @@ pub async fn connect(conf: &DbConfig) -> anyhow::Result> { Ok(pool) } +/// The pool of 1 connection a chain broadcast's writer check runs on, beside `pool`: a check holds +/// its connection for as long as its broadcast lasts, so it gets one of its own rather than 1 the +/// worker loops are counted on. Broadcasts take turns, so 1 is enough. Its session belongs to the +/// same process as `pool`'s, as `dipper//broadcast`, and it connects when first used. +pub fn broadcast_check_pool(pool: &Pool) -> Pool { + let options = writer_fence::named(pool.connect_options().as_ref().clone(), "broadcast"); + PgPoolOptions::new() + .max_connections(1) + .acquire_timeout(ACQUIRE_TIMEOUT) + .connect_lazy_with(options) +} + +/// Opens 1 session for work done on the database as a whole rather than as this process: the +/// migrations, and fencing the tables they add. The writer fence lets its writes through, and no +/// takeover ends it. Call it once [`connect`] has found the database answering. +pub async fn connect_operator(conf: &DbConfig) -> anyhow::Result { + let options = writer_fence::operator_options(connect_options(conf)?); + PgConnection::connect_with(&options) + .await + .map_err(|err| explain_refusal(err, conf.password.is_none())) + .context("failed to open the DB session for migrations") +} + /// The longest 1 connection attempt may take while waiting for the database at startup. const CONNECT_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(10); @@ -191,7 +228,7 @@ mod tests { let conf = db_config(&format!("postgres://{addr}/dipper?sslmode=require")); let (_, seen) = tokio::join!( - tokio::time::timeout(Duration::from_secs(5), connect(&conf)), + tokio::time::timeout(Duration::from_secs(5), connect(&conf, Uuid::now_v7())), tokio::time::timeout(Duration::from_secs(5), server), ); let (request, next) = seen @@ -293,7 +330,11 @@ mod tests { }; let url = format!("postgres://{host}:{}/dipper?{params}{root}", addr.port()); - let _ = tokio::time::timeout(Duration::from_secs(10), connect(&db_config(&url))).await; + let _ = tokio::time::timeout( + Duration::from_secs(10), + connect(&db_config(&url), Uuid::now_v7()), + ) + .await; let accepted = tokio::time::timeout(Duration::from_secs(10), handshake) .await .map(|joined| joined.unwrap_or(false)) @@ -393,7 +434,7 @@ mod tests { // pgtemp's default server trusts local connections, as a database behind the Cloud SQL // Auth Proxy with automatic IAM authentication asks the client for no password either. let temp_db = crate::test_support::temp_postgres(); - let pool = connect(&pgtemp_db_config(&temp_db, None)) + let pool = connect(&pgtemp_db_config(&temp_db, None), Uuid::now_v7()) .await .expect("connects without a password"); let one: i32 = sqlx::query_scalar("SELECT 1") @@ -403,12 +444,41 @@ mod tests { assert_eq!(one, 1); } + /// The writer fence tells processes apart by what their sessions carry: a session of the pool + /// belongs to this process, and the migrations' session to no process at all. + #[tokio::test] + async fn it_marks_every_session_with_whose_it_is() { + let temp_db = crate::test_support::temp_postgres(); + let conf = pgtemp_db_config(&temp_db, None); + let token = Uuid::now_v7(); + let carried = + "SELECT current_setting('dipper.writer'), current_setting('application_name')"; + + let pool = connect(&conf, token).await.expect("connect the pool"); + let (setting, name): (String, String) = sqlx::query_as(carried) + .fetch_one(&pool) + .await + .expect("read the pool's session"); + assert_eq!(setting, token.to_string()); + assert_eq!(name, format!("dipper/{token}")); + + let mut operator = connect_operator(&conf) + .await + .expect("connect as an operator"); + let (setting, name): (String, String) = sqlx::query_as(carried) + .fetch_one(&mut operator) + .await + .expect("read the operator's session"); + assert_eq!(setting, "operator"); + assert_eq!(name, "dipper-operator"); + } + #[tokio::test] async fn it_says_so_when_a_server_wants_the_password_that_is_not_set() { let (temp_db, dir) = password_checking_db(); - let without = connect(&pgtemp_db_config(&temp_db, None)).await; - let with = connect(&pgtemp_db_config(&temp_db, Some("s3cret"))).await; + let without = connect(&pgtemp_db_config(&temp_db, None), Uuid::now_v7()).await; + let with = connect(&pgtemp_db_config(&temp_db, Some("s3cret")), Uuid::now_v7()).await; drop(temp_db); let _ = std::fs::remove_dir_all(dir); @@ -444,7 +514,11 @@ mod tests { }) }; - let result = connect(&waiting_db_config(&format!("postgres://{addr}/dipper"), 2)).await; + let result = connect( + &waiting_db_config(&format!("postgres://{addr}/dipper"), 2), + Uuid::now_v7(), + ) + .await; server.abort(); assert!(result.is_err(), "the server never lets dipper in"); @@ -469,7 +543,11 @@ mod tests { }); let started = std::time::Instant::now(); - let result = connect(&waiting_db_config(&format!("postgres://{addr}/dipper"), 2)).await; + let result = connect( + &waiting_db_config(&format!("postgres://{addr}/dipper"), 2), + Uuid::now_v7(), + ) + .await; server.abort(); let err = format!("{:#}", result.expect_err("the server never answers")); diff --git a/bin/dipper-service/src/main.rs b/bin/dipper-service/src/main.rs index eacf4bd3..1b7ca2f1 100644 --- a/bin/dipper-service/src/main.rs +++ b/bin/dipper-service/src/main.rs @@ -42,6 +42,7 @@ mod telemetry; mod test_support; mod tls; mod worker; +mod writer; #[global_allocator] static ALLOC: snmalloc_rs::SnMalloc = snmalloc_rs::SnMalloc; @@ -68,13 +69,13 @@ const TEARDOWN_GRACE: std::time::Duration = std::time::Duration::from_secs(75); const WORKER_DRAIN: std::time::Duration = std::time::Duration::from_secs(45); /// The stop sequence's ceiling: the worker's drain and the cut-off of any job it left running, -/// with the services that feed or call it stopping alongside, then 4 steps in turn, each capped -/// at [`STOP_STEP_TIMEOUT`]: the services the jobs read from, the health endpoint, the event flush -/// and the DB pool. +/// with the services that feed or call it stopping alongside, then 5 steps in turn, each capped +/// at [`STOP_STEP_TIMEOUT`]: the services the jobs read from, the health endpoint, the event flush, +/// the DB pool, and the writer's handover. const TEARDOWN_CEILING: std::time::Duration = std::time::Duration::from_secs( WORKER_DRAIN.as_secs() + worker::service::CUT_OFF_WAIT.as_secs() - + 4 * STOP_STEP_TIMEOUT.as_secs(), + + 5 * STOP_STEP_TIMEOUT.as_secs(), ); // The sequence must end before the supervisor stops waiting for it. @@ -220,6 +221,9 @@ pub async fn main() -> anyhow::Result<()> { on-chain and cannot sign agreements without it" ), }; + if let Err(err) = chain_client_conf.validate() { + anyhow::bail!("invalid chain client config: {err}"); + } let rca_domain = { let cfg = &chain_client_conf; let mut attempt: u32 = 0; @@ -286,12 +290,26 @@ pub async fn main() -> anyhow::Result<()> { Arc::new(Eip712Signer::new(chain_id, domain)) }; - //- DB connect and run migrations - let db_conn = db::connect(&conf.db).await?; - tracing::info!(db = %config::database_name(&conf.db.url), "initialized DB connection pool"); + //- DB connect and run migrations. Every session of the pool carries this process's token: the + // database refuses their writes until this process becomes the writer, just before the + // services start below, and again once another process has taken over (see `writer`). + let writer_token = writer::new_token(); + let db_conn = db::connect(&conf.db, writer_token).await?; + tracing::info!( + db = %config::database_name(&conf.db.url), + writer_token = %writer_token, + "initialized DB connection pool" + ); - dipper_pgmq::run_db_migrations(&db_conn).await?; - dipper_pgregistry::run_db_migrations(&db_conn).await?; + // The migrations, and fencing any table they added, are work on the database as a whole, + // done on a session of their own that the writer fence lets through. + { + let mut operator = db::connect_operator(&conf.db).await?; + dipper_pgmq::run_db_migrations(&mut operator).await?; + dipper_pgregistry::run_db_migrations(&mut operator).await?; + writer::fence_every_table(&mut operator).await?; + let _ = sqlx::Connection::close(operator).await; + } tracing::info!("applied DB migrations"); //- The metrics sampler: the database's reachability and the queue's depth @@ -490,6 +508,10 @@ pub async fn main() -> anyhow::Result<()> { recurring_collector, agreement_conf.recurring_agreement_manager(), &secret_bytes, + Arc::new(writer::WriterGate::new( + db::broadcast_check_pool(&db_conn), + writer_token, + )), ) .expect("Failed to create AlloyChainClient"); tracing::info!( @@ -799,6 +821,22 @@ pub async fn main() -> anyhow::Result<()> { // Construct the task tree let mut task_tree = JoinSet::new(); + //- Become dipper's writer, as late as startup allows: everything above only reads. This waits + // while another dipper process is the healthy writer, then takes over. The heartbeat starts + // at once, so this process never looks silent while it waits for what the replaced one still + // had in flight, and it runs until the last step of the stop below. + let taken = writer::Takeover::new(&db_conn, writer_token, writer::holder()) + .take() + .await?; + let (writer_handle, heartbeat) = writer::heartbeat( + db_conn.connect_options().as_ref().clone(), + writer_token, + writer::refusals(), + ); + let heartbeat_task_handle = task_tree.spawn(heartbeat); + tracing::debug!(task_id=%heartbeat_task_handle.id(), "Writer heartbeat started"); + taken.settle().await?; + // Spawn the entity count cache if enabled let entity_count_handle = if let Some((handle, service)) = entity_count_service { let task_handle = task_tree.spawn(service); @@ -1035,13 +1073,21 @@ pub async fn main() -> anyhow::Result<()> { // on would hang it and then take a confusing `PoolClosed`. Skipping it, or giving up on // it, costs nothing: Postgres rolls back anything open once the sockets drop. if all_stopped { - stop_service("DB connection pool", db_conn.close()).await; + all_stopped &= stop_service("DB connection pool", db_conn.close()).await; } else { tracing::warn!( "skipping the graceful DB pool close because a service did not stop in time" ); } + // The last step. The heartbeat ran until now, so this process never looked silent while + // it stopped. It hands over only after a clean stop, so the next process can't take over + // while a service of this one may still be running: it then waits out the silence. + stop_service("Writer handover", async { + writer_handle.finish(all_stopped).await; + }) + .await; + // Everything is stopped, so surface the registration failure now. match registration_error { Some(err) => Err(anyhow::Error::new(err)), diff --git a/bin/dipper-service/src/network/service/indexing_request_consumer.rs b/bin/dipper-service/src/network/service/indexing_request_consumer.rs index 2ae7ed95..562a59f2 100644 --- a/bin/dipper-service/src/network/service/indexing_request_consumer.rs +++ b/bin/dipper-service/src/network/service/indexing_request_consumer.rs @@ -75,8 +75,9 @@ const LOCK_CALL_TIMEOUT: Duration = Duration::from_secs(5); /// How long giving the lock up may take, within the 5 seconds dipper allows a service to stop. const LOCK_RELEASE_TIMEOUT: Duration = Duration::from_secs(2); -/// The application name of the lock's database session, to find it by in `pg_stat_activity`. -const LOCK_SESSION_NAME: &str = "dipper-studio-request-consumer-lock"; +/// What the lock's database session is named, after the process's own name, to find it by in +/// `pg_stat_activity`: `dipper//studio-request-lock`, which is 63 bytes, all Postgres keeps. +const LOCK_SESSION_NAME: &str = "studio-request-lock"; /// How long the lock's session may sit idle before the database ends it and frees the lock. /// It bounds how long a dipper that vanished without closing its connection keeps the lock, @@ -487,7 +488,8 @@ async fn lock_taken( Ok(false) => wait.goes_on(format_args!( "another database session holds it, which is either a dipper that is still \ running or one that has gone and whose session the database has not ended yet \ - (in pg_stat_activity both have the application_name '{LOCK_SESSION_NAME}')" + (in pg_stat_activity both have an application_name ending in \ + '/{LOCK_SESSION_NAME}')" )), Err(error) => wait.goes_on(format_args!("the database could not be asked ({error})")), } diff --git a/bin/dipper-service/src/registry/result.rs b/bin/dipper-service/src/registry/result.rs index ace648ab..5e3328df 100644 --- a/bin/dipper-service/src/registry/result.rs +++ b/bin/dipper-service/src/registry/result.rs @@ -25,7 +25,12 @@ impl From for Error { fn from(value: dipper_pgregistry::Error) -> Self { match value { dipper_pgregistry::Error::NoRecordsUpdated => Error::NoRecordsUpdated, - dipper_pgregistry::Error::DbError(_) => Error::BackendError(value), + dipper_pgregistry::Error::DbError(ref err) => { + // A write the writer fence refused: the heartbeat checks at once whether another + // process has taken over, and stops this one if so. + crate::writer::note_db_refusal(err); + Error::BackendError(value) + } } } } diff --git a/bin/dipper-service/src/worker/service.rs b/bin/dipper-service/src/worker/service.rs index aa3acff9..a43e77e5 100644 --- a/bin/dipper-service/src/worker/service.rs +++ b/bin/dipper-service/src/worker/service.rs @@ -595,6 +595,7 @@ where // An unexpected DB failure (the empty queue is Ok(None) above); // surface it so a DB outage doesn't leave every loop spinning // silently while the worker still looks healthy. + crate::writer::note_refusal(&err); tracing::warn!(error=?err, "Failed to get next job from queue"); continue; } @@ -702,6 +703,11 @@ impl FinishedJob for JobGuard<'_, Message> { /// Removes, retries or defers a job according to how its run went. async fn settle_job(job: impl FinishedJob, result: JobResult<()>) { + // A job of a process another one has taken over from fails at its first write, and its + // settling is refused too, which leaves it queued for the new writer. + if let Err(JobError::Retryable(err, _) | JobError::Fatal(err)) = &result { + crate::writer::note_refusal(err); + } let kind = job.message().kind(); let outcome = match result { Ok(..) => recorded(remove_job(job).await, "success"), @@ -729,6 +735,7 @@ async fn drop_job(job: impl FinishedJob, err: &anyhow::Error) -> bool { true } Err(remove_err) => { + crate::writer::note_refusal(&remove_err); tracing::error!( job_id = %failed.id, kind = failed.kind, @@ -749,6 +756,7 @@ async fn remove_job(job: impl FinishedJob) -> bool { match job.remove().await { Ok(()) => true, Err(err) => { + crate::writer::note_refusal(&err); tracing::error!(job_id = %id, error = ?err, "Failed to remove job from queue"); false } @@ -769,6 +777,7 @@ async fn defer_job(job: impl FinishedJob, delay: Duration) -> bool { match job.defer_to(scheduled_for).await { Ok(()) => true, Err(err) => { + crate::writer::note_refusal(&err); tracing::error!(error=?err, "Failed to reschedule deferred job"); false } @@ -797,6 +806,7 @@ async fn retry_job( "gave_up" } Err(db_err) => { + crate::writer::note_refusal(&db_err); tracing::error!( job_id = %failed.id, kind = failed.kind, diff --git a/bin/dipper-service/src/writer.rs b/bin/dipper-service/src/writer.rs new file mode 100644 index 00000000..afda30a3 --- /dev/null +++ b/bin/dipper-service/src/writer.rs @@ -0,0 +1,889 @@ +//! Dipper's 1 writer, as this process takes part in it. +//! +//! Dipper's flows assume a single process acts. The writer fence makes the database enforce that +//! (see [`dipper_pgregistry::writer_fence`]): every session of this process carries its token, +//! and the database refuses their writes unless that token is the current writer's. A process +//! that has been replaced is therefore refused however late it finds out, and 2 processes +//! overlapping behave like the older one crashing, which dipper's flows already survive. +//! +//! This module decides when this process asks to be the writer ([`fence_every_table`] and +//! [`Takeover`] at start), keeps it the writer while it runs and hands over at a clean stop +//! ([`heartbeat`]), lets its chain broadcasts through only while it is the writer +//! ([`WriterGate`]), and stops it once another process has taken over. None of this decides +//! safety, which the database's check alone gives: the timings only decide how soon a handover +//! happens. + +use std::{ + sync::{Arc, OnceLock}, + time::{Duration, Instant}, +}; + +use anyhow::Context as _; +use async_trait::async_trait; +use dipper_pgregistry::writer_fence; +use sqlx::{ + ConnectOptions as _, Connection as _, PgConnection, PgPool, postgres::PgConnectOptions, +}; +use tokio::{ + sync::{Mutex, Notify, mpsc, oneshot}, + time::MissedTickBehavior, +}; +use uuid::Uuid; + +use crate::chain_client::{BroadcastGate, BroadcastTurn}; + +/// How long the writer may go without a heartbeat before a starting process takes over from it. +pub const STALE_AFTER: Duration = Duration::from_secs(20); + +/// How often the writer says it is alive: a quarter of [`STALE_AFTER`], so 3 heartbeats in a row +/// can fail before it looks silent. +const BEAT_EVERY: Duration = Duration::from_secs(5); + +/// The longest 1 heartbeat may take. A slower one counts as missed, and the next one is made on a +/// new connection. +const BEAT_TIMEOUT: Duration = Duration::from_secs(5); + +/// How often a starting process asks again while the writer is healthy. +const ASK_EVERY: Duration = Duration::from_secs(2); + +/// How often a starting process says it is still waiting for the writer. +const WAITING_LOG_EVERY: Duration = Duration::from_secs(30); + +/// How long a wait for the writer is ordinary: the old pod's 90 seconds to stop, then the +/// 20 seconds of silence a crash costs. Longer, and another dipper is running that shouldn't be. +const WAITING_TOO_LONG: Duration = Duration::from_secs(120); + +/// How long a takeover waits for the statements and broadcast attempts the old writer had in +/// flight before it ends that writer's sessions. The chain client's request timeout is held below +/// it (see `ChainClientConfig::validate`), so a broadcast attempt in flight ends first unless its +/// process is frozen. +pub const DRAIN_WAIT: Duration = Duration::from_secs(15); + +/// How long fencing 1 table may wait for a transaction that keeps it busy. +const ATTACH_WAIT: Duration = Duration::from_secs(5); + +/// A token for a new process: random, and unique to it. Version 7 also sorts by start time. +pub fn new_token() -> Uuid { + Uuid::now_v7() +} + +/// The name this process goes by in `dipper_writer.holder`, for operators: its host name, which +/// in Kubernetes is the pod's name. +pub fn holder() -> String { + std::env::var("HOSTNAME") + .ok() + .filter(|name| !name.is_empty()) + .unwrap_or_else(|| "unknown".to_owned()) +} + +/// Fences every table that isn't, as a start does once its migrations have run on `operator`, a +/// session marked as an operator's. A table a migration added is fenced this way without anyone +/// having to remember to. A table busy with a long transaction is tried again until it is free, +/// each time in a transaction of its own, so the wait never holds the other tables. +pub async fn fence_every_table(operator: &mut PgConnection) -> anyhow::Result<()> { + let mut waiting_since: Option = None; + loop { + let busy = fence_unfenced(operator).await?; + if busy.is_empty() { + break; + } + let since = *waiting_since.get_or_insert_with(Instant::now); + tracing::warn!( + event = "writer_fence_attach_waiting", + tables = ?busy, + waited_secs = since.elapsed().as_secs(), + "could not put the writer fence on these tables yet: a transaction keeps them busy, \ + as a process of a dipper release without the fence may while it stops. Trying again" + ); + tokio::time::sleep(ASK_EVERY).await; + } + warn_if_the_fence_is_off(operator).await +} + +/// Fences each table that isn't, until none is left or only busy ones are. Returns the busy ones. +async fn fence_unfenced(operator: &mut PgConnection) -> anyhow::Result> { + loop { + let unfenced = writer_fence::unfenced(operator) + .await + .context("failed to list the tables without the writer fence")?; + if unfenced.is_empty() { + return Ok(Vec::new()); + } + let mut busy = Vec::new(); + for table in unfenced { + let fenced = writer_fence::attach(operator, &table, ATTACH_WAIT) + .await + .with_context(|| format!("failed to put the writer fence on {table}"))?; + if fenced { + tracing::info!(table, "put the writer fence on the table"); + } else { + busy.push(table); + } + } + if !busy.is_empty() { + return Ok(busy); + } + } +} + +async fn warn_if_the_fence_is_off(conn: &mut PgConnection) -> anyhow::Result<()> { + let on = writer_fence::enforced(conn) + .await + .context("failed to read whether the writer fence is on")?; + if !on { + tracing::warn!( + event = "writer_fence_off", + "the writer fence is switched off: the database lets any process write, so nothing \ + stops a 2nd dipper from acting at once with this one. Switch it on again with \ + SELECT dipper_fence_set(true)" + ); + } + Ok(()) +} + +/// Becoming the writer, at start: wait while another process is the healthy writer, take over, +/// then wait for what the old writer still had in flight and end its sessions. Do it as late as +/// startup allows, just before the services start: until then, any write of this process is +/// refused. +pub struct Takeover { + options: PgConnectOptions, + token: Uuid, + holder: String, +} + +impl Takeover { + /// For the process whose sessions `pool` opens: they carry its token. + pub fn new(pool: &PgPool, token: Uuid, holder: String) -> Self { + Self { + options: pool.connect_options().as_ref().clone(), + token, + holder, + } + } + + /// Waits until this process may take over, and takes over. That happens once the writer + /// has handed over at a clean stop, or has been silent for [`STALE_AFTER`]. From when this + /// returns, the database refuses every statement the process it replaced starts; start the + /// [`heartbeat`] at once, then [`Taken::settle`]. + pub async fn take(&self) -> anyhow::Result { + let started = Instant::now(); + let mut last_said = started; + let mut conn: Option = None; + loop { + match self.ask(&mut conn).await { + Ok(true) => break, + Ok(false) => { + if last_said.elapsed() >= WAITING_LOG_EVERY { + last_said = Instant::now(); + say_waiting(started.elapsed()); + } + } + Err(err) if worth_asking_again(&err) => { + conn = None; + tracing::warn!(error = %err, "could not ask to become the writer; asking again"); + } + Err(err) => return Err(err).context("failed to ask to become the writer"), + } + tokio::time::sleep(ASK_EVERY).await; + } + let conn = match conn { + Some(conn) => conn, + None => self.connect().await?, + }; + Ok(Taken { + conn, + token: self.token, + waited: started.elapsed(), + }) + } + + /// Asks once, on `conn`, connecting it first if it isn't. + async fn ask(&self, conn: &mut Option) -> sqlx::Result { + let conn = match conn { + Some(conn) => conn, + None => conn.insert( + writer_fence::named(self.options.clone(), "takeover") + .connect() + .await?, + ), + }; + writer_fence::take(conn, self.token, &self.holder, STALE_AFTER).await + } + + async fn connect(&self) -> anyhow::Result { + writer_fence::named(self.options.clone(), "takeover") + .connect() + .await + .context("failed to connect to finish taking over as the writer") + } +} + +fn say_waiting(waited: Duration) { + let waited_secs = waited.as_secs(); + if waited >= WAITING_TOO_LONG { + tracing::warn!( + event = "writer_waiting", + waited_secs, + "still waiting to become the writer: another dipper process is the writer and \ + answers its heartbeat. A stopping pod hands over well before this, so another \ + dipper is running that shouldn't be; see dipper_writer.holder for its host" + ); + } else { + tracing::info!( + event = "writer_waiting", + waited_secs, + "waiting to become the writer: another dipper process is the writer, and hands over \ + when it stops or after 20 seconds without a heartbeat" + ); + } +} + +/// Whether asking failed in a way asking again may not: the database answered with an error of +/// its own rather than the connection failing or being ended. +fn worth_asking_again(err: &sqlx::Error) -> bool { + match err { + // Connection exceptions (08) and operator intervention (57), such as another starting + // process's takeover ending this session, or a statement timeout. + sqlx::Error::Database(db) => db + .code() + .is_some_and(|code| code.starts_with("08") || code.starts_with("57")), + _ => true, + } +} + +/// A takeover that has happened, with what the replaced process had in flight still to settle. +pub struct Taken { + conn: PgConnection, + token: Uuid, + waited: Duration, +} + +impl Taken { + /// Waits for the statements and broadcast attempts the replaced process had in flight, then + /// ends every session of it that is left, which rolls back what it had open and frees the + /// jobs and session locks it held. A session that blocks the wait is ended, and the wait + /// asked again, until nothing blocks it. Once this returns, this process may start working. + pub async fn settle(mut self) -> anyhow::Result<()> { + let conn = &mut self.conn; + writer_fence::drain(conn, DRAIN_WAIT) + .await + .context("failed to wait for the replaced writer's statements")?; + let mut sessions_cut = cut(conn, self.token).await?; + while !writer_fence::drain(conn, DRAIN_WAIT) + .await + .context("failed to wait for the replaced writer's statements")? + { + let blockers = writer_fence::drain_blockers(conn) + .await + .context("failed to list what the takeover is waiting for")?; + tracing::warn!( + event = "writer_drain_blocked", + ?blockers, + "a takeover keeps waiting for sessions of the dipper it replaced; ending them \ + and waiting again. A prepared transaction among them holds the takeover back \ + until an operator rolls it back" + ); + sessions_cut += cut(conn, self.token).await?; + } + tracing::info!( + event = "writer_taken", + waited_secs = self.waited.as_secs(), + sessions_cut, + "this process is now dipper's writer" + ); + let _ = self.conn.close().await; + Ok(()) + } +} + +async fn cut(conn: &mut PgConnection, token: Uuid) -> anyhow::Result { + writer_fence::cut(conn, token) + .await + .context("failed to end the replaced writer's sessions") +} + +/// Stops the [`heartbeat`] at the end of a stop. +pub struct Handle { + finish: mpsc::Sender<(bool, oneshot::Sender)>, +} + +impl Handle { + /// Stops the heartbeat. With `release` it then hands over, so the next process takes over + /// without waiting for this one to go silent: pass it only once every service has stopped. + /// Returns whether it handed over. + pub async fn finish(&self, release: bool) -> bool { + let (reply, answer) = oneshot::channel(); + if self.finish.send((release, reply)).await.is_err() { + // The heartbeat has stopped already: this process was replaced. + return false; + } + answer.await.unwrap_or(false) + } +} + +/// Why a [`heartbeat`] stopped the process. +#[derive(Debug, thiserror::Error)] +#[error("another dipper process has taken over as the writer")] +pub struct Superseded; + +/// Keeps this process the writer from its takeover until its stop: every few seconds it says it +/// is alive, on a connection of its own opened from `options` (the pool's), so a starting +/// process waits. Run it from the moment [`Takeover::take`] returns, and stop it through the +/// [`Handle`] as the last step of a stop. +/// +/// It ends with [`Superseded`] as soon as it finds another process has taken over, which stops +/// this one: when a heartbeat says so, or when told through `refusals` that the database refused +/// a write ([`note_refusal`]) and the heartbeat it then makes at once confirms it. A database +/// that can't be reached changes nothing: the writer stays the writer, and beats again once the +/// database answers. +pub fn heartbeat( + options: PgConnectOptions, + token: Uuid, + refusals: Arc, +) -> (Handle, impl Future>) { + let (finish, finishes) = mpsc::channel(1); + let options = writer_fence::named(options, "heartbeat") + .options([("statement_timeout", BEAT_TIMEOUT.as_millis().to_string())]); + let beats = Beats { + options, + token, + conn: None, + failing_since: None, + }; + (Handle { finish }, run_heartbeat(beats, refusals, finishes)) +} + +async fn run_heartbeat( + mut beats: Beats, + refusals: Arc, + mut finishes: mpsc::Receiver<(bool, oneshot::Sender)>, +) -> anyhow::Result<()> { + let mut ticks = tokio::time::interval(BEAT_EVERY); + ticks.set_missed_tick_behavior(MissedTickBehavior::Delay); + loop { + let refused = tokio::select! { + finish = finishes.recv() => { + let Some((release, reply)) = finish else { + return Ok(()); + }; + let released = release && beats.release().await; + beats.close().await; + let _ = reply.send(released); + return Ok(()); + } + _ = ticks.tick() => false, + () = refusals.notified() => true, + }; + match beats.beat().await { + Some(true) if refused => tracing::error!( + event = "writer_refused_while_writer", + "the database refused a write of this process although it is the writer: a \ + session of it lacks the process's token" + ), + Some(true) | None => {} + Some(false) => { + tracing::error!( + event = "writer_superseded", + "another dipper process has taken over as the writer; this one stops. The \ + database refuses its writes from the takeover on" + ); + return Err(Superseded.into()); + } + } + } +} + +/// What the heartbeat asks of the database. +#[derive(Clone, Copy)] +enum Call { + Beat, + Release, +} + +/// The heartbeat's connection, and what it last made of the database. +struct Beats { + options: PgConnectOptions, + token: Uuid, + conn: Option, + failing_since: Option, +} + +impl Beats { + /// Whether this process is still the writer, or `None` when the database couldn't be asked. + async fn beat(&mut self) -> Option { + match self.ask(Call::Beat).await { + Ok(still) => { + if let Some(since) = self.failing_since.take() { + tracing::info!( + failed_for_secs = since.elapsed().as_secs(), + "the writer's heartbeat reaches the database again" + ); + } + Some(still) + } + Err(err) => { + if self.failing_since.is_none() { + self.failing_since = Some(Instant::now()); + tracing::warn!( + error = %err, + "the writer's heartbeat could not reach the database. It goes on \ + trying; past 20 seconds of this, another dipper may take over" + ); + } + None + } + } + } + + /// Hands over. False if another process had taken over already, or the database couldn't + /// be asked: the next process then waits out the 20 seconds of silence. + async fn release(&mut self) -> bool { + match self.ask(Call::Release).await { + Ok(true) => { + tracing::info!( + event = "writer_released", + "handed over: the next dipper process takes over without waiting" + ); + true + } + Ok(false) => { + tracing::warn!("did not hand over: another dipper process had taken over already"); + false + } + Err(err) => { + tracing::warn!( + error = %err, + "could not hand over; the next dipper process takes over once this one has \ + been silent for 20 seconds" + ); + false + } + } + } + + /// Makes `call` on the heartbeat's connection, connecting it first if it isn't. A connection + /// that fails is given up and the call made once more on a new one: a takeover ends this + /// process's sessions, so a lost connection is the first sign of one. + async fn ask(&mut self, call: Call) -> anyhow::Result { + let had_connection = self.conn.is_some(); + match self.ask_once(call).await { + Err(_) if had_connection => self.ask_once(call).await, + asked => asked, + } + } + + /// Makes `call` on the heartbeat's connection, connecting it first if it isn't, within + /// [`BEAT_TIMEOUT`]. A failure drops the connection, so the next call connects afresh. + async fn ask_once(&mut self, call: Call) -> anyhow::Result { + let (options, token) = (&self.options, self.token); + let conn = &mut self.conn; + let asked = tokio::time::timeout(BEAT_TIMEOUT, async move { + let conn = match conn { + Some(conn) => conn, + None => conn.insert(options.connect().await?), + }; + match call { + Call::Beat => writer_fence::beat(conn, token).await, + Call::Release => writer_fence::release(conn, token).await, + } + }) + .await; + match asked { + Ok(Ok(answer)) => Ok(answer), + Ok(Err(err)) => { + self.conn = None; + Err(err.into()) + } + Err(_elapsed) => { + self.conn = None; + Err(anyhow::anyhow!( + "no answer within {}s", + BEAT_TIMEOUT.as_secs() + )) + } + } + } + + async fn close(&mut self) { + if let Some(conn) = self.conn.take() { + let _ = conn.close().await; + } + } +} + +/// Where [`note_refusal`] tells the heartbeat of a refused write. +static REFUSALS: OnceLock> = OnceLock::new(); + +/// What the [`heartbeat`] of this process listens on for refused writes. +pub fn refusals() -> Arc { + REFUSALS.get_or_init(|| Arc::new(Notify::new())).clone() +} + +/// Tells this process's heartbeat if `err` is the database refusing a write because this +/// process isn't the writer, so it checks at once instead of at its next beat, and the process +/// stops seconds sooner. Anything else is left alone. +pub fn note_refusal(err: &anyhow::Error) { + if refusal_in(err) { + refused(); + } +} + +/// Whether `err`, or an error it wraps, is the database refusing a write by the fence. +fn refusal_in(err: &anyhow::Error) -> bool { + err.chain().any(is_refusal) +} + +/// [`note_refusal`] for a database error. +pub fn note_db_refusal(err: &sqlx::Error) { + if writer_fence::is_refusal(err) { + refused(); + } +} + +fn refused() { + if let Some(refusals) = REFUSALS.get() { + refusals.notify_one(); + } +} + +/// Whether `err` is a refusal by the fence, as the database, the registry or the queue reports it. +fn is_refusal(err: &(dyn std::error::Error + 'static)) -> bool { + if let Some(err) = err.downcast_ref::() { + return writer_fence::is_refusal(err); + } + if let Some(dipper_pgregistry::Error::DbError(err)) = err.downcast_ref() { + return writer_fence::is_refusal(err); + } + if let Some(crate::registry::Error::BackendError(dipper_pgregistry::Error::DbError(err))) = + err.downcast_ref() + { + return writer_fence::is_refusal(err); + } + false +} + +/// Lets a chain broadcast through only while this process is the writer. Each broadcast holds a +/// pooled connection in a transaction for as long as it lasts, which a new writer's takeover +/// waits for. +pub struct WriterGate { + pool: PgPool, + token: Uuid, +} + +impl WriterGate { + pub fn new(pool: PgPool, token: Uuid) -> Self { + Self { pool, token } + } +} + +#[async_trait] +impl BroadcastGate for WriterGate { + async fn open(&self) -> anyhow::Result> { + let guard = writer_fence::BroadcastGuard::begin(&self.pool, self.token) + .await + .context("failed to start the broadcast's check that this process is the writer")?; + Ok(Box::new(WriterTurn(Mutex::new(guard)))) + } +} + +struct WriterTurn(Mutex); + +#[async_trait] +impl BroadcastTurn for WriterTurn { + async fn still_writer(&self) -> anyhow::Result { + let still = self + .0 + .lock() + .await + .still_writer() + .await + .context("failed to check that this process is still the writer")?; + if !still { + // Another process took over: the heartbeat confirms it and stops this one. + refused(); + } + Ok(still) + } + + async fn end(self: Box) { + if let Err(err) = self.0.into_inner().end().await { + // The transaction goes with its connection either way; a takeover then ends it. + tracing::debug!(error = %err, "could not end a broadcast's writer check cleanly"); + } + } +} + +#[cfg(test)] +mod tests { + use std::{sync::Arc, time::Duration}; + + use dipper_pgmq::{JobBuilder, PgQueue}; + use dipper_pgregistry::writer_fence; + use sqlx::{ + ConnectOptions as _, PgPool, + postgres::{PgConnectOptions, PgPoolOptions}, + }; + use tokio::{sync::Notify, task::JoinHandle}; + use uuid::Uuid; + + use super::*; + use crate::registry::IndexingRequestRegistry as _; + + /// A database as dipper's start leaves it before any takeover: both migrations run and every + /// table fenced, on an operator's session. + async fn started_db() -> (pgtemp::PgTempDB, PgConnectOptions) { + let temp_db = crate::test_support::temp_postgres(); + let base = crate::test_support::temp_postgres_options(&temp_db); + let mut operator = operator(&base).await; + dipper_pgmq::run_db_migrations(&mut operator) + .await + .expect("run the queue's migrations"); + dipper_pgregistry::run_db_migrations(&mut operator) + .await + .expect("run the registry's migrations"); + fence_every_table(&mut operator) + .await + .expect("fence every table"); + (temp_db, base) + } + + async fn operator(base: &PgConnectOptions) -> PgConnection { + writer_fence::operator_options(base.clone()) + .connect() + .await + .expect("open an operator session") + } + + /// The pool of the process with `token`, as `db::connect` opens it. + async fn pool_of(base: &PgConnectOptions, token: Uuid) -> PgPool { + PgPoolOptions::new() + .max_connections(4) + .connect_with(writer_fence::writer_options(base.clone(), token)) + .await + .expect("open the pool") + } + + /// Makes the process whose pool is `pool` the writer, as its start does: takes over, starts + /// the heartbeat, and settles what the process it replaced had in flight. + async fn start( + pool: &PgPool, + token: Uuid, + refusals: Arc, + ) -> (Handle, JoinHandle>) { + let taken = Takeover::new(pool, token, "test".to_owned()) + .take() + .await + .expect("take over"); + let (handle, beating) = heartbeat(pool.connect_options().as_ref().clone(), token, refusals); + let beating = tokio::spawn(beating); + taken.settle().await.expect("settle the takeover"); + (handle, beating) + } + + /// Hands over for the writer, as an operator does for one that won't stop. + async fn force_handover(base: &PgConnectOptions) { + sqlx::query("UPDATE dipper_writer_heartbeat SET released = true") + .execute(&mut operator(base).await) + .await + .expect("hand over by hand"); + } + + async fn write(pool: &PgPool) -> sqlx::Result<()> { + sqlx::query( + "INSERT INTO dipper_kafka_consumer_offsets (topic, partition_id, next_offset) \ + VALUES (gen_random_uuid()::text, 0, 1)", + ) + .execute(pool) + .await + .map(drop) + } + + fn refused(result: sqlx::Result<()>) -> bool { + result.is_err_and(|err| writer_fence::is_refusal(&err)) + } + + #[tokio::test] + async fn it_fences_every_table_and_a_new_database_is_taken_over_at_once() { + //* Given + let (_temp_db, base) = started_db().await; + let mut operator = operator(&base).await; + let token = new_token(); + let pool = pool_of(&base, token).await; + + //* Then - every table is fenced, the queue's without the lock a job would hold + assert!( + writer_fence::unfenced(&mut operator) + .await + .unwrap() + .is_empty() + ); + let queue_check: String = sqlx::query_scalar( + "SELECT p.proname::text FROM pg_trigger t JOIN pg_proc p ON p.oid = t.tgfoid \ + WHERE t.tgrelid = 'pgmq_queue'::regclass AND t.tgname = 'dipper_fence'", + ) + .fetch_one(&mut operator) + .await + .unwrap(); + assert_eq!(queue_check, "dipper_fence_nolock"); + assert!(refused(write(&pool).await), "refused until it takes over"); + + //* When + let started = Instant::now(); + let (handle, _beating) = start(&pool, token, Arc::new(Notify::new())).await; + + //* Then + assert!( + started.elapsed() < ASK_EVERY, + "a new database has no writer to wait for" + ); + assert!(write(&pool).await.is_ok()); + assert!(handle.finish(true).await, "it hands over at its stop"); + } + + #[tokio::test] + async fn it_waits_while_the_writer_is_healthy_and_takes_over_once_it_hands_over() { + //* Given + let (_temp_db, base) = started_db().await; + let (old, new) = (new_token(), new_token()); + let old_pool = pool_of(&base, old).await; + let (old_handle, _old_beating) = start(&old_pool, old, Arc::new(Notify::new())).await; + let new_pool = pool_of(&base, new).await; + let takeover = Takeover::new(&new_pool, new, "new".to_owned()); + + //* When + let waiting = tokio::spawn(async move { takeover.take().await }); + tokio::time::sleep(ASK_EVERY + Duration::from_secs(1)).await; + + //* Then + assert!(!waiting.is_finished(), "a healthy writer is waited for"); + + //* When - the old writer stops, and hands over + assert!(old_handle.finish(true).await); + + //* Then + let taken = tokio::time::timeout(ASK_EVERY * 3, waiting) + .await + .expect("it takes over at its next ask") + .expect("the takeover task") + .expect("take over"); + taken.settle().await.expect("settle the takeover"); + assert!(write(&new_pool).await.is_ok()); + assert!(refused(write(&old_pool).await)); + } + + #[tokio::test] + async fn it_stops_a_replaced_writer_as_soon_as_a_write_of_it_is_refused() { + //* Given - a writer that won't stop, and an operator forcing a handover + let (_temp_db, base) = started_db().await; + let (old, new) = (new_token(), new_token()); + let old_pool = pool_of(&base, old).await; + let refusals = Arc::new(Notify::new()); + let (_old_handle, old_beating) = start(&old_pool, old, Arc::clone(&refusals)).await; + force_handover(&base).await; + let new_pool = pool_of(&base, new).await; + let (_new_handle, _new_beating) = start(&new_pool, new, Arc::new(Notify::new())).await; + + //* When - the old writer's next write is refused, which tells its heartbeat + assert!(refused(write(&old_pool).await)); + refusals.notify_one(); + + //* Then - it stops well before its next heartbeat was due + let stopped = tokio::time::timeout(Duration::from_secs(2), old_beating) + .await + .expect("the heartbeat stops the process at once") + .expect("the heartbeat task"); + assert!( + stopped.is_err_and(|err| err.downcast_ref::().is_some()), + "it stops as replaced" + ); + } + + #[tokio::test] + async fn it_ends_the_replaced_writers_sessions_which_puts_its_running_job_back() { + //* Given - the old writer is running a job when an operator forces a handover + let (_temp_db, base) = started_db().await; + let (old, new) = (new_token(), new_token()); + let old_pool = pool_of(&base, old).await; + let (_old_handle, _old_beating) = start(&old_pool, old, Arc::new(Notify::new())).await; + let old_queue = PgQueue::with_max_retries(old_pool.clone(), 2); + old_queue + .push(JobBuilder::new("a job".to_owned())) + .await + .expect("queue a job"); + let running = old_queue + .pop::() + .await + .expect("pop") + .expect("the job"); + force_handover(&base).await; + + //* When + let new_pool = pool_of(&base, new).await; + let (_new_handle, _new_beating) = start(&new_pool, new, Arc::new(Notify::new())).await; + + //* Then - the new writer gets the job, and the old one can't settle it + let new_queue = PgQueue::with_max_retries(new_pool.clone(), 2); + let job = new_queue + .pop::() + .await + .expect("pop") + .expect("the job is free once the takeover has settled"); + assert_eq!(job.id(), running.id()); + assert!(running.remove().await.is_err()); + job.remove().await.expect("the new writer settles it"); + } + + #[tokio::test] + async fn it_lets_a_broadcast_through_only_while_this_process_is_the_writer() { + //* Given + let (_temp_db, base) = started_db().await; + let (old, new) = (new_token(), new_token()); + let old_pool = pool_of(&base, old).await; + let (_old_handle, _old_beating) = start(&old_pool, old, Arc::new(Notify::new())).await; + let gate = WriterGate::new(old_pool.clone(), old); + + //* Then + let turn = gate.open().await.expect("open a turn"); + assert!(turn.still_writer().await.expect("ask")); + turn.end().await; + + //* When + force_handover(&base).await; + let new_pool = pool_of(&base, new).await; + let (_new_handle, _new_beating) = start(&new_pool, new, Arc::new(Notify::new())).await; + + //* Then + let turn = gate.open().await.expect("open a turn"); + assert!(!turn.still_writer().await.expect("ask")); + turn.end().await; + } + + #[tokio::test] + async fn it_recognises_a_refusal_however_it_reaches_the_process() { + //* Given - a process that never became the writer + let (_temp_db, base) = started_db().await; + let pool = pool_of(&base, new_token()).await; + + //* When + let from_queue = PgQueue::with_max_retries(pool.clone(), 2) + .push(JobBuilder::new("a job".to_owned())) + .await + .expect_err("the queue refuses it"); + let from_registry = crate::registry::RegistryProvider::new(pool) + .set_indexing_target_candidates( + thegraph_core::alloy::primitives::Address::ZERO, + thegraph_core::deployment_id!("QmUzRg2HHMpbgf6Q4VHKNDbtBEJnyp5JWCh2gUX9AV6jXv"), + 1, + 1, + ) + .await + .expect_err("the registry refuses it"); + + //* Then + assert!(refusal_in(&from_queue)); + assert!(refusal_in( + &anyhow::Error::from(from_registry).context("in a job") + )); + assert!(!refusal_in(&anyhow::anyhow!("an error of another kind"))); + } +} diff --git a/dipper-pgregistry/migrations/20261120000000_add_writer_fence.sql b/dipper-pgregistry/migrations/20261120000000_add_writer_fence.sql new file mode 100644 index 00000000..31454492 --- /dev/null +++ b/dipper-pgregistry/migrations/20261120000000_add_writer_fence.sql @@ -0,0 +1,244 @@ +-- The writer fence. Dipper's flows assume a single process writes to this database; the fence is +-- what makes that true. 1 row names the process allowed to write, by a random token every +-- process picks at start and sets on each of its sessions as `dipper.writer`. A trigger on every +-- table refuses a write from any session whose token isn't that one, so a process that has been +-- replaced is refused however late it learns of it. Statements that passed the check hold a +-- shared advisory lock until their transaction ends, which lets a new writer wait for them. +-- +-- Sessions marked `dipper.writer = operator` (manual work and migrations) pass the check, and +-- `SELECT dipper_fence_set(false)` turns the fence off until `dipper_fence_set(true)`. + +CREATE TABLE dipper_writer +( + id BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (id), -- 1 row + token UUID NOT NULL, -- the current writer's token + holder TEXT NOT NULL, -- its host name, for operators + taken_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + enforced BOOLEAN NOT NULL DEFAULT TRUE -- false lets every write through +); + +-- Handover only: lets a starting process wait while the writer is healthy. Never used for safety. +CREATE TABLE dipper_writer_heartbeat +( + id BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (id), -- 1 row + token UUID NOT NULL, + seen_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + released BOOLEAN NOT NULL DEFAULT TRUE +); + +-- No writer yet, and released, so the first process to start takes over at once. +INSERT INTO dipper_writer (token, holder) VALUES (gen_random_uuid(), 'nobody'); +INSERT INTO dipper_writer_heartbeat (token) SELECT token FROM dipper_writer; + +-- Taken by every write and every chain broadcast that passed the check, until its transaction +-- ends. The 2-integer form shares no key space with the 1-bigint advisory locks used elsewhere. +CREATE FUNCTION dipper_fence_lock_shared() RETURNS void + LANGUAGE sql AS +$$ SELECT pg_advisory_xact_lock_shared(1684631664, 1) $$; + +-- Refuses a write unless this session carries the current writer's token. The lock comes first +-- and the token is read after it, with a fresh statement, so every statement that passed the +-- check holds the lock, and a new writer's drain waits for exactly those. +CREATE FUNCTION dipper_fence() RETURNS trigger + LANGUAGE plpgsql AS +$$ +DECLARE + who TEXT := current_setting('dipper.writer', TRUE); +BEGIN + IF who = 'operator' THEN + RETURN NULL; + END IF; + IF (SELECT NOT enforced FROM dipper_writer) THEN + RETURN NULL; + END IF; + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'dipper: its tables are written under READ COMMITTED only' + USING ERRCODE = 'DP002'; + END IF; + PERFORM dipper_fence_lock_shared(); + IF NOT EXISTS (SELECT 1 FROM dipper_writer WHERE token::TEXT = who) THEN + RAISE EXCEPTION 'dipper: this session is not the current writer' + USING ERRCODE = 'DP001', + HINT = 'A newer dipper took over, or this session has no dipper.writer setting.'; + END IF; + RETURN NULL; +END +$$; + +-- The same check without the lock, for the job queue: a job's transaction stays open for the +-- whole job, and must not hold a new writer back. The job's writes to the other tables are fenced +-- with the lock, and a takeover ends the old writer's sessions, which puts its jobs back. +CREATE FUNCTION dipper_fence_nolock() RETURNS trigger + LANGUAGE plpgsql AS +$$ +DECLARE + who TEXT := current_setting('dipper.writer', TRUE); +BEGIN + IF who = 'operator' THEN + RETURN NULL; + END IF; + IF (SELECT NOT enforced FROM dipper_writer) THEN + RETURN NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM dipper_writer WHERE token::TEXT = who) THEN + RAISE EXCEPTION 'dipper: this session is not the current writer' + USING ERRCODE = 'DP001', + HINT = 'A newer dipper took over, or this session has no dipper.writer setting.'; + END IF; + RETURN NULL; +END +$$; + +-- The off switch: 1 row update, so it takes no table lock, and it stays as set across restarts. +CREATE FUNCTION dipper_fence_set(enforce BOOLEAN) RETURNS void + LANGUAGE sql AS +$$ UPDATE dipper_writer SET enforced = enforce $$; + +-- The tables in this schema without an enabled fence. Checked at every start, so a table a later +-- migration adds is fenced without anyone having to remember to. +CREATE FUNCTION dipper_fence_unfenced() RETURNS SETOF regclass + LANGUAGE sql + STABLE AS +$$ +SELECT c.oid::regclass +FROM pg_class c + JOIN pg_namespace s ON s.oid = c.relnamespace +WHERE c.relkind IN ('r', 'p') + AND s.nspname = current_schema() + AND c.relname NOT IN ('dipper_writer', 'dipper_writer_heartbeat', '_sqlx_migrations') + AND NOT EXISTS (SELECT 1 + FROM pg_trigger g + WHERE g.tgrelid = c.oid + AND g.tgname = 'dipper_fence' + AND g.tgenabled IN ('O', 'A')) +$$; + +-- Fences 1 table. Called for 1 table at a time, each in a transaction of its own with a lock +-- timeout, so a table busy with a long transaction can't make it hold locks on the others. +CREATE FUNCTION dipper_fence_attach(tbl regclass) RETURNS void + LANGUAGE plpgsql AS +$$ +BEGIN + BEGIN + EXECUTE format( + 'CREATE TRIGGER dipper_fence BEFORE INSERT OR UPDATE OR DELETE OR TRUNCATE ON %s + FOR EACH STATEMENT EXECUTE FUNCTION %s()', + tbl, + CASE WHEN tbl = to_regclass('pgmq_queue') THEN 'dipper_fence_nolock' ELSE 'dipper_fence' END); + EXCEPTION + WHEN duplicate_object THEN NULL; -- another starting process got there first + END; + EXECUTE format('ALTER TABLE %s ENABLE TRIGGER dipper_fence', tbl); +END +$$; + +-- Takes over as the writer if the current one has released, or has been silent for +-- `stale_after`. False means a healthy writer exists: wait, and ask again. From the moment this +-- commits every new statement of the old writer is refused; `dipper_writer_drain` waits for the +-- statements it had already started. +CREATE FUNCTION dipper_writer_take(new UUID, me TEXT, stale_after INTERVAL) RETURNS BOOLEAN + LANGUAGE plpgsql AS +$$ +DECLARE + h dipper_writer_heartbeat; +BEGIN + -- 1 starting process at a time, and the current writer's heartbeat waits here too. + SELECT * INTO h FROM dipper_writer_heartbeat FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'dipper: the writer fence has no row' USING ERRCODE = 'DP003'; + END IF; + IF h.token = new THEN + RETURN TRUE; -- an earlier call of ours already took over + END IF; + IF NOT (h.released OR h.seen_at < clock_timestamp() - stale_after) THEN + RETURN FALSE; + END IF; + UPDATE dipper_writer SET token = new, holder = me, taken_at = clock_timestamp(); + IF NOT FOUND THEN + RAISE EXCEPTION 'dipper: the writer fence has no row' USING ERRCODE = 'DP003'; + END IF; + UPDATE dipper_writer_heartbeat SET token = new, seen_at = clock_timestamp(), released = FALSE; + RETURN TRUE; +END +$$; + +-- Waits until every write and broadcast that passed the check before the takeover has ended. +-- Statements arriving later queue behind this request, then read the new token and are refused. +CREATE FUNCTION dipper_writer_drain() RETURNS void + LANGUAGE sql AS +$$ SELECT pg_advisory_xact_lock(1684631664, 1) $$; + +-- Ends every session named for another dipper process (`dipper/...`), which rolls back +-- what it had open and frees the jobs and session locks it held. It waits up to 1 second for each +-- to be gone, so what they held is free when it returns. It acts only for the current writer, +-- and holds the row a takeover takes first, so no process can take over while it runs: a session +-- it ends is never the current writer's. +CREATE FUNCTION dipper_writer_cut(mine UUID) RETURNS INT + LANGUAGE plpgsql AS +$$ +DECLARE + s RECORD; + n INT := 0; +BEGIN + PERFORM 1 FROM dipper_writer_heartbeat WHERE token = mine FOR UPDATE; + IF NOT FOUND THEN + RETURN 0; + END IF; + FOR s IN SELECT pid + FROM pg_stat_activity + WHERE datname = current_database() + AND pid <> pg_backend_pid() + AND application_name LIKE 'dipper/%' + AND application_name NOT LIKE 'dipper/' || mine || '%' + LOOP + BEGIN + IF pg_terminate_backend(s.pid, 1000) THEN + n := n + 1; + END IF; + EXCEPTION + WHEN insufficient_privilege THEN NULL; -- another role's session: not ours to end + END; + END LOOP; + RETURN n; +END +$$; + +-- The writer's heartbeat. False means another process has taken over: stop at once. +CREATE FUNCTION dipper_writer_beat(mine UUID) RETURNS BOOLEAN + LANGUAGE plpgsql AS +$$ +BEGIN + UPDATE dipper_writer_heartbeat SET seen_at = clock_timestamp() WHERE token = mine; + RETURN FOUND; +END +$$; + +-- A clean shutdown's last step: lets the next process take over without waiting. +CREATE FUNCTION dipper_writer_release(mine UUID) RETURNS BOOLEAN + LANGUAGE plpgsql AS +$$ +BEGIN + UPDATE dipper_writer_heartbeat SET released = TRUE WHERE token = mine; + RETURN FOUND; +END +$$; + +-- A chain broadcast's guard. Called at the start of the broadcast's transaction and again before +-- each attempt: it holds off a new writer's drain, and says whether this process is still the +-- writer. Under any isolation but READ COMMITTED each call would read the token as the first did, +-- and miss a takeover, so it refuses as the write fence does. +CREATE FUNCTION dipper_writer_guard(mine UUID) RETURNS BOOLEAN + LANGUAGE plpgsql AS +$$ +BEGIN + IF (SELECT NOT enforced FROM dipper_writer) THEN + RETURN TRUE; + END IF; + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'dipper: a broadcast is checked under READ COMMITTED only' + USING ERRCODE = 'DP002'; + END IF; + PERFORM dipper_fence_lock_shared(); + RETURN EXISTS (SELECT 1 FROM dipper_writer WHERE token = mine); +END +$$; diff --git a/dipper-pgregistry/src/lib.rs b/dipper-pgregistry/src/lib.rs index d7b8f4d2..a1fb8681 100644 --- a/dipper-pgregistry/src/lib.rs +++ b/dipper-pgregistry/src/lib.rs @@ -9,6 +9,7 @@ mod indexing_agreement; mod indexing_request; mod postgres; mod result; +pub mod writer_fence; pub use indexing_agreement::{ Indexer as IndexingAgreementIndexer, IndexingAgreement, Status as IndexingAgreementStatus, diff --git a/dipper-pgregistry/src/postgres/advisory_lock.rs b/dipper-pgregistry/src/postgres/advisory_lock.rs index d6e6d791..c41703bc 100644 --- a/dipper-pgregistry/src/postgres/advisory_lock.rs +++ b/dipper-pgregistry/src/postgres/advisory_lock.rs @@ -18,8 +18,10 @@ pub struct AdvisoryLockConnection { impl PgRegistry { /// Opens a connection of its own, to the pool's database, to take the lock `key` on. It is - /// listed in `pg_stat_activity` under the application name `name`, and the database is told - /// to end it once nothing has been asked on it for `idle_timeout`, which frees the lock. + /// listed in `pg_stat_activity` under the application name `name`, after the pool's own name + /// when the pool has one (`dipper//`), so a takeover by another dipper process + /// ends it with the rest of this one's sessions. The database is told to end it once nothing + /// has been asked on it for `idle_timeout`, which frees the lock. pub async fn advisory_lock_connection( &self, key: i64, @@ -27,7 +29,7 @@ impl PgRegistry { idle_timeout: Duration, ) -> Result { let options = self.pool.connect_options().as_ref().clone(); - let mut conn = options.application_name(name).connect().await?; + let mut conn = crate::writer_fence::named(options, name).connect().await?; // Set once connected and not as a startup option, which a database that lacks the // setting would refuse the whole connection over. Without a unit the value is in ms. let set = sqlx::query("SELECT set_config('idle_session_timeout', $1, false)") diff --git a/dipper-pgregistry/src/writer_fence.rs b/dipper-pgregistry/src/writer_fence.rs new file mode 100644 index 00000000..eff3764f --- /dev/null +++ b/dipper-pgregistry/src/writer_fence.rs @@ -0,0 +1,253 @@ +//! The writer fence, from a dipper process's side. +//! +//! Dipper's flows assume a single process writes to its database. The migration that adds the +//! fence makes Postgres enforce it: 1 row names the process allowed to write, by a token every +//! process picks at start, and a trigger on every table refuses a write from any session that +//! doesn't carry that token. A process that has been replaced is refused however late it learns +//! of it, so 2 processes overlapping behave like the older one crashing. +//! +//! This module is what a process asks of the fence: to take over ([`take`]), to wait for the +//! statements the old writer had started ([`drain`]) and end its sessions ([`cut`]), to say it is +//! still alive ([`beat`]) and to hand over at a clean stop ([`release`]). A chain broadcast isn't +//! a database write, so it asks through a [`BroadcastGuard`] instead. + +use std::time::Duration; + +use sqlx::{Acquire as _, PgConnection, PgPool, Postgres, Transaction, postgres::PgConnectOptions}; +use uuid::Uuid; + +/// The session setting that says which dipper process a session belongs to: its token, or +/// [`OPERATOR`]. +pub const SETTING: &str = "dipper.writer"; + +/// The value of [`SETTING`] for manual work and migrations, which the fence lets through. +pub const OPERATOR: &str = "operator"; + +/// The application name of an [`OPERATOR`] session. It doesn't start with [`SESSION_PREFIX`], so +/// no takeover ends it. +pub const OPERATOR_SESSION: &str = "dipper-operator"; + +/// What every session of a dipper process is named, in `pg_stat_activity`, before its token. A +/// takeover ends every session named so for another token; see [`cut`]. +pub const SESSION_PREFIX: &str = "dipper/"; + +/// The SQLSTATE of a write the fence refused: the session isn't the current writer's. +pub const REFUSED: &str = "DP001"; + +/// The SQLSTATE of a statement that waited longer than its lock timeout (`lock_not_available`). +const LOCK_NOT_AVAILABLE: &str = "55P03"; + +/// The name of the sessions of the process with `token`: `dipper/`. +pub fn session_name(token: Uuid) -> String { + format!("{SESSION_PREFIX}{token}") +} + +/// `options` for a session of the process with `token`: the fence lets its writes through while +/// that process is the writer, and a takeover by another process ends it. +pub fn writer_options(options: PgConnectOptions, token: Uuid) -> PgConnectOptions { + options + .options([(SETTING, token)]) + .application_name(&session_name(token)) +} + +/// `options` for an [`OPERATOR`] session, which the fence lets through and no takeover ends. +pub fn operator_options(options: PgConnectOptions) -> PgConnectOptions { + options + .options([(SETTING, OPERATOR)]) + .application_name(OPERATOR_SESSION) +} + +/// `options` under a name of their own, `/`, so the session can be told apart +/// in `pg_stat_activity` and still counts as the same process's. Postgres keeps the first 63 +/// bytes of a name. +pub fn named(options: PgConnectOptions, part: &str) -> PgConnectOptions { + let name = match options.get_application_name() { + Some(base) => format!("{base}/{part}"), + None => part.to_owned(), + }; + options.application_name(&name) +} + +/// Whether `err` is the fence refusing a write, because the session isn't the current writer's. +pub fn is_refusal(err: &sqlx::Error) -> bool { + has_code(err, REFUSED) +} + +fn has_code(err: &sqlx::Error, code: &str) -> bool { + matches!(err, sqlx::Error::Database(db) if db.code().as_deref() == Some(code)) +} + +/// The tables without an enabled fence, by name. Every start fences them: see [`attach`]. +pub async fn unfenced(conn: &mut PgConnection) -> sqlx::Result> { + sqlx::query_scalar("SELECT tbl::text FROM dipper_fence_unfenced() AS tbl ORDER BY 1") + .fetch_all(conn) + .await +} + +/// Fences `table`, in a transaction of its own. False when a transaction kept the table busy for +/// longer than `lock_timeout`, which leaves it as it was: ask again. +pub async fn attach( + conn: &mut PgConnection, + table: &str, + lock_timeout: Duration, +) -> sqlx::Result { + let mut tx = conn.begin().await?; + set_lock_timeout(&mut tx, lock_timeout).await?; + let attached = sqlx::query("SELECT dipper_fence_attach($1::regclass)") + .bind(table) + .execute(&mut *tx) + .await; + finish_within_lock_timeout(tx, attached).await +} + +/// Whether the fence is on. `SELECT dipper_fence_set(false)` turns it off until it is turned on +/// again, across restarts. +pub async fn enforced(conn: &mut PgConnection) -> sqlx::Result { + sqlx::query_scalar("SELECT enforced FROM dipper_writer") + .fetch_one(conn) + .await +} + +/// Takes over as the writer if the current one released or has been silent for `stale_after`; +/// `holder` names this process for operators. False means a healthy writer exists: ask again. +/// +/// From the moment this returns true, every new statement of the old writer is refused. It may +/// still have statements in flight: [`drain`] waits for them. Asking again after a true, as after +/// a lost connection, answers true again. +pub async fn take( + conn: &mut PgConnection, + token: Uuid, + holder: &str, + stale_after: Duration, +) -> sqlx::Result { + sqlx::query_scalar("SELECT dipper_writer_take($1, $2, make_interval(secs => $3))") + .bind(token) + .bind(holder) + .bind(stale_after.as_secs_f64()) + .fetch_one(conn) + .await +} + +/// Waits until every write and broadcast that passed the fence before the takeover has ended. +/// False when that took longer than `lock_timeout`: a session of the old writer is stuck, and +/// [`cut`] ends it. +pub async fn drain(conn: &mut PgConnection, lock_timeout: Duration) -> sqlx::Result { + let mut tx = conn.begin().await?; + set_lock_timeout(&mut tx, lock_timeout).await?; + let drained = sqlx::query("SELECT dipper_writer_drain()") + .execute(&mut *tx) + .await; + finish_within_lock_timeout(tx, drained).await +} + +/// What a [`drain`] is waiting for: the sessions holding the fence's lock, by name, and any +/// prepared transaction holding it, which no session holds and no [`cut`] can end. +pub async fn drain_blockers(conn: &mut PgConnection) -> sqlx::Result> { + sqlx::query_scalar( + "SELECT coalesce(nullif(a.application_name, ''), 'pid ' || l.pid, \ + 'a prepared transaction (roll it back with ROLLBACK PREPARED)') \ + FROM pg_locks l LEFT JOIN pg_stat_activity a ON a.pid = l.pid \ + WHERE l.locktype = 'advisory' AND l.granted \ + AND l.classid = 1684631664 AND l.objid = 1 AND l.objsubid = 2 \ + AND l.database = (SELECT oid FROM pg_database WHERE datname = current_database()) \ + ORDER BY 1", + ) + .fetch_all(conn) + .await +} + +/// Ends every session named for another dipper process, which rolls back what it had open and +/// frees the jobs and locks it held; returns how many it ended. It acts only while `token` is the +/// writer, and no process can take over while it runs, so it never ends the current writer's. +/// Sessions of another database role are skipped: their role alone may end them. +pub async fn cut(conn: &mut PgConnection, token: Uuid) -> sqlx::Result { + sqlx::query_scalar("SELECT dipper_writer_cut($1)") + .bind(token) + .fetch_one(conn) + .await +} + +/// The writer's heartbeat. False means another process has taken over: stop at once. +pub async fn beat(conn: &mut PgConnection, token: Uuid) -> sqlx::Result { + sqlx::query_scalar("SELECT dipper_writer_beat($1)") + .bind(token) + .fetch_one(conn) + .await +} + +/// A clean stop's last step: the next process takes over without waiting for this one to go +/// silent. False if another process had already taken over. +pub async fn release(conn: &mut PgConnection, token: Uuid) -> sqlx::Result { + sqlx::query_scalar("SELECT dipper_writer_release($1)") + .bind(token) + .fetch_one(conn) + .await +} + +/// Lets 1 chain broadcast through only while this process is the writer. It holds a pooled +/// connection in a transaction for as long as the broadcast lasts, and the fence's shared lock +/// from the first check on, so a new writer's [`drain`] waits for the broadcast. Ask +/// [`BroadcastGuard::still_writer`] before each attempt, and [`BroadcastGuard::end`] it when the +/// broadcast ends. +pub struct BroadcastGuard { + tx: Transaction<'static, Postgres>, + token: Uuid, +} + +impl BroadcastGuard { + /// Starts the guard's transaction, on a connection from `pool`, under READ COMMITTED whatever + /// the database's default: each check must read the token afresh to see a takeover. + pub async fn begin(pool: &PgPool, token: Uuid) -> sqlx::Result { + Ok(Self { + tx: pool + .begin_with("BEGIN ISOLATION LEVEL READ COMMITTED") + .await?, + token, + }) + } + + /// Whether this process is still the writer, or the fence is off. Once it says false the + /// process has been replaced, and no attempt should start. + pub async fn still_writer(&mut self) -> sqlx::Result { + sqlx::query_scalar("SELECT dipper_writer_guard($1)") + .bind(self.token) + .fetch_one(&mut *self.tx) + .await + } + + /// Ends the guard's transaction, which lets go of the fence's lock at once. Dropping the + /// guard instead leaves that to whenever the pool next flushes the connection. + pub async fn end(self) -> sqlx::Result<()> { + self.tx.rollback().await + } +} + +async fn set_lock_timeout( + tx: &mut Transaction<'_, Postgres>, + lock_timeout: Duration, +) -> sqlx::Result<()> { + sqlx::query("SELECT set_config('lock_timeout', $1, true)") + .bind(format!("{}ms", lock_timeout.as_millis().max(1))) + .execute(&mut **tx) + .await?; + Ok(()) +} + +/// Commits `tx` if `outcome` succeeded; rolls it back and answers false if it ran out of its lock +/// timeout. +async fn finish_within_lock_timeout( + tx: Transaction<'_, Postgres>, + outcome: sqlx::Result, +) -> sqlx::Result { + match outcome { + Ok(_) => { + tx.commit().await?; + Ok(true) + } + Err(err) if has_code(&err, LOCK_NOT_AVAILABLE) => { + tx.rollback().await?; + Ok(false) + } + Err(err) => Err(err), + } +} diff --git a/dipper-pgregistry/tests/it_registry_postgres.rs b/dipper-pgregistry/tests/it_registry_postgres.rs index 71e175f2..e9f46fa8 100644 --- a/dipper-pgregistry/tests/it_registry_postgres.rs +++ b/dipper-pgregistry/tests/it_registry_postgres.rs @@ -1,16 +1,22 @@ #![cfg(feature = "fake")] -use std::collections::{HashMap, HashSet}; +use std::{ + collections::{HashMap, HashSet}, + time::Duration, +}; use dipper_core::ids::{IndexingAgreementId, IndexingRequestId}; use dipper_pgregistry::{ CancelKind, EndCorrection, Error, IndexingAgreementStatus, IndexingAgreementTerms, IndexingRequestStatus, NewAgreementParams, PgRegistry, ReconciliationAudit, ReconciliationItem, - RecordedEnd, SetAsideChange, SetAsideRequest, WithheldIndexers, + RecordedEnd, SetAsideChange, SetAsideRequest, WithheldIndexers, writer_fence, }; use fake::{Fake, Faker}; use pgtemp::{PgTempDB, PgTempDBBuilder}; -use sqlx::{Executor as _, Pool, Postgres, postgres::PgConnectOptions}; +use sqlx::{ + ConnectOptions as _, Executor as _, Pool, Postgres, + postgres::{PgConnectOptions, PgPoolOptions}, +}; use thegraph_core::{ DeploymentId, IndexerId, alloy::primitives::{ChainId, address}, @@ -38,22 +44,42 @@ fn temp_postgres() -> (PgTempDB, PgConnectOptions) { (temp_db, options) } -/// Initialize a temporary database for integration testing. +/// Initialize a temporary database for integration testing, as dipper's start leaves it: the +/// migrations run and every table fenced by an operator's session, and a pool whose sessions +/// belong to the process that is the writer. Every test here so runs through the writer fence. /// -/// This function creates a temporary database and runs the migrations. /// It returns the database connection pool and the temporary database guard. #[expect( clippy::expect_used, reason = "test setup; a failure should stop the test" )] async fn temp_registry_db() -> (Pool, PgTempDB) { - let (temp_db, options) = temp_postgres(); - let db = Pool::connect_with(options) + let (temp_db, base) = temp_postgres(); + let mut operator = writer_fence::operator_options(base.clone()) + .connect() .await .expect("Failed to connect to temporary database"); - dipper_pgregistry::run_db_migrations(&db) + dipper_pgregistry::run_db_migrations(&mut operator) .await .expect("Failed to run DB migrations"); + for table in writer_fence::unfenced(&mut operator) + .await + .expect("Failed to list the unfenced tables") + { + let fenced = writer_fence::attach(&mut operator, &table, Duration::from_secs(5)) + .await + .expect("Failed to fence a table"); + assert!(fenced, "{table} is free to fence"); + } + let writer = uuid::Uuid::now_v7(); + let took_over = writer_fence::take(&mut operator, writer, "test", Duration::ZERO) + .await + .expect("Failed to take over as the writer"); + assert!(took_over, "a new database has no writer to wait for"); + let db = PgPoolOptions::new() + .connect_with(writer_fence::writer_options(base, writer)) + .await + .expect("Failed to connect to temporary database"); (db, temp_db) } @@ -5195,17 +5221,24 @@ async fn a_database_that_refuses_the_idle_timeout_still_gives_a_connection_for_t } /// The lock's session has a name of its own, so that the session holding the lock can be -/// told from the pool's in `pg_stat_activity` when someone has to end it by hand. +/// told from the pool's in `pg_stat_activity` when someone has to end it by hand. It follows +/// the pool's own name, so a takeover by another dipper process ends it with the rest of this +/// process's sessions. #[tokio::test] async fn a_lock_connection_is_listed_by_the_database_under_its_name() { //* Given let (db, _temp_db) = temp_registry_db().await; let registry = PgRegistry::new(db.clone()); + let pool_name = db + .connect_options() + .get_application_name() + .map(str::to_owned) + .expect("the pool's sessions are named for their process"); let named = async || { sqlx::query_scalar::<_, i64>( "SELECT count(*) FROM pg_stat_activity WHERE application_name = $1", ) - .bind("dipper-test-lock") + .bind(format!("{pool_name}/dipper-test-lock")) .fetch_one(&db) .await .expect("read pg_stat_activity") diff --git a/dipper-pgregistry/tests/it_writer_fence.rs b/dipper-pgregistry/tests/it_writer_fence.rs new file mode 100644 index 00000000..d68a6df6 --- /dev/null +++ b/dipper-pgregistry/tests/it_writer_fence.rs @@ -0,0 +1,523 @@ +//! The writer fence against a real Postgres: who may write, how a process takes over, and what a +//! takeover does to the process it replaces. + +use std::time::Duration; + +use dipper_pgregistry::writer_fence; +use pgtemp::{PgTempDB, PgTempDBBuilder}; +use sqlx::{ + ConnectOptions as _, Connection as _, PgConnection, PgPool, postgres::PgConnectOptions, +}; +use uuid::Uuid; + +/// A database with dipper's migrations, every table fenced, as dipper leaves it at start, and no +/// writer yet. Returns the options sessions are opened from. The server listens on its Unix +/// socket only, as in the registry's other tests, so a parallel run can't take its port. +#[expect( + clippy::expect_used, + reason = "test setup; a failure should stop the test" +)] +async fn fenced_db() -> (PgTempDB, PgConnectOptions) { + let temp_db = PgTempDBBuilder::new() + .with_config_param("listen_addresses", "") + .start(); + let base = PgConnectOptions::new() + .socket(temp_db.data_dir()) + .port(temp_db.db_port()) + .username(temp_db.db_user()) + .password(temp_db.db_pass()) + .database(temp_db.db_name()); + let mut operator = operator(&base).await; + dipper_pgregistry::run_db_migrations(&mut operator) + .await + .expect("run the migrations"); + for table in writer_fence::unfenced(&mut operator) + .await + .expect("list the tables") + { + assert!( + writer_fence::attach(&mut operator, &table, Duration::from_secs(5)) + .await + .expect("fence the table"), + "{table} is free to fence" + ); + } + (temp_db, base) +} + +#[expect( + clippy::expect_used, + reason = "test setup; a failure should stop the test" +)] +async fn operator(base: &PgConnectOptions) -> PgConnection { + writer_fence::operator_options(base.clone()) + .connect() + .await + .expect("open an operator session") +} + +/// A session of the process with `token`. +#[expect( + clippy::expect_used, + reason = "test setup; a failure should stop the test" +)] +async fn session_of(base: &PgConnectOptions, token: Uuid) -> PgConnection { + writer_fence::writer_options(base.clone(), token) + .connect() + .await + .expect("open a session") +} + +/// Makes the process with `token` the writer, as its start does, on an operator's session, so +/// it leaves no session of that process behind. +#[expect( + clippy::expect_used, + reason = "test setup; a failure should stop the test" +)] +async fn take_over(base: &PgConnectOptions, token: Uuid) { + let mut conn = operator(base).await; + assert!( + writer_fence::take(&mut conn, token, "test", Duration::ZERO) + .await + .expect("take over"), + "the takeover goes through" + ); +} + +/// A write to 1 of dipper's tables, which the fence checks. +async fn write(conn: &mut PgConnection) -> sqlx::Result<()> { + sqlx::query( + "INSERT INTO dipper_kafka_consumer_offsets (topic, partition_id, next_offset) \ + VALUES (gen_random_uuid()::text, 0, 1)", + ) + .execute(conn) + .await + .map(drop) +} + +fn refused(result: sqlx::Result<()>) -> bool { + result.is_err_and(|err| writer_fence::is_refusal(&err)) +} + +#[tokio::test] +async fn every_table_of_dipper_is_fenced_and_stays_fenced() { + //* Given + let (_temp_db, base) = fenced_db().await; + let mut operator = operator(&base).await; + + //* Then - nothing is left unfenced, including the queue's table if it is there + assert_eq!( + writer_fence::unfenced(&mut operator).await.unwrap(), + Vec::::new() + ); + + //* When - someone disables 1 table's fence + sqlx::query("ALTER TABLE dipper_kafka_consumer_offsets DISABLE TRIGGER dipper_fence") + .execute(&mut operator) + .await + .unwrap(); + + //* Then - the next start finds it and fences it again + assert_eq!( + writer_fence::unfenced(&mut operator).await.unwrap(), + vec!["dipper_kafka_consumer_offsets".to_owned()] + ); + assert!( + writer_fence::attach( + &mut operator, + "dipper_kafka_consumer_offsets", + Duration::from_secs(5) + ) + .await + .unwrap() + ); + assert!( + writer_fence::unfenced(&mut operator) + .await + .unwrap() + .is_empty() + ); +} + +#[tokio::test] +async fn only_the_writer_and_operators_may_write() { + //* Given + let (_temp_db, base) = fenced_db().await; + let (writer, replaced) = (Uuid::now_v7(), Uuid::now_v7()); + take_over(&base, replaced).await; + take_over(&base, writer).await; + + //* Then + assert!(write(&mut session_of(&base, writer).await).await.is_ok()); + assert!(write(&mut operator(&base).await).await.is_ok()); + let mut stale = session_of(&base, replaced).await; + assert!(refused(write(&mut stale).await), "a replaced writer"); + let mut unnamed = base.clone().connect().await.unwrap(); + assert!( + refused(write(&mut unnamed).await), + "a session with no token" + ); + let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM dipper_kafka_consumer_offsets") + .fetch_one(&mut stale) + .await + .expect("a replaced writer may still read"); + assert_eq!(rows, 2); +} + +#[tokio::test] +async fn the_fence_switched_off_lets_every_session_write_until_it_is_on_again() { + //* Given + let (_temp_db, base) = fenced_db().await; + let mut operator = operator(&base).await; + let mut unnamed = base.clone().connect().await.unwrap(); + + //* When + sqlx::query("SELECT dipper_fence_set(false)") + .execute(&mut operator) + .await + .unwrap(); + + //* Then + assert!(!writer_fence::enforced(&mut operator).await.unwrap()); + assert!(write(&mut unnamed).await.is_ok()); + + //* When + sqlx::query("SELECT dipper_fence_set(true)") + .execute(&mut operator) + .await + .unwrap(); + + //* Then + assert!(refused(write(&mut unnamed).await)); +} + +#[tokio::test] +async fn a_process_takes_over_only_from_a_writer_that_released_or_went_silent() { + //* Given - the 1st process takes over a new database at once + let (_temp_db, base) = fenced_db().await; + let (a, b) = (Uuid::now_v7(), Uuid::now_v7()); + let mut conn = operator(&base).await; + let stale_after = Duration::from_secs(20); + assert!( + writer_fence::take(&mut conn, a, "a", stale_after) + .await + .unwrap() + ); + + //* Then - a 2nd waits while the 1st is healthy + assert!(writer_fence::beat(&mut conn, a).await.unwrap()); + assert!( + !writer_fence::take(&mut conn, b, "b", stale_after) + .await + .unwrap() + ); + + //* When - the 1st hands over + assert!(writer_fence::release(&mut conn, a).await.unwrap()); + + //* Then - the 2nd takes over, and asking again answers the same + assert!( + writer_fence::take(&mut conn, b, "b", stale_after) + .await + .unwrap() + ); + assert!( + writer_fence::take(&mut conn, b, "b", stale_after) + .await + .unwrap() + ); + assert!( + !writer_fence::beat(&mut conn, a).await.unwrap(), + "the 1st is told" + ); + assert!( + !writer_fence::release(&mut conn, a).await.unwrap(), + "the 1st's late release changes nothing" + ); + + //* When - the 2nd goes silent, for longer than a 3rd allows + let c = Uuid::now_v7(); + assert!( + writer_fence::take(&mut conn, c, "c", Duration::ZERO) + .await + .unwrap() + ); +} + +#[tokio::test] +async fn a_takeover_refuses_the_old_writer_at_once_and_drain_waits_for_its_open_write() { + //* Given - the old writer has a write in an open transaction + let (_temp_db, base) = fenced_db().await; + let (old, new) = (Uuid::now_v7(), Uuid::now_v7()); + take_over(&base, old).await; + let mut old_session = session_of(&base, old).await; + sqlx::query("BEGIN") + .execute(&mut old_session) + .await + .unwrap(); + write(&mut old_session).await.expect("still the writer"); + + //* When + let mut new_session = session_of(&base, new).await; + assert!( + writer_fence::take(&mut new_session, new, "new", Duration::ZERO) + .await + .unwrap(), + "the takeover doesn't wait for the old writer" + ); + + //* Then - the drain waits for the old writer's open transaction, which holds what passed + // the check + assert!( + !writer_fence::drain(&mut new_session, Duration::from_millis(300)) + .await + .unwrap() + ); + assert_eq!( + writer_fence::drain_blockers(&mut new_session) + .await + .unwrap(), + vec![writer_fence::session_name(old)] + ); + + //* When - the old writer makes its next statement + let next = write(&mut old_session).await; + + //* Then - it is refused, which aborts the old writer's transaction there and then: its + // earlier write is rolled back, and the drain no longer waits + assert!(refused(next)); + assert!( + writer_fence::drain(&mut new_session, Duration::from_secs(5)) + .await + .unwrap() + ); + let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM dipper_kafka_consumer_offsets") + .fetch_one(&mut new_session) + .await + .unwrap(); + assert_eq!(rows, 0, "nothing of the old writer's transaction landed"); +} + +#[tokio::test] +async fn a_cut_ends_only_sessions_of_processes_that_are_not_the_writer() { + //* Given + let (_temp_db, base) = fenced_db().await; + let (old, new) = (Uuid::now_v7(), Uuid::now_v7()); + take_over(&base, old).await; + let mut old_session = session_of(&base, old).await; + let mut old_lock_session = + writer_fence::named(writer_fence::writer_options(base.clone(), old), "lock") + .connect() + .await + .unwrap(); + let mut operator_session = operator(&base).await; + let mut new_session = session_of(&base, new).await; + let mut another_new_session = session_of(&base, new).await; + + //* When + take_over(&base, new).await; + let ended = writer_fence::cut(&mut new_session, new).await.unwrap(); + + //* Then - both of the old writer's sessions are ended, and nobody else's + assert_eq!(ended, 2); + assert!(old_session.ping().await.is_err()); + assert!(old_lock_session.ping().await.is_err()); + assert!(operator_session.ping().await.is_ok()); + assert!(another_new_session.ping().await.is_ok()); + + //* Then - the replaced process may not cut either + let mut old_again = session_of(&base, old).await; + assert_eq!(writer_fence::cut(&mut old_again, old).await.unwrap(), 0); + assert!(new_session.ping().await.is_ok()); +} + +#[tokio::test] +async fn a_broadcast_guard_holds_off_a_takeover_and_then_learns_of_it() { + //* Given - the old writer is broadcasting + let (_temp_db, base) = fenced_db().await; + let (old, new) = (Uuid::now_v7(), Uuid::now_v7()); + take_over(&base, old).await; + let pool = PgPool::connect_with(writer_fence::writer_options(base.clone(), old)) + .await + .unwrap(); + let mut guard = writer_fence::BroadcastGuard::begin(&pool, old) + .await + .unwrap(); + assert!(guard.still_writer().await.unwrap()); + + //* When + let mut new_session = session_of(&base, new).await; + assert!( + writer_fence::take(&mut new_session, new, "new", Duration::ZERO) + .await + .unwrap() + ); + + //* Then - the takeover waits for the broadcast, whose next attempt is told to stop + assert!( + !writer_fence::drain(&mut new_session, Duration::from_millis(300)) + .await + .unwrap() + ); + assert!(!guard.still_writer().await.unwrap()); + + //* When - the broadcast ends, and its connection goes back to the pool + guard.end().await.unwrap(); + + //* Then + assert!( + writer_fence::drain(&mut new_session, Duration::from_secs(5)) + .await + .unwrap() + ); +} + +#[tokio::test] +async fn sessions_carry_their_token_and_name_for_the_whole_session() { + //* Given + let (_temp_db, base) = fenced_db().await; + let token = Uuid::now_v7(); + let mut conn = writer_fence::named(writer_fence::writer_options(base, token), "heartbeat") + .connect() + .await + .unwrap(); + + //* When - something resets the session's settings + sqlx::query("DISCARD ALL").execute(&mut conn).await.unwrap(); + sqlx::query("RESET ALL").execute(&mut conn).await.unwrap(); + + //* Then - what was set at connect stays + let (setting, name): (String, String) = sqlx::query_as( + "SELECT current_setting('dipper.writer'), current_setting('application_name')", + ) + .fetch_one(&mut conn) + .await + .unwrap(); + assert_eq!(setting, token.to_string()); + assert_eq!(name, format!("dipper/{token}/heartbeat")); +} + +/// Waits until the session `pid` is waiting for a lock. +#[expect( + clippy::expect_used, + reason = "test setup; a failure should stop the test" +)] +async fn wait_until_waiting_on_a_lock(base: &PgConnectOptions, pid: i32) { + let mut watcher = operator(base).await; + for _ in 0..100 { + let waiting: Option = + sqlx::query_scalar("SELECT wait_event_type FROM pg_stat_activity WHERE pid = $1") + .bind(pid) + .fetch_one(&mut watcher) + .await + .expect("read pg_stat_activity"); + if waiting.as_deref() == Some("Lock") { + return; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + panic!("session {pid} never waited for a lock"); +} + +fn sqlstate(err: &sqlx::Error) -> Option { + err.as_database_error() + .and_then(|db| db.code()) + .map(|code| code.into_owned()) +} + +/// The fence takes its lock before it reads the token. A write already waiting for a takeover's +/// drain when the takeover commits so reads the new token, and is refused; read the other way +/// round, it would have read the old token and landed after the takeover. +#[tokio::test] +async fn a_write_queued_behind_a_takeover_is_refused_once_the_takeover_commits() { + //* Given - the old writer, and a drain holding the fence's lock + let (_temp_db, base) = fenced_db().await; + let (old, new) = (Uuid::now_v7(), Uuid::now_v7()); + take_over(&base, old).await; + let mut draining = operator(&base).await; + sqlx::query("BEGIN").execute(&mut draining).await.unwrap(); + sqlx::query("SELECT dipper_writer_drain()") + .execute(&mut draining) + .await + .unwrap(); + + //* When - a write of the old writer queues behind it, and the takeover commits meanwhile + let mut old_session = session_of(&base, old).await; + let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut old_session) + .await + .unwrap(); + let queued = tokio::spawn(async move { write(&mut old_session).await }); + wait_until_waiting_on_a_lock(&base, pid).await; + take_over(&base, new).await; + sqlx::query("COMMIT").execute(&mut draining).await.unwrap(); + + //* Then + assert!( + refused(queued.await.unwrap()), + "the queued write is refused" + ); + let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM dipper_kafka_consumer_offsets") + .fetch_one(&mut draining) + .await + .unwrap(); + assert_eq!(rows, 0); +} + +/// Outside READ COMMITTED a statement would read the token as its transaction first saw it and +/// miss a takeover, so the writer's writes and broadcast checks are refused there, with `DP002`. +#[tokio::test] +async fn the_writer_is_refused_outside_read_committed() { + //* Given + let (_temp_db, base) = fenced_db().await; + let token = Uuid::now_v7(); + take_over(&base, token).await; + let mut conn = session_of(&base, token).await; + + //* When + sqlx::query("BEGIN ISOLATION LEVEL REPEATABLE READ") + .execute(&mut conn) + .await + .unwrap(); + let write = write(&mut conn) + .await + .expect_err("a write under REPEATABLE READ"); + sqlx::query("ROLLBACK").execute(&mut conn).await.unwrap(); + sqlx::query("BEGIN ISOLATION LEVEL REPEATABLE READ") + .execute(&mut conn) + .await + .unwrap(); + let check = sqlx::query_scalar::<_, bool>("SELECT dipper_writer_guard($1)") + .bind(token) + .fetch_one(&mut conn) + .await + .expect_err("a broadcast check under REPEATABLE READ"); + + //* Then + assert_eq!(sqlstate(&write).as_deref(), Some("DP002")); + assert_eq!(sqlstate(&check).as_deref(), Some("DP002")); +} + +/// The broadcast guard runs under READ COMMITTED even where the database's default is another +/// level, so its checks still see a takeover. +#[tokio::test] +async fn a_broadcast_guard_sees_a_takeover_whatever_the_default_isolation() { + //* Given - sessions that default to REPEATABLE READ + let (_temp_db, base) = fenced_db().await; + let (old, new) = (Uuid::now_v7(), Uuid::now_v7()); + take_over(&base, old).await; + let options = writer_fence::writer_options(base.clone(), old) + .options([("default_transaction_isolation", "repeatable read")]); + let pool = PgPool::connect_with(options).await.unwrap(); + let mut guard = writer_fence::BroadcastGuard::begin(&pool, old) + .await + .unwrap(); + assert!(guard.still_writer().await.unwrap()); + + //* When + take_over(&base, new).await; + + //* Then + assert!(!guard.still_writer().await.unwrap()); + guard.end().await.unwrap(); +} diff --git a/k8s/README.md b/k8s/README.md index 521e9d9b..ad338bee 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -23,9 +23,30 @@ Kubernetes manifests for deploying the dipper service. Dipper requires IISA at startup: it runs an IISA health check, retrying with growing pauses for up to `iisa.startup_wait` (180s by default, enough for IISA's own rollout), and exits if IISA is still not reachable. It waits for the database the same way, for up to `db.connect_wait` (120s by default), but exits at once if the database refuses it, as with a wrong password. Deploy and verify IISA before starting dipper. -Run exactly 1 replica. The signer's nonce and the locks that keep 2 jobs from acting on the same agreement live in the process, so 2 pods side by side could send transactions on the same nonce or act on an agreement twice. `deployment.yaml` sets `strategy: Recreate` for that reason: a rollout stops the old pod before the new one starts, at the cost of a gap while the new pod starts up. Keep it if you deploy with other manifests. +Run 1 replica. Dipper's flows assume a single process acts: the signer's nonce and the locks that keep 2 jobs from acting on the same agreement live in the process. The database enforces that with the [writer fence](#the-writer-fence), so a pod started while another is still running waits for it, and nothing acts twice. When a pod is evicted, deleted or its node drained, Kubernetes starts the replacement while the old pod is still shutting down; the replacement takes over once the old pod hands over at the end of its stop, or once it has been silent for 20 seconds. No maintenance window is needed for that. -`Recreate` only covers rollouts. When a pod is evicted, deleted or its node drained, Kubernetes starts the replacement while the old pod is still shutting down, and the old pod's worker, though it takes no new job once its stop begins, finishes the ones it is running for up to 45 seconds. Until dipper holds a lock of its own for as long as it runs, keep such disruptions to planned windows: set a maintenance window on the cluster, and drain a node only after scaling dipper to 0. +`deployment.yaml` sets `strategy: Recreate`, so a rollout stops the old pod before the new one starts. Keep it if you deploy with other manifests: with a rolling update the new pod would wait for a writer that Kubernetes only stops once the new pod is ready, which it isn't while it waits. + +## The writer fence + +Every database session of a dipper process carries a token of that process, as the session setting `dipper.writer` and in its name, `dipper/` in `pg_stat_activity`. The table `dipper_writer` names the process allowed to write, and a trigger on every table refuses a write from any other session, with the error code `DP001`. A process another one has taken over from is refused however late it finds out, stops, and has its sessions ended by the new writer. + +| Task | How | +| --- | --- | +| Manual SQL that writes, a `pg_restore`, or a script such as `scripts/dedupe-open-indexing-requests.sql` | Mark the session as an operator's first: `SET dipper.writer = 'operator';`, or connect with `PGOPTIONS='-c dipper.writer=operator'` | +| See who the writer is, and whether the fence is on | `SELECT holder, taken_at, enforced FROM dipper_writer;` (`holder` is the pod's name) | +| See whether the writer is healthy | `SELECT seen_at, released FROM dipper_writer_heartbeat;` | +| See every dipper session and whose it is | `SELECT pid, application_name, state FROM pg_stat_activity WHERE application_name LIKE 'dipper/%';` | +| Hand over now, from a writer that won't stop | `UPDATE dipper_writer_heartbeat SET released = true;` The next pod takes over within 2 seconds; the old one is refused from then on, and stops | +| Turn the fence off in an emergency, or before going back to a release without it | `SELECT dipper_fence_set(false);` It stays off, across restarts, until `SELECT dipper_fence_set(true);` | + +It needs: + +- Postgres 14 or later, and dipper's sessions on 1 database role: a takeover ends only the sessions of its own role. +- Sessions that keep their settings, so a direct connection or the Cloud SQL Auth Proxy, not a pooler in transaction mode. +- No prepared transactions (Postgres disables them by default). One left behind holds a takeover back until an operator rolls it back; the start logs `writer_drain_blocked` naming it. + +What it logs, by `event`: `writer_taken` at each start, `writer_waiting` while a start waits for the writer (as a warning past 2 minutes, which means another dipper is running that shouldn't be), `writer_superseded` when a process finds it has been replaced, `writer_drain_blocked` when a takeover can't finish, and `writer_fence_off` at each start while the fence is off. All but `writer_taken` are alerted on by default. ## Configuration diff --git a/k8s/deployment.yaml b/k8s/deployment.yaml index ce08fb68..fe92bc85 100644 --- a/k8s/deployment.yaml +++ b/k8s/deployment.yaml @@ -5,13 +5,13 @@ metadata: labels: app: dipper spec: - # A rollout stops the old pod before starting the new one. With the default RollingUpdate - # both would run for a while: each keeps its own nonce for the one signer and its own - # in-process locks (the global reassess lock among them) while both pull jobs from the same - # queue, so they could send transactions on the same nonce and offer or cancel the same - # agreement twice. The price is a gap while the new pod starts. This covers rollouts only: - # when a pod is evicted, deleted or its node drained, Kubernetes starts the replacement while - # the old pod is still terminating, which only a lock in dipper itself can rule out. + # A rollout stops the old pod before starting the new one. Only 1 dipper process may act, and + # the database's writer fence makes a new pod wait until the old one hands over (see the + # README). With the default RollingUpdate the new pod would wait for an old pod that + # Kubernetes only stops once the new one is ready, which it isn't while it waits. The price is + # a gap while the new pod starts. When a pod is evicted, deleted or its node drained, + # Kubernetes starts the replacement while the old pod is still terminating; the fence makes + # the replacement wait for it. # `rollingUpdate: null` drops the defaulted settings a client-side apply would otherwise keep, # which the API refuses next to `Recreate`. strategy: @@ -28,8 +28,9 @@ spec: spec: # Above the service's own teardown budget: once shutdown starts it has 75s in # total to stop taking jobs, finish the running ones (45s at most), stop its - # other services, flush events and close the DB pool, after which it exits by - # itself. A SIGKILL part-way through the teardown stays out of reach. + # other services, flush events, close the DB pool and hand over to the next + # dipper, after which it exits by itself. A SIGKILL part-way through the teardown + # stays out of reach. terminationGracePeriodSeconds: 90 securityContext: runAsNonRoot: true