From 3b53423538c8d630bedd32ddc9f7a516c9ea57a2 Mon Sep 17 00:00:00 2001 From: Jeff Repanich Date: Sat, 28 Nov 2026 22:50:36 -0500 Subject: [PATCH] feat(storage): support Midge writer handoff --- Cargo.lock | 20 +-- Cargo.toml | 2 +- crates/fitz-server/src/api/broker.rs | 16 +- crates/fitz-server/src/api/broker_shutdown.rs | 99 ++++++++++- .../src/api/broker_shutdown/tests.rs | 119 +++++++++++++ crates/fitz-server/src/api/storage_runtime.rs | 90 ++++++++-- .../storage_runtime/tests/lease_lifecycle.rs | 47 ++++++ crates/fitz-server/src/boot/runtime/config.rs | 52 ++++++ .../src/boot/runtime/config/tests.rs | 1 + .../config/tests/base_auth_and_network.rs | 2 + .../runtime/config/tests/writer_handoff.rs | 159 ++++++++++++++++++ .../src/boot/runtime/config/writer_handoff.rs | 100 +++++++++++ .../src/testkit/transport/server.rs | 1 + docs/development/architecture.md | 9 + docs/user-guides/vars.md | 11 ++ 15 files changed, 691 insertions(+), 37 deletions(-) create mode 100644 crates/fitz-server/src/api/broker_shutdown/tests.rs create mode 100644 crates/fitz-server/src/boot/runtime/config/tests/writer_handoff.rs create mode 100644 crates/fitz-server/src/boot/runtime/config/writer_handoff.rs diff --git a/Cargo.lock b/Cargo.lock index 3baf069c5..5adeee45f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -408,9 +408,9 @@ dependencies = [ [[package]] name = "cntryl-midge" -version = "0.6.2" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8846edc97f276720bef79180955ef2f477b7240ac8a25640b8c5dd13e043faf" +checksum = "f9061dc50ff5fea668ab61e4897e12903278f039c58052391bea7104241f0888" dependencies = [ "arc-swap", "bytes", @@ -437,9 +437,9 @@ dependencies = [ [[package]] name = "cntryl-midge-core" -version = "0.6.2" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "154bccfcd407aad4e55cda195eed767d82eeedf113b9424c4e3b8f2330d60616" +checksum = "27d1674b120c1ff2a57bc6a48232d458988b88ac6f636444e442994d88b3a137" dependencies = [ "bytes", "crc32c", @@ -455,9 +455,9 @@ dependencies = [ [[package]] name = "cntryl-midge-durability" -version = "0.6.2" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9295fd5ef4b231fa3d4f358c956468ef7858e0dcce2f9386df757c33e2a7d8df" +checksum = "f5ec08eb3f6a3363638cfed2c79b77543df2f061358ebce8f7f0b16e0d835c83" dependencies = [ "arc-swap", "bytes", @@ -482,9 +482,9 @@ dependencies = [ [[package]] name = "cntryl-midge-storage" -version = "0.6.2" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9595e9f386010409b90b9db7c1d127d6376b55dca3e3e53a01d9768974bbad81" +checksum = "79c069d2f493394570f578a21c11216c765b2a7b85b0a4b2c73f2f538b8022db" dependencies = [ "base64 0.23.1", "bytes", @@ -514,9 +514,9 @@ dependencies = [ [[package]] name = "cntryl-midge-table" -version = "0.6.2" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d3acead56a681067405cad754a586f25ef725e4cda7f2613070de351ce97755" +checksum = "9002a43abdbae2f107b691e760e9a6dd32470af1630467e2f7e689316cab2749" dependencies = [ "arc-swap", "bytes", diff --git a/Cargo.toml b/Cargo.toml index 5577031f1..a8e7b47a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,7 +36,7 @@ base64 = "0.23.1" brotli = "9" bytes = "1.12" chrono = { version = "0.4", features = ["serde"] } -cntryl-midge = "0.6.2" +cntryl-midge = "0.7.0" crossbeam-channel = "0.5" dashmap = "6.2.1" flate2 = "1" diff --git a/crates/fitz-server/src/api/broker.rs b/crates/fitz-server/src/api/broker.rs index 8aef4ab97..215bd5569 100644 --- a/crates/fitz-server/src/api/broker.rs +++ b/crates/fitz-server/src/api/broker.rs @@ -349,7 +349,11 @@ async fn boot_initialized( } runtime.mark_storage_ready(); - shutdown.monitor_storage(runtime.clone(), Arc::downgrade(&shutdown_context.store)); + shutdown.monitor_storage( + runtime.clone(), + Arc::downgrade(&shutdown_context.store), + config.storage_writer_state_changes(), + ); let domains = match register_domains_stage(&router, &shutdown_context.store, &runtime, &config) { @@ -634,9 +638,10 @@ async fn shutdown_broker( let failure = match signal { ShutdownSignal::ActorFailure => "fatal domain actor failure", ShutdownSignal::StorageLeaseFailure => "primary Midge writer lease became unhealthy", - ShutdownSignal::CtrlC | ShutdownSignal::Sigterm | ShutdownSignal::DrainRequested => { - unreachable!() - } + ShutdownSignal::StorageWriterHandoff + | ShutdownSignal::CtrlC + | ShutdownSignal::Sigterm + | ShutdownSignal::DrainRequested => unreachable!(), }; return match shutdown_result { Ok(()) => Err(failure.into()), @@ -764,6 +769,9 @@ fn immediate_close_reason(signal: ShutdownSignal) -> String { ShutdownSignal::StorageLeaseFailure => { "broker stopped after losing the Midge writer lease".to_string() } + ShutdownSignal::StorageWriterHandoff => { + "broker stopped after Midge handed off the storage writer".to_string() + } ShutdownSignal::Sigterm | ShutdownSignal::DrainRequested => unreachable!(), } } diff --git a/crates/fitz-server/src/api/broker_shutdown.rs b/crates/fitz-server/src/api/broker_shutdown.rs index c2b58ce44..b25135fed 100644 --- a/crates/fitz-server/src/api/broker_shutdown.rs +++ b/crates/fitz-server/src/api/broker_shutdown.rs @@ -1,5 +1,5 @@ use crate::boot::{BootResult, Runtime}; -use std::sync::Weak; +use std::sync::{mpsc, Arc, Mutex, Weak}; use std::time::Duration; use tokio::sync::watch; use tokio::task::JoinHandle; @@ -11,6 +11,7 @@ pub(crate) enum ShutdownSignal { DrainRequested, ActorFailure, StorageLeaseFailure, + StorageWriterHandoff, } impl ShutdownSignal { @@ -24,6 +25,7 @@ impl ShutdownSignal { Self::DrainRequested => "drain_requested", Self::ActorFailure => "actor_failure", Self::StorageLeaseFailure => "storage_lease_failure", + Self::StorageWriterHandoff => "storage_writer_handoff", } } @@ -40,7 +42,7 @@ impl ShutdownSignal { fn priority(self) -> u8 { match self { Self::Sigterm | Self::DrainRequested => Self::PRIORITY_GRACEFUL, - Self::CtrlC => Self::PRIORITY_INTERRUPT, + Self::CtrlC | Self::StorageWriterHandoff => Self::PRIORITY_INTERRUPT, Self::ActorFailure | Self::StorageLeaseFailure => Self::PRIORITY_FATAL, } } @@ -151,12 +153,20 @@ impl ShutdownCoordinator { })); } - pub(super) fn monitor_storage(&mut self, runtime: Runtime, store: Weak) { + pub(super) fn monitor_storage( + &mut self, + runtime: Runtime, + store: Weak, + state_changes: Option>>>, + ) { let trigger = self.trigger.clone(); let mut requested_shutdown = self.receiver.clone(); self.tasks.push(tokio::spawn(async move { - let mut interval = tokio::time::interval(Duration::from_secs(1)); - interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + let mut state_interval = tokio::time::interval(Duration::from_millis(25)); + state_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + let mut lease_interval = tokio::time::interval(Duration::from_secs(1)); + lease_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + let mut last_writer_state = cntryl_midge::WriterState::Serving; loop { if requested_shutdown .borrow() @@ -175,7 +185,42 @@ impl ShutdownCoordinator { return; } } - _ = interval.tick() => { + _ = state_interval.tick() => { + if runtime.is_shutting_down() { + return; + } + let Some(store) = store.upgrade() else { + return; + }; + if let Some(state_changes) = &state_changes { + let receiver = state_changes + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + while let Ok(change) = receiver.try_recv() { + if handle_writer_state_change( + &runtime, + &trigger, + change.state, + &mut last_writer_state, + ) { + return; + } + } + } + let current_state = store.writer_state(); + drop(store); + if current_state != last_writer_state + && handle_writer_state_change( + &runtime, + &trigger, + current_state, + &mut last_writer_state, + ) + { + return; + } + } + _ = lease_interval.tick() => { if runtime.is_shutting_down() { return; } @@ -184,7 +229,7 @@ impl ShutdownCoordinator { }; let lease_is_healthy = store.is_primary_lease_healthy(); drop(store); - if !lease_is_healthy { + if !lease_is_healthy && last_writer_state != cntryl_midge::WriterState::Draining { handle_storage_lease_failure(&runtime, &trigger); return; } @@ -222,6 +267,42 @@ pub(super) fn handle_storage_lease_failure(runtime: &Runtime, trigger: &Shutdown runtime.begin_drain(); } +fn handle_writer_state_change( + runtime: &Runtime, + trigger: &ShutdownTrigger, + state: cntryl_midge::WriterState, + previous: &mut cntryl_midge::WriterState, +) -> bool { + match state { + cntryl_midge::WriterState::Serving => { + if *previous == cntryl_midge::WriterState::Draining { + tracing::info!("Midge writer handoff was deferred; restoring storage readiness"); + runtime.mark_storage_ready(); + } + *previous = state; + false + } + cntryl_midge::WriterState::Draining => { + tracing::info!("Midge writer handoff started; withdrawing storage readiness"); + runtime.mark_storage_unavailable(); + *previous = state; + false + } + cntryl_midge::WriterState::Retired => { + runtime.mark_storage_unavailable(); + if *previous == cntryl_midge::WriterState::Draining { + tracing::info!("Midge writer handoff retired this writer; shutting down Fitz"); + trigger.request(ShutdownSignal::StorageWriterHandoff); + runtime.begin_drain(); + } else { + handle_storage_lease_failure(runtime, trigger); + } + *previous = state; + true + } + } +} + impl Drop for ShutdownCoordinator { fn drop(&mut self) { for task in &self.tasks { @@ -260,6 +341,10 @@ fn start_os_signal_task(trigger: ShutdownTrigger) -> BootResult> })) } +#[cfg(test)] +#[path = "broker_shutdown/tests.rs"] +mod tests; + #[cfg(not(unix))] fn start_os_signal_task(trigger: ShutdownTrigger) -> BootResult> { Ok(tokio::spawn(async move { diff --git a/crates/fitz-server/src/api/broker_shutdown/tests.rs b/crates/fitz-server/src/api/broker_shutdown/tests.rs new file mode 100644 index 000000000..6f6645592 --- /dev/null +++ b/crates/fitz-server/src/api/broker_shutdown/tests.rs @@ -0,0 +1,119 @@ +use super::*; +use crate::runtime::Router; + +#[test] +fn should_withdraw_readiness_when_writer_enters_draining() { + // Arrange + let runtime = Runtime::new(Arc::new(Router::new())); + runtime.mark_storage_ready(); + runtime.mark_domains_ready(); + runtime.mark_auth_config_ready(); + runtime.mark_startup_complete(); + let (shutdown, trigger) = ShutdownCoordinator::manual(); + let mut state = cntryl_midge::WriterState::Serving; + assert!(runtime.is_ready_for_traffic()); + + // Act + let retired = handle_writer_state_change( + &runtime, + &trigger, + cntryl_midge::WriterState::Draining, + &mut state, + ); + + // Assert + assert!(!retired); + assert!(!runtime.is_storage_ready()); + assert!(!runtime.is_draining()); + assert!(!runtime.is_ready_for_traffic()); + assert_eq!(shutdown.requested(), None); +} + +#[test] +fn should_restore_readiness_when_deferred_writer_handoff_resumes() { + // Arrange + let runtime = Runtime::new(Arc::new(Router::new())); + runtime.mark_domains_ready(); + runtime.mark_auth_config_ready(); + runtime.mark_startup_complete(); + let (shutdown, trigger) = ShutdownCoordinator::manual(); + let mut state = cntryl_midge::WriterState::Draining; + + // Act + let retired = handle_writer_state_change( + &runtime, + &trigger, + cntryl_midge::WriterState::Serving, + &mut state, + ); + + // Assert + assert!(!retired); + assert!(runtime.is_storage_ready()); + assert!(runtime.is_ready_for_traffic()); + assert_eq!(shutdown.requested(), None); +} + +#[test] +fn should_immediately_stop_after_a_retired_writer_handoff() { + // Arrange + let runtime = Runtime::new(Arc::new(Router::new())); + runtime.mark_storage_ready(); + let (shutdown, trigger) = ShutdownCoordinator::manual(); + let mut state = cntryl_midge::WriterState::Serving; + assert!(!handle_writer_state_change( + &runtime, + &trigger, + cntryl_midge::WriterState::Draining, + &mut state, + )); + + // Act + let retired = handle_writer_state_change( + &runtime, + &trigger, + cntryl_midge::WriterState::Retired, + &mut state, + ); + + // Assert + assert!(retired); + assert!(!runtime.is_storage_ready()); + assert!(runtime.is_draining()); + assert_eq!( + shutdown.requested(), + Some(ShutdownSignal::StorageWriterHandoff) + ); + assert!(!shutdown + .requested() + .expect("handoff shutdown signal") + .is_failure()); +} + +#[test] +fn should_keep_retirement_without_a_drain_transition_as_a_lease_failure() { + // Arrange + let runtime = Runtime::new(Arc::new(Router::new())); + runtime.mark_storage_ready(); + let (shutdown, trigger) = ShutdownCoordinator::manual(); + let mut state = cntryl_midge::WriterState::Serving; + + // Act + let retired = handle_writer_state_change( + &runtime, + &trigger, + cntryl_midge::WriterState::Retired, + &mut state, + ); + + // Assert + assert!(retired); + assert_eq!( + shutdown.requested(), + Some(ShutdownSignal::StorageLeaseFailure) + ); + assert!(shutdown + .requested() + .expect("lease failure signal") + .is_failure()); +} diff --git a/crates/fitz-server/src/api/storage_runtime.rs b/crates/fitz-server/src/api/storage_runtime.rs index 8b677413f..2bb2c42a3 100644 --- a/crates/fitz-server/src/api/storage_runtime.rs +++ b/crates/fitz-server/src/api/storage_runtime.rs @@ -10,6 +10,7 @@ use tracing::{debug, info, warn}; mod backoff; mod contention; const STORAGE_STARTUP_ADMISSION_TIMEOUT: Duration = Duration::from_secs(60); +const STORAGE_WRITER_HANDOFF_TIMEOUT: Duration = Duration::from_secs(90); const STORAGE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30); const STORAGE_SHUTDOWN_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(5); const STORAGE_SHUTDOWN_RETRY_DELAY: Duration = Duration::from_millis(50); @@ -149,7 +150,12 @@ async fn init_memory( info!("Initializing in-memory storage (ephemeral, no persistence)"); let open_options = build_midge_open_options(cntryl_midge::OpenOptions::in_memory(), config)?; - let attempt = open_and_provision(open_options, config.route_families.clone()).await?; + let attempt = open_and_provision( + open_options, + config.route_families.clone(), + matches!(&config.storage_writer_handoff, Ok(Some(_))), + ) + .await?; if shutdown_requested(shutdown) { shutdown_cancelled_open_attempt(attempt).await?; return Ok(StorageInitOutcome::ShutdownRequested); @@ -192,6 +198,7 @@ async fn open_local_disk_with_retry( open_with_retry( open_options, config.route_families.clone(), + matches!(&config.storage_writer_handoff, Ok(Some(_))), shutdown, contention::is_retryable, |attempt, elapsed, delay, error| { @@ -205,6 +212,7 @@ async fn open_local_disk_with_retry( async fn open_with_retry( open_options: cntryl_midge::OpenOptions, route_families: Vec, + writer_handoff_enabled: bool, shutdown: &mut watch::Receiver>, should_retry: P, log_contention: L, @@ -222,14 +230,25 @@ where if shutdown_requested(shutdown) { return Ok(None); } - let attempt = open_and_provision(open_options.clone(), route_families.clone()).await?; + let attempt = open_and_provision( + open_options.clone(), + route_families.clone(), + writer_handoff_enabled, + ) + .await?; if shutdown_requested(shutdown) { shutdown_cancelled_open_attempt(attempt).await?; return Ok(None); } match attempt { OpenAttempt::Ready(store) => return Ok(Some(store)), - OpenAttempt::OpenFailed(error) if should_retry(&error) => { + OpenAttempt::OpenFailed(error) + if if writer_handoff_enabled { + matches!(error, cntryl_midge::MidgeError::Busy(_)) + } else { + should_retry(&error) + } => + { let delay = backoff::retry_delay(retry_attempt); retry_attempt = retry_attempt.saturating_add(1); log_contention(retry_attempt, retry_started_at.elapsed(), delay, &error); @@ -248,23 +267,52 @@ where async fn open_and_provision( open_options: cntryl_midge::OpenOptions, route_families: Vec, + writer_handoff_enabled: bool, ) -> BootResult { - tokio::task::spawn_blocking(move || match cntryl_midge::Engine::open(open_options) { - Ok(engine) => match ensure_column_families(&engine, &route_families).and_then(|()| { - ensure_startup_write_admission(&engine, STORAGE_STARTUP_ADMISSION_TIMEOUT) - }) { - Ok(()) => OpenAttempt::Ready(engine), - Err(error) => OpenAttempt::ProvisionFailed { - engine, - error: error.to_string(), + tokio::task::spawn_blocking(move || { + match open_midge_engine(open_options, writer_handoff_enabled) { + Ok(engine) => match ensure_column_families(&engine, &route_families).and_then(|()| { + ensure_startup_write_admission(&engine, STORAGE_STARTUP_ADMISSION_TIMEOUT) + }) { + Ok(()) => OpenAttempt::Ready(engine), + Err(error) => OpenAttempt::ProvisionFailed { + engine, + error: error.to_string(), + }, }, - }, - Err(error) => OpenAttempt::OpenFailed(error), + Err(error) => OpenAttempt::OpenFailed(error), + } }) .await .map_err(|error| format!("Midge open task failed: {error}").into()) } +fn open_midge_engine( + open_options: cntryl_midge::OpenOptions, + writer_handoff_enabled: bool, +) -> Result { + if !writer_handoff_enabled { + return cntryl_midge::Engine::open(open_options); + } + + match cntryl_midge::Engine::open(open_options.clone()) { + Ok(engine) => Ok(engine), + Err(cntryl_midge::MidgeError::LeaseHeld(_)) => { + match cntryl_midge::Engine::prepare_replacement( + open_options.clone(), + STORAGE_WRITER_HANDOFF_TIMEOUT, + ) { + Ok(prepared) => prepared.promote(STORAGE_WRITER_HANDOFF_TIMEOUT), + Err(cntryl_midge::MidgeError::LeaseUnavailable(_)) => { + cntryl_midge::Engine::open(open_options) + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } +} + async fn finish_open_attempt( attempt: OpenAttempt, error_context: &str, @@ -488,6 +536,10 @@ fn build_midge_open_options( let open_options = open_options .lease_ttl(config.storage_lease_ttl()) .runtime_response_timeout(STORAGE_RUNTIME_RESPONSE_TIMEOUT); + let open_options = match config.midge_writer_handoff() { + Some(handoff) => open_options.writer_handoff(handoff), + None => open_options, + }; open_options .build() @@ -531,8 +583,14 @@ async fn init_cloud( ), config, )?; - let Some(store) = - open_cloud_with_retry(open_options, config.route_families.clone(), cloud, shutdown).await? + let Some(store) = open_cloud_with_retry( + open_options, + config.route_families.clone(), + matches!(&config.storage_writer_handoff, Ok(Some(_))), + cloud, + shutdown, + ) + .await? else { return Ok(StorageInitOutcome::ShutdownRequested); }; @@ -550,12 +608,14 @@ async fn init_cloud( async fn open_cloud_with_retry( open_options: cntryl_midge::OpenOptions, route_families: Vec, + writer_handoff_enabled: bool, cloud: &CloudStorageConfig, shutdown: &mut watch::Receiver>, ) -> BootResult> { open_with_retry( open_options, route_families, + writer_handoff_enabled, shutdown, contention::is_retryable, |attempt, elapsed, delay, error| { diff --git a/crates/fitz-server/src/api/storage_runtime/tests/lease_lifecycle.rs b/crates/fitz-server/src/api/storage_runtime/tests/lease_lifecycle.rs index f7f4015bf..8a483b25e 100644 --- a/crates/fitz-server/src/api/storage_runtime/tests/lease_lifecycle.rs +++ b/crates/fitz-server/src/api/storage_runtime/tests/lease_lifecycle.rs @@ -42,6 +42,53 @@ async fn should_reopen_storage_given_clean_shutdown() { ); } +#[tokio::test] +async fn should_replace_local_writer_given_a_higher_configured_generation() { + // Arrange + let tempdir = TempDir::new().expect("tempdir"); + let db_path = tempdir.path().join("fitz-local-writer-handoff"); + let first_config = BootConfig::with_local_storage(db_path.to_string_lossy().to_string()) + .with_storage_writer_handoff( + std::num::NonZeroU64::new(1).expect("nonzero generation"), + None, + ); + let state_changes = first_config + .storage_writer_state_changes() + .expect("writer state observer"); + let first = init(&first_config).await.expect("open generation one"); + assert_eq!(first.writer_state(), cntryl_midge::WriterState::Serving); + let replacement_config = BootConfig::with_local_storage(db_path.to_string_lossy().to_string()) + .with_storage_writer_handoff( + std::num::NonZeroU64::new(2).expect("nonzero generation"), + None, + ); + + // Act + let replacement = tokio::time::timeout(Duration::from_secs(5), init(&replacement_config)) + .await + .expect("higher generation should finish the local writer handoff") + .expect("open replacement generation"); + + // Assert + assert_eq!( + replacement.writer_state(), + cntryl_midge::WriterState::Serving + ); + assert_eq!(first.writer_state(), cntryl_midge::WriterState::Retired); + let receiver = state_changes + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let states = receiver + .try_iter() + .map(|change| change.state) + .collect::>(); + assert!(states.contains(&cntryl_midge::WriterState::Draining)); + assert!(states.contains(&cntryl_midge::WriterState::Retired)); + drop(receiver); + shutdown_store(first); + shutdown_store(replacement); +} + #[tokio::test] async fn should_retry_local_disk_open_given_active_writer_lease_when_holder_releases() { // Arrange diff --git a/crates/fitz-server/src/boot/runtime/config.rs b/crates/fitz-server/src/boot/runtime/config.rs index 58c5e5eb5..4098739f5 100644 --- a/crates/fitz-server/src/boot/runtime/config.rs +++ b/crates/fitz-server/src/boot/runtime/config.rs @@ -266,6 +266,8 @@ use env::{ queue_max_attempts_from_env, required_env, schedule_preload_timeout_seconds_from_env, storage_lease_ttl_seconds_from_env, }; +pub(crate) mod writer_handoff; +use writer_handoff::StorageWriterHandoff; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum LocalListenerExposure { @@ -419,6 +421,18 @@ impl<'a> StorageConfig<'a> { ) .into()); } + if let Err(error) = &config.storage_writer_handoff { + return Err(error.clone().into()); + } + if matches!(&config.storage_writer_handoff, Ok(Some(_))) + && matches!(config.storage_mode, StorageMode::Memory) + { + return Err(format!( + "{} requires FITZ_STORAGE_MODE=local or cloud; Midge writer handoff requires shared storage", + writer_handoff::ENV_STORAGE_WRITER_GENERATION + ) + .into()); + } config .storage_memtable .validate() @@ -503,6 +517,7 @@ pub struct BootConfig { /// TTL for the embedded Midge primary storage-writer lease. pub storage_lease_ttl_seconds: u64, pub(crate) storage_lease_ttl_error: Option, + pub(crate) storage_writer_handoff: Result, String>, pub(crate) queue_write_policy_error: Option, /// Target dirty-data window before best-effort queue writes are flushed. pub queue_loss_window_ms: u64, @@ -670,6 +685,7 @@ impl Default for BootConfig { storage_memtable: StorageMemtableConfig::from_env(), storage_lease_ttl_seconds, storage_lease_ttl_error, + storage_writer_handoff: StorageWriterHandoff::from_env(), queue_write_policy_error, queue_loss_window_ms, queue_loss_window_error, @@ -866,6 +882,42 @@ impl BootConfig { self } + #[must_use] + /// Configure generation-ordered replacement for the embedded Midge writer. + pub fn with_storage_writer_handoff( + mut self, + generation: std::num::NonZeroU64, + transaction_drain_grace: Option, + ) -> Self { + self.storage_writer_handoff = Ok(Some(StorageWriterHandoff::new( + generation, + transaction_drain_grace, + ))); + self + } + + pub(crate) fn midge_writer_handoff(&self) -> Option { + self.storage_writer_handoff + .as_ref() + .ok() + .and_then(Option::as_ref) + .map(StorageWriterHandoff::midge_config) + } + + pub(crate) fn storage_writer_state_changes( + &self, + ) -> Option< + std::sync::Arc< + std::sync::Mutex>, + >, + > { + self.storage_writer_handoff + .as_ref() + .ok() + .and_then(Option::as_ref) + .map(StorageWriterHandoff::state_receiver) + } + #[must_use] /// Return the configured embedded Midge primary storage-writer lease TTL. pub fn storage_lease_ttl(&self) -> Duration { diff --git a/crates/fitz-server/src/boot/runtime/config/tests.rs b/crates/fitz-server/src/boot/runtime/config/tests.rs index 1142f2d57..85475fd2f 100644 --- a/crates/fitz-server/src/boot/runtime/config/tests.rs +++ b/crates/fitz-server/src/boot/runtime/config/tests.rs @@ -6,6 +6,7 @@ mod cloud_storage; mod queue_attempts; mod queue_retention; mod storage_local_and_stream; +mod writer_handoff; #[test] #[serial] diff --git a/crates/fitz-server/src/boot/runtime/config/tests/base_auth_and_network.rs b/crates/fitz-server/src/boot/runtime/config/tests/base_auth_and_network.rs index fa3d03988..0c50dccb9 100644 --- a/crates/fitz-server/src/boot/runtime/config/tests/base_auth_and_network.rs +++ b/crates/fitz-server/src/boot/runtime/config/tests/base_auth_and_network.rs @@ -95,6 +95,8 @@ pub(super) fn with_config_env(values: &[(&str, &str)], test: impl FnOnce() -> "FITZ_STORAGE_ACCOUNT", "FITZ_STORAGE_CLOUD_DURABILITY", "FITZ_STORAGE_LEASE_TTL_SECS", + "FITZ_STORAGE_WRITER_GENERATION", + "FITZ_STORAGE_WRITER_DRAIN_GRACE_MS", "FITZ_STORAGE_MEMTABLE_BYTES", "FITZ_STREAM_STORAGE_LAYOUT", "FITZ_STREAM_MAX_SUBSCRIPTIONS_PER_SESSION", diff --git a/crates/fitz-server/src/boot/runtime/config/tests/writer_handoff.rs b/crates/fitz-server/src/boot/runtime/config/tests/writer_handoff.rs new file mode 100644 index 000000000..244673d5d --- /dev/null +++ b/crates/fitz-server/src/boot/runtime/config/tests/writer_handoff.rs @@ -0,0 +1,159 @@ +use super::*; + +#[test] +#[serial] +fn should_leave_writer_handoff_disabled_by_default() { + with_config_env(&[], || { + // Arrange + + // Act + let config = BootConfig::default(); + + // Assert + assert!(config + .storage_writer_handoff + .as_ref() + .expect("valid config") + .is_none()); + assert!(config.midge_writer_handoff().is_none()); + }); +} + +#[test] +#[serial] +fn should_parse_writer_generation_and_drain_grace_from_environment() { + with_config_env( + &[ + ("FITZ_STORAGE_MODE", "local"), + ("FITZ_STORAGE_WRITER_GENERATION", "17"), + ("FITZ_STORAGE_WRITER_DRAIN_GRACE_MS", "700"), + ], + || { + // Arrange + + // Act + let config = BootConfig::default().with_auth_config(crate::auth::AuthConfig::Disabled); + + // Assert + let handoff = config + .storage_writer_handoff + .as_ref() + .expect("valid handoff config") + .as_ref() + .expect("configured writer handoff"); + assert_eq!(handoff.generation().get(), 17); + assert_eq!( + handoff.transaction_drain_grace(), + Some(Duration::from_millis(700)) + ); + assert!(config.midge_writer_handoff().is_some()); + assert!(config.validate().is_ok()); + }, + ); +} + +#[test] +#[serial] +fn should_preserve_midge_default_writer_drain_grace_when_unset() { + with_config_env(&[("FITZ_STORAGE_WRITER_GENERATION", "21")], || { + // Arrange + + // Act + let config = BootConfig::default(); + + // Assert + assert_eq!( + config + .storage_writer_handoff + .as_ref() + .expect("valid handoff config") + .as_ref() + .expect("configured writer handoff") + .transaction_drain_grace(), + None + ); + }); +} + +#[test] +#[serial] +fn should_reject_writer_drain_grace_without_a_generation() { + with_config_env(&[("FITZ_STORAGE_WRITER_DRAIN_GRACE_MS", "700")], || { + // Arrange + let config = BootConfig::default(); + + // Act + let result = config.validate(); + + // Assert + assert!(result.is_err()); + assert!(result.unwrap_err().to_string().contains( + "FITZ_STORAGE_WRITER_DRAIN_GRACE_MS requires FITZ_STORAGE_WRITER_GENERATION" + )); + }); +} + +#[test] +#[serial] +fn should_reject_zero_writer_generation() { + with_config_env(&[("FITZ_STORAGE_WRITER_GENERATION", "0")], || { + // Arrange + + // Act + let result = BootConfig::default().validate(); + + // Assert + assert!(result.is_err()); + assert!(result + .unwrap_err() + .to_string() + .contains("FITZ_STORAGE_WRITER_GENERATION must be a positive unsigned integer")); + }); +} + +#[test] +#[serial] +fn should_reject_malformed_writer_drain_grace() { + with_config_env( + &[ + ("FITZ_STORAGE_WRITER_GENERATION", "1"), + ("FITZ_STORAGE_WRITER_DRAIN_GRACE_MS", "later"), + ], + || { + // Arrange + + // Act + let result = BootConfig::default().validate(); + + // Assert + assert!(result.is_err()); + assert!(result.unwrap_err().to_string().contains( + "FITZ_STORAGE_WRITER_DRAIN_GRACE_MS must be an unsigned millisecond count" + )); + }, + ); +} + +#[test] +#[serial] +fn should_reject_writer_handoff_for_memory_storage() { + with_config_env( + &[ + ("FITZ_STORAGE_MODE", "memory"), + ("FITZ_STORAGE_WRITER_GENERATION", "1"), + ], + || { + // Arrange + + // Act + let result = BootConfig::default().validate(); + + // Assert + assert!(result.is_err()); + assert!(result + .unwrap_err() + .to_string() + .contains("Midge writer handoff requires shared storage")); + }, + ); +} diff --git a/crates/fitz-server/src/boot/runtime/config/writer_handoff.rs b/crates/fitz-server/src/boot/runtime/config/writer_handoff.rs new file mode 100644 index 000000000..5a1296078 --- /dev/null +++ b/crates/fitz-server/src/boot/runtime/config/writer_handoff.rs @@ -0,0 +1,100 @@ +use std::num::NonZeroU64; +use std::sync::{mpsc, Arc, Mutex}; +use std::time::Duration; + +pub(super) const ENV_STORAGE_WRITER_GENERATION: &str = "FITZ_STORAGE_WRITER_GENERATION"; +pub(super) const ENV_STORAGE_WRITER_DRAIN_GRACE_MS: &str = "FITZ_STORAGE_WRITER_DRAIN_GRACE_MS"; +const WRITER_STATE_EVENT_CAPACITY: usize = 4; + +#[derive(Debug, Clone)] +pub(crate) struct StorageWriterHandoff { + generation: NonZeroU64, + transaction_drain_grace: Option, + state_sender: mpsc::SyncSender, + state_receiver: Arc>>, +} + +impl StorageWriterHandoff { + pub(super) fn new(generation: NonZeroU64, transaction_drain_grace: Option) -> Self { + let (state_sender, state_receiver) = mpsc::sync_channel(WRITER_STATE_EVENT_CAPACITY); + Self { + generation, + transaction_drain_grace, + state_sender, + state_receiver: Arc::new(Mutex::new(state_receiver)), + } + } + + pub(super) fn from_env() -> Result, String> { + let generation = optional_env(ENV_STORAGE_WRITER_GENERATION)?; + let drain_grace_ms = optional_env(ENV_STORAGE_WRITER_DRAIN_GRACE_MS)?; + match (generation, drain_grace_ms) { + (None, None) => Ok(None), + (None, Some(_)) => Err(format!( + "{ENV_STORAGE_WRITER_DRAIN_GRACE_MS} requires {ENV_STORAGE_WRITER_GENERATION}" + )), + (Some(generation), drain_grace_ms) => { + let generation = generation + .parse::() + .ok() + .and_then(NonZeroU64::new) + .ok_or_else(|| { + format!( + "{ENV_STORAGE_WRITER_GENERATION} must be a positive unsigned integer" + ) + })?; + let transaction_drain_grace = drain_grace_ms + .map(|value| { + value.parse::().map(Duration::from_millis).map_err(|_| { + format!( + "{ENV_STORAGE_WRITER_DRAIN_GRACE_MS} must be an unsigned millisecond count" + ) + }) + }) + .transpose()?; + Ok(Some(Self::new(generation, transaction_drain_grace))) + } + } + } + + pub(super) fn midge_config(&self) -> cntryl_midge::WriterHandoffConfig { + let config = cntryl_midge::WriterHandoffConfig::new(self.generation.get()); + let config = match self.transaction_drain_grace { + Some(grace) => config.transaction_drain_grace(grace), + None => config, + }; + config.state_observer(self.state_sender.clone()) + } + + #[cfg(test)] + pub(super) fn generation(&self) -> NonZeroU64 { + self.generation + } + + #[cfg(test)] + pub(super) fn transaction_drain_grace(&self) -> Option { + self.transaction_drain_grace + } + + pub(super) fn state_receiver( + &self, + ) -> Arc>> { + Arc::clone(&self.state_receiver) + } +} + +fn optional_env(key: &str) -> Result, String> { + match std::env::var_os(key) { + None => Ok(None), + Some(value) => { + let value = value + .into_string() + .map_err(|_| format!("{key} must be valid UTF-8"))?; + let value = value.trim(); + if value.is_empty() { + return Err(format!("{key} must not be empty when set")); + } + Ok(Some(value.to_owned())) + } + } +} diff --git a/crates/fitz-server/src/testkit/transport/server.rs b/crates/fitz-server/src/testkit/transport/server.rs index 022660555..bca12a48c 100644 --- a/crates/fitz-server/src/testkit/transport/server.rs +++ b/crates/fitz-server/src/testkit/transport/server.rs @@ -505,6 +505,7 @@ impl TestServer { }, storage_lease_ttl_seconds: 30, storage_lease_ttl_error: None, + storage_writer_handoff: Ok(None), queue_write_policy_error: None, queue_loss_window_ms: 100, queue_loss_window_error: None, diff --git a/docs/development/architecture.md b/docs/development/architecture.md index 084e71d0c..6703b7a6b 100644 --- a/docs/development/architecture.md +++ b/docs/development/architecture.md @@ -837,6 +837,15 @@ attempting in-process lease reacquisition. Midge independently enforces the monotonic lease-valid-until deadline during provider renewal and fails closed on malformed cloud lease expiration. Fitz configures that deadline through `FITZ_STORAGE_LEASE_TTL_SECS`; Midge renews at one third of the TTL. + +When `FITZ_STORAGE_WRITER_GENERATION` enables Midge's writer handoff, +Fitz observes Midge's state channel and reconciles it with +`Engine::writer_state()`. `Draining` withdraws storage readiness, `Serving` +restores it if a replacement attempt is deferred, and `Retired` after a drain +transition triggers immediate broker shutdown. A `Retired` state without an +observed drain transition remains a fatal writer-lease failure. Midge owns the +transaction drain deadline; Fitz does not add its application session-drain +grace to a writer handoff. ### Configuration **Type:** `BootConfig` ```rust diff --git a/docs/user-guides/vars.md b/docs/user-guides/vars.md index 5e4a3b97c..f4ae8a068 100644 --- a/docs/user-guides/vars.md +++ b/docs/user-guides/vars.md @@ -150,6 +150,8 @@ For the auth and browser-perimeter checklist, see | FITZ_STORAGE_CACHE_PATH | Filesystem path | ./.fitz-cloud-cache | Local cache path for cloud-backed storage mode. | | FITZ_STORAGE_CLOUD_DURABILITY | background or strict | background | Cloud policy for broker-selected Schedule writes. KV and Stream require a client choice on COMMIT: Buffered always uses CloudAsync and Sync always uses CloudStrict. `background` completes at Midge's local cloud commit barrier and uploads asynchronously; `strict` waits for provider acknowledgement. | | FITZ_STORAGE_LEASE_TTL_SECS | Integer seconds, at least 30 | 30 | TTL for the embedded Midge primary storage-writer lease. Midge renews at one third of this interval. Increasing it reduces provider lease traffic but extends takeover after an ungraceful failure; graceful shutdown explicitly releases the lease. | +| FITZ_STORAGE_WRITER_GENERATION | Positive unsigned integer | Unset | Enables Midge generation-ordered writer handoff for shared local or cloud storage. The operator must supply a strictly higher value for each replacement deployment and image rollback; Fitz never generates this value. Rejected in memory mode. | +| FITZ_STORAGE_WRITER_DRAIN_GRACE_MS | Unsigned integer milliseconds | 250 ms (Midge default) | Optional transaction drain grace for a configured writer handoff. Unset preserves Midge's default; setting this without `FITZ_STORAGE_WRITER_GENERATION` fails startup. | | FITZ_STORAGE_MEMTABLE_BYTES | Unsigned integer byte count | Auto | Optional explicit memtable size override for embedded engine. | | FITZ_SCHEDULE_PRELOAD_TIMEOUT_SECS | Positive integer second count | 120 | Maximum aggregate wait for required Schedule actor preload during startup. Expiry fails startup with an explicit timeout rather than leaving the broker wedged indefinitely. | | FITZ_QUEUE_WRITE_POLICY | legacy `fast` only | unset | Deprecated: Queue persistence is always best effort. `fast` is accepted for compatibility; `buffered`, `strict`, and other values fail startup. | @@ -163,6 +165,15 @@ For the auth and browser-perimeter checklist, see | FITZ_STREAM_SUBSCRIPTION_BUDGET_BYTES | Positive integer | 134217728 | Retained Stream registration charges across one broker. Each registration costs 512 bytes plus the original selector and canonical selector path lengths in bytes. | | FITZ_MIN_MEMORY_BYTES | Unsigned integer byte count | 134217728 | Startup preflight minimum cgroup memory threshold. Set 0 to bypass memory-limit check. | +For the first migration from a legacy Midge writer, stop that writer cleanly +before starting Fitz with `FITZ_STORAGE_WRITER_GENERATION`. For each later +replacement using the same shared storage, increase the generation, including +when rolling back to an earlier Fitz image. A handoff makes `/healthz` and +`/readyz` unavailable while the incumbent drains; Fitz restores readiness if +Midge resumes `Serving`, and shuts down promptly after Midge reports +`Retired`. This uses Midge's transaction drain grace, not the longer +`FITZ_DRAIN_GRACE_SECONDS` session drain. + Schedule persistence follows the selected storage mode. `memory` mode uses best-effort writes and does not promise restart recovery. Persistent local mode waits for local sync, background-cloud mode completes at Midge's local cloud