toe_beans/v4/server/config/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(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 /// Construct a valid lease_time field.
26 pub fn new(lease_time: u32) -> Result<Self> {
27 if lease_time < MIN_LEASE_TIME {
28 return Err("Lease time cant be less than the minimum lease time (60 seconds)");
29 }
30
31 Ok(Self(lease_time))
32 }
33
34 /// The actual lease_time, not adjusted for drift.
35 pub fn as_server(&self) -> u32 {
36 self.0
37 }
38
39 /// The lease_time, with a small amount subtracted to adjust for drift
40 pub fn as_client(&self) -> u32 {
41 self.0 - DRIFT
42 }
43}
44
45#[cfg(test)]
46mod tests {
47 use super::*;
48
49 #[test]
50 fn test_min_lease_time_greater_than_drift() {
51 assert!(MIN_LEASE_TIME > DRIFT);
52 }
53}