footing 0.4.4

Feature-gated foundations for Rust backend services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use std::{
    collections::HashMap,
    fmt,
    sync::Mutex,
    time::{Duration, Instant},
};

use async_trait::async_trait;
use thiserror::Error;

use crate::{
    clock::{SharedClock, system_clock},
    result::{ClassifyError, ErrorKind},
};

use super::config::{validate_lease_owner, validate_worker_name};
use super::{WorkerConfigError, WorkerLeaseConfig};

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Represents worker lease.
pub struct WorkerLease {
    worker: String,
    owner: String,
    token: u64,
    expires_at: Instant,
}

impl WorkerLease {
    /// Creates a new instance.
    pub fn new(
        worker: impl Into<String>,
        owner: impl Into<String>,
        token: u64,
        expires_at: Instant,
    ) -> Result<Self, WorkerLeaseError> {
        let worker = worker.into();
        let owner = owner.into();
        validate_worker_name(&worker).map_err(WorkerLeaseError::InvalidConfig)?;
        validate_lease_owner(&owner).map_err(WorkerLeaseError::InvalidConfig)?;
        Ok(Self::from_valid_parts(worker, owner, token, expires_at))
    }

    fn from_valid_parts(worker: String, owner: String, token: u64, expires_at: Instant) -> Self {
        Self {
            worker,
            owner,
            token,
            expires_at,
        }
    }

    #[must_use]
    /// Returns the worker.
    pub fn worker(&self) -> &str {
        &self.worker
    }

    #[must_use]
    /// Returns the owner.
    pub fn owner(&self) -> &str {
        &self.owner
    }

    #[must_use]
    /// Returns the token.
    pub const fn token(&self) -> u64 {
        self.token
    }

    #[must_use]
    /// Returns the expires at.
    pub const fn expires_at(&self) -> Instant {
        self.expires_at
    }

    #[must_use]
    /// Returns whether the lease is inside its pre-expiry renewal window.
    pub fn should_renew(&self, now: Instant, renew_before: Duration) -> bool {
        now.checked_add(renew_before)
            .is_none_or(|renew_at| renew_at >= self.expires_at)
    }
}

#[derive(Error)]
#[non_exhaustive]
/// Errors that can occur while handling worker lease.
pub enum WorkerLeaseError {
    #[error("worker lease store lock is poisoned")]
    /// Indicates lock poisoned.
    LockPoisoned,
    #[error("invalid worker lease configuration")]
    /// The config is invalid.
    InvalidConfig(#[from] WorkerConfigError),
    #[error("worker lease store is unavailable")]
    /// An external lease backend failed; the original cause is retained.
    Store(#[source] crate::result::BoxError),
}

impl fmt::Debug for WorkerLeaseError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::LockPoisoned => formatter.write_str("LockPoisoned"),
            Self::InvalidConfig(error) => {
                formatter.debug_tuple("InvalidConfig").field(error).finish()
            }
            Self::Store(_) => formatter.debug_tuple("Store").field(&"[REDACTED]").finish(),
        }
    }
}

impl ClassifyError for WorkerLeaseError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::LockPoisoned | Self::Store(_) => ErrorKind::Unavailable,
            Self::InvalidConfig(source) => source.error_kind(),
        }
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        match self {
            Self::LockPoisoned | Self::Store(_) => {
                crate::result::ErrorCode::internal("worker_lease_unavailable")
            }
            Self::InvalidConfig(source) => source.error_code(),
        }
    }
}

#[async_trait]
/// Storage abstraction for worker leases.
///
/// Implementations must make every method cancellation-safe because the worker
/// runtime drops acquire/renew futures at their configured operation deadline or
/// during shutdown. Every new acquisition must issue a fencing token greater
/// than all tokens previously issued for that worker. Renewal must preserve the
/// current token, and both renewal and release must condition mutations on the
/// exact owner and token.
///
/// A lease only coordinates scheduling. It cannot revoke an already-running
/// external side effect, so workers remain at-least-once and must use idempotency
/// keys or propagate the fencing token to protected resources.
pub trait WorkerLeaseStore: Send + Sync + 'static {
    /// Attempts to acquire a worker lease using a fresh fencing token.
    async fn try_acquire(
        &self,
        worker: &str,
        owner: &str,
        config: WorkerLeaseConfig,
    ) -> Result<Option<WorkerLease>, WorkerLeaseError>;

    /// Renews only the exact unexpired owner/token pair.
    async fn renew(
        &self,
        lease: &WorkerLease,
        config: WorkerLeaseConfig,
    ) -> Result<Option<WorkerLease>, WorkerLeaseError>;

    /// Releases a lease if the exact owner/token pair is still current.
    async fn release(&self, lease: &WorkerLease) -> Result<(), WorkerLeaseError>;
}

#[non_exhaustive]
/// Storage abstraction for local worker lease.
pub struct LocalWorkerLeaseStore {
    state: Mutex<LocalLeaseState>,
    clock: SharedClock,
}

struct LocalLeaseState {
    leases: HashMap<String, WorkerLease>,
    next_token: u64,
}

impl LocalWorkerLeaseStore {
    #[must_use]
    /// Creates a new instance.
    pub fn new() -> Self {
        Self::with_clock(system_clock())
    }

    #[must_use]
    /// Configures clock and returns the updated value.
    pub fn with_clock(clock: SharedClock) -> Self {
        Self {
            state: Mutex::new(LocalLeaseState {
                leases: HashMap::new(),
                next_token: 1,
            }),
            clock,
        }
    }

    #[must_use]
    /// Returns the clock.
    pub fn clock(&self) -> &SharedClock {
        &self.clock
    }
}

impl fmt::Debug for LocalWorkerLeaseStore {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let lease_count = self.state.lock().map(|state| state.leases.len()).ok();
        formatter
            .debug_struct("LocalWorkerLeaseStore")
            .field("lease_count", &lease_count)
            .finish_non_exhaustive()
    }
}

impl Default for LocalWorkerLeaseStore {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl WorkerLeaseStore for LocalWorkerLeaseStore {
    async fn try_acquire(
        &self,
        worker: &str,
        owner: &str,
        config: WorkerLeaseConfig,
    ) -> Result<Option<WorkerLease>, WorkerLeaseError> {
        validate_worker_name(worker)?;
        validate_lease_owner(owner)?;

        let mut state = self
            .state
            .lock()
            .map_err(|_| WorkerLeaseError::LockPoisoned)?;
        let now = self.clock.now();
        let expires_at = worker_lease_expiry_after(now, config.lease_duration)?;

        // Acquisition creates a new fencing token. Even the same owner must use
        // `renew` while its current lease is live so concurrent tasks sharing an
        // owner cannot silently invalidate one another's token.
        if let Some(existing) = state.leases.get(worker)
            && existing.expires_at > now
        {
            return Ok(None);
        }

        let lease = WorkerLease::from_valid_parts(
            worker.to_owned(),
            owner.to_owned(),
            state.next_token,
            expires_at,
        );
        state.next_token = state.next_token.wrapping_add(1);
        state.leases.insert(worker.to_owned(), lease.clone());
        Ok(Some(lease))
    }

    async fn renew(
        &self,
        lease: &WorkerLease,
        config: WorkerLeaseConfig,
    ) -> Result<Option<WorkerLease>, WorkerLeaseError> {
        let mut state = self
            .state
            .lock()
            .map_err(|_| WorkerLeaseError::LockPoisoned)?;
        let now = self.clock.now();
        let expires_at = worker_lease_expiry_after(now, config.lease_duration)?;

        let Some(existing) = state.leases.get_mut(lease.worker()) else {
            return Ok(None);
        };

        if existing.owner != lease.owner
            || existing.token != lease.token
            || existing.expires_at <= now
        {
            return Ok(None);
        }

        existing.expires_at = expires_at;
        Ok(Some(existing.clone()))
    }

    async fn release(&self, lease: &WorkerLease) -> Result<(), WorkerLeaseError> {
        let mut state = self
            .state
            .lock()
            .map_err(|_| WorkerLeaseError::LockPoisoned)?;

        if let Some(existing) = state.leases.get(lease.worker())
            && existing.owner == lease.owner
            && existing.token == lease.token
        {
            state.leases.remove(lease.worker());
        }

        Ok(())
    }
}

fn worker_lease_expiry_after(
    now: Instant,
    lease_duration: Duration,
) -> Result<Instant, WorkerLeaseError> {
    now.checked_add(lease_duration)
        .ok_or(WorkerLeaseError::InvalidConfig(
            WorkerConfigError::InvalidLeaseDuration,
        ))
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, TryLockError, mpsc};

    use futures_util::FutureExt;

    use crate::clock::{Clock, ManualClock};

    use super::*;

    struct PausingClock {
        clock: ManualClock,
        pause: Mutex<Option<(mpsc::Sender<()>, mpsc::Receiver<()>)>>,
    }

    impl Clock for PausingClock {
        fn now(&self) -> Instant {
            let now = self.clock.now();
            let pause = self.pause.lock().unwrap().take();
            if let Some((sampled, resume)) = pause {
                sampled.send(()).unwrap();
                resume.recv().unwrap();
            }
            now
        }
    }

    fn lease_operation_uses_time_inside_its_state_lock(renew: bool) {
        let clock = Arc::new(PausingClock {
            clock: ManualClock::new(),
            pause: Mutex::new(None),
        });
        let store = Arc::new(LocalWorkerLeaseStore::with_clock(clock.clone()));
        let config = WorkerLeaseConfig::new(
            Duration::from_secs(30),
            Duration::from_secs(10),
            Duration::from_secs(5),
        )
        .unwrap();
        let lease = renew.then(|| {
            store
                .try_acquire("email", "node-a", config)
                .now_or_never()
                .unwrap()
                .unwrap()
                .unwrap()
        });

        let (sampled, sample_received) = mpsc::channel();
        let (resume, resumed) = mpsc::channel();
        *clock.pause.lock().unwrap() = Some((sampled, resumed));
        let working_store = Arc::clone(&store);
        let operation = std::thread::spawn(move || {
            match lease {
                Some(lease) => working_store.renew(&lease, config).now_or_never(),
                None => working_store
                    .try_acquire("email", "node-a", config)
                    .now_or_never(),
            }
            .unwrap()
            .unwrap()
        });

        sample_received.recv().unwrap();
        // Insert a competing critical section after the time sample only if
        // the operation has not locked its state yet. Once the sample is
        // protected by the lock, this interleaving is no longer possible.
        let expired_while_waiting = match store.state.try_lock() {
            Ok(guard) => {
                clock.clock.advance(Duration::from_secs(60)).unwrap();
                resume.send(()).unwrap();
                drop(guard);
                true
            }
            Err(TryLockError::WouldBlock) => {
                resume.send(()).unwrap();
                false
            }
            Err(TryLockError::Poisoned(_)) => panic!("lease state lock is poisoned"),
        };
        let result = operation.join().unwrap();
        if renew && expired_while_waiting {
            assert!(result.is_none(), "an expired lease must not be renewed");
        } else {
            let result = result.expect("an available lease should be acquired or renewed");
            assert!(
                result.expires_at() > clock.clock.now(),
                "a lease must not expire while waiting to mutate store state"
            );
        }
    }

    #[test]
    fn acquisition_samples_time_after_lock_contention() {
        lease_operation_uses_time_inside_its_state_lock(false);
    }

    #[test]
    fn renewal_does_not_revive_a_lease_expired_during_lock_contention() {
        lease_operation_uses_time_inside_its_state_lock(true);
    }
}