k8s_controller/leader_election.rs
1use std::error::Error as _;
2use std::future::Future;
3use std::pin::pin;
4use std::time::{Duration, Instant};
5
6use futures::FutureExt;
7use futures::future::{self, Either};
8use k8s_openapi::api::coordination::v1::{Lease, LeaseSpec};
9use k8s_openapi::apimachinery::pkg::apis::meta::v1::MicroTime;
10use k8s_openapi::jiff::Timestamp;
11use kube::Client;
12use kube::api::{Api, ObjectMeta, PostParams};
13use rand::{RngExt, rng};
14use tracing::{debug, error, info, warn};
15
16/// Lease-based leader election, allowing multiple replicas of a controller
17/// to run while ensuring that only one of them is reconciling at a time.
18///
19/// This uses a `coordination.k8s.io/v1` [`Lease`] object, following the same
20/// protocol (and using the same default timings) as the Kubernetes client-go
21/// `leaderelection` package: the leader repeatedly renews the lease, and
22/// other candidates take the lease over if the leader fails to renew it for
23/// `lease_duration`. Expiry is determined by observing the lease go
24/// unchanged for `lease_duration`, rather than by comparing timestamps in
25/// the lease against the local clock, so it is robust to clock skew between
26/// candidates. Note that this protocol is cooperative: it guarantees mutual
27/// exclusion only among candidates that respect the lease.
28///
29/// The controller's service account needs `get`, `create`, and `update`
30/// permissions on `leases` in the `coordination.k8s.io` API group for this
31/// to work.
32///
33/// The `identity` must be non-empty and unique among the candidates for a
34/// given lease; the pod name (available in the `HOSTNAME` environment
35/// variable, or via the downward API) is a good choice. Beware that
36/// candidates for the same lease which share an identity will each mistake
37/// the other's renewals for their own and all act as leader simultaneously,
38/// so never create multiple `LeaderElection`s in the same process with the
39/// same lease name and identity. To have one lease guard several
40/// controllers in a process, share a single `LeaderElection` via
41/// [`with_lease`](LeaderElection::with_lease) instead.
42#[derive(Clone)]
43pub struct LeaderElection {
44 api: Api<Lease>,
45 lease_name: String,
46 identity: String,
47 lease_duration: Duration,
48 renew_deadline: Duration,
49 retry_period: Duration,
50}
51
52/// How a call to [`LeaderElection::with_lease`] ended.
53#[derive(Debug, PartialEq, Eq)]
54pub enum LeaseOutcome<T> {
55 /// The future ran to completion with this output while holding the
56 /// lease, which was then released.
57 Completed(T),
58 /// Leadership was lost, and the future was dropped.
59 Lost,
60 /// Shutdown was requested before the lease was acquired, so the future
61 /// never ran.
62 Shutdown,
63}
64
65impl LeaderElection {
66 /// Creates a leader election configuration for the [`Lease`] named
67 /// `lease_name` in the given `namespace`, identifying this instance of
68 /// the controller as `identity`. The timings default to the client-go
69 /// defaults: a lease duration of 15 seconds, a renew deadline of 10
70 /// seconds, and a retry period of 2 seconds.
71 pub fn new(client: Client, namespace: &str, lease_name: &str, identity: &str) -> Self {
72 Self {
73 api: Api::namespaced(client, namespace),
74 lease_name: lease_name.to_owned(),
75 identity: identity.to_owned(),
76 lease_duration: Duration::from_secs(15),
77 renew_deadline: Duration::from_secs(10),
78 retry_period: Duration::from_secs(2),
79 }
80 }
81
82 /// Sets how long a non-leader must wait after the last observed change
83 /// to the lease before forcibly taking it over. Larger values slow down
84 /// failover; smaller values increase the risk that a leader which is
85 /// still running (but partitioned from the API server) has not yet
86 /// stopped reconciling when the new leader starts. Must be greater than
87 /// the renew deadline.
88 pub fn with_lease_duration(mut self, lease_duration: Duration) -> Self {
89 self.lease_duration = lease_duration;
90 self
91 }
92
93 /// Sets how long the leader will keep trying to renew the lease before
94 /// giving up leadership. Must be less than the lease duration (so that
95 /// a leader which cannot reach the API server gives up before another
96 /// candidate can take the lease over) and greater than the retry
97 /// period.
98 pub fn with_renew_deadline(mut self, renew_deadline: Duration) -> Self {
99 self.renew_deadline = renew_deadline;
100 self
101 }
102
103 /// Sets how often candidates poll the lease while waiting to acquire
104 /// it, and how often the leader renews it.
105 pub fn with_retry_period(mut self, retry_period: Duration) -> Self {
106 self.retry_period = retry_period;
107 self
108 }
109
110 /// Wait until this instance holds the lease, then run `fut` while
111 /// renewing the lease in the background.
112 ///
113 /// If `fut` completes on its own, the lease is voluntarily released
114 /// (handing leadership over immediately rather than making the other
115 /// candidates wait for it to expire) and its output is returned in
116 /// [`LeaseOutcome::Completed`].
117 ///
118 /// If leadership is lost (because the lease could not be renewed in
119 /// time, or was taken over by another candidate), `fut` is dropped,
120 /// cancelling its work, and this method returns [`LeaseOutcome::Lost`].
121 /// The caller should then promptly either exit the process (letting
122 /// Kubernetes restart it) or rejoin the election by calling this method
123 /// again. Note that dropping `fut` cancels it cooperatively: work it
124 /// has spawned as separate tasks, or blocking code, is not cancelled.
125 /// If `fut` does such things, prefer exiting the process so that no
126 /// work outlives the lease.
127 ///
128 /// `shutdown` is for graceful shutdown (for instance, on receiving a
129 /// termination signal); pass [`std::future::pending`] if there is none.
130 /// If it completes before the lease is acquired, `fut` is never run and
131 /// this method returns [`LeaseOutcome::Shutdown`]. A request to acquire
132 /// the lease which is in flight at that point is given up to the retry
133 /// period to complete, so that a lease it takes is released rather than
134 /// left to expire. Prefer this to dropping the future returned by this
135 /// method, since a dropped request which was already sent can still
136 /// take the lease.
137 ///
138 /// Once `fut` is running, `shutdown` is no longer watched: `fut` must
139 /// itself complete on shutdown (for instance, by giving each controller
140 /// the same signal via `graceful_shutdown_on`), which lets it finish
141 /// its in-flight work before the lease is released. Since the lease
142 /// can be acquired just as `shutdown` completes, `fut` must also handle
143 /// being started after shutdown.
144 ///
145 /// To run a [`Controller`](crate::Controller) under a lease, pass its
146 /// [`run`](crate::Controller::run) future; to have one lease guard
147 /// several controllers (rather than electing a separate leader per
148 /// controller), pass a future that runs all of them, for instance:
149 ///
150 /// ```ignore
151 /// leader_election
152 /// .with_lease(
153 /// shutdown,
154 /// futures::future::join(controller_a.run(), controller_b.run()),
155 /// )
156 /// .await;
157 /// ```
158 ///
159 /// Panics if the configured timings are inconsistent or the identity is
160 /// empty.
161 pub async fn with_lease<S: Future, F: Future>(
162 &self,
163 shutdown: S,
164 fut: F,
165 ) -> LeaseOutcome<F::Output> {
166 let Some(acquired_at) = self.acquire(shutdown).await else {
167 return LeaseOutcome::Shutdown;
168 };
169 let fut = pin!(fut);
170 let lost = pin!(self.hold(acquired_at));
171 match future::select(fut, lost).await {
172 Either::Left((output, _)) => {
173 self.release().await;
174 LeaseOutcome::Completed(output)
175 }
176 Either::Right(((), _)) => LeaseOutcome::Lost,
177 }
178 }
179
180 fn validate(&self) {
181 assert!(!self.identity.is_empty(), "identity must not be empty");
182 assert!(
183 self.renew_deadline < self.lease_duration,
184 "renew_deadline must be less than lease_duration"
185 );
186 assert!(
187 self.retry_period < self.renew_deadline,
188 "retry_period must be less than renew_deadline"
189 );
190 assert!(
191 i32::try_from(self.lease_duration.as_secs()).is_ok(),
192 "lease_duration must be at most i32::MAX seconds"
193 );
194 }
195
196 fn lease_duration_seconds(&self) -> i32 {
197 i32::try_from(self.lease_duration.as_secs())
198 .expect("lease_duration must be at most i32::MAX seconds")
199 }
200
201 /// Wait until we hold the lease, returning the instant captured just
202 /// before the request that acquired it was sent (the pessimistic time
203 /// from which renewal deadlines must be measured; see [`hold`]).
204 /// Returns `None`, without holding the lease, if `shutdown` completes
205 /// first. Panics if the configured timings are inconsistent or the
206 /// identity is empty.
207 ///
208 /// [`hold`]: LeaderElection::hold
209 async fn acquire(&self, shutdown: impl Future) -> Option<Instant> {
210 self.validate();
211 let mut shutdown = pin!(shutdown);
212 info!(
213 lease_name = %self.lease_name,
214 identity = %self.identity,
215 "attempting to acquire leadership lease",
216 );
217 let mut observed = None;
218 loop {
219 // checked before starting an attempt, so that an attempt which
220 // loses the race below is known to have been started
221 if shutdown.as_mut().now_or_never().is_some() {
222 return None;
223 }
224 let started = Instant::now();
225 let result = {
226 // A hung request must not keep us out of the election. If a
227 // timed-out request still takes the lease, the next attempt
228 // finds it held by us.
229 let attempt = pin!(tokio::time::timeout(
230 self.renew_deadline,
231 self.try_acquire(&mut observed),
232 ));
233 match future::select(attempt, shutdown.as_mut()).await {
234 Either::Left((result, _)) => result,
235 Either::Right((_, attempt)) => {
236 // dropping the attempt would not stop a request
237 // that was already sent from taking the lease, so
238 // let it land (within reason) and release whatever
239 // it took. both steps are bounded so that an
240 // unreachable API server can't hang shutdown
241 let result = tokio::time::timeout(self.retry_period, attempt).await;
242 if !matches!(result, Ok(Ok(Ok(false))))
243 && tokio::time::timeout(self.retry_period, self.release())
244 .await
245 .is_err()
246 {
247 warn!(
248 lease_name = %self.lease_name,
249 "timed out releasing leadership lease during shutdown",
250 );
251 }
252 return None;
253 }
254 }
255 };
256 match result {
257 Err(_) => {
258 warn!(
259 lease_name = %self.lease_name,
260 "attempt to acquire leadership lease did not complete within the renew deadline",
261 );
262 }
263 Ok(Ok(true)) => {
264 info!(
265 lease_name = %self.lease_name,
266 identity = %self.identity,
267 "acquired leadership lease",
268 );
269 return Some(started);
270 }
271 Ok(Ok(false)) => {
272 debug!(
273 lease_name = %self.lease_name,
274 "leadership lease is held by another candidate",
275 );
276 }
277 // a 401 or 403 will never resolve on its own; it almost
278 // always means the service account is missing RBAC
279 // permissions on leases, so log it more loudly
280 Ok(Err(kube::Error::Api(e))) if e.code == 401 || e.code == 403 => {
281 error!(
282 error = %e,
283 lease_name = %self.lease_name,
284 "not permitted to access the leadership lease; the \
285 service account needs get, create, and update \
286 permissions on leases in coordination.k8s.io",
287 );
288 }
289 Ok(Err(e)) => {
290 warn!(
291 error = %e,
292 source = e.source(),
293 lease_name = %self.lease_name,
294 "error while trying to acquire leadership lease",
295 );
296 }
297 }
298 // jitter the retry period to avoid thundering herds. the rng is
299 // bound separately because holding a `ThreadRng` (which is not
300 // `Send`) across the await point would make this future `!Send`
301 let jitter = rng().random_range(1.0..1.5);
302 let sleep = pin!(tokio::time::sleep(self.retry_period.mul_f64(jitter)));
303 if let Either::Right(_) = future::select(sleep, shutdown.as_mut()).await {
304 return None;
305 }
306 }
307 }
308
309 /// Try once to acquire the lease, returning whether we now hold it.
310 /// `observed` tracks the last seen state of the lease and when we saw
311 /// it, so that expiry is measured against our own clock.
312 async fn try_acquire(
313 &self,
314 observed: &mut Option<(LeaseSpec, Instant)>,
315 ) -> Result<bool, kube::Error> {
316 let Some(mut lease) = self.api.get_opt(&self.lease_name).await? else {
317 let lease = Lease {
318 metadata: ObjectMeta {
319 name: Some(self.lease_name.clone()),
320 ..Default::default()
321 },
322 spec: Some(next_spec(
323 &self.identity,
324 self.lease_duration_seconds(),
325 None,
326 Timestamp::now(),
327 )),
328 };
329 return match self.api.create(&PostParams::default(), &lease).await {
330 Ok(_) => Ok(true),
331 // another candidate created the lease first
332 Err(kube::Error::Api(e)) if e.code == 409 => Ok(false),
333 Err(e) => Err(e),
334 };
335 };
336
337 let spec = lease.spec.take().unwrap_or_default();
338 // a missing or empty holder means the lease was voluntarily
339 // released (client-go writes an empty string on release) and can be
340 // taken immediately
341 let holder = spec.holder_identity.as_deref().filter(|h| !h.is_empty());
342 let held_by_us = holder == Some(self.identity.as_str());
343 if !held_by_us && holder.is_some() {
344 if observed.as_ref().is_none_or(|(last, _)| *last != spec) {
345 *observed = Some((spec, Instant::now()));
346 return Ok(false);
347 }
348 let (_, observed_at) = observed.as_ref().unwrap();
349 if observed_at.elapsed() < self.lease_duration {
350 return Ok(false);
351 }
352 // the holder has failed to renew the lease for a full
353 // lease_duration, so we can take it over
354 }
355 lease.spec = Some(next_spec(
356 &self.identity,
357 self.lease_duration_seconds(),
358 Some(&spec),
359 Timestamp::now(),
360 ));
361 // replace (rather than patch) so that the write fails with a
362 // conflict if another candidate updated the lease since we read it
363 match self
364 .api
365 .replace(&self.lease_name, &PostParams::default(), &lease)
366 .await
367 {
368 Ok(_) => Ok(true),
369 Err(kube::Error::Api(e)) if e.code == 409 => Ok(false),
370 Err(e) => Err(e),
371 }
372 }
373
374 /// Renew the lease until we lose it, then return. Only call this while
375 /// holding the lease. `last_renew` must be an instant captured *before*
376 /// the request that last renewed (or acquired) the lease was sent.
377 ///
378 /// Renewals are measured from before their request is sent: other
379 /// candidates start their takeover clocks when they observe the written
380 /// lease, which can happen well before we receive the response, so
381 /// measuring from the response could extend our renew deadline past
382 /// their takeover time.
383 async fn hold(&self, mut last_renew: Instant) {
384 let mut interval = tokio::time::interval(self.retry_period);
385 // the first tick completes immediately, and the lease was just
386 // renewed by acquiring it
387 interval.tick().await;
388 loop {
389 // an interval (rather than a sleep) keeps renewals at a
390 // consistent cadence even when an attempt is slow, rather than
391 // eating into the renew deadline budget between attempts
392 interval.tick().await;
393 // bound each attempt by the time remaining until the renew
394 // deadline, so that a hung request (the kube client's default
395 // read timeout is much longer than the deadline) can't keep us
396 // acting as leader after another candidate may have taken over
397 let remaining = self.renew_deadline.saturating_sub(last_renew.elapsed());
398 let started = Instant::now();
399 match tokio::time::timeout(remaining, self.renew()).await {
400 Ok(Ok(true)) => last_renew = started,
401 Ok(Ok(false)) => {
402 warn!(
403 lease_name = %self.lease_name,
404 identity = %self.identity,
405 "leadership lease was taken by another candidate",
406 );
407 return;
408 }
409 Ok(Err(e)) => {
410 warn!(
411 error = %e,
412 source = e.source(),
413 lease_name = %self.lease_name,
414 "failed to renew leadership lease",
415 );
416 if last_renew.elapsed() >= self.renew_deadline {
417 warn!(
418 lease_name = %self.lease_name,
419 identity = %self.identity,
420 "failed to renew leadership lease within the renew deadline; giving up leadership",
421 );
422 return;
423 }
424 }
425 Err(_) => {
426 warn!(
427 lease_name = %self.lease_name,
428 identity = %self.identity,
429 "leadership lease renewal did not complete within the renew deadline; giving up leadership",
430 );
431 return;
432 }
433 }
434 }
435 }
436
437 /// Try once to renew the lease, returning whether we still hold it.
438 async fn renew(&self) -> Result<bool, kube::Error> {
439 let Some(mut lease) = self.api.get_opt(&self.lease_name).await? else {
440 return Ok(false);
441 };
442 let spec = lease.spec.take().unwrap_or_default();
443 if spec.holder_identity.as_deref() != Some(self.identity.as_str()) {
444 return Ok(false);
445 }
446 lease.spec = Some(next_spec(
447 &self.identity,
448 self.lease_duration_seconds(),
449 Some(&spec),
450 Timestamp::now(),
451 ));
452 self.api
453 .replace(&self.lease_name, &PostParams::default(), &lease)
454 .await?;
455 Ok(true)
456 }
457
458 /// Voluntarily release the lease if we hold it, allowing another
459 /// candidate to take it over immediately rather than waiting for it to
460 /// expire. [`with_lease`](LeaderElection::with_lease) does this itself
461 /// when its future completes or shutdown is requested, so this is only
462 /// needed after dropping the future it returns instead, once the
463 /// controller has stopped reconciling. This is
464 /// best-effort: errors are logged and ignored, since the lease will
465 /// expire on its own regardless.
466 pub async fn release(&self) {
467 match self.try_release().await {
468 Ok(true) => {
469 info!(
470 lease_name = %self.lease_name,
471 identity = %self.identity,
472 "released leadership lease",
473 );
474 }
475 Ok(false) => {
476 debug!(
477 lease_name = %self.lease_name,
478 "leadership lease is not held by us; nothing to release",
479 );
480 }
481 Err(e) => {
482 warn!(
483 error = %e,
484 source = e.source(),
485 lease_name = %self.lease_name,
486 "failed to release leadership lease",
487 );
488 }
489 }
490 }
491
492 /// Try once to release the lease, returning whether we released it.
493 async fn try_release(&self) -> Result<bool, kube::Error> {
494 let Some(mut lease) = self.api.get_opt(&self.lease_name).await? else {
495 return Ok(false);
496 };
497 let spec = lease.spec.take().unwrap_or_default();
498 if spec.holder_identity.as_deref() != Some(self.identity.as_str()) {
499 return Ok(false);
500 }
501 lease.spec = Some(released_spec(&spec));
502 match self
503 .api
504 .replace(&self.lease_name, &PostParams::default(), &lease)
505 .await
506 {
507 Ok(_) => Ok(true),
508 // another candidate already took the lease over
509 Err(kube::Error::Api(e)) if e.code == 409 => Ok(false),
510 Err(e) => Err(e),
511 }
512 }
513}
514
515/// Compute the lease spec that makes `identity` the holder, given the
516/// previous spec (if the lease already existed).
517fn next_spec(
518 identity: &str,
519 lease_duration_seconds: i32,
520 prev: Option<&LeaseSpec>,
521 now: Timestamp,
522) -> LeaseSpec {
523 let now = MicroTime(now);
524 let held_by_us = prev.is_some_and(|s| s.holder_identity.as_deref() == Some(identity));
525 LeaseSpec {
526 holder_identity: Some(identity.to_owned()),
527 lease_duration_seconds: Some(lease_duration_seconds),
528 acquire_time: if held_by_us {
529 prev.and_then(|s| s.acquire_time.clone())
530 } else {
531 Some(now.clone())
532 },
533 renew_time: Some(now),
534 lease_transitions: match prev {
535 None => Some(0),
536 Some(s) if held_by_us => s.lease_transitions,
537 Some(s) => Some(s.lease_transitions.unwrap_or(0).saturating_add(1)),
538 },
539 ..Default::default()
540 }
541}
542
543/// Compute the lease spec that marks the lease as no longer held,
544/// preserving the transition count for the next holder to increment.
545fn released_spec(prev: &LeaseSpec) -> LeaseSpec {
546 LeaseSpec {
547 holder_identity: None,
548 lease_transitions: prev.lease_transitions,
549 ..Default::default()
550 }
551}
552
553#[cfg(test)]
554mod tests {
555 use std::convert::Infallible;
556 use std::sync::{Arc, Mutex};
557
558 use kube::client::Body;
559 use serde_json::{Value, json};
560 use tokio::sync::oneshot;
561
562 use super::*;
563 use crate::test_util::block_on;
564
565 /// A stand-in API server holding a single lease.
566 #[derive(Clone, Default)]
567 struct LeaseServer {
568 lease: Arc<Mutex<Option<Value>>>,
569 /// Notified when a write arrives, which is then applied only after
570 /// yielding, so that a test can act while the write is in flight.
571 write_started: Arc<Mutex<Option<oneshot::Sender<()>>>>,
572 /// Makes the next request never receive a response.
573 hang_next: Arc<Mutex<bool>>,
574 }
575
576 impl LeaseServer {
577 fn held_by(holder: &str) -> Self {
578 let server = Self::default();
579 *server.lease.lock().unwrap() = Some(json!({
580 "apiVersion": "coordination.k8s.io/v1",
581 "kind": "Lease",
582 "metadata": {"name": "lease"},
583 "spec": {"holderIdentity": holder},
584 }));
585 server
586 }
587
588 fn holder(&self) -> Option<String> {
589 let lease = self.lease.lock().unwrap();
590 lease.as_ref()?["spec"]["holderIdentity"]
591 .as_str()
592 .map(str::to_owned)
593 }
594
595 fn leader_election(&self) -> LeaderElection {
596 let server = self.clone();
597 let service = tower::service_fn(move |req: http::Request<Body>| {
598 let server = server.clone();
599 async move {
600 if std::mem::take(&mut *server.hang_next.lock().unwrap()) {
601 future::pending::<()>().await;
602 }
603 let method = req.method().clone();
604 let bytes = req.into_body().collect_bytes().await.unwrap();
605 let (status, response) = if method == http::Method::GET {
606 match server.lease.lock().unwrap().clone() {
607 Some(lease) => (200, lease),
608 None => (
609 404,
610 json!({
611 "apiVersion": "v1",
612 "kind": "Status",
613 "status": "Failure",
614 "message": "not found",
615 "reason": "NotFound",
616 "code": 404,
617 }),
618 ),
619 }
620 } else {
621 let write_started = server.write_started.lock().unwrap().take();
622 if let Some(write_started) = write_started {
623 write_started.send(()).unwrap();
624 tokio::task::yield_now().await;
625 }
626 let lease: Value = serde_json::from_slice(&bytes).unwrap();
627 *server.lease.lock().unwrap() = Some(lease.clone());
628 (200, lease)
629 };
630 let response = http::Response::builder()
631 .status(status)
632 .header("content-type", "application/json")
633 .body(Body::from(serde_json::to_vec(&response).unwrap()))
634 .unwrap();
635 Ok::<_, Infallible>(response)
636 }
637 });
638 LeaderElection::new(Client::new(service, "default"), "default", "lease", "us")
639 }
640 }
641
642 #[test]
643 fn with_lease_runs_and_releases() {
644 let server = LeaseServer::default();
645 let outcome = block_on(async {
646 server
647 .leader_election()
648 .with_lease(future::pending::<()>(), async { server.holder() })
649 .await
650 });
651 assert_eq!(outcome, LeaseOutcome::Completed(Some("us".to_owned())));
652 assert_eq!(server.holder(), None);
653 }
654
655 #[test]
656 fn with_lease_retries_after_hung_acquire_request() {
657 let server = LeaseServer::default();
658 *server.hang_next.lock().unwrap() = true;
659 let outcome = block_on(async {
660 server
661 .leader_election()
662 .with_renew_deadline(Duration::from_millis(50))
663 .with_retry_period(Duration::from_millis(10))
664 .with_lease(future::pending::<()>(), async { server.holder() })
665 .await
666 });
667 assert_eq!(outcome, LeaseOutcome::Completed(Some("us".to_owned())));
668 }
669
670 #[test]
671 fn with_lease_stops_waiting_on_shutdown() {
672 let server = LeaseServer::held_by("them");
673 let (shutdown, shutdown_requested) = oneshot::channel::<()>();
674 let outcome = block_on(async {
675 let leader_election = server.leader_election();
676 let mut waiting = pin!(leader_election.with_lease(shutdown_requested, async {}));
677 // the lease is held, so this leaves it sleeping between attempts
678 for _ in 0..10 {
679 assert!(waiting.as_mut().now_or_never().is_none());
680 tokio::task::yield_now().await;
681 }
682 shutdown.send(()).unwrap();
683 waiting.await
684 });
685 assert_eq!(outcome, LeaseOutcome::Shutdown);
686 assert_eq!(server.holder(), Some("them".to_owned()));
687 }
688
689 #[test]
690 fn with_lease_releases_lease_taken_during_shutdown() {
691 let server = LeaseServer::default();
692 let (write_started, shutdown) = oneshot::channel();
693 *server.write_started.lock().unwrap() = Some(write_started);
694 let outcome = block_on(async {
695 server
696 .leader_election()
697 .with_lease(shutdown, async {})
698 .await
699 });
700 assert_eq!(outcome, LeaseOutcome::Shutdown);
701 // the write that was in flight landed, and was then released
702 let lease = server.lease.lock().unwrap().clone().unwrap();
703 assert_eq!(lease["spec"]["leaseTransitions"], 0);
704 assert_eq!(server.holder(), None);
705 }
706
707 fn now() -> Timestamp {
708 "2026-07-22T00:00:00Z".parse().unwrap()
709 }
710
711 #[test]
712 fn fresh_acquire() {
713 let spec = next_spec("us", 15, None, now());
714 assert_eq!(spec.holder_identity.as_deref(), Some("us"));
715 assert_eq!(spec.lease_duration_seconds, Some(15));
716 assert_eq!(spec.acquire_time, Some(MicroTime(now())));
717 assert_eq!(spec.renew_time, Some(MicroTime(now())));
718 assert_eq!(spec.lease_transitions, Some(0));
719 }
720
721 #[test]
722 fn renewal_preserves_acquire_time_and_transitions() {
723 let acquired: Timestamp = "2026-07-21T00:00:00Z".parse().unwrap();
724 let prev = LeaseSpec {
725 holder_identity: Some("us".to_owned()),
726 lease_duration_seconds: Some(15),
727 acquire_time: Some(MicroTime(acquired)),
728 renew_time: Some(MicroTime(acquired)),
729 lease_transitions: Some(3),
730 ..Default::default()
731 };
732 let spec = next_spec("us", 15, Some(&prev), now());
733 assert_eq!(spec.holder_identity.as_deref(), Some("us"));
734 assert_eq!(spec.acquire_time, Some(MicroTime(acquired)));
735 assert_eq!(spec.renew_time, Some(MicroTime(now())));
736 assert_eq!(spec.lease_transitions, Some(3));
737 }
738
739 #[test]
740 fn takeover_increments_transitions() {
741 let prev = LeaseSpec {
742 holder_identity: Some("them".to_owned()),
743 lease_duration_seconds: Some(15),
744 acquire_time: Some(MicroTime(now())),
745 renew_time: Some(MicroTime(now())),
746 lease_transitions: Some(3),
747 ..Default::default()
748 };
749 let spec = next_spec("us", 15, Some(&prev), now());
750 assert_eq!(spec.holder_identity.as_deref(), Some("us"));
751 assert_eq!(spec.acquire_time, Some(MicroTime(now())));
752 assert_eq!(spec.lease_transitions, Some(4));
753 }
754
755 #[test]
756 fn release_clears_holder_and_preserves_transitions() {
757 let prev = LeaseSpec {
758 holder_identity: Some("us".to_owned()),
759 lease_duration_seconds: Some(15),
760 acquire_time: Some(MicroTime(now())),
761 renew_time: Some(MicroTime(now())),
762 lease_transitions: Some(3),
763 ..Default::default()
764 };
765 let spec = released_spec(&prev);
766 assert_eq!(spec.holder_identity, None);
767 assert_eq!(spec.lease_transitions, Some(3));
768 assert_eq!(spec.renew_time, None);
769 }
770}