use std::sync::Arc;
use std::thread;
use std::time::Instant;
use crate::api::{RedDBError, RedDBResult};
use crate::replication::lease::LeaseStore;
use crate::runtime::lease_lifecycle::{ClaimHook, LeaseLifecycle, MarkDraining};
use crate::runtime::lease_timer_wheel::LeaseTimerWheel;
use crate::runtime::serverless_snapshot_publication::SnapshotPublicationStore;
use crate::runtime::serverless_wal_archive::{
archive_enabled, restore_generation, RestoredStream, ServerlessArchiveConfig,
ServerlessWalArchive,
};
use crate::runtime::RedDBRuntime;
use crate::storage::unified::store::WalArchiveTap;
pub struct LeaseBootPlan {
store: Arc<LeaseStore>,
backend: Arc<dyn crate::storage::backend::AtomicRemoteBackend>,
snapshot_publication: Option<Arc<SnapshotPublicationStore>>,
restored: Option<RestoredStream>,
holder_id: String,
database_key: String,
ttl_ms: u64,
initial_snapshot_required: bool,
}
pub fn prepare_lease_loop_if_required(
options: &mut crate::api::RedDBOptions,
) -> RedDBResult<Option<LeaseBootPlan>> {
if !lease_required() {
return Ok(None);
}
if options.read_only {
return Err(RedDBError::InvalidOperation(
"serverless writer leases require a writable local cache".into(),
));
}
let backend = options.remote_backend_atomic.clone().ok_or_else(|| {
RedDBError::Internal(
"RED_LEASE_REQUIRED=true but the configured backend does not support atomic CAS — \
use s3, fs, or http with RED_HTTP_CONDITIONAL_WRITES=true"
.to_string(),
)
})?;
let database_key = options
.remote_key
.clone()
.filter(|key| !key.is_empty())
.filter(|_| options.remote_backend.is_some())
.ok_or_else(|| {
RedDBError::InvalidOperation(
"serverless writer leases require a remote backend and database key".into(),
)
})?;
let prefix = std::env::var("RED_LEASE_PREFIX")
.ok()
.filter(|value| !value.trim().is_empty())
.unwrap_or_else(|| "leases/".to_string());
let snapshot_publication = match options.storage_profile.deploy_profile {
crate::storage::DeployProfile::Embedded | crate::storage::DeployProfile::Serverless => {
Some(Arc::new(SnapshotPublicationStore::new(
backend.clone(),
database_key.clone(),
)))
}
crate::storage::DeployProfile::PrimaryReplica | crate::storage::DeployProfile::Cluster => {
None
}
};
if snapshot_publication.is_some() {
verify_conditional_writes(
backend.as_ref(),
&format!("{prefix}{database_key}.cas-probe"),
)?;
}
options.remote_bootstrap_key = snapshot_publication
.as_ref()
.map(|publication| publication.observe_for_boot())
.transpose()
.map_err(|err| RedDBError::Internal(err.to_string()))?
.flatten();
let generation_head = snapshot_publication
.as_ref()
.and_then(|publication| publication.observed_head())
.filter(|head| head.generation.is_some());
let mut restored = None;
if let Some(head) = generation_head {
if !archive_enabled() {
return Err(RedDBError::InvalidOperation(
"the serverless head points at a physical generation; \
RED_SERVERLESS_WAL_ARCHIVE=false cannot hydrate it"
.into(),
));
}
let cache = crate::api::RedDBOptions::temporary();
let dir = cache
.data_path
.as_deref()
.and_then(std::path::Path::parent)
.ok_or_else(|| RedDBError::Internal("temporary cache has no directory".into()))?
.to_path_buf();
let stream = restore_generation(backend.as_ref(), &head, &dir).map_err(|err| {
RedDBError::Internal(format!("serverless generation restore failed: {err}"))
})?;
tracing::info!(
target: "reddb::serverless::archive",
generation_wal_lsn = stream.generation_wal_lsn,
restored_lsn = stream.last_lsn,
segments = stream.segments_replayed,
frames = stream.frames_replayed,
bytes = stream.bytes_downloaded,
duration_ms = stream.duration.as_millis() as u64,
"serverless generation restored"
);
options.data_path = Some(stream.data_path.clone());
options.metadata.insert(
crate::api::EPHEMERAL_RUNTIME_METADATA_KEY.into(),
"true".into(),
);
options.remote_bootstrap_key = None;
restored = Some(stream);
} else if options.remote_bootstrap_key.is_some()
&& options.storage_profile.deploy_profile != crate::storage::DeployProfile::Embedded
{
let cache = crate::api::RedDBOptions::in_memory();
options.data_path = cache.data_path;
options.metadata.insert(
crate::api::EPHEMERAL_RUNTIME_METADATA_KEY.into(),
"true".into(),
);
}
let initial_snapshot_required = snapshot_publication.is_some()
&& options.remote_bootstrap_key.is_none()
&& restored.is_none();
Ok(Some(LeaseBootPlan {
store: Arc::new(LeaseStore::new(backend.clone()).with_prefix(prefix)),
backend,
snapshot_publication,
restored,
holder_id: lease_holder_id(),
database_key,
ttl_ms: lease_ttl_secs() * 1000,
initial_snapshot_required,
}))
}
pub fn start_lease_loop_if_required(runtime: &RedDBRuntime) -> RedDBResult<()> {
let mut options = runtime.db().options().clone();
let plan = prepare_lease_loop_if_required(&mut options)?;
if options.remote_bootstrap_key.is_some()
|| plan.as_ref().is_some_and(|plan| plan.restored.is_some())
{
return Err(RedDBError::InvalidOperation(
"serverless snapshot head must be observed before runtime hydration; use the prepared lease boot path"
.to_string(),
));
}
start_prepared_lease_loop(runtime, plan)
}
pub fn start_prepared_lease_loop(
runtime: &RedDBRuntime,
plan: Option<LeaseBootPlan>,
) -> RedDBResult<()> {
let Some(plan) = plan else {
return Ok(());
};
if plan.snapshot_publication.is_some()
&& (plan.restored.is_some() || (archive_enabled() && runtime.db().is_paged()))
{
return start_generation_lease_loop(runtime, plan);
}
let local_snapshot = if plan.initial_snapshot_required {
Some(runtime.capture_serverless_snapshot()?)
} else {
None
};
let runtime_for_drain = Arc::downgrade(&runtime.inner);
let mark_draining: MarkDraining = Arc::new(move || {
if let Some(inner) = runtime_for_drain.upgrade() {
inner.lifecycle.mark_draining();
}
});
let term = runtime.current_replication_term();
let current_term = Arc::new(move || term);
let mut lifecycle = LeaseLifecycle::new(
plan.store,
runtime.write_gate_arc(),
runtime.audit_log_arc(),
mark_draining,
current_term,
plan.holder_id,
plan.database_key,
plan.ttl_ms,
);
if let Some(publication) = plan.snapshot_publication {
let database = runtime.db();
let snapshot_path = local_snapshot
.as_ref()
.map(|snapshot| snapshot.path())
.or_else(|| database.path())
.ok_or_else(|| {
RedDBError::InvalidOperation(
"serverless boot requires a persistent local cache".into(),
)
})?;
lifecycle = lifecycle.with_snapshot_publication(publication, snapshot_path);
}
let lifecycle = Arc::new(lifecycle);
lifecycle.try_acquire()?;
let lifecycle_for_runtime = Arc::clone(&lifecycle);
let _ = runtime.set_lease_lifecycle(lifecycle_for_runtime);
spawn_refresh_thread(runtime.clone(), lifecycle);
Ok(())
}
fn start_generation_lease_loop(runtime: &RedDBRuntime, plan: LeaseBootPlan) -> RedDBResult<()> {
let publication = plan
.snapshot_publication
.clone()
.ok_or_else(|| RedDBError::Internal("generation mode needs a publication store".into()))?;
let epoch = publication
.next_claim_epoch()
.map_err(|err| RedDBError::Internal(err.to_string()))?;
let (start_lsn, prev_sha) = plan
.restored
.as_ref()
.map(|restored| (restored.last_lsn + 1, restored.last_sha256))
.unwrap_or((1, None));
let config = ServerlessArchiveConfig::from_env();
let tap = Arc::new(WalArchiveTap::new(
epoch,
start_lsn,
prev_sha,
config.max_segment_bytes,
));
runtime
.db()
.store()
.attach_wal_archive_tap(Arc::clone(&tap))
.map_err(|err| RedDBError::Internal(format!("attach WAL archive: {err}")))?;
let archive = Arc::new(ServerlessWalArchive::new(
Arc::clone(&plan.backend),
Arc::clone(&publication),
tap,
epoch,
config,
plan.restored.as_ref(),
));
let initial = if plan.restored.is_none() {
Some(
archive
.stage_and_upload_generation(runtime, epoch, false)?
.0,
)
} else {
None
};
let previous_epoch = plan
.restored
.as_ref()
.and_then(|_| publication.observed_head())
.and_then(|head| head.generation)
.and_then(|generation| generation.wal_epochs.last().map(|claim| claim.epoch));
let claim_backend = Arc::clone(&plan.backend);
let claim_database = plan.database_key.clone();
let claim_publication = Arc::clone(&publication);
let claim: ClaimHook = Arc::new(move |lease| {
if let Some(epoch) = previous_epoch {
let prefix = reddb_file::serverless_wal_epoch_prefix(&claim_database, epoch);
let late = claim_backend
.list(&prefix)
.map_err(|err| format!("re-list {prefix} before claiming: {err}"))?
.into_iter()
.filter_map(|key| reddb_file::parse_serverless_wal_segment_key(&key))
.filter(|(segment_epoch, _, last)| *segment_epoch == epoch && *last >= start_lsn)
.map(|(_, _, last)| last)
.max();
if let Some(last) = late {
return Err(format!(
"the previous writer archived WAL through stream LSN {last} after this boot \
restored through {}; restart to restore it",
start_lsn.saturating_sub(1)
));
}
}
claim_publication
.claim_generation_stream(lease, start_lsn, initial.as_ref())
.map(|_| ())
.map_err(|err| err.to_string())
});
let runtime_for_drain = Arc::downgrade(&runtime.inner);
let mark_draining: MarkDraining = Arc::new(move || {
if let Some(inner) = runtime_for_drain.upgrade() {
inner.lifecycle.mark_draining();
}
});
let term = runtime.current_replication_term();
let lifecycle = Arc::new(
LeaseLifecycle::new(
plan.store,
runtime.write_gate_arc(),
runtime.audit_log_arc(),
mark_draining,
Arc::new(move || term),
plan.holder_id,
plan.database_key,
plan.ttl_ms,
)
.with_claim_hook(claim),
);
lifecycle.try_acquire()?;
archive.attach_lease(Arc::clone(&lifecycle));
let _ = runtime.set_lease_lifecycle(Arc::clone(&lifecycle));
runtime.set_serverless_wal_archive(Arc::clone(&archive));
archive.spawn(runtime.clone());
spawn_refresh_thread(runtime.clone(), lifecycle);
Ok(())
}
fn spawn_refresh_thread(runtime: RedDBRuntime, lifecycle: Arc<LeaseLifecycle>) {
let wheel = Arc::new(LeaseTimerWheel::new(1));
wheel.schedule(
"lease-refresh".to_string(),
Instant::now() + lifecycle.refresh_delay(),
);
let wheel_for_handler = Arc::clone(&wheel);
let _ = thread::Builder::new()
.name("reddb-lease-refresh".into())
.spawn(move || {
wheel.run_until_shutdown(move |_id| {
let phase = runtime.lifecycle().phase();
if phase == crate::runtime::lifecycle::Phase::Stopped {
let _ = lifecycle.release();
return false;
}
if lifecycle.refresh().is_err() {
return false;
}
wheel_for_handler.schedule(
"lease-refresh".to_string(),
Instant::now() + lifecycle.refresh_delay(),
);
true
});
});
}
pub fn verify_conditional_writes(
backend: &dyn crate::storage::backend::AtomicRemoteBackend,
probe_key: &str,
) -> RedDBResult<()> {
let mut result = probe_conditional_writes(backend, probe_key);
for attempt in 1..=2u64 {
match &result {
Err(RedDBError::Internal(_)) => {
std::thread::sleep(std::time::Duration::from_millis(250 * attempt));
result = probe_conditional_writes(backend, probe_key);
}
_ => break,
}
}
let _ = backend.delete(probe_key);
result
}
fn probe_conditional_writes(
backend: &dyn crate::storage::backend::AtomicRemoteBackend,
probe_key: &str,
) -> RedDBResult<()> {
use crate::storage::backend::{BackendError, ConditionalPut};
let internal = |err: BackendError| {
RedDBError::Internal(format!("conditional-write self-test on {probe_key}: {err}"))
};
let probe = reddb_file::ServerlessWriterLeaseTempFile::new("cas-probe");
let write = |tag: &str| {
probe
.write_bytes(format!("{tag}-{}", crate::utils::now_unix_nanos()).as_bytes())
.map_err(|err| RedDBError::Internal(err.to_string()))
};
for _ in 0..3 {
write("base")?;
let base =
match backend.upload_conditional(probe.path(), probe_key, ConditionalPut::IfAbsent) {
Ok(version) => version,
Err(BackendError::PreconditionFailed(_)) => {
match backend.object_version(probe_key).map_err(internal)? {
Some(version) => version,
None => continue,
}
}
Err(err) => return Err(internal(err)),
};
write("next")?;
match backend.upload_conditional(
probe.path(),
probe_key,
ConditionalPut::IfVersion(base.clone()),
) {
Ok(_) => {}
Err(BackendError::PreconditionFailed(_)) => continue,
Err(err) => return Err(internal(err)),
}
write("stale")?;
let stale =
backend.upload_conditional(probe.path(), probe_key, ConditionalPut::IfVersion(base));
let duplicate =
backend.upload_conditional(probe.path(), probe_key, ConditionalPut::IfAbsent);
let refused = |result: &Result<_, BackendError>| {
matches!(result, Err(BackendError::PreconditionFailed(_)))
};
if refused(&stale) && refused(&duplicate) {
return Ok(());
}
if stale.is_ok() || duplicate.is_ok() {
return Err(RedDBError::InvalidOperation(format!(
"RED_LEASE_REQUIRED=true but the remote backend accepted a write whose \
precondition no longer held ({probe_key}); it does not enforce If-Match / \
If-None-Match and cannot fence a writer lease"
)));
}
return Err([stale.err(), duplicate.err()]
.into_iter()
.flatten()
.find(|err| !matches!(err, BackendError::PreconditionFailed(_)))
.map_or_else(
|| {
RedDBError::Internal(format!(
"conditional-write self-test on {probe_key} failed"
))
},
internal,
));
}
Err(RedDBError::Internal(format!(
"conditional-write self-test on {probe_key} kept racing another boot"
)))
}
fn lease_required() -> bool {
std::env::var("RED_LEASE_REQUIRED")
.ok()
.map(|v| {
let t = v.trim();
t.eq_ignore_ascii_case("true") || t == "1" || t.eq_ignore_ascii_case("yes")
})
.unwrap_or(false)
}
fn lease_ttl_secs() -> u64 {
std::env::var("RED_LEASE_TTL_SECS")
.ok()
.and_then(|s| s.trim().parse::<u64>().ok())
.filter(|v| *v > 0)
.unwrap_or(60)
}
fn lease_holder_id() -> String {
if let Some(explicit) = crate::utils::env_with_file_fallback("RED_LEASE_HOLDER_ID") {
return explicit;
}
let host = std::env::var("HOSTNAME")
.or_else(|_| std::env::var("HOST"))
.unwrap_or_else(|_| "unknown-host".to_string());
format!("{}-{}", host, std::process::id())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::storage::backend::{AtomicRemoteBackend as _, RemoteBackend as _};
struct IgnoresPreconditions(crate::storage::backend::LocalBackend);
impl crate::storage::backend::RemoteBackend for IgnoresPreconditions {
fn name(&self) -> &str {
"ignores-preconditions"
}
fn download(
&self,
key: &str,
path: &std::path::Path,
) -> Result<bool, crate::storage::backend::BackendError> {
self.0.download(key, path)
}
fn upload(
&self,
path: &std::path::Path,
key: &str,
) -> Result<(), crate::storage::backend::BackendError> {
self.0.upload(path, key)
}
fn exists(&self, key: &str) -> Result<bool, crate::storage::backend::BackendError> {
self.0.exists(key)
}
fn delete(&self, key: &str) -> Result<(), crate::storage::backend::BackendError> {
self.0.delete(key)
}
fn list(&self, prefix: &str) -> Result<Vec<String>, crate::storage::backend::BackendError> {
self.0.list(prefix)
}
}
impl crate::storage::backend::AtomicRemoteBackend for IgnoresPreconditions {
fn object_version(
&self,
key: &str,
) -> Result<
Option<crate::storage::backend::BackendObjectVersion>,
crate::storage::backend::BackendError,
> {
self.0.object_version(key)
}
fn upload_conditional(
&self,
path: &std::path::Path,
key: &str,
_condition: crate::storage::backend::ConditionalPut,
) -> Result<
crate::storage::backend::BackendObjectVersion,
crate::storage::backend::BackendError,
> {
self.0.upload(path, key)?;
Ok(self.0.object_version(key)?.expect("object just written"))
}
fn delete_conditional(
&self,
key: &str,
_condition: crate::storage::backend::ConditionalDelete,
) -> Result<(), crate::storage::backend::BackendError> {
self.0.delete(key)
}
}
#[test]
fn conditional_write_self_test_accepts_cas_and_rejects_ignored_preconditions() {
let root = tempfile::tempdir().unwrap();
let key = root.path().join("leases/db.cas-probe");
let key = key.to_string_lossy();
verify_conditional_writes(&crate::storage::backend::LocalBackend, &key)
.expect("a CAS backend passes, on first boot and again later");
verify_conditional_writes(&crate::storage::backend::LocalBackend, &key)
.expect("an existing sentinel is reused");
let ignoring = IgnoresPreconditions(crate::storage::backend::LocalBackend);
let err = verify_conditional_writes(&ignoring, &key).expect_err("must refuse");
assert!(err.to_string().contains("cannot fence"), "{err}");
}
#[test]
fn lease_required_parses_truthy_values() {
unsafe {
std::env::set_var("RED_LEASE_REQUIRED", "true");
}
assert!(lease_required());
unsafe {
std::env::set_var("RED_LEASE_REQUIRED", "1");
}
assert!(lease_required());
unsafe {
std::env::set_var("RED_LEASE_REQUIRED", "yes");
}
assert!(lease_required());
unsafe {
std::env::set_var("RED_LEASE_REQUIRED", "false");
}
assert!(!lease_required());
unsafe {
std::env::remove_var("RED_LEASE_REQUIRED");
}
assert!(!lease_required());
}
#[test]
fn ttl_defaults_to_60_when_unset() {
unsafe {
std::env::remove_var("RED_LEASE_TTL_SECS");
}
assert_eq!(lease_ttl_secs(), 60);
}
#[test]
fn ttl_rejects_zero_and_negative() {
unsafe {
std::env::set_var("RED_LEASE_TTL_SECS", "0");
}
assert_eq!(lease_ttl_secs(), 60);
unsafe {
std::env::set_var("RED_LEASE_TTL_SECS", "abc");
}
assert_eq!(lease_ttl_secs(), 60);
unsafe {
std::env::set_var("RED_LEASE_TTL_SECS", "30");
}
assert_eq!(lease_ttl_secs(), 30);
unsafe {
std::env::remove_var("RED_LEASE_TTL_SECS");
}
}
#[test]
fn holder_id_falls_back_when_no_env() {
unsafe {
std::env::remove_var("RED_LEASE_HOLDER_ID");
}
let id = lease_holder_id();
assert!(id.contains('-'));
assert!(!id.is_empty());
}
#[test]
fn holder_id_uses_explicit_when_set() {
unsafe {
std::env::set_var("RED_LEASE_HOLDER_ID", "explicit-writer-1");
}
assert_eq!(lease_holder_id(), "explicit-writer-1");
unsafe {
std::env::remove_var("RED_LEASE_HOLDER_ID");
}
}
}