Skip to main content

reddb_server/runtime/
lease_loop.rs

1//! Writer-lease boot path with optional serverless snapshot hydration.
2//!
3//! Boot-time entrypoint that opts the runtime into lease-fenced
4//! writes when:
5//!   * `RED_LEASE_REQUIRED=true` (or `1`) is set, and
6//!   * a remote backend is configured (S3, FS, HTTP, …).
7//!
8//! All transitions (acquire / refresh / lost / release) are
9//! delegated to `LeaseLifecycle`; this module only owns env-var
10//! parsing, lifecycle construction, and the refresh thread.
11//!
12//! The refresh thread uses `LeaseTimerWheel` instead of a fixed
13//! `thread::sleep(ttl_ms / 3)` polling loop. The wheel wakes the
14//! thread exactly when the next refresh is due and reschedules after
15//! each successful refresh, so idle leases cost zero CPU.
16//!
17//! Env knobs:
18//!   * `RED_LEASE_REQUIRED` — `true` / `1` to enable. Default off.
19//!   * `RED_LEASE_TTL_SECS` — lease TTL in seconds. Default 60.
20//!   * `RED_LEASE_HOLDER_ID` — explicit holder id. Default
21//!     `<hostname>-<pid>`.
22//!   * `RED_LEASE_PREFIX` — backend prefix for the lease object key.
23//!     Default `leases/`.
24
25use std::sync::Arc;
26use std::thread;
27use std::time::Instant;
28
29use crate::api::{RedDBError, RedDBResult};
30use crate::replication::lease::LeaseStore;
31use crate::runtime::lease_lifecycle::{ClaimHook, LeaseLifecycle, MarkDraining};
32use crate::runtime::lease_timer_wheel::LeaseTimerWheel;
33use crate::runtime::serverless_snapshot_publication::SnapshotPublicationStore;
34use crate::runtime::serverless_wal_archive::{
35    archive_enabled, restore_generation, RestoredStream, ServerlessArchiveConfig,
36    ServerlessWalArchive,
37};
38use crate::runtime::RedDBRuntime;
39use crate::storage::unified::store::WalArchiveTap;
40
41pub struct LeaseBootPlan {
42    store: Arc<LeaseStore>,
43    backend: Arc<dyn crate::storage::backend::AtomicRemoteBackend>,
44    snapshot_publication: Option<Arc<SnapshotPublicationStore>>,
45    /// Generation restored before the runtime opened (generation heads).
46    restored: Option<RestoredStream>,
47    holder_id: String,
48    database_key: String,
49    ttl_ms: u64,
50    initial_snapshot_required: bool,
51}
52
53/// Observe the exact snapshot head before runtime hydration. The later lease
54/// claim CASes that observed version; publication racing with boot therefore
55/// aborts this boot instead of letting it serve a stale local snapshot.
56pub fn prepare_lease_loop_if_required(
57    options: &mut crate::api::RedDBOptions,
58) -> RedDBResult<Option<LeaseBootPlan>> {
59    if !lease_required() {
60        return Ok(None);
61    }
62    if options.read_only {
63        return Err(RedDBError::InvalidOperation(
64            "serverless writer leases require a writable local cache".into(),
65        ));
66    }
67    let backend = options.remote_backend_atomic.clone().ok_or_else(|| {
68        RedDBError::Internal(
69            "RED_LEASE_REQUIRED=true but the configured backend does not support atomic CAS — \
70             use s3, fs, or http with RED_HTTP_CONDITIONAL_WRITES=true"
71                .to_string(),
72        )
73    })?;
74    let database_key = options
75        .remote_key
76        .clone()
77        .filter(|key| !key.is_empty())
78        .filter(|_| options.remote_backend.is_some())
79        .ok_or_else(|| {
80            RedDBError::InvalidOperation(
81                "serverless writer leases require a remote backend and database key".into(),
82            )
83        })?;
84    let prefix = std::env::var("RED_LEASE_PREFIX")
85        .ok()
86        .filter(|value| !value.trim().is_empty())
87        .unwrap_or_else(|| "leases/".to_string());
88    // A primary/replica or cluster lease fences ownership of its local store.
89    // Only snapshot-backed profiles may replace that store from a remote head.
90    let snapshot_publication = match options.storage_profile.deploy_profile {
91        crate::storage::DeployProfile::Embedded | crate::storage::DeployProfile::Serverless => {
92            Some(Arc::new(SnapshotPublicationStore::new(
93                backend.clone(),
94                database_key.clone(),
95            )))
96        }
97        crate::storage::DeployProfile::PrimaryReplica | crate::storage::DeployProfile::Cluster => {
98            None
99        }
100    };
101    if snapshot_publication.is_some() {
102        verify_conditional_writes(
103            backend.as_ref(),
104            &format!("{prefix}{database_key}.cas-probe"),
105        )?;
106    }
107    options.remote_bootstrap_key = snapshot_publication
108        .as_ref()
109        .map(|publication| publication.observe_for_boot())
110        .transpose()
111        .map_err(|err| RedDBError::Internal(err.to_string()))?
112        .flatten();
113    let generation_head = snapshot_publication
114        .as_ref()
115        .and_then(|publication| publication.observed_head())
116        .filter(|head| head.generation.is_some());
117    let mut restored = None;
118    if let Some(head) = generation_head {
119        if !archive_enabled() {
120            return Err(RedDBError::InvalidOperation(
121                "the serverless head points at a physical generation; \
122                 RED_SERVERLESS_WAL_ARCHIVE=false cannot hydrate it"
123                    .into(),
124            ));
125        }
126        // Rebuild the generation and its archived WAL in an isolated cache;
127        // normal crash recovery replays the WAL when the runtime opens it.
128        let cache = crate::api::RedDBOptions::temporary();
129        let dir = cache
130            .data_path
131            .as_deref()
132            .and_then(std::path::Path::parent)
133            .ok_or_else(|| RedDBError::Internal("temporary cache has no directory".into()))?
134            .to_path_buf();
135        let stream = restore_generation(backend.as_ref(), &head, &dir).map_err(|err| {
136            RedDBError::Internal(format!("serverless generation restore failed: {err}"))
137        })?;
138        tracing::info!(
139            target: "reddb::serverless::archive",
140            generation_wal_lsn = stream.generation_wal_lsn,
141            restored_lsn = stream.last_lsn,
142            segments = stream.segments_replayed,
143            frames = stream.frames_replayed,
144            bytes = stream.bytes_downloaded,
145            duration_ms = stream.duration.as_millis() as u64,
146            "serverless generation restored"
147        );
148        options.data_path = Some(stream.data_path.clone());
149        options.metadata.insert(
150            crate::api::EPHEMERAL_RUNTIME_METADATA_KEY.into(),
151            "true".into(),
152        );
153        options.remote_bootstrap_key = None;
154        restored = Some(stream);
155    } else if options.remote_bootstrap_key.is_some()
156        && options.storage_profile.deploy_profile != crate::storage::DeployProfile::Embedded
157    {
158        // Operational caches have WAL and metadata siblings. Hydrate into an
159        // isolated boot directory so an old local WAL cannot replay over the
160        // authoritative snapshot. Reuse the existing ephemeral cleanup owner.
161        let cache = crate::api::RedDBOptions::in_memory();
162        options.data_path = cache.data_path;
163        options.metadata.insert(
164            crate::api::EPHEMERAL_RUNTIME_METADATA_KEY.into(),
165            "true".into(),
166        );
167    }
168    let initial_snapshot_required = snapshot_publication.is_some()
169        && options.remote_bootstrap_key.is_none()
170        && restored.is_none();
171    Ok(Some(LeaseBootPlan {
172        store: Arc::new(LeaseStore::new(backend.clone()).with_prefix(prefix)),
173        backend,
174        snapshot_publication,
175        restored,
176        holder_id: lease_holder_id(),
177        database_key,
178        ttl_ms: lease_ttl_secs() * 1000,
179        initial_snapshot_required,
180    }))
181}
182
183/// Try to start the writer-lease lifecycle if the operator opted in.
184/// Returns `Ok(())` when:
185///   * `RED_LEASE_REQUIRED` is unset / false, or
186///   * the lease was acquired and the refresh thread is running.
187///
188/// Returns `Err` when the operator asked for a lease and we couldn't
189/// get one — the caller should refuse to serve in that case.
190pub fn start_lease_loop_if_required(runtime: &RedDBRuntime) -> RedDBResult<()> {
191    let mut options = runtime.db().options().clone();
192    let plan = prepare_lease_loop_if_required(&mut options)?;
193    if options.remote_bootstrap_key.is_some()
194        || plan.as_ref().is_some_and(|plan| plan.restored.is_some())
195    {
196        return Err(RedDBError::InvalidOperation(
197            "serverless snapshot head must be observed before runtime hydration; use the prepared lease boot path"
198                .to_string(),
199        ));
200    }
201    start_prepared_lease_loop(runtime, plan)
202}
203
204pub fn start_prepared_lease_loop(
205    runtime: &RedDBRuntime,
206    plan: Option<LeaseBootPlan>,
207) -> RedDBResult<()> {
208    let Some(plan) = plan else {
209        return Ok(());
210    };
211    // Paged stores publish physical generations plus the archived WAL. A
212    // restored generation head always continues in that mode.
213    if plan.snapshot_publication.is_some()
214        && (plan.restored.is_some() || (archive_enabled() && runtime.db().is_paged()))
215    {
216        return start_generation_lease_loop(runtime, plan);
217    }
218    // Existing heads are claimed without re-uploading or re-checkpointing the
219    // hydrated database. Only migration to the first head needs a payload.
220    let local_snapshot = if plan.initial_snapshot_required {
221        Some(runtime.capture_serverless_snapshot()?)
222    } else {
223        None
224    };
225    let runtime_for_drain = Arc::downgrade(&runtime.inner);
226    let mark_draining: MarkDraining = Arc::new(move || {
227        if let Some(inner) = runtime_for_drain.upgrade() {
228            inner.lifecycle.mark_draining();
229        }
230    });
231    let term = runtime.current_replication_term();
232    let current_term = Arc::new(move || term);
233    let mut lifecycle = LeaseLifecycle::new(
234        plan.store,
235        runtime.write_gate_arc(),
236        runtime.audit_log_arc(),
237        mark_draining,
238        current_term,
239        plan.holder_id,
240        plan.database_key,
241        plan.ttl_ms,
242    );
243    if let Some(publication) = plan.snapshot_publication {
244        let database = runtime.db();
245        let snapshot_path = local_snapshot
246            .as_ref()
247            .map(|snapshot| snapshot.path())
248            .or_else(|| database.path())
249            .ok_or_else(|| {
250                RedDBError::InvalidOperation(
251                    "serverless boot requires a persistent local cache".into(),
252                )
253            })?;
254        lifecycle = lifecycle.with_snapshot_publication(publication, snapshot_path);
255    }
256    let lifecycle = Arc::new(lifecycle);
257    lifecycle.try_acquire()?;
258
259    // Stash the lifecycle on the runtime so admin handlers and the
260    // refresh thread share one instance. The OnceLock guarantees
261    // idempotency — re-entering the boot path (tests, double-init)
262    // returns Err and we drop the duplicate.
263    let lifecycle_for_runtime = Arc::clone(&lifecycle);
264    let _ = runtime.set_lease_lifecycle(lifecycle_for_runtime);
265
266    spawn_refresh_thread(runtime.clone(), lifecycle);
267    Ok(())
268}
269
270/// Generation mode: attach the WAL archive tap before any write is admitted,
271/// publish the first generation when the head has none, claim the head with
272/// this boot's stream epoch, then start the archive and refresh loops.
273fn start_generation_lease_loop(runtime: &RedDBRuntime, plan: LeaseBootPlan) -> RedDBResult<()> {
274    let publication = plan
275        .snapshot_publication
276        .clone()
277        .ok_or_else(|| RedDBError::Internal("generation mode needs a publication store".into()))?;
278    let epoch = publication
279        .next_claim_epoch()
280        .map_err(|err| RedDBError::Internal(err.to_string()))?;
281    let (start_lsn, prev_sha) = plan
282        .restored
283        .as_ref()
284        .map(|restored| (restored.last_lsn + 1, restored.last_sha256))
285        .unwrap_or((1, None));
286    let config = ServerlessArchiveConfig::from_env();
287    let tap = Arc::new(WalArchiveTap::new(
288        epoch,
289        start_lsn,
290        prev_sha,
291        config.max_segment_bytes,
292    ));
293    runtime
294        .db()
295        .store()
296        .attach_wal_archive_tap(Arc::clone(&tap))
297        .map_err(|err| RedDBError::Internal(format!("attach WAL archive: {err}")))?;
298    let archive = Arc::new(ServerlessWalArchive::new(
299        Arc::clone(&plan.backend),
300        Arc::clone(&publication),
301        tap,
302        epoch,
303        config,
304        plan.restored.as_ref(),
305    ));
306    // A head without a generation (first boot, or a single-file head being
307    // migrated) gets one before the claim. It is uploaded before the lease
308    // is taken so no object-store transfer runs under the lease lock.
309    let initial = if plan.restored.is_none() {
310        Some(
311            archive
312                .stage_and_upload_generation(runtime, epoch, false)?
313                .0,
314        )
315    } else {
316        None
317    };
318    // The restore listed the previous writer's segments before this node
319    // held the lease. A writer that flushed more WAL and then released the
320    // lease (graceful sleep whose final generation failed) would have those
321    // segments ignored forever once this claim starts the stream at
322    // `start_lsn`. Re-list under the lease and refuse to claim over them;
323    // the next boot restores them.
324    let previous_epoch = plan
325        .restored
326        .as_ref()
327        .and_then(|_| publication.observed_head())
328        .and_then(|head| head.generation)
329        .and_then(|generation| generation.wal_epochs.last().map(|claim| claim.epoch));
330    let claim_backend = Arc::clone(&plan.backend);
331    let claim_database = plan.database_key.clone();
332    let claim_publication = Arc::clone(&publication);
333    let claim: ClaimHook = Arc::new(move |lease| {
334        if let Some(epoch) = previous_epoch {
335            let prefix = reddb_file::serverless_wal_epoch_prefix(&claim_database, epoch);
336            let late = claim_backend
337                .list(&prefix)
338                .map_err(|err| format!("re-list {prefix} before claiming: {err}"))?
339                .into_iter()
340                .filter_map(|key| reddb_file::parse_serverless_wal_segment_key(&key))
341                .filter(|(segment_epoch, _, last)| *segment_epoch == epoch && *last >= start_lsn)
342                .map(|(_, _, last)| last)
343                .max();
344            if let Some(last) = late {
345                return Err(format!(
346                    "the previous writer archived WAL through stream LSN {last} after this boot \
347                     restored through {}; restart to restore it",
348                    start_lsn.saturating_sub(1)
349                ));
350            }
351        }
352        claim_publication
353            .claim_generation_stream(lease, start_lsn, initial.as_ref())
354            .map(|_| ())
355            .map_err(|err| err.to_string())
356    });
357    let runtime_for_drain = Arc::downgrade(&runtime.inner);
358    let mark_draining: MarkDraining = Arc::new(move || {
359        if let Some(inner) = runtime_for_drain.upgrade() {
360            inner.lifecycle.mark_draining();
361        }
362    });
363    let term = runtime.current_replication_term();
364    let lifecycle = Arc::new(
365        LeaseLifecycle::new(
366            plan.store,
367            runtime.write_gate_arc(),
368            runtime.audit_log_arc(),
369            mark_draining,
370            Arc::new(move || term),
371            plan.holder_id,
372            plan.database_key,
373            plan.ttl_ms,
374        )
375        .with_claim_hook(claim),
376    );
377    lifecycle.try_acquire()?;
378    archive.attach_lease(Arc::clone(&lifecycle));
379    let _ = runtime.set_lease_lifecycle(Arc::clone(&lifecycle));
380    runtime.set_serverless_wal_archive(Arc::clone(&archive));
381    archive.spawn(runtime.clone());
382    spawn_refresh_thread(runtime.clone(), lifecycle);
383    Ok(())
384}
385
386fn spawn_refresh_thread(runtime: RedDBRuntime, lifecycle: Arc<LeaseLifecycle>) {
387    // Timer wheel replaces thread::sleep(interval) — wakes exactly when the
388    // next refresh is due. Zero CPU during the idle window.
389    let wheel = Arc::new(LeaseTimerWheel::new(1));
390    wheel.schedule(
391        "lease-refresh".to_string(),
392        Instant::now() + lifecycle.refresh_delay(),
393    );
394
395    let wheel_for_handler = Arc::clone(&wheel);
396    let _ = thread::Builder::new()
397        .name("reddb-lease-refresh".into())
398        .spawn(move || {
399            wheel.run_until_shutdown(move |_id| {
400                // Keep the lease through drain and final publication. Shutdown
401                // releases it only after the last snapshot; a lease-loss path
402                // terminates below when refresh fails.
403                let phase = runtime.lifecycle().phase();
404                if phase == crate::runtime::lifecycle::Phase::Stopped {
405                    let _ = lifecycle.release();
406                    return false;
407                }
408
409                if lifecycle.refresh().is_err() {
410                    return false;
411                }
412
413                // Reschedule the next refresh.
414                wheel_for_handler.schedule(
415                    "lease-refresh".to_string(),
416                    Instant::now() + lifecycle.refresh_delay(),
417                );
418                true
419            });
420        });
421}
422
423/// Boot self-test for lease mode: the backend must refuse a PUT whose
424/// `If-Match` names a superseded version, and a create-only PUT on an
425/// existing key. A backend that silently ignores the precondition (OCI's
426/// S3-compatible API does) lets every writer win and cannot fence a lease,
427/// so startup fails instead of running unfenced.
428pub fn verify_conditional_writes(
429    backend: &dyn crate::storage::backend::AtomicRemoteBackend,
430    probe_key: &str,
431) -> RedDBResult<()> {
432    // Transport hiccups are retried; a backend that accepts a stale
433    // precondition fails at once. The sentinel is removed either way.
434    let mut result = probe_conditional_writes(backend, probe_key);
435    for attempt in 1..=2u64 {
436        match &result {
437            Err(RedDBError::Internal(_)) => {
438                std::thread::sleep(std::time::Duration::from_millis(250 * attempt));
439                result = probe_conditional_writes(backend, probe_key);
440            }
441            _ => break,
442        }
443    }
444    let _ = backend.delete(probe_key);
445    result
446}
447
448fn probe_conditional_writes(
449    backend: &dyn crate::storage::backend::AtomicRemoteBackend,
450    probe_key: &str,
451) -> RedDBResult<()> {
452    use crate::storage::backend::{BackendError, ConditionalPut};
453    let internal = |err: BackendError| {
454        RedDBError::Internal(format!("conditional-write self-test on {probe_key}: {err}"))
455    };
456    let probe = reddb_file::ServerlessWriterLeaseTempFile::new("cas-probe");
457    let write = |tag: &str| {
458        probe
459            .write_bytes(format!("{tag}-{}", crate::utils::now_unix_nanos()).as_bytes())
460            .map_err(|err| RedDBError::Internal(err.to_string()))
461    };
462    // A concurrent boot may advance the sentinel between our reads; retry.
463    for _ in 0..3 {
464        write("base")?;
465        let base =
466            match backend.upload_conditional(probe.path(), probe_key, ConditionalPut::IfAbsent) {
467                Ok(version) => version,
468                Err(BackendError::PreconditionFailed(_)) => {
469                    match backend.object_version(probe_key).map_err(internal)? {
470                        Some(version) => version,
471                        None => continue,
472                    }
473                }
474                Err(err) => return Err(internal(err)),
475            };
476        write("next")?;
477        match backend.upload_conditional(
478            probe.path(),
479            probe_key,
480            ConditionalPut::IfVersion(base.clone()),
481        ) {
482            Ok(_) => {}
483            Err(BackendError::PreconditionFailed(_)) => continue,
484            Err(err) => return Err(internal(err)),
485        }
486        write("stale")?;
487        let stale =
488            backend.upload_conditional(probe.path(), probe_key, ConditionalPut::IfVersion(base));
489        let duplicate =
490            backend.upload_conditional(probe.path(), probe_key, ConditionalPut::IfAbsent);
491        let refused = |result: &Result<_, BackendError>| {
492            matches!(result, Err(BackendError::PreconditionFailed(_)))
493        };
494        if refused(&stale) && refused(&duplicate) {
495            return Ok(());
496        }
497        if stale.is_ok() || duplicate.is_ok() {
498            return Err(RedDBError::InvalidOperation(format!(
499                "RED_LEASE_REQUIRED=true but the remote backend accepted a write whose \
500                 precondition no longer held ({probe_key}); it does not enforce If-Match / \
501                 If-None-Match and cannot fence a writer lease"
502            )));
503        }
504        // Both failed and at least one failure was not a 412.
505        return Err([stale.err(), duplicate.err()]
506            .into_iter()
507            .flatten()
508            .find(|err| !matches!(err, BackendError::PreconditionFailed(_)))
509            .map_or_else(
510                || {
511                    RedDBError::Internal(format!(
512                        "conditional-write self-test on {probe_key} failed"
513                    ))
514                },
515                internal,
516            ));
517    }
518    Err(RedDBError::Internal(format!(
519        "conditional-write self-test on {probe_key} kept racing another boot"
520    )))
521}
522
523fn lease_required() -> bool {
524    std::env::var("RED_LEASE_REQUIRED")
525        .ok()
526        .map(|v| {
527            let t = v.trim();
528            t.eq_ignore_ascii_case("true") || t == "1" || t.eq_ignore_ascii_case("yes")
529        })
530        .unwrap_or(false)
531}
532
533fn lease_ttl_secs() -> u64 {
534    std::env::var("RED_LEASE_TTL_SECS")
535        .ok()
536        .and_then(|s| s.trim().parse::<u64>().ok())
537        .filter(|v| *v > 0)
538        .unwrap_or(60)
539}
540
541fn lease_holder_id() -> String {
542    if let Some(explicit) = crate::utils::env_with_file_fallback("RED_LEASE_HOLDER_ID") {
543        return explicit;
544    }
545    let host = std::env::var("HOSTNAME")
546        .or_else(|_| std::env::var("HOST"))
547        .unwrap_or_else(|_| "unknown-host".to_string());
548    format!("{}-{}", host, std::process::id())
549}
550
551#[cfg(test)]
552mod tests {
553    use super::*;
554
555    use crate::storage::backend::{AtomicRemoteBackend as _, RemoteBackend as _};
556
557    /// An S3-compatible API that accepts every conditional write (as OCI's
558    /// does) must fail the boot self-test.
559    struct IgnoresPreconditions(crate::storage::backend::LocalBackend);
560
561    impl crate::storage::backend::RemoteBackend for IgnoresPreconditions {
562        fn name(&self) -> &str {
563            "ignores-preconditions"
564        }
565        fn download(
566            &self,
567            key: &str,
568            path: &std::path::Path,
569        ) -> Result<bool, crate::storage::backend::BackendError> {
570            self.0.download(key, path)
571        }
572        fn upload(
573            &self,
574            path: &std::path::Path,
575            key: &str,
576        ) -> Result<(), crate::storage::backend::BackendError> {
577            self.0.upload(path, key)
578        }
579        fn exists(&self, key: &str) -> Result<bool, crate::storage::backend::BackendError> {
580            self.0.exists(key)
581        }
582        fn delete(&self, key: &str) -> Result<(), crate::storage::backend::BackendError> {
583            self.0.delete(key)
584        }
585        fn list(&self, prefix: &str) -> Result<Vec<String>, crate::storage::backend::BackendError> {
586            self.0.list(prefix)
587        }
588    }
589
590    impl crate::storage::backend::AtomicRemoteBackend for IgnoresPreconditions {
591        fn object_version(
592            &self,
593            key: &str,
594        ) -> Result<
595            Option<crate::storage::backend::BackendObjectVersion>,
596            crate::storage::backend::BackendError,
597        > {
598            self.0.object_version(key)
599        }
600        fn upload_conditional(
601            &self,
602            path: &std::path::Path,
603            key: &str,
604            _condition: crate::storage::backend::ConditionalPut,
605        ) -> Result<
606            crate::storage::backend::BackendObjectVersion,
607            crate::storage::backend::BackendError,
608        > {
609            self.0.upload(path, key)?;
610            Ok(self.0.object_version(key)?.expect("object just written"))
611        }
612        fn delete_conditional(
613            &self,
614            key: &str,
615            _condition: crate::storage::backend::ConditionalDelete,
616        ) -> Result<(), crate::storage::backend::BackendError> {
617            self.0.delete(key)
618        }
619    }
620
621    #[test]
622    fn conditional_write_self_test_accepts_cas_and_rejects_ignored_preconditions() {
623        let root = tempfile::tempdir().unwrap();
624        let key = root.path().join("leases/db.cas-probe");
625        let key = key.to_string_lossy();
626        verify_conditional_writes(&crate::storage::backend::LocalBackend, &key)
627            .expect("a CAS backend passes, on first boot and again later");
628        verify_conditional_writes(&crate::storage::backend::LocalBackend, &key)
629            .expect("an existing sentinel is reused");
630        let ignoring = IgnoresPreconditions(crate::storage::backend::LocalBackend);
631        let err = verify_conditional_writes(&ignoring, &key).expect_err("must refuse");
632        assert!(err.to_string().contains("cannot fence"), "{err}");
633    }
634
635    #[test]
636    fn lease_required_parses_truthy_values() {
637        unsafe {
638            std::env::set_var("RED_LEASE_REQUIRED", "true");
639        }
640        assert!(lease_required());
641        unsafe {
642            std::env::set_var("RED_LEASE_REQUIRED", "1");
643        }
644        assert!(lease_required());
645        unsafe {
646            std::env::set_var("RED_LEASE_REQUIRED", "yes");
647        }
648        assert!(lease_required());
649        unsafe {
650            std::env::set_var("RED_LEASE_REQUIRED", "false");
651        }
652        assert!(!lease_required());
653        unsafe {
654            std::env::remove_var("RED_LEASE_REQUIRED");
655        }
656        assert!(!lease_required());
657    }
658
659    #[test]
660    fn ttl_defaults_to_60_when_unset() {
661        unsafe {
662            std::env::remove_var("RED_LEASE_TTL_SECS");
663        }
664        assert_eq!(lease_ttl_secs(), 60);
665    }
666
667    #[test]
668    fn ttl_rejects_zero_and_negative() {
669        unsafe {
670            std::env::set_var("RED_LEASE_TTL_SECS", "0");
671        }
672        assert_eq!(lease_ttl_secs(), 60);
673        unsafe {
674            std::env::set_var("RED_LEASE_TTL_SECS", "abc");
675        }
676        assert_eq!(lease_ttl_secs(), 60);
677        unsafe {
678            std::env::set_var("RED_LEASE_TTL_SECS", "30");
679        }
680        assert_eq!(lease_ttl_secs(), 30);
681        unsafe {
682            std::env::remove_var("RED_LEASE_TTL_SECS");
683        }
684    }
685
686    #[test]
687    fn holder_id_falls_back_when_no_env() {
688        unsafe {
689            std::env::remove_var("RED_LEASE_HOLDER_ID");
690        }
691        let id = lease_holder_id();
692        assert!(id.contains('-'));
693        assert!(!id.is_empty());
694    }
695
696    #[test]
697    fn holder_id_uses_explicit_when_set() {
698        unsafe {
699            std::env::set_var("RED_LEASE_HOLDER_ID", "explicit-writer-1");
700        }
701        assert_eq!(lease_holder_id(), "explicit-writer-1");
702        unsafe {
703            std::env::remove_var("RED_LEASE_HOLDER_ID");
704        }
705    }
706}