toe_beans/v4/server/leases/lease_time.rs
1use crate::v4::error::Result;
2use serde::{Deserialize, Serialize};
3
4/// The lowest valid value for lease_time (in seconds)
5const MIN_LEASE_TIME: u32 = 60;
6/// Used to adjust for clock drift between client and server (in seconds)
7const DRIFT: u32 = 10;
8
9/// The time, in seconds, before a lease expires.
10/// A lower value will increase dhcp traffic between client and server.
11/// A higher value will increase the chances that all ip addresses are assigned.
12///
13/// Lease time must be at least a minute because:
14/// 1. The server must subtract some time to account for drift.
15/// 2. The default value for T1 (renewal time) is half of the lease_time.
16#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
17pub struct LeaseTime(u32);
18
19impl LeaseTime {
20 /// DHCP reserves the maximum value of 4,294,967,295 to represent a lease that never expires.
21 ///
22 /// This is more performant than `LeaseTime::new`
23 pub const INFINITY: Self = Self(u32::MAX);
24
25 /// The number of seconds in one day (24 hours).
26 /// This is currently used as the default in `LeaseConfig`.
27 pub const ONE_DAY: Self = Self(86_400);
28
29 /// Construct a valid lease_time field.
30 pub fn new(lease_time: u32) -> Result<Self> {
31 if lease_time < MIN_LEASE_TIME {
32 return Err("Lease time cant be less than the minimum lease time (60 seconds)");
33 }
34
35 Ok(Self(lease_time))
36 }
37
38 /// The actual lease_time, not adjusted for drift.
39 pub fn as_server(&self) -> u32 {
40 self.0
41 }
42
43 /// The lease_time, with a small amount subtracted to adjust for drift
44 pub fn as_client(&self) -> u32 {
45 self.0 - DRIFT
46 }
47}
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52
53 #[test]
54 fn test_min_lease_time_greater_than_drift() {
55 assert!(MIN_LEASE_TIME > DRIFT);
56 }
57}